language
stringclasses
15 values
src_encoding
stringclasses
34 values
length_bytes
int64
6
7.85M
score
float64
1.5
5.69
int_score
int64
2
5
detected_licenses
listlengths
0
160
license_type
stringclasses
2 values
text
stringlengths
9
7.85M
JavaScript
UTF-8
75,368
2.75
3
[]
no_license
//import funkcji sprawdzających czy user lub komputer może postawić statek import { oneSquareHorizontal, twoSquaresHorizontal, threeSquaresHorizontal, fourSquaresHorizontal, oneSquareVertical, twoSquaresVertical, threeSquaresVertical, fourSquaresVertical, } from './conditions.js'; //zmienne dla planszy komputera let compDirection = undefined; let compRow = 0; let compColumn = 0; let compPosition = 0; let compShips = [4, 3, 3, 2, 2, 2, 1, 1, 1, 1]; let compPositions = [ [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, 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, 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], [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, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], ]; //zmienne dla planszy usera let userShips = [4, 3, 3, 2, 2, 2, 1, 1, 1, 1]; let userDirection = 'horizontal'; let chosenShip = 4; let chosenShip2 = '1'; let noShips = false; let horizontalBruh = false; let verticalBruh = false; let userPositions = [ [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, 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, 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], [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, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], ]; //zmienne do właściwej rozgrywki let gameHasStarted = false; let turn = 'user'; let counter = 1; let userGoodShots = 0; let compGoodShots = 0; let isGameOver = false; let userLastShot = 'miss'; let compLastShot = 'miss'; //DOM dla usera const userBoard = document.createElement('div'); const shipsBoard = document.createElement('div'); userBoard.id = 'userBoard'; shipsBoard.id = 'shipsBoard'; userBoard.onmouseenter = function () { if (gameHasStarted) { for (var i = 0; i < 100; i++) { let position = i + 1; let row; let column; if (position <= 10) row = 1; else row = Math.ceil(position / 10); if (position % 10 == 0) column = 10; else column = position - Math.floor(position / 10) * 10; if (userPositions[row][column] === 1) document.getElementById(`${position}`).style.backgroundColor = 'black'; } } }; userBoard.onmouseout = function () { if (gameHasStarted) { for (var i = 0; i < 100; i++) { let position = i + 1; let row; let column; if (position <= 10) row = 1; else row = Math.ceil(position / 10); if (position % 10 == 0) column = 10; else column = position - Math.floor(position / 10) * 10; if (userPositions[row][column] === 1) document.getElementById(`${position}`).style.backgroundColor = 'black'; } } }; userBoard.onmouseover = function () { if (!gameHasStarted) { this.style.cursor = 'pointer'; } else { this.style.cursor = 'not-allowed'; } }; //rozstawienie jedynek w tablicy compPositions const setCompShips = function () { compShips.forEach(element => { compDirection = returnDirection(element); if (compDirection === 'horizontal') { for (var i = 0; i < element; i++) { compPositions[compRow][compColumn + i] = 1; } } else if (compDirection === 'vertical') { for (var i = 0; i < element; i++) { compPositions[compRow + i][compColumn] = 1; } } compDirection = undefined; compRow = 0; compColumn = 0; compPosition = 0; }); }; setCompShips(); //postawienie planszy komputera const compBoard = document.createElement('div'); compBoard.id = 'compBoard'; const setCompBoard = function () { compPositions.forEach((higherElement, higherIndex) => { higherElement.forEach((lowerElement, lowerIndex) => { if ( higherIndex == 0 || higherIndex == 11 || lowerIndex == 0 || lowerIndex == 11 ) { } else { let compSquare = document.createElement('div'); compSquare.classList.add('compSquare'); compSquare.classList.add(counter.toString()); compSquare.style.backgroundColor = 'white'; compSquare.onmouseover = function () { if (gameHasStarted) { this.style.cursor = 'pointer'; } }; compSquare.onclick = function () { if (!isGameOver && gameHasStarted) { if ( turn === 'user' && this.className.substr(this.className.length - 4).trim() != 'miss' && this.className.substr(this.className.length - 4).trim() != 'hit' ) { let chosenPosition = parseInt(this.className.substr(11)); let chosenRow = 0; let chosenColumn = 0; if (chosenPosition <= 10) chosenRow = 1; else chosenRow = Math.ceil(chosenPosition / 10); if (chosenPosition % 10 == 0) chosenColumn = 10; else chosenColumn = chosenPosition - Math.floor(chosenPosition / 10) * 10; if (compPositions[chosenRow][chosenColumn] === 0) { const miss = document.createElement('img'); miss.src = './miss.png'; this.appendChild(miss); this.classList.add('miss'); userLastShot = 'miss'; } else if (compPositions[chosenRow][chosenColumn] === 1) { const hit = document.createElement('img'); hit.src = './hit.png'; this.appendChild(hit); this.classList.add('hit'); userLastShot = 'hit'; userGoodShots++; if (userGoodShots === 20) userWin(); } if (userLastShot === 'hit') { turn = 'user'; } else if (userLastShot === 'miss') { turn = 'computer'; computerShot(); } } else if ( this.className.substr(this.className.length - 4).trim() === 'miss' || this.className.substr(this.className.length - 4).trim() === 'hit' ) alert('Nie strzelaj tam gdzie już strzelałeś!'); else if (!isGameOver && turn !== 'user') alert('Poczekaj aż komputer wykona ruch!'); } }; compBoard.appendChild(compSquare); counter++; } }); }); }; setCompBoard(); //rozstawienie statków usera z boku const giveShipsToUser = function () { userShips.forEach((element, index) => { let ship = document.createElement('div'); ship.classList.add('ship'); ship.classList.add(`${index + 1}`); for (var i = 0; i < element; i++) { let square = document.createElement('div'); square.classList.add('shipSquare'); square.onmouseover = function () { this.style.cursor = 'pointer'; }; ship.appendChild(square); } switch (element) { case 4: ship.style.width = '128px'; ship.style.backgroundColor = 'orange'; break; case 3: ship.style.width = '96px'; break; case 2: ship.style.width = '64px'; break; case 1: ship.style.width = '32px'; break; } ship.onmouseover = function () { if (this.style.backgroundColor !== 'orange') this.style.backgroundColor = 'blue'; }; ship.onmouseout = function () { if ( (this.style.backgroundColor === 'blue' || this.style.backgroundColor === 'orange') && this.className.substr(5) === chosenShip2 ) this.style.backgroundColor = 'orange'; else this.style.backgroundColor = 'white'; }; ship.onclick = function () { let clearShips = document.getElementsByClassName('ship'); let len = clearShips.length; for (var i = 0; i < len; i++) { clearShips[i].style.backgroundColor = 'white'; } chosenShip = element; chosenShip2 = this.className.substr(5); this.style.backgroundColor = 'orange'; userDirection = 'horizontal'; }; shipsBoard.appendChild(ship); }); }; giveShipsToUser(); //plansza usera const setUserBoard = function () { for (var i = 0; i < 100; i++) { let square = document.createElement('div'); square.id = `${i + 1}`; square.classList.add('boardSquare'); let row; if (i == 0) { row = 1; } else if (i % 10 == 0) { row = Math.ceil(i / 10) + 1; } else row = Math.ceil(i / 10); let column = i - Math.floor(i / 10) * 10 + 1; square.onmouseover = function () { horizontalBruh = false; verticalBruh = false; let hoveredSquare = document.getElementById(`${parseInt(this.id)}`); if (chosenShip != undefined) { if (userDirection === 'horizontal') { if (parseInt(hoveredSquare.id) % 10 === 8 && chosenShip === 4) { horizontalBruh = true; if (fourSquaresHorizontal(row, column - 1, userPositions)) { for (var i = -1; i < 3; i++) { document.getElementById( `${parseInt(this.id) + i}` ).style.backgroundColor = 'green'; } } else { for (var i = -1; i < 3; i++) { document.getElementById( `${parseInt(this.id) + i}` ).style.backgroundColor = 'red'; } } } else if ( parseInt(hoveredSquare.id) % 10 === 9 && chosenShip === 4 ) { horizontalBruh = true; if (fourSquaresHorizontal(row, column - 2, userPositions)) { for (var i = -2; i < 2; i++) { document.getElementById( `${parseInt(this.id) + i}` ).style.backgroundColor = 'green'; } } else { for (var i = -2; i < 2; i++) { document.getElementById( `${parseInt(this.id) + i}` ).style.backgroundColor = 'red'; } } } else if ( parseInt(hoveredSquare.id) % 10 === 9 && chosenShip === 3 ) { horizontalBruh = true; if (threeSquaresHorizontal(row, column - 1, userPositions)) { for (var i = -1; i < 2; i++) { document.getElementById( `${parseInt(this.id) + i}` ).style.backgroundColor = 'green'; } } else { for (var i = -1; i < 2; i++) { document.getElementById( `${parseInt(this.id) + i}` ).style.backgroundColor = 'red'; } } } else if ( parseInt(hoveredSquare.id) % 10 === 0 && chosenShip === 4 ) { horizontalBruh = true; if (fourSquaresHorizontal(row, column - 3, userPositions)) { for (var i = -3; i < 1; i++) { document.getElementById( `${parseInt(this.id) + i}` ).style.backgroundColor = 'green'; } } else { for (var i = -3; i < 1; i++) { document.getElementById( `${parseInt(this.id) + i}` ).style.backgroundColor = 'red'; } } } else if ( parseInt(hoveredSquare.id) % 10 === 0 && chosenShip === 3 ) { horizontalBruh = true; if (threeSquaresHorizontal(row, column - 2, userPositions)) { for (var i = -2; i < 1; i++) { document.getElementById( `${parseInt(this.id) + i}` ).style.backgroundColor = 'green'; } } else { for (var i = -2; i < 1; i++) { document.getElementById( `${parseInt(this.id) + i}` ).style.backgroundColor = 'red'; } } } else if ( parseInt(hoveredSquare.id) % 10 === 0 && chosenShip === 2 ) { horizontalBruh = true; if (twoSquaresHorizontal(row, column - 1, userPositions)) { document.getElementById( `${parseInt(this.id) - 1}` ).style.backgroundColor = 'green'; document.getElementById( `${parseInt(this.id)}` ).style.backgroundColor = 'green'; } else { document.getElementById( `${parseInt(this.id) - 1}` ).style.backgroundColor = 'red'; document.getElementById( `${parseInt(this.id)}` ).style.backgroundColor = 'red'; } } else { horizontalBruh = false; switch (chosenShip) { case 4: if (fourSquaresHorizontal(row, column, userPositions)) { for (var i = 0; i < 4; i++) { document.getElementById( `${parseInt(this.id) + i}` ).style.backgroundColor = 'green'; } } else { for (var i = 0; i < 4; i++) { document.getElementById( `${parseInt(this.id) + i}` ).style.backgroundColor = 'red'; } } break; case 3: if (threeSquaresHorizontal(row, column, userPositions)) { for (var i = 0; i < 3; i++) { document.getElementById( `${parseInt(this.id) + i}` ).style.backgroundColor = 'green'; } } else { for (var i = 0; i < 3; i++) { document.getElementById( `${parseInt(this.id) + i}` ).style.backgroundColor = 'red'; } } break; case 2: if (twoSquaresHorizontal(row, column, userPositions)) { document.getElementById( `${parseInt(this.id)}` ).style.backgroundColor = 'green'; document.getElementById( `${parseInt(this.id) + 1}` ).style.backgroundColor = 'green'; } else { document.getElementById( `${parseInt(this.id)}` ).style.backgroundColor = 'red'; document.getElementById( `${parseInt(this.id) + 1}` ).style.backgroundColor = 'red'; } break; case 1: if (oneSquareHorizontal(row, column, userPositions)) { document.getElementById( `${parseInt(this.id)}` ).style.backgroundColor = 'green'; } else { document.getElementById( `${parseInt(this.id)}` ).style.backgroundColor = 'red'; } break; } } } else if (userDirection === 'vertical') { if ( ((hoveredSquare.id.substr(0, 1) === '7' && hoveredSquare.id.length !== 1) || parseInt(hoveredSquare.id) === 80) && chosenShip === 4 ) { verticalBruh = true; if (fourSquaresVertical(row - 1, column, userPositions)) { for (var i = -1; i < 3; i++) { document.getElementById( `${parseInt(this.id) + i * 10}` ).style.backgroundColor = 'green'; } } else { for (var i = -1; i < 3; i++) { document.getElementById( `${parseInt(this.id) + i * 10}` ).style.backgroundColor = 'red'; } } } else if ( ((hoveredSquare.id.substr(0, 1) === '8' && hoveredSquare.id.length !== 1) || parseInt(hoveredSquare.id) === 90) && chosenShip === 4 ) { verticalBruh = true; if (fourSquaresVertical(row - 2, column, userPositions)) { for (var i = -2; i < 2; i++) { document.getElementById( `${parseInt(this.id) + i * 10}` ).style.backgroundColor = 'green'; } } else { for (var i = -2; i < 2; i++) { document.getElementById( `${parseInt(this.id) + i * 10}` ).style.backgroundColor = 'red'; } } } else if ( ((hoveredSquare.id.substr(0, 1) === '8' && hoveredSquare.id.length !== 1) || parseInt(hoveredSquare.id) === 90) && chosenShip === 3 ) { verticalBruh = true; if (threeSquaresVertical(row - 1, column, userPositions)) { for (var i = -1; i < 2; i++) { document.getElementById( `${parseInt(this.id) + i * 10}` ).style.backgroundColor = 'green'; } } else { for (var i = -1; i < 2; i++) { document.getElementById( `${parseInt(this.id) + i * 10}` ).style.backgroundColor = 'red'; } } } else if ( ((hoveredSquare.id.substr(0, 1) === '9' && hoveredSquare.id.length !== 1) || parseInt(hoveredSquare.id) === 100) && chosenShip === 4 ) { verticalBruh = true; if (fourSquaresVertical(row - 3, column, userPositions)) { for (var i = -3; i < 1; i++) { document.getElementById( `${parseInt(this.id) + i * 10}` ).style.backgroundColor = 'green'; } } else { for (var i = -3; i < 1; i++) { document.getElementById( `${parseInt(this.id) + i * 10}` ).style.backgroundColor = 'red'; } } } else if ( ((hoveredSquare.id.substr(0, 1) === '9' && hoveredSquare.id.length !== 1) || parseInt(hoveredSquare.id) === 100) && chosenShip === 3 ) { verticalBruh = true; if (threeSquaresVertical(row - 2, column, userPositions)) { for (var i = -2; i < 1; i++) { document.getElementById( `${parseInt(this.id) + i * 10}` ).style.backgroundColor = 'green'; } } else { for (var i = -2; i < 1; i++) { document.getElementById( `${parseInt(this.id) + i * 10}` ).style.backgroundColor = 'red'; } } } else if ( ((hoveredSquare.id.substr(0, 1) === '9' && hoveredSquare.id.length !== 1) || parseInt(hoveredSquare.id) === 100) && chosenShip === 2 ) { verticalBruh = true; if (twoSquaresVertical(row - 1, column, userPositions)) { document.getElementById( `${parseInt(this.id) - 10}` ).style.backgroundColor = 'green'; document.getElementById( `${parseInt(this.id)}` ).style.backgroundColor = 'green'; } else { document.getElementById( `${parseInt(this.id) - 10}` ).style.backgroundColor = 'red'; document.getElementById( `${parseInt(this.id)}` ).style.backgroundColor = 'red'; } } else { verticalBruh = false; switch (chosenShip) { case 4: if (fourSquaresVertical(row, column, userPositions)) { for (var i = 0; i < 4; i++) { document.getElementById( `${parseInt(this.id) + i * 10}` ).style.backgroundColor = 'green'; } } else { for (var i = 0; i < 4; i++) { document.getElementById( `${parseInt(this.id) + i * 10}` ).style.backgroundColor = 'red'; } } break; case 3: if (threeSquaresVertical(row, column, userPositions)) { for (var i = 0; i < 3; i++) { document.getElementById( `${parseInt(this.id) + i * 10}` ).style.backgroundColor = 'green'; } } else { for (var i = 0; i < 3; i++) { document.getElementById( `${parseInt(this.id) + i * 10}` ).style.backgroundColor = 'red'; } } break; case 2: if (twoSquaresVertical(row, column, userPositions)) { document.getElementById( `${parseInt(this.id)}` ).style.backgroundColor = 'green'; document.getElementById( `${parseInt(this.id) + 10}` ).style.backgroundColor = 'green'; } else { document.getElementById( `${parseInt(this.id)}` ).style.backgroundColor = 'red'; document.getElementById( `${parseInt(this.id) + 10}` ).style.backgroundColor = 'red'; } break; case 1: if (oneSquareVertical(row, column, userPositions)) { document.getElementById( `${parseInt(this.id)}` ).style.backgroundColor = 'green'; } else { document.getElementById( `${parseInt(this.id)}` ).style.backgroundColor = 'red'; } break; } } } } }; square.onmouseout = function () { let squares = document.getElementsByClassName('boardSquare'); let len = squares.length; for (var i = 0; i < len; i++) { if (squares[i].className.substr(12) == 'occupied') { squares[i].style.backgroundColor = 'black'; } else squares[i].style.backgroundColor = 'white'; } }; square.oncontextmenu = function (e) { let hoveredSquare = document.getElementById(`${this.id}`); e.preventDefault(); switch (userDirection) { case 'horizontal': for (var i = 1; i < chosenShip; i++) { if (horizontalBruh) { if ( document .getElementById(`${parseInt(this.id) - i}`) .className.substr(12, 8) !== 'occupied' ) { document.getElementById( `${parseInt(this.id) - i}` ).style.backgroundColor = 'white'; } else { document.getElementById( `${parseInt(this.id) - i}` ).style.backgroundColor = 'black'; } if ( document.getElementById(`${parseInt(this.id) + i}`) !== null && document .getElementById(`${parseInt(this.id) + i}`) .className.substr(12, 8) !== 'occupied' ) { document.getElementById( `${parseInt(this.id) + i}` ).style.backgroundColor = 'white'; } else if ( document.getElementById(`${parseInt(this.id) + i}`) !== null ) { document.getElementById( `${parseInt(this.id) + i}` ).style.backgroundColor = 'black'; } } else { if ( document .getElementById(`${parseInt(this.id) + i}`) .className.substr(12, 8) !== 'occupied' ) { document.getElementById( `${parseInt(this.id) + i}` ).style.backgroundColor = 'white'; } else { document.getElementById( `${parseInt(this.id) + i}` ).style.backgroundColor = 'black'; } } } break; case 'vertical': for (var i = 1; i < chosenShip; i++) { if (verticalBruh) { if ( document.getElementById(`${parseInt(this.id) - i * 10}`) != null ) { if ( document .getElementById(`${parseInt(this.id) - i * 10}`) .className.substr(12, 8) !== 'occupied' ) { document.getElementById( `${parseInt(this.id) - i * 10}` ).style.backgroundColor = 'white'; } else { document.getElementById( `${parseInt(this.id) - i * 10}` ).style.backgroundColor = 'black'; } } if ( document.getElementById(`${parseInt(this.id) + i * 10}`) != null ) { if ( document .getElementById(`${parseInt(this.id) + i * 10}`) .className.substr(12, 8) !== 'occupied' ) { document.getElementById( `${parseInt(this.id) + i * 10}` ).style.backgroundColor = 'white'; } else { document.getElementById( `${parseInt(this.id) + i * 10}` ).style.backgroundColor = 'black'; } } } else { if ( document.getElementById(`${parseInt(this.id) + i * 10}`) != null ) { if ( document .getElementById(`${parseInt(this.id) + i * 10}`) .className.substr(12, 8) !== 'occupied' ) { document.getElementById( `${parseInt(this.id) + i * 10}` ).style.backgroundColor = 'white'; } else { document.getElementById( `${parseInt(this.id) + i * 10}` ).style.backgroundColor = 'black'; } } } } break; } if (userDirection === 'vertical') userDirection = 'horizontal'; else userDirection = 'vertical'; if (userDirection === 'horizontal') { if ( (parseInt(hoveredSquare.id) % 10 === 8 && chosenShip === 4) || (parseInt(hoveredSquare.id) % 10 === 9 && chosenShip === 4) || (parseInt(hoveredSquare.id) % 10 === 9 && chosenShip === 3) || (parseInt(hoveredSquare.id) % 10 === 0 && chosenShip === 4) || (parseInt(hoveredSquare.id) % 10 === 0 && chosenShip === 3) || (parseInt(hoveredSquare.id) % 10 === 0 && chosenShip === 2) ) horizontalBruh = true; if (horizontalBruh) { if (parseInt(hoveredSquare.id) % 10 === 8 && chosenShip === 4) { horizontalBruh = true; if (fourSquaresHorizontal(row, column - 1, userPositions)) { for (var i = -1; i < 3; i++) { document.getElementById( `${parseInt(this.id) + i}` ).style.backgroundColor = 'green'; } } else { for (var i = -1; i < 3; i++) { document.getElementById( `${parseInt(this.id) + i}` ).style.backgroundColor = 'red'; } } } else if ( parseInt(hoveredSquare.id) % 10 === 9 && chosenShip === 4 ) { horizontalBruh = true; if (fourSquaresHorizontal(row, column - 2, userPositions)) { for (var i = -2; i < 2; i++) { document.getElementById( `${parseInt(this.id) + i}` ).style.backgroundColor = 'green'; } } else { for (var i = -2; i < 2; i++) { document.getElementById( `${parseInt(this.id) + i}` ).style.backgroundColor = 'red'; } } } else if ( parseInt(hoveredSquare.id) % 10 === 9 && chosenShip === 3 ) { horizontalBruh = true; if (threeSquaresHorizontal(row, column - 1, userPositions)) { for (var i = -1; i < 2; i++) { document.getElementById( `${parseInt(this.id) + i}` ).style.backgroundColor = 'green'; } } else { for (var i = -1; i < 2; i++) { document.getElementById( `${parseInt(this.id) + i}` ).style.backgroundColor = 'red'; } } } else if ( parseInt(hoveredSquare.id) % 10 === 0 && chosenShip === 4 ) { horizontalBruh = true; if (fourSquaresHorizontal(row, column - 3, userPositions)) { for (var i = -3; i < 1; i++) { document.getElementById( `${parseInt(this.id) + i}` ).style.backgroundColor = 'green'; } } else { for (var i = -3; i < 1; i++) { document.getElementById( `${parseInt(this.id) + i}` ).style.backgroundColor = 'red'; } } } else if ( parseInt(hoveredSquare.id) % 10 === 0 && chosenShip === 3 ) { horizontalBruh = true; if (threeSquaresHorizontal(row, column - 2, userPositions)) { for (var i = -2; i < 1; i++) { document.getElementById( `${parseInt(this.id) + i}` ).style.backgroundColor = 'green'; } } else { for (var i = -2; i < 1; i++) { document.getElementById( `${parseInt(this.id) + i}` ).style.backgroundColor = 'red'; } } } else if ( parseInt(hoveredSquare.id) % 10 === 0 && chosenShip === 2 ) { horizontalBruh = true; if (twoSquaresHorizontal(row, column - 1, userPositions)) { document.getElementById( `${parseInt(this.id) - 1}` ).style.backgroundColor = 'green'; document.getElementById( `${parseInt(this.id)}` ).style.backgroundColor = 'green'; } else { document.getElementById( `${parseInt(this.id) - 1}` ).style.backgroundColor = 'red'; document.getElementById( `${parseInt(this.id)}` ).style.backgroundColor = 'red'; } } else { horizontalBruh = false; switch (chosenShip) { case 4: if (fourSquaresHorizontal(row, column, userPositions)) { for (var i = 0; i < 4; i++) { document.getElementById( `${parseInt(this.id) + i}` ).style.backgroundColor = 'green'; } } else { for (var i = 0; i < 4; i++) { document.getElementById( `${parseInt(this.id) + i}` ).style.backgroundColor = 'red'; } } break; case 3: if (threeSquaresHorizontal(row, column, userPositions)) { for (var i = 0; i < 3; i++) { document.getElementById( `${parseInt(this.id) + i}` ).style.backgroundColor = 'green'; } } else { for (var i = 0; i < 3; i++) { document.getElementById( `${parseInt(this.id) + i}` ).style.backgroundColor = 'red'; } } break; case 2: if (twoSquaresHorizontal(row, column, userPositions)) { document.getElementById( `${parseInt(this.id)}` ).style.backgroundColor = 'green'; document.getElementById( `${parseInt(this.id) + 1}` ).style.backgroundColor = 'green'; } else { document.getElementById( `${parseInt(this.id)}` ).style.backgroundColor = 'red'; document.getElementById( `${parseInt(this.id) + 1}` ).style.backgroundColor = 'red'; } break; case 1: if (oneSquareHorizontal(row, column, userPositions)) { document.getElementById( `${parseInt(this.id)}` ).style.backgroundColor = 'green'; } else { document.getElementById( `${parseInt(this.id)}` ).style.backgroundColor = 'red'; } break; } } } else { switch (chosenShip) { case 4: if (fourSquaresHorizontal(row, column, userPositions)) { for (var i = 0; i < 4; i++) { document.getElementById( `${parseInt(this.id) + i}` ).style.backgroundColor = 'green'; } } else { for (var i = 0; i < 4; i++) { document.getElementById( `${parseInt(this.id) + i}` ).style.backgroundColor = 'red'; } } break; case 3: if (threeSquaresHorizontal(row, column, userPositions)) { for (var i = 0; i < 3; i++) { document.getElementById( `${parseInt(this.id) + i}` ).style.backgroundColor = 'green'; } } else { for (var i = 0; i < 3; i++) { document.getElementById( `${parseInt(this.id) + i}` ).style.backgroundColor = 'red'; } } break; case 2: if (twoSquaresHorizontal(row, column, userPositions)) { document.getElementById( `${parseInt(this.id)}` ).style.backgroundColor = 'green'; document.getElementById( `${parseInt(this.id) + 1}` ).style.backgroundColor = 'green'; } else { document.getElementById( `${parseInt(this.id)}` ).style.backgroundColor = 'red'; document.getElementById( `${parseInt(this.id) + 1}` ).style.backgroundColor = 'red'; } break; case 1: if (oneSquareHorizontal(row, column, userPositions)) { document.getElementById( `${parseInt(this.id)}` ).style.backgroundColor = 'green'; } else { document.getElementById( `${parseInt(this.id)}` ).style.backgroundColor = 'red'; } break; } } } else if (userDirection === 'vertical') { if ( (((hoveredSquare.id.substr(0, 1) === '7' && hoveredSquare.id.length !== 1) || parseInt(hoveredSquare.id) === 80) && chosenShip === 4) || (((hoveredSquare.id.substr(0, 1) === '8' && hoveredSquare.id.length !== 1) || parseInt(hoveredSquare.id) === 90) && chosenShip === 4) || (((hoveredSquare.id.substr(0, 1) === '8' && hoveredSquare.id.length !== 1) || parseInt(hoveredSquare.id) === 90) && chosenShip === 3) || (((hoveredSquare.id.substr(0, 1) === '9' && hoveredSquare.id.length !== 1) || parseInt(hoveredSquare.id) === 100) && chosenShip === 4) || (((hoveredSquare.id.substr(0, 1) === '9' && hoveredSquare.id.length !== 1) || parseInt(hoveredSquare.id) === 100) && chosenShip === 3) || (((hoveredSquare.id.substr(0, 1) === '9' && hoveredSquare.id.length !== 1) || parseInt(hoveredSquare.id) === 100) && chosenShip === 2) ) verticalBruh = true; if (verticalBruh) { if ( ((hoveredSquare.id.substr(0, 1) === '7' && hoveredSquare.id.length !== 1) || parseInt(hoveredSquare.id) === 80) && chosenShip === 4 ) { verticalBruh = true; if (fourSquaresVertical(row - 1, column, userPositions)) { for (var i = -1; i < 3; i++) { document.getElementById( `${parseInt(this.id) + i * 10}` ).style.backgroundColor = 'green'; } } else { for (var i = -1; i < 3; i++) { document.getElementById( `${parseInt(this.id) + i * 10}` ).style.backgroundColor = 'red'; } } } else if ( ((hoveredSquare.id.substr(0, 1) === '8' && hoveredSquare.id.length !== 1) || parseInt(hoveredSquare.id) === 90) && chosenShip === 4 ) { verticalBruh = true; if (fourSquaresVertical(row - 2, column, userPositions)) { for (var i = -2; i < 2; i++) { document.getElementById( `${parseInt(this.id) + i * 10}` ).style.backgroundColor = 'green'; } } else { for (var i = -2; i < 2; i++) { document.getElementById( `${parseInt(this.id) + i * 10}` ).style.backgroundColor = 'red'; } } } else if ( ((hoveredSquare.id.substr(0, 1) === '8' && hoveredSquare.id.length !== 1) || parseInt(hoveredSquare.id) === 90) && chosenShip === 3 ) { verticalBruh = true; if (threeSquaresVertical(row - 1, column, userPositions)) { for (var i = -1; i < 2; i++) { document.getElementById( `${parseInt(this.id) + i * 10}` ).style.backgroundColor = 'green'; } } else { for (var i = -1; i < 2; i++) { document.getElementById( `${parseInt(this.id) + i * 10}` ).style.backgroundColor = 'red'; } } } else if ( ((hoveredSquare.id.substr(0, 1) === '9' && hoveredSquare.id.length !== 1) || parseInt(hoveredSquare.id) === 100) && chosenShip === 4 ) { verticalBruh = true; if (fourSquaresVertical(row - 3, column, userPositions)) { for (var i = -3; i < 1; i++) { document.getElementById( `${parseInt(this.id) + i * 10}` ).style.backgroundColor = 'green'; } } else { for (var i = -3; i < 1; i++) { document.getElementById( `${parseInt(this.id) + i * 10}` ).style.backgroundColor = 'red'; } } } else if ( ((hoveredSquare.id.substr(0, 1) === '9' && hoveredSquare.id.length !== 1) || parseInt(hoveredSquare.id) === 100) && chosenShip === 3 ) { verticalBruh = true; if (threeSquaresVertical(row - 2, column, userPositions)) { for (var i = -2; i < 1; i++) { document.getElementById( `${parseInt(this.id) + i * 10}` ).style.backgroundColor = 'green'; } } else { for (var i = -2; i < 1; i++) { document.getElementById( `${parseInt(this.id) + i * 10}` ).style.backgroundColor = 'red'; } } } else if ( ((hoveredSquare.id.substr(0, 1) === '9' && hoveredSquare.id.length !== 1) || parseInt(hoveredSquare.id) === 100) && chosenShip === 2 ) { verticalBruh = true; if (twoSquaresVertical(row - 1, column, userPositions)) { document.getElementById( `${parseInt(this.id) - 10}` ).style.backgroundColor = 'green'; document.getElementById( `${parseInt(this.id)}` ).style.backgroundColor = 'green'; } else { document.getElementById( `${parseInt(this.id) - 10}` ).style.backgroundColor = 'red'; document.getElementById( `${parseInt(this.id)}` ).style.backgroundColor = 'red'; } } } else { switch (chosenShip) { case 4: if (fourSquaresVertical(row, column, userPositions)) { for (var i = 0; i < 4; i++) { document.getElementById( `${parseInt(this.id) + i * 10}` ).style.backgroundColor = 'green'; } } else { for (var i = 0; i < 4; i++) { document.getElementById( `${parseInt(this.id) + i * 10}` ).style.backgroundColor = 'red'; } } break; case 3: if (threeSquaresVertical(row, column, userPositions)) { for (var i = 0; i < 3; i++) { document.getElementById( `${parseInt(this.id) + i * 10}` ).style.backgroundColor = 'green'; } } else { for (var i = 0; i < 3; i++) { document.getElementById( `${parseInt(this.id) + i * 10}` ).style.backgroundColor = 'red'; } } break; case 2: if (twoSquaresVertical(row, column, userPositions)) { document.getElementById( `${parseInt(this.id)}` ).style.backgroundColor = 'green'; document.getElementById( `${parseInt(this.id) + 10}` ).style.backgroundColor = 'green'; } else { document.getElementById( `${parseInt(this.id)}` ).style.backgroundColor = 'red'; document.getElementById( `${parseInt(this.id) + 10}` ).style.backgroundColor = 'red'; } break; case 1: if (oneSquareVertical(row, column, userPositions)) { document.getElementById( `${parseInt(this.id)}` ).style.backgroundColor = 'green'; } else { document.getElementById( `${parseInt(this.id)}` ).style.backgroundColor = 'red'; } break; } } } }; square.onclick = function () { let hoveredSquare = document.getElementById(`${this.id}`); if (chosenShip != undefined && this.style.backgroundColor != 'red') { if (userDirection === 'horizontal') { if (horizontalBruh) { if (parseInt(hoveredSquare.id) % 10 == 8 && chosenShip === 4) { document.getElementById( `${parseInt(this.id) - 1}` ).style.backgroundColor = 'black'; document.getElementById( `${parseInt(this.id)}` ).style.backgroundColor = 'black'; document.getElementById( `${parseInt(this.id) + 1}` ).style.backgroundColor = 'black'; document.getElementById( `${parseInt(this.id) + 2}` ).style.backgroundColor = 'black'; document .getElementById(`${parseInt(this.id) - 1}`) .classList.add('occupied'); document .getElementById(`${parseInt(this.id)}`) .classList.add('occupied'); document .getElementById(`${parseInt(this.id) + 1}`) .classList.add('occupied'); document .getElementById(`${parseInt(this.id) + 2}`) .classList.add('occupied'); userPositions[row][column - 1] = 1; userPositions[row][column] = 1; userPositions[row][column + 1] = 1; userPositions[row][column + 2] = 1; } else if ( parseInt(hoveredSquare.id) % 10 == 9 && chosenShip === 4 ) { document.getElementById( `${parseInt(this.id) - 2}` ).style.backgroundColor = 'black'; document.getElementById( `${parseInt(this.id) - 1}` ).style.backgroundColor = 'black'; document.getElementById( `${parseInt(this.id)}` ).style.backgroundColor = 'black'; document.getElementById( `${parseInt(this.id) + 1}` ).style.backgroundColor = 'black'; document .getElementById(`${parseInt(this.id) - 2}`) .classList.add('occupied'); document .getElementById(`${parseInt(this.id) - 1}`) .classList.add('occupied'); document .getElementById(`${parseInt(this.id)}`) .classList.add('occupied'); document .getElementById(`${parseInt(this.id) + 1}`) .classList.add('occupied'); userPositions[row][column - 2] = 1; userPositions[row][column - 1] = 1; userPositions[row][column] = 1; userPositions[row][column + 1] = 1; } else if ( parseInt(hoveredSquare.id) % 10 == 9 && chosenShip === 3 ) { document.getElementById( `${parseInt(this.id) - 1}` ).style.backgroundColor = 'black'; document.getElementById( `${parseInt(this.id)}` ).style.backgroundColor = 'black'; document.getElementById( `${parseInt(this.id) + 1}` ).style.backgroundColor = 'black'; document .getElementById(`${parseInt(this.id) - 1}`) .classList.add('occupied'); document .getElementById(`${parseInt(this.id)}`) .classList.add('occupied'); document .getElementById(`${parseInt(this.id) + 1}`) .classList.add('occupied'); userPositions[row][column - 1] = 1; userPositions[row][column] = 1; userPositions[row][column + 1] = 1; } else if ( parseInt(hoveredSquare.id) % 10 == 0 && chosenShip === 4 ) { document.getElementById( `${parseInt(this.id) - 3}` ).style.backgroundColor = 'black'; document.getElementById( `${parseInt(this.id) - 2}` ).style.backgroundColor = 'black'; document.getElementById( `${parseInt(this.id) - 1}` ).style.backgroundColor = 'black'; document.getElementById( `${parseInt(this.id)}` ).style.backgroundColor = 'black'; document .getElementById(`${parseInt(this.id) - 3}`) .classList.add('occupied'); document .getElementById(`${parseInt(this.id) - 2}`) .classList.add('occupied'); document .getElementById(`${parseInt(this.id) - 1}`) .classList.add('occupied'); document .getElementById(`${parseInt(this.id)}`) .classList.add('occupied'); userPositions[row][column - 3] = 1; userPositions[row][column - 2] = 1; userPositions[row][column - 1] = 1; userPositions[row][column] = 1; } else if ( parseInt(hoveredSquare.id) % 10 == 0 && chosenShip === 3 ) { document.getElementById( `${parseInt(this.id) - 2}` ).style.backgroundColor = 'black'; document.getElementById( `${parseInt(this.id) - 1}` ).style.backgroundColor = 'black'; document.getElementById( `${parseInt(this.id)}` ).style.backgroundColor = 'black'; document .getElementById(`${parseInt(this.id) - 2}`) .classList.add('occupied'); document .getElementById(`${parseInt(this.id) - 1}`) .classList.add('occupied'); document .getElementById(`${parseInt(this.id)}`) .classList.add('occupied'); userPositions[row][column - 2] = 1; userPositions[row][column - 1] = 1; userPositions[row][column] = 1; } else if ( parseInt(hoveredSquare.id) % 10 == 0 && chosenShip === 2 ) { document.getElementById( `${parseInt(this.id) - 1}` ).style.backgroundColor = 'black'; document.getElementById( `${parseInt(this.id)}` ).style.backgroundColor = 'black'; document .getElementById(`${parseInt(this.id) - 1}`) .classList.add('occupied'); document .getElementById(`${parseInt(this.id)}`) .classList.add('occupied'); userPositions[row][column - 1] = 1; userPositions[row][column] = 1; } } else { switch (chosenShip) { case 4: document.getElementById( `${parseInt(this.id)}` ).style.backgroundColor = 'black'; document.getElementById( `${parseInt(this.id) + 1}` ).style.backgroundColor = 'black'; document.getElementById( `${parseInt(this.id) + 2}` ).style.backgroundColor = 'black'; document.getElementById( `${parseInt(this.id) + 3}` ).style.backgroundColor = 'black'; document .getElementById(`${parseInt(this.id)}`) .classList.add('occupied'); document .getElementById(`${parseInt(this.id) + 1}`) .classList.add('occupied'); document .getElementById(`${parseInt(this.id) + 2}`) .classList.add('occupied'); document .getElementById(`${parseInt(this.id) + 3}`) .classList.add('occupied'); userPositions[row][column] = 1; userPositions[row][column + 1] = 1; userPositions[row][column + 2] = 1; userPositions[row][column + 3] = 1; break; case 3: document.getElementById( `${parseInt(this.id)}` ).style.backgroundColor = 'black'; document.getElementById( `${parseInt(this.id) + 1}` ).style.backgroundColor = 'black'; document.getElementById( `${parseInt(this.id) + 2}` ).style.backgroundColor = 'black'; document .getElementById(`${parseInt(this.id)}`) .classList.add('occupied'); document .getElementById(`${parseInt(this.id) + 1}`) .classList.add('occupied'); document .getElementById(`${parseInt(this.id) + 2}`) .classList.add('occupied'); userPositions[row][column] = 1; userPositions[row][column + 1] = 1; userPositions[row][column + 2] = 1; break; case 2: document.getElementById( `${parseInt(this.id)}` ).style.backgroundColor = 'black'; document.getElementById( `${parseInt(this.id) + 1}` ).style.backgroundColor = 'black'; document .getElementById(`${parseInt(this.id)}`) .classList.add('occupied'); document .getElementById(`${parseInt(this.id) + 1}`) .classList.add('occupied'); userPositions[row][column] = 1; userPositions[row][column + 1] = 1; break; case 1: document.getElementById( `${parseInt(this.id)}` ).style.backgroundColor = 'black'; document .getElementById(`${parseInt(this.id)}`) .classList.add('occupied'); userPositions[row][column] = 1; break; } } } else if (userDirection === 'vertical') { if (verticalBruh) { if ( (hoveredSquare.id.substr(0, 1) === '7' || parseInt(hoveredSquare.id) === 80) && chosenShip === 4 ) { document.getElementById( `${parseInt(this.id) - 10}` ).style.backgroundColor = 'black'; document.getElementById( `${parseInt(this.id)}` ).style.backgroundColor = 'black'; document.getElementById( `${parseInt(this.id) + 10}` ).style.backgroundColor = 'black'; document.getElementById( `${parseInt(this.id) + 20}` ).style.backgroundColor = 'black'; document .getElementById(`${parseInt(this.id) - 10}`) .classList.add('occupied'); document .getElementById(`${parseInt(this.id)}`) .classList.add('occupied'); document .getElementById(`${parseInt(this.id) + 10}`) .classList.add('occupied'); document .getElementById(`${parseInt(this.id) + 20}`) .classList.add('occupied'); userPositions[row - 1][column] = 1; userPositions[row][column] = 1; userPositions[row + 1][column] = 1; userPositions[row + 2][column] = 1; } else if ( (hoveredSquare.id.substr(0, 1) === '8' || parseInt(hoveredSquare.id) === 90) && chosenShip === 4 ) { document.getElementById( `${parseInt(this.id) - 20}` ).style.backgroundColor = 'black'; document.getElementById( `${parseInt(this.id) - 10}` ).style.backgroundColor = 'black'; document.getElementById( `${parseInt(this.id)}` ).style.backgroundColor = 'black'; document.getElementById( `${parseInt(this.id) + 10}` ).style.backgroundColor = 'black'; document .getElementById(`${parseInt(this.id) - 20}`) .classList.add('occupied'); document .getElementById(`${parseInt(this.id) - 10}`) .classList.add('occupied'); document .getElementById(`${parseInt(this.id)}`) .classList.add('occupied'); document .getElementById(`${parseInt(this.id) + 10}`) .classList.add('occupied'); userPositions[row - 2][column] = 1; userPositions[row - 1][column] = 1; userPositions[row][column] = 1; userPositions[row + 1][column] = 1; } else if ( (hoveredSquare.id.substr(0, 1) === '8' || parseInt(hoveredSquare.id) === 90) && chosenShip === 3 ) { document.getElementById( `${parseInt(this.id) - 10}` ).style.backgroundColor = 'black'; document.getElementById( `${parseInt(this.id)}` ).style.backgroundColor = 'black'; document.getElementById( `${parseInt(this.id) + 10}` ).style.backgroundColor = 'black'; document .getElementById(`${parseInt(this.id) - 10}`) .classList.add('occupied'); document .getElementById(`${parseInt(this.id)}`) .classList.add('occupied'); document .getElementById(`${parseInt(this.id) + 10}`) .classList.add('occupied'); userPositions[row - 1][column] = 1; userPositions[row][column] = 1; userPositions[row + 1][column] = 1; } else if ( (hoveredSquare.id.substr(0, 1) === '9' || parseInt(hoveredSquare.id) === 100) && chosenShip === 4 ) { document.getElementById( `${parseInt(this.id) - 30}` ).style.backgroundColor = 'black'; document.getElementById( `${parseInt(this.id) - 20}` ).style.backgroundColor = 'black'; document.getElementById( `${parseInt(this.id) - 10}` ).style.backgroundColor = 'black'; document.getElementById( `${parseInt(this.id)}` ).style.backgroundColor = 'black'; document .getElementById(`${parseInt(this.id) - 30}`) .classList.add('occupied'); document .getElementById(`${parseInt(this.id) - 20}`) .classList.add('occupied'); document .getElementById(`${parseInt(this.id) - 10}`) .classList.add('occupied'); document .getElementById(`${parseInt(this.id)}`) .classList.add('occupied'); userPositions[row - 3][column] = 1; userPositions[row - 2][column] = 1; userPositions[row - 1][column] = 1; userPositions[row][column] = 1; } else if ( (hoveredSquare.id.substr(0, 1) === '9' || parseInt(hoveredSquare.id) === 100) && chosenShip === 3 ) { document.getElementById( `${parseInt(this.id) - 20}` ).style.backgroundColor = 'black'; document.getElementById( `${parseInt(this.id) - 10}` ).style.backgroundColor = 'black'; document.getElementById( `${parseInt(this.id)}` ).style.backgroundColor = 'black'; document .getElementById(`${parseInt(this.id) - 20}`) .classList.add('occupied'); document .getElementById(`${parseInt(this.id) - 10}`) .classList.add('occupied'); document .getElementById(`${parseInt(this.id)}`) .classList.add('occupied'); userPositions[row - 2][column] = 1; userPositions[row - 1][column] = 1; userPositions[row][column] = 1; } else if ( (hoveredSquare.id.substr(0, 1) === '9' || parseInt(hoveredSquare.id) === 100) && chosenShip === 2 ) { document.getElementById( `${parseInt(this.id) - 10}` ).style.backgroundColor = 'black'; document.getElementById( `${parseInt(this.id)}` ).style.backgroundColor = 'black'; document .getElementById(`${parseInt(this.id) - 10}`) .classList.add('occupied'); document .getElementById(`${parseInt(this.id)}`) .classList.add('occupied'); userPositions[row - 1][column] = 1; userPositions[row][column] = 1; } } else { switch (chosenShip) { case 4: document.getElementById( `${parseInt(this.id)}` ).style.backgroundColor = 'black'; document.getElementById( `${parseInt(this.id) + 10}` ).style.backgroundColor = 'black'; document.getElementById( `${parseInt(this.id) + 20}` ).style.backgroundColor = 'black'; document.getElementById( `${parseInt(this.id) + 30}` ).style.backgroundColor = 'black'; document .getElementById(`${parseInt(this.id)}`) .classList.add('occupied'); document .getElementById(`${parseInt(this.id) + 10}`) .classList.add('occupied'); document .getElementById(`${parseInt(this.id) + 20}`) .classList.add('occupied'); document .getElementById(`${parseInt(this.id) + 30}`) .classList.add('occupied'); userPositions[row][column] = 1; userPositions[row + 1][column] = 1; userPositions[row + 2][column] = 1; userPositions[row + 3][column] = 1; break; case 3: document.getElementById( `${parseInt(this.id)}` ).style.backgroundColor = 'black'; document.getElementById( `${parseInt(this.id) + 10}` ).style.backgroundColor = 'black'; document.getElementById( `${parseInt(this.id) + 20}` ).style.backgroundColor = 'black'; document .getElementById(`${parseInt(this.id)}`) .classList.add('occupied'); document .getElementById(`${parseInt(this.id) + 10}`) .classList.add('occupied'); document .getElementById(`${parseInt(this.id) + 20}`) .classList.add('occupied'); userPositions[row][column] = 1; userPositions[row + 1][column] = 1; userPositions[row + 2][column] = 1; break; case 2: document.getElementById( `${parseInt(this.id)}` ).style.backgroundColor = 'black'; document.getElementById( `${parseInt(this.id) + 10}` ).style.backgroundColor = 'black'; document .getElementById(`${parseInt(this.id)}`) .classList.add('occupied'); document .getElementById(`${parseInt(this.id) + 10}`) .classList.add('occupied'); userPositions[row][column] = 1; userPositions[row + 1][column] = 1; break; case 1: document.getElementById( `${parseInt(this.id)}` ).style.backgroundColor = 'black'; document .getElementById(`${parseInt(this.id)}`) .classList.add('occupied'); userPositions[row][column] = 1; break; } } } let el = document.getElementsByClassName(chosenShip2); el[0].remove(); chosenShip = undefined; chosenShip2 = undefined; userDirection = 'horizontal'; } if (document.getElementById('shipsBoard').innerHTML === '' && !noShips) { noShips = !noShips; let btn = document.createElement('button'); btn.innerText = 'Rozpocznij grę'; btn.id = 'start-btn'; btn.classList.add('btn'); btn.onclick = function () { gameHasStarted = !gameHasStarted; btn.disabled = 'true'; userBoard.onclick = function () { if (gameHasStarted) { if (turn === 'user') { alert('Ruch gracza!'); } else { alert('Poczekaj aż komputer wykona ruch!'); } } }; }; document.body.style.width = '900px'; document.body.appendChild(btn); } }; userBoard.appendChild(square); } }; //TODO popraw context menu na skrajach setUserBoard(); //losowanie i zwracanie wylosowanego kierunku jeśli można postawić na wylosowanej pozycji statek function returnDirection(element) { while (compDirection == undefined) { generatePosition(); let dir = Math.floor(Math.random() * 2); if (dir === 0) { if (compPositions[compRow][compColumn + element - 1] != undefined) compDirection = 'horizontal'; } else if (dir === 1 || compDirection == undefined) { if (compPositions[compRow + element - 1] != undefined) compDirection = 'vertical'; } if (compDirection === 'horizontal') { compDirection = undefined; switch (element) { case 4: if (fourSquaresHorizontal(compRow, compColumn, compPositions)) compDirection = 'horizontal'; break; case 3: if (threeSquaresHorizontal(compRow, compColumn, compPositions)) compDirection = 'horizontal'; break; case 2: if (twoSquaresHorizontal(compRow, compColumn, compPositions)) compDirection = 'horizontal'; break; case 1: if (oneSquareHorizontal(compRow, compColumn, compPositions)) compDirection = 'horizontal'; break; } } else if (compDirection === 'vertical' || compDirection == undefined) { compDirection = undefined; switch (element) { case 4: if (fourSquaresVertical(compRow, compColumn, compPositions)) compDirection = 'vertical'; break; case 3: if (threeSquaresVertical(compRow, compColumn, compPositions)) compDirection = 'vertical'; break; case 2: if (twoSquaresVertical(compRow, compColumn, compPositions)) compDirection = 'vertical'; break; case 1: if (oneSquareVertical(compRow, compColumn, compPositions)) compDirection = 'vertical'; break; } } } return compDirection; } //wylosowanie pozycji, ustawienie wiersza i kolumny dla komputera function generatePosition() { compPosition = Math.ceil(Math.random() * 100); if (compPosition < 10) compRow = 1; else compRow = Math.ceil(compPosition / 10); if (compPosition % 10 == 0) compColumn = 10; else compColumn = compPosition - Math.floor(compPosition / 10) * 10; } //strzał komputera function computerShot() { if (!isGameOver) { setTimeout(() => { let randomPosition = Math.ceil(Math.random() * 100); while ( document .getElementById(`${randomPosition}`) .className.substr( document.getElementById(`${randomPosition}`).className.length - 4 ) .trim() == 'miss' || document .getElementById(`${randomPosition}`) .className.substr( document.getElementById(`${randomPosition}`).className.length - 4 ) .trim() == 'hit' ) { randomPosition = Math.ceil(Math.random() * 100); } if ( document.getElementById(`${randomPosition}`).style.backgroundColor === 'black' ) { const hit = document.createElement('img'); hit.src = './hit.png'; document.getElementById(`${randomPosition}`).classList.add('hit'); document.getElementById(`${randomPosition}`).appendChild(hit); document.getElementById(`${randomPosition}`).style.backgroundColor = 'black'; compGoodShots++; compLastShot = 'hit'; } else if ( document.getElementById(`${randomPosition}`).style.backgroundColor === 'white' ) { const miss = document.createElement('img'); miss.src = './miss.png'; document.getElementById(`${randomPosition}`).classList.add('miss'); document.getElementById(`${randomPosition}`).appendChild(miss); compLastShot = 'miss'; } if (compLastShot === 'miss') { turn = 'user'; } if (compLastShot === 'hit') { computerShot(); } if (compGoodShots === 20) computerWin(); }, 1000); } } //wygrana usera function userWin() { isGameOver = !isGameOver; alert('Wygrałeś!'); let btn = document.createElement('button'); btn.innerText = 'Nowa gra'; btn.id = 'new-game'; btn.classList.add('btn'); btn.onclick = function () { clearEverything(); }; document.body.removeChild(document.body.lastChild); document.body.appendChild(btn); } //wygrana komputera function computerWin() { isGameOver = !isGameOver; alert('Wygrał komputer!'); compPositions.forEach((higherElement, higherIndex) => { higherElement.forEach((lowerElement, lowerIndex) => { if (lowerElement === 1) { if (higherIndex === 1) { let el = document.getElementsByClassName(`${lowerIndex}`); el[0].style.backgroundColor = 'black'; } else if (higherIndex === 10 && lowerIndex === 10) { let el = document.getElementsByClassName('100'); el[0].style.backgroundColor = 'black'; } else { if (lowerIndex % 10 == 0) { let el = document.getElementsByClassName(`${higherIndex}0`); el[0].style.backgroundColor = 'black'; } else { let el = document.getElementsByClassName( `${higherIndex - 1}${lowerIndex}` ); el[0].style.backgroundColor = 'black'; } } } }); }); let btn = document.createElement('button'); btn.innerText = 'Nowa gra'; btn.id = 'new-game'; btn.classList.add('btn'); btn.onclick = function () { clearEverything(); }; document.body.removeChild(document.body.lastChild); document.body.appendChild(btn); } //czyszczenie wszystkiego i przygotowanie nowej gry function clearEverything() { //zmienne komputera compDirection = undefined; compRow = 0; compColumn = 0; compPosition = 0; compPositions = [ [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, 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, 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], [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, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], ]; //zmienne usera userDirection = 'horizontal'; chosenShip = 4; chosenShip2 = '1'; noShips = false; userPositions = [ [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, 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, 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], [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, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], ]; //zmienne gry gameHasStarted = false; turn = 'user'; counter = 1; userGoodShots = 0; compGoodShots = 0; isGameOver = false; userLastShot = 'miss'; compLastShot = 'miss'; //usunięcie przycisku nowa graq for (var i = 0; i < 4; i++) { document.body.removeChild(document.body.lastChild); } //wyczyszczenie plansz userBoard.innerHTML = ''; shipsBoard.innerHTML = ''; compBoard.innerHTML = ''; userBoard.style.cursor = 'arrow'; //rozstawienie plansz użytownika i komputera setCompShips(); setCompBoard(); giveShipsToUser(); setUserBoard(); //dodanie plansz na stronę document.body.style.width = '1000px'; document.body.appendChild(shipsBoard); document.body.appendChild(userBoard); document.body.appendChild(compBoard); } //dodanie plansz na stronę document.body.appendChild(shipsBoard); document.body.appendChild(userBoard); document.body.appendChild(compBoard);
Java
UTF-8
1,659
3.3125
3
[]
no_license
import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.function.BiFunction; import java.util.function.Function; import java.util.function.Predicate; import java.util.stream.Collectors; class ListOps { static <T> List<T> append(List<T> list1, List<T> list2) { ArrayList list1AsArrayList = new ArrayList(list1); list1AsArrayList.addAll(list2); return list1AsArrayList; } static <T> List<T> concat(List<List<T>> listOfLists) { List<T> result = new ArrayList(); listOfLists.forEach(x -> result.addAll(x)); return result; } static <T> List<T> filter(List<T> list, Predicate<T> predicate) { return list.stream().filter(predicate).collect(Collectors.toList()); } static <T> int size(List<T> list) { return list.size(); } static <T, U> List<U> map(List<T> list, Function<T, U> transform) { throw new UnsupportedOperationException("Delete this statement and write your own implementation."); } static <T> List<T> reverse(List<T> list) { throw new UnsupportedOperationException("Delete this statement and write your own implementation."); } static <T, U> U foldLeft(List<T> list, U initial, BiFunction<U, T, U> f) { throw new UnsupportedOperationException("Delete this statement and write your own implementation."); } static <T, U> U foldRight(List<T> list, U initial, BiFunction<T, U, U> f) { throw new UnsupportedOperationException("Delete this statement and write your own implementation."); } private ListOps() { // No instances. } }
Markdown
UTF-8
7,673
2.859375
3
[]
no_license
--- title: Head First Python 笔记 date: tags: python入门 categories: python --- ### 第一章 点记法调用方法 append()--列表末尾添加 pop()--列表末尾删除 extend()--列表末尾添加数据项集合 remove()--删除特定项 insert(0,'able')--特定位置前添加项 len()--长度 for 目标标识符 in 列表: 列表处理 (!for 只打印外列表的各数据项) isinstance()--判断当前处理的特定标识符是否本身为某特定类型数据 dir(_bulitins_)--BIF列表 if 必有一个else与之对应 def 函数名(参数): 内容 列表用中括号包围 ### 第二章 模块 ####自建模块(windows) 1、将模块文件nester.py放到模块文件夹nester中 2、模块文件夹中创建setup.py,包含有关发布的元数据 from distutils.core import setup setup( name = 'nester', version = '1.0.0', py_modules = ['nester'], author = 'hfpython',--可以不同 author_email = 'hfpython@headfirstlabs.com',-- url = 'http://www.headfirstlabs.com'-- description = 'A simple printer of nested lists',-- ) 3、构建发布文件: 在模块文件夹nester中打开终端窗口,键入命令 E:\coding\python3.6.2\python.exe(Python安装路径) setup.py sdist 4、将发布安装到python本地副本中 E:\coding\python3.6.2\python.exe(安装路径) setup.py install **准备就绪** #### 导入使用模块 导入:import 模块名 使用时注意命名空间:**nester**.python_lol() from module import function--导入模块到当前命名空间(模块中的内容可能覆盖自己定义的内容) import sys; sys.path--展示已有模块路径 range(4)--给定范围(不包括给定数据) end=''--作为print()BIF的一个参数会:在输入中自动包含换行 indent 缩进 ### 第三章 文件与异常 open()BIF--打开磁盘文件,一次读取一个数据行 import os--导入os模块 os.getcwd()--查询当前工作目录 data.readline()--从打开的文件获取一个数据行 data.seek(0)--返回文件起始位置 python的文件也可使用tell() 命令行中使用for... in ...:后下一行要使用tab缩进 data.close()--文件处理完一定关闭 (":",1)--以:来分解,可选参数控制将数据行分为几部分,设为1可分为两部分 (role,line_spoken) = each_line.split(':',1) find(':')--找出一个字符串的子串,找不到返回-1,找到返回子串在原字符串中的索引位置 (tuple)--不可改变值 ValueError--数据格式不符合期望 IOError--数据无法正常访问 #### 异常处理 try: 保护代码 except:--要用一种不那么一般化的方式使用except--指定异常 替代代码 import os if os.path.exists('sketch.txt'):--检查文件是否存在 data = open('sketch.txt') . . . else: print('The data file is missing!') ##### 特殊化异常 try: ... except **ValueError**:--或者IOError pass ### 第四章 strip()--该方法从字符串中去除空白字符 out = open('data.out','w')--默认r,若以写模式使用w file参数指定数据文件对象 print("Norwegian Blues stun easily.",**file=out**)--file参数控制将数据发送/保存到哪里 str()访问任何数据对象(支持串转换)的串表示 out.close()--刷新输出!! open的参数: **w**:文件存在--清空其全部内容 文件不存在--先创建这个文件,再打开文件写 访问模式**a**:追加到文件 **w+**:打开一个文件完成读写(不清除) #### try中的finally扩展 --不论出现什么错误都必须运行finally中的代码 locals()--返回当前作用域中定义的所有名(变量)的一个集合 in --测试成员关系 + --联接字符串,两数相加 ##### 显示具体错误内容!!! try: data = open('missing.txt') print(data.readline(),end='') except IOError as err:#为异常对象给定一个名字 print('File error:'+str(err))#err类型必须为str,可以知道具体哪里出了问题 finally: if 'data'in locals(): data.close() #### with技术使代码简洁 使用with可以不考虑close(),可自动关闭已打开文件,即使异常也不例外,with也使用as关键字 #### 格式化输出 标准输出(standard output):sys.stdout 可从标准库的“sys”模块导入 使用之前定义的模块nester print(value,sep='',end='\n',file=sys.stdout)有4个参数 只有缺省值不是想要的值时才需要提供值 调用时可以: print('Dead Parrot Sketch',file='myfavmonty.txt') #### 持久存储 pickle--标准库,可保存加载py数据对象(包括列表) 允许容易而高效地将py数据对象保存到磁盘以及从磁盘恢复 腌制--将数据对象保存到一个持久存储中的过程中 解除腌制--从持久态恢复到已保存的数据对象的过程 dump()--保存数据至硬盘 load()--从硬盘恢复数据 处理数据要求:以二进制访问模式打开 --open使用wb/rb import pickle #导入模块 ... with open('mydata.pickle','wb') as mysavedata:# 保存用dump() pickle.dump([1,2,'three'],mysavadata) ... with open('mydata.pickle','rb') as myrestoredata:# 恢复用load() a_list = pickle.load(myrestoredata) print(a_list) ### 第五章 处理数据 方法串链:james = data.strip().split(',')--从左向右读 ??有顺序要求吗--有啊,但是还不知道是啥样的要求 函数串联:对数据应用一系列函数--从右向左读 嵌套 ####排序 原地排序:排序并替换,原顺序丢失 对于列表:sort()方法 复制排序:返回有序副本,原顺序保留 sorted()BIF--注意BIF和方法使用方式不一样 如果传入 reverse=True可按 **降序**排列数据 data2 = sorted(data) #### 推导列表 #####注意顺序: james1 = sorted([sanitize(j) for j in james])--将规格化的数据排序 james1 = [sorted(sanitize(j)) for j in james]--将每个字符规格化排好序 ####删除重复 #####方法一 julie = sorted([sanitize(j) for j in julie]) unique_julie = [] for each_t in julie: if each_t not in unique_julie: unique_julie.append(each_t) print(unique_julie[0:3]) #####方法二:集合 创建空集合 set()BIF distances = set() distances ={10.6,11,8,10.6,"two",7}--重复项会被忽略 分片 james2 = sorted(set(james1))[0:3]--利用sorted()生成的列表应用分片 ### 第六章 定制数据对象 pop()--调用本方法将 删除并返回列表内指定数据项 x = pop(0)--调用会删除第一个数据并把它赋给指定变量x 定义字典: cleese = {} cleese = dict() #### 打包数据和代码:类 对于面向对象,代码称为类的方法(method)数据称为类的属性(attribute) 实例化的实例化的数据对象:实例(instance) 定义类: class Athlete: def_init_(self): #初始化各对象的代码 __init__()方法的第一个参数都是self(调用对象实例) ![class](hfpy_class_down.png) __init__里是强制绑定初始属性,**init左右各有两个下划线** #####访问限制 内部属性:属性名称前加两个下划线__--私有变量 #####继承和多态 class AthleteList(list): def __init__(self,name): list.__init__([]) self.name=name ### 第七章 web开发
Markdown
UTF-8
1,202
2.9375
3
[]
no_license
#序列化-Rustful ![序列化](Serializer序列化.png) 序列化过程 ```` 在Python的Django框架中,解释就很明显了。将ORM对象(queryset)等转化为JSON或者XML编码格式的数据。 反序列化与之相反。 restful,请求进来(经过视图层),获取数据库中需要的数据,然后转为json格式,那样可以给前端, 或者其他程序调用。或者请求数据以JSON格式进来,转化为数据库能接收的形式, 存到数据库(反序列化)。 ```` ```` 1.我们可以通过统一资源标识符(Universal Resource Identifier,URI)来识别和定位资源, 并且针对这些资源而执行的操作是通过 HTTP 规范定义的。其核心操作只有GET,POST,PUT,DELETE。 也就是:URL定位资源,用HTTP动词(GET,POST,DELETE,DETC)描述操作。 2.因此设计web接口的时候,REST主要是用于定义接口名,接口名一般是用名次写,不用动词, 那怎么表达“获取”或者“删除”或者“更新”这样的操作呢——用请求类型(GET,PUT,POST,DELETE)来区分。 ```` ##实现步骤 ```` 1.配置model 2.在serializers.py中配置model 3.创建视图 4.url路由配置 ````
Java
UTF-8
2,451
2.40625
2
[]
no_license
/* * Created on 18 Apr 2017 ( Time 13:24:45 ) * Generated by Telosys Tools Generator ( version 2.1.1 ) */ package org.trams.hello.business.service.mapping; import org.modelmapper.ModelMapper; import org.modelmapper.convention.MatchingStrategies; import org.springframework.stereotype.Component; import org.trams.hello.bean.VoucherUser; import org.trams.hello.bean.jpa.VoucherEntity; import org.trams.hello.bean.jpa.VoucherUserEntity; /** * Mapping between entity beans and display beans. */ @Component public class VoucherUserServiceMapper extends AbstractServiceMapper { /** * ModelMapper : bean to bean mapping library. */ private ModelMapper modelMapper; /** * Constructor. */ public VoucherUserServiceMapper() { modelMapper = new ModelMapper(); modelMapper.getConfiguration().setMatchingStrategy(MatchingStrategies.STRICT); } /** * Mapping from 'VoucherUserEntity' to 'VoucherUser' * @param voucherUserEntity */ public VoucherUser mapVoucherUserEntityToVoucherUser(VoucherUserEntity voucherUserEntity) { if(voucherUserEntity == null) { return null; } //--- Generic mapping VoucherUser voucherUser = map(voucherUserEntity, VoucherUser.class); //--- Link mapping ( link to Voucher ) if(voucherUserEntity.getVoucher() != null) { voucherUser.setVoucherId(voucherUserEntity.getVoucher().getId()); } return voucherUser; } /** * Mapping from 'VoucherUser' to 'VoucherUserEntity' * @param voucherUser * @param voucherUserEntity */ public void mapVoucherUserToVoucherUserEntity(VoucherUser voucherUser, VoucherUserEntity voucherUserEntity) { if(voucherUser == null) { return; } //--- Generic mapping map(voucherUser, voucherUserEntity); //--- Link mapping ( link : voucherUser ) if( hasLinkToVoucher(voucherUser) ) { VoucherEntity voucher1 = new VoucherEntity(); voucher1.setId( voucherUser.getVoucherId() ); voucherUserEntity.setVoucher( voucher1 ); } else { voucherUserEntity.setVoucher( null ); } } /** * Verify that Voucher id is valid. * @param Voucher Voucher * @return boolean */ private boolean hasLinkToVoucher(VoucherUser voucherUser) { if(voucherUser.getVoucherId() != null) { return true; } return false; } /** * {@inheritDoc} */ @Override protected ModelMapper getModelMapper() { return modelMapper; } protected void setModelMapper(ModelMapper modelMapper) { this.modelMapper = modelMapper; } }
Java
UTF-8
6,016
2.5
2
[]
no_license
package com.whatmygpa.dao; import java.util.List; import javax.persistence.EntityManager; import javax.persistence.EntityTransaction; import javax.persistence.Persistence; import javax.persistence.TypedQuery; import com.whatmygpa.models.CourseEnrollment; import com.whatmygpa.models.CourseEnrollmentPK; import com.whatmygpa.models.Courses; import com.whatmygpa.models.Users; public class CourseEnrollmentServices { // PERSISTENCE_UNIT_NAME is the name recorded in the persistence.xml file private static final String PERSISTENCE_UNIT_NAME = "WhatMyGPA_JPA"; private static EntityManager em = Persistence.createEntityManagerFactory(PERSISTENCE_UNIT_NAME) .createEntityManager(); private static EntityTransaction et = em.getTransaction(); public static List<CourseEnrollment> getAllCourseEnrollmentsWithUser(Users user) { TypedQuery<CourseEnrollment> query = em.createNamedQuery("CourseEnrollment.findAllForUser", CourseEnrollment.class); query.setParameter("user", user); return query.getResultList(); } public static CourseEnrollment getOneCourseEnrollment(Users user, Courses course) { TypedQuery<CourseEnrollment> query = em.createNamedQuery("CourseEnrollment.findSpecific", CourseEnrollment.class); query.setParameter("user", user); query.setParameter("course", course); return query.getSingleResult(); } private static double calculateEarnedGrade(int credits, int grade) { return getScale(grade) * credits; } public static double calculateOverallGPA(Users user) { // public static void calculateOverallGPA(Users user) { TypedQuery<CourseEnrollment> query = em.createNamedQuery("CourseEnrollment.findByUser", CourseEnrollment.class); query.setParameter("user", user); List<CourseEnrollment> ce = query.getResultList(); // sum all earnedGpa for course enrollments with this user.id double sumEarnedGpa = 0; // sum all credits for course enrollments.course with this user.id int sumCredits = 0; for (CourseEnrollment courseEnrollment : ce) { sumEarnedGpa += courseEnrollment.getEarnedGPA(); sumCredits += courseEnrollment.getCourse().getCredits(); } System.out.println("sumearnedgpa " + sumEarnedGpa); System.out.println("sumCredits " + sumCredits); // divide 1/2 = overallgpa double overallGpa = sumEarnedGpa / sumCredits; System.out.println("overallGpa " + overallGpa); return overallGpa; // try { // et.begin(); // Users updatedUser = user; // updatedUser.setGpa(overallGpa); // // updatedCourse.setCredits(credits); // em.persist(updatedUser); // // automatic rollback on SQL Exception // et.commit(); // } catch (RollbackException re) { // re.printStackTrace(System.err); // } // et.begin(); // try { // // // update user overall gpa // // user.setGpa(calculateOverallGPA(user)); // // Query query2 = em.createQuery("UPDATE users u SET gpa = " + overallGpa + // "WHERE u.id = :id"); // query2.setParameter("id", user.getId()); // query2.executeUpdate(); // // // persist course enrollment // // em.persist(user); // // // update user overall gpa - this will become virtual field, not stored in // user // // table // // em.flush(); // et.commit(); // } catch (Exception e) { // et.rollback(); // } } public static void addCourseEnrollment(Users user, Courses course, int gradeReceived) { et.begin(); try { // create new course enrollment CourseEnrollment enrollment = new CourseEnrollment(); // user . add course enrollment (enrollment) user.addCourseEnrollment(enrollment); // course . add course enrollment (enrollment) course.addCourseEnrollment(enrollment); // calculate earnedGPA, set for enrollment // scale * credits = earned GPA for this course // e.g. A+ for 4.0 credits = 18.0 earned gpa // overall GPA = sum of earnedGPA/sum of credits // enrollment.setEarnedGPA(getScale(gradeReceived) * course.getCredits()); enrollment.setGradeReceived(gradeReceived); CourseEnrollmentPK pk = new CourseEnrollmentPK(); pk.setCourseId(course.getCode()); pk.setUserId(user.getId()); enrollment.setId(pk); enrollment.setEarnedGPA(calculateEarnedGrade(course.getCredits(), gradeReceived)); em.persist(enrollment); // update user overall gpa // user.setGpa(calculateOverallGPA(user)); // Query query = em.createQuery("UPDATE users u SET gpa = " + // calculateOverallGPA(user) + "WHERE u.id = :id"); // query.setParameter("id", user.getId()); // query.executeUpdate(); // persist course enrollment // em.persist(user); // update user overall gpa - this will become virtual field, not stored in user // table // em.flush(); et.commit(); } catch (Exception e) { et.rollback(); } } public static boolean removeCourseEnrollment(Courses course, Users user) { TypedQuery<CourseEnrollment> query = em.createNamedQuery("CourseEnrollment.removeOne", CourseEnrollment.class); et.begin(); CourseEnrollment ce = getOneCourseEnrollment(user, course); user.removeCourseEnrollment(ce); course.removeCourseEnrollment(ce); int deletedCount = query.setParameter("user", user).setParameter("course", course).executeUpdate(); em.flush(); et.commit(); return deletedCount > 0; } public static void updateCourseEnrollment(CourseEnrollment ce, int gradeReceived) { et.begin(); ce.setGradeReceived(gradeReceived); ce.setEarnedGPA(calculateEarnedGrade(ce.getCourse().getCredits(), gradeReceived)); em.persist(ce); et.commit(); } private static double getScale(int percentage) { // A+ 90-100 if (percentage >= 90) return 4.5; // A 80-89 if (percentage >= 80) return 4; // B+ 75-79 if (percentage >= 75) return 3.5; // B 70-74 if (percentage >= 70) return 3; // C+ 65-69 if (percentage >= 65) return 2.5; // C 60-64 if (percentage >= 60) return 2; // D+ 55-59 if (percentage >= 55) return 1.5; // D 50-54 if (percentage >= 50) return 1; // F 0-49 else return 0; } }
JavaScript
UTF-8
944
4.03125
4
[]
no_license
//takes JSON and converts it to HTML recursively function convertJsonToHtml(jsonObject) { const content = jsonObject.content; const tag = jsonObject.tag; //if the next level down is an object, wrap it in element defined by tag and pass it recursively if (isObject(content)) { return (`<${tag}>${convertJsonToHtml(content)}</${tag}>`); } //if the next level down is an array, wrap it in element defined by tag and pass all elements of the array recursively, then join them else if (Array.isArray(content)) { return (`<${tag}>${content.map(section => convertJsonToHtml(section)).join('')}</${tag}>`); } //terminate recursion at end of JSON tree by returning content wrapped in element defined by tag. else { return (`<${tag}>${content}</${tag}>`); } } //returns true if an object, false otherwise function isObject (item) { return (typeof item === "object" && !Array.isArray(item) && item !== null); }
Java
UTF-8
3,232
2
2
[]
no_license
package ru.fitnessmanager.controller.userparameters; import org.springframework.format.annotation.DateTimeFormat; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.web.bind.annotation.*; import org.springframework.web.servlet.support.ServletUriComponentsBuilder; import ru.fitnessmanager.model.UserParameters; import ru.fitnessmanager.to.UserParametersTo; import java.net.URI; import java.util.Date; import java.util.List; @RestController @RequestMapping(value = UserParametersRestController.REST_URL, produces = MediaType.APPLICATION_JSON_VALUE) public class UserParametersRestController extends AbstractUserParametersController { static final String REST_URL = "/rest/userparameters/{userId}"; @Override @PreAuthorize("hasRole('ROLE_USER')") @GetMapping("/{parameterId}") public List<UserParameters> getAll(@PathVariable("userId") int userId, @PathVariable("parameterId") int parameterId) { return super.getAll(userId, parameterId); } @Override @PreAuthorize("hasRole('ROLE_USER')") @GetMapping("/{parameterId}/{id}") public UserParameters get(@PathVariable("id") int id, @PathVariable("userId") int userId, @PathVariable("parameterId") int parameterId) { return super.get(id, userId, parameterId); } @Override @PreAuthorize("hasRole('ROLE_USER')") @DeleteMapping("/{parameterId}/{id}") public void delete(@PathVariable("id") int id, @PathVariable("userId") int userId, @PathVariable("parameterId") int parameterId) { super.delete(id, userId, parameterId); } @Override @PreAuthorize("hasRole('ROLE_USER')") @PutMapping("/{parameterId}/{id}") public void update(@RequestBody UserParameters userParameters, @PathVariable("id") int id, @PathVariable("userId") int userId, @PathVariable("parameterId") int parameterId) { super.update(userParameters, id, userId, parameterId); } @PreAuthorize("hasRole('ROLE_USER')") @PostMapping(value = "/{parameterId}", consumes = MediaType.APPLICATION_JSON_VALUE) public ResponseEntity<UserParameters> createWithLocation(@RequestBody UserParameters userParameters, @PathVariable("userId") int userId, @PathVariable("parameterId") int parameterId) { UserParameters created = super.create(userParameters, userId, parameterId); URI uriOfNewResource = ServletUriComponentsBuilder.fromCurrentContextPath() .path(REST_URL + "/{id}") .buildAndExpand(userId, parameterId, created.getId()).toUri(); return ResponseEntity.created(uriOfNewResource).body(created); } @Override @PreAuthorize("hasRole('ROLE_USER')") @GetMapping("/foruser") public List<UserParametersTo> getForUser(@RequestParam(value = "startDate", required = false) @DateTimeFormat(pattern="yyyy-MM-dd") Date startDate, @RequestParam(value = "endDate", required = false) @DateTimeFormat(pattern="yyyy-MM-dd") Date endDate, @PathVariable("userId") int userId) { return super.getForUser(startDate, endDate, userId); } }
C++
UTF-8
2,032
3.8125
4
[]
no_license
#include<iostream.h> #include<conio.h> #include<process.h>//for exit function #include<dos.h> //for delay function struct node { int data; node *next; }; class STACK { node *top; public: STACK() { top=NULL; } void push(); void pop(); void display(); ~STACK(); }; void STACK::push()/*function to perform Push Operation*/ { node *temp=new node; cout<<"\nEnter the Data to be inserted: "; cin>>temp->data; temp->next=top; top=temp; getch(); } void STACK::pop()/*function to perform Pop Operation*/ { if(top==NULL) cout<<"\n\t\t\t STACK UNDERFLOW!!!"; else { node *temp=top; cout<<"\nDeleted Record is: "<<temp->data; top=top->next; delete temp; } getch(); } void STACK::display()/*function to Display all the Elements*/ { if(top==NULL) cout<<"\n\t\t\t STACK UNDERFLOW!!!"; else { node *temp=top; cout<<"\nElements in STACK are: "; while(temp!=NULL) { cout<<" "<<temp->data; temp=temp->next; } } getch(); } STACK::~STACK() { node *temp; while(top!=NULL) { temp=top; top=top->next; delete temp; } } void main() { STACK st; /*st is the object of class STACK*/ int ch,s=0; do { clrscr(); cout<<"\n\n\t\t\t\t ::WELCOME:: "; cout<<"\n\n\t\t\t ::STACK WITH LINKED LIST::"<<endl; cout<<"\n\nYour Options Are:-"; cout<<"\n\n1.Press 1 for PUSH Operation."; cout<<"\n2.Press 2 for POP Operation."; cout<<"\n3.Press 3 to DISPLAY all the Elements. "; cout<<"\n4.Press 4 to Exit from the Program."; cout<<"\n\nENTER YOUR CHOICE: "; cin>>ch; switch(ch) { case 1: /*Case for Push Operation*/ st.push(); break; case 2:/*Case for Pop Operation*/ st.pop(); break; case 3: /*Case to Display all the elements*/ st.display(); break; case 4: cout<<"\nGetting Out Of The Program."; delay(1000);//delay 1000 milliseconds exit(0); //getting out of the program break; default: //when no case matches cout<<"\nWrong Choice!!!Please Enter Again."; delay(2000);//delay 2000 milliseconds } } while(s==0); getch(); }
Java
UTF-8
1,529
2.34375
2
[]
no_license
package teqvirtual.deep.fashionbook.Adapter; import android.content.Context; import android.support.annotation.NonNull; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import teqvirtual.deep.fashionbook.MainProfileActivity; import teqvirtual.deep.fashionbook.R; public class ShoesAdapter extends RecyclerView.Adapter<ShoesAdapter.MyViewHolder> { Context context; LayoutInflater layoutInflater; int[] sho_img; public ShoesAdapter(MainProfileActivity mainProfileActivity, int[] sho_img) { this.context=mainProfileActivity; this.sho_img=sho_img; layoutInflater=layoutInflater.from(context); } @NonNull @Override public ShoesAdapter.MyViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) { View view=layoutInflater.inflate(R.layout.shoes_item,null); return new MyViewHolder(view); } @Override public void onBindViewHolder(@NonNull ShoesAdapter.MyViewHolder myViewHolder, int i) { myViewHolder.imageView.setImageResource(sho_img[i]); } @Override public int getItemCount() { return sho_img.length; } public class MyViewHolder extends RecyclerView.ViewHolder { ImageView imageView; public MyViewHolder(@NonNull View itemView) { super(itemView); imageView=(ImageView)itemView.findViewById(R.id.shoe_img); } } }
Ruby
UTF-8
214
3.109375
3
[]
no_license
original = "Welcome to the forum.\nHere you can learn Ruby.\nAlong with other members.\n" string_list = original.split("\n") string_list.with_index(0) do |index, line| puts "Line %d: %s" % [index + 1, line] end
Java
UTF-8
2,412
2.65625
3
[]
no_license
import org.junit.Assert; import org.junit.Before; import org.junit.Test; import java.util.regex.Matcher; import java.util.regex.Pattern; import static org.junit.Assert.*; public class HamletParserTest { private String hamletText; private HamletParser hamletParser; @Before public void setUp() { this.hamletParser = new HamletParser(); this.hamletText = hamletParser.getHamletData(); } @Test public void testChangeHamletToLeon() { Pattern pattern = Pattern.compile("Hamlet", Pattern.CASE_INSENSITIVE); Matcher matcher = pattern.matcher(hamletText); String expected =matcher.replaceAll("Leon"); String actual = hamletParser.changeHamletToLeon(); } @Test public void testChangeHoratioToTariq() { Pattern pattern = Pattern.compile("Horatio", Pattern.CASE_INSENSITIVE); Matcher matcher = pattern.matcher(hamletText); String expected =matcher.replaceAll("Tariq"); String actual = hamletParser.changeHoratioToTariq(); Assert.assertEquals(expected, actual); } @Test public void testFindHoratio() { Pattern pattern = Pattern.compile("Horatio", Pattern.CASE_INSENSITIVE); Matcher matcher = pattern.matcher(hamletText); for (int i = 0; matcher.find(); i++) { System.out.println(new StringBuilder() .append("\n-------------------") .append("\nValue = " + matcher.group()) .append("\nMatch Number = " + i) .append("\nStarting index = " + matcher.start()) .append("\nEnding index = " + matcher.end()) .toString()); } String actual = hamletParser.changeHamletToLeon(); } @Test public void testFindHamlet() { Pattern pattern = Pattern.compile("Hamlet", Pattern.CASE_INSENSITIVE); Matcher matcher = pattern.matcher(hamletText); for (int i = 0; matcher.find(); i++) { System.out.println(new StringBuilder() .append("\n-------------------") .append("\nValue = " + matcher.group()) .append("\nMatch Number = " + i) .append("\nStarting index = " + matcher.start()) .append("\nEnding index = " + matcher.end()) .toString()); } } }
Python
UTF-8
3,100
2.65625
3
[]
no_license
import re from commcare_export.minilinq import Apply, Literal, Reference SELECTED_AT = 'selected-at' SELECTED = 'selected' TEMPLATE = 'template' SUBSTR = 'substr' class ParsingException(Exception): def __init__(self, message): self.message = message def parse_function_arg(slug, expr_string): """ expr_string should start with the slug and the expression should be enclosed in () after it like expr_string = selected(Other_(Specify)) slug = selected should return Other_(Specify) """ regex = r'^{0}\((.*)\)$'.format(slug) matches = re.match(regex, expr_string) if not matches: raise ParsingException( 'Error: Unable to parse: {}'.format(expr_string) ) return matches.groups()[0] def parse_selected_at(value_expr, selected_at_expr_string): index = parse_function_arg(SELECTED_AT, selected_at_expr_string) try: index = int(index) except ValueError: return Literal( 'Error: selected-at index must be an integer: {}' .format(selected_at_expr_string) ) return Apply(Reference(SELECTED_AT), value_expr, Literal(index)) def parse_selected(value_expr, selected_expr_string): ref_val = parse_function_arg(SELECTED, selected_expr_string) return Apply(Reference(SELECTED), value_expr, Literal(ref_val)) def parse_template(value_expr, format_expr_string): args_string = parse_function_arg(TEMPLATE, format_expr_string) args = [arg.strip() for arg in args_string.split(',') if arg.strip()] if len(args) < 1: return Literal( 'Error: template function requires the format template: ' f'{format_expr_string}' ) template = args.pop(0) if args: args = [Reference(arg) for arg in args] else: args = [value_expr] return Apply(Reference(TEMPLATE), Literal(template), *args) def parse_substr(value_expr, substr_expr_string): args_string = parse_function_arg(SUBSTR, substr_expr_string) regex = r'^\s*(\d+)\s*,\s*(\d+)\s*$' matches = re.match(regex, args_string) if not matches or len(matches.groups()) != 2: raise ParsingException( 'Error: both substr arguments must be non-negative integers: ' f'{substr_expr_string}' ) # These conversions should always succeed after a pattern match. start = int(matches.groups()[0]) end = int(matches.groups()[1]) return Apply(Reference(SUBSTR), value_expr, Literal(start), Literal(end)) MAP_FORMAT_PARSERS = { SELECTED_AT: parse_selected_at, SELECTED: parse_selected, TEMPLATE: parse_template, SUBSTR: parse_substr, } def compile_map_format_via(value_expr, map_format_expression_string): fn_name = map_format_expression_string.split('(')[0] parser = MAP_FORMAT_PARSERS.get(fn_name) if parser: try: return parser(value_expr, map_format_expression_string) except ParsingException as e: return Literal(e.message) return Apply(Reference(map_format_expression_string), value_expr)
PHP
UTF-8
7,890
2.828125
3
[ "MIT" ]
permissive
<?php namespace App\Console\Commands; use App\Shortcode; use Goutte\Client; use Illuminate\Console\Command; use Illuminate\Support\Facades\Log; class ScapeShortcodes extends Command { /** * The name and signature of the console command. * * @var string */ protected $signature = 'scrape:short-code {page}'; /** * The console command description. * * @var string */ protected $description = 'Command description.'; /** * Create a new command instance. * * @return void */ public function __construct() { parent::__construct(); } /** * Execute the console command. * * @return mixed */ public function handle() { // $page = $this->argument('page'); $client = new Client(); Log::info('INIT CLIENT'); $crawler = $client->request('GET', 'http://short-codes.com/codes/browse/60000-64999/100_'.$page); Log::info('START CRAWLER'); $row = 1; $crawler->filter('.codes tr')->each(function ($node) use (&$row) { Log::info('LOOP THRU TABLE ROWS'); if ($row > 2) { $col = 1; Log::info(' '); Log::info('ROW'); $available = true; $sc = ''; $node->filter('td')->each(function ($n) use (&$col, &$available, &$sc) { if ($col==2) { $sc = trim($n->text()); Log::info('SC: '.json_encode($n->text())); } if ($col>3 && $col<9) { $text = $n->filter('img')->attr('title'); Log::info('OUTPUT: '.json_encode($text)); if ($text != 'Active') { $available = false; } } if ($col==10) { if ($available) { try { Shortcode::create(['shortcode' => $sc]); } catch (\Exception $e) { Log::info(' '); Log::info('ERROR: '.json_encode($e->getMessage())); } } } $col++; }); } $row++; }); $crawler1 = $client->request('GET', 'http://short-codes.com/codes/browse/65000-68999/100_'.$page); Log::info('START CRAWLER'); $row1 = 1; $crawler1->filter('.codes tr')->each(function ($node) use (&$row1) { Log::info('LOOP THRU TABLE ROWS'); if ($row1 > 2) { $col = 1; Log::info(' '); Log::info('ROW'); $available = true; $sc = ''; $node->filter('td')->each(function ($n) use (&$col, &$available, &$sc) { if ($col==2) { $sc = trim($n->text()); Log::info('SC: '.json_encode($n->text())); } if ($col>3 && $col<9) { $text = $n->filter('img')->attr('title'); Log::info('OUTPUT: '.json_encode($text)); if ($text != 'Active') { $available = false; } } if ($col==10) { if ($available) { try { Shortcode::create(['shortcode' => $sc]); } catch (\Exception $e) { Log::info(' '); Log::info('ERROR: '.json_encode($e->getMessage())); } } } $col++; }); } $row1++; }); $crawler2 = $client->request('GET', 'http://short-codes.com/codes/browse/80000-84999/100_'.$page); Log::info('START CRAWLER'); $row2 = 1; $crawler2->filter('.codes tr')->each(function ($node) use (&$row2) { Log::info('LOOP THRU TABLE ROWS'); if ($row2 > 2) { $col = 1; Log::info(' '); Log::info('ROW'); $available = true; $sc = ''; $node->filter('td')->each(function ($n) use (&$col, &$available, &$sc) { if ($col==2) { $sc = trim($n->text()); Log::info('SC: '.json_encode($n->text())); } if ($col>3 && $col<9) { $text = $n->filter('img')->attr('title'); Log::info('OUTPUT: '.json_encode($text)); if ($text != 'Active') { $available = false; } } if ($col==10) { if ($available) { try { Shortcode::create(['shortcode' => $sc]); } catch (\Exception $e) { Log::info(' '); Log::info('ERROR: '.json_encode($e->getMessage())); } } } $col++; }); } $row2++; }); Log::info('INIT CLIENT'); $crawler3 = $client->request('GET', 'http://short-codes.com/codes/browse/85000-88999/100_'.$page); Log::info('START CRAWLER'); $row3 = 1; $crawler3->filter('.codes tr')->each(function ($node) use (&$row3) { Log::info('LOOP THRU TABLE ROWS'); if ($row3 > 2) { $col = 1; Log::info(' '); Log::info('ROW'); $available = true; $sc = ''; $node->filter('td')->each(function ($n) use (&$col, &$available, &$sc) { if ($col==2) { $sc = trim($n->text()); Log::info('SC: '.json_encode($n->text())); } if ($col>3 && $col<9) { $text = $n->filter('img')->attr('title'); Log::info('OUTPUT: '.json_encode($text)); if ($text != 'Active') { $available = false; } } if ($col==10) { if ($available) { try { Shortcode::create(['shortcode' => $sc]); } catch (\Exception $e) { Log::info(' '); Log::info('ERROR: '.json_encode($e->getMessage())); } } } $col++; }); } $row3++; }); } }
JavaScript
UTF-8
1,204
2.703125
3
[]
no_license
const createTooltip = require('./src/createTooltip'); const removeTooltip = require('./src/removeTooltip'); const insertElement = require('./src/helpers/insertElement'); const getDefaultConfig = require('./src/helpers/getDefaultConfig'); const objectAssign = require('./src/helpers/objectAssignPolyfill'); objectAssign.polyfill(); /** * global class for creating tooltip * @param {HTMLElement} element * @param {String} message * * @returns {void} */ class Tooltip { constructor(element, config) { const defaultConfig = getDefaultConfig(); this.element = element; this.message = config.message; this.config = Object.assign({}, defaultConfig, config); this.config.style = Object.assign({}, defaultConfig.style, config.style); this.config.arrowStyle = Object.assign({}, defaultConfig.arrowStyle, config.arrowStyle); if (config.where) { this.config.where = config.where; } } /** * Rendering tooltip * * @returns {void} */ render() { let tooltip = createTooltip(this.element, this.message, this.config); this.content = tooltip; insertElement(document.body, tooltip); removeTooltip(tooltip); } } module.exports = Tooltip;
Shell
UTF-8
343
2.90625
3
[]
no_license
#!/bin/bash set -ex cd docker names=`echo push-go-{app,endpoint,log,notification,subscription}` for name in $names do sed -e "s/{NAME}/$name/g" Dockerfile.template > $name docker build -f $name -t nokamotohub/$name . docker push nokamotohub/$name done ./test.sh for name in $names do docker push nokamotohub/$name done
Python
UTF-8
1,899
2.609375
3
[]
no_license
from luma.core.render import canvas from luma.core.interface.serial import i2c from luma.oled.device import ssd1306 from PIL import ImageFont import time import datetime from pygame import mixer serial = i2c(port=0, address=0x3C) device = ssd1306(serial) running = True mixer.pre_init(22050, -8, 2, 512, None) mixer.init() font = ImageFont.load_default() bpm = 1 stepscount = 8 path = 'samples/' patterns = [] class Track: name = '' steps = [] audio = None def __init__(self, name): self.name = name class Pattern: tracks = [] def main(): kick = Track("kick") kick.audio = mixer.Sound(path + kick.name + ".wav") snare = Track("snar") snare.audio = mixer.Sound(path + snare.name + ".wav") kick.steps = ['x','0','0','x','0','0','0','0'] snare.steps =['0','0','0','0','x','0','0','0'] mid = Pattern() mid.tracks = [kick, snare] x = 0 while running == True: with canvas(device) as draw: draw.text((0, 0), kick.name + " " + " ".join(kick.steps), font=font, fill=255) draw.text((0, 10), snare.name + " " + " ".join(snare.steps), font=font, fill=255) for y in range(len(mid.tracks)): y1 = y y2 = y if (len(mid.tracks)-1) > y: y2 = y + 1 y1 = y else: y2 = y y1 = y - 1 if stepscount <= x: x = 0 if str(mid.tracks[y1].steps[x]) == 'x': mid.tracks[y1].audio.play() print("kick") if str(mid.tracks[y2].steps[x]) == 'x': mid.tracks[y2].audio.play() print("snare") x = x + 1 time.sleep(0.2) main()
C
UTF-8
7,416
2.515625
3
[ "MIT" ]
permissive
/** * @file web_server.c * @brief implementation of web server. * @author Xiangyu Guo */ #include <stdlib.h> #include <string.h> #include <sys/types.h> #include <sys/stat.h> #include <sys/socket.h> #include <fcntl.h> #include <unistd.h> #include <dirent.h> #include <event2/event.h> #include <event2/http.h> #include <event2/buffer.h> #include <event2/util.h> #include <event2/keyvalq_struct.h> #include <wiringPi.h> #include "spi/spi_mcp3208.h" #include "i2c/i2c_bmp180.h" #include "pin/pin_motor.h" #include "pin/pin_dht_11.h" #include "web_server.h" #define MAX_LIGHT_BOUNDRY (4) /**< LED from 0 - 4, 5 in total. */ #define LED_STATUS_THRESHOLD (100) /**< LED off status */ #define POWER_PIN (24) /**< wiringPi pin number of power */ const int g_led_pins[MAX_LIGHT_BOUNDRY + 1] = {7, 0, 2, 3, 25}; /**< LED on GPIO*/ /** * =========================================== * Call back functions handle the http request * =========================================== */ static void power_request_cb(struct evhttp_request *req, void *arg); static void switch_request_cb(struct evhttp_request *req, void *arg); static void status_request_cb(struct evhttp_request *req, void *arg); static void temperature_request_cb(struct evhttp_request *req, void *arg); static void temp_humi_request_cb(struct evhttp_request *req, void *arg); static void dump_request_cb(struct evhttp_request *req, void *arg); /** * @brief setup the wiringPi */ static void setup_wiringPi(void); /** * @brief setting up the web server * @param base event base. */ void web_server_init(struct event_base *base) { struct evhttp *http; struct evhttp_bound_socket *handle; ev_uint16_t port = 80; setup_wiringPi(); /* Create a new evhttp object to handle requests. */ http = evhttp_new(base); if (!http) { fprintf(stderr, "couldn't create evhttp. Exiting.\n"); exit(errno); } evhttp_set_cb(http, "/power/on", power_request_cb, "on"); evhttp_set_cb(http, "/power/off", power_request_cb, "off"); evhttp_set_cb(http, "/power/status", power_request_cb, "status"); //evhttp_set_cb(http, "/status", status_request_cb, NULL); //evhttp_set_cb(http, "/switch/on", switch_request_cb, "on"); //evhttp_set_cb(http, "/switch/off", switch_request_cb, "off"); //evhttp_set_cb(http, "/motor/on", switch_request_cb, "on"); //evhttp_set_cb(http, "/motor/off", switch_request_cb, "off"); //evhttp_set_cb(http, "/temp/status", temperature_request_cb, NULL); evhttp_set_cb(http, "/temp_humi/status", temp_humi_request_cb, NULL); /* The /dump URI will dump all requests to stdout and say 200 ok. */ evhttp_set_gencb(http, dump_request_cb, NULL); /* Now we tell the evhttp what port to listen on */ handle = evhttp_bind_socket_with_handle(http, "0.0.0.0", port); if (!handle) { fprintf(stderr, "couldn't bind to port %d. Exiting.\n", (int)port); exit(errno); } printf("server started\n"); } static void power_request_cb(struct evhttp_request *req, void *arg) { struct evbuffer *evb = NULL; if (strcmp(arg, "on") == 0) { digitalWrite(POWER_PIN, 1); } else if (strcmp(arg, "off") == 0) { digitalWrite(POWER_PIN, 0); } else { evb = evbuffer_new(); evbuffer_add_printf(evb, "%d\n", digitalRead(POWER_PIN)); } evhttp_send_reply(req, 200, "OK", evb); if (evb != NULL) evbuffer_free(evb); } static void switch_request_cb(struct evhttp_request *req, void *arg) { struct evkeyvalq headers; const char *q; int led; // Parse the query for later lookups evhttp_parse_query(evhttp_request_get_uri(req), &headers); q = evhttp_find_header (&headers, "led"); led = atoi(q); if (strcmp(arg, "on")) { digitalWrite(g_led_pins[led], 0); } else { digitalWrite(g_led_pins[led], 1); } evhttp_send_reply(req, 200, "OK", NULL); } static void status_request_cb(struct evhttp_request *req, void *arg) { struct evbuffer *evb = NULL; struct evkeyvalq headers; mcp3208_module_st *mcp3208 = NULL; const char *q; // Parse the query for later lookups evhttp_parse_query(evhttp_request_get_uri(req), &headers); q = evhttp_find_header (&headers, "led"); mcp3208 = mcp3208_module_get_instance(); int value = mcp3208_read_data(mcp3208, atoi(q)); evhttp_request_get_uri(req); evb = evbuffer_new(); if (value < LED_STATUS_THRESHOLD) evbuffer_add_printf(evb, "0\n"); else evbuffer_add_printf(evb, "1\n"); evhttp_send_reply(req, 200, "OK", evb); evbuffer_free(evb); } static void temperature_request_cb(struct evhttp_request *req, void *arg) { struct evbuffer *evb = NULL; bmp180_module_st *bmp180 = NULL; bmp180_data_st value; bmp180 = bmp180_module_init(BMP180_ULTRA_HIGH_RESOLUTION); bmp180_read_data(bmp180, &value); evb = evbuffer_new(); evbuffer_add_printf(evb, "{\"temperature\": %.1f, \"humidity\": 0}", value.temperature); evhttp_send_reply(req, 200, "OK", evb); bmp180_module_fini(bmp180); evbuffer_free(evb); } static void temp_humi_request_cb(struct evhttp_request *req, void *arg) { struct evbuffer *evb = NULL; dht_data_st value; pin_dht_11_init(); pin_dht_11_read(&value); evb = evbuffer_new(); evbuffer_add_printf(evb, "{\"temperature\": %.2f, \"humidity\": %.2f}", value.temperature, value.humidity); evhttp_send_reply(req, 200, "OK", evb); evbuffer_free(evb); } /* Callback used for the /dump URI, and for every non-GET request: * dumps all information to stdout and gives back a trivial 200 ok */ static void dump_request_cb(struct evhttp_request *req, void *arg) { const char *cmdtype; struct evkeyvalq *headers; struct evkeyval *header; struct evbuffer *buf; switch (evhttp_request_get_command(req)) { case EVHTTP_REQ_GET: cmdtype = "GET"; break; case EVHTTP_REQ_POST: cmdtype = "POST"; break; case EVHTTP_REQ_HEAD: cmdtype = "HEAD"; break; case EVHTTP_REQ_PUT: cmdtype = "PUT"; break; case EVHTTP_REQ_DELETE: cmdtype = "DELETE"; break; case EVHTTP_REQ_OPTIONS: cmdtype = "OPTIONS"; break; case EVHTTP_REQ_TRACE: cmdtype = "TRACE"; break; case EVHTTP_REQ_CONNECT: cmdtype = "CONNECT"; break; case EVHTTP_REQ_PATCH: cmdtype = "PATCH"; break; default: cmdtype = "unknown"; break; } printf("Received a %s request for %s\nHeaders:\n", cmdtype, evhttp_request_get_uri(req)); headers = evhttp_request_get_input_headers(req); for (header = headers->tqh_first; header; header = header->next.tqe_next) { printf(" %s: %s\n", header->key, header->value); } buf = evhttp_request_get_input_buffer(req); puts("Input data: <<<"); while (evbuffer_get_length(buf)) { int n; char cbuf[128]; n = evbuffer_remove(buf, cbuf, sizeof(cbuf)); if (n > 0) (void) fwrite(cbuf, 1, n, stdout); } puts(">>>"); evhttp_send_reply(req, 200, "OK", NULL); } static void setup_wiringPi(void) { int i, led; if (wiringPiSetup() < 0) exit(errno); for (i = 0; i <= MAX_LIGHT_BOUNDRY; ++i) { led = g_led_pins[i]; pinMode(led, OUTPUT); digitalWrite(led, 0); } }
Shell
UTF-8
259
2.78125
3
[]
no_license
#!/bin/bash for process in $(ps -A -o pid | tail -n +2) do status="/proc/$process/status" sched="/proc/$process/sched" ppid=$(grep -hsi "PPid:" "$status" | awk 'BEGIN{FS="\t"}{print $2}') sleepavg=$(grep -hsi "avg_atom" "$sched" | grep -o "[0-9.]\+ " done
SQL
UTF-8
1,900
3.828125
4
[ "MIT" ]
permissive
\connect mypostgraphile; create schema mygraphile; /*Create user table in mygraphile schema*/ CREATE TABLE mygraphile.user ( id SERIAL PRIMARY KEY, username VARCHAR (255) NOT NULL, created_date TIMESTAMP DEFAULT CURRENT_TIMESTAMP ); COMMENT ON TABLE mygraphile.user IS 'Forum users.'; /*Create post table in mygraphile schema*/ CREATE TABLE mygraphile.post ( id SERIAL PRIMARY KEY, title VARCHAR (255) NOT NULL, body TEXT, created_date TIMESTAMP DEFAULT CURRENT_TIMESTAMP, author_id INTEGER NOT NULL REFERENCES mygraphile.user(id) ); COMMENT ON TABLE mygraphile.post IS 'Forum posts written by a user.'; /*Create store table in mygraphile schema*/ CREATE TABLE mygraphile.store ( id SERIAL PRIMARY KEY, storename VARCHAR (255) NOT NULL, created_date TIMESTAMP DEFAULT CURRENT_TIMESTAMP ); COMMENT ON TABLE mygraphile.store IS 'List of stores.'; /*Create product table in mygraphile schema*/ CREATE TABLE mygraphile.product ( id SERIAL PRIMARY KEY, productname VARCHAR (255) NOT NULL, created_date TIMESTAMP DEFAULT CURRENT_TIMESTAMP ); COMMENT ON TABLE mygraphile.product IS 'List of products.'; /*Create brand table in mygraphile schema*/ CREATE TABLE mygraphile.brand ( id SERIAL PRIMARY KEY, brandname VARCHAR (255) NOT NULL, price NUMERIC(5,2), created_date TIMESTAMP DEFAULT CURRENT_TIMESTAMP, product_id INTEGER NOT NULL REFERENCES mygraphile.product(id) ); COMMENT ON TABLE mygraphile.brand IS 'List of brands.'; /*Create brand table in mygraphile schema*/ CREATE TABLE mygraphile.sale ( id SERIAL PRIMARY KEY, quantity SMALLINT NOT NULL CHECK (quantity > 0), created_date TIMESTAMP DEFAULT CURRENT_TIMESTAMP, store_id INTEGER NOT NULL REFERENCES mygraphile.store(id), brand_id INTEGER NOT NULL REFERENCES mygraphile.brand(id) ); COMMENT ON TABLE mygraphile.sale IS 'Record of sales.';
C++
GB18030
1,673
3.453125
3
[]
no_license
/** * POJ1328 Radar Installation * ̰ * ÿ״ﰲõĺ䣬Щ䰴˵ * ұһϲ˵ܱͬһ״̽⣬Ϊ佻 */ #include <iostream> #include <vector> #include <math.h> #include <algorithm> using namespace std; struct node { double left, right; bool operator<(const node &b) const { return left < b.left; } }; int main() { std::ios::sync_with_stdio(false); cin.tie(NULL); int ci = 0; int n, d; while (cin >> n >> d) { if (n == 0 && d == 0) { break; } ci++; vector<node> vec; double dsquare = d * d; bool flag = true; for (int i = 0; i < n; i++) { int x, y; cin >> x >> y; if (y > d) { flag = false; } if (flag) { double d = sqrt(dsquare - y * y); vec.push_back({x - d, x + d}); } } if (!flag) { cout << "Case " << ci << ": -1" << endl; continue; } sort(vec.begin(), vec.end()); int i = 0; while (i < vec.size() - 1) { if (vec[i].right >= vec[i + 1].left) { vec[i + 1].right = min(vec[i].right, vec[i + 1].right); vec.erase(vec.begin() + i); } else i++; } cout << "Case " << ci << ": " << vec.size() << endl; } return 0; }
C#
UTF-8
1,747
3.109375
3
[]
no_license
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace StringGraph { public class Node { public Graph Graph { get; internal set; } public string Value { get; set; } public List<Node> Nodes { get; set; } = new List<Node>(); public List<bool> Nodeflags { get; set; } = new List<bool>(); public bool Was { get; set; } = false; public int X { get; set; } public int Y { get; set; } internal Node(string value, int x, int y,Graph gr) { Value = value; X = x; Y = y; Graph = gr; } public void AddEdgeTo(Node node) { if (node.Graph != Graph) throw new ArgumentException(); if (Nodes.Contains(node)) return; Nodes.Add(node); Nodeflags.Add(false); node.Nodes.Add(this); node.Nodeflags.Add(false); } public bool RemoveEdgeTo(Node node) { if (node.Graph != Graph) throw new ArgumentException(); if (!Nodes.Contains(node)) return false; Nodeflags.RemoveAt(Nodes.IndexOf(node)); Nodes.Remove(node); node.Nodeflags.RemoveAt(node.Nodes.IndexOf(this)); node.Nodes.Remove(this); return true; } internal void RemoveAllEdges() { for (int i = 0; i < Nodes.Count; i++) { Nodes[i].Nodeflags.RemoveAt(Nodes[i].Nodes.IndexOf(this)); Nodes[i].Nodes.Remove(this); } Nodes.Clear(); } } }
TypeScript
UTF-8
2,922
2.859375
3
[]
no_license
// console.log('My first typescript server'); //debug purposes // do not use ts-node! Use "node ..." // import * as express from 'express'; //commented due to import error /* import express = require('express'); // import INC = require("./incident"); // import INC = require("c:/Users/Kta/Documents/firstAngularApp/server/incident"); import { setDefaultService } from 'selenium-webdriver/edge'; import { Incident } from './incident'; const app = express(); // var incidents = new Array(); let date = new Date(); // incidents[0] = new incident(10, [date.getHours(), date.getMinutes(), date.getSeconds()], "bla", "bla");// initialize incident // incidents.push(new incident(10, [11, 23, 32], "bla", "bla")); // var length = incidents.push(INCobj); //return length of incidents array (may not use) app.get('/', (req, res) =>{ // res.send({hello: 'hello world'}); res.send(incidents); }) app.listen(4202, '127.0.0.1', function(){ console.log('Typescript server currently listening on 4202'); }) */ import {IncidentList} from "./incidents-list"; import {Incident} from "./incident"; import { Time } from "./time"; // import * as express from "express"; import express = require("express"); class Server { private _list: IncidentList; constructor() { const incidentOneTime: Time = new Time(12, 12, 12); const incidentOne: Incident = new Incident(1, new Time(12, 12, 12), "Android", "Crash"); const incidentTwo: Incident = new Incident(2, new Time(12, 12, 12), "Android", "Crash"); const incidentThree: Incident = new Incident(3, new Time(20, 54, 25), "Web", "Crash"); const incidents = []; incidents.push(incidentOne); incidents.push(incidentTwo); incidents.push(incidentThree); incidents.push(new Incident(3, new Time(10, 35, 10), "Web", "Crash")); this._list = new IncidentList(incidents); // this._list = new IncidentList([incidentOne, incidentTwo]); } public listIncidents(): void { const size = this._list.len; // finds the size using custom getter from incident-list.ts console.log(`There are ${size} incidents\n`); for (let i = 0; i < this._list.incidents.length; i++) { const time = this._list.incidents[i].loggedTime.createTime; // creates time using custom getter from time.ts console.log(`Incident: ${this._list.incidents[i].id}`); console.log(`Time: ${time}`); console.log(`Device: ${this._list.incidents[i].device}`); console.log(`Type: ${this._list.incidents[i].type}\n`); } } } const _server: Server = new Server(); _server.listIncidents(); const app = express(); app.get("/", (req, res) => { // res.send({hello: 'hello world'}); res.send(_server.listIncidents()); }); app.listen(4202, "127.0.0.1", function() { console.log("Typescript server currently listening on 4202"); });
Java
UTF-8
1,393
2.796875
3
[]
no_license
package DataMapper; import org.apache.poi.openxml4j.exceptions.InvalidFormatException; import org.apache.poi.ss.usermodel.Sheet; import org.apache.poi.ss.usermodel.Workbook; import org.apache.poi.ss.usermodel.WorkbookFactory; import org.testng.Assert; import org.testng.annotations.Test; import java.io.*; @Test public class ExcelReader { static Sheet sheet; public static Sheet TestCaseReader(String path) { try{ File dataFile = new File(path); //File dataFile = new File("C:\\Users\\kguttiko\\Documents\\GitHub\\keyword-driven-framework\\src\\main\\resources\\TestData\\TestCases.xlsx"); //Feed the opened file to FileInputStream FileInputStream inputStream = new FileInputStream(dataFile); //Feed the input Stream to buffered stream BufferedInputStream bufferStream = new BufferedInputStream(inputStream); //create a workbook out of buffered stream Workbook workbook = WorkbookFactory.create(bufferStream); //GetSheet sheet = workbook.getSheet("TestCases"); System.out.println(sheet.getLastRowNum()); } catch (Exception e){ System.out.println("Unable to read excel"+e.getMessage()); Assert.fail("Failed to get data from Excel"); } //open a file return sheet; } }
Python
UTF-8
928
2.671875
3
[]
no_license
import networkx as nx import matplotlib.pyplot as plt import numpy as np from graph import Graph from mingus.containers import Track from mingus.midi import midi_file_out from mingus.containers.instrument import MidiInstrument from mingus.containers import NoteContainer def generate_track(g, n, name): root = np.random.randint(0,n) edges = nx.bfs_edges(g.G, root) nodes = [root] + [v for u, v in edges] m = MidiInstrument(4) t = Track() track = [] t.instrument = m nNotes = 0 print("##### Creating Tracks") for x in nodes: value = t.add_notes(NoteContainer(g.G.nodes[x]["note"]), g.G.nodes[x]["duration"]) t.bars[-1].set_meter((n, 1)) track.append(g.G.nodes[x]["note"]) nNotes = nNotes + 1 print("##### Notes Generated:") print(*t) print("##### Number of notes:") print(nNotes) midi_file_out.write_Track( name +".mid", t) return t
Markdown
UTF-8
509
2.734375
3
[]
no_license
# Read-mem 从指定位置读取七个内存单元的内存值,进行加40操作后,再重新读一次。 # 指令 ./read_mem 相应内存地址下的值会显示出来,在进行+40操作后,重新读取内存值,验证操作是否有效。 # 注意 如果想读取其他位置的内存单元,可修改程序: map_base = (unsigned char *)mmap((void *)0x42000000, 0xff, PROT_READ|PROT_WRITE, MAP_SHARED, fd, 0); 将0x42000000修改为自己想访问的地址即可 需要重新make clean;make
Markdown
UTF-8
1,508
2.609375
3
[]
no_license
#Kaardirakendus ##Sissejuhatus: See rakendus võimaldab kaardile märkida punktobjekte. Igale objektile peab määrama nime, kirjeldus on valikuline. Kui objektile asub lähemal kui 500 meetrit mõni teine objekt, on objekti ikoon punane, muul juhul roheline. Enne vastava arvutuse tegemist on ikoon kollane. ##Kasutamine: Rakenduse käivitamiseks tuleb avada "index.html" fail. Rakendus avaneb vaikimisi määratud brauseris. Et objekti kaardile märkida, tuleb täita tekstiväli "Nimi". Seda võib teha kas enne või pärast "Märgi kaardile" vajutamist. Soovi korral võib täita ka "Kirjeldus" tekstivälja. Pärast "Märgi kaardile" vajutamist on võimalik kaardile objekt märkida. "Salvesta" salvestab objekti ja selle nime ja kirjelduse tabelisse, lisaks määratakse objektile popup nime ja kirjeldusega ning identifikaator (#). "Katkesta" tühistab käimasoleva objekti märkimise. Tabelis reale või kaardil objektile vajutades avaneb vastava objekti popup nime ja kirjeldusega. Tabeli rea lõpus oleva "Kustuta" nupu abil on võimalik objekte kustutada, kustub nii tabeli rida kui objekt kaardil. Objekte on võimalik kaardil lohistada, misjärel tehakse kauguse arvutused uuesti ja objektide ikoonid omandavad vastava värvi (kui mõni teine objekt lähemal kui 500 meetrit -> punane, vastasel juhul roheline). Tabelis muudetakse lohistatud objekti koordinaadid hetkeolukorrale vastavaks. Üleval paremal kuvatakse viimati märgitud või lohistatud objekti koordinaadid. Autor: Silver Piir
Java
UTF-8
1,077
2.140625
2
[]
no_license
package com.fisnikz.coffee_express.finance.control; import com.fisnikz.coffee_express.finance.entity.BankAccount; import com.fisnikz.coffee_express.finance.entity.CreditCardInfo; import io.quarkus.runtime.StartupEvent; import javax.enterprise.context.RequestScoped; import javax.enterprise.event.Observes; import javax.transaction.Transactional; import java.time.LocalDate; import java.util.UUID; /** * @author Fisnik Zejnullahu */ @RequestScoped public class Initializer { @Transactional void onStart(@Observes StartupEvent event) { CreditCardInfo creditCardInfo = new CreditCardInfo(); creditCardInfo.cardNumber = 3782822463100005L; creditCardInfo.cvc = 123; creditCardInfo.expirationDate = LocalDate.now().plusYears(2); BankAccount bankAccount = new BankAccount(); bankAccount.id = UUID.fromString("70d273a8-03ec-11eb-adc1-0242ac120002"); bankAccount.customerId = UUID.fromString("045cf19e-34b9-4d1e-a566-921874129ff0"); bankAccount.creditCardInfo = creditCardInfo; bankAccount.persist(); } }
Java
UTF-8
262
2.109375
2
[ "Apache-2.0" ]
permissive
package com.google.errorprone.annotations; import java.lang.annotation.Target; import static java.lang.annotation.ElementType.CONSTRUCTOR; import static java.lang.annotation.ElementType.METHOD; @Target({CONSTRUCTOR, METHOD}) public @interface MustBeClosed {}
Java
UTF-8
691
1.890625
2
[]
no_license
package com.itheima.health.service; import com.itheima.health.pojo.OrderSetting; import java.util.Date; import java.util.List; /** * @author zhangmeng * @description 预约设置SERVICE * @date 2019/9/29 **/ public interface OrderSettingService { /** * 批量添加 * @param orderSettings */ void addAll(List<OrderSetting> orderSettings); /** * 根据月份查询数据 * @param month * @param year * @return */ List<OrderSetting> getOrderSettingByMonth(int year, int month); /** * 根据日期编辑number * @param orderDate * @param number */ void editNumberByDate(Date orderDate, int number); }
Python
UTF-8
4,306
2.71875
3
[]
no_license
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Here every gf is a gfvec, i.e every green-function is a vector of green function. To lighten the writing we supress the "vec". Maybe consider putting everything as in the README.txt. """ import numpy as np from .import abc_iomodel class IOTriangle(abc_iomodel.ABCIOModel): """ """ def __init__(self) -> None: """ """ super().__init__() return None @property def U(self): return (1/np.sqrt(2)*np.array([ [1.0, 0.0, 1.0, 0.0], [0.0, 1.0, 0.0, 1.0], [1.0, 0.0, -1.0, 0.0], [0.0, 1.0, 0.0, -1.0] ]) ) def to_to_c(self, zn_vec, gf_to): """convert from tabular-out form to cluster form""" zn_vec = zn_vec.copy() ; gf_to = gf_to.copy() assert(zn_vec.shape[0] == gf_to.shape[0]) assert(gf_to.shape[1] == 11) #the following three lines could be replaced by: gf_t = to_to_t(gf_to) # but I do this for tests purposes (np.testing) gf_t = np.zeros((gf_to.shape[0], (gf_to.shape[1] -1)//2)) gf_t = 1.0*gf_to[:, 1::2] + 1.0j*gf_to[:, 2::2] np.testing.assert_allclose(gf_t, self.to_to_t(gf_to)) gf_c = np.zeros((zn_vec.shape[0], 4, 4), dtype=complex) gf_c[:, 0, 0] = gf_t[:, 0] ; gf_c[:, 0, 1] = gf_t[:, 2] ; gf_c[:, 0, 2] = gf_t[:, 3] ; gf_c[:, 0, 3] = gf_t[:, 2] gf_c[:, 1, 0] = gf_t[:, 2] ; gf_c[:, 1, 1] = gf_t[:, 1] ; gf_c[:, 1, 2] = gf_t[:, 2] ; gf_c[:, 1, 3] = gf_t[:, 4] gf_c[:, 2, 0] = gf_t[:, 3] ; gf_c[:, 2, 1] = gf_t[:, 2] ; gf_c[:, 2, 2] = gf_t[:, 0] ; gf_c[:, 2, 3] = gf_t[:, 2] gf_c[:, 3, 0] = gf_t[:, 2] ; gf_c[:, 3, 1] = gf_t[:, 4] ; gf_c[:, 3, 2] = gf_t[:, 2] ; gf_c[:, 3, 3] = gf_t[:, 1] return gf_c def c_to_to(self, zn_vec, gf_c): """convert from cluster form to tabular-out form """ zn_vec = zn_vec.copy() ; gf_c = gf_c.copy() assert(zn_vec.shape[0] == gf_c.shape[0]) assert(gf_c.shape[1] == gf_c.shape[2]) ; assert(gf_c.shape[1] == 4) gf_to = np.zeros((zn_vec.shape[0], 11)) gf_to[:, 0] = zn_vec gf_to[:, 1] = gf_c[:, 0, 0].real ; gf_to[:, 2] = gf_c[:, 0, 0].imag gf_to[:, 3] = gf_c[:, 1, 1].real ; gf_to[:, 4] = gf_c[:, 1, 1].imag gf_to[:, 5] = gf_c[:, 0, 1].real ; gf_to[:, 6] = gf_c[:, 0, 1].imag gf_to[:, 7] = gf_c[:, 0, 2].real ; gf_to[:, 8] = gf_c[:, 0, 2].imag gf_to[:, 9] = gf_c[:, 1, 3].real ; gf_to[:, 10] = gf_c[:, 1, 3].imag return gf_to def ir_to_to(self, zn_vec, gf_ir): """convert from irreducible form to tabular-out form """ zn_vec = zn_vec.copy() ; gf_ir = gf_ir.copy() assert(zn_vec.shape[0] == gf_ir.shape[0]) assert(gf_ir.shape[1] == gf_ir.shape[2]) ; assert(gf_ir.shape[1] == 4) gf_to = np.zeros((zn_vec.shape[0], 11)) gf_to[:, 0] = zn_vec gf_to[:, 1] = gf_ir[:, 0, 0].real ; gf_to[:, 2] = gf_ir[:, 0, 0].imag gf_to[:, 3] = gf_ir[:, 1, 1].real ; gf_to[:, 4] = gf_ir[:, 1, 1].imag gf_to[:, 5] = gf_ir[:, 2, 2].real ; gf_to[:, 6] = gf_ir[:, 2, 2].imag gf_to[:, 7] = gf_ir[:, 3, 3].real ; gf_to[:, 8] = gf_ir[:, 3, 3].imag gf_to[:, 9] = gf_ir[:, 0, 1].real ; gf_to[:, 10] = gf_ir[:, 0, 1].imag return gf_to def to_to_ir(self, zn_vec, gf_to): """convert from tabular-out form to cluster form""" zn_vec = zn_vec.copy() ; gf_to = gf_to.copy() assert(zn_vec.shape[0] == gf_to.shape[0]) assert(gf_to.shape[1] == 11) #the following three lines could be replaced by: gf_t = to_to_t(gf_to) # but I do this for tests purposes (np.testing) gf_t = np.zeros((gf_to.shape[0], (gf_to.shape[1] -1)//2)) gf_t = 1.0*gf_to[:, 1::2] + 1.0j*gf_to[:, 2::2] np.testing.assert_allclose(gf_t, self.to_to_t(gf_to)) gf_ir = np.zeros((zn_vec.shape[0], 4, 4), dtype=complex) gf_ir[:, 0, 0] = gf_t[:, 0] ; gf_ir[:, 0, 1] = gf_t[:, 4] gf_ir[:, 1, 0] = gf_ir[:, 0, 1] ; gf_ir[:, 1, 1] = gf_t[:, 1] gf_ir[:, 2, 2] = gf_t[:, 2] ; gf_ir[:, 3, 3] = gf_t[:, 3] return gf_ir
Python
UTF-8
5,395
3
3
[]
no_license
# coding: utf-8 '''城市相关的公共函数 ''' import os city2code = None code2city = None code2province = {} province2code = {} def gen_province(location_json): global code2province, province2code location = location_json["location"] china = location["coutryregion"][0] for s in china["state"]: code = int(s["code"]) code2province[code] = s["name"] province2code[s["name"]] = code def init(): global city2code, code2city if city2code and code2city: return from location import get_location_json gen_province(get_location_json()) import json from location import get_city_tuple city_tuple = get_city_tuple() code2city = {x[1]: x[0] for x in city_tuple} city2code = dict(city_tuple) # 2010年襄樊更名为襄阳.为保持兼容性,襄樊和襄阳返回同样city_code city2code[u'襄樊'] = 420600 def get_code2city(): ''' >>> len(get_code2city()) 370 ''' init() return code2city def get_city_code(name): u''' >>> get_city_code('酒泉') 620900 >>> get_city_code(u'酒泉') 620900 >>> get_city_code(u'三亚') 460200 >>> get_city_code(u'襄阳') 420600 >>> get_city_code(u'襄樊') 420600 >>> get_city_code('xx') ''' if not name: return None if isinstance(name, str): name = name.decode('utf-8') if name == u'未知': return -1 init() return city2code.get(name) def get_city_name(code): u''' >>> get_city_name(620900) == u'酒泉' True >>> print get_city_name('620900') 酒泉 >>> print get_city_name(u'110000') 北京 >>> print get_city_name('460200') 三亚 >>> print get_city_name('420600') 襄阳 >>> get_city_name('1') >>> get_city_name(None) ''' if not code: return None if code < 0: return u'未知' init() return code2city.get(int(code)) def get_city_list(): ''' >>> len(get_city_list()) 371 ''' init() return city2code.keys() def get_province_list(): ''' >>> len(get_province_list()) 34 ''' init() return [t[1] for t in sorted(code2province.items())] def get_province_code(city_code): """ city_code的前缀就是province_code. return str >>> get_province_code(152601) '15' >>> get_province_code('152601') '15' >>> get_province_code('1526011') '-1' >>> get_province_code(10) '-1' """ city_code = str(city_code) if len(city_code) != 6: return '-1' return city_code[:2] def get_province_code_by_name(name): u''' >>> get_province_code_by_name('北京') 11 >>> get_province_code_by_name(u'四川') 51 >>> get_province_code_by_name(u'xx') ''' init() if isinstance(name, str): name = name.decode('utf-8') return province2code.get(name) def get_province_name(code): u''' >>> get_province_name(51) == u'四川' True >>> get_province_name('51') == u'四川' True >>> get_province_name('1') >>> get_province_name(None) ''' init() return None if code is None else code2province.get(int(code)) def get_area_name(code): u''' >>> get_area_name(51) == u'四川' True >>> get_area_name(620900) == u'酒泉' True ''' return get_province_name(code) or get_city_name(code) def get_area_code(name): u''' >>> get_area_code('四川') 51 >>> get_area_code(u'北京') 11 >>> get_area_code(u'成都') 510100 ''' return get_province_code_by_name(name) or get_city_code(name) code2region = {} region2code = {} def init_region(): import os, csv global code2region, region2code if code2region and region2code: return CITY_CODE_IND = 1 REGION_NAME_IND = 5 REGION_CODE_IND = 2 encoding = 'utf-8' with open(os.path.join(os.path.dirname(__file__), 'city_info.csv'), 'r') as csv_f: csv_reader = csv.reader(csv_f, dialect=csv.excel) for row in csv_reader: try: city_code = int(row[CITY_CODE_IND]) region_code = int(row[REGION_CODE_IND]) if city_code and region_code: region_name = row[REGION_NAME_IND].decode(encoding) city_tuples = region2code.setdefault(region_name, []) city_tuples.append((city_code, region_code)) code2region[region_code] = region_name except Exception, e: pass def get_region_code(city_code_in, region_name): u''' >>> get_region_code(111, '') is None True >>> get_region_code(111, 'xxxx') is None True >>> get_region_code(445100, u'潮安县') 445121 >>> get_region_code(445100, u'潮安县111') is None True ''' init_region() if not region_name: return None if isinstance(region_name, str): region_name = region_name.decode('utf-8') for city_code, region_code in region2code.get(region_name, []): if city_code_in == city_code: return region_code return None def get_region_name(region_code): u''' >>> get_region_name(12345) is None True >>> get_region_name(441781) == u'阳春市' True ''' init_region() return code2region.get(region_code, None)
JavaScript
UTF-8
1,222
4.15625
4
[]
no_license
/* * Difficulty: * Medium * * Desc: * Given two numbers, hour and minutes. * Return the smaller angle (in sexagesimal units) formed between the hour and the minute hand. * * Example 1: * Input: hour = 12, minutes = 30 * Output: 165 * * Example 2: * Input: hour = 3, minutes = 30 * Output: 75 * * Example 3: * Input: hour = 3, minutes = 15 * Output: 7.5 * * Example 4: * Input: hour = 4, minutes = 50 * Output: 155 * * Example 5: * Input: hour = 12, minutes = 0 * Output: 0 * * Constraints: * 1. 1 <= hour <= 12 * 2. 0 <= minutes <= 59 * 3. Answers within 10^-5 of the actual value will be accepted as correct. * * 给你两个数 hour 和 minutes 。请你返回在时钟上,由给定时间的时针和分针组成的较小角的角度(60 单位制)。 */ /** * @param {number} hour * @param {number} minutes * @return {number} */ var angleClock = function(hour, minutes) { const h = (minutes / 60) + (hour === 12 ? 0 : hour) const hAngle = h / 12 const mAngle = minutes / 60 if (mAngle <= hAngle) { return Math.min( hAngle - mAngle, (1 - hAngle) + mAngle ) * 360 } return Math.min( mAngle - hAngle, (1 - mAngle) + hAngle ) * 360 }
C++
UTF-8
1,295
2.59375
3
[]
no_license
//------------------------------------------------------------------- // ADXL345_ex //------------------------------------------------------------------- #include "OLED.h" // OLED OLED myOLED; //------------------------------------------------------------------- #include "CCS811.h" // DS18B20 #define SDA_PIN PA4 ///< pin for SDA #define SCL_PIN PA5 ///< pin for SCL CCS811 voc; float humidity ; float temp; //------------------------------------------------------------------- int main(void) { //setup SystemClock_Config(); // OLED myOLED.begin(FONT_8x16); // or FONT_6x8 myOLED.println("VOC Test"); delay(100); // VOC voc.begin(SDA_PIN, SCL_PIN); // LED pinMode(LED_R, OUTPUT); digitalWrite(LED_R,LOW); // LED Red OFF //loop while (1) { delay(1000); digitalWrite(LED_R,HIGH);// LED Red ON voc.getData(); humidity = ((125 * voc.readHUMIDITY() ) / 65536.0) - 6; temp = ((175.72 * voc.readTEMPERATURE() )/ 65536.0) - 46.85; myOLED.setPosi(0,0); myOLED.print("temp :"); myOLED.println(temp); myOLED.print("humidity :"); myOLED.println(humidity); myOLED.print("co2 :"); myOLED.println(voc.readCO2()); myOLED.print("Tvoc :"); myOLED.println(voc.readTVOC()); digitalWrite(LED_R,LOW);// LED Red OFF } }
Java
UTF-8
160
1.804688
2
[]
no_license
package controller; public class Controller implements Core { @Override public void init() { } @Override public void update() { } }
PHP
UTF-8
890
2.53125
3
[]
no_license
<?php if (!defined('BASEPATH')) exit('No direct script access allowed'); /* * Dashboard Model * These are used by the Dashboard library to populate the dashboard UI. * Without this file, the exiting module will not display in the dashboard. * * Model should return an array of objects, and include 'helper', and 'title' * properties for the dashboard helper. * * /application/modules/pages/models/ */ class Sidebars_dashboard_model extends MY_Model { var $_table = 'mc_content'; var $_page_type = 'sidebar'; var $_helper = 'list_parent_kids'; var $_heading = 'Sidebars'; public function __construct() { $this->init(); } public function init() { $data = $this->db->where('page_type',$this->_page_type)->get($this->_table); if($data->num_rows() > 0) { $this->_results = $data->result(); } return $this; } } // End class
Java
UTF-8
498
3.78125
4
[]
no_license
import java.util.Scanner; public class PP2_10 { public static void main(String arg[]){ Scanner sc = new Scanner(System.in); System.out.print("Enter the length of a square's side: "); int num = sc.nextInt(); System.out.println("Perimeter is " + num * 4 + "\nArea is " + Math.pow(num,2)); } } /* * write an application that prompts for and reads an integer repre- * senting the length of a square's side and then prints the square's * perimeter and area * */
Python
UTF-8
1,746
2.953125
3
[]
no_license
#!/usr/bin/python import sys class bcolors: HEADER = '\033[95m' OKBLUE = '\033[94m' OKGREEN = '\033[92m' WARNING = '\033[93m' FAIL = '\033[91m' ENDC = '\033[0m' BOLD = '\033[1m' UNDERLINE = '\033[4m' def make_class(): if len(sys.argv) == 1: print(bcolors.FAIL + "Error:" + bcolors.ENDC + " Provide class name as" + " argument.") return make_header() if len(sys.argv) == 2: make_source() return def make_header(): class_name = sys.argv[1] is_template = False template_args = '' if len(sys.argv) > 3 and sys.argv[2] == '-t': is_template = True template_args = sys.argv[3:] header = open(class_name.lower() + ".hpp", "w") define = class_name.upper() + "_HPP" header_contents = ( r'#ifndef ' + define + '\n' r'#define ' + define + '\n\n' ) if is_template: header_contents += 'template <' for param in template_args: header_contents += 'typename ' + param + ', ' header_contents = header_contents[:-2] header_contents += '>\n' header_contents += ( r'class ' + class_name + ' {\n' r' public:''\n\t\n' r' private:''\n\t\n' r'};''\n\n' r'#endif''\t'r'// ' + define ) header.write(header_contents) header.close() return def make_source(): class_name = sys.argv[1] source_file = open(class_name.lower() + '.cpp', "w") source_contents = ( r'#include "' + class_name.lower() + '.hpp"' ) source_file.write(source_contents) source_file.close() return if __name__ == '__main__': make_class()
Java
UTF-8
390
2.140625
2
[]
no_license
package RemoteControl; interface IRemoteControl { public abstract void turnOn(); public abstract void turnOff(); public abstract void openMenu(); public abstract void closeMenu(); public abstract void volumeUp(); public abstract void volumeDown(); public abstract void mute(); public abstract void unmute(); public abstract void play(); public abstract void pause(); }
C#
UTF-8
396
2.65625
3
[]
no_license
class Foo { public static void Main() { Process p1 = new Process(); p1.StartInfo.FileName = "pdftotext"; p1.StartInfo.Arguments = "test.pdf test.txt"; p1.StartInfo.UseShellExecute = false; p1.StartInfo.WorkingDirectory = @"C:\"; p1.Start(); p1.WaitForExit(); } }
C++
UTF-8
2,650
2.734375
3
[]
no_license
//Author: Manan Patel, mvp5542@psu.edu, Thursday 8:00 AM - 9:50 AM //Class: CMPSC 121 //Experiment 05 //File: P:\Private\CMPSC 121\Experiments\exp05\exp5\exp5 //purpose: To find the assesment value and property tax for a piece of property //Academic Integrity Affidavit: I certify that, this program code is my work.Others may have assisted me //with planning and concepts, but the code was written, solely by me. //I understand that submitting code which is totally or partially the product of other individuals is a violation //of the Academic Integrity Policy and accepted ethical precepts. Falsified execution results are also results of improper //activities. Such violations may result in zero credit for the assignment, reduced credit for the assignment, or course failure. //Sources of logic assistance: 121 study group: None #include <iostream> #include <string> #include <iomanip> using namespace std; int main() { const int LT20 = 20; const double LT20Charge = 0.10; const int LT40 = 40; const double LT40Charge = 0.08; const int LT60 = 60; const double LT60Charge = 0.06; const double GTE60Charge = 0.04; const double BALANCELIMIT = 400.00; const double LOWBALANCECHARGE = 15.00; int numberOfChecks; bool isUnder = false; double balance, serviceFee = 0, checkCharge; cout << fixed << setprecision(2); cout << "Please enter beginning balance and number of checks written: " << endl; cin >> balance >> numberOfChecks; if (balance < BALANCELIMIT) { serviceFee + LOWBALANCECHARGE; isUnder = true; } if (numberOfChecks < LT20) serviceFee += (LT20Charge*numberOfChecks); else if (numberOfChecks < LT40) serviceFee += (LT40Charge*numberOfChecks); else if (numberOfChecks < LT60) serviceFee += (LT60Charge*numberOfChecks); else serviceFee += (GTE60Charge*numberOfChecks); cout << "MEGABUX Bancorp" << endl; cout << "Your balance was " << balance << endl; if (isUnder) { cout << "You did not maintain the minimum balance! " << endl; cout << "You incurred a fee of $ " << LOWBALANCECHARGE << endl; } cout << "Total service charge = $ " << serviceFee << endl; return 0; } /* Execution Sample: #1) Please enter beginning balance and number of checks written: 100 5 MEGABUX Bancorp Your balance was 100.00 You did not maintain the minimum balance! You incurred a fee of $ 15.00 Total service charge = $ 0.50 Press any key to continue . . . #2) Please enter beginning balance and number of checks written: 500 35 MEGABUX Bancorp Your balance was 500.00 Total service charge = $ 2.80 Press any key to continue . . . */
Markdown
UTF-8
421
3.15625
3
[]
no_license
# SomeUnitConversions This is a C program to do some common unit conversions, as follows:- 1. Km to miles 2. Inch to feet 3. Cm to inch 4. Pound to kg 5. Inches to metres. This menu driven program asks everytime for an input from the user which contains his/her choice of conversions as follows:- A for km to miles, B for inches to feet, C for cm to inches, D for pounds to kgs, E for inches to metres, Q to quit.
C++
UTF-8
645
3.265625
3
[]
no_license
#include <iostream> #include "Factory.h" int main(){ Container< Shape * > con; try{ con.push_back(Factory::create("Point")); con.push_back(Factory::create("Circle")); con.push_back(Factory::create("Rect")); con.push_back(Factory::create("Square")); con.push_back(Factory::create("Polyline")); con.push_back(Factory::create("Polygon")); std::cout << "Now " << Shape::getCount() << ": Elements" << "\n"; for (unsigned int i = 0; i < con.size(); i++){ con[i]->print(); } con.free(); std::cout << "Now " << Shape::getCount() << " Elements" << "\n"; } catch (std::exception & e){ std::cout << e.what(); } return 0; }
Java
UTF-8
601
2.109375
2
[]
no_license
package test.provider; import test.API.HelloService; import rpc.RPCFramwork2; import java.io.IOException; /** * @author: zhun.huang * @create: 2018-05-02 上午11:29 * @email: nolan.zhun@gmail.com * @description: */ public class Provider { public static void main(String[] args) throws InterruptedException, IOException { HelloService helloService = new HelloServiceImpl(); try { RPCFramwork2.export(helloService,12371); } catch (Exception e) { e.printStackTrace(); } System.in.read(); System.out.println("exit server"); } }
JavaScript
UTF-8
1,883
3.28125
3
[]
no_license
const labelMap = { 1: { name:'Car', color:'lime' }, 2: { name:'Handphone', color:'yellow' } } // Main drawing function export const drawRectCustomModel = (boxes, classes, scores, threshold, imgWidth, imgHeight, ctx) =>{ // Loop through each prediction for(let i=0; i <= boxes.length; i++){ // Check if prediction is valid if(boxes[i] && classes[i] && scores[i]>threshold){ // Exrtract boxes and classes const [y, x, height, width] = boxes[i]; const text = classes[i]; console.log(width, height, labelMap[text]['name'] + ' ' + Math.round(scores[i]*100) + '%') // Setup canvas styles // const color = Math.floor(Math.random()*16777215).toString(16); ctx.beginPath(); ctx.strokeStyle = labelMap[text]['color'] ctx.font = '20px Arial'; ctx.fillStyle = labelMap[text]['color'] ctx.lineWidth = 5 // Draw text and rectangle ctx.fillText(labelMap[text]['name'] + ' ' + Math.round(scores[i]*100) + '%', x*imgWidth, y*imgHeight-5); ctx.rect(x*imgWidth, y*imgHeight, width*imgWidth/2, height*imgWidth/2); ctx.stroke(); } } } export const drawRectCOCOModel = (detections, ctx) =>{ // Loop through each prediction detections.forEach(prediction => { // Extract boxes and classes const [x, y, width, height] = prediction['bbox']; const text = prediction['class']; // ctx.scale(-1, 1); // Set styling const color = Math.floor(Math.random()*16777215).toString(16); ctx.strokeStyle = '#' + color ctx.font = '20px Arial'; // Draw rectangles and text ctx.beginPath(); ctx.fillStyle = '#' + color ctx.fillText(text + ' ' + Math.round(prediction['score']*100) + '%', x, y-10); ctx.lineWidth = 5 ctx.rect(x, y, width, height); ctx.stroke(); }); }
Python
UTF-8
3,638
3.34375
3
[]
no_license
""" author rochanaph October 23 2017""" import w3,w4,w5, os def main(): path = './text files' this_path = os.path.split(__file__)[0] path = os.path.join(this_path, path) # membaca sekaligus pre-processing semua artikel simpan ke dictionary articles = {} for item in os.listdir(path): if item.endswith(".txt"): with open(path + "/" + item, 'r') as file: articles[item] = w3.prepro_base(file.read()) # representasi bow list_of_bow = [] # membuat list kosong for key, value in articles.items(): # iterasi pasangan key, value # print key, value list_token = value.split() # cari kata2 dengan men-split dic = w4.bow(list_token) # membuat bow list_of_bow.append(dic) # append bow ke list kosong yg di atas # membuat matrix matrix_akhir = w4.matrix(list_of_bow) # jalankan fungsi matrix ke list_of_bow # mencari jarak jarak = {} for key, vektor in zip(articles.keys(), matrix_akhir): jarak[key] = w5.euclidean(matrix_akhir[0], vektor) # simpan nama file sbg key, jarak sbg value return jarak # print main() def findSim(keyword, path): # membuat dictionary articles # membaca semua file .txt yang berada di direktori path(text files) # kemudian dimasukan kedalam dictionary articles dengan nama item/index(nama dokumen) articles = {} for item in os.listdir(path): if item.endswith(".txt"): with open(path + item, 'r') as file: articles[item] = w3.prepro_base(file.read()) # memasukan kata kunci kedalam dictionary dengan nama item/index(keyword_index) # kemudian dimasukan ke dictionary articles dengan value keyword yang dimasukan kata_kunci = 'keyword_index' articles[kata_kunci] = w3.prepro_base(keyword) #menyimpan baris pertama dari dokumen dan menyimpannya dalam dictionary isi_doc = {} for isi in os.listdir(path): if isi.endswith(".txt"): with open(path + isi,'r') as file: isi_doc[isi] = file.read() # membuat list list_of_bow # yang kemudian dimasukan token-token unik di setiap dokumennya list_of_bow = [] for key, value in articles.items(): list_token = value.split() dic = w4.bow(list_token) list_of_bow.append(dic) # membuat matrix tiap-tiap dokumen dengan token unik dari semua dokumen matrix_akhir = w4.matrix(list_of_bow) # mencari id/urutan keyword_index # membuat dictionary presentase untuk semua dokumen id_keyword = articles.keys().index(kata_kunci) presentase = {} for key, vektor in zip(articles.keys(), matrix_akhir): if key != kata_kunci: presentase[key] = round(w5.cosine(matrix_akhir[id_keyword], vektor),2) #mencari baris dalam suati dokumen yang relevan dengan keyword baris = {} token_key = w3.prepro_base(keyword).split() for item in os.listdir(path): if item.endswith(".txt"): # baris[item] = "" tmp = [] doc = open(path + item, 'r').readlines() for word in token_key: for line in doc: if word in w3.tokenize(w3.prepro_base(line)) and line not in(value for index,value in enumerate(tmp)): tmp.append(line) if tmp != [] : #line of keyword lok = ''.join(tmp) baris[item] = lok else : baris[item] = 'kosong' return w4.sortdic(presentase, isi_doc, baris, descending=True) # print findSim('./text files/ot_2.txt','./text files')
TypeScript
UTF-8
1,078
2.609375
3
[ "Apache-2.0", "MIT", "BSD-3-Clause" ]
permissive
import { Component, ElementRef, Input, ViewEncapsulation } from '@angular/core'; import { AbstractFdNgxClass } from '../../utils/abstract-fd-ngx-class'; /** * Label component, used to indicate status, without any background or border * Colors, generally in combination with text, are used to easily highlight the state of an object. */ @Component({ // tslint:disable-next-line:component-selector selector: '[fd-label]', template: `<ng-content></ng-content>`, encapsulation: ViewEncapsulation.None, styleUrls: ['./label.component.scss'] }) export class LabelComponent extends AbstractFdNgxClass { /** Color coded status for the label. Options are 'success', 'warning', and 'error'. Leave empty for default label. */ @Input() status: string = ''; /** @hidden */ _setProperties() { this._addClassToElement('fd-label'); if (this.status) { this._addClassToElement('fd-label--' + this.status); } } /** @hidden */ constructor(private elementRef: ElementRef) { super(elementRef); } }
Java
UTF-8
1,343
2.453125
2
[]
no_license
package com.example.medicalcart; import android.support.annotation.NonNull; 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.List; public class ProductListAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> { private List<String> productList; public class SimpleViewHolder extends RecyclerView.ViewHolder { public SimpleViewHolder(View itemView) { super(itemView); } } @NonNull @Override public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) { View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.product_item, viewGroup, false); return new SimpleViewHolder(view); } @Override public void onBindViewHolder(@NonNull RecyclerView.ViewHolder viewHolder, int i) { View view = viewHolder.itemView; TextView productName = view.findViewById(R.id.product_name); productName.setText(productList.get(i)); } @Override public int getItemCount() { return productList.size(); } public void setProductList(List<String> productList) { this.productList = productList; notifyDataSetChanged(); } }
Markdown
UTF-8
15,353
2.6875
3
[]
no_license
--- title: "gin源码" categories: [coder] tags: [go,源码] date: 2021-07-21 fancybox: true --- gin是go开发的一个开源高性能http框架,其主要是把go官方的`net/http`进行了扩展,前缀树实现了动态路由、支持了中间件、对请求信息进行封装方便用户层使用等。本文基于 `gin v1.7.2`版本 ## 创建流程 一个Engine实例可以使用`New` 或者 `Default`进行创建,唯一区别就是`Default`默认增加了两个中间件:日志Logger(), panic捕获 Recovery() 初始化会初始化以下内容: ```go //gin.go engine := &Engine{ //默认的分组 RouterGroup: RouterGroup{ Handlers: nil, basePath: "/", root: true, }, FuncMap: template.FuncMap{}, RedirectTrailingSlash: true, RedirectFixedPath: false, HandleMethodNotAllowed: false, ForwardedByClientIP: true, RemoteIPHeaders: []string{"X-Forwarded-For", "X-Real-IP"}, TrustedProxies: []string{"0.0.0.0/0"}, TrustedPlatform: defaultPlatform, UseRawPath: false, RemoveExtraSlash: false, UnescapePathValues: true, MaxMultipartMemory: defaultMultipartMemory, trees: make(methodTrees, 0, 9), delims: render.Delims{Left: "{{", Right: "}}"}, secureJSONPrefix: "while(1);", } engine.RouterGroup.engine = engine //Context上下文Pool engine.pool.New = func() interface{} { return engine.allocateContext() } ``` 初始化好后,就可以注册业务的相关api,比如GET、POST等。默认情况下所有的api都是在根分组下,举个例子: ```go r := gin.Default() //此处的api所在的分组是默认分组,所以请求api的时候直接 /ping即可 r.GET("/ping", func(c *gin.Context) { c.String(http.StatusOK, "pong") }) ``` 下面说一下注册api的流程: ```go //routergroup.go func (group *RouterGroup) handle(httpMethod, relativePath string, handlers HandlersChain) IRoutes { //2. 将相对路径转为绝对路径 //主要就是 分组的路径+请求的路径,比如:分组为 v1/,请求路径是 hello ,这个请求的全路径就是 v1/hello absolutePath := group.calculateAbsolutePath(relativePath) //3. 因为gin支持中间件,这里是把组携带的handler和传递过来的请求函数进行组合 handlers = group.combineHandlers(handlers) //4. 将中间件和请求函数的组合放入路由中 //这样的话,一次api请求,会执行一系列的函数集,达到中间件的效果 //因为中间件是属于组的,所以一个组下的所有api都支持 group.engine.addRoute(httpMethod, absolutePath, handlers) return group.returnObj() } //1. 对外提供的http方法 //其他POST DELETE PUT 等注册流程都一样 func (group *RouterGroup) GET(relativePath string, handlers ...HandlerFunc) IRoutes { return group.handle(http.MethodGet, relativePath, handlers) } ``` 初始化好一个Engine,并且注册了api后,就可以运行服务,对外使用了。 ```go // main.go func main() { r := gin.Default() r.GET("/ping", func(c *gin.Context) { c.String(http.StatusOK, "pong") }) r.Run(":9000") } // gin.go func (engine *Engine) Run(addr ...string) (err error) { defer func() { debugPrintError(err) }() err = engine.parseTrustedProxies() if err != nil { return err } address := resolveAddress(addr) debugPrint("Listening and serving HTTP on %s\n", address) //gin实现了ServeHTTP(w http.ResponseWriter, req *http.Request) //所以注册到http服务 err = http.ListenAndServe(address, engine) return } ``` 因为官方 `net/http` 提供了接口:`ServeHTTP(ResponseWriter, *Request)`,gin实现了接口: ```go //gin.go func (engine *Engine) ServeHTTP(w http.ResponseWriter, req *http.Request) { c := engine.pool.Get().(*Context) c.writermem.reset(w) c.Request = req c.reset() engine.handleHTTPRequest(c) engine.pool.Put(c) } ``` 所以在底层收到http消息后,会回调gin实现的ServeHTTP,这样http消息就可以走gin提供的路由、中间件等逻辑了 ## 请求流程 1. 发起http请求 2. 底层回调gin注册函数`ServeHTTP` 3. 从sync.pool中获取一个可用`Context` 4. 因为是结构体并且sync.pool机制不会主动重置`Context`,所以手动重置`Context` 5. 从前缀树中寻找对应路由 6. 执行请求对应的函数 7. 将结果写入响应`Response` 8. `Context`放回sync.pool中 ```go //gin.go //底层回调gin注册函数`ServeHTTP` func (engine *Engine) ServeHTTP(w http.ResponseWriter, req *http.Request) { //从sync.pool中获取一个可用`Context` c := engine.pool.Get().(*Context) c.writermem.reset(w) c.Request = req //因为是结构体并且sync.pool机制不会主动重置`Context`,所以手动重置`Context` c.reset() //执行请求 engine.handleHTTPRequest(c) engine.pool.Put(c) } ``` 从pool中获取,如果没有会进行创建,创建函数是在初始化的时候注册的。 ```go //gin.go func New() *Engine { //... engine.pool.New = func() interface{} { return engine.allocateContext() } } func (engine *Engine) allocateContext() *Context { v := make(Params, 0, engine.maxParams) return &Context{engine: engine, params: &v} } ``` ## 分组与中间件 ### 分组的作用 分组的好处是将其下的所有api进行统一管理,如果没有分组,增加一个通用功能,就需要对每一个api分别添加。比如:对`/admin`开头的路由进行鉴权,gin中只需要这样做: ```go gAdmin:=r.Group("/admin").Use(func(c *gin.Context) { //鉴权 }) gAdmin.GET("/delUser", func(c *gin.Context) {}) gAdmin.GET("/addUser", func(c *gin.Context) {}) ``` 当用户请求 `/admin/delUser`和`/admin/addUser`时,会先执行鉴权函数。`Use`也就是增加中间件的方法。 ### 分组的路由 另外一个路由的添加是由分组地址+api的地址组合而成,初始化`Engine`的时候会默认有个根组它的`basePath`为 `/`: ```go //gin.go func New() *Engine { engine := &Engine{ RouterGroup: RouterGroup{ Handlers: nil, basePath: "/", root: true, }, //... } //... return engine } ``` 如果不创建其他组,使用默认组的话: ```go func main() { r := gin.Default() //请求路由为 group.basePath+ `/ping` = http://127.0.0.1/ping r.GET("/ping", func(c *gin.Context) { c.String(http.StatusOK, "pong") }) } ``` 分组有父子关系,下面这个`a`分组派生于根分组,所以`a`分组下的api路由是 `/a/xxx`,b分组下的api路由是`/a/b/xxx`,`c`分组由根分组派生,所以`c`分组下的api路由是 `/c` ```go func main() { r := gin.Default() aGroup := r.Group("/a") bGroup := aGroup.Group("/b") cGroup := r.Group("/c") } ``` 路由如此,中间件也会如此,组`b`下的api包含所有父组的中间件: ```go //routergroup.go func (group *RouterGroup) Group(relativePath string, handlers ...HandlerFunc) *RouterGroup { return &RouterGroup{ //新的组包含父辈的所有中间件 Handlers: group.combineHandlers(handlers), basePath: group.calculateAbsolutePath(relativePath), engine: group.engine, } } ``` ### 中间件的执行 现在知道了分组和路由的关系,看看中间件是如何执行的。gin在注册一个api的时候,会把组中的中间件函数和api函数放到数组里,增加到路由里: ```go //routergroup.go func (group *RouterGroup) handle(httpMethod, relativePath string, handlers HandlersChain) IRoutes { absolutePath := group.calculateAbsolutePath(relativePath) //将中间件和api函数组合,中间件在数组前面 api函数在其后 handlers = group.combineHandlers(handlers) group.engine.addRoute(httpMethod, absolutePath, handlers) return group.returnObj() } func (group *RouterGroup) combineHandlers(handlers HandlersChain) HandlersChain { finalSize := len(group.Handlers) + len(handlers) assert1(finalSize < int(abortIndex), "too many handlers") mergedHandlers := make(HandlersChain, finalSize) copy(mergedHandlers, group.Handlers) copy(mergedHandlers[len(group.Handlers):], handlers) return mergedHandlers } ``` 来了一个请求后,找到对应路由下的函数放到`Context`上下文中,调用`Next`执行,并且要注意的是所有的中间件所有的函数都用的同一个`Context` ```go func (engine *Engine) handleHTTPRequest(c *Context) { //.. value := root.getValue(rPath, c.params, unescape) if value.params != nil { c.Params = *value.params } if value.handlers != nil { c.handlers = value.handlers c.fullPath = value.fullPath c.Next() c.writermem.WriteHeaderNow() return } //.. } ``` 这里说一下Next执行细节,用个例子来说明:对分组`a`下所有api请求计时 ```go func Logger(c *gin.Context) { //开始计时 t := time.Now() //调用下一个函数 c.Next() //计算用时 latency := time.Since(t) log.Print(latency) } func Hello(c *gin.Context){ fmt.Println("hello") } func main() { r := gin.Default() aGroup := r.Group("/a").Use(Logger) aGroup.GET("b", Hello) r.Run(":9000") } ``` 1. 初始化Context ```go func (c *Context) reset() { c.Writer = &c.writermem c.Params = c.Params[:0] c.handlers = nil //index字段是-1 c.index = -1 c.fullPath = "" c.Keys = nil c.Errors = c.Errors[:0] c.Accepted = nil c.queryCache = nil c.formCache = nil *c.params = (*c.params)[:0] } ``` 2. 调用函数 Next(index=0) ```go func (c *Context) Next() { c.index++ for c.index < int8(len(c.handlers)) { c.handlers[c.index](c) c.index++ } } ``` 3. 执行了Logger函数: 开始计时 4. Logger内部执行c.Next,再次调用Next函数 5. 因为index是c中的变量,所以会变成index=1 6. 所以此时执行了Hello 7. Hello执行后因为index已经变成2了,所以Next完结 8. Logger因c.Next()完成,继续执行后续操作:计算时间 打印时间 9. 完成了整个api调用 ## 路由 上面说的各种流程都没讲一个请求过来,是如何找到具体的执行函数的,这里就是路由的作用了。用`map`存路由表,索引效率高效,但只支持静态路由。类似`/hello/:name` 可以匹配到 `/hello/wang` `/hello/zhang`的动态路由不支持。gin里使用了前缀树来实现。前缀树就不在这里介绍了 ### 创建路由 下面注册了5个api,从源码看看是如何执行的 ```go func main() { r := gin.New() r.GET("/index", func(c *gin.Context) { c.JSON(200, "index") }) r.GET("/inter", func(c *gin.Context) { c.JSON(200, "inter") }) r.GET("/user/get", func(c *gin.Context) { c.JSON(200, "/user/get") }) r.GET("/user/del", func(c *gin.Context) { c.JSON(200, "/user/del") }) r.GET("/user/:name", func(c *gin.Context) { c.JSON(200, "/user/:name") }) r.Run(":9000") } ``` ```go func (n *node) addRoute(path string, handlers HandlersChain) { fullPath := path n.priority++ // 第一个api注册因为根节点path和children是空的所以直接成为根节点的子节点 if len(n.path) == 0 && len(n.children) == 0 { n.insertChild(path, fullPath, handlers) n.nType = root return } parentFullPathIndex := 0 walk: for { // 获得第一次字符不同的位置 比如 // "/index" 和 "/inter" 第一次字符不同的位置 也就是 i=3 i := longestCommonPrefix(path, n.path) if i < len(n.path) { child := node{ path: n.path[i:], wildChild: n.wildChild, indices: n.indices, children: n.children, handlers: n.handlers, priority: n.priority - 1, fullPath: n.fullPath, } /*当前node增加一个子节点child 以 inter为例子,api inter插入之前已经有了index,并且发现他们有相同字符in所以将index节点改为 in节点,dex变成子in的子节点,后面的代码会再将 ter放到in子节点中。 child := node{ path: n.path[i:], // dex wildChild: n.wildChild, // false indices: n.indices, // "" children: n.children, //null handlers: n.handlers, // index func priority: n.priority - 1, fullPath: n.fullPath, // /index } n.indices = "d" n.path = "/in" n.fullPath = "" */ n.children = []*node{&child} n.indices = bytesconv.BytesToString([]byte{n.path[i]}) n.path = path[:i] n.handlers = nil n.wildChild = false n.fullPath = fullPath[:parentFullPathIndex+i] } if i < len(path) { path = path[i:] c := path[0] if n.nType == param && c == '/' && len(n.children) == 1 { parentFullPathIndex += len(n.path) n = n.children[0] n.priority++ continue walk } // 以user/del为例; // 此时根节点的indices= "iu" 匹配到了相同字符 `u` 于是进行跳转,并将n指向 path="user/" 的节点 for i, max := 0, len(n.indices); i < max; i++ { if c == n.indices[i] { parentFullPathIndex += len(n.path) i = n.incrementChildPrio(i) n = n.children[i] continue walk } } if c != ':' && c != '*' && n.nType != catchAll { //以插入inter api为例: // 此时n.indices = "dt" dex和ter的首字母 n.indices += bytesconv.BytesToString([]byte{c}) child := &node{ fullPath: fullPath, } n.addChild(child) n.incrementChildPrio(len(n.indices) - 1) //这里这么写是方便后面流程通用 看 FF: n = child } else if n.wildChild { n = n.children[len(n.children)-1] n.priority++ if len(path) >= len(n.path) && n.path == path[:len(n.path)] && n.nType != catchAll && (len(n.path) >= len(path) || path[len(n.path)] == '/') { continue walk } pathSeg := path if n.nType != catchAll { pathSeg = strings.SplitN(pathSeg, "/", 2)[0] } prefix := fullPath[:strings.Index(fullPath, pathSeg)] + n.path panic("'" + pathSeg + "' in new path '" + fullPath + "' conflicts with existing wildcard '" + n.path + "' in existing prefix '" + prefix + "'") } n.insertChild(path, fullPath, handlers) return } //FF: if n.handlers != nil { panic("handlers are already registered for path '" + fullPath + "'") } n.handlers = handlers n.fullPath = fullPath return } } ``` 最后这个前缀树的结构应该是这样的: ![前缀树](../../../img/2021/trie-gin.png) ### api请求 `engine.trees`这是一个数组,每个请求类型(POST GET PUT...)独立一个树 ```go type methodTree struct { method string root *node } type methodTrees []methodTree ``` 当接收到底层传来的http请求后,先找到指定请求类型的树结构,然后再查询路由,查询方式比较简单,主要就是遍历树。为了提高查询效率,indices的作用就是在查询子节点之前,先找indices里有没有请求的path首字符,没有的话直接查询失败。 ```go //gin.go func (engine *Engine) handleHTTPRequest(c *Context) { //... httpMethod := c.Request.Method t := engine.trees for i, tl := 0, len(t); i < tl; i++ { if t[i].method != httpMethod { continue } root := t[i].root //查询路由 value := root.getValue(rPath, c.params, unescape) if value.params != nil { c.Params = *value.params } if value.handlers != nil { c.handlers = value.handlers c.fullPath = value.fullPath c.Next() c.writermem.WriteHeaderNow() return } //... } } ```
C++
UTF-8
1,508
2.890625
3
[]
no_license
#include "pch.h" #include "JobManager.h" using namespace Jobs; JobManager* JobManager::instance = nullptr; JobManager* JobManager::GetInstance() { if (instance == nullptr) instance = new JobManager(); return instance; } void JobManager::ReleaseInstance() { if (instance != nullptr) { delete instance; instance = nullptr; } } JobManager::JobManager() { const unsigned int SupportedThreads = GetAmountOfSuppoertedThreads(); isDone = false; for (size_t i = 0; i < SupportedThreads; i++) { workerThreads.push_back(std::thread(&Jobs::JobManager::WorkerThread, this)); } } JobManager::~JobManager() { isDone = true; for (auto &item : workerThreads) { item.join(); } } void JobManager::AddJob(void(*func_ptr)(void*, int), void* args, int index) { CpuJob aJob; aJob.jobArgs = args; aJob.index = index; IJOB* jobPtr = new JobFunc(func_ptr); aJob.jobPtr = jobPtr; locklessQueue.enqueue(aJob); } void JobManager::WorkerThread() { while (true) { if (isDone) return; CpuJob currJob; bool found = locklessQueue.try_dequeue(currJob); if (found) { if (currJob.jobPtr) { currJob.jobPtr->invoke(currJob.jobArgs, currJob.index); delete currJob.jobPtr; } } else { std::this_thread::sleep_for(std::chrono::microseconds(3)); } } } //Accessories inline const size_t JobManager::GetThreadCount() const { return workerThreads.size(); } inline int JobManager::GetAmountOfSuppoertedThreads() { return std::thread::hardware_concurrency(); }
Java
UTF-8
3,762
3.59375
4
[]
no_license
package hard; import java.util.Stack; /** * @program: leetcode * @description: 84. Largest Rectangle in Histogram * array stack * @author: Liu Hanyi * @create: 2019-05-07 16:02 **/ public class LargestRectangleArea84 { public static void main(String[] args) { int[] heights = {2, 1, 5, 6, 2, 3}; System.out.println(new LargestRectangleArea84().largestRectangleArea4(heights)); } public int largestRectangleArea(int[] heights) { int max = 0; for (int i = 0; i < heights.length; i++) { int area = heights[i]; int minHeight = heights[i]; for (int j = i + 1; j < heights.length; j++) { minHeight = Math.min(minHeight, heights[j]); area = Math.max(area, (j - i + 1) * minHeight); } max = Math.max(area, max); } return max; } public int largestRectangleArea2(int[] heights) { if (heights == null || heights.length == 0) { return 0; } int[] lessFromLeft = new int[heights.length]; // idx of the first bar the left that is lower than current int[] lessFromRight = new int[heights.length]; // idx of the first bar the right that is lower than current lessFromRight[heights.length - 1] = heights.length; lessFromLeft[0] = -1; for (int i = 1; i < heights.length; i++) { int p = i - 1; while (p >= 0 && heights[p] >= heights[i]) p = lessFromLeft[p]; lessFromLeft[i] = p; } for (int i = heights.length - 2; i >= 0; i--) { int p = i + 1; while (p < heights.length && heights[p] >= heights[i]) p = lessFromRight[p]; lessFromRight[i] = p; } int max = 0; for (int i = 0; i < heights.length; i++) { max = Math.max(max, heights[i] * (lessFromRight[i] - lessFromLeft[i] - 1)); } return max; } public int largestRectangleArea3(int[] height) { int len = height.length; Stack<Integer> s = new Stack<Integer>(); int maxArea = 0; for (int i = 0; i <= len; i++) { int h = (i == len ? 0 : height[i]); if (s.isEmpty() || h >= height[s.peek()]) { s.push(i); } else { int tp = s.pop(); maxArea = Math.max(maxArea, height[tp] * (s.isEmpty() ? i : i - 1 - s.peek())); i--; } } return maxArea; } public int largestRectangleArea4(int[] height) { if (height.length == 0) return 0; return largestRectangleArea(height, 0, height.length - 1); } private int largestRectangleArea(int[] height, int start, int end) { if (start == end) return height[start]; int mid = start + (end - start) / 2; int area = largestRectangleArea(height, start, mid); area = Math.max(area, largestRectangleArea(height, mid + 1, end)); area = Math.max(area, largestRectangleArea(height, start, mid, end)); return area; } private int largestRectangleArea(int[] height, int start, int mid, int end) { int i = mid, j = mid + 1; int area = 0; int h = Math.min(height[i],height[j]); while (i >= start && j <= end){ h = Math.min(h,Math.min(height[i],height[j])); area = Math.max(area,h * (j-i+1)); if (i == start) j++; else if (j == end) i--; else { if (height[i-1] > height[j+1]) i--; else j++; } } return area; } }
Go
UTF-8
1,380
4.1875
4
[]
no_license
package main import ( "fmt" "time" ) type Node struct { Next *Node Value interface{} } //Creating Struct For link list type LinkedList struct { Length int // will be used for counting the Length Head *Node Tail *Node } // to push a new node at the end of the link list func (l *LinkedList) Push(val interface{}) { node := &Node{Value: val} if l.Head == nil { l.Head = node } else { l.Tail.Next = node } l.Tail = node l.Length = l.Length + 1 } // this will pop the last element in the link list func (l *LinkedList) Pop() { node := l.Head if l.Length == 1 { l.Head = nil } else { for i := 1; i < l.Length-1; i++ { node = node.Next } node.Next = node.Next.Next } l.Length = l.Length - 1 } func producers(l *LinkedList, c1, c2 chan string, number int){ for i:=1; i< number+1 ;i++{ l.Push(i) c1 <- "produced" <-c2 } close(c1) } func consumer(l *LinkedList, c1, c2 chan string){ for _ = range c1{ l.Pop() c2 <- "consumed" } close(c2) } func main() { var l LinkedList var number int var c1 = make(chan string, 10) var c2 = make(chan string, 10) fmt.Println("Enter the number of producers you want: ") fmt.Scanf("%d", &number) start := time.Now() go producers(&l, c1, c2, number) go consumer(&l, c1, c2) elapsed := time.Since(start) fmt.Println("Time taken is: ", elapsed) }
Java
UTF-8
636
2.578125
3
[]
no_license
package com.lamp.commons.lang.time; import java.util.Date; /** * @author muqi * */ public class TimeTuple<T> { private T beginTime; private T endTime; public TimeTuple(T beginTime , T endTime){ this.beginTime = beginTime; this.endTime = endTime; } public T getBeginTime() { return beginTime; } public void setBeginTime(T beginTime) { this.beginTime = beginTime; } public T getEndTime() { return endTime; } public void setEndTime(T endTime) { this.endTime = endTime; } @Override public String toString() { return "TimeTuple [beginTime=" + beginTime + ", endTime=" + endTime + "]"; } }
Java
UTF-8
511
2.65625
3
[]
no_license
package builder.ejercicioTarea7; public class Cocinero_Director { private BuilderPizza builderPizza; public void setBuilderPizza(BuilderPizza builderPizza) { this.builderPizza = builderPizza; } public Pizza getPizza(){ return builderPizza.getPizza(); } public void armarPizza(){ this.builderPizza.createPizza(); this.builderPizza.buildIngredientes(); this.builderPizza.buildTipoDeMasa(); this.builderPizza.buildTipoDeQueso(); } }
Python
UTF-8
2,024
2.96875
3
[]
no_license
from ejers_1.utils import clean_tonkenize class InvertexIndex: index = {} def __init__(self, path_list): """ initializes the new InvertexIndex instance by indexing file content of files from path_list :param path_list: list of file paths to be indexed """ for file_path in path_list: with open(file_path) as file: self.process_file(file, file_path) def process_file(self, file, file_path): """ indexes the content of a file :param file: :param file_path: :return: """ # for line in file: # for token in clean_tonkenize(line): for token in clean_tonkenize(file.read()): token_indexed_values = self.index.get(token, set()) token_indexed_values.add(file_path) self.index[token] = token_indexed_values class InvertedQuery: def __init__(self, invertex_index): """ initializes the new InvertedQuery instance by setting the InvertexIndex to query :param invertex_index: index to query """ self.invertex_index = invertex_index def query(self, query): result_doc_set = set() query_token_list = [t for t in clean_tonkenize(query)] for token in query_token_list: [result_doc_set.add(doc) for doc in self.invertex_index.index[token]] return result_doc_set ''' Prueba de concepto''' print("Invertex: prueba de concepto") import datetime t_start = datetime.datetime.now() t_invertex_index = InvertexIndex(['.\corpus\pg135.txt', '.\corpus\pg76.txt', '.\corpus\pg5200.txt']) t_query = InvertedQuery(t_invertex_index) t_index = datetime.datetime.now() print("index build time: %s" % str(t_index-t_start)) print(t_query.query("The house was in England")) t_finish = datetime.datetime.now() print("query time: %s" % str(t_finish-t_index)) print("Total time: %s" % str(t_finish-t_start))
Java
UTF-8
224
1.632813
2
[]
no_license
package org.donghyun.mreview.repository; import org.donghyun.mreview.entity.Member; import org.springframework.data.jpa.repository.JpaRepository; public interface MemberRepository extends JpaRepository<Member, Long> { }
Python
UTF-8
2,001
2.84375
3
[]
no_license
""" Export RTL-SDR barometer readings to prometheus http://www.smbaker.com/ Dependencies: sudo pip install prometheus_client """ import sys import json import traceback from prometheus_client import Gauge, start_http_server class Exporter(object): def __init__(self): start_http_server(8000) self.gauge_humid = Gauge("SensorHumid", "BME280 Sensor Humidity", ["id"]) self.gauge_temp = Gauge("SensorTemp", "BME280 Sensor Temperature", ["id"]) self.gauge_barom = Gauge("SensorBarom", "BME280 Sensor Barometer", ["id"]) self.gauge_seq = Gauge("SensorSeq", "BME280 Sensor Sequence Number", ["id"]) self.gauge_time = Gauge("SensorTime", "BME280 Sensor Timestamp", ["id"]) def process_lines(self): while True: try: self.process_line() except SystemExit, e: raise e except Exception: traceback.print_exc("Exception in main") def process_line(self): line = sys.stdin.readline().strip() if not line: # readline() will always return a /n terminated string, except # on the last line of input. If we see an empty string then # we must be at eof. print >> sys.stderr, "exporter reached EOF" sys.exit(0) data = json.loads(line) print json.dumps(data) if "id" not in data: return id = data["id"] if "temp" in data: self.gauge_temp.labels(id=id).set(data["temp"]/10.0) if "humid" in data: self.gauge_humid.labels(id=id).set(data["humid"]/10.0) if "barom" in data: self.gauge_barom.labels(id=id).set(data["barom"]) if "seq" in data: self.gauge_seq.labels(id=id).set(data["seq"]) self.gauge_time.labels(id=id).set_to_current_time() def main(): exp = Exporter() exp.process_lines() if __name__ == "__main__": main()
Python
UTF-8
534
4.09375
4
[]
no_license
# Grid with Randomness def setup(): size(800, 800) smooth() noLoop() def draw() : background(255) strokeWeight(2) stroke(0) noFill() n = 8 w = width/n for y in range(0, n): for x in range(0, n): px = x*w py = y*w #the chance of drawing a circle is 5% #otherwise, it draws a square chance = random(1) if (chance < .1): ellipse(px + w/2, py+w/2, w-25, w-25) else: rect(px+10, py+10, w-20, w-20)
C++
UTF-8
5,180
3
3
[]
no_license
//Ian Forsyth //CPSC 478 //Final Project #include <iostream> #include <string> #include <GL/gl.h> #include <GL/glut.h> #include <cstdlib> #include <ctime> #include <math.h> #include <sstream> #include "createMaze.h" createMaze::createMaze(float height, float width){ goal = location(width-1, height-1); //Start the goal in the far corner player = location(0.0,0.0); //Start the player in the opposite corner srand(time(0)); score = 0; //Start the score at 0 //Set the maze height theMaze.resize(height); setChecker.resize(height); //Set the maze width, fill with walls in actual maze, fill //with sequential numbers for pseudo-maze for (int counter = 0; counter < height; counter++) { theMaze[counter].resize(width, part(false, false)); setChecker[counter].resize(width, NULL); for (int counter2 = 0; counter2 < width; counter2++) setChecker[counter][counter2] = (counter*width)+counter2; } //Iterate randomly through every wall in the maze and //clear a path through the walls using Kruskal's algorithm, //implemented in the makeMaze function for (int counter = 0; counter < theMaze.size()*theMaze[0].size()*10; counter++) makeMaze(location(rand()%(int)theMaze[0].size(), rand()%(int)theMaze.size())); } //Returns a true or false value about whether //the player can move. Based on the 'start' location //and the bool values in upClear and rightClear of the //location itself and neighbors. bool createMaze::stepChecker(unsigned int dir, location start){ //Check up direction if (dir == 0) return theMaze[start.y][start.x].upClear; //Check right direction else if (dir == 1) return theMaze[start.y][start.x].rightClear; //Check down direction else if (dir == 2 & start.y < theMaze.size()-1) return theMaze[start.y+1][start.x].upClear; //Check left direction else if (dir == 3 & start.x > 0) return theMaze[start.y][start.x-1].rightClear; return false; } //After checking if the player can move, handle //actually moving in the corresponding direction location createMaze::partStepper(location start, int dir){ //Move up if (dir == 0) return location(start.x, start.y-1); //Move right else if (dir == 1) return location(start.x+1, start.y); //Move down else if (dir == 2) return location(start.x, start.y+1); //Move left else if (dir == 3) return location(start.x-1, start.y); else return start; } bool createMaze::makeMaze(location start){ int dir = rand()%2; //Random up or right int setID = setChecker[start.y][start.x]; int newSetID; //Check to make sure the border of the maze stays solid if ((dir == 0 && start.y == 0) || (dir == 1 && start.x == theMaze[0].size()-1)) return false; //Depending on the random, check if the upper or right wall should be //removed based on previous removals if (dir == 0){ newSetID = setChecker[start.y-1][start.x]; if (newSetID == setID) return false; theMaze[start.y][start.x].upClear = true; } if (dir == 1){ newSetID = setChecker[start.y][start.x+1]; if (newSetID == setID) return false; theMaze[start.y][start.x].rightClear = true; } //Here renumber the big numbered-grid to start creating sets for (int row = 0; row < theMaze.size(); row++) for (int column = 0; column < theMaze[0].size(); column++) if (setChecker[row][column] == setID) setChecker[row][column] = newSetID; } //Resets the maze to have all the walls back up //iterates through and sets all the clear boolean //values to false void createMaze::resetMaze(){ //Placing all the walls back in the maze for (int row = 0; row < theMaze.size(); row++) for (int column = 0; column < theMaze[0].size(); column++){ theMaze[row][column].upClear = false; theMaze[row][column].rightClear = false; setChecker[row][column] = (row*theMaze[0].size())+column; } //Iterate through every wall in the maze randomly and run //Kruskal's algorithm to create a path for (int counter = 0; counter < theMaze.size()*theMaze[0].size()*10; counter++) makeMaze(location(rand()%(int)theMaze[0].size(), rand()%(int)theMaze.size())); //Place the goal object at a random location in the maze goal = location(rand()%(int)(height()-1), rand()%(int)(width()-1)); //If the goal object is placed on the player object, reset again if(goal.x == player.x && goal.y == player.y) resetMaze(); //Add to score total score++; } //Move the player based on the permission boolean void createMaze::movePlayer(int dir){ if(stepChecker(dir, player)){ player = partStepper(player, dir); //If move causes a collision between player and goal, //reset the maze (score total incremented in resetMaze) if(player.x == goal.x && player.y == goal.y) resetMaze(); } } //References location createMaze::findPlayer() {return player;} float createMaze::height() {return theMaze.size();} float createMaze::width() {return theMaze[1].size();} location createMaze::findGoal() {return goal;} createMaze::createMaze() {return;} //Converts the integer 'score' to a string so it can be drawn //on the play screen string createMaze::scoreString(){ stringstream output; output << "Your score: "<<score<<"/5"; return output.str(); }
C
UTF-8
722
3.15625
3
[]
no_license
/* * LedDriver.c * * Created: 21/03/2018 9:00:51 * Author: Kris */ #include "../headers/LedDriver.h" /** LEDS init @param void. @return void */ void ledsInit(void) { // All output DDRA = 0b11111111; } /** LEDS on @param bitmask char. @return void */ void ledsOn(char bitmask) { PORTA = PORTA | bitmask; } /** Turn off LEDS @param bitmask char. @return void */ void ledsOff(char bitmask) { PORTA = ~bitmask & PORTA; } /** LEDS Toggle -> choose leds to toggle @param bitmask char. @return void */ void ledsToggle(char bitmask) { PORTA = bitmask ^ PORTA; } /** LEDS set @param bitmask char -> absolute value. @return void */ void ledsSet(char bitmask) { PORTA = bitmask; }
PHP
UTF-8
2,597
2.640625
3
[]
no_license
<?php namespace CGG\ConferenceBundle\Tools; use CGG\ConferenceBundle\Repository\PageRepository; use Symfony\Bundle\TwigBundle\TwigEngine; use Symfony\Component\HttpFoundation\RequestStack; use Symfony\Component\Security\Core\SecurityContext; class MailAdminConferenceCreated { private $request; private $conferenceAttributes; private $context; private $user; private $mailer; private $template; public function __construct(RequestStack $request, SecurityContext $context, \Swift_Mailer $mailer, TwigEngine $template) { $this->request=$request; $this->context=$context; $this->mailer = $mailer; $this->template = $template; } public function mailAdminConferenceCreated(){ $this->conferenceAttributes = $this->request->getCurrentRequest()->request->get('cgg_conferencebundle_conference'); $conferenceTitle = $this->conferenceAttributes['name']; $conferenceDescription = $this->conferenceAttributes['description']; $conferenceStartDate = $this->conferenceAttributes['startDate']; $conferenceEndDate = $this->conferenceAttributes['endDate']; $this->user = $this->context->getToken()->getUser(); $username = $this->user->getUsername(); $userEmail = $this->user->getEmail(); $subject = $username . ' demande à créer une conférence nommée : ' . $conferenceTitle; $from = $this->user->getEmail(); $to = 'cally.cyril@hotmail.fr'; $body = $this->template->render('CGGConferenceBundle:Mail:bodyEmailAdminConferenceCreated.html.twig', [ 'username'=>$username, 'userEmail'=>$userEmail, 'conferenceTitle'=>$conferenceTitle, 'conferenceDescription'=>$conferenceDescription, 'conferenceStartDate'=>$conferenceStartDate, 'conferenceEndDate'=>$conferenceEndDate, ]); $this->sendMailAdminConferenceCreated($subject, $from, $to, $body); } public function sendMailAdminConferenceCreated($subject, $from, $to, $body){ $transport = \Swift_SmtpTransport::newInstance('smtp.gmail.com', 587, 'tls') ->setUsername('yoann.galland71@gmail.com') ->setPassword('cafartee') ; $this->mailer->newInstance($transport); $message = \Swift_Message::newInstance() ->setSubject($subject) ->setFrom($from) ->setTo($to) ->setBody( $body, 'text/html' ); $this->mailer->send($message); } }
Java
UTF-8
1,181
3
3
[]
no_license
package physics; import game.Object; import geometry.*; public class RigidBody{ public double mass; public double drag; public Object object; public RigidBody(Object object, double mass){ this.object = object; this.mass = mass; this.drag = 0; this.object.setAcceleration(Vector.DOWN().scalar(9.8f)); } public void update(double dt){ if(drag > 0) object.setVelocity(object.getVelocity().scalar(Math.min(Math.max((double)(1 - dt * getDrag()), 0), 1))); } public double getMass(){ return mass; } public void setMass(double mass){ this.mass = Math.max(mass, 0); } public double getDrag(){ return drag; } public void setDrag(double drag){ this.drag = Math.max(drag, 0); } public Vector getPosition(){ return object.getPosition(); } public void setPosition(Vector position){ object.setPosition(position); } public void setPosition(double x, double y, double z){ object.setPosition(x, y, z); } public Vector getVelocity(){ return object.getVelocity(); } public void setVelocity(Vector velocity){ object.setVelocity(velocity); } public void setVelocity(double x, double y, double z){ object.setVelocity(x, y, z); } }
Shell
UTF-8
575
2.765625
3
[]
no_license
#!/bin/bash ./gradlew clean build -x test java -jar eureka-server/build/libs/eureka-server*.jar &>/dev/null & EUREKA_PID=$! java -jar sample-application/build/libs/sample-application*.jar &>/dev/null & SAMPLE_PID=$! java -jar gateway-server/build/libs/gateway-server*.jar > log & GATEWAY_PID=$! echo "wait for initialization" until curl "http://localhost:8881/sample/tests" -w %{http_code}\\n -s -o /dev/null -L --insecure | grep -E "(200|500)" || [[ "$retries" -lt 0 ]]; do sleep 5s done ./gradlew :sample-application:test kill $EUREKA_PID $SAMPLE_PID $GATEWAY_PID
PHP
UTF-8
2,723
3.078125
3
[]
no_license
<?php //分页的函数 function news($pageNum = 1, $pageSize = 3) { include 'mysql.php'; $array = array(); // limit为约束显示多少条信息,后面有两个参数,第一个为从第几个开始,第二个为长度 $rs = "select * from news limit " . (($pageNum - 1) * $pageSize) . "," . $pageSize; $r = mysqli_query($conn, $rs); while ($obj = mysqli_fetch_object($r)) { $array[] = $obj; } mysqli_close($conn); return $array; } //显示总页数的函数 function allNews() { include 'mysql.php'; $rs = "select count(*) num from news"; //可以显示出总页数 $r = mysqli_query($conn, $rs); $obj = mysqli_fetch_object($r); mysqli_close($conn); return $obj->num; } @$allNum = allNews(); @$pageSize = 3; //约定每页显示几条信息 @$pageNum = empty($_GET["pageNum"])?1:$_GET["pageNum"]; @$endPage = ceil($allNum/$pageSize); //总页数 @$array = news($pageNum,$pageSize); ?> <?php session_start(); if(!isset($_SESSION['username'])){ header('Refresh:0.0001;url=login.php'); echo "<script> alert('非法访问!')</script>"; exit(); } include 'DBConn.php'; ?> <!DOCTYPE html> <html lang="en"> <head> <title>修改日志</title> </head> <body bgcolor="#C0A890"> <h1>修改日志</h1> <tr> <td colspan="2" align="center"> <a href='homepage.php'>日志首页</a></td> </tr> <div align="center"> <table width="900" border="1" align="center"> <tr> <th>日志ID</th> <th>标题</th> <th>关键字</th> <th>作者</th> <th>发布时间</th> <th>内容</th> <th>操作</th> </tr> <?php include('mysql.php'); //利用 查询语句 $sql="select * from news "; //$conn->query('SET NAMES UTF8'); $cx=mysqli_query($conn,$sql); foreach($array as $key=>$row){ echo "<tr align='center'>"; echo "<td>$row->id</td>"; echo "<td>$row->title</td>"; echo "<td>$row->keywords</td>"; echo "<td>$row->author</td>"; echo "<td>$row->addtime</td>"; echo "<td>$row->content</td>"; echo "<td><a href='xg.php?id={$row->id}'>修改</a></td>"; echo "</tr>"; } ?> </table> <div> <a href="?pageNum=1">首页</a> <a href="?pageNum=<?php echo $pageNum==1?1:($pageNum-1)?>">上一页</a> <a href="?pageNum=<?php echo $pageNum==$endPage?$endPage:($pageNum+1)?>">下一页</a> <a href="?pageNum=<?php echo $endPage?>">尾页</a> </div> </div> </body> </html>
C++
UTF-8
1,863
3.171875
3
[ "MIT" ]
permissive
/* * 2520 is the smallest number that can be divided by each of the numbers from 1 to 10 * without any remainder. * * What is the smallest positive number that is evenly divisible by all of the numbers * from 1 to 20? */ #ifndef PROBLEM0005_HPP__ #define PROBLEM0005_HPP__ #include <iostream> #include <algorithm> #include <iterator> #include <vector> #include <numeric> #include <map> #include <cmath> #include "trial_division.hpp" long problem5() { vector<long> factors(19); iota(factors.begin(), factors.end(), 2); vector<vector<long>> prime_factors; for (auto x : factors) { prime_factors.push_back(vector<long>()); trial_division(x, back_inserter(prime_factors.back())); } vector<long> unique_factors; for (auto element_prime_factors : prime_factors) { for (auto element_factor : element_prime_factors) { if (count(unique_factors.begin(), unique_factors.end(), element_factor) == 0) { unique_factors.push_back(element_factor); } } sort(unique_factors.begin(), unique_factors.end()); } map<long, long> factor_powers_map; for_each(unique_factors.begin(), unique_factors.end(), [&](long x) { factor_powers_map.insert(make_pair(x, 0UL)); }); for_each(unique_factors.begin(), unique_factors.end(), [&](long x) { for (auto element_prime_factors : prime_factors) { auto factor_exponent = count(element_prime_factors.begin(), element_prime_factors.end(), x); if (factor_exponent > factor_powers_map[x]) { factor_powers_map[x] = factor_exponent; } }; }); return accumulate(factor_powers_map.begin(), factor_powers_map.end(), 1L, [](long previous, const pair<long, long>& factor_with_power) { return previous *= pow(factor_with_power.first, factor_with_power.second); }); } #endif
Markdown
UTF-8
12,200
3.078125
3
[]
no_license
1. Data 2. Software 3. Key commands [TOC] >为防止系统出现操作失误或系统故障导致数据丢失,我们需要将全部或部分数据集合从应用主机的硬盘或阵列复制到其它存储介质。 ## Part1:备份知多少 ### Q1:当我们谈备份时,我们在谈论着什么? 上周技能树里的小伙伴提到因为服务器断电而不慎丢失数据的悲惨事件,因此觉得有必要在这信息爆炸的时代学会保护自己的数据,不然哪天丢了都不知该怎么办好(经费充足且及时补救还存在数据恢复服务这一选项)。暗自推算,按照一般价格算50RMB/GB价格,恢复2000G的硬盘…… >![恢复价格](http://east2-image.oss-cn-shanghai.aliyuncs.com/18-12-12/67385809.jpg) 某网站的收费清单。。。 总之,做生信分析,还是得牢牢把控住数据源头啊。 ### Q2:有什么备份的方式呢? 简单而言可以分成两类,一类是逻辑备份,另一类是物理备份。一般而言,个人用户主要采用物理备份中的冷备份。随着技术的不断发展,网络备份也越来越普及,网络备份一般通过专业的数据存储管理软件结合相应的硬件和存储设备来实现(常见的有各种网盘及其变种)。 > - 逻辑备份:指通过逻辑导出对数据进行备份。将数据库中的用户对象导出到一个二进制文件中,逻辑备份使用导入导出工具:EXPDP/IMPDP或EXP/IMP,由于将数据库对象导出到操作系统二进制文件中,或由二进制文件中把数据导入到数据库中。逻辑备份可以作为备份的补充方法,但是不要把逻辑备份当成唯一的数据库备份方案。逻辑备份则是对物理备份的方式的一种补充,由于逻辑备份具有平台无关性,逻辑备份被作为数据迁移及移动的主要手段。 - 物理备份: 指通过物理文件拷贝的方式对数据库进行备份,物理备份又可以分为冷备份和热备份。 + 冷备份:是指对数据库进行关闭后的拷贝备份,这样的备份具有一致和完整的时间点数据,恢复时只需要恢复所有文件就可以启动数据库; + 热备份:在生产系统中最常见的备份方式是热备份,进行热备份的数据库需要运行在归档模式,热备份时不需要关闭数据库,从而能够保证系统的持续运行,在进行恢复时,通过备份的数据文件及归档日志文件,数据库可以进行完全恢复。当然,如果是为了恢复某些用户错误,热备份的恢复完全可以在某一个时间点上停止恢复,也就是不完全恢复。 ### Q3:我该从哪些角度进行完整备份? 数据的备份不同于整个系统备份,将不同数据按照优先级分类,根据用户需求,备份重要文件。使数据独立于操作系统,降低备份成本与时间。 首先我们得有一个对自己文件清楚的了解,避免冗余,减少备份系统的成本。其次根据要备份的文件估算备份需要的时间,也可以定期自动备份。 基本数据分类: - 用户数据、用户目录,及私人文件等。 - 系统信息:系统用户、组、密码,主机列表等。 - 应用程序:系统版本不变的备份可以镜像复制,但 - 应用程序的配置文件与数据:针对不同的应用程序,不同的配置参数和重要数据文件。 - 数据库:事实上数据库可以单独提供针对数据库所有数据的备份与同步功能。 适用于个人或者小型网站的备份策略: - 完全备份:适合于第一次备份或者忘记备份的内容是什么(之前备份的东西毫无价值。。) - 增量备份:第一次备份后,为了减少备份硬盘的再次读写和时间损耗,通常采取增量备份的策略 ### Q4: 策略了解了,那数据存放的物理介质有什么选择吗? 1. 磁盘阵列柜:IT预算宽裕的企业的"宠儿" 2. 文件服务器:专门负责企业内部文件的管理与处理,文件服务器日常的数据管理及处理工作通常包括数据上传、下载、共享、存储、备份等,对于大多数中小企业而言是一个不错的选择 3. 光盘塔:光盘容量非常有限及购买光盘的花费大,刻录机寿命不长,人工操作,而且光盘易丢失、损坏,数据管理与恢复工作繁琐 4. 磁带机:建议结合其他存储设备一起使用,做到万无一失 5. NAS(网络附加存储):已成为或即将成为主流! >NAS英文全称为 Network Attached Storage,可译为网络附加存储,是一种专用网络数据存储备份设备。 它以数据为中心,将存储设备与服务器彻底分离,集中管理数据,从而释放网络带宽、提高性能、降低总拥有成本、提高IT投资的有效性。)NAS(网络附加存储)的构成将硬盘连起组成阵列,就是一个小型磁盘阵列柜,NAS本身内含CPU、内存、主板(与普通PC、服务器不同,中高端的NAS采用工业级标准的部件作为其硬件构成,自带操作系统,与通用操作系统不同 NAS采用的是嵌入式以LINNUX为内核的精简化(整个操作系统已去除多余媒体指令,整个系统仅仅数M的存储占用量)操作系统,工业级的部件结合精简化的操作系统使其具备独力工作的能力,作为专用的数据存储/备份设备,部分品牌NAS如IBM、HP、自由遁等品牌的部分产品已整合高度智能化、全自动的专业数据备份软件,几无地域限制结合优异的网络连接功能使它能够在本地、异地、远程的数据备份能力得到充分的展示,同时无地域限制限制布署容易,简易的操作大大提升了NAS易用性(IE式的管理与访问、操作界面让不需要太多的专业IT知识的操作人员也可轻松驾驭)。作为专门为数据存储、备份而生的存储设备,部分品牌NAS采取磁轨式数据备份技术,同时在数据备份方式方面除了完全数据备份以外,部分品牌(如IBM、EMC、自由遁等)的部分产品自带的备份软件中含有增量、差异数据备份方式。 ## Part2:动手备份吧 不同的操作系统可能使用不同的数据备份方式,本文介绍了通用的 Unix/Linux 实用程序 tar以及远程备份工具 rsync,windows下则是freefilesync软件,大家也可以另行搜索(软件测评一大把,此处不再赘述)。 ### Windows下的备份 一般而言,个人用户在windows系统下的备份可以比较粗暴。小编还少不更事的时候,采用的策略都是完全备份(简单粗暴,用U盘或者移动硬盘直接复制粘贴)。 软件的话freefilesync已可满足一般需求,具体可以到官网查看:https://freefilesync.org/ ![](http://east2-image.oss-cn-shanghai.aliyuncs.com/18-12-12/37035110.jpg) ### Linux下的备份 #### 工具1:tar ![tar参数](http://east2-image.oss-cn-shanghai.aliyuncs.com/18-12-12/1166500.jpg) ![](http://east2-image.oss-cn-shanghai.aliyuncs.com/18-12-12/14906327.jpg) #### 工具2:Rsync rsync(Remote Sync)是 Unix/Linux 系统下一款优秀的数据备份与同步工具。它可以对文件集进行同步。然而更有价值的是,rsync 使用文件的增量,也就是说,它在网络中仅发送两个文件集合有区别的部分。这样可以占用更少的带宽,并且速度更快。能够实现增量备份、更新整个目录树和文件系统、本地备份及远程备份,以及保留文件权限、所有权、链接及更多对象在命令行上,使用脚本和计划任务,实现备份任务自动化。下期仔细讲讲这个工具。 常用参数: ![](http://east2-image.oss-cn-shanghai.aliyuncs.com/18-12-12/48646572.jpg) ![](http://east2-image.oss-cn-shanghai.aliyuncs.com/18-12-12/8278760.jpg) 首次传输过程进行完全备份,当再次运行该命令时,rsync 将只传输数据的增量。从而完成增量备份。 ### 小白,增加数据备份意识! #### 措施1:平时注意避免物理损伤习惯(他人含泪总结!) 由于没有经历过损失数据这样惨痛DIY经历,特摘录他人教训一份(引自知乎,【数据备份】- 含泪总结:如何保护自己的重要数据? - Steven的文章 https://zhuanlan.zhihu.com/p/29157250) 1. 尽可能的多备份几份数据,最好台式机备份一份,移动硬盘备份一份。(移动硬盘很容易被摔,台式机比较稳定,数据损失的可能性低,但要预防病毒) 2. 备份用的硬盘最好使用WD(西部数据),西部数据的转速只有5400转/分,而希捷、三星的硬盘转速高达7200转/分,硬盘转速越快,数据读取快,硬盘价格也贵,但数据损坏的概率也就大很多了。盘面旋转快,被划伤的可能性就会很大。 3. 硬盘被摔后,不要频繁通电。有些小伙伴在磁盘摔了后,频繁通电检测,非常容易导致数据的全部丢失,因为磁头可能还在划伤盘面,导致数据恢复的可能性大幅降低,甚至无法恢复。 4. 硬盘数据不要使用第三方加密程序或加密狗加密,尤其是某些公司购买的全国没几人能够解密的加密软件进行加密,导致数据完全无法恢复。 5. 数据备份尽量不要使用SSD(固态硬盘),因为固态硬盘不会轻易坏,但坏了数据恢复的可能性很低,而且恢复成本也非常高。 #### 措施2:我的硬盘已经毁了,怎么整? 好吧,你备份了吗?在追悔之余,还是赶快学习一下这期推送的内容吧,下次就有底了。 ### 参考 [1]数据无价 谨慎备份----论数据备份的重要性[EB/OL]. 知乎专栏, [2018-12-12]. https://zhuanlan.zhihu.com/p/24648648. [2]数据库备份的分类 - Paul’s Notes - CSDN博客[EB/OL]. [2018-12-12]. https://blog.csdn.net/pan_tian/article/details/42198909. [3]全量、增量、差异备份,这个故事讲得很透[EB/OL]. 知乎专栏, [2018-12-12]. https://zhuanlan.zhihu.com/p/28783571. [4]冷数据备份存储技术探索 - 云+社区 - 腾讯云[EB/OL]. [2018-12-12]. https://cloud.tencent.com/developer/article/1030061. [5]教程:数据备份存储设备分类 - 51CTO.COM[EB/OL]. [2018-12-12]. http://stor.51cto.com/art/200808/86043.htm. [6]个人数据备份的常见方案-月光博客[EB/OL]. [2018-12-12]. https://www.williamlong.info/archives/4381.html. [7]【数据备份】- 含泪总结:如何保护自己的重要数据?[EB/OL]. 知乎专栏, [2018-12-12]. https://zhuanlan.zhihu.com/p/29157250. --- http://www.cnic.cas.cn/zcfw/sjfw/sjzyzx/xxfw_sdb03/201007/t20100730_2915568.html #### 其他备份工具资源 1. Backupninja 这款功能强大的备份工具让用户可以备份活动配置文件,这些文件可以放入到/etc/backup.d/目录。它有助于通过网络,执行安全的远程备份以及增量备份。 主要功能: 易于读取ini式样的配置文件 使用脚本处理你系统上新类型的备份 计划并安排备份何时进行 用户可以选择用于状态报告的电子邮件何时发送给自己。 可使用基于控制台的向导(ninjahelper),轻松构建备份操作配置文件。 可与Linux-Vserver协同运行。 2. Kbackup ![Kbackup_sct](https://dn-linuxcn.qbox.me/data/attachment/album/201604/02/213904c6zduqwqhidz65u5.png) 这款易于使用的备份工具面向Unix操作系统,可以在Linux上使用。它可以构建归档文件,然后分别使用tar和gzip实用工具来进行压缩。 Kbackup具有下列功能: 易于使用、菜单驱动的界面。 支持压缩、加密和双重缓存。 自动化无人值守备份。 高度可靠。 支持完全备份或增量备份。 跨网络进行远程备份。 3. Back Time ![](https://dn-linuxcn.qbox.me/data/attachment/album/201604/02/213904p1dx6s1cbs2dggg9.png) 这是一款简单的、易于使用的备份工具,面向Linux操作系统,它可以对指定的目录拍取快照,然后加以备份。 它具有配置等功能,比如可以配置: 保存快照的存储位置。 手动或自动备份。 备份目录。
C#
UTF-8
1,494
2.703125
3
[]
no_license
using School.DataLayer.Abstract; using School.Model.Entities; using School.Model.Helpers; using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Text; using System.Threading.Tasks; namespace School.Logic { public class CoursesLogic { private IUnitOfWork _unitOfWork; public CoursesLogic(IUnitOfWork unitOfWork) { _unitOfWork = unitOfWork; } public IEnumerable<Course> GetCourses(Expression<Func<Course, bool>> filter = null, PageInf pageInf = null, Expression<Func<Course, object>> orderBy = null, bool byDesc = false) { var coursesRepo = _unitOfWork.GetRepositiry<Course>(); var courses = coursesRepo.Get(filter, pageInf, c => c.Groups, orderBy, byDesc); return courses; } public virtual IEnumerable<Course> InsertOrUpdate(IEnumerable<Course> courses) { var coursesRepo = _unitOfWork.GetRepositiry<Course>(); var insOrUpdCourses = coursesRepo.InsertOrUpdate(courses); _unitOfWork.Save(); return insOrUpdCourses; } public virtual IEnumerable<Course> Delete(int courseId) { var coursesRepo = _unitOfWork.GetRepositiry<Course>(); var retCourses = coursesRepo.Delete(courseId); _unitOfWork.Save(); return retCourses; } } }
C
GB18030
1,004
3.015625
3
[]
no_license
#pragma once //ҵ //LinkNode *node -----> LinkNode head -----> LinkNode node LinkNodeͽLinkNode *next // char name[25] char name[25] ӦΪLinkNode *data(ݵĵַ) // int age int age //С typedef struct LinkNode { struct LinkNode *next;// }LinkNode; // typedef struct LinkList { LinkNode head;//ֱʹLinkNodeͽ㣬Ҫָָ int size; }LinkList; typedef void (*PrintNode)(LinkNode *); typedef int (*Compare)(LinkNode *,LinkNode *); //ʼ LinkList *Init_LinkList(); // void Insert(LinkList *list, int pos, LinkNode *data); //ɾ void Del(LinkList *list, int pos); // void Find(LinkList *list, LinkNode *data,Compare find); //شС int Size(LinkList *list); //ӡ void Print_List(LinkList *list, PrintNode print); //ͷ void Free(LinkList *list);
C
UTF-8
922
2.703125
3
[]
no_license
#include <stdio.h> #include <stdlib.h> #include "agenda.h" int main(){ void* buffer; int* aux_int; float* aux_float; char* aux_char; Header* aux_header; Contact* aux_contact; buffer = (void*) malloc(sizeof(char)+sizeof(int)+sizeof(float)+sizeof(Header)+10*sizeof(Contact)); aux_char = (char*) buffer; aux_int = (int*) buffer + sizeof(int); aux_float = (float*) aux_int + sizeof(float); aux_header = (Header*) aux_float + sizeof(Header); aux_contact = (Contact*) aux_header + sizeof(Contact); aux_header->first = (Contact*) aux_contact; aux_header->last = (Contact*) aux_contact; initAgenda(aux_header); scanf("%[^\n]s", aux_contact->name); scanf("%d", &aux_contact->tel); insertContact(aux_header,aux_contact); setbuf(stdin,NULL); scanf("%[^\n]s", aux_contact->name); scanf("%d", &aux_contact->tel); insertContact(aux_header,aux_contact); printContacts(aux_header); // showMenu(); return 0; }
Markdown
UTF-8
2,515
3.5625
4
[ "CC-BY-SA-4.0", "BSD-3-Clause", "CC-BY-4.0" ]
permissive
--- id: 5a2efd662fb457916e1fe604 title: do...while 循环 challengeType: 1 videoUrl: 'https://scrimba.com/c/cDqWGcp' forumTopicId: 301172 dashedName: iterate-with-javascript-do---while-loops --- # --description-- 这一节我们将要学习的是`do...while`循环,它会先执行`do`里面的代码,如果`while`表达式为真则重复执行,反之则停止执行。我们来看一个例子。 ```js var ourArray = []; var i = 0; do { ourArray.push(i); i++; } while (i < 5); ``` 这看起来和其他循环语句差不多,返回的结果是`[0, 1, 2, 3, 4]`,`do...while`与其他循环不同点在于,初始条件为假时的表现,让我们通过实际的例子来看看。 这是一个普通的 while 循环,只要`i < 5`,它就会在循环中运行代码。 ```js var ourArray = []; var i = 5; while (i < 5) { ourArray.push(i); i++; } ``` 注意,我们首先将`i`的值初始化为 5。执行下一行时,注意到`i`不小于 5,循环内的代码将不会执行。所以`ourArray`最终没有添加任何内容,因此示例中的所有代码执行完时,`ourArray`仍然是`[]`。 现在,看一下`do...while`循环。 ```js var ourArray = []; var i = 5; do { ourArray.push(i); i++; } while (i < 5); ``` 在这里,和使用 while 循环时一样,我们将`i`的值初始化为 5。执行下一行时,没有检查`i`的值,直接执行花括号内的代码。数组会添加一个元素,并在进行条件检查之前递增`i`。然后,在条件检查时因为`i`等于 6 不符合条件`i < 5`,所以退出循环。最终`ourArray`的值是`[5]`。 本质上,`do...while`循环确保循环内的代码至少运行一次。 让我们通过`do...while`循环将值添加到数组中。 # --instructions-- 将代码中的`while`循环更改为`do...while`循环,实现数字 10 添加到`myArray`中,代码执行完时,`i`等于`11`。 # --hints-- 你应该使用`do...while`循环。 ```js assert(code.match(/do/g)); ``` `myArray`应该等于`[10]`。 ```js assert.deepEqual(myArray, [10]); ``` `i`应该等于`11`。 ```js assert.deepEqual(i, 11); ``` # --seed-- ## --after-user-code-- ```js if(typeof myArray !== "undefined"){(function(){return myArray;})();} ``` ## --seed-contents-- ```js // Setup var myArray = []; var i = 10; // Only change code below this line while (i < 5) { myArray.push(i); i++; } ``` # --solutions-- ```js var myArray = []; var i = 10; do { myArray.push(i); i++; } while (i < 5) ```
Markdown
UTF-8
547
2.640625
3
[]
no_license
# Code-Snippet-WPF-and-PowerShell This code is to provide a generic PowerShell code template so that we just need to paste the XAML code of a WPF form in the here-string provided. You can also choose to get the XAML content from a file (using Get-Content and storing it in a PowerShell variable), instead of using a Here-String with the code pasted inside... Tried to make a synoptical view of the process in the below schema with small sample screenshots: ![WPF from Visual Studio to PowerShell](DocResources/How-o-CreatePowerShellWPFApp.jpg)
C++
UTF-8
1,593
3.03125
3
[]
no_license
#include <fstream> #include "JsonBagIdea.h" int main(int argc, char* argv[]) { std::cout << "//////////// Struct Profile to Json //////////////" << std::endl << std::endl; Profile user1, user2, user3; std::vector<Profile> profileList; user1.name = "Thanawat Suriya"; user1.school_name = "BagIdea"; user1.age = 26; user2.name = "Hello Jaaa"; user2.school_name = "BagIdea"; user2.age = 12; user3.name = "Sample Najaa"; user3.school_name = "Tontan"; user3.age = 45; profileList.push_back(user1); profileList.push_back(user2); profileList.push_back(user3); std::string json_user1 = JsonBagIdea::GenerateJson(user1); std::cout << json_user1 << std::endl << std::endl; std::string jsonList = JsonBagIdea::GenerateJsonList(profileList); std::cout << jsonList << std::endl; std::cout << "\n//////////// Json to Profile Struct //////////////" << std::endl << std::endl; std::string jsonTest, jsonData; std::fstream file("jsonData.txt"); std::getline(file, jsonTest); std::getline(file, jsonData); file.close(); std::cout << jsonTest << std::endl << std::endl; Profile profileTest = JsonBagIdea::CreateProfileFromJson(jsonTest); std::cout << "Name: " << profileTest.name << "\tSchoolName: " << profileTest.school_name << "\tAge: " << profileTest.age << std::endl << std::endl; std::cout << jsonData << std::endl << std::endl; std::vector<Profile> profileData = JsonBagIdea::CreateProfileVectorFromJson(jsonData); for(Profile obj : profileData) std::cout << "Name: " << obj.name << "\tSchoolName: " << obj.school_name << "\tAge: " << obj.age << std::endl; return 0; }
Java
WINDOWS-1250
1,788
2.171875
2
[]
no_license
package bean; import javax.validation.constraints.NotNull; import org.springframework.format.annotation.NumberFormat; import org.springframework.format.annotation.NumberFormat.Style; public class ZuzycieBeanWzorzec { @NotNull(message="Prosz wypeni pole") @NumberFormat(style=Style.NUMBER) private Double finalne; @NotNull(message="Prosz wypeni pole") @NumberFormat(style=Style.NUMBER) private Double sO2; @NotNull(message="Prosz wypeni pole") @NumberFormat(style=Style.NUMBER) private Double nox; @NotNull(message="Prosz wypeni pole") @NumberFormat(style=Style.NUMBER) private Double cO; @NotNull(message="Prosz wypeni pole") @NumberFormat(style=Style.NUMBER) private Double pyl; @NotNull(message="Prosz wypeni pole") @NumberFormat(style=Style.NUMBER) private Double cO2; @NotNull(message="Prosz wypeni pole") @NumberFormat(style=Style.NUMBER) private Double baP; private Double rok; public Double getFinalne() { return finalne; } public void setFinalne(Double finalne) { this.finalne = finalne; } public Double getsO2() { return sO2; } public void setsO2(Double sO2) { this.sO2 = sO2; } public Double getNox() { return nox; } public void setNox(Double nox) { this.nox = nox; } public Double getcO() { return cO; } public void setcO(Double cO) { this.cO = cO; } public Double getPyl() { return pyl; } public void setPyl(Double pyl) { this.pyl = pyl; } public Double getcO2() { return cO2; } public void setcO2(Double cO2) { this.cO2 = cO2; } public Double getBaP() { return baP; } public void setBaP(Double baP) { this.baP = baP; } public Double getRok() { return rok; } public void setRok(Double rok) { this.rok = rok; } }
Java
UTF-8
1,140
3.703125
4
[]
no_license
import java.util.Stack; public class BasicCalculator { public static int calculate(String s) { s = s.replaceAll("\\s+", ""); Stack<Integer> stack = new Stack<Integer>(); if(s.length() == 0){ return 0; } s = "(" + s + ")"; int sign = 1; int sum = 0; int num = 0; for(char c : s.toCharArray()){ if(c == '('){ stack.push(sum); stack.push(sign); sum = 0; sign = 1; }else if(c == '-'){ sum += num * sign; num = 0; sign = -1; }else if(c == '+'){ sum += num * sign; num = 0; sign = 1; }else if(c == ')'){ sum += num * sign; sum *= stack.pop(); sum = sum + stack.pop(); num = 0; }else if(Character.isDigit(c)){ num = num * 10 + (int)(c - '0'); } } return sum; } public static void main(String[] args) { System.out.println(calculate("1 - 2 - (3 - 4 + (5-6))")); } }
Java
UTF-8
9,957
1.867188
2
[]
no_license
package com.perficient.test.cat.catinspectweb.basepages; import static com.perficient.test.cat.catinspectweb.util.CustomizedFunctionUtil.click; import static com.perficient.test.cat.catinspectweb.util.FunctionUtil.tryAllConvertStringToDate; import java.util.ArrayList; import java.util.Date; import java.util.List; import org.openqa.selenium.By; import org.openqa.selenium.WebElement; import org.openqa.selenium.support.FindBy; public class ManageFormPage extends BasicPage{ //Select Filter type @FindBy(xpath="//div[@class='col-xs-6 cat_right_border']//select[contains(@class,'cat_status_select')]") public WebElement selectorOfFilter; //Select Family selector @FindBy(xpath="//div[@class='col-xs-6']//select[contains(@class,'cat_status_select')]") public WebElement selectorOfselectfamily; //Option: Filter Type @FindBy(xpath="//div[@class='col-xs-6 cat_right_border']/select/option") public List<WebElement> listOfFilterType; //search icon @FindBy(xpath="//span[@class='glyphicon glyphicon-search']") public WebElement iconOfSearch; //Button: upload button @FindBy(xpath="//i[contains(@class, 'upload')]") public WebElement btnOfUpload; //Input : Serial Number Prefix @FindBy(xpath="//input[@placeholder = 'Serial Number Prefix']") public WebElement inputOfSerialNumberPrefix; //Input: search field @FindBy(xpath="//div[@class = 'cat_search_filter col-xs-3']/input") public WebElement inputOfSearchValue; //List: List of question shown in Form Information when click on category id. @FindBy(xpath="//div[@class = 'queBorder']") public List<WebElement> listOfQuestion; //List: slider color @FindBy(xpath="(//table[@id= 'table_width']//tr[@class = 'formActionHover'])//td[1]/span") public List<WebElement> listOfSliderColor; //List: Serial number @FindBy(xpath="(//table[@id= 'table_width']//tr[@class = 'formActionHover'])//td[2]/span") public List<WebElement> listOfSerialNumberPrefix; //List: Type @FindBy(xpath="(//table[@id= 'table_width']//tr[@class = 'formActionHover'])//td[3]") public List<WebElement> listOfType; //List:Form Name @FindBy(xpath="//td/a[@href='javascript:void(0)']") public List<WebElement> listOfFormName; //List: Created By @FindBy(xpath="(//table[@id= 'table_width']//tr[@class = 'formActionHover'])//td[5]") public List<WebElement> listOfCreator; //List: Last Modified Date @FindBy(xpath="(//table[@id= 'table_width']//tr[@class = 'formActionHover'])//td[6]") public List<WebElement> listOfModifiedDate; //List: Form number @FindBy(xpath="(//table[@id= 'table_width']//tr[@class = 'formActionHover'])//td[7]") public List<WebElement> listOfFormNumber; //List: form Actions in the last column, i.e. the column containing open, download and delete icons. @FindBy(xpath="//table[@id= 'table_width']//td[@class='actions']") public List<WebElement> listOfFormActions; //List: Archive/Active @FindBy(xpath="//td/i[1][contains(@class, 'material-icons')]") public List<WebElement> listOfCheckBox; //Selector: All Forms @FindBy(xpath="//div[@class= 'cat_date_filter cat_right_border col-xs-4']/select") public WebElement selectorOfFormStatus; //Selector: All Types @FindBy(xpath="//div[@class = 'col-xs-4 cat_right_border']/select") public WebElement selectorOfFormType; //Option list: FormStatus @FindBy(xpath="//div[@class ='cat_date_filter cat_right_border col-xs-4']/select/option") public List<WebElement> listOfFormStatusOption; //Option List; Form type @FindBy(xpath="//div[@class = 'col-xs-4 cat_right_border']/select/option") public List<WebElement> listOfFormTypeOption; //Button: OK button in dialog box @FindBy(xpath="//button[@class = 'btn btn-success']") public WebElement btnOfOK; //BUtton: Cancel @FindBy(xpath="//button[@class = 'btn btn-danger']") public WebElement btnOfCancel; //Text: Confirmation of archiving a form @FindBy(xpath="//span[contains(text(),'Are you sure')]") public WebElement textOfconfimationofArchiveOrActivateForm; //Text: warning text: NO Data @FindBy(xpath="//span[@class = 'text-center']") public WebElement textOfNoData; //Text: Message when uploading an incorrect file. @FindBy(xpath="(//h3//span)[2]") public WebElement textOfMessageForuploadOrDeletedraftForm; //List: sorted column @FindBy(xpath="//th[@sort-by]") public List<WebElement> listOfSortedColumn; //List: List Of Draft form Name. @FindBy(xpath="(//table[@id= 'table_width']//tr[contains(@class , 'formActionHover')])//td[1]") public List<WebElement> listOfDraftFormName; //List: List Of Draft form Type. @FindBy(xpath="(//table[@id= 'table_width']//tr[contains(@class , 'formActionHover')])//td[2]") public List<WebElement> listOfDraftFormType; //List: List Of Draft form Family. @FindBy(xpath="(//table[@id= 'table_width']//tr[contains(@class , 'formActionHover')])//td[3]") public List<WebElement> listOfDraftFormFamily; //List: List Of Draft Serial number prefix. @FindBy(xpath="(//table[@id= 'table_width']//tr[contains(@class , 'formActionHover')])//td[4]") public List<WebElement> listOfDraftFormSerialNumberPre; //List: List Of Draft form Type. @FindBy(xpath="(//table[@id= 'table_width']//tr[contains(@class , 'formActionHover')])//td[5]") public List<WebElement> listOfDraftFormCreatedTime; //List: Download icon @FindBy(xpath="//i[@title = 'Download']") public List<WebElement> listOfDownloadIcon; //List: Delete icon @FindBy(xpath="//i[@title = 'Delete']") public List<WebElement> listOfDeleteIcon; /** * Get the index of the first form by status * @author herby.he * @param status(you can enter archived or active value) * @return * @throws Exception */ public int getIndexOfTheFirstFormByStatus(String status) throws Exception{ for(int i =0;i <listOfSliderColor.size();i++){ if(listOfSliderColor.get(i).getAttribute("class").contains(status)){ return i; } } return -1; } /** * Only for Manager Form page, select a option from the drop-down list. * @author herby.he * @param selector * @param optionList * @param selectedIndex * @throws Exception */ public void selectAOptionFromdropdownlist(WebElement selector, List<WebElement> optionList, int selectedIndex) throws Exception { click(selector,"click on selector"); click(optionList.get(selectedIndex),"Select the expected option from the drop-down list"); } /** * verify the number list is ordered correctly. * @author herby.he * @param webElement * @param index (starting from this value) * @param listName * @param xec (true means ascending order, false means descending order) * @throws Exception */ public void verifyNumberOrderCorrectly(List<WebElement> webElement, int index, String listName, final Boolean xec) throws Exception { List<Integer> origalList= new ArrayList<Integer>(); for(int i = index; i<webElement.size();i++) { int value = Integer.parseInt(webElement.get(i).getText().trim()); //Transfer string to integer type. origalList.add(value); } for(int j= 0;j<(origalList.size()-1);j++) { if(xec) { if(origalList.get(j)>origalList.get(j+1)) { customAssertion.assertTrue(false,"The ascending order for "+listName+" is incorrect"); break; } }else { if(origalList.get(j)<origalList.get(j+1)) { customAssertion.assertTrue(false,"The descending order for "+listName+" is incorrect"); break; } } } } /** * Verify the order of date is correct. * @author herby.he * @param webElement * @param index (Starting from this value) * @param listName * @param xec (true means ascending order, false means descending order.) */ public void verifyDateOrdercorrectly(List<WebElement> webElement, int index, String listName, final Boolean xec ) { List<Date> origalList= new ArrayList<Date>(); for(int i = 0; i<webElement.size();i++) { Date date = new Date(); //Filter out empty component. if(webElement.get(i).getText().trim().length()>4) { date = tryAllConvertStringToDate(webElement.get(i).getText().trim()); origalList.add(date); } } for(int j =0;j<origalList.size()-1;j++) { int result = origalList.get(j).compareTo(origalList.get(j+1)); if(xec) { if(result==1) { customAssertion.assertTrue(false,"The order for "+listName+" is incorrect." + j); break; } }else { if(result==-1) { customAssertion.assertTrue(false,"The order for "+listName+" is incorrect." + j); break; } } } } /** * Hover over the cursor on the last column at the specific row, * then click on an action icon as specified, i.e. open, download or delete. * @author matthew.feng * @param rowNum the row number in the last column, starting from 1. * @param iconNum the icon number in the selected row, starting from 1. * @throws Exception */ public void clickOnFormActionIconFromTheLastColumn(int rowNum, int iconNum) throws Exception{ click(listOfFormActions.get(rowNum-1)); WebElement rowItem = listOfFormActions.get(rowNum-1); List<WebElement> iconList = rowItem.findElements(By.tagName("i")); click(iconList.get(iconNum-1), "Click on the "+iconList.get(iconNum-1).getAttribute("title")+" icon."); } }
C++
UTF-8
2,307
3.03125
3
[ "MIT" ]
permissive
#include <string> #include "Direction.hpp" #include "Board.hpp" #include "Direction.hpp" using namespace std; using std::string; namespace ariel { void Board::post(unsigned int row, unsigned int column, Direction direction, std::string message) { unsigned int siz = (message.size()); if (direction == Direction::Horizontal) { unsigned int i = 0; for (unsigned int x = column; x < siz + column; x++) { brd[row][x] = message.at(i); i++; } } if (direction == Direction::Vertical) { unsigned int i = 0; for (unsigned int x = row; x < siz + row; x++) { brd[x][column] = message.at(i); i++; } } } string Board::read(unsigned int row, unsigned int column, Direction direction, unsigned int length) { string result; if (direction == Direction::Horizontal) { for (unsigned int x = column; x < length + column; x++) { if (brd[row][x].empty()) { brd[row][x] += "_"; result+="_"; } else { result += brd[row][x]; } } } else { if (direction == Direction::Vertical) { for (unsigned int x = row; x < length + row; x++) { if (brd[x][column].empty()) { brd[x][column] += "_"; result += "_"; } else { result += brd[x][column]; } } } } return result; } void Board::show() { map<unsigned int, map<unsigned int, string>>::iterator it; map<unsigned int, string>::iterator itr; for (it = brd.begin(); it != brd.end(); it++) { for (itr = it->second.begin(); itr != it->second.end(); itr++) { cout << itr->second; } cout << "\n"; } } }
C++
UTF-8
1,162
3.359375
3
[]
no_license
#include <bits/stdc++.h> using namespace std; int n; bool is_attacked(int x, int y, bool board[n][n]) { // if queen is in any cell in xth row for(int j=0;j<n;j++) { if(board[x][j]) return true; } // if queen is in any cell in yth column for(int i=0;i<n;i++) { if(board[i][y]) return true; } //checking for diagonals for(int i=0;i<n;i++) { for(int j=0; j<n; j++) { if(((i+j == x+y)&& board[i][j]) || ((i-j == x-y)&& board[i][j]) return true; } } return false; } bool NQueens(bool board[n][n],int y) { if(y>=n) return true; for(int i=0; i<n; i++) { if(!is_attacked(i,y,board)) { board[i][y]=true; if(NQueens(board,y+1)) return true; board[i][y]= false; } } return false; } int main() { cin>>n; bool board[n][n]= {false}; if(NQueens(board,0)) { cout<<"NQueens solution is found with "<<n<<" queens"<<endl; } else { cout<<"No possible NQueens solution with "<<n<<" queens"<<endl; } return 0; }
C
UTF-8
333
2.953125
3
[]
no_license
#include <stdio.h> #include <signal.h> #include <unistd.h> //here is the signal handler void catch_int(int sig_num){ //re-set the signal handler again to catch_int, for next time signal(SIGINT, catch_int); printf("Ouch!-I got signal %d\n", sig_num); } int main(){ signal(SIGINT, catch_int); for( ; ; ) pause(); return 0; }
Ruby
UTF-8
288
3.59375
4
[]
no_license
#!/usr/bin/ruby # -*- coding: utf-8 -*- # create a hash books = {} # or Hash.new(0) # :splendid is a symbol books["Gravity's Rainbow"] = :splendid puts books.keys puts books.values books.keys.each { |title| puts title } books.each { |title, symbol| print title, " => ", symbol, "\n"}
C#
UTF-8
1,565
3.5
4
[]
no_license
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace TSP { class RouletteWheelSelector { private Random rnd; private Func<TSPSolution, double> fitness; public RouletteWheelSelector(Random rnd, Func<TSPSolution, double> fitness) { this.rnd = rnd; this.fitness = fitness; } public TSPSolution SelectOne(List<TSPSolution> from) { var slot = GetBestIndex(from); return from[slot]; } public void Transfer(int count, List<TSPSolution> from, List<TSPSolution> to) { for (int i = 0; i < count; ++i) { var slot = GetBestIndex(from); to.Add(from[slot]); from.RemoveAt(slot); } } private int GetBestIndex(List<TSPSolution> from) { // generate the wheel double totalFitness = 0; foreach (var s in from) totalFitness += fitness(s); // shoot at the wheel int slot = 0; double shotPercentage = rnd.NextDouble(); // figure out where the shot landed while (shotPercentage > 0 && slot < from.Count) { var slotFitness = fitness(from[slot++]); var slotPercentage = slotFitness / totalFitness; shotPercentage -= slotPercentage; } // return the element's index return (slot - 1); } } }
Python
UTF-8
4,325
2.84375
3
[]
no_license
#!usr/bin/env python3 #-*- coding:utf-8 -*- """ version: 1.3 author: hunta this script will compare two test result xml file of iTest, find all same case with two different result. if a case run for two times(for exp. fail at first time, rerun after clear up), it will take the second result to compare. no clear-up case result change log: 1.1: the latest result include abort, fail, error(except pass) 1.2: delete abort entries if abort at the both times 1.3: support combine several result summary to one """ import re from bs4 import BeautifulSoup import xlsxwriter def error_flag(self): if error_flag is True: print('there is an error') def create_table(soup): result = [] table = [] case = soup.find_all(text=re.compile('test_cases')) v = soup.select('a') #取出 pass,fail,abort 合并成列表 for i in range(0, len(v)): x = str(v[i]).split('>') result.append(x[1]) # case 和 result 的数目,应相同,一一对应组成 table1 for i in range(0, len(v)): if len(case) != len(v): error_flag(True) else: table.append([case[i],result[i]]) return table #将列表 table 转化成 dict def list_to_dict(table): dict = {} for i in range(0, len(table)): dict[table[i][0]]= table[i][1] return dict #抓取最新一次结果是 fail 和 abort 的 case, def compare_dict(result_1, result_2): differences = {} for key in result_2.keys(): if key in result_1.keys(): if result_2[key] != 'Pass</a': differences[key]=[result_1[key], result_2[key]] for key in list(differences.keys()): if differences[key][0] == differences[key][1] == 'Abort</a': del differences[key] return differences if __name__ == '__main__': #输入xml 路径,可输入多次,会将结果合并后再比较 table_1 = [] while True: names = locals() i = 1 names['1xml%s'% i] = input('请输入上次运行结果的路径: ') names['1soup%s' % i] = BeautifulSoup(open(names['1xml%s'% i]), 'lxml') names['1table%s' % i] = create_table(names['1soup%s' % i]) table_1 += names['1table%s' % i] tag = input('是否还要添加脚本结果? Y/N: ') if tag == 'y' or tag == 'Y': i += 1 else: break table_2 = [] while True: names = locals() i = 1 names['2xml%s'% i] = input('请输入这次运行结果的路径: ') names['2soup%s' % i] = BeautifulSoup(open(names['2xml%s'% i]), 'lxml') names['2table%s' % i] = create_table(names['2soup%s' % i]) table_2 += names['2table%s' % i] tag = input('是否还要添加脚本结果? Y/N: ') if tag == 'y' or tag == 'Y': i += 1 else: break # soup_1 = BeautifulSoup(open(xml1), 'lxml') # soup_2 = BeautifulSoup(open(xml2), 'lxml') # table_1 = create_table(soup_1) # table_2 = create_table(soup_2) #转化 list 到 dict dict_1 = list_to_dict(table_1) dict_2 = list_to_dict(table_2) print('上一次运行的 case 数目为 %s' % len(dict_1)) print('这一次运行的 case 数目为 %s' % len(dict_2)) #比较,生成不同结果的字典 print('there are %s Failed cases in this time' % len(compare_dict(dict_1, dict_2))) dict_content = compare_dict(dict_1, dict_2) for s1, s2 in dict_content.items(): print(s1, s2) #将字典导入 excel 文件 excel_url= input('请输入需要导出的 excel 文件路径(请确保文件存在):') book = xlsxwriter.Workbook(excel_url) sheet1 = book.add_worksheet() num = [k for k in dict_content] lennum = len(num) for a in range(lennum): lena = len(dict_content[num[a]]) lena1 = dict_content[num[a]] try: print(lena1) except Exception as e: print(e) a1 = num[a] sheet1.write(a + 1, 0, a1) b1x = [] for b in range(lena): b1 = (lena1[b])[0] b2 = (lena1[b])[1] b1x.append(b1) sheet1.write(a + 1, b + 1, b1) if a == 0: for y in range(len(b1x)): bx = b1x[y] sheet1.write(0, y + 1, bx) book.close()
Java
UTF-8
1,011
3.515625
4
[]
no_license
package com.Java.Questions; import java.util.Scanner; import com.Java.Questions.Util.NumberUtils; public class Q15 { private static final Scanner sc = new Scanner(System.in); public static void main(String[] args) { System.out.println("enter three inputs : "); String Input1 = sc.next(); String Input2 = sc.next(); String Input3 = sc.next(); boolean isValidInputs = NumberUtils.validateNumbers(Input1,Input2,Input3); if(isValidInputs){ int firstnumber = Integer.parseInt(Input1); int secondnumber = Integer.parseInt(Input2); int thirdnumber = Integer.parseInt(Input3); int largest ; if (firstnumber > secondnumber && firstnumber > thirdnumber ) largest = firstnumber; else if ( secondnumber > firstnumber && secondnumber > thirdnumber ) largest = secondnumber; else largest = thirdnumber; System.out.println("Largest Number is : "+largest); }else{ System.out.println("Invalid Inputs"); } } }
Shell
UTF-8
192
2.546875
3
[]
no_license
#!/bin/sh pass="123anh" echo "Moi ban nhap mat khau: " read mk; while [ $mk != $pass ] do echo "Mat khau ban da nhap khong dung !!!" echo "Moi ban nhap lai mat khau:" read mk done
C#
UTF-8
167
3.21875
3
[]
no_license
DateTime endDate = DateTime.Today; for (DateTime dt = startDate; dt <= endDate; dt = dt.AddMonths(1)) { Console.WriteLine("{0:M/yyyy}", dt); }
Markdown
UTF-8
1,551
2.53125
3
[ "MIT" ]
permissive
Test cases to cover all functionality that's to be achieved by the first demo **Functions in project report** * RobotStability * Robot remains upright with no arm * Robot remains upright with arm at 'minimum extension' * Robot remains upright with arm at 'maximum extension' * Robot remains upright during simulated 'movement' of the train (no arm) * Robot remains upright during simulated 'movement' of the train arm 'minimum extension' * Robot remains upright during simulated 'movement' of the train arm 'maximum extension' * RobotMovement * Robot moves through carriage without collisions with seating area starting 1m away from end * Robot moves through carriage without collisions with seating area starting 5m away from end * Robot doesn't collide with unexpected obstacles in front of it * CarriageEndRecognition * Robot identifies carriage end when immediately in front of it * Robot identifies carriage end from 1m * Robot identifies carriage end from 5m * Robot stop before carriage end * Robot starts facing 90 degrees to end - > identify carriage end from 1m * Robot starts facing 180 degrees to end - > identify carriage end from 1m * Robot starts facing 90 degrees to end - > identify carriage end from 5m * Robot starts facing 180 degrees to end - > identify carriage end from 5m * Robot identifies obstacle which is not carriage end when immediately in front of it * Robot detects obstacle which is not carriage end from 1m * Robot detects obstacle which is not carriage end from 5m
Java
UTF-8
1,189
3.5
4
[]
no_license
package _316去除重复字母; import java.util.*; /** * *单调栈 */ class Solution { public static String removeDuplicateLetters(String s) { boolean visit[] = new boolean[26]; int last[] = new int[26]; char[] chars = s.toCharArray(); for (int i = 0; i < chars.length; i++) { last[chars[i]-'a']=i; } Deque<Character> stack = new ArrayDeque<>(); for (int i = 0; i < chars.length; i++) { if(visit[chars[i]-'a']) { continue; } while (!stack.isEmpty()&&stack.peekLast()>chars[i]&&last[stack.peekLast()-'a']>i) { Character character = stack.removeLast(); visit[character-'a']=false; } stack.addLast(chars[i]); visit[chars[i]-'a']=true; } StringBuilder sb = new StringBuilder(); for (Character character : stack) { sb.append(character); } return sb.toString(); } public static void main(String[] args) { String bcbcaddabc = removeDuplicateLetters("ecbacba"); System.out.println(bcbcaddabc); } }
Python
UTF-8
775
3.03125
3
[]
no_license
# -*- coding=UTF-8 -*- from PIL import Image im = Image.open('in.jpg') #打开图片 width = im.size[0] height = im.size[1] print width, height new_width = width / 8 new_height = height / 8 im = im.convert('L').resize((new_width, new_height), Image.ANTIALIAS); #将原图改为灰度图并重设大小 im.save('res.jpg') #存下处理后的图片 charset = '.,_+!:"<>(){}?/;[]^F\*@#$A' #print len(charset) txt = '' for m in range(0, new_height): for n in range(0, new_width): pixel = im.getpixel((n, m)) txt += charset[pixel / 10] txt += charset[pixel / 10] txt += '\n' print txt
Ruby
UTF-8
1,418
2.609375
3
[ "MIT" ]
permissive
class Location < ActiveRecord::Base has_one :event validates_associated :event #TODO: When going back to spaital db, put code below in appropriate html files in script section. # // Should work for point and multipoint but no other types yet. # <% @event.location.each {|g| %> # <%= raw 'xxxMap.addMarker("'+g.latitude.to_s+' '+g.longitude.to_s+'", 17, true);' %> # <% } %> #TODO: Remarked out code sections below for non-spatial db. # Using float columns for latitude & longitude instead of geometry collection column. # By default, use the GEOS implementation for spatial columns. # self.rgeo_factory_generator = RGeo::Geos.factory_generator # But use a geographic implementation for the spatial column. # set_rgeo_factory_for_column(:geom, RGeo::Geographic.spherical_factory(:srid => 4326)) def num_geometries # self.geom.num_geometries end #TODO: This assumes a single geometry in the collection. Should take param for index or create a list of types? def geom_type # self.geom.geometry_n(0).geometry_type "Point" # Hard-coding for non-spaital database deployment end #TODO: This assumes a single point so needs to be updated to handle anything else! def geom_coords # self.geom.geometry_n(0).y.to_s + " " + self.geom.geometry_n(0).x.to_s "" + self.latitude.to_s + " " + self.longitude.to_s end end
Swift
UTF-8
630
3.09375
3
[]
no_license
// // Bubble.swift // Pop // // Created by Megan Lim on 3/12/15. // Copyright © 2015 Megan Lim. All rights reserved. // import Foundation import UIKit class Bubble { // MARK: Properties var title: String var comment: String? var location: String var noOfPeople: Int // MARK: Initialisation init?(title: String, comment: String?, location: String, noOfPeople: Int) { self.title = title self.comment = comment self.location = location self.noOfPeople = noOfPeople if title.isEmpty || location.isEmpty { return nil } } }
C#
UTF-8
2,524
2.5625
3
[]
no_license
using Microsoft.Azure.Documents; using Microsoft.Azure.Documents.Client; using Microsoft.Azure.Documents.Linq; using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Threading.Tasks; namespace TradeAssist.DocumentStorage { public class DynamicDocumentClient { readonly string databaseId; readonly string collectionId; readonly DocumentClient client; internal DynamicDocumentClient(TADocumentClient client, string databaseId, string collectionId) { this.client = client.Client; this.databaseId = databaseId; this.collectionId = collectionId; } public async Task<dynamic> Get(string id) { try { dynamic item = await client.ReadDocumentAsync<dynamic>(UriFactory.CreateDocumentUri(databaseId, collectionId, id)); return item.Document; } catch (DocumentClientException e) { if (e.StatusCode == System.Net.HttpStatusCode.NotFound) { return default(dynamic); } else { throw; } } } public async Task<IEnumerable<dynamic>> GetMany( Expression<Func<dynamic, bool>> predicate) { IDocumentQuery<dynamic> query = client.CreateDocumentQuery( UriFactory.CreateDocumentCollectionUri(databaseId, collectionId), new FeedOptions { MaxItemCount = -1 }) .Where(predicate) .AsDocumentQuery(); List<dynamic> results = new List<dynamic>(); while (query.HasMoreResults) { results.AddRange(await query.ExecuteNextAsync()); } return results; } public async Task<Document> Create(dynamic item) { return await client.CreateDocumentAsync(UriFactory.CreateDocumentCollectionUri(databaseId, collectionId), item); } public async Task<Document> Update(string id, dynamic item) { return await client.ReplaceDocumentAsync(UriFactory.CreateDocumentUri(databaseId, collectionId, id), item); } public async Task Delete(string id) { await client.DeleteDocumentAsync(UriFactory.CreateDocumentUri(databaseId, collectionId, id)); } } }
C#
UTF-8
2,490
3.6875
4
[]
no_license
using System; namespace RadioControlledCar { class MonsterTruck : Car { public MonsterTruck(int positionX, int positionY, char direction) { direction = Char.ToLower(direction); if(positionX < 0 || positionY < 0) { throw new ArgumentException("The x and y coordinate need to both be positive integers."); } if(!Array.Exists(validDirections, validDirection => validDirection == direction)) { throw new ArgumentException("The the direction has to be one of the following: n,s,w,e."); } _position.x = positionX; _position.y = positionY; _direction = direction; } private char[] validDirections = { 'n', 's', 'w', 'e' }; public int _speed { get; set; } public char _direction { get; set; } // Moves the car forward(f) or backwards(b) in x or y _direction // depending on the current _direction(w,e,n,s) and updates _position. public override void Move(char command) { switch (_direction) { case 'n' : _position.x = command == 'f' ? _position.x + 1 : _position.x - 1; break; case 's': _position.x = command == 'f' ? _position.x - 1 : _position.x + 1; break; case 'w': _position.y = command == 'f' ? _position.y - 1 : _position.y + 1; break; case 'e': _position.y = command == 'f' ? _position.y + 1 : _position.y - 1; break; } } // Rotates the car 90 degrees, either left or right // Updates the _direction depending on current _direction and command public override void Rotate(char command) { switch (_direction) { case 'n': _direction = command == 'l' ? 'w' : 'e'; break; case 's': _direction = command == 'l' ? 'e' : 'w'; break; case 'w': _direction = command == 'l' ? 's' : 'n'; break; case 'e': _direction = command == 'l' ? 'n' : 's'; break; } } } }
Java
UTF-8
988
3.34375
3
[ "Apache-2.0" ]
permissive
package com.kevin.streams; import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; import java.util.stream.IntStream; public class Simple { List<String> myList = Arrays.asList("a1", "a2", "b1", "c2", "c1", "c1"); public void mapToObject() { IntStream.range(1,4).mapToObj(i -> "C"+i ); } public void extractStartsWithCMapToUpperSort() { myList .stream() .filter(s -> s.startsWith("c")) .map(String::toUpperCase) .sorted() .forEach(System.out::println); List<String> yyy = myList .stream() .filter(s -> s.startsWith("c")) .map(String::toUpperCase) .sorted().collect(Collectors.toList()); yyy.forEach(System.out::println); } public static void main(String[] inArgs) { Simple xxx = new Simple(); // xxx.mine(); } }
JavaScript
UTF-8
3,559
2.71875
3
[]
no_license
// TODO reduce the amount of global var gameLevel; var camera, scene, renderer; ////////////////////////////////////////////////////////////////////////////////// // ctor/dtor // ////////////////////////////////////////////////////////////////////////////////// Marble.PageGameLife = function() { this._containerSel = '#canvasContainer'; console.log("enter PageGameLife") // test if webgl is supported //console.assert( Detector.webgl, "WebGL isnt supported" ); this._requestAnimId = null; // initialiaze everything this._init(); this._animate(); } Marble.PageGameLife.prototype.destroy = function() { this._requestAnimId && cancelRequestAnimationFrame( this._requestAnimId ); this._requestAnimId = null; this._winResize && this._winResize.stop(); this._stats && this._stats.domElement.parentNode.removeChild(this._stats.domElement); gameLevel.destroy(); gameLevel = null; renderer = null; jQuery(this._containerSel).empty(); } // mixin MicroEvent MicroEvent.mixin(Marble.PageGameLife); ////////////////////////////////////////////////////////////////////////////////// // misc // ////////////////////////////////////////////////////////////////////////////////// Marble.PageGameLife.prototype.triggerEndOfLevel = function(result, reason) { console.assert( result === 'win' || result === 'dead' ); if( result === 'dead' ){ this.trigger('completed', reason); } } ////////////////////////////////////////////////////////////////////////////////// // misc // ////////////////////////////////////////////////////////////////////////////////// Marble.PageGameLife.prototype._init = function(){ // create the container element var container = jQuery(this._containerSel).get(0); // init the WebGL renderer and append it to the Dom var supportWebGL= Detector.webgl ? true : false; var useWebGL = supportWebGL; useWebGL = jQuery.url().param('render') ? false : useWebGL; if( useWebGL ){ renderer = new THREE.WebGLRenderer({ antialias : true, preserveDrawingBuffer : true }); }else{ renderer = new THREE.CanvasRenderer(); } renderer.setSize( window.innerWidth, window.innerHeight ); container.appendChild( renderer.domElement ); // create the renderer cache renderer._microCache = new MicroCache(); // init the Stats and append it to the Dom - performance vuemeter this._stats = new Stats(); this._stats.domElement.style.position = 'absolute'; this._stats.domElement.style.bottom = '0px'; container.appendChild( this._stats.domElement ); // create the Scene scene = new THREE.Scene(); // for debug //var mesh = new THREE.Mesh( new THREE.SphereGeometry(75,16,8), new THREE.MeshNormalMaterial() ); //scene.add(mesh); // for debug - display xyz axes on the screen scene.add(new THREE.Axes()); gameLevel = new Marble.GameLevel(); this._winResize = THREEx.WindowResize(renderer, gameLevel.camera().object()); } // ## Animate and Display the Scene Marble.PageGameLife.prototype._animate = function() { // render the 3D scene this._render(); // relaunch the 'timer' this._requestAnimId = requestAnimationFrame( this._animate.bind(this) ); // update the stats this._stats.update(); } // ## Render the 3D Scene Marble.PageGameLife.prototype._render = function() { // gameLevel .tick() gameLevel.tick(); // FIXME this should be INSIDE webgl renderer... bug renderer instanceof THREE.WebGLRenderer && renderer.context.depthMask( true ); // actually display the scene in the Dom element renderer.render( scene, gameLevel.camera().object() ); }
Markdown
UTF-8
9,026
3.03125
3
[]
no_license
# Directions for Space scene ## __NOTICE: This section assumes you have fully completed the Setup Instructions.__ ## Getting Started Once you've followed the instructions from the Setup_Instructions document and have installed the software, next you need to download some textures in preparation for the creation of the planets. - [Textures](https://www.solarsystemscope.com/textures/) : Textures for each of the celestial bodies we'll be creating. - [Moon](https://svs.gsfc.nasa.gov/4720) : Texture for the moon. - [Pluto](http://planetpixelemporium.com/pluto.html) - Texture for pluto. # Creating a Star! In order to create the solar system we will need to create our star, the sun! From the blank scene in the project you've created after 'Setup Instructions' we will first clear the scene. ## 1. Right click Directional Light > Delete. ![Delete_Add_New](Screenshots/Delete_Add_New.png "Delete Directional light and Add New 3D Object") ## 2. Click the + icon under 'Hierarchy' > Select 3D Object > Select Sphere ![Create_Sphere](Screenshots/Create_Sphere.png "Create a sphere") Make sure that the sphere is located at (0, 0, 0) and set the scale to an arbitrarily large number, for this example we will pick (4000, 4000, 4000). ![Sun_Size_Scale](Screenshots/Sun_Size_Scale.png "Sun size and scale") You may have to zoom out using the scroll wheel to see the entirety of the sun. It is very large now. ## 3. Creating the material! Now that we have a sphere, we need to create a new material from our sun texture we downloaded. Right click the Assets panel > Select 'Create' > Select 'Material' > Name it "Sun_Material" ![Create_New_Material](Screenshots/Create_New_Material.png "Create a new material for the sun!") Now that we have the material created, we want to add the texture that we downloaded for the sun and set the Material's Albedo to that texture. In order to do that, click and drag the texture from the Assets panel into the small Albedo box within the Sun_Material under the 'Inspector' panel on the right side of Unity. ![Sun_Texture_And_Material](Screenshots/Sun_Texture_And_Material.png "Texture and material") ![Sun_Click_Drag](Screenshots/Sun_Click_Drag.png "Click and drag the sun texture to the Albedo") The Inspector for our material should look like this now: ![Sun_Inpector](Screenshots/Sun_Inspector.png) Finally we can click and drag our material onto our sphere in the Scene itself to apply our material. ![Sun_Applied_Material](Screenshots/Sun_Applied_Material.png "Applied material") But wait! We've applied the material but our sphere is still black! Why is that? Well, remember when we deleted the Directional Light from the scene? That is why our sphere is still dark. We can fix this though by allowing our material we created to emit light by itself. This light won't impact the rest of the scene, but it will allow the texture to be visible. To do this, select our material again and check the box next to 'Emission.' Then drag the sun texture into the little box next to Color. This will give the most accurate color profile for the light emission for our material. ![Sun_Material_Emit](Screenshots/Sun_Material_Emit.png "Sun emitting material texture") ![Sun-Shine](Screenshots/Sun_Shine.png "Sun now emits texture") At last, our sun is now visible! As a last step, you can right click the Sphere object in the 'Hierarchy' to rename it to "Sun" for proper clarification. # Creating a Galaxy! Now that we have a sun, it looks out of place with the standard unity backdrop. What we need is a sweet space texture for our skybox background! This will be similar to creating our sun. First we need to create a new Material and name it "Skybox". After creating a new material, select the Skybox option in the dropdown menu under our 'Inspector' and select '6 Sided' for the type of skybox. ![Skybox_Material](Screenshots/Skybox_Material.png "Skybox Material") Next, click and drag our galaxy/space/stars texture into each of the 6 sides of our material. ![Galaxy_Texture](Screenshots/Galaxy_Texture.png) ![Galaxy6](Screenshots/Galaxy6.png "Galaxy six sided skybox") Last but not least, click and drag our new material into the Scene and drop it on the background! As you can see, our sun is now in a galaxy of other stars! ![Sun_Galaxy](Screenshots/Sun_Galaxy.png "Sun in space!") # Making our sun bright! In order for our sun to emit light like a real star, we have to do something sneaky. Our 3D Sphere can't emit light on its own, so we have to create a point light and place it in the center of our star at (0, 0, 0). This will make it seem like our sun is actually emitting light when it really isn't. ![Point_Light](Screenshots/Point_Light.png "Create a point light") Now that we have our point light, we need to make sure it is in the position (0, 0, 0). After that we need to make sure it will reach the ends of our solar system. To do that we will set the range of our point light to an arbitrarily large number, for now we will pick 30,000. Finally in order to increase the brightness of our star's light, we will increase the intensity to two. ![Point_Light_Options](Screenshots/Point_Light_Options.png "Point light settings") In order to keep organized, we can click and drag our point light directly onto our Sun under our 'Hierarchy.' This will make the point light a child of our Sun object. The final product for our point light should be as follows: ![Point_Light_Final](Screenshots/Point_Light_Final.png "Point Light Final") From now on, whenever you add another object to the scene, it will appear as if our Sun object is illuminating it. # Creating Planets! Creating planets is basically the exact same thing as creating the sun, just with different Positions and Scales relative to the center of the solar system. This part is up to you. Now that you know how to create a 3D sphere object and create a meterial for that object. you can create as many planets and stars as you'd like. Two paths: 1) Create your own solar system! Have one, two or even three suns! Create as many wild and wacky planets as you'd like! 2) Create an accurate representation of our current real life solar system! If you ever get stuck, just go back to the previous sections to help you out! :) # Creating Rings Like On Saturn! [Old but useful video for reference.](https://www.youtube.com/watch?v=HM6TaDdM63k) Now after you've taken some time to create some extra planets and the like, maybe you would like to add Rings to your planet or star, just like Saturn. Unity doesn't have any prefab for a set of rings, so we will have to create them in Blender and then import them into our project in Unity! Steps to create rings: 1) Delete default cube in blender 2) Press NUMPAD-7 to look in Top View 3) Press Shift-A > Mesh > Circle 4) Press Tab to enter edit mode and see vertices 5) Press E to enter Extrude mode 6) Press S to extrude inward and move mosue toward center of circle to create the hole size of your choosing 7) Left click once your selection is done 8) Add a Subdivision Surface modifier so that the texture in unity will adhere ![Blender_Circle](Screenshots/Blender_Circle.png "Circle in blender") ![Blender_Circle_Edit_Mode](Screenshots/Blender_Circle_Edit_Mode.png "Circle in Edit mode") ![Blender_Circle_Extrude_Inward](Screenshots/Blender_Circle_Extrude_Inward.png "Extrude inward") ![Blender_Circle_Sub](Screenshots/Blender_Circle_Sub.png "Subdivision Surface modifier") ![Blender_Sub](Screenshots/Blender_Sub.png "Subdivision Surface Modifier") Now all you need to do is save your rings as a .blend file into the Assets directory of your project. Unity will do the rest in terms of importing the model into the engine. ![Unity_Ring](Screenshots/Blender_Sub.png "Ring") Once it is in unity, you can click and drag the file into the Scene and your rings should show up! You may have to rotate it and scale it to see the side that is visible though! ![Unity_Sun_Rings](Screenshots/Unity_Sun_Rings.png "Rings shown in the editor") # Where to go from here? Once you have created all the models you want for your solar system, the next challenges are rotation and revolution. If you look at our implementation of the project, you will notice a couple of scripts called Rotation and Revolution. These can be added to your objects and cause them to move dynamically when you press play on the editor. It is a good idea to look at our code to see how it works and then modify it for your own interests. All the code we've used is commented and documented so that you can understand what each line of code is doing. Make things as fast or slow as you'd like; as wild and crazy as you'd like. Scripts can be created just like how you create a material only selecting 'C# Script' in the menu as opposed to Material. We leave the rest of the project to you as a challenge to your own ability and creativity! I hope you have a great time messing around with things! It's one of the best ways to learn programming!
Java
UTF-8
604
2.609375
3
[ "Apache-2.0" ]
permissive
package ru.job4j.tracker.singleton; import org.junit.Test; import static org.hamcrest.core.Is.is; import static org.junit.Assert.*; /** * Test. * * @author Plaksin Arseniy (arsp93@mail.ru) * @version 0.1 * @since 26.12.2018 */ public class TrackerStaticFinalFieldTest { /** * Тест на равенство двух объектов. */ @Test public void whenTwoTrackerAreEqual() { TrackerStaticFinalField first = TrackerStaticFinalField.getInstance(); TrackerStaticFinalField second = TrackerStaticFinalField.getInstance(); assertThat(first, is(second)); } }
Markdown
UTF-8
1,192
2.828125
3
[ "MIT" ]
permissive
##### Mandatory Data Elements and Terminology The following data-elements are mandatory (i.e data MUST be present). These are presented below in a simple human-readable explanation. Profile specific guidance and examples are provided as well. The [**Formal Profile Definition**](#profile) below provides the formal summary, definitions, and terminology requirements. **Each Composition must have:** 1. a status 1. a code to represent the document type. 1. a class code to represent this document as Health Check Assessment document. 1. a subject ([Patient]) 1. a date (indicating when the details were recorded) 1. an author (detailing who has recorded the details) 1. title of the document 1. a reference to [Encounter] instance. * Refer to the Base Profile: [NCDHC Base Composition] for base rules that are applied in this profile. [NCDHC Base Composition]: http://build.fhir.org/ig/hl7au/au-fhir-childhealth/StructureDefinition-ncdhc-composition-base.html [Patient]: http://build.fhir.org/ig/hl7au/au-fhir-childhealth/StructureDefinition-ncdhc-patient-baby.html [Encounter]: http://build.fhir.org/ig/hl7au/au-fhir-childhealth/StructureDefinition-ncdhc-encounter.html
Markdown
UTF-8
9,338
3.1875
3
[]
no_license
--- title : 新的旅程 data : 2017-11-1 11:07:42 tags : [目录] --- 一年没有更新博客了,这一年忙忙碌碌的就过去了,简单做个回顾记录一下大三一年。 <!--more--> # 大三上 ## 六级 大三上是非常令我烦躁的一个学期,主要的问题是六级还没过。因为那个时候还不确定政策是什么样的,听说要取消省一的竞赛保研,而我个弱渣最多只拿到了省一和国三,所以当时我就打算放弃走竞赛这条路了。但是因为大二的时候太过浪,两次六级都没过,到那个时候才知道一切事情都要早做准备,不然会很痛苦的。于是我就提前三四个月买了考虫这套教材,正好从网上看到了他的宣传(其实我也忘记从哪里看到的了),下定决心一定要一次考过。那个学期算是我大学以来最糟心的一个学期了,虽然课程压力不是很大,但是准备六级感觉还是很痛苦的,因为一是两次都没过,担忧万一这次还不过那就只剩下最后一次机会了。二是感觉周围人都过了,那个时候就开始谈笑风生了,压力就很大,所以那段时间我很抗拒看到什么保研的字样。 接下来的三个多月,我就起早贪黑的开始背单词,跟视频了。本来英语就是弱项,那个时候感觉就很虚。所以心情一直很不好,还好jh一直陪着我度过了那段时光(这里给个爱心)。临近考试的时候,感觉还是有点信心的,模考也能550(虽然水分很大的那种)。然鹅上场考试的那天我还是紧张了,听力勉强过去,还算感觉良好(最后结果也证明了听力还可以),写作部分我觉得是我写的最好的地方了,到了阅读就完全跪了,阅读理解那次挺难的,反正看完之后就觉得可能要gg。最后十道阅读错了六道还是五道,完全失去了平常的水平。临场我的感觉就是药丸,考完出来之后整个人就昏昏沉沉的,那天还和kh和fq去北区外吃了一顿火锅,喝了点白酒,一阵酒意算是把这摊子事情给揭页了。其实那次真的是过于紧张,下学期的那场六级就完全不是这个样子了,最后考的结果居然还差不多,真的是心态决定一切。 接着就是苦苦的等待的时光了,我还记得前几次查成绩的时候,都是很紧张的,第一次查六级没过是在家里,感觉反正还有那么多次机会,再看看空间里的一群人也没过的哀叹,也不是很有所谓。第二次其实就看到cy在准备六级了,但是那个时候警惕性太低了,还是觉得不需要准备,说不定随便考考就过了。第二次查成绩的时候是在动车上,查到以后其实就有点开始紧张了(这就是罪恶的源头啊!)。然后这一次就是在家里了,心态还算平和,反正都已经成了定论了,我已经做好了再考一次的准备了,没想到居然这次给我过了,虽然不是很高也就488,但那个时候我还是非常高兴的,因为过了保研就有着落了,而且很多学校会有六级线,比如我知道的浙大就卡480,我的分数比他还高一点所以我就挺庆幸的。之后一看分数,果然听力和写作分数都是170-180这样,阅读就跪了,但是还没跪太惨,可能是因为和六级成绩计算的方式有关,大家考的都菜的话,那最终分数可能会好一点。总之查完成绩之后就差敲锣打鼓了,一件心事总归算是放下了,之后就是大三下全力准备保研的事情了,这又是后话了。 大三下其实还考了一次六级,因为我妈的要求下,就是抱着随便考考的心态去的,考完以后感觉也不是很好,不过那次阅读感觉理想,最后成绩出来后居然比第一次考的还高,所以说心态真的是很关键。于是到此为止,我的大学考cet经历就此结束了。从这以后,我对学弟学妹们说的第一件事就是凡事一定要早做准备。 ## 国创 大三上还是国创项目结项的时候,那个时候的确是什么也没有做,在国庆之前根本就是一点都没动,这里要好好地夸一下yh大腿,真是稳得不行,还好当初拉了他做项目,现在想来真是明智。总之,我们组就我们两个人开始了工作,一开始读文献,找到了一篇山东大学做的kinect体感研究,那个时候就觉得硕士论文怎么这么水,感觉是没什么难度的,不过可能也是因为我们做的只是论文的简单的部分,于是我们就开始复现那篇论文了。那个时候对神经网络还不是很了解,于是买了周志华的西瓜书和李航的统计学习方法开始瞎琢磨。之后我们选定了SVM来当分类器,因为名字感觉很有逼格啊,其实后来才知道原来SVM的效果是非常不错的,我们算是瞎猫碰上死耗子,选中了一个很通用的方法,在神经网络出现之前,SVM还是很有看头的,虽然现在已经没人搞了吧。接着,我就找到了台湾林智仁教授做的libsvm库,用C#做界面,开发了一个非常简单版本的人体动作识别软件(虽然名字起得很有看头,但其实内容没有多少)。 利用国庆的时间,我和yh两人就宅在实验室,起早贪黑的搞定了,训练模型,跑数据,做测试等等。后续的界面开发还花了额外的时间,不过最重要的工作都在那个时候完成了。这里还要再吹一波yh大大,界面都是他包了,可以说苦活累活都是他干了。这次项目让我接触了一下基本的分类方法,也对机器学习有个大概的了解,也给我增添了一点项目光彩吧,这个点在接下来的保研中还是很有用处的,挺多老师看重是不是有机器学习基础的。接着过了一段时间,就国创结项答辩了,要提交一些电子版报告和展板,这里麻烦了另一个组员yxh,中间她给我们当过模特采集过数据,然后做了一下展板。国创结项答辩的时候其实已经不那么紧张了,不如中期答辩的时候紧张,因为那个时候我还什么东西都没做出来,只做了理论调查。最后结项答辩的话就只需要展示一下结果就可以了,然后老师们好像还觉得挺有意思的,最后也没展示多久就结束了。过了一段时间,yb老师说让我去签个字,优秀指导教师。没想到还摊上了一个优秀的结项。 到此为止,时隔接近两年的国创项目就告一个段落了,其实没花多少的经费,也是因为当初申请的少,早知道就申请个1w了(就这事还被yb讲过,说申请的有点少了),最后手头就2k,买了一点点书什么的,硬件是没敢上了。然后就是2017年10月中旬的那段时间,yb找到我来做项目交接,把这个烂摊子交给了学长们。 ## ACM竞赛 说起这个真的是痛啊,可能从小就没有竞赛的基因。混了两年多了,除了大一上的暑假我觉得是有真正的认真学习过的,剩下的时间里,感觉都是在吃老本,该会的会,不会的还是不会,很多方法没有完全掌握,高端的名词倒是听了不少,现在想过去,真的是有点浪费了那段时光。不过我还是很庆幸能接触到ACM的,毕竟这个比赛含金量还是很高的,无论对以后的就业还是打计算机基础都是很有用的。大三上的比赛真的是挺多的,那段时间应该是收获了我最多有价值奖牌的时光了吧,大二下的省赛银牌,大三上的ACMICPC区域铜,还有大三下的蓝桥省一和国三。其实都是一些很菜的奖项,懂得人就知道没什么太多价值,不过我想这毕竟也是算是一种肯定吧。努力了两年,能有这些回忆还是很满足的,这个博客开的初衷也是为了记录一下ACM的历程,虽然两年多以来就没记录多少有价值的东西,现在补也懒得动手了,过段时间整理一下,就让这段经历到这里画上一个句号好了。 这里应该是写不下太多的东西了,把竞赛的经历都挤到一篇里也不是很好看,有闲暇时光的时候我会再开一篇记录一下这几年竞赛的一个感受,希望能给学弟学妹们一些警醒,时光不饶人啊。。。 # 大三下 ## 保研 到这里,总算到了正题了。读了三年多的大学,最后的选择无非是工作、读研、出国,大一的时候我就有读研究生的打算,没想到如今不止读了研究生,还要读博士,真是世事难料。这里也有很长的一段故事可以叙述,如今我坐在自动化所的工位上码着字着实不太方便一一讲述,待我有闲暇的时光后,再抽空将这段经历补上。 以上便是我大三一年主要的事情,说来也惭愧,细数一下也没做什么活,除了光读点书,剩下的技能是一点都没进步。如今我已经坐在了中科院自动化所的工位上,一切又是一个新的开始,新的旅程又要起步了。今日做次记录,在这里做一个小小的回忆,希望明年能在毕业季之时,能对大学生活做一个全面的总结,以便几年后能想起来,我的大学到底做了些什么,不留遗憾。
C++
UHC
1,190
2.90625
3
[]
no_license
#include <iostream> #include <thread> #include <mutex> #include <chrono> #include <atomic> using namespace std; using namespace chrono; volatile int sum; mutex sum_lock; volatile bool flag[2] = { false, false }; volatile int victim; void p_lock(const int tid) { int other = 1 - tid; flag[tid] = true; victim = tid; atomic_thread_fence(memory_order_seq_cst); while (flag[other] && victim == tid); } void p_unlock(const int tid) { flag[tid] = false; } void worker(int tid) { for (int i = 0; i < 25'000'000; ++i) { p_lock(tid); sum += 2; p_unlock(tid); } } int main() { auto start = high_resolution_clock::now(); thread t1{ worker, 0 }; thread t2{ worker, 1 }; t1.join(); t2.join(); auto end = high_resolution_clock::now(); auto exec = end - start; cout << "Exec Time : " << duration_cast<milliseconds>(exec).count() << "ms\n"; cout << "sum : " << sum << endl; } /* ̱۽ 118ms ̱۹ؽ 1135ms 󽺷 249ms ߸ ؽ 1519ms ͽ 3385ms (99924458) mfence 2074ms 潺 3193ms */ /* ͽ 3645ms 99630506 4979ms 100000000 潺 3585ms 100000000 */
Java
UTF-8
6,053
2.296875
2
[ "Apache-2.0" ]
permissive
package org.ovirt.engine.ui.uicommon.models.userportal; import java.util.Collections; import org.ovirt.engine.core.compat.*; import org.ovirt.engine.ui.uicompat.*; import org.ovirt.engine.core.common.businessentities.*; import org.ovirt.engine.core.common.vdscommands.*; import org.ovirt.engine.core.common.queries.*; import org.ovirt.engine.core.common.action.*; import org.ovirt.engine.ui.frontend.*; import org.ovirt.engine.ui.uicommon.*; import org.ovirt.engine.ui.uicommon.models.*; import org.ovirt.engine.core.common.*; import org.ovirt.engine.ui.uicommon.models.templates.*; import org.ovirt.engine.core.common.*; import org.ovirt.engine.core.common.businessentities.*; import org.ovirt.engine.core.common.interfaces.*; import org.ovirt.engine.ui.uicommon.*; import org.ovirt.engine.ui.uicommon.models.*; @SuppressWarnings("unused") public class UserPortalTemplateListModel extends TemplateListModel implements IFrontendMultipleQueryAsyncCallback { @Override protected void SyncSearch() { MultilevelAdministrationByAdElementIdParameters parameters = new MultilevelAdministrationByAdElementIdParameters(Frontend.getLoggedInUser().getUserId()); // Get user permissions and send them to PostGetUserPermissions: AsyncQuery _asyncQuery = new AsyncQuery(); _asyncQuery.setModel(this); _asyncQuery.asyncCallback = new INewAsyncCallback() { public void OnSuccess(Object model, Object ReturnValue) { UserPortalTemplateListModel userPortalTemplateListModel = (UserPortalTemplateListModel)model; java.util.ArrayList<permissions> userPermissions = ReturnValue != null ? (java.util.ArrayList<permissions>)((VdcQueryReturnValue)ReturnValue).getReturnValue() : new java.util.ArrayList<permissions>(); userPortalTemplateListModel.PostGetUserPermissions(userPermissions); }}; Frontend.RunQuery(VdcQueryType.GetPermissionsByAdElementId, parameters, _asyncQuery); } @Override public void Search() { EnsureAsyncSearchStopped(); SyncSearch(); } public void PostGetUserPermissions(java.util.ArrayList<permissions> userPermissions) { java.util.ArrayList<VdcQueryType> listQueryType = new java.util.ArrayList<VdcQueryType>(); java.util.ArrayList<VdcQueryParametersBase> listQueryParameters = new java.util.ArrayList<VdcQueryParametersBase>(); for (permissions userPermission : userPermissions) { if (userPermission.getObjectType() == VdcObjectType.System) { // User has a permission on System -> Get all templates in the system: listQueryType.add(VdcQueryType.Search); SearchParameters searchParams = new SearchParameters("Template:", SearchType.VmTemplate); searchParams.setMaxCount(9999); listQueryParameters.add(searchParams); break; } else { // if user has a permission on a Template, add a query-request for that template: if (userPermission.getObjectType() == VdcObjectType.VmTemplate) { listQueryType.add(VdcQueryType.GetVmTemplate); listQueryParameters.add(new GetVmTemplateParameters(userPermission.getObjectId())); } // if user has a permission on a DataCenter, add a query-request for all the templates in that DataCenter: else if (userPermission.getObjectType() == VdcObjectType.StoragePool) { listQueryType.add(VdcQueryType.Search); SearchParameters searchParams = new SearchParameters("Template: datacenter = " + userPermission.getObjectName(), SearchType.VmTemplate); searchParams.setMaxCount(9999); listQueryParameters.add(searchParams); } } } GetUserTemplates(listQueryType, listQueryParameters); } private void GetUserTemplates(java.util.ArrayList<VdcQueryType> listQueryType, java.util.ArrayList<VdcQueryParametersBase> listQueryParameters) { if (listQueryType.isEmpty()) { setItems(new java.util.ArrayList<VmTemplate>()); } else { Frontend.RunMultipleQueries(listQueryType, listQueryParameters, this); } } public void Executed(FrontendMultipleQueryAsyncResult result) { java.util.ArrayList<VmTemplate> items = new java.util.ArrayList<VmTemplate>(); if (result != null) { java.util.List<VdcQueryType> listQueryType = result.getQueryTypes(); java.util.List<VdcQueryReturnValue> listReturnValue = result.getReturnValues(); for (int i = 0; i < listQueryType.size(); i++) { switch (listQueryType.get(i)) { case GetVmTemplate: if (listReturnValue.get(i) != null && listReturnValue.get(i).getSucceeded() && listReturnValue.get(i).getReturnValue() != null) { VmTemplate template = (VmTemplate) listReturnValue.get(i).getReturnValue(); items.add(template); } break; case Search: if (listReturnValue.get(i) != null && listReturnValue.get(i).getSucceeded() && listReturnValue.get(i).getReturnValue() != null) { java.util.ArrayList<VmTemplate> templateList = (java.util.ArrayList<VmTemplate>) listReturnValue.get(i).getReturnValue(); items.addAll(templateList); } break; } } } // Sort templates list java.util.ArrayList<VmTemplate> list = new java.util.ArrayList<VmTemplate>(); VmTemplate blankTemplate = new VmTemplate(); for (VmTemplate template : items) { if (template.getId().equals(Guid.Empty)) { blankTemplate = template; continue; } list.add(template); } Collections.sort(list, new Linq.VmTemplateByNameComparer()); if (items.contains(blankTemplate)) { list.add(0, blankTemplate); } setItems(list); } @Override protected void UpdateActionAvailability() { VmTemplate item = (VmTemplate)getSelectedItem(); if (item != null) { java.util.ArrayList items = new java.util.ArrayList(); items.add(item); getEditCommand().setIsExecutionAllowed(item.getstatus() != VmTemplateStatus.Locked && !item.getId().equals(Guid.Empty)); getRemoveCommand().setIsExecutionAllowed(VdcActionUtils.CanExecute(items, VmTemplate.class, VdcActionType.RemoveVmTemplate)); } else { getEditCommand().setIsExecutionAllowed(false); getRemoveCommand().setIsExecutionAllowed(false); } } }
C
UTF-8
1,558
4.09375
4
[]
no_license
#include<stdio.h> #include<malloc/malloc.h> struct node { int data; struct node *left ,*right; }; struct node *tree = NULL; struct node *insert(struct node *,int ); void preorder(struct node *); int main() { int choice , val; do{ printf("1. INSERT A NODE IN BST 2 .PREORDER 3 .EXIT "); scanf("%d",&choice); switch(choice ) { case 1 : printf("ENTER THE VALUE TO BE INSERTED IN BST"); scanf("%d",&val); tree = insert(tree,val); break; case 2 : preorder(tree); break; } }while(choice != 3); } struct node *insert(struct node *tree, int val) { struct node *newnode; newnode = (struct node *)malloc(sizeof(struct node )); newnode ->data = val; if(tree == NULL) { tree = newnode; newnode ->left = newnode->right =NULL; } else { struct node *nodeptr ,*ptr; nodeptr = tree; ptr =NULL; while(nodeptr != NULL) { ptr = nodeptr; if(val <nodeptr->data ) nodeptr = nodeptr ->left; else nodeptr = nodeptr ->right; } if(val < ptr ->data) ptr ->left = newnode; else ptr ->right = newnode; } return tree; } void preorder( struct node *tree) { while(tree != NULL) { printf("%d\t",tree->data); preorder(tree ->left); preorder(tree ->right); } }