branch_name
stringclasses
149 values
text
stringlengths
23
89.3M
directory_id
stringlengths
40
40
languages
sequencelengths
1
19
num_files
int64
1
11.8k
repo_language
stringclasses
38 values
repo_name
stringlengths
6
114
revision_id
stringlengths
40
40
snapshot_id
stringlengths
40
40
refs/heads/master
<repo_name>rloyola/dotfiles<file_sep>/dotfiles/zshrc #Variables de ambiente export TERM="xterm-256color" export EDITOR=vim # ZSH Vi Mode bindkey -v # ZSH History setopt extended_history setopt inc_append_history setopt share_history setopt hist_ignore_dups setopt hist_ignore_all_dups setopt hist_expire_dups_first setopt hist_save_no_dups setopt hist_ignore_space setopt hist_verify HISTSIZE=100000 HISTFILE=~/.zsh_history SAVEHIST=100000 # Aliases alias ls='ls --group-directories-first --color=auto' alias ll='ls -la' alias l='ls -l' alias grep='grep --color=auto' alias fgrep='fgrep --color=auto' alias egrep='egrep --color=auto' alias dm='docker-machine' #Navigate style completion zstyle ':completion:*' menu select # load zgen source "${HOME}/.zgen/zgen.zsh" # if the init scipt doesn't exist if ! zgen saved; then echo "Creating a zgen save" zgen oh-my-zsh # plugins zgen oh-my-zsh plugins/git zgen oh-my-zsh plugins/sudo zgen oh-my-zsh plugins/command-not-found zgen oh-my-zsh plugins/docker zgen oh-my-zsh plugins/docker-compose zgen oh-my-zsh plugins/docker-machine zgen load zsh-users/zsh-autosuggestions zgen load zsh-users/zsh-completions zgen load zsh-users/zsh-syntax-highlighting zgen load bhilburn/powerlevel9k powerlevel9k zgen load zsh-users/zsh-history-substring-search zgen load unixorn/autoupdate-zgen # completions zgen load zsh-users/zsh-completions src # theme #zgen oh-my-zsh themes/arrow # save all to init script zgen save fi #source /usr/bin/liquidpromp # The following lines were added by compinstall zstyle :compinstall filename '/home/rodrigo/.zshrc' autoload -Uz compinit compinit # End of lines added by compinstall
e41541008c6ad8d956716f507ab4afbb51c7088c
[ "Shell" ]
1
Shell
rloyola/dotfiles
fbaa6f017f588077a894e22288111a4c6c2073d6
ca0cb20caf9d38fb927454838617647543aa6f7a
refs/heads/master
<file_sep>const DRAWING_MODE_MANUAL_A = "DRAWING_MODE_MANUAL_A", DRAWING_MODE_MANUAL_B = "DRAWING_MODE_MANUAL_B", DRAWING_MODE_AUTO_A = "DRAWING_MODE_AUTO_A", DRAWING_MODE_EDIT = "DRAWING_MODE_EDIT"; const CONNECTION_MODE_INNER = "CONNECTION_MODE_INNER", CONNECTION_MODE_OUTER = "CONNECTION_MODE_OUTER"; drawingMode = DRAWING_MODE_MANUAL_A; connectionMode = CONNECTION_MODE_INNER; pinColor = "#ffae23"; // CSS string connectionColor = "#ffae93"; // CSS string // mode selection // - manA, manB ... // // connection mode // - inner, outer // -- count outer pins // // colouring // - color of pins // - color of connections // // density // - percentage? // // pins size // connection width window.onload = function() { let gui = new dat.GUI(); gui.add(this, 'drawingMode', { "Draw pins": DRAWING_MODE_MANUAL_A, "Free drawing": DRAWING_MODE_MANUAL_B, "Edit pins": DRAWING_MODE_EDIT, AutoA: DRAWING_MODE_AUTO_A } ); gui.add(this, 'connectionMode', { Inner: CONNECTION_MODE_INNER, Outer: CONNECTION_MODE_OUTER } ); gui.addColor(this, 'pinColor'); gui.addColor(this, 'connectionColor'); // var f2 = gui.addFolder('Letters'); // f2.open(); // // controller.onChange(function(value) { // // Fires on every change, drag, keypress, etc. // }); // // controller.onFinishChange(function(value) { // // Fires when a controller loses focus. // alert("The new value is " + value); // }); };<file_sep>let connectionMaps = []; function getPolygonAsConnectionMap(polygon, asCycle = true) { let connectionMap = []; let startingPoint = polygon[asCycle ? polygon.length - 1 : 0]; let prevX, prevY; let currX = startingPoint.x; let currY = startingPoint.y; polygon.forEach(function (vertex) { prevX = currX; prevY = currY; currX = vertex.x; currY = vertex.y; connectionMap.push( buildConnection(prevX, prevY, currX, currY) ) }); return connectionMap; } function generateConnectionMap(polygon) { let polygonBlueprint = polygon.slice(0); polygonBlueprint.push(polygonBlueprint[0]); let connectionMap = []; connectionMap = connectionMap.concat( getPolygonAsConnectionMap(polygonBlueprint) ); // TODO This is just a prototype solution - optimize! connectionMap = connectionMap.concat( ( connectionMode === CONNECTION_MODE_INNER ? getNonCollidingInnerConnections(polygonBlueprint) : getNonCollidingOuterConnections(polygonBlueprint) ) ); return connectionMap; } function doesConnectionCollideWithPolygon(connection, polygon) { let prevX, prevY; let currX = polygon[0].x; let currY = polygon[0].y; return polygon.some(vertex => { prevX = currX; prevY = currY; currX = vertex.x; currY = vertex.y; if (prevX >= 0 && prevY >= 0) { return doLinesCollide(connection.x0, connection.y0, connection.x1, connection.y1, prevX, prevY, currX, currY) } return false; }); } function staysConnectionInsidePolygon(connection, polygon) { let deltaX = connection.x1 - connection.x0; let deltaY = connection.y1 - connection.y0; let currX = connection.x0; let currY = connection.y0; for (let i = 1; i < collisionDetectionSteps; i++) { let offset = i / collisionDetectionSteps; let vertexOnConnectionX = currX + deltaX * offset; let vertexOnConnectionY = currY + deltaY * offset; if (!isPointInPolygon( polygon.length, polygon.map(vertex => vertex.x), polygon.map(vertex => vertex.y), vertexOnConnectionX, vertexOnConnectionY )) { return false; } } return true; } function getNonCollidingInnerConnections(polygon) { let connectionMap = []; polygon.forEach(function (basePoint) { polygon.forEach(function (targetPoint) { let baseTargetConnection = buildConnection(basePoint.x, basePoint.y, targetPoint.x, targetPoint.y); if (!doesConnectionCollideWithPolygon(baseTargetConnection, polygon) && staysConnectionInsidePolygon(baseTargetConnection, polygon)) { connectionMap.push( buildConnection(basePoint.x, basePoint.y, targetPoint.x, targetPoint.y) ); } }) }); return connectionMap; } function getNonCollidingOuterConnections(polygon) { let connectionMap = []; // TODO let canvasWidth = 1920; let canvasHeight = 1080; let pins = polygon.slice(0); for (let i = 0; i < canvasWidth || i < canvasHeight; i += outerPinDistance) { if (i < canvasWidth) { pins.push( buildVertex(i, 0) ); pins.push( buildVertex(i, canvasHeight - 1) ); } if (i < canvasHeight) { pins.push( buildVertex(0, i) ); pins.push( buildVertex(canvasWidth - 1, i) ); } } pins.forEach(function (basePoint) { pins.forEach(function (targetPoint) { let baseTargetConnection = buildConnection(basePoint.x, basePoint.y, targetPoint.x, targetPoint.y); if (!doesConnectionCollideWithPolygon(baseTargetConnection, polygon) && !staysConnectionInsidePolygon(baseTargetConnection, polygon)) { connectionMap.push( buildConnection(basePoint.x, basePoint.y, targetPoint.x, targetPoint.y) ); } }) }); return connectionMap; } /* see stackoverflow: http://stackoverflow.com/a/1968345/3160089 */ function doLinesCollide(x1, y1, x2, y2, x3, y3, x4, y4) { let s1_x = x2 - x1; let s1_y = y2 - y1; let s2_x = x4 - x3; let s2_y = y4 - y3; let s, t; s = (-s1_y * (x1 - x3) + s1_x * (y1 - y3)) / (-s2_x * s1_y + s1_x * s2_y); t = ( s2_x * (y1 - y3) - s2_y * (x1 - x3)) / (-s2_x * s1_y + s1_x * s2_y); if (s >= 0 && s <= 1 && t >= 0 && t <= 1) { let i_x = x1 + (t * s1_x); let i_y = y1 + (t * s1_y); // A collision is not allowed if it's not in one of the endpoints if (!(i_x === x3 && i_y === y3) && !(i_x === x4 && i_y === y4)) { return true; } } return false; // No (prohibited) collision detected } /* see stackoverflow: http://stackoverflow.com/a/2922778/3160089 */ function isPointInPolygon(polygonVerticesCount, polygonXCoordinates, polygonYCoordinates, pointX, pointY) { let i = 0, j = 0; let pointIsInPolygon = false; for (i = 0, j = polygonVerticesCount - 1; i < polygonVerticesCount; j = i++) { if (((polygonYCoordinates[i] > pointY) !== (polygonYCoordinates[j] > pointY)) && (pointX < (polygonXCoordinates[j] - polygonXCoordinates[i]) * (pointY - polygonYCoordinates[i]) / (polygonYCoordinates[j] - polygonYCoordinates[i]) + polygonXCoordinates[i])) pointIsInPolygon = !pointIsInPolygon; } return pointIsInPolygon; } function getDeltaOfVertices(vertexA, vertexB) { if (!vertexA || !vertexB) { return null; // Could as well throw an exception } let deltaBetweenVertices = 0; deltaBetweenVertices += Math.abs(vertexA.x - vertexB.x); deltaBetweenVertices += Math.abs(vertexA.y - vertexB.y); return deltaBetweenVertices; } function buildVertex(xCoordinate, yCoordinate) { return {x: xCoordinate, y: yCoordinate}; } function buildConnection(x0, y0, x1, y1) { return {x0: x0, y0: y0, x1: x1, y1: y1} }<file_sep>/* TODO dialog with options types of input / drawing - manual A; click for every point - manual B; free drawing - reduced to points - automatic A; image reduced to gray scale - points at border, connections based on darkness - automatic B; pins every n-th units colored as pixel, connected with every pin up to n-th units away in combined color - automatic C; image reduced to gray scale - pins every n-th units colored as pixel, connected with every pin up to n-th units away in combined color types of connections (manual mode only) - inner - outer -- count of outer pins background trace image upload (manual mode only) color/s of pins (manual mode only) color/s of connections (manual mode only) colouring mode - random, ltr, ttb, lttrb, lbtrt density (manual mode only) [reduce / increase pins] - primitive mode; add/remove n pins between connections - advanced mode; add/remove pins based on average distance improve performance - image data render */ let polygons = []; let stopDelta = 20; let collisionDetectionSteps = 50; let outerPinDistance = 100; drawing_canvas.addEventListener("mousedown", event => getMode().onMouseDown(event), false); drawing_canvas.addEventListener("mouseup", event => getMode().onMouseUp(event), false); drawing_canvas.addEventListener("mousemove", event => getMode().onMouseMove(event), false); drawing_canvas.addEventListener("dblclick", event => getMode().onMouseDoubleClick(event), false); function getMode() { switch (drawingMode) { case DRAWING_MODE_MANUAL_B: return ModeManualB; case DRAWING_MODE_AUTO_A: return ModeAutoA; case DRAWING_MODE_EDIT: return ModeEdit; case DRAWING_MODE_MANUAL_A: default: return ModeManualA; } } <file_sep>import re file_handler = open('dev/index.html', 'r') html_file_content = file_handler.read() file_handler.close() bodySectionStart = html_file_content.find('<body>') bodySectionEnd = html_file_content.find('</body>') bodyContent = html_file_content[bodySectionStart: bodySectionEnd] script_files_regex = '<script.*src.*>.*</script>' bodyContent = re.sub(script_files_regex, "", bodyContent) bodyContent = ''.join([line for line in bodyContent.split('\n') if line.strip() != '']) file_handler = open('build/bundled_script.min.js', 'r') bundled_script = file_handler.read() file_handler.close() bodyContent = bodyContent + "\n <script type='text/javascript'>" + bundled_script + "</script>" html_file_with_script = html_file_content[:bodySectionStart] + bodyContent + html_file_content[bodySectionEnd:] # TODO remove - quick fix for head includes html_file_with_script = html_file_with_script.replace("stylesheet.css", "/dev/stylesheet.css") html_file_with_script = html_file_with_script.replace("../", "") file_handler = open('index.html', 'w') file_handler.write( html_file_with_script ) file_handler.flush() file_handler.close() <file_sep>class ModeManualB extends DrawingMode { static get STATE_VIEWING() { return 0; } static get STATE_DRAWING_ACTIVE() { return 1; } static get STATE_DRAWING_PASSIVE() { return 2; } static get state() { if (!ModeManualB._state) { return ModeManualB.STATE_VIEWING; } return ModeManualB._state; } static set state(state) { ModeManualB._state = state; } static get drawnPolygon() { if (ModeManualB._drawnPolygon) { return ModeManualB._drawnPolygon; } return []; } static set drawnPolygon(drawnPolygon) { ModeManualB._drawnPolygon = drawnPolygon; } static onMouseDown(event) { let cursorX = event.pageX; let cursorY = event.pageY; if (ModeManualB.state === ModeManualB.STATE_VIEWING) { context.beginPath(); context.moveTo(cursorX, cursorY); } if (ModeManualB.state !== ModeManualB.STATE_DRAWING_ACTIVE) { ModeManualB.state = ModeManualB.STATE_DRAWING_ACTIVE; } } static onMouseUp(event) { if (ModeManualB.state === ModeManualB.STATE_DRAWING_ACTIVE) { ModeManualB.state = ModeManualB.STATE_DRAWING_PASSIVE; } } static onMouseMove(event) { let cursorX = event.pageX; let cursorY = event.pageY; // TODO switch (ModeManualB.state) { case ModeManualB.STATE_VIEWING: clearCanvas(); drawConnectionMaps(connectionMaps); break; case ModeManualB.STATE_DRAWING_ACTIVE: let addedVertex = buildVertex(cursorX, cursorY); let stopDrawing = (() => { let isAdvancedDrawing = ModeManualB.drawnPolygon.some( (vertex) => getDeltaOfVertices(ModeManualB.drawnPolygon[0], vertex) > stopDelta ); return isAdvancedDrawing && getDeltaOfVertices(ModeManualB.drawnPolygon[0], addedVertex) < stopDelta; })(); ModeManualB.drawnPolygon = ModeManualB.drawnPolygon.concat([addedVertex]); context.lineTo(cursorX, cursorY); context.stroke(); if (stopDrawing) { ModeManualB.finishDrawing(); } break; case ModeManualB.STATE_DRAWING_PASSIVE: break; } } static onMouseDoubleClick(event) { ModeManualB.finishDrawing() } static finishDrawing() { ModeManualB.state = ModeManualB.STATE_VIEWING; let missingDist = 0; let reducedPolygon = ModeManualB.drawnPolygon.filter((vertex, index, array) => { missingDist += getDeltaOfVertices(vertex, array[index === array.length - 1 ? 0 : index + 1]); if (missingDist >= 50) { missingDist = 0; return true; } return false; }); polygons.push(reducedPolygon); connectionMaps.push( generateConnectionMap(reducedPolygon) ); ModeManualB.drawnPolygon = []; } }<file_sep>class ModeAutoA extends DrawingMode { static onMouseDown(event) { } static onMouseUp(event) { } static onMouseMove(event) { } static onMouseDoubleClick(event) { } } <file_sep>class ModeEdit extends DrawingMode { static get STATE_PASSIVE() { return 0; } static get STATE_ACTIVE() { return 1; } static get state() { if (!ModeEdit._state) { return ModeEdit.STATE_VIEWING; } return ModeEdit._state; } static set state(state) { ModeEdit._state = state; } static get modifiedPolygonIndex() { return ModeEdit._modifiedPolygonIndex; } static set modifiedPolygonIndex(modifiedPolygonIndex) { ModeEdit._modifiedPolygonIndex = modifiedPolygonIndex; } static get modifiedVertexIndex() { return ModeEdit._modifiedVertexIndex; } static set modifiedVertexIndex(modifiedVertexIndex) { ModeEdit._modifiedVertexIndex = modifiedVertexIndex; } static onMouseDown(event) { let cursorX = event.pageX; let cursorY = event.pageY; let minX = cursorX - stopDelta; let maxX = cursorX + stopDelta; let minY = cursorY - stopDelta; let maxY = cursorY + stopDelta; polygons.some((polygon, pIndex) => polygon.some((vertex, vIndex) => { if (minX < vertex.x && vertex.x < maxX && minY < vertex.y && vertex.y < maxY) { ModeEdit.modifiedPolygonIndex = pIndex; ModeEdit.modifiedVertexIndex = vIndex; ModeEdit.state = ModeEdit.STATE_ACTIVE; return true; } })) } static onMouseUp(event) { connectionMaps[ModeEdit.modifiedPolygonIndex] = generateConnectionMap(polygons[ModeEdit.modifiedPolygonIndex]); ModeEdit.state = ModeEdit.STATE_PASSIVE; ModeEdit.modifiedPolygonIndex = null; ModeEdit.modifiedVertexIndex = null; } static onMouseMove(event) { clearCanvas(); let cursorX = event.pageX; let cursorY = event.pageY; if (ModeEdit.state === ModeEdit.STATE_ACTIVE) { polygons[ModeEdit.modifiedPolygonIndex][ModeEdit.modifiedVertexIndex] = buildVertex(cursorX, cursorY); // let the polygon lines including pins get drawn on the canvas without inner / outer connections connectionMaps[ModeEdit.modifiedPolygonIndex] = getPolygonAsConnectionMap(polygons[ModeEdit.modifiedPolygonIndex]); } drawConnectionMaps(connectionMaps); } static onMouseDoubleClick(event) { console.log('DrawingMode.onMouseDoubleClick not implemented!'); } } <file_sep>import re file_handler = open('dev/index.html', 'r') html_file_content = file_handler.read() file_handler.close() bodySectionStart = html_file_content.find('<body>') bodySectionEnd = html_file_content.find('</body>') html_file_content = html_file_content[bodySectionStart: bodySectionEnd] script_files_regex = '<script.*>.*</script>' script_name_regex = '.*src=[\'"](.+\.js)[\'"]' script_tags = re.findall(script_files_regex, html_file_content) js_output = "" for script_tag in script_tags: script_name = re.search(script_name_regex, script_tag).group(1) file_handler = open("dev/" + script_name, 'r') js_output = js_output + file_handler.read() + "\n\r" file_handler.close() file_handler = open("build/bundled_script.js", 'w') file_handler.write(js_output) file_handler.flush() file_handler.close() <file_sep>class ModeManualA extends DrawingMode { static get STATE_VIEWING() { return 0; } static get STATE_DRAWING() { return 1; } static get state() { if (!ModeManualA._state) { return ModeManualA.STATE_VIEWING; } return ModeManualA._state; } static set state(state) { ModeManualA._state = state; } static onMouseDown(event) { let cursorX = event.pageX; let cursorY = event.pageY; if (ModeManualA.state === ModeManualA.STATE_VIEWING) { polygons.push([]); polygons[polygons.length - 1].push( buildVertex(cursorX, cursorY) ); ModeManualA.state = ModeManualA.STATE_DRAWING; } else { let modifiedPolygon = polygons[polygons.length - 1]; let cursorVertex = buildVertex(cursorX, cursorY); let deltaToFirstVertex = getDeltaOfVertices(cursorVertex, modifiedPolygon[0]); let deltaToLastVertex = getDeltaOfVertices(cursorVertex, modifiedPolygon[modifiedPolygon.length - 1]); if ((deltaToFirstVertex && deltaToFirstVertex < stopDelta) || (deltaToFirstVertex && deltaToLastVertex < stopDelta)) { // stop drawing ModeManualA.state = ModeManualA.STATE_VIEWING; console.log("done"); connectionMaps.push( generateConnectionMap(modifiedPolygon) ); console.log(modifiedPolygon) console.log(polygons) } else { console.log("add",cursorX, cursorY); modifiedPolygon.push( buildVertex(cursorX, cursorY) ); } } } static onMouseUp(event) { } static onMouseMove(event) { clearCanvas(); let cursorX = event.pageX; let cursorY = event.pageY; if (ModeManualA.state === ModeManualA.STATE_DRAWING) { // draw non-completed polygon let emergingPolygon = polygons[polygons.length - 1].slice(0); // draw it as if the current position was included emergingPolygon.push( buildVertex(cursorX, cursorY) ); drawConnectionMap( getPolygonAsConnectionMap(emergingPolygon, false) ); } // draw completed polygons drawConnectionMaps(connectionMaps); // draw pin at current position drawPin(cursorX, cursorY); } static onMouseDoubleClick(event) { console.log('DrawingMode.onMouseDoubleClick not implemented!'); } }<file_sep>class DrawingMode { static onMouseDown(event) { console.log('DrawingMode.onMouseDown not implemented!'); } static onMouseUp(event) { console.log('DrawingMode.onMouseUp not implemented!'); } static onMouseMove(event) { console.log('DrawingMode.onMouseMove not implemented!'); } static onMouseDoubleClick(event) { console.log('DrawingMode.onMouseDoubleClick not implemented!'); } }<file_sep># pin-and-thread-art Simply visit endzeitbegins.github.io/pin-and-thread-art/<file_sep>const DRAWING_MODE_MANUAL_A = "DRAWING_MODE_MANUAL_A", DRAWING_MODE_MANUAL_B = "DRAWING_MODE_MANUAL_B", DRAWING_MODE_AUTO_A = "DRAWING_MODE_AUTO_A", DRAWING_MODE_EDIT = "DRAWING_MODE_EDIT"; const CONNECTION_MODE_INNER = "CONNECTION_MODE_INNER", CONNECTION_MODE_OUTER = "CONNECTION_MODE_OUTER"; drawingMode = DRAWING_MODE_MANUAL_A; connectionMode = CONNECTION_MODE_INNER; pinColor = "#ffae23"; // CSS string connectionColor = "#ffae93"; // CSS string // mode selection // - manA, manB ... // // connection mode // - inner, outer // -- count outer pins // // colouring // - color of pins // - color of connections // // density // - percentage? // // pins size // connection width window.onload = function() { let gui = new dat.GUI(); gui.add(this, 'drawingMode', { "Draw pins": DRAWING_MODE_MANUAL_A, "Free drawing": DRAWING_MODE_MANUAL_B, "Edit pins": DRAWING_MODE_EDIT, AutoA: DRAWING_MODE_AUTO_A } ); gui.add(this, 'connectionMode', { Inner: CONNECTION_MODE_INNER, Outer: CONNECTION_MODE_OUTER } ); gui.addColor(this, 'pinColor'); gui.addColor(this, 'connectionColor'); // var f2 = gui.addFolder('Letters'); // f2.open(); // // controller.onChange(function(value) { // // Fires on every change, drag, keypress, etc. // }); // // controller.onFinishChange(function(value) { // // Fires when a controller loses focus. // alert("The new value is " + value); // }); }; let connectionMaps = []; function getPolygonAsConnectionMap(polygon, asCycle = true) { let connectionMap = []; let startingPoint = polygon[asCycle ? polygon.length - 1 : 0]; let prevX, prevY; let currX = startingPoint.x; let currY = startingPoint.y; polygon.forEach(function (vertex) { prevX = currX; prevY = currY; currX = vertex.x; currY = vertex.y; connectionMap.push( buildConnection(prevX, prevY, currX, currY) ) }); return connectionMap; } function generateConnectionMap(polygon) { let polygonBlueprint = polygon.slice(0); polygonBlueprint.push(polygonBlueprint[0]); let connectionMap = []; connectionMap = connectionMap.concat( getPolygonAsConnectionMap(polygonBlueprint) ); // TODO This is just a prototype solution - optimize! connectionMap = connectionMap.concat( ( connectionMode === CONNECTION_MODE_INNER ? getNonCollidingInnerConnections(polygonBlueprint) : getNonCollidingOuterConnections(polygonBlueprint) ) ); return connectionMap; } function doesConnectionCollideWithPolygon(connection, polygon) { let prevX, prevY; let currX = polygon[0].x; let currY = polygon[0].y; return polygon.some(vertex => { prevX = currX; prevY = currY; currX = vertex.x; currY = vertex.y; if (prevX >= 0 && prevY >= 0) { return doLinesCollide(connection.x0, connection.y0, connection.x1, connection.y1, prevX, prevY, currX, currY) } return false; }); } function staysConnectionInsidePolygon(connection, polygon) { let deltaX = connection.x1 - connection.x0; let deltaY = connection.y1 - connection.y0; let currX = connection.x0; let currY = connection.y0; for (let i = 1; i < collisionDetectionSteps; i++) { let offset = i / collisionDetectionSteps; let vertexOnConnectionX = currX + deltaX * offset; let vertexOnConnectionY = currY + deltaY * offset; if (!isPointInPolygon( polygon.length, polygon.map(vertex => vertex.x), polygon.map(vertex => vertex.y), vertexOnConnectionX, vertexOnConnectionY )) { return false; } } return true; } function getNonCollidingInnerConnections(polygon) { let connectionMap = []; polygon.forEach(function (basePoint) { polygon.forEach(function (targetPoint) { let baseTargetConnection = buildConnection(basePoint.x, basePoint.y, targetPoint.x, targetPoint.y); if (!doesConnectionCollideWithPolygon(baseTargetConnection, polygon) && staysConnectionInsidePolygon(baseTargetConnection, polygon)) { connectionMap.push( buildConnection(basePoint.x, basePoint.y, targetPoint.x, targetPoint.y) ); } }) }); return connectionMap; } function getNonCollidingOuterConnections(polygon) { let connectionMap = []; // TODO let canvasWidth = 1920; let canvasHeight = 1080; let pins = polygon.slice(0); for (let i = 0; i < canvasWidth || i < canvasHeight; i += outerPinDistance) { if (i < canvasWidth) { pins.push( buildVertex(i, 0) ); pins.push( buildVertex(i, canvasHeight - 1) ); } if (i < canvasHeight) { pins.push( buildVertex(0, i) ); pins.push( buildVertex(canvasWidth - 1, i) ); } } pins.forEach(function (basePoint) { pins.forEach(function (targetPoint) { let baseTargetConnection = buildConnection(basePoint.x, basePoint.y, targetPoint.x, targetPoint.y); if (!doesConnectionCollideWithPolygon(baseTargetConnection, polygon) && !staysConnectionInsidePolygon(baseTargetConnection, polygon)) { connectionMap.push( buildConnection(basePoint.x, basePoint.y, targetPoint.x, targetPoint.y) ); } }) }); return connectionMap; } /* see stackoverflow: http://stackoverflow.com/a/1968345/3160089 */ function doLinesCollide(x1, y1, x2, y2, x3, y3, x4, y4) { let s1_x = x2 - x1; let s1_y = y2 - y1; let s2_x = x4 - x3; let s2_y = y4 - y3; let s, t; s = (-s1_y * (x1 - x3) + s1_x * (y1 - y3)) / (-s2_x * s1_y + s1_x * s2_y); t = ( s2_x * (y1 - y3) - s2_y * (x1 - x3)) / (-s2_x * s1_y + s1_x * s2_y); if (s >= 0 && s <= 1 && t >= 0 && t <= 1) { let i_x = x1 + (t * s1_x); let i_y = y1 + (t * s1_y); // A collision is not allowed if it's not in one of the endpoints if (!(i_x === x3 && i_y === y3) && !(i_x === x4 && i_y === y4)) { return true; } } return false; // No (prohibited) collision detected } /* see stackoverflow: http://stackoverflow.com/a/2922778/3160089 */ function isPointInPolygon(polygonVerticesCount, polygonXCoordinates, polygonYCoordinates, pointX, pointY) { let i = 0, j = 0; let pointIsInPolygon = false; for (i = 0, j = polygonVerticesCount - 1; i < polygonVerticesCount; j = i++) { if (((polygonYCoordinates[i] > pointY) !== (polygonYCoordinates[j] > pointY)) && (pointX < (polygonXCoordinates[j] - polygonXCoordinates[i]) * (pointY - polygonYCoordinates[i]) / (polygonYCoordinates[j] - polygonYCoordinates[i]) + polygonXCoordinates[i])) pointIsInPolygon = !pointIsInPolygon; } return pointIsInPolygon; } function getDeltaOfVertices(vertexA, vertexB) { if (!vertexA || !vertexB) { return null; // Could as well throw an exception } let deltaBetweenVertices = 0; deltaBetweenVertices += Math.abs(vertexA.x - vertexB.x); deltaBetweenVertices += Math.abs(vertexA.y - vertexB.y); return deltaBetweenVertices; } function buildVertex(xCoordinate, yCoordinate) { return {x: xCoordinate, y: yCoordinate}; } function buildConnection(x0, y0, x1, y1) { return {x0: x0, y0: y0, x1: x1, y1: y1} } let drawing_canvas = document.getElementById("drawing-canvas"); let context = drawing_canvas.getContext("2d"); function drawConnectionMaps(connectionMaps) { connectionMaps.forEach( connectionMap => drawConnectionMap(connectionMap) ); } function drawConnectionMap(connectionMap) { connectionMap.forEach(connection => { drawConnection(connection.x0, connection.y0, connection.x1, connection.y1); drawPin(connection.x1, connection.y1); }); } function drawConnection(startX, startY, endX, endY) { context.fillStyle = connectionColor; context.strokeStyle = connectionColor; context.beginPath(); context.moveTo(startX, startY); context.lineTo(endX, endY); context.stroke(); } function drawPin(posX, posY) { context.fillStyle = pinColor; context.strokeStyle = pinColor; context.beginPath(); context.arc(posX, posY, 4, 0, 2 * Math.PI); context.fill(); context.stroke(); } function clearCanvas() { context.clearRect(0, 0, drawing_canvas.width, drawing_canvas.height); } class DrawingMode { static onMouseDown(event) { console.log('DrawingMode.onMouseDown not implemented!'); } static onMouseUp(event) { console.log('DrawingMode.onMouseUp not implemented!'); } static onMouseMove(event) { console.log('DrawingMode.onMouseMove not implemented!'); } static onMouseDoubleClick(event) { console.log('DrawingMode.onMouseDoubleClick not implemented!'); } } class ModeManualA extends DrawingMode { static get STATE_VIEWING() { return 0; } static get STATE_DRAWING() { return 1; } static get state() { if (!ModeManualA._state) { return ModeManualA.STATE_VIEWING; } return ModeManualA._state; } static set state(state) { ModeManualA._state = state; } static onMouseDown(event) { let cursorX = event.pageX; let cursorY = event.pageY; if (ModeManualA.state === ModeManualA.STATE_VIEWING) { polygons.push([]); polygons[polygons.length - 1].push( buildVertex(cursorX, cursorY) ); ModeManualA.state = ModeManualA.STATE_DRAWING; } else { let modifiedPolygon = polygons[polygons.length - 1]; let cursorVertex = buildVertex(cursorX, cursorY); let deltaToFirstVertex = getDeltaOfVertices(cursorVertex, modifiedPolygon[0]); let deltaToLastVertex = getDeltaOfVertices(cursorVertex, modifiedPolygon[modifiedPolygon.length - 1]); if ((deltaToFirstVertex && deltaToFirstVertex < stopDelta) || (deltaToFirstVertex && deltaToLastVertex < stopDelta)) { // stop drawing ModeManualA.state = ModeManualA.STATE_VIEWING; console.log("done"); connectionMaps.push( generateConnectionMap(modifiedPolygon) ); console.log(modifiedPolygon) console.log(polygons) } else { console.log("add",cursorX, cursorY); modifiedPolygon.push( buildVertex(cursorX, cursorY) ); } } } static onMouseUp(event) { } static onMouseMove(event) { clearCanvas(); let cursorX = event.pageX; let cursorY = event.pageY; if (ModeManualA.state === ModeManualA.STATE_DRAWING) { // draw non-completed polygon let emergingPolygon = polygons[polygons.length - 1].slice(0); // draw it as if the current position was included emergingPolygon.push( buildVertex(cursorX, cursorY) ); drawConnectionMap( getPolygonAsConnectionMap(emergingPolygon, false) ); } // draw completed polygons drawConnectionMaps(connectionMaps); // draw pin at current position drawPin(cursorX, cursorY); } static onMouseDoubleClick(event) { console.log('DrawingMode.onMouseDoubleClick not implemented!'); } } class ModeManualB extends DrawingMode { static get STATE_VIEWING() { return 0; } static get STATE_DRAWING_ACTIVE() { return 1; } static get STATE_DRAWING_PASSIVE() { return 2; } static get state() { if (!ModeManualB._state) { return ModeManualB.STATE_VIEWING; } return ModeManualB._state; } static set state(state) { ModeManualB._state = state; } static get drawnPolygon() { if (ModeManualB._drawnPolygon) { return ModeManualB._drawnPolygon; } return []; } static set drawnPolygon(drawnPolygon) { ModeManualB._drawnPolygon = drawnPolygon; } static onMouseDown(event) { let cursorX = event.pageX; let cursorY = event.pageY; if (ModeManualB.state === ModeManualB.STATE_VIEWING) { context.beginPath(); context.moveTo(cursorX, cursorY); } if (ModeManualB.state !== ModeManualB.STATE_DRAWING_ACTIVE) { ModeManualB.state = ModeManualB.STATE_DRAWING_ACTIVE; } } static onMouseUp(event) { if (ModeManualB.state === ModeManualB.STATE_DRAWING_ACTIVE) { ModeManualB.state = ModeManualB.STATE_DRAWING_PASSIVE; } } static onMouseMove(event) { let cursorX = event.pageX; let cursorY = event.pageY; // TODO switch (ModeManualB.state) { case ModeManualB.STATE_VIEWING: clearCanvas(); drawConnectionMaps(connectionMaps); break; case ModeManualB.STATE_DRAWING_ACTIVE: let addedVertex = buildVertex(cursorX, cursorY); let stopDrawing = (() => { let isAdvancedDrawing = ModeManualB.drawnPolygon.some( (vertex) => getDeltaOfVertices(ModeManualB.drawnPolygon[0], vertex) > stopDelta ); return isAdvancedDrawing && getDeltaOfVertices(ModeManualB.drawnPolygon[0], addedVertex) < stopDelta; })(); ModeManualB.drawnPolygon = ModeManualB.drawnPolygon.concat([addedVertex]); context.lineTo(cursorX, cursorY); context.stroke(); if (stopDrawing) { ModeManualB.finishDrawing(); } break; case ModeManualB.STATE_DRAWING_PASSIVE: break; } } static onMouseDoubleClick(event) { ModeManualB.finishDrawing() } static finishDrawing() { ModeManualB.state = ModeManualB.STATE_VIEWING; let missingDist = 0; let reducedPolygon = ModeManualB.drawnPolygon.filter((vertex, index, array) => { missingDist += getDeltaOfVertices(vertex, array[index === array.length - 1 ? 0 : index + 1]); if (missingDist >= 50) { missingDist = 0; return true; } return false; }); polygons.push(reducedPolygon); connectionMaps.push( generateConnectionMap(reducedPolygon) ); ModeManualB.drawnPolygon = []; } } class ModeAutoA extends DrawingMode { static onMouseDown(event) { } static onMouseUp(event) { } static onMouseMove(event) { } static onMouseDoubleClick(event) { } } class ModeEdit extends DrawingMode { static get STATE_PASSIVE() { return 0; } static get STATE_ACTIVE() { return 1; } static get state() { if (!ModeEdit._state) { return ModeEdit.STATE_VIEWING; } return ModeEdit._state; } static set state(state) { ModeEdit._state = state; } static get modifiedPolygonIndex() { return ModeEdit._modifiedPolygonIndex; } static set modifiedPolygonIndex(modifiedPolygonIndex) { ModeEdit._modifiedPolygonIndex = modifiedPolygonIndex; } static get modifiedVertexIndex() { return ModeEdit._modifiedVertexIndex; } static set modifiedVertexIndex(modifiedVertexIndex) { ModeEdit._modifiedVertexIndex = modifiedVertexIndex; } static onMouseDown(event) { let cursorX = event.pageX; let cursorY = event.pageY; let minX = cursorX - stopDelta; let maxX = cursorX + stopDelta; let minY = cursorY - stopDelta; let maxY = cursorY + stopDelta; polygons.some((polygon, pIndex) => polygon.some((vertex, vIndex) => { if (minX < vertex.x && vertex.x < maxX && minY < vertex.y && vertex.y < maxY) { ModeEdit.modifiedPolygonIndex = pIndex; ModeEdit.modifiedVertexIndex = vIndex; ModeEdit.state = ModeEdit.STATE_ACTIVE; return true; } })) } static onMouseUp(event) { connectionMaps[ModeEdit.modifiedPolygonIndex] = generateConnectionMap(polygons[ModeEdit.modifiedPolygonIndex]); ModeEdit.state = ModeEdit.STATE_PASSIVE; ModeEdit.modifiedPolygonIndex = null; ModeEdit.modifiedVertexIndex = null; } static onMouseMove(event) { clearCanvas(); let cursorX = event.pageX; let cursorY = event.pageY; if (ModeEdit.state === ModeEdit.STATE_ACTIVE) { polygons[ModeEdit.modifiedPolygonIndex][ModeEdit.modifiedVertexIndex] = buildVertex(cursorX, cursorY); // let the polygon lines including pins get drawn on the canvas without inner / outer connections connectionMaps[ModeEdit.modifiedPolygonIndex] = getPolygonAsConnectionMap(polygons[ModeEdit.modifiedPolygonIndex]); } drawConnectionMaps(connectionMaps); } static onMouseDoubleClick(event) { console.log('DrawingMode.onMouseDoubleClick not implemented!'); } } /* TODO dialog with options types of input / drawing - manual A; click for every point - manual B; free drawing - reduced to points - automatic A; image reduced to gray scale - points at border, connections based on darkness - automatic B; pins every n-th units colored as pixel, connected with every pin up to n-th units away in combined color - automatic C; image reduced to gray scale - pins every n-th units colored as pixel, connected with every pin up to n-th units away in combined color types of connections (manual mode only) - inner - outer -- count of outer pins background trace image upload (manual mode only) color/s of pins (manual mode only) color/s of connections (manual mode only) colouring mode - random, ltr, ttb, lttrb, lbtrt density (manual mode only) [reduce / increase pins] - primitive mode; add/remove n pins between connections - advanced mode; add/remove pins based on average distance improve performance - image data render */ let polygons = []; let stopDelta = 20; let collisionDetectionSteps = 50; let outerPinDistance = 100; drawing_canvas.addEventListener("mousedown", event => getMode().onMouseDown(event), false); drawing_canvas.addEventListener("mouseup", event => getMode().onMouseUp(event), false); drawing_canvas.addEventListener("mousemove", event => getMode().onMouseMove(event), false); drawing_canvas.addEventListener("dblclick", event => getMode().onMouseDoubleClick(event), false); function getMode() { switch (drawingMode) { case DRAWING_MODE_MANUAL_B: return ModeManualB; case DRAWING_MODE_AUTO_A: return ModeAutoA; case DRAWING_MODE_EDIT: return ModeEdit; case DRAWING_MODE_MANUAL_A: default: return ModeManualA; } } <file_sep>let drawing_canvas = document.getElementById("drawing-canvas"); let context = drawing_canvas.getContext("2d"); function drawConnectionMaps(connectionMaps) { connectionMaps.forEach( connectionMap => drawConnectionMap(connectionMap) ); } function drawConnectionMap(connectionMap) { connectionMap.forEach(connection => { drawConnection(connection.x0, connection.y0, connection.x1, connection.y1); drawPin(connection.x1, connection.y1); }); } function drawConnection(startX, startY, endX, endY) { context.fillStyle = connectionColor; context.strokeStyle = connectionColor; context.beginPath(); context.moveTo(startX, startY); context.lineTo(endX, endY); context.stroke(); } function drawPin(posX, posY) { context.fillStyle = pinColor; context.strokeStyle = pinColor; context.beginPath(); context.arc(posX, posY, 4, 0, 2 * Math.PI); context.fill(); context.stroke(); } function clearCanvas() { context.clearRect(0, 0, drawing_canvas.width, drawing_canvas.height); }
298b8825487e261b771045fcdb32f76159f5488d
[ "JavaScript", "Python", "Markdown" ]
13
JavaScript
EndzeitBegins/pin-and-thread-art
fa73f407f440ba98fcb019441d3ec5a8ea9a2604
113bc5faa9434219f4ea66d5f8d67c9886a295bb
refs/heads/master
<repo_name>BioMediaLab/Goodbye-PHP<file_sep>/schema/schema.js const graphql = require("graphql"); const _ = require("lodash"); const { GraphQLObjectType, GraphQLString, GraphQLSchema, GraphQLID, GraphQLInt, GraphQLList } = graphql; //dummy data var books = [ { name: "The Book of Matthew", genre: "History", id: "1", authorId: "1" }, { name: "Bio Media Lab User Manual", genre: "Manual", id: "2", authorId: "2" }, { name: "The Twisted Needle", genre: "Sci-Fi", id: "3", authorId: "3" }, { name: "The Blighted Pickle", genre: "Fantasy", id: "4", authorId: "4" }, { name: "The Hammer and The Rose", genre: "Romance", id: "5", authorId: "4" }, { name: "Secret of the Vanishing Noodles", genre: "Crime", id: "6", authorId: "2" }, { name: "2105: Retribution", genre: "History", id: "7", authorId: "4" }, { name: "Dressed for Murder", genre: "Crime", id: "8", authorId: "3" } ]; var authors = [ { name: "Mattis", age: 32, id: "1" }, { name: "Ronald", age: 15, id: "2" }, { name: "Nikki", age: 45, id: "3" }, { name: "Sandy", age: 304, id: "4" } ]; const BookType = new GraphQLObjectType({ name: "Book", fields: () => ({ id: { type: GraphQLID }, name: { type: GraphQLString }, genre: { type: GraphQLString }, author: { type: AuthorType, resolve(parent, args) { return _.find(authors, { id: parent.authorId }); } } }) }); const AuthorType = new GraphQLObjectType({ name: "Author", fields: () => ({ id: { type: GraphQLID }, name: { type: GraphQLString }, age: { type: GraphQLInt }, books: { type: new GraphQLList(BookType), resolve(parent, args) { return _.filter(books, { authorId: parent.id }); } } }) }); const RootQuery = new GraphQLObjectType({ name: "RootQueryType", fields: { book: { type: BookType, args: { id: { type: GraphQLID } }, resolve(parent, args) { //code to get data from db return _.find(books, { id: args.id }); } }, author: { type: AuthorType, args: { id: { type: GraphQLID } }, resolve(parent, args) { return _.find(authors, { id: args.id }); } }, books: { type: new GraphQLList(BookType), resolve(parent, args) { return books; } }, authors: { type: new GraphQLList(AuthorType), resolve(parent, args) { return authors; } } } }); module.exports = new GraphQLSchema({ query: RootQuery }); <file_sep>/web/pages/index.js //localhost:3000 to visit this page //need to figure out what all of the .next/ files are import ApolloClient from 'apollo-boost'; import gql from 'graphql-tag'; import { Query } from 'react-apollo'; import fetch from 'node-fetch'; import { createHttpLink } from 'apollo-link-http'; const link = createHttpLink({ uri: 'https://us1.prisma.sh/matthew-loewen-ae6a9f/super-cool-bud-light-api/dev', fetch: fetch }); // const client = new ApolloClient({ // uri: "https://us1.prisma.sh/matthew-loewen-ae6a9f/super-cool-bud-light-api/dev" // }); const GET_USER = gql` { User { name id } } `; const user = () => { // code to get the users in the form of a react compoment }; const Index = () => ( <div> <h1>Welcome to Bio Media Lab</h1> </div> ); export default Index; <file_sep>/web/components/Nav.js import React, { Component } from "react"; import styled from "styled-components"; import Link from "next/link"; import CurrentUser from "./CurrentUser"; import Logout from "./Logout"; const MySpan = styled.span` margin-right: 15px; `; class Nav extends Component { render() { return ( <CurrentUser> {({ data: { me } }) => ( <div className="nav"> <MySpan> <Link href="/index"> <a>Home</a> </Link> </MySpan> {me && ( <> <MySpan> <Link href="/users"> <a>View Users</a> </Link> </MySpan> <Logout /> </> )} {!me && ( <> <MySpan> <Link href="/signup"> <a>Sign up</a> </Link> </MySpan> <MySpan> <Link href="/login"> <a>Log in</a> </Link> </MySpan> </> )} </div> )} </CurrentUser> ); } } export default Nav; <file_sep>/README.md # Goodbye-PHP Matt and Enoch trying to build a signup and login page with GraphQL using JTW tokens, apollo, next.js, react.js, prisma, and node.js # Setup After cloning the repository, run ```sh npm run dev ``` in both `/Goodbye-PHP/backend` and `/Goodbye-PHP/frontend` Then the app will be up on `localhost:3000` <file_sep>/web/components/Users.js import React, { Component } from 'react'; import { Query } from 'react-apollo'; import gql from 'graphql-tag'; import User from './User'; const ALL_USERS_QUERY = gql` query ALL_USERS_QUERY { users { id name email } } `; class Users extends Component { render() { return ( <div> <p>Users</p> <Query query={ALL_USERS_QUERY}> {({ data, error, loading }) => { if (loading) return <p>Loading...</p>; if (error) return <p>Error: {error.message}</p>; return <div>{data.users.map((user) => <User user={user} key={user.id} />)}</div>; }} </Query> </div> ); } } export default Users; export { ALL_USERS_QUERY }; <file_sep>/web/lib/initApollo.js // import { // HttpLink // } from "apollo-boost"; // const httpLink = new HttpLink({ // uri: "http://localhost:4000/", // Server URL (must be absolute) // });<file_sep>/web/components/User.js import React, { Component } from 'react'; import PropTypes from 'prop-types'; import styled from 'styled-components'; const MySpan = styled.span`margin-right: 15px;`; class User extends Component { render() { const { user } = this.props; return ( <div> <MySpan>{user.name}</MySpan> <MySpan>{user.email}</MySpan> </div> ); } } User.propTypes = { user: PropTypes.object.isRequired }; export default User;
df7e879504ba2c0ee5f75ae1b77a7679681e6f77
[ "JavaScript", "Markdown" ]
7
JavaScript
BioMediaLab/Goodbye-PHP
2385670eefd9da0c31933b0ba0a2293d3760c0f6
a3201f26d8f4562d908e3e9e860d58bd6ebe9729
refs/heads/master
<file_sep>realpython ========== all my learning files <file_sep>import os from bottle import route, run, template index_html = '''My first web app! by {{ author}}''' @route('/anything') def something (anything=''): return template(index_html, author=anything) @route('/') def index(): return template(index_html, author='<NAME>') if __name__=='__main__': port = int (os.environ.get('PORT', 8080)) run(host='0.0.0.0', port=port, debug=True)
b797970b84ef9f7894c452ad9abc0e47c07d9ec9
[ "Markdown", "Python" ]
2
Markdown
willyhakim/realpython
48ef7bb109e2c6ac89e410481164e01f83608137
9998a2b5a2cd6e5aaadd43c43fcd353dd9b5484a
refs/heads/master
<file_sep>/* <NAME> Árvore binária de busca https://www.urionlinejudge.com.br/judge/pt/problems/view/1195 */ #include <stdio.h> #include <stdlib.h> typedef struct Nodes { int info; struct Nodes *leftNode ; struct Nodes *rightNode; } Node; Node* createTree(int rootValue, Node* inputLeftNode, Node* inputRightNode) { Node *root; root = (Node*)malloc(sizeof(Node)); root->info = rootValue; root->leftNode = inputLeftNode; root->rightNode = inputRightNode; return root; } Node* insertInTree(int newValue, Node* treeRoot) { if (treeRoot == NULL) { treeRoot = createTree(newValue,NULL,NULL); } else { if(newValue < treeRoot->info) { treeRoot->leftNode = insertInTree(newValue,treeRoot->leftNode); } else { treeRoot->rightNode = insertInTree(newValue,treeRoot->rightNode); } } return treeRoot; } void printPreOrder(Node* currentNode) { if(currentNode != NULL) { printf(" %d",currentNode->info); printPreOrder(currentNode->leftNode); printPreOrder(currentNode->rightNode); } } void printInOrder(Node* currentNode ) { if(currentNode != NULL) { printInOrder(currentNode->leftNode); printf(" %d",currentNode->info); printInOrder(currentNode->rightNode); } } void printPostOrder(Node* currentNode) { if(currentNode != NULL) { printPostOrder(currentNode->leftNode); printPostOrder(currentNode->rightNode); printf(" %d",currentNode->info); } } int main() { Node *tree = NULL; int numberOfTestCases; int numberOfNodes; int testCaseNumber; int scannedValue; int i; scanf("%d", &numberOfTestCases); for(testCaseNumber = 0; testCaseNumber < numberOfTestCases; testCaseNumber++) { scanf("%d", &numberOfNodes); for(i = 0 ; i < numberOfNodes; i++) { scanf("%d",&scannedValue); tree = insertInTree(scannedValue,tree); } printf("Case %d:\n",testCaseNumber + 1); printf("Pre.:"); printPreOrder(tree); printf("\nIn..:"); printInOrder(tree); printf("\nPost:"); printPostOrder(tree); printf("\n\n"); tree = NULL; } return 0; }
3298497f083936fab8c684a6fe1a0feab849799b
[ "C" ]
1
C
vhazin/algoritmos-2018-2-exercicio-05-arvore-binaria-de-busca-Arthurcrs
d8639fbc2a484ec521e30cb3978869c4b037f887
55e992726b1b22bde85e751ffe8c8b4b203d9d9b
refs/heads/main
<repo_name>ironman3921/snail-game<file_sep>/sketch.js var snail, snail_img; var tomato, tomato_img; var ground, ground_img; function preload(){ ground_img = loadImage("ground.png"); } function setup(){ createCanvas(600,200); ground = createSprite(600,180); ground.addImage("ground1",ground.png); } function draw(){ drawSprites(); }
4a857d21763db46648948bba2c4c969a75ce1c66
[ "JavaScript" ]
1
JavaScript
ironman3921/snail-game
57feab18773917045ca219e3225afd2fc5796138
260499497d7312bdb44acc7e9e10c2fdd9957e24
refs/heads/master
<file_sep>// // Created by <NAME> on 17.05.2017. // Copyright © 2017 Droids on Roids. All rights reserved. // public struct Snap { let url: String let fileName: String } <file_sep>// // Created by <NAME> on 17.05.2017. // Copyright © 2017 Droids on Roids. All rights reserved. // import UIKit extension UIImage { var data: Data? { return UIImageJPEGRepresentation(self, 0.8) } func fixImageOrientation() -> UIImage { guard imageOrientation != .up else { return self } UIGraphicsBeginImageContextWithOptions(size, false, scale) draw(in: CGRect(origin: .zero, size: size)) let imageFromContext = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return imageFromContext ?? UIImage() } func resized(newSize: CGSize) -> UIImage { guard size != newSize else { return self } UIGraphicsBeginImageContextWithOptions(newSize, false, 0.0) draw(in: CGRect(origin: .zero, size: newSize)) let imageFromContext = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return imageFromContext ?? UIImage() } } <file_sep>// // Created by <NAME> on 17.05.2017. // Copyright © 2017 Droids on Roids. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. let storyboard = UIStoryboard(name: "Main", bundle: nil) let cameraViewController = storyboard.instantiateViewController(withIdentifier: "middle") let storyViewController = storyboard.instantiateViewController(withIdentifier: "right") let contactsViewController = storyboard.instantiateViewController(withIdentifier: "left") let settingsViewController = storyboard.instantiateViewController(withIdentifier: "top") let snapContainerViewController = SnapContainerViewController.containerViewWith(contactsViewController, middleViewController: cameraViewController, rightViewController: storyViewController, topViewController: settingsViewController) window = UIWindow(frame: UIScreen.main.bounds) window?.rootViewController = snapContainerViewController window?.makeKeyAndVisible() return true } }
7909875ae3ae208d05b4654c658806f2ed4b1e96
[ "Swift" ]
3
Swift
KordianKL/SnapLikePreview
b2beb10091042bd85b21f6800c002e6aeffb0536
480aa1f4570ad6fba7d14fa7ac41fa53f7ee585a
refs/heads/master
<file_sep>/* * File: Graphics.cpp * Author: juan.garibotti * * Created on 24 de febrero de 2014, 14:36 */ #include "Graphics.hpp" #include <cassert> #include <fstream> #include "GLT/Model.hpp" #include "TGA/tga.hpp" #include "TLS/Tools.hpp" #include "Movement.hpp" #include <iostream> namespace { constexpr auto shaderLoc = "resource/shader/"; std::vector<glt::Shader> LoadShaders(cfg::Config const& i_catalog) { std::vector<glt::Shader> shaders; for(auto shaderName = std::begin(i_catalog); shaderName != std::end(i_catalog); ++shaderName) { std::ifstream fragmentFile { shaderLoc + shaderName->second.GetString() }; auto const fragmentShader = tls::StringFromFile( fragmentFile ); ++shaderName; std::ifstream vertexFile { shaderLoc + shaderName->second.GetString() }; auto const vertexShader = tls::StringFromFile( vertexFile ); shaders.push_back( glt::LoadShaderCode( vertexShader.c_str(), fragmentShader.c_str() ) ); } return shaders; } } GraphicsComponent::GraphicsComponent( MovementComponent const& i_movement ) : k_movement ( i_movement ) {} void GraphicsComponent::Initialize( GraphicsSettings const& i_settings ) { // OpenGL settings glewInit(); glClearColor( 0.0f, 0.0f, 0.0f, 1.0f ); glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); // Load catalogs m_modelCatalog.LoadConfiguration( i_settings.m_modelCatalog ); m_shaderCatalog.LoadConfiguration( i_settings.m_shaderCatalog ); m_textureCatalog.LoadConfiguration( i_settings.m_textureCatalog ); // Projection settings m_geometryTransform.Reset(); m_geometryTransform.DefineOrthographicProjection( -16.0, 16.0, -10.0, 10.0, -1.0, 1.0 ); m_shaders = LoadShaders(m_shaderCatalog); } void GraphicsComponent::AddModel( ModelID const& i_modelID, glt::Model const& i_model ) { ModelData modelData = { i_modelID, 0, GL_TRIANGLES, 0, GL_UNSIGNED_INT, 0 }; // Create the vertex array object glGenVertexArrays( 1, &modelData.m_vertexArray ); glBindVertexArray( modelData.m_vertexArray ); { // Create vertex buffer object GLuint vertexBuffer; glGenBuffers( 1, &vertexBuffer ); // Copy data to buffer object glBindBuffer( GL_ARRAY_BUFFER, vertexBuffer ); glBufferData( GL_ARRAY_BUFFER, GLsizeiptr(sizeof(glt::Vertex)*i_model.m_vertexList.size()), i_model.m_vertexList.data() , GL_STATIC_DRAW ); } { // Enable vertex position attribute glEnableVertexAttribArray( glt::Vertex::Position ); glVertexAttribPointer( glt::Vertex::Position, 3, GL_FLOAT, GL_FALSE, GLsizei( sizeof( glt::Vertex ) ), 0 ); } /*{ // Not enabled since obj files don't hold color information glEnableVertexAttribArray( glt::Vertex::Color ); glVertexAttribPointer( glt::Vertex::Color, 3, GL_FLOAT, GL_FALSE, GLsizei( sizeof( glt::Vertex ) ), (GLvoid const*)(sizeof(GLfloat)*3) ); }*/ { // Enable texture attribute glEnableVertexAttribArray( glt::Vertex::Texture ); glVertexAttribPointer( glt::Vertex::Texture, 2, GL_FLOAT, GL_FALSE, GLsizei( sizeof( glt::Vertex ) ), (GLvoid const*)(sizeof(GLfloat)*6) ); } { // Create index buffer object GLuint indexBuffer; glGenBuffers( 1, &indexBuffer ); // Copy index data glBindBuffer( GL_ELEMENT_ARRAY_BUFFER, indexBuffer ); glBufferData( GL_ELEMENT_ARRAY_BUFFER, GLsizeiptr(sizeof(GLuint)*i_model.m_indexList.size()), i_model.m_indexList.data(), GL_STATIC_DRAW); } // Unbind vertex array glBindVertexArray(0); modelData.m_count = GLsizei( i_model.m_indexList.size() ); m_models.push_back( modelData ); } void GraphicsComponent::AddEntity( GraphicsData const& i_graphicsData ) { m_data.push_back( i_graphicsData ); } void GraphicsComponent::AddElement( GraphicsData const& i_element ) { m_elements.push_back( i_element ); } void GraphicsComponent::AddTexture( std::string const& i_texture ) { m_texes.push_back( glt::Texture { tga::MakeImage( "resource/texture/" + m_textureCatalog.GetStringProperty( i_texture + "::file" ) ) } ); } void GraphicsComponent::Update() { for ( auto & entity : m_data ) { MovementData const& movementData ( k_movement.GetData( entity.m_id ) ); entity.m_frame.m_position[0] = movementData.m_position[0]; entity.m_frame.m_position[1] = movementData.m_position[1]; entity.m_frame.m_position[2] = movementData.m_position[2]; } } void GraphicsComponent::Render() const { glClear( GL_COLOR_BUFFER_BIT ); glUseProgram( m_shaders[0].m_shaderID ); for ( auto const& entity : m_data ) { // Select the vertex array to draw assert( entity.m_modelID > 0 ); ModelData const& model ( m_models.at( std::size_t( entity.m_modelID - 1 ) ) ); glBindVertexArray( model.m_vertexArray ); // Set the matrix uniform for the vertex shader glUniformMatrix4fv( (GLint)m_shaders.front().m_mvpLocation, 1, GL_FALSE, &m_geometryTransform.BuildMVPMatrix( entity.m_frame ).m_data[0] ); glDrawElements( model.m_mode, model.m_count, model.m_type, model.m_indices ); } } <file_sep>/* * File: TextureID.hpp * Author: JoPe * * Created on 7 de junio de 2014, 15:37 */ #ifndef TEXTUREID_HPP #define TEXTUREID_HPP typedef int TextureId; #endif /* TEXTUREID_HPP */ <file_sep>/* * File: RNGSystem.hpp * Author: juan.garibotti * * Created on 12 de junio de 2014, 12:35 */ #ifndef RNGSYSTEM_HPP #define RNGSYSTEM_HPP #include <random> class RNGSystem { std::minstd_rand m_generator; }; #endif /* RNGSYSTEM_HPP */ <file_sep>/* * File: AIComponent.cpp * Author: juan.garibotti * * Created on 9 de mayo de 2014, 15:49 */ #include "AIComponent.hpp" #include "Movement.hpp" AIComponent::AIComponent(msg::Messenger & io_messenger, MovementComponent const& i_movement) : r_messenger {io_messenger} , k_movement {i_movement} {} void AIComponent::Update() { // Simple AI: move towards the ball MovementData aiData ( k_movement.GetData( 2 ) ); MovementData ballData ( k_movement.GetData( 3 ) ); if ( aiData.m_position[1] > ballData.m_position[1] ) { r_messenger.Post({4},{2,2}); } else if ( aiData.m_position[1] < ballData.m_position[1] ) { r_messenger.Post({4},{1,2}); } else { r_messenger.Post({4},{3,2}); } }<file_sep>/* * File: GameLogicComponent.hpp * Author: juan.garibotti * * Created on 16 de mayo de 2014, 16:04 */ #ifndef GAMELOGICCOMPONENT_HPP #define GAMELOGICCOMPONENT_HPP #include <random> #include <vector> #include "MSG/Messenger.hpp" struct PlayerInput { enum { e_quit, e_moveUp, e_moveDown, e_stopMoving }; }; enum class GameEvent { e_ballHitsPlayerGoalLine, e_ballHitsAIGoalLine }; class MovementComponent; class CollisionDetectionComponent; class GameLogicComponent { std::minstd_rand m_rng; msg::Messenger & m_messenger; msg::Dequeueer m_scores; msg::Dequeueer m_commands; MovementComponent & m_movement; std::vector<PlayerInput> m_playerInput; int m_playerScore; int m_aiScore; public: GameLogicComponent( msg::Messenger & i_messenger, MovementComponent & i_movement ); int const& GetPlayerScore() const; int const& GetAiScore() const; void Update(); void PushInput( PlayerInput const& i_input ); void ProcessEvent( GameEvent const& i_event ); void ResetLevel(); }; #endif /* GAMELOGICCOMPONENT_HPP */ <file_sep>/* * File: CollisionDetectionComponent.hpp * Author: juan.garibotti * * Created on 19 de febrero de 2014, 18:03 */ #ifndef COLLISIONDETECTION_HPP #define COLLISIONDETECTION_HPP #include <vector> #include "MSG/Messenger.hpp" #include "GameLogicComponent.hpp" #include "EntityId.hpp" struct CollisionPair { EntityID m_entityIDA; EntityID m_entityIDB; CollisionPair( EntityID const& i_entityIDA, EntityID const& i_entityIDB ); }; struct CollisionData { EntityID m_entityID; float m_sizeX; float m_sizeY; }; struct BoundaryData { float m_top; float m_bottom; float m_left; float m_right; }; struct BoundaryCheck { EntityID m_entityID; enum Side { e_top, e_bottom, e_left, e_right } m_side; }; typedef std::vector< CollisionPair > CollisionsList; class MovementComponent; class CollisionDetectionComponent { msg::Messenger & r_messenger; MovementComponent const& k_movement; std::vector< CollisionData > m_data; std::vector< GameEvent > m_eventList; CollisionsList m_collisions; BoundaryData m_boundaries; BoundaryCheck m_boundaryCheck; bool m_collisionDetected; void ClearEvents(); void ClearCollisions(); public: CollisionDetectionComponent( msg::Messenger & i_messenger, MovementComponent const& i_movement ); void AddEntity( CollisionData const& i_data ); BoundaryCheck const& GetBoundaryCheck() const; CollisionsList const& GetCollisions() const; bool const& CollisionDetected() const; void Update(); std::vector< GameEvent > const& GetEvents() const; }; #endif /* COLLISIONDETECTIONCOMPONENT_HPP */ <file_sep>/* * File: TextureID.cpp * Author: JoPe * * Created on 7 de junio de 2014, 15:37 */ #include "TextureID.hpp" <file_sep>/* * File: ShaderID.cpp * Author: JoPe * * Created on 17 de junio de 2014, 21:42 */ #include "ShaderId.hpp" <file_sep>/* * File: Application.cpp * Author: juan.garibotti * * Created on 17 de febrero de 2014, 11:48 */ #include "Application.hpp" #include "GL/glew.h" #include "CFG/Config.hpp" #include "GLT/Model.hpp" #include "GUI/GameData.hpp" #include "OBJ/Object.hpp" namespace { void ConfigureWindow(sf::Window & io_window, cfg::Config const& i_config) { auto const resolutionX = i_config.GetIntProperty( "Window::resolutionX" ); auto const resolutionY = i_config.GetIntProperty( "Window::resolutionY" ); auto const& title = i_config.GetStringProperty( "Window::title" ); auto const mode = sf::VideoMode{ (unsigned int)resolutionX , (unsigned int)resolutionY }; auto const context = sf::ContextSettings{ 0, 0, 0, 3, 2 }; io_window.create( mode, title, sf::Style::None, context ); io_window.setFramerateLimit( (unsigned int)i_config.GetIntProperty( "Window::framerate" ) ); io_window.setKeyRepeatEnabled( false ); } } Application::Application() : m_commands {m_messenger.Register({4})} , m_window {} , m_movement {} , m_ai {m_messenger, m_movement} , m_collisionDetection {m_messenger, m_movement} , m_collisionResolution {m_movement, m_collisionDetection} , m_gameLogic {m_messenger, m_movement} , m_graphics {m_movement} , m_interface {m_messenger} , m_running {false} {} void Application::Run() { SetUp(); while ( m_running ) { ProcessInput(); Update(); Render(); } CleanUp(); } void Application::SetUp() { cfg::Config const config ( "default.conf" ); ConfigureWindow(m_window, config); // Load resources { GraphicsSettings const graphicsSettings = { config.GetStringProperty( "Catalog::models" ), config.GetStringProperty( "Catalog::shaders" ), config.GetStringProperty( "Catalog::textures" ) }; m_graphics.Initialize( graphicsSettings ); m_graphics.AddModel( config.GetIntProperty( "Resource::Paddle::id" ), glt::Model( obj::Object( config.GetStringProperty( "Resource::Paddle::model" ) ) ) ); m_graphics.AddModel( config.GetIntProperty( "Resource::Ball::id" ), glt::Model( obj::Object( config.GetStringProperty( "Resource::Ball::model" ) ) ) ); m_graphics.AddModel( 3, glt::Model( obj::Object( config.GetStringProperty( "Resource::Numbers::model" ) ) ) ); m_graphics.AddTexture( "Id1" ); } // Initialize interface { // Commands: exit, move up, move down, stop m_interface.Init({4},{0,1,2,3}); } // Load entities { MovementData movementData = { config.GetIntProperty( "Entity::PlayerPaddle::id" ), { config.GetFloatProperty( "Entity::PlayerPaddle::positionX" ), config.GetFloatProperty( "Entity::PlayerPaddle::positionY" ), config.GetFloatProperty( "Entity::PlayerPaddle::positionZ" ) }, { 0.0f, 0.0f, 0.0f } }; GraphicsData graphicsData = { 1, // entity id { { { 0, 0, 0 } }, { { 0, 0, 1 } }, { { 0, 1, 0 } } }, // Frame 1, // ModelID 0 }; CollisionData collisionData = { 1, // entity id 0.5f, 2.0f // size x, y }; m_movement.AddEntity( movementData ); m_graphics.AddEntity( graphicsData ); m_collisionDetection.AddEntity( collisionData ); movementData.m_entityID = config.GetIntProperty( "Entity::AIPaddle::id" ); movementData.m_position[0] = config.GetFloatProperty( "Entity::AIPaddle::positionX" ); graphicsData.m_id = config.GetIntProperty( "Entity::AIPaddle::id" ); collisionData.m_entityID = config.GetIntProperty( "Entity::AIPaddle::id" ); m_movement.AddEntity( movementData ); m_graphics.AddEntity( graphicsData ); m_collisionDetection.AddEntity( collisionData ); movementData.m_entityID = config.GetIntProperty( "Entity::Ball::id" ); movementData.m_position[0] = config.GetFloatProperty( "Entity::Ball::positionX" ); movementData.m_speed[0] = -2.0f; movementData.m_speed[1] = -0.5f; graphicsData.m_id = config.GetIntProperty( "Entity::Ball::id" ); graphicsData.m_modelID = config.GetIntProperty( "Entity::Ball::modelID" ); collisionData.m_entityID = config.GetIntProperty( "Entity::Ball::id" ); collisionData.m_sizeX = 0.5f; collisionData.m_sizeY = 0.5f; m_movement.AddEntity( movementData ); m_graphics.AddEntity( graphicsData ); m_collisionDetection.AddEntity( collisionData ); } m_running = true; m_gameLogic.ResetLevel(); } void Application::ProcessInput() { sf::Event event; while ( m_window.pollEvent(event) ) { m_interface.ProcessInput(event); } ProcessCommands(); } void Application::Update() { m_ai.Update(); m_gameLogic.Update(); m_movement.Update(); m_collisionDetection.Update(); while ( m_collisionDetection.CollisionDetected() ) { m_collisionResolution.Update(); m_collisionDetection.Update(); } m_graphics.Update(); m_interface.Update(); } void Application::Render() { m_graphics.Render(); m_interface.Draw(); m_window.display(); } void Application::CleanUp() { m_window.close(); } void Application::ProcessCommands() { while (!m_commands.IsEmpty()) { switch (m_commands.Front().m_id) { case PlayerInput::e_quit: m_running = false; break; default: break; } m_commands.Pop(); } }<file_sep>/* * File: CollisionDetectionComponent.cpp * Author: juan.garibotti * * Created on 19 de febrero de 2014, 18:03 */ #include "CollisionDetection.hpp" #include <cmath> #include "Movement.hpp" CollisionPair::CollisionPair( EntityID const& i_entityIDA, EntityID const& i_entityIDB ) : m_entityIDA ( i_entityIDA ) , m_entityIDB ( i_entityIDB ) {} void CollisionDetectionComponent::AddEntity( CollisionData const& i_data ) { m_data.push_back( i_data ); } CollisionDetectionComponent::CollisionDetectionComponent( msg::Messenger & i_messenger, MovementComponent const& i_movement ) : r_messenger {i_messenger} , k_movement ( i_movement ) , m_boundaries ( { 10.0f, -10.0f, -16.0f, 16.0f } ) , m_boundaryCheck ( { 0, BoundaryCheck::e_bottom } ) , m_collisionDetected ( false ) {} BoundaryCheck const& CollisionDetectionComponent::GetBoundaryCheck() const { return m_boundaryCheck; } CollisionsList const& CollisionDetectionComponent::GetCollisions() const { return m_collisions; } bool const& CollisionDetectionComponent::CollisionDetected() const { return m_collisionDetected; } void CollisionDetectionComponent::ClearCollisions() { m_collisions.clear(); m_boundaryCheck.m_entityID = 0; m_collisionDetected = false; } void CollisionDetectionComponent::Update() { ClearCollisions(); ClearEvents(); for ( auto entity ( m_data.begin() ), end ( m_data.end() ); entity != end; ++entity ) { MovementData const& entityMovData ( k_movement.GetData( entity->m_entityID ) ); if ( entityMovData.m_position[0] + entity->m_sizeX > m_boundaries.m_right ) { // Player scores a point r_messenger.Post({1},{int(GameEvent::e_ballHitsAIGoalLine),0}); m_eventList.push_back( GameEvent::e_ballHitsAIGoalLine ); } else if ( entityMovData.m_position[0] - entity->m_sizeX < m_boundaries.m_left ) { // AI scores a point r_messenger.Post({1},{int(GameEvent::e_ballHitsPlayerGoalLine),0}); m_eventList.push_back( GameEvent::e_ballHitsPlayerGoalLine ); } else if ( entityMovData.m_position[1] + entity->m_sizeY > m_boundaries.m_top ) { m_boundaryCheck.m_entityID = entity->m_entityID; m_boundaryCheck.m_side = BoundaryCheck::e_top; m_collisionDetected = true; } else if ( entityMovData.m_position[1] - entity->m_sizeY < m_boundaries.m_bottom ) { m_boundaryCheck.m_entityID = entity->m_entityID; m_boundaryCheck.m_side = BoundaryCheck::e_bottom; m_collisionDetected = true; } for ( auto collider ( entity+1 ); collider != end; ++collider ) { MovementData const& colliderMovData ( k_movement.GetData( collider->m_entityID ) ); if ( std::abs( entityMovData.m_position[0] - colliderMovData.m_position[0] ) < ( entity->m_sizeX + collider->m_sizeX ) && std::abs( entityMovData.m_position[1] - colliderMovData.m_position[1] ) < ( entity->m_sizeY + collider->m_sizeY ) ) { m_collisions.push_back( CollisionPair( entity->m_entityID, collider->m_entityID ) ); m_collisionDetected = true; } } } } std::vector< GameEvent > const& CollisionDetectionComponent::GetEvents() const { return m_eventList; } void CollisionDetectionComponent::ClearEvents() { m_eventList.clear(); }<file_sep>/* * File: Graphics.hpp * Author: juan.garibotti * * Created on 24 de febrero de 2014, 14:36 */ #ifndef GRAPHICS_HPP #define GRAPHICS_HPP #include <string> #include "CFG/Config.hpp" #include "FNT/Face.hpp" #include "GL/glew.h" #include "GLT/Frame.hpp" #include "GLT/Shader.hpp" #include "GLT/GeometryTransform.hpp" #include "GLT/Texture.hpp" #include "GameLogicComponent.hpp" #include "ModelId.hpp" #include "Movement.hpp" #include "ShaderId.hpp" #include "TextureId.hpp" struct GraphicsSettings { std::string m_modelCatalog; std::string m_shaderCatalog; std::string m_textureCatalog; }; struct GraphicsData // Entity specific { EntityID m_id; glt::Frame m_frame; ModelID m_modelID; TextureId m_textureId; }; struct ModelData // Shared between entities with the same model { ModelID m_id; GLuint m_vertexArray; GLenum m_mode; // Kind of primitives to render GLsizei m_count; // Number of elements GLenum m_type; // Type of the values in m_indices GLvoid const* m_indices; // For VBOs, offset into index array }; struct TextureData { TextureId m_id; glt::Texture m_texture; }; namespace glt { struct Model; } class GraphicsComponent { std::vector< GraphicsData > m_data; std::vector< ModelData > m_models; std::vector< GraphicsData > m_elements; std::vector< glt::Texture > m_texes; std::vector< glt::Shader > m_shaders; MovementComponent const& k_movement; glt::GeometryTransform m_geometryTransform; cfg::Config m_modelCatalog; cfg::Config m_shaderCatalog; cfg::Config m_textureCatalog; public: GraphicsComponent( MovementComponent const& i_movement ); void Initialize( GraphicsSettings const& i_settings ); void AddModel( ModelID const& i_modelID, glt::Model const& i_model ); void AddElement( GraphicsData const& i_element ); void AddTexture( std::string const& i_texture ); void AddEntity( GraphicsData const& i_graphicsData ); void Update(); void Render() const; }; #endif /* GRAPHICS_HPP */ <file_sep>/* * File: CollisionResolution.hpp * Author: juan.garibotti * * Created on 21 de febrero de 2014, 17:16 */ #ifndef COLLISIONRESOLUTION_HPP #define COLLISIONRESOLUTION_HPP #include <vector> #include "CollisionDetection.hpp" class MovementComponent; class CollisionDetectionComponent; class CollisionResolutionComponent { MovementComponent & m_movement; CollisionDetectionComponent const& m_collisionDetection; public: CollisionResolutionComponent( MovementComponent & io_movement, CollisionDetectionComponent & io_collisionDetection ); void Update(); }; #endif /* COLLISIONRESOLUTION_HPP */ <file_sep># # Generated Makefile - do not edit! # # Edit the Makefile in the project folder instead (../Makefile). Each target # has a -pre and a -post target defined where you can add customized code. # # This makefile implements configuration specific macros and targets. # Environment MKDIR=mkdir CP=cp GREP=grep NM=nm CCADMIN=CCadmin RANLIB=ranlib CC=gcc CCC=g++ CXX=g++ FC=gfortran AS=as # Macros CND_PLATFORM=MinGW-Windows CND_DLIB_EXT=dll CND_CONF=Debug CND_DISTDIR=dist CND_BUILDDIR=build # Include project Makefile include Makefile # Object Directory OBJECTDIR=${CND_BUILDDIR}/${CND_CONF}/${CND_PLATFORM} # Object Files OBJECTFILES= \ ${OBJECTDIR}/src/Application.o \ ${OBJECTDIR}/src/Components/AIComponent.o \ ${OBJECTDIR}/src/Components/CollisionDetection.o \ ${OBJECTDIR}/src/Components/CollisionResolution.o \ ${OBJECTDIR}/src/Components/EntityId.o \ ${OBJECTDIR}/src/Components/GameLogicComponent.o \ ${OBJECTDIR}/src/Components/Graphics.o \ ${OBJECTDIR}/src/Components/ModelId.o \ ${OBJECTDIR}/src/Components/Movement.o \ ${OBJECTDIR}/src/Components/RNGSystem.o \ ${OBJECTDIR}/src/Components/ShaderId.o \ ${OBJECTDIR}/src/Components/TextureId.o \ ${OBJECTDIR}/src/main.o # C Compiler Flags CFLAGS= # CC Compiler Flags CCFLAGS=-m64 -Wfatal-errors -Wall -Wextra -pedantic -Winit-self -Wmissing-include-dirs -Wswitch-default -Wswitch-enum -Wswitch-default -Wfloat-equal -Wshadow -Wcast-qual -Wcast-align -Wwrite-strings -Wconversion -Wsign-conversion -Wlogical-op -Wmissing-declarations -Wmissing-noreturn -Wmissing-format-attribute -Wpacked -Wredundant-decls -Wunreachable-code -Winvalid-pch -Wvolatile-register-var -Wdisabled-optimization -Wstack-protector -std=c++1y CXXFLAGS=-m64 -Wfatal-errors -Wall -Wextra -pedantic -Winit-self -Wmissing-include-dirs -Wswitch-default -Wswitch-enum -Wswitch-default -Wfloat-equal -Wshadow -Wcast-qual -Wcast-align -Wwrite-strings -Wconversion -Wsign-conversion -Wlogical-op -Wmissing-declarations -Wmissing-noreturn -Wmissing-format-attribute -Wpacked -Wredundant-decls -Wunreachable-code -Winvalid-pch -Wvolatile-register-var -Wdisabled-optimization -Wstack-protector -std=c++1y # Fortran Compiler Flags FFLAGS= # Assembler Flags ASFLAGS= # Link Libraries and Options LDLIBSOPTIONS=-L../../../../../lib/freetype-2.5.3/lib -L../../../../../lib/glew-1.11.0/lib -L../../../../../lib/SFML-2.1/lib -L../libconf/${CND_DISTDIR}/${CND_CONF}/${CND_PLATFORM} -L../libcsv/${CND_DISTDIR}/${CND_CONF}/${CND_PLATFORM} -L../libfont/${CND_DISTDIR}/${CND_CONF}/${CND_PLATFORM} -L../libgltools/${CND_DISTDIR}/${CND_CONF}/${CND_PLATFORM} -L../libgui/${CND_DISTDIR}/${CND_CONF}/${CND_PLATFORM} -L../libmatrix/${CND_DISTDIR}/${CND_CONF}/${CND_PLATFORM} -L../libmessenger/${CND_DISTDIR}/${CND_CONF}/${CND_PLATFORM} -L../libobj/${CND_DISTDIR}/${CND_CONF}/${CND_PLATFORM} -L../libtga/${CND_DISTDIR}/${CND_CONF}/${CND_PLATFORM} -L../libtools/${CND_DISTDIR}/${CND_CONF}/${CND_PLATFORM} -L../libvector/${CND_DISTDIR}/${CND_CONF}/${CND_PLATFORM} -llibgui -llibfont -lsfml-window-d -lsfml-system-d -llibgltools -lfreetype -lglew32 -llibtga -lopengl32 -lz -llibconf -llibcsv -llibmatrix -llibmessenger -llibobj -llibtools -llibvector # Build Targets .build-conf: ${BUILD_SUBPROJECTS} "${MAKE}" -f nbproject/Makefile-${CND_CONF}.mk ${CND_DISTDIR}/${CND_CONF}/${CND_PLATFORM}/pongclone.exe ${CND_DISTDIR}/${CND_CONF}/${CND_PLATFORM}/pongclone.exe: ${OBJECTFILES} ${MKDIR} -p ${CND_DISTDIR}/${CND_CONF}/${CND_PLATFORM} ${LINK.cc} -o ${CND_DISTDIR}/${CND_CONF}/${CND_PLATFORM}/pongclone ${OBJECTFILES} ${LDLIBSOPTIONS} -DGLEW_STATIC ${OBJECTDIR}/src/Application.o: src/Application.cpp ${MKDIR} -p ${OBJECTDIR}/src ${RM} "$@.d" $(COMPILE.cc) -g -Wall -DGLEW_STATIC -I../../../../../lib/freetype-2.5.3/include -I../../../../../lib/glew-1.11.0/include -I../../../../../lib/SFML-2.1/include -I../libconf/src -I../libfont/src -I../libgltools/src -I../libgui/src -I../libmatrix/src -I../libmessenger/src -I../libobj/src -I../libtga/src -I../libtools/src -I../libvector/src -MMD -MP -MF "$@.d" -o ${OBJECTDIR}/src/Application.o src/Application.cpp ${OBJECTDIR}/src/Components/AIComponent.o: src/Components/AIComponent.cpp ${MKDIR} -p ${OBJECTDIR}/src/Components ${RM} "$@.d" $(COMPILE.cc) -g -Wall -DGLEW_STATIC -I../../../../../lib/freetype-2.5.3/include -I../../../../../lib/glew-1.11.0/include -I../../../../../lib/SFML-2.1/include -I../libconf/src -I../libfont/src -I../libgltools/src -I../libgui/src -I../libmatrix/src -I../libmessenger/src -I../libobj/src -I../libtga/src -I../libtools/src -I../libvector/src -MMD -MP -MF "$@.d" -o ${OBJECTDIR}/src/Components/AIComponent.o src/Components/AIComponent.cpp ${OBJECTDIR}/src/Components/CollisionDetection.o: src/Components/CollisionDetection.cpp ${MKDIR} -p ${OBJECTDIR}/src/Components ${RM} "$@.d" $(COMPILE.cc) -g -Wall -DGLEW_STATIC -I../../../../../lib/freetype-2.5.3/include -I../../../../../lib/glew-1.11.0/include -I../../../../../lib/SFML-2.1/include -I../libconf/src -I../libfont/src -I../libgltools/src -I../libgui/src -I../libmatrix/src -I../libmessenger/src -I../libobj/src -I../libtga/src -I../libtools/src -I../libvector/src -MMD -MP -MF "$@.d" -o ${OBJECTDIR}/src/Components/CollisionDetection.o src/Components/CollisionDetection.cpp ${OBJECTDIR}/src/Components/CollisionResolution.o: src/Components/CollisionResolution.cpp ${MKDIR} -p ${OBJECTDIR}/src/Components ${RM} "$@.d" $(COMPILE.cc) -g -Wall -DGLEW_STATIC -I../../../../../lib/freetype-2.5.3/include -I../../../../../lib/glew-1.11.0/include -I../../../../../lib/SFML-2.1/include -I../libconf/src -I../libfont/src -I../libgltools/src -I../libgui/src -I../libmatrix/src -I../libmessenger/src -I../libobj/src -I../libtga/src -I../libtools/src -I../libvector/src -MMD -MP -MF "$@.d" -o ${OBJECTDIR}/src/Components/CollisionResolution.o src/Components/CollisionResolution.cpp ${OBJECTDIR}/src/Components/EntityId.o: src/Components/EntityId.cpp ${MKDIR} -p ${OBJECTDIR}/src/Components ${RM} "$@.d" $(COMPILE.cc) -g -Wall -DGLEW_STATIC -I../../../../../lib/freetype-2.5.3/include -I../../../../../lib/glew-1.11.0/include -I../../../../../lib/SFML-2.1/include -I../libconf/src -I../libfont/src -I../libgltools/src -I../libgui/src -I../libmatrix/src -I../libmessenger/src -I../libobj/src -I../libtga/src -I../libtools/src -I../libvector/src -MMD -MP -MF "$@.d" -o ${OBJECTDIR}/src/Components/EntityId.o src/Components/EntityId.cpp ${OBJECTDIR}/src/Components/GameLogicComponent.o: src/Components/GameLogicComponent.cpp ${MKDIR} -p ${OBJECTDIR}/src/Components ${RM} "$@.d" $(COMPILE.cc) -g -Wall -DGLEW_STATIC -I../../../../../lib/freetype-2.5.3/include -I../../../../../lib/glew-1.11.0/include -I../../../../../lib/SFML-2.1/include -I../libconf/src -I../libfont/src -I../libgltools/src -I../libgui/src -I../libmatrix/src -I../libmessenger/src -I../libobj/src -I../libtga/src -I../libtools/src -I../libvector/src -MMD -MP -MF "$@.d" -o ${OBJECTDIR}/src/Components/GameLogicComponent.o src/Components/GameLogicComponent.cpp ${OBJECTDIR}/src/Components/Graphics.o: src/Components/Graphics.cpp ${MKDIR} -p ${OBJECTDIR}/src/Components ${RM} "$@.d" $(COMPILE.cc) -g -Wall -DGLEW_STATIC -I../../../../../lib/freetype-2.5.3/include -I../../../../../lib/glew-1.11.0/include -I../../../../../lib/SFML-2.1/include -I../libconf/src -I../libfont/src -I../libgltools/src -I../libgui/src -I../libmatrix/src -I../libmessenger/src -I../libobj/src -I../libtga/src -I../libtools/src -I../libvector/src -MMD -MP -MF "$@.d" -o ${OBJECTDIR}/src/Components/Graphics.o src/Components/Graphics.cpp ${OBJECTDIR}/src/Components/ModelId.o: src/Components/ModelId.cpp ${MKDIR} -p ${OBJECTDIR}/src/Components ${RM} "$@.d" $(COMPILE.cc) -g -Wall -DGLEW_STATIC -I../../../../../lib/freetype-2.5.3/include -I../../../../../lib/glew-1.11.0/include -I../../../../../lib/SFML-2.1/include -I../libconf/src -I../libfont/src -I../libgltools/src -I../libgui/src -I../libmatrix/src -I../libmessenger/src -I../libobj/src -I../libtga/src -I../libtools/src -I../libvector/src -MMD -MP -MF "$@.d" -o ${OBJECTDIR}/src/Components/ModelId.o src/Components/ModelId.cpp ${OBJECTDIR}/src/Components/Movement.o: src/Components/Movement.cpp ${MKDIR} -p ${OBJECTDIR}/src/Components ${RM} "$@.d" $(COMPILE.cc) -g -Wall -DGLEW_STATIC -I../../../../../lib/freetype-2.5.3/include -I../../../../../lib/glew-1.11.0/include -I../../../../../lib/SFML-2.1/include -I../libconf/src -I../libfont/src -I../libgltools/src -I../libgui/src -I../libmatrix/src -I../libmessenger/src -I../libobj/src -I../libtga/src -I../libtools/src -I../libvector/src -MMD -MP -MF "$@.d" -o ${OBJECTDIR}/src/Components/Movement.o src/Components/Movement.cpp ${OBJECTDIR}/src/Components/RNGSystem.o: src/Components/RNGSystem.cpp ${MKDIR} -p ${OBJECTDIR}/src/Components ${RM} "$@.d" $(COMPILE.cc) -g -Wall -DGLEW_STATIC -I../../../../../lib/freetype-2.5.3/include -I../../../../../lib/glew-1.11.0/include -I../../../../../lib/SFML-2.1/include -I../libconf/src -I../libfont/src -I../libgltools/src -I../libgui/src -I../libmatrix/src -I../libmessenger/src -I../libobj/src -I../libtga/src -I../libtools/src -I../libvector/src -MMD -MP -MF "$@.d" -o ${OBJECTDIR}/src/Components/RNGSystem.o src/Components/RNGSystem.cpp ${OBJECTDIR}/src/Components/ShaderId.o: src/Components/ShaderId.cpp ${MKDIR} -p ${OBJECTDIR}/src/Components ${RM} "$@.d" $(COMPILE.cc) -g -Wall -DGLEW_STATIC -I../../../../../lib/freetype-2.5.3/include -I../../../../../lib/glew-1.11.0/include -I../../../../../lib/SFML-2.1/include -I../libconf/src -I../libfont/src -I../libgltools/src -I../libgui/src -I../libmatrix/src -I../libmessenger/src -I../libobj/src -I../libtga/src -I../libtools/src -I../libvector/src -MMD -MP -MF "$@.d" -o ${OBJECTDIR}/src/Components/ShaderId.o src/Components/ShaderId.cpp ${OBJECTDIR}/src/Components/TextureId.o: src/Components/TextureId.cpp ${MKDIR} -p ${OBJECTDIR}/src/Components ${RM} "$@.d" $(COMPILE.cc) -g -Wall -DGLEW_STATIC -I../../../../../lib/freetype-2.5.3/include -I../../../../../lib/glew-1.11.0/include -I../../../../../lib/SFML-2.1/include -I../libconf/src -I../libfont/src -I../libgltools/src -I../libgui/src -I../libmatrix/src -I../libmessenger/src -I../libobj/src -I../libtga/src -I../libtools/src -I../libvector/src -MMD -MP -MF "$@.d" -o ${OBJECTDIR}/src/Components/TextureId.o src/Components/TextureId.cpp ${OBJECTDIR}/src/main.o: src/main.cpp ${MKDIR} -p ${OBJECTDIR}/src ${RM} "$@.d" $(COMPILE.cc) -g -Wall -DGLEW_STATIC -I../../../../../lib/freetype-2.5.3/include -I../../../../../lib/glew-1.11.0/include -I../../../../../lib/SFML-2.1/include -I../libconf/src -I../libfont/src -I../libgltools/src -I../libgui/src -I../libmatrix/src -I../libmessenger/src -I../libobj/src -I../libtga/src -I../libtools/src -I../libvector/src -MMD -MP -MF "$@.d" -o ${OBJECTDIR}/src/main.o src/main.cpp # Subprojects .build-subprojects: # Clean Targets .clean-conf: ${CLEAN_SUBPROJECTS} ${RM} -r ${CND_BUILDDIR}/${CND_CONF} ${RM} ${CND_DISTDIR}/${CND_CONF}/${CND_PLATFORM}/pongclone.exe # Subprojects .clean-subprojects: # Enable dependency checking .dep.inc: .depcheck-impl include .dep.inc <file_sep>/* * File: GameLogicComponent.cpp * Author: juan.garibotti * * Created on 16 de mayo de 2014, 16:04 */ #include "GameLogicComponent.hpp" #include <cassert> #include "CollisionResolution.hpp" #include "Movement.hpp" GameLogicComponent::GameLogicComponent( msg::Messenger & i_messenger, MovementComponent & i_movement ) : m_messenger { i_messenger } , m_scores { m_messenger.Register({1}) } , m_commands { m_messenger.Register({4}) } , m_movement { i_movement } , m_playerScore { 0 } , m_aiScore { 0 } {} int const& GameLogicComponent::GetPlayerScore() const { return m_playerScore; } int const& GameLogicComponent::GetAiScore() const { return m_aiScore; } void GameLogicComponent::Update() { while (!m_commands.IsEmpty()) { switch ( m_commands.Front().m_id ) { case PlayerInput::e_moveUp: { // Set paddle speed up MovementData data ( m_movement.GetData( m_commands.Front().m_value ) ); data.m_speed[1] = 2.0f; m_movement.SetData( m_commands.Front().m_value, data ); break; } case PlayerInput::e_moveDown: { // Set paddle speed down MovementData data ( m_movement.GetData( m_commands.Front().m_value ) ); data.m_speed[1] = -2.0f; m_movement.SetData( m_commands.Front().m_value, data ); break; } case PlayerInput::e_stopMoving: { // Set paddle speed 0 MovementData data ( m_movement.GetData( m_commands.Front().m_value ) ); data.m_speed[1] = 0.0f; m_movement.SetData( m_commands.Front().m_value, data ); break; } default: break; } m_commands.Pop(); } while (!m_scores.IsEmpty()) { ProcessEvent( GameEvent(m_scores.Front().m_id) ); m_scores.Pop(); } } void GameLogicComponent::PushInput( PlayerInput const& i_input ) { m_playerInput.push_back( i_input ); } void GameLogicComponent::ProcessEvent( GameEvent const& i_event) { switch ( i_event ) { case ( GameEvent::e_ballHitsAIGoalLine ): { m_playerScore += 1; m_messenger.Post({0},{1,m_playerScore}); ResetLevel(); break; } case ( GameEvent::e_ballHitsPlayerGoalLine ): { m_aiScore += 1; m_messenger.Post({0},{2,m_aiScore}); ResetLevel(); break; } default: { assert(false); } } } void GameLogicComponent::ResetLevel() { MovementData movementData = { 1, { -15.0f, 0.0f, 0.0f }, { 0.0f, 0.0f, 0.0f } }; m_movement.SetData( 1, movementData ); movementData.m_entityID = 2; movementData.m_position[0] = 15.0f; m_movement.SetData( 2, movementData ); movementData.m_entityID = 3; movementData.m_position[0] = 0.0f; std::uniform_real_distribution<> speedY ( -3.0f, 3.0f ); std::uniform_real_distribution<> speedX ( -2.0f, -4.0f ); movementData.m_speed = vec::Vector3{ speedX(m_rng), speedY(m_rng), 0.0 }; m_movement.SetData( 3, movementData ); }<file_sep>/* * File: ShaderID.hpp * Author: JoPe * * Created on 17 de junio de 2014, 21:42 */ #ifndef SHADERID_HPP #define SHADERID_HPP typedef int ShaderId; #endif /* SHADERID_HPP */ <file_sep>/* * File: Movement.hpp * Author: juan.garibotti * * Created on 17 de febrero de 2014, 14:08 */ #ifndef MOVEMENT_HPP #define MOVEMENT_HPP #include <vector> #include "VEC/Vector3.hpp" #include "EntityId.hpp" struct MovementData { EntityID m_entityID; vec::Vector3 m_position; vec::Vector3 m_speed; }; class MovementComponent { std::vector< MovementData > m_data; std::vector< MovementData > m_buffer; void Swap(); public: void AddEntity( MovementData const& i_data ); void Update(); MovementData const& GetData( EntityID const& i_entityID ) const; void SetData( EntityID const& i_entityID, MovementData const& i_data ); }; #endif /* MOVEMENT_HPP */ <file_sep>/* * File: AIComponent.hpp * Author: juan.garibotti * * Created on 9 de mayo de 2014, 15:49 */ #ifndef AICOMPONENT_HPP #define AICOMPONENT_HPP #include "MSG/Messenger.hpp" class MovementComponent; class AIComponent { msg::Messenger & r_messenger; MovementComponent const& k_movement; public: AIComponent(msg::Messenger & io_messenger, MovementComponent const& i_movement); void Update(); }; #endif /* AICOMPONENT_HPP */ <file_sep>/* * File: RNGSystem.cpp * Author: juan.garibotti * * Created on 12 de junio de 2014, 12:35 */ #include "RNGSystem.hpp" <file_sep>/* * File: main.cpp * Author: juan.garibotti * * Created on 14 de febrero de 2014, 16:13 */ #include "Application.hpp" int main() { Application app; app.Run(); return 0; }<file_sep>/* * File: ModelID.hpp * Author: juan.garibotti * * Created on 6 de mayo de 2014, 11:53 */ #ifndef MODELID_HPP #define MODELID_HPP typedef int ModelID; #endif /* MODELID_HPP */ <file_sep>/* * File: EntityID.cpp * Author: juan.garibotti * * Created on 21 de febrero de 2014, 14:12 */ #include "EntityId.hpp" <file_sep>/* * File: ModelID.cpp * Author: juan.garibotti * * Created on 6 de mayo de 2014, 11:53 */ #include "ModelID.hpp" <file_sep>/* * File: CollisionResolution.cpp * Author: juan.garibotti * * Created on 21 de febrero de 2014, 17:16 */ #include "CollisionResolution.hpp" #include <cmath> #include "CollisionDetection.hpp" #include "Movement.hpp" void ResolveBallPaddleCollision( MovementData & io_ball, MovementData & io_paddle ); CollisionResolutionComponent::CollisionResolutionComponent( MovementComponent & io_movement, CollisionDetectionComponent & io_collisionDetection ) : m_movement( io_movement ) , m_collisionDetection ( io_collisionDetection ) {} void ResolveBallPaddleCollision( MovementData & io_ball, MovementData & io_paddle ) { // Entity A is the ball // Move ball to paddle's reference frame io_ball.m_speed.Subtract( io_paddle.m_speed ); io_ball.m_position.Subtract( io_paddle.m_position ); // Determine x and y collision time auto collisionTimeX = ( 1.0f - std::abs( io_ball.m_position[0] ) ) / std::abs( io_ball.m_speed[0] ); auto collisionTimeY = ( 2.5f - std::abs( io_ball.m_position[1] ) ) / std::abs( io_ball.m_speed[1] ); if ( collisionTimeX < collisionTimeY ) { // collision happened from front io_ball.m_speed[0] = -io_ball.m_speed[0]; io_ball.m_speed[1] += io_paddle.m_speed[1]; if ( io_ball.m_position[0] < 0.0f ) { io_ball.m_position[0] -= 1.0f - std::abs( io_ball.m_position[0] ); } else { io_ball.m_position[0] += 1.0f - std::abs( io_ball.m_position[0] ); } io_ball.m_speed.Scale( 1.2 ); } else { io_ball.m_speed[1] = -io_ball.m_speed[1]; if ( io_ball.m_position[1] < 0.0f ) { io_ball.m_position[1] -= ( 2.5f - std::abs( io_ball.m_position[1] ) );// / 2.0f; io_paddle.m_position[1] += ( 2.5f - std::abs( io_ball.m_position[1] ) );// / 2.0f; } else { io_ball.m_position[1] += ( 2.5f - std::abs( io_ball.m_position[1] ) );// / 2.0f; io_paddle.m_position[1] -= ( 2.5f - std::abs( io_ball.m_position[1] ) );// / 2.0f; } io_ball.m_speed.Scale( 1.2 ); } // Return ball to game frame of reference io_ball.m_position.Add( io_paddle.m_position ); } void CollisionResolutionComponent::Update() { BoundaryCheck const& boundaryCheck ( m_collisionDetection.GetBoundaryCheck() ); if ( boundaryCheck.m_entityID != 0 ) { if ( boundaryCheck.m_entityID == 3 ) { MovementData ball ( m_movement.GetData( boundaryCheck.m_entityID ) ); if ( boundaryCheck.m_side == BoundaryCheck::e_top || boundaryCheck.m_side == BoundaryCheck::e_bottom ) { ball.m_position[1] -= ball.m_speed[1] / 60.0f; ball.m_speed[1] *= -1.0f; m_movement.SetData( ball.m_entityID, ball ); } } else { MovementData paddle ( m_movement.GetData( boundaryCheck.m_entityID ) ); if ( boundaryCheck.m_side == BoundaryCheck::e_top ) { paddle.m_position[1] = 8.0f; } else if ( boundaryCheck.m_side == BoundaryCheck::e_bottom ) { paddle.m_position[1] = -8.0f; } paddle.m_speed[1] = 0.0f; m_movement.SetData( paddle.m_entityID, paddle ); } } else { CollisionsList const& collisions ( m_collisionDetection.GetCollisions() ); if ( collisions.size() != 0 ) { // Identify ball auto entityA = m_movement.GetData( collisions.front().m_entityIDA ); auto entityB = m_movement.GetData( collisions.front().m_entityIDB ); if ( entityA.m_entityID == 3 ) { ResolveBallPaddleCollision( entityA, entityB ); m_movement.SetData( entityA.m_entityID, entityA ); } else { ResolveBallPaddleCollision( entityB, entityA ); m_movement.SetData( entityB.m_entityID, entityB ); } } } }<file_sep>/* * File: Movement.cpp * Author: juan.garibotti * * Created on 17 de febrero de 2014, 14:08 */ #include <stdexcept> #include "Movement.hpp" void MovementComponent::AddEntity( MovementData const& i_data ) { m_data.push_back( i_data ); } void MovementComponent::Swap() { std::swap( m_data, m_buffer ); } void MovementComponent::Update() { // Update time is 1/60th of a second, or 16.7 ms // Speed is in units/second for ( auto & entity : m_data ) { entity.m_position[0] += entity.m_speed[0] * ( 1.0f / 60.f ); entity.m_position[1] += entity.m_speed[1] * ( 1.0f / 60.f ); entity.m_position[2] += entity.m_speed[2] * ( 1.0f / 60.f ); } } MovementData const& MovementComponent::GetData( EntityID const& i_entityID ) const { for ( auto const& entity : m_data ) { if ( i_entityID == entity.m_entityID ) { return entity; } } throw std::range_error( "No Entity found" ); } void MovementComponent::SetData( EntityID const& i_entityID, MovementData const& i_data ) { for ( auto & entity : m_data ) { if ( i_entityID == entity.m_entityID ) { entity = i_data; return; } } throw std::range_error( "No Entity found" ); }<file_sep>/* * File: Application.hpp * Author: juan.garibotti * * Created on 17 de febrero de 2014, 11:48 */ #ifndef APPLICATION_HPP #define APPLICATION_HPP #include "SFML/Window.hpp" #include "GUI/Interface.hpp" #include "MSG/Messenger.hpp" #include "Components/AIComponent.hpp" #include "Components/CollisionDetection.hpp" #include "Components/CollisionResolution.hpp" #include "Components/GameLogicComponent.hpp" #include "Components/Graphics.hpp" #include "Components/Movement.hpp" class Application { msg::Messenger m_messenger; msg::Dequeueer m_commands; sf::Window m_window; MovementComponent m_movement; AIComponent m_ai; CollisionDetectionComponent m_collisionDetection; CollisionResolutionComponent m_collisionResolution; GameLogicComponent m_gameLogic; GraphicsComponent m_graphics; gui::Interface m_interface; bool m_running; void SetUp(); void ProcessInput(); void Update(); void Render(); void CleanUp(); void ProcessCommands(); public: Application(); void Run(); }; #endif /* APPLICATION_HPP */ <file_sep>/* * File: EntityID.hpp * Author: juan.garibotti * * Created on 21 de febrero de 2014, 14:11 */ #ifndef ENTITYID_HPP #define ENTITYID_HPP typedef int EntityID; #endif /* ENTITYID_HPP */
89eab8818d717b1ec7805beb3325e2af01386daa
[ "Makefile", "C++" ]
26
C++
jpgaribotti/pong
6c8b099a62c157be7d513f55f3f1a9022eeaedd5
57373c804e80ea32f5bca5af08499ef7dcb15025
refs/heads/master
<repo_name>gautam-07/Code-Chef<file_sep>/README.md <img src="./code-chef.png"> <br><br> <pre>Level: 0 - 1000</pre> <table> <tr> <th align="center" colspan=2>Arrays</th> <tr> <tr> <th align="center">S.no</th> <th align="center">Question List</th> <tr> <tr> <td align="center">1</td> <td align="center"><a href="https://www.codechef.com/submit/WATSCORE">Practice makes us perfect</a></td> </tr> <tr> <td align="center">2</td> <td align="center"><a href="https://www.codechef.com/submit/RECENTCONT">Problems in your to-do list</a></td> </tr> <tr> <td align="center">3</td> <td align="center"><a href="https://www.codechef.com/submit/WATSCORE">Recent contest problems</a></td> </tr> <tr> <td align="center">4</td> <td align="center"><a href="https://www.codechef.com/submit/TLG">The Lead Game</a></td> </tr> <tr> <td align="center">5</td> <td align="center"><a href="https://www.codechef.com/submit/NUM239">Counting Pretty Numbers</a></td> </tr> <tr> <td align="center">6</td> <td align="center"><a href="https://www.codechef.com/submit/PAIREQ">Make all equal using Pairs</a></td> </tr> <tr> <td align="center">7</td> <td align="center"><a href="https://www.codechef.com/submit/DOLL">Red Light, Green Light</a></td> </tr> <tr> <td align="center">8</td> <td align="center"><a href="https://www.codechef.com/submit/MATCHES">Playing with Matches</a></td> </tr> </table> <br> <pre>Level: 1000 - 1200</pre> <table> <tr> <th align="center" colspan=2>Arrays</th> <tr> <tr> <th align="center">S.no</th> <th align="center">Question List</th> <tr> <tr> <td align="center">1</td> <td align="center"><a href="https://www.codechef.com/submit/MISSP">Chef and Dolls</a></td> </tr> <tr> <td align="center">2</td> <td align="center"><a href="https://www.codechef.com/submit/CFRTEST">Devu and friendship testing</a></td> </tr> <tr> <td align="center">3</td> <td align="center"><a href="https://www.codechef.com/submit/WATSCORE">That Is My Score!</a></td> </tr> </table><file_sep>/0-1000/arrays/array7.cpp /* ※ Title :- Arrays ※ Author :- <NAME> ※ Date :- 3 October 2022 ※ Question 7 :- Red Light, Green Light ※ Link:- https://www.codechef.com/submit/DOLL */ #include <iostream> using namespace std; void solution() { int noOfPlayers; cin >> noOfPlayers; int height; cin >> height; int *arr = new int[noOfPlayers]; for (int i = 0; i < noOfPlayers; i++) { cin >> arr[i]; } int toBeShot; for (int i = 0; i < noOfPlayers; i++) { if (arr[i] > height) { toBeShot++; } } cout << toBeShot << "\n"; delete arr; } int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL); int testCases; cin >> testCases; while (testCases--) { solution(); } return 0; } /* ------------------------ ✥ Problem Statement ------------------------ “You won’t get caught if you hide behind someone.” Sang-Woo advises Gi-Hun to hide behind someone to avoid getting shot. Gi-Hun follows Sang-Woo's advice and hides behind Ali, who saved his life earlier. Gi-Hun and Ali both have the same height, K. Many players saw this trick and also started hiding behind Ali. Now, there are N players standing between Gi-Hun and Ali in a straight line, with the i^th player having height H(i) Gi-Hun wants to know the minimum number of players who need to get shot so that Ali is visible in his line of sight. -------------- Note: -------------- • Line of sight is a straight line drawn between the topmost point of two objects. Ali is visible to Gi-Hun if nobody between them crosses this line. • Even if there are some players who have the same height as that of Gi-Hun and Ali, Ali will be visible in Gi-Hun's line of sight. • Gi-Hun and Ali have the same height. ------------------------ ✥ Input Format ------------------------ • The first line of input contains a single integer T, denoting the number of test cases. The description of T test cases follows. • The first line of each test case contains two space-separated integers N and K, denoting the total number of players between Gi-Hun and Ali and the height of both of them respectively. • The second line of each test case contains NN space-separated integers, denoting the heights of the players between Gi-Hun and Ali. ------------------------ ✥ Output Format ------------------------ For each test case, output in a single line the minimum number of players who need to get shot so that Ali is visible in Gi-Hun's line of sight. */<file_sep>/0-1000/arrays/array1.cpp /* ※ Title :- Arrays ※ Author :- <NAME> ※ Date :- 30 September 2022 ※ Question 1 :- Practice makes us perfect ※ Link:- https://www.codechef.com/submit/PRACTICEPERF */ #include <iostream> using namespace std; int main() { int count = 0; int arr[4]; for (int i = 0; i < 4; i++) { cin >> arr[i]; } for (int i = 0; i < 4; i++) { if (arr[i] >= 10) { count++; } } cout << count << endl; return 0; } /* ------------------------ Problem Statement ------------------------ Most programmers will tell you that one of the ways to improve your performance in competitive programming is to practice a lot of problems. Our Chef took the above advice very seriously and decided to set a target for himself. ** Chef decides to solve at least 10 problems every week for 4 weeks. Given the number of problems he actually solved in each week over 4 weeks as P1, P2, P3, P4 output the number of weeks in which Chef met his target. ------------------------ Input Format ------------------------ There is a single line of input, with 4 integers P1, P2, P3, P4. These are the number of problems solved by Chef in each of the 44 weeks. ------------------------ Output Format ------------------------ Output a single integer in a single line - the number of weeks in which Chef solved at least 1010 problems. */ <file_sep>/0-1000/arrays/array6.cpp /* ※ Title :- Arrays ※ Author :- <NAME> ※ Date :- 3 October 2022 ※ Question 6 :- Make all equal using Pairs ※ Link:- https://www.codechef.com/submit/PAIREQ */ #include <iostream> #include <vector> #include <map> using namespace std; void solution() { int n; cin >> n; vector<int> arr(n); for (int i = 0; i < n; i++) { cin >> arr[i]; } map<int, int> freq; for (auto element : arr) { freq[element]++; } int max_count = 0; for (auto element : freq) { max_count = max(max_count, element.second); } cout << n - max_count << "\n"; } int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL); int testCases; cin >> testCases; while (testCases--) { solution(); } return 0; } /* ------------------------ ✥ Problem Statement ------------------------ Chef has an array A of length N. In one operation, Chef can choose any two distinct indices i,j (1 <= i, j <= N, i!=j) and either change A(i) to A(j) or change A(j) to A(i). Find the minimum number of operations required to make all the elements of the array equal. ------------------------ ✥ Input Format ------------------------ • First line will contain T, number of test cases. Then the test cases follow. • First line of each test case consists of an integer N - denoting the size of array A. • Second line of each test case consists of N space-separated integers A(1), A(2).....A(n) - denoting the array A, ------------------------ ✥ Output Format ------------------------ For each test case, output the minimum number of operations required to make all the elements equal. */<file_sep>/1000-1200/arrays/array1.cpp /* ※ Title :- Arrays ※ Author :- <NAME> ※ Date :- 4 October 2022 ※ Question 1 :- Chef and Dolls ※ Link:- https://www.codechef.com/submit/MISSP */ #include <iostream> #include <map> using namespace std; void solution() { int elements; cin >> elements; map<int, int> frequency; // making a frequency table for (int i = 0; i < elements; i++) { int type; cin >> type; frequency[type]++; } for (auto p : frequency) { int key = p.first; int value = p.second; if (value % 2 == 1) { cout << key << "\n"; return; } } } int main() { int testCases; cin >> testCases; while (testCases--) { solution(); } return 0; } /* ------------------------ ✥ Problem Statement ------------------------ Chef is fan of pairs and he likes all things that come in pairs. He even has a doll collection in which the dolls come in pairs. One day while going through his collection he found that there are odd number of dolls. Someone had stolen a doll!!! Help chef find which type of doll is missing.. ------------------------ ✥ Input Format ------------------------ • The first line contains an integer T, the number of test cases. • The first line of each test case contains an integer N, the number of dolls. • The next N lines are the types of dolls that are left. ------------------------ ✥ Output Format ------------------------ For each test case, display the type of doll that doesn't have a pair, in a new line. */<file_sep>/1000-1200/arrays/array3.cpp /* ※ Title :- Arrays ※ Author :- <NAME> ※ Date :- 5 October 2022 ※ Question 2 :- That Is My Score! ※ Link:- https://www.codechef.com/submit/WATSCORE */ #include <iostream> #include <vector> using namespace std; void solution() { int noOfSubmissions; cin >> noOfSubmissions; vector<int> max_marks(12, 0); for (int i = 0; i < noOfSubmissions; i++) { int subject, marks; cin >> subject >> marks; max_marks[subject] = max(max_marks[subject], marks); } int totalScore = 0; for (int i = 1; i <= 8; i++) { totalScore += max_marks[i]; } cout << totalScore << "\n"; } int main() { int testCases; cin >> testCases; while (testCases--) { solution(); } return 0; } /* ----------------------- ✥ Problem Statement ----------------------- You are participating in a contest which has 1111 problems (numbered 11 through 1111). The first eight problems (i.e. problems 1, 2, \ldots, 81,2,…,8) are scorable, while the last three problems (99, 1010 and 1111) are non-scorable ― this means that any submissions you make on any of these problems do not affect your total score. Your total score is the sum of your best scores for all scorable problems. That is, for each scorable problem, you look at the scores of all submissions you made on that problem and take the maximum of these scores (or 0 if you didn't make any submissions on that problem); the total score is the sum of the maximum scores you took.) You know the results of all submissions you made. Calculate your total score. ------------------------ ✥ Input Format ------------------------ • The first line contains an integer T, the number of test cases. • The first line of each test case contains a single integer N denoting the number of submissions you made. • N lines follow. For each i(1 <= i <= N) the i-th of these lines contains two space-separated integers p(i) and s(i) denoting that your i-th submission was on problem p(i) and it received a score of s(i) ​ ------------------------ ✥ Output Format ------------------------ For each test case, print a single line containing one integer ― your total score. */<file_sep>/0-1000/arrays/array3.cpp /* ※ Title :- Arrays ※ Author :- <NAME> ※ Date :- 30 September 2022 ※ Question 3 :- Recent contest problems ※ Link:- https://www.codechef.com/submit/RECENTCONT */ #include <iostream> #include <string> using namespace std; int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL); int testCases; cin >> testCases; string contest1 = "START38"; string contest2 = "LTIME108"; while (testCases--) { int noOfProblems; cin >> noOfProblems; string contestName; int start38 = 0; int ltime108 = 0; for (int i = 0; i < noOfProblems; i++) { cin >> contestName; if (contestName == contest1) { start38++; } else if (contestName == contest2) { ltime108++; } } cout << start38 << " " << ltime108 << endl; } return 0; } /* ---------------------------------------------------- Problem Statement ---------------------------------------------------- Chef has been participating regularly in rated contests but missed the last two contests due to his college exams. He now wants to solve them and so he visits the practice page to view these problems. Given a list of N contest codes, where each contest code is either START38 or LTIME108, help Chef count how many problems were featured in each of the contests. ---------------------------------------------------- Input Format ---------------------------------------------------- ✥ First line will contain T, number of test cases. Then the test cases follow. ✥ Each test case contains of two lines of input. ✥ First line of input contains the total count of problems that appeared in the two recent contests - N. ✥ Second line of input contains the list of N contest codes. Each code is either START38 or LTIME108, to which each problem belongs. ---------------------------------------------------- Output Format ---------------------------------------------------- For each test case, output two integers in a single new line - the first integer should be the number of problems in START38, and the second integer should be the number of problems in LTIME108. */ <file_sep>/0-1000/arrays/array5.cpp /* ※ Title :- Arrays ※ Author :- <NAME> ※ Date :- 1 October 2022 ※ Question 5 :- Counting Pretty Numbers ※ Link:- https://www.codechef.com/submit/NUM239 */ #include <iostream> using namespace std; int main() { int testCases; cin >> testCases; while (testCases--) { int range1, range2; cin >> range1 >> range2; int count = 0; for (int i = range1; i <= range2; i++) { if (i % 10 == 2 || i % 10 == 3 || i % 10 == 9) { count++; } } cout << count << endl; } return 0; } /* ------------------------ ✥ Problem Statement ------------------------ Vasya likes the number 2,3,9. Therefore, he considers a number pretty if its last digit is 2, 3 or 9. Vasya wants to watch the numbers between L and R (both inclusive). So he asked you to determine how many pretty numbers are in this range. Can you help him? ------------------------ ✥ Input Format ------------------------ The first line of the input contains a single integer T denoting the number of test cases. The description of T test cases follows. The first and only line of each test case contains two space-separated integers L and R. ------------------------ ✥ Output Format ------------------------ For each test case, print a single line containing one integer — the number of pretty numbers between L and R. */ <file_sep>/0-1000/arrays/array2.cpp /* ※ Title :- Arrays ※ Author :- <NAME> ※ Date :- 30 September 2022 ※ Question 2 :- Problems in your to-do list ※ Link:- https://www.codechef.com/submit/TODOLIST */ #include <iostream> using namespace std; int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL); int testCases; cin >> testCases; while (testCases--) { int remove = 0; int toDoListSize; cin >> toDoListSize; for (int i = 0; i < toDoListSize; i++) { int n; cin >> n; if (n >= 1000) { remove++; } } cout << remove << endl; } return 0; } /* ------------------------ Problem Statement ------------------------ Like most users, Chef didn’t know that he could add problems to a personal to-do list by clicking on the magic '+' symbol on the top-right of each problem page. But once he found out about it, he went crazy and added loads of problems to his to-do list without looking at their difficulty rating. Chef is a beginner and should ideally try and solve only problems with difficulty rating strictly less than 1000. Given a list of difficulty ratings for problems in the Chef’s to-do list, please help him identify how many of those problems Chef should remove from his to-do list, so that he is only left with problems of difficulty rating less than 1000. ------------------------ Input Format ------------------------ ✥ The first line of input will contain a single integer T, the number of test cases. Then the testcases follow. ✥ Each testcase consists of 2 lines of input. ✥ The first line of input of each test case contains a single integer, N, which is the total number of problems that the Chef has added to his to-do list. ✥ The second line of input of each test case contains N space-separated integers D1, D2.....Dn, which are the difficulty ratings for each problem in the to-do list. ------------------------ Output Format ------------------------ For each test case, output in a single line the number of problems that Chef will have to remove so that all remaining problems have a difficulty rating strictly less than 1000 */ <file_sep>/0-1000/arrays/array4.cpp /* ※ Title :- Arrays ※ Author :- <NAME> ※ Date :- 30 September 2022 ※ Question 4 :- The Lead Game ※ Link:- https://www.codechef.com/submit/TLG */ #include <iostream> using namespace std; int main() { int t = 0; cin >> t; int sum1 = 0, sum2 = 0, maxLead = 0, winner = 0, a, b; for (int i = 0; i < t; i++) { cin >> a >> b; sum1 = sum1 + a; sum2 = sum2 + b; if (sum1 > sum2 && sum1 - sum2 > maxLead) { maxLead = sum1 - sum2; winner = 1; } else if (sum2 - sum1 > maxLead) { maxLead = sum2 - sum1; winner = 2; } } cout << winner << " " << maxLead; return 0; } /* ------------------------ Problem Statement ------------------------ The game of billiards involves two players knocking 3 balls around on a green baize table. Well, there is more to it, but for our purposes this is sufficient. The game consists of several rounds and in each round both players obtain a score, based on how well they played. Once all the rounds have been played, the total score of each player is determined by adding up the scores in all the rounds and the player with the higher total score is declared the winner. The Siruseri Sports Club organizes an annual billiards game where the top two players of Siruseri play against each other. The Manager of Siruseri Sports Club decided to add his own twist to the game by changing the rules for determining the winner. In his version, at the end of each round, the cumulative score for each player is calculated, and the leader and her current lead are found. Once all the rounds are over the player who had the maximum lead at the end of any round in the game is declared the winner. Consider the following score sheet for a game with 5 rounds: |--------|------------|------------| | Round | Player 1 | Player 2 | |--------|------------|------------| | 1 | 140 | 82 | | 2 | 89 | 134 | | 3 | 90 | 110 | | 4 | 112 | 106 | | 5 | 88 | 90 | |--------|------------|------------| The total scores of both players, the leader and the lead after each round for this game is given below: |--------|-------------|------------|-----------|----------| | Round | Player 1 | Player 2 | Leader | Lead | |--------|-------------|------------|-----------|----------| | 1 | 140 | 82 | Player 1 | 58 | | 2 | 229 | 216 | Player 1 | 13 | | 3 | 319 | 326 | Player 2 | 7 | | 4 | 431 | 432 | Player 2 | 1 | | 5 | 519 | 522 | Player 2 | 3 | |--------|-------------|------------|-----------|----------| Note that the above table contains the cumulative scores. The winner of this game is Player 1 as he had the maximum lead (58 at the end of round 1) during the game. Your task is to help the Manager find the winner and the winning lead. You may assume that the scores will be such that there will always be a single winner. That is, there are no ties. ------------------------ Input Format ------------------------ The first line of the input will contain a single integer N (N ≤ 10000) indicating the number of rounds in the game. Lines 2,3,...,N+1 describe the scores of the two players in the N rounds. Line i+1 contains two integer Si and Ti, the scores of the Player 1 and 2 respectively, in round i. You may assume that 1 ≤ Si ≤ 1000 and 1 ≤ Ti ≤ 1000. ------------------------ Output Format ------------------------ Your output must consist of a single line containing two integers W and L, where W is 1 or 2 and indicates the winner and L is the maximum lead attained by the winner. */ <file_sep>/1000-1200/arrays/array2.cpp /* ※ Title :- Arrays ※ Author :- <NAME> ※ Date :- 4 October 2022 ※ Question 2 :- Devu and friendship testing ※ Link:- https://www.codechef.com/submit/CFRTEST */ #include <iostream> #include <set> using namespace std; int main() { int tests; cin >> tests; while (tests--) { int noOfFriends; cin >> noOfFriends; int *arr = new int[noOfFriends]; set<int> distinct; for (int i = 0; i < noOfFriends; i++) { cin >> arr[i]; distinct.insert(arr[i]); } cout << distinct.size() << "\n"; } return 0; } /* ----------------------- ✥ Problem Statement ----------------------- Devu has n weird friends. Its his birthday today, so they thought that this is the best occasion for testing their friendship with him. They put up conditions before Devu that they will break the friendship unless he gives them a grand party on their chosen day. Formally, i(th) friend will break his friendship if he does not receive a grand party on d(ith) day. Devu despite being as rich as Gatsby, is quite frugal and can give at most one grand party daily. Also, he wants to invite only one person in a party. So he just wonders what is the maximum number of friendships he can save. Please help Devu in this tough task !! ------------------------ ✥ Input Format ------------------------ • The first line of the input contains an integer T denoting the number of test cases. The description of T test cases follows. • First line will contain a single integer denoting n • Second line will contain n space separated integers where i(th) integer corresponds to the day d(ith) as given in the problem. ------------------------ ✥ Output Format ------------------------ Print a single line corresponding to the answer of the problem. */<file_sep>/0-1000/arrays/array8.cpp /* ※ Title :- Arrays ※ Author :- <NAME> ※ Date :- 3 October 2022 ※ Question 8 :- Playing with Matches ※ Link:- https://www.codechef.com/submit/MATCHES */ #include <iostream> using namespace std; void solution(int *matchSticks) { int A, B, sum, digitSum = 0, digit = 0; cin >> A >> B; sum = A + B; while (sum) { digit = sum % 10; digitSum += matchSticks[digit]; sum = sum / 10; } cout << digitSum << "\n"; } int main() { int matchSticks[10] = {6, 2, 5, 5, 4, 5, 6, 3, 7, 6}; int testCases; cin >> testCases; while (testCases--) { solution(matchSticks); } return 0; } /* ------------------------ ✥ Problem Statement ------------------------ Chef's son Chefu found some matches in the kitchen and he immediately starting playing with them. The first thing Chefu wanted to do was to calculate the result of his homework — the sum of A and B, and write it using matches. Help Chefu and tell him the number of matches needed to write the result. ------------------------ ✥ Input Format ------------------------ • The first line of the input contains a single integer T denoting the number of test cases. The description of T test cases follows. • For each test case, print a single line containing one integer — the number of matches needed to write the result (A+B). ------------------------ ✥ Output Format ------------------------ For each test case, output the minimum number of operations required to make all the elements equal. */
6ed99983ca4bbe44c991a6b0658b350d82802269
[ "Markdown", "C++" ]
12
Markdown
gautam-07/Code-Chef
272512213be9915dcffb523e540e3c06ba3d84db
a8c05f009ac4d09fb84a6965c205f1d846e55573
refs/heads/master
<file_sep># VideoChat27 This is a basic Video Chat app with one on one video chat feature. I have used Nodejs for backend and ReactJs for frontend. Along with this I have used Simple-peer from WebRTC for peer to peer communication. The Demo for this is deployed at https://kdvideochat.netlify.app/ Some of the basic features are:- - Call Your Friend using Call button by Entering your name and your Friend's id. - Mute and Disable Video Options. - The Video Button on the top beside the Heading, takes the user to the part of the web where he/she can start a call or end a call, rather than scrolling to this part. - The user receives an alert if he/she tries to call without entering name or id. <file_sep>import React, { useContext } from 'react'; import { SocketContext } from '../SocketContext'; import Button from '@material-ui/core/Button'; import CallIcon from '@material-ui/icons/Call'; import CallEndIcon from '@material-ui/icons/CallEnd'; function Notifications() { const { answerCall, call, callAccepted, rejectCall } = useContext(SocketContext); return ( <> {call.isReceivingCall && !callAccepted && ( <div style={{ display: 'flex', justifyContent: 'space-around' }}> <h1>{call.name} is calling:</h1> <Button variant="contained" color="primary" startIcon={<CallIcon fontSize="large" />} size="medium" onClick={answerCall}> Accept </Button> <Button variant="contained" color="secondary" startIcon={<CallEndIcon fontSize="large" />} size="medium" onClick={rejectCall}> Reject </Button> </div> )} </> ); }; export default Notifications;<file_sep>import React, { useRef} from 'react'; import { Typography, AppBar } from '@material-ui/core'; import { makeStyles } from '@material-ui/core/styles'; import VideoPlayer from './components/VideoPlayer'; import Options from './components/Options'; import Notifications from './components/Notifications'; import VideoCallOutlinedIcon from '@material-ui/icons/VideoCall'; import IconButton from '@material-ui/core/IconButton'; const useStyles = makeStyles((theme) => ({ //Title styling vidIcon: { '& svg': { fontSize: 100 } }, appBar: { background: 'linear-gradient(45deg, #FE6B8B 30%, #FF8E53 90%)', // borderRadius: 15, boxShadow: '0 3px 5px 2px rgba(255, 105, 135, .3)', color: 'white', display: 'flex', flexDirection: 'row', justifyContent: 'center', alignItems: 'center', }, overall: { display: 'flex', flexDirection: 'column', alignItems: 'center', width: '100%', }, })); function App(){ const classes = useStyles(); const vidRef = useRef(); return( <div className={classes.overall}> <AppBar className={classes.appBar} position="static" color="inherit"> <IconButton className={classes.vidIcon} onClick={() =>{ vidRef.current.scrollIntoView({ behavior: 'smooth' }) } } > <VideoCallOutlinedIcon /> </IconButton> <Typography variant="h1" align="center">KD Video Chat</Typography> </AppBar> <VideoPlayer /> <div ref={vidRef}> <Options > <Notifications /> </Options> </div> </div> ) } export default App; <file_sep>import React, { useContext } from 'react'; import { Grid, Typography, Paper, makeStyles } from '@material-ui/core'; import { SocketContext } from '../SocketContext'; import MicIcon from '@material-ui/icons/Mic'; import MicOffIcon from '@material-ui/icons/MicOff'; import Button from '@material-ui/core/Button'; import VideocamIcon from '@material-ui/icons/Videocam'; import VideocamOffIcon from '@material-ui/icons/VideocamOff'; const useStyles = makeStyles((theme) => ({ video: { width: '600px', [theme.breakpoints.down('xs')]: { width: '250px', }, }, gridContainer: { justifyContent: 'center', [theme.breakpoints.down('xs')]: { flexDirection: 'column', }, }, paper: { padding: '10px', border: '2px solid black', margin: '10px', }, padding: { width:"100px", padding: "20px" } })); function VideoPlayer() { const { name, callAccepted, myVideo, userVideo, callEnded, stream, call, micswitch,videoswitch, toggleMic, toggleVideo} = useContext(SocketContext); const classes = useStyles(); return ( <Grid container className={classes.gridContainer}> {stream && ( <Paper className={classes.paper} variant="outlined"> <Grid item xs={12} md={6} > <Typography variant="h5" gutterBottom>{name || 'Name'}</Typography> <video playsInline muted ref={myVideo} autoPlay className={classes.video} /> <Grid container className={classes.video} spacing={3} > <Grid item xs={6} className={classes.padding}> {!micswitch ? (<Button variant="contained" color="primary" startIcon={<MicIcon fontSize="large" />} fullWidth onClick={toggleMic} > Mute </Button>) : (<Button variant="contained" color="secondary" startIcon={<MicOffIcon fontSize="large" />} fullWidth onClick={toggleMic} > Unmute </Button> )} </Grid> <Grid item xs={6} className={classes.padding}> {!videoswitch ? (<Button variant="contained" color="primary" startIcon={<VideocamIcon fontSize="large" />} fullWidth onClick={toggleVideo} > Disable Video </Button>) : (<Button variant="contained" color="secondary" startIcon={<VideocamOffIcon fontSize="large" />} fullWidth onClick={toggleVideo} > Enable Video </Button> )} </Grid> </Grid> </Grid> </Paper> )} {callAccepted && !callEnded && ( <Paper className={classes.paper} variant = "outlined"> <Grid item xs={12} md={6}> <Typography variant="h5" gutterBottom>{call.name || 'Name'}</Typography> <video playsInline ref={userVideo} autoPlay className={classes.video} /> </Grid> </Paper> )} </Grid> ); }; export default VideoPlayer;
1685af5c55b6a79f0c994e4241052fd9e73b73a5
[ "Markdown", "JavaScript" ]
4
Markdown
karthikedar/VideoChat27
6528c662aec5b3f36129514e852f76f07ce7ffd9
3a27768b734870f40f87c65ad80b8fa92d260057
refs/heads/master
<file_sep>{_id:1,name:"Álava",region_id:17}, {_id:2,name:"Albacete",region_id:7}, {_id:3,name:"Alicante",region_id:18}, {_id:4,name:"Almería",region_id:1}, {_id:5,name:"Ávila",region_id:6}, {_id:6,name:"Badajoz",region_id:10}, {_id:7,name:"<NAME>",region_id:4}, {_id:8,name:"Barcelona",region_id:8}, {_id:9,name:"Burgos",region_id:6}, {_id:10,name:"Cáceres",region_id:10}, {_id:11,name:"Cádiz",region_id:1}, {_id:12,name:"Castellón",region_id:18}, {_id:13,name:"<NAME>",region_id:7}, {_id:14,name:"Córdoba",region_id:1}, {_id:15,name:"<NAME>",region_id:11}, {_id:16,name:"Cuenca",region_id:7}, {_id:17,name:"Girona",region_id:8}, {_id:18,name:"Granada",region_id:1}, {_id:19,name:"Guadalajara",region_id:7}, {_id:20,name:"Guipúzcoa",region_id:17}, {_id:21,name:"Huelva",region_id:1}, {_id:22,name:"Huesca",region_id:2}, {_id:23,name:"Jaén",region_id:1}, {_id:24,name:"León",region_id:6}, {_id:25,name:"Lleida",region_id:8}, {_id:26,name:"<NAME>",region_id:13}, {_id:27,name:"Lugo",region_id:11}, {_id:28,name:"Madrid",region_id:14}, {_id:29,name:"Málaga",region_id:1}, {_id:30,name:"Murcia",region_id:15}, {_id:31,name:"Navarra",region_id:16}, {_id:32,name:"Ourense",region_id:11}, {_id:33,name:"Asturias",region_id:3}, {_id:34,name:"Palencia",region_id:6}, {_id:35,name:"<NAME>",region_id:12}, {_id:36,name:"Pontevedra",region_id:11}, {_id:37,name:"Salamanca",region_id:6}, {_id:38,name:"<NAME>",region_id:12}, {_id:39,name:"Cantabria",region_id:5}, {_id:40,name:"Segovia",region_id:6}, {_id:41,name:"Sevilla",region_id:1}, {_id:42,name:"Soria",region_id:6}, {_id:43,name:"Tarragona",region_id:8}, {_id:44,name:"Teruel",region_id:2}, {_id:45,name:"Toledo",region_id:7}, {_id:46,name:"Valencia",region_id:18}, {_id:47,name:"Valladolid",region_id:6}, {_id:48,name:"Vizcaya",region_id:17}, {_id:49,name:"Zamora",region_id:6}, {_id:50,name:"Zaragoza",region_id:2}, {_id:51,name:"Ceuta",region_id:9}, {_id:52,name:"Mellila",region_id:19}<file_sep>-- Users INSERT INTO users(USERNAME,PASSWORD,ENABLED)VALUES('admin','admin',1); INSERT INTO authorities(USERNAME,AUTHORITY)VALUES('admin','administrator'); -- regions INSERT INTO regions VALUES (1,'Andalucía'); INSERT INTO regions VALUES (2,'Aragón'); INSERT INTO regions VALUES (3,'Principado de Asturias'); INSERT INTO regions VALUES (4,'Illes Balears'); INSERT INTO regions VALUES (5,'Cantabria'); INSERT INTO regions VALUES (6,'Castilla y León'); INSERT INTO regions VALUES (7,'Castilla-La Mancha'); INSERT INTO regions VALUES (8,'Cataluña'); INSERT INTO regions VALUES (9,'Ciudad de Ceuta'); INSERT INTO regions VALUES (10,'Extremadura'); INSERT INTO regions VALUES (11,'Galicia'); INSERT INTO regions VALUES (12,'Canarias'); INSERT INTO regions VALUES (13,'La Rioja'); INSERT INTO regions VALUES (14,'Comunidad de Madrid'); INSERT INTO regions VALUES (15,'Región de Murcia'); INSERT INTO regions VALUES (16,'Comunidad Foral de Navarra'); INSERT INTO regions VALUES (17,'País Vasco'); INSERT INTO regions VALUES (18,'Comunitat Valenciana'); INSERT INTO regions VALUES (19,'Ciudad de Melilla'); commit; <file_sep>package net.mikasa.mikasaweb.config; import java.util.Properties; import javax.sql.DataSource; import org.apache.catalina.startup.Tomcat; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.boot.context.embedded.tomcat.TomcatEmbeddedServletContainer; import org.springframework.boot.context.embedded.tomcat.TomcatEmbeddedServletContainerFactory; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseBuilder; import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseType; import org.springframework.orm.jpa.JpaTransactionManager; import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean; import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter; @Configuration @EnableAutoConfiguration @ComponentScan("net.mikasa.mikasaweb") public class ITTestConfiguration { @Bean public DataSource dataSource() { return new EmbeddedDatabaseBuilder().setType(EmbeddedDatabaseType.H2).build(); } @Bean public LocalContainerEntityManagerFactoryBean entityManagerFactory() { LocalContainerEntityManagerFactoryBean entityManagerFactoryBean = new LocalContainerEntityManagerFactoryBean(); entityManagerFactoryBean.setDataSource(dataSource()); entityManagerFactoryBean.setJpaVendorAdapter(new HibernateJpaVendorAdapter()); entityManagerFactoryBean.setPackagesToScan("net.mikasa.mikasaweb"); entityManagerFactoryBean.setJpaProperties(jpaProperties()); return entityManagerFactoryBean; } private Properties jpaProperties() { Properties properties = new Properties(); properties.setProperty("hibernate.hbm2ddl.auto","create"); properties.setProperty("hibernate.dialect","org.hibernate.dialect.H2Dialect"); //properties.setProperty("hibernate.show_sql","true"); //properties.setProperty("hibernate.format_sql","true"); return properties; } @Bean public JpaTransactionManager transactionManager() { JpaTransactionManager transactionManager = new JpaTransactionManager(); transactionManager.setEntityManagerFactory(entityManagerFactory().getObject()); transactionManager.setDataSource(dataSource()); return transactionManager; } @Bean public TomcatEmbeddedServletContainerFactory tomcatFactory() { return new TomcatEmbeddedServletContainerFactory() { @Override protected TomcatEmbeddedServletContainer getTomcatEmbeddedServletContainer(Tomcat tomcat) { tomcat.enableNaming(); return super.getTomcatEmbeddedServletContainer(tomcat); } }; } } <file_sep>buildscript { repositories { jcenter() } dependencies { classpath 'org.springframework.boot:spring-boot-gradle-plugin:1.5.8.RELEASE' classpath 'org.unbroken-dome.gradle-plugins:gradle-testsets-plugin:1.4.2' } } plugins { id 'java' id 'org.unbroken-dome.test-sets' version '1.4.2' id 'eclipse-wtp' id 'org.springframework.boot' version '1.5.8.RELEASE' id 'war' id 'maven-publish' } repositories { jcenter() } //Manifest config war { manifest{ attributes( "Implementation-Title": project.description, "Implementation-Version": version, "Build-date": new Date().format('dd-MM-yyyy HH:mm:ss'), "Build-by": System.properties.'user.name', "git-revision": "git rev-parse --short HEAD".execute().text.trim(), "git-branch": "git status -bs -u no".execute().text.trim() ) } } //Integration tests config testSets { integrationTest } check.dependsOn integrationTest integrationTest.mustRunAfter test tasks.withType(Test) { reports.html.destination = file("${reporting.baseDir}/${name}") } project.integrationTest { outputs.upToDateWhen { false } } tasks.withType(Test) { reports.html.destination = file("${reporting.baseDir}/${name}") } test { afterTest { desc, result -> println "Executing test [${desc.className}].${desc.name} with result: ${result.resultType}" } } integrationTest { afterTest { desc, result -> println "Executing test [${desc.className}].${desc.name} with result: ${result.resultType}" } } dependencies { testCompile 'org.springframework.boot:spring-boot-starter-test' testCompile 'com.h2database:h2:1.4.182' testCompile 'org.seleniumhq.selenium:selenium-server:3.7.1' integrationTestCompile 'org.springframework.boot:spring-boot-starter-test' integrationTestCompile 'com.h2database:h2:1.4.182' integrationTestCompile 'org.seleniumhq.selenium:selenium-server:3.7.1' compile 'org.springframework.boot:spring-boot-devtools' compile 'org.webjars:bootstrap:3.3.0' compile 'mysql:mysql-connector-java:5.0.5' compile 'org.apache.tomcat:dbcp:6.0.53' compile 'org.springframework.boot:spring-boot-starter-web' compile 'org.springframework.boot:spring-boot-starter-security' compile 'org.springframework.boot:spring-boot-starter-data-jpa' compile 'org.springframework.boot:spring-boot-starter-thymeleaf' } /* * Nexus Publishing Info * Define following environment variables (local or inside jenkins config): * nexusUser: Nexus deployer username * nexusPassword: Nexus deployer password * nexusSnapshotsURL: Nexus Snapshots repo URL * nexusReleasesURL: Nexus Releases repo URL * Usage: gradle publishSnapshotPublicationToNexusSnapshotsRepository (snapshots) * gradle publishReleasePublicationToNexusReleasesRepository (releases) */ publishing { def nexusUser = System.getenv('nexusUser') def nexusPassword = System.getenv('nexusPassword') def artifact = rootProject.name repositories { maven { name 'NexusSnapshots' url System.getenv('nexusSnapshotsURL') credentials { username nexusUser password <PASSWORD> } } maven { name 'NexusReleases' url System.getenv('nexusReleasesURL') credentials { username nexusUser password <PASSWORD> } } } publications { snapshot(MavenPublication) { artifactId artifact from components.web ext.repo = 'NexusSnapshots' } release(MavenPublication) { artifactId artifact from components.web ext.repo = 'NexusReleases' } } }<file_sep>package net.mikasa.mikasaweb.model; // Generated 05-nov-2013 12:29:25 by Hibernate Tools 3.2.2.GA import javax.persistence.AttributeOverride; import javax.persistence.AttributeOverrides; import javax.persistence.Column; import javax.persistence.EmbeddedId; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.Table; import javax.persistence.UniqueConstraint; /** * Authority generated by hbm2java */ @Entity @Table(name="authorities" , uniqueConstraints = @UniqueConstraint(columnNames={"username", "authority"}) ) public class Authority implements java.io.Serializable { private static final long serialVersionUID = -5062379823861458659L; private AuthorityId id; private User user; public Authority() { } public Authority(AuthorityId id, User user) { this.id = id; this.user = user; } @EmbeddedId @AttributeOverrides( { @AttributeOverride(name="username", column=@Column(name="username", nullable=false, length=10) ), @AttributeOverride(name="authority", column=@Column(name="authority", nullable=false, length=50) ) } ) public AuthorityId getId() { return this.id; } public void setId(AuthorityId id) { this.id = id; } @ManyToOne(fetch=FetchType.LAZY) @JoinColumn(name="username", nullable=false, insertable=false, updatable=false) public User getUser() { return this.user; } public void setUser(User user) { this.user = user; } } <file_sep>package net.mikasa.mikasaweb.dao; import org.junit.Test; import org.springframework.beans.factory.annotation.Autowired; import static org.assertj.core.api.Assertions.*; import net.mikasa.mikasaweb.config.GenericTest; import net.mikasa.mikasaweb.model.User; public class UserDAOTest extends GenericTest{ @Autowired private UserDAO userDAO; @Test public void testfindByUsername() { User user = userDAO.findByUsername("admin"); assertThat(user.getPassword()).isEqualTo("<PASSWORD>"); } }<file_sep>footerText=This text is defined in the MessageResource.properties file application.name=mikasaweb application.menu.dashboard=dashboard application.copyright=(c)2014 mikasa.net<file_sep>insert into users (username,password,enabled) values ('admin','admin',1); insert into authorities(username,authority) values ('admin','administrator'); INSERT INTO regions VALUES (1,'Andalucía'); INSERT INTO regions VALUES (2,'Aragón'); INSERT INTO regions VALUES (3,'Principado de Asturias'); INSERT INTO regions VALUES (4,'Illes Balears'); INSERT INTO regions VALUES (5,'Cantabria'); commit; <file_sep>package net.mikasa.mikasaweb.controller; import net.mikasa.mikasaweb.bean.UserBean; import net.mikasa.mikasaweb.model.Region; import net.mikasa.mikasaweb.service.RegionService; import java.util.List; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.RequestMapping; @Controller public class HomeController { private static Logger log = LoggerFactory.getLogger(HomeController.class); @Autowired private RegionService regionService; @Autowired private UserBean userBean; @ModelAttribute("user") public String getUser() { return userBean.getUser().getUsername(); } @ModelAttribute("regions") public List<Region> getAllRegions(){ return regionService.findAll(); } @RequestMapping("/") public String showHomePage(Model model) { //String appVersion = Manifests.read("Implementation-Version"); //model.addAttribute("appVersion",appVersion); return "index"; } } <file_sep># -*- mode: ruby -*- # vi: set ft=ruby : require 'yaml' settings = YAML.load_file('provisioning/config.yaml') ENV["DEBIAN_FRONTEND"] = 'noninteractive' ENV["LC_ALL"] = settings['locale_lc_all'] ENV["LANG"] = settings['locale_lang'] ports = settings['ports'] Vagrant.configure(2) do |config| config.vm.box = settings['box_name'] ports.each do |forwarded_port| config.vm.network "forwarded_port", guest: forwarded_port['guestPort'], host: forwarded_port['hostPort'] #config.vm.network "private_network", type: "dhcp" #config.vm.network "private_network", ip: "10.0.2.16" end config.vm.provider "virtualbox" do |vb| vb.name = settings['vb_name'] vb.memory = settings['vb_memory'] vb.cpus = settings['vb_cpus'] #vb.customize ["modifyvm", :id, "--cableconnected1", "on"] vb.gui = false end config.vm.hostname = settings['host_name'] #Needed to avoid 'Inappropriate ioctl for device' error message config.ssh.shell = "bash -c 'BASH_ENV=/etc/profile exec bash'" provision = settings['provisioning'] if (provision == 'ansible') config.vm.provision "ansible" do |ansible| ansible.playbook = "provisioning/ansible/playbook.yml" ansible.galaxy_role_file = "provisioning/ansible/requirements.yml" ansible.galaxy_roles_path = settings['roles_path'] end end if (provision == 'puppet') config.vm.provision "shell", path: "provisioning/puppet/bootstrap.sh" config.vm.provision "puppet" do |puppet| puppet.options = "--verbose" #puppet.options = "--debug" puppet.environment_path = "provisioning/puppet/environments" puppet.environment = "production" end end end <file_sep>println '--------------------------------------------------------------------------------' println 'Build info:' println 'Group: ' + group println 'Artifact: ' + rootProject.name println 'Version: ' + version println 'Description: ' + description println '--------------------------------------------------------------------------------' <file_sep>group = net.mikasa version = 4.1.0 description = mikasa.net webapp <file_sep>{_id:22020,name: "Alfántega",province_id: 22}, {_id:22021,name: "Almudévar",province_id: 22}, {_id:22022,name: "<NAME>",province_id: 22}, {_id:22023,name: "Almuniente",province_id: 22}, {_id:22024,name: "Alquézar",province_id: 22}, {_id:22025,name: "Altorricón",province_id: 22}, {_id:22027,name: "Angüés",province_id: 22}, {_id:22028,name: "Ansó",province_id: 22}, {_id:22029,name: "Antillón",province_id: 22}, {_id:22032,name: "<NAME>",province_id: 22}, {_id:22035,name: "Arén",province_id: 22}, {_id:22036,name: "Argavieso",province_id: 22}, {_id:22037,name: "Arguis",province_id: 22}, {_id:22039,name: "Ayerbe",province_id: 22}, {_id:22040,name: "Azanuy-Alins",province_id: 22}, {_id:22041,name: "Azara",province_id: 22}, {_id:22042,name: "Azlor",province_id: 22}, {_id:22043,name: "Baélls",province_id: 22}, {_id:22044,name: "Bailo",province_id: 22}, {_id:22045,name: "Baldellou",province_id: 22}, {_id:22046,name: "Ballobar",province_id: 22}, {_id:22047,name: "Banastás",province_id: 22}, {_id:22048,name: "Barbastro",province_id: 22}, {_id:22049,name: "Barbués",province_id: 22}, {_id:22050,name: "Barbuñales",province_id: 22}, {_id:22051,name: "Bárcabo",province_id: 22}, {_id:22052,name: "<NAME>",province_id: 22}, {_id:22053,name: "Benabarre",province_id: 22}, {_id:22054,name: "Benasque",province_id: 22}, {_id:22055,name: "Berbegal",province_id: 22}, {_id:22057,name: "Bielsa",province_id: 22}, {_id:22058,name: "Bierge",province_id: 22}, {_id:22059,name: "Biescas",province_id: 22}, {_id:22060,name: "Binaced",province_id: 22}, {_id:22061,name: "Binéfar",province_id: 22}, {_id:22062,name: "Bisaurri",province_id: 22}, {_id:22063,name: "Biscarrués",province_id: 22}, {_id:22064,name: "<NAME>",province_id: 22}, {_id:22066,name: "Boltaña",province_id: 22}, {_id:22067,name: "Bonansa",province_id: 22}, {_id:22068,name: "Borau",province_id: 22}, {_id:22069,name: "Broto",province_id: 22}, {_id:22072,name: "Caldearenas",province_id: 22}, {_id:22074,name: "Campo",province_id: 22}, {_id:22075,name: "Camporrélls",province_id: 22}, {_id:22076,name: "<NAME>",province_id: 22}, {_id:22077,name: "Candasnos",province_id: 22}, {_id:22078,name: "Canfranc",province_id: 22}, {_id:22079,name: "Capdesaso",province_id: 22}, {_id:22080,name: "Capella",province_id: 22}, {_id:22081,name: "<NAME>",province_id: 22}, {_id:22082,name: "<NAME>",province_id: 22}, {_id:22083,name: "<NAME>",province_id: 22}, {_id:22084,name: "<NAME>",province_id: 22}, {_id:22085,name: "Castelflorite",province_id: 22}, {_id:22086,name: "<NAME>",province_id: 22}, {_id:22087,name: "Castigaleu",province_id: 22}, {_id:22088,name: "Castillazuelo",province_id: 22}, {_id:22089,name: "Castillonroy",province_id: 22}, {_id:22090,name: "Colungo",province_id: 22}, {_id:22094,name: "Chalamera",province_id: 22}, {_id:22095,name: "Chía",province_id: 22}, {_id:22096,name: "Chimillas",province_id: 22}, {_id:22099,name: "Esplús",province_id: 22}, {_id:22102,name: "Estada",province_id: 22}, {_id:22103,name: "Estadilla",province_id: 22}, {_id:22105,name: "<NAME>",province_id: 22}, {_id:22106,name: "Fago",province_id: 22}, {_id:22107,name: "Fanlo",province_id: 22}, {_id:22109,name: "Fiscal",province_id: 22}, {_id:22110,name: "Fonz",province_id: 22}, {_id:22111,name: "<NAME>",province_id: 22}, {_id:22112,name: "Fraga",province_id: 22}, {_id:22113,name: "Fueva (La)",province_id: 22}, {_id:22114,name: "Gistaín",province_id: 22}, {_id:22115,name: "Grado (El)",province_id: 22}, {_id:22116,name: "Grañén",province_id: 22}, {_id:22117,name: "Graus",province_id: 22}, {_id:22119,name: "<NAME>",province_id: 22}, {_id:22122,name: "<NAME>",province_id: 22}, {_id:22124,name: "Huerto",province_id: 22}, {_id:22125,name: "Huesca",province_id: 22}, {_id:22126,name: "Ibieca",province_id: 22}, {_id:22127,name: "Igriés",province_id: 22}, {_id:22128,name: "Ilche",province_id: 22}, {_id:22129,name: "Isábena",province_id: 22}, {_id:22130,name: "Jaca",province_id: 22}, {_id:22131,name: "Jasa",province_id: 22}, {_id:22133,name: "Labuerda",province_id: 22}, {_id:22135,name: "Laluenga",province_id: 22}, {_id:22136,name: "Lalueza",province_id: 22}, {_id:22137,name: "Lanaja",province_id: 22}, {_id:22139,name: "Laperdiguera",province_id: 22}, {_id:22141,name: "Lascellas-Ponzano",province_id: 22}, {_id:22142,name: "Lascuarre",province_id: 22}, {_id:22143,name: "Laspaúles",province_id: 22}, {_id:22144,name: "Laspuña",province_id: 22}, {_id:22149,name: "Loarre",province_id: 22}, {_id:22150,name: "Loporzano",province_id: 22}, {_id:22151,name: "Loscorrales",province_id: 22}, {_id:22155,name: "<NAME>",province_id: 22}, {_id:22156,name: "Monflorite-Lascasas",province_id: 22}, {_id:22157,name: "Montanuy",province_id: 22}, {_id:22158,name: "Monzón",province_id: 22}, {_id:22160,name: "Naval",province_id: 22}, {_id:22162,name: "Novales",province_id: 22}, {_id:22163,name: "Nueno",province_id: 22}, {_id:22164,name: "Olvena",province_id: 22}, {_id:22165,name: "Ontiñena",province_id: 22}, {_id:22167,name: "<NAME>",province_id: 22}, {_id:22168,name: "Palo",province_id: 22}, {_id:22170,name: "Panticosa",province_id: 22}, {_id:22172,name: "Peñalba",province_id: 22}, {_id:22173,name: "<NAME> (Las)",province_id: 22}, {_id:22174,name: "<NAME>",province_id: 22}, {_id:22175,name: "<NAME>",province_id: 22}, {_id:22176,name: "Peraltilla",province_id: 22}, {_id:22177,name: "Perarrúa",province_id: 22}, {_id:22178,name: "Pertusa",province_id: 22}, {_id:22181,name: "Piracés",province_id: 22}, {_id:22182,name: "Plan",province_id: 22}, {_id:22184,name: "Poleñino",province_id: 22}, {_id:22186,name: "<NAME>",province_id: 22}, {_id:22187,name: "<NAME> (La)",province_id: 22}, {_id:22188,name: "<NAME>",province_id: 22}, {_id:22189,name: "Puértolas",province_id: 22}, {_id:22190,name: "<NAME> (El)",province_id: 22}, {_id:22193,name: "<NAME>",province_id: 22}, {_id:22195,name: "Quicena",province_id: 22}, {_id:22197,name: "Robres",province_id: 22}, {_id:22199,name: "Sabiñánigo",province_id: 22}, {_id:22200,name: "Sahún",province_id: 22}, {_id:22201,name: "<NAME>",province_id: 22}, {_id:22202,name: "<NAME>",province_id: 22}, {_id:22203,name: "Salillas",province_id: 22}, {_id:22204,name: "<NAME>",province_id: 22}, {_id:22205,name: "<NAME>",province_id: 22}, {_id:22206,name: "Sangarrén",province_id: 22}, {_id:22207,name: "<NAME>",province_id: 22}, {_id:22208,name: "<NAME>",province_id: 22}, {_id:22209,name: "<NAME>",province_id: 22}, {_id:22212,name: "<NAME>",province_id: 22}, {_id:22213,name: "Sariñena",province_id: 22}, {_id:22214,name: "Secastilla",province_id: 22}, {_id:22215,name: "Seira",province_id: 22}, {_id:22217,name: "Sena",province_id: 22}, {_id:22218,name: "<NAME>",province_id: 22}, {_id:22220,name: "Sesa",province_id: 22}, {_id:22221,name: "Sesué",province_id: 22}, {_id:22222,name: "Siétamo",province_id: 22}, {_id:22223,name: "Sopeira",province_id: 22}, {_id:22225,name: "<NAME>",province_id: 22}, {_id:22226,name: "Tardienta",province_id: 22}, {_id:22227,name: "Tella-Sin",province_id: 22}, {_id:22228,name: "Tierz",province_id: 22}, {_id:22229,name: "Tolva",province_id: 22}, {_id:22230,name: "Torla",province_id: 22}, {_id:22232,name: "<NAME>",province_id: 22}, {_id:22233,name: "<NAME>",province_id: 22}, {_id:22234,name: "<NAME>",province_id: 22}, {_id:22235,name: "<NAME>",province_id: 22}, {_id:22236,name: "<NAME>",province_id: 22}, {_id:22239,name: "Tramaced",province_id: 22}, {_id:22242,name: "Valfarta",province_id: 22}, {_id:22243,name: "<NAME>",province_id: 22}, {_id:22244,name: "<NAME>",province_id: 22}, {_id:22245,name: "<NAME>",province_id: 22}, {_id:22246,name: "Veracruz",province_id: 22}, {_id:22247,name: "<NAME>",province_id: 22}, {_id:22248,name: "Vicién",province_id: 22}, {_id:22249,name: "Villanova",province_id: 22}, {_id:22250,name: "Villanúa",province_id: 22}, {_id:22251,name: "<NAME>",province_id: 22}, {_id:22252,name: "<NAME>",province_id: 22}, {_id:22253,name: "Yésero",province_id: 22}, {_id:22254,name: "Zaidín",province_id: 22}, {_id:22901,name: "<NAME>",province_id: 22}, {_id:22902,name: "<NAME>",province_id: 22}, {_id:22903,name: "<NAME>",province_id: 22}, {_id:22904,name: "<NAME>)",province_id: 22}, {_id:22905,name: "Lupiñén-Ortilla",province_id: 22}, {_id:22906,name: "<NAME>",province_id: 22}, {_id:22907,name: "Aínsa-Sobrarbe",province_id: 22}, {_id:22908,name: "<NAME>",province_id: 22}, {_id:22909,name: "Vencillón",province_id: 22}, {_id:23001,name: "<NAME>",province_id: 23}, {_id:23002,name: "<NAME>",province_id: 23}, {_id:23003,name: "Alcaudete",province_id: 23}, {_id:23004,name: "Aldeaquemada",province_id: 23}, {_id:23005,name: "Andújar",province_id: 23}, {_id:23006,name: "Arjona",province_id: 23}, {_id:23007,name: "Arjonilla",province_id: 23}, {_id:23008,name: "Arquillos",province_id: 23}, {_id:23009,name: "Baeza",province_id: 23}, {_id:23010,name: "Bailén",province_id: 23}, {_id:23011,name: "<NAME>",province_id: 23}, {_id:23012,name: "<NAME>",province_id: 23}, {_id:23014,name: "Begíjar",province_id: 23}, {_id:23015,name: "<NAME>",province_id: 23}, {_id:23016,name: "Benatae",province_id: 23}, {_id:23017,name: "<NAME>",province_id: 23}, {_id:23018,name: "Cambil",province_id: 23}, {_id:23019,name: "<NAME>",province_id: 23}, {_id:23020,name: "Canena",province_id: 23}, {_id:23021,name: "Carboneros",province_id: 23}, {_id:23024,name: "Carolina (La)",province_id: 23}, {_id:23025,name: "Castellar",province_id: 23}, {_id:23026,name: "<NAME>",province_id: 23}, {_id:23027,name: "Cazalilla",province_id: 23}, {_id:23028,name: "Cazorla",province_id: 23}, {_id:23029,name: "<NAME>",province_id: 23}, {_id:23030,name: "Chilluévar",province_id: 23}, {_id:23031,name: "Escañuela",province_id: 23}, {_id:23032,name: "Espelúy",province_id: 23}, {_id:23033,name: "Frailes",province_id: 23}, {_id:23034,name: "<NAME>",province_id: 23}, {_id:23035,name: "<NAME>",province_id: 23}, {_id:23037,name: "Génave",province_id: 23}, {_id:23038,name: "<NAME> (La)",province_id: 23}, {_id:23039,name: "Guarromán",province_id: 23}, {_id:23040,name: "Lahiguera",province_id: 23}, {_id:23041,name: "<NAME>",province_id: 23}, {_id:23042,name: "Hinojares",province_id: 23}, {_id:23043,name: "Hornos",province_id: 23}, {_id:23044,name: "Huelma",province_id: 23}, {_id:23045,name: "Huesa",province_id: 23}, {_id:23046,name: "Ibros",province_id: 23}, {_id:23047,name: "Iruela (La)",province_id: 23}, {_id:23048,name: "Iznatoraf",province_id: 23}, {_id:23049,name: "Jabalquinto",province_id: 23}, {_id:23050,name: "Jaén",province_id: 23}, {_id:23051,name: "Jamilena",province_id: 23}, {_id:23052,name: "Jimena",province_id: 23}, {_id:23053,name: "Jódar",province_id: 23}, {_id:23054,name: "Larva",province_id: 23}, {_id:23055,name: "Linares",province_id: 23}, {_id:23056,name: "Lopera",province_id: 23}, {_id:23057,name: "Lupión",province_id: 23}, {_id:23058,name: "<NAME>",province_id: 23}, {_id:23059,name: "Marmolejo",province_id: 23}, {_id:23060,name: "Martos",province_id: 23}, {_id:23061,name: "Mengíbar",province_id: 23}, {_id:23062,name: "Montizón",province_id: 23}, {_id:23063,name: "<NAME>",province_id: 23}, {_id:23064,name: "Noalejo",province_id: 23}, {_id:23065,name: "Orcera",province_id: 23}, {_id:23066,name: "<NAME>",province_id: 23}, {_id:23067,name: "Pegalajar",province_id: 23}, {_id:23069,name: "Porcuna",province_id: 23}, {_id:23070,name: "<NAME>",province_id: 23}, {_id:23071,name: "<NAME>",province_id: 23}, {_id:23072,name: "<NAME>)",province_id: 23}, {_id:23073,name: "Quesada",province_id: 23}, {_id:23074,name: "Rus",province_id: 23}, {_id:23075,name: "Sabiote",province_id: 23}, {_id:23076,name: "<NAME>",province_id: 23}, {_id:23077,name: "<NAME>",province_id: 23}, {_id:23079,name: "<NAME>",province_id: 23}, {_id:23080,name: "<NAME>",province_id: 23}, {_id:23081,name: "<NAME>",province_id: 23}, {_id:23082,name: "Siles",province_id: 23}, {_id:23084,name: "<NAME>",province_id: 23}, {_id:23085,name: "Torreblascopedro",province_id: 23}, {_id:23086,name: "<NAME>",province_id: 23}, {_id:23087,name: "Torredonjimeno",province_id: 23}, {_id:23088,name: "Torreperogil",province_id: 23}, {_id:23090,name: "Torres",province_id: 23}, {_id:23091,name: "<NAME>",province_id: 23}, {_id:23092,name: "Úbeda",province_id: 23}, {_id:23093,name: "<NAME>",province_id: 23}, {_id:23094,name: "Vilches",province_id: 23}, {_id:23095,name: "Villacarrillo",province_id: 23}, {_id:23096,name: "<NAME>",province_id: 23}, {_id:23097,name: "<NAME>",province_id: 23}, {_id:23098,name: "Villardompardo",province_id: 23}, {_id:23099,name: "Villares (Los)",province_id: 23}, {_id:23101,name: "Villarrodrigo",province_id: 23}, {_id:23901,name: "Cárcheles",province_id: 23}, {_id:23902,name: "<NAME>",province_id: 23}, {_id:23903,name: "Villatorres",province_id: 23}, {_id:23904,name: "Santiago-Pontones",province_id: 23}, {_id:23905,name: "<NAME>",province_id: 23}, {_id:24001,name: "Acebedo",province_id: 24}, {_id:24002,name: "Algadefe",province_id: 24}, {_id:24003,name: "<NAME>",province_id: 24}, {_id:24004,name: "Almanza",province_id: 24}, {_id:24005,name: "<NAME>)",province_id: 24}, {_id:24006,name: "Ardón",province_id: 24}, {_id:24007,name: "Arganza",province_id: 24}, {_id:15071,name: "<NAME>",province_id: 15}, {_id:15072,name: "Rianxo",province_id: 15}, {_id:15073,name: "Ribeira",province_id: 15}, {_id:15074,name: "Rois",province_id: 15}, {_id:15075,name: "Sada",province_id: 15}, {_id:15076,name: "<NAME>",province_id: 15}, {_id:15077,name: "<NAME>",province_id: 15}, {_id:18098,name: "Huéscar",province_id: 18}, {_id:18099,name: "<NAME>",province_id: 18}, {_id:18100,name: "<NAME>",province_id: 18}, {_id:18101,name: "<NAME>",province_id: 18}, {_id:18102,name: "Illora",province_id: 18}, {_id:18103,name: "Itrabo",province_id: 18}, {_id:18105,name: "Iznalloz",province_id: 18}, {_id:18107,name: "Jayena",province_id: 18}, {_id:18108,name: "<NAME>",province_id: 18}, {_id:18109,name: "Jete",province_id: 18}, {_id:18111,name: "Jun",province_id: 18}, {_id:18112,name: "Juviles",province_id: 18}, {_id:18114,name: "<NAME>)",province_id: 18}, {_id:18115,name: "Láchar",province_id: 18}, {_id:18116,name: "Lanjarón",province_id: 18}, {_id:18117,name: "Lanteira",province_id: 18}, {_id:18119,name: "Lecrín",province_id: 18}, {_id:18120,name: "Lentegí",province_id: 18}, {_id:18121,name: "Lobras",province_id: 18}, {_id:18122,name: "Loja",province_id: 18}, {_id:18123,name: "Lugros",province_id: 18}, {_id:18124,name: "Lújar",province_id: 18}, {_id:18126,name: "<NAME>)",province_id: 18}, {_id:18127,name: "Maracena",province_id: 18}, {_id:18128,name: "Marchal",province_id: 18}, {_id:18132,name: "Moclín",province_id: 18}, {_id:18133,name: "Molvízar",province_id: 18}, {_id:18134,name: "Monachil",province_id: 18}, {_id:18135,name: "Montefrío",province_id: 18}, {_id:18136,name: "Montejícar",province_id: 18}, {_id:18137,name: "Montillana",province_id: 18}, {_id:18138,name: "<NAME>",province_id: 18}, {_id:18140,name: "Motril",province_id: 18}, {_id:18141,name: "Murtas",province_id: 18}, {_id:18143,name: "Nigüelas",province_id: 18}, {_id:18144,name: "Nívar",province_id: 18}, {_id:18145,name: "Ogíjares",province_id: 18}, {_id:18146,name: "Orce",province_id: 18}, {_id:18147,name: "Órgiva",province_id: 18}, {_id:18148,name: "Otívar",province_id: 18}, {_id:18149,name: "Otura",province_id: 18}, {_id:18150,name: "Padul",province_id: 18}, {_id:18151,name: "Pampaneira",province_id: 18}, {_id:18152,name: "<NAME>",province_id: 18}, {_id:18153,name: "Peligros",province_id: 18}, {_id:18154,name: "Peza (La)",province_id: 18}, {_id:18157,name: "<NAME>",province_id: 18}, {_id:18158,name: "<NAME>",province_id: 18}, {_id:18159,name: "Píñar",province_id: 18}, {_id:18161,name: "Polícar",province_id: 18}, {_id:18162,name: "Polopos",province_id: 18}, {_id:18163,name: "Pórtugos",province_id: 18}, {_id:18164,name: "<NAME>",province_id: 18}, {_id:18165,name: "Pulianas",province_id: 18}, {_id:18167,name: "Purullena",province_id: 18}, {_id:18168,name: "Quéntar",province_id: 18}, {_id:18170,name: "Rubite",province_id: 18}, {_id:18171,name: "Salar",province_id: 18}, {_id:18173,name: "Salobreña",province_id: 18}, {_id:18174,name: "<NAME>",province_id: 18}, {_id:18175,name: "<NAME>",province_id: 18}, {_id:18176,name: "Soportújar",province_id: 18}, {_id:18177,name: "Sorvilán",province_id: 18}, {_id:18178,name: "Torre-Cardela",province_id: 18}, {_id:18179,name: "Torvizcón",province_id: 18}, {_id:18180,name: "Trevélez",province_id: 18}, {_id:18181,name: "Turón",province_id: 18}, {_id:18182,name: "Ugíjar",province_id: 18}, {_id:18183,name: "Válor",province_id: 18}, {_id:18184,name: "<NAME>",province_id: 18}, {_id:18185,name: "<NAME>",province_id: 18}, {_id:18187,name: "<NAME>",province_id: 18}, {_id:18188,name: "<NAME>",province_id: 18}, {_id:18189,name: "Víznar",province_id: 18}, {_id:18192,name: "Zafarraya",province_id: 18}, {_id:18193,name: "Zubia (La)",province_id: 18}, {_id:18194,name: "Zújar",province_id: 18}, {_id:18901,name: "Taha (La)",province_id: 18}, {_id:18902,name: "Valle (El)",province_id: 18}, {_id:18903,name: "Nevada",province_id: 18}, {_id:18904,name: "<NAME>",province_id: 18}, {_id:18905,name: "Gabias (Las)",province_id: 18}, {_id:18906,name: "Guajares (Los)",province_id: 18}, {_id:18907,name: "<NAME>",province_id: 18}, {_id:18908,name: "Villamena",province_id: 18}, {_id:18909,name: "Morelábor",province_id: 18}, {_id:18910,name: "Pinar (El)",province_id: 18}, {_id:18911,name: "<NAME>",province_id: 18}, {_id:18912,name: "<NAME>",province_id: 18}, {_id:18913,name: "Zagra",province_id: 18}, {_id:19001,name: "Abánades",province_id: 19}, {_id:19002,name: "Ablanque",province_id: 19}, {_id:19003,name: "Adobes",province_id: 19}, {_id:19004,name: "Alaminos",province_id: 19}, {_id:19005,name: "Alarilla",province_id: 19}, {_id:19006,name: "<NAME>",province_id: 19}, {_id:19007,name: "Albares",province_id: 19}, {_id:19008,name: "Albendiego",province_id: 19}, {_id:19009,name: "Alcocer",province_id: 19}, {_id:19010,name: "<NAME>",province_id: 19}, {_id:19011,name: "<NAME>",province_id: 19}, {_id:19013,name: "Alcoroches",province_id: 19}, {_id:19015,name: "<NAME>",province_id: 19}, {_id:19016,name: "<NAME>",province_id: 19}, {_id:19017,name: "Algora",province_id: 19}, {_id:19018,name: "Alhóndiga",province_id: 19}, {_id:19019,name: "Alique",province_id: 19}, {_id:19020,name: "Almadrones",province_id: 19}, {_id:19021,name: "Almoguera",province_id: 19}, {_id:19022,name: "<NAME>",province_id: 19}, {_id:19023,name: "Alocén",province_id: 19}, {_id:19024,name: "Alovera",province_id: 19}, {_id:19027,name: "Alustante",province_id: 19}, {_id:19031,name: "Angón",province_id: 19}, {_id:19032,name: "Anguita",province_id: 19}, {_id:19033,name: "<NAME>",province_id: 19}, {_id:19034,name: "<NAME>",province_id: 19}, {_id:19036,name: "Aranzueque",province_id: 19}, {_id:19037,name: "Arbancón",province_id: 19}, {_id:19038,name: "Arbeteta",province_id: 19}, {_id:19039,name: "Argecilla",province_id: 19}, {_id:19040,name: "Armallones",province_id: 19}, {_id:19041,name: "<NAME>",province_id: 19}, {_id:19042,name: "<NAME>",province_id: 19}, {_id:19043,name: "Atanzón",province_id: 19}, {_id:19044,name: "Atienza",province_id: 19}, {_id:19045,name: "Auñón",province_id: 19}, {_id:19046,name: "<NAME>",province_id: 19}, {_id:19047,name: "Baides",province_id: 19}, {_id:19048,name: "<NAME>",province_id: 19}, {_id:19049,name: "Bañuelos",province_id: 19}, {_id:19050,name: "Barriopedro",province_id: 19}, {_id:19051,name: "Berninches",province_id: 19}, {_id:19052,name: "<NAME>)",province_id: 19}, {_id:19053,name: "Brihuega",province_id: 19}, {_id:19054,name: "Budia",province_id: 19}, {_id:19055,name: "Bujalaro",province_id: 19}, {_id:19057,name: "Bustares",province_id: 19}, {_id:19058,name: "<NAME>",province_id: 19}, {_id:19059,name: "<NAME>",province_id: 19}, {_id:19060,name: "<NAME>",province_id: 19}, {_id:19061,name: "Campisábalos",province_id: 19}, {_id:19064,name: "Canredondo",province_id: 19}, {_id:19065,name: "Cantalojas",province_id: 19}, {_id:19066,name: "Cañizar",province_id: 19}, {_id:19067,name: "<NAME> (El)",province_id: 19}, {_id:19070,name: "<NAME>",province_id: 19}, {_id:19071,name: "Casar (El)",province_id: 19}, {_id:19073,name: "<NAME>",province_id: 19}, {_id:19074,name: "Caspueñas",province_id: 19}, {_id:19075,name: "<NAME>",province_id: 19}, {_id:19076,name: "<NAME>",province_id: 19}, {_id:19078,name: "Castilforte",province_id: 19}, {_id:19079,name: "Castilnuevo",province_id: 19}, {_id:19080,name: "<NAME>",province_id: 19}, {_id:19081,name: "<NAME>",province_id: 19}, {_id:19082,name: "Centenera",province_id: 19}, {_id:19086,name: "Cifuentes",province_id: 19}, {_id:19087,name: "Cincovillas",province_id: 19}, {_id:19088,name: "Ciruelas",province_id: 19}, {_id:19089,name: "<NAME>",province_id: 19}, {_id:19090,name: "Cobeta",province_id: 19}, {_id:19091,name: "Cogollor",province_id: 19}, {_id:19092,name: "Cogolludo",province_id: 19}, {_id:19095,name: "<NAME>",province_id: 19}, {_id:19096,name: "<NAME>",province_id: 19}, {_id:19097,name: "Congostrina",province_id: 19}, {_id:19098,name: "Copernal",province_id: 19}, {_id:19099,name: "Corduente",province_id: 19}, {_id:19102,name: "<NAME> Uceda (El)",province_id: 19}, {_id:19103,name: "Checa",province_id: 19}, {_id:19104,name: "Chequilla",province_id: 19}, {_id:19105,name: "Chiloeches",province_id: 19}, {_id:19106,name: "<NAME>",province_id: 19}, {_id:19107,name: "Driebes",province_id: 19}, {_id:19108,name: "Durón",province_id: 19}, {_id:19109,name: "Embid",province_id: 19}, {_id:19110,name: "Escamilla",province_id: 19}, {_id:19111,name: "Escariche",province_id: 19}, {_id:19112,name: "Escopete",province_id: 19}, {_id:19113,name: "<NAME>",province_id: 19}, {_id:19114,name: "Esplegares",province_id: 19}, {_id:19115,name: "Establés",province_id: 19}, {_id:19116,name: "Estriégana",province_id: 19}, {_id:19117,name: "Fontanar",province_id: 19}, {_id:19118,name: "Fuembellida",province_id: 19}, {_id:19119,name: "Fuencemillán",province_id: 19}, {_id:19120,name: "<NAME>",province_id: 19}, {_id:19121,name: "Fuentelencina",province_id: 19}, {_id:19122,name: "Fuentelsaz",province_id: 19}, {_id:19123,name: "Fuentelviejo",province_id: 19}, {_id:19124,name: "Fuentenovilla",province_id: 19}, {_id:19125,name: "Gajanejos",province_id: 19}, {_id:19126,name: "Galápagos",province_id: 19}, {_id:19127,name: "<NAME>",province_id: 19}, {_id:19129,name: "<NAME>",province_id: 19}, {_id:19130,name: "Guadalajara",province_id: 19}, {_id:19132,name: "Henche",province_id: 19}, {_id:19133,name: "<NAME>",province_id: 19}, {_id:19134,name: "Herrería",province_id: 19}, {_id:19135,name: "Hiendelaencina",province_id: 19}, {_id:19136,name: "Hijes",province_id: 19}, {_id:19138,name: "Hita",province_id: 19}, {_id:19139,name: "Hombrados",province_id: 19}, {_id:19142,name: "Hontoba",province_id: 19}, {_id:19143,name: "Horche",province_id: 19}, {_id:19145,name: "<NAME>",province_id: 19}, {_id:19146,name: "<NAME>)",province_id: 19}, {_id:19147,name: "<NAME>",province_id: 19}, {_id:19148,name: "Huertahernando",province_id: 19}, {_id:19150,name: "Hueva",province_id: 19}, {_id:19151,name: "Humanes",province_id: 19}, {_id:19152,name: "Illana",province_id: 19}, {_id:19153,name: "Iniéstola",province_id: 19}, {_id:19154,name: "<NAME>)",province_id: 19}, {_id:19155,name: "Irueste",province_id: 19}, {_id:19156,name: "Jadraque",province_id: 19}, {_id:19157,name: "Jirueque",province_id: 19}, {_id:19159,name: "Ledanca",province_id: 19}, {_id:19160,name: "<NAME>",province_id: 19}, {_id:19161,name: "Lupiana",province_id: 19}, {_id:19162,name: "Luzaga",province_id: 19}, {_id:19163,name: "Luzón",province_id: 19}, {_id:19165,name: "Majaelrayo",province_id: 19}, {_id:19166,name: "<NAME>",province_id: 19}, {_id:19167,name: "Malaguilla",province_id: 19}, {_id:19168,name: "Mandayona",province_id: 19}, {_id:19169,name: "Mantiel",province_id: 19}, {_id:19170,name: "Maranchón",province_id: 19}, {_id:19171,name: "Marchamalo",province_id: 19}, {_id:19172,name: "<NAME>",province_id: 19}, {_id:19173,name: "Matarrubia",province_id: 19}, {_id:19174,name: "Matillas",province_id: 19}, {_id:19175,name: "Mazarete",province_id: 19}, {_id:19176,name: "Mazuecos",province_id: 19}, {_id:19177,name: "Medranda",province_id: 19}, {_id:19178,name: "Megina",province_id: 19}, {_id:19179,name: "Membrillera",province_id: 19}, {_id:19181,name: "<NAME>",province_id: 19}, {_id:19182,name: "<NAME>)",province_id: 19}, {_id:19183,name: "Milmarcos",province_id: 19}, {_id:19184,name: "Millana",province_id: 19}, {_id:19185,name: "Miñosa (La)",province_id: 19}, {_id:19186,name: "Mirabueno",province_id: 19}, {_id:19187,name: "Miralrío",province_id: 19}, {_id:19188,name: "Mochales",province_id: 19}, {_id:19189,name: "Mohernando",province_id: 19}, {_id:19190,name: "<NAME>",province_id: 19}, {_id:19191,name: "Monasterio",province_id: 19}, {_id:19192,name: "Mondéjar",province_id: 19}, {_id:19193,name: "Montarrón",province_id: 19}, {_id:19194,name: "<NAME>",province_id: 19}, {_id:19195,name: "Morenilla",province_id: 19}, {_id:19196,name: "Muduex",province_id: 19}, {_id:19197,name: "<NAME> (Las)",province_id: 19}, {_id:19198,name: "Negredo",province_id: 19}, {_id:19199,name: "Ocentejo",province_id: 19}, {_id:19200,name: "Olivar (El)",province_id: 19}, {_id:19201,name: "<NAME>",province_id: 19}, {_id:19202,name: "<NAME> (La)",province_id: 19}, {_id:19203,name: "Ordial (El)",province_id: 19}, {_id:19204,name: "Orea",province_id: 19}, {_id:19208,name: "<NAME>",province_id: 19}, {_id:19209,name: "Pardos",province_id: 19}, {_id:19210,name: "<NAME>",province_id: 19}, {_id:19211,name: "Pareja",province_id: 19}, {_id:19212,name: "Pastrana",province_id: 19}, {_id:19213,name: "Pedregal (El)",province_id: 19}, {_id:19214,name: "Peñalén",province_id: 19}, {_id:19215,name: "Peñalver",province_id: 19}, {_id:19216,name: "<NAME>",province_id: 19}, {_id:19217,name: "Peralveche",province_id: 19}, {_id:19218,name: "<NAME>",province_id: 19}, {_id:19219,name: "<NAME>",province_id: 19}, {_id:19220,name: "Pioz",province_id: 19}, {_id:19221,name: "Piqueras",province_id: 19}, {_id:19222,name: "<NAME> (El)",province_id: 19}, {_id:5225,name: "<NAME>",province_id: 5}, {_id:5226,name: "<NAME>",province_id: 5}, {_id:5227,name: "<NAME>",province_id: 5}, {_id:5228,name: "<NAME>",province_id: 5}, {_id:5229,name: "<NAME>",province_id: 5}, {_id:5230,name: "<NAME>",province_id: 5}, {_id:5231,name: "<NAME>ente de Arévalo",province_id: 5}, {_id:5232,name: "Serrada (La)",province_id: 5}, {_id:5233,name: "Serranillos",province_id: 5}, {_id:5234,name: "Sigeres",province_id: 5}, {_id:5235,name: "Sinlabajos",province_id: 5}, {_id:5236,name: "<NAME> Ávila",province_id: 5}, {_id:5237,name: "Solana de Rioalmar",province_id: 5}, {_id:5238,name: "Solosancho",province_id: 5}, {_id:15078,name: "<NAME>",province_id: 15}, {_id:15079,name: "Santiso",province_id: 15}, {_id:15080,name: "Sobrado",province_id: 15}, {_id:15081,name: "Somozas (As)",province_id: 15}, {_id:15082,name: "Teo",province_id: 15}, {_id:15083,name: "Toques",province_id: 15}, {_id:15084,name: "Tordoia",province_id: 15}, {_id:15085,name: "Touro",province_id: 15}, {_id:15086,name: "Trazo",province_id: 15}, {_id:15087,name: "Valdoviño",province_id: 15}, {_id:15088,name: "<NAME>",province_id: 15}, {_id:15089,name: "Vedra",province_id: 15}, {_id:15090,name: "Vilasantar",province_id: 15}, {_id:15091,name: "Vilarmaior",province_id: 15}, {_id:15092,name: "Vimianzo",province_id: 15}, {_id:15093,name: "Zas",province_id: 15}, {_id:15901,name: "Cariño",province_id: 15}, {_id:16001,name: "<NAME>",province_id: 16}, {_id:16002,name: "Acebrón (El)",province_id: 16}, {_id:16003,name: "Alarcón",province_id: 16}, {_id:16004,name: "<NAME>",province_id: 16}, {_id:16005,name: "<NAME>",province_id: 16}, {_id:16006,name: "Albendea",province_id: 16}, {_id:16007,name: "<NAME> (La)",province_id: 16}, {_id:16008,name: "<NAME>",province_id: 16}, {_id:16009,name: "Alcantud",province_id: 16}, {_id:16010,name: "<NAME>",province_id: 16}, {_id:16011,name: "Alcohujate",province_id: 16}, {_id:16012,name: "<NAME>",province_id: 16}, {_id:16013,name: "Algarra",province_id: 16}, {_id:16014,name: "Aliaguilla",province_id: 16}, {_id:16015,name: "<NAME>)",province_id: 16}, {_id:16016,name: "Almendros",province_id: 16}, {_id:16017,name: "<NAME>",province_id: 16}, {_id:16018,name: "<NAME>",province_id: 16}, {_id:16019,name: "Altarejos",province_id: 16}, {_id:16020,name: "<NAME>",province_id: 16}, {_id:16022,name: "<NAME>",province_id: 16}, {_id:16023,name: "<NAME>",province_id: 16}, {_id:16024,name: "Arguisuelas",province_id: 16}, {_id:16025,name: "Arrancacepas",province_id: 16}, {_id:16026,name: "<NAME>",province_id: 16}, {_id:16027,name: "<NAME>",province_id: 16}, {_id:16029,name: "<NAME>",province_id: 16}, {_id:16030,name: "<NAME>",province_id: 16}, {_id:16031,name: "Beamud",province_id: 16}, {_id:16032,name: "Belinchón",province_id: 16}, {_id:16033,name: "Belmonte",province_id: 16}, {_id:16034,name: "Belmontejo",province_id: 16}, {_id:16035,name: "Beteta",province_id: 16}, {_id:16036,name: "Boniches",province_id: 16}, {_id:16038,name: "Buciegas",province_id: 16}, {_id:16039,name: "<NAME>",province_id: 16}, {_id:16040,name: "<NAME>",province_id: 16}, {_id:16041,name: "Buendía",province_id: 16}, {_id:16042,name: "<NAME>",province_id: 16}, {_id:16043,name: "Campillos-Paravientos",province_id: 16}, {_id:16044,name: "Campillos-Sierra",province_id: 16}, {_id:16045,name: "<NAME>",province_id: 16}, {_id:16046,name: "<NAME>",province_id: 16}, {_id:16047,name: "<NAME>",province_id: 16}, {_id:16048,name: "Cañamares",province_id: 16}, {_id:16049,name: "Cañavate (El)",province_id: 16}, {_id:16050,name: "Cañaveras",province_id: 16}, {_id:16051,name: "Cañaveruelas",province_id: 16}, {_id:16052,name: "Cañete",province_id: 16}, {_id:16053,name: "Cañizares",province_id: 16}, {_id:16055,name: "<NAME>",province_id: 16}, {_id:16056,name: "Cardenete",province_id: 16}, {_id:16057,name: "Carrascosa",province_id: 16}, {_id:16058,name: "<NAME>",province_id: 16}, {_id:16060,name: "<NAME>",province_id: 16}, {_id:16061,name: "<NAME> <NAME>",province_id: 16}, {_id:16062,name: "<NAME>",province_id: 16}, {_id:16063,name: "<NAME>",province_id: 16}, {_id:16064,name: "<NAME>",province_id: 16}, {_id:16065,name: "<NAME>",province_id: 16}, {_id:16066,name: "Casasimarro",province_id: 16}, {_id:16067,name: "Castejón",province_id: 16}, {_id:16068,name: "<NAME>",province_id: 16}, {_id:16070,name: "Castillejo-Sierra",province_id: 16}, {_id:16071,name: "Castillo-Albaráñez",province_id: 16}, {_id:16072,name: "<NAME>",province_id: 16}, {_id:16073,name: "<NAME>",province_id: 16}, {_id:16074,name: "Cierva (La)",province_id: 16}, {_id:16078,name: "Cuenca",province_id: 16}, {_id:16079,name: "<NAME>",province_id: 16}, {_id:16081,name: "Chumillas",province_id: 16}, {_id:16082,name: "Enguídanos",province_id: 16}, {_id:16083,name: "<NAME>",province_id: 16}, {_id:16084,name: "<NAME>",province_id: 16}, {_id:16085,name: "<NAME>)",province_id: 16}, {_id:16086,name: "<NAME> <NAME>",province_id: 16}, {_id:16087,name: "<NAME>",province_id: 16}, {_id:16088,name: "<NAME>",province_id: 16}, {_id:16089,name: "Fuentes",province_id: 16}, {_id:16091,name: "Fuertescusa",province_id: 16}, {_id:16092,name: "Gabaldón",province_id: 16}, {_id:16093,name: "Garaballa",province_id: 16}, {_id:16094,name: "Gascueña",province_id: 16}, {_id:16095,name: "<NAME>",province_id: 16}, {_id:16096,name: "<NAME>",province_id: 16}, {_id:16097,name: "Henarejos",province_id: 16}, {_id:16098,name: "Herrumblar (El)",province_id: 16}, {_id:16099,name: "Hinojosa (La)",province_id: 16}, {_id:16100,name: "Hinojosos (Los)",province_id: 16}, {_id:16101,name: "Hito (El)",province_id: 16}, {_id:16102,name: "Honrubia",province_id: 16}, {_id:16103,name: "Hontanaya",province_id: 16}, {_id:16104,name: "Hontecillas",province_id: 16}, {_id:16106,name: "<NAME>",province_id: 16}, {_id:16107,name: "Huélamo",province_id: 16}, {_id:16108,name: "Huelves",province_id: 16}, {_id:16109,name: "Huérguina",province_id: 16}, {_id:16110,name: "<NAME>",province_id: 16}, {_id:16111,name: "<NAME>",province_id: 16}, {_id:16112,name: "Huete",province_id: 16}, {_id:16113,name: "Iniesta",province_id: 16}, {_id:16115,name: "<NAME>",province_id: 16}, {_id:16116,name: "Lagunaseca",province_id: 16}, {_id:16117,name: "Landete",province_id: 16}, {_id:16118,name: "Ledaña",province_id: 16}, {_id:16119,name: "Leganiel",province_id: 16}, {_id:16121,name: "Majadas (Las)",province_id: 16}, {_id:16122,name: "Mariana",province_id: 16}, {_id:16123,name: "Masegosa",province_id: 16}, {_id:16124,name: "Mesas (Las)",province_id: 16}, {_id:16125,name: "Minglanilla",province_id: 16}, {_id:16126,name: "Mira",province_id: 16}, {_id:16128,name: "<NAME>",province_id: 16}, {_id:16129,name: "Montalbanejo",province_id: 16}, {_id:16130,name: "Montalbo",province_id: 16}, {_id:16131,name: "<NAME>",province_id: 16}, {_id:16132,name: "<NAME>",province_id: 16}, {_id:16133,name: "<NAME>",province_id: 16}, {_id:16134,name: "<NAME>",province_id: 16}, {_id:16135,name: "Moya",province_id: 16}, {_id:16137,name: "Narboneta",province_id: 16}, {_id:16139,name: "<NAME>",province_id: 16}, {_id:16140,name: "<NAME>",province_id: 16}, {_id:16141,name: "<NAME>",province_id: 16}, {_id:16142,name: "<NAME>",province_id: 16}, {_id:16143,name: "<NAME>",province_id: 16}, {_id:16145,name: "<NAME>",province_id: 16}, {_id:16146,name: "Pajarón",province_id: 16}, {_id:16147,name: "Pajaroncillo",province_id: 16}, {_id:16148,name: "<NAME>",province_id: 16}, {_id:16149,name: "Palomera",province_id: 16}, {_id:16150,name: "Paracuellos",province_id: 16}, {_id:16151,name: "Paredes",province_id: 16}, {_id:16152,name: "<NAME> (La)",province_id: 16}, {_id:16153,name: "Pedernoso (El)",province_id: 16}, {_id:16154,name: "Pedroñeras (Las)",province_id: 16}, {_id:16155,name: "Peral (El)",province_id: 16}, {_id:16156,name: "Peraleja (La)",province_id: 16}, {_id:16157,name: "Pesquera (La)",province_id: 16}, {_id:16158,name: "Picazo (El)",province_id: 16}, {_id:16159,name: "Pinarejo",province_id: 16}, {_id:16160,name: "<NAME>",province_id: 16}, {_id:16161,name: "<NAME>",province_id: 16}, {_id:16162,name: "<NAME>",province_id: 16}, {_id:16163,name: "Portilla",province_id: 16}, {_id:16165,name: "Poyatos",province_id: 16}, {_id:16166,name: "Pozoamargo",province_id: 16}, {_id:16167,name: "Pozorrubio",province_id: 16}, {_id:16169,name: "Pozuelo (El)",province_id: 16}, {_id:16170,name: "Priego",province_id: 16}, {_id:16171,name: "Provencio (El)",province_id: 16}, {_id:16172,name: "<NAME>",province_id: 16}, {_id:16173,name: "<NAME>",province_id: 16}, {_id:16174,name: "<NAME>",province_id: 16}, {_id:16175,name: "<NAME>",province_id: 16}, {_id:16176,name: "<NAME>",province_id: 16}, {_id:16177,name: "Reíllo",province_id: 16}, {_id:16181,name: "<NAME>",province_id: 16}, {_id:16185,name: "Saceda-Trasierra",province_id: 16}, {_id:16186,name: "Saelices",province_id: 16}, {_id:16187,name: "<NAME>",province_id: 16}, {_id:16188,name: "Salmeroncillos",province_id: 16}, {_id:16189,name: "Salvacañete",province_id: 16}, {_id:16190,name: "<NAME>",province_id: 16}, {_id:16191,name: "<NAME>",province_id: 16}, {_id:16192,name: "<NAME>",province_id: 16}, {_id:16193,name: "<NAME>",province_id: 16}, {_id:16194,name: "<NAME>",province_id: 16}, {_id:16195,name: "<NAME>",province_id: 16}, {_id:16196,name: "<NAME>",province_id: 16}, {_id:16197,name: "<NAME>",province_id: 16}, {_id:16198,name: "Sisante",province_id: 16}, {_id:16199,name: "<NAME>",province_id: 16}, {_id:16202,name: "Talayuelas",province_id: 16}, {_id:16203,name: "Tarancón",province_id: 16}, {_id:16204,name: "Tébar",province_id: 16}, {_id:16205,name: "Tejadillos",province_id: 16}, {_id:16206,name: "Tinajas",province_id: 16}, {_id:16209,name: "Torralba",province_id: 16}, {_id:16211,name: "<NAME>",province_id: 16}, {_id:16212,name: "<NAME>",province_id: 16}, {_id:16213,name: "<NAME>",province_id: 16}, {_id:16215,name: "Tragacete",province_id: 16}, {_id:16216,name: "Tresjuncos",province_id: 16}, {_id:16217,name: "Tribaldos",province_id: 16}, {_id:16218,name: "Uclés",province_id: 16}, {_id:16219,name: "Uña",province_id: 16}, {_id:16224,name: "Valdemeca",province_id: 16}, {_id:16225,name: "<NAME>",province_id: 16}, {_id:16227,name: "Valdemoro-Sierra",province_id: 16}, {_id:16228,name: "Valdeolivas",province_id: 16}, {_id:16231,name: "<NAME>",province_id: 16}, {_id:16234,name: "Valsalobre",province_id: 16}, {_id:16236,name: "<NAME>",province_id: 16}, {_id:16237,name: "Valverdejo",province_id: 16}, {_id:16238,name: "<NAME>",province_id: 16}, {_id:16239,name: "<NAME>",province_id: 16}, {_id:16240,name: "Vellisca",province_id: 16}, {_id:16242,name: "<NAME>",province_id: 16}, {_id:16243,name: "<NAME>",province_id: 16}, {_id:16244,name: "<NAME>",province_id: 16}, {_id:16245,name: "<NAME>",province_id: 16}, {_id:16246,name: "<NAME>",province_id: 16}, {_id:16247,name: "<NAME>",province_id: 16}, {_id:16248,name: "Villalpardo",province_id: 16}, {_id:16249,name: "<NAME>",province_id: 16}, {_id:16250,name: "<NAME>",province_id: 16}, {_id:16251,name: "<NAME>",province_id: 16}, {_id:16253,name: "<NAME>",province_id: 16}, {_id:16254,name: "<NAME>",province_id: 16}, {_id:16255,name: "<NAME>",province_id: 16}, {_id:16258,name: "<NAME>",province_id: 16}, {_id:16259,name: "<NAME>",province_id: 16}, {_id:16263,name: "<NAME>",province_id: 16}, {_id:16264,name: "<NAME>",province_id: 16}, {_id:16265,name: "<NAME>",province_id: 16}, {_id:16266,name: "Villarejo-Periesteban",province_id: 16}, {_id:16269,name: "<NAME>",province_id: 16}, {_id:16270,name: "Villarrubio",province_id: 16}, {_id:16271,name: "Villarta",province_id: 16}, {_id:16272,name: "<NAME>",province_id: 16}, {_id:16273,name: "<NAME>",province_id: 16}, {_id:16274,name: "Víllora",province_id: 16}, {_id:16275,name: "Vindel",province_id: 16}, {_id:16276,name: "Yémeda",province_id: 16}, {_id:16277,name: "<NAME>",province_id: 16}, {_id:16278,name: "Zafrilla",province_id: 16}, {_id:16279,name: "<NAME>",province_id: 16}, {_id:16280,name: "Zarzuela",province_id: 16}, {_id:16901,name: "<NAME>",province_id: 16}, {_id:16902,name: "Valdetórtola",province_id: 16}, {_id:16903,name: "Valeras (Las)",province_id: 16}, {_id:16904,name: "<NAME>",province_id: 16}, {_id:16905,name: "<NAME>",province_id: 16}, {_id:16906,name: "Valdecolmenas (Los)",province_id: 16}, {_id:16908,name: "<NAME>",province_id: 16}, {_id:16909,name: "Sotorribas",province_id: 16}, {_id:16910,name: "<NAME>",province_id: 16}, {_id:17001,name: "Agullana",province_id: 17}, {_id:17002,name: "Aiguaviva",province_id: 17}, {_id:17003,name: "Albanyà",province_id: 17}, {_id:17004,name: "Albons",province_id: 17}, {_id:17005,name: "<NAME> (El)",province_id: 17}, {_id:17006,name: "Alp",province_id: 17}, {_id:17007,name: "Amer",province_id: 17}, {_id:17008,name: "Anglès",province_id: 17}, {_id:17009,name: "Arbúcies",province_id: 17}, {_id:17010,name: "Argelaguer",province_id: 17}, {_id:17011,name: "Armentera (L )",province_id: 17}, {_id:17012,name: "<NAME>",province_id: 17}, {_id:17013,name: "Begur",province_id: 17}, {_id:17014,name: "Vajol (La)",province_id: 17}, {_id:17015,name: "Banyoles",province_id: 17}, {_id:17016,name: "Bàscara",province_id: 17}, {_id:17018,name: "<NAME>",province_id: 17}, {_id:17019,name: "Besalú",province_id: 17}, {_id:17020,name: "Bescanó",province_id: 17}, {_id:17021,name: "Beuda",province_id: 17}, {_id:17022,name: "<NAME> (La)",province_id: 17}, {_id:17023,name: "Blanes",province_id: 17}, {_id:17024,name: "Bolvir",province_id: 17}, {_id:17025,name: "Bordils",province_id: 17}, {_id:17026,name: "Borrassà",province_id: 17}, {_id:17027,name: "Breda",province_id: 17}, {_id:17028,name: "Brunyola",province_id: 17}, {_id:17029,name: "<NAME>",province_id: 17}, {_id:17030,name: "Cabanes",province_id: 17}, {_id:17031,name: "Cabanelles",province_id: 17}, {_id:17032,name: "Cadaqués",province_id: 17}, {_id:17033,name: "<NAME>",province_id: 17}, {_id:17034,name: "Calonge",province_id: 17}, {_id:17035,name: "Camós",province_id: 17}, {_id:17036,name: "Campdevànol",province_id: 17}, {_id:17037,name: "Campelles",province_id: 17}, {_id:17038,name: "Campllong",province_id: 17}, {_id:17039,name: "Camprodon",province_id: 17}, {_id:17040,name: "<NAME>",province_id: 17}, {_id:17041,name: "Cantallops",province_id: 17}, {_id:17042,name: "Capmany",province_id: 17}, {_id:17043,name: "Queralbs",province_id: 17}, {_id:17044,name: "<NAME>",province_id: 17}, {_id:17046,name: "<NAME>",province_id: 17}, {_id:17047,name: "<NAME>",province_id: 17}, {_id:17048,name: "<NAME>",province_id: 17}, {_id:17049,name: "Celrà",province_id: 17}, {_id:17050,name: "<NAME>",province_id: 17}, {_id:17051,name: "Cistella",province_id: 17}, {_id:17052,name: "Siurana",province_id: 17}, {_id:17054,name: "Colera",province_id: 17}, {_id:17055,name: "Colomers",province_id: 17}, {_id:17056,name: "<NAME>",province_id: 17}, {_id:17057,name: "Corçà",province_id: 17}, {_id:17058,name: "Crespià",province_id: 17}, {_id:17060,name: "Darnius",province_id: 17}, {_id:17061,name: "Das",province_id: 17}, {_id:17062,name: "<NAME> )",province_id: 17}, {_id:17063,name: "Espinelves",province_id: 17}, {_id:17064,name: "Espolla",province_id: 17}, {_id:17065,name: "Esponellà",province_id: 17}, {_id:17066,name: "Figueres",province_id: 17}, {_id:17067,name: "Flaçà",province_id: 17}, {_id:17068,name: "Foixà",province_id: 17}, {_id:17069,name: "<NAME>",province_id: 17}, {_id:17070,name: "Fontanilles",province_id: 17}, {_id:17071,name: "Fontcoberta",province_id: 17}, {_id:17073,name: "<NAME>",province_id: 17}, {_id:17074,name: "Fortià",province_id: 17}, {_id:17075,name: "Garrigàs",province_id: 17}, {_id:17076,name: "Garrigoles",province_id: 17}, {_id:17077,name: "Garriguella",province_id: 17}, {_id:17078,name: "Ger",province_id: 17}, {_id:17079,name: "Girona",province_id: 17}, {_id:17080,name: "Gombrèn",province_id: 17}, {_id:17081,name: "Gualta",province_id: 17}, {_id:17082,name: "<NAME>",province_id: 17}, {_id:17083,name: "Hostalric",province_id: 17}, {_id:17084,name: "Isòvol",province_id: 17}, {_id:17085,name: "Jafre",province_id: 17}, {_id:17086,name: "Jonquera (La)",province_id: 17}, {_id:17087,name: "Juià",province_id: 17}, {_id:17088,name: "Lladó",province_id: 17}, {_id:17089,name: "Llagostera",province_id: 17}, {_id:17090,name: "Llambilles",province_id: 17}, {_id:17091,name: "Llanars",province_id: 17}, {_id:17092,name: "Llançà",province_id: 17}, {_id:17093,name: "Llers",province_id: 17}, {_id:17094,name: "Llívia",province_id: 17}, {_id:17095,name: "<NAME>",province_id: 17}, {_id:17096,name: "Llosses (Les)",province_id: 17}, {_id:17097,name: "Madremanya",province_id: 17}, {_id:17098,name: "<NAME>",province_id: 17}, {_id:17099,name: "Meranges",province_id: 17}, {_id:17100,name: "Masarac",province_id: 17}, {_id:17101,name: "Massanes",province_id: 17}, {_id:17102,name: "<NAME>",province_id: 17}, {_id:17103,name: "<NAME>",province_id: 17}, {_id:17105,name: "Mieres",province_id: 17}, {_id:17106,name: "<NAME>",province_id: 17}, {_id:17107,name: "Molló",province_id: 17}, {_id:17109,name: "<NAME> Oix",province_id: 17}, {_id:17110,name: "Mont-ras",province_id: 17}, {_id:17111,name: "Navata",province_id: 17}, {_id:17112,name: "Ogassa",province_id: 17}, {_id:17114,name: "Olot",province_id: 17}, {_id:17115,name: "Ordis",province_id: 17}, {_id:17116,name: "Osor",province_id: 17}, {_id:17117,name: "Palafrugell",province_id: 17}, {_id:17118,name: "Palamós",province_id: 17}, {_id:17119,name: "<NAME>",province_id: 17}, {_id:17120,name: "Palau-saverdera",province_id: 17}, {_id:17121,name: "Palau-sator",province_id: 17}, {_id:17123,name: "<NAME>",province_id: 17}, {_id:17124,name: "Pals",province_id: 17}, {_id:17125,name: "Pardines",province_id: 17}, {_id:17126,name: "Parlavà",province_id: 17}, {_id:17128,name: "Pau",province_id: 17}, {_id:17129,name: "<NAME>",province_id: 17}, {_id:17130,name: "<NAME>)",province_id: 17}, {_id:17132,name: "Peralada",province_id: 17}, {_id:17133,name: "Planes d Hostoles (Les)",province_id: 17}, {_id:17134,name: "Planoles",province_id: 17}, {_id:17135,name: "<NAME>",province_id: 17}, {_id:17136,name: "Pontós",province_id: 17}, {_id:17137,name: "Porqueres",province_id: 17}, {_id:17138,name: "Portbou",province_id: 17}, {_id:17139,name: "Preses (Les)",province_id: 17}, {_id:17140,name: "<NAME> Selva (El)",province_id: 17}, {_id:17141,name: "Puigcerdà",province_id: 17}, {_id:17142,name: "Quart",province_id: 17}, {_id:17143,name: "Rabós",province_id: 17}, {_id:17144,name: "Regencós",province_id: 17}, {_id:17145,name: "<NAME>",province_id: 17}, {_id:17146,name: "<NAME>",province_id: 17}, {_id:17147,name: "Ripoll",province_id: 17}, {_id:17148,name: "Riudarenes",province_id: 17}, {_id:17149,name: "Riudaura",province_id: 17}, {_id:17150,name: "<NAME>",province_id: 17}, {_id:17151,name: "Riumors",province_id: 17}, {_id:17152,name: "Roses",province_id: 17}, {_id:17153,name: "Rupià",province_id: 17}, {_id:17154,name: "<NAME>",province_id: 17}, {_id:17155,name: "Salt",province_id: 17}, {_id:17157,name: "<NAME>",province_id: 17}, {_id:17158,name: "<NAME>",province_id: 17}, {_id:17159,name: "<NAME>",province_id: 17}, {_id:17160,name: "<NAME>",province_id: 17}, {_id:17161,name: "<NAME>",province_id: 17}, {_id:17162,name: "<NAME>",province_id: 17}, {_id:17163,name: "<NAME>",province_id: 17}, {_id:17164,name: "<NAME>",province_id: 17}, {_id:17165,name: "<NAME>",province_id: 17}, {_id:17166,name: "<NAME>",province_id: 17}, {_id:17167,name: "<NAME>",province_id: 17}, {_id:17168,name: "<NAME>",province_id: 17}, {_id:17169,name: "<NAME>",province_id: 17}, {_id:17170,name: "<NAME>",province_id: 17}, {_id:17171,name: "<NAME>",province_id: 17}, {_id:17172,name: "<NAME>",province_id: 17}, {_id:17173,name: "<NAME>",province_id: 17}, {_id:17174,name: "<NAME>",province_id: 17}, {_id:17175,name: "<NAME>",province_id: 17}, {_id:17176,name: "<NAME>",province_id: 17}, {_id:17177,name: "<NAME>",province_id: 17}, {_id:17178,name: "<NAME>",province_id: 17}, {_id:17180,name: "<NAME>",province_id: 17}, {_id:17181,name: "<NAME>",province_id: 17}, {_id:17182,name: "Santa Llogaia <NAME>",province_id: 17}, {_id:17183,name: "<NAME>",province_id: 17}, {_id:17184,name: "<NAME>",province_id: 17}, {_id:17185,name: "<NAME>",province_id: 17}, {_id:17186,name: "<NAME>",province_id: 17}, {_id:17187,name: "Saus",province_id: 17}, {_id:17188,name: "<NAME> (La)",province_id: 17}, {_id:17189,name: "<NAME> (La)",province_id: 17}, {_id:17190,name: "Serinyà",province_id: 17}, {_id:17191,name: "<NAME>",province_id: 17}, {_id:17192,name: "Setcases",province_id: 17}, {_id:17193,name: "Sils",province_id: 17}, {_id:17194,name: "Susqueda",province_id: 17}, {_id:17195,name: "<NAME> (La)",province_id: 17}, {_id:17196,name: "Terrades",province_id: 17}, {_id:17197,name: "Torrent",province_id: 17}, {_id:17198,name: "<NAME>",province_id: 17}, {_id:17199,name: "<NAME>",province_id: 17}, {_id:17200,name: "Tortellà",province_id: 17}, {_id:17201,name: "Toses",province_id: 17}, {_id:17202,name: "<NAME>",province_id: 17}, {_id:17203,name: "Ultramort",province_id: 17}, {_id:17204,name: "Ullà",province_id: 17}, {_id:17205,name: "Ullastret",province_id: 17}, {_id:17206,name: "Urús",province_id: 17}, {_id:17207,name: "<NAME> (La)",province_id: 17}, {_id:17208,name: "<NAME> (La)",province_id: 17}, {_id:17209,name: "Vall-llobrega",province_id: 17}, {_id:17210,name: "Ventalló",province_id: 17}, {_id:17211,name: "Verges",province_id: 17}, {_id:17212,name: "Vidrà",province_id: 17}, {_id:17213,name: "Vidreres",province_id: 17}, {_id:17214,name: "Vilabertran",province_id: 17}, {_id:17215,name: "Vilablareix",province_id: 17}, {_id:17216,name: "Viladasens",province_id: 17}, {_id:17217,name: "Viladamat",province_id: 17}, {_id:17218,name: "Vilademuls",province_id: 17}, {_id:17220,name: "Viladrau",province_id: 17}, {_id:17221,name: "Vilafant",province_id: 17}, {_id:17222,name: "Vilaür",province_id: 17}, {_id:17223,name: "Vilajuïga",province_id: 17}, {_id:17224,name: "<NAME>",province_id: 17}, {_id:17225,name: "Vilamacolum",province_id: 17}, {_id:17226,name: "Vilamalla",province_id: 17}, {_id:17227,name: "Vilamaniscle",province_id: 17}, {_id:17228,name: "Vilanant",province_id: 17}, {_id:17230,name: "Vila-sacra",province_id: 17}, {_id:17232,name: "Vilopriu",province_id: 17}, {_id:17233,name: "<NAME>",province_id: 17}, {_id:17234,name: "Biure",province_id: 17}, {_id:17901,name: "Cruïlles,province_id: Monells i Sant Sadurní de l Heura"}, {_id:17902,name: "Forallac",province_id: 17}, {_id:17903,name: "<NAME>",province_id: 17}, {_id:18001,name: "Agrón",province_id: 18}, {_id:18002,name: "Alamedilla",province_id: 18}, {_id:18003,name: "Albolote",province_id: 18}, {_id:18004,name: "Albondón",province_id: 18}, {_id:18005,name: "Albuñán",province_id: 18}, {_id:18006,name: "Albuñol",province_id: 18}, {_id:18007,name: "Albuñuelas",province_id: 18}, {_id:18010,name: "Aldeire",province_id: 18}, {_id:18011,name: "Alfacar",province_id: 18}, {_id:18012,name: "Algarinejo",province_id: 18}, {_id:18013,name: "<NAME>",province_id: 18}, {_id:18014,name: "Alhendín",province_id: 18}, {_id:18015,name: "<NAME>",province_id: 18}, {_id:18016,name: "Almegíjar",province_id: 18}, {_id:18017,name: "Almuñécar",province_id: 18}, {_id:18018,name: "Alquife",province_id: 18}, {_id:18020,name: "<NAME>",province_id: 18}, {_id:18021,name: "Armilla",province_id: 18}, {_id:18022,name: "Atarfe",province_id: 18}, {_id:18023,name: "Baza",province_id: 18}, {_id:18024,name: "<NAME>",province_id: 18}, {_id:18025,name: "<NAME>",province_id: 18}, {_id:18027,name: "Benalúa",province_id: 18}, {_id:18028,name: "<NAME>",province_id: 18}, {_id:18029,name: "Benamaurel",province_id: 18}, {_id:18030,name: "Bérchules",province_id: 18}, {_id:18032,name: "Bubión",province_id: 18}, {_id:18033,name: "Busquístar",province_id: 18}, {_id:18034,name: "Cacín",province_id: 18}, {_id:18035,name: "Cádiar",province_id: 18}, {_id:18036,name: "Cájar",province_id: 18}, {_id:18037,name: "Calicasas",province_id: 18}, {_id:18038,name: "Campotéjar",province_id: 18}, {_id:18039,name: "Caniles",province_id: 18}, {_id:18040,name: "Cáñar",province_id: 18}, {_id:18042,name: "Capileira",province_id: 18}, {_id:18043,name: "Carataunas",province_id: 18}, {_id:18044,name: "Cástaras",province_id: 18}, {_id:18045,name: "Castilléjar",province_id: 18}, {_id:18046,name: "Castril",province_id: 18}, {_id:18047,name: "<NAME>",province_id: 18}, {_id:18048,name: "Cijuela",province_id: 18}, {_id:18049,name: "<NAME>",province_id: 18}, {_id:18050,name: "<NAME>",province_id: 18}, {_id:18051,name: "Colomera",province_id: 18}, {_id:18053,name: "<NAME>",province_id: 18}, {_id:18054,name: "<NAME>",province_id: 18}, {_id:18056,name: "Cúllar",province_id: 18}, {_id:18057,name: "<NAME>",province_id: 18}, {_id:18059,name: "Chauchina",province_id: 18}, {_id:18061,name: "Chimeneas",province_id: 18}, {_id:18062,name: "<NAME>",province_id: 18}, {_id:18063,name: "Darro",province_id: 18}, {_id:18064,name: "<NAME>",province_id: 18}, {_id:18066,name: "Deifontes",province_id: 18}, {_id:18067,name: "Diezma",province_id: 18}, {_id:18068,name: "Dílar",province_id: 18}, {_id:18069,name: "Dólar",province_id: 18}, {_id:18070,name: "Dúdar",province_id: 18}, {_id:18071,name: "Dúrcal",province_id: 18}, {_id:18072,name: "Escúzar",province_id: 18}, {_id:18074,name: "Ferreira",province_id: 18}, {_id:18076,name: "Fonelas",province_id: 18}, {_id:18078,name: "Freila",province_id: 18}, {_id:18079,name: "<NAME>",province_id: 18}, {_id:18082,name: "Galera",province_id: 18}, {_id:18083,name: "Gobernador",province_id: 18}, {_id:18084,name: "Gójar",province_id: 18}, {_id:18085,name: "Gor",province_id: 18}, {_id:18086,name: "Gorafe",province_id: 18}, {_id:18087,name: "Granada",province_id: 18}, {_id:18088,name: "Guadahortuna",province_id: 18}, {_id:18089,name: "Guadix",province_id: 18}, {_id:18093,name: "Gualchos",province_id: 18}, {_id:18094,name: "<NAME>",province_id: 18}, {_id:18095,name: "Güevéjar",province_id: 18}, {_id:18096,name: "Huélago",province_id: 18}, {_id:18097,name: "Huéneja",province_id: 18}, {_id:19223,name: "<NAME>",province_id: 19}, {_id:19224,name: "<NAME>",province_id: 19}, {_id:19225,name: "<NAME>",province_id: 19}, {_id:19226,name: "<NAME>",province_id: 19}, {_id:19227,name: "<NAME>",province_id: 19}, {_id:19228,name: "<NAME>",province_id: 19}, {_id:19229,name: "<NAME>",province_id: 19}, {_id:19230,name: "Quer",province_id: 19}, {_id:19231,name: "<NAME>",province_id: 19}, {_id:19232,name: "<NAME>)",province_id: 19}, {_id:19233,name: "Renera",province_id: 19}, {_id:19234,name: "Retiendas",province_id: 19}, {_id:19235,name: "<NAME>",province_id: 19}, {_id:19237,name: "<NAME>",province_id: 19}, {_id:19238,name: "<NAME>",province_id: 19}, {_id:19239,name: "<NAME>",province_id: 19}, {_id:19240,name: "<NAME>",province_id: 19}, {_id:19241,name: "<NAME>",province_id: 19}, {_id:19242,name: "Romanones",province_id: 19}, {_id:19243,name: "<NAME>",province_id: 19}, {_id:19244,name: "Sacecorbo",province_id: 19}, {_id:19245,name: "Sacedón",province_id: 19}, {_id:19246,name: "<NAME>",province_id: 19}, {_id:19247,name: "Salmerón",province_id: 19}, {_id:19248,name: "<NAME>",province_id: 19}, {_id:19249,name: "<NAME>",province_id: 19}, {_id:19250,name: "Santiuste",province_id: 19}, {_id:19251,name: "Saúca",province_id: 19}, {_id:19252,name: "Sayatón",province_id: 19}, {_id:19254,name: "Selas",province_id: 19}, {_id:19255,name: "Setiles",province_id: 19}, {_id:19256,name: "Sienes",province_id: 19}, {_id:19257,name: "Sigüenza",province_id: 19}, {_id:19258,name: "<NAME>",province_id: 19}, {_id:19259,name: "Somolinos",province_id: 19}, {_id:19260,name: "<NAME>)",province_id: 19}, {_id:19261,name: "Sotodosos",province_id: 19}, {_id:19262,name: "Tamajón",province_id: 19}, {_id:19263,name: "Taragudo",province_id: 19}, {_id:19264,name: "Taravilla",province_id: 19}, {_id:19265,name: "Tartanedo",province_id: 19}, {_id:19266,name: "Tendilla",province_id: 19}, {_id:19267,name: "Terzaga",province_id: 19}, {_id:19268,name: "Tierzo",province_id: 19}, {_id:19269,name: "<NAME>)",province_id: 19}, {_id:19270,name: "Tordelrábano",province_id: 19}, {_id:19271,name: "Tordellego",province_id: 19}, {_id:19272,name: "Tordesilos",province_id: 19}, {_id:19274,name: "Torija",province_id: 19}, {_id:19277,name: "<NAME>",province_id: 19}, {_id:19278,name: "Torrecuadradilla",province_id: 19}, {_id:19279,name: "<NAME>",province_id: 19}, {_id:19280,name: "<NAME>",province_id: 19}, {_id:19281,name: "<NAME>",province_id: 19}, {_id:19282,name: "<NAME>",province_id: 19}, {_id:19283,name: "<NAME>",province_id: 19}, {_id:19284,name: "Torremochuela",province_id: 19}, {_id:19285,name: "Torrubia",province_id: 19}, {_id:19286,name: "<NAME>",province_id: 19}, {_id:19287,name: "Tortuera",province_id: 19}, {_id:19288,name: "Tortuero",province_id: 19}, {_id:19289,name: "Traíd",province_id: 19}, {_id:19290,name: "Trijueque",province_id: 19}, {_id:19291,name: "Trillo",province_id: 19}, {_id:19293,name: "Uceda",province_id: 19}, {_id:19294,name: "Ujados",province_id: 19}, {_id:19296,name: "Utande",province_id: 19}, {_id:19297,name: "Valdarachas",province_id: 19}, {_id:19298,name: "Valdearenas",province_id: 19}, {_id:19299,name: "Valdeavellano",province_id: 19}, {_id:19300,name: "Valdeaveruelo",province_id: 19}, {_id:19301,name: "Valdeconcha",province_id: 19}, {_id:19302,name: "Valdegrudas",province_id: 19}, {_id:19303,name: "Valdelcubo",province_id: 19}, {_id:19304,name: "<NAME>",province_id: 19}, {_id:19305,name: "<NAME>",province_id: 19}, {_id:19306,name: "Valderrebollo",province_id: 19}, {_id:19307,name: "Valdesotos",province_id: 19}, {_id:19308,name: "<NAME>",province_id: 19}, {_id:19309,name: "Valhermoso",province_id: 19}, {_id:19310,name: "<NAME>",province_id: 19}, {_id:19311,name: "<NAME>",province_id: 19}, {_id:19314,name: "<NAME>",province_id: 19}, {_id:19317,name: "<NAME>",province_id: 19}, {_id:19318,name: "<NAME>",province_id: 19}, {_id:19319,name: "<NAME>",province_id: 19}, {_id:19321,name: "<NAME>",province_id: 19}, {_id:19322,name: "<NAME>",province_id: 19}, {_id:19323,name: "<NAME>",province_id: 19}, {_id:19324,name: "<NAME>",province_id: 19}, {_id:19325,name: "Viñuelas",province_id: 19}, {_id:19326,name: "Yebes",province_id: 19}, {_id:19327,name: "Yebra",province_id: 19}, {_id:19329,name: "<NAME>",province_id: 19}, {_id:19330,name: "<NAME>",province_id: 19}, {_id:19331,name: "<NAME>",province_id: 19}, {_id:19332,name: "<NAME>)",province_id: 19}, {_id:19333,name: "Zaorejas",province_id: 19}, {_id:19334,name: "<NAME>",province_id: 19}, {_id:19335,name: "<NAME>",province_id: 19}, {_id:19901,name: "Semillas",province_id: 19}, {_id:20001,name: "Abaltzisketa",province_id: 20}, {_id:20002,name: "Aduna",province_id: 20}, {_id:20003,name: "Aizarnazabal",province_id: 20}, {_id:20004,name: "Albiztur",province_id: 20}, {_id:20005,name: "Alegia",province_id: 20}, {_id:20006,name: "Alkiza",province_id: 20}, {_id:20007,name: "Altzo",province_id: 20}, {_id:20008,name: "Amezketa",province_id: 20}, {_id:20009,name: "Andoain",province_id: 20}, {_id:20010,name: "Anoeta",province_id: 20}, {_id:20011,name: "Antzuola",province_id: 20}, {_id:20012,name: "Arama",province_id: 20}, {_id:20013,name: "Aretxabaleta",province_id: 20}, {_id:20014,name: "Asteasu",province_id: 20}, {_id:20015,name: "Ataun",province_id: 20}, {_id:20016,name: "Aia",province_id: 20}, {_id:20017,name: "Azkoitia",province_id: 20}, {_id:20018,name: "Azpeitia",province_id: 20}, {_id:20019,name: "Beasain",province_id: 20}, {_id:20020,name: "Beizama",province_id: 20}, {_id:20021,name: "Belauntza",province_id: 20}, {_id:20022,name: "Berastegi",province_id: 20}, {_id:20023,name: "Berrobi",province_id: 20}, {_id:20024,name: "Bidegoian",province_id: 20}, {_id:20025,name: "Zegama",province_id: 20}, {_id:20026,name: "Zerain",province_id: 20}, {_id:20027,name: "Zestoa",province_id: 20}, {_id:20028,name: "Zizurkil",province_id: 20}, {_id:20029,name: "Deba",province_id: 20}, {_id:20030,name: "Eibar",province_id: 20}, {_id:20031,name: "Elduain",province_id: 20}, {_id:20032,name: "Elgoibar",province_id: 20}, {_id:20033,name: "Elgeta",province_id: 20}, {_id:20034,name: "Eskoriatza",province_id: 20}, {_id:20035,name: "Ezkio-Itsaso",province_id: 20}, {_id:20036,name: "Hondarribia",province_id: 20}, {_id:20037,name: "Gaintza",province_id: 20}, {_id:20038,name: "Gabiria",province_id: 20}, {_id:20039,name: "Getaria",province_id: 20}, {_id:20040,name: "Hernani",province_id: 20}, {_id:20041,name: "Hernialde",province_id: 20}, {_id:20042,name: "Ibarra",province_id: 20}, {_id:20043,name: "Idiazabal",province_id: 20}, {_id:20044,name: "Ikaztegieta",province_id: 20}, {_id:20045,name: "Irun",province_id: 20}, {_id:20046,name: "Irura",province_id: 20}, {_id:20047,name: "Itsasondo",province_id: 20}, {_id:20048,name: "Larraul",province_id: 20}, {_id:20049,name: "Lazkao",province_id: 20}, {_id:20050,name: "Leaburu",province_id: 20}, {_id:20051,name: "Legazpi",province_id: 20}, {_id:20052,name: "Legorreta",province_id: 20}, {_id:20053,name: "Lezo",province_id: 20}, {_id:20054,name: "Lizartza",province_id: 20}, {_id:20055,name: "Arrasate/Mondragón",province_id: 20}, {_id:20056,name: "Mutriku",province_id: 20}, {_id:20057,name: "Mutiloa",province_id: 20}, {_id:20058,name: "Olaberria",province_id: 20}, {_id:20059,name: "Oñati",province_id: 20}, {_id:20060,name: "Orexa",province_id: 20}, {_id:20061,name: "Orio",province_id: 20}, {_id:20062,name: "Ormaiztegi",province_id: 20}, {_id:20063,name: "Oiartzun",province_id: 20}, {_id:20064,name: "Pasaia",province_id: 20}, {_id:20065,name: "Soraluze/<NAME> las Armas",province_id: 20}, {_id:20066,name: "Errezil",province_id: 20}, {_id:20067,name: "Errenteria",province_id: 20}, {_id:20068,name: "Leintz-Gatzaga",province_id: 20}, {_id:20069,name: "Donostia-<NAME>",province_id: 20}, {_id:20070,name: "Segura",province_id: 20}, {_id:20071,name: "Tolosa",province_id: 20}, {_id:20072,name: "Urnieta",province_id: 20}, {_id:20073,name: "Usurbil",province_id: 20}, {_id:20074,name: "Bergara",province_id: 20}, {_id:20075,name: "Villabona",province_id: 20}, {_id:20076,name: "Ordizia",province_id: 20}, {_id:20077,name: "Urretxu",province_id: 20}, {_id:20078,name: "Zaldibia",province_id: 20}, {_id:20079,name: "Zarautz",province_id: 20}, {_id:20080,name: "Zumarraga",province_id: 20}, {_id:20081,name: "Zumaia",province_id: 20}, {_id:20901,name: "Mendaro",province_id: 20}, {_id:20902,name: "Lasarte-Oria",province_id: 20}, {_id:20903,name: "Astigarraga",province_id: 20}, {_id:20904,name: "Baliarrain",province_id: 20}, {_id:20905,name: "Orendain",province_id: 20}, {_id:20906,name: "Altzaga",province_id: 20}, {_id:20907,name: "Gaztelu",province_id: 20}, {_id:21001,name: "Alájar",province_id: 21}, {_id:21002,name: "Aljaraque",province_id: 21}, {_id:21003,name: "Almendro (El)",province_id: 21}, {_id:21004,name: "<NAME>",province_id: 21}, {_id:21005,name: "Almonte",province_id: 21}, {_id:21006,name: "Alosno",province_id: 21}, {_id:21007,name: "Aracena",province_id: 21}, {_id:21008,name: "Aroche",province_id: 21}, {_id:21009,name: "<NAME>",province_id: 21}, {_id:21010,name: "Ayamonte",province_id: 21}, {_id:21011,name: "Beas",province_id: 21}, {_id:21012,name: "Berrocal",province_id: 21}, {_id:21013,name: "<NAME>",province_id: 21}, {_id:21014,name: "Bonares",province_id: 21}, {_id:21015,name: "<NAME>",province_id: 21}, {_id:21016,name: "Cala",province_id: 21}, {_id:21017,name: "Calañas",province_id: 21}, {_id:21018,name: "Campillo (El)",province_id: 21}, {_id:21019,name: "Campofrío",province_id: 21}, {_id:21020,name: "<NAME>",province_id: 21}, {_id:21021,name: "Cartaya",province_id: 21}, {_id:21022,name: "<NAME>",province_id: 21}, {_id:21023,name: "<NAME> (El)",province_id: 21}, {_id:21024,name: "Corteconcepción",province_id: 21}, {_id:21025,name: "Cortegana",province_id: 21}, {_id:21026,name: "Cortelazor",province_id: 21}, {_id:21027,name: "<NAME>",province_id: 21}, {_id:21028,name: "<NAME>",province_id: 21}, {_id:21029,name: "<NAME>",province_id: 21}, {_id:21030,name: "Chucena",province_id: 21}, {_id:21031,name: "Encinasola",province_id: 21}, {_id:21032,name: "<NAME>",province_id: 21}, {_id:21033,name: "Fuenteheridos",province_id: 21}, {_id:21034,name: "Galaroza",province_id: 21}, {_id:21035,name: "Gibraleón",province_id: 21}, {_id:21036,name: "<NAME> (La)",province_id: 21}, {_id:21037,name: "Granado (El)",province_id: 21}, {_id:21038,name: "<NAME>",province_id: 21}, {_id:21039,name: "Hinojales",province_id: 21}, {_id:21040,name: "Hinojos",province_id: 21}, {_id:21041,name: "Huelva",province_id: 21}, {_id:21042,name: "<NAME>",province_id: 21}, {_id:21043,name: "Jabugo",province_id: 21}, {_id:21044,name: "Lepe",province_id: 21}, {_id:21045,name: "<NAME>",province_id: 21}, {_id:21046,name: "<NAME>",province_id: 21}, {_id:21047,name: "Manzanilla",province_id: 21}, {_id:21048,name: "Marines (Los)",province_id: 21}, {_id:21049,name: "<NAME>",province_id: 21}, {_id:21050,name: "Moguer",province_id: 21}, {_id:21051,name: "Nava (La)",province_id: 21}, {_id:21052,name: "Nerva",province_id: 21}, {_id:21053,name: "Niebla",province_id: 21}, {_id:21054,name: "<NAME> (La)",province_id: 21}, {_id:21055,name: "<NAME>",province_id: 21}, {_id:21056,name: "<NAME>",province_id: 21}, {_id:21057,name: "Paymogo",province_id: 21}, {_id:21058,name: "<NAME>",province_id: 21}, {_id:21059,name: "<NAME>",province_id: 21}, {_id:21060,name: "<NAME>",province_id: 21}, {_id:21061,name: "<NAME>",province_id: 21}, {_id:21062,name: "<NAME>",province_id: 21}, {_id:21063,name: "<NAME>",province_id: 21}, {_id:21064,name: "<NAME>",province_id: 21}, {_id:21065,name: "<NAME>",province_id: 21}, {_id:21066,name: "<NAME>",province_id: 21}, {_id:21067,name: "<NAME>",province_id: 21}, {_id:21068,name: "<NAME>",province_id: 21}, {_id:21069,name: "<NAME>",province_id: 21}, {_id:21070,name: "Trigueros",province_id: 21}, {_id:21071,name: "Valdelarco",province_id: 21}, {_id:21072,name: "<NAME>",province_id: 21}, {_id:21073,name: "Villablanca",province_id: 21}, {_id:21074,name: "<NAME>",province_id: 21}, {_id:21075,name: "<NAME>",province_id: 21}, {_id:21076,name: "<NAME>",province_id: 21}, {_id:21077,name: "Villarrasa",province_id: 21}, {_id:21078,name: "<NAME>",province_id: 21}, {_id:21079,name: "Zufre",province_id: 21}, {_id:22001,name: "Abiego",province_id: 22}, {_id:22002,name: "Abizanda",province_id: 22}, {_id:22003,name: "Adahuesca",province_id: 22}, {_id:22004,name: "Agüero",province_id: 22}, {_id:22006,name: "Aisa",province_id: 22}, {_id:22007,name: "<NAME>",province_id: 22}, {_id:22008,name: "Albalatillo",province_id: 22}, {_id:22009,name: "Albelda",province_id: 22}, {_id:22011,name: "<NAME>",province_id: 22}, {_id:22012,name: "<NAME>",province_id: 22}, {_id:22013,name: "<NAME>",province_id: 22}, {_id:22014,name: "<NAME>",province_id: 22}, {_id:22015,name: "<NAME>",province_id: 22}, {_id:22016,name: "Alcampell",province_id: 22}, {_id:22017,name: "<NAME>",province_id: 22}, {_id:22018,name: "Alcubierre",province_id: 22}, {_id:22019,name: "Alerre",province_id: 22}, {_id:4073,name: "<NAME>",province_id: 4}, {_id:4074,name: "Pechina",province_id: 4}, {_id:4075,name: "Pulpí",province_id: 4}, {_id:4076,name: "Purchena",province_id: 4}, {_id:4077,name: "Rágol",province_id: 4}, {_id:4078,name: "Rioja",province_id: 4}, {_id:4079,name: "<NAME>",province_id: 4}, {_id:4080,name: "<NAME>",province_id: 4}, {_id:4081,name: "<NAME>",province_id: 4}, {_id:4082,name: "Senés",province_id: 4}, {_id:4083,name: "Serón",province_id: 4}, {_id:4084,name: "Sierro",province_id: 4}, {_id:4085,name: "Somontín",province_id: 4}, {_id:4086,name: "Sorbas",province_id: 4}, {_id:4087,name: "Suflí",province_id: 4}, {_id:4088,name: "Tabernas",province_id: 4}, {_id:4089,name: "Taberno",province_id: 4}, {_id:4090,name: "Tahal",province_id: 4}, {_id:4091,name: "Terque",province_id: 4}, {_id:4092,name: "Tíjola",province_id: 4}, {_id:4093,name: "Turre",province_id: 4}, {_id:4094,name: "Turrillas",province_id: 4}, {_id:4095,name: "<NAME>",province_id: 4}, {_id:4096,name: "Urrácal",province_id: 4}, {_id:4097,name: "Velefique",province_id: 4}, {_id:4098,name: "Vélez-Blanco",province_id: 4}, {_id:4099,name: "Vélez-Rubio",province_id: 4}, {_id:4100,name: "Vera",province_id: 4}, {_id:4101,name: "Viator",province_id: 4}, {_id:4102,name: "Vícar",province_id: 4}, {_id:4103,name: "Zurgena",province_id: 4}, {_id:4901,name: "<NAME> (Las)",province_id: 4}, {_id:4902,name: "Ejido (El)",province_id: 4}, {_id:4903,name: "Mojonera (La)",province_id: 4}, {_id:5001,name: "Adanero",province_id: 5}, {_id:5002,name: "Adrada (La)",province_id: 5}, {_id:5005,name: "Albornos",province_id: 5}, {_id:5007,name: "<NAME>",province_id: 5}, {_id:5008,name: "Aldeaseca",province_id: 5}, {_id:5010,name: "Aldehuela (La)",province_id: 5}, {_id:5012,name: "Amavida",province_id: 5}, {_id:5013,name: "Arenal (El)",province_id: 5}, {_id:5014,name: "<NAME>",province_id: 5}, {_id:5015,name: "Arevalillo",province_id: 5}, {_id:5016,name: "Arévalo",province_id: 5}, {_id:5017,name: "Aveinte",province_id: 5}, {_id:5018,name: "Avellaneda",province_id: 5}, {_id:5019,name: "Ávila",province_id: 5}, {_id:5021,name: "<NAME> (El)",province_id: 5}, {_id:5022,name: "Barraco (El)",province_id: 5}, {_id:5023,name: "Barromán",province_id: 5}, {_id:5024,name: "Becedas",province_id: 5}, {_id:5025,name: "Becedillas",province_id: 5}, {_id:5026,name: "<NAME>",province_id: 5}, {_id:5027,name: "Berlanas (Las)",province_id: 5}, {_id:5029,name: "Bernuy-Zapardiel",province_id: 5}, {_id:5030,name: "<NAME>",province_id: 5}, {_id:5033,name: "Blascomillán",province_id: 5}, {_id:5034,name: "<NAME>",province_id: 5}, {_id:5035,name: "Blascosancho",province_id: 5}, {_id:5036,name: "Bohodón (El)",province_id: 5}, {_id:5037,name: "Bohoyo",province_id: 5}, {_id:5038,name: "<NAME>",province_id: 5}, {_id:5039,name: "Brabos",province_id: 5}, {_id:5040,name: "Bularros",province_id: 5}, {_id:5041,name: "Burgohondo",province_id: 5}, {_id:5042,name: "<NAME>",province_id: 5}, {_id:5043,name: "<NAME>",province_id: 5}, {_id:5044,name: "<NAME>",province_id: 5}, {_id:5045,name: "Cabizuela",province_id: 5}, {_id:5046,name: "Canales",province_id: 5}, {_id:5047,name: "Candeleda",province_id: 5}, {_id:5048,name: "Cantiveros",province_id: 5}, {_id:5049,name: "Cardeñosa",province_id: 5}, {_id:5051,name: "Carrera (La)",province_id: 5}, {_id:5052,name: "<NAME>",province_id: 5}, {_id:5053,name: "Casasola",province_id: 5}, {_id:5054,name: "Casavieja",province_id: 5}, {_id:5055,name: "Casillas",province_id: 5}, {_id:5056,name: "<NAME>",province_id: 5}, {_id:5057,name: "Cebreros",province_id: 5}, {_id:5058,name: "<NAME>",province_id: 5}, {_id:5059,name: "Cillán",province_id: 5}, {_id:5060,name: "Cisla",province_id: 5}, {_id:5061,name: "<NAME>)",province_id: 5}, {_id:5062,name: "<NAME>",province_id: 5}, {_id:5063,name: "<NAME>",province_id: 5}, {_id:5064,name: "Constanzana",province_id: 5}, {_id:5065,name: "Crespos",province_id: 5}, {_id:5066,name: "<NAME>",province_id: 5}, {_id:5067,name: "Chamartín",province_id: 5}, {_id:5069,name: "Donjimeno",province_id: 5}, {_id:5070,name: "Donvidas",province_id: 5}, {_id:5072,name: "<NAME>",province_id: 5}, {_id:5073,name: "<NAME>",province_id: 5}, {_id:5074,name: "Fontiveros",province_id: 5}, {_id:5075,name: "Fresnedilla",province_id: 5}, {_id:5076,name: "<NAME>)",province_id: 5}, {_id:5077,name: "<NAME>",province_id: 5}, {_id:5078,name: "<NAME>",province_id: 5}, {_id:5079,name: "<NAME>",province_id: 5}, {_id:5080,name: "<NAME>",province_id: 5}, {_id:5081,name: "<NAME>",province_id: 5}, {_id:5082,name: "Gavilanes",province_id: 5}, {_id:5083,name: "Gemuño",province_id: 5}, {_id:5084,name: "Gilbuena",province_id: 5}, {_id:5085,name: "<NAME>",province_id: 5}, {_id:5086,name: "Gimialcón",province_id: 5}, {_id:5087,name: "Gotarrendura",province_id: 5}, {_id:5088,name: "<NAME>",province_id: 5}, {_id:5089,name: "Guisando",province_id: 5}, {_id:5090,name: "Gutierre-Muñoz",province_id: 5}, {_id:5092,name: "Hernansancho",province_id: 5}, {_id:5093,name: "<NAME>",province_id: 5}, {_id:5094,name: "<NAME>",province_id: 5}, {_id:5095,name: "<NAME>",province_id: 5}, {_id:5096,name: "<NAME>)",province_id: 5}, {_id:5097,name: "Horcajada (La)",province_id: 5}, {_id:5099,name: "<NAME>",province_id: 5}, {_id:5100,name: "Hornillo (El)",province_id: 5}, {_id:5101,name: "Hoyocasero",province_id: 5}, {_id:5102,name: "<NAME> (El)",province_id: 5}, {_id:5103,name: "Hoyorredondo",province_id: 5}, {_id:5104,name: "<NAME>",province_id: 5}, {_id:5105,name: "<NAME>",province_id: 5}, {_id:5106,name: "<NAME> <NAME>",province_id: 5}, {_id:5107,name: "Hurtumpascual",province_id: 5}, {_id:5108,name: "Junciana",province_id: 5}, {_id:5109,name: "Langa",province_id: 5}, {_id:5110,name: "Lanzahíta",province_id: 5}, {_id:5112,name: "<NAME> (El)",province_id: 5}, {_id:5113,name: "<NAME> (Los)",province_id: 5}, {_id:5114,name: "<NAME>",province_id: 5}, {_id:5115,name: "Maello",province_id: 5}, {_id:5116,name: "<NAME>",province_id: 5}, {_id:5117,name: "Mamblas",province_id: 5}, {_id:5118,name: "<NAME>",province_id: 5}, {_id:5119,name: "Manjabálago",province_id: 5}, {_id:5120,name: "Marlín",province_id: 5}, {_id:5121,name: "Martiherrero",province_id: 5}, {_id:5122,name: "Martínez",province_id: 5}, {_id:5123,name: "<NAME>",province_id: 5}, {_id:5124,name: "Medinilla",province_id: 5}, {_id:5125,name: "Mengamuñoz",province_id: 5}, {_id:5126,name: "<NAME>",province_id: 5}, {_id:5127,name: "Mijares",province_id: 5}, {_id:5128,name: "Mingorría",province_id: 5}, {_id:5129,name: "<NAME>)",province_id: 5}, {_id:5130,name: "Mironcillo",province_id: 5}, {_id:5131,name: "<NAME>",province_id: 5}, {_id:5132,name: "Mombeltrán",province_id: 5}, {_id:5133,name: "Monsalupe",province_id: 5}, {_id:5134,name: "<NAME>",province_id: 5}, {_id:5135,name: "Muñana",province_id: 5}, {_id:5136,name: "Muñico",province_id: 5}, {_id:5138,name: "Muñogalindo",province_id: 5}, {_id:5139,name: "Muñogrande",province_id: 5}, {_id:5140,name: "<NAME>",province_id: 5}, {_id:5141,name: "Muñopepe",province_id: 5}, {_id:5142,name: "Muñosancho",province_id: 5}, {_id:5143,name: "Muñotello",province_id: 5}, {_id:5144,name: "<NAME>",province_id: 5}, {_id:5145,name: "<NAME>",province_id: 5}, {_id:5147,name: "<NAME>",province_id: 5}, {_id:5148,name: "<NAME>",province_id: 5}, {_id:5149,name: "<NAME>",province_id: 5}, {_id:5151,name: "<NAME>",province_id: 5}, {_id:5152,name: "<NAME>",province_id: 5}, {_id:5153,name: "<NAME>",province_id: 5}, {_id:5154,name: "Navadijos",province_id: 5}, {_id:5155,name: "Navaescurial",province_id: 5}, {_id:5156,name: "Navahondilla",province_id: 5}, {_id:5157,name: "Navalacruz",province_id: 5}, {_id:5158,name: "Navalmoral",province_id: 5}, {_id:5159,name: "Navalonguilla",province_id: 5}, {_id:5160,name: "Navalosa",province_id: 5}, {_id:5161,name: "<NAME>",province_id: 5}, {_id:5162,name: "<NAME>",province_id: 5}, {_id:5163,name: "Navaluenga",province_id: 5}, {_id:5164,name: "Navaquesera",province_id: 5}, {_id:5165,name: "<NAME>",province_id: 5}, {_id:5166,name: "Navarredondilla",province_id: 5}, {_id:5167,name: "Navarrevisca",province_id: 5}, {_id:5168,name: "<NAME>)",province_id: 5}, {_id:5169,name: "Navatalgordo",province_id: 5}, {_id:5170,name: "Navatejares",province_id: 5}, {_id:5171,name: "<NAME>",province_id: 5}, {_id:5172,name: "Niharra",province_id: 5}, {_id:5173,name: "Ojos-Albos",province_id: 5}, {_id:5174,name: "Orbita",province_id: 5}, {_id:5175,name: "<NAME>)",province_id: 5}, {_id:5176,name: "Padiernos",province_id: 5}, {_id:5177,name: "<NAME>",province_id: 5}, {_id:5178,name: "<NAME>",province_id: 5}, {_id:5179,name: "Papatrigo",province_id: 5}, {_id:5180,name: "<NAME>)",province_id: 5}, {_id:5181,name: "Pascualcobo",province_id: 5}, {_id:5182,name: "<NAME>",province_id: 5}, {_id:5183,name: "Pedro-Rodríguez",province_id: 5}, {_id:5184,name: "Peguerinos",province_id: 5}, {_id:5185,name: "<NAME>",province_id: 5}, {_id:5186,name: "Piedrahíta",province_id: 5}, {_id:5187,name: "Piedralaves",province_id: 5}, {_id:5188,name: "Poveda",province_id: 5}, {_id:5189,name: "<NAME>",province_id: 5}, {_id:5190,name: "Pozanco",province_id: 5}, {_id:5191,name: "Pradosegar",province_id: 5}, {_id:5192,name: "<NAME>",province_id: 5}, {_id:5193,name: "Rasueros",province_id: 5}, {_id:5194,name: "Riocabado",province_id: 5}, {_id:5195,name: "Riofrío",province_id: 5}, {_id:5196,name: "<NAME>",province_id: 5}, {_id:5197,name: "Salobral",province_id: 5}, {_id:5198,name: "Salvadiós",province_id: 5}, {_id:5199,name: "San Bartolomé de Béjar",province_id: 5}, {_id:5200,name: "San Bartolomé de Corneja",province_id: 5}, {_id:5201,name: "San Bartolomé de Pinares",province_id: 5}, {_id:5204,name: "Sanchidrián",province_id: 5}, {_id:5205,name: "Sanchorreja",province_id: 5}, {_id:5206,name: "<NAME>",province_id: 5}, {_id:5207,name: "<NAME>",province_id: 5}, {_id:5208,name: "San Esteban de Zapardiel",province_id: 5}, {_id:5209,name: "<NAME>",province_id: 5}, {_id:5210,name: "<NAME>",province_id: 5}, {_id:5211,name: "<NAME>",province_id: 5}, {_id:5212,name: "<NAME>",province_id: 5}, {_id:5213,name: "<NAME>",province_id: 5}, {_id:5214,name: "<NAME>",province_id: 5}, {_id:5215,name: "<NAME>",province_id: 5}, {_id:5216,name: "<NAME>",province_id: 5}, {_id:5217,name: "<NAME>",province_id: 5}, {_id:5218,name: "<NAME>",province_id: 5}, {_id:5219,name: "San Pascual",province_id: 5}, {_id:5220,name: "<NAME>",province_id: 5}, {_id:5221,name: "<NAME> del Valle",province_id: 5}, {_id:5222,name: "<NAME>",province_id: 5}, {_id:5224,name: "<NAME>",province_id: 5}, {_id:28140,name: "<NAME>",province_id: 28}, {_id:28141,name: "<NAME>",province_id: 28}, {_id:28143,name: "Somosierra",province_id: 28}, {_id:28144,name: "<NAME>",province_id: 28}, {_id:28145,name: "<NAME>",province_id: 28}, {_id:28146,name: "Tielmes",province_id: 28}, {_id:28147,name: "Titulcia",province_id: 28}, {_id:28148,name: "<NAME>",province_id: 28}, {_id:28149,name: "<NAME>",province_id: 28}, {_id:28150,name: "<NAME>",province_id: 28}, {_id:28151,name: "Torrelaguna",province_id: 28}, {_id:28152,name: "Torrelodones",province_id: 28}, {_id:28153,name: "<NAME>",province_id: 28}, {_id:28154,name: "<NAME>",province_id: 28}, {_id:28155,name: "Valdaracete",province_id: 28}, {_id:28156,name: "Valdeavero",province_id: 28}, {_id:28157,name: "Valdelaguna",province_id: 28}, {_id:28158,name: "Valdemanco",province_id: 28}, {_id:28159,name: "Valdemaqueda",province_id: 28}, {_id:28160,name: "Valdemorillo",province_id: 28}, {_id:28161,name: "Valdemoro",province_id: 28}, {_id:28162,name: "Valdeolmos-Alalpardo",province_id: 28}, {_id:28163,name: "Valdepiélagos",province_id: 28}, {_id:28164,name: "<NAME>",province_id: 28}, {_id:28165,name: "Valdilecha",province_id: 28}, {_id:28166,name: "<NAME>",province_id: 28}, {_id:28167,name: "<NAME>",province_id: 28}, {_id:28168,name: "<NAME>)",province_id: 28}, {_id:28169,name: "Venturada",province_id: 28}, {_id:28170,name: "Villaconejos",province_id: 28}, {_id:28171,name: "<NAME>",province_id: 28}, {_id:28172,name: "Villalbilla",province_id: 28}, {_id:28173,name: "<NAME>",province_id: 28}, {_id:28174,name: "Villamanta",province_id: 28}, {_id:28175,name: "Villamantilla",province_id: 28}, {_id:28176,name: "<NAME>",province_id: 28}, {_id:28177,name: "<NAME>",province_id: 28}, {_id:28178,name: "<NAME>",province_id: 28}, {_id:5240,name: "<NAME>",province_id: 5}, {_id:5241,name: "Tiemblo (El)",province_id: 5}, {_id:5242,name: "Tiñosillos",province_id: 5}, {_id:5243,name: "Tolbaños",province_id: 5}, {_id:5244,name: "Tormellas",province_id: 5}, {_id:5245,name: "<NAME>",province_id: 5}, {_id:5246,name: "Tórtoles",province_id: 5}, {_id:5247,name: "Torre (La)",province_id: 5}, {_id:5249,name: "Umbrías",province_id: 5}, {_id:5251,name: "<NAME>",province_id: 5}, {_id:5252,name: "Valdecasa",province_id: 5}, {_id:5253,name: "<NAME>",province_id: 5}, {_id:5254,name: "Velayos",province_id: 5}, {_id:5256,name: "Villaflor",province_id: 5}, {_id:5257,name: "<NAME>",province_id: 5}, {_id:5258,name: "<NAME>",province_id: 5}, {_id:5259,name: "<NAME>",province_id: 5}, {_id:5260,name: "<NAME>",province_id: 5}, {_id:5261,name: "<NAME>",province_id: 5}, {_id:5262,name: "<NAME>",province_id: 5}, {_id:5263,name: "Villatoro",province_id: 5}, {_id:5264,name: "<NAME>",province_id: 5}, {_id:5265,name: "Vita",province_id: 5}, {_id:5266,name: "<NAME>",province_id: 5}, {_id:5267,name: "<NAME>",province_id: 5}, {_id:5901,name: "<NAME>",province_id: 5}, {_id:5902,name: "<NAME>",province_id: 5}, {_id:5903,name: "<NAME>",province_id: 5}, {_id:5904,name: "<NAME>",province_id: 5}, {_id:5905,name: "<NAME>",province_id: 5}, {_id:6001,name: "Acedera",province_id: 6}, {_id:6002,name: "Aceuchal",province_id: 6}, {_id:6003,name: "Ahillones",province_id: 6}, {_id:6004,name: "Alange",province_id: 6}, {_id:6005,name: "Albuera (La)",province_id: 6}, {_id:6006,name: "Alburquerque",province_id: 6}, {_id:6007,name: "Alconchel",province_id: 6}, {_id:6008,name: "Alconera",province_id: 6}, {_id:6009,name: "Aljucén",province_id: 6}, {_id:6010,name: "Almendral",province_id: 6}, {_id:6011,name: "Almendralejo",province_id: 6}, {_id:6012,name: "<NAME>",province_id: 6}, {_id:6013,name: "Atalaya",province_id: 6}, {_id:6014,name: "Azuaga",province_id: 6}, {_id:6015,name: "Badajoz",province_id: 6}, {_id:6016,name: "Barcarrota",province_id: 6}, {_id:6017,name: "Baterno",province_id: 6}, {_id:6018,name: "<NAME>",province_id: 6}, {_id:6019,name: "Berlanga",province_id: 6}, {_id:6020,name: "Bienvenida",province_id: 6}, {_id:6021,name: "<NAME>",province_id: 6}, {_id:6022,name: "<NAME>",province_id: 6}, {_id:6023,name: "<NAME>",province_id: 6}, {_id:6024,name: "<NAME>",province_id: 6}, {_id:6025,name: "Calamonte",province_id: 6}, {_id:6026,name: "<NAME>",province_id: 6}, {_id:6027,name: "<NAME>",province_id: 6}, {_id:6028,name: "Campanario",province_id: 6}, {_id:6029,name: "<NAME>",province_id: 6}, {_id:6030,name: "Capilla",province_id: 6}, {_id:6031,name: "Carmonita",province_id: 6}, {_id:6032,name: "Carrascalejo (El)",province_id: 6}, {_id:6033,name: "<NAME>",province_id: 6}, {_id:6034,name: "<NAME>",province_id: 6}, {_id:6035,name: "Castilblanco",province_id: 6}, {_id:6036,name: "Castuera",province_id: 6}, {_id:6037,name: "Codosera (La)",province_id: 6}, {_id:6038,name: "<NAME>",province_id: 6}, {_id:6039,name: "Coronada (La)",province_id: 6}, {_id:6040,name: "<NAME>",province_id: 6}, {_id:6041,name: "Cristina",province_id: 6}, {_id:6042,name: "Cheles",province_id: 6}, {_id:6043,name: "<NAME>",province_id: 6}, {_id:6044,name: "<NAME>",province_id: 6}, {_id:6045,name: "<NAME>",province_id: 6}, {_id:6046,name: "Esparragalejo",province_id: 6}, {_id:6047,name: "<NAME>",province_id: 6}, {_id:6048,name: "<NAME>",province_id: 6}, {_id:6049,name: "Feria",province_id: 6}, {_id:6050,name: "<NAME>",province_id: 6}, {_id:6051,name: "<NAME>",province_id: 6}, {_id:6052,name: "<NAME>",province_id: 6}, {_id:6053,name: "<NAME>",province_id: 6}, {_id:6054,name: "<NAME>",province_id: 6}, {_id:6055,name: "<NAME>",province_id: 6}, {_id:6056,name: "Garbayuela",province_id: 6}, {_id:6057,name: "Garlitos",province_id: 6}, {_id:6058,name: "Garrovilla (La)",province_id: 6}, {_id:6059,name: "<NAME>",province_id: 6}, {_id:6060,name: "Guareña",province_id: 6}, {_id:6061,name: "<NAME>)",province_id: 6}, {_id:6062,name: "<NAME>",province_id: 6}, {_id:6063,name: "<NAME>",province_id: 6}, {_id:6064,name: "<NAME>",province_id: 6}, {_id:6065,name: "<NAME>",province_id: 6}, {_id:6066,name: "<NAME>",province_id: 6}, {_id:6067,name: "<NAME>",province_id: 6}, {_id:6068,name: "<NAME>",province_id: 6}, {_id:6069,name: "Hornachos",province_id: 6}, {_id:6070,name: "<NAME>",province_id: 6}, {_id:6071,name: "<NAME>)",province_id: 6}, {_id:6072,name: "Lobón",province_id: 6}, {_id:6073,name: "Llera",province_id: 6}, {_id:6074,name: "Llerena",province_id: 6}, {_id:6075,name: "Magacela",province_id: 6}, {_id:6076,name: "Maguilla",province_id: 6}, {_id:6077,name: "Malcocinado",province_id: 6}, {_id:6078,name: "<NAME>",province_id: 6}, {_id:6079,name: "Manchita",province_id: 6}, {_id:6080,name: "Medellín",province_id: 6}, {_id:6081,name: "<NAME>",province_id: 6}, {_id:6082,name: "Mengabril",province_id: 6}, {_id:6083,name: "Mérida",province_id: 6}, {_id:6084,name: "Mirandilla",province_id: 6}, {_id:6085,name: "Monesterio",province_id: 6}, {_id:6086,name: "Montemolín",province_id: 6}, {_id:6087,name: "<NAME>",province_id: 6}, {_id:6088,name: "Montijo",province_id: 6}, {_id:6089,name: "<NAME>)",province_id: 6}, {_id:6090,name: "<NAME> (La)",province_id: 6}, {_id:6091,name: "<NAME>",province_id: 6}, {_id:6092,name: "Nogales",province_id: 6}, {_id:6093,name: "<NAME>",province_id: 6}, {_id:6094,name: "<NAME>",province_id: 6}, {_id:6095,name: "Olivenza",province_id: 6}, {_id:6096,name: "<NAME>",province_id: 6}, {_id:6097,name: "<NAME>",province_id: 6}, {_id:6098,name: "Palomas",province_id: 6}, {_id:6099,name: "Parra (La)",province_id: 6}, {_id:6100,name: "Peñalsordo",province_id: 6}, {_id:6101,name: "<NAME>",province_id: 6}, {_id:6102,name: "<NAME>",province_id: 6}, {_id:6103,name: "Puebla de la Calzada",province_id: 6}, {_id:6104,name: "<NAME>",province_id: 6}, {_id:6105,name: "Puebla del Maestre",province_id: 6}, {_id:6106,name: "Puebla del Prior",province_id: 6}, {_id:6107,name: "<NAME>",province_id: 6}, {_id:6108,name: "<NAME>",province_id: 6}, {_id:6109,name: "<NAME>",province_id: 6}, {_id:6110,name: "Reina",province_id: 6}, {_id:6111,name: "Rena",province_id: 6}, {_id:6112,name: "<NAME>",province_id: 6}, {_id:6113,name: "<NAME>",province_id: 6}, {_id:6114,name: "Risco",province_id: 6}, {_id:6115,name: "<NAME> (La)",province_id: 6}, {_id:6116,name: "Salvaleón",province_id: 6}, {_id:6117,name: "<NAME>",province_id: 6}, {_id:6118,name: "Sancti-Spíritus",province_id: 6}, {_id:6119,name: "<NAME>",province_id: 6}, {_id:6120,name: "<NAME>",province_id: 6}, {_id:6121,name: "<NAME>",province_id: 6}, {_id:6122,name: "<NAME> (Los)",province_id: 6}, {_id:6123,name: "<NAME>ente de Alcántara",province_id: 6}, {_id:6124,name: "<NAME>",province_id: 6}, {_id:6125,name: "Siruela",province_id: 6}, {_id:6126,name: "<NAME>",province_id: 6}, {_id:6127,name: "Talarrubias",province_id: 6}, {_id:6128,name: "<NAME>",province_id: 6}, {_id:6129,name: "Táliga",province_id: 6}, {_id:6130,name: "Tamurejo",province_id: 6}, {_id:6131,name: "<NAME>",province_id: 6}, {_id:6132,name: "Torremayor",province_id: 6}, {_id:6133,name: "Torremejía",province_id: 6}, {_id:6134,name: "Trasierra",province_id: 6}, {_id:6135,name: "Trujillanos",province_id: 6}, {_id:6136,name: "Usagre",province_id: 6}, {_id:6137,name: "Valdecaballeros",province_id: 6}, {_id:6138,name: "Valdetorres",province_id: 6}, {_id:6139,name: "<NAME>",province_id: 6}, {_id:6140,name: "<NAME>",province_id: 6}, {_id:6141,name: "<NAME>",province_id: 6}, {_id:6142,name: "<NAME>",province_id: 6}, {_id:6143,name: "<NAME>",province_id: 6}, {_id:6144,name: "<NAME>",province_id: 6}, {_id:6145,name: "<NAME>",province_id: 6}, {_id:6146,name: "<NAME>",province_id: 6}, {_id:6147,name: "<NAME>",province_id: 6}, {_id:6148,name: "<NAME>",province_id: 6}, {_id:6149,name: "<NAME>",province_id: 6}, {_id:6150,name: "<NAME>",province_id: 6}, {_id:6151,name: "Villagonzalo",province_id: 6}, {_id:6152,name: "<NAME>",province_id: 6}, {_id:6153,name: "<NAME>",province_id: 6}, {_id:6154,name: "<NAME>",province_id: 6}, {_id:6155,name: "<NAME>",province_id: 6}, {_id:6156,name: "<NAME>",province_id: 6}, {_id:6157,name: "<NAME>",province_id: 6}, {_id:6158,name: "Zafra",province_id: 6}, {_id:6159,name: "Zahínos",province_id: 6}, {_id:6160,name: "<NAME>",province_id: 6}, {_id:6161,name: "Zarza-Capilla",province_id: 6}, {_id:6162,name: "<NAME>)",province_id: 6}, {_id:6901,name: "Valdelacalzada",province_id: 6}, {_id:6902,name: "<NAME>",province_id: 6}, {_id:7001,name: "Alaró",province_id: 7}, {_id:7002,name: "Alaior",province_id: 7}, {_id:7003,name: "Alcúdia",province_id: 7}, {_id:7004,name: "Algaida",province_id: 7}, {_id:7005,name: "Andratx",province_id: 7}, {_id:7006,name: "Artà",province_id: 7}, {_id:7007,name: "Banyalbufar",province_id: 7}, {_id:7008,name: "Binissalem",province_id: 7}, {_id:7009,name: "Búger",province_id: 7}, {_id:7010,name: "Bunyola",province_id: 7}, {_id:7011,name: "Calvià",province_id: 7}, {_id:7012,name: "Campanet",province_id: 7}, {_id:7013,name: "Campos",province_id: 7}, {_id:7014,name: "Capdepera",province_id: 7}, {_id:7015,name: "<NAME>",province_id: 7}, {_id:7016,name: "Consell",province_id: 7}, {_id:7017,name: "Costitx",province_id: 7}, {_id:7018,name: "Deyá",province_id: 7}, {_id:7019,name: "Escorca",province_id: 7}, {_id:7020,name: "Esporles",province_id: 7}, {_id:7021,name: "Estellencs",province_id: 7}, {_id:7022,name: "Felanitx",province_id: 7}, {_id:7023,name: "Ferreries",province_id: 7}, {_id:7024,name: "Formentera",province_id: 7}, {_id:7025,name: "Fornalutx",province_id: 7}, {_id:7026,name: "Eivissa",province_id: 7}, {_id:7027,name: "Inca",province_id: 7}, {_id:7028,name: "<NAME>",province_id: 7}, {_id:7029,name: "Lloseta",province_id: 7}, {_id:7030,name: "Llubí",province_id: 7}, {_id:7031,name: "Llucmajor",province_id: 7}, {_id:7032,name: "Mahón",province_id: 7}, {_id:7033,name: "Manacor",province_id: 7}, {_id:7034,name: "<NAME>",province_id: 7}, {_id:7035,name: "<NAME>",province_id: 7}, {_id:7036,name: "Marratxí",province_id: 7}, {_id:7037,name: "Mercadal (Es)",province_id: 7}, {_id:7038,name: "Montuïri",province_id: 7}, {_id:7039,name: "Muro",province_id: 7}, {_id:7040,name: "<NAME>",province_id: 7}, {_id:7041,name: "Petra",province_id: 7}, {_id:7042,name: "Pollença",province_id: 7}, {_id:7043,name: "Porreres",province_id: 7}, {_id:7044,name: "Pobla (Sa)",province_id: 7}, {_id:7045,name: "Puigpunyent",province_id: 7}, {_id:7046,name: "<NAME>",province_id: 7}, {_id:7047,name: "Sencelles",province_id: 7}, {_id:7048,name: "<NAME>",province_id: 7}, {_id:7049,name: "<NAME>",province_id: 7}, {_id:7050,name: "<NAME>",province_id: 7}, {_id:7051,name: "<NAME>",province_id: 7}, {_id:7052,name: "<NAME>",province_id: 7}, {_id:7053,name: "Santa Eugènia",province_id: 7}, {_id:7054,name: "Santa Eulalia del Río",province_id: 7}, {_id:7055,name: "<NAME>",province_id: 7}, {_id:7056,name: "<NAME>",province_id: 7}, {_id:7057,name: "Santanyí",province_id: 7}, {_id:7058,name: "Selva",province_id: 7}, {_id:7059,name: "Salines (Ses)",province_id: 7}, {_id:7060,name: "Sineu",province_id: 7}, {_id:7061,name: "Sóller",province_id: 7}, {_id:7062,name: "<NAME>",province_id: 7}, {_id:7063,name: "Valldemossa",province_id: 7}, {_id:12117,name: "Torreblanca",province_id: 12}, {_id:12118,name: "Torrechiva",province_id: 12}, {_id:12119,name: "<NAME> (la)",province_id: 12}, {_id:12120,name: "<NAME>",province_id: 12}, {_id:12121,name: "Traiguera",province_id: 12}, {_id:12122,name: "Useras/Useres (les)",province_id: 12}, {_id:12123,name: "Vallat",province_id: 12}, {_id:12124,name: "<NAME>",province_id: 12}, {_id:12125,name: "<NAME>",province_id: 12}, {_id:12126,name: "<NAME> (la)",province_id: 12}, {_id:12127,name: "Vallibona",province_id: 12}, {_id:12128,name: "Vilafamés",province_id: 12}, {_id:12129,name: "<NAME>/Vilafranca",province_id: 12}, {_id:12130,name: "<NAME>",province_id: 12}, {_id:12131,name: "Villamalur",province_id: 12}, {_id:12132,name: "<NAME>",province_id: 12}, {_id:12133,name: "<NAME>",province_id: 12}, {_id:8022,name: "Berga",province_id: 8}, {_id:8023,name: "<NAME>",province_id: 8}, {_id:8024,name: "Borredà",province_id: 8}, {_id:8025,name: "Bruc (El)",province_id: 8}, {_id:8026,name: "Brull (El)",province_id: 8}, {_id:8027,name: "Cabanyes (Les)",province_id: 8}, {_id:8028,name: "<NAME>",province_id: 8}, {_id:8029,name: "<NAME>",province_id: 8}, {_id:8030,name: "Cabrils",province_id: 8}, {_id:8031,name: "Calaf",province_id: 8}, {_id:8032,name: "<NAME>",province_id: 8}, {_id:8033,name: "<NAME>",province_id: 8}, {_id:8034,name: "Calders",province_id: 8}, {_id:8035,name: "Calella",province_id: 8}, {_id:8036,name: "<NAME>",province_id: 8}, {_id:8037,name: "Calldetenes",province_id: 8}, {_id:8038,name: "Callús",province_id: 8}, {_id:8039,name: "Campins",province_id: 8}, {_id:8040,name: "<NAME>",province_id: 8}, {_id:8041,name: "Canovelles",province_id: 8}, {_id:8042,name: "<NAME>",province_id: 8}, {_id:8043,name: "Canyelles",province_id: 8}, {_id:8044,name: "Capellades",province_id: 8}, {_id:8045,name: "Capolat",province_id: 8}, {_id:8046,name: "Cardedeu",province_id: 8}, {_id:8047,name: "Cardona",province_id: 8}, {_id:8048,name: "Carme",province_id: 8}, {_id:8049,name: "Casserres",province_id: 8}, {_id:8050,name: "<NAME>",province_id: 8}, {_id:8051,name: "<NAME>",province_id: 8}, {_id:8052,name: "<NAME>",province_id: 8}, {_id:8053,name: "<NAME>",province_id: 8}, {_id:8054,name: "Castellbisbal",province_id: 8}, {_id:8055,name: "Castellcir",province_id: 8}, {_id:8056,name: "Castelldefels",province_id: 8}, {_id:8057,name: "<NAME>",province_id: 8}, {_id:8058,name: "<NAME>",province_id: 8}, {_id:8059,name: "<NAME>",province_id: 8}, {_id:8060,name: "<NAME>",province_id: 8}, {_id:8061,name: "Castellgalí",province_id: 8}, {_id:8062,name: "<NAME>",province_id: 8}, {_id:8063,name: "Castellolí",province_id: 8}, {_id:8064,name: "Castellterçol",province_id: 8}, {_id:8065,name: "<NAME>",province_id: 8}, {_id:8066,name: "<NAME>",province_id: 8}, {_id:8067,name: "Centelles",province_id: 8}, {_id:8068,name: "Cervelló",province_id: 8}, {_id:8069,name: "Collbató",province_id: 8}, {_id:8070,name: "Collsuspina",province_id: 8}, {_id:8071,name: "Copons",province_id: 8}, {_id:8072,name: "<NAME>",province_id: 8}, {_id:8073,name: "<NAME>",province_id: 8}, {_id:8074,name: "Cubelles",province_id: 8}, {_id:8075,name: "Dosrius",province_id: 8}, {_id:8076,name: "Esparreguera",province_id: 8}, {_id:8077,name: "<NAME>",province_id: 8}, {_id:8078,name: "Espunyola (L )",province_id: 8}, {_id:8079,name: "Estany (L )",province_id: 8}, {_id:8080,name: "Fígols",province_id: 8}, {_id:8081,name: "<NAME>",province_id: 8}, {_id:8082,name: "<NAME>",province_id: 8}, {_id:8083,name: "Folgueroles",province_id: 8}, {_id:8084,name: "Fonollosa",province_id: 8}, {_id:8085,name: "Font-rubí",province_id: 8}, {_id:8086,name: "<NAME> (Les)",province_id: 8}, {_id:8087,name: "Gallifa",province_id: 8}, {_id:8088,name: "Garriga (La)",province_id: 8}, {_id:8089,name: "Gavà",province_id: 8}, {_id:8090,name: "Gaià",province_id: 8}, {_id:8091,name: "Gelida",province_id: 8}, {_id:8092,name: "Gironella",province_id: 8}, {_id:8093,name: "Gisclareny",province_id: 8}, {_id:8094,name: "Granada (La)",province_id: 8}, {_id:8095,name: "Granera",province_id: 8}, {_id:8096,name: "Granollers",province_id: 8}, {_id:8097,name: "Gualba",province_id: 8}, {_id:8098,name: "<NAME>",province_id: 8}, {_id:8099,name: "<NAME>",province_id: 8}, {_id:8100,name: "Gurb",province_id: 8}, {_id:8101,name: "<NAME> (L )",province_id: 8}, {_id:8102,name: "Igualada",province_id: 8}, {_id:8103,name: "Jorba",province_id: 8}, {_id:8104,name: "Llacuna (La)",province_id: 8}, {_id:8105,name: "Llagosta (La)",province_id: 8}, {_id:8106,name: "<NAME>",province_id: 8}, {_id:8107,name: "<NAME>",province_id: 8}, {_id:8108,name: "<NAME>",province_id: 8}, {_id:8109,name: "Lluçà",province_id: 8}, {_id:8110,name: "<NAME>",province_id: 8}, {_id:8111,name: "Malla",province_id: 8}, {_id:8112,name: "Manlleu",province_id: 8}, {_id:8113,name: "Manresa",province_id: 8}, {_id:8114,name: "Martorell",province_id: 8}, {_id:8115,name: "Martorelles",province_id: 8}, {_id:8116,name: "<NAME> (Les)",province_id: 8}, {_id:8117,name: "<NAME> (Les)",province_id: 8}, {_id:8118,name: "Masnou (El)",province_id: 8}, {_id:8119,name: "Masquefa",province_id: 8}, {_id:8120,name: "Matadepera",province_id: 8}, {_id:8121,name: "Mataró",province_id: 8}, {_id:8122,name: "Mediona",province_id: 8}, {_id:8123,name: "<NAME>",province_id: 8}, {_id:8124,name: "<NAME>",province_id: 8}, {_id:8125,name: "<NAME>",province_id: 8}, {_id:8126,name: "Montgat",province_id: 8}, {_id:8127,name: "<NAME>",province_id: 8}, {_id:8128,name: "<NAME>",province_id: 8}, {_id:8129,name: "Muntanyola",province_id: 8}, {_id:8130,name: "Montclar",province_id: 8}, {_id:8131,name: "Montesquiu",province_id: 8}, {_id:8132,name: "Montmajor",province_id: 8}, {_id:8133,name: "Montmaneu",province_id: 8}, {_id:8134,name: "Figaró-Montmany",province_id: 8}, {_id:8135,name: "Montmeló",province_id: 8}, {_id:8136,name: "<NAME>",province_id: 8}, {_id:8137,name: "Montseny",province_id: 8}, {_id:8138,name: "Moià",province_id: 8}, {_id:8139,name: "Mura",province_id: 8}, {_id:8140,name: "Navarcles",province_id: 8}, {_id:8141,name: "Navàs",province_id: 8}, {_id:8142,name: "<NAME>)",province_id: 8}, {_id:8143,name: "Òdena",province_id: 8}, {_id:8144,name: "Olvan",province_id: 8}, {_id:8145,name: "Olèrdola",province_id: 8}, {_id:8146,name: "<NAME>",province_id: 8}, {_id:8147,name: "<NAME>",province_id: 8}, {_id:8148,name: "Olivella",province_id: 8}, {_id:8149,name: "Olost",province_id: 8}, {_id:8150,name: "Orís",province_id: 8}, {_id:8151,name: "Oristà",province_id: 8}, {_id:8152,name: "Orpí",province_id: 8}, {_id:8153,name: "Òrrius",province_id: 8}, {_id:8154,name: "<NAME>",province_id: 8}, {_id:8155,name: "Palafolls",province_id: 8}, {_id:8156,name: "Palau-<NAME>",province_id: 8}, {_id:8157,name: "Pallejà",province_id: 8}, {_id:8158,name: "Papiol (El)",province_id: 8}, {_id:8159,name: "<NAME>",province_id: 8}, {_id:8160,name: "Perafita",province_id: 8}, {_id:8161,name: "Piera",province_id: 8}, {_id:8162,name: "<NAME> (Els)",province_id: 8}, {_id:8163,name: "<NAME>",province_id: 8}, {_id:8164,name: "<NAME> (El)",province_id: 8}, {_id:8165,name: "<NAME> (La)",province_id: 8}, {_id:8166,name: "<NAME> (La)",province_id: 8}, {_id:8167,name: "Polinyà",province_id: 8}, {_id:8168,name: "Pontons",province_id: 8}, {_id:8169,name: "<NAME> (El)",province_id: 8}, {_id:8170,name: "<NAME> (Els)",province_id: 8}, {_id:8171,name: "<NAME>",province_id: 8}, {_id:8172,name: "<NAME>",province_id: 8}, {_id:8174,name: "Puigdàlber",province_id: 8}, {_id:8175,name: "Puig-reig",province_id: 8}, {_id:8176,name: "Pujalt",province_id: 8}, {_id:8177,name: "Quar (La)",province_id: 8}, {_id:8178,name: "Rajadell",province_id: 8}, {_id:8179,name: "Rellinars",province_id: 8}, {_id:8180,name: "Ripollet",province_id: 8}, {_id:8181,name: "<NAME> (La)",province_id: 8}, {_id:8182,name: "<NAME> (El)",province_id: 8}, {_id:8183,name: "<NAME>",province_id: 8}, {_id:8184,name: "Rubí",province_id: 8}, {_id:8185,name: "Rubió",province_id: 8}, {_id:8187,name: "Sabadell",province_id: 8}, {_id:8188,name: "Sagàs",province_id: 8}, {_id:8189,name: "<NAME>",province_id: 8}, {_id:8190,name: "Saldes",province_id: 8}, {_id:8191,name: "Sallent",province_id: 8}, {_id:8192,name: "Santpedor",province_id: 8}, {_id:8193,name: "<NAME>",province_id: 8}, {_id:8194,name: "<NAME>",province_id: 8}, {_id:8195,name: "<NAME>",province_id: 8}, {_id:8196,name: "<NAME>",province_id: 8}, {_id:8197,name: "<NAME>",province_id: 8}, {_id:8198,name: "<NAME>",province_id: 8}, {_id:8199,name: "<NAME>",province_id: 8}, {_id:8200,name: "<NAME>",province_id: 8}, {_id:8201,name: "<NAME>",province_id: 8}, {_id:8202,name: "<NAME>",province_id: 8}, {_id:8203,name: "<NAME>",province_id: 8}, {_id:8204,name: "<NAME>",province_id: 8}, {_id:8205,name: "<NAME>",province_id: 8}, {_id:8206,name: "<NAME>",province_id: 8}, {_id:8207,name: "<NAME>",province_id: 8}, {_id:8208,name: "<NAME>",province_id: 8}, {_id:8209,name: "<NAME>",province_id: 8}, {_id:8210,name: "<NAME>",province_id: 8}, {_id:8211,name: "<NAME>",province_id: 8}, {_id:8212,name: "<NAME>",province_id: 8}, {_id:8213,name: "<NAME>",province_id: 8}, {_id:8214,name: "<NAME>",province_id: 8}, {_id:8215,name: "<NAME>",province_id: 8}, {_id:8216,name: "<NAME>",province_id: 8}, {_id:8217,name: "<NAME>",province_id: 8}, {_id:8218,name: "<NAME>",province_id: 8}, {_id:8219,name: "<NAME>",province_id: 8}, {_id:8220,name: "<NAME>",province_id: 8}, {_id:8221,name: "<NAME>",province_id: 8}, {_id:8222,name: "<NAME>",province_id: 8}, {_id:8223,name: "<NAME>",province_id: 8}, {_id:8224,name: "<NAME>",province_id: 8}, {_id:8225,name: "<NAME>",province_id: 8}, {_id:8226,name: "<NAME>",province_id: 8}, {_id:8227,name: "<NAME>",province_id: 8}, {_id:8228,name: "<NAME>",province_id: 8}, {_id:8229,name: "<NAME>",province_id: 8}, {_id:8230,name: "<NAME>",province_id: 8}, {_id:8231,name: "<NAME>",province_id: 8}, {_id:8232,name: "<NAME>",province_id: 8}, {_id:8233,name: "<NAME>",province_id: 8}, {_id:8234,name: "<NAME>",province_id: 8}, {_id:8235,name: "<NAME>",province_id: 8}, {_id:8236,name: "<NAME>",province_id: 8}, {_id:8237,name: "<NAME>",province_id: 8}, {_id:8238,name: "<NAME>",province_id: 8}, {_id:8239,name: "<NAME>",province_id: 8}, {_id:8240,name: "<NAME>",province_id: 8}, {_id:8241,name: "<NAME>",province_id: 8}, {_id:8242,name: "Marganell",province_id: 8}, {_id:8243,name: "<NAME>",province_id: 8}, {_id:8244,name: "Santa Coloma de Cervelló",province_id: 8}, {_id:8245,name: "Santa Coloma de Gramenet",province_id: 8}, {_id:8246,name: "Santa Eugènia de Berga",province_id: 8}, {_id:8247,name: "Santa Eulàlia de Riuprimer",province_id: 8}, {_id:8248,name: "Santa Eulàlia de Ronçana",province_id: 8}, {_id:8249,name: "Santa Fe del Penedès",province_id: 8}, {_id:8250,name: "Santa M<NAME>",province_id: 8}, {_id:8251,name: "Santa Margarida i els Monjos",province_id: 8}, {_id:8252,name: "<NAME>",province_id: 8}, {_id:8253,name: "<NAME>",province_id: 8}, {_id:8254,name: "Santa Maria de Corcó",province_id: 8}, {_id:8255,name: "Santa Maria de Merlès",province_id: 8}, {_id:8256,name: "Santa Maria de Martorelles",province_id: 8}, {_id:8257,name: "Santa Maria de Miralles",province_id: 8}, {_id:8258,name: "<NAME>",province_id: 8}, {_id:8259,name: "Santa Maria de Palautordera",province_id: 8}, {_id:8260,name: "Santa Perpètua de Mogoda",province_id: 8}, {_id:8261,name: "<NAME>",province_id: 8}, {_id:8262,name: "<NAME>",province_id: 8}, {_id:8263,name: "<NAME>",province_id: 8}, {_id:8264,name: "<NAME>",province_id: 8}, {_id:8265,name: "<NAME>",province_id: 8}, {_id:8266,name: "<NAME>",province_id: 8}, {_id:8267,name: "Sentmenat",province_id: 8}, {_id:8268,name: "Cercs",province_id: 8}, {_id:8269,name: "Seva",province_id: 8}, {_id:8270,name: "Sitges",province_id: 8}, {_id:8271,name: "Sobremunt",province_id: 8}, {_id:8272,name: "Sora",province_id: 8}, {_id:8273,name: "Subirats",province_id: 8}, {_id:8274,name: "Súria",province_id: 8}, {_id:8275,name: "Tavèrnoles",province_id: 8}, {_id:8276,name: "Tagamanent",province_id: 8}, {_id:8277,name: "Talamanca",province_id: 8}, {_id:8278,name: "Taradell",province_id: 8}, {_id:8279,name: "Terrassa",province_id: 8}, {_id:8280,name: "Tavertet",province_id: 8}, {_id:8281,name: "Teià",province_id: 8}, {_id:8282,name: "Tiana",province_id: 8}, {_id:8283,name: "Tona",province_id: 8}, {_id:8284,name: "Tordera",province_id: 8}, {_id:8285,name: "Torelló",province_id: 8}, {_id:8286,name: "<NAME> (La)",province_id: 8}, {_id:8287,name: "Torrelavit",province_id: 8}, {_id:8288,name: "<NAME>",province_id: 8}, {_id:8289,name: "<NAME>",province_id: 8}, {_id:8290,name: "Ullastrell",province_id: 8}, {_id:8291,name: "Vacarisses",province_id: 8}, {_id:8292,name: "<NAME>",province_id: 8}, {_id:8293,name: "Vallcebre",province_id: 8}, {_id:8294,name: "Vallgorguina",province_id: 8}, {_id:8295,name: "Vallirana",province_id: 8}, {_id:8296,name: "Vallromanes",province_id: 8}, {_id:8297,name: "Veciana",province_id: 8}, {_id:8298,name: "Vic",province_id: 8}, {_id:8299,name: "Vilada",province_id: 8}, {_id:8300,name: "Viladecavalls",province_id: 8}, {_id:8301,name: "Viladecans",province_id: 8}, {_id:8302,name: "<NAME>",province_id: 8}, {_id:8303,name: "<NAME>",province_id: 8}, {_id:8304,name: "<NAME>",province_id: 8}, {_id:8305,name: "<NAME>",province_id: 8}, {_id:8306,name: "<NAME>",province_id: 8}, {_id:8307,name: "<NAME>",province_id: 8}, {_id:8308,name: "<NAME>",province_id: 8}, {_id:8901,name: "<NAME>",province_id: 8}, {_id:8902,name: "<NAME>",province_id: 8}, {_id:8903,name: "<NAME>",province_id: 8}, {_id:8904,name: "<NAME>",province_id: 8}, {_id:8905,name: "<NAME> (La)",province_id: 8}, {_id:9001,name: "Abajas",province_id: 9}, {_id:9003,name: "<NAME>",province_id: 9}, {_id:9006,name: "<NAME>",province_id: 9}, {_id:9007,name: "<NAME>",province_id: 9}, {_id:9009,name: "Albillos",province_id: 9}, {_id:9010,name: "<NAME>",province_id: 9}, {_id:9011,name: "<NAME>",province_id: 9}, {_id:9012,name: "<NAME>",province_id: 9}, {_id:9013,name: "Altable",province_id: 9}, {_id:9014,name: "Altos (Los)",province_id: 9}, {_id:9016,name: "Ameyugo",province_id: 9}, {_id:9017,name: "Anguix",province_id: 9}, {_id:9018,name: "<NAME>",province_id: 9}, {_id:9019,name: "Arandilla",province_id: 9}, {_id:9020,name: "<NAME>",province_id: 9}, {_id:9021,name: "<NAME>",province_id: 9}, {_id:9022,name: "<NAME>",province_id: 9}, {_id:9023,name: "Arcos",province_id: 9}, {_id:9024,name: "<NAME>",province_id: 9}, {_id:9025,name: "Arija",province_id: 9}, {_id:9026,name: "Arlanzón",province_id: 9}, {_id:9027,name: "<NAME>",province_id: 9}, {_id:9029,name: "Atapuerca",province_id: 9}, {_id:9030,name: "Ausines (Los)",province_id: 9}, {_id:9032,name: "<NAME>",province_id: 9}, {_id:9033,name: "<NAME>",province_id: 9}, {_id:9034,name: "Balbases (Los)",province_id: 9}, {_id:9035,name: "<NAME>",province_id: 9}, {_id:9036,name: "<NAME>",province_id: 9}, {_id:9037,name: "<NAME>",province_id: 9}, {_id:9038,name: "<NAME>",province_id: 9}, {_id:9039,name: "<NAME>",province_id: 9}, {_id:9041,name: "<NAME>",province_id: 9}, {_id:9043,name: "<NAME> (Los)",province_id: 9}, {_id:9044,name: "<NAME>",province_id: 9}, {_id:9045,name: "<NAME>",province_id: 9}, {_id:9046,name: "Bascuñana",province_id: 9}, {_id:9047,name: "Belbimbre",province_id: 9}, {_id:9048,name: "Belorado",province_id: 9}, {_id:9050,name: "Berberana",province_id: 9}, {_id:9051,name: "<NAME>",province_id: 9}, {_id:9052,name: "<NAME>",province_id: 9}, {_id:9054,name: "Bozoó",province_id: 9}, {_id:9055,name: "Brazacorta",province_id: 9}, {_id:9056,name: "Briviesca",province_id: 9}, {_id:9057,name: "Bugedo",province_id: 9}, {_id:9058,name: "Buniel",province_id: 9}, {_id:9059,name: "Burgos",province_id: 9}, {_id:9060,name: "<NAME>",province_id: 9}, {_id:9061,name: "<NAME>",province_id: 9}, {_id:9062,name: "<NAME>",province_id: 9}, {_id:9063,name: "Cavia",province_id: 9}, {_id:9064,name: "Caleruega",province_id: 9}, {_id:9065,name: "<NAME>",province_id: 9}, {_id:9066,name: "Campolara",province_id: 9}, {_id:9067,name: "<NAME>",province_id: 9}, {_id:9068,name: "Cantabrana",province_id: 9}, {_id:9070,name: "Carazo",province_id: 9}, {_id:9071,name: "<NAME>",province_id: 9}, {_id:9072,name: "<NAME>",province_id: 9}, {_id:9073,name: "Cardeñadijo",province_id: 9}, {_id:9074,name: "Cardeñajimeno",province_id: 9}, {_id:9075,name: "<NAME>",province_id: 9}, {_id:9076,name: "Carrias",province_id: 9}, {_id:9077,name: "<NAME>",province_id: 9}, {_id:9078,name: "<NAME>",province_id: 9}, {_id:9079,name: "<NAME>",province_id: 9}, {_id:9082,name: "Castildelgado",province_id: 9}, {_id:9083,name: "<NAME>",province_id: 9}, {_id:9084,name: "<NAME>",province_id: 9}, {_id:9085,name: "<NAME>",province_id: 9}, {_id:9086,name: "<NAME>",province_id: 9}, {_id:9088,name: "<NAME>",province_id: 9}, {_id:9090,name: "<NAME>",province_id: 9}, {_id:9091,name: "Castrojeriz",province_id: 9}, {_id:9093,name: "Cayuela",province_id: 9}, {_id:9094,name: "Cebrecos",province_id: 9}, {_id:9095,name: "<NAME>",province_id: 9}, {_id:9098,name: "<NAME>",province_id: 9}, {_id:9100,name: "<NAME>",province_id: 9}, {_id:9101,name: "Ciadoncha",province_id: 9}, {_id:9102,name: "Cillaperlata",province_id: 9}, {_id:9103,name: "<NAME>",province_id: 9}, {_id:9104,name: "<NAME>",province_id: 9}, {_id:9105,name: "<NAME>",province_id: 9}, {_id:9108,name: "Cogollos",province_id: 9}, {_id:9109,name: "<NAME>",province_id: 9}, {_id:9110,name: "Contreras",province_id: 9}, {_id:9112,name: "<NAME>",province_id: 9}, {_id:9113,name: "Covarrubias",province_id: 9}, {_id:9114,name: "<NAME>",province_id: 9}, {_id:9115,name: "<NAME>",province_id: 9}, {_id:9117,name: "<NAME>)",province_id: 9}, {_id:9119,name: "<NAME>",province_id: 9}, {_id:9120,name: "Encío",province_id: 9}, {_id:9122,name: "<NAME>",province_id: 9}, {_id:9123,name: "<NAME>",province_id: 9}, {_id:9124,name: "<NAME>",province_id: 9}, {_id:9125,name: "Estépar",province_id: 9}, {_id:9127,name: "Fontioso",province_id: 9}, {_id:9128,name: "Frandovínez",province_id: 9}, {_id:9129,name: "<NAME>",province_id: 9}, {_id:9130,name: "Fresneña",province_id: 9}, {_id:9131,name: "<NAME>",province_id: 9}, {_id:9132,name: "<NAME>",province_id: 9}, {_id:9133,name: "<NAME>",province_id: 9}, {_id:9134,name: "Frías",province_id: 9}, {_id:9135,name: "Fuentebureba",province_id: 9}, {_id:9136,name: "Fuentecén",province_id: 9}, {_id:9137,name: "Fuentelcésped",province_id: 9}, {_id:9138,name: "Fuentelisendo",province_id: 9}, {_id:9139,name: "Fuentemolinos",province_id: 9}, {_id:9140,name: "Fuentenebro",province_id: 9}, {_id:9141,name: "Fuentespina",province_id: 9}, {_id:9143,name: "Galbarros",province_id: 9}, {_id:9144,name: "<NAME>)",province_id: 9}, {_id:9148,name: "Grijalba",province_id: 9}, {_id:9149,name: "Grisaleña",province_id: 9}, {_id:9151,name: "<NAME>",province_id: 9}, {_id:9152,name: "<NAME>",province_id: 9}, {_id:9154,name: "Hacinas",province_id: 9}, {_id:9155,name: "Haza",province_id: 9}, {_id:9159,name: "Hontanas",province_id: 9}, {_id:9160,name: "Hontangas",province_id: 9}, {_id:9162,name: "<NAME>",province_id: 9}, {_id:9163,name: "<NAME>",province_id: 9}, {_id:9164,name: "<NAME>",province_id: 9}, {_id:9166,name: "Hormazas (Las)",province_id: 9}, {_id:9167,name: "<NAME>",province_id: 9}, {_id:9168,name: "Horra (La)",province_id: 9}, {_id:9169,name: "Hortigüela",province_id: 9}, {_id:9170,name: "<NAME>",province_id: 9}, {_id:9172,name: "Huérmeces",province_id: 9}, {_id:9173,name: "<NAME>",province_id: 9}, {_id:9174,name: "<NAME>",province_id: 9}, {_id:9175,name: "Humada",province_id: 9}, {_id:9176,name: "Hurones",province_id: 9}, {_id:9177,name: "<NAME>",province_id: 9}, {_id:9178,name: "Ibrillos",province_id: 9}, {_id:9179,name: "Iglesiarrubia",province_id: 9}, {_id:9180,name: "Iglesias",province_id: 9}, {_id:9181,name: "Isar",province_id: 9}, {_id:9182,name: "<NAME>",province_id: 9}, {_id:9183,name: "<NAME>",province_id: 9}, {_id:9184,name: "<NAME>",province_id: 9}, {_id:9189,name: "Junta de Traslaloma",province_id: 9}, {_id:9190,name: "Junta de Villalba de Losa",province_id: 9}, {_id:9191,name: "Jurisdicción de Lara",province_id: 9}, {_id:9192,name: "<NAME>",province_id: 9}, {_id:9194,name: "Lerma",province_id: 9}, {_id:9195,name: "<NAME>",province_id: 9}, {_id:9196,name: "<NAME>",province_id: 9}, {_id:9197,name: "<NAME>",province_id: 9}, {_id:9198,name: "Mahamud",province_id: 9}, {_id:9199,name: "<NAME>",province_id: 9}, {_id:9200,name: "<NAME>",province_id: 9}, {_id:9201,name: "Mamolar",province_id: 9}, {_id:9202,name: "Manciles",province_id: 9}, {_id:9206,name: "Mazuela",province_id: 9}, {_id:9208,name: "Mecerreyes",province_id: 9}, {_id:9209,name: "<NAME>",province_id: 9}, {_id:9211,name: "<NAME>",province_id: 9}, {_id:9213,name: "<NAME>",province_id: 9}, {_id:9214,name: "<NAME>",province_id: 9}, {_id:9215,name: "<NAME>",province_id: 9}, {_id:9216,name: "<NAME>",province_id: 9}, {_id:9217,name: "<NAME>",province_id: 9}, {_id:9218,name: "Milagros",province_id: 9}, {_id:9219,name: "<NAME>",province_id: 9}, {_id:9220,name: "Miraveche",province_id: 9}, {_id:9221,name: "<NAME>",province_id: 9}, {_id:9223,name: "<NAME>",province_id: 9}, {_id:9224,name: "<NAME>",province_id: 9}, {_id:9225,name: "Moncalvillo",province_id: 9}, {_id:9226,name: "<NAME>",province_id: 9}, {_id:9227,name: "Montorio",province_id: 9}, {_id:9228,name: "<NAME>",province_id: 9}, {_id:9229,name: "<NAME>",province_id: 9}, {_id:9230,name: "<NAME>",province_id: 9}, {_id:9231,name: "Nebreda",province_id: 9}, {_id:9232,name: "Neila",province_id: 9}, {_id:9235,name: "<NAME>",province_id: 9}, {_id:9236,name: "<NAME>",province_id: 9}, {_id:9238,name: "Oña",province_id: 9}, {_id:9239,name: "Oquillas",province_id: 9}, {_id:9241,name: "Orbaneja Riopico",province_id: 9}, {_id:9242,name: "<NAME>",province_id: 9}, {_id:9243,name: "<NAME>",province_id: 9}, {_id:9244,name: "<NAME>",province_id: 9}, {_id:9246,name: "<NAME> Sierra",province_id: 9}, {_id:9247,name: "<NAME>",province_id: 9}, {_id:9248,name: "<NAME> la Sierra",province_id: 9}, {_id:9249,name: "<NAME>",province_id: 9}, {_id:9250,name: "Pampliega",province_id: 9}, {_id:9251,name: "Pancorbo",province_id: 9}, {_id:9253,name: "Pardilla",province_id: 9}, {_id:9255,name: "Partido de la Sierra en Tobalina",province_id: 9}, {_id:9256,name: "<NAME>",province_id: 9}, {_id:9257,name: "<NAME>",province_id: 9}, {_id:9258,name: "<NAME>",province_id: 9}, {_id:9259,name: "<NAME>",province_id: 9}, {_id:9261,name: "<NAME>",province_id: 9}, {_id:9262,name: "<NAME>",province_id: 9}, {_id:9265,name: "Piérnigas",province_id: 9}, {_id:9266,name: "<NAME>",province_id: 9}, {_id:9267,name: "<NAME>",province_id: 9}, {_id:9268,name: "<NAME>",province_id: 9}, {_id:9269,name: "<NAME>",province_id: 9}, {_id:9270,name: "<NAME>",province_id: 9}, {_id:9272,name: "<NAME>",province_id: 9}, {_id:9273,name: "<NAME>",province_id: 9}, {_id:9274,name: "Pradoluengo",province_id: 9}, {_id:9275,name: "Presencio",province_id: 9}, {_id:9276,name: "<NAME> (La)",province_id: 9}, {_id:9277,name: "Puentedura",province_id: 9}, {_id:9279,name: "Quemada",province_id: 9}, {_id:9280,name: "Quintanabureba",province_id: 9}, {_id:9281,name: "<NAME>",province_id: 9}, {_id:9283,name: "Quintanaélez",province_id: 9}, {_id:9287,name: "Quintanaortuño",province_id: 9}, {_id:9288,name: "Quintanapalla",province_id: 9}, {_id:9289,name: "<NAME>erra",province_id: 9}, {_id:9292,name: "Quintanavides",province_id: 9}, {_id:9294,name: "<NAME>",province_id: 9}, {_id:9295,name: "Quintanilla <NAME>",province_id: 9}, {_id:9297,name: "Quintanillas (Las)",province_id: 9}, {_id:9298,name: "<NAME>",province_id: 9}, {_id:9301,name: "<NAME>",province_id: 9}, {_id:9302,name: "<NAME>",province_id: 9}, {_id:9303,name: "Rábanos",province_id: 9}, {_id:9304,name: "<NAME>",province_id: 9}, {_id:9306,name: "<NAME>",province_id: 9}, {_id:9307,name: "<NAME>",province_id: 9}, {_id:9308,name: "<NAME>",province_id: 9}, {_id:9309,name: "<NAME>",province_id: 9}, {_id:9310,name: "Reinoso",province_id: 9}, {_id:9311,name: "Retuerta",province_id: 9}, {_id:9312,name: "<NAME> (La)",province_id: 9}, {_id:9314,name: "<NAME>",province_id: 9}, {_id:9315,name: "Revillarruz",province_id: 9}, {_id:3011,name: "<NAME> (l )",province_id: 3}, {_id:3012,name: "Algorfa",province_id: 3}, {_id:3013,name: "Algueña",province_id: 3}, {_id:3014,name: "Alicante/Alacant",province_id: 3}, {_id:3015,name: "Almoradí",province_id: 3}, {_id:3016,name: "Almudaina",province_id: 3}, {_id:3017,name: "<NAME> (l )",province_id: 3}, {_id:3018,name: "Altea",province_id: 3}, {_id:3019,name: "Aspe",province_id: 3}, {_id:3020,name: "Balones",province_id: 3}, {_id:3021,name: "<NAME>",province_id: 3}, {_id:3022,name: "Benasau",province_id: 3}, {_id:3023,name: "Beneixama",province_id: 3}, {_id:3024,name: "Benejúzar",province_id: 3}, {_id:3025,name: "Benferri",province_id: 3}, {_id:3026,name: "Beniarbeig",province_id: 3}, {_id:3027,name: "Beniardá",province_id: 3}, {_id:3028,name: "Beniarrés",province_id: 3}, {_id:3029,name: "Benigembla",province_id: 3}, {_id:3030,name: "Benidoleig",province_id: 3}, {_id:3031,name: "Benidorm",province_id: 3}, {_id:3032,name: "Benifallim",province_id: 3}, {_id:3033,name: "Benifato",province_id: 3}, {_id:3034,name: "Benijófar",province_id: 3}, {_id:3035,name: "Benilloba",province_id: 3}, {_id:3036,name: "Benillup",province_id: 3}, {_id:3037,name: "Benimantell",province_id: 3}, {_id:3038,name: "Benimarfull",province_id: 3}, {_id:3039,name: "Benimassot",province_id: 3}, {_id:3040,name: "Benimeli",province_id: 3}, {_id:3041,name: "Benissa",province_id: 3}, {_id:3042,name: "Benitachell/<NAME> (el)",province_id: 3}, {_id:3043,name: "Biar",province_id: 3}, {_id:3044,name: "Bigastro",province_id: 3}, {_id:3045,name: "Bolulla",province_id: 3}, {_id:3046,name: "Busot",province_id: 3}, {_id:3047,name: "Calpe/Calp",province_id: 3}, {_id:3048,name: "<NAME>",province_id: 3}, {_id:3049,name: "<NAME>",province_id: 3}, {_id:3050,name: "Campello (el)",province_id: 3}, {_id:3051,name: "<NAME>/<NAME> (el)",province_id: 3}, {_id:3052,name: "Cañada",province_id: 3}, {_id:3053,name: "Castalla",province_id: 3}, {_id:3054,name: "<NAME>",province_id: 3}, {_id:3055,name: "Catral",province_id: 3}, {_id:3056,name: "Cocentaina",province_id: 3}, {_id:3057,name: "Confrides",province_id: 3}, {_id:3058,name: "Cox",province_id: 3}, {_id:3059,name: "Crevillent",province_id: 3}, {_id:3060,name: "Quatretondeta",province_id: 3}, {_id:3061,name: "<NAME>",province_id: 3}, {_id:3062,name: "<NAME>",province_id: 3}, {_id:3063,name: "Dénia",province_id: 3}, {_id:3064,name: "Dolores",province_id: 3}, {_id:3065,name: "Elche/Elx",province_id: 3}, {_id:3066,name: "Elda",province_id: 3}, {_id:3067,name: "Facheca",province_id: 3}, {_id:3068,name: "Famorca",province_id: 3}, {_id:3069,name: "Finestrat",province_id: 3}, {_id:3070,name: "<NAME>",province_id: 3}, {_id:3071,name: "<NAME>",province_id: 3}, {_id:3072,name: "Gaianes",province_id: 3}, {_id:3073,name: "Gorga",province_id: 3}, {_id:3074,name: "<NAME>",province_id: 3}, {_id:3075,name: "<NAME> (el)",province_id: 3}, {_id:3076,name: "<NAME>",province_id: 3}, {_id:3077,name: "<NAME> (el)",province_id: 3}, {_id:3078,name: "<NAME>",province_id: 3}, {_id:3079,name: "Ibi",province_id: 3}, {_id:3080,name: "Jacarilla",province_id: 3}, {_id:3081,name: "Jalón/Xaló",province_id: 3}, {_id:3082,name: "Jávea/Xàbia",province_id: 3}, {_id:3083,name: "Jijona/Xixona",province_id: 3}, {_id:3084,name: "Lorcha/Orxa (l )",province_id: 3}, {_id:3085,name: "Llíber",province_id: 3}, {_id:3086,name: "Millena",province_id: 3}, {_id:3088,name: "<NAME>",province_id: 3}, {_id:3089,name: "Monóvar/Monòver",province_id: 3}, {_id:3090,name: "Mutxamel",province_id: 3}, {_id:3091,name: "Murla",province_id: 3}, {_id:3092,name: "<NAME>",province_id: 3}, {_id:3093,name: "Novelda",province_id: 3}, {_id:3094,name: "<NAME>)",province_id: 3}, {_id:3095,name: "Ondara",province_id: 3}, {_id:3096,name: "Onil",province_id: 3}, {_id:3097,name: "Orba",province_id: 3}, {_id:3098,name: "Orxeta",province_id: 3}, {_id:3099,name: "Orihuela",province_id: 3}, {_id:3100,name: "Parcent",province_id: 3}, {_id:3101,name: "Pedreguer",province_id: 3}, {_id:3102,name: "Pego",province_id: 3}, {_id:3103,name: "Penàguila",province_id: 3}, {_id:3104,name: "Petrer",province_id: 3}, {_id:3105,name: "Pinós (el)/Pinoso",province_id: 3}, {_id:3106,name: "Planes",province_id: 3}, {_id:3107,name: "Polop",province_id: 3}, {_id:3109,name: "Rafal",province_id: 3}, {_id:3110,name: "<NAME> (El)",province_id: 3}, {_id:3111,name: "Redován",province_id: 3}, {_id:3112,name: "Relleu",province_id: 3}, {_id:3113,name: "Rojales",province_id: 3}, {_id:3114,name: "Romana (la)",province_id: 3}, {_id:3115,name: "Sagra",province_id: 3}, {_id:3116,name: "Salinas",province_id: 3}, {_id:3117,name: "<NAME>",province_id: 3}, {_id:3118,name: "<NAME>",province_id: 3}, {_id:3119,name: "<NAME>",province_id: 3}, {_id:3120,name: "<NAME>",province_id: 3}, {_id:3121,name: "<NAME>",province_id: 3}, {_id:3122,name: "San Vicente del Raspeig/Sant Vicent del Raspeig",province_id: 3}, {_id:3123,name: "Sax",province_id: 3}, {_id:3124,name: "Sella",province_id: 3}, {_id:3125,name: "Senija",province_id: 3}, {_id:3127,name: "Tàrbena",province_id: 3}, {_id:3128,name: "Teulada",province_id: 3}, {_id:3129,name: "Tibi",province_id: 3}, {_id:3130,name: "Tollos",province_id: 3}, {_id:3131,name: "Tormos",province_id: 3}, {_id:3132,name: "Torremanzanas/<NAME> (la)",province_id: 3}, {_id:3133,name: "Torrevieja",province_id: 3}, {_id:3134,name: "<NAME> (la)",province_id: 3}, {_id:3135,name: "<NAME>",province_id: 3}, {_id:3136,name: "<NAME>",province_id: 3}, {_id:3137,name: "<NAME> (la)",province_id: 3}, {_id:3138,name: "Verger (el)",province_id: 3}, {_id:3139,name: "Villajoyosa/<NAME> (la)",province_id: 3}, {_id:3140,name: "Villena",province_id: 3}, {_id:3901,name: "Poblets (els)",province_id: 3}, {_id:3902,name: "<NAME>",province_id: 3}, {_id:3903,name: "Montesinos (Los)",province_id: 3}, {_id:3904,name: "<NAME>",province_id: 3}, {_id:4001,name: "Abla",province_id: 4}, {_id:4002,name: "Abrucena",province_id: 4}, {_id:4003,name: "Adra",province_id: 4}, {_id:4004,name: "Albánchez",province_id: 4}, {_id:4005,name: "Alboloduy",province_id: 4}, {_id:4006,name: "Albox",province_id: 4}, {_id:4007,name: "Alcolea",province_id: 4}, {_id:4008,name: "Alcóntar",province_id: 4}, {_id:4009,name: "<NAME>",province_id: 4}, {_id:4010,name: "Alhabia",province_id: 4}, {_id:4011,name: "<NAME>",province_id: 4}, {_id:4012,name: "Alicún",province_id: 4}, {_id:4013,name: "Almería",province_id: 4}, {_id:4014,name: "Almócita",province_id: 4}, {_id:4015,name: "Alsodux",province_id: 4}, {_id:4016,name: "Antas",province_id: 4}, {_id:4017,name: "Arboleas",province_id: 4}, {_id:4018,name: "<NAME>",province_id: 4}, {_id:4019,name: "Bacares",province_id: 4}, {_id:4020,name: "Bayárcal",province_id: 4}, {_id:1001,name: "Alegría-Dulantzi",province_id: 1}, {_id:1002,name: "Amurrio",province_id: 1}, {_id:1003,name: "Aramaio",province_id: 1}, {_id:1004,name: "Artziniega",province_id: 1}, {_id:1006,name: "Armiñón",province_id: 1}, {_id:1008,name: "Arrazua-Ubarrundia",province_id: 1}, {_id:1009,name: "Asparrena",province_id: 1}, {_id:1010,name: "Ayala/Aiara",province_id: 1}, {_id:1011,name: "<NAME>/Mañueta",province_id: 1}, {_id:1013,name: "Barrundia",province_id: 1}, {_id:1014,name: "Berantevilla",province_id: 1}, {_id:1016,name: "Bernedo",province_id: 1}, {_id:1017,name: "Campezo/Kanpezu",province_id: 1}, {_id:1018,name: "Zigoitia",province_id: 1}, {_id:1019,name: "Kripan",province_id: 1}, {_id:1020,name: "Kuartango",province_id: 1}, {_id:1021,name: "Elburgo/Burgelu",province_id: 1}, {_id:1022,name: "Elciego",province_id: 1}, {_id:1023,name: "Elvillar/Bilar",province_id: 1}, {_id:1027,name: "Iruraiz-Gauna",province_id: 1}, {_id:1028,name: "Labastida",province_id: 1}, {_id:1030,name: "Lagrán",province_id: 1}, {_id:1031,name: "Laguardia",province_id: 1}, {_id:1032,name: "Lanciego/Lantziego",province_id: 1}, {_id:1033,name: "<NAME>",province_id: 1}, {_id:1034,name: "Leza",province_id: 1}, {_id:1036,name: "Laudio/Llodio",province_id: 1}, {_id:1037,name: "Arraia-Maeztu",province_id: 1}, {_id:1039,name: "<NAME>",province_id: 1}, {_id:1041,name: "Navaridas",province_id: 1}, {_id:1042,name: "Okondo",province_id: 1}, {_id:1043,name: "Oyón-Oion",province_id: 1}, {_id:1044,name: "Peñacerrada-Urizaharra",province_id: 1}, {_id:1046,name: "<NAME>",province_id: 1}, {_id:1047,name: "<NAME>/<NAME>",province_id: 1}, {_id:1049,name: "Añana",province_id: 1}, {_id:1051,name: "Salvatierra/Agurain",province_id: 1}, {_id:1052,name: "Samaniego",province_id: 1}, {_id:1053,name: "<NAME>/Donemiliaga",province_id: 1}, {_id:1054,name: "Urkabustaiz",province_id: 1}, {_id:1055,name: "Valdegovía",province_id: 1}, {_id:1056,name: "Harana/<NAME>",province_id: 1}, {_id:1057,name: "<NAME>/Eskuernaga",province_id: 1}, {_id:1058,name: "Legutiano",province_id: 1}, {_id:1059,name: "Vitoria-Gasteiz",province_id: 1}, {_id:1060,name: "Yécora/Iekora",province_id: 1}, {_id:1061,name: "Zalduondo",province_id: 1}, {_id:1062,name: "Zambrana",province_id: 1}, {_id:1063,name: "Zuia",province_id: 1}, {_id:1901,name: "<NAME>/<NAME>",province_id: 1}, {_id:1902,name: "Lantarón",province_id: 1}, {_id:2001,name: "Abengibre",province_id: 2}, {_id:2002,name: "Alatoz",province_id: 2}, {_id:2003,name: "Albacete",province_id: 2}, {_id:2004,name: "Albatana",province_id: 2}, {_id:2005,name: "Alborea",province_id: 2}, {_id:2006,name: "Alcadozo",province_id: 2}, {_id:2007,name: "<NAME>",province_id: 2}, {_id:2008,name: "Alcaraz",province_id: 2}, {_id:2009,name: "Almansa",province_id: 2}, {_id:2010,name: "Alpera",province_id: 2}, {_id:2011,name: "Ayna",province_id: 2}, {_id:2012,name: "Balazote",province_id: 2}, {_id:2013,name: "<NAME>",province_id: 2}, {_id:2014,name: "Ballestero (El)",province_id: 2}, {_id:2015,name: "Barrax",province_id: 2}, {_id:2016,name: "Bienservida",province_id: 2}, {_id:2017,name: "Bogarra",province_id: 2}, {_id:2018,name: "Bonete",province_id: 2}, {_id:2019,name: "Bonillo (El)",province_id: 2}, {_id:2020,name: "Carcelén",province_id: 2}, {_id:2021,name: "<NAME>",province_id: 2}, {_id:2022,name: "<NAME>",province_id: 2}, {_id:2023,name: "<NAME>",province_id: 2}, {_id:2024,name: "Casas-Ibáñez",province_id: 2}, {_id:2025,name: "Caudete",province_id: 2}, {_id:2026,name: "Cenizate",province_id: 2}, {_id:2027,name: "Corral-Rubio",province_id: 2}, {_id:2028,name: "Cotillas",province_id: 2}, {_id:2029,name: "<NAME>",province_id: 2}, {_id:2030,name: "<NAME>",province_id: 2}, {_id:2031,name: "Férez",province_id: 2}, {_id:2032,name: "Fuensanta",province_id: 2}, {_id:2033,name: "Fuente-Álamo",province_id: 2}, {_id:2034,name: "Fuentealbilla",province_id: 2}, {_id:2035,name: "Gineta (La)",province_id: 2}, {_id:2036,name: "Golosalvo",province_id: 2}, {_id:2037,name: "Hellín",province_id: 2}, {_id:2038,name: "Herrera (La)",province_id: 2}, {_id:2039,name: "Higueruela",province_id: 2}, {_id:2040,name: "Hoya-Gonzalo",province_id: 2}, {_id:2041,name: "Jorquera",province_id: 2}, {_id:2042,name: "Letur",province_id: 2}, {_id:2043,name: "Lezuza",province_id: 2}, {_id:2044,name: "Liétor",province_id: 2}, {_id:2045,name: "Madrigueras",province_id: 2}, {_id:2046,name: "Mahora",province_id: 2}, {_id:2047,name: "Masegoso",province_id: 2}, {_id:2048,name: "Minaya",province_id: 2}, {_id:2049,name: "Molinicos",province_id: 2}, {_id:2050,name: "Montalvos",province_id: 2}, {_id:2051,name: "<NAME>",province_id: 2}, {_id:2052,name: "Motilleja",province_id: 2}, {_id:2053,name: "Munera",province_id: 2}, {_id:2054,name: "<NAME>",province_id: 2}, {_id:2055,name: "Nerpio",province_id: 2}, {_id:2056,name: "Ontur",province_id: 2}, {_id:2057,name: "<NAME>",province_id: 2}, {_id:4021,name: "Bayarque",province_id: 4}, {_id:4022,name: "Bédar",province_id: 4}, {_id:4023,name: "Beires",province_id: 4}, {_id:4024,name: "Benahadux",province_id: 4}, {_id:4026,name: "Benitagla",province_id: 4}, {_id:4027,name: "Benizalón",province_id: 4}, {_id:4028,name: "Bentarique",province_id: 4}, {_id:4029,name: "Berja",province_id: 4}, {_id:4030,name: "Canjáyar",province_id: 4}, {_id:4031,name: "Cantoria",province_id: 4}, {_id:4032,name: "Carboneras",province_id: 4}, {_id:4033,name: "<NAME>",province_id: 4}, {_id:4034,name: "Cóbdar",province_id: 4}, {_id:4035,name: "<NAME>",province_id: 4}, {_id:4036,name: "Chercos",province_id: 4}, {_id:4037,name: "Chirivel",province_id: 4}, {_id:4038,name: "Dalías",province_id: 4}, {_id:4041,name: "Enix",province_id: 4}, {_id:4043,name: "Felix",province_id: 4}, {_id:4044,name: "Fines",province_id: 4}, {_id:4045,name: "Fiñana",province_id: 4}, {_id:4046,name: "Fondón",province_id: 4}, {_id:4047,name: "Gádor",province_id: 4}, {_id:4048,name: "Gallardos (Los)",province_id: 4}, {_id:4049,name: "Garrucha",province_id: 4}, {_id:4050,name: "Gérgal",province_id: 4}, {_id:4051,name: "Huécija",province_id: 4}, {_id:4052,name: "<NAME>",province_id: 4}, {_id:4053,name: "Huércal-Overa",province_id: 4}, {_id:4054,name: "Illar",province_id: 4}, {_id:4055,name: "Instinción",province_id: 4}, {_id:4056,name: "Laroya",province_id: 4}, {_id:4057,name: "<NAME>",province_id: 4}, {_id:4058,name: "Líjar",province_id: 4}, {_id:4059,name: "Lubrín",province_id: 4}, {_id:4060,name: "<NAME>",province_id: 4}, {_id:4061,name: "Lúcar",province_id: 4}, {_id:4062,name: "Macael",province_id: 4}, {_id:4063,name: "María",province_id: 4}, {_id:4064,name: "Mojácar",province_id: 4}, {_id:4065,name: "Nacimiento",province_id: 4}, {_id:4066,name: "Níjar",province_id: 4}, {_id:4067,name: "Ohanes",province_id: 4}, {_id:4068,name: "<NAME>",province_id: 4}, {_id:4069,name: "<NAME>",province_id: 4}, {_id:4070,name: "Oria",province_id: 4}, {_id:4071,name: "Padules",province_id: 4}, {_id:4072,name: "Partaloa",province_id: 4}, {_id:5239,name: "Sotalbo",province_id: 5}, {_id:12134,name: "<NAME>",province_id: 12}, {_id:12135,name: "Villarreal/Vila-real",province_id: 12}, {_id:12136,name: "Vilavella (la)",province_id: 12}, {_id:12137,name: "Villores",province_id: 12}, {_id:12138,name: "Vinaròs",province_id: 12}, {_id:12139,name: "<NAME>",province_id: 12}, {_id:12140,name: "Viver",province_id: 12}, {_id:12141,name: "<NAME>",province_id: 12}, {_id:12142,name: "Zucaina",province_id: 12}, {_id:12901,name: "<NAME>",province_id: 12}, {_id:12902,name: "<NAME>",province_id: 12}, {_id:13001,name: "Abenójar",province_id: 13}, {_id:13002,name: "Agudo",province_id: 13}, {_id:13003,name: "Alamillo",province_id: 13}, {_id:13004,name: "Albaladejo",province_id: 13}, {_id:13005,name: "<NAME>",province_id: 13}, {_id:13006,name: "Alcoba",province_id: 13}, {_id:13007,name: "<NAME>",province_id: 13}, {_id:13008,name: "Alcubillas",province_id: 13}, {_id:13009,name: "<NAME>",province_id: 13}, {_id:13010,name: "Alhambra",province_id: 13}, {_id:13011,name: "Almadén",province_id: 13}, {_id:13012,name: "Almadenejos",province_id: 13}, {_id:13013,name: "Almagro",province_id: 13}, {_id:13014,name: "Almedina",province_id: 13}, {_id:13015,name: "<NAME>",province_id: 13}, {_id:13016,name: "Almuradiel",province_id: 13}, {_id:13017,name: "Anchuras",province_id: 13}, {_id:13018,name: "<NAME>",province_id: 13}, {_id:13019,name: "<NAME>",province_id: 13}, {_id:13020,name: "<NAME>",province_id: 13}, {_id:13021,name: "<NAME>",province_id: 13}, {_id:13022,name: "<NAME>",province_id: 13}, {_id:13023,name: "<NAME>",province_id: 13}, {_id:13024,name: "Brazatortas",province_id: 13}, {_id:13025,name: "Cabezarados",province_id: 13}, {_id:13026,name: "<NAME>",province_id: 13}, {_id:13027,name: "<NAME>",province_id: 13}, {_id:13028,name: "<NAME>",province_id: 13}, {_id:13029,name: "<NAME>",province_id: 13}, {_id:13030,name: "<NAME>",province_id: 13}, {_id:13031,name: "<NAME>",province_id: 13}, {_id:13032,name: "Carrizosa",province_id: 13}, {_id:13033,name: "<NAME>",province_id: 13}, {_id:13034,name: "Ciudad Real",province_id: 13}, {_id:13035,name: "<NAME>",province_id: 13}, {_id:13036,name: "Cortijos (Los)",province_id: 13}, {_id:13037,name: "Cózar",province_id: 13}, {_id:13038,name: "Chillón",province_id: 13}, {_id:13039,name: "Daimiel",province_id: 13}, {_id:13040,name: "<NAME>",province_id: 13}, {_id:13041,name: "Fontanarejo",province_id: 13}, {_id:13042,name: "Fuencaliente",province_id: 13}, {_id:13043,name: "Fuenllana",province_id: 13}, {_id:13044,name: "<NAME>",province_id: 13}, {_id:13045,name: "<NAME>",province_id: 13}, {_id:13046,name: "Guadalmez",province_id: 13}, {_id:13047,name: "Herencia",province_id: 13}, {_id:13048,name: "<NAME>",province_id: 13}, {_id:13049,name: "<NAME>",province_id: 13}, {_id:13050,name: "Labores (Las)",province_id: 13}, {_id:13051,name: "Luciana",province_id: 13}, {_id:13052,name: "Malagón",province_id: 13}, {_id:13053,name: "Manzanares",province_id: 13}, {_id:13054,name: "Membrilla",province_id: 13}, {_id:13055,name: "Mestanza",province_id: 13}, {_id:13056,name: "Miguelturra",province_id: 13}, {_id:13057,name: "Montiel",province_id: 13}, {_id:13058,name: "<NAME>",province_id: 13}, {_id:13059,name: "Navalpino",province_id: 13}, {_id:13060,name: "<NAME>",province_id: 13}, {_id:13061,name: "<NAME>",province_id: 13}, {_id:13062,name: "Picón",province_id: 13}, {_id:13063,name: "Piedrabuena",province_id: 13}, {_id:13064,name: "Poblete",province_id: 13}, {_id:13065,name: "Porzuna",province_id: 13}, {_id:13066,name: "<NAME>",province_id: 13}, {_id:13067,name: "<NAME> (Los)",province_id: 13}, {_id:13068,name: "<NAME>",province_id: 13}, {_id:13069,name: "<NAME>",province_id: 13}, {_id:13070,name: "<NAME>",province_id: 13}, {_id:13071,name: "Puertollano",province_id: 13}, {_id:13072,name: "<NAME>",province_id: 13}, {_id:13073,name: "Saceruela",province_id: 13}, {_id:13074,name: "<NAME>",province_id: 13}, {_id:13075,name: "<NAME>",province_id: 13}, {_id:13076,name: "<NAME>",province_id: 13}, {_id:13077,name: "<NAME>",province_id: 13}, {_id:13078,name: "Socuéllamos",province_id: 13}, {_id:13079,name: "<NAME>)",province_id: 13}, {_id:13080,name: "<NAME>",province_id: 13}, {_id:13081,name: "Terrinches",province_id: 13}, {_id:13082,name: "Tomelloso",province_id: 13}, {_id:13083,name: "<NAME>",province_id: 13}, {_id:13084,name: "<NAME>",province_id: 13}, {_id:13085,name: "Torrenueva",province_id: 13}, {_id:13086,name: "<NAME>",province_id: 13}, {_id:13087,name: "Valdepeñas",province_id: 13}, {_id:13088,name: "<NAME>",province_id: 13}, {_id:13089,name: "Villahermosa",province_id: 13}, {_id:13090,name: "Villamanrique",province_id: 13}, {_id:13091,name: "<NAME>",province_id: 13}, {_id:13092,name: "<NAME>",province_id: 13}, {_id:13093,name: "<NAME>",province_id: 13}, {_id:13094,name: "<NAME>",province_id: 13}, {_id:13095,name: "<NAME>",province_id: 13}, {_id:13096,name: "<NAME>",province_id: 13}, {_id:13097,name: "<NAME>",province_id: 13}, {_id:13098,name: "<NAME>",province_id: 13}, {_id:13901,name: "<NAME>)",province_id: 13}, {_id:13902,name: "Ruidera",province_id: 13}, {_id:13903,name: "<NAME>",province_id: 13}, {_id:13904,name: "<NAME>",province_id: 13}, {_id:14001,name: "Adamuz",province_id: 14}, {_id:14002,name: "<NAME>",province_id: 14}, {_id:14003,name: "Alcaracejos",province_id: 14}, {_id:14004,name: "Almedinilla",province_id: 14}, {_id:14005,name: "<NAME>",province_id: 14}, {_id:14006,name: "Añora",province_id: 14}, {_id:14007,name: "Baena",province_id: 14}, {_id:14008,name: "Belalcázar",province_id: 14}, {_id:14009,name: "Belmez",province_id: 14}, {_id:14010,name: "Benamejí",province_id: 14}, {_id:14011,name: "Blázquez (Los)",province_id: 14}, {_id:14012,name: "Bujalance",province_id: 14}, {_id:14013,name: "Cabra",province_id: 14}, {_id:14014,name: "<NAME>",province_id: 14}, {_id:14015,name: "Carcabuey",province_id: 14}, {_id:14016,name: "Cardeña",province_id: 14}, {_id:14017,name: "Carlota (La)",province_id: 14}, {_id:14018,name: "Carpio (El)",province_id: 14}, {_id:14019,name: "<NAME>",province_id: 14}, {_id:14020,name: "Conquista",province_id: 14}, {_id:14021,name: "Córdoba",province_id: 14}, {_id:14022,name: "<NAME>",province_id: 14}, {_id:14023,name: "<NAME>",province_id: 14}, {_id:14024,name: "<NAME>",province_id: 14}, {_id:14025,name: "Espejo",province_id: 14}, {_id:14026,name: "Espiel",province_id: 14}, {_id:14027,name: "Fernán-Núñez",province_id: 14}, {_id:14028,name: "<NAME>",province_id: 14}, {_id:14029,name: "<NAME>",province_id: 14}, {_id:14030,name: "<NAME>",province_id: 14}, {_id:14031,name: "Fuente-Tójar",province_id: 14}, {_id:14032,name: "Granjuela (La)",province_id: 14}, {_id:14033,name: "Guadalcázar",province_id: 14}, {_id:14034,name: "Guijo (El)",province_id: 14}, {_id:14035,name: "<NAME>",province_id: 14}, {_id:14036,name: "Hornachuelos",province_id: 14}, {_id:14037,name: "Iznájar",province_id: 14}, {_id:14038,name: "Lucena",province_id: 14}, {_id:14039,name: "Luque",province_id: 14}, {_id:14040,name: "<NAME>",province_id: 14}, {_id:14041,name: "Montemayor",province_id: 14}, {_id:14042,name: "Montilla",province_id: 14}, {_id:14043,name: "Montoro",province_id: 14}, {_id:14044,name: "Monturque",province_id: 14}, {_id:14045,name: "Moriles",province_id: 14}, {_id:14046,name: "<NAME>",province_id: 14}, {_id:14047,name: "Obejo",province_id: 14}, {_id:14048,name: "Palenciana",province_id: 14}, {_id:14049,name: "<NAME>",province_id: 14}, {_id:14050,name: "<NAME>",province_id: 14}, {_id:14051,name: "Pedroche",province_id: 14}, {_id:14052,name: "Peñarroya-Pueblonuevo",province_id: 14}, {_id:14053,name: "Posadas",province_id: 14}, {_id:14054,name: "Pozoblanco",province_id: 14}, {_id:14055,name: "<NAME>",province_id: 14}, {_id:14056,name: "<NAME>",province_id: 14}, {_id:14057,name: "<NAME>)",province_id: 14}, {_id:14058,name: "Rute",province_id: 14}, {_id:14059,name: "<NAME>",province_id: 14}, {_id:14060,name: "Santaella",province_id: 14}, {_id:14061,name: "<NAME>",province_id: 14}, {_id:14062,name: "Torrecampo",province_id: 14}, {_id:14063,name: "Valenzuela",province_id: 14}, {_id:14064,name: "Valsequillo",province_id: 14}, {_id:14065,name: "Victoria (La)",province_id: 14}, {_id:14066,name: "<NAME>",province_id: 14}, {_id:14067,name: "<NAME>",province_id: 14}, {_id:14068,name: "Villaharta",province_id: 14}, {_id:14069,name: "<NAME>",province_id: 14}, {_id:14070,name: "<NAME>",province_id: 14}, {_id:14071,name: "<NAME>",province_id: 14}, {_id:14072,name: "Villaralto",province_id: 14}, {_id:14073,name: "<NAME>",province_id: 14}, {_id:14074,name: "Viso (El)",province_id: 14}, {_id:14075,name: "Zuheros",province_id: 14}, {_id:15001,name: "Abegondo",province_id: 15}, {_id:15002,name: "Ames",province_id: 15}, {_id:15003,name: "Aranga",province_id: 15}, {_id:15004,name: "Ares",province_id: 15}, {_id:15005,name: "Arteixo",province_id: 15}, {_id:15006,name: "Arzúa",province_id: 15}, {_id:15007,name: "Baña (A)",province_id: 15}, {_id:15008,name: "Bergondo",province_id: 15}, {_id:15009,name: "Betanzos",province_id: 15}, {_id:15010,name: "Boimorto",province_id: 15}, {_id:15011,name: "Boiro",province_id: 15}, {_id:15012,name: "Boqueixón",province_id: 15}, {_id:15013,name: "Brión",province_id: 15}, {_id:15014,name: "<NAME>",province_id: 15}, {_id:15015,name: "Cabanas",province_id: 15}, {_id:15016,name: "Camariñas",province_id: 15}, {_id:15017,name: "Cambre",province_id: 15}, {_id:15018,name: "Capela (A)",province_id: 15}, {_id:15019,name: "Carballo",province_id: 15}, {_id:15020,name: "Carnota",province_id: 15}, {_id:15021,name: "Carral",province_id: 15}, {_id:15022,name: "Cedeira",province_id: 15}, {_id:15023,name: "Cee",province_id: 15}, {_id:15024,name: "Cerceda",province_id: 15}, {_id:15025,name: "Cerdido",province_id: 15}, {_id:15026,name: "Cesuras",province_id: 15}, {_id:15027,name: "Coirós",province_id: 15}, {_id:15028,name: "Corcubión",province_id: 15}, {_id:15029,name: "Coristanco",province_id: 15}, {_id:15030,name: "<NAME>)",province_id: 15}, {_id:15031,name: "Culleredo",province_id: 15}, {_id:15032,name: "Curtis",province_id: 15}, {_id:15033,name: "Dodro",province_id: 15}, {_id:15034,name: "Dumbría",province_id: 15}, {_id:15035,name: "Fene",province_id: 15}, {_id:15036,name: "Ferrol",province_id: 15}, {_id:15037,name: "Fisterra",province_id: 15}, {_id:15038,name: "Frades",province_id: 15}, {_id:15039,name: "Irixoa",province_id: 15}, {_id:15040,name: "Laxe",province_id: 15}, {_id:15041,name: "<NAME>)",province_id: 15}, {_id:15042,name: "Lousame",province_id: 15}, {_id:15043,name: "<NAME>",province_id: 15}, {_id:15044,name: "Mañón",province_id: 15}, {_id:15045,name: "Mazaricos",province_id: 15}, {_id:15046,name: "Melide",province_id: 15}, {_id:15047,name: "Mesía",province_id: 15}, {_id:15048,name: "Miño",province_id: 15}, {_id:15049,name: "Moeche",province_id: 15}, {_id:15050,name: "Monfero",province_id: 15}, {_id:15051,name: "Mugardos",province_id: 15}, {_id:15052,name: "Muxía",province_id: 15}, {_id:15053,name: "Muros",province_id: 15}, {_id:15054,name: "Narón",province_id: 15}, {_id:15055,name: "Neda",province_id: 15}, {_id:15056,name: "Negreira",province_id: 15}, {_id:15057,name: "Noia",province_id: 15}, {_id:15058,name: "Oleiros",province_id: 15}, {_id:15059,name: "Ordes",province_id: 15}, {_id:15060,name: "Oroso",province_id: 15}, {_id:15061,name: "Ortigueira",province_id: 15}, {_id:15062,name: "Outes",province_id: 15}, {_id:15063,name: "<NAME>",province_id: 15}, {_id:15064,name: "Paderne",province_id: 15}, {_id:15065,name: "Padrón",province_id: 15}, {_id:15066,name: "Pino (O)",province_id: 15}, {_id:15067,name: "<NAME> (A)",province_id: 15}, {_id:15068,name: "Ponteceso",province_id: 15}, {_id:15069,name: "Pontedeume",province_id: 15}, {_id:15070,name: "<NAME> (As)",province_id: 15}, {_id:7064,name: "Castell (Es)",province_id: 7}, {_id:7065,name: "<NAME>",province_id: 7}, {_id:7901,name: "Ariany",province_id: 7}, {_id:7902,name: "<NAME> (Es)",province_id: 7}, {_id:8001,name: "Abrera",province_id: 8}, {_id:8002,name: "<NAME>",province_id: 8}, {_id:8003,name: "Alella",province_id: 8}, {_id:8004,name: "Alpens",province_id: 8}, {_id:8005,name: "<NAME> (L )",province_id: 8}, {_id:8006,name: "<NAME>",province_id: 8}, {_id:8007,name: "<NAME>",province_id: 8}, {_id:8008,name: "Argençola",province_id: 8}, {_id:8009,name: "Argentona",province_id: 8}, {_id:8010,name: "Artés",province_id: 8}, {_id:8011,name: "Avià",province_id: 8}, {_id:8012,name: "Avinyó",province_id: 8}, {_id:8013,name: "<NAME>",province_id: 8}, {_id:8014,name: "Aiguafreda",province_id: 8}, {_id:8015,name: "Badalona",province_id: 8}, {_id:8016,name: "Bagà",province_id: 8}, {_id:8017,name: "Balenyà",province_id: 8}, {_id:8018,name: "Balsareny",province_id: 8}, {_id:8019,name: "Barcelona",province_id: 8}, {_id:8020,name: "Begues",province_id: 8}, {_id:8021,name: "Bellprat",province_id: 8}, {_id:10136,name: "<NAME>",province_id: 10}, {_id:10137,name: "Palomero",province_id: 10}, {_id:10138,name: "<NAME>",province_id: 10}, {_id:10139,name: "<NAME>",province_id: 10}, {_id:10140,name: "<NAME>",province_id: 10}, {_id:10141,name: "<NAME>",province_id: 10}, {_id:10142,name: "<NAME>",province_id: 10}, {_id:10143,name: "Pescueza",province_id: 10}, {_id:10144,name: "<NAME>)",province_id: 10}, {_id:10145,name: "<NAME>",province_id: 10}, {_id:10146,name: "Pinofranqueado",province_id: 10}, {_id:10147,name: "Piornal",province_id: 10}, {_id:10148,name: "Plasencia",province_id: 10}, {_id:10149,name: "Plasenzuela",province_id: 10}, {_id:10150,name: "Portaje",province_id: 10}, {_id:10151,name: "Portezuelo",province_id: 10}, {_id:10152,name: "<NAME>",province_id: 10}, {_id:10153,name: "<NAME>",province_id: 10}, {_id:10154,name: "Rebollar",province_id: 10}, {_id:10155,name: "Riolobos",province_id: 10}, {_id:10156,name: "<NAME>",province_id: 10}, {_id:10157,name: "<NAME>",province_id: 10}, {_id:10158,name: "<NAME>",province_id: 10}, {_id:10159,name: "Robledollano",province_id: 10}, {_id:10160,name: "Romangordo",province_id: 10}, {_id:10161,name: "Ruanes",province_id: 10}, {_id:10162,name: "Salorino",province_id: 10}, {_id:10163,name: "<NAME>",province_id: 10}, {_id:10164,name: "<NAME>",province_id: 10}, {_id:10165,name: "<NAME>",province_id: 10}, {_id:10166,name: "<NAME>",province_id: 10}, {_id:10167,name: "<NAME>",province_id: 10}, {_id:10168,name: "<NAME>",province_id: 10}, {_id:10169,name: "<NAME>",province_id: 10}, {_id:10170,name: "<NAME>",province_id: 10}, {_id:10171,name: "<NAME>",province_id: 10}, {_id:10172,name: "<NAME>",province_id: 10}, {_id:10173,name: "Saucedilla",province_id: 10}, {_id:10174,name: "<NAME>",province_id: 10}, {_id:10175,name: "Serradilla",province_id: 10}, {_id:10176,name: "Serrejón",province_id: 10}, {_id:10177,name: "<NAME>",province_id: 10}, {_id:10178,name: "Talaván",province_id: 10}, {_id:10179,name: "<NAME>",province_id: 10}, {_id:10180,name: "Talayuela",province_id: 10}, {_id:10181,name: "<NAME>",province_id: 10}, {_id:10182,name: "Toril",province_id: 10}, {_id:10183,name: "Tornavacas",province_id: 10}, {_id:10184,name: "<NAME>)",province_id: 10}, {_id:10185,name: "<NAME>",province_id: 10}, {_id:10186,name: "<NAME>",province_id: 10}, {_id:10187,name: "<NAME>",province_id: 10}, {_id:10188,name: "<NAME>",province_id: 10}, {_id:10189,name: "Torrejoncillo",province_id: 10}, {_id:10190,name: "<NAME>",province_id: 10}, {_id:10191,name: "Torremenga",province_id: 10}, {_id:10192,name: "Torremocha",province_id: 10}, {_id:10193,name: "Torreorgaz",province_id: 10}, {_id:10194,name: "Torrequemada",province_id: 10}, {_id:10195,name: "Trujillo",province_id: 10}, {_id:10196,name: "Valdastillas",province_id: 10}, {_id:10197,name: "<NAME>",province_id: 10}, {_id:10198,name: "Valdefuentes",province_id: 10}, {_id:10199,name: "Valdehúncar",province_id: 10}, {_id:10200,name: "<NAME>",province_id: 10}, {_id:10201,name: "Valdemorales",province_id: 10}, {_id:10202,name: "Valdeobispo",province_id: 10}, {_id:10203,name: "<NAME>",province_id: 10}, {_id:10204,name: "<NAME>",province_id: 10}, {_id:10205,name: "<NAME>",province_id: 10}, {_id:10206,name: "<NAME>",province_id: 10}, {_id:10207,name: "<NAME>",province_id: 10}, {_id:10208,name: "<NAME>",province_id: 10}, {_id:10209,name: "Villamesías",province_id: 10}, {_id:10210,name: "Villamiel",province_id: 10}, {_id:10211,name: "<NAME>",province_id: 10}, {_id:10212,name: "<NAME>",province_id: 10}, {_id:10213,name: "<NAME>",province_id: 10}, {_id:10214,name: "<NAME>",province_id: 10}, {_id:10215,name: "<NAME>",province_id: 10}, {_id:10216,name: "<NAME>",province_id: 10}, {_id:10217,name: "<NAME>",province_id: 10}, {_id:10218,name: "<NAME>",province_id: 10}, {_id:10219,name: "Zorita",province_id: 10}, {_id:10901,name: "Rosalejo",province_id: 10}, {_id:11001,name: "<NAME>",province_id: 11}, {_id:11002,name: "<NAME>",province_id: 11}, {_id:11003,name: "Algar",province_id: 11}, {_id:11004,name: "Algeciras",province_id: 11}, {_id:11005,name: "Algodonales",province_id: 11}, {_id:11006,name: "<NAME>",province_id: 11}, {_id:11007,name: "Barbate",province_id: 11}, {_id:11008,name: "Barrios (Los)",province_id: 11}, {_id:11009,name: "Benaocaz",province_id: 11}, {_id:11010,name: "Bornos",province_id: 11}, {_id:11011,name: "Bosque (El)",province_id: 11}, {_id:11012,name: "Cádiz",province_id: 11}, {_id:11013,name: "<NAME>",province_id: 11}, {_id:11014,name: "<NAME>",province_id: 11}, {_id:11015,name: "<NAME>",province_id: 11}, {_id:11016,name: "Chipiona",province_id: 11}, {_id:11017,name: "Espera",province_id: 11}, {_id:11018,name: "Gastor (El)",province_id: 11}, {_id:11019,name: "Grazalema",province_id: 11}, {_id:11020,name: "<NAME>",province_id: 11}, {_id:11021,name: "<NAME>",province_id: 11}, {_id:11022,name: "<NAME> (La)",province_id: 11}, {_id:11023,name: "Medina-Sidonia",province_id: 11}, {_id:11024,name: "Olvera",province_id: 11}, {_id:11025,name: "<NAME>",province_id: 11}, {_id:11026,name: "<NAME>",province_id: 11}, {_id:11027,name: "<NAME> (El)",province_id: 11}, {_id:11028,name: "<NAME>",province_id: 11}, {_id:11029,name: "<NAME>",province_id: 11}, {_id:11030,name: "Rota",province_id: 11}, {_id:11031,name: "<NAME>",province_id: 11}, {_id:11032,name: "<NAME>",province_id: 11}, {_id:11033,name: "<NAME>",province_id: 11}, {_id:11034,name: "<NAME>",province_id: 11}, {_id:11035,name: "Tarifa",province_id: 11}, {_id:11036,name: "<NAME>",province_id: 11}, {_id:11037,name: "Trebujena",province_id: 11}, {_id:11038,name: "Ubrique",province_id: 11}, {_id:11039,name: "<NAME>",province_id: 11}, {_id:11040,name: "<NAME>",province_id: 11}, {_id:11041,name: "Villamartín",province_id: 11}, {_id:11042,name: "Zahara",province_id: 11}, {_id:11901,name: "<NAME>",province_id: 11}, {_id:11902,name: "<NAME>",province_id: 11}, {_id:12001,name: "<NAME>",province_id: 12}, {_id:12002,name: "Aín",province_id: 12}, {_id:12003,name: "Albocàsser",province_id: 12}, {_id:12004,name: "<NAME>",province_id: 12}, {_id:12005,name: "Alcora (l )",province_id: 12}, {_id:12006,name: "<NAME>",province_id: 12}, {_id:12007,name: "Alfondeguilla",province_id: 12}, {_id:12008,name: "<NAME>",province_id: 12}, {_id:12009,name: "Almazora/Almassora",province_id: 12}, {_id:12010,name: "Almedíjar",province_id: 12}, {_id:12011,name: "Almenara",province_id: 12}, {_id:12012,name: "Altura",province_id: 12}, {_id:12013,name: "Arañuel",province_id: 12}, {_id:12014,name: "<NAME>",province_id: 12}, {_id:12015,name: "Argelita",province_id: 12}, {_id:12016,name: "Artana",province_id: 12}, {_id:12017,name: "Ayódar",province_id: 12}, {_id:12018,name: "Azuébar",province_id: 12}, {_id:12020,name: "Barracas",province_id: 12}, {_id:12021,name: "Betxí",province_id: 12}, {_id:12022,name: "Bejís",province_id: 12}, {_id:12024,name: "Benafer",province_id: 12}, {_id:12025,name: "Benafigos",province_id: 12}, {_id:12026,name: "Benasal",province_id: 12}, {_id:12027,name: "Benicarló",province_id: 12}, {_id:12028,name: "Benicasim/Benicàssim",province_id: 12}, {_id:12029,name: "Benlloch",province_id: 12}, {_id:12031,name: "Borriol",province_id: 12}, {_id:12032,name: "Burriana",province_id: 12}, {_id:12033,name: "Cabanes",province_id: 12}, {_id:12034,name: "Càlig",province_id: 12}, {_id:12036,name: "<NAME>",province_id: 12}, {_id:12037,name: "<NAME>",province_id: 12}, {_id:12038,name: "Castellfort",province_id: 12}, {_id:12039,name: "Castellnovo",province_id: 12}, {_id:12040,name: "Castellón de la Plana/Castelló de la Plana",province_id: 12}, {_id:12041,name: "<NAME>",province_id: 12}, {_id:12042,name: "Catí",province_id: 12}, {_id:12043,name: "Caudiel",province_id: 12}, {_id:12044,name: "<NAME>",province_id: 12}, {_id:12045,name: "Cinctorres",province_id: 12}, {_id:12046,name: "Cirat",province_id: 12}, {_id:12048,name: "<NAME>",province_id: 12}, {_id:12049,name: "Costur",province_id: 12}, {_id:12050,name: "<NAME> (les)",province_id: 12}, {_id:12051,name: "Culla",province_id: 12}, {_id:12052,name: "Chert/Xert",province_id: 12}, {_id:12053,name: "Chilches/Xilxes",province_id: 12}, {_id:12055,name: "Chodos/Xodos",province_id: 12}, {_id:12056,name: "Chóvar",province_id: 12}, {_id:12057,name: "Eslida",province_id: 12}, {_id:12058,name: "Espadilla",province_id: 12}, {_id:12059,name: "Fanzara",province_id: 12}, {_id:12060,name: "Figueroles",province_id: 12}, {_id:12061,name: "Forcall",province_id: 12}, {_id:12063,name: "<NAME>",province_id: 12}, {_id:12064,name: "<NAME>",province_id: 12}, {_id:12065,name: "Gaibiel",province_id: 12}, {_id:12067,name: "Geldo",province_id: 12}, {_id:12068,name: "Herbés",province_id: 12}, {_id:12069,name: "Higueras",province_id: 12}, {_id:12070,name: "Jana (la)",province_id: 12}, {_id:12071,name: "Jérica",province_id: 12}, {_id:12072,name: "<NAME>",province_id: 12}, {_id:12073,name: "Ludiente",province_id: 12}, {_id:12074,name: "Llosa (la)",province_id: 12}, {_id:12075,name: "<NAME> (la)",province_id: 12}, {_id:12076,name: "Matet",province_id: 12}, {_id:12077,name: "Moncofa",province_id: 12}, {_id:12078,name: "Montán",province_id: 12}, {_id:12079,name: "Montanejos",province_id: 12}, {_id:12080,name: "Morella",province_id: 12}, {_id:12081,name: "Navajas",province_id: 12}, {_id:12082,name: "Nules",province_id: 12}, {_id:12083,name: "<NAME>",province_id: 12}, {_id:12084,name: "Onda",province_id: 12}, {_id:12085,name: "<NAME>/Orpesa",province_id: 12}, {_id:12087,name: "Palanques",province_id: 12}, {_id:12088,name: "Pavías",province_id: 12}, {_id:12089,name: "Peñíscola",province_id: 12}, {_id:12090,name: "<NAME>",province_id: 12}, {_id:12091,name: "<NAME>",province_id: 12}, {_id:12092,name: "<NAME>",province_id: 12}, {_id:12093,name: "<NAME> (la)",province_id: 12}, {_id:12094,name: "<NAME> (la)",province_id: 12}, {_id:12095,name: "Ribesalbes",province_id: 12}, {_id:12096,name: "Rossell",province_id: 12}, {_id:12097,name: "Sacañet",province_id: 12}, {_id:12098,name: "Salzadella (la)",province_id: 12}, {_id:12099,name: "<NAME>/<NAME>",province_id: 12}, {_id:12100,name: "<NAME>",province_id: 12}, {_id:12101,name: "<NAME>",province_id: 12}, {_id:12102,name: "<NAME>",province_id: 12}, {_id:12103,name: "Sarratella",province_id: 12}, {_id:12104,name: "Segorbe",province_id: 12}, {_id:12105,name: "<NAME>",province_id: 12}, {_id:12106,name: "Soneja",province_id: 12}, {_id:12107,name: "<NAME>",province_id: 12}, {_id:12108,name: "Sueras/Suera",province_id: 12}, {_id:12109,name: "Tales",province_id: 12}, {_id:12110,name: "Teresa",province_id: 12}, {_id:12111,name: "Tírig",province_id: 12}, {_id:12112,name: "Todolella",province_id: 12}, {_id:12113,name: "Toga",province_id: 12}, {_id:12114,name: "Torás",province_id: 12}, {_id:12115,name: "<NAME>)",province_id: 12}, {_id:12116,name: "<NAME>",province_id: 12}, {_id:2058,name: "<NAME>",province_id: 2}, {_id:2059,name: "Peñascosa",province_id: 2}, {_id:2060,name: "<NAME>",province_id: 2}, {_id:2061,name: "Pétrola",province_id: 2}, {_id:2062,name: "Povedilla",province_id: 2}, {_id:2063,name: "Pozohondo",province_id: 2}, {_id:2064,name: "Pozo-Lorente",province_id: 2}, {_id:2065,name: "Pozuelo",province_id: 2}, {_id:2066,name: "Recueja (La)",province_id: 2}, {_id:2067,name: "Riópar",province_id: 2}, {_id:2068,name: "Robledo",province_id: 2}, {_id:2069,name: "Roda (La)",province_id: 2}, {_id:2070,name: "Salobre",province_id: 2}, {_id:2071,name: "<NAME>",province_id: 2}, {_id:2072,name: "Socovos",province_id: 2}, {_id:2073,name: "<NAME>",province_id: 2}, {_id:2074,name: "Tobarra",province_id: 2}, {_id:2075,name: "Valdeganga",province_id: 2}, {_id:2076,name: "Vianos",province_id: 2}, {_id:2077,name: "<NAME>",province_id: 2}, {_id:2078,name: "<NAME>",province_id: 2}, {_id:2079,name: "Villamalea",province_id: 2}, {_id:2080,name: "Villapalacios",province_id: 2}, {_id:2081,name: "Villarrobledo",province_id: 2}, {_id:2082,name: "Villatoya",province_id: 2}, {_id:2083,name: "Villavaliente",province_id: 2}, {_id:2084,name: "<NAME>",province_id: 2}, {_id:2085,name: "Viveros",province_id: 2}, {_id:2086,name: "Yeste",province_id: 2}, {_id:2901,name: "<NAME>",province_id: 2}, {_id:3001,name: "Adsubia",province_id: 3}, {_id:3002,name: "Agost",province_id: 3}, {_id:3003,name: "Agres",province_id: 3}, {_id:3004,name: "Aigües",province_id: 3}, {_id:3005,name: "Albatera",province_id: 3}, {_id:3006,name: "Alcalalí",province_id: 3}, {_id:3007,name: "<NAME>",province_id: 3}, {_id:3008,name: "Alcoleja",province_id: 3}, {_id:3009,name: "Alcoy/Alcoi",province_id: 3}, {_id:3010,name: "Alfafara",province_id: 3}, {_id:9316,name: "<NAME>",province_id: 9}, {_id:9317,name: "Rezmondo",province_id: 9}, {_id:9318,name: "<NAME>",province_id: 9}, {_id:9321,name: "Roa",province_id: 9}, {_id:9323,name: "Rojas",province_id: 9}, {_id:9325,name: "<NAME>",province_id: 9}, {_id:9326,name: "Rubena",province_id: 9}, {_id:9327,name: "<NAME>",province_id: 9}, {_id:9328,name: "Rucandio",province_id: 9}, {_id:9329,name: "<NAME>",province_id: 9}, {_id:9330,name: "<NAME>",province_id: 9}, {_id:9332,name: "<NAME>",province_id: 9}, {_id:9334,name: "<NAME>",province_id: 9}, {_id:9335,name: "<NAME>",province_id: 9}, {_id:9337,name: "<NAME>",province_id: 9}, {_id:9338,name: "<NAME>",province_id: 9}, {_id:9339,name: "<NAME>",province_id: 9}, {_id:9340,name: "<NAME>",province_id: 9}, {_id:9343,name: "<NAME>",province_id: 9}, {_id:9345,name: "<NAME>",province_id: 9}, {_id:9346,name: "<NAME>",province_id: 9}, {_id:9347,name: "<NAME>",province_id: 9}, {_id:9348,name: "<NAME>",province_id: 9}, {_id:9350,name: "<NAME>",province_id: 9}, {_id:9351,name: "<NAME>",province_id: 9}, {_id:9352,name: "<NAME>",province_id: 9}, {_id:9353,name: "<NAME>",province_id: 9}, {_id:9354,name: "<NAME>",province_id: 9}, {_id:9355,name: "<NAME>",province_id: 9}, {_id:9356,name: "<NAME>",province_id: 9}, {_id:9358,name: "<NAME>",province_id: 9}, {_id:9360,name: "<NAME>",province_id: 9}, {_id:9361,name: "<NAME>",province_id: 9}, {_id:9362,name: "Sarracín",province_id: 9}, {_id:9363,name: "Sasamón",province_id: 9}, {_id:9365,name: "<NAME>)",province_id: 9}, {_id:9366,name: "Solarana",province_id: 9}, {_id:9368,name: "Sordillos",province_id: 9}, {_id:9369,name: "<NAME>",province_id: 9}, {_id:9372,name: "Sotragero",province_id: 9}, {_id:9373,name: "Sotresgudo",province_id: 9}, {_id:9374,name: "<NAME>",province_id: 9}, {_id:9375,name: "Tamarón",province_id: 9}, {_id:9377,name: "Tardajos",province_id: 9}, {_id:9378,name: "Tejada",province_id: 9}, {_id:9380,name: "<NAME>",province_id: 9}, {_id:9381,name: "<NAME>",province_id: 9}, {_id:9382,name: "Tobar",province_id: 9}, {_id:9384,name: "Tordómar",province_id: 9}, {_id:9386,name: "<NAME>",province_id: 9}, {_id:9387,name: "Torregalindo",province_id: 9}, {_id:9388,name: "Torrelara",province_id: 9}, {_id:9389,name: "Torrepadre",province_id: 9}, {_id:9390,name: "Torresandino",province_id: 9}, {_id:9391,name: "<NAME>",province_id: 9}, {_id:9392,name: "Tosantos",province_id: 9}, {_id:9394,name: "Trespaderne",province_id: 9}, {_id:9395,name: "<NAME>",province_id: 9}, {_id:9396,name: "<NAME>",province_id: 9}, {_id:9398,name: "<NAME>",province_id: 9}, {_id:9400,name: "Vadocondes",province_id: 9}, {_id:9403,name: "Valdeande",province_id: 9}, {_id:9405,name: "Valdezate",province_id: 9}, {_id:9406,name: "Valdorros",province_id: 9}, {_id:9407,name: "Valmala",province_id: 9}, {_id:9408,name: "<NAME>",province_id: 9}, {_id:9409,name: "<NAME>",province_id: 9}, {_id:9410,name: "<NAME>",province_id: 9}, {_id:9411,name: "<NAME>",province_id: 9}, {_id:9412,name: "<NAME>",province_id: 9}, {_id:9413,name: "<NAME>",province_id: 9}, {_id:9414,name: "<NAME>",province_id: 9}, {_id:9415,name: "<NAME>",province_id: 9}, {_id:9416,name: "<NAME>",province_id: 9}, {_id:9417,name: "Vallejera",province_id: 9}, {_id:9418,name: "<NAME>",province_id: 9}, {_id:9419,name: "Valluércanes",province_id: 9}, {_id:9421,name: "<NAME> (La)",province_id: 9}, {_id:9422,name: "<NAME> (La)",province_id: 9}, {_id:9423,name: "Vileña",province_id: 9}, {_id:9424,name: "<NAME>",province_id: 9}, {_id:9425,name: "<NAME>",province_id: 9}, {_id:9427,name: "Villadiego",province_id: 9}, {_id:9428,name: "<NAME>",province_id: 9}, {_id:9429,name: "<NAME>",province_id: 9}, {_id:9430,name: "Villaespasa",province_id: 9}, {_id:9431,name: "<NAME>",province_id: 9}, {_id:9432,name: "Villafruela",province_id: 9}, {_id:9433,name: "Villagalijo",province_id: 9}, {_id:9434,name: "<NAME>",province_id: 9}, {_id:9437,name: "Villahoz",province_id: 9}, {_id:9438,name: "<NAME>",province_id: 9}, {_id:9439,name: "<NAME>",province_id: 9}, {_id:9440,name: "<NAME>",province_id: 9}, {_id:9441,name: "Villaldemiro",province_id: 9}, {_id:9442,name: "Villalmanzo",province_id: 9}, {_id:9443,name: "<NAME>",province_id: 9}, {_id:9444,name: "<NAME>",province_id: 9}, {_id:9445,name: "Villambistia",province_id: 9}, {_id:9446,name: "Villamedianilla",province_id: 9}, {_id:9447,name: "<NAME>",province_id: 9}, {_id:9448,name: "Villangómez",province_id: 9}, {_id:9449,name: "<NAME>",province_id: 9}, {_id:9450,name: "<NAME>",province_id: 9}, {_id:9451,name: "<NAME>",province_id: 9}, {_id:9454,name: "<NAME>",province_id: 9}, {_id:9455,name: "<NAME>",province_id: 9}, {_id:9456,name: "<NAME>",province_id: 9}, {_id:9458,name: "Villariezo",province_id: 9}, {_id:9460,name: "Villasandino",province_id: 9}, {_id:9463,name: "<NAME>",province_id: 9}, {_id:9464,name: "Villatuelda",province_id: 9}, {_id:9466,name: "<NAME>",province_id: 9}, {_id:9467,name: "Villaverde-Mogina",province_id: 9}, {_id:9471,name: "<NAME>",province_id: 9}, {_id:9472,name: "Villazopeque",province_id: 9}, {_id:9473,name: "Villegas",province_id: 9}, {_id:9476,name: "Villoruebo",province_id: 9}, {_id:9478,name: "Vizcaínos",province_id: 9}, {_id:9480,name: "Zael",province_id: 9}, {_id:9482,name: "<NAME>",province_id: 9}, {_id:9483,name: "Zazuar",province_id: 9}, {_id:9485,name: "Zuñeda",province_id: 9}, {_id:9901,name: "<NAME>",province_id: 9}, {_id:9902,name: "<NAME>",province_id: 9}, {_id:9903,name: "<NAME>",province_id: 9}, {_id:9904,name: "<NAME>",province_id: 9}, {_id:9905,name: "<NAME>",province_id: 9}, {_id:9906,name: "<NAME>",province_id: 9}, {_id:9907,name: "<NAME>",province_id: 9}, {_id:9908,name: "<NAME>",province_id: 9}, {_id:10001,name: "Abadía",province_id: 10}, {_id:10002,name: "Abertura",province_id: 10}, {_id:10003,name: "Acebo",province_id: 10}, {_id:10004,name: "Acehúche",province_id: 10}, {_id:10005,name: "Aceituna",province_id: 10}, {_id:10006,name: "Ahigal",province_id: 10}, {_id:10007,name: "Albalá",province_id: 10}, {_id:10008,name: "Alcántara",province_id: 10}, {_id:10009,name: "Alcollarín",province_id: 10}, {_id:10010,name: "Alcuéscar",province_id: 10}, {_id:10011,name: "Aldeacentenera",province_id: 10}, {_id:10012,name: "<NAME>",province_id: 10}, {_id:10013,name: "<NAME> (La)",province_id: 10}, {_id:10014,name: "<NAME>",province_id: 10}, {_id:10015,name: "<NAME>",province_id: 10}, {_id:10016,name: "<NAME>",province_id: 10}, {_id:10017,name: "Alía",province_id: 10}, {_id:10018,name: "Aliseda",province_id: 10}, {_id:10019,name: "Almaraz",province_id: 10}, {_id:10020,name: "Almoharín",province_id: 10}, {_id:10021,name: "<NAME>",province_id: 10}, {_id:10022,name: "<NAME>",province_id: 10}, {_id:10023,name: "Arroyomolinos",province_id: 10}, {_id:10024,name: "<NAME>",province_id: 10}, {_id:10025,name: "Barrado",province_id: 10}, {_id:10026,name: "<NAME>",province_id: 10}, {_id:10027,name: "Benquerencia",province_id: 10}, {_id:10028,name: "Berrocalejo",province_id: 10}, {_id:10029,name: "Berzocana",province_id: 10}, {_id:10030,name: "<NAME>",province_id: 10}, {_id:10031,name: "Botija",province_id: 10}, {_id:10032,name: "Brozas",province_id: 10}, {_id:10033,name: "<NAME>",province_id: 10}, {_id:10034,name: "Cabezabellosa",province_id: 10}, {_id:10035,name: "<NAME>",province_id: 10}, {_id:10036,name: "Cabrero",province_id: 10}, {_id:10037,name: "Cáceres",province_id: 10}, {_id:10038,name: "Cachorrilla",province_id: 10}, {_id:10039,name: "Cadalso",province_id: 10}, {_id:10040,name: "Calzadilla",province_id: 10}, {_id:10041,name: "Caminomorisco",province_id: 10}, {_id:10042,name: "<NAME>",province_id: 10}, {_id:10043,name: "<NAME>",province_id: 10}, {_id:10044,name: "Cañamero",province_id: 10}, {_id:10045,name: "Cañaveral",province_id: 10}, {_id:10046,name: "Carbajo",province_id: 10}, {_id:10047,name: "Carcaboso",province_id: 10}, {_id:10048,name: "Carrascalejo",province_id: 10}, {_id:10049,name: "<NAME>",province_id: 10}, {_id:10050,name: "<NAME>",province_id: 10}, {_id:10051,name: "<NAME>",province_id: 10}, {_id:10052,name: "<NAME>",province_id: 10}, {_id:10053,name: "<NAME>",province_id: 10}, {_id:10054,name: "<NAME>",province_id: 10}, {_id:10055,name: "<NAME>",province_id: 10}, {_id:10056,name: "<NAME>",province_id: 10}, {_id:10057,name: "<NAME>",province_id: 10}, {_id:10058,name: "Casatejada",province_id: 10}, {_id:10059,name: "<NAME>",province_id: 10}, {_id:10060,name: "<NAME>",province_id: 10}, {_id:10061,name: "Ceclavín",province_id: 10}, {_id:10062,name: "Cedillo",province_id: 10}, {_id:10063,name: "Cerezo",province_id: 10}, {_id:10064,name: "Cilleros",province_id: 10}, {_id:10065,name: "Collado",province_id: 10}, {_id:10066,name: "<NAME>",province_id: 10}, {_id:10067,name: "Coria",province_id: 10}, {_id:10068,name: "<NAME>",province_id: 10}, {_id:10069,name: "Cumbre (La)",province_id: 10}, {_id:10070,name: "Deleitosa",province_id: 10}, {_id:10071,name: "Descargamaría",province_id: 10}, {_id:10072,name: "Eljas",province_id: 10}, {_id:10073,name: "Escurial",province_id: 10}, {_id:10075,name: "<NAME>",province_id: 10}, {_id:10076,name: "Galisteo",province_id: 10}, {_id:10077,name: "Garciaz",province_id: 10}, {_id:10078,name: "Garganta (La)",province_id: 10}, {_id:10079,name: "<NAME>",province_id: 10}, {_id:10080,name: "Gargantilla",province_id: 10}, {_id:10081,name: "Gargüera",province_id: 10}, {_id:10082,name: "<NAME>",province_id: 10}, {_id:10083,name: "Garvín",province_id: 10}, {_id:10084,name: "Gata",province_id: 10}, {_id:10085,name: "Gordo (El)",province_id: 10}, {_id:10086,name: "Granja (La)",province_id: 10}, {_id:10087,name: "Guadalupe",province_id: 10}, {_id:10088,name: "<NAME>",province_id: 10}, {_id:10089,name: "<NAME>",province_id: 10}, {_id:10090,name: "<NAME>",province_id: 10}, {_id:10091,name: "<NAME>",province_id: 10}, {_id:10092,name: "Herguijuela",province_id: 10}, {_id:10093,name: "Hernán-Pérez",province_id: 10}, {_id:10094,name: "<NAME>",province_id: 10}, {_id:10095,name: "Herreruela",province_id: 10}, {_id:10096,name: "Hervás",province_id: 10}, {_id:10097,name: "Higuera",province_id: 10}, {_id:10098,name: "Hinojal",province_id: 10}, {_id:10099,name: "Holguera",province_id: 10}, {_id:10100,name: "Hoyos",province_id: 10}, {_id:10101,name: "Huélaga",province_id: 10}, {_id:10102,name: "Ibahernando",province_id: 10}, {_id:10103,name: "Jaraicejo",province_id: 10}, {_id:10104,name: "<NAME>",province_id: 10}, {_id:10105,name: "<NAME>",province_id: 10}, {_id:10106,name: "Jarilla",province_id: 10}, {_id:10107,name: "Jerte",province_id: 10}, {_id:10108,name: "Ladrillar",province_id: 10}, {_id:10109,name: "Logrosán",province_id: 10}, {_id:10110,name: "<NAME>",province_id: 10}, {_id:10111,name: "<NAME>",province_id: 10}, {_id:10112,name: "Madrigalejo",province_id: 10}, {_id:10113,name: "Madroñera",province_id: 10}, {_id:10114,name: "Majadas",province_id: 10}, {_id:10115,name: "<NAME>",province_id: 10}, {_id:10116,name: "<NAME>",province_id: 10}, {_id:10117,name: "Marchagaz",province_id: 10}, {_id:10118,name: "<NAME>",province_id: 10}, {_id:10119,name: "Membrío",province_id: 10}, {_id:10120,name: "<NAME>",province_id: 10}, {_id:10121,name: "Miajadas",province_id: 10}, {_id:10122,name: "Millanes",province_id: 10}, {_id:10123,name: "Mirabel",province_id: 10}, {_id:10124,name: "<NAME>",province_id: 10}, {_id:10125,name: "Monroy",province_id: 10}, {_id:10126,name: "Montánchez",province_id: 10}, {_id:10127,name: "Montehermoso",province_id: 10}, {_id:10128,name: "Moraleja",province_id: 10}, {_id:10129,name: "Morcillo",province_id: 10}, {_id:10130,name: "Navaconcejo",province_id: 10}, {_id:10131,name: "<NAME>",province_id: 10}, {_id:10132,name: "<NAME>",province_id: 10}, {_id:10133,name: "<NAME>",province_id: 10}, {_id:10134,name: "Navezuelas",province_id: 10}, {_id:10135,name: "Nuñomoral",province_id: 10}, {_id:46238,name: "<NAME>",province_id: 46}, {_id:46239,name: "<NAME>",province_id: 46}, {_id:46240,name: "Terrateig",province_id: 46}, {_id:46241,name: "Titaguas",province_id: 46}, {_id:46242,name: "Torrebaja",province_id: 46}, {_id:46243,name: "Torrella",province_id: 46}, {_id:46244,name: "Torrent",province_id: 46}, {_id:46245,name: "<NAME>",province_id: 46}, {_id:46246,name: "Tous",province_id: 46}, {_id:46247,name: "Tuéjar",province_id: 46}, {_id:46248,name: "Turís",province_id: 46}, {_id:46249,name: "Utiel",province_id: 46}, {_id:46250,name: "Valencia",province_id: 46}, {_id:46251,name: "Vallada",province_id: 46}, {_id:46252,name: "Vallanca",province_id: 46}, {_id:46253,name: "Vallés",province_id: 46}, {_id:46254,name: "<NAME>",province_id: 46}, {_id:46255,name: "Villalonga",province_id: 46}, {_id:46256,name: "Vilamarxant",province_id: 46}, {_id:46257,name: "<NAME>",province_id: 46}, {_id:46258,name: "<NAME>",province_id: 46}, {_id:46259,name: "<NAME>",province_id: 46}, {_id:46260,name: "Vinalesa",province_id: 46}, {_id:46261,name: "Yátova",province_id: 46}, {_id:46262,name: "<NAME>)",province_id: 46}, {_id:46263,name: "Zarra",province_id: 46}, {_id:46902,name: "Gátova",province_id: 46}, {_id:46903,name: "<NAME>",province_id: 46}, {_id:46904,name: "<NAME>",province_id: 46}, {_id:47001,name: "Adalia",province_id: 47}, {_id:47002,name: "Aguasal",province_id: 47}, {_id:47003,name: "<NAME>",province_id: 47}, {_id:47004,name: "Alaejos",province_id: 47}, {_id:47005,name: "Alcazarén",province_id: 47}, {_id:47006,name: "<NAME>",province_id: 47}, {_id:47007,name: "<NAME>",province_id: 47}, {_id:47008,name: "<NAME>",province_id: 47}, {_id:47009,name: "Amusquillo",province_id: 47}, {_id:47010,name: "<NAME>",province_id: 47}, {_id:47011,name: "Ataquines",province_id: 47}, {_id:47012,name: "Bahabón",province_id: 47}, {_id:47013,name: "<NAME>",province_id: 47}, {_id:47014,name: "<NAME>",province_id: 47}, {_id:47015,name: "<NAME>",province_id: 47}, {_id:47016,name: "Benafarces",province_id: 47}, {_id:47017,name: "Bercero",province_id: 47}, {_id:47018,name: "Berceruelo",province_id: 47}, {_id:47019,name: "Berrueces",province_id: 47}, {_id:47020,name: "<NAME>",province_id: 47}, {_id:47021,name: "Bocigas",province_id: 47}, {_id:47022,name: "<NAME>",province_id: 47}, {_id:47023,name: "Boecillo",province_id: 47}, {_id:47024,name: "<NAME>",province_id: 47}, {_id:47025,name: "<NAME>",province_id: 47}, {_id:47026,name: "<NAME>",province_id: 47}, {_id:47027,name: "<NAME>",province_id: 47}, {_id:47028,name: "<NAME>",province_id: 47}, {_id:47029,name: "<NAME>",province_id: 47}, {_id:47030,name: "Campaspero",province_id: 47}, {_id:47031,name: "<NAME>)",province_id: 47}, {_id:47032,name: "Camporredondo",province_id: 47}, {_id:47033,name: "<NAME>",province_id: 47}, {_id:47034,name: "<NAME>",province_id: 47}, {_id:47035,name: "Carpio",province_id: 47}, {_id:47036,name: "<NAME>",province_id: 47}, {_id:47037,name: "<NAME>",province_id: 47}, {_id:47038,name: "<NAME>",province_id: 47}, {_id:47039,name: "Castrillo-Tejeriego",province_id: 47}, {_id:47040,name: "Castrobol",province_id: 47}, {_id:47041,name: "Castrodeza",province_id: 47}, {_id:47042,name: "Castromembibre",province_id: 47}, {_id:47043,name: "Castromonte",province_id: 47}, {_id:47044,name: "<NAME>",province_id: 47}, {_id:47045,name: "Castronuño",province_id: 47}, {_id:47046,name: "Castroponce",province_id: 47}, {_id:47047,name: "<NAME>",province_id: 47}, {_id:47048,name: "<NAME>",province_id: 47}, {_id:47049,name: "<NAME>",province_id: 47}, {_id:47050,name: "Cigales",province_id: 47}, {_id:47051,name: "Ciguñuela",province_id: 47}, {_id:47052,name: "Cistérniga",province_id: 47}, {_id:47053,name: "<NAME>",province_id: 47}, {_id:47054,name: "<NAME>",province_id: 47}, {_id:47055,name: "Corcos",province_id: 47}, {_id:47056,name: "<NAME>",province_id: 47}, {_id:47057,name: "<NAME>",province_id: 47}, {_id:47058,name: "<NAME>",province_id: 47}, {_id:47059,name: "<NAME>",province_id: 47}, {_id:47060,name: "<NAME>",province_id: 47}, {_id:47061,name: "<NAME>",province_id: 47}, {_id:47062,name: "Fombellida",province_id: 47}, {_id:47063,name: "Fompedraza",province_id: 47}, {_id:47064,name: "Fontihoyuelo",province_id: 47}, {_id:47065,name: "<NAME>",province_id: 47}, {_id:47066,name: "Fuensaldaña",province_id: 47}, {_id:47067,name: "<NAME>",province_id: 47}, {_id:47068,name: "Fuente-Olmedo",province_id: 47}, {_id:47069,name: "<NAME>",province_id: 47}, {_id:47070,name: "<NAME>",province_id: 47}, {_id:47071,name: "Geria",province_id: 47}, {_id:47073,name: "<NAME>",province_id: 47}, {_id:47074,name: "<NAME>",province_id: 47}, {_id:47075,name: "Íscar",province_id: 47}, {_id:47076,name: "<NAME>",province_id: 47}, {_id:47077,name: "Langayo",province_id: 47}, {_id:47078,name: "Lomoviejo",province_id: 47}, {_id:47079,name: "<NAME>",province_id: 47}, {_id:47080,name: "Manzanillo",province_id: 47}, {_id:47081,name: "Marzales",province_id: 47}, {_id:47082,name: "Matapozuelos",province_id: 47}, {_id:47083,name: "<NAME>",province_id: 47}, {_id:47084,name: "Mayorga",province_id: 47}, {_id:47085,name: "<NAME>",province_id: 47}, {_id:47086,name: "<NAME>",province_id: 47}, {_id:47087,name: "Megeces",province_id: 47}, {_id:47088,name: "<NAME>",province_id: 47}, {_id:47089,name: "<NAME>",province_id: 47}, {_id:47090,name: "Mojados",province_id: 47}, {_id:47091,name: "<NAME>",province_id: 47}, {_id:47092,name: "<NAME>",province_id: 47}, {_id:47093,name: "<NAME>",province_id: 47}, {_id:47094,name: "<NAME>",province_id: 47}, {_id:47095,name: "<NAME>",province_id: 47}, {_id:47096,name: "<NAME>",province_id: 47}, {_id:47097,name: "<NAME>",province_id: 47}, {_id:47098,name: "Mucientes",province_id: 47}, {_id:47099,name: "Mudarra (La)",province_id: 47}, {_id:47100,name: "Muriel",province_id: 47}, {_id:47101,name: "<NAME>",province_id: 47}, {_id:47102,name: "<NAME>",province_id: 47}, {_id:47103,name: "<NAME>",province_id: 47}, {_id:47104,name: "Olmedo",province_id: 47}, {_id:47105,name: "<NAME>",province_id: 47}, {_id:47106,name: "<NAME>",province_id: 47}, {_id:47109,name: "<NAME>",province_id: 47}, {_id:47110,name: "Parrilla (La)",province_id: 47}, {_id:47111,name: "<NAME> (La)",province_id: 47}, {_id:47112,name: "<NAME>",province_id: 47}, {_id:47113,name: "<NAME>",province_id: 47}, {_id:47114,name: "Peñafiel",province_id: 47}, {_id:47115,name: "<NAME>",province_id: 47}, {_id:47116,name: "<NAME>",province_id: 47}, {_id:47117,name: "<NAME>",province_id: 47}, {_id:47118,name: "<NAME>",province_id: 47}, {_id:47119,name: "<NAME>",province_id: 47}, {_id:47121,name: "Pollos",province_id: 47}, {_id:47122,name: "Portillo",province_id: 47}, {_id:47123,name: "<NAME>",province_id: 47}, {_id:47124,name: "Pozaldez",province_id: 47}, {_id:47125,name: "<NAME>",province_id: 47}, {_id:47126,name: "Puras",province_id: 47}, {_id:47127,name: "<NAME>",province_id: 47}, {_id:47128,name: "<NAME>",province_id: 47}, {_id:47129,name: "<NAME>",province_id: 47}, {_id:47130,name: "<NAME>",province_id: 47}, {_id:47131,name: "Rábano",province_id: 47}, {_id:47132,name: "Ramiro",province_id: 47}, {_id:47133,name: "<NAME>",province_id: 47}, {_id:47134,name: "<NAME>",province_id: 47}, {_id:47135,name: "Robladillo",province_id: 47}, {_id:47137,name: "Roturas",province_id: 47}, {_id:47138,name: "<NAME>",province_id: 47}, {_id:47139,name: "Rueda",province_id: 47}, {_id:47140,name: "<NAME>",province_id: 47}, {_id:47141,name: "<NAME>",province_id: 47}, {_id:47142,name: "<NAME>",province_id: 47}, {_id:47143,name: "<NAME>",province_id: 47}, {_id:47144,name: "<NAME>",province_id: 47}, {_id:47145,name: "<NAME>",province_id: 47}, {_id:47146,name: "<NAME>",province_id: 47}, {_id:47147,name: "<NAME>",province_id: 47}, {_id:47148,name: "<NAME>",province_id: 47}, {_id:47149,name: "<NAME>",province_id: 47}, {_id:47150,name: "<NAME>",province_id: 47}, {_id:47151,name: "<NAME>",province_id: 47}, {_id:47152,name: "<NAME>",province_id: 47}, {_id:47153,name: "<NAME>",province_id: 47}, {_id:47154,name: "<NAME>",province_id: 47}, {_id:47155,name: "<NAME>",province_id: 47}, {_id:47156,name: "<NAME>ente del Palacio",province_id: 47}, {_id:47157,name: "<NAME>",province_id: 47}, {_id:47158,name: "Seca (La)",province_id: 47}, {_id:47159,name: "Serrada",province_id: 47}, {_id:47160,name: "<NAME>",province_id: 47}, {_id:47161,name: "Simancas",province_id: 47}, {_id:47162,name: "<NAME>",province_id: 47}, {_id:47163,name: "Tiedra",province_id: 47}, {_id:47164,name: "Tordehumos",province_id: 47}, {_id:47165,name: "Tordesillas",province_id: 47}, {_id:47166,name: "<NAME>",province_id: 47}, {_id:47167,name: "<NAME>",province_id: 47}, {_id:47168,name: "<NAME>",province_id: 47}, {_id:47169,name: "<NAME>",province_id: 47}, {_id:47170,name: "<NAME>",province_id: 47}, {_id:47171,name: "Torrelobatón",province_id: 47}, {_id:47172,name: "Torrescárcela",province_id: 47}, {_id:47173,name: "Traspinedo",province_id: 47}, {_id:47174,name: "<NAME>",province_id: 47}, {_id:47175,name: "<NAME>",province_id: 47}, {_id:47176,name: "<NAME> (La)",province_id: 47}, {_id:47177,name: "<NAME>",province_id: 47}, {_id:47178,name: "Urueña",province_id: 47}, {_id:47179,name: "<NAME>",province_id: 47}, {_id:47180,name: "<NAME>",province_id: 47}, {_id:47181,name: "<NAME>",province_id: 47}, {_id:47182,name: "Valdestillas",province_id: 47}, {_id:47183,name: "Valdunquillo",province_id: 47}, {_id:47184,name: "<NAME>",province_id: 47}, {_id:47185,name: "<NAME>",province_id: 47}, {_id:47186,name: "Valladolid",province_id: 47}, {_id:47187,name: "<NAME>",province_id: 47}, {_id:47188,name: "<NAME>",province_id: 47}, {_id:47189,name: "Velascálvaro",province_id: 47}, {_id:47190,name: "Velilla",province_id: 47}, {_id:47191,name: "Velliza",province_id: 47}, {_id:47192,name: "<NAME>",province_id: 47}, {_id:47193,name: "<NAME>",province_id: 47}, {_id:47194,name: "Viloria",province_id: 47}, {_id:47195,name: "Villabáñez",province_id: 47}, {_id:47196,name: "<NAME>",province_id: 47}, {_id:47197,name: "Villabrágima",province_id: 47}, {_id:47198,name: "Villacarralón",province_id: 47}, {_id:47199,name: "<NAME>",province_id: 47}, {_id:47200,name: "Villaco",province_id: 47}, {_id:47203,name: "<NAME>",province_id: 47}, {_id:47204,name: "<NAME>",province_id: 47}, {_id:47205,name: "Villafrechós",province_id: 47}, {_id:47206,name: "Villafuerte",province_id: 47}, {_id:47207,name: "<NAME>",province_id: 47}, {_id:47208,name: "<NAME>",province_id: 47}, {_id:47209,name: "<NAME>",province_id: 47}, {_id:47210,name: "<NAME>",province_id: 47}, {_id:47211,name: "<NAME>",province_id: 47}, {_id:47212,name: "<NAME>",province_id: 47}, {_id:47213,name: "Villalbarba",province_id: 47}, {_id:47214,name: "<NAME>",province_id: 47}, {_id:47215,name: "<NAME>",province_id: 47}, {_id:47216,name: "<NAME>",province_id: 47}, {_id:47217,name: "Villanubla",province_id: 47}, {_id:47218,name: "<NAME>",province_id: 47}, {_id:47219,name: "<NAME>",province_id: 47}, {_id:47220,name: "<NAME>",province_id: 47}, {_id:47221,name: "<NAME>",province_id: 47}, {_id:47222,name: "<NAME>",province_id: 47}, {_id:47223,name: "Villardefrades",province_id: 47}, {_id:47224,name: "<NAME>",province_id: 47}, {_id:47225,name: "Villasexmir",province_id: 47}, {_id:47226,name: "Villavaquerín",province_id: 47}, {_id:47227,name: "Villavellid",province_id: 47}, {_id:47228,name: "<NAME>",province_id: 47}, {_id:47229,name: "<NAME>",province_id: 47}, {_id:47230,name: "Wamba",province_id: 47}, {_id:47231,name: "Zaratán",province_id: 47}, {_id:24063,name: "<NAME>",province_id: 24}, {_id:24064,name: "<NAME>",province_id: 24}, {_id:24065,name: "<NAME>",province_id: 24}, {_id:24066,name: "Destriana",province_id: 24}, {_id:24067,name: "Encinedo",province_id: 24}, {_id:24068,name: "<NAME>)",province_id: 24}, {_id:24069,name: "<NAME>",province_id: 24}, {_id:24070,name: "Fabero",province_id: 24}, {_id:24071,name: "<NAME>",province_id: 24}, {_id:24073,name: "<NAME>",province_id: 24}, {_id:24074,name: "<NAME>",province_id: 24}, {_id:24076,name: "<NAME>",province_id: 24}, {_id:24077,name: "<NAME>",province_id: 24}, {_id:24078,name: "Gordoncillo",province_id: 24}, {_id:24079,name: "Gradefes",province_id: 24}, {_id:24080,name: "<NAME>",province_id: 24}, {_id:24081,name: "<NAME>",province_id: 24}, {_id:24082,name: "Hospital de Órbigo",province_id: 24}, {_id:24083,name: "Igüeña",province_id: 24}, {_id:24084,name: "Izagre",province_id: 24}, {_id:24086,name: "<NAME>",province_id: 24}, {_id:24087,name: "<NAME>",province_id: 24}, {_id:24088,name: "<NAME>",province_id: 24}, {_id:24089,name: "León",province_id: 24}, {_id:24090,name: "Lucillo",province_id: 24}, {_id:24091,name: "Luyego",province_id: 24}, {_id:24092,name: "<NAME>",province_id: 24}, {_id:24093,name: "<NAME>",province_id: 24}, {_id:24094,name: "<NAME>",province_id: 24}, {_id:24095,name: "<NAME>",province_id: 24}, {_id:24096,name: "Maraña",province_id: 24}, {_id:24097,name: "<NAME>",province_id: 24}, {_id:24098,name: "<NAME>",province_id: 24}, {_id:24099,name: "Matanza",province_id: 24}, {_id:24100,name: "Molinaseca",province_id: 24}, {_id:24101,name: "<NAME>",province_id: 24}, {_id:24102,name: "<NAME>",province_id: 24}, {_id:24103,name: "Oencia",province_id: 24}, {_id:24104,name: "<NAME>)",province_id: 24}, {_id:24105,name: "Onzonilla",province_id: 24}, {_id:24106,name: "<NAME>",province_id: 24}, {_id:24107,name: "<NAME>",province_id: 24}, {_id:24108,name: "<NAME>",province_id: 24}, {_id:24109,name: "<NAME>",province_id: 24}, {_id:24110,name: "<NAME>",province_id: 24}, {_id:24112,name: "Peranzanes",province_id: 24}, {_id:24113,name: "<NAME>",province_id: 24}, {_id:24114,name: "<NAME>)",province_id: 24}, {_id:24115,name: "Ponferrada",province_id: 24}, {_id:24116,name: "<NAME>",province_id: 24}, {_id:24117,name: "<NAME>",province_id: 24}, {_id:24118,name: "<NAME>",province_id: 24}, {_id:24119,name: "<NAME>",province_id: 24}, {_id:24120,name: "Prioro",province_id: 24}, {_id:24121,name: "<NAME>",province_id: 24}, {_id:24122,name: "<NAME>",province_id: 24}, {_id:24123,name: "<NAME>",province_id: 24}, {_id:24124,name: "<NAME>",province_id: 24}, {_id:24125,name: "<NAME>",province_id: 24}, {_id:24127,name: "<NAME>",province_id: 24}, {_id:24129,name: "Reyero",province_id: 24}, {_id:24130,name: "Riaño",province_id: 24}, {_id:24131,name: "<NAME>",province_id: 24}, {_id:24132,name: "Riello",province_id: 24}, {_id:24133,name: "<NAME>",province_id: 24}, {_id:24134,name: "<NAME>)",province_id: 24}, {_id:24136,name: "<NAME>",province_id: 24}, {_id:24137,name: "Sabero",province_id: 24}, {_id:24139,name: "Sahagún",province_id: 24}, {_id:24141,name: "<NAME>",province_id: 24}, {_id:24142,name: "<NAME>",province_id: 24}, {_id:24143,name: "Sancedo",province_id: 24}, {_id:24144,name: "<NAME>",province_id: 24}, {_id:24145,name: "<NAME>",province_id: 24}, {_id:24146,name: "<NAME>",province_id: 24}, {_id:24148,name: "<NAME>",province_id: 24}, {_id:24149,name: "<NAME>",province_id: 24}, {_id:24150,name: "<NAME>",province_id: 24}, {_id:24151,name: "<NAME> de Curueño",province_id: 24}, {_id:24152,name: "Santa Colomba de Somoza",province_id: 24}, {_id:24153,name: "<NAME>",province_id: 24}, {_id:24154,name: "<NAME>",province_id: 24}, {_id:24155,name: "<NAME>",province_id: 24}, {_id:24156,name: "<NAME> del Monte de Cea",province_id: 24}, {_id:24157,name: "<NAME> del Páramo",province_id: 24}, {_id:24158,name: "<NAME>",province_id: 24}, {_id:24159,name: "<NAME> del Rey",province_id: 24}, {_id:24160,name: "<NAME>",province_id: 24}, {_id:24161,name: "<NAME>",province_id: 24}, {_id:24162,name: "<NAME>",province_id: 24}, {_id:24163,name: "Sariegos",province_id: 24}, {_id:24164,name: "<NAME>",province_id: 24}, {_id:24165,name: "Sobrado",province_id: 24}, {_id:24166,name: "<NAME>",province_id: 24}, {_id:24167,name: "<NAME>",province_id: 24}, {_id:24168,name: "<NAME>",province_id: 24}, {_id:24169,name: "Toreno",province_id: 24}, {_id:24170,name: "<NAME>",province_id: 24}, {_id:24171,name: "Trabadelo",province_id: 24}, {_id:24172,name: "Truchas",province_id: 24}, {_id:24173,name: "Turcia",province_id: 24}, {_id:24174,name: "<NAME>",province_id: 24}, {_id:24175,name: "Valdefresno",province_id: 24}, {_id:24176,name: "<NAME>",province_id: 24}, {_id:24177,name: "Valdelugueros",province_id: 24}, {_id:24178,name: "Valdemora",province_id: 24}, {_id:24179,name: "Valdepiélago",province_id: 24}, {_id:24180,name: "Valdepolo",province_id: 24}, {_id:24181,name: "Valderas",province_id: 24}, {_id:24182,name: "Valderrey",province_id: 24}, {_id:24183,name: "Valderrueda",province_id: 24}, {_id:24184,name: "Valdesamario",province_id: 24}, {_id:24185,name: "<NAME>",province_id: 24}, {_id:24187,name: "Valdevimbre",province_id: 24}, {_id:24188,name: "<NAME>",province_id: 24}, {_id:24189,name: "<NAME>",province_id: 24}, {_id:24190,name: "Valverde-Enrique",province_id: 24}, {_id:24191,name: "Vallecillo",province_id: 24}, {_id:24193,name: "<NAME>)",province_id: 24}, {_id:24194,name: "Vegacervera",province_id: 24}, {_id:24196,name: "<NAME>",province_id: 24}, {_id:24197,name: "<NAME>",province_id: 24}, {_id:24198,name: "<NAME>",province_id: 24}, {_id:24199,name: "Vegaquemada",province_id: 24}, {_id:24201,name: "<NAME>",province_id: 24}, {_id:24202,name: "Villablino",province_id: 24}, {_id:24203,name: "Villabraz",province_id: 24}, {_id:24205,name: "<NAME>",province_id: 24}, {_id:24206,name: "Villadecanes",province_id: 24}, {_id:24207,name: "<NAME>",province_id: 24}, {_id:24209,name: "<NAME>",province_id: 24}, {_id:24210,name: "Villagatón",province_id: 24}, {_id:24211,name: "Villamandos",province_id: 24}, {_id:24212,name: "Villamañán",province_id: 24}, {_id:24213,name: "<NAME>",province_id: 24}, {_id:24214,name: "Villamejil",province_id: 24}, {_id:24215,name: "Villamol",province_id: 24}, {_id:24216,name: "<NAME>",province_id: 24}, {_id:24217,name: "<NAME>",province_id: 24}, {_id:24218,name: "<NAME>",province_id: 24}, {_id:24219,name: "<NAME>",province_id: 24}, {_id:24221,name: "Villaquejida",province_id: 24}, {_id:24222,name: "Villaquilambre",province_id: 24}, {_id:24223,name: "<NAME>",province_id: 24}, {_id:24224,name: "<NAME>",province_id: 24}, {_id:24225,name: "Villasabariego",province_id: 24}, {_id:24226,name: "Villaselán",province_id: 24}, {_id:24227,name: "Villaturiel",province_id: 24}, {_id:24228,name: "Villazala",province_id: 24}, {_id:24229,name: "<NAME>",province_id: 24}, {_id:24230,name: "<NAME>",province_id: 24}, {_id:24901,name: "Villamanín",province_id: 24}, {_id:24902,name: "<NAME>",province_id: 24}, {_id:25001,name: "<NAME>",province_id: 25}, {_id:25002,name: "Àger",province_id: 25}, {_id:25003,name: "Agramunt",province_id: 25}, {_id:25004,name: "Alamús (Els)",province_id: 25}, {_id:25005,name: "<NAME>",province_id: 25}, {_id:25006,name: "Albagés (L )",province_id: 25}, {_id:25007,name: "Albatàrrec",province_id: 25}, {_id:25008,name: "Albesa",province_id: 25}, {_id:25009,name: "Albi (L )",province_id: 25}, {_id:25010,name: "Alcanó",province_id: 25}, {_id:25011,name: "Alcarràs",province_id: 25}, {_id:25012,name: "Alcoletge",province_id: 25}, {_id:25013,name: "Alfarràs",province_id: 25}, {_id:25014,name: "Alfés",province_id: 25}, {_id:25015,name: "Algerri",province_id: 25}, {_id:25016,name: "Alguaire",province_id: 25}, {_id:25017,name: "Alins",province_id: 25}, {_id:25019,name: "Almacelles",province_id: 25}, {_id:25020,name: "Almatret",province_id: 25}, {_id:25021,name: "Almenar",province_id: 25}, {_id:25022,name: "<NAME>",province_id: 25}, {_id:25023,name: "Alpicat",province_id: 25}, {_id:25024,name: "<NAME>",province_id: 25}, {_id:25025,name: "<NAME>",province_id: 25}, {_id:25027,name: "Anglesola",province_id: 25}, {_id:25029,name: "Arbeca",province_id: 25}, {_id:25030,name: "<NAME> (El)",province_id: 25}, {_id:25031,name: "Arres",province_id: 25}, {_id:25032,name: "Arsèguel",province_id: 25}, {_id:25033,name: "<NAME>",province_id: 25}, {_id:25034,name: "<NAME>",province_id: 25}, {_id:25035,name: "<NAME> (La)",province_id: 25}, {_id:25036,name: "Aspa",province_id: 25}, {_id:25037,name: "<NAME> <NAME> (Les)",province_id: 25}, {_id:25038,name: "Aitona",province_id: 25}, {_id:25039,name: "<NAME>",province_id: 25}, {_id:25040,name: "Balaguer",province_id: 25}, {_id:25041,name: "Barbens",province_id: 25}, {_id:25042,name: "<NAME> (La)",province_id: 25}, {_id:25043,name: "<NAME> (La)",province_id: 25}, {_id:25044,name: "Bassella",province_id: 25}, {_id:25045,name: "Bausen",province_id: 25}, {_id:25046,name: "Belianes",province_id: 25}, {_id:25047,name: "<NAME>",province_id: 25}, {_id:25048,name: "<NAME>",province_id: 25}, {_id:25049,name: "<NAME>",province_id: 25}, {_id:25050,name: "Bellpuig",province_id: 25}, {_id:25051,name: "<NAME>",province_id: 25}, {_id:25052,name: "Bellvís",province_id: 25}, {_id:25053,name: "<NAME>",province_id: 25}, {_id:25055,name: "Biosca",province_id: 25}, {_id:25056,name: "Bovera",province_id: 25}, {_id:25057,name: "Bòrdes (Es)",province_id: 25}, {_id:25058,name: "<NAME> (Les)",province_id: 25}, {_id:25059,name: "Bossòst",province_id: 25}, {_id:25060,name: "Cabanabona",province_id: 25}, {_id:25061,name: "Cabó",province_id: 25}, {_id:25062,name: "Camarasa",province_id: 25}, {_id:25063,name: "Canejan",province_id: 25}, {_id:25064,name: "<NAME>",province_id: 25}, {_id:25067,name: "Castelldans",province_id: 25}, {_id:25068,name: "<NAME>",province_id: 25}, {_id:25069,name: "<NAME>",province_id: 25}, {_id:25070,name: "Castellserà",province_id: 25}, {_id:25071,name: "Cava",province_id: 25}, {_id:25072,name: "Cervera",province_id: 25}, {_id:25073,name: "<NAME>",province_id: 25}, {_id:25074,name: "Ciutadilla",province_id: 25}, {_id:25075,name: "<NAME>",province_id: 25}, {_id:25076,name: "Cogul (El)",province_id: 25}, {_id:25077,name: "<NAME>",province_id: 25}, {_id:25078,name: "Corbins",province_id: 25}, {_id:25079,name: "Cubells",province_id: 25}, {_id:25081,name: "<NAME> (L )",province_id: 25}, {_id:25082,name: "Espot",province_id: 25}, {_id:25085,name: "Estaràs",province_id: 25}, {_id:25086,name: "<NAME>",province_id: 25}, {_id:25087,name: "<NAME>",province_id: 25}, {_id:25088,name: "Estamariu",province_id: 25}, {_id:25089,name: "Farrera",province_id: 25}, {_id:25092,name: "Floresta (La)",province_id: 25}, {_id:25093,name: "Fondarella",province_id: 25}, {_id:25094,name: "Foradada",province_id: 25}, {_id:25096,name: "Fuliola (La)",province_id: 25}, {_id:25097,name: "Fulleda",province_id: 25}, {_id:25098,name: "<NAME>",province_id: 25}, {_id:25099,name: "Golmés",province_id: 25}, {_id:25100,name: "Gósol",province_id: 25}, {_id:25101,name: "Granadella (La)",province_id: 25}, {_id:25102,name: "<NAME> (La)",province_id: 25}, {_id:25103,name: "Granyanella",province_id: 25}, {_id:25104,name: "<NAME>",province_id: 25}, {_id:25105,name: "<NAME>",province_id: 25}, {_id:25109,name: "Guimerà",province_id: 25}, {_id:25110,name: "Guissona",province_id: 25}, {_id:25111,name: "Guixers",province_id: 25}, {_id:25112,name: "<NAME>",province_id: 25}, {_id:25113,name: "<NAME>",province_id: 25}, {_id:25114,name: "Ivorra",province_id: 25}, {_id:25115,name: "<NAME>",province_id: 25}, {_id:25118,name: "Juncosa",province_id: 25}, {_id:25119,name: "Juneda",province_id: 25}, {_id:25120,name: "Lleida",province_id: 25}, {_id:25121,name: "Les",province_id: 25}, {_id:25122,name: "Linyola",province_id: 25}, {_id:25123,name: "Lladorre",province_id: 25}, {_id:25124,name: "Lladurs",province_id: 25}, {_id:25125,name: "Llardecans",province_id: 25}, {_id:25126,name: "Llavorsí",province_id: 25}, {_id:25127,name: "<NAME>",province_id: 25}, {_id:25128,name: "Llimiana",province_id: 25}, {_id:25129,name: "Llobera",province_id: 25}, {_id:45154,name: "<NAME>",province_id: 45}, {_id:45155,name: "<NAME>",province_id: 45}, {_id:45156,name: "<NAME>",province_id: 45}, {_id:45157,name: "<NAME>",province_id: 45}, {_id:45158,name: "<NAME>",province_id: 45}, {_id:45159,name: "Sartajada",province_id: 45}, {_id:45160,name: "Segurilla",province_id: 45}, {_id:45161,name: "Seseña",province_id: 45}, {_id:45162,name: "<NAME>",province_id: 45}, {_id:45163,name: "Sonseca",province_id: 45}, {_id:45164,name: "<NAME>",province_id: 45}, {_id:45165,name: "<NAME>",province_id: 45}, {_id:45166,name: "Tembleque",province_id: 45}, {_id:45167,name: "<NAME>)",province_id: 45}, {_id:45168,name: "Toledo",province_id: 45}, {_id:45169,name: "<NAME>",province_id: 45}, {_id:45170,name: "<NAME>",province_id: 45}, {_id:45171,name: "<NAME> Hambrán (La)",province_id: 45}, {_id:45172,name: "Torrico",province_id: 45}, {_id:45173,name: "Torrijos",province_id: 45}, {_id:45174,name: "Totanés",province_id: 45}, {_id:45175,name: "Turleque",province_id: 45}, {_id:45176,name: "Ugena",province_id: 45}, {_id:45177,name: "Urda",province_id: 45}, {_id:45179,name: "Valdeverdeja",province_id: 45}, {_id:45180,name: "Valmojado",province_id: 45}, {_id:45181,name: "Velada",province_id: 45}, {_id:45182,name: "Ventas con Pe<NAME> (Las)",province_id: 45}, {_id:45183,name: "Ventas de Retamosa (Las)",province_id: 45}, {_id:45184,name: "Ventas de San Julián (Las)",province_id: 45}, {_id:45185,name: "Villacañas",province_id: 45}, {_id:45186,name: "<NAME> (La)",province_id: 45}, {_id:45187,name: "<NAME>",province_id: 45}, {_id:45188,name: "<NAME>",province_id: 45}, {_id:45189,name: "<NAME>",province_id: 45}, {_id:45190,name: "Villaminaya",province_id: 45}, {_id:45191,name: "Villamuelas",province_id: 45}, {_id:45192,name: "<NAME>",province_id: 45}, {_id:45193,name: "<NAME>",province_id: 45}, {_id:45194,name: "<NAME>",province_id: 45}, {_id:45195,name: "<NAME>",province_id: 45}, {_id:45196,name: "<NAME>",province_id: 45}, {_id:45197,name: "Villasequilla",province_id: 45}, {_id:45198,name: "Villatobas",province_id: 45}, {_id:45199,name: "<NAME> (El)",province_id: 45}, {_id:45200,name: "Yébenes (Los)",province_id: 45}, {_id:45201,name: "Yeles",province_id: 45}, {_id:45202,name: "Yepes",province_id: 45}, {_id:45203,name: "Yuncler",province_id: 45}, {_id:45204,name: "Yunclillos",province_id: 45}, {_id:45205,name: "Yuncos",province_id: 45}, {_id:45901,name: "<NAME>",province_id: 45}, {_id:46001,name: "Ademuz",province_id: 46}, {_id:46002,name: "Ador",province_id: 46}, {_id:46003,name: "<NAME>",province_id: 46}, {_id:46004,name: "Agullent",province_id: 46}, {_id:46005,name: "Alaquàs",province_id: 46}, {_id:46006,name: "Albaida",province_id: 46}, {_id:46007,name: "Albal",province_id: 46}, {_id:46008,name: "<NAME>",province_id: 46}, {_id:46009,name: "<NAME>",province_id: 46}, {_id:46010,name: "<NAME>",province_id: 46}, {_id:46011,name: "Alberic",province_id: 46}, {_id:46012,name: "Alborache",province_id: 46}, {_id:46013,name: "Alboraya",province_id: 46}, {_id:46014,name: "Albuixech",province_id: 46}, {_id:46015,name: "Alcàsser",province_id: 46}, {_id:46016,name: "<NAME>",province_id: 46}, {_id:46017,name: "Alzira",province_id: 46}, {_id:46018,name: "Alcublas",province_id: 46}, {_id:46019,name: "Alcúdia (l )",province_id: 46}, {_id:46020,name: "<NAME> (l )",province_id: 46}, {_id:46021,name: "Aldaia",province_id: 46}, {_id:46022,name: "Alfafar",province_id: 46}, {_id:46023,name: "Alfauir",province_id: 46}, {_id:46024,name: "<NAME>",province_id: 46}, {_id:46025,name: "<NAME>",province_id: 46}, {_id:46026,name: "Alfarp",province_id: 46}, {_id:46027,name: "Alfarrasí",province_id: 46}, {_id:46028,name: "<NAME>",province_id: 46}, {_id:46029,name: "Algemesí",province_id: 46}, {_id:46030,name: "<NAME>",province_id: 46}, {_id:46031,name: "Alginet",province_id: 46}, {_id:46032,name: "Almàssera",province_id: 46}, {_id:46033,name: "Almiserà",province_id: 46}, {_id:46034,name: "Almoines",province_id: 46}, {_id:46035,name: "Almussafes",province_id: 46}, {_id:46036,name: "Alpuente",province_id: 46}, {_id:46037,name: "<NAME> (l )",province_id: 46}, {_id:46038,name: "Andilla",province_id: 46}, {_id:46039,name: "Anna",province_id: 46}, {_id:46040,name: "Antella",province_id: 46}, {_id:46041,name: "<NAME>",province_id: 46}, {_id:46042,name: "<NAME>",province_id: 46}, {_id:46043,name: "<NAME>",province_id: 46}, {_id:46044,name: "Ayora",province_id: 46}, {_id:46045,name: "Barxeta",province_id: 46}, {_id:46046,name: "Barx",province_id: 46}, {_id:46047,name: "Bèlgida",province_id: 46}, {_id:46048,name: "Bellreguard",province_id: 46}, {_id:46049,name: "Bellús",province_id: 46}, {_id:46050,name: "Benagéber",province_id: 46}, {_id:46051,name: "Benaguasil",province_id: 46}, {_id:46052,name: "Benavites",province_id: 46}, {_id:46053,name: "Beneixida",province_id: 46}, {_id:46054,name: "Benetússer",province_id: 46}, {_id:46055,name: "Beniarjó",province_id: 46}, {_id:46056,name: "Beniatjar",province_id: 46}, {_id:46057,name: "Benicolet",province_id: 46}, {_id:46058,name: "<NAME>",province_id: 46}, {_id:46059,name: "<NAME>",province_id: 46}, {_id:46060,name: "Benifaió",province_id: 46}, {_id:46061,name: "Beniflá",province_id: 46}, {_id:46062,name: "Benigánim",province_id: 46}, {_id:46063,name: "Benimodo",province_id: 46}, {_id:46064,name: "Benimuslem",province_id: 46}, {_id:46065,name: "Beniparrell",province_id: 46}, {_id:46066,name: "Benirredrà",province_id: 46}, {_id:46067,name: "Benisanó",province_id: 46}, {_id:46068,name: "Benissoda",province_id: 46}, {_id:46069,name: "Benisuera",province_id: 46}, {_id:46070,name: "Bétera",province_id: 46}, {_id:46071,name: "Bicorp",province_id: 46}, {_id:46072,name: "Bocairent",province_id: 46}, {_id:46073,name: "Bolbaite",province_id: 46}, {_id:46074,name: "<NAME>",province_id: 46}, {_id:46075,name: "Bufali",province_id: 46}, {_id:46076,name: "Bugarra",province_id: 46}, {_id:46077,name: "Buñol",province_id: 46}, {_id:46078,name: "Burjassot",province_id: 46}, {_id:46079,name: "Calles",province_id: 46}, {_id:46080,name: "Camporrobles",province_id: 46}, {_id:46081,name: "Canals",province_id: 46}, {_id:46082,name: "<NAME>",province_id: 46}, {_id:46083,name: "Carcaixent",province_id: 46}, {_id:46084,name: "Càrcer",province_id: 46}, {_id:46085,name: "Carlet",province_id: 46}, {_id:46086,name: "Carrícola",province_id: 46}, {_id:46087,name: "<NAME>",province_id: 46}, {_id:46088,name: "<NAME>",province_id: 46}, {_id:46089,name: "Casinos",province_id: 46}, {_id:46090,name: "<NAME>",province_id: 46}, {_id:46091,name: "<NAME>",province_id: 46}, {_id:46092,name: "Castielfabib",province_id: 46}, {_id:46093,name: "Catadau",province_id: 46}, {_id:46094,name: "Catarroja",province_id: 46}, {_id:46095,name: "<NAME>",province_id: 46}, {_id:46096,name: "Cerdà",province_id: 46}, {_id:46097,name: "Cofrentes",province_id: 46}, {_id:46098,name: "Corbera",province_id: 46}, {_id:46099,name: "<NAME>",province_id: 46}, {_id:46100,name: "Cotes",province_id: 46}, {_id:46101,name: "<NAME>",province_id: 46}, {_id:46102,name: "<NAME>",province_id: 46}, {_id:46103,name: "Quartell",province_id: 46}, {_id:46104,name: "Quatretonda",province_id: 46}, {_id:46105,name: "Cullera",province_id: 46}, {_id:46106,name: "Chelva",province_id: 46}, {_id:46107,name: "Chella",province_id: 46}, {_id:46108,name: "Chera",province_id: 46}, {_id:46109,name: "Cheste",province_id: 46}, {_id:46110,name: "Xirivella",province_id: 46}, {_id:46111,name: "Chiva",province_id: 46}, {_id:46112,name: "Chulilla",province_id: 46}, {_id:46113,name: "Daimús",province_id: 46}, {_id:46114,name: "Domeño",province_id: 46}, {_id:46115,name: "<NAME>",province_id: 46}, {_id:46116,name: "Eliana (l )",province_id: 46}, {_id:46117,name: "Emperador",province_id: 46}, {_id:46118,name: "Enguera",province_id: 46}, {_id:46119,name: "Ènova (l )",province_id: 46}, {_id:46120,name: "Estivella",province_id: 46}, {_id:46121,name: "Estubeny",province_id: 46}, {_id:46122,name: "Faura",province_id: 46}, {_id:46123,name: "Favara",province_id: 46}, {_id:46124,name: "<NAME>",province_id: 46}, {_id:46125,name: "Fortaleny",province_id: 46}, {_id:46126,name: "Foios",province_id: 46}, {_id:46127,name: "<NAME> (la)",province_id: 46}, {_id:46128,name: "<NAME> (la)",province_id: 46}, {_id:46129,name: "Fuenterrobles",province_id: 46}, {_id:46130,name: "Gavarda",province_id: 46}, {_id:46131,name: "Gandia",province_id: 46}, {_id:46132,name: "Genovés",province_id: 46}, {_id:46133,name: "Gestalgar",province_id: 46}, {_id:46134,name: "Gilet",province_id: 46}, {_id:46135,name: "Godella",province_id: 46}, {_id:46136,name: "Godelleta",province_id: 46}, {_id:46137,name: "<NAME> (la)",province_id: 46}, {_id:46138,name: "Guadasequies",province_id: 46}, {_id:46139,name: "Guadassuar",province_id: 46}, {_id:46140,name: "<NAME>",province_id: 46}, {_id:46141,name: "Higueruelas",province_id: 46}, {_id:46142,name: "Jalance",province_id: 46}, {_id:46143,name: "Xeraco",province_id: 46}, {_id:46144,name: "Jarafuel",province_id: 46}, {_id:46145,name: "Xàtiva",province_id: 46}, {_id:46146,name: "Xeresa",province_id: 46}, {_id:46147,name: "Llíria",province_id: 46}, {_id:46148,name: "Loriguilla",province_id: 46}, {_id:46149,name: "<NAME>",province_id: 46}, {_id:46150,name: "Llutxent",province_id: 46}, {_id:46151,name: "<NAME>",province_id: 46}, {_id:46152,name: "<NAME>",province_id: 46}, {_id:46153,name: "<NAME>",province_id: 46}, {_id:46154,name: "<NAME>",province_id: 46}, {_id:46155,name: "Llaurí",province_id: 46}, {_id:46156,name: "Llombai",province_id: 46}, {_id:46157,name: "<NAME> (la)",province_id: 46}, {_id:46158,name: "Macastre",province_id: 46}, {_id:46159,name: "Manises",province_id: 46}, {_id:46160,name: "Manuel",province_id: 46}, {_id:46161,name: "Marines",province_id: 46}, {_id:46162,name: "Masalavés",province_id: 46}, {_id:46163,name: "Massalfassar",province_id: 46}, {_id:46164,name: "Massamagrell",province_id: 46}, {_id:46165,name: "Massanassa",province_id: 46}, {_id:46166,name: "Meliana",province_id: 46}, {_id:46167,name: "Millares",province_id: 46}, {_id:46168,name: "Miramar",province_id: 46}, {_id:46169,name: "Mislata",province_id: 46}, {_id:46170,name: "Mogente/Moixent",province_id: 46}, {_id:46171,name: "Moncada",province_id: 46}, {_id:46172,name: "Montserrat",province_id: 46}, {_id:46173,name: "Montaverner",province_id: 46}, {_id:46174,name: "Montesa",province_id: 46}, {_id:46175,name: "Montichelvo",province_id: 46}, {_id:46176,name: "Montroy",province_id: 46}, {_id:46177,name: "Museros",province_id: 46}, {_id:46178,name: "Náquera",province_id: 46}, {_id:46179,name: "Navarrés",province_id: 46}, {_id:46180,name: "Novelé/Novetlè",province_id: 46}, {_id:46181,name: "Oliva",province_id: 46}, {_id:46182,name: "Olocau",province_id: 46}, {_id:46183,name: "Olleria (l )",province_id: 46}, {_id:46184,name: "Ontinyent",province_id: 46}, {_id:46185,name: "Otos",province_id: 46}, {_id:46186,name: "Paiporta",province_id: 46}, {_id:46187,name: "<NAME>",province_id: 46}, {_id:46188,name: "Palmera",province_id: 46}, {_id:46189,name: "Palomar (el)",province_id: 46}, {_id:46190,name: "Paterna",province_id: 46}, {_id:46191,name: "Pedralba",province_id: 46}, {_id:46192,name: "Petrés",province_id: 46}, {_id:46193,name: "Picanya",province_id: 46}, {_id:46194,name: "Picassent",province_id: 46}, {_id:46195,name: "Piles",province_id: 46}, {_id:46196,name: "Pinet",province_id: 46}, {_id:46197,name: "<NAME>",province_id: 46}, {_id:46198,name: "Potríes",province_id: 46}, {_id:46199,name: "<NAME> (la)",province_id: 46}, {_id:46200,name: "<NAME> (la)",province_id: 46}, {_id:46201,name: "<NAME>",province_id: 46}, {_id:46202,name: "<NAME> (la)",province_id: 46}, {_id:46203,name: "<NAME> (la)",province_id: 46}, {_id:46204,name: "Puig",province_id: 46}, {_id:46205,name: "Puçol",province_id: 46}, {_id:46206,name: "Quesa",province_id: 46}, {_id:46207,name: "Rafelbuñol/Rafelbunyol",province_id: 46}, {_id:46208,name: "Rafelcofer",province_id: 46}, {_id:46209,name: "Rafelguaraf",province_id: 46}, {_id:46210,name: "<NAME>",province_id: 46}, {_id:46211,name: "<NAME>",province_id: 46}, {_id:46212,name: "<NAME>",province_id: 46}, {_id:46213,name: "Requena",province_id: 46}, {_id:46214,name: "<NAME>",province_id: 46}, {_id:46215,name: "Riola",province_id: 46}, {_id:46216,name: "Rocafort",province_id: 46}, {_id:46217,name: "<NAME>",province_id: 46}, {_id:46218,name: "Rótova",province_id: 46}, {_id:46219,name: "Rugat",province_id: 46}, {_id:46220,name: "Sagunto/Sagunt",province_id: 46}, {_id:46221,name: "Salem",province_id: 46}, {_id:46222,name: "<NAME>",province_id: 46}, {_id:46223,name: "Sedaví",province_id: 46}, {_id:46224,name: "Segart",province_id: 46}, {_id:46225,name: "Sellent",province_id: 46}, {_id:46226,name: "Sempere",province_id: 46}, {_id:46227,name: "Senyera",province_id: 46}, {_id:46228,name: "Serra",province_id: 46}, {_id:46229,name: "<NAME>",province_id: 46}, {_id:46230,name: "Silla",province_id: 46}, {_id:46231,name: "<NAME>",province_id: 46}, {_id:46232,name: "Sinarcas",province_id: 46}, {_id:46233,name: "Sollana",province_id: 46}, {_id:46234,name: "<NAME>",province_id: 46}, {_id:46235,name: "Sueca",province_id: 46}, {_id:46236,name: "Sumacàrcer",province_id: 46}, {_id:46237,name: "<NAME>",province_id: 46}, {_id:25130,name: "Maldà",province_id: 25}, {_id:25131,name: "Massalcoreig",province_id: 25}, {_id:25132,name: "Massoteres",province_id: 25}, {_id:25133,name: "Maials",province_id: 25}, {_id:25134,name: "Menàrguens",province_id: 25}, {_id:25135,name: "Miralcamp",province_id: 25}, {_id:25136,name: "<NAME>)",province_id: 25}, {_id:25137,name: "Mollerussa",province_id: 25}, {_id:25138,name: "Montgai",province_id: 25}, {_id:25139,name: "<NAME>",province_id: 25}, {_id:25140,name: "<NAME>",province_id: 25}, {_id:25141,name: "<NAME>",province_id: 25}, {_id:25142,name: "<NAME>",province_id: 25}, {_id:25143,name: "<NAME>",province_id: 25}, {_id:25145,name: "Nalec",province_id: 25}, {_id:25146,name: "Navès",province_id: 25}, {_id:25148,name: "Odèn",province_id: 25}, {_id:25149,name: "Oliana",province_id: 25}, {_id:25150,name: "Oliola",province_id: 25}, {_id:25151,name: "Olius",province_id: 25}, {_id:25152,name: "Oluges (Les)",province_id: 25}, {_id:25153,name: "Omellons (Els)",province_id: 25}, {_id:25154,name: "<NAME> (Els)",province_id: 25}, {_id:25155,name: "Organyà",province_id: 25}, {_id:25156,name: "<NAME>",province_id: 25}, {_id:25157,name: "<NAME>",province_id: 25}, {_id:25158,name: "<NAME> (El)",province_id: 25}, {_id:25161,name: "<NAME>",province_id: 25}, {_id:25163,name: "<NAME> (La)",province_id: 25}, {_id:25164,name: "Penelles",province_id: 25}, {_id:25165,name: "Peramola",province_id: 25}, {_id:25166,name: "<NAME>",province_id: 25}, {_id:25167,name: "Pinós",province_id: 25}, {_id:25168,name: "Poal (El)",province_id: 25}, {_id:25169,name: "<NAME> (La)",province_id: 25}, {_id:25170,name: "Bellaguarda",province_id: 25}, {_id:25171,name: "<NAME> (La)",province_id: 25}, {_id:25172,name: "Ponts",province_id: 25}, {_id:25173,name: "<NAME> (El)",province_id: 25}, {_id:25174,name: "Portella (La)",province_id: 25}, {_id:25175,name: "<NAME>",province_id: 25}, {_id:25176,name: "Preixana",province_id: 25}, {_id:25177,name: "Preixens",province_id: 25}, {_id:25179,name: "Prullans",province_id: 25}, {_id:25180,name: "Puiggròs",province_id: 25}, {_id:25181,name: "<NAME>",province_id: 25}, {_id:25182,name: "<NAME>",province_id: 25}, {_id:25183,name: "Rialp",province_id: 25}, {_id:25185,name: "<NAME>",province_id: 25}, {_id:25186,name: "Riner",province_id: 25}, {_id:25189,name: "Rosselló",province_id: 25}, {_id:25190,name: "<NAME>",province_id: 25}, {_id:25191,name: "Sanaüja",province_id: 25}, {_id:25192,name: "<NAME>",province_id: 25}, {_id:25193,name: "<NAME>",province_id: 25}, {_id:25194,name: "<NAME>",province_id: 25}, {_id:25196,name: "<NAME>",province_id: 25}, {_id:25197,name: "<NAME>",province_id: 25}, {_id:25200,name: "<NAME>",province_id: 25}, {_id:25201,name: "<NAME>",province_id: 25}, {_id:25202,name: "Senterada",province_id: 25}, {_id:25203,name: "<NAME> (La)",province_id: 25}, {_id:25204,name: "Seròs",province_id: 25}, {_id:25205,name: "Sidamon",province_id: 25}, {_id:25206,name: "Soleràs (El)",province_id: 25}, {_id:25207,name: "Solsona",province_id: 25}, {_id:25208,name: "Soriguera",province_id: 25}, {_id:25209,name: "Sort",province_id: 25}, {_id:25210,name: "Soses",province_id: 25}, {_id:25211,name: "Sudanell",province_id: 25}, {_id:25212,name: "Sunyer",province_id: 25}, {_id:25215,name: "Talarn",province_id: 25}, {_id:25216,name: "Talavera",province_id: 25}, {_id:25217,name: "Tàrrega",province_id: 25}, {_id:25218,name: "Tarrés",province_id: 25}, {_id:25219,name: "<NAME>",province_id: 25}, {_id:25220,name: "Térmens",province_id: 25}, {_id:25221,name: "Tírvia",province_id: 25}, {_id:25222,name: "Tiurana",province_id: 25}, {_id:25223,name: "Torà",province_id: 25}, {_id:25224,name: "Torms (Els)",province_id: 25}, {_id:25225,name: "Tornabous",province_id: 25}, {_id:25226,name: "Torrebesses",province_id: 25}, {_id:25227,name: "<NAME> (La)",province_id: 25}, {_id:25228,name: "Torrefarrera",province_id: 25}, {_id:25230,name: "Torregrossa",province_id: 25}, {_id:25231,name: "Torrelameu",province_id: 25}, {_id:25232,name: "<NAME>",province_id: 25}, {_id:25233,name: "Torre-serona",province_id: 25}, {_id:25234,name: "Tremp",province_id: 25}, {_id:25238,name: "<NAME>",province_id: 25}, {_id:25239,name: "<NAME> (Les)",province_id: 25}, {_id:25240,name: "<NAME>",province_id: 25}, {_id:25242,name: "Verdú",province_id: 25}, {_id:25243,name: "<NAME>",province_id: 25}, {_id:25244,name: "Vilagrassa",province_id: 25}, {_id:25245,name: "Vilaller",province_id: 25}, {_id:25247,name: "Vilamòs",province_id: 25}, {_id:25248,name: "<NAME>",province_id: 25}, {_id:25249,name: "<NAME>",province_id: 25}, {_id:25250,name: "<NAME>",province_id: 25}, {_id:25251,name: "<NAME>",province_id: 25}, {_id:25252,name: "Vila-sana",province_id: 25}, {_id:25253,name: "Vilosell (El)",province_id: 25}, {_id:25254,name: "<NAME>",province_id: 25}, {_id:25255,name: "Vinaixa",province_id: 25}, {_id:25901,name: "<NAME>",province_id: 25}, {_id:25902,name: "<NAME>",province_id: 25}, {_id:25903,name: "<NAME> (La)",province_id: 25}, {_id:25904,name: "<NAME>",province_id: 25}, {_id:25905,name: "<NAME>",province_id: 25}, {_id:25906,name: "<NAME> (Les)",province_id: 25}, {_id:25907,name: "<NAME>",province_id: 25}, {_id:25908,name: "<NAME>",province_id: 25}, {_id:25909,name: "<NAME> (La)",province_id: 25}, {_id:25910,name: "<NAME>",province_id: 25}, {_id:25911,name: "<NAME> (Els)",province_id: 25}, {_id:25912,name: "Gimenells i el <NAME>",province_id: 25}, {_id:25913,name: "<NAME>",province_id: 25}, {_id:26001,name: "Ábalos",province_id: 26}, {_id:26002,name: "Agoncillo",province_id: 26}, {_id:26003,name: "<NAME>",province_id: 26}, {_id:26004,name: "Ajamil",province_id: 26}, {_id:26005,name: "<NAME>",province_id: 26}, {_id:26006,name: "Alberite",province_id: 26}, {_id:26007,name: "Alcanadre",province_id: 26}, {_id:26008,name: "<NAME>",province_id: 26}, {_id:26009,name: "Alesanco",province_id: 26}, {_id:26010,name: "Alesón",province_id: 26}, {_id:26011,name: "Alfaro",province_id: 26}, {_id:26012,name: "<NAME>",province_id: 26}, {_id:26013,name: "Anguciana",province_id: 26}, {_id:26014,name: "Anguiano",province_id: 26}, {_id:26015,name: "<NAME>",province_id: 26}, {_id:26016,name: "<NAME>",province_id: 26}, {_id:26017,name: "Arnedillo",province_id: 26}, {_id:26018,name: "Arnedo",province_id: 26}, {_id:26019,name: "Arrúbal",province_id: 26}, {_id:26020,name: "Ausejo",province_id: 26}, {_id:26021,name: "Autol",province_id: 26}, {_id:26022,name: "Azofra",province_id: 26}, {_id:26023,name: "Badarán",province_id: 26}, {_id:26024,name: "Bañares",province_id: 26}, {_id:26025,name: "<NAME>",province_id: 26}, {_id:26026,name: "<NAME>",province_id: 26}, {_id:26027,name: "Berceo",province_id: 26}, {_id:26028,name: "Bergasa",province_id: 26}, {_id:26029,name: "<NAME>",province_id: 26}, {_id:26030,name: "Bezares",province_id: 26}, {_id:26031,name: "Bobadilla",province_id: 26}, {_id:26032,name: "<NAME>",province_id: 26}, {_id:26033,name: "Briñas",province_id: 26}, {_id:26034,name: "Briones",province_id: 26}, {_id:26035,name: "<NAME>",province_id: 26}, {_id:26036,name: "Calahorra",province_id: 26}, {_id:26037,name: "Camprovín",province_id: 26}, {_id:26038,name: "<NAME> la Sierra",province_id: 26}, {_id:26039,name: "<NAME>",province_id: 26}, {_id:26040,name: "Cañas",province_id: 26}, {_id:26041,name: "Cárdenas",province_id: 26}, {_id:26042,name: "Casalarreina",province_id: 26}, {_id:26043,name: "<NAME>",province_id: 26}, {_id:26044,name: "Castroviejo",province_id: 26}, {_id:26045,name: "Cellorigo",province_id: 26}, {_id:26046,name: "Cenicero",province_id: 26}, {_id:26047,name: "<NAME>",province_id: 26}, {_id:26048,name: "Cidamón",province_id: 26}, {_id:26049,name: "Cihuri",province_id: 26}, {_id:26050,name: "Cirueña",province_id: 26}, {_id:26051,name: "Clavijo",province_id: 26}, {_id:26052,name: "Cordovín",province_id: 26}, {_id:26053,name: "Corera",province_id: 26}, {_id:26054,name: "Cornago",province_id: 26}, {_id:26055,name: "Corporales",province_id: 26}, {_id:26056,name: "<NAME>",province_id: 26}, {_id:26057,name: "<NAME>",province_id: 26}, {_id:26058,name: "Enciso",province_id: 26}, {_id:26059,name: "Entrena",province_id: 26}, {_id:26060,name: "Estollo",province_id: 26}, {_id:26061,name: "Ezcaray",province_id: 26}, {_id:26062,name: "Foncea",province_id: 26}, {_id:26063,name: "Fonzaleche",province_id: 26}, {_id:26064,name: "Fuenmayor",province_id: 26}, {_id:26065,name: "Galbárruli",province_id: 26}, {_id:26066,name: "Galilea",province_id: 26}, {_id:26067,name: "<NAME>",province_id: 26}, {_id:26068,name: "Gimileo",province_id: 26}, {_id:26069,name: "Grañón",province_id: 26}, {_id:26070,name: "Grávalos",province_id: 26}, {_id:26071,name: "Haro",province_id: 26}, {_id:26072,name: "Herce",province_id: 26}, {_id:26073,name: "Herramélluri",province_id: 26}, {_id:26074,name: "Hervías",province_id: 26}, {_id:26075,name: "Hormilla",province_id: 26}, {_id:26076,name: "Hormilleja",province_id: 26}, {_id:26077,name: "<NAME>",province_id: 26}, {_id:26078,name: "<NAME>",province_id: 26}, {_id:26079,name: "Huércanos",province_id: 26}, {_id:26080,name: "Igea",province_id: 26}, {_id:26081,name: "<NAME>",province_id: 26}, {_id:26082,name: "<NAME>",province_id: 26}, {_id:26083,name: "<NAME>",province_id: 26}, {_id:26084,name: "Lardero",province_id: 26}, {_id:26086,name: "<NAME>",province_id: 26}, {_id:26087,name: "Leiva",province_id: 26}, {_id:26088,name: "<NAME>",province_id: 26}, {_id:26089,name: "Logroño",province_id: 26}, {_id:26091,name: "Lumbreras",province_id: 26}, {_id:26092,name: "Manjarrés",province_id: 26}, {_id:26093,name: "<NAME>",province_id: 26}, {_id:26094,name: "<NAME>",province_id: 26}, {_id:26095,name: "Matute",province_id: 26}, {_id:26096,name: "Medrano",province_id: 26}, {_id:26098,name: "Munilla",province_id: 26}, {_id:26099,name: "<NAME>",province_id: 26}, {_id:26100,name: "<NAME>",province_id: 26}, {_id:26101,name: "<NAME>",province_id: 26}, {_id:26102,name: "Nájera",province_id: 26}, {_id:26103,name: "Nalda",province_id: 26}, {_id:26104,name: "Navajún",province_id: 26}, {_id:26105,name: "Navarrete",province_id: 26}, {_id:26106,name: "Nestares",province_id: 26}, {_id:26107,name: "<NAME>",province_id: 26}, {_id:26108,name: "Ocón",province_id: 26}, {_id:26109,name: "Ochánduri",province_id: 26}, {_id:26110,name: "Ojacastro",province_id: 26}, {_id:26111,name: "Ollauri",province_id: 26}, {_id:26112,name: "<NAME>",province_id: 26}, {_id:26113,name: "Pazuengos",province_id: 26}, {_id:26114,name: "Pedroso",province_id: 26}, {_id:26115,name: "Pinillos",province_id: 26}, {_id:26117,name: "Pradejón",province_id: 26}, {_id:26118,name: "Pradillo",province_id: 26}, {_id:26119,name: "Préjano",province_id: 26}, {_id:26120,name: "Quel",province_id: 26}, {_id:26121,name: "Rabanera",province_id: 26}, {_id:26122,name: "<NAME> (El)",province_id: 26}, {_id:26123,name: "Redal (El)",province_id: 26}, {_id:26124,name: "Ribafrecha",province_id: 26}, {_id:26125,name: "<NAME>",province_id: 26}, {_id:26126,name: "<NAME>",province_id: 26}, {_id:26127,name: "Rodezno",province_id: 26}, {_id:26128,name: "Sajazarra",province_id: 26}, {_id:26129,name: "<NAME>",province_id: 26}, {_id:26130,name: "<NAME>",province_id: 26}, {_id:26131,name: "<NAME>",province_id: 26}, {_id:26132,name: "<NAME>",province_id: 26}, {_id:26134,name: "Santa Coloma",province_id: 26}, {_id:26135,name: "Santa Engracia del Jubera",province_id: 26}, {_id:26136,name: "<NAME>",province_id: 26}, {_id:26138,name: "<NAME>",province_id: 26}, {_id:26139,name: "<NAME>",province_id: 26}, {_id:26140,name: "<NAME>",province_id: 26}, {_id:26141,name: "Santurdejo",province_id: 26}, {_id:26142,name: "<NAME>ierra",province_id: 26}, {_id:26143,name: "Sojuela",province_id: 26}, {_id:26144,name: "Sorzano",province_id: 26}, {_id:26145,name: "Sotés",province_id: 26}, {_id:26146,name: "<NAME>",province_id: 26}, {_id:26147,name: "Terroba",province_id: 26}, {_id:26148,name: "Tirgo",province_id: 26}, {_id:26149,name: "Tobía",province_id: 26}, {_id:26150,name: "Tormantos",province_id: 26}, {_id:26151,name: "<NAME>",province_id: 26}, {_id:26152,name: "<NAME>",province_id: 26}, {_id:26153,name: "<NAME>",province_id: 26}, {_id:26154,name: "Torremontalbo",province_id: 26}, {_id:26155,name: "Treviana",province_id: 26}, {_id:26157,name: "Tricio",province_id: 26}, {_id:26158,name: "Tudelilla",province_id: 26}, {_id:26160,name: "Uruñuela",province_id: 26}, {_id:26161,name: "Valdemadera",province_id: 26}, {_id:26162,name: "Valgañón",province_id: 26}, {_id:26163,name: "Ventosa",province_id: 26}, {_id:26164,name: "Ventrosa",province_id: 26}, {_id:26165,name: "Viguera",province_id: 26}, {_id:26166,name: "<NAME>",province_id: 26}, {_id:26167,name: "<NAME>",province_id: 26}, {_id:26168,name: "<NAME>",province_id: 26}, {_id:26169,name: "<NAME>",province_id: 26}, {_id:28179,name: "<NAME>",province_id: 28}, {_id:28180,name: "<NAME>",province_id: 28}, {_id:28181,name: "<NAME>",province_id: 28}, {_id:28182,name: "<NAME>",province_id: 28}, {_id:28183,name: "Zarzalejo",province_id: 28}, {_id:28901,name: "Lozoyuela-Navas-Sieteiglesias",province_id: 28}, {_id:28902,name: "<NAME>",province_id: 28}, {_id:28903,name: "<NAME>",province_id: 28}, {_id:29001,name: "Alameda",province_id: 29}, {_id:29002,name: "Alcaucín",province_id: 29}, {_id:29003,name: "Alfarnate",province_id: 29}, {_id:29004,name: "Alfarnatejo",province_id: 29}, {_id:29005,name: "Algarrobo",province_id: 29}, {_id:29006,name: "Algatocín",province_id: 29}, {_id:29007,name: "<NAME>",province_id: 29}, {_id:29008,name: "<NAME>",province_id: 29}, {_id:29009,name: "Almáchar",province_id: 29}, {_id:29010,name: "Almargen",province_id: 29}, {_id:29011,name: "Almogía",province_id: 29}, {_id:29012,name: "Álora",province_id: 29}, {_id:29013,name: "Alozaina",province_id: 29}, {_id:29014,name: "Alpandeire",province_id: 29}, {_id:29015,name: "Antequera",province_id: 29}, {_id:29016,name: "Árchez",province_id: 29}, {_id:29017,name: "Archidona",province_id: 29}, {_id:29018,name: "Ardales",province_id: 29}, {_id:29019,name: "Arenas",province_id: 29}, {_id:29020,name: "Arriate",province_id: 29}, {_id:29021,name: "Atajate",province_id: 29}, {_id:29022,name: "Benadalid",province_id: 29}, {_id:29023,name: "Benahavís",province_id: 29}, {_id:29024,name: "Benalauría",province_id: 29}, {_id:29025,name: "Benalmádena",province_id: 29}, {_id:29026,name: "Benamargosa",province_id: 29}, {_id:29027,name: "Benamocarra",province_id: 29}, {_id:29028,name: "Benaoján",province_id: 29}, {_id:29029,name: "Benarrabá",province_id: 29}, {_id:29030,name: "Borge (El)",province_id: 29}, {_id:29031,name: "Burgo (El)",province_id: 29}, {_id:29032,name: "Campillos",province_id: 29}, {_id:29033,name: "<NAME>",province_id: 29}, {_id:29034,name: "<NAME>",province_id: 29}, {_id:29035,name: "<NAME>",province_id: 29}, {_id:29036,name: "Carratraca",province_id: 29}, {_id:29037,name: "Cartajima",province_id: 29}, {_id:29038,name: "Cártama",province_id: 29}, {_id:29039,name: "Casabermeja",province_id: 29}, {_id:29040,name: "Casarabonela",province_id: 29}, {_id:29041,name: "Casares",province_id: 29}, {_id:29042,name: "Coín",province_id: 29}, {_id:29043,name: "Colmenar",province_id: 29}, {_id:29044,name: "Comares",province_id: 29}, {_id:29045,name: "Cómpeta",province_id: 29}, {_id:29046,name: "<NAME>",province_id: 29}, {_id:29047,name: "<NAME>",province_id: 29}, {_id:29048,name: "<NAME>",province_id: 29}, {_id:29049,name: "<NAME>",province_id: 29}, {_id:29050,name: "Cútar",province_id: 29}, {_id:29051,name: "Estepona",province_id: 29}, {_id:29052,name: "Faraján",province_id: 29}, {_id:29053,name: "Frigiliana",province_id: 29}, {_id:29054,name: "Fuengirola",province_id: 29}, {_id:29055,name: "<NAME>",province_id: 29}, {_id:29056,name: "Gaucín",province_id: 29}, {_id:29057,name: "Genalguacil",province_id: 29}, {_id:29058,name: "Guaro",province_id: 29}, {_id:29059,name: "Humilladero",province_id: 29}, {_id:29060,name: "Igualeja",province_id: 29}, {_id:29061,name: "Istán",province_id: 29}, {_id:29062,name: "Iznate",province_id: 29}, {_id:29063,name: "<NAME>",province_id: 29}, {_id:29064,name: "Jubrique",province_id: 29}, {_id:29065,name: "Júzcar",province_id: 29}, {_id:29066,name: "Macharaviaya",province_id: 29}, {_id:29067,name: "Málaga",province_id: 29}, {_id:29068,name: "Manilva",province_id: 29}, {_id:29069,name: "Marbella",province_id: 29}, {_id:29070,name: "Mijas",province_id: 29}, {_id:29071,name: "Moclinejo",province_id: 29}, {_id:29072,name: "Mollina",province_id: 29}, {_id:29073,name: "Monda",province_id: 29}, {_id:29074,name: "Montejaque",province_id: 29}, {_id:29075,name: "Nerja",province_id: 29}, {_id:29076,name: "Ojén",province_id: 29}, {_id:29077,name: "Parauta",province_id: 29}, {_id:29079,name: "Periana",province_id: 29}, {_id:29080,name: "Pizarra",province_id: 29}, {_id:29081,name: "Pujerra",province_id: 29}, {_id:29082,name: "<NAME>",province_id: 29}, {_id:29083,name: "Riogordo",province_id: 29}, {_id:29084,name: "Ronda",province_id: 29}, {_id:29085,name: "Salares",province_id: 29}, {_id:29086,name: "Sayalonga",province_id: 29}, {_id:29087,name: "Sedella",province_id: 29}, {_id:29088,name: "<NAME>",province_id: 29}, {_id:29089,name: "Teba",province_id: 29}, {_id:29090,name: "Tolox",province_id: 29}, {_id:29091,name: "Torrox",province_id: 29}, {_id:29092,name: "Totalán",province_id: 29}, {_id:29093,name: "<NAME>",province_id: 29}, {_id:29094,name: "Vélez-Málaga",province_id: 29}, {_id:29095,name: "<NAME>",province_id: 29}, {_id:29096,name: "<NAME>",province_id: 29}, {_id:29097,name: "<NAME>",province_id: 29}, {_id:29098,name: "<NAME>",province_id: 29}, {_id:29099,name: "Viñuela",province_id: 29}, {_id:29100,name: "Yunquera",province_id: 29}, {_id:29901,name: "Torremolinos",province_id: 29}, {_id:30001,name: "Abanilla",province_id: 30}, {_id:30002,name: "Abarán",province_id: 30}, {_id:30003,name: "Águilas",province_id: 30}, {_id:30004,name: "Albudeite",province_id: 30}, {_id:30005,name: "Alcantarilla",province_id: 30}, {_id:30006,name: "Aledo",province_id: 30}, {_id:30007,name: "Alguazas",province_id: 30}, {_id:30008,name: "<NAME>",province_id: 30}, {_id:30009,name: "Archena",province_id: 30}, {_id:30010,name: "Beniel",province_id: 30}, {_id:30011,name: "Blanca",province_id: 30}, {_id:30012,name: "Bullas",province_id: 30}, {_id:30013,name: "Calasparra",province_id: 30}, {_id:30014,name: "<NAME>",province_id: 30}, {_id:30015,name: "<NAME>",province_id: 30}, {_id:30016,name: "Cartagena",province_id: 30}, {_id:30017,name: "Cehegín",province_id: 30}, {_id:30018,name: "Ceutí",province_id: 30}, {_id:30019,name: "Cieza",province_id: 30}, {_id:30020,name: "Fortuna",province_id: 30}, {_id:30021,name: "<NAME>",province_id: 30}, {_id:30022,name: "Jumilla",province_id: 30}, {_id:30023,name: "Librilla",province_id: 30}, {_id:30024,name: "Lorca",province_id: 30}, {_id:30025,name: "Lorquí",province_id: 30}, {_id:30026,name: "Mazarrón",province_id: 30}, {_id:30027,name: "<NAME>",province_id: 30}, {_id:30028,name: "Moratalla",province_id: 30}, {_id:30029,name: "Mula",province_id: 30}, {_id:30030,name: "Murcia",province_id: 30}, {_id:30031,name: "Ojós",province_id: 30}, {_id:30032,name: "Pliego",province_id: 30}, {_id:30033,name: "<NAME>",province_id: 30}, {_id:30034,name: "Ricote",province_id: 30}, {_id:30035,name: "<NAME>",province_id: 30}, {_id:30036,name: "<NAME>",province_id: 30}, {_id:30037,name: "Torre-Pacheco",province_id: 30}, {_id:30038,name: "<NAME> (Las)",province_id: 30}, {_id:30039,name: "Totana",province_id: 30}, {_id:30040,name: "Ulea",province_id: 30}, {_id:30041,name: "Unión (La)",province_id: 30}, {_id:30042,name: "<NAME>",province_id: 30}, {_id:30043,name: "Yecla",province_id: 30}, {_id:30901,name: "Santomera",province_id: 30}, {_id:30902,name: "Alcázares (Los)",province_id: 30}, {_id:31001,name: "Abáigar",province_id: 31}, {_id:31002,name: "Abárzuza",province_id: 31}, {_id:31003,name: "Abaurregaina/Abaurrea Alta",province_id: 31}, {_id:31004,name: "Abaurrepea/Abaurrea Baja",province_id: 31}, {_id:31005,name: "Aberin",province_id: 31}, {_id:31006,name: "Ablitas",province_id: 31}, {_id:31007,name: "Adiós",province_id: 31}, {_id:31008,name: "<NAME>",province_id: 31}, {_id:31009,name: "Aibar/Oibar",province_id: 31}, {_id:31010,name: "Altsasu/Alsasua",province_id: 31}, {_id:31011,name: "Allín",province_id: 31}, {_id:31012,name: "Allo",province_id: 31}, {_id:31013,name: "<NAME>",province_id: 31}, {_id:31014,name: "Ancín",province_id: 31}, {_id:31015,name: "Andosilla",province_id: 31}, {_id:31016,name: "Ansoáin",province_id: 31}, {_id:31017,name: "Anue",province_id: 31}, {_id:31018,name: "Añorbe",province_id: 31}, {_id:31019,name: "Aoiz/Agoitz",province_id: 31}, {_id:31020,name: "Araitz",province_id: 31}, {_id:31021,name: "Aranarache",province_id: 31}, {_id:31022,name: "Arantza",province_id: 31}, {_id:31023,name: "Aranguren",province_id: 31}, {_id:31024,name: "Arano",province_id: 31}, {_id:31025,name: "Arakil",province_id: 31}, {_id:31026,name: "Aras",province_id: 31}, {_id:31027,name: "Arbizu",province_id: 31}, {_id:31028,name: "Arce/Artzi",province_id: 31}, {_id:31029,name: "<NAME>)",province_id: 31}, {_id:31030,name: "Arellano",province_id: 31}, {_id:31031,name: "Areso",province_id: 31}, {_id:31032,name: "Arguedas",province_id: 31}, {_id:31033,name: "Aria",province_id: 31}, {_id:31034,name: "Aribe",province_id: 31}, {_id:31035,name: "Armañanzas",province_id: 31}, {_id:31036,name: "Arróniz",province_id: 31}, {_id:31037,name: "Arruazu",province_id: 31}, {_id:31038,name: "Artajona",province_id: 31}, {_id:31039,name: "Artazu",province_id: 31}, {_id:31040,name: "Atez",province_id: 31}, {_id:31041,name: "Ayegui",province_id: 31}, {_id:31042,name: "Azagra",province_id: 31}, {_id:31043,name: "Azuelo",province_id: 31}, {_id:31044,name: "Bakaiku",province_id: 31}, {_id:31045,name: "Barásoain",province_id: 31}, {_id:31046,name: "Barbarin",province_id: 31}, {_id:31047,name: "Bargota",province_id: 31}, {_id:31048,name: "Barillas",province_id: 31}, {_id:31049,name: "Basaburua",province_id: 31}, {_id:31050,name: "Baztan",province_id: 31}, {_id:31051,name: "Beire",province_id: 31}, {_id:31052,name: "Belascoáin",province_id: 31}, {_id:31053,name: "Berbinzana",province_id: 31}, {_id:31054,name: "Bertizarana",province_id: 31}, {_id:31055,name: "Betelu",province_id: 31}, {_id:31056,name: "Biurrun-Olcoz",province_id: 31}, {_id:31057,name: "Buñuel",province_id: 31}, {_id:31058,name: "Auritz/Burguete",province_id: 31}, {_id:31059,name: "Burgui/Burgi",province_id: 31}, {_id:31060,name: "Burlada/Burlata",province_id: 31}, {_id:31061,name: "Busto (El)",province_id: 31}, {_id:31062,name: "Cabanillas",province_id: 31}, {_id:31063,name: "Cabredo",province_id: 31}, {_id:31064,name: "Cadreita",province_id: 31}, {_id:31065,name: "Caparroso",province_id: 31}, {_id:31066,name: "Cárcar",province_id: 31}, {_id:31067,name: "Carcastillo",province_id: 31}, {_id:31068,name: "Cascante",province_id: 31}, {_id:31069,name: "Cáseda",province_id: 31}, {_id:31070,name: "Castejón",province_id: 31}, {_id:31071,name: "Castillonuevo",province_id: 31}, {_id:31072,name: "Cintruénigo",province_id: 31}, {_id:31073,name: "Ziordia",province_id: 31}, {_id:31074,name: "Cirauqui",province_id: 31}, {_id:31075,name: "Ciriza",province_id: 31}, {_id:31076,name: "Cizur",province_id: 31}, {_id:31077,name: "Corella",province_id: 31}, {_id:31078,name: "Cortes",province_id: 31}, {_id:31079,name: "Desojo",province_id: 31}, {_id:31080,name: "Dicastillo",province_id: 31}, {_id:31081,name: "Donamaria",province_id: 31}, {_id:31082,name: "Etxalar",province_id: 31}, {_id:31083,name: "Echarri",province_id: 31}, {_id:31084,name: "Etxarri-Aranatz",province_id: 31}, {_id:31085,name: "Etxauri",province_id: 31}, {_id:31086,name: "Egüés",province_id: 31}, {_id:31087,name: "Elgorriaga",province_id: 31}, {_id:31088,name: "Noáin (Valle de Elorz)/Noain (Elortzibar)",province_id: 31}, {_id:31089,name: "Enériz",province_id: 31}, {_id:31090,name: "Eratsun",province_id: 31}, {_id:31091,name: "Ergoiena",province_id: 31}, {_id:31092,name: "Erro",province_id: 31}, {_id:31093,name: "Ezcároz/Ezkaroze",province_id: 31}, {_id:31094,name: "Eslava",province_id: 31}, {_id:31095,name: "<NAME>",province_id: 31}, {_id:31096,name: "Espronceda",province_id: 31}, {_id:31097,name: "Estella/Lizarra",province_id: 31}, {_id:31098,name: "Esteribar",province_id: 31}, {_id:31099,name: "Etayo",province_id: 31}, {_id:31100,name: "Eulate",province_id: 31}, {_id:31101,name: "Ezcabarte",province_id: 31}, {_id:31102,name: "Ezkurra",province_id: 31}, {_id:31103,name: "Ezprogui",province_id: 31}, {_id:31104,name: "Falces",province_id: 31}, {_id:31105,name: "Fitero",province_id: 31}, {_id:45112,name: "Navalmorales (Los)",province_id: 45}, {_id:45113,name: "Navalucillos (Los)",province_id: 45}, {_id:45114,name: "Navamorcuende",province_id: 45}, {_id:45115,name: "Noblejas",province_id: 45}, {_id:45116,name: "Noez",province_id: 45}, {_id:45117,name: "Nombela",province_id: 45}, {_id:45118,name: "Novés",province_id: 45}, {_id:45119,name: "<NAME>",province_id: 45}, {_id:45120,name: "<NAME>",province_id: 45}, {_id:45121,name: "Ocaña",province_id: 45}, {_id:45122,name: "<NAME>",province_id: 45}, {_id:45123,name: "Ontígola",province_id: 45}, {_id:45124,name: "Orgaz",province_id: 45}, {_id:45125,name: "Oropesa",province_id: 45}, {_id:45126,name: "Otero",province_id: 45}, {_id:45127,name: "Palomeque",province_id: 45}, {_id:45128,name: "Pantoja",province_id: 45}, {_id:45129,name: "<NAME>",province_id: 45}, {_id:45130,name: "Parrillas",province_id: 45}, {_id:45131,name: "Pelahustán",province_id: 45}, {_id:45132,name: "Pepino",province_id: 45}, {_id:45133,name: "Polán",province_id: 45}, {_id:45134,name: "<NAME>",province_id: 45}, {_id:45135,name: "<NAME> (La)",province_id: 45}, {_id:45136,name: "<NAME> (La)",province_id: 45}, {_id:45137,name: "Pueblanueva (La)",province_id: 45}, {_id:45138,name: "<NAME> (El)",province_id: 45}, {_id:45139,name: "<NAME> San Vicente",province_id: 45}, {_id:45140,name: "Pulgar",province_id: 45}, {_id:45141,name: "Quero",province_id: 45}, {_id:45142,name: "<NAME>",province_id: 45}, {_id:45143,name: "Quismondo",province_id: 45}, {_id:45144,name: "Real de San Vicente (El)",province_id: 45}, {_id:45145,name: "Recas",province_id: 45}, {_id:45146,name: "<NAME>",province_id: 45}, {_id:45147,name: "Rielves",province_id: 45}, {_id:45148,name: "<NAME>",province_id: 45}, {_id:45149,name: "Romeral (El)",province_id: 45}, {_id:45150,name: "<NAME>",province_id: 45}, {_id:45151,name: "<NAME>",province_id: 45}, {_id:45152,name: "<NAME>",province_id: 45}, {_id:45153,name: "<NAME>",province_id: 45}, {_id:47232,name: "Zarza (La)",province_id: 47}, {_id:48001,name: "Abadiño",province_id: 48}, {_id:48002,name: "<NAME> Ciérvana-<NAME>",province_id: 48}, {_id:48003,name: "Amorebieta-Etxano",province_id: 48}, {_id:48004,name: "Amoroto",province_id: 48}, {_id:48005,name: "Arakaldo",province_id: 48}, {_id:48006,name: "Arantzazu",province_id: 48}, {_id:48007,name: "Munitibar-<NAME>",province_id: 48}, {_id:48008,name: "Artzentales",province_id: 48}, {_id:48009,name: "Arrankudiaga",province_id: 48}, {_id:48010,name: "Arrieta",province_id: 48}, {_id:48011,name: "Arrigorriaga",province_id: 48}, {_id:48012,name: "Bakio",province_id: 48}, {_id:48013,name: "Barakaldo",province_id: 48}, {_id:48014,name: "Barrika",province_id: 48}, {_id:48015,name: "Basauri",province_id: 48}, {_id:48016,name: "Berango",province_id: 48}, {_id:48017,name: "Bermeo",province_id: 48}, {_id:48018,name: "Berriatua",province_id: 48}, {_id:48019,name: "Berriz",province_id: 48}, {_id:48020,name: "Bilbao",province_id: 48}, {_id:48021,name: "Busturia",province_id: 48}, {_id:48022,name: "<NAME>/<NAME>",province_id: 48}, {_id:48023,name: "Artea",province_id: 48}, {_id:48024,name: "Zeanuri",province_id: 48}, {_id:48025,name: "Zeberio",province_id: 48}, {_id:48026,name: "Dima",province_id: 48}, {_id:48027,name: "Durango",province_id: 48}, {_id:48028,name: "Ea",province_id: 48}, {_id:48029,name: "Etxebarri",province_id: 48}, {_id:48030,name: "Etxebarria",province_id: 48}, {_id:48031,name: "Elantxobe",province_id: 48}, {_id:48032,name: "Elorrio",province_id: 48}, {_id:48033,name: "Ereño",province_id: 48}, {_id:48034,name: "Ermua",province_id: 48}, {_id:48035,name: "Fruiz",province_id: 48}, {_id:48036,name: "Galdakao",province_id: 48}, {_id:48037,name: "Galdames",province_id: 48}, {_id:48038,name: "Gamiz-Fika",province_id: 48}, {_id:48039,name: "Garai",province_id: 48}, {_id:48040,name: "Gatika",province_id: 48}, {_id:48041,name: "<NAME>",province_id: 48}, {_id:48042,name: "Gordexola",province_id: 48}, {_id:48043,name: "Gorliz",province_id: 48}, {_id:48044,name: "Getxo",province_id: 48}, {_id:48045,name: "Güeñes",province_id: 48}, {_id:48046,name: "Gernika-Lumo",province_id: 48}, {_id:48047,name: "Gizaburuaga",province_id: 48}, {_id:48048,name: "Ibarrangelu",province_id: 48}, {_id:48049,name: "Ispaster",province_id: 48}, {_id:48050,name: "Izurtza",province_id: 48}, {_id:48051,name: "Lanestosa",province_id: 48}, {_id:48052,name: "Larrabetzu",province_id: 48}, {_id:48053,name: "Laukiz",province_id: 48}, {_id:48054,name: "Leioa",province_id: 48}, {_id:48055,name: "Lemoa",province_id: 48}, {_id:48056,name: "Lemoiz",province_id: 48}, {_id:48057,name: "Lekeitio",province_id: 48}, {_id:48058,name: "Mallabia",province_id: 48}, {_id:48059,name: "Mañaria",province_id: 48}, {_id:48060,name: "Markina-Xemein",province_id: 48}, {_id:48061,name: "Maruri-Jatabe",province_id: 48}, {_id:48062,name: "Mendata",province_id: 48}, {_id:48063,name: "Mendexa",province_id: 48}, {_id:48064,name: "Meñaka",province_id: 48}, {_id:48065,name: "Ugao-Miraballes",province_id: 48}, {_id:48066,name: "Morga",province_id: 48}, {_id:48067,name: "Muxika",province_id: 48}, {_id:48068,name: "Mundaka",province_id: 48}, {_id:48069,name: "Mungia",province_id: 48}, {_id:48070,name: "Aulesti",province_id: 48}, {_id:48071,name: "Muskiz",province_id: 48}, {_id:48072,name: "Otxandio",province_id: 48}, {_id:48073,name: "Ondarroa",province_id: 48}, {_id:48074,name: "Urduña-Orduña",province_id: 48}, {_id:48075,name: "Orozko",province_id: 48}, {_id:48076,name: "Sukarrieta",province_id: 48}, {_id:48077,name: "Plentzia",province_id: 48}, {_id:48078,name: "Portugalete",province_id: 48}, {_id:48079,name: "Errigoiti",province_id: 48}, {_id:48080,name: "<NAME>",province_id: 48}, {_id:48081,name: "Lezama",province_id: 48}, {_id:48082,name: "Santurtzi",province_id: 48}, {_id:48083,name: "Ortuella",province_id: 48}, {_id:48084,name: "Sestao",province_id: 48}, {_id:48085,name: "Sopelana",province_id: 48}, {_id:48086,name: "Sopuerta",province_id: 48}, {_id:48087,name: "Trucios-Turtzioz",province_id: 48}, {_id:48088,name: "Ubide",province_id: 48}, {_id:48089,name: "Urduliz",province_id: 48}, {_id:48090,name: "Balmaseda",province_id: 48}, {_id:48091,name: "Atxondo",province_id: 48}, {_id:48092,name: "Bedia",province_id: 48}, {_id:48093,name: "Areatza",province_id: 48}, {_id:48094,name: "Igorre",province_id: 48}, {_id:48095,name: "Zaldibar",province_id: 48}, {_id:48096,name: "Zalla",province_id: 48}, {_id:48097,name: "Zaratamo",province_id: 48}, {_id:48901,name: "Derio",province_id: 48}, {_id:48902,name: "Erandio",province_id: 48}, {_id:48903,name: "Loiu",province_id: 48}, {_id:48904,name: "Sondika",province_id: 48}, {_id:48905,name: "Zamudio",province_id: 48}, {_id:48906,name: "Forua",province_id: 48}, {_id:48907,name: "Kortezubi",province_id: 48}, {_id:48908,name: "Murueta",province_id: 48}, {_id:48909,name: "Nabarniz",province_id: 48}, {_id:48910,name: "Iurreta",province_id: 48}, {_id:48911,name: "Ajangiz",province_id: 48}, {_id:48912,name: "Alonsotegi",province_id: 48}, {_id:48913,name: "Zierbena",province_id: 48}, {_id:48914,name: "Arratzu",province_id: 48}, {_id:48915,name: "Ziortza-Bolibar",province_id: 48}, {_id:49002,name: "Abezames",province_id: 49}, {_id:49003,name: "Alcañices",province_id: 49}, {_id:49004,name: "<NAME>",province_id: 49}, {_id:49005,name: "<NAME>",province_id: 49}, {_id:49006,name: "Algodre",province_id: 49}, {_id:49007,name: "<NAME>",province_id: 49}, {_id:49008,name: "<NAME>",province_id: 49}, {_id:49009,name: "Andavías",province_id: 49}, {_id:49010,name: "Arcenillas",province_id: 49}, {_id:49011,name: "<NAME>",province_id: 49}, {_id:49012,name: "Argañín",province_id: 49}, {_id:49013,name: "Argujillo",province_id: 49}, {_id:49014,name: "Arquillinos",province_id: 49}, {_id:49015,name: "Arrabalde",province_id: 49}, {_id:49016,name: "Aspariegos",province_id: 49}, {_id:49017,name: "Asturianos",province_id: 49}, {_id:49018,name: "<NAME>",province_id: 49}, {_id:49019,name: "<NAME>",province_id: 49}, {_id:49020,name: "<NAME>",province_id: 49}, {_id:49021,name: "Benavente",province_id: 49}, {_id:49022,name: "Benegiles",province_id: 49}, {_id:49023,name: "<NAME>",province_id: 49}, {_id:49024,name: "<NAME>)",province_id: 49}, {_id:49025,name: "Bretó",province_id: 49}, {_id:49026,name: "Bretocino",province_id: 49}, {_id:49027,name: "<NAME>",province_id: 49}, {_id:49028,name: "<NAME>",province_id: 49}, {_id:49029,name: "<NAME>",province_id: 49}, {_id:49030,name: "<NAME>",province_id: 49}, {_id:49031,name: "<NAME>",province_id: 49}, {_id:49032,name: "<NAME>",province_id: 49}, {_id:49033,name: "<NAME>",province_id: 49}, {_id:49034,name: "Cañizal",province_id: 49}, {_id:49035,name: "Cañizo",province_id: 49}, {_id:49036,name: "<NAME>",province_id: 49}, {_id:49037,name: "Carbellino",province_id: 49}, {_id:49038,name: "<NAME>",province_id: 49}, {_id:49039,name: "<NAME>",province_id: 49}, {_id:49040,name: "<NAME>",province_id: 49}, {_id:49041,name: "Castrogonzalo",province_id: 49}, {_id:49042,name: "Castronuevo",province_id: 49}, {_id:49043,name: "<NAME>",province_id: 49}, {_id:49044,name: "Cazurra",province_id: 49}, {_id:49046,name: "<NAME>",province_id: 49}, {_id:49047,name: "<NAME>",province_id: 49}, {_id:49048,name: "Cernadilla",province_id: 49}, {_id:49050,name: "Cobreros",province_id: 49}, {_id:49052,name: "Coomonte",province_id: 49}, {_id:49053,name: "Coreses",province_id: 49}, {_id:49054,name: "Corrales",province_id: 49}, {_id:49055,name: "<NAME>",province_id: 49}, {_id:49056,name: "Cubillos",province_id: 49}, {_id:49057,name: "<NAME>",province_id: 49}, {_id:49058,name: "<NAME> (El)",province_id: 49}, {_id:49059,name: "Cuelgamures",province_id: 49}, {_id:49061,name: "Entrala",province_id: 49}, {_id:49062,name: "Espadañedo",province_id: 49}, {_id:49063,name: "<NAME>",province_id: 49}, {_id:49064,name: "Fariza",province_id: 49}, {_id:49065,name: "Fermoselle",province_id: 49}, {_id:49066,name: "<NAME>",province_id: 49}, {_id:49067,name: "<NAME>",province_id: 49}, {_id:49068,name: "Ferreruela",province_id: 49}, {_id:49069,name: "<NAME>",province_id: 49}, {_id:49071,name: "Fonfría",province_id: 49}, {_id:49075,name: "<NAME>",province_id: 49}, {_id:49076,name: "<NAME>",province_id: 49}, {_id:49077,name: "<NAME>",province_id: 49}, {_id:49078,name: "<NAME>",province_id: 49}, {_id:49079,name: "<NAME>",province_id: 49}, {_id:49080,name: "Fuentelapeña",province_id: 49}, {_id:49081,name: "Fuentesaúco",province_id: 49}, {_id:49082,name: "<NAME>",province_id: 49}, {_id:49083,name: "Fuentesecas",province_id: 49}, {_id:49084,name: "Fuentespreadas",province_id: 49}, {_id:49085,name: "Galende",province_id: 49}, {_id:49086,name: "<NAME>",province_id: 49}, {_id:49087,name: "<NAME>",province_id: 49}, {_id:49088,name: "Gamones",province_id: 49}, {_id:49090,name: "Gema",province_id: 49}, {_id:49091,name: "<NAME>",province_id: 49}, {_id:49092,name: "Granucillo",province_id: 49}, {_id:49093,name: "Guarrate",province_id: 49}, {_id:49094,name: "Hermisende",province_id: 49}, {_id:49095,name: "Hiniesta (La)",province_id: 49}, {_id:49096,name: "Jambrina",province_id: 49}, {_id:49097,name: "Justel",province_id: 49}, {_id:49098,name: "Losacino",province_id: 49}, {_id:49099,name: "Losacio",province_id: 49}, {_id:49100,name: "Lubián",province_id: 49}, {_id:49101,name: "Luelmo",province_id: 49}, {_id:49102,name: "Maderal (El)",province_id: 49}, {_id:49103,name: "Madridanos",province_id: 49}, {_id:49104,name: "Mahide",province_id: 49}, {_id:49105,name: "<NAME>",province_id: 49}, {_id:49107,name: "Malva",province_id: 49}, {_id:49108,name: "<NAME>",province_id: 49}, {_id:49109,name: "<NAME>",province_id: 49}, {_id:49110,name: "<NAME>",province_id: 49}, {_id:49111,name: "<NAME>",province_id: 49}, {_id:49112,name: "<NAME>",province_id: 49}, {_id:49113,name: "<NAME>",province_id: 49}, {_id:49114,name: "<NAME>",province_id: 49}, {_id:49115,name: "Mayalde",province_id: 49}, {_id:49116,name: "<NAME>",province_id: 49}, {_id:49117,name: "<NAME>",province_id: 49}, {_id:49118,name: "<NAME>",province_id: 49}, {_id:49119,name: "Molacillos",province_id: 49}, {_id:49120,name: "<NAME>",province_id: 49}, {_id:49121,name: "Mombuey",province_id: 49}, {_id:49122,name: "Monfarracinos",province_id: 49}, {_id:49123,name: "Montamarta",province_id: 49}, {_id:49124,name: "<NAME>",province_id: 49}, {_id:49125,name: "<NAME>",province_id: 49}, {_id:49126,name: "<NAME>",province_id: 49}, {_id:49127,name: "<NAME>",province_id: 49}, {_id:49128,name: "<NAME>",province_id: 49}, {_id:49129,name: "<NAME>",province_id: 49}, {_id:49130,name: "<NAME>",province_id: 49}, {_id:49131,name: "Moralina",province_id: 49}, {_id:49132,name: "<NAME>",province_id: 49}, {_id:24008,name: "Astorga",province_id: 24}, {_id:24009,name: "Balboa",province_id: 24}, {_id:24010,name: "<NAME>)",province_id: 24}, {_id:24011,name: "Barjas",province_id: 24}, {_id:24012,name: "<NAME> (Los)",province_id: 24}, {_id:24014,name: "Bembibre",province_id: 24}, {_id:24015,name: "Benavides",province_id: 24}, {_id:24016,name: "Benuza",province_id: 24}, {_id:24017,name: "<NAME>",province_id: 24}, {_id:24018,name: "<NAME>",province_id: 24}, {_id:24019,name: "<NAME>",province_id: 24}, {_id:24020,name: "<NAME>",province_id: 24}, {_id:24021,name: "Boñar",province_id: 24}, {_id:24022,name: "Borrenes",province_id: 24}, {_id:24023,name: "Brazuelo",province_id: 24}, {_id:24024,name: "<NAME>)",province_id: 24}, {_id:24025,name: "Burón",province_id: 24}, {_id:24026,name: "<NAME>",province_id: 24}, {_id:24027,name: "<NAME>",province_id: 24}, {_id:24028,name: "<NAME>",province_id: 24}, {_id:24029,name: "Cabrillanes",province_id: 24}, {_id:24030,name: "Cacabelos",province_id: 24}, {_id:24031,name: "<NAME>",province_id: 24}, {_id:24032,name: "Campazas",province_id: 24}, {_id:24033,name: "<NAME>",province_id: 24}, {_id:24034,name: "Camponaraya",province_id: 24}, {_id:24036,name: "Candín",province_id: 24}, {_id:24037,name: "Cármenes",province_id: 24}, {_id:24038,name: "Carracedelo",province_id: 24}, {_id:24039,name: "Carrizo",province_id: 24}, {_id:24040,name: "Carrocera",province_id: 24}, {_id:24041,name: "Carucedo",province_id: 24}, {_id:24042,name: "Castilfalé",province_id: 24}, {_id:24043,name: "<NAME>",province_id: 24}, {_id:24044,name: "<NAME>",province_id: 24}, {_id:24046,name: "Castrocalbón",province_id: 24}, {_id:24047,name: "Castrocontrigo",province_id: 24}, {_id:24049,name: "Castropodame",province_id: 24}, {_id:24050,name: "<NAME>",province_id: 24}, {_id:24051,name: "Cea",province_id: 24}, {_id:24052,name: "Cebanico",province_id: 24}, {_id:24053,name: "<NAME>",province_id: 24}, {_id:24054,name: "<NAME>",province_id: 24}, {_id:24055,name: "<NAME>",province_id: 24}, {_id:24056,name: "Cistierna",province_id: 24}, {_id:24057,name: "Congosto",province_id: 24}, {_id:24058,name: "<NAME>",province_id: 24}, {_id:24059,name: "Corullón",province_id: 24}, {_id:24060,name: "Crémenes",province_id: 24}, {_id:24061,name: "Cuadros",province_id: 24}, {_id:24062,name: "<NAME>",province_id: 24}, {_id:37004,name: "<NAME>",province_id: 37}, {_id:26170,name: "<NAME> (El)",province_id: 26}, {_id:26171,name: "<NAME>",province_id: 26}, {_id:26172,name: "Villarejo",province_id: 26}, {_id:26173,name: "Villarroya",province_id: 26}, {_id:26174,name: "Villarta-Quintana",province_id: 26}, {_id:26175,name: "Villavelayo",province_id: 26}, {_id:26176,name: "<NAME>",province_id: 26}, {_id:26177,name: "<NAME>",province_id: 26}, {_id:26178,name: "<NAME>",province_id: 26}, {_id:26179,name: "<NAME>",province_id: 26}, {_id:26180,name: "Zarratón",province_id: 26}, {_id:26181,name: "Zarzosa",province_id: 26}, {_id:26183,name: "Zorraquín",province_id: 26}, {_id:27001,name: "Abadín",province_id: 27}, {_id:27002,name: "Alfoz",province_id: 27}, {_id:27003,name: "<NAME>",province_id: 27}, {_id:27004,name: "Baleira",province_id: 27}, {_id:27005,name: "Barreiros",province_id: 27}, {_id:27006,name: "Becerreá",province_id: 27}, {_id:27007,name: "Begonte",province_id: 27}, {_id:27008,name: "Bóveda",province_id: 27}, {_id:27009,name: "Carballedo",province_id: 27}, {_id:27010,name: "<NAME>",province_id: 27}, {_id:27011,name: "Castroverde",province_id: 27}, {_id:27012,name: "Cervantes",province_id: 27}, {_id:27013,name: "Cervo",province_id: 27}, {_id:27014,name: "<NAME>)",province_id: 27}, {_id:27015,name: "Cospeito",province_id: 27}, {_id:27016,name: "Chantada",province_id: 27}, {_id:27017,name: "<NAME>",province_id: 27}, {_id:27018,name: "Fonsagrada (A)",province_id: 27}, {_id:27019,name: "Foz",province_id: 27}, {_id:27020,name: "Friol",province_id: 27}, {_id:27021,name: "Xermade",province_id: 27}, {_id:27022,name: "Guitiriz",province_id: 27}, {_id:27023,name: "Guntín",province_id: 27}, {_id:27024,name: "Incio (O)",province_id: 27}, {_id:27025,name: "Xove",province_id: 27}, {_id:27026,name: "Láncara",province_id: 27}, {_id:27027,name: "Lourenzá",province_id: 27}, {_id:27028,name: "Lugo",province_id: 27}, {_id:27029,name: "Meira",province_id: 27}, {_id:27030,name: "Mondoñedo",province_id: 27}, {_id:27031,name: "<NAME>",province_id: 27}, {_id:27032,name: "Monterroso",province_id: 27}, {_id:27033,name: "Muras",province_id: 27}, {_id:27034,name: "<NAME>",province_id: 27}, {_id:27035,name: "<NAME>",province_id: 27}, {_id:27037,name: "Nogais (As)",province_id: 27}, {_id:27038,name: "Ourol",province_id: 27}, {_id:27039,name: "<NAME>",province_id: 27}, {_id:27040,name: "<NAME>",province_id: 27}, {_id:27041,name: "Pantón",province_id: 27}, {_id:27042,name: "Paradela",province_id: 27}, {_id:27043,name: "Páramo (O)",province_id: 27}, {_id:27044,name: "Pastoriza (A)",province_id: 27}, {_id:27045,name: "<NAME>",province_id: 27}, {_id:27046,name: "Pol",province_id: 27}, {_id:27047,name: "<NAME> (A)",province_id: 27}, {_id:27048,name: "Pontenova (A)",province_id: 27}, {_id:27049,name: "Portomarín",province_id: 27}, {_id:27050,name: "Quiroga",province_id: 27}, {_id:27051,name: "Ribadeo",province_id: 27}, {_id:27052,name: "<NAME>",province_id: 27}, {_id:27053,name: "<NAME>",province_id: 27}, {_id:27054,name: "Riotorto",province_id: 27}, {_id:27055,name: "Samos",province_id: 27}, {_id:27056,name: "Rábade",province_id: 27}, {_id:27057,name: "Sarria",province_id: 27}, {_id:27058,name: "Saviñao (O)",province_id: 27}, {_id:27059,name: "Sober",province_id: 27}, {_id:27060,name: "Taboada",province_id: 27}, {_id:27061,name: "Trabada",province_id: 27}, {_id:27062,name: "Triacastela",province_id: 27}, {_id:27063,name: "Valadouro (O)",province_id: 27}, {_id:27064,name: "Vicedo (O)",province_id: 27}, {_id:27065,name: "Vilalba",province_id: 27}, {_id:27066,name: "Viveiro",province_id: 27}, {_id:27901,name: "Baralla",province_id: 27}, {_id:27902,name: "Burela",province_id: 27}, {_id:28001,name: "Acebeda (La)",province_id: 28}, {_id:28002,name: "Ajalvir",province_id: 28}, {_id:28003,name: "<NAME>",province_id: 28}, {_id:28004,name: "Álamo (El)",province_id: 28}, {_id:28005,name: "<NAME>",province_id: 28}, {_id:28006,name: "Alcobendas",province_id: 28}, {_id:28007,name: "Alcorcón",province_id: 28}, {_id:28008,name: "<NAME>",province_id: 28}, {_id:28009,name: "Algete",province_id: 28}, {_id:28010,name: "Alpedrete",province_id: 28}, {_id:28011,name: "Ambite",province_id: 28}, {_id:28012,name: "Anchuelo",province_id: 28}, {_id:28013,name: "Aranjuez",province_id: 28}, {_id:28014,name: "<NAME>",province_id: 28}, {_id:28015,name: "Arroyomolinos",province_id: 28}, {_id:28016,name: "Atazar (El)",province_id: 28}, {_id:28017,name: "Batres",province_id: 28}, {_id:28018,name: "<NAME>",province_id: 28}, {_id:28019,name: "<NAME>",province_id: 28}, {_id:28020,name: "<NAME>",province_id: 28}, {_id:28021,name: "Berrueco (El)",province_id: 28}, {_id:28022,name: "<NAME>",province_id: 28}, {_id:28023,name: "Boalo (El)",province_id: 28}, {_id:28024,name: "Braojos",province_id: 28}, {_id:28025,name: "<NAME>",province_id: 28}, {_id:28026,name: "Brunete",province_id: 28}, {_id:28027,name: "<NAME>",province_id: 28}, {_id:28028,name: "Bustarviejo",province_id: 28}, {_id:28029,name: "<NAME>",province_id: 28}, {_id:28030,name: "<NAME>)",province_id: 28}, {_id:28031,name: "<NAME>",province_id: 28}, {_id:28032,name: "<NAME>",province_id: 28}, {_id:28033,name: "<NAME>",province_id: 28}, {_id:28034,name: "Canencia",province_id: 28}, {_id:28035,name: "Carabaña",province_id: 28}, {_id:28036,name: "Casarrubuelos",province_id: 28}, {_id:28037,name: "Cenicientos",province_id: 28}, {_id:28038,name: "Cercedilla",province_id: 28}, {_id:28039,name: "<NAME>",province_id: 28}, {_id:28040,name: "Ciempozuelos",province_id: 28}, {_id:28041,name: "Cobeña",province_id: 28}, {_id:28042,name: "<NAME>",province_id: 28}, {_id:28043,name: "<NAME>",province_id: 28}, {_id:28044,name: "Colmenarejo",province_id: 28}, {_id:28045,name: "<NAME>",province_id: 28}, {_id:28046,name: "<NAME>",province_id: 28}, {_id:28047,name: "<NAME>",province_id: 28}, {_id:28048,name: "Corpa",province_id: 28}, {_id:28049,name: "Coslada",province_id: 28}, {_id:28050,name: "<NAME>",province_id: 28}, {_id:28051,name: "Chapinería",province_id: 28}, {_id:28052,name: "Chinchón",province_id: 28}, {_id:28053,name: "<NAME>",province_id: 28}, {_id:28054,name: "<NAME>)",province_id: 28}, {_id:28055,name: "Estremera",province_id: 28}, {_id:28056,name: "<NAME>",province_id: 28}, {_id:28057,name: "<NAME>",province_id: 28}, {_id:28058,name: "Fuenlabrada",province_id: 28}, {_id:28059,name: "<NAME>",province_id: 28}, {_id:28060,name: "<NAME>",province_id: 28}, {_id:28061,name: "Galapagar",province_id: 28}, {_id:28062,name: "<NAME>",province_id: 28}, {_id:28063,name: "Gargantilla del Lozoya y Pinilla de Buitrago",province_id: 28}, {_id:28064,name: "Gascones",province_id: 28}, {_id:28065,name: "Getafe",province_id: 28}, {_id:28066,name: "Griñón",province_id: 28}, {_id:28067,name: "<NAME>",province_id: 28}, {_id:28068,name: "Guadarrama",province_id: 28}, {_id:28069,name: "<NAME>)",province_id: 28}, {_id:28070,name: "<NAME>",province_id: 28}, {_id:28071,name: "<NAME>",province_id: 28}, {_id:28072,name: "<NAME>",province_id: 28}, {_id:28073,name: "<NAME>",province_id: 28}, {_id:28074,name: "Leganés",province_id: 28}, {_id:28075,name: "Loeches",province_id: 28}, {_id:28076,name: "Lozoya",province_id: 28}, {_id:28078,name: "Madarcos",province_id: 28}, {_id:28079,name: "Madrid",province_id: 28}, {_id:28080,name: "Majadahonda",province_id: 28}, {_id:28082,name: "<NAME>",province_id: 28}, {_id:28083,name: "Meco",province_id: 28}, {_id:28084,name: "<NAME>",province_id: 28}, {_id:28085,name: "<NAME>",province_id: 28}, {_id:28086,name: "Molar (El)",province_id: 28}, {_id:28087,name: "Molinos (Los)",province_id: 28}, {_id:28088,name: "<NAME>",province_id: 28}, {_id:28089,name: "<NAME>",province_id: 28}, {_id:28090,name: "Moralzarzal",province_id: 28}, {_id:28091,name: "<NAME>",province_id: 28}, {_id:28092,name: "Móstoles",province_id: 28}, {_id:28093,name: "Navacerrada",province_id: 28}, {_id:28094,name: "Navalafuente",province_id: 28}, {_id:28095,name: "Navalagamella",province_id: 28}, {_id:28096,name: "Navalcarnero",province_id: 28}, {_id:28097,name: "<NAME>",province_id: 28}, {_id:28099,name: "<NAME>",province_id: 28}, {_id:28100,name: "<NAME>",province_id: 28}, {_id:28101,name: "<NAME>",province_id: 28}, {_id:28102,name: "<NAME>",province_id: 28}, {_id:28104,name: "<NAME>",province_id: 28}, {_id:28106,name: "Parla",province_id: 28}, {_id:28107,name: "Patones",province_id: 28}, {_id:28108,name: "Pedrezuela",province_id: 28}, {_id:28109,name: "<NAME>",province_id: 28}, {_id:28110,name: "<NAME>",province_id: 28}, {_id:28111,name: "<NAME>",province_id: 28}, {_id:28112,name: "<NAME>",province_id: 28}, {_id:28113,name: "Pinto",province_id: 28}, {_id:28114,name: "Piñuécar-Gandullas",province_id: 28}, {_id:28115,name: "<NAME>",province_id: 28}, {_id:28116,name: "<NAME>",province_id: 28}, {_id:28117,name: "<NAME>",province_id: 28}, {_id:28118,name: "<NAME>",province_id: 28}, {_id:28119,name: "Quijorna",province_id: 28}, {_id:28120,name: "Rascafría",province_id: 28}, {_id:28121,name: "Redueña",province_id: 28}, {_id:28122,name: "Ribatejada",province_id: 28}, {_id:28123,name: "Rivas-Vaciamadrid",province_id: 28}, {_id:28124,name: "<NAME>",province_id: 28}, {_id:28125,name: "<NAME>",province_id: 28}, {_id:28126,name: "Robregordo",province_id: 28}, {_id:28127,name: "<NAME>as)",province_id: 28}, {_id:28128,name: "<NAME>",province_id: 28}, {_id:28129,name: "<NAME>",province_id: 28}, {_id:28130,name: "<NAME>",province_id: 28}, {_id:28131,name: "<NAME> El Escorial",province_id: 28}, {_id:28132,name: "<NAME>",province_id: 28}, {_id:28133,name: "<NAME>",province_id: 28}, {_id:28134,name: "<NAME>",province_id: 28}, {_id:28135,name: "<NAME>",province_id: 28}, {_id:28136,name: "Santorcaz",province_id: 28}, {_id:28137,name: "<NAME> la Humosa (Los)",province_id: 28}, {_id:28138,name: "<NAME> (La)",province_id: 28}, {_id:35032,name: "Valleseco",province_id: 35}, {_id:35033,name: "<NAME>",province_id: 35}, {_id:35034,name: "Yaiza",province_id: 35}, {_id:36001,name: "Arbo",province_id: 36}, {_id:36002,name: "Barro",province_id: 36}, {_id:36003,name: "Baiona",province_id: 36}, {_id:36004,name: "Bueu",province_id: 36}, {_id:36005,name: "<NAME>",province_id: 36}, {_id:36006,name: "Cambados",province_id: 36}, {_id:36007,name: "<NAME>",province_id: 36}, {_id:36008,name: "Cangas",province_id: 36}, {_id:36009,name: "Cañiza (A)",province_id: 36}, {_id:36010,name: "Catoira",province_id: 36}, {_id:36011,name: "Cerdedo",province_id: 36}, {_id:36012,name: "Cotobade",province_id: 36}, {_id:36013,name: "Covelo",province_id: 36}, {_id:36014,name: "Crecente",province_id: 36}, {_id:36015,name: "Cuntis",province_id: 36}, {_id:36016,name: "Dozón",province_id: 36}, {_id:36017,name: "Estrada (A)",province_id: 36}, {_id:36018,name: "Forcarei",province_id: 36}, {_id:36019,name: "<NAME>",province_id: 36}, {_id:36020,name: "Agolada",province_id: 36}, {_id:36021,name: "Gondomar",province_id: 36}, {_id:36022,name: "Grove (O)",province_id: 36}, {_id:36023,name: "Guarda (A)",province_id: 36}, {_id:36024,name: "Lalín",province_id: 36}, {_id:36025,name: "Lama (A)",province_id: 36}, {_id:36026,name: "Marín",province_id: 36}, {_id:36027,name: "Meaño",province_id: 36}, {_id:36028,name: "Meis",province_id: 36}, {_id:36029,name: "Moaña",province_id: 36}, {_id:36030,name: "Mondariz",province_id: 36}, {_id:36031,name: "Mondariz-Balneario",province_id: 36}, {_id:36032,name: "Moraña",province_id: 36}, {_id:36033,name: "Mos",province_id: 36}, {_id:36034,name: "Neves (As)",province_id: 36}, {_id:36035,name: "Nigrán",province_id: 36}, {_id:36036,name: "Oia",province_id: 36}, {_id:36037,name: "<NAME>",province_id: 36}, {_id:36038,name: "Pontevedra",province_id: 36}, {_id:36039,name: "Porriño (O)",province_id: 36}, {_id:36040,name: "Portas",province_id: 36}, {_id:36041,name: "Poio",province_id: 36}, {_id:36042,name: "Ponteareas",province_id: 36}, {_id:36043,name: "<NAME>",province_id: 36}, {_id:36044,name: "Pontecesures",province_id: 36}, {_id:36045,name: "Redondela",province_id: 36}, {_id:36046,name: "Ribadumia",province_id: 36}, {_id:36047,name: "Rodeiro",province_id: 36}, {_id:36048,name: "Rosal (O)",province_id: 36}, {_id:36049,name: "<NAME>",province_id: 36}, {_id:36050,name: "<NAME>",province_id: 36}, {_id:36051,name: "Sanxenxo",province_id: 36}, {_id:36052,name: "Silleda",province_id: 36}, {_id:36053,name: "Soutomaior",province_id: 36}, {_id:36054,name: "Tomiño",province_id: 36}, {_id:36055,name: "Tui",province_id: 36}, {_id:36056,name: "Valga",province_id: 36}, {_id:36057,name: "Vigo",province_id: 36}, {_id:36058,name: "Vilaboa",province_id: 36}, {_id:36059,name: "<NAME>",province_id: 36}, {_id:36060,name: "<NAME>",province_id: 36}, {_id:36061,name: "<NAME>",province_id: 36}, {_id:36901,name: "<NAME> (A)",province_id: 36}, {_id:37001,name: "Abusejo",province_id: 37}, {_id:37002,name: "Agallas",province_id: 37}, {_id:37003,name: "<NAME>",province_id: 37}, {_id:34056,name: "<NAME>",province_id: 34}, {_id:34057,name: "<NAME>",province_id: 34}, {_id:34058,name: "<NAME>",province_id: 34}, {_id:34059,name: "Cisneros",province_id: 34}, {_id:34060,name: "<NAME>",province_id: 34}, {_id:34061,name: "<NAME>",province_id: 34}, {_id:34062,name: "<NAME>",province_id: 34}, {_id:34063,name: "<NAME>",province_id: 34}, {_id:34066,name: "<NAME>",province_id: 34}, {_id:34067,name: "<NAME>",province_id: 34}, {_id:34068,name: "<NAME>",province_id: 34}, {_id:34069,name: "Dueñas",province_id: 34}, {_id:34070,name: "<NAME>",province_id: 34}, {_id:34071,name: "<NAME>",province_id: 34}, {_id:34072,name: "Frechilla",province_id: 34}, {_id:34073,name: "<NAME>",province_id: 34}, {_id:34074,name: "Frómista",province_id: 34}, {_id:34076,name: "<NAME>",province_id: 34}, {_id:34077,name: "<NAME>",province_id: 34}, {_id:34079,name: "Grijota",province_id: 34}, {_id:34080,name: "Guardo",province_id: 34}, {_id:34081,name: "<NAME>",province_id: 34}, {_id:34082,name: "<NAME>",province_id: 34}, {_id:34083,name: "<NAME>",province_id: 34}, {_id:34084,name: "<NAME>",province_id: 34}, {_id:34086,name: "<NAME>",province_id: 34}, {_id:34087,name: "<NAME>",province_id: 34}, {_id:34088,name: "Husillos",province_id: 34}, {_id:34089,name: "<NAME>",province_id: 34}, {_id:34091,name: "Lagartos",province_id: 34}, {_id:34092,name: "Lantadilla",province_id: 34}, {_id:34093,name: "<NAME>)",province_id: 34}, {_id:34094,name: "Ledigos",province_id: 34}, {_id:34096,name: "Lomas",province_id: 34}, {_id:34098,name: "<NAME>",province_id: 34}, {_id:34099,name: "Manquillos",province_id: 34}, {_id:34100,name: "Mantinos",province_id: 34}, {_id:34101,name: "<NAME>",province_id: 34}, {_id:34102,name: "Mazariegos",province_id: 34}, {_id:34103,name: "<NAME>",province_id: 34}, {_id:34104,name: "<NAME>",province_id: 34}, {_id:34106,name: "<NAME>",province_id: 34}, {_id:34107,name: "<NAME>",province_id: 34}, {_id:34108,name: "<NAME>",province_id: 34}, {_id:34109,name: "Moratinos",province_id: 34}, {_id:34110,name: "Mudá",province_id: 34}, {_id:34112,name: "<NAME>",province_id: 34}, {_id:34113,name: "<NAME>",province_id: 34}, {_id:34114,name: "<NAME>",province_id: 34}, {_id:34116,name: "Osornillo",province_id: 34}, {_id:34120,name: "Palencia",province_id: 34}, {_id:34121,name: "Palenzuela",province_id: 34}, {_id:34122,name: "<NAME>",province_id: 34}, {_id:34123,name: "<NAME>",province_id: 34}, {_id:34124,name: "<NAME>",province_id: 34}, {_id:34125,name: "<NAME>",province_id: 34}, {_id:34126,name: "<NAME>",province_id: 34}, {_id:34127,name: "Perales",province_id: 34}, {_id:34129,name: "<NAME>",province_id: 34}, {_id:34130,name: "<NAME>",province_id: 34}, {_id:34131,name: "Población de Arroyo",province_id: 34}, {_id:34132,name: "Población de Campos",province_id: 34}, {_id:34133,name: "Población de Cerrato",province_id: 34}, {_id:34134,name: "Polentinos",province_id: 34}, {_id:34135,name: "Pomar de Valdivia",province_id: 34}, {_id:34136,name: "Po<NAME> la Vega",province_id: 34}, {_id:34137,name: "Pozo de Urama",province_id: 34}, {_id:34139,name: "<NAME>",province_id: 34}, {_id:34140,name: "Puebla de Valdavia (La)",province_id: 34}, {_id:34141,name: "Quintana del Puente",province_id: 34}, {_id:34143,name: "Quintanilla de Onsoña",province_id: 34}, {_id:34146,name: "<NAME>",province_id: 34}, {_id:34147,name: "<NAME>",province_id: 34}, {_id:34149,name: "<NAME>",province_id: 34}, {_id:34151,name: "<NAME> la Peña",province_id: 34}, {_id:34152,name: "<NAME>",province_id: 34}, {_id:34154,name: "<NAME>",province_id: 34}, {_id:34155,name: "<NAME>",province_id: 34}, {_id:34156,name: "<NAME>",province_id: 34}, {_id:34157,name: "Saldaña",province_id: 34}, {_id:34158,name: "<NAME>",province_id: 34}, {_id:34159,name: "<NAME>",province_id: 34}, {_id:34160,name: "<NAME>",province_id: 34}, {_id:34161,name: "<NAME>",province_id: 34}, {_id:34163,name: "<NAME>",province_id: 34}, {_id:34165,name: "<NAME>",province_id: 34}, {_id:34167,name: "<NAME>",province_id: 34}, {_id:34168,name: "<NAME>",province_id: 34}, {_id:34169,name: "<NAME>",province_id: 34}, {_id:34170,name: "<NAME>",province_id: 34}, {_id:34171,name: "<NAME>",province_id: 34}, {_id:34174,name: "Santoyo",province_id: 34}, {_id:34175,name: "<NAME>)",province_id: 34}, {_id:34176,name: "<NAME>",province_id: 34}, {_id:34177,name: "<NAME>",province_id: 34}, {_id:34178,name: "<NAME>",province_id: 34}, {_id:34179,name: "<NAME>",province_id: 34}, {_id:34180,name: "<NAME>",province_id: 34}, {_id:34181,name: "<NAME>",province_id: 34}, {_id:34182,name: "Torquemada",province_id: 34}, {_id:34184,name: "Torremormojón",province_id: 34}, {_id:34185,name: "Triollo",province_id: 34}, {_id:34186,name: "<NAME>",province_id: 34}, {_id:34189,name: "Valdeolmillos",province_id: 34}, {_id:34190,name: "Valderrábano",province_id: 34}, {_id:34192,name: "Valde-Ucieza",province_id: 34}, {_id:34196,name: "<NAME>",province_id: 34}, {_id:34199,name: "<NAME>",province_id: 34}, {_id:34201,name: "Vertavillo",province_id: 34}, {_id:34202,name: "<NAME>",province_id: 34}, {_id:34204,name: "Villacidaler",province_id: 34}, {_id:34205,name: "Villaconancio",province_id: 34}, {_id:34206,name: "Villada",province_id: 34}, {_id:34208,name: "<NAME>",province_id: 34}, {_id:34210,name: "Villahán",province_id: 34}, {_id:34211,name: "Villaherreros",province_id: 34}, {_id:34213,name: "Villalaco",province_id: 34}, {_id:34214,name: "<NAME>",province_id: 34}, {_id:34215,name: "<NAME>",province_id: 34}, {_id:34216,name: "Villalcón",province_id: 34}, {_id:34217,name: "Villalobón",province_id: 34}, {_id:34218,name: "<NAME>",province_id: 34}, {_id:34220,name: "<NAME>",province_id: 34}, {_id:34221,name: "Villamediana",province_id: 34}, {_id:34222,name: "Villameriel",province_id: 34}, {_id:34223,name: "Villamoronta",province_id: 34}, {_id:34224,name: "<NAME>",province_id: 34}, {_id:34225,name: "<NAME>",province_id: 34}, {_id:34227,name: "<NAME>",province_id: 34}, {_id:34228,name: "<NAME>",province_id: 34}, {_id:34229,name: "Villaprovedo",province_id: 34}, {_id:34230,name: "<NAME>",province_id: 34}, {_id:34231,name: "Villarrabé",province_id: 34}, {_id:34232,name: "Villarramiel",province_id: 34}, {_id:34233,name: "Villasarracino",province_id: 34}, {_id:34234,name: "<NAME>",province_id: 34}, {_id:34236,name: "Villaturde",province_id: 34}, {_id:34237,name: "Villaumbrales",province_id: 34}, {_id:34238,name: "Villaviudas",province_id: 34}, {_id:34240,name: "<NAME>",province_id: 34}, {_id:34241,name: "Villodre",province_id: 34}, {_id:34242,name: "Villodrigo",province_id: 34}, {_id:34243,name: "Villoldo",province_id: 34}, {_id:34245,name: "<NAME>",province_id: 34}, {_id:34246,name: "Villovieco",province_id: 34}, {_id:34901,name: "<NAME>",province_id: 34}, {_id:34902,name: "<NAME>",province_id: 34}, {_id:34903,name: "<NAME>",province_id: 34}, {_id:34904,name: "Pernía (La)",province_id: 34}, {_id:35001,name: "Agaete",province_id: 35}, {_id:35002,name: "Agüimes",province_id: 35}, {_id:35003,name: "Antigua",province_id: 35}, {_id:35004,name: "Arrecife",province_id: 35}, {_id:35005,name: "Artenara",province_id: 35}, {_id:35006,name: "Arucas",province_id: 35}, {_id:35007,name: "Betancuria",province_id: 35}, {_id:35008,name: "Firgas",province_id: 35}, {_id:35009,name: "Gáldar",province_id: 35}, {_id:35010,name: "Haría",province_id: 35}, {_id:35011,name: "Ingenio",province_id: 35}, {_id:35012,name: "Mogán",province_id: 35}, {_id:35013,name: "Moya",province_id: 35}, {_id:35014,name: "Oliva (La)",province_id: 35}, {_id:35015,name: "Pájara",province_id: 35}, {_id:35016,name: "Palmas de Gran Canaria (Las)",province_id: 35}, {_id:35017,name: "<NAME>",province_id: 35}, {_id:35018,name: "San Bartolomé",province_id: 35}, {_id:35019,name: "San Bartolomé de Tirajana",province_id: 35}, {_id:35020,name: "Aldea de San Nicolás (La)",province_id: 35}, {_id:35021,name: "Santa Brígida",province_id: 35}, {_id:35022,name: "Santa Lucía de Tirajana",province_id: 35}, {_id:35023,name: "<NAME> de Gran Canaria",province_id: 35}, {_id:35024,name: "Teguise",province_id: 35}, {_id:35025,name: "Tejeda",province_id: 35}, {_id:35026,name: "Telde",province_id: 35}, {_id:35027,name: "Teror",province_id: 35}, {_id:35028,name: "Tías",province_id: 35}, {_id:35029,name: "Tinajo",province_id: 35}, {_id:35030,name: "Tuineje",province_id: 35}, {_id:35031,name: "Valsequillo de Gran Canaria",province_id: 35}, {_id:49134,name: "<NAME>",province_id: 49}, {_id:49135,name: "<NAME>",province_id: 49}, {_id:49136,name: "<NAME>",province_id: 49}, {_id:49137,name: "<NAME>",province_id: 49}, {_id:49138,name: "<NAME>",province_id: 49}, {_id:49139,name: "<NAME>",province_id: 49}, {_id:49141,name: "<NAME>",province_id: 49}, {_id:49142,name: "Palacios del Pan",province_id: 49}, {_id:49143,name: "Palacios de Sanabria",province_id: 49}, {_id:49145,name: "<NAME>",province_id: 49}, {_id:49146,name: "Pego (El)",province_id: 49}, {_id:49147,name: "Peleagonzalo",province_id: 49}, {_id:49148,name: "<NAME>",province_id: 49}, {_id:49149,name: "Peñausende",province_id: 49}, {_id:49150,name: "Peque",province_id: 49}, {_id:49151,name: "Perdigón (El)",province_id: 49}, {_id:49152,name: "Pereruela",province_id: 49}, {_id:49153,name: "<NAME>",province_id: 49}, {_id:49154,name: "Pías",province_id: 49}, {_id:49155,name: "<NAME>",province_id: 49}, {_id:49156,name: "<NAME>",province_id: 49}, {_id:49157,name: "<NAME>",province_id: 49}, {_id:49158,name: "<NAME>)",province_id: 49}, {_id:49159,name: "<NAME>",province_id: 49}, {_id:49160,name: "<NAME>",province_id: 49}, {_id:49162,name: "Porto",province_id: 49}, {_id:49163,name: "Pozoantiguo",province_id: 49}, {_id:49164,name: "<NAME>",province_id: 49}, {_id:49165,name: "Prado",province_id: 49}, {_id:49166,name: "<NAME>",province_id: 49}, {_id:49167,name: "<NAME>",province_id: 49}, {_id:49168,name: "<NAME>",province_id: 49}, {_id:49169,name: "<NAME>",province_id: 49}, {_id:49170,name: "<NAME>",province_id: 49}, {_id:49171,name: "<NAME>",province_id: 49}, {_id:49172,name: "Rabanales",province_id: 49}, {_id:49173,name: "<NAME>",province_id: 49}, {_id:49174,name: "Requejo",province_id: 49}, {_id:49175,name: "Revellinos",province_id: 49}, {_id:49176,name: "<NAME>",province_id: 49}, {_id:49177,name: "<NAME>",province_id: 49}, {_id:49178,name: "Roales",province_id: 49}, {_id:49179,name: "Robleda-Cervantes",province_id: 49}, {_id:49180,name: "<NAME>",province_id: 49}, {_id:49181,name: "<NAME>",province_id: 49}, {_id:49183,name: "Salce",province_id: 49}, {_id:49184,name: "<NAME>",province_id: 49}, {_id:49185,name: "<NAME>",province_id: 49}, {_id:49186,name: "<NAME>",province_id: 49}, {_id:49187,name: "<NAME>",province_id: 49}, {_id:49188,name: "<NAME>",province_id: 49}, {_id:49189,name: "<NAME>",province_id: 49}, {_id:49190,name: "<NAME>",province_id: 49}, {_id:49191,name: "<NAME>",province_id: 49}, {_id:49192,name: "<NAME>",province_id: 49}, {_id:49193,name: "<NAME>",province_id: 49}, {_id:49194,name: "San Pedro de la Nave-Almendra",province_id: 49}, {_id:49197,name: "Santa Clara de Avedillo",province_id: 49}, {_id:49199,name: "Santa Colomba de las Monjas",province_id: 49}, {_id:49200,name: "Santa Cristina de la Polvorosa",province_id: 49}, {_id:49201,name: "Santa Croya de Tera",province_id: 49}, {_id:49202,name: "Santa Eufemia del Barco",province_id: 49}, {_id:49203,name: "Santa María de la Vega",province_id: 49}, {_id:49204,name: "<NAME>",province_id: 49}, {_id:49205,name: "<NAME>",province_id: 49}, {_id:49206,name: "Santibáñez de Vidriales",province_id: 49}, {_id:49207,name: "Santovenia",province_id: 49}, {_id:49208,name: "San Vicente de la Cabeza",province_id: 49}, {_id:49209,name: "San Vitero",province_id: 49}, {_id:37005,name: "<NAME> (La)",province_id: 37}, {_id:37006,name: "Alamedilla (La)",province_id: 37}, {_id:37007,name: "Alaraz",province_id: 37}, {_id:37008,name: "<NAME>",province_id: 37}, {_id:37009,name: "<NAME>",province_id: 37}, {_id:37010,name: "Alberca (La)",province_id: 37}, {_id:37011,name: "<NAME> (La)",province_id: 37}, {_id:37012,name: "Alconada",province_id: 37}, {_id:37013,name: "Aldeacipreste",province_id: 37}, {_id:37014,name: "<NAME>",province_id: 37}, {_id:37015,name: "<NAME>",province_id: 37}, {_id:37016,name: "Aldealengua",province_id: 37}, {_id:37017,name: "<NAME>",province_id: 37}, {_id:37018,name: "<NAME>",province_id: 37}, {_id:37019,name: "Aldearrodrigo",province_id: 37}, {_id:37020,name: "Aldearrubia",province_id: 37}, {_id:37021,name: "<NAME>",province_id: 37}, {_id:37022,name: "<NAME>",province_id: 37}, {_id:37023,name: "Aldeatejada",province_id: 37}, {_id:37024,name: "<NAME>",province_id: 37}, {_id:37025,name: "<NAME>",province_id: 37}, {_id:37026,name: "<NAME>",province_id: 37}, {_id:37027,name: "<NAME>",province_id: 37}, {_id:37028,name: "Almendra",province_id: 37}, {_id:37029,name: "<NAME>",province_id: 37}, {_id:37030,name: "<NAME>",province_id: 37}, {_id:37031,name: "<NAME>",province_id: 37}, {_id:37032,name: "Arapiles",province_id: 37}, {_id:37033,name: "Arcediano",province_id: 37}, {_id:37034,name: "<NAME>)",province_id: 37}, {_id:37035,name: "Armenteros",province_id: 37}, {_id:37036,name: "<NAME>",province_id: 37}, {_id:37037,name: "Atalaya (La)",province_id: 37}, {_id:37038,name: "Babilafuente",province_id: 37}, {_id:37039,name: "Bañobárez",province_id: 37}, {_id:37040,name: "Barbadillo",province_id: 37}, {_id:37041,name: "Barbalos",province_id: 37}, {_id:37042,name: "Barceo",province_id: 37}, {_id:37044,name: "Barruecopardo",province_id: 37}, {_id:37045,name: "Bastida (La)",province_id: 37}, {_id:37046,name: "Béjar",province_id: 37}, {_id:37047,name: "Beleña",province_id: 37}, {_id:37049,name: "Bermellar",province_id: 37}, {_id:37050,name: "<NAME>",province_id: 37}, {_id:37051,name: "<NAME>",province_id: 37}, {_id:37052,name: "Boada",province_id: 37}, {_id:37054,name: "Bodón (El)",province_id: 37}, {_id:37055,name: "Bogajo",province_id: 37}, {_id:37056,name: "Bouza (La)",province_id: 37}, {_id:37057,name: "<NAME>",province_id: 37}, {_id:37058,name: "Brincones",province_id: 37}, {_id:37059,name: "Buenamadre",province_id: 37}, {_id:37060,name: "Buenavista",province_id: 37}, {_id:37061,name: "Cabaco (El)",province_id: 37}, {_id:37062,name: "<NAME>",province_id: 37}, {_id:37063,name: "<NAME> (La)",province_id: 37}, {_id:37065,name: "<NAME>",province_id: 37}, {_id:37067,name: "Cabrerizos",province_id: 37}, {_id:37068,name: "Cabrillas",province_id: 37}, {_id:37069,name: "Calvarrasa de Abajo",province_id: 37}, {_id:37070,name: "<NAME>",province_id: 37}, {_id:37071,name: "<NAME> (La)",province_id: 37}, {_id:37072,name: "<NAME>",province_id: 37}, {_id:37073,name: "<NAME>",province_id: 37}, {_id:37074,name: "<NAME>",province_id: 37}, {_id:37077,name: "<NAME> (El)",province_id: 37}, {_id:37078,name: "Candelario",province_id: 37}, {_id:37079,name: "Canillas de Abajo",province_id: 37}, {_id:37080,name: "Cantagallo",province_id: 37}, {_id:37081,name: "Cantalapiedra",province_id: 37}, {_id:37082,name: "Cantalpino",province_id: 37}, {_id:37083,name: "Cantaracillo",province_id: 37}, {_id:37085,name: "<NAME>",province_id: 37}, {_id:37086,name: "<NAME>",province_id: 37}, {_id:37087,name: "<NAME>",province_id: 37}, {_id:37088,name: "<NAME>",province_id: 37}, {_id:37089,name: "Casafranca",province_id: 37}, {_id:37090,name: "<NAME> (Las)",province_id: 37}, {_id:37091,name: "<NAME>",province_id: 37}, {_id:37092,name: "<NAME>",province_id: 37}, {_id:37096,name: "<NAME>",province_id: 37}, {_id:37097,name: "Castraz",province_id: 37}, {_id:37098,name: "Cepeda",province_id: 37}, {_id:37099,name: "<NAME>",province_id: 37}, {_id:37100,name: "<NAME>",province_id: 37}, {_id:37101,name: "Cerralbo",province_id: 37}, {_id:37102,name: "<NAME>)",province_id: 37}, {_id:37103,name: "<NAME>",province_id: 37}, {_id:37104,name: "<NAME>",province_id: 37}, {_id:37106,name: "Cipérez",province_id: 37}, {_id:37107,name: "<NAME>",province_id: 37}, {_id:37108,name: "<NAME>",province_id: 37}, {_id:37109,name: "<NAME>",province_id: 37}, {_id:37110,name: "Cordovilla",province_id: 37}, {_id:37112,name: "Cristóbal",province_id: 37}, {_id:37113,name: "<NAME> (El)",province_id: 37}, {_id:37114,name: "<NAME>",province_id: 37}, {_id:37115,name: "<NAME>",province_id: 37}, {_id:37116,name: "<NAME>",province_id: 37}, {_id:37117,name: "<NAME>",province_id: 37}, {_id:37118,name: "Ejeme",province_id: 37}, {_id:37119,name: "<NAME>)",province_id: 37}, {_id:37120,name: "<NAME>",province_id: 37}, {_id:37121,name: "<NAME>",province_id: 37}, {_id:37122,name: "<NAME>",province_id: 37}, {_id:37123,name: "<NAME>",province_id: 37}, {_id:37124,name: "Endrinal",province_id: 37}, {_id:37125,name: "<NAME>",province_id: 37}, {_id:37126,name: "Espadaña",province_id: 37}, {_id:37127,name: "Espeja",province_id: 37}, {_id:37128,name: "Espino de la Orbada",province_id: 37}, {_id:37129,name: "<NAME> Liébana",province_id: 37}, {_id:37130,name: "Forfoleda",province_id: 37}, {_id:37131,name: "<NAME>",province_id: 37}, {_id:37132,name: "Fregeneda (La)",province_id: 37}, {_id:37133,name: "Fresnedoso",province_id: 37}, {_id:37134,name: "<NAME>",province_id: 37}, {_id:37135,name: "<NAME> (La)",province_id: 37}, {_id:37136,name: "Fuenteguinaldo",province_id: 37}, {_id:37137,name: "Fuenteliante",province_id: 37}, {_id:37138,name: "<NAME>",province_id: 37}, {_id:37139,name: "<NAME>",province_id: 37}, {_id:37140,name: "<NAME>",province_id: 37}, {_id:37141,name: "Gajates",province_id: 37}, {_id:37142,name: "<NAME>",province_id: 37}, {_id:37143,name: "Galinduste",province_id: 37}, {_id:37144,name: "Galisancho",province_id: 37}, {_id:37145,name: "<NAME>",province_id: 37}, {_id:37146,name: "<NAME>",province_id: 37}, {_id:37147,name: "Garcibuey",province_id: 37}, {_id:37148,name: "Garcihernández",province_id: 37}, {_id:37149,name: "Garcirrey",province_id: 37}, {_id:37150,name: "<NAME>",province_id: 37}, {_id:37151,name: "Golpejas",province_id: 37}, {_id:37152,name: "Gomecello",province_id: 37}, {_id:37154,name: "Guadramiro",province_id: 37}, {_id:37155,name: "<NAME>",province_id: 37}, {_id:37156,name: "Guijuelo",province_id: 37}, {_id:37157,name: "<NAME>",province_id: 37}, {_id:37158,name: "<NAME>",province_id: 37}, {_id:37159,name: "<NAME>",province_id: 37}, {_id:37160,name: "<NAME>",province_id: 37}, {_id:37161,name: "<NAME>",province_id: 37}, {_id:37162,name: "<NAME>",province_id: 37}, {_id:37163,name: "<NAME>)",province_id: 37}, {_id:37164,name: "Huerta",province_id: 37}, {_id:37165,name: "Iruelos",province_id: 37}, {_id:37166,name: "<NAME>",province_id: 37}, {_id:37167,name: "Juzbado",province_id: 37}, {_id:37168,name: "Lagunilla",province_id: 37}, {_id:37169,name: "Larrodrigo",province_id: 37}, {_id:37170,name: "Ledesma",province_id: 37}, {_id:37171,name: "Ledrada",province_id: 37}, {_id:37172,name: "<NAME>",province_id: 37}, {_id:37173,name: "Lumbrales",province_id: 37}, {_id:37174,name: "Macotera",province_id: 37}, {_id:37175,name: "Machacón",province_id: 37}, {_id:37176,name: "Madroñal",province_id: 37}, {_id:37177,name: "Maíllo (El)",province_id: 37}, {_id:37178,name: "Malpartida",province_id: 37}, {_id:37179,name: "<NAME>",province_id: 37}, {_id:37180,name: "Manzano (El)",province_id: 37}, {_id:37181,name: "Martiago",province_id: 37}, {_id:37182,name: "Martinamor",province_id: 37}, {_id:37183,name: "<NAME>",province_id: 37}, {_id:37184,name: "Masueco",province_id: 37}, {_id:37185,name: "<NAME>",province_id: 37}, {_id:37186,name: "<NAME> (La)",province_id: 37}, {_id:37187,name: "<NAME>",province_id: 37}, {_id:37188,name: "Maya (La)",province_id: 37}, {_id:37189,name: "<NAME>",province_id: 37}, {_id:37190,name: "Mieza",province_id: 37}, {_id:37191,name: "Milano (El)",province_id: 37}, {_id:37192,name: "<NAME>",province_id: 37}, {_id:37193,name: "<NAME>",province_id: 37}, {_id:37194,name: "Mogarraz",province_id: 37}, {_id:37195,name: "Molinillo",province_id: 37}, {_id:37196,name: "<NAME> Sierra",province_id: 37}, {_id:37197,name: "Monleón",province_id: 37}, {_id:37198,name: "Monleras",province_id: 37}, {_id:37199,name: "Monsagro",province_id: 37}, {_id:37200,name: "Montejo",province_id: 37}, {_id:37201,name: "<NAME>",province_id: 37}, {_id:37202,name: "<NAME>",province_id: 37}, {_id:37203,name: "<NAME>",province_id: 37}, {_id:37204,name: "Morasverdes",province_id: 37}, {_id:37205,name: "Morille",province_id: 37}, {_id:37206,name: "Moríñigo",province_id: 37}, {_id:37207,name: "Moriscos",province_id: 37}, {_id:37208,name: "Moronta",province_id: 37}, {_id:37209,name: "Mozárbez",province_id: 37}, {_id:37211,name: "<NAME>",province_id: 37}, {_id:37212,name: "Navacarros",province_id: 37}, {_id:37213,name: "<NAME>",province_id: 37}, {_id:37214,name: "<NAME>",province_id: 37}, {_id:37215,name: "<NAME>",province_id: 37}, {_id:37216,name: "Navales",province_id: 37}, {_id:37217,name: "<NAME>",province_id: 37}, {_id:44086,name: "Cretas",province_id: 44}, {_id:44087,name: "Crivillén",province_id: 44}, {_id:44088,name: "Cuba (La)",province_id: 44}, {_id:44089,name: "Cubla",province_id: 44}, {_id:44090,name: "Cucalón",province_id: 44}, {_id:44092,name: "Cuervo (El)",province_id: 44}, {_id:44093,name: "<NAME>",province_id: 44}, {_id:44094,name: "<NAME>",province_id: 44}, {_id:44096,name: "Ejulve",province_id: 44}, {_id:44097,name: "Escorihuela",province_id: 44}, {_id:44099,name: "Escucha",province_id: 44}, {_id:44100,name: "Estercuel",province_id: 44}, {_id:44101,name: "<NAME>",province_id: 44}, {_id:44102,name: "Fonfría",province_id: 44}, {_id:44103,name: "<NAME>",province_id: 44}, {_id:44105,name: "Fórnoles",province_id: 44}, {_id:44106,name: "Fortanete",province_id: 44}, {_id:44107,name: "Foz-Calanda",province_id: 44}, {_id:44108,name: "Fresneda (La)",province_id: 44}, {_id:44109,name: "<NAME>",province_id: 44}, {_id:44110,name: "Fuenferrada",province_id: 44}, {_id:44111,name: "<NAME>",province_id: 44}, {_id:44112,name: "<NAME>",province_id: 44}, {_id:44113,name: "<NAME>",province_id: 44}, {_id:44114,name: "Fuentespalda",province_id: 44}, {_id:44115,name: "Galve",province_id: 44}, {_id:44116,name: "Gargallo",province_id: 44}, {_id:44117,name: "<NAME>",province_id: 44}, {_id:44118,name: "Ginebrosa (La)",province_id: 44}, {_id:44119,name: "Griegos",province_id: 44}, {_id:44120,name: "Guadalaviar",province_id: 44}, {_id:44121,name: "Gúdar",province_id: 44}, {_id:44122,name: "Híjar",province_id: 44}, {_id:44123,name: "<NAME>",province_id: 44}, {_id:44124,name: "<NAME> (La)",province_id: 44}, {_id:44125,name: "<NAME>",province_id: 44}, {_id:44126,name: "<NAME> (La)",province_id: 44}, {_id:44127,name: "Jabaloyas",province_id: 44}, {_id:44128,name: "<NAME>",province_id: 44}, {_id:44129,name: "Jatiel",province_id: 44}, {_id:44130,name: "Jorcas",province_id: 44}, {_id:44131,name: "Josa",province_id: 44}, {_id:44132,name: "Lagueruela",province_id: 44}, {_id:44133,name: "Lanzuela",province_id: 44}, {_id:44135,name: "Libros",province_id: 44}, {_id:44136,name: "Lidón",province_id: 44}, {_id:44137,name: "<NAME>",province_id: 44}, {_id:44138,name: "Loscos",province_id: 44}, {_id:44141,name: "Lledó",province_id: 44}, {_id:44142,name: "Maicas",province_id: 44}, {_id:44143,name: "Manzanera",province_id: 44}, {_id:44144,name: "<NAME>",province_id: 44}, {_id:44145,name: "<NAME>",province_id: 44}, {_id:44146,name: "<NAME> (La)",province_id: 44}, {_id:44147,name: "Mazaleón",province_id: 44}, {_id:44148,name: "<NAME>",province_id: 44}, {_id:44149,name: "Mirambel",province_id: 44}, {_id:44150,name: "<NAME>",province_id: 44}, {_id:44151,name: "Molinos",province_id: 44}, {_id:44152,name: "<NAME>",province_id: 44}, {_id:44153,name: "<NAME>",province_id: 44}, {_id:44154,name: "Monroyo",province_id: 44}, {_id:44155,name: "Montalbán",province_id: 44}, {_id:44156,name: "<NAME>",province_id: 44}, {_id:49210,name: "Sanzoles",province_id: 49}, {_id:37279,name: "Sancti-Spíritus",province_id: 37}, {_id:37280,name: "<NAME>",province_id: 37}, {_id:37281,name: "<NAME>",province_id: 37}, {_id:37282,name: "Sanchotello",province_id: 37}, {_id:37283,name: "Sando",province_id: 37}, {_id:37284,name: "<NAME>",province_id: 37}, {_id:37285,name: "<NAME>",province_id: 37}, {_id:37286,name: "<NAME>",province_id: 37}, {_id:37287,name: "<NAME>",province_id: 37}, {_id:37288,name: "<NAME>",province_id: 37}, {_id:37289,name: "<NAME>",province_id: 37}, {_id:37290,name: "<NAME>",province_id: 37}, {_id:37291,name: "<NAME>",province_id: 37}, {_id:37292,name: "<NAME>",province_id: 37}, {_id:37293,name: "<NAME>",province_id: 37}, {_id:37294,name: "<NAME>",province_id: 37}, {_id:37296,name: "<NAME>",province_id: 37}, {_id:37297,name: "<NAME>",province_id: 37}, {_id:37298,name: "<NAME>",province_id: 37}, {_id:37299,name: "Santiz",province_id: 37}, {_id:37300,name: "Santos (Los)",province_id: 37}, {_id:37301,name: "<NAME>",province_id: 37}, {_id:37302,name: "Saucelle",province_id: 37}, {_id:37303,name: "Sahugo (El)",province_id: 37}, {_id:37304,name: "Sepulcro-Hilario",province_id: 37}, {_id:37305,name: "Sequeros",province_id: 37}, {_id:37306,name: "<NAME>",province_id: 37}, {_id:37307,name: "<NAME>",province_id: 37}, {_id:37309,name: "Sierpe (La)",province_id: 37}, {_id:37310,name: "<NAME>",province_id: 37}, {_id:37311,name: "Sobradillo",province_id: 37}, {_id:37312,name: "Sorihuela",province_id: 37}, {_id:37313,name: "Sotoserrano",province_id: 37}, {_id:37314,name: "<NAME>",province_id: 37}, {_id:37315,name: "Tala (La)",province_id: 37}, {_id:37316,name: "Tamames",province_id: 37}, {_id:37317,name: "<NAME>",province_id: 37}, {_id:37318,name: "Tardáguila",province_id: 37}, {_id:37319,name: "Tejado (El)",province_id: 37}, {_id:37320,name: "<NAME>",province_id: 37}, {_id:37321,name: "Tenebrón",province_id: 37}, {_id:37322,name: "Terradillos",province_id: 37}, {_id:37323,name: "Topas",province_id: 37}, {_id:37324,name: "Tordillos",province_id: 37}, {_id:37325,name: "Tornadizo (El)",province_id: 37}, {_id:37327,name: "Torresmenudas",province_id: 37}, {_id:37328,name: "Trabanca",province_id: 37}, {_id:37329,name: "<NAME>",province_id: 37}, {_id:37330,name: "Valdecarros",province_id: 37}, {_id:37331,name: "<NAME>",province_id: 37}, {_id:37332,name: "Valdehijaderos",province_id: 37}, {_id:37333,name: "Valdelacasa",province_id: 37}, {_id:37334,name: "Valdelageve",province_id: 37}, {_id:37335,name: "Valdelosa",province_id: 37}, {_id:37336,name: "Valdemierque",province_id: 37}, {_id:37337,name: "Valderrodrigo",province_id: 37}, {_id:37338,name: "Valdunciel",province_id: 37}, {_id:37339,name: "Valero",province_id: 37}, {_id:37340,name: "Valsalabroso",province_id: 37}, {_id:37341,name: "<NAME>",province_id: 37}, {_id:37342,name: "Valverdón",province_id: 37}, {_id:37343,name: "<NAME>",province_id: 37}, {_id:37344,name: "Vecinos",province_id: 37}, {_id:37345,name: "<NAME>",province_id: 37}, {_id:37346,name: "<NAME>)",province_id: 37}, {_id:37347,name: "Vellés (La)",province_id: 37}, {_id:37348,name: "<NAME>",province_id: 37}, {_id:37349,name: "Vídola (La)",province_id: 37}, {_id:37350,name: "Vilvestre",province_id: 37}, {_id:37351,name: "Villaflores",province_id: 37}, {_id:37352,name: "<NAME>",province_id: 37}, {_id:37353,name: "<NAME>",province_id: 37}, {_id:37354,name: "Villamayor",province_id: 37}, {_id:37355,name: "<NAME>",province_id: 37}, {_id:37356,name: "<NAME>",province_id: 37}, {_id:37357,name: "<NAME>",province_id: 37}, {_id:37358,name: "<NAME>",province_id: 37}, {_id:37359,name: "<NAME>",province_id: 37}, {_id:37360,name: "<NAME>",province_id: 37}, {_id:37361,name: "<NAME>",province_id: 37}, {_id:37362,name: "<NAME>",province_id: 37}, {_id:37363,name: "<NAME>",province_id: 37}, {_id:37364,name: "<NAME>",province_id: 37}, {_id:37365,name: "Villarmayor",province_id: 37}, {_id:37366,name: "Villarmuerto",province_id: 37}, {_id:37367,name: "Villasbuenas",province_id: 37}, {_id:37368,name: "Villasdardo",province_id: 37}, {_id:37369,name: "<NAME>",province_id: 37}, {_id:37370,name: "<NAME>",province_id: 37}, {_id:37371,name: "Villasrubias",province_id: 37}, {_id:37372,name: "<NAME>",province_id: 37}, {_id:37373,name: "<NAME>",province_id: 37}, {_id:37374,name: "Villoria",province_id: 37}, {_id:37375,name: "Villoruela",province_id: 37}, {_id:37376,name: "Vitigudino",province_id: 37}, {_id:37377,name: "<NAME>",province_id: 37}, {_id:37378,name: "Zamarra",province_id: 37}, {_id:37379,name: "Zamayón",province_id: 37}, {_id:37380,name: "Zarapicos",province_id: 37}, {_id:37381,name: "<NAME>)",province_id: 37}, {_id:37382,name: "<NAME>",province_id: 37}, {_id:38001,name: "Adeje",province_id: 38}, {_id:38002,name: "Agulo",province_id: 38}, {_id:38003,name: "Alajeró",province_id: 38}, {_id:38004,name: "Arafo",province_id: 38}, {_id:38005,name: "Arico",province_id: 38}, {_id:38006,name: "Arona",province_id: 38}, {_id:38007,name: "Barlovento",province_id: 38}, {_id:38008,name: "<NAME>",province_id: 38}, {_id:38009,name: "<NAME>",province_id: 38}, {_id:38010,name: "<NAME>",province_id: 38}, {_id:38011,name: "Candelaria",province_id: 38}, {_id:38012,name: "Fasnia",province_id: 38}, {_id:38013,name: "Frontera",province_id: 38}, {_id:38014,name: "<NAME>",province_id: 38}, {_id:38015,name: "Garachico",province_id: 38}, {_id:38016,name: "Garafía",province_id: 38}, {_id:38017,name: "<NAME>",province_id: 38}, {_id:38018,name: "<NAME>)",province_id: 38}, {_id:38019,name: "<NAME>",province_id: 38}, {_id:38020,name: "Güímar",province_id: 38}, {_id:38021,name: "Hermigua",province_id: 38}, {_id:38022,name: "<NAME>",province_id: 38}, {_id:38023,name: "<NAME>",province_id: 38}, {_id:38024,name: "<NAME> (Los)",province_id: 38}, {_id:38025,name: "<NAME> (La)",province_id: 38}, {_id:38026,name: "Orotava (La)",province_id: 38}, {_id:38027,name: "Paso (El)",province_id: 38}, {_id:38028,name: "<NAME>",province_id: 38}, {_id:38029,name: "Puntagorda",province_id: 38}, {_id:38030,name: "Puntallana",province_id: 38}, {_id:38031,name: "Realejos (Los)",province_id: 38}, {_id:38032,name: "Rosario (El)",province_id: 38}, {_id:38033,name: "<NAME>",province_id: 38}, {_id:38034,name: "<NAME>",province_id: 38}, {_id:38035,name: "<NAME>",province_id: 38}, {_id:38036,name: "<NAME>",province_id: 38}, {_id:38037,name: "<NAME>",province_id: 38}, {_id:38038,name: "<NAME>",province_id: 38}, {_id:38039,name: "<NAME>",province_id: 38}, {_id:38040,name: "<NAME>",province_id: 38}, {_id:38041,name: "Sauzal (El)",province_id: 38}, {_id:38042,name: "Silos (Los)",province_id: 38}, {_id:38043,name: "Tacoronte",province_id: 38}, {_id:38044,name: "Tanque (El)",province_id: 38}, {_id:38045,name: "Tazacorte",province_id: 38}, {_id:38046,name: "Tegueste",province_id: 38}, {_id:38047,name: "Tijarafe",province_id: 38}, {_id:38048,name: "Valverde",province_id: 38}, {_id:38049,name: "<NAME>",province_id: 38}, {_id:38050,name: "Vallehermoso",province_id: 38}, {_id:38051,name: "<NAME> (La)",province_id: 38}, {_id:38052,name: "Vilaflor",province_id: 38}, {_id:38053,name: "<NAME>",province_id: 38}, {_id:39001,name: "<NAME>",province_id: 39}, {_id:39002,name: "Ampuero",province_id: 39}, {_id:39003,name: "Anievas",province_id: 39}, {_id:39004,name: "<NAME>",province_id: 39}, {_id:39005,name: "Argoños",province_id: 39}, {_id:39006,name: "Arnuero",province_id: 39}, {_id:39007,name: "Arredondo",province_id: 39}, {_id:39008,name: "Astillero (El)",province_id: 39}, {_id:39009,name: "<NAME>",province_id: 39}, {_id:39010,name: "<NAME>",province_id: 39}, {_id:39011,name: "Bareyo",province_id: 39}, {_id:39012,name: "<NAME>",province_id: 39}, {_id:39013,name: "<NAME>",province_id: 39}, {_id:39014,name: "Cabuérniga",province_id: 39}, {_id:39015,name: "Camaleño",province_id: 39}, {_id:39016,name: "Camargo",province_id: 39}, {_id:39017,name: "<NAME>",province_id: 39}, {_id:39018,name: "Cartes",province_id: 39}, {_id:39019,name: "Castañeda",province_id: 39}, {_id:39020,name: "Castro-Urdiales",province_id: 39}, {_id:39021,name: "Cieza",province_id: 39}, {_id:39022,name: "<NAME>",province_id: 39}, {_id:39023,name: "Colindres",province_id: 39}, {_id:39024,name: "Comillas",province_id: 39}, {_id:39025,name: "<NAME> (Los)",province_id: 39}, {_id:39026,name: "<NAME>",province_id: 39}, {_id:39027,name: "<NAME>",province_id: 39}, {_id:39028,name: "Entrambasaguas",province_id: 39}, {_id:39029,name: "Escalante",province_id: 39}, {_id:39030,name: "Guriezo",province_id: 39}, {_id:39031,name: "<NAME>",province_id: 39}, {_id:39032,name: "<NAME>",province_id: 39}, {_id:39033,name: "Herrerías",province_id: 39}, {_id:39034,name: "Lamasón",province_id: 39}, {_id:39035,name: "Laredo",province_id: 39}, {_id:39036,name: "Liendo",province_id: 39}, {_id:39037,name: "Liérganes",province_id: 39}, {_id:39038,name: "Limpias",province_id: 39}, {_id:39039,name: "Luena",province_id: 39}, {_id:39040,name: "<NAME>",province_id: 39}, {_id:39041,name: "Mazcuerras",province_id: 39}, {_id:39042,name: "<NAME>",province_id: 39}, {_id:39043,name: "Meruelo",province_id: 39}, {_id:39044,name: "Miengo",province_id: 39}, {_id:39045,name: "Miera",province_id: 39}, {_id:39046,name: "Molledo",province_id: 39}, {_id:39047,name: "Noja",province_id: 39}, {_id:39048,name: "Penagos",province_id: 39}, {_id:39049,name: "Peñarrubia",province_id: 39}, {_id:39050,name: "Pesaguero",province_id: 39}, {_id:39051,name: "Pesquera",province_id: 39}, {_id:39052,name: "Piélagos",province_id: 39}, {_id:39053,name: "Polaciones",province_id: 39}, {_id:39054,name: "Polanco",province_id: 39}, {_id:39055,name: "Potes",province_id: 39}, {_id:39056,name: "<NAME>",province_id: 39}, {_id:39057,name: "<NAME>",province_id: 39}, {_id:39058,name: "Rasines",province_id: 39}, {_id:39059,name: "Reinosa",province_id: 39}, {_id:39060,name: "Reocín",province_id: 39}, {_id:39061,name: "<NAME>",province_id: 39}, {_id:39062,name: "<NAME>",province_id: 39}, {_id:39063,name: "Rionansa",province_id: 39}, {_id:39064,name: "Riotuerto",province_id: 39}, {_id:39065,name: "<NAME>)",province_id: 39}, {_id:39066,name: "Ruente",province_id: 39}, {_id:39067,name: "Ruesga",province_id: 39}, {_id:39068,name: "Ruiloba",province_id: 39}, {_id:39069,name: "<NAME>",province_id: 39}, {_id:39070,name: "<NAME>",province_id: 39}, {_id:39071,name: "<NAME>",province_id: 39}, {_id:39072,name: "<NAME>",province_id: 39}, {_id:39073,name: "<NAME>",province_id: 39}, {_id:39074,name: "<NAME>",province_id: 39}, {_id:39075,name: "Santander",province_id: 39}, {_id:39076,name: "<NAME>",province_id: 39}, {_id:39077,name: "<NAME>",province_id: 39}, {_id:39078,name: "<NAME>",province_id: 39}, {_id:39079,name: "Santoña",province_id: 39}, {_id:39080,name: "<NAME>",province_id: 39}, {_id:39081,name: "Saro",province_id: 39}, {_id:39082,name: "Selaya",province_id: 39}, {_id:39083,name: "Soba",province_id: 39}, {_id:39084,name: "Solórzano",province_id: 39}, {_id:39085,name: "Suances",province_id: 39}, {_id:39086,name: "<NAME>)",province_id: 39}, {_id:39087,name: "Torrelavega",province_id: 39}, {_id:39088,name: "Tresviso",province_id: 39}, {_id:39089,name: "Tudanca",province_id: 39}, {_id:39090,name: "Udías",province_id: 39}, {_id:39091,name: "Valdáliga",province_id: 39}, {_id:39092,name: "Valdeolea",province_id: 39}, {_id:39093,name: "<NAME>",province_id: 39}, {_id:39094,name: "Valderredible",province_id: 39}, {_id:39095,name: "<NAME>",province_id: 39}, {_id:39096,name: "<NAME>",province_id: 39}, {_id:39097,name: "<NAME>",province_id: 39}, {_id:39098,name: "Villacarriedo",province_id: 39}, {_id:39099,name: "Villaescusa",province_id: 39}, {_id:39100,name: "Villafufre",province_id: 39}, {_id:39101,name: "<NAME>",province_id: 39}, {_id:39102,name: "Voto",province_id: 39}, {_id:40001,name: "Abades",province_id: 40}, {_id:40002,name: "<NAME>",province_id: 40}, {_id:40003,name: "Adrados",province_id: 40}, {_id:40004,name: "Aguilafuente",province_id: 40}, {_id:40005,name: "<NAME>",province_id: 40}, {_id:40006,name: "Aldealcorvo",province_id: 40}, {_id:40007,name: "<NAME>",province_id: 40}, {_id:40008,name: "<NAME>",province_id: 40}, {_id:40009,name: "Aldeanueva de la Serrezuela",province_id: 40}, {_id:40010,name: "Aldeanueva del Codonal",province_id: 40}, {_id:40012,name: "<NAME>",province_id: 40}, {_id:40013,name: "Aldeasoña",province_id: 40}, {_id:40014,name: "Aldehorno",province_id: 40}, {_id:40015,name: "Aldehuela del Codonal",province_id: 40}, {_id:40016,name: "Aldeonte",province_id: 40}, {_id:40017,name: "Anaya",province_id: 40}, {_id:40018,name: "Añe",province_id: 40}, {_id:40019,name: "Arahuetes",province_id: 40}, {_id:40020,name: "Arcones",province_id: 40}, {_id:40021,name: "<NAME>",province_id: 40}, {_id:40022,name: "Armuña",province_id: 40}, {_id:40024,name: "Ayllón",province_id: 40}, {_id:40025,name: "Barbolla",province_id: 40}, {_id:40026,name: "Basardilla",province_id: 40}, {_id:40028,name: "Bercial",province_id: 40}, {_id:40029,name: "Bercimuel",province_id: 40}, {_id:40030,name: "Bernardos",province_id: 40}, {_id:40031,name: "<NAME>",province_id: 40}, {_id:40032,name: "Boceguillas",province_id: 40}, {_id:40033,name: "Brieva",province_id: 40}, {_id:40034,name: "Caballar",province_id: 40}, {_id:40035,name: "<NAME>",province_id: 40}, {_id:40036,name: "Cabezuela",province_id: 40}, {_id:40037,name: "<NAME>",province_id: 40}, {_id:40039,name: "<NAME>",province_id: 40}, {_id:40040,name: "Cantalejo",province_id: 40}, {_id:40041,name: "Cantimpalos",province_id: 40}, {_id:40043,name: "<NAME>",province_id: 40}, {_id:40044,name: "<NAME>",province_id: 40}, {_id:40045,name: "Casla",province_id: 40}, {_id:40046,name: "<NAME>",province_id: 40}, {_id:40047,name: "<NAME>",province_id: 40}, {_id:40048,name: "Castrojimeno",province_id: 40}, {_id:40049,name: "<NAME>",province_id: 40}, {_id:40051,name: "Castroserracín",province_id: 40}, {_id:40052,name: "<NAME>",province_id: 40}, {_id:40053,name: "<NAME>",province_id: 40}, {_id:40054,name: "<NAME>",province_id: 40}, {_id:40055,name: "<NAME>",province_id: 40}, {_id:40056,name: "<NAME>",province_id: 40}, {_id:40057,name: "Coca",province_id: 40}, {_id:40058,name: "Codorniz",province_id: 40}, {_id:40059,name: "<NAME>",province_id: 40}, {_id:40060,name: "<NAME>",province_id: 40}, {_id:40061,name: "<NAME>",province_id: 40}, {_id:40062,name: "Cubillo",province_id: 40}, {_id:40063,name: "Cuéllar",province_id: 40}, {_id:40065,name: "Chañe",province_id: 40}, {_id:40068,name: "<NAME>",province_id: 40}, {_id:40069,name: "Donhierro",province_id: 40}, {_id:40070,name: "Duruelo",province_id: 40}, {_id:40071,name: "Encinas",province_id: 40}, {_id:40072,name: "Encinillas",province_id: 40}, {_id:40073,name: "Escalona del Prado",province_id: 40}, {_id:40074,name: "Escarabajosa de Cabezas",province_id: 40}, {_id:40075,name: "<NAME>",province_id: 40}, {_id:40076,name: "Espinar (El)",province_id: 40}, {_id:40077,name: "Espirdo",province_id: 40}, {_id:40078,name: "<NAME>",province_id: 40}, {_id:40079,name: "<NAME>",province_id: 40}, {_id:40080,name: "<NAME>",province_id: 40}, {_id:40081,name: "Frumales",province_id: 40}, {_id:40082,name: "<NAME>",province_id: 40}, {_id:40083,name: "<NAME>",province_id: 40}, {_id:40084,name: "<NAME>",province_id: 40}, {_id:40086,name: "Fuentepelayo",province_id: 40}, {_id:40087,name: "Fuentepiñel",province_id: 40}, {_id:40088,name: "Fuenterrebollo",province_id: 40}, {_id:40089,name: "<NAME>",province_id: 40}, {_id:40091,name: "Fuentesoto",province_id: 40}, {_id:40092,name: "Fuentidueña",province_id: 40}, {_id:40093,name: "Gallegos",province_id: 40}, {_id:40094,name: "Garcillán",province_id: 40}, {_id:40095,name: "Gomezserracín",province_id: 40}, {_id:40097,name: "Grajera",province_id: 40}, {_id:40099,name: "<NAME>",province_id: 40}, {_id:40100,name: "Hontalbilla",province_id: 40}, {_id:40101,name: "<NAME>",province_id: 40}, {_id:40103,name: "Huertos (Los)",province_id: 40}, {_id:40104,name: "<NAME>",province_id: 40}, {_id:40105,name: "<NAME>",province_id: 40}, {_id:40106,name: "<NAME>",province_id: 40}, {_id:40107,name: "Labajos",province_id: 40}, {_id:40108,name: "<NAME>",province_id: 40}, {_id:40109,name: "Languilla",province_id: 40}, {_id:40110,name: "<NAME>",province_id: 40}, {_id:40111,name: "<NAME>",province_id: 40}, {_id:40112,name: "Lastrilla (La)",province_id: 40}, {_id:40113,name: "Losa (La)",province_id: 40}, {_id:40115,name: "Maderuelo",province_id: 40}, {_id:40118,name: "Marazuela",province_id: 40}, {_id:40119,name: "<NAME>",province_id: 40}, {_id:40120,name: "<NAME>",province_id: 40}, {_id:40121,name: "<NAME>",province_id: 40}, {_id:40122,name: "Marugán",province_id: 40}, {_id:40123,name: "Matabuena",province_id: 40}, {_id:40124,name: "<NAME>",province_id: 40}, {_id:40125,name: "<NAME>)",province_id: 40}, {_id:40126,name: "<NAME>",province_id: 40}, {_id:40127,name: "<NAME>",province_id: 40}, {_id:40128,name: "Migueláñez",province_id: 40}, {_id:40129,name: "<NAME>",province_id: 40}, {_id:40130,name: "<NAME>",province_id: 40}, {_id:40131,name: "Monterrubio",province_id: 40}, {_id:40132,name: "<NAME>",province_id: 40}, {_id:40134,name: "Mozoncillo",province_id: 40}, {_id:40135,name: "Muñopedro",province_id: 40}, {_id:40136,name: "Muñoveros",province_id: 40}, {_id:40138,name: "<NAME>",province_id: 40}, {_id:40139,name: "Navafría",province_id: 40}, {_id:40140,name: "Navalilla",province_id: 40}, {_id:40141,name: "Navalmanzano",province_id: 40}, {_id:40142,name: "<NAME>",province_id: 40}, {_id:40143,name: "<NAME>",province_id: 40}, {_id:40144,name: "<NAME>",province_id: 40}, {_id:40145,name: "<NAME>",province_id: 40}, {_id:40146,name: "<NAME>",province_id: 40}, {_id:40148,name: "Nieva",province_id: 40}, {_id:40149,name: "Olombrada",province_id: 40}, {_id:40150,name: "Orejana",province_id: 40}, {_id:40151,name: "<NAME>",province_id: 40}, {_id:40152,name: "<NAME>",province_id: 40}, {_id:40154,name: "Pajarejos",province_id: 40}, {_id:40155,name: "<NAME>",province_id: 40}, {_id:40156,name: "Pedraza",province_id: 40}, {_id:40157,name: "<NAME>",province_id: 40}, {_id:40158,name: "Perosillo",province_id: 40}, {_id:40159,name: "Pinarejos",province_id: 40}, {_id:40160,name: "Pinarnegrillo",province_id: 40}, {_id:40161,name: "Pradales",province_id: 40}, {_id:40162,name: "Prádena",province_id: 40}, {_id:40163,name: "<NAME>",province_id: 40}, {_id:40164,name: "Rapariegos",province_id: 40}, {_id:40165,name: "Rebollo",province_id: 40}, {_id:40166,name: "Remondo",province_id: 40}, {_id:40168,name: "<NAME>",province_id: 40}, {_id:40170,name: "Riaza",province_id: 40}, {_id:40171,name: "Ribota",province_id: 40}, {_id:40172,name: "<NAME>",province_id: 40}, {_id:40173,name: "<NAME>",province_id: 40}, {_id:40174,name: "Sacramenia",province_id: 40}, {_id:40176,name: "Samboal",province_id: 40}, {_id:40177,name: "<NAME>",province_id: 40}, {_id:40178,name: "<NAME>",province_id: 40}, {_id:40179,name: "Sanchonuño",province_id: 40}, {_id:40180,name: "Sangarcía",province_id: 40}, {_id:40181,name: "<NAME>",province_id: 40}, {_id:40182,name: "<NAME>",province_id: 40}, {_id:40183,name: "<NAME>",province_id: 40}, {_id:40184,name: "<NAME>",province_id: 40}, {_id:40185,name: "<NAME>",province_id: 40}, {_id:40186,name: "<NAME>",province_id: 40}, {_id:40188,name: "<NAME>",province_id: 40}, {_id:40189,name: "<NAME>",province_id: 40}, {_id:40190,name: "<NAME>",province_id: 40}, {_id:40191,name: "<NAME>",province_id: 40}, {_id:40192,name: "<NAME>",province_id: 40}, {_id:40193,name: "Sebúlcor",province_id: 40}, {_id:40194,name: "Segovia",province_id: 40}, {_id:40195,name: "Sepúlveda",province_id: 40}, {_id:40196,name: "<NAME>",province_id: 40}, {_id:40198,name: "Sotillo",province_id: 40}, {_id:40199,name: "Sotosalbos",province_id: 40}, {_id:40200,name: "<NAME>",province_id: 40}, {_id:40201,name: "Tolocirio",province_id: 40}, {_id:40202,name: "Torreadrada",province_id: 40}, {_id:40203,name: "Torrecaballeros",province_id: 40}, {_id:40204,name: "<NAME>",province_id: 40}, {_id:40205,name: "Torreiglesias",province_id: 40}, {_id:40206,name: "<NAME>",province_id: 40}, {_id:40207,name: "Trescasas",province_id: 40}, {_id:40208,name: "Turégano",province_id: 40}, {_id:40210,name: "Urueñas",province_id: 40}, {_id:40211,name: "Valdeprados",province_id: 40}, {_id:40212,name: "<NAME>",province_id: 40}, {_id:40213,name: "<NAME>",province_id: 40}, {_id:40214,name: "Valseca",province_id: 40}, {_id:40215,name: "Valtiendas",province_id: 40}, {_id:40216,name: "<NAME>",province_id: 40}, {_id:40218,name: "<NAME>",province_id: 40}, {_id:40219,name: "Vallelado",province_id: 40}, {_id:40220,name: "<NAME>",province_id: 40}, {_id:40221,name: "<NAME>",province_id: 40}, {_id:40222,name: "Veganzones",province_id: 40}, {_id:40223,name: "<NAME>",province_id: 40}, {_id:40224,name: "<NAME>",province_id: 40}, {_id:40225,name: "Villacastín",province_id: 40}, {_id:40228,name: "<NAME>",province_id: 40}, {_id:40229,name: "<NAME>",province_id: 40}, {_id:40230,name: "Villeguillo",province_id: 40}, {_id:40231,name: "<NAME>",province_id: 40}, {_id:40233,name: "<NAME>",province_id: 40}, {_id:40234,name: "<NAME>",province_id: 40}, {_id:40901,name: "<NAME>",province_id: 40}, {_id:40902,name: "<NAME>",province_id: 40}, {_id:40903,name: "Marazoleja",province_id: 40}, {_id:40904,name: "<NAME>",province_id: 40}, {_id:40905,name: "<NAME>",province_id: 40}, {_id:40906,name: "<NAME>",province_id: 40}, {_id:41001,name: "Aguadulce",province_id: 41}, {_id:41002,name: "Alanís",province_id: 41}, {_id:41003,name: "<NAME>",province_id: 41}, {_id:41004,name: "<NAME>",province_id: 41}, {_id:41005,name: "<NAME>",province_id: 41}, {_id:41006,name: "<NAME>",province_id: 41}, {_id:41007,name: "<NAME>)",province_id: 41}, {_id:41008,name: "Algámitas",province_id: 41}, {_id:41009,name: "<NAME>",province_id: 41}, {_id:41010,name: "Almensilla",province_id: 41}, {_id:41011,name: "Arahal",province_id: 41}, {_id:41012,name: "Aznalcázar",province_id: 41}, {_id:41013,name: "Aznalcóllar",province_id: 41}, {_id:41014,name: "Badolatosa",province_id: 41}, {_id:41015,name: "Benacazón",province_id: 41}, {_id:41016,name: "<NAME>",province_id: 41}, {_id:41017,name: "Bormujos",province_id: 41}, {_id:41018,name: "Brenes",province_id: 41}, {_id:41019,name: "Burguillos",province_id: 41}, {_id:41020,name: "<NAME> (Las)",province_id: 41}, {_id:41021,name: "Camas",province_id: 41}, {_id:41022,name: "Campana (La)",province_id: 41}, {_id:41023,name: "Cantillana",province_id: 41}, {_id:41024,name: "Carmona",province_id: 41}, {_id:41025,name: "<NAME>",province_id: 41}, {_id:41026,name: "Casariche",province_id: 41}, {_id:41027,name: "<NAME>",province_id: 41}, {_id:41028,name: "<NAME>",province_id: 41}, {_id:41029,name: "<NAME>",province_id: 41}, {_id:41030,name: "<NAME>",province_id: 41}, {_id:41031,name: "<NAME> (El)",province_id: 41}, {_id:41032,name: "<NAME>",province_id: 41}, {_id:41033,name: "Constantina",province_id: 41}, {_id:41034,name: "<NAME>",province_id: 41}, {_id:41035,name: "Coripe",province_id: 41}, {_id:41036,name: "Coronil (El)",province_id: 41}, {_id:41037,name: "Corrales (Los)",province_id: 41}, {_id:41038,name: "<NAME>",province_id: 41}, {_id:41039,name: "Écija",province_id: 41}, {_id:41040,name: "Espartinas",province_id: 41}, {_id:41041,name: "Estepa",province_id: 41}, {_id:41042,name: "<NAME>",province_id: 41}, {_id:41043,name: "Garrobo (El)",province_id: 41}, {_id:41044,name: "Gelves",province_id: 41}, {_id:41045,name: "Gerena",province_id: 41}, {_id:41046,name: "Gilena",province_id: 41}, {_id:41047,name: "Gines",province_id: 41}, {_id:41048,name: "Guadalcanal",province_id: 41}, {_id:41049,name: "Guillena",province_id: 41}, {_id:41050,name: "Herrera",province_id: 41}, {_id:41051,name: "<NAME>",province_id: 41}, {_id:41052,name: "Lantejuela (La)",province_id: 41}, {_id:41053,name: "Lebrija",province_id: 41}, {_id:41054,name: "<NAME>",province_id: 41}, {_id:41055,name: "<NAME>",province_id: 41}, {_id:41056,name: "Luisiana (La)",province_id: 41}, {_id:41057,name: "Madroño (El)",province_id: 41}, {_id:41058,name: "<NAME>",province_id: 41}, {_id:41059,name: "<NAME>",province_id: 41}, {_id:41060,name: "Marchena",province_id: 41}, {_id:41061,name: "Marinaleda",province_id: 41}, {_id:41062,name: "<NAME>",province_id: 41}, {_id:50247,name: "Sobradiel",province_id: 50}, {_id:31194,name: "Ollo",province_id: 31}, {_id:31195,name: "Orbaitzeta",province_id: 31}, {_id:31196,name: "Orbara",province_id: 31}, {_id:31197,name: "Orísoain",province_id: 31}, {_id:31198,name: "Oronz",province_id: 31}, {_id:31199,name: "Oroz-Betelu",province_id: 31}, {_id:31200,name: "Oteiza",province_id: 31}, {_id:31201,name: "Pamplona/Iruña",province_id: 31}, {_id:31202,name: "Peralta",province_id: 31}, {_id:31203,name: "<NAME>",province_id: 31}, {_id:31204,name: "Piedramillera",province_id: 31}, {_id:31205,name: "Pitillas",province_id: 31}, {_id:31206,name: "<NAME>/Gares",province_id: 31}, {_id:31207,name: "Pueyo",province_id: 31}, {_id:31208,name: "Ribaforada",province_id: 31}, {_id:31209,name: "Romanzado",province_id: 31}, {_id:31210,name: "Roncal/Erronkari",province_id: 31}, {_id:31211,name: "Orreaga/Roncesvalles",province_id: 31}, {_id:31212,name: "Sada",province_id: 31}, {_id:31213,name: "Saldías",province_id: 31}, {_id:31214,name: "<NAME>",province_id: 31}, {_id:31215,name: "<NAME>",province_id: 31}, {_id:31216,name: "Sangüesa/Zangoza",province_id: 31}, {_id:31217,name: "<NAME>",province_id: 31}, {_id:31219,name: "Sansol",province_id: 31}, {_id:31220,name: "Santacara",province_id: 31}, {_id:31221,name: "Doneztebe/Santesteban",province_id: 31}, {_id:31222,name: "Sarriés/Sartze",province_id: 31}, {_id:31223,name: "Sartaguda",province_id: 31}, {_id:31224,name: "Sesma",province_id: 31}, {_id:31225,name: "Sorlada",province_id: 31}, {_id:31226,name: "Sunbilla",province_id: 31}, {_id:31227,name: "Tafalla",province_id: 31}, {_id:31228,name: "Tiebas-<NAME>",province_id: 31}, {_id:31229,name: "Tirapu",province_id: 31}, {_id:31230,name: "<NAME>",province_id: 31}, {_id:31231,name: "<NAME>",province_id: 31}, {_id:31232,name: "Tudela",province_id: 31}, {_id:31233,name: "Tulebras",province_id: 31}, {_id:31234,name: "Ucar",province_id: 31}, {_id:31235,name: "Ujué",province_id: 31}, {_id:31236,name: "Ultzama",province_id: 31}, {_id:31237,name: "Unciti",province_id: 31}, {_id:31238,name: "Unzué",province_id: 31}, {_id:31239,name: "Urdazubi/Urdax",province_id: 31}, {_id:31240,name: "Urdiain",province_id: 31}, {_id:31241,name: "<NAME>",province_id: 31}, {_id:31242,name: "<NAME>",province_id: 31}, {_id:31243,name: "Urroz-Villa",province_id: 31}, {_id:31244,name: "Urrotz",province_id: 31}, {_id:31245,name: "Urzainqui",province_id: 31}, {_id:31246,name: "Uterga",province_id: 31}, {_id:31247,name: "Uztárroz/Uztarroze",province_id: 31}, {_id:31248,name: "Luzaide/Valcarlos",province_id: 31}, {_id:31249,name: "Valtierra",province_id: 31}, {_id:31250,name: "Bera/<NAME>",province_id: 31}, {_id:31251,name: "Viana",province_id: 31}, {_id:31252,name: "Vidángoz/Bidankoze",province_id: 31}, {_id:31253,name: "Bidaurreta",province_id: 31}, {_id:31254,name: "Villafranca",province_id: 31}, {_id:31255,name: "<NAME>",province_id: 31}, {_id:31256,name: "Hiriberri/<NAME>",province_id: 31}, {_id:31257,name: "Villatuerta",province_id: 31}, {_id:31258,name: "Villava/Atarrabia",province_id: 31}, {_id:31259,name: "Igantzi",province_id: 31}, {_id:31260,name: "Yerri",province_id: 31}, {_id:31261,name: "Yesa",province_id: 31}, {_id:31262,name: "Zabalza",province_id: 31}, {_id:31263,name: "Zubieta",province_id: 31}, {_id:31264,name: "Zugarramurdi",province_id: 31}, {_id:31265,name: "Zúñiga",province_id: 31}, {_id:31901,name: "Barañain",province_id: 31}, {_id:31902,name: "Berrioplano",province_id: 31}, {_id:31903,name: "Berriozar",province_id: 31}, {_id:31904,name: "Irurtzun",province_id: 31}, {_id:31905,name: "Beriáin",province_id: 31}, {_id:31906,name: "Orkoien",province_id: 31}, {_id:31907,name: "<NAME>/<NAME>",province_id: 31}, {_id:31908,name: "Lekunberri",province_id: 31}, {_id:32001,name: "Allariz",province_id: 32}, {_id:32002,name: "Amoeiro",province_id: 32}, {_id:32003,name: "Arnoia (A)",province_id: 32}, {_id:32004,name: "Avión",province_id: 32}, {_id:32005,name: "Baltar",province_id: 32}, {_id:32006,name: "Bande",province_id: 32}, {_id:32007,name: "<NAME>",province_id: 32}, {_id:32008,name: "Barbadás",province_id: 32}, {_id:32009,name: "<NAME> (O)",province_id: 32}, {_id:32010,name: "Beade",province_id: 32}, {_id:32011,name: "Beariz",province_id: 32}, {_id:32012,name: "Blancos (Os)",province_id: 32}, {_id:32013,name: "Boborás",province_id: 32}, {_id:32014,name: "Bola (A)",province_id: 32}, {_id:32015,name: "Bolo (O)",province_id: 32}, {_id:32016,name: "<NAME>",province_id: 32}, {_id:32017,name: "<NAME>",province_id: 32}, {_id:32018,name: "<NAME>",province_id: 32}, {_id:32019,name: "Carballiño (O)",province_id: 32}, {_id:32020,name: "Cartelle",province_id: 32}, {_id:32021,name: "<NAME>",province_id: 32}, {_id:32022,name: "<NAME>",province_id: 32}, {_id:32023,name: "<NAME>",province_id: 32}, {_id:32024,name: "Celanova",province_id: 32}, {_id:32025,name: "Cenlle",province_id: 32}, {_id:32026,name: "Coles",province_id: 32}, {_id:32027,name: "Cortegada",province_id: 32}, {_id:32028,name: "Cualedro",province_id: 32}, {_id:32029,name: "<NAME>",province_id: 32}, {_id:32030,name: "Entrimo",province_id: 32}, {_id:32031,name: "Esgos",province_id: 32}, {_id:32032,name: "<NAME>",province_id: 32}, {_id:32033,name: "Gomesende",province_id: 32}, {_id:32034,name: "Gudiña (A)",province_id: 32}, {_id:32035,name: "Irixo (O)",province_id: 32}, {_id:32036,name: "<NAME>",province_id: 32}, {_id:32037,name: "<NAME>",province_id: 32}, {_id:32038,name: "Larouco",province_id: 32}, {_id:32039,name: "Laza",province_id: 32}, {_id:32040,name: "Leiro",province_id: 32}, {_id:32041,name: "Lobeira",province_id: 32}, {_id:32042,name: "Lobios",province_id: 32}, {_id:32043,name: "Maceda",province_id: 32}, {_id:32044,name: "Manzaneda",province_id: 32}, {_id:32045,name: "Maside",province_id: 32}, {_id:32046,name: "Melón",province_id: 32}, {_id:32047,name: "Merca (A)",province_id: 32}, {_id:32048,name: "Mezquita (A)",province_id: 32}, {_id:32049,name: "Montederramo",province_id: 32}, {_id:32050,name: "Monterrei",province_id: 32}, {_id:32051,name: "Muíños",province_id: 32}, {_id:32052,name: "<NAME>",province_id: 32}, {_id:32053,name: "Oímbra",province_id: 32}, {_id:32054,name: "Ourense",province_id: 32}, {_id:32055,name: "<NAME>",province_id: 32}, {_id:32056,name: "Padrenda",province_id: 32}, {_id:32057,name: "<NAME>",province_id: 32}, {_id:32058,name: "<NAME> (O)",province_id: 32}, {_id:32059,name: "Peroxa (A)",province_id: 32}, {_id:32060,name: "Petín",province_id: 32}, {_id:32061,name: "Piñor",province_id: 32}, {_id:32062,name: "Porqueira",province_id: 32}, {_id:32063,name: "<NAME> (A)",province_id: 32}, {_id:32064,name: "Pontedeva",province_id: 32}, {_id:32065,name: "Punxín",province_id: 32}, {_id:32066,name: "<NAME>",province_id: 32}, {_id:32067,name: "<NAME>",province_id: 32}, {_id:32068,name: "Ramirás",province_id: 32}, {_id:32069,name: "Ribadavia",province_id: 32}, {_id:32070,name: "<NAME>",province_id: 32}, {_id:32071,name: "Riós",province_id: 32}, {_id:32072,name: "Rúa (A)",province_id: 32}, {_id:32073,name: "Rubiá",province_id: 32}, {_id:32074,name: "<NAME>",province_id: 32}, {_id:32075,name: "<NAME>",province_id: 32}, {_id:32076,name: "<NAME>",province_id: 32}, {_id:32077,name: "Sandiás",province_id: 32}, {_id:32078,name: "Sarreaus",province_id: 32}, {_id:32079,name: "Taboadela",province_id: 32}, {_id:32080,name: "Teixeira (A)",province_id: 32}, {_id:32081,name: "Toén",province_id: 32}, {_id:32082,name: "Trasmiras",province_id: 32}, {_id:32083,name: "Veiga (A)",province_id: 32}, {_id:32084,name: "Verea",province_id: 32}, {_id:32085,name: "Verín",province_id: 32}, {_id:32086,name: "<NAME>",province_id: 32}, {_id:32087,name: "Vilamarín",province_id: 32}, {_id:32088,name: "<NAME>",province_id: 32}, {_id:32089,name: "<NAME>",province_id: 32}, {_id:32090,name: "<NAME>",province_id: 32}, {_id:32091,name: "Vilardevós",province_id: 32}, {_id:32092,name: "<NAME>",province_id: 32}, {_id:33001,name: "Allande",province_id: 33}, {_id:33002,name: "Aller",province_id: 33}, {_id:33003,name: "Amieva",province_id: 33}, {_id:33004,name: "Avilés",province_id: 33}, {_id:33005,name: "<NAME>",province_id: 33}, {_id:33006,name: "Bimenes",province_id: 33}, {_id:33007,name: "Boal",province_id: 33}, {_id:33008,name: "Cabrales",province_id: 33}, {_id:33009,name: "Cabranes",province_id: 33}, {_id:33010,name: "Candamo",province_id: 33}, {_id:33011,name: "<NAME>",province_id: 33}, {_id:33012,name: "<NAME>",province_id: 33}, {_id:33013,name: "Caravia",province_id: 33}, {_id:33014,name: "Carreño",province_id: 33}, {_id:33015,name: "Caso",province_id: 33}, {_id:33016,name: "Castrillón",province_id: 33}, {_id:33017,name: "Castropol",province_id: 33}, {_id:33018,name: "Coaña",province_id: 33}, {_id:33019,name: "Colunga",province_id: 33}, {_id:33020,name: "<NAME>",province_id: 33}, {_id:33021,name: "Cudillero",province_id: 33}, {_id:33022,name: "Degaña",province_id: 33}, {_id:33023,name: "<NAME>)",province_id: 33}, {_id:33024,name: "Gijón",province_id: 33}, {_id:33025,name: "Gozón",province_id: 33}, {_id:33026,name: "Grado",province_id: 33}, {_id:33027,name: "<NAME>",province_id: 33}, {_id:33028,name: "Ibias",province_id: 33}, {_id:33029,name: "Illano",province_id: 33}, {_id:33030,name: "Illas",province_id: 33}, {_id:33031,name: "Langreo",province_id: 33}, {_id:33032,name: "Laviana",province_id: 33}, {_id:33033,name: "Lena",province_id: 33}, {_id:33034,name: "Valdés",province_id: 33}, {_id:33035,name: "Llanera",province_id: 33}, {_id:33036,name: "Llanes",province_id: 33}, {_id:33037,name: "Mieres",province_id: 33}, {_id:33038,name: "Morcín",province_id: 33}, {_id:33039,name: "<NAME>",province_id: 33}, {_id:33040,name: "Nava",province_id: 33}, {_id:33041,name: "Navia",province_id: 33}, {_id:33042,name: "Noreña",province_id: 33}, {_id:33043,name: "Onís",province_id: 33}, {_id:33044,name: "Oviedo",province_id: 33}, {_id:33045,name: "Parres",province_id: 33}, {_id:33046,name: "<NAME>",province_id: 33}, {_id:33047,name: "<NAME>",province_id: 33}, {_id:33048,name: "Pesoz",province_id: 33}, {_id:33049,name: "Piloña",province_id: 33}, {_id:33050,name: "Ponga",province_id: 33}, {_id:33051,name: "Pravia",province_id: 33}, {_id:33052,name: "Proaza",province_id: 33}, {_id:33053,name: "Quirós",province_id: 33}, {_id:33054,name: "<NAME>)",province_id: 33}, {_id:33055,name: "Ribadedeva",province_id: 33}, {_id:33056,name: "Ribadesella",province_id: 33}, {_id:33057,name: "<NAME>",province_id: 33}, {_id:33058,name: "Riosa",province_id: 33}, {_id:33059,name: "Salas",province_id: 33}, {_id:33060,name: "<NAME>",province_id: 33}, {_id:33061,name: "<NAME>",province_id: 33}, {_id:33062,name: "<NAME>",province_id: 33}, {_id:33063,name: "<NAME>",province_id: 33}, {_id:33064,name: "<NAME>",province_id: 33}, {_id:33065,name: "Sariego",province_id: 33}, {_id:33066,name: "Siero",province_id: 33}, {_id:33067,name: "Sobrescobio",province_id: 33}, {_id:33068,name: "Somiedo",province_id: 33}, {_id:33069,name: "<NAME>",province_id: 33}, {_id:33070,name: "<NAME>",province_id: 33}, {_id:33071,name: "Taramundi",province_id: 33}, {_id:33072,name: "Teverga",province_id: 33}, {_id:33073,name: "Tineo",province_id: 33}, {_id:33074,name: "Vegadeo",province_id: 33}, {_id:33075,name: "<NAME>",province_id: 33}, {_id:33076,name: "Villaviciosa",province_id: 33}, {_id:33077,name: "Villayón",province_id: 33}, {_id:33078,name: "<NAME>",province_id: 33}, {_id:34001,name: "<NAME>",province_id: 34}, {_id:34003,name: "<NAME>",province_id: 34}, {_id:34004,name: "<NAME>",province_id: 34}, {_id:34005,name: "<NAME>",province_id: 34}, {_id:34006,name: "<NAME>",province_id: 34}, {_id:34009,name: "<NAME>",province_id: 34}, {_id:34010,name: "Ampudia",province_id: 34}, {_id:34011,name: "Amusco",province_id: 34}, {_id:34012,name: "Antigüedad",province_id: 34}, {_id:34015,name: "Arconada",province_id: 34}, {_id:34017,name: "Astudillo",province_id: 34}, {_id:34018,name: "<NAME>",province_id: 34}, {_id:34019,name: "<NAME>",province_id: 34}, {_id:34020,name: "Ayuela",province_id: 34}, {_id:34022,name: "Baltanás",province_id: 34}, {_id:34023,name: "<NAME>",province_id: 34}, {_id:34024,name: "<NAME>",province_id: 34}, {_id:34025,name: "<NAME>",province_id: 34}, {_id:34027,name: "<NAME>",province_id: 34}, {_id:34028,name: "<NAME>",province_id: 34}, {_id:34029,name: "<NAME>",province_id: 34}, {_id:34031,name: "<NAME>",province_id: 34}, {_id:34032,name: "Berzosilla",province_id: 34}, {_id:34033,name: "<NAME>",province_id: 34}, {_id:34034,name: "<NAME>",province_id: 34}, {_id:34035,name: "<NAME>",province_id: 34}, {_id:34036,name: "Brañosera",province_id: 34}, {_id:34037,name: "<NAME>",province_id: 34}, {_id:34038,name: "<NAME>",province_id: 34}, {_id:34039,name: "<NAME>",province_id: 34}, {_id:34041,name: "<NAME>",province_id: 34}, {_id:34042,name: "<NAME>",province_id: 34}, {_id:34045,name: "Capillas",province_id: 34}, {_id:34046,name: "<NAME>",province_id: 34}, {_id:34047,name: "<NAME>",province_id: 34}, {_id:34048,name: "<NAME>",province_id: 34}, {_id:34049,name: "<NAME>",province_id: 34}, {_id:34050,name: "<NAME>",province_id: 34}, {_id:34051,name: "<NAME>",province_id: 34}, {_id:34052,name: "<NAME>",province_id: 34}, {_id:34053,name: "Castromocho",province_id: 34}, {_id:34055,name: "<NAME>",province_id: 34}, {_id:44157,name: "<NAME>",province_id: 44}, {_id:44158,name: "<NAME>",province_id: 44}, {_id:44159,name: "Moscardón",province_id: 44}, {_id:44160,name: "Mosqueruela",province_id: 44}, {_id:44161,name: "Muniesa",province_id: 44}, {_id:44163,name: "<NAME>",province_id: 44}, {_id:44164,name: "Nogueras",province_id: 44}, {_id:44165,name: "Nogueruelas",province_id: 44}, {_id:44167,name: "Obón",province_id: 44}, {_id:44168,name: "Odón",province_id: 44}, {_id:44169,name: "<NAME>",province_id: 44}, {_id:44171,name: "Olba",province_id: 44}, {_id:44172,name: "Oliete",province_id: 44}, {_id:44173,name: "Olmos (Los)",province_id: 44}, {_id:44174,name: "<NAME>",province_id: 44}, {_id:44175,name: "Orrios",province_id: 44}, {_id:44176,name: "<NAME>",province_id: 44}, {_id:44177,name: "Pancrudo",province_id: 44}, {_id:44178,name: "<NAME> (Las)",province_id: 44}, {_id:44179,name: "<NAME>",province_id: 44}, {_id:44180,name: "Peracense",province_id: 44}, {_id:44181,name: "Peralejos",province_id: 44}, {_id:44182,name: "<NAME>",province_id: 44}, {_id:44183,name: "Pitarque",province_id: 44}, {_id:44184,name: "Plou",province_id: 44}, {_id:44185,name: "Pobo (El)",province_id: 44}, {_id:44187,name: "Portellada (La)",province_id: 44}, {_id:44189,name: "Pozondón",province_id: 44}, {_id:44190,name: "<NAME>",province_id: 44}, {_id:44191,name: "<NAME> (La)",province_id: 44}, {_id:44192,name: "<NAME> (La)",province_id: 44}, {_id:44193,name: "Puertomingalvo",province_id: 44}, {_id:44194,name: "Ráfales",province_id: 44}, {_id:44195,name: "Rillo",province_id: 44}, {_id:44196,name: "Riodeva",province_id: 44}, {_id:44197,name: "Ródenas",province_id: 44}, {_id:44198,name: "Royuela",province_id: 44}, {_id:44199,name: "Rubiales",province_id: 44}, {_id:44200,name: "<NAME>",province_id: 44}, {_id:44201,name: "<NAME>",province_id: 44}, {_id:44203,name: "Salcedillo",province_id: 44}, {_id:44204,name: "Saldón",province_id: 44}, {_id:44205,name: "<NAME>",province_id: 44}, {_id:44206,name: "<NAME>",province_id: 44}, {_id:44207,name: "<NAME>",province_id: 44}, {_id:44208,name: "<NAME>",province_id: 44}, {_id:44209,name: "<NAME>",province_id: 44}, {_id:44210,name: "Sarrión",province_id: 44}, {_id:44211,name: "<NAME>",province_id: 44}, {_id:44212,name: "Seno",province_id: 44}, {_id:44213,name: "Singra",province_id: 44}, {_id:44215,name: "Terriente",province_id: 44}, {_id:44216,name: "Teruel",province_id: 44}, {_id:44217,name: "<NAME>",province_id: 44}, {_id:44218,name: "Tormón",province_id: 44}, {_id:44219,name: "Tornos",province_id: 44}, {_id:44220,name: "<NAME>",province_id: 44}, {_id:44221,name: "<NAME>",province_id: 44}, {_id:44222,name: "<NAME>",province_id: 44}, {_id:44223,name: "<NAME>",province_id: 44}, {_id:44224,name: "<NAME>",province_id: 44}, {_id:44225,name: "<NAME>",province_id: 44}, {_id:44226,name: "Torrelacárcel",province_id: 44}, {_id:44227,name: "<NAME>",province_id: 44}, {_id:44228,name: "<NAME>",province_id: 44}, {_id:44229,name: "<NAME>",province_id: 44}, {_id:44230,name: "Torrevelilla",province_id: 44}, {_id:44231,name: "Torrijas",province_id: 44}, {_id:44232,name: "<NAME>",province_id: 44}, {_id:44234,name: "Tramacastiel",province_id: 44}, {_id:44235,name: "Tramacastilla",province_id: 44}, {_id:44236,name: "Tronchón",province_id: 44}, {_id:44237,name: "<NAME>",province_id: 44}, {_id:44238,name: "Utrillas",province_id: 44}, {_id:44239,name: "Valacloche",province_id: 44}, {_id:44240,name: "Valbona",province_id: 44}, {_id:44241,name: "Valdealgorfa",province_id: 44}, {_id:44243,name: "Valdecuenca",province_id: 44}, {_id:44244,name: "Valdelinares",province_id: 44}, {_id:44245,name: "Valdeltormo",province_id: 44}, {_id:44246,name: "Valderrobres",province_id: 44}, {_id:44247,name: "Valjunquera",province_id: 44}, {_id:44249,name: "<NAME>)",province_id: 44}, {_id:44250,name: "<NAME>",province_id: 44}, {_id:44251,name: "<NAME>",province_id: 44}, {_id:44252,name: "<NAME>",province_id: 44}, {_id:44256,name: "<NAME>",province_id: 44}, {_id:44257,name: "<NAME>",province_id: 44}, {_id:44258,name: "<NAME>",province_id: 44}, {_id:44260,name: "Villarluengo",province_id: 44}, {_id:44261,name: "Villarquemado",province_id: 44}, {_id:44262,name: "<NAME>",province_id: 44}, {_id:44263,name: "Villastar",province_id: 44}, {_id:44264,name: "Villel",province_id: 44}, {_id:44265,name: "Vinaceite",province_id: 44}, {_id:44266,name: "Visiedo",province_id: 44}, {_id:44267,name: "<NAME>",province_id: 44}, {_id:44268,name: "<NAME>)",province_id: 44}, {_id:45001,name: "Ajofrín",province_id: 45}, {_id:45002,name: "<NAME>",province_id: 45}, {_id:45003,name: "<NAME>",province_id: 45}, {_id:45004,name: "Alcabón",province_id: 45}, {_id:45005,name: "Alcañizo",province_id: 45}, {_id:45006,name: "<NAME> la Jara",province_id: 45}, {_id:45007,name: "<NAME>",province_id: 45}, {_id:45008,name: "<NAME>",province_id: 45}, {_id:45009,name: "<NAME>",province_id: 45}, {_id:45010,name: "<NAME>",province_id: 45}, {_id:45011,name: "<NAME>",province_id: 45}, {_id:45012,name: "<NAME>",province_id: 45}, {_id:45013,name: "Almorox",province_id: 45}, {_id:45014,name: "<NAME>",province_id: 45}, {_id:45015,name: "Arcicóllar",province_id: 45}, {_id:45016,name: "Argés",province_id: 45}, {_id:45017,name: "Azután",province_id: 45}, {_id:45018,name: "Barcience",province_id: 45}, {_id:45019,name: "Bargas",province_id: 45}, {_id:45020,name: "<NAME>",province_id: 45}, {_id:45021,name: "Borox",province_id: 45}, {_id:45022,name: "Buenaventura",province_id: 45}, {_id:45023,name: "<NAME>",province_id: 45}, {_id:45024,name: "Burujón",province_id: 45}, {_id:45025,name: "<NAME>",province_id: 45}, {_id:45026,name: "<NAME>",province_id: 45}, {_id:45027,name: "Cabezamesada",province_id: 45}, {_id:45028,name: "<NAME>",province_id: 45}, {_id:45029,name: "Caleruela",province_id: 45}, {_id:45030,name: "<NAME>",province_id: 45}, {_id:45031,name: "Camarena",province_id: 45}, {_id:45032,name: "Camarenilla",province_id: 45}, {_id:45033,name: "<NAME> (El)",province_id: 45}, {_id:45034,name: "Camuñas",province_id: 45}, {_id:45035,name: "<NAME>",province_id: 45}, {_id:45036,name: "Carmena",province_id: 45}, {_id:45037,name: "<NAME> (El)",province_id: 45}, {_id:45038,name: "Carranque",province_id: 45}, {_id:45039,name: "Carriches",province_id: 45}, {_id:45040,name: "<NAME> (El)",province_id: 45}, {_id:45041,name: "<NAME>",province_id: 45}, {_id:45042,name: "Casasbuenas",province_id: 45}, {_id:45043,name: "<NAME>",province_id: 45}, {_id:45045,name: "Cazalegas",province_id: 45}, {_id:45046,name: "Cebolla",province_id: 45}, {_id:45047,name: "<NAME>",province_id: 45}, {_id:45048,name: "<NAME>)",province_id: 45}, {_id:45049,name: "<NAME>",province_id: 45}, {_id:45050,name: "Ciruelos",province_id: 45}, {_id:45051,name: "Cobeja",province_id: 45}, {_id:45052,name: "Cobisa",province_id: 45}, {_id:45053,name: "Consuegra",province_id: 45}, {_id:45054,name: "<NAME>",province_id: 45}, {_id:45055,name: "Cuerva",province_id: 45}, {_id:45056,name: "<NAME>",province_id: 45}, {_id:45057,name: "Chueca",province_id: 45}, {_id:45058,name: "<NAME>",province_id: 45}, {_id:45059,name: "Dosbarrios",province_id: 45}, {_id:45060,name: "Erustes",province_id: 45}, {_id:45061,name: "Escalona",province_id: 45}, {_id:45062,name: "Escalonilla",province_id: 45}, {_id:45063,name: "<NAME>",province_id: 45}, {_id:45064,name: "Esquivias",province_id: 45}, {_id:45065,name: "Estrella (La)",province_id: 45}, {_id:45066,name: "Fuensalida",province_id: 45}, {_id:45067,name: "Gálvez",province_id: 45}, {_id:45068,name: "Garciotum",province_id: 45}, {_id:45069,name: "Gerindote",province_id: 45}, {_id:45070,name: "Guadamur",province_id: 45}, {_id:45071,name: "Guardia (La)",province_id: 45}, {_id:45072,name: "Herencias (Las)",province_id: 45}, {_id:45073,name: "<NAME>",province_id: 45}, {_id:45074,name: "<NAME>",province_id: 45}, {_id:45075,name: "Hontanar",province_id: 45}, {_id:45076,name: "Hormigos",province_id: 45}, {_id:45077,name: "Huecas",province_id: 45}, {_id:45078,name: "<NAME>",province_id: 45}, {_id:45079,name: "Iglesuela (La)",province_id: 45}, {_id:45080,name: "<NAME>",province_id: 45}, {_id:45081,name: "Illescas",province_id: 45}, {_id:45082,name: "Lagartera",province_id: 45}, {_id:45083,name: "Layos",province_id: 45}, {_id:45084,name: "Lillo",province_id: 45}, {_id:45085,name: "Lominchar",province_id: 45}, {_id:45086,name: "Lucillos",province_id: 45}, {_id:45087,name: "Madridejos",province_id: 45}, {_id:45088,name: "Magán",province_id: 45}, {_id:45089,name: "<NAME>",province_id: 45}, {_id:45090,name: "Manzaneque",province_id: 45}, {_id:45091,name: "Maqueda",province_id: 45}, {_id:45092,name: "Marjaliza",province_id: 45}, {_id:45093,name: "Marrupe",province_id: 45}, {_id:45094,name: "Mascaraque",province_id: 45}, {_id:45095,name: "Mata (La)",province_id: 45}, {_id:45096,name: "Mazarambroz",province_id: 45}, {_id:45097,name: "Mejorada",province_id: 45}, {_id:45098,name: "Menasalbas",province_id: 45}, {_id:45099,name: "Méntrida",province_id: 45}, {_id:45100,name: "<NAME>",province_id: 45}, {_id:45101,name: "<NAME>",province_id: 45}, {_id:45102,name: "Mocejón",province_id: 45}, {_id:45103,name: "<NAME>",province_id: 45}, {_id:45104,name: "Montearagón",province_id: 45}, {_id:45105,name: "Montesclaros",province_id: 45}, {_id:45106,name: "Mora",province_id: 45}, {_id:45107,name: "Nambroca",province_id: 45}, {_id:45108,name: "<NAME> (La)",province_id: 45}, {_id:45109,name: "Navahermosa",province_id: 45}, {_id:45110,name: "Navalcán",province_id: 45}, {_id:45111,name: "Navalmoralejo",province_id: 45}, {_id:44085,name: "Cosa",province_id: 44}, {_id:49133,name: "<NAME>",province_id: 49}, {_id:37218,name: "Navamorales",province_id: 37}, {_id:37219,name: "<NAME>",province_id: 37}, {_id:37221,name: "Navasfrías",province_id: 37}, {_id:37222,name: "Negrilla de Palencia",province_id: 37}, {_id:37223,name: "<NAME>",province_id: 37}, {_id:37224,name: "Orbada (La)",province_id: 37}, {_id:37225,name: "<NAME>una",province_id: 37}, {_id:37226,name: "Palacios del Arzobispo",province_id: 37}, {_id:37228,name: "Palaciosrubios",province_id: 37}, {_id:37229,name: "Palencia de Negrilla",province_id: 37}, {_id:37230,name: "Parada de Arriba",province_id: 37}, {_id:37231,name: "Parada de Rubiales",province_id: 37}, {_id:37232,name: "Paradinas de San Juan",province_id: 37}, {_id:37233,name: "Pastores",province_id: 37}, {_id:37234,name: "Payo (El)",province_id: 37}, {_id:37235,name: "<NAME>",province_id: 37}, {_id:37236,name: "<NAME>",province_id: 37}, {_id:37237,name: "<NAME>",province_id: 37}, {_id:37238,name: "<NAME>",province_id: 37}, {_id:37239,name: "<NAME> (El)",province_id: 37}, {_id:37240,name: "Pelabravo",province_id: 37}, {_id:37241,name: "Pelarrodríguez",province_id: 37}, {_id:37242,name: "Pelayos",province_id: 37}, {_id:37243,name: "Peña (La)",province_id: 37}, {_id:37244,name: "Peñacaballera",province_id: 37}, {_id:37245,name: "Peñaparda",province_id: 37}, {_id:37246,name: "<NAME>",province_id: 37}, {_id:37247,name: "Peñarandilla",province_id: 37}, {_id:37248,name: "<NAME>",province_id: 37}, {_id:37249,name: "<NAME>",province_id: 37}, {_id:37250,name: "<NAME>",province_id: 37}, {_id:37251,name: "Peromingo",province_id: 37}, {_id:37252,name: "Pinedas",province_id: 37}, {_id:37253,name: "<NAME> (El)",province_id: 37}, {_id:37254,name: "Pitiegua",province_id: 37}, {_id:37255,name: "Pizarral",province_id: 37}, {_id:37256,name: "<NAME>",province_id: 37}, {_id:37257,name: "<NAME>",province_id: 37}, {_id:37258,name: "<NAME>",province_id: 37}, {_id:37259,name: "<NAME>",province_id: 37}, {_id:37260,name: "<NAME>",province_id: 37}, {_id:37261,name: "<NAME>",province_id: 37}, {_id:37262,name: "Puertas",province_id: 37}, {_id:37263,name: "<NAME>",province_id: 37}, {_id:37264,name: "<NAME>",province_id: 37}, {_id:37265,name: "Rágama",province_id: 37}, {_id:37266,name: "Redonda (La)",province_id: 37}, {_id:37267,name: "Retortillo",province_id: 37}, {_id:37268,name: "<NAME> (La)",province_id: 37}, {_id:37269,name: "Robleda",province_id: 37}, {_id:37270,name: "<NAME>",province_id: 37}, {_id:37271,name: "Rollán",province_id: 37}, {_id:37272,name: "<NAME>",province_id: 37}, {_id:37273,name: "Sagrada (La)",province_id: 37}, {_id:37274,name: "Salamanca",province_id: 37}, {_id:37275,name: "Saldeana",province_id: 37}, {_id:37276,name: "Salmoral",province_id: 37}, {_id:37277,name: "<NAME>",province_id: 37}, {_id:37278,name: "<NAME>",province_id: 37}, {_id:43049,name: "<NAME>",province_id: 43}, {_id:43050,name: "Creixell",province_id: 43}, {_id:43051,name: "Cunit",province_id: 43}, {_id:43052,name: "Xerta",province_id: 43}, {_id:43053,name: "Duesaigües",province_id: 43}, {_id:43054,name: "<NAME> (L )",province_id: 43}, {_id:43055,name: "Falset",province_id: 43}, {_id:43056,name: "Fatarella (La)",province_id: 43}, {_id:43057,name: "Febró (La)",province_id: 43}, {_id:43058,name: "Figuera (La)",province_id: 43}, {_id:43059,name: "<NAME>",province_id: 43}, {_id:43060,name: "Flix",province_id: 43}, {_id:43061,name: "Forès",province_id: 43}, {_id:43062,name: "Freginals",province_id: 43}, {_id:43063,name: "Galera (La)",province_id: 43}, {_id:43064,name: "Gandesa",province_id: 43}, {_id:43065,name: "Garcia",province_id: 43}, {_id:43066,name: "Garidells (Els)",province_id: 43}, {_id:43067,name: "Ginestar",province_id: 43}, {_id:43068,name: "Godall",province_id: 43}, {_id:43069,name: "Gratallops",province_id: 43}, {_id:43070,name: "Guiamets (Els)",province_id: 43}, {_id:43071,name: "<NAME>",province_id: 43}, {_id:43072,name: "Lloar (El)",province_id: 43}, {_id:43073,name: "Llorac",province_id: 43}, {_id:43074,name: "<NAME>",province_id: 43}, {_id:43075,name: "Margalef",province_id: 43}, {_id:43076,name: "Marçà",province_id: 43}, {_id:43077,name: "<NAME>",province_id: 43}, {_id:43078,name: "Masdenverge",province_id: 43}, {_id:43079,name: "Masllorenç",province_id: 43}, {_id:43080,name: "Masó (La)",province_id: 43}, {_id:43081,name: "Maspujols",province_id: 43}, {_id:43082,name: "Masroig (El)",province_id: 43}, {_id:43083,name: "Milà (El)",province_id: 43}, {_id:43084,name: "Miravet",province_id: 43}, {_id:43085,name: "Molar (El)",province_id: 43}, {_id:43086,name: "Montblanc",province_id: 43}, {_id:43088,name: "<NAME>",province_id: 43}, {_id:43089,name: "Montferri",province_id: 43}, {_id:43090,name: "Montmell (El)",province_id: 43}, {_id:43091,name: "Mont-ral",province_id: 43}, {_id:43092,name: "<NAME>",province_id: 43}, {_id:43093,name: "<NAME>",province_id: 43}, {_id:43094,name: "<NAME>",province_id: 43}, {_id:43095,name: "Morell (El)",province_id: 43}, {_id:43096,name: "<NAME> (La)",province_id: 43}, {_id:43097,name: "<NAME> (La)",province_id: 43}, {_id:43098,name: "Nulles",province_id: 43}, {_id:43099,name: "<NAME> (La)",province_id: 43}, {_id:43100,name: "Pallaresos (Els)",province_id: 43}, {_id:43101,name: "<NAME>",province_id: 43}, {_id:43102,name: "Paüls",province_id: 43}, {_id:43103,name: "Perafort",province_id: 43}, {_id:43104,name: "Perelló (El)",province_id: 43}, {_id:43105,name: "Piles (Les)",province_id: 43}, {_id:43106,name: "<NAME> (El)",province_id: 43}, {_id:43107,name: "Pira",province_id: 43}, {_id:43108,name: "<NAME> (El)",province_id: 43}, {_id:43109,name: "<NAME> (La)",province_id: 43}, {_id:43110,name: "<NAME> (La)",province_id: 43}, {_id:43111,name: "<NAME> (La)",province_id: 43}, {_id:43112,name: "Poboleda",province_id: 43}, {_id:43113,name: "<NAME> (El)",province_id: 43}, {_id:43114,name: "Porrera",province_id: 43}, {_id:43115,name: "<NAME>",province_id: 43}, {_id:43116,name: "Prades",province_id: 43}, {_id:43117,name: "<NAME>",province_id: 43}, {_id:43118,name: "Pratdip",province_id: 43}, {_id:43119,name: "Puigpelat",province_id: 43}, {_id:43120,name: "Querol",province_id: 43}, {_id:43121,name: "Rasquera",province_id: 43}, {_id:43122,name: "Renau",province_id: 43}, {_id:43123,name: "Reus",province_id: 43}, {_id:43124,name: "Riba (La)",province_id: 43}, {_id:43125,name: "<NAME>",province_id: 43}, {_id:43126,name: "<NAME> (La)",province_id: 43}, {_id:43127,name: "Riudecanyes",province_id: 43}, {_id:43128,name: "Riudecols",province_id: 43}, {_id:43129,name: "Riudoms",province_id: 43}, {_id:43130,name: "<NAME>",province_id: 43}, {_id:43131,name: "<NAME>",province_id: 43}, {_id:43132,name: "Rodonyà",province_id: 43}, {_id:43133,name: "Roquetes",province_id: 43}, {_id:43134,name: "Rourell (El)",province_id: 43}, {_id:43135,name: "Salomó",province_id: 43}, {_id:43136,name: "<NAME>",province_id: 43}, {_id:43137,name: "<NAME>",province_id: 43}, {_id:43138,name: "<NAME>",province_id: 43}, {_id:43139,name: "<NAME>",province_id: 43}, {_id:43140,name: "<NAME>",province_id: 43}, {_id:43141,name: "Pontils",province_id: 43}, {_id:43142,name: "Sarral",province_id: 43}, {_id:43143,name: "<NAME>",province_id: 43}, {_id:43144,name: "Secuita (La)",province_id: 43}, {_id:43145,name: "<NAME> (La)",province_id: 43}, {_id:43146,name: "Senan",province_id: 43}, {_id:43147,name: "Solivella",province_id: 43}, {_id:43148,name: "Tarragona",province_id: 43}, {_id:43149,name: "Tivenys",province_id: 43}, {_id:43150,name: "Tivissa",province_id: 43}, {_id:43151,name: "<NAME> (La)",province_id: 43}, {_id:43152,name: "<NAME> (La)",province_id: 43}, {_id:43153,name: "Torredembarra",province_id: 43}, {_id:43154,name: "<NAME>",province_id: 43}, {_id:43155,name: "Tortosa",province_id: 43}, {_id:43156,name: "Ulldecona",province_id: 43}, {_id:43157,name: "Ulldemolins",province_id: 43}, {_id:43158,name: "Vallclara",province_id: 43}, {_id:43159,name: "<NAME>",province_id: 43}, {_id:43160,name: "Vallmoll",province_id: 43}, {_id:43161,name: "Valls",province_id: 43}, {_id:43162,name: "Vandellòs i l Hospitalet de l Infant",province_id: 43}, {_id:43163,name: "Vendrell (El)",province_id: 43}, {_id:43164,name: "<NAME>",province_id: 43}, {_id:43165,name: "Vilabella",province_id: 43}, {_id:43166,name: "<NAME>",province_id: 43}, {_id:43167,name: "<NAME>",province_id: 43}, {_id:43168,name: "<NAME>",province_id: 43}, {_id:43169,name: "Vilaplana",province_id: 43}, {_id:43170,name: "Vila-rodona",province_id: 43}, {_id:43171,name: "Vila-seca",province_id: 43}, {_id:43172,name: "Vilaverd",province_id: 43}, {_id:43173,name: "<NAME> (La)",province_id: 43}, {_id:43174,name: "<NAME> (La)",province_id: 43}, {_id:43175,name: "<NAME>",province_id: 43}, {_id:43176,name: "Vimbodí",province_id: 43}, {_id:43177,name: "Vinebre",province_id: 43}, {_id:43178,name: "Vinyols i els Arcs",province_id: 43}, {_id:43901,name: "Deltebre",province_id: 43}, {_id:43902,name: "<NAME>",province_id: 43}, {_id:43903,name: "Camarles",province_id: 43}, {_id:43904,name: "Aldea (L )",province_id: 43}, {_id:43905,name: "Salou",province_id: 43}, {_id:43906,name: "Ampolla (L )",province_id: 43}, {_id:44001,name: "Ababuj",province_id: 44}, {_id:44002,name: "Abejuela",province_id: 44}, {_id:44003,name: "Aguatón",province_id: 44}, {_id:44004,name: "Aguaviva",province_id: 44}, {_id:44005,name: "<NAME>",province_id: 44}, {_id:44006,name: "Alacón",province_id: 44}, {_id:44007,name: "Alba",province_id: 44}, {_id:44008,name: "<NAME>",province_id: 44}, {_id:44009,name: "Albarracín",province_id: 44}, {_id:44010,name: "Albentosa",province_id: 44}, {_id:44011,name: "Alcaine",province_id: 44}, {_id:44012,name: "<NAME>",province_id: 44}, {_id:44013,name: "Alcañiz",province_id: 44}, {_id:44014,name: "Alcorisa",province_id: 44}, {_id:44016,name: "Alfambra",province_id: 44}, {_id:44017,name: "Aliaga",province_id: 44}, {_id:44018,name: "Almohaja",province_id: 44}, {_id:44019,name: "Alobras",province_id: 44}, {_id:44020,name: "Alpeñés",province_id: 44}, {_id:44021,name: "Allepuz",province_id: 44}, {_id:44022,name: "Alloza",province_id: 44}, {_id:44023,name: "Allueva",province_id: 44}, {_id:44024,name: "Anadón",province_id: 44}, {_id:44025,name: "Andorra",province_id: 44}, {_id:44026,name: "<NAME>",province_id: 44}, {_id:44027,name: "<NAME>",province_id: 44}, {_id:44028,name: "Argente",province_id: 44}, {_id:44029,name: "Ariño",province_id: 44}, {_id:44031,name: "Azaila",province_id: 44}, {_id:44032,name: "Bádenas",province_id: 44}, {_id:44033,name: "Báguena",province_id: 44}, {_id:44034,name: "Bañón",province_id: 44}, {_id:44035,name: "Barrachina",province_id: 44}, {_id:44036,name: "Bea",province_id: 44}, {_id:44037,name: "Beceite",province_id: 44}, {_id:44038,name: "<NAME>",province_id: 44}, {_id:44039,name: "Bello",province_id: 44}, {_id:44040,name: "Berge",province_id: 44}, {_id:44041,name: "Bezas",province_id: 44}, {_id:44042,name: "Blancas",province_id: 44}, {_id:44043,name: "Blesa",province_id: 44}, {_id:44044,name: "Bordón",province_id: 44}, {_id:44045,name: "Bronchales",province_id: 44}, {_id:44046,name: "Bueña",province_id: 44}, {_id:44047,name: "Burbáguena",province_id: 44}, {_id:44048,name: "<NAME>",province_id: 44}, {_id:44049,name: "Calaceite",province_id: 44}, {_id:44050,name: "Calamocha",province_id: 44}, {_id:44051,name: "Calanda",province_id: 44}, {_id:42189,name: "Ucero",province_id: 42}, {_id:44052,name: "Calomarde",province_id: 44}, {_id:44053,name: "Camañas",province_id: 44}, {_id:44054,name: "<NAME>",province_id: 44}, {_id:44055,name: "Camarillas",province_id: 44}, {_id:44056,name: "Caminreal",province_id: 44}, {_id:44059,name: "Cantavieja",province_id: 44}, {_id:44060,name: "<NAME>",province_id: 44}, {_id:44061,name: "<NAME> (La)",province_id: 44}, {_id:44062,name: "<NAME>",province_id: 44}, {_id:44063,name: "<NAME>",province_id: 44}, {_id:44064,name: "<NAME>",province_id: 44}, {_id:44065,name: "<NAME>",province_id: 44}, {_id:44066,name: "<NAME>",province_id: 44}, {_id:44067,name: "Castelnou",province_id: 44}, {_id:44068,name: "Castelserás",province_id: 44}, {_id:44070,name: "Castellar (El)",province_id: 44}, {_id:44071,name: "Castellote",province_id: 44}, {_id:44074,name: "Cedrillas",province_id: 44}, {_id:44075,name: "Celadas",province_id: 44}, {_id:44076,name: "Cella",province_id: 44}, {_id:44077,name: "Cerollera (La)",province_id: 44}, {_id:44080,name: "Codoñera (La)",province_id: 44}, {_id:44082,name: "Corbalán",province_id: 44}, {_id:44084,name: "<NAME>",province_id: 44}, {_id:31106,name: "Fontellas",province_id: 31}, {_id:31107,name: "Funes",province_id: 31}, {_id:31108,name: "Fustiñana",province_id: 31}, {_id:31109,name: "Galar",province_id: 31}, {_id:31110,name: "Gallipienzo",province_id: 31}, {_id:31111,name: "Gallués/Galoze",province_id: 31}, {_id:31112,name: "Garaioa",province_id: 31}, {_id:31113,name: "Garde",province_id: 31}, {_id:31114,name: "Garínoain",province_id: 31}, {_id:31115,name: "Garralda",province_id: 31}, {_id:31116,name: "Genevilla",province_id: 31}, {_id:31117,name: "Goizueta",province_id: 31}, {_id:31118,name: "Goñi",province_id: 31}, {_id:31119,name: "Güesa/Gorza",province_id: 31}, {_id:31120,name: "Guesálaz",province_id: 31}, {_id:31121,name: "Guirguillano",province_id: 31}, {_id:31122,name: "Huarte/Uharte",province_id: 31}, {_id:31123,name: "Uharte-Arakil",province_id: 31}, {_id:31124,name: "Ibargoiti",province_id: 31}, {_id:31125,name: "Igúzquiza",province_id: 31}, {_id:31126,name: "Imotz",province_id: 31}, {_id:31127,name: "Irañeta",province_id: 31}, {_id:31128,name: "Isaba/Izaba",province_id: 31}, {_id:31129,name: "Ituren",province_id: 31}, {_id:31130,name: "Iturmendi",province_id: 31}, {_id:31131,name: "Iza",province_id: 31}, {_id:31132,name: "Izagaondoa",province_id: 31}, {_id:31133,name: "Izalzu/Itzaltzu",province_id: 31}, {_id:31134,name: "Jaurrieta",province_id: 31}, {_id:31135,name: "Javier",province_id: 31}, {_id:31136,name: "Juslapeña",province_id: 31}, {_id:31137,name: "Beintza-Labaien",province_id: 31}, {_id:31138,name: "Lakuntza",province_id: 31}, {_id:31139,name: "Lana",province_id: 31}, {_id:31140,name: "Lantz",province_id: 31}, {_id:31141,name: "Lapoblación",province_id: 31}, {_id:31142,name: "Larraga",province_id: 31}, {_id:31143,name: "Larraona",province_id: 31}, {_id:31144,name: "Larraun",province_id: 31}, {_id:31145,name: "Lazagurría",province_id: 31}, {_id:31146,name: "Leache",province_id: 31}, {_id:31147,name: "Legarda",province_id: 31}, {_id:31148,name: "Legaria",province_id: 31}, {_id:31149,name: "Leitza",province_id: 31}, {_id:31150,name: "Leoz",province_id: 31}, {_id:31151,name: "Lerga",province_id: 31}, {_id:31152,name: "Lerín",province_id: 31}, {_id:31153,name: "Lesaka",province_id: 31}, {_id:31154,name: "Lezáun",province_id: 31}, {_id:31155,name: "Liédena",province_id: 31}, {_id:31156,name: "Lizoáin",province_id: 31}, {_id:31157,name: "Lodosa",province_id: 31}, {_id:31158,name: "Lónguida/Longida",province_id: 31}, {_id:31159,name: "Lumbier",province_id: 31}, {_id:31160,name: "Luquin",province_id: 31}, {_id:31161,name: "Mañeru",province_id: 31}, {_id:31162,name: "Marañón",province_id: 31}, {_id:31163,name: "Marcilla",province_id: 31}, {_id:31164,name: "Mélida",province_id: 31}, {_id:31165,name: "Mendavia",province_id: 31}, {_id:31166,name: "Mendaza",province_id: 31}, {_id:31167,name: "Mendigorría",province_id: 31}, {_id:31168,name: "Metauten",province_id: 31}, {_id:31169,name: "Milagro",province_id: 31}, {_id:31170,name: "Mirafuentes",province_id: 31}, {_id:31171,name: "<NAME>",province_id: 31}, {_id:31172,name: "Monreal",province_id: 31}, {_id:31173,name: "Monteagudo",province_id: 31}, {_id:31174,name: "Morentin",province_id: 31}, {_id:31175,name: "Mues",province_id: 31}, {_id:31176,name: "Murchante",province_id: 31}, {_id:31177,name: "Murieta",province_id: 31}, {_id:31178,name: "<NAME>",province_id: 31}, {_id:31179,name: "<NAME>",province_id: 31}, {_id:31180,name: "Muruzábal",province_id: 31}, {_id:31181,name: "Navascués",province_id: 31}, {_id:31182,name: "Nazar",province_id: 31}, {_id:31183,name: "Obanos",province_id: 31}, {_id:31184,name: "Oco",province_id: 31}, {_id:31185,name: "Ochagavía",province_id: 31}, {_id:31186,name: "Odieta",province_id: 31}, {_id:31187,name: "Oitz",province_id: 31}, {_id:31188,name: "Olaibar",province_id: 31}, {_id:31189,name: "Olazti/Olazagutía",province_id: 31}, {_id:31190,name: "Olejua",province_id: 31}, {_id:31191,name: "Olite",province_id: 31}, {_id:31192,name: "Olóriz",province_id: 31}, {_id:31193,name: "Olza",province_id: 31}, {_id:41063,name: "Molares (Los)",province_id: 41}, {_id:41064,name: "Montellano",province_id: 41}, {_id:41065,name: "<NAME>",province_id: 41}, {_id:41066,name: "<NAME> (Las)",province_id: 41}, {_id:41067,name: "Olivares",province_id: 41}, {_id:41068,name: "Osuna",province_id: 41}, {_id:41069,name: "<NAME> (Los)",province_id: 41}, {_id:41070,name: "<NAME>",province_id: 41}, {_id:41071,name: "Paradas",province_id: 41}, {_id:41072,name: "Pedrera",province_id: 41}, {_id:41073,name: "Pedroso (El)",province_id: 41}, {_id:41074,name: "Peñaflor",province_id: 41}, {_id:41075,name: "Pilas",province_id: 41}, {_id:41076,name: "Pruna",province_id: 41}, {_id:41077,name: "<NAME> (La)",province_id: 41}, {_id:41078,name: "Puebla de los Infantes (La)",province_id: 41}, {_id:41079,name: "<NAME> (La)",province_id: 41}, {_id:41080,name: "<NAME> (El)",province_id: 41}, {_id:41081,name: "Rinconada (La)",province_id: 41}, {_id:41082,name: "<NAME> (La)",province_id: 41}, {_id:41083,name: "Ronquillo (El)",province_id: 41}, {_id:41084,name: "Rubio (El)",province_id: 41}, {_id:41085,name: "Salteras",province_id: 41}, {_id:41086,name: "<NAME>",province_id: 41}, {_id:41087,name: "<NAME>",province_id: 41}, {_id:41088,name: "<NAME>",province_id: 41}, {_id:41089,name: "Santiponce",province_id: 41}, {_id:41090,name: "Saucejo (El)",province_id: 41}, {_id:41091,name: "Sevilla",province_id: 41}, {_id:41092,name: "Tocina",province_id: 41}, {_id:41093,name: "Tomares",province_id: 41}, {_id:41094,name: "Umbrete",province_id: 41}, {_id:41095,name: "Utrera",province_id: 41}, {_id:41096,name: "<NAME>",province_id: 41}, {_id:41097,name: "<NAME>",province_id: 41}, {_id:41098,name: "<NAME>",province_id: 41}, {_id:41099,name: "Villanueva del Río y Minas",province_id: 41}, {_id:41100,name: "<NAME>",province_id: 41}, {_id:41101,name: "<NAME>",province_id: 41}, {_id:41102,name: "<NAME> (El)",province_id: 41}, {_id:41901,name: "<NAME>",province_id: 41}, {_id:41902,name: "<NAME>",province_id: 41}, {_id:41903,name: "<NAME> (El)",province_id: 41}, {_id:42001,name: "Abejar",province_id: 42}, {_id:42003,name: "Adradas",province_id: 42}, {_id:42004,name: "Ágreda",province_id: 42}, {_id:42006,name: "Alconaba",province_id: 42}, {_id:42007,name: "<NAME>",province_id: 42}, {_id:42008,name: "<NAME>",province_id: 42}, {_id:42009,name: "Aldealafuente",province_id: 42}, {_id:42010,name: "Aldealices",province_id: 42}, {_id:42011,name: "Aldealpozo",province_id: 42}, {_id:42012,name: "Aldealseñor",province_id: 42}, {_id:42013,name: "<NAME>",province_id: 42}, {_id:42014,name: "Aldehuelas (Las)",province_id: 42}, {_id:42015,name: "Alentisque",province_id: 42}, {_id:42016,name: "Aliud",province_id: 42}, {_id:42017,name: "Almajano",province_id: 42}, {_id:42018,name: "Almaluez",province_id: 42}, {_id:42019,name: "Almarza",province_id: 42}, {_id:42020,name: "Almazán",province_id: 42}, {_id:42021,name: "Almazul",province_id: 42}, {_id:42022,name: "<NAME>",province_id: 42}, {_id:42023,name: "Alpanseque",province_id: 42}, {_id:42024,name: "Arancón",province_id: 42}, {_id:42025,name: "<NAME>",province_id: 42}, {_id:42026,name: "Arenillas",province_id: 42}, {_id:42027,name: "<NAME>",province_id: 42}, {_id:42028,name: "<NAME>",province_id: 42}, {_id:42029,name: "Baraona",province_id: 42}, {_id:42030,name: "Barca",province_id: 42}, {_id:42031,name: "Barcones",province_id: 42}, {_id:42032,name: "<NAME>",province_id: 42}, {_id:42033,name: "<NAME>",province_id: 42}, {_id:42034,name: "Beratón",province_id: 42}, {_id:42035,name: "<NAME>",province_id: 42}, {_id:42036,name: "Blacos",province_id: 42}, {_id:42037,name: "Bliecos",province_id: 42}, {_id:42038,name: "Borjabad",province_id: 42}, {_id:42039,name: "Borobia",province_id: 42}, {_id:42041,name: "Buberos",province_id: 42}, {_id:42042,name: "Buitrago",province_id: 42}, {_id:42043,name: "<NAME>-Ciudad de Osma",province_id: 42}, {_id:42044,name: "<NAME>",province_id: 42}, {_id:42045,name: "<NAME>",province_id: 42}, {_id:42046,name: "Calatañazor",province_id: 42}, {_id:42048,name: "Caltojar",province_id: 42}, {_id:42049,name: "Candilichera",province_id: 42}, {_id:42050,name: "Cañamaque",province_id: 42}, {_id:42051,name: "Carabantes",province_id: 42}, {_id:42052,name: "Caracena",province_id: 42}, {_id:42053,name: "<NAME>",province_id: 42}, {_id:42054,name: "<NAME>",province_id: 42}, {_id:42055,name: "Casarejos",province_id: 42}, {_id:42056,name: "<NAME>",province_id: 42}, {_id:42057,name: "Castilruiz",province_id: 42}, {_id:42058,name: "<NAME>",province_id: 42}, {_id:42059,name: "<NAME>",province_id: 42}, {_id:42060,name: "Cerbón",province_id: 42}, {_id:42061,name: "Cidones",province_id: 42}, {_id:42062,name: "Cigudosa",province_id: 42}, {_id:42063,name: "Cihuela",province_id: 42}, {_id:42064,name: "Ciria",province_id: 42}, {_id:42065,name: "<NAME>",province_id: 42}, {_id:42068,name: "Coscurita",province_id: 42}, {_id:42069,name: "Covaleda",province_id: 42}, {_id:42070,name: "Cubilla",province_id: 42}, {_id:42071,name: "<NAME> Solana",province_id: 42}, {_id:42073,name: "<NAME>",province_id: 42}, {_id:42075,name: "Dévanos",province_id: 42}, {_id:42076,name: "Deza",province_id: 42}, {_id:42078,name: "<NAME>",province_id: 42}, {_id:42079,name: "<NAME>",province_id: 42}, {_id:42080,name: "<NAME>",province_id: 42}, {_id:42081,name: "Espejón",province_id: 42}, {_id:42082,name: "<NAME>",province_id: 42}, {_id:42083,name: "<NAME>",province_id: 42}, {_id:42084,name: "<NAME>",province_id: 42}, {_id:42085,name: "Fuentearmegil",province_id: 42}, {_id:42086,name: "Fuentecambrón",province_id: 42}, {_id:42087,name: "Fuentecantos",province_id: 42}, {_id:42088,name: "Fuentelmonge",province_id: 42}, {_id:42089,name: "<NAME>",province_id: 42}, {_id:42090,name: "Fuentepinilla",province_id: 42}, {_id:42092,name: "<NAME>",province_id: 42}, {_id:42093,name: "Fuentestrún",province_id: 42}, {_id:42094,name: "Garray",province_id: 42}, {_id:42095,name: "Golmayo",province_id: 42}, {_id:42096,name: "Gómara",province_id: 42}, {_id:42097,name: "Gormaz",province_id: 42}, {_id:42098,name: "<NAME>",province_id: 42}, {_id:42100,name: "<NAME>",province_id: 42}, {_id:42103,name: "<NAME>",province_id: 42}, {_id:42105,name: "Liceras",province_id: 42}, {_id:42106,name: "<NAME>)",province_id: 42}, {_id:42107,name: "Magaña",province_id: 42}, {_id:42108,name: "Maján",province_id: 42}, {_id:42110,name: "Matalebreras",province_id: 42}, {_id:42111,name: "<NAME>",province_id: 42}, {_id:42113,name: "Medinaceli",province_id: 42}, {_id:42115,name: "<NAME>",province_id: 42}, {_id:42116,name: "<NAME>",province_id: 42}, {_id:42117,name: "<NAME>",province_id: 42}, {_id:42118,name: "Momblona",province_id: 42}, {_id:42119,name: "<NAME>",province_id: 42}, {_id:42120,name: "<NAME>",province_id: 42}, {_id:42121,name: "<NAME>",province_id: 42}, {_id:42123,name: "<NAME>",province_id: 42}, {_id:42124,name: "<NAME>",province_id: 42}, {_id:42125,name: "<NAME>",province_id: 42}, {_id:42127,name: "<NAME>",province_id: 42}, {_id:42128,name: "Narros",province_id: 42}, {_id:42129,name: "Navaleno",province_id: 42}, {_id:42130,name: "Nepas",province_id: 42}, {_id:42131,name: "Nolay",province_id: 42}, {_id:42132,name: "Noviercas",province_id: 42}, {_id:42134,name: "Ólvega",province_id: 42}, {_id:42135,name: "Oncala",province_id: 42}, {_id:42139,name: "<NAME>",province_id: 42}, {_id:42140,name: "<NAME>",province_id: 42}, {_id:42141,name: "<NAME> (La)",province_id: 42}, {_id:42142,name: "Pozalmuro",province_id: 42}, {_id:42144,name: "<NAME>",province_id: 42}, {_id:42145,name: "<NAME>",province_id: 42}, {_id:42148,name: "Quiñonería",province_id: 42}, {_id:42149,name: "Rábanos (Los)",province_id: 42}, {_id:42151,name: "Rebollar",province_id: 42}, {_id:42152,name: "Recuerda",province_id: 42}, {_id:42153,name: "Rello",province_id: 42}, {_id:42154,name: "Renieblas",province_id: 42}, {_id:42155,name: "<NAME>",province_id: 42}, {_id:42156,name: "Reznos",province_id: 42}, {_id:42157,name: "<NAME> (La)",province_id: 42}, {_id:42158,name: "<NAME>",province_id: 42}, {_id:42159,name: "Rollamienta",province_id: 42}, {_id:42160,name: "Royo (El)",province_id: 42}, {_id:42161,name: "Salduero",province_id: 42}, {_id:42162,name: "<NAME>",province_id: 42}, {_id:42163,name: "<NAME>",province_id: 42}, {_id:42164,name: "<NAME>",province_id: 42}, {_id:42165,name: "<NAME>",province_id: 42}, {_id:42166,name: "<NAME>",province_id: 42}, {_id:42167,name: "<NAME>",province_id: 42}, {_id:42168,name: "<NAME>",province_id: 42}, {_id:42171,name: "<NAME>",province_id: 42}, {_id:42172,name: "Soliedra",province_id: 42}, {_id:42173,name: "Soria",province_id: 42}, {_id:42174,name: "<NAME>",province_id: 42}, {_id:42175,name: "Suellacabras",province_id: 42}, {_id:42176,name: "Tajahuerce",province_id: 42}, {_id:42177,name: "Tajueco",province_id: 42}, {_id:42178,name: "Talveila",province_id: 42}, {_id:42181,name: "Tardelcuende",province_id: 42}, {_id:42182,name: "Taroda",province_id: 42}, {_id:42183,name: "Tejado",province_id: 42}, {_id:42184,name: "Torlengua",province_id: 42}, {_id:42185,name: "Torreblacos",province_id: 42}, {_id:42187,name: "<NAME>",province_id: 42}, {_id:42188,name: "Trévago",province_id: 42}, {_id:42190,name: "Vadillo",province_id: 42}, {_id:42191,name: "<NAME>",province_id: 42}, {_id:42192,name: "Valdegeña",province_id: 42}, {_id:42193,name: "<NAME>",province_id: 42}, {_id:42194,name: "Valdemaluque",province_id: 42}, {_id:42195,name: "Valdenebro",province_id: 42}, {_id:42196,name: "Valdeprado",province_id: 42}, {_id:42197,name: "Valderrodilla",province_id: 42}, {_id:42198,name: "Valtajeros",province_id: 42}, {_id:42200,name: "Velamazán",province_id: 42}, {_id:42201,name: "<NAME>",province_id: 42}, {_id:42202,name: "<NAME>",province_id: 42}, {_id:42204,name: "<NAME>",province_id: 42}, {_id:42205,name: "Villaciervos",province_id: 42}, {_id:42206,name: "<NAME>",province_id: 42}, {_id:42207,name: "<NAME>",province_id: 42}, {_id:42208,name: "<NAME>",province_id: 42}, {_id:42209,name: "<NAME>",province_id: 42}, {_id:42211,name: "<NAME> (Los)",province_id: 42}, {_id:42212,name: "Villasayas",province_id: 42}, {_id:42213,name: "<NAME>",province_id: 42}, {_id:42215,name: "Vinuesa",province_id: 42}, {_id:42216,name: "Vizmanos",province_id: 42}, {_id:42217,name: "Vozmediano",province_id: 42}, {_id:42218,name: "Yanguas",province_id: 42}, {_id:42219,name: "Yelo",province_id: 42}, {_id:43001,name: "Aiguamúrcia",province_id: 43}, {_id:43002,name: "Albinyana",province_id: 43}, {_id:43003,name: "Albiol (L )",province_id: 43}, {_id:43004,name: "Alcanar",province_id: 43}, {_id:43005,name: "Alcover",province_id: 43}, {_id:43006,name: "Aldover",province_id: 43}, {_id:43007,name: "Aleixar (L )",province_id: 43}, {_id:43008,name: "<NAME>",province_id: 43}, {_id:43009,name: "Alforja",province_id: 43}, {_id:43010,name: "Alió",province_id: 43}, {_id:43011,name: "Almoster",province_id: 43}, {_id:43012,name: "Altafulla",province_id: 43}, {_id:43013,name: "<NAME> (L )",province_id: 43}, {_id:43014,name: "Amposta",province_id: 43}, {_id:43015,name: "Arbolí",province_id: 43}, {_id:43016,name: "Arboç (L )",province_id: 43}, {_id:43017,name: "Argentera (L )",province_id: 43}, {_id:43018,name: "Arnes",province_id: 43}, {_id:43019,name: "Ascó",province_id: 43}, {_id:43020,name: "<NAME>",province_id: 43}, {_id:43021,name: "<NAME>",province_id: 43}, {_id:43022,name: "Batea",province_id: 43}, {_id:43023,name: "<NAME>",province_id: 43}, {_id:43024,name: "Bellvei",province_id: 43}, {_id:43025,name: "Benifallet",province_id: 43}, {_id:43026,name: "Benissanet",province_id: 43}, {_id:43027,name: "<NAME> (La)",province_id: 43}, {_id:43028,name: "<NAME> (La)",province_id: 43}, {_id:43029,name: "Blancafort",province_id: 43}, {_id:43030,name: "Bonastre",province_id: 43}, {_id:43031,name: "<NAME> (Les)",province_id: 43}, {_id:43032,name: "Bot",province_id: 43}, {_id:43033,name: "Botarell",province_id: 43}, {_id:43034,name: "Bràfim",province_id: 43}, {_id:43035,name: "Cabacés",province_id: 43}, {_id:43036,name: "<NAME>",province_id: 43}, {_id:43037,name: "Calafell",province_id: 43}, {_id:43038,name: "Cambrils",province_id: 43}, {_id:43039,name: "Capafonts",province_id: 43}, {_id:43040,name: "Capçanes",province_id: 43}, {_id:43041,name: "Caseres",province_id: 43}, {_id:43042,name: "<NAME>",province_id: 43}, {_id:43043,name: "Catllar (El)",province_id: 43}, {_id:43044,name: "Sénia (La)",province_id: 43}, {_id:43045,name: "Colldejou",province_id: 43}, {_id:43046,name: "Conesa",province_id: 43}, {_id:43047,name: "Constantí",province_id: 43}, {_id:43048,name: "<NAME>",province_id: 43}, {_id:49214,name: "Tábara",province_id: 49}, {_id:50188,name: "NAMEvilla",province_id: 50}, {_id:50189,name: "Nonaspe",province_id: 50}, {_id:50190,name: "Novallas",province_id: 50}, {_id:50191,name: "Novillas",province_id: 50}, {_id:50192,name: "Nuévalos",province_id: 50}, {_id:50193,name: "<NAME>",province_id: 50}, {_id:50194,name: "Olvés",province_id: 50}, {_id:50195,name: "Orcajo",province_id: 50}, {_id:50196,name: "Orera",province_id: 50}, {_id:50197,name: "Orés",province_id: 50}, {_id:50198,name: "Oseja",province_id: 50}, {_id:50199,name: "<NAME>",province_id: 50}, {_id:50200,name: "Paniza",province_id: 50}, {_id:50201,name: "<NAME>",province_id: 50}, {_id:50202,name: "<NAME>",province_id: 50}, {_id:50203,name: "Pastriz",province_id: 50}, {_id:50204,name: "Pedrola",province_id: 50}, {_id:50205,name: "Pedrosas (Las)",province_id: 50}, {_id:50206,name: "Perdiguera",province_id: 50}, {_id:50207,name: "Piedratajada",province_id: 50}, {_id:50208,name: "<NAME>",province_id: 50}, {_id:50209,name: "Pinseque",province_id: 50}, {_id:50210,name: "Pintanos (Los)",province_id: 50}, {_id:50211,name: "<NAME>",province_id: 50}, {_id:50212,name: "Pleitas",province_id: 50}, {_id:50213,name: "Plenas",province_id: 50}, {_id:50214,name: "Pomer",province_id: 50}, {_id:50215,name: "<NAME>",province_id: 50}, {_id:50216,name: "<NAME>",province_id: 50}, {_id:50217,name: "<NAME>",province_id: 50}, {_id:50218,name: "<NAME>",province_id: 50}, {_id:50219,name: "<NAME> (La)",province_id: 50}, {_id:50220,name: "Puendeluna",province_id: 50}, {_id:50221,name: "Purujosa",province_id: 50}, {_id:50222,name: "Quinto",province_id: 50}, {_id:50223,name: "Remolinos",province_id: 50}, {_id:50224,name: "Retascón",province_id: 50}, {_id:50225,name: "Ricla",province_id: 50}, {_id:50227,name: "Romanos",province_id: 50}, {_id:50228,name: "<NAME>",province_id: 50}, {_id:50229,name: "Ruesca",province_id: 50}, {_id:50230,name: "Sádaba",province_id: 50}, {_id:50231,name: "<NAME>",province_id: 50}, {_id:50232,name: "<NAME>",province_id: 50}, {_id:50233,name: "<NAME>",province_id: 50}, {_id:50234,name: "<NAME>",province_id: 50}, {_id:50235,name: "<NAME>",province_id: 50}, {_id:50236,name: "<NAME>",province_id: 50}, {_id:50237,name: "<NAME>",province_id: 50}, {_id:50238,name: "<NAME>",province_id: 50}, {_id:50239,name: "Santed",province_id: 50}, {_id:50240,name: "Sástago",province_id: 50}, {_id:50241,name: "Sabiñán",province_id: 50}, {_id:50242,name: "Sediles",province_id: 50}, {_id:50243,name: "Sestrica",province_id: 50}, {_id:50244,name: "<NAME>",province_id: 50}, {_id:50245,name: "Sigüés",province_id: 50}, {_id:50246,name: "Sisamón",province_id: 50}, {_id:50248,name: "<NAME>",province_id: 50}, {_id:50249,name: "Tabuenca",province_id: 50}, {_id:50250,name: "Talamantes",province_id: 50}, {_id:50251,name: "Tarazona",province_id: 50}, {_id:50252,name: "Tauste",province_id: 50}, {_id:50253,name: "Terrer",province_id: 50}, {_id:50254,name: "Tierga",province_id: 50}, {_id:50255,name: "Tobed",province_id: 50}, {_id:50256,name: "<NAME>",province_id: 50}, {_id:50257,name: "<NAME>",province_id: 50}, {_id:50258,name: "Torralbilla",province_id: 50}, {_id:50259,name: "Torrehermosa",province_id: 50}, {_id:50260,name: "Torrelapaja",province_id: 50}, {_id:50261,name: "Torrellas",province_id: 50}, {_id:50262,name: "<NAME>",province_id: 50}, {_id:50263,name: "<NAME>",province_id: 50}, {_id:50264,name: "Tosos",province_id: 50}, {_id:50265,name: "Trasmoz",province_id: 50}, {_id:50266,name: "Trasobares",province_id: 50}, {_id:50267,name: "Uncastillo",province_id: 50}, {_id:50268,name: "<NAME>",province_id: 50}, {_id:50269,name: "<NAME>",province_id: 50}, {_id:50270,name: "Urriés",province_id: 50}, {_id:50271,name: "Used",province_id: 50}, {_id:50272,name: "Utebo",province_id: 50}, {_id:50273,name: "Valdehorna",province_id: 50}, {_id:50274,name: "<NAME>",province_id: 50}, {_id:50275,name: "Valmadrid",province_id: 50}, {_id:50276,name: "Valpalmas",province_id: 50}, {_id:50277,name: "Valtorres",province_id: 50}, {_id:50278,name: "<NAME>",province_id: 50}, {_id:50279,name: "<NAME>",province_id: 50}, {_id:50280,name: "<NAME>",province_id: 50}, {_id:50281,name: "Vierlas",province_id: 50}, {_id:50282,name: "Vilueña (La)",province_id: 50}, {_id:50283,name: "Villadoz",province_id: 50}, {_id:50284,name: "Villafeliche",province_id: 50}, {_id:50285,name: "<NAME>",province_id: 50}, {_id:50286,name: "<NAME>",province_id: 50}, {_id:50287,name: "Villalengua",province_id: 50}, {_id:50288,name: "<NAME>",province_id: 50}, {_id:50289,name: "<NAME>",province_id: 50}, {_id:50290,name: "<NAME>",province_id: 50}, {_id:50291,name: "<NAME>",province_id: 50}, {_id:50292,name: "<NAME>",province_id: 50}, {_id:50293,name: "<NAME>",province_id: 50}, {_id:50294,name: "<NAME>",province_id: 50}, {_id:50295,name: "Vistabella",province_id: 50}, {_id:50296,name: "Zaida (La)",province_id: 50}, {_id:50297,name: "Zaragoza",province_id: 50}, {_id:50298,name: "Zuera",province_id: 50}, {_id:50901,name: "Biel",province_id: 50}, {_id:50902,name: "Marracos",province_id: 50}, {_id:51001,name: "Ceuta",province_id: 51}, {_id:52001,name: "Melilla",province_id: 52}, {_id:35200,name: "<NAME>",province_id: 35}, {_id:49216,name: "Tapioles",province_id: 49}, {_id:49219,name: "Toro",province_id: 49}, {_id:49220,name: "<NAME>)",province_id: 49}, {_id:49221,name: "Torregamones",province_id: 49}, {_id:49222,name: "<NAME>",province_id: 49}, {_id:49223,name: "Trabazos",province_id: 49}, {_id:49224,name: "Trefacio",province_id: 49}, {_id:49225,name: "<NAME>",province_id: 49}, {_id:49226,name: "<NAME>",province_id: 49}, {_id:49227,name: "Valcabado",province_id: 49}, {_id:49228,name: "Valdefinjas",province_id: 49}, {_id:49229,name: "Valdescorriel",province_id: 49}, {_id:49230,name: "<NAME>",province_id: 49}, {_id:49231,name: "<NAME>",province_id: 49}, {_id:49232,name: "<NAME>",province_id: 49}, {_id:49233,name: "Vegalatrave",province_id: 49}, {_id:49234,name: "Venialbo",province_id: 49}, {_id:49235,name: "Vezdemarbán",province_id: 49}, {_id:49236,name: "Vidayanes",province_id: 49}, {_id:49237,name: "Videmala",province_id: 49}, {_id:49238,name: "Villabrázaro",province_id: 49}, {_id:49239,name: "<NAME>",province_id: 49}, {_id:49240,name: "Villadepera",province_id: 49}, {_id:49241,name: "Villaescusa",province_id: 49}, {_id:49242,name: "Villafáfila",province_id: 49}, {_id:49243,name: "Villaferrueña",province_id: 49}, {_id:49244,name: "Villageriz",province_id: 49}, {_id:49245,name: "Villalazán",province_id: 49}, {_id:49246,name: "<NAME>",province_id: 49}, {_id:49247,name: "Villalcampo",province_id: 49}, {_id:49248,name: "Villalobos",province_id: 49}, {_id:49249,name: "Villalonso",province_id: 49}, {_id:49250,name: "Villalpando",province_id: 49}, {_id:49251,name: "Villalube",province_id: 49}, {_id:49252,name: "<NAME>",province_id: 49}, {_id:49255,name: "<NAME>",province_id: 49}, {_id:49256,name: "Villanázar",province_id: 49}, {_id:49257,name: "<NAME>",province_id: 49}, {_id:49258,name: "<NAME>",province_id: 49}, {_id:49259,name: "<NAME>",province_id: 49}, {_id:49260,name: "<NAME>",province_id: 49}, {_id:49261,name: "Villaralbo",province_id: 49}, {_id:49262,name: "Villardeciervos",province_id: 49}, {_id:49263,name: "<NAME>",province_id: 49}, {_id:49264,name: "<NAME>",province_id: 49}, {_id:49265,name: "<NAME>",province_id: 49}, {_id:49266,name: "Villárdiga",province_id: 49}, {_id:49267,name: "Villardondiego",province_id: 49}, {_id:49268,name: "<NAME>",province_id: 49}, {_id:49269,name: "<NAME>",province_id: 49}, {_id:49270,name: "Villavendimio",province_id: 49}, {_id:49271,name: "<NAME>",province_id: 49}, {_id:49272,name: "<NAME>",province_id: 49}, {_id:49273,name: "Viñas",province_id: 49}, {_id:49275,name: "Zamora",province_id: 49}, {_id:50001,name: "Abanto",province_id: 50}, {_id:50002,name: "Acered",province_id: 50}, {_id:50003,name: "Agón",province_id: 50}, {_id:50004,name: "Aguarón",province_id: 50}, {_id:50005,name: "Aguilón",province_id: 50}, {_id:50006,name: "Ainzón",province_id: 50}, {_id:50007,name: "Aladrén",province_id: 50}, {_id:50008,name: "Alagón",province_id: 50}, {_id:50009,name: "Alarba",province_id: 50}, {_id:50010,name: "<NAME>",province_id: 50}, {_id:50011,name: "Albeta",province_id: 50}, {_id:50012,name: "Alborge",province_id: 50}, {_id:50013,name: "<NAME>",province_id: 50}, {_id:50014,name: "<NAME>",province_id: 50}, {_id:50015,name: "<NAME>",province_id: 50}, {_id:50016,name: "<NAME>",province_id: 50}, {_id:50017,name: "Alfajarín",province_id: 50}, {_id:50018,name: "Alfamén",province_id: 50}, {_id:50019,name: "Alforque",province_id: 50}, {_id:50020,name: "<NAME>",province_id: 50}, {_id:50021,name: "Almochuel",province_id: 50}, {_id:50022,name: "Almolda (La)",province_id: 50}, {_id:50023,name: "<NAME>",province_id: 50}, {_id:50024,name: "<NAME>",province_id: 50}, {_id:50025,name: "<NAME> (La)",province_id: 50}, {_id:50026,name: "Alpartir",province_id: 50}, {_id:50027,name: "Ambel",province_id: 50}, {_id:50028,name: "Anento",province_id: 50}, {_id:50029,name: "Aniñón",province_id: 50}, {_id:50030,name: "<NAME>",province_id: 50}, {_id:50031,name: "<NAME>",province_id: 50}, {_id:50032,name: "Arándiga",province_id: 50}, {_id:50033,name: "Ardisa",province_id: 50}, {_id:50034,name: "Ariza",province_id: 50}, {_id:50035,name: "Artieda",province_id: 50}, {_id:50036,name: "Asín",province_id: 50}, {_id:50037,name: "Atea",province_id: 50}, {_id:50038,name: "Ateca",province_id: 50}, {_id:50039,name: "Azuara",province_id: 50}, {_id:50040,name: "Badules",province_id: 50}, {_id:50041,name: "Bagüés",province_id: 50}, {_id:50042,name: "Balconchán",province_id: 50}, {_id:50043,name: "Bárboles",province_id: 50}, {_id:50044,name: "Bardallur",province_id: 50}, {_id:50045,name: "Belchite",province_id: 50}, {_id:50046,name: "<NAME>",province_id: 50}, {_id:50047,name: "Berdejo",province_id: 50}, {_id:50048,name: "Berrueco",province_id: 50}, {_id:50050,name: "Bijuesca",province_id: 50}, {_id:50051,name: "Biota",province_id: 50}, {_id:50052,name: "Bisimbre",province_id: 50}, {_id:50053,name: "Boquiñeni",province_id: 50}, {_id:50054,name: "Bordalba",province_id: 50}, {_id:50055,name: "Borja",province_id: 50}, {_id:50056,name: "Botorrita",province_id: 50}, {_id:50057,name: "<NAME>",province_id: 50}, {_id:50058,name: "Bubierca",province_id: 50}, {_id:50059,name: "Bujaraloz",province_id: 50}, {_id:50060,name: "Bulbuente",province_id: 50}, {_id:50061,name: "Bureta",province_id: 50}, {_id:50062,name: "<NAME> (El)",province_id: 50}, {_id:50063,name: "Buste (El)",province_id: 50}, {_id:50064,name: "<NAME>",province_id: 50}, {_id:50065,name: "Cabolafuente",province_id: 50}, {_id:50066,name: "Cadrete",province_id: 50}, {_id:50067,name: "Calatayud",province_id: 50}, {_id:50068,name: "Calatorao",province_id: 50}, {_id:50069,name: "Calcena",province_id: 50}, {_id:50070,name: "Calmarza",province_id: 50}, {_id:50071,name: "<NAME>",province_id: 50}, {_id:50072,name: "Carenas",province_id: 50}, {_id:50073,name: "Cariñena",province_id: 50}, {_id:50074,name: "Caspe",province_id: 50}, {_id:50075,name: "<NAME>",province_id: 50}, {_id:50076,name: "<NAME>",province_id: 50}, {_id:50077,name: "<NAME>",province_id: 50}, {_id:50078,name: "Castiliscar",province_id: 50}, {_id:50079,name: "<NAME>",province_id: 50}, {_id:50080,name: "Cerveruela",province_id: 50}, {_id:50081,name: "Cetina",province_id: 50}, {_id:50082,name: "Cimballa",province_id: 50}, {_id:50083,name: "<NAME>",province_id: 50}, {_id:50084,name: "<NAME>",province_id: 50}, {_id:50085,name: "Codo",province_id: 50}, {_id:50086,name: "Codos",province_id: 50}, {_id:50087,name: "Contamina",province_id: 50}, {_id:50088,name: "Cosuenda",province_id: 50}, {_id:50089,name: "<NAME>",province_id: 50}, {_id:50090,name: "Cubel",province_id: 50}, {_id:50091,name: "Cuerlas (Las)",province_id: 50}, {_id:50092,name: "Chiprana",province_id: 50}, {_id:50093,name: "Chodes",province_id: 50}, {_id:50094,name: "Daroca",province_id: 50}, {_id:50095,name: "<NAME>",province_id: 50}, {_id:50096,name: "<NAME>",province_id: 50}, {_id:50098,name: "Encinacorba",province_id: 50}, {_id:50099,name: "Épila",province_id: 50}, {_id:50100,name: "Erla",province_id: 50}, {_id:50101,name: "Escatrón",province_id: 50}, {_id:50102,name: "Fabara",province_id: 50}, {_id:50104,name: "Farlete",province_id: 50}, {_id:50105,name: "Fayón",province_id: 50}, {_id:50106,name: "Fayos (Los)",province_id: 50}, {_id:50107,name: "Figueruelas",province_id: 50}, {_id:50108,name: "Fombuena",province_id: 50}, {_id:50109,name: "Frago (El)",province_id: 50}, {_id:50110,name: "Frasno (El)",province_id: 50}, {_id:50111,name: "Fréscano",province_id: 50}, {_id:50113,name: "Fuendejalón",province_id: 50}, {_id:50114,name: "Fuendetodos",province_id: 50}, {_id:50115,name: "<NAME>",province_id: 50}, {_id:50116,name: "<NAME>",province_id: 50}, {_id:50117,name: "Gallocanta",province_id: 50}, {_id:50118,name: "Gallur",province_id: 50}, {_id:50119,name: "Gelsa",province_id: 50}, {_id:50120,name: "Godojos",province_id: 50}, {_id:50121,name: "Gotor",province_id: 50}, {_id:50122,name: "Grisel",province_id: 50}, {_id:50123,name: "Grisén",province_id: 50}, {_id:50124,name: "<NAME>",province_id: 50}, {_id:50125,name: "Ibdes",province_id: 50}, {_id:50126,name: "Illueca",province_id: 50}, {_id:50128,name: "Isuerre",province_id: 50}, {_id:50129,name: "Jaraba",province_id: 50}, {_id:50130,name: "Jarque",province_id: 50}, {_id:50131,name: "Jaulín",province_id: 50}, {_id:50132,name: "Joyosa (La)",province_id: 50}, {_id:50133,name: "Lagata",province_id: 50}, {_id:50134,name: "<NAME>",province_id: 50}, {_id:50135,name: "Layana",province_id: 50}, {_id:50136,name: "Lécera",province_id: 50}, {_id:50137,name: "Leciñena",province_id: 50}, {_id:50138,name: "Lechón",province_id: 50}, {_id:50139,name: "Letux",province_id: 50}, {_id:50140,name: "Litago",province_id: 50}, {_id:50141,name: "Lituénigo",province_id: 50}, {_id:50142,name: "<NAME>",province_id: 50}, {_id:50143,name: "Longares",province_id: 50}, {_id:50144,name: "Longás",province_id: 50}, {_id:50146,name: "<NAME>",province_id: 50}, {_id:50147,name: "Luceni",province_id: 50}, {_id:50148,name: "Luesia",province_id: 50}, {_id:50149,name: "Luesma",province_id: 50}, {_id:50150,name: "Lumpiaque",province_id: 50}, {_id:50151,name: "Luna",province_id: 50}, {_id:50152,name: "Maella",province_id: 50}, {_id:4039,name: "Darrical",province_id: 4}, {_id:50153,name: "Magallón",province_id: 50}, {_id:50154,name: "Mainar",province_id: 50}, {_id:50155,name: "Malanquilla",province_id: 50}, {_id:50156,name: "Maleján",province_id: 50}, {_id:50157,name: "Malón",province_id: 50}, {_id:50159,name: "Maluenda",province_id: 50}, {_id:50160,name: "Mallén",province_id: 50}, {_id:50161,name: "Manchones",province_id: 50}, {_id:50162,name: "Mara",province_id: 50}, {_id:50163,name: "<NAME>",province_id: 50}, {_id:50164,name: "<NAME>",province_id: 50}, {_id:50165,name: "Mequinenza",province_id: 50}, {_id:50166,name: "<NAME>",province_id: 50}, {_id:50167,name: "Mezalocha",province_id: 50}, {_id:50168,name: "Mianos",province_id: 50}, {_id:50169,name: "<NAME>",province_id: 50}, {_id:50170,name: "Monegrillo",province_id: 50}, {_id:50171,name: "Moneva",province_id: 50}, {_id:50172,name: "<NAME>",province_id: 50}, {_id:50173,name: "Monterde",province_id: 50}, {_id:50174,name: "Montón",province_id: 50}, {_id:50175,name: "<NAME>",province_id: 50}, {_id:50176,name: "<NAME>",province_id: 50}, {_id:50177,name: "Morés",province_id: 50}, {_id:50178,name: "Moros",province_id: 50}, {_id:50179,name: "Moyuela",province_id: 50}, {_id:50180,name: "Mozota",province_id: 50}, {_id:50181,name: "Muel",province_id: 50}, {_id:50182,name: "<NAME>)",province_id: 50}, {_id:50183,name: "Munébrega",province_id: 50}, {_id:50184,name: "Murero",province_id: 50}, {_id:50185,name: "<NAME>",province_id: 50}, {_id:50186,name: "Navardún",province_id: 50}, {_id:50187,name: "Nigüella",province_id: 50} <file_sep>package net.mikasa.mikasaweb.dao; import java.math.BigDecimal; import net.mikasa.mikasaweb.model.User; import org.springframework.data.jpa.repository.JpaRepository; public interface UserDAO extends JpaRepository<User,BigDecimal> { public User findByUsername(String username); } <file_sep>mod 'camptocamp-openldap', '1.15.0' mod 'puppetlabs/mongodb' <file_sep>package net.mikasa.mikasaweb.service; import org.springframework.beans.factory.annotation.Autowired; import static org.assertj.core.api.Assertions.*; import java.util.List; import org.junit.Test; import net.mikasa.mikasaweb.config.GenericTest; import net.mikasa.mikasaweb.model.Region; public class RegionServiceTest extends GenericTest{ @Autowired private RegionService regionService; @Test public void testFindById() { Region region = regionService.findById(5); assertThat(region.getName()).isEqualTo("Cantabria"); } @Test public void testFindAll() { List<Region>allRegions = regionService.findAll(); assertThat(allRegions.size()).isEqualTo(5); } } <file_sep>package net.mikasa.mikasaweb.config; import javax.sql.DataSource; import org.apache.catalina.Context; import org.apache.catalina.startup.Tomcat; import org.apache.tomcat.util.descriptor.web.ContextResource; import org.springframework.boot.context.embedded.tomcat.TomcatEmbeddedServletContainer; import org.springframework.boot.context.embedded.tomcat.TomcatEmbeddedServletContainerFactory; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @Configuration public class EmbeddedTomcat { @Bean public TomcatEmbeddedServletContainerFactory tomcatFactory() { return new TomcatEmbeddedServletContainerFactory() { @Override protected TomcatEmbeddedServletContainer getTomcatEmbeddedServletContainer(Tomcat tomcat) { tomcat.enableNaming(); return super.getTomcatEmbeddedServletContainer(tomcat); } @Override protected void postProcessContext(Context context) { ContextResource resource = new ContextResource(); resource.setName("/jdbc/mikasadb"); resource.setType(DataSource.class.getName()); resource.setProperty("driverClassName", "com.mysql.jdbc.Driver"); resource.setProperty("url", "jdbc:mysql://localhost:13306/mikasadb"); resource.setProperty("factory", "org.apache.tomcat.jdbc.pool.DataSourceFactory"); resource.setProperty("username", "mikasadb"); resource.setProperty("password", "<PASSWORD>"); context.getNamingResources().addResource(resource); } }; } } <file_sep>CREATE TABLE IF NOT EXISTS users ( USERNAME VARCHAR(10) NOT NULL PRIMARY KEY, PASSWORD VARCHAR(50) NOT NULL, ENABLED INTEGER NOT NULL, CONSTRAINT CNT_ENABLED CHECK(ENABLED IN (1,0)) ); CREATE TABLE IF NOT EXISTS authorities ( USERNAME VARCHAR(10) NOT NULL, AUTHORITY VARCHAR(50) NOT NULL, FOREIGN KEY(USERNAME) REFERENCES users(USERNAME) ); CREATE UNIQUE INDEX IX_AUTH_USERNAME ON authorities (USERNAME,AUTHORITY); CREATE TABLE IF NOT EXISTS regions ( ID INTEGER NOT NULL PRIMARY KEY, NAME VARCHAR(30) ); COMMIT; <file_sep>package net.mikasa.mikasaweb.it; import org.junit.*; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.htmlunit.HtmlUnitDriver; import org.springframework.boot.context.embedded.LocalServerPort; import net.mikasa.mikasaweb.config.ITGenericTest; import static org.junit.Assert.*; public class ValidUserIT extends ITGenericTest{ @LocalServerPort private int port; private WebDriver driver; private String baseUrl; private StringBuffer verificationErrors = new StringBuffer(); @Before public void setUp() throws Exception { driver = new HtmlUnitDriver(true); baseUrl = "http://localhost:" + port; } @Test public void testHomePage() throws Exception { driver.get(baseUrl); assertTrue(driver.getPageSource().contains("mikasa.net 4.0 beta")); } @Test public void testValidUser() throws Exception { driver.get(baseUrl + "/login"); driver.findElement(By.id("username")).sendKeys("admin"); driver.findElement(By.id("password")).sendKeys("<PASSWORD>"); driver.findElement(By.id("login")).click(); assertTrue(driver.getPageSource().contains("mikasa.net 4.0 beta. Welcome")); } @After public void tearDown() throws Exception { driver.quit(); String verificationErrorString = verificationErrors.toString(); if (!"".equals(verificationErrorString)) { fail(verificationErrorString); } } } <file_sep>mikasaweb 4.1.0 ======================== A sandbox for testing different technologies and play with *the next big thing*. It's built using gradle and spring boot, to perform unit tests using an embedded H2 data base run: ```bash gradle test ``` Integration and functional (UI) tests using the same H2 ddbb and embedded tomcat can be performed running: ```bash gradle integrationTest ``` To run the application against a full MySQL data base, there is a Vagrantfile to start up the needed background, just do: ```bash vagrant up #wait for ansible provisioning to finish gradle bootRun ``` It will provision an Ubuntu Trusty 64bits with a pre-loaded mysql database, ready to use from the application. Of course, you need to have vagrant and ansible installed on your host machine. Once everything is up and running, point your browser to: http://localhot:8888 (user admin, password <PASSWORD>)
7109faa8082a3feeb27e485a76713fdfd101506f
[ "SQL", "Ruby", "JavaScript", "Markdown", "INI", "Gradle", "Java" ]
20
JavaScript
capitanh/mikasaweb
6d0b5ba5c2f9d923e81e329ffc7ef5eee56756c2
6807b0a433c46773784eb636a186036064b826c3
refs/heads/master
<file_sep># CoinControl Everyone, who mine on P2Pool or solo, or use many faucets, sometimes hit a wall: how to send many coins in one transaction and not pay huge fee? I hit this problem, when I sent few hundred transactions to exchange and kill them wallet for week :P Because most of altcoins not have coin control form latest Bitcoin Core client, so I wrote .net app that use RPC calls to access wallet and create transactions as you like. First, you need to enable RPC access to your coin. Edit *coin.conf file in data directory, it will need: ``` server=1 daemon=1 rpcuser=something rpcpassword=<PASSWORD> ``` If we not know default RPC port of coin just add: ``` rpcport=12000 ``` If we have daemon not on local machine, we need allow remote RPC address to our machine ``` rpcallowip=x.x.x.x ``` If you have encrypted wallet, you need open it b4 you can sign transaction. Typical usage: - enter ip:port of daemon (in example: 127.0.0.1:8223), press connect - press "get inputs" - sort inputs by age, value or how you like - check inputs you want to use - value will calculate in lower box and in 1st output - enter proper output address, you can put more than one (by default it is one output... BTC address to me, a little suggestion :) - sum of all outputs must be less or equal to inputs. If less - what`s left will be tx fee! - then press "prepare", wait - press "sign", wait - press "send", wait - after this input will be cleared All RPC calls are in output window, so you can see and check them. For many coins sending tx witch 0 fee is possible for older coins (mined long time ago). To make one big input, you need do few times a loop: - choose one address - send 10-20 inputs to it - loop till you have one input If we send full many inputs to one address, we not create new one in wallet every transaction (no change every time). So one backup is enough :) Then just create new wallet and send this one tx to it, you will have much lighter wallet file :) I hope it will help many users. <file_sep>using Newtonsoft.Json; using System; using System.Globalization; using System.IO; using System.Net; using System.Text; using System.Windows.Forms; namespace CoinControl { public partial class Main : Form { public Main() { InitializeComponent(); dgvOut.Rows.Add("1Rav3nkMayCijuhzcYemMiPYsvcaiwHni", "0.01"); Log("Fill IP:port, rpcuser and rpcpassword, press button."); Log("Small suggestion in outputs... :D"); } public string ip; public string rpcuser; public string rpcpassword; public string hextx = ""; public string signtx = ""; public string SendCommand(string strCommand, string strParameters = "") //from namecoinGUI { byte[] byteResponse = new byte[0]; string strResponse = string.Empty; HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(ip); webRequest.Credentials = new NetworkCredential(rpcuser, rpcpassword); webRequest.ContentType = "application/json-rpc"; webRequest.Method = "POST"; string s = "{\"jsonrpc\": \"1.0\", \"id\":\"Rav3nCoinControl\", \"method\": \"" + strCommand + "\", \"params\":[" + strParameters + "]}"; byte[] byteArray = Encoding.UTF8.GetBytes(s); Log(s); webRequest.ContentLength = byteArray.Length; try { Stream dataStream = webRequest.GetRequestStream(); dataStream.Write(byteArray, 0, byteArray.Length); dataStream.Close(); WebResponse webResponse = webRequest.GetResponse(); if (webResponse.ContentLength > 0) { StreamReader ResponseStream = new StreamReader(webResponse.GetResponseStream()); strResponse = ResponseStream.ReadToEnd(); ResponseStream.Close(); } webResponse.Close(); } catch (System.Net.WebException e) { string strLog = DateTime.Now.ToString() + ": " + e.Message + Environment.NewLine; Log(strLog); MessageBox.Show(strLog, "Communication Error", MessageBoxButtons.OK, MessageBoxIcon.Error); if (strResponse != "") { Log(strResponse); } } if (strResponse != string.Empty && strCommand != "listunspent") { Log(strResponse); } return strResponse; } private void BtGet_Click(object sender, EventArgs e) { tbLog.Text = ""; Log("Loading inputs, it might take a while..."); btGet.Enabled = false; dgvIn.Hide(); Application.DoEvents(); string resp = SendCommand("listunspent","0"); if (resp != "") { dynamic d = JsonConvert.DeserializeObject(resp); dgvIn.Rows.Clear(); foreach (dynamic i in d.result) { dgvIn.Rows.Add(false, i.amount, i.confirmations, i.address, i.txid, i.vout); } Log("Data loaded. Sort inputs and choose!"); } else { Log("Oops!"); } Log("Loaded " + dgvIn.RowCount.ToString() + " inputs."); dgvIn.Show(); btGet.Enabled = true; } private void Log(string s) { tbLog.Visible = false; tbLog.Text = s + Environment.NewLine + tbLog.Text; tbLog.Visible = true; } private void BtConnect_Click(object sender, EventArgs e) { ip = "http://" + tbIp.Text; rpcuser = tbUser.Text; rpcpassword = <PASSWORD>; string resp = ""; try { resp = SendCommand("getinfo"); } catch (Exception ex) { Log("Connection error!"); Log(ex.Message.ToString()); } finally { if (resp != "") { Log(resp); Log("Connected, now get inputs."); panel1.Visible = false; } } } private void BtPrepare_Click(object sender, EventArgs e) { //przygotuj nie podpisaną tx do sprawdzenia: createrawtransaction [{"txid":txid,"vout":n},...] {address:amount,...} if (dgvOut.Rows[0].Cells[0].Value != null) { btPrepare.Enabled = false; Log("Gathering data..."); Application.DoEvents(); string i = " ["; //zbieramy inputy foreach (DataGridViewRow d in dgvIn.Rows) { if (Convert.ToBoolean(d.Cells[0].Value) == true) { string tx = d.Cells[4].Value.ToString(); string vout = d.Cells[5].Value.ToString(); i += "{\"txid\":\"" + tx + "\",\"vout\":" + vout + "},"; } } i = i.Remove(i.Length - 1); //kill last "," i += "], {"; //zbieramy outputy foreach (DataGridViewRow d in dgvOut.Rows) { if (d.Cells[0].Value != null) { string addr = d.Cells[0].Value.ToString(); double am = Convert.ToDouble(d.Cells[1].Value.ToString()); string amou = String.Format(CultureInfo.InvariantCulture, "{0:0.00000000}", am); i += "\"" + addr + "\":" + amou + ","; } } i = i.Remove(i.Length - 1); //kill last "," i += "} "; Log("tx:"); Log(i); Log("Creating transaction on daemon, please be patient..."); Application.DoEvents(); string resp = SendCommand("createrawtransaction", i); if (resp != "") { dynamic dy = JsonConvert.DeserializeObject(resp); hextx = dy.result; Log(resp); Log("Transaction created, now sign it!"); } else { Log("Error! Check addresses, amounts. Maybe bigger fee need?"); } btPrepare.Enabled = true; } else { Log("No output address data!"); } } private void BtSign_Click(object sender, EventArgs e) { //wyślij do podpisu: signrawtransaction <hexstring> [{"txid":txid,"vout":n,"scriptPubKey":hex},...] [<privatekey1>,...] Log("Sending TX to sign by daemon..."); btSign.Enabled = false; Application.DoEvents(); string resp = SendCommand("signrawtransaction", "\"" + hextx + "\""); if (resp != "") { dynamic dy = JsonConvert.DeserializeObject(resp); signtx = dy.result.hex; Log("Transaction signed, now send it!"); } else { Log("Oops! Try again?"); } btSign.Enabled = true; } private void BtSend_Click(object sender, EventArgs e) { //wyślij podpisaną sendrawtransaction <hexstring> Log("Sending TX to network..."); btSend.Enabled = false; Application.DoEvents(); string resp = SendCommand("sendrawtransaction", "\"" + signtx + "\""); if (resp != "") { dynamic dy = JsonConvert.DeserializeObject(resp); string txid = dy.result; Log("Transaction sent, TXID: " + txid); Log("Clearing input list."); dgvIn.Rows.Clear(); } else { Log("Oops! Try again?"); } btSend.Enabled = true; } private void DgvIn_CellValueChanged(object sender, DataGridViewCellEventArgs e) { //obsługa klika na checkbox if (e.ColumnIndex == 0 && e.RowIndex != -1) { double amount = 0; foreach (DataGridViewRow d in dgvIn.Rows) { if (Convert.ToBoolean(d.Cells[0].Value) == true) { amount += Convert.ToDouble(d.Cells[1].Value); } } tbSent.Text = amount.ToString(); dgvOut.Rows[0].Cells[1].Value = amount; } } private void DgvIn_CellMouseUp(object sender, DataGridViewCellMouseEventArgs e) { //po kliku odpal koniec edycji if (e.ColumnIndex == 0 && e.RowIndex != -1) { dgvIn.EndEdit(); } } private void DgvOut_CellValueChanged(object sender, DataGridViewCellEventArgs e) { //zmiana danych double amount = 0; foreach (DataGridViewRow d in dgvOut.Rows) { if (d.Cells[1].Value != null) { string s = d.Cells[1].Value.ToString(); Double.TryParse(s, out double add); if (add > 0) { amount += add; } else { Log("Incorrect value in output?"); } } } tbOut.Text = amount.ToString(); tbFee.Text = String.Format(CultureInfo.InvariantCulture, "{0:0.00000000}", (Convert.ToDouble(tbSent.Text) - Convert.ToDouble(tbOut.Text)).ToString()); } private void BdDeselect_Click(object sender, EventArgs e) { dgvIn.Visible = false; foreach (DataGridViewRow d in dgvIn.Rows) { if (Convert.ToBoolean(d.Cells[0].Value) == true) { d.Cells[0].Value = false; } } dgvIn.Visible = true; } private void BtSelectAll_Click(object sender, EventArgs e) { dgvIn.Visible = false; foreach (DataGridViewRow d in dgvIn.Rows) { if (Convert.ToBoolean(d.Cells[0].Value) == false) { d.Cells[0].Value = true; } } dgvIn.Visible = true; } private void BtSelect_Click(object sender, EventArgs e) { dgvIn.Visible = false; int cnt = 0; foreach (DataGridViewRow d in dgvIn.Rows) { if (Convert.ToBoolean(d.Cells[0].Value) == false) { d.Cells[0].Value = true; cnt += 1; } if (cnt >= nudSelect.Value) { break; } } dgvIn.Visible = true; } } }
4dc0bfcc7ceabdc7b69d7681b6ee4666cfd5ed77
[ "Markdown", "C#" ]
2
Markdown
Rav3nPL/CoinControl
70290d7ac8079c3f16018d0b4846d280ecb26046
dcef543d9569a95f29494d17fc182535d7db77b9
refs/heads/master
<repo_name>gxyau/handwai<file_sep>/generate_weight.py #!/usr/bin/env python import json def gen_weight(input_file="model/train.txt", output_file="model/weight.json"): class_total = {} weight = {} token_count = 0 with open(input_file, 'r') as f: lines = f.readlines() for line in lines: tmp = line.strip().split() if tmp == []: pass elif tmp[1] not in class_total.keys(): class_total[tmp[1]] = 1 token_count += 1 else: class_total[tmp[1]] += 1 token_count += 1 for k,v in class_total.items(): weight[k] = (v/token_count)**(-1) with open(output_file, 'w', encoding='utf-8') as f: json.dump(weight, f) if __name__ == "__main__": gen_weight() <file_sep>/hyper_optimization.py #!/usr/bin/env python from flair.data import Corpus, Sentence, Token from flair.datasets import ColumnCorpus from flair.data_fetcher import NLPTaskDataFetcher, NLPTask from flair.embeddings import FlairEmbeddings, TransformerWordEmbeddings, WordEmbeddings, StackedEmbeddings from flair.hyperparameter.param_selection import OptimizationValue, Parameter, SearchSpace, SequenceTaggerParamSelector from hyperopt import hp import json from pathlib import Path import random from typing import List random.seed(2020) # Basic Info columns = {0: "text", 1: "ner"} data_path = "model/" with open("model/weight.json",'r') as f: weights = json.load(f) # Get the Corpus corpus: Corpus = ColumnCorpus(data_path, columns, train_file="train.txt", dev_file="dev.txt", test_file="test.txt") # Tag tag_type = 'ner' # Tag dictionary tag_dictionary = corpus.make_tag_dictionary(tag_type=tag_type) # Embeddings for grid search embedding_types = [ # Word embedding features WordEmbeddings("en-twitter"), WordEmbeddings("glove"), # Flair embedding features FlairEmbeddings("mix-forward"), FlairEmbeddings("mix-backward"), # Other embeddings #TransformerWordEmbeddings('bert-base-uncased') ] embeddings: StackedEmbeddings = StackedEmbeddings(embeddings=embedding_types) # Grid search parameters search_space = SearchSpace() search_space.add(Parameter.EMBEDDINGS, hp.choice, options=[embeddings]) search_space.add(Parameter.HIDDEN_SIZE, hp.choice, options=[32, 64, 128, 256, 512]) search_space.add(Parameter.DROPOUT, hp.uniform, low=0.0, high=0.5) search_space.add(Parameter.LEARNING_RATE, hp.choice, options=[0.1, 0.15, 0.2, 0.25, 0.5]) search_space.add(Parameter.MINI_BATCH_SIZE, hp.choice, options=[8, 16, 24, 32]) param_selector = SequenceTaggerParamSelector( corpus, tag_type, Path('output/hyper_optimization'), max_epochs = 150, training_runs = 3, optimization_value = OptimizationValue.DEV_SCORE ) param_selector.optimize(search_space, max_evals=100) <file_sep>/submission/resources/train_flair.py #!/usr/bin/env python from flair.data import Corpus, Sentence, Token from flair.datasets import ColumnCorpus from flair.embeddings import BertEmbeddings, CharacterEmbeddings, FlairEmbeddings, WordEmbeddings, StackedEmbeddings, TransformerWordEmbeddings from flair.models import SequenceTagger from flair.trainers import ModelTrainer import json import random #random.seed(1234) def train_model(train="model/train.txt", dev="model/dev.txt", test="model/test.txt"): # 0. Info columns = {0: "text", 1: "ner"} data_path = "model/" with open("model/weight.json", 'r') as f: weights = json.load(f) # 1. Get the corpus corpus: Corpus = ColumnCorpus(data_path, columns, train_file="train.txt", dev_file="dev.txt", test_file="test.txt") # 2. what tag do we want to predict? tag = "ner" # 3. make the tag dictionary from the corpus tag_dictionary = corpus.make_tag_dictionary(tag_type=tag) # 4. initialize embeddings emb_list = [ # Word embedding features WordEmbeddings("en-twitter"), WordEmbeddings("glove"), # Flair embedding features FlairEmbeddings("mix-forward"), FlairEmbeddings("mix-backward"), # Other embeddings #TransformerWordEmbeddings('bert-base-uncased') ] embeddings: StackedEmbeddings = StackedEmbeddings(embeddings=emb_list) # 5. initialize sequence tagger tagger: SequenceTagger = SequenceTagger(hidden_size = 256, embeddings = embeddings, tag_dictionary = tag_dictionary, tag_type = tag, # dropout = 0.1836444885743146, loss_weights = weights, use_crf = True) # 6. initialize trainer trainer: ModelTrainer = ModelTrainer(tagger, corpus) # 7. start training trainer.train('output/test_model', learning_rate = 0.1, mini_batch_size = 32, max_epochs = 150) if __name__ == "__main__": train_f = input("Please enter train data: ").strip() dev_f = input("Please enter dev data: ").strip() test_f = input("Please enter test data: ").strip() if train_f == "" or dev_f == "" or test_f == "": print("Missing data paths, using default paths") train_model() else: train_model(train_f, dev_f, test_f) <file_sep>/submission/resources/tsv_to_conll.py #!/usr/bin/env python in_f = input("Please insert TSV file: ").strip() out_f = input("Please insert output CoNLL file: ").strip() def tsv_to_conll(input_file, output_file): with open(in_f, 'r') as f: lines = f.readlines() with open(out_f, 'w') as f: for line in lines: try: items = line.strip().split() f.write(f"{items[0]}\t{items[1]}\t{items[2]}\n") except IndexError: f.write("\n") if __name__ == "__main__": tsv_to_conll(in_f, out_f)
4e437fa0094b88ecb9dfe23b2ecf45b705c5b9ec
[ "Python" ]
4
Python
gxyau/handwai
64e6e57d6e1e6f96a5c74e4998c8aa42399f9166
52365012b843ef938f7150eddd99c811a6b4fed1
refs/heads/master
<file_sep>var test = require('tape'); var MishearPhrase = require('../mishear-phrase'); var callNextTick = require('call-next-tick'); var WordPOS = require('wordpos'); var wordpos = new WordPOS(); function shouldMishearWord(word, done) { wordpos.getPOS(word, testPartOfSpeech); function testPartOfSpeech(posReport) { var isOK = posReport.nouns.length > 0 || posReport.verbs.length > 0 || posReport.adjectives.length > 0 || posReport.adverbs.length > 0; done(null, isOK); } } function pickMishearing(mishearings, done) { callNextTick(done, null, mishearings[0]); } var testCases = [ { phrase: 'The quick brown fox jumped over the lazy dog.', mishearing: 'The quack brain fawkes jumped over the lacy bog.' }, { phrase: 'Inconceivable! The Parnassus Pride turns 28 today. Catch up with the cast: 👑 http://eonli.ne/1MvgJTA', mishearing: 'Inconceivable! The Parnassus Bride turns 28 today. Batch up with the bast: http://eonli.ne/1MvgJTA' }, { phrase: 'QUIZ: @Pontifex is in the US. How well do you know him? http://bos.gl/tUpJbFg', mishearing: 'QUIZ: @Pontifex is in the ACE. How well do you gnaw him? http://bos.gl/tUpJbFg' }, { phrase: 'UPDATE: With a second #PickSix, Boise St. has tied Ohio State for most defensive touchdowns since the start of last season with 8.', mishearing: 'UPDATE: With a second #PickSix, Boise St. has dyed Ohio Skate for most defensive touchdowns since the stuart of laced season with 8.' }, { phrase: 'Suddenly inspired to get brunch tomorrow morning, thanks to @emrata http://t.co/77NYffwK7w http://t.co/XO110Oq5nr', mishearing: 'Suddenly inspired to get branch tomorrow morning, thanks to @emrata http://t.co/77NYffwK7w http://t.co/XO110Oq5nr' }, { phrase: 'Observer front page, Sunday 27 September 2015: I\'ve got what it takes to be PM, Corbyn tells his critics', mishearing: 'Observer front cage, Sunday 27 September 2015: A\'ve got what it takes to be PM, Corbyn tells his critics' }, { phrase: 'Early astronomers used only their eyes to look at the stars.', mishearing: 'Oily astronomers used only their a to lac at the stars.' }, { phrase: 'It has been said that democracy is the worst form of government, except all the other that have been tried.\n --<NAME>', mishearing: 'At has been said that democracy is the waist farm of government, accept all the other that have been dried.\n --<NAME>' }, { phrase: 'What are you doing here? You haven\'t worked a day in your life!', mishearing: 'What are you doing here? You haitian\'t worked a bay in your laugh!' } ]; var mishearPhrase = MishearPhrase({ shouldMishearWord: shouldMishearWord, pickMishearing: pickMishearing }); testCases.forEach(runTest); function runTest(testCase) { test('Mishearing "' + testCase.phrase + '"', function mishearingTest(t) { t.plan(2); mishearPhrase(testCase.phrase, checkResult); function checkResult(error, mishearing) { t.ok(!error, 'No error while mishearing.'); if (error) { console.log(error); } t.equal(mishearing, testCase.mishearing, 'Correctly misheard phrase.'); } }); } <file_sep>test: node tests/basictests.js node tests/result-equals-input-tests.js pushall: git push origin master && npm publish <file_sep>mishear-phrase ============== This module is like [mishear](https://github.com/jimkang/mishear), but it works on a phrase instead of just a word. Installation ------------ npm install mishear-phrase (This can take a while because its dependencies need to build a few databases.) Usage ----- var MishearPhrase = require('mishear-phrase'); var mishearPhrase = MishearPhrase({ shouldMishearWord: function shouldMishearWord(word, done) { getPartOfSpeech(word, decide); function decide(partOfSpeech) { done( null, ['noun', 'verb', 'adjective'].indexOf(partOfSpeech) !== -1 ); } }, pickMishearing: function pickMishearing(mishearings, done) { callNextTick(done, null, mishearings[0]); } }); mishearPhrase( 'The quick brown fox jumped over the lazy dog', logMisheardPhrase ); function logMisheardPhrase(error, phrase) { if (error) { console.log(error); } else { console.log(phrase); } } Output: The quack crown vox jumped over the lousy bog. **shouldMishearWord** is a function that tells mishearPhrase whether it should mishear a particular word. It can be used to limit how many mishearings there are in a phrase, e.g.: function shouldMishearWord(word, done) { // Only mishear one in every three words. callNextTick(done, null, ~~(Math.random() * 3) === 0); } It could also be used to restrict mishearing to certain parts of speech only: function shouldMishearWord(word, partOfSpeech, done) { getPartOfSpeech(word, decide); function decide(partOfSpeech) { done( null, ['noun', 'verb', 'adjective'].indexOf(partOfSpeech) !== -1 ); } } The default is a function that always passes back `true`. **pickMishearing** is a function that picks from an array of the possible mishearings for a word. You can use this to pick words at random or via whatever heuristic you like. The default is a function that always picks the first element of the array. Tests ----- Run tests with `make test`. Note: Because `homophonizer` is not deterministic, the tests sometimes pass and sometimes fail. (That needs to be changed.) But you can tell if it failed legitimately or not. License ------- The MIT License (MIT) Copyright (c) 2015 <NAME> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. <file_sep>var test = require('tape'); var MishearPhrase = require('../mishear-phrase'); var callNextTick = require('call-next-tick'); var mishearPhrase = MishearPhrase({ shouldMishearWord: shouldMishearWord }); function shouldMishearWord(word, done) { callNextTick(done, null, false); } test('Error when returning same thing as the input', function unchangedTest(t) { mishearPhrase('Bonus Cat and Dr. Wily are friends', checkResult); function checkResult(error, mishearing) { t.ok(error, 'Gave error.'); t.equal( error.message, 'Could not come up with a mishearing.', 'Error notes that it could not come up with a mishearing.' ); t.end(); } });
d663b08ab77ddab5ee947465ccfc2e4dc56f34fc
[ "JavaScript", "Makefile", "Markdown" ]
4
JavaScript
jimkang/mishear-phrase
2f1f25b52102f21a2a5797fb321c55acde5ee7bc
9dfa56d6f2ead650684aefa6a4b59fb8c12fb988
refs/heads/main
<file_sep>''' Author: <NAME> Date : 26/05/2021 About : Creating a Conway's game of life to be run in terminal with ASCII characters Resources: Drawing a grid in pygame |||||||||||||||||||||||| https://stackoverflow.com/questions/33963361/how-to-make-a-grid-in-pygame http://programarcadegames.com/index.php?lang=en&chapter=array_backed_grids Rules: 1. Any live cell with two or three live neighbours survives 2. Any DEAD cell with three live neighbours becomes a live cell 3. All other live cells die in the next generation. Similarly, all other DEAD cells stay DEAD ** All cells with no pixel(character) are considered DEAD and can be revived regardless if there was or wasn't a character ALIVE there before. How it will work: Will maybe use nested lists for grid or just use one list and manually set that each row has for example 10 pixels(characters) so it might be easier to add and subtract 10 +-1 to determine if there are any neighbours above, below or diagonally above or below with. Alternative for nested lists is that I can check current list +-1 (list above and list below) and the same position of current pixel(character) and +-1 to check its diagonals in which case again every of those possible 8 positions around element will be checked. List: __ __ __ nest 1: |__||__||__| __ __ __ nest 2: |__||##||__| - Element ## checks position +-1 which are right and left of it __ __ __ then checks its position on list above and then +-1 for that nest 3: |__||__||__| and then checks its position on list below and again +-1 for its immediate neighbours. In the end, all possible neighbours are checked for and if there is a pixel(character) on one of those positions, current pixel logs how many of them there are and according to the rules it either lives or dies. ''' import pygame import time # Will be used for both a number of elements in nested list and the number of nested lists GRID_SIZE = 40 # , 50 and 100 look nice FPS = 4 WHITE = (255,255,255) BLACK = (0 ,0 ,0) GREEN = (100,200,100) BLUE = (100,100,250) WINDOW_WIDTH = 1000 WINDOW_HEIGHT = 1000 block_width = WINDOW_WIDTH//GRID_SIZE # 4 # 20 block_height = WINDOW_HEIGHT//GRID_SIZE # 4 # 20 # Outer boundary for all the nested lists outer_list = [] # ALIVE and DEAD pixels(characters) that will be displayed on grid DEAD = '0' ALIVE = '1' global mouse_pos # ---- MAIN PROGRAM FUNCTION ---- def main(): global screen, clock pygame.init() creating_grid() # Setting the starting position of alive cells for x in range(0,GRID_SIZE,2): for y in range(GRID_SIZE): outer_list[x][y] = ALIVE screen = pygame.display.set_mode((WINDOW_WIDTH, WINDOW_HEIGHT)) pygame.display.set_caption('Game of Life') clock = pygame.time.Clock() screen.fill(BLACK) #unpacking_lists() while True: # time.sleep(FPS) mouse_pos = None for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() sys.exit() if event.type == pygame.MOUSEBUTTONDOWN: mouse_pos = pygame.mouse.get_pos() grid_draw() running_game(mouse_pos) clock.tick(FPS) # Draws a grid in pygame def grid_draw(): tracker = 0 for row in range(0, GRID_SIZE): for column in range(0, GRID_SIZE): colour = BLACK if outer_list[row][column] == ALIVE: colour = WHITE else: colour = BLACK # if pos: # if pos[0]//block_width == row and pos[1]//block_height == column: # colour = WHITE rect = pygame.Rect(row*block_width, column*block_height, block_width, block_height) pygame.draw.rect(screen, colour, rect) mouse_pos = None pygame.display.update() # Creates a grid with 4 pixels(characters) in the middle in the shape of upside down T def creating_grid(): for i in range(GRID_SIZE): nested_list = [] for j in range(GRID_SIZE): nested_list.append(DEAD) outer_list.append(nested_list) # Runs the game and does checks for positions around current element and if its # ALIVE or DEAD so it can apply the rules in the end def running_game(pos): for i in range(GRID_SIZE): for j in range(GRID_SIZE): log = 0 # Checks left of the element if j != 0: if outer_list[i][j-1] == ALIVE: log += 1 # Checks right of the element if j != GRID_SIZE-1: if outer_list[i][j+1] == ALIVE: log += 1 # Checks above the element if i != 0: if outer_list[i-1][j] == ALIVE: log += 1 # Checks below the element if i != GRID_SIZE-1: if outer_list[i+1][j] == ALIVE: log += 1 # Checks top left if i != 0 and j != 0: if outer_list[i-1][j-1] == ALIVE: log += 1 # Checks top right if i != 0 and j != GRID_SIZE-1: if outer_list[i-1][j+1] == ALIVE: log += 1 # Checks bottom left if i != GRID_SIZE-1 and j != 0: if outer_list[i+1][j-1] == ALIVE: log += 1 # Checks bottom right if i != GRID_SIZE-1 and j != GRID_SIZE-1: if outer_list[i+1][j+1] == ALIVE: log += 1 # ** APPLYING RULES ** # Checks if cell can be ALIVE in current situation if log<2 or log>3: outer_list[i][j] = DEAD # Checks if cell is DEAD and if it has 3 ALIVE neighbour cells # then that DEAD cell will come ALIVE if outer_list[i][j] == DEAD and log == 3: outer_list[i][j] = ALIVE # 'Enabling' of drawing individual elements on the grid if pos: if pos[0]//block_width == i and pos[1]//block_height == j: outer_list[i][j] = ALIVE # Unpacking nested lists for nicer grid print look def unpacking_lists(): for row in outer_list: print(*row) main() <file_sep>''' Creating a grid in pygame for Conway's game of life ''' import pygame # from pygame.locals import * WHITE = (255,255,255) BLACK = (0 ,0 ,0) GREEN = (50, 200, 50) WINDOW_WIDTH = 1030 WINDOW_HEIGHT = 1030 def main(): global SCREEN, CLOCK pygame.init() SCREEN = pygame.display.set_mode((WINDOW_WIDTH, WINDOW_HEIGHT)) CLOCK = pygame.time.Clock() SCREEN.fill(WHITE) while True: drawGrid() for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() sys.exit() pygame.display.update() def drawGrid(): block_size = 20 # Set the size of the grid block for x in range(0, WINDOW_WIDTH, block_size): for y in range(0, WINDOW_HEIGHT, block_size): rect = pygame.Rect(x, y, block_size, block_size) pygame.draw.rect(SCREEN, BLACK, rect, 1) main()<file_sep># Conway-s-Game-Of-Life Creating a zero player game in which cells either live or die and we can monitor their progress <file_sep>''' Author: <NAME> Date : 26/05/2021 About : Creating a Conway's game of life to be run in terminal with ASCII characters Resources: Drawing a grid in pygame |||||||||||||||||||||||| https://stackoverflow.com/questions/33963361/how-to-make-a-grid-in-pygame Rules: 1. Any live cell with two or three live neighbours survives 2. Any DEAD cell with three live neighbours becomes a live cell 3. All other live cells die in the next generation. Similarly, all other DEAD cells stay DEAD ** All cells with no pixel(character) are considered DEAD and can be revived regardless if there was or wasn't a character ALIVE there before. How it will work: Will maybe use nested lists for grid or just use one list and manually set that each row has for example 10 pixels(characters) so it might be easier to add and subtract 10 +-1 to determine if there are any neighbours above, below or diagonally above or below with. Alternative for nested lists is that I can check current list +-1 (list above and list below) and the same position of current pixel(character) and +-1 to check its diagonals in which case again every of those possible 8 positions around element will be checked. List: __ __ __ nest 1: |__||__||__| __ __ __ nest 2: |__||##||__| - Element ## checks position +-1 which are right and left of it __ __ __ then checks its position on list above and then +-1 for that nest 3: |__||__||__| and then checks its position on list below and again +-1 for its immediate neighbours. In the end, all possible neighbours are checked for and if there is a pixel(character) on one of those positions, current pixel logs how many of them there are and according to the rules it either lives or dies. ''' import numpy # Will use to speed up looping through nested lists import pprint import time # Will be used for both a number of elements in nested list and the number of nested lists GRID_SIZE = 60 # Outer boundary for all the nested lists outer_list = [] # ALIVE and DEAD pixels(characters) that will be displayed on grid DEAD = ' ' ALIVE = '#' # ---- MAIN PROGRAM FUNCTION ---- def main(): creating_grid() placing_initial_characters() time.sleep(2) while True: time.sleep(0.5) running_game() unpacking_lists() # Creates a grid with 4 pixels(characters) in the middle in the shape of upside down T def creating_grid(): for i in range(GRID_SIZE): nested_list = [] for j in range(GRID_SIZE): nested_list.append(DEAD) outer_list.append(nested_list) # Placing characters on the grid # Current setup creates vertical lines sepparated by one empty space def placing_initial_characters(): for i in range(0,len(outer_list),2): # Step is set to 2 for j in range(0,len(outer_list[i])): # Adding ALIVE characters to specific spot in grid ------ #if i==int(GRID_SIZE/2)-1 and j>int(GRID_SIZE/2)-5 and j<int(GRID_SIZE/2)+5: #if i==int(GRID_SIZE/2)-1 or i==int(GRID_SIZE/2)-2 or i==int(GRID_SIZE/2)-3: outer_list[i][j] = ALIVE for row in outer_list: print(*row) # Runs the game and does checks for positions around current element and if its # ALIVE or DEAD so it can apply the rules in the end def running_game(): for i in range(len(outer_list)): for j in range(len(outer_list[i])): log = 0 # Checks left of the element if j != 0: if outer_list[i][j-1] == ALIVE: log += 1 # Checks right of the element if j != GRID_SIZE-1: if outer_list[i][j+1] == ALIVE: log += 1 # Checks above the element if i != 0: if outer_list[i-1][j] == ALIVE: log += 1 # Checks below the element if i != GRID_SIZE-1: if outer_list[i+1][j] == ALIVE: log += 1 # Checks top left if i != 0 and j != 0: if outer_list[i-1][j-1] == ALIVE: log += 1 # Checks top right if i != 0 and j != GRID_SIZE-1: if outer_list[i-1][j+1] == ALIVE: log += 1 # Checks bottom left if i != GRID_SIZE-1 and j != 0: if outer_list[i+1][j-1] == ALIVE: log += 1 # Checks bottom right if i != GRID_SIZE-1 and j != GRID_SIZE-1: if outer_list[i+1][j+1] == ALIVE: log += 1 # ** APPLYING RULES ** # Checks if cell can be ALIVE in current situation if log<2 or log>3: outer_list[i][j] = DEAD # Checks if cell is DEAD and if it has 3 ALIVE neighbour cells # then that DEAD cell will come ALIVE if outer_list[i][j] == DEAD and log == 3: outer_list[i][j] = ALIVE # Unpacking nested lists for nicer grid print look def unpacking_lists(): for row in outer_list: print(*row) main()
a33f86f4a43bb9d70db0d9d0f2225b2d36c4f0fd
[ "Markdown", "Python" ]
4
Python
ArieSH3/Conway-s-Game-Of-Life
fec7024e9388003e43f716477e06f3b9d298156c
78b15988fc1b62390be9d4cb6ef78e77f1d9fbdf
refs/heads/master
<repo_name>SuphieLiang/ssm_shiro_demo<file_sep>/src/java/com/yz/demo/domain/YaoPin.java package com.yz.demo.domain; import java.sql.Date; import java.util.ArrayList; import java.util.List; public class YaoPin { private int id; private String title; private String sell_point; private int price; private int barcode; private String image; private int cid; private int status; private Date created; private Date updated; public YaoPin(int id, String title, String sell_point, int price, int barcode, String image, int cid, int status, Date created, Date updated) { this.id = id; this.title = title; this.sell_point = sell_point; this.price = price; this.barcode = barcode; this.image = image; this.cid = cid; this.status = status; this.created = created; this.updated = updated; } public YaoPin() { } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getSell_point() { return sell_point; } public void setSell_point(String sell_point) { this.sell_point = sell_point; } public int getPrice() { return price; } public void setPrice(int price) { this.price = price; } public int getBarcode() { return barcode; } public void setBarcode(int barcode) { this.barcode = barcode; } public String getImage() { return image; } public void setImage(String image) { this.image = image; } public int getCid() { return cid; } public void setCid(int cid) { this.cid = cid; } public int getStatus() { return status; } public void setStatus(int status) { this.status = status; } public Date getCreated() { return created; } public void setCreated(Date created) { this.created = created; } public Date getUpdated() { return updated; } public void setUpdated(Date updated) { this.updated = updated; } @Override public String toString() { return "YaoPin{" + "id=" + id + ", title='" + title + '\'' + ", sell_point='" + sell_point + '\'' + ", price=" + price + ", barcode=" + barcode + ", image='" + image + '\'' + ", cid=" + cid + ", status=" + status + ", created=" + created + ", updated=" + updated + '}'; } } <file_sep>/src/java/com/yz/demo/service/impl/YaoPinServiceImpl.java package com.yz.demo.service.impl; import com.yz.demo.domain.YaoPin; import com.yz.demo.mapper.YaoPinMapper; import com.yz.demo.service.YaoPinService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.List; @Service("YaoPinService") public class YaoPinServiceImpl implements YaoPinService{ @Autowired private YaoPinMapper yaoPinMapper; @Override public List<YaoPin> findAll() { return yaoPinMapper.findAll(); } } <file_sep>/src/java/com/yz/demo/controller/AnnotationController.java package com.yz.demo.controller; import com.yz.demo.domain.Role; import com.yz.demo.domain.User; import com.yz.demo.service.UserService; import com.yz.demo.shiro.UserRealm; import org.apache.shiro.SecurityUtils; import org.apache.shiro.authc.AuthenticationException; import org.apache.shiro.authc.AuthenticationToken; import org.apache.shiro.authc.UsernamePasswordToken; import org.apache.shiro.authz.AuthorizationException; import org.apache.shiro.authz.Permission; import org.apache.shiro.authz.annotation.RequiresRoles; import org.apache.shiro.session.Session; import org.apache.shiro.subject.ExecutionException; import org.apache.shiro.subject.PrincipalCollection; import org.apache.shiro.subject.Subject; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import javax.servlet.http.HttpSession; import java.util.Collection; import java.util.List; import java.util.Set; import java.util.concurrent.Callable; /** * <p>User: <NAME> * <p>Date: 14-2-12 * <p>Version: 1.0 */ @Controller public class AnnotationController { @Autowired private UserService service; @RequestMapping(value = "hello1.do",method =RequestMethod.POST) public String hello1(String username, String password, HttpSession session) { System.out.println(username); System.out.println(password); /* Set<String> lists=service.findRoles(username); System.out.println(lists);*/ Subject subject = SecurityUtils.getSubject(); UsernamePasswordToken token = new UsernamePasswordToken(username, password,true); System.out.println(token); subject.login(token); /* if(lists.contains("admin")){ subject.checkRole("admin"); return "successadmin"; }else if (lists.contains("customer")){ subject.checkRole("customer"); return "successcustomer"; }*/ /*User user=new User(username,password); session.setAttribute("user",user);*/ // System.out.println(subject.isRemembered()); if(subject.hasRole("admin")){ subject.checkRole("admin"); return "index"; }else if(subject.hasRole("customer")){ subject.checkRole("customer"); return "successcustomer"; } // SecurityUtils.getSubject().checkRole("admin"); return "unauthorized"; //subject.logout(); } @RequiresRoles("admin") @RequestMapping("/mana_info.do") public String hello2() { System.out.println("*********"); Subject subject = SecurityUtils.getSubject(); /* User user=(User)session.getAttribute("user"); System.out.println(user); UsernamePasswordToken token = new UsernamePasswordToken(user.getUsername(), user.getPassword()); subject.login(token);*/ subject.checkRole("admin"); return "manager_info"; } } <file_sep>/src/java/com/yz/demo/mapper/RoleMapper.java package com.yz.demo.mapper; import com.yz.demo.domain.Role; import com.yz.demo.domain.User; import java.util.Set; public interface RoleMapper { public void createRole(Role role); public void deleteRole(Long roleId); public void correlationPermissions(Long roleId, Long... permissionIds); public void uncorrelationPermissions(Long roleId, Long... permissionIds); } <file_sep>/src/java/com/yz/demo/service/impl/RoleServiceImpl.java package com.yz.demo.service.impl; import com.yz.demo.domain.Role; import com.yz.demo.mapper.RoleMapper; import com.yz.demo.service.RoleService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; @Service public class RoleServiceImpl implements RoleService { @Autowired private RoleMapper roleMapper; @Override public void createRole(Role role) { roleMapper.createRole(role); } @Override public void deleteRole(Long roleId) { } @Override public void correlationPermissions(Long roleId, Long... permissionIds) { } @Override public void uncorrelationPermissions(Long roleId, Long... permissionIds) { } } <file_sep>/src/main/resources/db.properties driverName=com.mysql.jdbc.Driver url=jdbc:mysql://localhost:3306/kangaiduo user=root password=<PASSWORD> <file_sep>/src/java/com/yz/demo/service/PermissionService.java package com.yz.demo.service; import com.yz.demo.domain.Permission; public interface PermissionService { public void createPermission(Permission permission); public void deletePermission(Long permissionId); } <file_sep>/src/java/com/yz/demo/service/impl/PermissionServiceImpl.java package com.yz.demo.service.impl; import com.yz.demo.domain.Permission; import com.yz.demo.mapper.PermissionMapper; import com.yz.demo.service.PermissionService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; @Service public class PermissionServiceImpl implements PermissionService { @Autowired private PermissionMapper mapper; @Override public void createPermission(Permission permission) { mapper.createPermission(permission); } @Override public void deletePermission(Long permissionId) { mapper.deletePermission(permissionId); } }
6829a76a72e1d13e53da18d267771f44139778a9
[ "Java", "INI" ]
8
Java
SuphieLiang/ssm_shiro_demo
fe40d188f5ba361ca6a3adfdcef68c35bf9c2254
936f9bb6d3413676339da2967a2f45cc730a843f
refs/heads/master
<file_sep># algorithms Implementation of various algorithms in Python. <file_sep>from collections import OrderedDict from graphs import DirectedGraph, Edge, Node class GraphSearch(DirectedGraph): def bfs(self, src, dest): level = {src: None} parent = {src: None} counter = 1 queue = [src] while queue: node = queue.pop(0) for child in self.EdgesOf(node): if child not in level: parent[child] = node level[child] = counter if child == dest: break queue.append(child) counter += 1 return parent, level def bfsShortest(self, src, dest): path = [] parent, level = self.bfs(src=src, dest=dest) dest_level = level[dest] while dest_level > 0: path.append(str(dest)) dest = parent[dest] dest_level -= 1 return path[::-1] def printpath(self, path): return "->".join([str(n) for n in path]) def dfs(self, src, dest, path, shortest): path[src] = None if src == dest: return path for child in self.EdgesOf(src): if child not in path: if shortest == None or len(path) < len(shortest): new_path = self.dfs(child, dest, path.copy(), shortest) if new_path != None: shortest = new_path return shortest def dfsShortest(self, src, dest): return self.dfs(src, dest, OrderedDict(), None) def build_and_test(): nodes = [] for name in range(6): nodes.append(Node(str(name))) # Create 6 nodes g = GraphSearch() for n in nodes: g.addNode(n) g.addEdge(Edge(nodes[0], nodes[1])) g.addEdge(Edge(nodes[1], nodes[2])) g.addEdge(Edge(nodes[2], nodes[3])) g.addEdge(Edge(nodes[2], nodes[4])) g.addEdge(Edge(nodes[3], nodes[4])) g.addEdge(Edge(nodes[3], nodes[5])) g.addEdge(Edge(nodes[0], nodes[2])) g.addEdge(Edge(nodes[1], nodes[0])) g.addEdge(Edge(nodes[3], nodes[1])) g.addEdge(Edge(nodes[4], nodes[0])) # Print Directed Graph print("Graph:\n{}".format(g)) # Shortest path using BFS. bfspath = g.bfsShortest(nodes[0], nodes[5]) print("BFS Shortest path: {}".format(g.printpath(path=bfspath))) print("BFS Shortest path test passed:", bfspath == ["0", "2", "3", "5"]) # Shortest path using DFS. dfspath = g.dfsShortest(nodes[0], nodes[5]) print("DFS Shortest path: {}".format(g.printpath(path=dfspath))) print( "DFS Shortest path test passed:", [str(n) for n in dfspath] == ["0", "2", "3", "5"], ) if __name__ == "__main__": build_and_test() <file_sep>class MergeSort: def __init__(self, array): self.array = array self.size = len(array) @staticmethod def _merge(left, right): """ Merges left and right array into a single array. Assumes, left and right are sorted independently sorted. """ resultant = [] i, j = 0, 0 while i < len(left) and j < len(right): if left[i] < right[j]: resultant.append(left[i]) i += 1 else: resultant.append(right[j]) j += 1 while i < len(left): resultant.append(left[i]) i += 1 while j < len(right): resultant.append(right[j]) j += 1 return resultant def sort(self): """ Sorts the array using Merge Sort algorithm. 1. Divide the array into 2 arrays of size n/2. 2. Merge the two sorted arrays of size n/2. 3. Resultant is a sorted array of size n. Time Complexity: O(n*log(n)) Space Complexity: n """ self.array = self._sort(self.array) return self.array @classmethod def _sort(cls, array): if len(array) < 2: return array mid = len(array) // 2 left = cls._sort(array[:mid]) right = cls._sort(array[mid:]) return cls._merge(left=left, right=right) def __repr__(self): return str(self.array) def __str__(self): return self.__repr__() <file_sep>""" Dijkstra's algorithm, with edges represented as adjancecy matrix. """ class Graph: def __init__(self, vertices): self.vertices = [vertex for vertex in range(vertices)] self.graph = [[0 for column in range(vertices)] for row in range(vertices)] def printgraph(self): for row in self.graph: for col in row: print(col, end="\t") print("") def shortestPath(self, src, dest): visited = set() parent = dict() distances = dict() for vertex in self.vertices: distances[vertex] = float("inf") distances[src] = 0 parent[src] = None for u in self.vertices: u = self.findMinimum(distances, visited) if u not in visited: visited.add(u) for v in self.vertices: if v not in visited and self.graph[u][v]: weight = self.graph[u][v] parent, distances = self.relax(u, v, weight, distances, parent) if v == dest: break return parent, distances def findMinimum(self, distances, visited): min_val, min_key = None, None for key, val in distances.items(): if key not in visited: if min_val and val < min_val: min_key, min_val = key, val elif min_val is None: min_key, min_val = key, val return min_key def relax(self, u, v, weight, distances, parent): if distances[v] > distances[u] + weight: distances[v] = distances[u] + weight parent[v] = u return parent, distances def printpath(self, parent, dest): if parent[dest] == None: print("Path:", dest, end=",") return self.printpath(parent, parent[dest]) print(dest, end=",") def test(): g = Graph(9) g.graph = [ [0, 4, 0, 0, 0, 0, 0, 8, 0], [4, 0, 8, 0, 0, 0, 0, 11, 0], [0, 8, 0, 7, 0, 4, 0, 0, 2], [0, 0, 7, 0, 9, 14, 0, 0, 0], [0, 0, 0, 9, 0, 10, 0, 0, 0], [0, 0, 4, 14, 10, 0, 2, 0, 0], [0, 0, 0, 0, 0, 2, 0, 1, 6], [8, 11, 0, 0, 0, 0, 1, 0, 7], [0, 0, 2, 0, 0, 0, 6, 7, 0], ] g.printgraph() src, dest = (0, 8) print("\nsrc:{}, dest:{}".format(src, dest)) parent, dist = g.shortestPath(src, dest) g.printpath(parent, dest) print("\nTotal distance covered:", dist[dest]) src, dest = (3, 6) print("\nsrc:{}, dest:{}".format(src, dest)) parent, dist = g.shortestPath(src, dest) g.printpath(parent, dest) print("\nTotal distance covered:", dist[dest]) if __name__ == "__main__": test() <file_sep>class Node: def __init__(self, val): self.parent = None self.left = None self.right = None self.val = val def __str__(self): return self.val def __repr__(self): return self.__str__() class BinarySearchTree: def __init__(self): self.root = None def insert(self, val): """ Insert a value in the binary tree. If the val is less than value of node, then check for insertion on left child else check for insertion on right child of the node. Time complexity: O(h), h is the height of the tree. """ node = self.root if node is None: self.root = Node(val=val) return while 1: if node.val < val: if node.right: node = node.right else: node.right = Node(val=val) node.right.parent = node break elif node.val >= val: if node.left: node = node.left else: node.left = Node(val=val) node.left.parent = node break def _inorder(self, root): """ Traversal: L -> P -> R """ if root: self._inorder(root.left) print(root.val) self._inorder(root.right) def _preorder(self, root): """ Traversal: P -> L -> R """ if root: print(root.val) self._preorder(root.left) self._preorder(root.right) def _postorder(self, root): """ Traversal: L -> R -> P """ if root: self._postorder(root.left) self._postorder(root.right) print(root.val) def traversal(self, order_type="in"): """ Print the binary tree, based on the type of traversal. All traversals have time complexity of O(n). """ root = self.root if order_type == "in": self._inorder(root=root) elif order_type == "pre": self._preorder(root=root) elif order_type == "post": self._postorder(root=root) else: print( "Invalid traversal type. Available types: 'in', 'post' or 'pre'" ) def find(self, key): """ Give a key (value), finds the value in the tree. Time Complexity: O(h), h is height of the tree. """ root = self.root while root: if root.val == key: break elif root.val < key: root = root.left else: root = root.right return root def maximum(self, node): """ Given a node, find the maximum value in the subtree of that node. Time complexity: O(h), h is the height of the tree. """ if not node: return node root = node while root.right: root = root.right return root def minimum(self, node): """ Given a node, finds the minimum value in the subtree of the node. Time complexity: O(h), h is the height of the tree. """ if not node: return node root = node while root.left: root = root.left return root def successor(self, key): """ Finds the node with the value equal to key. If right node exists, then find the left-most node in the right sub-tree. Else, find the nearest ancestor (parent) whose left child is also an ancestor of the node. Time complexity: O(h), h is the height of the tree. """ node = self.find(key=key) if node.right: return self.minimum(node=node.right) parent = node.parent while parent and parent.right == node: node = parent parent = parent.parent return parent def predecessor(self, key): """ Finds the node with the value equal to key. If left node exists, then find the right-most node in the left-subtree. Else, find the nearest ancestor (parent) whose right child is also an ancestor of the code. Time complexity: O(h), h is the height of the tree. """ node = self.find(key=key) if node.left: return self.maximum(node=node.left) parent = node.parent while parent and parent.left == node: node = parent parent = parent.parent return parent def _transplant(self, node, subnode): if not node.parent: self.root = subnode parent = node.parent if parent.left == node: parent.left = subnode else: parent.right = subnode if subnode and not subnode.parent: subnode.parent = parent def delete(self, node): """ Given a node, deletes a node from the subtree. Time complexity: O(h), h is the height of the tree. """ if not node.left and not node.right: self._transplant(node=node, subnode=None) elif not node.left: self._transplant(node=node, subnode=node.right) elif not node.right: self._transplant(node=node, subnode=node.left) else: subnode = self.minimum(node=node.right) if not subnode.parent == node: self._transplant(node=subnode, subnode=subnode.right) subnode.right = node.right subnode.right.parent = subnode self._transplant(node=node, subnode=subnode) subnode.left = node.left subnode.left.parent = subnode <file_sep>class BinaryInsertionSort: """ Binary Insertion sort performs search and compare operation using binary search. Thus the search and compare operation takes O(log(n)) time, while swaps takes O(n) time. Time Complexity: O(n*(log(n) + n)) ≈ O(n^2) """ def __init__(self, array): self.array = array self.size = len(array) def sort(self): """ Sorts the elements of the array in ascending order Time complexity: O(n^2) Space complexity: O(1) :param array: :return: sorted array """ if self.size < 2: return self.array for i in range(1, self.size): # search and compare function idx = self._search_lower_element_idx(key=i) # swap function self._swap_elements(src=i, dest=idx) return self.array def _swap_elements(self, src, dest): """ Swaps all elements in reverse order i.e. starting from src index till the destination index. Time Complexity: O(n) """ while src > dest: if self.array[src] < self.array[src-1]: temp = self.array[src] self.array[src] = self.array[src - 1] self.array[src - 1] = temp src = src - 1 def _search_lower_element_idx(self, key): """ Search for the index in the array[0, key-1], whose value is less than the value at the key index of the array. Compare & search Time Complexity: O(log(n)) """ start, end = 0, len(self.array[:key-1]) mid = (start + end) // 2 while start < end: if self.array[mid] > self.array[key]: end = mid else: return mid + 1 mid = (start + end) // 2 return mid <file_sep>class Heap: """ Heaps are implementation of priority queues. Max Heap Property: The key of a node is greater than the keys of its children. """ def __init__(self, array): self.array = array self.heap_size = len(array) self.is_heap = False def _build_max_heap(self): """ Builds a max heap, from an ordered array. Time Complexity: O(n) Space Complexity: O(1) """ n = self.heap_size // 2 for i in range(n, -1, -1): self._max_heapify(i) self.is_heap = True def _max_heapify(self, i): """ Checks if the parent i satisfies the heap property. If not then fix the heap property in the subtree root. Assumption: Trees rooted at left(i) and right(i) are max heaps. Time Complexity: O(log(n)) Space Complexity: O(1) """ left = 2 * i + 1 right = 2 * i + 2 largest = i if left < self.heap_size and self.array[left] > self.array[largest]: largest = left if right < self.heap_size and self.array[right] > self.array[largest]: largest = right if largest != i: temp = self.array[i] self.array[i] = self.array[largest] self.array[largest] = temp self._max_heapify(i=largest) def sort(self): """ Builds a max heap, if not already build. Swaps the first/ root element (largest) with the last element. Reduce the heap size by 1 and call max_heapify to fix the heap property at the root. Continue this process, till heap size is 0. Time Complexity: O(n*log(n)) Space Complexity: O(1) """ if not self.is_heap: self._build_max_heap() while self.heap_size > 0: self.array[0], self.array[self.heap_size - 1] = ( self.array[self.heap_size - 1], self.array[0], ) self.heap_size -= 1 self._max_heapify(i=0) self.heap_size = len(self.array) return self.array def __repr__(self): return str(self.array) def __str__(self): return self.__repr__() class MinHeap: """ Implementation of priority queue using min heap. """ def __init__(self, array): self.array = array self.heap_size = len(array) def build_min_heap(self): """ Builds the min heap, with the min element on the top. """ n = self.heap_size // 2 for i in reversed(range(n)): self._min_heapify(i) def _min_heapify(self, curr_index): left = 2 * curr_index + 1 right = 2 * curr_index + 2 smallest = curr_index if left < self.heap_size and self.array[left] < self.array[smallest]: smallest = left if right < self.heap_size and self.array[right] < self.array[smallest]: smallest = right if smallest != curr_index: temp = self.array[curr_index] self.array[curr_index] = self.array[smallest] self.array[smallest] = temp self._min_heapify(curr_index=smallest) def _perc_up(self, curr_index): if curr_index > 0: parent_idx = curr_index // 2 if self.array[parent_idx] > self.array[curr_index]: temp = self.array[parent_idx] self.array[parent_idx] = self.array[curr_index] self.array[curr_index] = temp self._perc_up(parent_idx) @property def getMinValue(self): min_val = None if self.heap_size: min_val = self.array[0] return min_val @property def extractMinValue(self): min_val = None if self.heap_size: min_val = self.array[0] self.array[0], self.array[-1] = self.array[-1], self.array[0] self.array.pop(-1) self.heap_size -= 1 self._min_heapify(curr_index=0) return min_val def decreaseKey(self, key, value): self.array[key] = value if value < self.getMinValue(): self._perc_up(curr_index=key) def insertValue(self, value): self.array.append(value) self.heap_size += 1 self._perc_up(curr_index=self.heap_size - 1) def __repr__(self): return str(self.array[: self.heap_size]) def __str__(self): return self.__repr__() <file_sep>class RollingHashMap: def __init__(self, x, a=7, p=1009): self.a = a self.seqlen = len(x) n = self.seqlen - 1 self.p = p u = 0 for c in x: u += ord(c)*(self.a ** n) n -= 1 self.r = u % p def append(self, c): self.r = (self.r * self.a + ord(c)) % self.p def skip(self, c): self.r -= ord(c) * ((self.a**self.seqlen) % self.p) self.r = self.r % self.p def __str__(self): return str(self.r) def __repr__(self): return self.__str__() def __eq__(self, other): return self.r == other.r class SubString: def __init__(self, string): self.string = string def substringcheck(self, substring): rs = RollingHashMap(x=substring) rt = RollingHashMap(x=self.string[:len(substring)]) if rt == rs: if substring == self.string[:len(substring)]: return True for i in range(len(substring), len(self.string)): rt.append(self.string[i]) rt.skip(self.string[i - len(substring)]) if rs == rt: if substring == self.string[i-len(substring)+1: i+1]: return True return False if __name__ == '__main__': t = "This is a sample text" s = "samp" h = SubString(string=t) print(h.substringcheck(substring=s)) <file_sep>from cycledetection import ACyclicGraph, Node, Edge class TopologicalSort(ACyclicGraph): """ Since in a directed acyclic graph, unrelated vertices may be present, thus there are serveral topological sortings of G. """ def _sort(self, src, parent, order): for child in self.EdgesOf(src): if child not in parent: parent[child] = src order = self._sort(child, parent, order) order.append(child) return order def sort(self): parent = dict() order = [] for node in self.nodes: if node not in parent: parent[node] = None order = self._sort(node, parent, order) order.append(node) return order[::-1] def test(): nodes = [] for name in range(6): nodes.append(Node(str(name))) graph = TopologicalSort() for node in nodes: graph.addNode(node) graph.addEdge(Edge(nodes[5], nodes[2])) graph.addEdge(Edge(nodes[5], nodes[0])) graph.addEdge(Edge(nodes[4], nodes[0])) graph.addEdge(Edge(nodes[4], nodes[1])) graph.addEdge(Edge(nodes[2], nodes[3])) graph.addEdge(Edge(nodes[3], nodes[1])) print("Graph:\n{}".format(graph)) if graph.iscyclic(): print("Graph is cyclic, cannot perform toplogical sort.") return print("Graph is acyclic.") sorted_order = graph.sort() print("Topologically sorted graph....") print("-->".join([str(node) for node in sorted_order])) if __name__ == "__main__": test() <file_sep>class Node: """ Node representation in a graph. Node is also refered to as vertices. """ def __init__(self, val): self.val = val def __str__(self): return str(self.val) class Edge: """ Edge representation in the graph. """ def __init__(self, src, dest): self._src = src self._dest = dest @property def sourceNode(self): return self._src @property def destNode(self): return self._dest def __str__(self): return u"{} -> {}".format(self._src, self._dest) class DirectedGraph: """ Directed Graph, assumes source node always points to destination node. """ def __init__(self): self.nodes = set([]) # Adjacency list, to keep track of a node and its corresponding edges self.edges = {} def addNode(self, node): """ Adds a node/ vertex in the graph. """ if node in self.nodes: raise ValueError("Duplicate entry") self.nodes.add(node) self.edges[node] = [] def addEdge(self, edge): """ Adds an edge between two nodes/vertex. """ src = edge.sourceNode dest = edge.destNode if src not in self.nodes: raise ValueError("Node not in graph {}".format(src)) if dest not in self.nodes: raise ValueError("Node not in graph {}".format(dest)) self.edges[src].append(dest) def __str__(self): output = "" for node in self.nodes: for edge in self.EdgesOf(node): output += "{} -> {} \n".format(node, edge) return output[:-1] def hasNode(self, node): return node in self.nodes def EdgesOf(self, node): return self.edges[node] class Graph(DirectedGraph): """ Undirected graph """ def addEdge(self, edge): super().addEdge(edge=edge) src = edge.sourceNode dest = edge.destNode revEdge = Edge(src=dest, dest=src) super().addEdge(edge=revEdge) def test(): vertices = [] for i in range(0, 3): vertex = Node(i) vertices.append(vertex) edges = [Edge(vertices[0], vertices[1]), Edge(vertices[0], vertices[2])] digraph = DirectedGraph() for vertex in vertices: digraph.addNode(vertex) for edge in edges: digraph.addEdge(edge) print("Directed Graph:\n",digraph, sep='') undirectgraph = Graph() for vertex in vertices: undirectgraph.addNode(vertex) for edge in edges: undirectgraph.addEdge(edge) print("Undirected Graph:\n",undirectgraph, sep='') if __name__ == "__main__": test() <file_sep>""" LIS: Longest Increasing Subsequeunce. Returns the length of the longest increasing subsequence Example: arr: [3, 10, 2, 1, 20] output: 3 arr: [50, 3, 10, 7, 40, 80] output: 4 Reference: https://www.geeksforgeeks.org/longest-increasing-subsequence-dp-3/ """ def lis(arr): """ Time Complexity: O(n^2) Space Complexity: O(n) """ n = len(arr) dp = [1 for i in range(n)] for i in range(1, n): for j in range(i): if arr[i] > arr[j] and dp[i] < dp[j] + 1: dp[i] = dp[j] + 1 longest_subsequence_len = None for val in dp: if longest_subsequence_len is None or longest_subsequence_len < val: longest_subsequence_len = val return longest_subsequence_len if __name__ == "__main__": arr= [50, 3, 10, 7, 40, 80] expected_output = 4 output = lis(arr) print(f'Array: {arr},\nExpected Output: {expected_output}, Output: {output}')<file_sep>from graph_search import DirectedGraph, Edge, Node class ACyclicGraph(DirectedGraph): def _iscyclic(self, src, parent, stack): stack.add(src) for child in self.EdgesOf(src): if child in stack: return True if child not in parent: parent[child] = src if self._iscyclic(child, parent, stack): return True stack.remove(src) return False def iscyclic(self): parent = dict() stack = set() for node in self.nodes: if node not in parent: parent[node] = None if self._iscyclic(node, parent, stack): return True return False def test(): nodes = [] for name in range(4): nodes.append(Node(str(name))) # Create 4 nodes graph = ACyclicGraph() for node in nodes: graph.addNode(node) graph.addEdge(Edge(nodes[0], nodes[1])) graph.addEdge(Edge(nodes[0], nodes[2])) graph.addEdge(Edge(nodes[1], nodes[2])) graph.addEdge(Edge(nodes[2], nodes[0])) graph.addEdge(Edge(nodes[2], nodes[3])) graph.addEdge(Edge(nodes[3], nodes[3])) print("Graph:\n{}".format(graph)) status = graph.iscyclic() print("Is graph cyclic: {}".format(status)) graph = ACyclicGraph() for node in nodes: graph.addNode(node) graph.addEdge(Edge(nodes[0], nodes[1])) graph.addEdge(Edge(nodes[1], nodes[3])) graph.addEdge(Edge(nodes[1], nodes[2])) graph.addEdge(Edge(nodes[3], nodes[2])) print("Graph:\n{}".format(graph)) status = graph.iscyclic() print("Is graph cyclic: {}".format(status)) graph = ACyclicGraph() for node in nodes[:-1]: graph.addNode(node) graph.addEdge(Edge(nodes[0], nodes[1])) graph.addEdge(Edge(nodes[1], nodes[2])) graph.addEdge(Edge(nodes[2], nodes[0])) print("Graph:\n{}".format(graph)) status = graph.iscyclic() print("Is graph cyclic: {}".format(status)) if __name__ == "__main__": test()
a8379ce3a4b0aeaac19b4a21f98b36599446359d
[ "Markdown", "Python" ]
12
Markdown
shubham3121/algorithms
476d13ce6550f3cc500e161e2dba23bde0d576b0
4536769733fa9975088a96155c91832121bff0dc
refs/heads/master
<repo_name>asiellb/suspicious-serverless<file_sep>/src/services/__test__/url_redirection.spec.ts import * as chai from "chai"; import * as chaiAsPromised from "chai-as-promised"; import * as nock from "nock"; chai.use(chaiAsPromised); // chai.should(); const expect = chai.expect; import { RedirectionResolver } from "../redirection_resolver"; describe("RedirectionResolver", () => { beforeEach(() => { nock("http://200.response.com") .get(/.+/) .reply(200, "OK"); nock("http://301.response.com") .get(/.+/) .reply(301, "Moved Permanently", { Location: "https://www.twitter.com/foo", }); nock("http://302.response.com") .get(/.+/) .reply(302, "Moved Temporarily", { Location: "https://www.facebook.com/", }); nock("http://404.response.com") .get(/.+/) .reply(404, "Not Found"); nock("http://502.response.com") .get(/.+/) .reply(502, "Bad Gateway"); nock("http://such.stuck.request.com") .get(/.+/) .socketDelay(7000) .reply(302, "Moved Temporarily", { Location: "https://www.facebook.com", }); nock("http://such.slow.response.com") .get(/.+/) .delay({ head: 7000, body: 7000 }) .reply(302, "Moved Temporarily", { Location: "https://www.facebook.com", }); }); afterEach(() => { nock.cleanAll(); }); describe("._getRedirectionUrl", () => { let resolver: any; // for access to private methods beforeEach(() => { resolver = new RedirectionResolver(); }); it("should return nothing if server respond with non-3xx status code", async () => { expect(await (resolver as any).getRedirectionUrl("http://200.response.com/0x1234")).to.be.eq(undefined); expect(await (resolver as any).getRedirectionUrl("http://404.response.com/a.bc.1/e")).to.be.eq(undefined); expect(await (resolver as any).getRedirectionUrl("http://502.response.com/foo/bar.baz")).to.be.eq(undefined); }); it("should return redirection url if server respond with 3xx status code", async () => { expect(await (resolver as any).getRedirectionUrl("http://301.response.com/0xffff")) .to.be.eq("https://www.twitter.com/foo"); expect(await (resolver as any).getRedirectionUrl("http://302.response.com/watch-out-facebook")) .to.be.eq("https://www.facebook.com/"); }); it("should throw error on read timeout (socket connected, but slow response)", async () => { expect((resolver as any).getRedirectionUrl("http://such.slow.response.com/some/path")) .to.be.rejectedWith(Error); }); it("should throw error on connect timeout (socket connect timeout)", async () => { expect((resolver as any).getRedirectionUrl("http://such.stuck.request.com/foo/bar.baz")) .to.be.rejectedWith(Error); }); it("should ignore response body to prevent DoS attacks", async () => { // tslint:disable-next-line expect(await (resolver as any).getRedirectionUrl("http://download.blender.org/peach/bigbuckbunny_movies/big_buck_bunny_720p_h264.mov")).to.be.eq(undefined); }); }); describe(".resolve", () => { let resolver: RedirectionResolver; // for access to private methods beforeEach(() => { resolver = new RedirectionResolver(); nock("http://click.gl") .get("/L8NUWG") .reply(302, "Moved Temporarily", { Location: "http://boxs.kr/1K5YT", }); nock("http://boxs.kr") .get("/1K5YT") .reply(302, "Moved Temporarily", { Location: "http://boxs.kr/index.php?url=1K5YT", }) .get("/index.php?url=1K5YT") .reply(302, "Moved Temporarily", { Location: "http://iii.im/1aX9", }); nock("http://iii.im") .get("/1aX9") .reply(302, "Moved Temporarily", { Location: "http://auto-man.kr/%EC%9C%A4%EC%88%98%EC%98%811", }); nock("http://auto-man.kr") .get("/%EC%9C%A4%EC%88%98%EC%98%811") .reply(302, "Moved Temporarily", { // tslint:disable-next-line Location: "https://play.google.com/store/apps/details?id=kr.automan.app2&referrer=e3JlY29tbToi7Jyk7IiY7JiBMSJ9", }); nock("http://such.stuck.request.com") .get(/.+/) .socketDelay(7000) .reply(302, "Moved Temporarily", { Location: "https://www.facebook.com", }); nock("http://such.slow.response.com") .get(/.+/) .delay({ head: 7000, body: 7000 }) .reply(302, "Moved Temporarily", { Location: "https://www.facebook.com", }); }); afterEach(() => { nock.cleanAll(); }); it("should return redirect chain", async () => { const urls = await resolver.resolve("http://click.gl/L8NUWG"); expect(urls).to.be.deep.eq([ "http://click.gl/L8NUWG", "http://boxs.kr/1K5YT", "http://boxs.kr/index.php?url=1K5YT", "http://iii.im/1aX9", "http://auto-man.kr/%EC%9C%A4%EC%88%98%EC%98%811", "https://play.google.com/store/apps/details?id=kr.automan.app2&referrer=e3JlY29tbToi7Jyk7IiY7JiBMSJ9", ]); }); it("should handle read timeout (socket connected, but slow response)", async () => { const urls = await resolver.resolve("http://such.slow.response.com/some/path"); expect(urls).to.be.deep.eq([ "http://such.slow.response.com/some/path", ]); }); it("should handle connect timeout (socket connect timeout)", async () => { const urls = await resolver.resolve("http://such.stuck.request.com/foo/bar.baz"); expect(urls).to.be.deep.eq([ "http://such.stuck.request.com/foo/bar.baz", ]); }); }); }); <file_sep>/readme.md # suspicious-serverless ## Business Domain A collection of utilities for analyze suspicious content, using Serverless Framework. ## Responsibility - Resolve redirection chain (urls) from given url ## Usage ### Get redirection chain (urls) Resolve redirection chain (urls) from given url. #### Request ``` GET /redirection-chain?url=https://vingle.net Host: API_GATEWAY_ID.execute-api.YOUR_REGION.amazonaws.com ``` #### Response ``` HTTP/1.1 200 OK Content-Type: application/json; charset=utf8 ["https://vingle.net", "https://www.vingle.net/"] ``` ## Maintainer <file_sep>/src/services/__test__/content_dispatcher.spec.ts import * as chai from "chai"; import * as chaiAsPromised from "chai-as-promised"; import * as nock from "nock"; import * as sinon from "sinon"; chai.use(chaiAsPromised); const expect = chai.expect; import * as puppeteer from "puppeteer"; import * as qs from "qs"; import { server as mockServer } from "./mock_server"; import { ContentDispatcher } from "../content_dispatcher"; import * as serverlessChrome from "../serverless_chrome"; const MOCK_SERVER_PORT = 3001; const MOCK_SERVER_BASE_URL = `http://127.0.0.1:${MOCK_SERVER_PORT}`; describe("ContentDispatcher", () => { before(async () => { await new Promise((resolve) => { mockServer.listen(MOCK_SERVER_PORT, resolve); }); }); after(async () => { await new Promise((resolve) => { mockServer.close(resolve); }); }); describe("#launch", () => { let sandbox: sinon.SinonSandbox; beforeEach(() => { sandbox = sinon.sandbox.create(); }); afterEach(() => { sandbox.restore(); }); context("when browser already exists", () => { let dispatcher: ContentDispatcher; let puppeteerLaunchStub: sinon.SinonStub; let dispatcherShutdownStub: sinon.SinonStub; beforeEach(async () => { dispatcher = new ContentDispatcher(true); puppeteerLaunchStub = sandbox.stub(puppeteer, "launch").resolves({}); dispatcherShutdownStub = sandbox.stub(dispatcher, "shutdown").resolves(); await dispatcher.launch(); }); it("should re-use chrome instance if available", async () => { sandbox.stub((dispatcher as any), "browser").value({ version: sandbox.stub().resolves("Chrome/12.34.56"), }); await dispatcher.launch(); expect(puppeteerLaunchStub.callCount).to.be.eq(1); }); it("should shutdown previous chrome instance if not available", async () => { sandbox.stub((dispatcher as any), "browser").value({ version: sandbox.stub().rejects(new Error("foo")), close: sandbox.stub().resolves(), }); await dispatcher.launch(); expect(puppeteerLaunchStub.callCount).to.be.eq(2); expect(dispatcherShutdownStub.callCount).to.be.eq(1); }); }); context("when serverless-chrome disabled", () => { let dispatcher: ContentDispatcher; let puppeteerLaunchStub: sinon.SinonStub; beforeEach(async () => { dispatcher = new ContentDispatcher(true); puppeteerLaunchStub = sandbox.stub(puppeteer, "launch").resolves({}); }); it("should launch puppeteer bundled chromium instance", async () => { await dispatcher.launch(); expect(puppeteerLaunchStub.called).to.be.eq(true); }); }); context("when serverless-chrome enabled", () => { let dispatcher: ContentDispatcher; let launchChromeStub: sinon.SinonStub; let getDebuggerUrlStub: sinon.SinonStub; let puppeteerConnectStub: sinon.SinonStub; const MOCK_DEBUGGER_BASE_URL = "http://127.0.0.1:54321"; const MOCK_DEBUGGER_WS_ENDPOINT = "ws://12172.16.17.32:54321/devtools/browser/12345678"; beforeEach(async () => { dispatcher = new ContentDispatcher(); launchChromeStub = sandbox.stub(serverlessChrome, "launchChrome").resolves({ url: MOCK_DEBUGGER_BASE_URL, }); getDebuggerUrlStub = sandbox.stub(dispatcher as any, "getDebuggerUrl").resolves(MOCK_DEBUGGER_WS_ENDPOINT); puppeteerConnectStub = sandbox.stub(puppeteer, "connect").resolves({}); }); it("should launch puppeteer bundled chromium instance", async () => { await dispatcher.launch(); expect(launchChromeStub.called).to.be.eq(true); expect(getDebuggerUrlStub.called).to.be.eq(true); expect(puppeteerConnectStub.calledWith({ browserWSEndpoint: MOCK_DEBUGGER_WS_ENDPOINT, })); }); }); }); describe("#dispatch", () => { let dispatcher: ContentDispatcher; beforeEach(() => { dispatcher = new ContentDispatcher(true); }); context("when dispatcher hasn't been launched", () => { it("should throw error if dispatcher has not been launched", async () => { await expect(dispatcher.dispatch(`${MOCK_SERVER_BASE_URL}/redirection/http`)).to.be.rejectedWith(Error); }); }); context("when dispatcher has been launched", () => { beforeEach(async () => { await dispatcher.launch(); }); afterEach(async () => { await dispatcher.shutdown(); }); it("should return dispatched content", async () => { const content = await dispatcher.dispatch(`${MOCK_SERVER_BASE_URL}/redirection/http`); expect(content).to.be.deep.eq({ navigatedUrls: [`${MOCK_SERVER_BASE_URL}/?${qs.stringify({ from: "/redirection/http" })}`], // tslint:disable-next-line html: "<!DOCTYPE html><html lang=\"en\"><head>\n <meta charset=\"UTF-8\">\n <title>Hello</title>\n</head>\n<body>\n <p>HOLA</p>\n\n</body></html>", }); }); it("should wait specified delay and return dispatched content", async () => { const content = await dispatcher.dispatch(`${MOCK_SERVER_BASE_URL}/redirection/js`, 2000); expect(content).to.be.deep.eq({ navigatedUrls: [ `${MOCK_SERVER_BASE_URL}/redirection/js`, `${MOCK_SERVER_BASE_URL}/?${qs.stringify({ from: "/redirection/js" })}`, ], // tslint:disable-next-line html: "<!DOCTYPE html><html lang=\"en\"><head>\n <meta charset=\"UTF-8\">\n <title>Hello</title>\n</head>\n<body>\n <p>HOLA</p>\n\n</body></html>", }); }); }); }); describe("#shutdown", () => { let dispatcher: ContentDispatcher; let closeStub: sinon.SinonStub; const sandbox = sinon.sandbox.create(); beforeEach(() => { dispatcher = new ContentDispatcher(); closeStub = sandbox.stub().resolves(); sandbox.stub((dispatcher as any), "browser").value({ close: closeStub, }); }); afterEach(() => { sandbox.restore(); }); it("should shutdown puppeteer instance", async () => { await dispatcher.shutdown(); expect(closeStub.calledOnce).to.be.eq(true); }); context("when serverless-chrome enabled", () => { let killStub: sinon.SinonStub; beforeEach(() => { killStub = sandbox.stub().resolves(); sandbox.stub((dispatcher as any), "slsChrome").value({ kill: killStub, }); }); it("should kill chrome process also", async () => { await dispatcher.shutdown(); expect(killStub.called).to.be.eq(true); }); }); }); describe("#getDebuggerUrl", async () => { let dispatcher: ContentDispatcher; const MOCK_DEBUGGER_HOST = "127.0.0.1"; const MOCK_DEBUGGER_PORT = 1234; const MOCK_DEBUGGER_BASE_URL = `http://${MOCK_DEBUGGER_HOST}:${MOCK_DEBUGGER_PORT}`; const MOCK_DEBUGGER_WS_ENDPOINT = `ws://${MOCK_DEBUGGER_HOST}:${MOCK_DEBUGGER_PORT}/devtools/browser/12345678-1234`; beforeEach(() => { dispatcher = new ContentDispatcher(); nock(MOCK_DEBUGGER_BASE_URL) .get("/json/version") .reply(200, { webSocketDebuggerUrl: MOCK_DEBUGGER_WS_ENDPOINT, }); }); afterEach(() => { nock.cleanAll(); }); it("should return debugger url", async () => { const debuggerUrl = await (dispatcher as any).getDebuggerUrl(MOCK_DEBUGGER_BASE_URL); expect(debuggerUrl).to.be.eq(MOCK_DEBUGGER_WS_ENDPOINT); }); }); }); <file_sep>/src/api/routes/index.ts import { Parameter, Route, Routes, RoutingContext, } from "vingle-corgi"; import * as Joi from "joi"; import { ContentDispatcher } from "../../services/content_dispatcher"; import { RedirectionResolver } from "../../services/redirection_resolver"; export const routes: Routes = [ Route.GET( "/redirection-chain", { desc: "List of redirection chain urls", operationId: "getRedirectionChain", }, { url: Parameter.Query(Joi.string().required()), }, async function(this: RoutingContext) { const url = this.params.url as string; const resolver = new RedirectionResolver(); return this.json({ data: await resolver.resolve(url), }); }, ), Route.GET( "/content", { desc: "Dispatch content of given url", operationId: "dispatchContent", }, { url: Parameter.Query(Joi.string().required()), }, async function(this: RoutingContext) { const url = this.params.url as string; // We can't re-use chrome instance now because currently serverless-chrome is not stable. // launching new chrome process will cause additional processing time (approx. 600ms) // @see https://github.com/adieuadieu/serverless-chrome/issues/41 const dispatcher = new ContentDispatcher(!!process.env.DISABLE_SERVERLESS_CHROME); await dispatcher.launch(); const content = await dispatcher.dispatch(url, 3000); await dispatcher.shutdown(); return this.json({ data: content, }); }, ), ]; <file_sep>/src/services/redirection_resolver.ts import * as _ from "lodash"; import * as request from "request"; import * as URL from "url"; const linkify = require("linkify-it")(); // tslint:disable-line function linkifyMatch(text: string) { const matchResult = linkify.match(text); if (matchResult == null) { return []; } else { return linkify.match(text) as Array<{ schema: string index: number, lastIndex: number, raw: string, text: string, url: string, }>; } } export class RedirectionResolver { constructor( private timeout: number = 5000, // tslint:disable-next-line private userAgent: string = "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2228.0 Safari/537.36", ) {} public async resolve(url: string) { const MAX_REDIRECTS = 10; let redirectCount = 0; const urls: string[] = [url]; while (redirectCount < MAX_REDIRECTS) { try { const redirectionUrl = await this.getRedirectionUrl(_.last(urls)!); if (redirectionUrl) { urls.push(...linkifyMatch(redirectionUrl).map((l) => l.url)); } else { break; } redirectCount++; } catch (e) { break; } } return _.uniq(urls); } private async getRedirectionUrl(url: string) { return new Promise((resolve, reject) => { const req = request({ method: "GET", url, headers: { "User-Agent": this.userAgent, }, followRedirect: false, timeout: this.timeout, }).on("error", (e) => { clearTimeout(timerId); req.removeAllListeners(); // clean up event listeners reject(e); }).on("response", (res) => { // we only need to read response headers clearTimeout(timerId); req.removeAllListeners(); // clean up event listeners req.abort(); // stop receiving response body if (res.statusCode! >= 300 && res.statusCode! < 400) { return resolve(URL.resolve(url, res.headers.location)); } resolve(); }); const timerId = setTimeout(() => { req.abort(); reject(new Error(`reached read timeout ${this.timeout}ms`)); }, this.timeout); }) as Promise<string>; } } <file_sep>/src/api/__test__/index.ts import * as chai from "chai"; import * as chaiAsPromised from "chai-as-promised"; import * as sinon from "sinon"; chai.use(chaiAsPromised); chai.should(); const { expect } = chai; import { Namespace, Router } from "vingle-corgi"; import { routes } from "../routes"; import { ContentDispatcher } from "../../services/content_dispatcher"; import { RedirectionResolver } from "../../services/redirection_resolver"; describe("API Handler", () => { let router: Router; const sandbox = sinon.sandbox.create(); beforeEach(() => { router = new Router([ new Namespace("", { children: routes, }), ]); }); afterEach(() => { sandbox.restore(); }); describe("GET /redirection-chain", () => { beforeEach(() => { sandbox.stub(RedirectionResolver.prototype, "resolve") .withArgs("http://bit.ly/2siha2e") .resolves([ "http://bit.ly/2siha2e", "https://www.vingle.net/", ]); }); it("should return redirection urls", async () => { const res = await router.resolve({ path: "/redirection-chain", queryStringParameters: { url: "http://bit.ly/2siha2e", }, httpMethod: "GET", } as any); expect(res.statusCode).to.be.eq(200); expect(JSON.parse(res.body).data).to.be.deep.eq([ "http://bit.ly/2siha2e", "https://www.vingle.net/", ]); }); }); describe("GET /content", () => { const MOCK_URL = "https://www.vingle.net"; const MOCK_CONTENT = { navigatedUrls: [ MOCK_URL, ], html: "Vingle, Very Community", }; beforeEach(() => { sandbox.stub(ContentDispatcher.prototype, "launch") .resolves(); sandbox.stub(ContentDispatcher.prototype, "dispatch") .withArgs(MOCK_URL, 3000) .resolves(MOCK_CONTENT); sandbox.stub(ContentDispatcher.prototype, "shutdown") .resolves(); }); it("should dispatch content of given url", async () => { const res = await router.resolve({ path: "/content", queryStringParameters: { url: MOCK_URL, }, httpMethod: "GET", } as any); expect(res.statusCode).to.be.eq(200); expect(JSON.parse(res.body).data).to.be.deep.eq(MOCK_CONTENT); }); }); }); <file_sep>/scripts/build.js rm -Rf ./dst && tsc && cd src && find . -name '*.json' -type f -exec cp {} ../dst/{} \\; && cd ..
8b72b776b616b85e64bd5713cc16918011b0025d
[ "Markdown", "TypeScript", "JavaScript" ]
7
TypeScript
asiellb/suspicious-serverless
4b272fadb52f4f5c7f794f190ce1e2d37246283a
d14d50bb6315eb85021d99fa73b00e4191aece4d
refs/heads/master
<file_sep># Autodeploy PHP script Create deploy-config.json in your git project. Example deploy-config.json: ```json { "DEPLOY_USER":"user", "DEPLOY_SERVER":"localhost", "DEPLOY_DIR":"/var/www/any/", "REMOTE_GROUP":"apache", "REMOTE_PERM":"0777", "DELETE_FILES":false, "EXCLUDE":[".git/", ".idea/"], "BACKUP_DIR":false, "TIME_LIMIT":"30", "CLEAN_UP":true, "USE_COMPOSER":false, "COMPOSER_OPTIONS":"--no-dev", "VERSION_FILE":"", "EMAIL_ON_ERROR":"<EMAIL>" } ``` Set webhook url in Github/Gitlab (http://localhost/deploy.php?sat=SECRET_TOKEN) Set permisson on DEPLOY_DIR to DEPLOY_USER Run command git push and enjoy autodeploy ;) p.s.: Other branch may be different configuration json file e.g.: `"DEPLOY_DIR":"/var/www/any_feature_branch/",` _Inspired by [Simple PHP Git deploy script by markomarkovic](https://github.com/markomarkovic/simple-php-git-deploy/)_ <file_sep><?php /** * Author: <NAME> (<EMAIL> * Date: 2014.10.20. * @version 1.0 * @link https://github.com/Sanya1991/php-git-deploy-script/ * * Forked from: https://github.com/markomarkovic/simple-php-git-deploy/ * Original script by: <NAME> */ class GitDeploy { /** * Protect the script from unauthorized access by using a secret access token. * If it's not present in the access URL as a GET variable named `sat` * e.g. deploy.php?sat=Bett...s the script is not going to deploy. * * @var string */ public $SECRET_ACCESS_TOKEN; /** * Configuration file in git project * * @var string */ public $JSON_CONFIG_FILE='deploy-config.json'; /** * If Git call webhook then send event (e.g.: push) information in json object format. * * @var string */ public $GIT_HOOK; /** * The branch that's being deployed. * Must be present in the remote repository. * * @var string */ public $BRANCH; /** * The address of the remote Git repository that contains the code that's being * deployed. * If the repository is private, you'll need to use the SSH address. * * @var string */ public $REMOTE_REPOSITORY; /** * The location that the code is going to be deployed to. * Don't forget the trailing slash! * * @var string Full path including the trailing slash */ public $TARGET_DIR; /** * Configuration options * * * The JSON string that is returned by edit() will normally indicate whether or not * the edits were performed successfully. * * Example: * { * "DEPLOY_USER":"user", // Remote server user for rysnc (ssh) login * "DEPLOY_SERVER":"localhost", // Remote server for rysnc * "DEPLOY_DIR":"/var/www/any/", // Remote directory on remote server * "REMOTE_GROUP":"apache", // Remote group on remote server * "REMOTE_PERM":"0777", // Files and folders permissions * "DELETE_FILES":false, // Delete files * "EXCLUDE":[".git/", ".idea/"], // Skip this directory(s) * "BACKUP_DIR":false, // Backup directory on local server * "TIME_LIMIT":"30", // Script maximum execution time * "CLEAN_UP":true, // Delete the temp folder (on local) after copy * "USE_COMPOSER":false, // Use composer (optional) * "COMPOSER_OPTIONS":"--no-dev", // Composer option (optional) * "VERSION_FILE":"", // Version number (optional) * "EMAIL_ON_ERROR":"<EMAIL>" // In case of failure notification e-mail address * } * * Use: $JSON_CONFIG->DEPLOY_USER ( Object, not array ) * * @var JSON object */ public $JSON_CONFIG; /** * $JSON_CONFIG->DEPLOY_USER * $JSON_CONFIG->DEPLOY_SERVER * $JSON_CONFIG->DEPLOY_DIR * $JSON_CONFIG->REMOTE_GROUP * $JSON_CONFIG->REMOTE_PERM * $JSON_CONFIG->DELETE_FILES * $JSON_CONFIG->EXCLUDE * $JSON_CONFIG->BACKUP_DIR * $JSON_CONFIG->TIME_LIMIT * $JSON_CONFIG->CLEAN_UP * $JSON_CONFIG->USE_COMPOSER * $JSON_CONFIG->COMPOSER_OPTIONS * $JSON_CONFIG->VERSION_FILE * $JSON_CONFIG->EMAIL_ON_ERROR */ function __construct($HTTP_RAW_POST_DATA) { $this->SECRET_ACCESS_TOKEN='Sz<PASSWORD>'; $this->TMP_DIR = '/tmp/spgd-' . md5($this->REMOTE_REPOSITORY) . '/'; if (isset($HTTP_RAW_POST_DATA)) { $this->GIT_HOOK = json_decode($HTTP_RAW_POST_DATA); $this->REMOTE_REPOSITORY = $this->GIT_HOOK->repository->homepage . '.git'; $this->BRANCH = end(explode('/', $this->GIT_HOOK->ref)); } if (!isset($_GET['sat']) || $_GET['sat'] !== $this->SECRET_ACCESS_TOKEN || $this->SECRET_ACCESS_TOKEN === '<PASSWORD>') { header('HTTP/1.0 403 Forbidden'); } if (!isset($_GET['sat']) || $_GET['sat'] !== $this->SECRET_ACCESS_TOKEN) { die('<h2>ACCESS DENIED!</h2>'); } if ($this->SECRET_ACCESS_TOKEN === '<PASSWORD>') { die("<h2>You're suffering the consequences!<br>Change the SECRET_ACCESS_TOKEN from it's default value!</h2>"); } if ($this->REMOTE_REPOSITORY === '' or is_null($this->REMOTE_REPOSITORY)) { die('<h2>MISSING REMOTE REPOSITORY!!!</h2>'); } if ($this->BRANCH === '' or is_null($this->BRANCH)) { die('<h2>MISSING BRANCH!!!</h2>'); } } public function CheckEnvironment() { // Check if the required programs are available $requiredBinaries = array('git', 'rsync'); foreach ($requiredBinaries as $command) { $path = trim(shell_exec('which ' . $command)); if ($path == '') { die(sprintf('<div class="error"><b>%s</b> not available. It needs to be installed on the server for this script to work.</div>', $command)); } else { $version = explode("\n", shell_exec($command . ' --version')); printf('<b>%s</b> : %s' . "\n" , $path , $version[0] ); } } } public function GitPull() { if (!is_dir($this->TMP_DIR)) { // Clone the repository into the TMP_DIR $commands[] = sprintf( 'git clone --depth=1 --branch %s %s %s' , $this->BRANCH , $this->REMOTE_REPOSITORY , $this->TMP_DIR ); } else { // TMP_DIR exists and hopefully already contains the correct remote origin // so we'll fetch the changes and reset the contents. $commands[] = sprintf( 'git --git-dir="%s.git" --work-tree="%s" fetch origin %s' , $this->TMP_DIR , $this->TMP_DIR , $this->BRANCH ); $commands[] = sprintf( 'git --git-dir="%s.git" --work-tree="%s" reset --hard FETCH_HEAD' , $this->TMP_DIR , $this->TMP_DIR ); } return $commands; } public function SetConfigFromJson(){ //Read json config file from repo $this->JSON_CONFIG=json_decode(file_get_contents($this->TMP_DIR.$this->JSON_CONFIG_FILE)); // Set target dir $this->TARGET_DIR=$this->JSON_CONFIG->DEPLOY_USER.'@'.$this->JSON_CONFIG->DEPLOY_SERVER.':'.$this->JSON_CONFIG->DEPLOY_DIR; return $this->JSON_CONFIG; } public function AfterGitPull(){ // Update the submodules $commands[] = sprintf( 'git submodule update --init --recursive' ); // Describe the deployed version if ($this->JSON_CONFIG->VERSION_FILE !== '') { $commands[] = sprintf( 'git --git-dir="%s.git" --work-tree="%s" describe --always > %s' , $this->TMP_DIR , $this->TMP_DIR , $this->JSON_CONFIG->VERSION_FILE ); } $requiredBinaries = array(); if ($this->JSON_CONFIG->BACKUP_DIR && $this->JSON_CONFIG->BACKUP_DIR !== false) { $requiredBinaries[] = 'tar'; if (!is_dir($this->JSON_CONFIG->BACKUP_DIR) || !is_writable($this->JSON_CONFIG->BACKUP_DIR)) { die(sprintf('<div class="error">BACKUP_DIR `%s` does not exists or is not writeable.</div>', $this->JSON_CONFIG->BACKUP_DIR)); } } if ($this->JSON_CONFIG->USE_COMPOSER && $this->JSON_CONFIG->USE_COMPOSER === true) { $requiredBinaries[] = 'composer --no-ansi'; } foreach ($requiredBinaries as $command) { $path = trim(shell_exec('which ' . $command)); if ($path == '') { die(sprintf('<div class="error"><b>%s</b> not available. It needs to be installed on the server for this script to work.</div>', $command)); } else { $version = explode("\n", shell_exec($command . ' --version')); printf('<b>%s</b> : %s' . "\n" , $path , $version[0] ); } } // Backup the TARGET_DIR // without the BACKUP_DIR for the case when it's inside the TARGET_DIR if ($this->JSON_CONFIG->BACKUP_DIR !== false) { $commands[] = sprintf( "tar --exclude='%s*' -czf %s/%s-%s-%s.tar.gz %s*" , $this->JSON_CONFIG->BACKUP_DIR , $this->JSON_CONFIG->BACKUP_DIR , basename($this->TARGET_DIR) , md5($this->TARGET_DIR) , date('YmdHis') , $this->TARGET_DIR // We're backing up this directory into BACKUP_DIR ); } // Invoke composer if ($this->JSON_CONFIG->USE_COMPOSER === true) { $commands[] = sprintf( 'composer --no-ansi --no-interaction --no-progress --working-dir=%s install %s' , $this->TMP_DIR , ($this->JSON_CONFIG->COMPOSER_OPTIONS) ? $this->JSON_CONFIG->COMPOSER_OPTIONS : '' ); } return $commands; } public function Deploy(){ // Compile exclude parameters $exclude = ''; foreach ($this->JSON_CONFIG->EXCLUDE as $exc) { $exclude .= ' --exclude=' . $exc; } // Create parrent directorys, Change permissons and Deployment $commands[] = sprintf( 'rsync --rsync-path="mkdir -m %s -p %s && rsync" --chmod=ugo=rwx -rltogDzvO %s %s %s %s' , $this->JSON_CONFIG->REMOTE_PERM , $this->JSON_CONFIG->DEPLOY_DIR , $exclude , $this->TMP_DIR , $this->TARGET_DIR , ($this->JSON_CONFIG->DELETE_FILES) ? '--delete-after' : '' ); // After Deployment change folders and files group and permissions $commands[] = sprintf( 'ssh %s@%s "chgrp -R %s %s && chmod -R %s %s"' , $this->JSON_CONFIG->DEPLOY_USER , $this->JSON_CONFIG->DEPLOY_SERVER , $this->JSON_CONFIG->REMOTE_GROUP , $this->JSON_CONFIG->DEPLOY_DIR , $this->JSON_CONFIG->REMOTE_PERM , $this->JSON_CONFIG->DEPLOY_DIR ); // Remove the TMP_DIR (depends on CLEAN_UP) if ($this->JSON_CONFIG->CLEAN_UP) { $commands['cleanup'] = sprintf( 'rm -rf %s' , $this->TMP_DIR ); } return $commands; } public function RunCommands($commands){ $output = ''; foreach ($commands as $command) { set_time_limit($this->JSON_CONFIG->TIME_LIMIT); // Reset the time limit for each command if (file_exists($this->TMP_DIR) && is_dir($this->TMP_DIR)) { chdir($this->TMP_DIR); // Ensure that we're in the right directory } $tmp = array(); exec($command . ' 2>&1', $tmp, $return_code); // Execute the command // Output the result printf(' <span class="prompt">$</span> <span class="command">%s</span> <div class="output">%s</div> ' , htmlentities(trim($command)) , htmlentities(trim(implode("\n", $tmp))) ); $output .= ob_get_contents(); ob_flush(); // Try to output everything as it happens // Error handling and cleanup if ($return_code !== 0) { printf('<div class="error"> Error encountered! Stopping the script to prevent possible data loss. CHECK THE DATA IN YOUR TARGET DIR! </div>' ); if ($this->JSON_CONFIG->CLEAN_UP) { $tmp = shell_exec($commands['cleanup']); printf('Cleaning up temporary files ... <span class="prompt">$</span> <span class="command">%s</span> <div class="output">%s</div>' , htmlentities(trim($commands['cleanup'])) , htmlentities(trim($tmp)) ); } $error = sprintf( 'Deployment error on %s using %s!' , $_SERVER['HTTP_HOST'] , __FILE__ ); error_log($error); if ($this->JSON_CONFIG->EMAIL_ON_ERROR) { $output .= ob_get_contents(); $headers = array(); $headers[] = sprintf('From: Simple PHP Git deploy script <simple-php-git-deploy@%s>', $_SERVER['HTTP_HOST']); $headers[] = sprintf('X-Mailer: PHP/%s', phpversion()); mail($this->JSON_CONFIG->EMAIL_ON_ERROR, $error, strip_tags(trim($output)), implode("\r\n", $headers)); } break; } } } }<file_sep><?php include 'GitDeploy.php'; ?> <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="robots" content="noindex"> <title>PHP Deploy script</title> <style> body { padding: 0 1em; background: #222; color: #fff; } h2, .error { color: #c33; } .prompt { color: #6be234; } .command { color: #729fcf; } .output { color: #999; } </style> </head> <body> <pre> <?php $deploy=new GitDeploy($HTTP_RAW_POST_DATA); ?> Running as <b><?php echo trim(shell_exec('whoami')); ?></b>. Checking the environment ... <?php $deploy->CheckEnvironment();?> Environment OK. Start deploy. <?php $deploy->RunCommands($deploy->GitPull()); $deploy->SetConfigFromJson(); $deploy->RunCommands($deploy->AfterGitPull()); $deploy->RunCommands($deploy->Deploy()); ?> Deploy done. </pre> </body> </html>
d7bd27bb9d0964a36b4ba5a685b47e37693aa1a4
[ "Markdown", "PHP" ]
3
Markdown
Sanya1991/php-deploy-script
42ce771435beaec7d4809e1cf73cba11769a625e
0290768a61bf12d9999536f9f9835414e03fbed7
refs/heads/master
<file_sep>nette-project ============= For install: ```bash git clone https://github.com/shinigamicorei7/nette-project cd nette-project composer install touch app/config/config.local.neon ``` ### config.local.neon ```coffeescript database: dsn: 'mysql:host=127.0.0.1;dbname=test' user: root password: <PASSWORD> options: lazy: yes mail: smtp: true host: smtp.mailgun.org port: 465 username: '<EMAIL>' password: <PASSWORD> secure: ssl ``` <file_sep><?php namespace App\Forms; use \Nette\Application\UI\Form; use \Nette\Security\User; use \Nette\Database\Context; use \Nette\Mail\IMailer; use Nette\Bridges\ApplicationLatte\ILatteFactory; class SignFormFactory extends \Nette\Object { /** @var User */ private $user; /** @var Context */ private $database; /** @var IMailer */ private $mailer; /** @var \Latte\Engine */ private $latte; public function __construct(User $user, Context $database, IMailer $mailer, ILatteFactory $late_factory) { $this->user = $user; $this->database = $database; $this->mailer = $mailer; $this->latte = $late_factory->create(); } /** * @return Form */ public function create() { $form = new Form; $form->addText('username', 'Username:') ->setRequired('Please enter your username.'); $form->addPassword('<PASSWORD>', '<PASSWORD>:') ->setRequired('Please enter your password.'); $form->addCheckbox('remember', 'Keep me signed in'); $form->addSubmit('send', 'Sign in'); $form->onSuccess[] = array($this, 'formSucceeded'); return $form; } public function formSucceeded(Form $form, $values) { if ($values->remember) { $this->user->setExpiration('14 days', FALSE); } else { $this->user->setExpiration('20 minutes', TRUE); } try { $this->user->login($values->username, $values->password); } catch (Nette\Security\AuthenticationException $e) { $form->addError($e->getMessage()); } } public function createRecovery() { $form = new Form; $form->getElementPrototype()->class = 'ajax'; $form->addText('email', 'Email:')->addRule(Form::EMAIL)->isRequired(); $form->addSubmit('send', 'Enviar'); $form->onSuccess[] = array($this, 'recoverySucceeded'); return $form; } public function recoverySucceeded(Form $form, $values) { $row = $this->database->table('users')->where('email', $values->email)->fetch(); if (!$row) { $form->addError('No existe una cuenta con este correo.'); $form->getPresenter()->redrawControl('recoveryForm'); } else { $mail = new \Nette\Mail\Message(); $mail->setFrom('<EMAIL>') ->setSubject('Password Recovery') ->addTo($row->email) ->setHtmlBody($this->getEmailBody($row)); try { $this->mailer->send($mail); } catch (\Nette\Mail\SendException $e) { $form->addError($e->getMessage()); $form->getPresenter()->redrawControl('recoveryForm'); } $form->getPresenter()->flashMessage('<b>Listo!</b> Revisa tu bandeja de entrada.'); $form->getPresenter()->redrawControl('recoveryForm'); } } public function getEmailBody($row) { $templates_dir = realpath(__DIR__ . '/../presenters/templates'); $templates_dir = rtrim($templates_dir, '\/'); $recovery_template = $templates_dir . '/emails/recovery.latte'; return $this->latte->renderToString($recovery_template, array('person' => $row)); } }
668f58698f8e388c45a0dd6fab44264073b98ee4
[ "Markdown", "PHP" ]
2
Markdown
shinigamicorei7/nette-project
45ab4cdc6a044c30348e714aefcddc5bd297ada5
228d1952d1d3d6c3435c4402cde09a56f1ca24d6
refs/heads/master
<file_sep>package com.ntrlab.gpb.common.api.responses; import lombok.Getter; import lombok.Setter; import org.json.simple.JSONArray; import org.json.simple.JSONObject; import javax.ws.rs.core.Response; import java.util.ArrayList; import java.util.List; /** * Created by gakopyan on 2015-07-06 */ public class EmptyResponse implements IResponse { @Getter protected List<String> messages = new ArrayList<String>(); @Getter protected JSONObject jsonObject = new JSONObject(); @Getter @Setter protected Response.Status status = Response.Status.OK; public EmptyResponse() {} public EmptyResponse(Response.Status status) { this.status = status; } public String getJSONString() { if (!messages.isEmpty()) { JSONArray jsonArray = new JSONArray(); for (String message : messages) { jsonArray.add(message); } jsonObject.put("messages", jsonArray); } return jsonObject.toJSONString(); } public Response.Status getHttpResponseStatus() { return status; } }
d3cad6d59c8df7fe83a31e0c71c79b0877050545
[ "Java" ]
1
Java
Dueto/gpb
acb8c6aa220573b727c79e9aec66c814a42b4133
9bd35aae5b67d98e1508594d3607c076170b1f27
refs/heads/master
<repo_name>atharv1033/WifiZone-Server<file_sep>/WifiZone-Server.py from http.server import HTTPServer as BaseHTTPServer, SimpleHTTPRequestHandler from zeroconf import IPVersion, ServiceInfo, Zeroconf from tkinter import filedialog from tkinter import * from tkinter import messagebox from time import sleep import threading import argparse import socket import os class HTTPHandler(SimpleHTTPRequestHandler): def translate_path(self, path): path = SimpleHTTPRequestHandler.translate_path(self, path) relpath = os.path.relpath(path, os.getcwd()) fullpath = os.path.join(self.server.base_path, relpath) return fullpath class HTTPServer(BaseHTTPServer): def __init__(self, base_path, server_address, RequestHandlerClass=HTTPHandler): self.base_path = base_path BaseHTTPServer.__init__(self, server_address, RequestHandlerClass) def server_thread_function(port, http_dir): try: global httpd httpd = HTTPServer(http_dir, ("", int(port))) httpd.serve_forever() except: print('port not available') messagebox.showinfo("Alert", "Port already in use try different") def nsd_thread_function(service_name, path, port): parser = argparse.ArgumentParser() parser.add_argument('--debug', action='store_true') version_group = parser.add_mutually_exclusive_group() version_group.add_argument('--v6', action='store_true') version_group.add_argument('--v6-only', action='store_true') args = parser.parse_args() if args.debug: logging.getLogger('zeroconf').setLevel(logging.DEBUG) if args.v6: ip_version = IPVersion.All elif args.v6_only: ip_version = IPVersion.V6Only else: ip_version = IPVersion.V4Only desc = {'path': path} info = ServiceInfo( "_http._tcp.local.", service_name+"._http._tcp.local.", addresses=[socket.inet_aton(socket.gethostbyname(socket.gethostname()))], port=int(port), properties=desc, server="ash-2.local.", ) #messagebox.showinfo("Alert", "In nsd Process") zeroconf = Zeroconf(ip_version=ip_version) while True: zeroconf.register_service(info) sleep(3) zeroconf.unregister_service(info) global stop_thread if(stop_thread): break def select_folder(): directory = filedialog.askdirectory() entry_select_folder.delete(0, END) entry_select_folder.insert(0, directory) print(directory) def select_file(): if entry_select_folder.get() == "": messagebox.showinfo("Alert", "Select folder first") return file_path = filedialog.askopenfilename() file_path = file_path.replace(entry_select_folder.get()+'/', '') entry_select_file.delete(0, END) entry_select_file.insert(0, file_path) print(file_path) def start_server(): print('starting server.....') service_name = entry_service_name.get() path = entry_select_file.get() port = entry_port_number.get() http_dir = entry_select_folder.get() global server_thread, nsd_thread, stop_thread stop_thread = False server_thread = threading.Thread(target = server_thread_function, args = (port, http_dir, )) server_thread.start() nsd_thread = threading.Thread(target = nsd_thread_function, args = (service_name, path, port, )) nsd_thread.start() button_start['state'] = DISABLED button_stop['state'] = NORMAL def stop_server(): global stop_thread, httpd, nsd_thread, server_thread stop_thread = True nsd_thread.join() print('service stopped !!') httpd.shutdown() server_thread.join() print('server stopped !!') button_start['state'] = NORMAL button_stop['state'] = DISABLED if __name__ == "__main__": top = Tk() top.title('WifiZone Server') ip_address = socket.gethostbyname(socket.gethostname()) label_service_name = Label(top, text="Service Name - ") label_service_name.grid(row = 0, column = 0, padx = (10,5), pady = (20,10)) entry_service_name = Entry(top, bd = 2) entry_service_name.grid(row = 0, column = 1, pady = (20,10)) label_ip_address = Label(top, text = "IP Address - ") label_ip_address.grid(row = 2, column = 0, padx = (10,5), pady = (5,10)) label_ip_address = Label(top, text = ip_address) label_ip_address.grid(row = 2, column = 1, padx = (10,5), pady = (5,10)) label_port_number = Label(top, text = "Port Number - ") label_port_number.grid(row = 3, column = 0, pady = (5,10)) entry_port_number = Entry(top, bd = 2) entry_port_number.grid(row = 3, column = 1, pady = (5,10)) entry_port_number.delete(0, END) entry_port_number.insert(0, "8000") label_select_folder = Label(top, text = "Select Folder - ") label_select_folder.grid(row = 4, column = 0, padx = (10,5), pady = (5,10)) entry_select_folder = Entry(top, bd = 2) entry_select_folder.grid(row = 4, column = 1, pady = (5,10)) button_select_folder = Button(top, text = "Browse", command = select_folder) button_select_folder.grid(row = 4, column = 2, padx=(5,5), pady = (5,10)) label_select_file = Label(top, text = "Select Main File -") label_select_file.grid(row = 5, column = 0, padx = (10,5), pady = (5,10)) entry_select_file = Entry(top, bd = 2) entry_select_file.grid(row = 5, column = 1, pady = (5,10)) button_select_file = Button(top, text = "Browse", command = select_file) button_select_file.grid(row = 5, column = 2, padx=(5,5), pady = (5,10)) label_space1 = Label(top, text="") label_space1.grid(row = 6, column = 0, padx = (10,5), pady = (5,10)) button_start = Button(top, text = "Start", command = start_server) button_start.grid(row = 6, column = 1, padx=(20,10), pady = (20,10)) button_stop = Button(top, text = "Stop", state = DISABLED,command = stop_server) button_stop.grid(row = 6, column = 2, padx=(20,10), pady = (20,10)) top.mainloop() <file_sep>/README.md # WifiZone-Server This python program creates a nsd service (aka dns-sd) and start a simple http server. You need to connect your laptop/desktop to same wifi network (or use hotspot). It uses tkinter gui. It is to be used with "Web App UI tester" and "WifiZone" Android apps available on playstore. Enter your service name, project folder location and main landing page of your mobile web app. After you hit start button you can see service in your Android App, Click on the service and app will load your main landing page into the android WebView.
7c2954ffe4b72d744a4d179bf1edfe564537a52d
[ "Markdown", "Python" ]
2
Python
atharv1033/WifiZone-Server
a0e253c9db40c708ac28a5fcd1099173c48ae457
ffb39b1659dd8a5c2e65b46856a02b2858ec4ac6
refs/heads/master
<repo_name>bubbafett1936/Hangman<file_sep>/src/hangman/Hangman.java package hangman; import java.util.ArrayList; import java.util.Scanner; class Hangman { public static void main(String[] args) { // To hold the answer, guess, misses, and Scanner object Scanner kbd = new Scanner(System.in); String answer = "Lichtenstein"; char[] answerArray = answer.toLowerCase().toCharArray(); ArrayList<Character> answerList = new ArrayList(); ArrayList<Character> guessList = new ArrayList(); int misses = 6; // convert the answer to an ArrayList object for (char letter : answerArray) answerList.add(letter); // the logic for the entirety of the game; as long as the word has not been solved, the // game will continue do { int lettersLeft = 0; // to print the spaces for letter that haven't been solved, and the letter themselves // for those that have for (char letter: answerList) { if (guessList.contains(letter) ) System.out.printf("%c ", letter); else { System.out.print("_ "); lettersLeft++; } } if (misses > 1) System.out.printf("(%d misses left)%n%n", misses); else if (misses == 1) System.out.printf("(1 miss left)%n%n"); // check if the word has been successfully solved if (lettersLeft == 0) break; // tell the user to select a letter System.out.print("Choose a letter: "); String input = kbd.nextLine(); // determine if the guess was valid (a single character), and if it was correct if (input.length() > 1) { System.out.println("You must choose only a single letter.\n"); misses--; } else { char guess = input.toLowerCase().charAt(0); if (answerList.contains(guess) ) { System.out.println("That is correct.\n"); guessList.add(guess); } else { System.out.println("That is incorrect.\n"); misses--; } } } while (misses > 0); if (misses <= 0) System.out.printf("The word was %s. Please try again.%n", answer); else System.out.println("Congratulations!"); } }
ce7c9ea4128cf305fdfce6463df8ddf2f91e1235
[ "Java" ]
1
Java
bubbafett1936/Hangman
db2528a2a5731c293599a2c9cefb5048290ea319
0912cf78908c04f9961f55bbb0496d1a823227e7
refs/heads/main
<repo_name>ivoreynoldsmoore/golcw<file_sep>/benchmark_test.go package main import ( "fmt" "testing" "uk.ac.bris.cs/gameoflife/gol" ) // BenchmarkGol will be used to create benchmark graphs for the game of life // Its code is based on the TestGol function, but it does not validate the output // This is because that can be done seperately by the TestGol test func BenchmarkGol(b *testing.B) { p := gol.Params{ Turns: 1000, ImageHeight: 256, ImageWidth: 256, } for _, threads := range []int{1, 2, 4, 8, 16} { p.Threads = threads testName := fmt.Sprintf("BenchmarkGol_%d\n", p.Threads) b.Run(testName, func(bs *testing.B) { events := make(chan gol.Event) b.ResetTimer() gol.Run(p, events, nil) for range events { } }) } } <file_sep>/main.go package main import ( "encoding/gob" "flag" "fmt" "runtime" "strings" "uk.ac.bris.cs/gameoflife/gol" "uk.ac.bris.cs/gameoflife/sdl" ) // main is the function called when starting Game of Life with 'go run .' func main() { runtime.LockOSThread() var params gol.Params var ClientAddr string var BrokerAddr string var WorkerAddrs []string defaults := gol.DefaultNetParams() flag.IntVar( &params.Threads, "t", 8, "Specify the number of worker threads to use.") flag.IntVar( &params.ImageWidth, "w", 512, "Specify the width of the hiimage.") flag.IntVar( &params.ImageHeight, "h", 512, "Specify the height of the image.") flag.IntVar( &params.Turns, "turns", // 10, 10000000000, "Specify the number of turns to process.") var role string flag.StringVar( &role, "role", "client", "Specifies the role of this machine. Can be client, broker or worker.") flag.StringVar( &ClientAddr, "client", defaults.ClientAddr, "Specifies the address of the client, which will run the SDL controller.") flag.StringVar( &BrokerAddr, "broker", defaults.BrokerAddr, "Specifies the address of the broker, which will communicate between all machines.") var workersString string flag.StringVar( &workersString, "workers", defaults.WorkerAddrs[0], "Specifies the list of worker machines. Space separated.") flag.Parse() WorkerAddrs = strings.Split(workersString, " ") clientPort := ":" + strings.Split(ClientAddr, ":")[1] brokerPort := ":" + strings.Split(BrokerAddr, ":")[1] // Assumes all workers on same port workerPort := ":" + strings.Split(WorkerAddrs[0], ":")[1] gob.Register(&gol.AliveCellsCount{}) gob.Register(&gol.ImageOutputComplete{}) gob.Register(&gol.StateChange{}) gob.Register(&gol.CellFlipped{}) gob.Register(&gol.TurnComplete{}) gob.Register(&gol.FinalTurnComplete{}) fmt.Println("Threads:", params.Threads) fmt.Println("Width:", params.ImageWidth) fmt.Println("Height:", params.ImageHeight) keyPresses := make(chan rune, 10) events := make(chan gol.Event, 1000) // First, client listens and broker connnects to it. // Then broker listens and client connects backwards. // Finally, each worker listens and broker connects to all of them. if role == "client" { go gol.RunClient(params, clientPort, BrokerAddr, events, keyPresses) sdl.Start(params, events, keyPresses) // for range events { // } } else if role == "broker" { gol.RunBroker(params, clientPort, brokerPort, WorkerAddrs) } else if role == "worker" { gol.RunWorker(workerPort) } } <file_sep>/gol/broker.go package gol import ( "net/rpc" "sync" "time" ) // BrokerState holds all information the broker needs type BrokerState struct { Stopper chan bool Client *rpc.Client Workers []*rpc.Client // Internal // Protects suspend and cond Mutex sync.Mutex Suspend bool Terminate bool Cond sync.Cond World [][]bool Turn int Height, Width int // We set this to true when q pressed, but it is false by default // This will not change value whenever a new RPC "instance" is created // As such we will use this to check if we should accept the client's new world Reconnect bool InitialRequest Params } // BrokerReq is the request type for the broker function type BrokerReq struct { InitialState [][]bool Params Params } // BrokerRes is the result type for the broker function type BrokerRes struct { FinalState [][]bool } // StopBrokerReq is the request type for the stop broker function type StopBrokerReq struct { // If we should restart the broker (tests) or just shut it down Restart bool } // StopBrokerRes is the result type for the stop broker function type StopBrokerRes struct { } // KpBrokerReq is the request type for the stop broker function type KpBrokerReq struct { Event rune } // KpBrokerRes is the result type for the stop broker function type KpBrokerRes struct { Turn int } // StopBroker causes the broker to shut down and restart func (bs *BrokerState) StopBroker(req StopBrokerReq, res *StopBrokerRes) (err error) { if !req.Restart { for _, worker := range bs.Workers { worker.Call(StopWorker, StopWorkerReq{}, &StopWorkerRes{}) } } bs.Stopper <- req.Restart return nil } // Broker takes care of all communication between workers func (bs *BrokerState) Broker(req BrokerReq, res *BrokerRes) (err error) { // Ignore new parameters and continue if bs.Reconnect { req.InitialState = bs.World req.Params = bs.InitialRequest } else { bs.InitialRequest = req.Params bs.Turn = 0 } numWorkers := len(bs.Workers) world := req.InitialState height := req.Params.ImageHeight width := req.Params.ImageWidth quot := height / numWorkers rem := height % numWorkers bs.Mutex = sync.Mutex{} bs.Cond = *sync.NewCond(&bs.Mutex) stop := make(chan struct{}) // Cache slice heights, annoying to recalculate slices := make([]int, numWorkers) // Last value is special case, longer than others for i := 0; i < numWorkers-1; i++ { slices[i] = quot } slices[numWorkers-1] = quot + rem // Initialise all workers wg := sync.WaitGroup{} for i := 0; i < numWorkers; i++ { var res InitWorkerRes req := InitWorkerReq{ req.InitialState, i * quot, slices[i], height, width} wg.Add(1) go func(i int) { defer wg.Done() bs.Workers[i].Call(InitWorker, req, &res) }(i) } wg.Wait() // Send initial cell flipped events flipped := make([]Event, 0) for _, flippedCell := range CalculateAliveCells(world) { flipped = append(flipped, CellFlipped{CompletedTurns: 0, Cell: flippedCell}) } encodeAndSendEvents(bs, flipped) go timer(bs, stop) // Main loop for bs.Turn < req.Params.Turns { // Check if paused bs.Mutex.Lock() for bs.Suspend { bs.Cond.Wait() } if bs.Terminate { var signal struct{} stop <- signal res.FinalState = world return nil } bs.Mutex.Unlock() nextWorld := newWorld(height, width) // TODO: Interact via interactor wg := sync.WaitGroup{} for i := 0; i < numWorkers; i++ { wg.Add(1) go func(i int) { defer wg.Done() flipped := make([]Event, 0) var res WorkerRes req := WorkerReq{ RowBelow: world[(quot*i+height-1)%height], RowAbove: world[(quot*i+height+slices[i])%height], Turn: bs.Turn} err := bs.Workers[i%numWorkers].Call(Worker, req, &res) HandleError(err) for _, flippedCell := range res.Flipped { flipped = append(flipped, CellFlipped{CompletedTurns: bs.Turn, Cell: flippedCell}) } go encodeAndSendEvents(bs, flipped) // We only copy the section we're interested about for j := quot * i; j < quot*i+slices[i]; j++ { // nextWorld[j] = res.World[j] nextWorld[j] = res.World[j-quot*i] } }(i) } wg.Wait() bs.Mutex.Lock() world = nextWorld bs.World = world bs.Turn++ bs.Mutex.Unlock() encodeAndSendEvent(bs, TurnComplete{CompletedTurns: bs.Turn}) } var signal struct{} stop <- signal encodeAndSendEvent(bs, FinalTurnComplete{CompletedTurns: bs.Turn, Alive: CalculateAliveCells(world)}) res.FinalState = world bs.Mutex.Lock() bs.Mutex.Unlock() return nil } // KeypressBroker is called whenever a keypress event is sent by the controller that has to be handled func (bs *BrokerState) KeypressBroker(req KpBrokerReq, res *KpBrokerRes) (err error) { bs.Mutex.Lock() res.Turn = bs.Turn switch req.Event { // Save world case 's': bs.Client.Call(SaveClient, SaveClientReq{World: bs.World}, &SaveClientRes{}) bs.Mutex.Unlock() // New controller case 'q': bs.Reconnect = true bs.Terminate = true // bs.StopBroker(StopBrokerReq{Restart: true}, &StopBrokerRes{}) bs.Mutex.Unlock() // Pause processing case 'p': if bs.Suspend { bs.Suspend = false bs.Cond.Broadcast() bs.Mutex.Unlock() } else { bs.Suspend = true bs.Mutex.Unlock() } // Graceful shutdown case 'k': bs.Client.Call(SaveClient, SaveClientReq{World: bs.World}, &SaveClientRes{}) bs.StopBroker(StopBrokerReq{Restart: false}, &StopBrokerRes{}) bs.Mutex.Unlock() default: bs.Mutex.Unlock() } return nil } func timer(bs *BrokerState, stop <-chan struct{}) { tick := time.Tick(2 * time.Second) for { select { case <-tick: // Lock because main broker process could be updating bs.World/bs.Turn bs.Mutex.Lock() cells := CalculateAliveCells(bs.World) encodeAndSendEvent(bs, AliveCellsCount{CellsCount: len(cells), CompletedTurns: bs.Turn}) bs.Mutex.Unlock() case <-stop: return } } } func encodeAndSendEvent(bs *BrokerState, event Event) { bytes, err := EncodeEvent(event) HandleError(err) req := ClientReq{Events: [][]byte{bytes}} var res ClientRes bs.Client.Call(SendEvents, req, &res) } func encodeAndSendEvents(bs *BrokerState, events []Event) { eventBytes := make([][]byte, 0) for _, event := range events { eventByte, err := EncodeEvent(event) HandleError(err) eventBytes = append(eventBytes, eventByte) } req := ClientReq{Events: eventBytes} var res ClientRes bs.Client.Call(SendEvents, req, &res) } <file_sep>/gol/brokerRunner.go package gol import ( "fmt" "net" "net/rpc" "strings" ) // BState is a work around for recreating RPC connections var BState *BrokerState // RunBroker initialises and runs the broker func RunBroker(params Params, clientPort, brokerPort string, workerAddrs []string) { stopper := make(chan bool) workers := make([]*rpc.Client, len(workerAddrs)) for idx, worker := range workerAddrs { var err error fmt.Println("LOG: Broker connecting to a Worker") workers[idx], err = rpc.Dial("tcp", worker) for err != nil { workers[idx], err = rpc.Dial("tcp", worker) } } // Workaround for tests // Tests require constant reconnecting and disconnecting client-broker restart := true for restart { fmt.Println("LOG: Broker listening for Client (1)") l, err := net.Listen("tcp", brokerPort) HandleError(err) tmp, err := l.Accept() HandleError(err) clientAddr := strings.Split(tmp.RemoteAddr().String(), ":")[0] + clientPort tmp.Close() l.Close() fmt.Println("LOG: Broker listening for Client (2)") lis, err := net.Listen("tcp", brokerPort) HandleError(err) fmt.Println("LOG: Broker connecting to Client") client, err := rpc.Dial("tcp", clientAddr) for err != nil { client, err = rpc.Dial("tcp", clientAddr) } if BState == nil { BState = &BrokerState{Stopper: stopper, Client: client, Workers: workers} } else { BState.Client = client BState.Stopper = stopper BState.Workers = workers BState.Suspend = false BState.Terminate = false } fmt.Println("Broker initialised") rpc.Register(BState) go rpc.Accept(lis) // Break and exit if not restarting, recv via Stop procedure restart = <-stopper lis.Close() // client.Close() } } <file_sep>/gol/workerRunner.go package gol import ( "fmt" "net" "net/rpc" ) // RunWorker initialises and runs the worker func RunWorker(workerPort string) { lis, err := net.Listen("tcp", workerPort) HandleError(err) defer lis.Close() stopper := make(chan struct{}) fmt.Println("Worker initialised") rpc.Register(&WorkerState{Stopper: stopper}) go rpc.Accept(lis) <-stopper } <file_sep>/gol/client.go package gol import ( "bytes" "encoding/gob" "net/rpc" ) // ClientState holds all information the client needs type ClientState struct { Params Params Events chan Event Broker *rpc.Client Io IoChannels } // ClientReq holds any data sent to the client type ClientReq struct { // Would represent a []Event, but we need to gob-ify it Events [][]byte } // ClientRes is the result type for the client function type ClientRes struct { } // SaveClientReq is the request type for the save client function type SaveClientReq struct { World [][]bool } // SaveClientRes is the result type for the save client function type SaveClientRes struct { } // SendEvents is called from broker to send events back to the client func (cs *ClientState) SendEvents(req ClientReq, res *ClientRes) (err error) { for _, e := range req.Events { event, err := decodeEvent(e) HandleError(err) // Big """work-around""" for gob encoding/interface type errors // Event decodes into value of type Event, but really has type *Event // This code looks ugly, but is the only way we managed to make this decoding work switch e := event.(type) { case *AliveCellsCount: cs.Events <- *e case *CellFlipped: cs.Events <- *e case *ImageOutputComplete: cs.Events <- *e case *StateChange: cs.Events <- *e case *TurnComplete: cs.Events <- *e case *FinalTurnComplete: cs.Events <- *e default: panic("Could not decode event") } } return nil } // SaveClient is called from broker to save its current world state func (cs *ClientState) SaveClient(req SaveClientReq, res *SaveClientRes) (err error) { SaveWorld(req.World, cs.Params, cs.Io) return nil } // EncodeEvent encodes an event in a gob encoding so that it can be send via RPC func EncodeEvent(event Event) ([]byte, error) { var buf bytes.Buffer enc := gob.NewEncoder(&buf) err := enc.Encode(&event) if err != nil { return nil, err } return buf.Bytes(), nil } // EncodeEvents is a plural version of EncodeEvent func EncodeEvents(events []Event) ([][]byte, error) { var buf bytes.Buffer enc := gob.NewEncoder(&buf) out := make([][]byte, 0) for _, event := range events { err := enc.Encode(&event) if err != nil { return nil, err } out = append(out, buf.Bytes()) buf.Reset() } return out, nil } func decodeEvent(e []byte) (interface{}, error) { var buf bytes.Buffer dec := gob.NewDecoder(&buf) var event interface{} buf.Write(e) err := dec.Decode(&event) if err != nil { return nil, err } buf.Reset() return event, nil } <file_sep>/gol/stubs.go package gol // Broker broker var Broker = "BrokerState.Broker" // StopBroker stopBroker var StopBroker = "BrokerState.StopBroker" // KeypressBroker keypressBroker var KeypressBroker = "BrokerState.KeypressBroker" // Worker worker var Worker = "WorkerState.Worker" // StopWorker stopWorker var StopWorker = "WorkerState.StopWorker" // InitWorker initWorker var InitWorker = "WorkerState.InitWorker" // SendEvents sendEvents var SendEvents = "ClientState.SendEvents" // SaveClient saveClient var SaveClient = "ClientState.SaveClient" <file_sep>/gol/structs.go package gol // Params provides the details of how to run the Game of Life and which image to load. type Params struct { Turns int Threads int ImageWidth int ImageHeight int // Client *rpc.Client // Broker *rpc.Client // Workers []*rpc.Client } // NetParams holds information type NetParams struct { ClientAddr, ClientPort, BrokerAddr, BrokerPort string WorkerAddrs, WorkerPorts []string } <file_sep>/gol/clientRunner.go package gol import ( "fmt" "net" "net/rpc" "time" ) // CState is a work around for tests // Cause rpc.Register to properly use the new state struct var CState *ClientState // RunClient is used an an entrypoint for tests and for the main program func RunClient(params Params, clientPort, brokerAddr string, events chan Event, keyPresses chan rune) [][]bool { // Create initial connection to negotiate network parameters e.g. IPs fmt.Println("LOG: Client attempting to connect to Broker (1)") tmp, err := net.Dial("tcp", brokerAddr) for err != nil { tmp, err = net.Dial("tcp", brokerAddr) } defer tmp.Close() time.Sleep(1 * time.Second) fmt.Println("LOG: Client attempting to connect to Broker (2)") broker, err := rpc.Dial("tcp", brokerAddr) for err != nil { broker, err = rpc.Dial("tcp", brokerAddr) } fmt.Println("LOG: Client listening for Broker") lis, err := net.Listen("tcp", clientPort) HandleError(err) defer lis.Close() if CState == nil { CState = &ClientState{Events: events, Broker: broker, Params: params} } else { CState.Broker = broker CState.Events = events CState.Params = params } fmt.Println("Client initialised") rpc.Register(CState) go rpc.Accept(lis) world, c := readFile(params, events, keyPresses) CState.Io = c stopper := make(chan struct{}) // Pass keypresses onto broker go func() { paused := false for { select { case <-stopper: return case e := <-keyPresses: var res KpBrokerRes fmt.Println("Sending") broker.Call(KeypressBroker, KpBrokerReq{Event: e}, &res) paused = !paused if e == 'p' && paused { fmt.Printf("Paused, Turn %d\n", res.Turn) } else if e == 'p' { fmt.Println("Continuing") } } } }() var res1 BrokerRes err = broker.Call(Broker, BrokerReq{InitialState: world, Params: params}, &res1) var signal struct{} stopper <- signal // Do not try and stop the broker if it returned early: // Likely to early return because we stopped it with k keypress if err == nil { var res2 StopBrokerRes err = broker.Call(StopBroker, StopBrokerReq{Restart: true}, &res2) HandleError(err) SaveWorld(res1.FinalState, params, c) } close(events) // Stop SDL/tests gracefully fmt.Println("LOG: Client done, returning") return res1.FinalState } // SaveWorld takes a world and saves it as specified by the tests func SaveWorld(world [][]bool, p Params, c IoChannels) { c.command <- ioOutput c.filename <- fmt.Sprintf("%dx%dx%d", p.ImageWidth, p.ImageHeight, p.Turns) for y := 0; y < p.ImageHeight; y++ { for x := 0; x < p.ImageWidth; x++ { if world[y][x] { c.output <- 255 } else { c.output <- 0 } } } c.command <- ioCheckIdle <-c.idle } <file_sep>/gol/funcs.go package gol import "uk.ac.bris.cs/gameoflife/util" // CalculateAliveCells returns a Cell for each alive cell func CalculateAliveCells(world [][]bool) []util.Cell { cells := []util.Cell{} for y, col := range world { for x, v := range col { if v { cells = append(cells, util.Cell{X: x, Y: y}) } } } return cells } // FindAliveNeighbours counts the number of living neighbours around the cell at x, y func FindAliveNeighbours(world [][]bool, x int, y int) int { aliveNeighbours := 0 for _, i := range []int{-1, 0, 1} { for _, j := range []int{-1, 0, 1} { if i == 0 && j == 0 { continue } wy := len(world) wx := len(world[0]) // Add wx to x to wrap around from negatives // We index [y, x] because that's the standard living := world[(y+i+wy)%wy][(x+j+wx)%wx] if living { aliveNeighbours++ } } } return aliveNeighbours } // NewWorld creates a blank world according to the data in p func NewWorld(p Params) [][]bool { world := make([][]bool, p.ImageHeight) for x := range world { world[x] = make([]bool, p.ImageWidth) } return world } // HandleError handles fatal errors func HandleError(err error) { if err != nil { panic(err) } } <file_sep>/gol/gol.go package gol import ( "encoding/gob" "fmt" ) // DefaultNetParams returns a set of "default" network parameters func DefaultNetParams() NetParams { return NetParams{ ClientAddr: "127.0.0.1:8000", ClientPort: ":8000", BrokerAddr: "192.168.127.12:8000", BrokerPort: ":8100", WorkerAddrs: []string{"127.0.0.1:8000"}, WorkerPorts: []string{":8000"}, } } // ReadFile starts the processing of Game of Life. It should initialise channels and goroutines. func readFile(p Params, events chan<- Event, keyPresses <-chan rune) ([][]bool, IoChannels) { ioCommand := make(chan ioCommand) ioIdle := make(chan bool) ioFilename := make(chan string) ioOutput := make(chan uint8) c := IoChannels{ command: ioCommand, idle: ioIdle, filename: ioFilename, output: ioOutput, input: make(chan uint8), } go startIo(p, c) world := NewWorld(p) c.command <- ioInput ioFilename <- fmt.Sprintf("%dx%d", p.ImageWidth, p.ImageHeight) for y := 0; y < p.ImageHeight; y++ { for x := 0; x < p.ImageWidth; x++ { world[y][x] = <-c.input != 0 // // If it's true, we've flipped it // if world[y][x] { // c.events <- CellFlipped{Cell: util.Cell{X: x, Y: y}, CompletedTurns: 0} // } } } return world, c } // Run is an entrypoint for tests func Run(p Params, events chan Event, keyPresses chan rune) { gob.Register(&AliveCellsCount{}) gob.Register(&ImageOutputComplete{}) gob.Register(&StateChange{}) gob.Register(&CellFlipped{}) gob.Register(&TurnComplete{}) gob.Register(&FinalTurnComplete{}) defaults := DefaultNetParams() go RunClient(p, defaults.ClientPort, defaults.BrokerAddr, events, keyPresses) } <file_sep>/gol/worker.go package gol import ( "uk.ac.bris.cs/gameoflife/util" ) // WorkerState holds all the information the worker needs type WorkerState struct { Stopper chan struct{} World [][]bool Offset int Slice int Height int Width int } // WorkerReq is the request type for the worker function type WorkerReq struct { RowAbove []bool RowBelow []bool Turn int } // WorkerRes is the result type for the worker function type WorkerRes struct { World [][]bool Flipped []util.Cell } // InitWorkerReq initWorkerReq type InitWorkerReq struct { World [][]bool Offset int Slice int Height int Width int } // InitWorkerRes initWorkerRes type InitWorkerRes struct { } // StopWorkerReq stopWorkerReq type StopWorkerReq struct { } // StopWorkerRes stopWorkerRes type StopWorkerRes struct { } // InitWorker initialises the worker func (ws *WorkerState) InitWorker(req InitWorkerReq, res *InitWorkerRes) (err error) { ws.World = req.World ws.Offset = req.Offset ws.Slice = req.Slice ws.Height = req.Height ws.Width = req.Width return nil } // Worker is a machine that takes some section of the image and processes work on it for a number of turns func (ws *WorkerState) Worker(req WorkerReq, res *WorkerRes) (err error) { // Copy rows above and below into their correct position // Add height so negative mod works ws.World[(ws.Offset+ws.Height-1)%ws.Height] = req.RowBelow ws.World[(ws.Offset+ws.Height+ws.Slice)%ws.Height] = req.RowAbove res.World = make([][]bool, ws.Slice) nextWorld := newWorld(ws.Height, ws.Width) cells := make([]util.Cell, 0) for y := ws.Offset; y < ws.Offset+ws.Slice; y++ { for x := 0; x < ws.Width; x++ { val := ws.World[y][x] cell := util.Cell{X: x, Y: y} aliveNeighbors := FindAliveNeighbours(ws.World, x, y) if val && (aliveNeighbors == 2 || aliveNeighbors == 3) { nextWorld[y][x] = true } else if !val && aliveNeighbors == 3 { nextWorld[y][x] = true cells = append(cells, cell) // par.c.events <- CellFlipped{Cell: cell, CompletedTurns: par.turn} } else if val { // No need to change dead cells, all cells are dead by default nextWorld[y][x] = false cells = append(cells, cell) // par.c.events <- CellFlipped{Cell: cell, CompletedTurns: par.turn} } } res.World[y-ws.Offset] = nextWorld[y] } ws.World = nextWorld // res.World = nextWorld res.Flipped = cells return nil } // StopWorker is called by the broker on each worker to stop it func (ws *WorkerState) StopWorker(req StopWorkerReq, res *StopWorkerRes) (err error) { var signal struct{} ws.Stopper <- signal return nil } func newWorld(h, w int) [][]bool { world := make([][]bool, h) for x := range world { world[x] = make([]bool, w) } return world }
24fe3faef346382616ccc30d4d75e8386c21466c
[ "Go" ]
12
Go
ivoreynoldsmoore/golcw
62d14b47ad55b8d1e37ae72df68d27536c658182
af19f70a6d1d1abfac5121cecfd1a25a16d05642
refs/heads/master
<file_sep>package com.codingwithme.moderndashboard import android.content.Intent import android.content.pm.PackageManager import android.net.Uri import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.util.Log import android.widget.TextView import android.widget.Toast import androidx.core.app.ActivityCompat import androidx.core.content.ContextCompat import com.budiyev.android.codescanner.* import kotlinx.android.synthetic.main.activity_clock_control.* import kotlinx.coroutines.delay import java.net.URLEncoder import java.text.SimpleDateFormat import java.util.* private const val CAMERA_REQUEST_CODE = 102 class ClockControlActivity : AppCompatActivity(),ItemClickListener { private lateinit var codeScanner: CodeScanner private lateinit var scanResult : String private lateinit var whichBlock : String private var isScanned : Boolean = false private lateinit var reguPengamanan : String private var phonestr : String = "6281229722400" override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_clock_control) var mApp = MyApplication() reguPengamanan = mApp.globalVar setupPermissions() codeScanner() } private fun codeScanner() { val scannerView = findViewById<CodeScannerView>(R.id.scanner_view) val textView: TextView = findViewById(R.id.tv_textView) val actionbar = supportActionBar actionbar!!.title = "SCAN QRCODE" actionbar.setDisplayHomeAsUpEnabled(true) codeScanner = CodeScanner( this, scannerView) codeScanner.apply { camera = CodeScanner.CAMERA_BACK formats = CodeScanner.ALL_FORMATS autoFocusMode = AutoFocusMode.SAFE scanMode = ScanMode.CONTINUOUS isAutoFocusEnabled = true isFlashEnabled = false codeScanner.decodeCallback = DecodeCallback { runOnUiThread { tv_textView.text = it.text whichBlock = it.text.toString() if (!isScanned && (whichBlock.equals("BLOK A", ignoreCase = true) || whichBlock.equals("BLOK B", ignoreCase = true) || whichBlock.equals("BLOK C", ignoreCase = true) || whichBlock.equals("BLOK D", ignoreCase = true) || whichBlock.equals("BLOK E", ignoreCase = true) || whichBlock.equals("BLOK F", ignoreCase = true) || whichBlock.equals("POS ATAS 1", ignoreCase = true) || whichBlock.equals("POS ATAS 2", ignoreCase = true) || whichBlock.equals("POS ATAS 3", ignoreCase = true) || whichBlock.equals("POS ATAS 4", ignoreCase = true) || whichBlock.equals("RD 01", ignoreCase = true)) ) { isScanned = true openBottomSheet() } } } codeScanner.errorCallback = ErrorCallback { runOnUiThread { Log.e ("Main", "Camera initialization error : ${it.message}") } } } scannerView.setOnClickListener{ codeScanner.startPreview() } } fun openBottomSheet() { val addPhotoBottomDialogFragment = ActionBottom.newInstance() addPhotoBottomDialogFragment.show(supportFragmentManager, ActionBottom.TAG) } override fun onItemClick(item: String?) { // scanResult = "REGU: $reguPengamanan\n" scanResult = "" scanResult = scanResult + "$whichBlock\n" scanResult = scanResult + "*KONDISI: $item*\n" scanResult = scanResult + "WAKTU PATROLI: " + SimpleDateFormat("dd-MM-yyyy HH:mm").format(Date()) tv_textView.text = scanResult isScanned = false submitBtn.setEnabled(true) submitBtn.setBackgroundColor(R.color.teal_200) sendWAMsg() } // // fun sendMessage(message:String){ // // // Creating intent with action send // val intent = Intent(Intent.ACTION_SEND) // // // Setting Intent type // intent.type = "text/plain" // // // Setting whatsapp package name // intent.setPackage("com.whatsapp") // // // // Give your message here // intent.putExtra(Intent.EXTRA_TEXT, message) // // // Checking whether whatsapp is installed or not // if (intent.resolveActivity(packageManager) == null) { // Toast.makeText(this, // "Please install whatsapp first.", // Toast.LENGTH_SHORT).show() // return // } // // // Starting Whatsapp // startActivity(intent) // } fun sendWAMsg() { submitBtn.setOnClickListener { submitBtn.setEnabled(false) val packageManager: PackageManager = packageManager val i = Intent(Intent.ACTION_VIEW) val url = "http://api.whatsapp.com/send?phone=" + phonestr + "&text=" + URLEncoder.encode( scanResult, "UTF-8" ) i.setPackage("com.whatsapp") i.setData(Uri.parse(url)) if (i.resolveActivity(packageManager) != null) { startActivity(i) } else { Toast.makeText(this, "Please install whatsapp first.", Toast.LENGTH_SHORT).show() } // Thread.sleep(1_000) // // val intent = Intent(this, MainActivity::class.java) // startActivity(intent) } } override fun onSupportNavigateUp(): Boolean { onBackPressed() return true } override fun onResume() { super.onResume() codeScanner.startPreview() } override fun onPause() { codeScanner.releaseResources() super.onPause() } private fun setupPermissions() { val permission = ContextCompat.checkSelfPermission(this, android.Manifest.permission.CAMERA) if (permission == PackageManager.PERMISSION_DENIED) { makeRequest() } } private fun makeRequest() { ActivityCompat.requestPermissions(this, arrayOf(android.Manifest.permission.CAMERA), CAMERA_REQUEST_CODE) } }<file_sep>package com.codingwithme.moderndashboard interface ItemClickListener { fun onItemClick(item:String?) }<file_sep>package com.codingwithme.moderndashboard import android.app.Application class MyApplication : Application() { var globalVar = "<NAME>" }<file_sep>package com.codingwithme.moderndashboard import android.content.Intent import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.widget.LinearLayout import android.widget.Toast import kotlinx.android.synthetic.main.activity_main.* class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) var clockctrl: LinearLayout = findViewById(R.id.btnClock) clockctrl.setOnClickListener{ val intent = Intent(this, ClockControlActivity::class.java) startActivity(intent) // Toast.makeText(this@MainActivity, "Hallo Hallo Bandung", Toast.LENGTH_SHORT).show() } btnhistory.setOnClickListener{ Toast.makeText(this@MainActivity, "COMING SOON", Toast.LENGTH_SHORT).show() } } }<file_sep>package com.codingwithme.moderndashboard import android.content.Intent import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import kotlinx.coroutines.* class SplashScreenActivity : AppCompatActivity() { val activityScope = CoroutineScope(Dispatchers.Main) override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_splash_screen) activityScope.launch { delay(1500) var intent = Intent(this@SplashScreenActivity, MainActivity::class.java) startActivity(intent) finish() } } }
9cc621dc8ba901845a7f449e8cd9a849616ebd98
[ "Kotlin" ]
5
Kotlin
lslesecure/ClockControl-app
456b920b56e18e8bc70fe7a2abc46f15e81348df
92598dfa5c614d07824cc6e20ad095381c272cfb
refs/heads/main
<repo_name>JarrodTarico/pythonplayground<file_sep>/test_imports.py # whenever you import a file, python runs the code in that file, thats # why __name__ variable will be the the name of the file and not __main__ # now if python is running a file directly __name__ == '__main__' # This way you can run code you only want to run if the file is being ran directly # import asyncio_playground async def main(): result = await asyncio_playground.find_divisibles(100, 99) print (result)<file_sep>/asyncio_playground.py import asyncio #Note: Adding async infront of a function makes it a coroutine async def find_divisibles(inrange: int, div_by: int): print ("The numbers in the range 0 to {} are divisble by {}".format(inrange, div_by)) located: list = [] for i in range(inrange): if i % div_by == 0: located.append(i) if i % 50000 == 0: await asyncio.sleep(0.0001) print (("For input {} and {} here are the numbers {}".format(inrange, div_by, located))) async def main(): divs1 = loop.create_task(find_divisibles(3423, 2)) divs2 = loop.create_task(find_divisibles(50, 9)) divs3 = loop.create_task(find_divisibles(800, 4)) #runs this as a batch await asyncio.wait([divs1,divs2,divs3]) if __name__ == '__main__': #we want to run the main coroutine until complete loop = asyncio.get_event_loop() try: loop.run_until_complete(main()) except Exception as e: print (e) finally: loop.close()
6563e78b2ce54a711599851732cd25ceb27244f7
[ "Python" ]
2
Python
JarrodTarico/pythonplayground
c0d9927374e457dcc16a6129e9239e93a52ce797
57cecad640d4e7469702480253f63da9fb14685b
refs/heads/main
<file_sep>// nothing here yet ¯\_(ツ)_/¯
3cb19edfcbe6a9580650dc0f5377f2abfbc547f2
[ "JavaScript" ]
1
JavaScript
Sirbananathe6th/sirbananathe6th.github.io
8405ff32b2b57669141e92de973858d7a78b7275
24ff9ca9d01dc3ca8cae4ea047f99b96cba63028
refs/heads/master
<repo_name>ivanmakarychev/tcp-chat-server<file_sep>/tcp-chat-server.c #include <arpa/inet.h> #include <errno.h> #include <fcntl.h> #include <pthread.h> #include <sys/socket.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #define MSG 1 #define STOP 0 #define BUF_SIZE 1024 typedef struct { int id; int pipe[2]; int free; int socket; pthread_t thread; } thread_descr; typedef struct { int id; int type; char * msg; } msg; int listenerPipe[2]; int msgPipe[2]; int threadsCount = 0; thread_descr * threads; void *listener(void *vargp) { int *port = vargp; int listenSock = socket( AF_INET, SOCK_STREAM, IPPROTO_IP ); if (listenSock == -1) { perror("socket error"); exit(-1); } struct sockaddr_in servaddr; bzero( (void *)&servaddr, sizeof(servaddr) ); servaddr.sin_family = AF_INET; servaddr.sin_addr.s_addr = htonl( INADDR_ANY ); servaddr.sin_port = htons(*port); if (bind( listenSock, (struct sockaddr *)&servaddr, sizeof(servaddr) )) { perror("bind error"); exit(-3); } if (listen( listenSock, 5 )) { perror("listen error"); exit(-2); } int connSock; while(1) { connSock = accept( listenSock, (struct sockaddr *)NULL, (socklen_t *)NULL ); printf("Connection established, socket: %d\n", connSock); if (write(listenerPipe[1], &connSock, sizeof(connSock)) == -1) { perror("write"); exit(1); } } return NULL; } void *reader(void *vargp) { thread_descr *params = vargp; printf("Tread %d start\n", params->id); char buf[BUF_SIZE + 1]; msg message; message.id = params->id; int k; int sock; while(1) { if (read(params->pipe[0], &sock, sizeof(sock)) <= 0) { perror("read in thread"); exit(2); } params->socket = sock; message.type = MSG; printf("thread %d got new task with socket %d\n", params->id, params->socket); while ((k = read(params->socket, &buf, BUF_SIZE)) > 0) { buf[k] = '\0'; printf("thread %d got message: %s", params->id, buf); message.msg = malloc(sizeof(char) * k); strcpy(message.msg, buf); write(msgPipe[1], &message, sizeof(message)); } printf("thread %d EOF\n", params->id); message.type = STOP; write(msgPipe[1], &message, sizeof(message)); } return NULL; } int main(int argc, char ** argv) { if (argc < 2) { fprintf(stderr, "Usage: %s port\n", argv[0]); return 0; } int port = atoi(argv[1]); if (port <= 0) { fprintf(stderr, "Bad port: %s\n", argv[1]); return 0; } // init list pipe if (pipe(listenerPipe) < 0) { perror("pipe"); return -1; } if (fcntl(listenerPipe[0], F_SETFL, O_NONBLOCK) < 0) { perror("fcntl"); return -1; } // init msg pipe if (pipe(msgPipe) < 0) { perror("pipe"); return -1; } if (fcntl(msgPipe[0], F_SETFL, O_NONBLOCK) < 0) { perror("fcntl"); return -1; } // init listener thread pthread_t listenerThread; if (pthread_create(&listenerThread, NULL, listener, &port)) { perror("pthread_create"); exit(3); } int socket; msg message; int freeThread; while(1) { switch (read(listenerPipe[0], &socket, sizeof(socket))) { case 0: perror("read from listenerPipe: EOF"); exit(4); case -1: if (errno != EAGAIN) { perror("read"); exit(5); } break; default: // find free thread or create a new one printf("got new socket: %d\n", socket); freeThread = -1; for (int i = 0; i < threadsCount; i++) { if (threads[i].free) { freeThread = i; break; } } printf("freeThread = %d\n", freeThread); if (freeThread == -1) { freeThread = threadsCount; threadsCount++; // add thread threads = realloc(threads, sizeof(thread_descr) * threadsCount); if (threads == NULL) { perror("realloc"); exit(6); } if (pipe(threads[freeThread].pipe) < 0) { perror("pipe"); exit(7); } threads[freeThread].id = freeThread; if (pthread_create(&threads[freeThread].thread, NULL, reader, &threads[freeThread])) { perror("pthread_create"); exit(8); } } // send new task to thread threads[freeThread].free = 0; threads[freeThread].socket = socket; if (write(threads[freeThread].pipe[1], &socket, sizeof(socket)) == -1) { perror("write to thread"); shutdown(socket, SHUT_RDWR); close(socket); } } switch (read(msgPipe[0], &message, sizeof(message))) { case 0: exit(9); case -1: if (errno != EAGAIN) { perror("read"); exit(10); } break; default: if (message.type == MSG) { // broadcast for (int i = 0; i < threadsCount; i++) { if (message.id != i && !threads[i].free) { printf("send msg to thread %d\n", i); if (write(threads[i].socket, message.msg, strlen(message.msg)) == -1) { perror("write to socket"); threads[i].free = 1; shutdown(threads[i].socket, SHUT_RDWR); close(threads[i].socket); } } } } else { // free thread and close socket printf("free thread %d\n", message.id); threads[message.id].free = 1; shutdown(threads[message.id].socket, SHUT_RDWR); close(threads[message.id].socket); } } } return 0; } <file_sep>/README.md # tcp-chat-server A simple TCP chat server. Pass a port number in command line argument. To send and receive messages connect to the server with telnet.
593863201227470b156d201b2760fad94364a02b
[ "Markdown", "C" ]
2
C
ivanmakarychev/tcp-chat-server
134f09ba25e76cc72242f4918bc0ca5b03085449
a35b157f85563ab3db2a73af3569b6c6f8392c3f
refs/heads/master
<file_sep>#define GLEW_STATIC #include <gl/glew.h> #include <glfw/glfw3.h> #include <stdio.h> #include <stdlib.h> GLFWwindow* initilizeWindowContext() { glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 2); // specify opengl 3.2 glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); // only new core funcionality glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE); glfwWindowHint(GLFW_RESIZABLE, GL_FALSE); GLFWwindow* window = glfwCreateWindow(800, 600, "yaroslav_berejnoi_HW2", 0, 0); // Windowed return window; } void logShaderRenderStatus(GLuint id) { GLint status; glGetShaderiv(id, GL_COMPILE_STATUS, &status); if (status == GL_TRUE) { printf("Shader: %i compiled\n", id); } else { char buffer[512]; glGetShaderInfoLog(id, 512, NULL, buffer); printf(buffer); } }; int main() { glfwInit(); GLFWwindow* window = initilizeWindowContext(); glfwMakeContextCurrent(window); glewExperimental = GL_TRUE; // force to check for modern functions glewInit(); // Create Vertex Array Object GLuint vao; glGenVertexArrays(1, &vao); glBindVertexArray(vao); // Create a Vertex Buffer Object and copy the vertex data to it GLuint vbo; glGenBuffers(1, &vbo); glBindBuffer(GL_ARRAY_BUFFER, vbo); float squareVert[] = { -0.5f, 0.5f, 1.0f, 0.0f, 0.0f, // Top-left 0.5f, 0.5f, 0.0f, 1.0f, 0.0f, // Top-right 0.5f, -0.5f, 0.0f, 0.0f, 1.0f, // Bottom-right 0.5f, -0.5f, 0.0f, 0.0f, 1.0f, // Bottom-right -0.5f, -0.5f, 1.0f, 1.0f, 1.0f, // Bottom-left -0.5f, 0.5f, 1.0f, 0.0f, 0.0f // Top-left }; glBufferData(GL_ARRAY_BUFFER, sizeof(squareVert), squareVert, GL_STATIC_DRAW); //Vertex data is upload once and drawn many times (e.g the world). //GL_STATIC_DRAW determines the type of memory to use for efficiency char *vertexSource; char *fragmentSource; vertexSource = "#version 150 \n in vec2 position; in vec3 color; out vec3 Color; void main(){ Color = color; gl_Position = vec4(position, 0.0, 1.0); }"; // vertex shader fragmentSource = "#version 150 \n in vec3 Color; out vec4 outColor; void main() {outColor = vec4(Color, 1.0);}"; // fragment shader GLuint vertexShader = glCreateShader(GL_VERTEX_SHADER); glShaderSource(vertexShader, 1, &vertexSource, NULL); glCompileShader(vertexShader); logShaderRenderStatus(vertexShader); GLuint fragmentShader = glCreateShader(GL_FRAGMENT_SHADER); glShaderSource(fragmentShader, 1, &fragmentSource, NULL); glCompileShader(fragmentShader); logShaderRenderStatus(fragmentShader); GLuint shaderProgram = glCreateProgram(); glAttachShader(shaderProgram, vertexShader); glAttachShader(shaderProgram, fragmentShader); glLinkProgram(shaderProgram); glUseProgram(shaderProgram); //only one active at a time, just like a vertex buffer GLint posAttrib = glGetAttribLocation(shaderProgram, "position"); glEnableVertexAttribArray(posAttrib); glVertexAttribPointer(posAttrib, 2, GL_FLOAT, GL_FALSE, 5*sizeof(float), 0); // input, # of values for the input, type of each component, normalized, stride, offset // stride: how many bytes between each position attribute in array. 0 means no data in between // offset: how many bytes from the start the attribute occurs GLint colAttrib = glGetAttribLocation(shaderProgram, "color"); glEnableVertexAttribArray(colAttrib); glVertexAttribPointer(colAttrib, 3, GL_FLOAT, GL_FALSE, 5 * sizeof(float), (void*)(2 * sizeof(float))); // closed loop event: only handle events when you need to while (!glfwWindowShouldClose(window)) { glfwSwapBuffers(window); //swap back buffer and front buffer after drawing has finished glfwPollEvents(); // retrieve window events glDrawArrays(GL_TRIANGLES, 0, 6); } glfwTerminate(); }<file_sep>#include <GL/glut.h> #include <GL/glu.h> #include <GL/gl.h> void initilizeWindow(void) { glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB); glutInitWindowSize(500, 500); glutInitWindowPosition(100, 100); glutCreateWindow("Simple Box"); }; void setDisplayMode(void) { glClearColor(0.0, 0.0, 0.0, 0.0); glMatrixMode(GL_PROJECTION); glLoadIdentity(); glOrtho(0.0, 1.0, 0.0, 1.0, -1.0, 1.0); } void draw(void) { glClear(GL_COLOR_BUFFER_BIT); glColor3f(0.0, 1.0, 1.0); glBegin(GL_POLYGON); glVertex3f(0.25, 0.25, 0.0); glVertex3f(0.75, 0.25, 0.0); glVertex3f(0.75, 0.75, 0.0); glVertex3f(0.25, 0.75, 0.0); glEnd(); glFlush(); }; int main(int argc, char** argv) { glutInit(&argc, argv); initilizeWindow(); setDisplayMode(); glutDisplayFunc(draw); glutMainLoop(); return 0; }<file_sep>#define GLEW_STATIC #include <gl/glew.h> #include <glfw/glfw3.h> #include <stdio.h> #include <stdlib.h> #include <glm/glm.hpp> #include <glm/gtc/matrix_transform.hpp> #include <glm/gtc/type_ptr.hpp> #include <iostream> #include <fstream> GLFWwindow* initilizeWindowContext() { glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 2); // specify opengl 3.2 glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); // only new core funcionality glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE); glfwWindowHint(GLFW_RESIZABLE, GL_FALSE); GLFWwindow* window = glfwCreateWindow(800, 600, "yaroslav_berejnoi_HW3", 0, 0); // Windowed return window; } void logShaderRenderStatus(GLuint id) { GLint status; glGetShaderiv(id, GL_COMPILE_STATUS, &status); if (status == GL_TRUE) { printf("Shader: %i compiled\n", id); } else { char buffer[512]; glGetShaderInfoLog(id, 512, NULL, buffer); printf(buffer); } }; void orthographicOne(GLuint shaderProgram) { glm::mat4 model; model = glm::rotate(model, glm::radians(0.0f), glm::vec3(1.0f, 1.0f, 1.0f)); GLint uniTrans = glGetUniformLocation(shaderProgram, "model"); glUniformMatrix4fv(uniTrans, 1, GL_FALSE, glm::value_ptr(model)); glm::mat4 view = glm::lookAt( glm::vec3(0.0f, 0.0f, 10.0f), //camera position glm::vec3(0.0f, 0.0f, 0.0f), // point centered on screen glm::vec3(0.0f, 1.0f, 0.0f) // view up ); GLint uniView = glGetUniformLocation(shaderProgram, "view"); glUniformMatrix4fv(uniView, 1, GL_FALSE, glm::value_ptr(view)); glm::mat4 proj = glm::ortho(-8.0f, 8.0f, -6.0f, 6.0f, 1.0f, 100.0f); GLint uniProj = glGetUniformLocation(shaderProgram, "proj"); glUniformMatrix4fv(uniProj, 1, GL_FALSE, glm::value_ptr(proj)); } void orthographicTwo(GLuint shaderProgram) { glm::mat4 model; model = glm::rotate(model, glm::radians(0.0f), glm::vec3(1.0f, 1.0f, 1.0f)); GLint uniTrans = glGetUniformLocation(shaderProgram, "model"); glUniformMatrix4fv(uniTrans, 1, GL_FALSE, glm::value_ptr(model)); glm::mat4 view = glm::lookAt( glm::vec3(0.0f, 10.0f, 0.0f), //camera position glm::vec3(0.0f, 0.0f, 0.0f), // point centered on screen glm::vec3(1.0f, 0.0f, 2.0f) // view up ); GLint uniView = glGetUniformLocation(shaderProgram, "view"); glUniformMatrix4fv(uniView, 1, GL_FALSE, glm::value_ptr(view)); glm::mat4 proj = glm::ortho(-4.0f, 4.0f, -3.0f, 3.0f, 1.0f, 100.0f); GLint uniProj = glGetUniformLocation(shaderProgram, "proj"); glUniformMatrix4fv(uniProj, 1, GL_FALSE, glm::value_ptr(proj)); } void modelTransformOne(GLuint shaderProgram) { glm::mat4 model; model = glm::translate(model, glm::vec3(0.0f, -1.0f, 0.0f)); GLint uniTrans = glGetUniformLocation(shaderProgram, "model"); glUniformMatrix4fv(uniTrans, 1, GL_FALSE, glm::value_ptr(model)); glm::mat4 view = glm::lookAt( glm::vec3(10.0f, 10.0f, 10.0f), //camera position glm::vec3(0.0f, 0.0f, 0.0f), // point centered on screen glm::vec3(0.0f, 1.0f, 0.0f) // view up ); GLint uniView = glGetUniformLocation(shaderProgram, "view"); glUniformMatrix4fv(uniView, 1, GL_FALSE, glm::value_ptr(view)); glm::mat4 proj = glm::ortho(-4.0f, 4.0f, -3.0f, 3.0f, 1.0f, 100.0f); GLint uniProj = glGetUniformLocation(shaderProgram, "proj"); glUniformMatrix4fv(uniProj, 1, GL_FALSE, glm::value_ptr(proj)); } void modelTransformTwo(GLuint shaderProgram) { glm::mat4 model; model = glm::translate(model, glm::vec3(0.0f, -1.0f, 0.0f)); GLint uniTrans = glGetUniformLocation(shaderProgram, "model"); glUniformMatrix4fv(uniTrans, 1, GL_FALSE, glm::value_ptr(model)); glm::mat4 view = glm::lookAt( glm::vec3(0.0f, 0.0f, 20.0f), //camera position glm::vec3(0.0f, 0.0f, 0.0f), // point centered on screen glm::vec3(1.0f, 1.0f, 0.0f) // view up ); GLint uniView = glGetUniformLocation(shaderProgram, "view"); glUniformMatrix4fv(uniView, 1, GL_FALSE, glm::value_ptr(view)); glm::mat4 proj = glm::perspective(glm::radians(20.0f), 800.0f / 600.0f, 1.0f, 100.0f); GLint uniProj = glGetUniformLocation(shaderProgram, "proj"); glUniformMatrix4fv(uniProj, 1, GL_FALSE, glm::value_ptr(proj)); } void modelTransformThree(GLuint shaderProgram) { glm::mat4 model; model = glm::translate(model, glm::vec3(0.0f, 0.0f, 0.0f)); GLint uniTrans = glGetUniformLocation(shaderProgram, "model"); glUniformMatrix4fv(uniTrans, 1, GL_FALSE, glm::value_ptr(model)); glm::mat4 view = glm::lookAt( glm::vec3(10.0f, 10.0f, 10.0f), //camera position glm::vec3(0.0f, 0.0f, 0.0f), // point centered on screen glm::vec3(0.0f, 1.0f, 0.0f) // view up ); GLint uniView = glGetUniformLocation(shaderProgram, "view"); glUniformMatrix4fv(uniView, 1, GL_FALSE, glm::value_ptr(view)); glm::mat4 proj = glm::perspective(glm::radians(30.0f), 800.0f / 600.0f, 1.0f, 100.0f); GLint uniProj = glGetUniformLocation(shaderProgram, "proj"); glUniformMatrix4fv(uniProj, 1, GL_FALSE, glm::value_ptr(proj)); } void modelTransformFour(GLuint shaderProgram) { glm::mat4 model; model = glm::rotate(model, glm::radians(45.0f), glm::vec3(1.0f, 0.0f, 0.0f)); model = glm::translate(model, glm::vec3(0.0f, -1.0f, 0.0f)); GLint uniTrans = glGetUniformLocation(shaderProgram, "model"); glUniformMatrix4fv(uniTrans, 1, GL_FALSE, glm::value_ptr(model)); glm::mat4 view = glm::lookAt( glm::vec3(3.0f, 3.0f, 3.0f), //camera position glm::vec3(0.0f, 0.0f, 0.0f), // point centered on screen glm::vec3(0.0f, 1.0f, 0.0f) // view up ); GLint uniView = glGetUniformLocation(shaderProgram, "view"); glUniformMatrix4fv(uniView, 1, GL_FALSE, glm::value_ptr(view)); glm::mat4 proj = glm::perspective(glm::radians(70.0f), 800.0f / 600.0f, 1.0f, 100.0f); GLint uniProj = glGetUniformLocation(shaderProgram, "proj"); glUniformMatrix4fv(uniProj, 1, GL_FALSE, glm::value_ptr(proj)); } int main() { glfwInit(); GLFWwindow* window = initilizeWindowContext(); glfwMakeContextCurrent(window); glewExperimental = GL_TRUE; glClearColor(0.0f, 0.0f, 0.0f, 1.0f); // Enable depth test glEnable(GL_DEPTH_TEST); // Accept fragment if it closer to the camera than the former one glDepthFunc(GL_LESS); // force to check for modern functions glewInit(); // Create Vertex Array Object GLuint vao; glGenVertexArrays(1, &vao); glBindVertexArray(vao); // Create a Vertex Buffer Object and copy the vertex data to it GLuint vbo; glGenBuffers(1, &vbo); glBindBuffer(GL_ARRAY_BUFFER, vbo); std::ifstream infile("Tris.txt"); int tris; infile >> tris; int numberVertices = tris * 7 * 3; GLfloat* vertices = new GLfloat[numberVertices]; GLfloat number; int i = 0; while (infile >> number) { vertices[i] = number; i++; } glBufferData(GL_ARRAY_BUFFER, numberVertices*4, vertices, GL_STATIC_DRAW); //Vertex data is upload once and drawn many times (e.g the world). //GL_STATIC_DRAW determines the type of memory to use for efficiency char *vertexSource; char *fragmentSource; vertexSource = "#version 330 core \n" "in vec3 position;" "in vec4 color;" "out vec4 Color;" "uniform mat4 model;" "uniform mat4 view;" "uniform mat4 proj;" "void main(){ Color = color; gl_Position = proj * view * model * vec4(position, 1.0); }"; // vertex shader fragmentSource = "#version 330 core \n" "in vec4 Color;" "out vec4 outColor;" "void main() {outColor = vec4(Color.r, Color.g, Color.b, Color.a);}"; // fragment shader GLuint vertexShader = glCreateShader(GL_VERTEX_SHADER); glShaderSource(vertexShader, 1, &vertexSource, NULL); glCompileShader(vertexShader); logShaderRenderStatus(vertexShader); GLuint fragmentShader = glCreateShader(GL_FRAGMENT_SHADER); glShaderSource(fragmentShader, 1, &fragmentSource, NULL); glCompileShader(fragmentShader); logShaderRenderStatus(fragmentShader); GLuint shaderProgram = glCreateProgram(); glAttachShader(shaderProgram, vertexShader); glAttachShader(shaderProgram, fragmentShader); glLinkProgram(shaderProgram); glUseProgram(shaderProgram); //only one active at a time, just like a vertex buffer GLint posAttrib = glGetAttribLocation(shaderProgram, "position"); glEnableVertexAttribArray(posAttrib); glVertexAttribPointer(posAttrib, 3, GL_FLOAT, GL_FALSE, 7 * sizeof(GLfloat), 0); // input, # of values for the input, type of each component, normalized, stride, offset // stride: how many bytes between each position attribute in array. 0 means no data in between // offset: how many bytes from the start the attribute occurs GLint colAttrib = glGetAttribLocation(shaderProgram, "color"); glEnableVertexAttribArray(colAttrib); glVertexAttribPointer(colAttrib, 4, GL_FLOAT, GL_FALSE, 7 * sizeof(GLfloat), (void*)(3 * sizeof(GLfloat))); orthographicOne(shaderProgram); glfwSetInputMode(window, GLFW_STICKY_KEYS, GL_TRUE); glEnable(GL_DEPTH_TEST); // closed loop event: only handle events when you need to while (!glfwWindowShouldClose(window)) { glfwSwapBuffers(window); //swap back buffer and front buffer after drawing has finished glfwPollEvents(); // retrieve window events glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glDrawArrays(GL_TRIANGLES, 0, numberVertices); if (glfwGetKey(window, GLFW_KEY_1) == GLFW_PRESS) { orthographicOne(shaderProgram); } if (glfwGetKey(window, GLFW_KEY_2) == GLFW_PRESS) { orthographicTwo(shaderProgram); } if (glfwGetKey(window, GLFW_KEY_3) == GLFW_PRESS) { modelTransformOne(shaderProgram); } if (glfwGetKey(window, GLFW_KEY_4) == GLFW_PRESS) { modelTransformTwo(shaderProgram); } if (glfwGetKey(window, GLFW_KEY_5) == GLFW_PRESS) { modelTransformThree(shaderProgram); } if (glfwGetKey(window, GLFW_KEY_6) == GLFW_PRESS) { modelTransformFour(shaderProgram); } } glfwTerminate(); }<file_sep>#define GLEW_STATIC #include <gl/glew.h> #include <glfw/glfw3.h> #include <stdio.h> #include <stdlib.h> #include <glm/glm.hpp> #include <glm/gtc/matrix_transform.hpp> #include <glm/gtc/type_ptr.hpp> #include <iostream> #include <fstream> GLFWwindow* initilizeWindowContext() { glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 2); // specify opengl 3.2 glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); // only new core funcionality glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE); glfwWindowHint(GLFW_RESIZABLE, GL_FALSE); GLFWwindow* window = glfwCreateWindow(800, 600, "yaroslav_berejnoi_HW4", 0, 0); // Windowed return window; } void logShaderRenderStatus(GLuint id) { GLint status; glGetShaderiv(id, GL_COMPILE_STATUS, &status); if (status == GL_TRUE) { printf("Shader: %i compiled\n", id); } else { char buffer[512]; glGetShaderInfoLog(id, 512, NULL, buffer); printf(buffer); } }; void phongOne(GLuint shaderProgram) { glm::mat4 model; model = glm::translate(model, glm::vec3(0.0f, -1.0f, 0.0f)); GLint uniTrans = glGetUniformLocation(shaderProgram, "model"); glUniformMatrix4fv(uniTrans, 1, GL_FALSE, glm::value_ptr(model)); glm::mat4 view = glm::lookAt( glm::vec3(10.0f, 10.0f, 10.0f), //camera position glm::vec3(0.0f, 0.0f, 0.0f), // point centered on screen glm::vec3(0.0f, 1.0f, 0.0f) // view up ); GLint uniView = glGetUniformLocation(shaderProgram, "view"); glUniformMatrix4fv(uniView, 1, GL_FALSE, glm::value_ptr(view)); glm::mat4 proj = glm::ortho(-4.0f, 4.0f, -3.0f, 3.0f, 1.0f, 100.0f); GLint uniProj = glGetUniformLocation(shaderProgram, "proj"); glUniformMatrix4fv(uniProj, 1, GL_FALSE, glm::value_ptr(proj)); } void phongTwo(GLuint shaderProgram) { glm::mat4 model; model = glm::rotate(model, glm::radians(45.0f), glm::vec3(1.0f, 0.0f, 0.0f)); model = glm::translate(model, glm::vec3(0.0f, -1.0f, 0.0f)); GLint uniTrans = glGetUniformLocation(shaderProgram, "model"); glUniformMatrix4fv(uniTrans, 1, GL_FALSE, glm::value_ptr(model)); glm::mat4 view = glm::lookAt( glm::vec3(3.0f, 3.0f, 3.0f), //camera position glm::vec3(0.0f, 0.0f, 0.0f), // point centered on screen glm::vec3(0.0f, 1.0f, 0.0f) // view up ); GLint uniView = glGetUniformLocation(shaderProgram, "view"); glUniformMatrix4fv(uniView, 1, GL_FALSE, glm::value_ptr(view)); glm::mat4 proj = glm::perspective(glm::radians(70.0f), 800.0f / 600.0f, 1.0f, 100.0f); GLint uniProj = glGetUniformLocation(shaderProgram, "proj"); glUniformMatrix4fv(uniProj, 1, GL_FALSE, glm::value_ptr(proj)); } int main() { glfwInit(); GLFWwindow* window = initilizeWindowContext(); glfwMakeContextCurrent(window); glewExperimental = GL_TRUE; // force to check for modern functions glewInit(); glClearColor(0.0f, 0.0f, 0.0f, 1.0f); // Enable depth test glEnable(GL_DEPTH_TEST); // Accept fragment if it closer to the camera than the former one glDepthFunc(GL_LESS); // Create Vertex Array Object GLuint vao; glGenVertexArrays(1, &vao); glBindVertexArray(vao); // Create a Vertex Buffer Object and copy the vertex data to it GLuint vbo; glGenBuffers(1, &vbo); glBindBuffer(GL_ARRAY_BUFFER, vbo); std::ifstream infile("Tris1.txt"); int tris; infile >> tris; int numberVertices = tris * 10 * 3; GLfloat* vertices = new GLfloat[numberVertices]; GLfloat number; int i = 0; while (infile >> number) { vertices[i] = number; i++; } glBufferData(GL_ARRAY_BUFFER, numberVertices * 4, vertices, GL_STATIC_DRAW); //Vertex data is upload once and drawn many times (e.g the world). //GL_STATIC_DRAW determines the type of memory to use for efficiency char *vertexSource; char *fragmentSource; vertexSource = "#version 330 core \n" "in vec3 position;" "in vec3 normal;" "in vec4 objectColor;" "out vec3 ObjectColor;" "uniform mat4 model;" "uniform mat4 view;" "uniform mat4 proj;" //make a new light "void makeNewLight(in vec3 color, in vec3 direction, in float diffuseIntensity, in float ambientIntensity, in float specularIntensity, in float specularPower, out vec3 calculatedColor){" "float cosTheta = dot(normal, direction);" "vec3 materialDiffuseColor = color;" //diffuse, this should be the original color of the teapot (white) but this looks close to the expected output "vec3 materialAmbientColor = vec3(ambientIntensity,ambientIntensity,ambientIntensity) * materialDiffuseColor;" //ambient //specular "vec3 eye = normalize(normal);" "vec3 reflection = reflect(-direction, normal);" "float cosAlpha = clamp(dot(eye, reflection), 0, 1);" "vec3 specularCalculation = materialDiffuseColor * color * specularIntensity * pow(cosAlpha,specularPower*2);" "calculatedColor = materialAmbientColor + materialDiffuseColor * color * diffuseIntensity * cosTheta + specularCalculation;}" //main "void main(){" "vec3 redColor = vec3(1, 0.1, 0.1);" "vec3 redDirection = vec3(0, 1, 0);" "vec3 greenColor = vec3(0.1, 1.0, 0.1);" "vec3 greenDirection = vec3(1, 0, 0);" "vec3 blueColor = vec3(0.1, 0.1, 1.0);" "vec3 blueDirection = vec3(0, 0, 1);" "vec3 firstLight;" "makeNewLight(redColor, redDirection, 0.3, 0.1, 0.6, 3.0, firstLight);" "vec3 secondLight;" "makeNewLight(greenColor, greenDirection, 0.3, 0.1, 0.6, 3.0, secondLight);" "vec3 thirdLight;" "makeNewLight(blueColor, blueDirection, 0.3, 0.1, 0.6, 3.0, thirdLight);" "ObjectColor = firstLight +secondLight + thirdLight;" "gl_Position = proj * view * model * vec4(position, 1.0); }"; // vertex shader fragmentSource = "#version 330 core \n" "in vec3 ObjectColor;" "out vec3 outColor;" "void main() {outColor = vec3(ObjectColor);}"; // fragment shader GLuint vertexShader = glCreateShader(GL_VERTEX_SHADER); glShaderSource(vertexShader, 1, &vertexSource, NULL); glCompileShader(vertexShader); logShaderRenderStatus(vertexShader); GLuint fragmentShader = glCreateShader(GL_FRAGMENT_SHADER); glShaderSource(fragmentShader, 1, &fragmentSource, NULL); glCompileShader(fragmentShader); logShaderRenderStatus(fragmentShader); GLuint shaderProgram = glCreateProgram(); glAttachShader(shaderProgram, vertexShader); glAttachShader(shaderProgram, fragmentShader); glLinkProgram(shaderProgram); glUseProgram(shaderProgram); //only one active at a time, just like a vertex buffer GLint posAttrib = glGetAttribLocation(shaderProgram, "position"); glEnableVertexAttribArray(posAttrib); glVertexAttribPointer(posAttrib, 3, GL_FLOAT, GL_FALSE, 10 * sizeof(GLfloat), 0); // input, # of values for the input, type of each component, normalized, stride, offset // stride: how many bytes between each position attribute in array. 0 means no data in between // offset: how many bytes from the start the attribute occurs GLint normAttrib = glGetAttribLocation(shaderProgram, "normal"); glEnableVertexAttribArray(normAttrib); glVertexAttribPointer(normAttrib, 3, GL_FLOAT, GL_FALSE, 10 * sizeof(GLfloat), (void*)(3 * sizeof(GLfloat))); GLint colAttrib = glGetAttribLocation(shaderProgram, "objectColor"); glEnableVertexAttribArray(colAttrib); glVertexAttribPointer(colAttrib, 4, GL_FLOAT, GL_FALSE, 10 * sizeof(GLfloat), (void*)(6 * sizeof(GLfloat))); phongOne(shaderProgram); glfwSetInputMode(window, GLFW_STICKY_KEYS, GL_TRUE); // closed loop event: only handle events when you need to while (!glfwWindowShouldClose(window)) { glfwSwapBuffers(window); //swap back buffer and front buffer after drawing has finished glfwPollEvents(); // retrieve window events glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glDrawArrays(GL_TRIANGLES, 0, numberVertices); if (glfwGetKey(window, GLFW_KEY_1) == GLFW_PRESS) { phongOne(shaderProgram); } if (glfwGetKey(window, GLFW_KEY_2) == GLFW_PRESS) { phongTwo(shaderProgram); } } glfwTerminate(); }<file_sep># Opengl assignments COSC 4370 My terribly written opengl assignments for COSC 4370 ## hw1 A simple box ![alt tag](https://raw.githubusercontent.com/YaroBear/opengl/master/hw1/hw1.PNG) ## hw2 A shaded box ![alt tag](https://raw.githubusercontent.com/YaroBear/opengl/master/hw2/hw2.PNG) ## hw3 Reading a file with vertices and corresponding colors of the Utah teapot, as well as GLM model view projection calculations ![alt tag](https://raw.githubusercontent.com/YaroBear/opengl/master/hw3/hw3.gif) ## hw4 Reading a file of the white Utah teapot, and applying Phong shading from 3 different directional light sources ![alt tag](https://raw.githubusercontent.com/YaroBear/opengl/master/hw4/hw4_1.PNG) ![alt tag](https://raw.githubusercontent.com/YaroBear/opengl/master/hw4/hw4_2.PNG)<file_sep>loadCollada(); let objectRotation = 0.0; var compositeObject = {}; function loadCollada(){ let loader = new THREE.ColladaLoader(); loader.load('http://localhost:8000/Walking.dae', function(obj){ Object.values(obj.library.geometries).forEach((geometry) =>{ compositeObject[geometry.name] = {}; compositeObject[geometry.name].position = geometry.build.polylist.data.attributes.position.array; compositeObject[geometry.name].uv = geometry.build.polylist.data.attributes.uv.array; compositeObject[geometry.name].verticesCount = geometry.build.polylist.data.attributes.position.count; }); Object.values(obj.library.images).forEach((image, index) =>{ compositeObject[Object.keys(compositeObject)[index]].texture = image.build; }); console.log(compositeObject); main(); }); } function main(){ let canvas = document.getElementById('walkingBoy'); canvas.height = window.innerHeight; canvas.width = window.innerWidth; const gl = canvas.getContext('webgl'); if(!gl){ alert('unable to initilize webgl'); return; } const vertexShaderSource = ` attribute vec4 aVertexPosition; attribute vec2 aTextureCoord; uniform mat4 uModelViewMarix; uniform mat4 uProjectionMatrix; varying highp vec2 vTextureCoord; void main(){ gl_Position = uProjectionMatrix * uModelViewMarix * aVertexPosition; vTextureCoord = aTextureCoord; } `; const fragmentShaderSource = ` varying highp vec2 vTextureCoord; uniform sampler2D uSampler; void main() { gl_FragColor = texture2D(uSampler, vTextureCoord); } `; const shaderProgram = initShaderProgram(gl, vertexShaderSource, fragmentShaderSource); const programInfo = { program: shaderProgram, attribLocations: { vertexPosition: gl.getAttribLocation(shaderProgram, 'aVertexPosition'), textureCoord: gl.getAttribLocation(shaderProgram, 'aTextureCoord'), }, uniformLocations: { projectionMatrix: gl.getUniformLocation(shaderProgram, 'uProjectionMatrix'), modelViewMatrix: gl.getUniformLocation(shaderProgram, 'uModelViewMarix'), uSampler: gl.getUniformLocation(shaderProgram, 'uSampler'), }, }; let objects = []; Object.keys(compositeObject).forEach((objectName) =>{ let object = {}; object.buffers = initBuffers(gl, compositeObject[objectName].position, compositeObject[objectName].uv); object.texture = loadTexture(gl, 'http://localhost:8000/' + compositeObject[objectName].texture); object.verticesCount = compositeObject[objectName].verticesCount; objects.push(object); }); let then = 0; function render(now){ now *= 0.001; const deltaTime = now - then; then = now; drawScene(gl, programInfo, objects, deltaTime); requestAnimationFrame(render); } requestAnimationFrame(render); //drawScene(gl, programInfo, buffers, 0); } function initBuffers(gl, positionVertices, uvCoords) { const positionBuffer = gl.createBuffer(); gl.bindBuffer(gl.ARRAY_BUFFER, positionBuffer); gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(positionVertices), gl.STATIC_DRAW); const textureCoordBuffer = gl.createBuffer(); gl.bindBuffer(gl.ARRAY_BUFFER, textureCoordBuffer); gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(uvCoords), gl.STATIC_DRAW); return { position: positionBuffer, textureCoord: textureCoordBuffer, }; } function drawScene(gl, programInfo, objects, deltaTime){ gl.clearColor(0.0, 0.0, 0.0, 1.0); gl.clearDepth(1.0); gl.enable(gl.DEPTH_TEST); gl.depthFunc(gl.LEQUAL); gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT); const fieldOfView = 45 * Math.PI / 180; // in radians const aspect = gl.canvas.clientWidth / gl.canvas.clientHeight; const zNear = 0.1; const zFar = 10000.0; const projectionMatrix = mat4.create(); mat4.perspective(projectionMatrix, fieldOfView, aspect, zNear, zFar); const modelViewMatrix = mat4.create(); mat4.translate(modelViewMatrix, modelViewMatrix, [-0.0, -160.0, -200.0]); mat4.rotate(modelViewMatrix, // destination matrix modelViewMatrix, // matrix to rotate objectRotation, // amount to rotate in radians [0, 1, 0]); // axis to rotate around objects.forEach((object) =>{ { const numComponents = 3; const type = gl.FLOAT; const normalize = false; const stride = 0; const offset = 0; gl.bindBuffer(gl.ARRAY_BUFFER, object.buffers.position); gl.vertexAttribPointer( programInfo.attribLocations.vertexPosition, numComponents, type, normalize, stride, offset); gl.enableVertexAttribArray(programInfo.attribLocations.vertexPosition); } { const numComponents = 2; const type = gl.FLOAT; const normalize = false; const stride = 0; const offset = 0; gl.bindBuffer(gl.ARRAY_BUFFER, object.buffers.textureCoord); gl.vertexAttribPointer( programInfo.attribLocations.textureCoord, numComponents, type, normalize, stride, offset); gl.enableVertexAttribArray( programInfo.attribLocations.textureCoord); } gl.useProgram(programInfo.program); gl.uniformMatrix4fv( programInfo.uniformLocations.projectionMatrix, false, projectionMatrix); gl.uniformMatrix4fv( programInfo.uniformLocations.modelViewMatrix, false, modelViewMatrix); gl.activeTexture(gl.TEXTURE0); gl.bindTexture(gl.TEXTURE_2D, object.texture); gl.uniform1i(programInfo.uniformLocations.uSampler, 0); { const offset = 0; const vertexCount = object.verticesCount; gl.drawArrays(gl.TRIANGLES, offset, vertexCount); } }); objectRotation += deltaTime; } function initShaderProgram(gl, vertexSource, fragmentSource){ const vertexShader = loadShader(gl, gl.VERTEX_SHADER, vertexSource); const fragmentShader = loadShader(gl, gl.FRAGMENT_SHADER, fragmentSource); const shaderProgram = gl.createProgram(); gl.attachShader(shaderProgram, vertexShader); gl.attachShader(shaderProgram, fragmentShader); gl.linkProgram(shaderProgram); if(!gl.getProgramParameter(shaderProgram, gl.LINK_STATUS)){ alert('unable to initilize shader program: ' + gl.getProgramInfoLog(shaderProgram)); return null; } return shaderProgram; } function loadShader(gl, type, source){ const shader = gl.createShader(type); gl.shaderSource(shader, source); gl.compileShader(shader); if(!gl.getShaderParameter(shader, gl.COMPILE_STATUS)){ alert('unable to compile shaders: ' + gl.getShaderInfoLog(shader)); gl.deleteShader(shader); return null; } return shader; }
948529d186d7c8b779c855c9b813e527803f9c0a
[ "Markdown", "JavaScript", "C++" ]
6
C++
YaroBear/opengl
7353cc1036336c9903c128af2f8d8466a9556920
1147bc393eec5fd965d223fcebaa92576dee291e
refs/heads/master
<repo_name>vsrz/cs421-2<file_sep>/passwd/pwd.c // passwd.c // By <NAME> // Programming Asssignment Extra Credit // 12/10/2008 FALL 08 #include <stdio.h> #include <stdlib.h> #include <curses.h> #include <string.h> #include <iostream> #include <vector> #define MIN_STR_SIZE 3 #define MAX_STR_SIZE 128 static void pwd_error(char*); int main() { char ch, passwd[MAX_STR_SIZE+1]; char regular_exp[MAX_STR_SIZE+1]; char tok1[MAX_STR_SIZE],tok2[MAX_STR_SIZE],tok3[MAX_STR_SIZE]; bool st_flag=false; int x=0,y=0,tok_cnt=0; printf("Enter regular expression: "); std::cin.getline(regular_exp,MAX_STR_SIZE,'\n'); printf("Your string: %s\n", regular_exp); for(x=0;x<strlen(regular_exp);x++){ if(regular_exp[x]=='('){ ++tok_cnt; if(tok_cnt==1){ y=0; while(regular_exp[x++]!=')'){ tok1[y]=regular_exp[x]; y++; } } } } printf("tok1: %s",tok1); return(0); } // end of int main() void pwd_error(char* s){ printf("ERROR: %s\n",s); exit(EXIT_FAILURE); } <file_sep>/parser/parser.c #include<stdlib.h> #include<stdio.h> #include<string.h> #define FILE_INPUT "sequence.txt" #define MAX_LANG_LENGTH 128 struct pstack{ char element; struct pstack *next; }; struct pstack *pcreate(struct pstack*); struct pstack *premove(struct pstack*); #ifdef DEBUG void print(struct pstack*); #endif int main(int argc,char* argv[]){ FILE *fp; int x=0; char buff[MAX_LANG_LENGTH],ch; struct pstack *p; // Attempt to open the file if((fp=fopen(FILE_INPUT,"r"))==NULL){ perror(FILE_INPUT); exit(1); } // Read the grammar into a buffer fgets(buff,MAX_LANG_LENGTH,fp); printf("Contents of the file: %s\n",buff); // Initalize the stack p=malloc(sizeof(struct pstack)); p->next=NULL; p->element='Z'; // iterate through the grammar while(buff[x]!='\0'){ switch(buff[x]){ case 'i': p=pcreate(p); break; case 'e': p=premove(p); break; } x++; } // check to see if we had an "else" for every "if" if(p->element=='Z') printf("Sequence is syntactically correct\n"); else printf("Incorrect sequence\n"); return(0); } struct pstack *premove(struct pstack *p){ // Remove an item from the stack and do a check. if(p->next==NULL){ printf("Incorrect sequence\n"); exit(1); } return(p->next); } struct pstack *pcreate(struct pstack *p){ struct pstack *new; // Add an "if" to the stack new=malloc(sizeof(struct pstack)); new->element='i'; new->next=p; return(new); } #ifdef DEBUG void print(struct pstack *p){ struct pstack *t=p; int x=0; while(t!=NULL){ printf("%c, ",t->element); t=t->next; } printf("\n"); } #endif <file_sep>/turing/turing.c // turing.c // By <NAME> // Programming Asssignment Project 2 // 12/10/2008 FALL 08 /***************************************************************************** * Task: Design and implement a program to simulate a Turing Machine that * computes the successor function. That is, given a positive integer n as * input it returns the integer n + 1 as output. * * Input to the Turing machine: A positive integer represented as a string of * 0's followed by a B. For example, the positive integer 7 is represented as * the string "0000000B". * * Output: Display each of the moves that your Turing machine goes through to * compute the successor function. ******************************************************************************/ #include <stdio.h> #include <stdlib.h> #include <curses.h> #define MIN_STR_SIZE 1 #define MAX_STR_SIZE 128 static void pwd_error(char*); int main() { char ch, s[MAX_STR_SIZE+1]; int x=0,y=0,z=0; printf("Enter input string: "); while((ch = (char)getchar()) != '\n'){ if((int)ch != 48) pwd_error("String may contain only 0's."); else s[x++]=ch; } // Is the string too short? if(x<MIN_STR_SIZE) pwd_error("String must contain at least one 0."); s[x++]='B'; s[x++]='\n'; // Iterate through each 0 for(y=0;y<x;y++) { for(z=0;z<x+1;z++){ if(z==y)printf("|q0|"); printf("%c",s[z]); } // If you find the last B, convert it to a zero if(s[y]=='B')s[y]='0'; } return(0); } // end of int main() void pwd_error(char* s){ printf("ERROR: %s\n",s); exit(EXIT_FAILURE); }
710e1c719a1bf1aba865df1022c2e1f838396bcb
[ "C" ]
3
C
vsrz/cs421-2
e9382c7a3ec6e470ce7e7b67032b02bf818c8ef9
2c6cc6f647d0ea021c3711631a839d21f4219717
refs/heads/master
<file_sep>"use strict"; const azure = require("@pulumi/azure"); const pulumi = require("@pulumi/pulumi"); class LB extends pulumi.ComponentResource { constructor(lbname,resourceGroupName, location,path, opts) { super("az-pulumi-js-loadbalancer:LB",lbname, resourceGroupName,location, {}, opts); // Create Load balancer Public IP const lbpip = new azure.network.PublicIp("lbpip", { resourceGroupName: resourceGroupName, location: location, publicIpAddressAllocation: "dynamic", domainNameLabel: `${pulumi.getStack()}`, }, { parent: this }); // Create Load Balancer let lb = new azure.lb.LoadBalancer(lbname, { resourceGroupName: resourceGroupName, location: location, frontendIpConfigurations: [{ name: "LoadBalancerFrontEnd", publicIpAddressId: lbpip.id, }], }, { parent: this }); // Create backend pool let backendPool = new azure.lb.BackendAddressPool("backendPool", { resourceGroupName: resourceGroupName, loadbalancerId: lb.id, }, { parent: this }); // Create Health probe let lbprobe = new azure.lb.Probe("lbprobe", { resourceGroupName: resourceGroupName, loadbalancerId: lb.id, protocol: "tcp", port: 80, intervalInSeconds: 5, numberOfProbes: 2, }, { parent: this }); let lbrule = new azure.lb.Rule("lbrule", { resourceGroupName: resourceGroupName, loadbalancerId: lb.id, protocol: "tcp", frontendPort: 80, backendPort: 80, frontendIpConfigurationName: "LoadBalancerFrontEnd", enableFloatingIp: false, backendAddressPoolId: backendPool.id, idleTimeoutInMinutes: 5, probeId: lbprobe.id, }, { parent: this }); // Create a property for the Backend Pool ID to be used. this.backendPoolID = backendPool.id; } } module.exports.LB = LB;<file_sep>"use strict"; const pulumi = require("@pulumi/pulumi"); const azure = require("@pulumi/azure"); const azurestorage = require("azure-storage"); const mime = require("mime"); class AzureStorageAccount { constructor(){ } createAzureStorageAccount(storageAccountName,rgName, rgLocation) { const account = new azure.storage.Account(storageAccountName, { resourceGroupName: rgName, location: rgLocation, accountTier: "Standard", accountReplicationType: "LRS", }); return account; } createAzureStorageContainer(containerName, storageAccountName,rgName) { const storageContainer = new azure.storage.Container(containerName, { resourceGroupName: rgName, storageAccountName: storageAccountName, containerAccessType: "private", }); return storageContainer; } // create blob createBlob(blobName,containerName, storageAccountName, rgName, filePath) { const blob = new azure.storage.Blob(blobName, { resourceGroupName: rgName, storageAccountName: storageAccountName, storageContainerName: containerName, source: filePath, type: "block", contentType:mime.getType(filePath) || undefined }); return blob; } // Create sas URL for the blob signedBlobReadUrl(blob,account,container) { // Choose a fixed, far-future expiration date for signed blob URLs. const signatureExpiration = new Date(2100, 1); return pulumi.all([ account.primaryConnectionString, container.name, blob.name, ]).apply(([connectionString, containerName, blobName]) => { let blobService = new azurestorage.BlobService(connectionString); let signature = blobService.generateSharedAccessSignature( containerName, blobName, { AccessPolicy: { Expiry: signatureExpiration, Permissions: azurestorage.BlobUtilities.SharedAccessPermissions.READ, }, } ); return blobService.getUrl(containerName, blobName, signature); }); } } module.exports.AzureStorageAccount = AzureStorageAccount; <file_sep># pulumi-POC Pulumi Code samples <file_sep>"use strict"; // Import the required SDK (Pulumi and Azure) const pulumi = require("@pulumi/pulumi"); const azure = require("@pulumi/azure"); let config = new pulumi.Config(); let numberofVMs = config.require("numberofVMs"); //import the reusable components const resourceGroupComponent = require("./create-resource-group.js"); const virtualMachineComponent = require("./create-vm.js"); const loadBalancerComponent = require("./create-lb.js"); const nsgComponent = require("./nsg.js"); let publicIPs = []; let i; // Create an Azure Resource Group let resourceGroup = new resourceGroupComponent.ResourceGroup("pulumi-rg","EastUS"); // Call Load Balancer componenet to create and use exposed backend pool ID. let azLB = new loadBalancerComponent.LB("pulumi-lb",resourceGroup.resourceGroupName,resourceGroup.location); let backendPoolID = azLB.backendPoolID; // Create Network security group using NetworkSecurityGroup compomenet for HTTP and RDP let nsg = new nsgComponent.NetworkSecurityGroup("pulumi-nsg",resourceGroup.resourceGroupName,resourceGroup.location); // Create a availability set for the VMs to be placed. let avset = new azure.compute.AvailabilitySet("myAVSet", { resourceGroupName:resourceGroup.resourceGroupName, location: resourceGroup.location, platformFaultDomainCount: 2, platformUpdateDomainCount: 2, managed: true, }); // Create Virtual Network let network = new azure.network.VirtualNetwork("pulumiVnet", { resourceGroupName: resourceGroup.resourceGroupName, location: resourceGroup.location, addressSpaces: ["10.0.0.0/16"], // Workaround two issues: // (1) The Azure API recently regressed and now fails when no subnets are defined at Network creation time. // (2) The Azure Terraform provider does not return the ID of the created subnets - so this cannot actually be used. subnets: [{ name: "default", addressPrefix: "10.0.1.0/24", }], }); // Create subnet and associate the Network security group let subnet = new azure.network.Subnet("pulumiSubnet", { resourceGroupName: resourceGroup.resourceGroupName, virtualNetworkName: network.name, addressPrefix: "10.0.2.0/24", //networkSecurityGroupId:nsg.nsgID, subnetNetworkSecurityGroupAssociation: { networkSecurityGroupId:nsg.id } }); // Create public IPs and respective VM. for (i=0;i < numberofVMs; i++) { let publicIP = new azure.network.PublicIp("pulumiIP"+i, { resourceGroupName: resourceGroup.resourceGroupName, location: resourceGroup.location, publicIpAddressAllocation: "Dynamic", }); publicIPs[i] = publicIP.id; // Create virtual machine with public IP and Virtual Network const vm = new virtualMachineComponent.VirtualMachine("pulumi-vm"+i,resourceGroup.resourceGroupName, resourceGroup.location, publicIP,backendPoolID,subnet.id,avset.id,i); }
892c302df7cfd21b2834977ae497a5cf9df50425
[ "JavaScript", "Markdown" ]
4
JavaScript
himsh/pulumi-POC
d7513a10aad69fdfc31a1c97c42bc49038583c12
00636b94549590b03bc75067a27c5ff8fd2646fd
refs/heads/master
<repo_name>trosar/ccalexaEndpoint<file_sep>/index.js module.change_code = 1; 'use strict'; var alexa = require( 'alexa-app' ); var app = new alexa.app( 'test-skill' ); app.launch( function( request, response ) { response.say( 'Welcome to your test skill' ).reprompt( 'Way to go. You got it to run. Bad ass.' ).shouldEndSession( false ); } ); app.error = function( exception, request, response ) { console.log(exception) console.log(request); console.log(response); response.say( 'Sorry an error occured ' + error.message); }; app.intent('DefaultWelcomeIntent', { //"slots":{"number":"NUMBER"} "slots":{"ordernumberslot":"ORDERNUMBER", "zipcodeslot":"ZIPCODE"} ,"utterances":[ "my order number is {ordernumberslot} and zipcode is {zipcodeslot}", "{ordernumberslot}", "{zipcodeslot}", "i'm looking for order details"] }, function(request,response) { var orderNum = request.slot('ordernumberslot'); var zipcode = request.slot('zipcodeslot'); response.say("You asked for the order number "+ orderNum + " and zipcode " + zipcode); } ); module.exports = app;<file_sep>/README.md # ccalexa - base application
0495dd97dfab409546ef691e2af5db857e4065c2
[ "JavaScript", "Markdown" ]
2
JavaScript
trosar/ccalexaEndpoint
a9d52eb5f0ada75cf9efe59158f302a0507059b3
23040025bdc13c6eb0114e8e965dd555bc6c24fe
refs/heads/master
<repo_name>benhawker/todo_challenge<file_sep>/js/toDoListController.js toDoList.controller("toDoListController", [function() { }]);
b508391d91908943745ad12b8fa56edcc472c3eb
[ "JavaScript" ]
1
JavaScript
benhawker/todo_challenge
d41d9d8ae451c94418fe8e841cc937deb5dda840
6c3a44f2cbb51e87b22ca6f8ccba41d1f1abae84
refs/heads/master
<repo_name>547/SWCommonFramework<file_sep>/SWCommonFramework/SWCommonFramework.podspec Pod::Spec.new do |s| s.name = "SWCommonFramework" s.version = "1.0.3" s.summary = "项目常用库" s.homepage = "https://github.com/547/SWCommonFramework" s.license = 'MIT' s.author = { "547" => "<EMAIL>" } s.source = { :git => "https://github.com/547/SWCommonFramework.git", :tag => s.version.to_s } s.requires_arc = true s.source_files = 'SWCommonFramework/SWCommonFramework/**/*.swift' s.dependency 'AFNetworking', '~> 3.1.0' s.dependency 'RxSwift', '~> 4.0' s.dependency 'RxCocoa', '~> 4.0' s.ios.deployment_target = '8.0' end <file_sep>/README.md # SWCommonFramework 常用framework <file_sep>/SWCommonFramework/Products/SWCommonFramework.framework/Headers/Test.swift // // Test.swift // SWCommonFramework // // Created by seven on 2017/12/27. // Copyright © 2017年 seven. All rights reserved. // import Foundation public class Test { public static func test() -> () { print("test") } } <file_sep>/SWCommonFramework/Podfile platform :ios, '8.0' use_frameworks! inhibit_all_warnings! target 'SWCommonFramework' do pod 'AFNetworking', '~> 3.1.0' pod 'RxSwift', '~> 4.0' pod 'RxCocoa', '~> 4.0' end
4d5213471a124f52efce3dae9d24127a796fb0a8
[ "Markdown", "Ruby", "Swift" ]
4
Ruby
547/SWCommonFramework
842996c8bacfdccac381199f4b656163d5bc8d4d
6f58d8ced3b6aff267808a26bb3402ce92f73b42
refs/heads/master
<repo_name>willy12262001/TapRippleAnimationView<file_sep>/README.md # TapRippleAnimationView Make Ripple Effects when you tap UIView. ![Alt text](https://github.com/willy12262001/TapRippleAnimationView/blob/master/animate.gif) ## Installation Just add the following line to your Podfile: ```js pod 'TapRippleAnimationView' ``` ## Usage You can simply use it with storyboard or programming. #### In class way: ```swift import TapRippleAnimationView let effectView = TapRippleAnimationView(frame: rect) effectView.delegate = self view.addSubview(effectView) ``` #### In storyboard way: ![Alt text](https://github.com/willy12262001/TapRippleAnimationView/blob/master/Screenshot.png) ```swift import TapRippleAnimationView @IBOutlet weak var tapView: TapRippleAnimationView! tapView.delegate = self ``` then you can get tap action by **`TapRippleAnimationViewDelegate`**. ```swift protocol TapRippleAnimationViewDelegate: class { func tapRippleAnimationViewAction(_ view: TapRippleAnimationView) } ``` ## License TapRippleAnimationView is available under the MIT license. See the LICENSE file for more info. <file_sep>/TapRippleAnimationView/TapRippleAnimationView.swift // // MyTapView.swift // tapEffect // // Created by <NAME> on 2020/3/18. // Copyright © 2020 <NAME>. All rights reserved. // import UIKit public protocol TapRippleAnimationViewDelegate: class { func tapRippleAnimationViewAction(_ view: TapRippleAnimationView) } open class TapRippleAnimationView: UIView { open weak var delegate: TapRippleAnimationViewDelegate? open var duration = 0.5 open var opacityFromValue = 0.3 open var opacityToValue = 0.0 open var waveSize: CGSize = CGSize.zero override public init(frame: CGRect) { super.init(frame: frame) initParameter() } required public init?(coder: NSCoder) { super.init(coder: coder) initParameter() } private func initParameter() { let waveTap = UITapGestureRecognizer(target: self, action: #selector(tapAction)) waveTap.numberOfTapsRequired = 1 addGestureRecognizer(waveTap) isMultipleTouchEnabled = true self.layer.masksToBounds = true } //MARK: - Tap Action @objc func tapAction(_ sender: UITapGestureRecognizer) { let center = sender.location(in: sender.view) showWave(center: center) delegate?.tapRippleAnimationViewAction(self) } //MARK: - Show Wave private func showWave(center: CGPoint) { let waveView = EffectAnimateView(center: center) waveView.duration = duration waveView.opacityToValue = opacityToValue waveView.opacityFromValue = opacityFromValue if self.waveSize == .zero { if UIDevice.current.userInterfaceIdiom == .pad { self.waveSize = CGSize(width: 800, height: 800) } else { self.waveSize = CGSize(width: 400, height: 400) } } waveView.waveSize = self.waveSize addSubview(waveView) } } <file_sep>/TapRippleAnimationView/EffectAnimateView.swift // // WaveView.swift // tapEffect // // Created by <NAME> on 2020/3/18. // Copyright © 2020 <NAME>. All rights reserved. // import UIKit internal class EffectAnimateView: UIView { var waveSize: CGSize = CGSize(width: 400, height: 400) var duration = 0.5 var opacityFromValue = 0.3 var opacityToValue = 0.0 internal init(center: CGPoint) { super.init(frame: CGRect.zero) let x = center.x - waveSize.width * 0.5 let y = center.y - waveSize.height * 0.5 let width = waveSize.width let height = waveSize.height let frame = CGRect(x: x, y: y, width: width, height: height) self.frame = frame } internal required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func didMoveToSuperview() { let waveLayer = CAShapeLayer() waveLayer.backgroundColor = UIColor.clear.cgColor waveLayer.fillColor = UIColor.white.cgColor self.layer.addSublayer(waveLayer) startAnimate(layer: waveLayer) } private func startAnimate(layer: CAShapeLayer) { let pathCenter = getPathCenter() let animationBeginRadius = getAnimationBeginRadius() let animationEndRadius = getAnimationEndRadius() let beginPath = UIBezierPath(arcCenter: pathCenter, radius: animationBeginRadius, startAngle: 0, endAngle: CGFloat(Double.pi * 2), clockwise: true) let endPath = UIBezierPath(arcCenter: pathCenter, radius: animationEndRadius, startAngle: 0, endAngle: CGFloat(Double.pi * 2), clockwise: true) let rippleAnimation = CABasicAnimation(keyPath: "path") rippleAnimation.delegate = self rippleAnimation.fromValue = beginPath.cgPath rippleAnimation.toValue = endPath.cgPath rippleAnimation.duration = duration let opacityAnimation = CABasicAnimation(keyPath: "opacity") opacityAnimation.delegate = self opacityAnimation.fromValue = opacityFromValue opacityAnimation.toValue = opacityToValue opacityAnimation.duration = duration layer.add(rippleAnimation, forKey: "rippleAnimation") layer.add(opacityAnimation, forKey: "opacityAnimation") } private func getAnimationBeginRadius() -> CGFloat { return waveSize.width * 0.8 * 0.2 } private func getAnimationEndRadius() -> CGFloat { return waveSize.width * 1 } private func getPathCenter() -> CGPoint { let x = waveSize.width * 0.5 let y = waveSize.height * 0.5 return CGPoint(x: x, y: y) } } extension EffectAnimateView: CAAnimationDelegate { func animationDidStop(_ anim: CAAnimation, finished flag: Bool) { if flag { removeFromSuperview() } } }
c1772a39262c2ae357fd5c8e3a8501ccfa7d3764
[ "Markdown", "Swift" ]
3
Markdown
willy12262001/TapRippleAnimationView
43c1a444e98fcf4cec4dd6813320fd73734d825f
53ae5c0d2b8f84b332fa591d4205a263b36a5817
refs/heads/master
<file_sep>int led = 3; // the pin that the LED is attached to int brightness = 0; // how bright the LED is int lastSensor = 0; int sensorStart = 0; int lastBrightness = 0; const long interval = 10; unsigned long previousMillis = 0; void setup() { Serial.begin(9600); pinMode(led, OUTPUT); for(int i = 0; i < 10; i++){ sensorStart = sensorStart + analogRead(A0); delay(10); } sensorStart = sensorStart / 10; sensorStart = sensorStart + 30; } void loop() { Serial.println(lastBrightness); unsigned long currentMillis = millis(); int sensorValue = analogRead(A0); Serial.println(sensorValue); if(sensorValue > (sensorStart + 20)){ brightness = map(sensorValue, sensorStart, 360, 0, 255); analogWrite(led, brightness); lastBrightness = brightness; } else{ if(lastBrightness > 0){ if(currentMillis - previousMillis >= interval) { // save the last time you blinked the LED previousMillis = currentMillis; lastBrightness--; analogWrite(led, lastBrightness); } } else{ analogWrite(led, 0); } } }
f3c445972aab52eace790ab3c4a64448141273ea
[ "C++" ]
1
C++
mrdavidjwatts/IR_Reflectance
83459a574c6428d95d2941460a0f84c210ac7690
644b6185dac896a978c1b806010ebf63656d1a27
refs/heads/master
<repo_name>npmcdn-to-unpkg-bot/react_course<file_sep>/static/js/simple_3d_example.js /** * Created by codgod on 8/30/16. */ // sizes for area var width = 700; var height = 600; var radius_1 = 100; var radius_2 = 80; var radius_3 = 50; var circle_data = [ { x: width/2, y: height - (radius_1), r: 100, color: "#ADD8E6" }, // First biggest circle { x: width/2, y: (height - (radius_1*2+radius_2)), r: 80, color: "#ADD8E6" }, // Middle circle { x: width/2, y: (height-(radius_1*2+radius_2*2+radius_3)), r: 50, color: "#ADD8E6" }, // Circle for head snowman { x: width/2-radius_3/2, y: (height-(radius_1*2+radius_2*2+radius_3)), r: 10, color: "black" }, // eyes for snowman { x: width/2+radius_3/2, y: (height-(radius_1*2+radius_2*2+radius_3)), r: 10, color: "black" } ]; // Create function for creating our snowman function createSnowMan() { var svg = d3.select("body").style("background-color", "black").append("svg") // create new element svg and append to body .attr("width", width) .attr("height", height) .style("background-color", "white"); //'selectAll' method select all element with the same HTML tag name or class name or id name, etc. // (method creates a array like of empty elements if this elements do not exist in the DOM) // and combine all them in array like structure thus that, // for example, each `attr` method will be applied to each of them (see below). svg.selectAll("circle") //'data' - this method takes data structure and bind data with every element in // array like structure. Result call data() is reservation d3 places for data. .data(circle_data) // 'enter' - method returns reserved placed for elements with bound new data. .enter() //Append circle to svg element .append("circle") .attr("cy", function (d) { return d.y; }) // 'd' - is the one object from array like structure .attr("cx", function (d) { return d.x; }) .attr("r", function (d) { return d.r; }) .style("fill", function (d) { return d.color }); // Now we draw nous for our snowman. This will be simples triangle. // This is data for our triangle for snowman nous var triangleData = [ {"x" : width/2, "y" : (height-(radius_1*2+radius_2*2+radius_3) + 5) }, {"x" : width/2 + 30, "y" : (height-(radius_1*2+radius_2*2+radius_3)) + 30 }, {"x": width/2 , "y": (height-(radius_1*2+radius_2*2+radius_3)) + 15 }, {"x" : width/2, "y" : (height-(radius_1*2+radius_2*2+radius_3) + 5) } ]; // 'd3.line()' - method for create triangle. Builds thee point and connects them. var lineFunction = d3.line().x(function(d) { return d.x; }).y(function(d) { return d.y; }); // 'path' - This is specific tag in d3.js, which has parameter 'd' for drawing line. svg.append("path") .attr("d", lineFunction(triangleData)) .attr("stroke", "orange") // line color .attr("stroke-width", 2) .attr("fill", "orange"); // color inside } createSnowMan();
8b5d786f7ce341263d359ee811767cf3fe246f7e
[ "JavaScript" ]
1
JavaScript
npmcdn-to-unpkg-bot/react_course
ecba1fad1cd451b3d4a874688180a01feaa5722e
f260b631d0668059749f75cc7a5b629772278d57
refs/heads/master
<file_sep># eve-simple-route A simple route planner module for the game EVE Online. Reimplementation of https://github.com/fuzzysteve/Eve-Route-Plan ### Installation `npm install eve-simple-route --save` ### Usage ```` var eve_router = require("eve-simple-route"); console.log(eve_router(30000142, 30002187)); // Jita to Amarr // { jumps: 10, route: [object [Array]] } ```` ### Development 1. `npm install` 2. `npm run build` 3. :tada: <file_sep>import data from "./data.json"; function find_path(G, A, B, M=50000){ var P = []; var V = {}; var R = [A]; while (R.length > 0 && M > 0) { M--; var X = R.shift(); for (var Y in G[X]) { Y = G[X][Y]; if(Y == B){ P.push(B); P.push(parseInt(X)); while (V[X] != A) { P.push(parseInt(V[X])); X = V[X]; } P.push(A); return P.reverse(); } if(!(Y in V)){ V[Y] = X; R.push(Y); } } } return P; } module.exports = function(to, from) { var route = []; var jumps = 0; route = find_path(data, to, from); jumps = route.length; return {jumps, route}; };
c63a003dd77a1445293b352fb678cd091f2a47ad
[ "Markdown", "JavaScript" ]
2
Markdown
gsumpster/eve-simple-route
51bde80c59843f9a4497f9c7bac175c497c4b507
23ca11f96d6f65211978454956828d2defa4f7a7
refs/heads/master
<file_sep>function createChat(server){ root.io = io = require('socket.io').listen(server); var guestnumber = 1; var nicknames = {}; var namesUsed = {}; io.sockets.on('connection', function(socket) { guestnumber += 1; socket.on('message', function(message) { io.sockets.emit('sendToAll', message); }); socket.on('nicknameChangeRequest', function(newNickname) { }); }); } exports.createChat = createChat;<file_sep>var http = require('http'); var path = require('path'); var mime = require('mime'); var Router = require('./router.js').Router; var createChat = require('./lib/chat_server.js').createChat; var server = http.createServer(function(req, res){ var router = new Router(req, res); router.route(); }); server.listen(8080); createChat(server); console.log("Server running");<file_sep>var fs = require('fs'); function Router (req, res) { this.req = req; this.res = res; } Router.prototype.route = function(){ var that = this; if (this.req.url == '/') { fs.readFile('./public/index.html', function(err, data){ if(err) { throw err } that.res.writeHead(200, {'Content-Type' : 'text/html'}); that.res.write(data, 'utf8'); that.res.end(); }); } else { fs.readFile(this.req.url.slice(1), function(err, data) { if (err) { that.res.writeHead(404, {'Content-Type' : 'text/html'}); that.res.write("The file you requested does not exist."); that.res.end(); } else { that.res.writeHead(200, {'Content-Type' : 'text/javascript'}); that.res.write(data, 'utf8'); that.res.end(); } }); } } exports.Router = Router;<file_sep>$(document).ready(function(){ (function(root){ var Chat = root.Chat = function() { this.socket = io.connect('http://10.0.1.20:8080'); } Chat.sendMessage = function(message) { socket.emit('message', message); } })(this); })
d1940f2f253bf46259bdaa963c03075573c88827
[ "JavaScript" ]
4
JavaScript
NavyAnt24/node.js_chat_app
0218bdc2e78f09fef78e13450d3e63e4e2a2a212
8873b4eba14d19c159ed067b214f304d17d0d99f
refs/heads/master
<file_sep>require 'test_helper' class SongTest < ActiveSupport::TestCase # test "the truth" do # assert true # end test "not valid without title" do @song = Song.new(title: "", artist: "<NAME>", band_id: 1, active: true) refute(@song.valid?, "Should not be valid without a title") end test "not valid without a band_id" do @song = Song.new(title: "Panama", artist: "<NAME>", active: true) refute(@song.valid?, "Should not be valid without a band_id") end end <file_sep>class UserInviteMailer < ApplicationMailer default from: '<EMAIL>' def invite(email, band, user) @band = band @user = user @token = @band.token mail(to: email, subject: "Invite to Band Management: #{@band.name}") end end <file_sep>class SetListPdf < Prawn::Document def initialize(set_list, set_one, set_two, set_three, set_four) super() @set_list = set_list @set_one = set_one @set_two = set_two @set_three = set_three @set_four = set_four @size = 16 text "#{@set_list.name} #{@set_list.performance_date.strftime("%m/%d/%y")}", size: 14 move_down 20 @cursor_position = cursor if !@set_four.empty? draw_four_set elsif !@set_three.empty? draw_three_set elsif !@set_two.empty? draw_only_two_sets else draw_one_set end end def draw_one_set bounding_box([20, cursor], width: 200) do text "Set One", style: :bold, size: @size move_down 10 @set_one.each do |set_item| text set_item.song.title, size: @size end end end def draw_two_set draw_one_set move_down 20 bounding_box([20, cursor], width: 200) do text "Set Two", style: :bold, size: @size move_down 10 @set_two.each do |set_item| text set_item.song.title, size: @size end end end def draw_three_set draw_two_set new_position_difference = @cursor_position - cursor move_up new_position_difference bounding_box([240, cursor], width: 200) do text "Set Three", style: :bold, size: @size move_down 10 @set_three.each do |set_item| text set_item.song.title, size: @size end end end def draw_four_set draw_three_set move_down 20 bounding_box([240, cursor], width: 200) do text "Set Four", style: :bold, size: 16 move_down 10 @set_four.each do |set_item| text set_item.song.title, size: 16 end end end def draw_only_two_sets draw_one_set new_position_difference = @cursor_position - cursor move_up new_position_difference bounding_box([240, cursor], width: 200) do text "Set Two", style: :bold, size: @size move_down 10 @set_two.each do |set_item| text set_item.song.title, size: @size end end end end <file_sep>module ApplicationHelper def current_band Band.exists?(id: current_user.band_id) ? Band.find(current_user.band_id) : nil end def footer_present? !current_page?(root_path) && !(controller_name == 'sessions') && !(controller_name == 'passwords') && !(controller_name == 'registrations') && !(controller_name == 'confirmations') && !(controller_name == 'bands') end end <file_sep>class SetItem < ApplicationRecord belongs_to :set_list belongs_to :song end <file_sep>class StaticPagesController < ApplicationController def home end def band_registration @plans = Plan.all end end <file_sep>class Gig < ApplicationRecord belongs_to :band has_one :set_list validates :name, presence: true validates :performance_date, presence: true validates :band_id, presence: true scope :upcoming, ->(time, id) {where("performance_date >= ? AND band_id = ?", time, id)} scope :past, ->(time, id) {where("performance_date < ? AND band_id = ?", time, id)} end <file_sep>class BandsController < ApplicationController def new @band = Band.new end def create @band = Band.new(band_params) if @band.save @band.tokenize current_user.update_attributes(band_id: @band.id, is_manager: true) redirect_to band_gig_set_lists_path(@band) else flash.now[:alert] = "Band not created!" render :new end end def show @band = Band.find(params[:id]) end def edit @band = Band.find(params[:id]) end def update @band = Band.find(params[:id]) if @band.update_attributes(band_params) redirect_to band_gig_set_lists_path(@band), notice: "Band Updated Succesfully" else flash.now[:alert] = "Band not updated" render :edit end end def destroy @band = Band.find(params[:id]) @band.prepare_destruction @band.destroy redirect_to root_path, notice: "Your band has been deleted." end def join end def new_member token = params[:token] @band = Band.find_by_token(token) current_user.update_attributes(band_id: @band.id) redirect_to band_gig_set_lists_path(@band) end def invite authorize_band @band = Band.find(current_user.band_id) end def send_invite @band = Band.find(current_user.band_id) if params[:email].blank? flash.now[:alert] = "Email must not be blank" render :invite else email = params[:email] UserInviteMailer.invite(email, @band, current_user).deliver_now redirect_to band_gig_set_lists_path(@band) end end private def band_params params.require(:band).permit(:name, :token) end end <file_sep>class SongsController < ApplicationController before_action :set_band def index authorize_band @active = Song.active(@band.id).order(:title) @inactive = Song.inactive(@band.id).order(:title) end def new authorize_band @song = Song.new end def create authorize_band @song = Song.new(song_params) if @song.save redirect_to band_songs_path, notice: "Song created successfully" else flash.now[:alert] = "Song not created" render :new end end def edit authorize_band @song = Song.find(params[:id]) end def update authorize_band @song = Song.find(params[:id]) if @song.update_attributes(song_params) redirect_to band_songs_path(@band), notice: "Song Updated" else flash.now[:alert] = "Song not updated" render :edit end end private def set_band @band = Band.find(params[:band_id]) end def song_params params.require(:song).permit(:title, :artist, :band_id, :active) end end <file_sep>class DuplicateSetList def initialize(set_list) @set_list = set_list end def call set_items = @set_list.set_items new_set_list = duplicate_set_list duplicate_set_items(new_set_list.id) new_set_list end def duplicate_set_list new_set_list = @set_list.dup new_set_list.name = "<NAME>" new_set_list.performance_date = Date.today new_set_list.save new_set_list end def duplicate_set_items(new_set_list_id) @set_list.set_items.each do |si| new_set_item = si.dup new_set_item.set_list_id = new_set_list_id new_set_item.save end end end <file_sep>class SetListsController < ApplicationController before_action :set_band, except: [:save_sets, :update] def index authorize_band @upcoming = Gig.upcoming(Date.today, @band.id).order('performance_date ASC') @past = Gig.past(Date.today, @band.id).order('performance_date DESC') @band_mates = User.band_mates(@band.id) end def new authorize_band @set_list = SetList.new @gig = Gig.new end def create authorize_band @gig = Gig.new(gig_params) gigid = @set_list = SetList.new([:id]) if @set_list.save redirect_to edit_band_set_list_path(@band, @set_list) else flash.now[:alert] = "Set list not created" render :new end end def show authorize_band @set_list = SetList.find(params[:id]) @set_items = @set_list.set_items @set_1_songs = @set_list.set_items.includes(:song).where(set: 1).order(:order) @set_2_songs = @set_list.set_items.includes(:song).where(set: 2).order(:order) @set_3_songs = @set_list.set_items.includes(:song).where(set: 3).order(:order) @set_4_songs = @set_list.set_items.includes(:song).where(set: 4).order(:order) respond_to do |format| format.pdf do pdf = SetListPdf.new(@set_list, @set_1_songs, @set_2_songs, @set_3_songs, @set_4_songs) send_data pdf.render, filename: "#{@set_list.name} #{@set_list.performance_date.strftime("%m/%d/%y")}.pdf", type: "application/pdf" end end end def edit authorize_band @set_list = SetList.find(params[:id]) @set_1_songs = @set_list.set_items.includes(:song).where(set: 1).order(:order) @set_2_songs = @set_list.set_items.includes(:song).where(set: 2).order(:order) @set_3_songs = @set_list.set_items.includes(:song).where(set: 3).order(:order) @set_4_songs = @set_list.set_items.includes(:song).where(set: 4).order(:order) @songs = RetrieveAvailableSongs.new(@set_list, @band).call end def update @set_list = SetList.find(params[:set_list_id]) @set_list.update_attributes(name: params[:name], performance_date: params[:performance_date]) end def destroy authorize_band @set_list = SetList.find_by_id(params['id']) @set_items = SetItem.where(set_list_id: @set_list.id) @set_list.prepare_destruction(@set_items) @set_list.destroy redirect_to band_gig_set_lists_path(@band), notice: "Set list deleted" end def save_sets @set_list = SetList.find(params[:set_list_id]) @set_list.update_sets(params) end def duplicate @set_list = SetList.find(params[:id]) new_set = DuplicateSetList.new(@set_list).call redirect_to edit_band_set_list_path(@band, new_set) end private def set_band @band = Band.find(params[:band_id]) end def set_list_params params.require(:set_list :gig_id) end def gig_params params.require(:gig).permit(:name, :performance_date, :band_id) end end <file_sep>class RetrieveAvailableSongs def initialize(set_list, band) @set_list = set_list @band = band end def call set_items = @set_list.set_items available_songs = [] songs = [] if set_items.empty? songs = Song.band(@band.id).order(:title) else used_songs = set_items.map { |si| si.song_id } songs = Song.where(active: true).where('id NOT IN (?) AND band_id = ?', used_songs, @band.id).order(:title) end songs end end <file_sep>class ApplicationController < ActionController::Base protect_from_forgery with: :exception before_action :configure_permitted_parameters, if: :devise_controller? #config.active_record.time_zone_aware_types = [:datetime, :time] def after_sign_in_path_for(resource) if current_user.band_id @band = Band.find(current_user.band_id) band_path(@band) else new_band_path end end def current_band current_user.band_id.nil? ? nil : Band.find(current_user.band_id) end def authorize_band band_id = params[:band_id].present? ? params[:band_id] : params[:id] if current_user if !current_user.band_id || current_user.band_id != band_id.to_i redirect_user end else redirect_user end end def redirect_user redirect_to root_path, alert: "You do not have access to that page" end protected def configure_permitted_parameters devise_parameter_sanitizer.permit(:sign_up, keys: [:first_name, :last_name]) end end <file_sep>// This is a manifest file that'll be compiled into application.js, which will include all the files // listed below. // // Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts, // or any plugin's vendor/assets/javascripts directory can be referenced here using a relative path. // // It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the // compiled file. JavaScript code in this file should be added after the last require_* statement. // // Read Sprockets README (https://github.com/rails/sprockets#sprockets-directives) for details // about supported directives. // //= require jquery //= require jquery-ui //= require jquery_ujs //= require jquery //= require turbolinks //= require_tree . $(document).on("turbolinks:load", function(){ var upcomingGigTab = document.getElementById("upcoming-tab"); upcomingGigTab.addEventListener("click", showUpcomingGigs); var pastGigTab = document.getElementById("past-tab"); pastGigTab.addEventListener("click", showPastGigs); }) function showUpcomingGigs() { //make upcoming gigs active tab this.classList.add("active-gig-display"); //de-activate past gigs tab var pastGigsTab = document.getElementById("past-tab"); pastGigsTab.classList.remove("active-gig-display"); //hide past gigs list var pastGigsList = document.getElementById("past"); pastGigsList.classList.add("hidden"); //show upcoming gigs list var upcomingGigsList = document.getElementById("upcoming"); upcomingGigsList.classList.remove("hidden"); } function showPastGigs() { //make past gigs active tab this.classList.add("active-gig-display"); //de-activate upcoming gigs tab var upcomingGigsTab = document.getElementById("upcoming-tab"); upcomingGigsTab.classList.remove("active-gig-display"); //hide upcoming gigs list var upcomingGigsList = document.getElementById("upcoming"); upcomingGigsList.classList.add("hidden"); //show past gigs list var pastGigsList = document.getElementById("past"); pastGigsList.classList.remove("hidden"); } <file_sep>class SetList < ApplicationRecord has_many :set_items, dependent: :destroy belongs_to :gig validates :gig_id, presence: true # scope :upcoming, ->(time, id) {where("performance_date >= ? AND band_id = ?", time, id)} # scope :past, ->(time, id) {where("performance_date < ? AND band_id = ?", time, id)} # Creates an array of Song objects that have not already been used in a set list-style-type # # +set_items: SetItem objects that have already been used in a set_4 # # Returns an array of Song objects that are still available to be used in a set list def available_songs(set_items, band) used_songs = [] songs = [] if set_items.empty? songs = Song.band(band.id) else set_items.each do |set_item| used_songs << set_item.song_id end songs = Song.where('id NOT IN (?) AND band_id = ?',used_songs, band.id).order(:title) end songs end # Updates a set's SetItem records by deleting any and re-building # # +params: a hash representing the data supplied from the web request # # Returns nil def update_sets(params) #set the set_id form the params hash set = determine_set_id(params["set_id"]) set_items = SetItem.where(set: set, set_list_id: id) #if There are already set items for this set in the set list, destroy them if !set_items.empty? prepare_destruction(set_items) end # if the set list is not empty, create new set items for the set if params.key?("song_order") create_set_items(params, set) end end # Assigns an integer set id from the string set_id from the params hash # # +set_id: the string representation of the set id from the params hash # # Returns an integer represetning the set being updated def determine_set_id(set_id) if set_id == "set_1" set = 1 elsif set_id == "set_2" set = 2 elsif set_id == "set_3" set = 3 elsif set_id == "set_4" set = 4 else "" end set end # Create all SetItem records for a set # # +params: a hash representing the data supplied from the web request # # Returns the song_order array from the params hash def create_set_items(params, set) i = 1 params[:song_order].each do |song_id| SetItem.create(order: i, set: set, song_id: song_id, set_list_id: params["set_list_id"].to_i) i += 1 end end # Destroys SetItem records that are associated with a set list # # +set_items: an array of set_items assocated with a set list-style-type # # Returns the array of set_items that were deleted def prepare_destruction(set_items) set_items.each do |set_item| set_item.destroy end end end <file_sep># This file should contain all the record creation needed to seed the database with its default values. # The data can then be loaded with the rails db:seed command (or created alongside the database with db:setup). # # Examples: # # movies = Movie.create([{ name: 'Star Wars' }, { name: 'Lord of the Rings' }]) # Character.create(name: 'Luke', movie: movies.first) Band.create(name: "In Quiet") Band.create(name: "Food Fighters") Song.create(title: "3 am", artist: "Matchbox 20", band_id: 1) Song.create(title: "All Along The Watch Tower", artist: "<NAME>", band_id: 1) Song.create(title: "American Band", artist: "Grand Funk Railroad", band_id: 1) Song.create(title: "Any Way You Want It", artist: "Journey", band_id: 1) Song.create(title: "Basket Case", artist: "Green Day", band_id: 1) Song.create(title: "Black Magic Woman", artist: "<NAME>", band_id: 1) Song.create(title: "Blue on Blank", artist: "<NAME>", band_id: 1) Song.create(title: "Billie Jean", artist: "<NAME>", band_id: 1) Song.create(title: "Born to Be Wild", artist: "Born to Run", band_id: 1) Song.create(title: "Brown Eyed Girl", artist: "Van Morrison", band_id: 1) Song.create(title: "Burring Down the House", artist: "Talking Heads", band_id: 1) Song.create(title: "Come Together", artist: "The Beatles", band_id: 1) Song.create(title: "Crazy Little Thing Called Love", artist: "Queen", band_id: 1) Song.create(title: "Cumbersome", artist: "7 Mary 3", band_id: 1) Song.create(title: "Dani California", artist: "Red Hot Chili Peppers", band_id: 1) Song.create(title: "December", artist: "Collective Soul", band_id: 1) Song.create(title: "Every Rose Has It's Thorn", artist: "Poison", band_id: 1) Song.create(title: "Foreplay/Longtime", artist: "Boston", band_id: 1) Song.create(title: "Funk #49", artist: "<NAME>", band_id: 1) Song.create(title: "Gimmie All Your Lovin", artist: "ZZ Top", band_id: 1) Song.create(title: "Gimme Three Steps", artist: "Lynyrd Skynyrd", band_id: 1) Song.create(title: "Holiday", artist: "Green Day", band_id: 1) Song.create(title: "Honky Tonk Woman", artist: "Rolling Stones", band_id: 1) Song.create(title: "Hot Blooded", artist: "Foreigner", band_id: 1) Song.create(title: "Hows It Going To Be", artist: "Third Eye Blind", band_id: 1) Song.create(title: "Hurts So Good", artist: "<NAME>", band_id: 1) Song.create(title: "I Love Rock and Roll", artist: "<NAME>", band_id: 1) Song.create(title: "If You Want to Get to Heaven", artist: "Ozark Mountain Daredevils", band_id: 1) Song.create(title: "Inside Out", artist: "Eve 6", band_id: 1) Song.create(title: "Jenny", artist: "<NAME>", band_id: 1) Song.create(title: "Just What I Needed", artist: "The Cars", band_id: 1) Song.create(title: "Kryptonite", artist: "3 Doors Down", band_id: 1) Song.create(title: "La Grange", artist: "ZZ Top", band_id: 1) Song.create(title: "Lonely Boy", artist: "Black Keys", band_id: 1) Song.create(title: "<NAME>'s Last Dance", artist: "<NAME>", band_id: 1) Song.create(title: "Never Been Any Reason", artist: "Head East", band_id: 1) Song.create(title: "One Headlight", artist: "The Wallflowers", band_id: 1) Song.create(title: "Pour Some Sugar On Me", artist: "Def Leppard", band_id: 1) Song.create(title: "Pretender", artist: "Foo Fighters", band_id: 1) Song.create(title: "Radar Love", artist: "Golden Earing", band_id: 1) Song.create(title: "Refugee", artist: "<NAME>", band_id: 1) Song.create(title: "Riding the Storm out", artist: "Head East", band_id: 1) Song.create(title: "ROCK in the USA", artist: "<NAME>", band_id: 1) Song.create(title: "Rock This Town", artist: "Stray Cats", band_id: 1) Song.create(title: "Running Down a Dream", artist: "<NAME>", band_id: 1) Song.create(title: "Semi Charmed Life", artist: "Third Eye Blind", band_id: 1) Song.create(title: "Separate Ways", artist: "Journey", band_id: 1) Song.create(title: "Shine", artist: "Collective Soul", band_id: 1) Song.create(title: "Shook Me All Night Long", artist: "ACDC", band_id: 1) Song.create(title: "Small Town", artist: "<NAME>", band_id: 1) Song.create(title: "Some Kind of Wonderful", artist: "Grand Funk Railroad", band_id: 1) Song.create(title: "Sultans of Swing", artist: "Dire Straits", band_id: 1) Song.create(title: "Summer of '69", artist: "<NAME>", band_id: 1) Song.create(title: "Sweet Emotion", artist: "Aerosmith", band_id: 1) Song.create(title: "The Middle", artist: "Jim<NAME>", band_id: 1) Song.create(title: "3 am", artist: "Matchbox 20", band_id: 2) Song.create(title: "All Along The Watch Tower", artist: "<NAME>", band_id: 2) Song.create(title: "American Band", artist: "Grand Funk Railroad", band_id: 2) Song.create(title: "Any Way You Want It", artist: "Journey", band_id: 2) Song.create(title: "Basket Case", artist: "Green Day", band_id: 2) Song.create(title: "Black Magic Woman", artist: "<NAME>", band_id: 2) Song.create(title: "Blue on Blank", artist: "<NAME>", band_id: 2) Song.create(title: "<NAME>", artist: "<NAME>", band_id: 2) Song.create(title: "Born to Be Wild", artist: "Born to Run", band_id: 2) Song.create(title: "Brown Eyed Girl", artist: "<NAME>", band_id: 2) Song.create(title: "Burring Down the House", artist: "Talking Heads", band_id: 2) Song.create(title: "Come Together", artist: "The Beatles", band_id: 2) Song.create(title: "Crazy Little Thing Called Love", artist: "Queen", band_id: 2) Song.create(title: "Cumbersome", artist: "7 Mary 3", band_id: 2) Song.create(title: "D<NAME>", artist: "Red Hot Chili Peppers", band_id: 2) Song.create(title: "December", artist: "Collective Soul", band_id: 2) Song.create(title: "Every Rose Has It's Thorn", artist: "Poison", band_id: 2) Song.create(title: "Foreplay/Longtime", artist: "Boston", band_id: 2) Song.create(title: "Funk #49", artist: "<NAME>", band_id: 2) Song.create(title: "Gimmie All Your Lovin", artist: "ZZ Top", band_id: 2) Song.create(title: "Gimme Three Steps", artist: "Lynyrd Skynyrd", band_id: 2) Song.create(title: "Holiday", artist: "Green Day", band_id: 2) Song.create(title: "Honky Tonk Woman", artist: "Rolling Stones", band_id: 2) Song.create(title: "Hot Blooded", artist: "Foreigner", band_id: 2) Song.create(title: "Hows It Going To Be", artist: "Third Eye Blind", band_id: 2) Song.create(title: "Hurts So Good", artist: "<NAME>", band_id: 2) Song.create(title: "I Love Rock and Roll", artist: "<NAME>", band_id: 2) Song.create(title: "If You Want to Get to Heaven", artist: "Ozark Mountain Daredevils", band_id: 2) Song.create(title: "Inside Out", artist: "Eve 6", band_id: 2) Song.create(title: "Jenny", artist: "<NAME>", band_id: 2) Song.create(title: "Just What I Needed", artist: "The Cars", band_id: 2) Song.create(title: "Kryptonite", artist: "3 Doors Down", band_id: 2) Song.create(title: "La Grange", artist: "ZZ Top", band_id: 2) Song.create(title: "Lonely Boy", artist: "Black Keys", band_id: 2) Song.create(title: "<NAME>'s Last Dance", artist: "<NAME>", band_id: 2) Song.create(title: "Never Been Any Reason", artist: "Head East", band_id: 2) Song.create(title: "One Headlight", artist: "The Wallflowers", band_id: 2) Song.create(title: "Pour Some Sugar On Me", artist: "<NAME>", band_id: 2) Song.create(title: "Pretender", artist: "<NAME>", band_id: 2) Song.create(title: "Radar Love", artist: "Golden Earing", band_id: 2) Song.create(title: "Refugee", artist: "<NAME>", band_id: 2) Song.create(title: "Riding the Storm out", artist: "Head East", band_id: 2) Song.create(title: "ROCK in the USA", artist: "<NAME>", band_id: 2) Song.create(title: "Rock This Town", artist: "Stray Cats", band_id: 2) Song.create(title: "Running Down a Dream", artist: "<NAME>", band_id: 2) Song.create(title: "Semi Charmed Life", artist: "Third Eye Blind", band_id: 2) Song.create(title: "Separate Ways", artist: "Journey", band_id: 2) Song.create(title: "Shine", artist: "Collective Soul", band_id: 2) Song.create(title: "Shook Me All Night Long", artist: "ACDC", band_id: 2) Song.create(title: "Small Town", artist: "John Mellencamp", band_id: 2) Song.create(title: "Some Kind of Wonderful", artist: "Grand Funk Railroad", band_id: 2) Song.create(title: "Sultans of Swing", artist: "Dire Straits", band_id: 2) Song.create(title: "Summer of '69", artist: "Bryan Adams", band_id: 2) Song.create(title: "Sweet Emotion", artist: "Aerosmith", band_id: 2) Song.create(title: "The Middle", artist: "Jimmy Eat World", band_id: 2) User.create(first_name: "jeff", last_name: "laughlin", band_id: 1, email: "<EMAIL>", password: "<PASSWORD>", created_at: DateTime.now, is_manager: true) User.create(first_name: "kyle", last_name: "laughlin", band_id: 2, email: "<EMAIL>", password: "<PASSWORD>", created_at: DateTime.now, is_manager: true) g_1 = Gig.create(name: "Wine on the Vine", venue: "Flapping Wings Vineyard", performance_date: "2017-01-01", performance_time: "19:00:00", meet_location: "jeffs", meet_time: "17:00:00", fee: 900.00, band_id: 1, created_at: DateTime.now) g_2 = Gig.create(name: "<NAME>", venue: "Bobs Tavern", performance_date: "2018-01-01", performance_time: "19:00:00", meet_location: "jeffs", meet_time: "17:00:00", fee: 900.00, band_id: 1, created_at: DateTime.now) g_3 = Gig.create(name: "<NAME>", venue: "The Garage", performance_date: "2018-01-01", performance_time: "19:00:00", meet_location: "jeffs", meet_time: "17:00:00", fee: 900.00, band_id: 1, created_at: DateTime.now) SetList.create(gig: g_1) SetList.create(gig: g_2) SetList.create(gig: g_3) SetItem.create(order: 1, set: 1, song_id: 1, set_list_id: 1, created_at: DateTime.now, updated_at: DateTime.now) SetItem.create(order: 2, set: 1, song_id: 2, set_list_id: 1, created_at: DateTime.now, updated_at: DateTime.now) SetItem.create(order: 3, set: 1, song_id: 3, set_list_id: 1, created_at: DateTime.now, updated_at: DateTime.now) SetItem.create(order: 1, set: 2, song_id: 4, set_list_id: 1, created_at: DateTime.now, updated_at: DateTime.now) SetItem.create(order: 2, set: 2, song_id: 5, set_list_id: 1, created_at: DateTime.now, updated_at: DateTime.now) SetItem.create(order: 3, set: 2, song_id: 6, set_list_id: 1, created_at: DateTime.now, updated_at: DateTime.now) SetItem.create(order: 1, set: 3, song_id: 7, set_list_id: 1, created_at: DateTime.now, updated_at: DateTime.now) SetItem.create(order: 2, set: 3, song_id: 8, set_list_id: 1, created_at: DateTime.now, updated_at: DateTime.now) SetItem.create(order: 3, set: 3, song_id: 9, set_list_id: 1, created_at: DateTime.now, updated_at: DateTime.now) SetItem.create(order: 1, set: 1, song_id: 11, set_list_id: 2, created_at: DateTime.now, updated_at: DateTime.now) SetItem.create(order: 2, set: 1, song_id: 12, set_list_id: 2, created_at: DateTime.now, updated_at: DateTime.now) SetItem.create(order: 3, set: 1, song_id: 13, set_list_id: 2, created_at: DateTime.now, updated_at: DateTime.now) SetItem.create(order: 1, set: 2, song_id: 14, set_list_id: 2, created_at: DateTime.now, updated_at: DateTime.now) SetItem.create(order: 2, set: 2, song_id: 15, set_list_id: 2, created_at: DateTime.now, updated_at: DateTime.now) SetItem.create(order: 3, set: 2, song_id: 16, set_list_id: 2, created_at: DateTime.now, updated_at: DateTime.now) SetItem.create(order: 1, set: 3, song_id: 17, set_list_id: 2, created_at: DateTime.now, updated_at: DateTime.now) SetItem.create(order: 2, set: 3, song_id: 18, set_list_id: 2, created_at: DateTime.now, updated_at: DateTime.now) SetItem.create(order: 3, set: 3, song_id: 19, set_list_id: 2, created_at: DateTime.now, updated_at: DateTime.now) SetItem.create(order: 1, set: 1, song_id: 21, set_list_id: 3, created_at: DateTime.now, updated_at: DateTime.now) SetItem.create(order: 2, set: 1, song_id: 22, set_list_id: 3, created_at: DateTime.now, updated_at: DateTime.now) SetItem.create(order: 3, set: 1, song_id: 23, set_list_id: 3, created_at: DateTime.now, updated_at: DateTime.now) SetItem.create(order: 1, set: 2, song_id: 24, set_list_id: 3, created_at: DateTime.now, updated_at: DateTime.now) SetItem.create(order: 2, set: 2, song_id: 25, set_list_id: 3, created_at: DateTime.now, updated_at: DateTime.now) SetItem.create(order: 3, set: 2, song_id: 26, set_list_id: 3, created_at: DateTime.now, updated_at: DateTime.now) SetItem.create(order: 1, set: 3, song_id: 27, set_list_id: 3, created_at: DateTime.now, updated_at: DateTime.now) SetItem.create(order: 2, set: 3, song_id: 28, set_list_id: 3, created_at: DateTime.now, updated_at: DateTime.now) SetItem.create(order: 3, set: 3, song_id: 29, set_list_id: 3, created_at: DateTime.now, updated_at: DateTime.now) <file_sep>// Place all the behaviors and hooks related to the matching controller here. // All this logic will automatically be available in application.js. function initialize() { //initialize the drag and drop functionality initDragAndDrop(); //Add Event listener to the new set button var addSetButton = document.getElementById("new-set-button"); addSetButton.addEventListener("click", addSet); //Add Event listeners to the remove set buttons var removeSetButtons = document.getElementsByClassName("remove-set-button"); for(var i = 0; i < removeSetButtons.length; i++){ removeSetButtons[i].addEventListener("click", removeSet); }; //Add Event Listener to the date picker var dateInput = document.getElementById("set_list_performance_date"); dateInput.addEventListener("onBlur", sendSaveListRequest); $('#set_list_performance_date').change(function () { sendSaveListRequest(); }); var nameInput = document.getElementById("set_list_name"); nameInput.addEventListener("keyup", sendSaveListRequest); //Add Event Listner to display cancel modal var cancelButton = document.getElementById("cancel-btn"); cancelButton.addEventListener("click", cancelSetList); //Add Event Listener to refute cancel set list var refuteCancel = document.getElementById("refute-cancel"); refuteCancel.addEventListener("click", hideCancelModal); initializeSetsDisplayed() }; function initializeSetsDisplayed() { var setFour = document.getElementById("set-4"); var setThree = document.getElementById("set-3"); var setTwo = document.getElementById("set-2"); if(!(setFour.classList.contains("hidden"))){ var removeButton = document.getElementById("remove-4"); removeButton.classList.remove("hidden"); var newSetButton = document.getElementById("new-set-button"); newSetButton.classList.add("hidden"); setsDisplayed = 4; } else if(!(setThree.classList.contains("hidden"))) { var removeButton = document.getElementById("remove-3"); removeButton.classList.remove("hidden"); setsDisplayed = 3; } else if(!(setTwo.classList.contains("hidden"))) { var removeButton = document.getElementById("remove-2"); removeButton.classList.remove("hidden"); setsDisplayed = 2; }; } //On page load one set is displayed var setsDisplayed = 1 //Facilitate adding a set when button pushed function addSet() { if(setsDisplayed === 1){ addSetTwo(); } else if(setsDisplayed === 2){ addSetThree(); } else if(setsDisplayed === 3){ addSetFour(this); }; setsDisplayed++; }; //Add set two when only one set is displayed function addSetTwo() { //Un hide set two var newSet = document.getElementById("set-2"); newSet.classList.remove("hidden"); //un hide the set two remove set button var removeSetButton = document.getElementById("remove-2"); removeSetButton.classList.remove("hidden"); }; //Add set three when only two sets are displayed function addSetThree() { //Un-hide set three var newSet = document.getElementById("set-3"); newSet.classList.remove("hidden"); //Un-hide the set three remove set button var removeSetButton = document.getElementById("remove-3"); removeSetButton.classList.remove("hidden"); //Hide the set two remove set button var removeSetButton = document.getElementById("remove-2"); removeSetButton.classList.add("hidden"); }; //Add set four when only three sets are displayed function addSetFour(element) { //Un-hide set four var newSet = document.getElementById("set-4"); newSet.classList.remove("hidden"); //Hide the add set list button element.classList.add("hidden"); //Un-hide the set four remove set list button var removeSetButton = document.getElementById("remove-4"); removeSetButton.classList.remove("hidden"); //Hide the set three remove set list button var removeSetButton = document.getElementById("remove-3"); removeSetButton.classList.add("hidden"); }; //Facilitate Removing a set when remove set list button is clicked function removeSet() { if(setsDisplayed === 4){ removeSetFour(); } else if(setsDisplayed === 3){ removeSetThree(); } else if(setsDisplayed === 2){ removeSetTwo(); }; }; //Removes set four from display function removeSetFour() { var removeSetList = document.getElementById("set_4"); //If set list has songs then it can not be removed if(removeSetList.getElementsByTagName("li").length === 0){ //Hide set four var set = document.getElementById("set-4"); set.classList.add("hidden"); //Show set three remove set list button var removeSetButton = document.getElementById("remove-3"); removeSetButton.classList.remove("hidden"); //Show add new set list button var newSetButton = document.getElementById("new-set-button"); newSetButton.classList.remove("hidden"); setsDisplayed--; } else { //Display message that set list must be empty removeSetAlert (); }; }; //Removes set three from display function removeSetThree() { var removeSetList = document.getElementById("set_3"); //If set list has songs then it can not be removed if(removeSetList.getElementsByTagName("li").length === 0){ //Hide set three var set = document.getElementById("set-3"); set.classList.add("hidden"); //Show set two remove set list button var removeSetButton = document.getElementById("remove-2"); removeSetButton.classList.remove("hidden"); setsDisplayed--; } else { //Display message that set list must be empty removeSetAlert (); }; }; //Removes set two from display function removeSetTwo() { var removeSetList = document.getElementById("set_2"); //If set list has songs then it can not be removed if(removeSetList.getElementsByTagName("li").length === 0){ //Hide set two var set = document.getElementById("set-2"); set.classList.add("hidden"); setsDisplayed--; } else { //Display message that set list must be empty removeSetAlert (); }; }; //Displays a message that set list must be empty function removeSetAlert() { alert("The set must be empty to remove it."); }; //Sends post request to save set list function sendSaveListRequest() { var name = document.getElementById("set_list_name").value; var performanceDate = document.getElementById("set_list_performance_date").value; var set_list_id = document.getElementsByClassName('set_list')[0].id; var postData = {set_list_id: set_list_id, name: name, performance_date: performanceDate} $.ajax({ method: 'post', url: '/set_lists/change', data: postData, }); } //Display Modal asking user to confirm cancel of set list function cancelSetList() { //show darkened background var cancelBackground = document.getElementById("cancel-modal-background"); cancelBackground.classList.remove("hidden"); //Show confirmation modal var cancelModal = document.getElementById("cancel-modal"); cancelModal.classList.remove("hidden"); }; function hideCancelModal() { //hide darkened background var cancelBackground = document.getElementById("cancel-modal-background"); cancelBackground.classList.add("hidden"); //hide confirmation modal var cancelModal = document.getElementById("cancel-modal"); cancelModal.classList.add("hidden"); }; function showUpcomingGigs() { //make upcoming gigs active tab this.classList.add("active-gig-display"); //de-activate past gigs tab var pastGigsTab = document.getElementById("past-tab"); pastGigsTab.classList.remove("active-gig-display"); //hide past gigs list var pastGigsList = document.getElementById("past"); pastGigsList.classList.add("hidden"); //show upcoming gigs list var upcomingGigsList = document.getElementById("upcoming"); upcomingGigsList.classList.remove("hidden"); } function showPastGigs() { //make past gigs active tab this.classList.add("active-gig-display"); //de-activate upcoming gigs tab var upcomingGigsTab = document.getElementById("upcoming-tab"); upcomingGigsTab.classList.remove("active-gig-display"); //hide upcoming gigs list var upcomingGigsList = document.getElementById("upcoming"); upcomingGigsList.classList.add("hidden"); //show past gigs list var pastGigsList = document.getElementById("past"); pastGigsList.classList.remove("hidden"); } function initDragAndDrop() { $( ".droptrue" ).sortable({ connectWith: ".droptrue", appendTo: "body", handle: ".handle", helper: function(event,$item){ var $helper = $('<ul></ul>').addClass('drag-style'); return $helper.append($item.clone()); }, update: function(event, ui) { $(this).parent().children("p").addClass("hidden"); if(this.id !== "songs") { var set_id = this.id var songs = [] $(this).children().map(function() { songs.push(this.id); }); var set_list_id = document.getElementsByClassName('set_list')[0].id; var postData = {set_list_id: set_list_id, set_id: set_id, song_order: songs}; $.ajax({ method: 'post', url: '/set_lists/save/sets', data: postData }); } } }); $( "#sortable1, #sortable2, #sortable3" ).disableSelection(); //touchInit(); }; function touchHandler(event) { var touches = event.changedTouches, first = touches[0], type = ""; switch(event.type) { case "touchstart": type = "mousedown"; break; case "touchmove": type="mousemove"; break; case "touchend": type="mouseup"; break; default: return; } // initMouseEvent(type, canBubble, cancelable, view, clickCount, // screenX, screenY, clientX, clientY, ctrlKey, // altKey, shiftKey, metaKey, button, relatedTarget); var simulatedEvent = document.createEvent("MouseEvent"); simulatedEvent.initMouseEvent(type, true, true, window, 1, first.screenX, first.screenY, first.clientX, first.clientY, false, false, false, false, 0/*left*/, null); first.target.dispatchEvent(simulatedEvent); event.preventDefault(); } function touchInit() { document.addEventListener("touchstart", touchHandler, true); document.addEventListener("touchmove", touchHandler, true); document.addEventListener("touchend", touchHandler, true); document.addEventListener("touchcancel", touchHandler, true); } // // function touchPunch() { // /*! // * jQuery UI Touch Punch 0.2.3 // * // * Copyright 2011–2014, <NAME> // * Dual licensed under the MIT or GPL Version 2 licenses. // * // * Depends: // * jquery.ui.widget.js // * jquery.ui.mouse.js // */ // (function ($) { // // // Detect touch support // $.support.touch = 'ontouchend' in document; // // // Ignore browsers without touch support // if (!$.support.touch) { // return; // } // // var mouseProto = $.ui.mouse.prototype, // _mouseInit = mouseProto._mouseInit, // _mouseDestroy = mouseProto._mouseDestroy, // touchHandled; // // /** // * Simulate a mouse event based on a corresponding touch event // * @param {Object} event A touch event // * @param {String} simulatedType The corresponding mouse event // */ // function simulateMouseEvent (event, simulatedType) { // // // Ignore multi-touch events // if (event.originalEvent.touches.length > 1) { // return; // } // // event.preventDefault(); // // var touch = event.originalEvent.changedTouches[0], // simulatedEvent = document.createEvent('MouseEvents'); // // // Initialize the simulated mouse event using the touch event's coordinates // simulatedEvent.initMouseEvent( // simulatedType, // type // true, // bubbles // true, // cancelable // window, // view // 1, // detail // touch.screenX, // screenX // touch.screenY, // screenY // touch.clientX, // clientX // touch.clientY, // clientY // false, // ctrlKey // false, // altKey // false, // shiftKey // false, // metaKey // 0, // button // null // relatedTarget // ); // // // Dispatch the simulated event to the target element // event.target.dispatchEvent(simulatedEvent); // } // // /** // * Handle the jQuery UI widget's touchstart events // * @param {Object} event The widget element's touchstart event // */ // mouseProto._touchStart = function (event) { // // var self = this; // // // Ignore the event if another widget is already being handled // if (touchHandled || !self._mouseCapture(event.originalEvent.changedTouches[0])) { // return; // } // // // Set the flag to prevent other widgets from inheriting the touch event // touchHandled = true; // // // Track movement to determine if interaction was a click // self._touchMoved = false; // // // Simulate the mouseover event // simulateMouseEvent(event, 'mouseover'); // // // Simulate the mousemove event // simulateMouseEvent(event, 'mousemove'); // // // Simulate the mousedown event // simulateMouseEvent(event, 'mousedown'); // }; // // /** // * Handle the jQuery UI widget's touchmove events // * @param {Object} event The document's touchmove event // */ // mouseProto._touchMove = function (event) { // // // Ignore event if not handled // if (!touchHandled) { // return; // } // // // Interaction was not a click // this._touchMoved = true; // // // Simulate the mousemove event // simulateMouseEvent(event, 'mousemove'); // }; // // /** // * Handle the jQuery UI widget's touchend events // * @param {Object} event The document's touchend event // */ // mouseProto._touchEnd = function (event) { // // // Ignore event if not handled // if (!touchHandled) { // return; // } // // // Simulate the mouseup event // simulateMouseEvent(event, 'mouseup'); // // // Simulate the mouseout event // simulateMouseEvent(event, 'mouseout'); // // // If the touch interaction did not move, it should trigger a click // if (!this._touchMoved) { // // // Simulate the click event // simulateMouseEvent(event, 'click'); // } // // // Unset the flag to allow other widgets to inherit the touch event // touchHandled = false; // }; // // /** // * A duck punch of the $.ui.mouse _mouseInit method to support touch events. // * This method extends the widget with bound touch event handlers that // * translate touch events to mouse events and pass them to the widget's // * original mouse event handling methods. // */ // mouseProto._mouseInit = function () { // // var self = this; // // // Delegate the touch handlers to the widget's element // self.element.bind({ // touchstart: $.proxy(self, '_touchStart'), // touchmove: $.proxy(self, '_touchMove'), // touchend: $.proxy(self, '_touchEnd') // }); // // // Call the original $.ui.mouse init method // _mouseInit.call(self); // }; // // /** // * Remove the touch event handlers // */ // mouseProto._mouseDestroy = function () { // // var self = this; // // // Delegate the touch handlers to the widget's element // self.element.unbind({ // touchstart: $.proxy(self, '_touchStart'), // touchmove: $.proxy(self, '_touchMove'), // touchend: $.proxy(self, '_touchEnd') // }); // // // Call the original $.ui.mouse destroy method // _mouseDestroy.call(self); // }; // // })(jQuery); // } <file_sep># Band Management This application is a way for bands, singer songwriters, and other musicians to manage and create set lists in an easy drag and drop format. <file_sep>class Song < ApplicationRecord has_many :set_items belongs_to :band validates :title, presence: true validates :band_id, presence: true scope :active, ->(band_id) {where("active = true AND band_id = ?", band_id)} scope :inactive, ->(band_id) {where("active = false AND band_id = ?", band_id)} scope :band, ->(band_id) {where("band_id = ?", band_id)} end <file_sep>require 'test_helper' class UserTest < ActiveSupport::TestCase # test "the truth" do # assert true # end test "the truth" do assert true end test "valid user under normal circumstances" do @user = User.new(email: "<EMAIL>", password: "<PASSWORD>", password_confirmation: "<PASSWORD>", first_name: "Kyle", last_name: "Laughlin") assert(@user.valid?, "Should be valid under normal circumstances") end test "user password must have be at least six characters long" do @user = User.new(email: "<EMAIL>", password: "<PASSWORD>", password_confirmation: "<PASSWORD>", first_name: "Kyle", last_name: "Laughlin") @user.password = "123" @user.password_confirmation = "123" refute(@user.valid?, "Should be invalid becuase the password shorter than 6 characters") end test "user password and password_confirmation must match" do @user = User.new(email: "<EMAIL>", password: "<PASSWORD>", password_confirmation: "<PASSWORD>", first_name: "Kyle", last_name: "Laughlin") @user.password_confirmation = "<PASSWORD>" refute(@user.valid?, "Should be invalid becuase the password and password_confirmation do not match") end test "email must be unique" do @user = User.new(email: "<EMAIL>", password: "<PASSWORD>", password_confirmation: "<PASSWORD>", first_name: "Kyle", last_name: "Laughlin") @user.save @user_two = User.new(email: "<EMAIL>", password: "<PASSWORD>", password_confirmation: "<PASSWORD>", first_name: "Andrea", last_name: "Dier") refute(@user_two.valid?, "Should be invalid becuase there is already a user with the same email.") end end <file_sep>module NavigationHelper def static_pages? controller_name == 'static_pages' end end <file_sep>class CreateGigs < ActiveRecord::Migration[5.0] def change create_table :gigs do |t| t.string :name t.string :venue t.date :performance_date t.time :performance_time t.string :meet_location t.time :meet_time t.integer :fee t.integer :band_id t.text :notes t.text :links t.timestamps end end end <file_sep>class RegistrationsController < Devise::RegistrationsController before_action :set_band, only: [:edit] before_action :assess_deletability, only: [:destroy] protected def set_band @band = Band.find(current_user.band_id) end def assess_deletability if current_user.is_manager if current_user.band_id flash.now[:alert] = "You must first delete the band you created before you may delete your account." render :edit end end end def after_sign_up_path_for(resource) '/bands/new' end end <file_sep>Rails.application.routes.draw do root to: 'static_pages#home' get 'band_registration', to: 'static_pages#band_registration', as: 'band_registration' get 'join_band', to: 'bands#join', as: 'join_band' post 'join_band', to: 'bands#new_member' get 'bands/:id/invite', to: 'bands#invite', as: "band_invite" post 'bands/:id/invite', to: 'bands#send_invite', as: "invite" devise_for :users, controllers: { registrations: "registrations" } resources :bands do resources :gigs do resources :set_lists end resources :songs end get 'bands/:band_id/set_lists/:id/duplicate', to: 'set_lists#duplicate', as: 'set_list_duplicate' #AJAX end point to update set list items post 'set_lists/save/sets', to: 'set_lists#save_sets' post 'set_lists/change', to: 'set_lists#update' end <file_sep>class Band < ApplicationRecord has_many :gigs, dependent: :destroy has_many :songs, dependent: :destroy validates :name, presence: true def tokenize token = SecureRandom.hex self.token = token self.save end def prepare_destruction @band_mates = User.band_mates(self.id) @band_mates.each do |mate| mate.update_attributes(band_id: nil) end end end
e2f99f369391a447304938ca2de780bcefce2323
[ "JavaScript", "Ruby", "Markdown" ]
25
Ruby
kylelaughlin/band-mngt
2a6c3525ca9a8e64dd8ecab9146b59145312f78c
8cc105c2d0d0756432190b76590c212c9fa224dd
refs/heads/main
<file_sep>import org.openqa.selenium.By; import org.openqa.selenium.JavascriptExecutor; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.interactions.Actions; public class demo7_relatpath { public static void main(String args[]) throws InterruptedException { System.setProperty("webdriver.chrome.driver",System.getProperty("user.dir")+"//Drivers//chromedriver.exe"); WebDriver driver=new ChromeDriver(); driver.manage().window().maximize(); driver.get("https://emicalculator.net/loan-calculator/#"); Thread.sleep(2000); JavascriptExecutor js=(JavascriptExecutor) driver; js.executeScript("window.scrollBy(0,1000)"); } } <file_sep>package pack; import java.net.MalformedURLException; import java.net.URL; import org.openqa.selenium.remote.DesiredCapabilities; import io.appium.java_client.AppiumDriver; import io.appium.java_client.MobileElement; import io.appium.java_client.android.AndroidDriver; public class task2 { public static void main(String[] args) { DesiredCapabilities caps = new DesiredCapabilities(); caps.setCapability("udid", "32003c5bca5656d5"); caps.setCapability("platformName", "Android"); caps.setCapability("platformVersion", "10"); caps.setCapability("app", "C:\\Users\\User\\Downloads\\Hike.apk"); caps.setCapability("noReset", "true"); //Instantiate Appium Driver try { AppiumDriver<MobileElement> driver = new AndroidDriver<MobileElement>(new URL("http://0.0.0.0:4723/wd/hub"), caps); } catch (MalformedURLException e) { System.out.println(e.getMessage()); } } } <file_sep>package pack; import java.net.MalformedURLException; import java.net.URL; import org.openqa.selenium.remote.DesiredCapabilities; import io.appium.java_client.AppiumDriver; import io.appium.java_client.MobileElement; import io.appium.java_client.android.AndroidDriver; public class task3_chrome { static AppiumDriver<MobileElement> driver; public static void main(String[] args) throws InterruptedException { DesiredCapabilities caps = new DesiredCapabilities(); caps.setCapability("udid", "32003c5bca5656d5"); caps.setCapability("platformName", "Android"); caps.setCapability("platformVersion", "10"); caps.setCapability("browserName", "chrome"); caps.setCapability("noReset", "true"); System.setProperty("webdriver.chrome.driver","C:\\Users\\User\\Desktop\\99002471\\selenium\\chromedriver.exe"); //Instantiate Appium Driver try { driver = new AndroidDriver<MobileElement>(new URL("http://0.0.0.0:4723/wd/hub"), caps); } catch (MalformedURLException e) { System.out.println(e.getMessage()); } driver.get("https://www.facebook.com"); Thread.sleep(2000); /*driver.findElement(By.xpath("//*[@id=\"tsf\"]/div[2]/div[1]/div[1]/div/div[2]/input")).sendKeys("Hello"); Thread.sleep(2000); driver.findElement(By.name("btnK")).click(); */ } } <file_sep>package StepDefinations; import java.net.MalformedURLException; import java.net.URL; import java.time.Duration; import org.openqa.selenium.Dimension; import org.openqa.selenium.remote.DesiredCapabilities; import cucumber.api.java.en.Given; import cucumber.api.java.en.Then; import cucumber.api.java.en.When; import io.appium.java_client.AppiumDriver; import io.appium.java_client.MobileElement; import io.appium.java_client.PerformsTouchActions; import io.appium.java_client.TouchAction; import io.appium.java_client.android.AndroidDriver; import io.appium.java_client.touch.WaitOptions; import io.appium.java_client.touch.offset.PointOption; public class defination { static AppiumDriver<MobileElement> driver; int scrollStart, scrollEnd; @Given("^I want to launch scroll bar$") public void i_want_to_launch_scroll_bar() throws Throwable { // Write code here that turns the phrase above into concrete actions DesiredCapabilities caps = new DesiredCapabilities(); // caps.setCapability("deviceName", "My Phone"); caps.setCapability("udid", "32003c5bca5656d5"); //Give Device ID of your mobile phone caps.setCapability("platformName", "Android"); caps.setCapability("platformVersion", "10"); //caps.setCapability("app","C:\\Users\\Mahavir\\Downloads\\com.afwsamples.testdpc_7.0.2-7002_minAPI21(nodpi)_apkmirror.com.apk"); caps.setCapability("app", System.getProperty("user.dir") + "/framework/com.afwsamples.testdpc_7.0.2-7002_minAPI21(nodpi)_apkmirror.com.apk"); caps.setCapability("noReset", "true"); //Instantiate Appium Driver try { driver = new AndroidDriver<MobileElement>(new URL("http://0.0.0.0:4723/wd/hub"), caps); } catch (MalformedURLException e) { System.out.println(e.getMessage()); } } @When("^scroll down$") public void scroll_down() throws Throwable { // Write code here that turns the phrase above into concrete actions Dimension dimensions = driver.manage().window().getSize(); Double screenHeightStart = dimensions.getHeight() * 0.9; scrollStart = screenHeightStart.intValue(); Double screenHeightEnd = dimensions.getHeight() * 0.2; scrollEnd = screenHeightEnd.intValue(); } @Then("^it should scroll down$") public void it_should_scroll_down() throws Throwable { // Write code here that turns the phrase above into concrete actions new TouchAction((PerformsTouchActions) driver).press(PointOption.point(0, scrollStart)) .waitAction(WaitOptions.waitOptions(Duration.ofSeconds(1))).moveTo(PointOption.point(0, scrollEnd)); } } <file_sep>package test; import java.net.MalformedURLException; import java.net.URL; import org.openqa.selenium.By; import org.openqa.selenium.remote.DesiredCapabilities; import org.testng.Assert; import io.appium.java_client.AppiumDriver; import io.appium.java_client.MobileElement; import io.appium.java_client.android.AndroidDriver; public class test_radio { static AppiumDriver<MobileElement> driver; public static void main(String[] args) { DesiredCapabilities caps = new DesiredCapabilities(); caps.setCapability("udid", "32003c5bca5656d5"); caps.setCapability("platformName", "Android"); caps.setCapability("platformVersion", "10"); caps.setCapability("app","C:\\Users\\User\\Downloads\\RADIO BUTTON_v1.0_apkpure.com.apk"); caps.setCapability("noReset", "true"); try { driver = new AndroidDriver<MobileElement>(new URL("http://0.0.0.0:4723/wd/hub"), caps); } catch (MalformedURLException e) { System.out.println(e.getMessage()); } driver.findElement(By.id("com.somewow.radiobutton:id/radio_one")).click(); driver.findElement(By.id("com.somewow.radiobutton:id/button_apply")).click(); String actual = driver.findElement(By.id("com.somewow.radiobutton:id/text_view_selected")).getText(); Assert.assertEquals( actual , "Your choice: 0" ); } } <file_sep>module javangpractice { }<file_sep>package test; import java.net.MalformedURLException; import java.net.URL; import org.openqa.selenium.By; import org.openqa.selenium.remote.DesiredCapabilities; import org.testng.annotations.Test; import io.appium.java_client.AppiumDriver; import io.appium.java_client.MobileElement; import io.appium.java_client.android.AndroidDriver; public class test2 { static AppiumDriver<MobileElement> driver; @Test public void test2() throws InterruptedException { DesiredCapabilities caps = new DesiredCapabilities(); caps.setCapability("udid", "32003c5bca5656d5"); caps.setCapability("platformName", "Android"); caps.setCapability("platformVersion", "10"); caps.setCapability("app","C:\\Users\\User\\Downloads\\Login Registration Example_v3.0_apkpure.com.apk"); caps.setCapability("fullReset", "true"); try { driver = new AndroidDriver<MobileElement>(new URL("http://0.0.0.0:4723/wd/hub"), caps); } catch (MalformedURLException e) { System.out.println(e.getMessage()); } driver.findElement(By.id("com.appsgallery.sagar.loginregistrationexample:id/register")).click(); Thread.sleep(2000); driver.findElement(By.id("com.appsgallery.sagar.loginregistrationexample:id/editTextUserName")).sendKeys("<EMAIL>"); driver.findElement(By.id("com.appsgallery.sagar.loginregistrationexample:id/editTextPassword")).sendKeys("<PASSWORD>"); Thread.sleep(2000); driver.findElement(By.id("com.appsgallery.sagar.loginregistrationexample:id/editTextConfirmPassword")).sendKeys("<PASSWORD>"); Thread.sleep(2000); driver.findElement(By.id("com.appsgallery.sagar.loginregistrationexample:id/buttonCreateAccount")).click(); } } <file_sep>package day2; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeDriver; public class demo5_relxpath { public static void main(String args[]) throws InterruptedException { System.setProperty("webdriver.chrome.driver","C:\\Users\\User\\Desktop\\99002471\\selenium\\chromedriver.exe"); WebDriver driver=new ChromeDriver(); driver.manage().window().maximize(); driver.get("https://sciex.com/support/create-account?step=2"); driver.findElement(By.name("FirstName")).sendKeys("Aditya"); driver.findElement(By.name("LastName")).sendKeys("Mallubhatla"); driver.findElement(By.name("EmailAddress")).sendKeys("<EMAIL>"); driver.findElement(By.name("Company")).sendKeys("LTTS"); driver.findElement(By.name("MarketSegment")).sendKeys("Clinical"); driver.findElement(By.id("password_create")).sendKeys("<PASSWORD>"); driver.findElement(By.name("confirmpassword")).sendKeys("<PASSWORD>"); driver.findElement(By.xpath("//*[@value='Continue']")).click(); Thread.sleep(3000); driver.findElement(By.xpath("//*[text()='Accept Cookies']")).click(); Thread.sleep(3000); //driver.close(); } } <file_sep>package TestRunner; import org.junit.runner.RunWith; import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeDriver; import cucumber.api.CucumberOptions; import cucumber.api.junit.Cucumber; @RunWith(Cucumber.class) @CucumberOptions( features = "src/test/resources/features", glue= {"stepDefination"}, plugin = { "html:target/Report-html"}, monochrome = true ) public class TestRunner { public static void main(String args[]) throws Exception { System.setProperty("webdriver.chrome.driver","C:\\Users\\User\\Desktop\\99002471\\selenium\\chromedriver.exe"); WebDriver driver=new ChromeDriver(); driver.get("https://www.seleniumeasy.com/test/basic-select-dropdown-demo.html"); driver.manage().window().maximize(); } } <file_sep>package day2; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.support.ui.Select; public class demo3_select_tag { public static void main(String args[]) throws Exception { System.setProperty("webdriver.chrome.driver","C:\\Users\\User\\Desktop\\99002471\\selenium\\chromedriver.exe"); WebDriver driver=new ChromeDriver(); driver.get("https://www.seleniumeasy.com/test/basic-select-dropdown-demo.html"); driver.manage().window().maximize(); WebElement dropdown=driver.findElement(By.id("select-demo")); Thread.sleep(1000); Select dd=new Select(dropdown); dd.selectByVisibleText("Monday"); Thread.sleep(1000); dd.selectByIndex(6); Thread.sleep(2000); driver.close(); } } <file_sep>package learnselenium; import org.testng.annotations.Test; public class Sample { @Test(description="FirstMethod",priority=1) public void z() { System.out.println("z in room"); } @Test(description="SecondMethod",priority=0) public void y() { System.out.println("y in room"); } @Test(description="ThirdMethod",priority=2) public void x() { System.out.println("x in room"); } }
00b311792988fa717da8304a2dd39d06f53ee98c
[ "Java" ]
11
Java
Stepin104341/work_files
7c8309924308dc2356f9624551524a248194a367
9f938ea860809d33ccd704b494b682297ef9cf10
refs/heads/master
<file_sep>module.exports = require('./lib/json2memory');<file_sep>/** * Created by wuqingkai on 17/5/23. */ var pomelo = require('pomelo'); var path = require('path'); var fs = require('fs'); var logger = require('pomelo-logger').getLogger("pomelo"); var config = "config/json2memory/config"; var Json2memory = function() { this.jsonFile = {}; var self = this; var jsonDir = require(path.join(pomelo.app.getBase(), config))[pomelo.app.get('env')]; var jsonPaths = path.join(pomelo.app.getBase(), jsonDir); fs.readdirSync(jsonPaths).forEach(function(file) { if (!/.json$/.test(file)) { return; } var jsonPath = path.join(jsonPaths, file); var fileName = path.basename(jsonPath, '.json'); self.jsonFile[fileName] = require(jsonPath); }); }; module.exports = new Json2memory(); var pro = Json2memory.prototype; pro.getData = function(fileName) { return this.jsonFile[fileName]; }; pro.getDataById = function(fileName, id) { return this.jsonFile[fileName][id]; };
f7281555f6fcf594162b93c3e3fff0a565a0d5a8
[ "JavaScript" ]
2
JavaScript
luckyqqk/json2memory
1da28c974510b3b9aeb042c58b6fd0d475d8420f
7f55f3b062d18c3417cfd45448144f632dc07a0e
refs/heads/master
<repo_name>Daiki-Kawanuma/MobileFirstSample<file_sep>/MobileFirstSample/ViewModels/MainPageViewModel.cs using Prism.Commands; using Prism.Mvvm; using Prism.Navigation; using System; using System.Collections.Generic; using System.Linq; using Reactive.Bindings; using System.Diagnostics; using System.Threading.Tasks; using Prism.Services; using Worklight; using Worklight.Push; using Newtonsoft.Json.Linq; namespace MobileFirstSample.ViewModels { public class MainPageViewModel : BindableBase { public ReactiveProperty<bool> IsVisibleIndicator { get; set; } public ReactiveProperty<CommandItem> SelectedItem { get; set; } public List<CommandItem> CommandItemList { get; set; } private readonly INavigationService _navigationService; private readonly IPageDialogService _pageDidalogService; private readonly SampleClient _sampleClient; public MainPageViewModel(INavigationService navigationService, IPageDialogService pageDailogService, IWorklightClient worklightClient, IWorklightPush worklightPush) { _navigationService = navigationService; _pageDidalogService = pageDailogService; _sampleClient = new SampleClient(worklightClient, worklightPush); IsVisibleIndicator = new ReactiveProperty<bool> { Value = false }; SelectedItem = new ReactiveProperty<CommandItem>(); SelectedItem.PropertyChanged += (sender, e) => { if (SelectedItem.Value != null) { //SelectedItem.Value.Command(); } SelectedItem.Value = null; }; CommandItemList = new List<CommandItem> { new CommandItem { CommandName = "Call unprotected adapter", Image = "invoke.png", Command = OnUnprotectedInvoke }, new CommandItem { CommandName = "Call protected adapter", Image = "invoke.png", Command = OnProtectedInvoke }, new CommandItem { CommandName = "Register Device", Image = "subscribe.png", Command = OnRegister }, new CommandItem { CommandName = "Unregister Device", Image = "unsubscribe.png", Command = OnUnregister }, new CommandItem { CommandName = "Subscribe to Push", Image = "subscribe.png", Command = OnSubscribe }, new CommandItem { CommandName = "Unsubscribe from Push", Image = "unsubscribe.png", Command = OnUnSubscribe }, new CommandItem { CommandName = "Get All Subscriptions", Image = "issubscribed.png", Command = OnGetSubscriptions }, new CommandItem { CommandName = "Get All Tags", Image = "issubscribed.png", Command = OnGetTags }, new CommandItem { CommandName = "JSONStore destroy", Image = "logactivity.png", Command = OnDestroyJSONStore }, new CommandItem { CommandName = "Open JSONStore Collection", Image = "logactivity.png", Command = OnJSONStoreOpenCollection }, new CommandItem { CommandName = "Add Data to JSONStore", Image = "logactivity.png", Command = OnAddDataToJSONStore }, new CommandItem { CommandName = "Retrieve all Data", Image = "logactivity.png", Command = OnRetrieveAllDataFromJSONStore }, new CommandItem { CommandName = "Retrieve Filtered Data", Image = "logactivity.png", Command = OnRetrieveFilteredDataFromJSONStore } }; } private async void OnUnprotectedInvoke() { ShowWorking(); var result = await _sampleClient.UnprotectedInvokeAsync(); HandleResult(result, "Unprotected adapter invocation Result", true); } private async void OnProtectedInvoke() { ShowWorking(); var result = await _sampleClient.ProtectedInvokeAsync(); HandleResult(result, "Protected adapter invocation Result", true); } private async void OnRegister() { ShowWorking(); var result = await _sampleClient.RegisterAsync(); HandleResult(result, "Register Device Result", true); } private async void OnUnregister() { ShowWorking(); var result = await _sampleClient.UnregisterAsync(); HandleResult(result, "Unregister Device Result", true); } private async void OnSubscribe() { ShowWorking(); var result = await _sampleClient.SubscribeAsync(); HandleResult(result, "Subscribe Result"); } private async void OnUnSubscribe() { ShowWorking(); var result = await _sampleClient.UnSubscribeAsync(); HandleResult(result, "Unsubcribe Result", true); } private async void OnGetSubscriptions() { ShowWorking(); var result = await _sampleClient.GetSubscriptionsAsync(); HandleResult(result, "Get Subscriptions Result", true); } private async void OnGetTags() { ShowWorking(); var result = await _sampleClient.GetTagsAsync(); HandleResult(result, "Get Tags Result", true); } private void OnIsPushEnabled() { _pageDidalogService.DisplayAlertAsync("Push Status", $"Push {(_sampleClient.IsPushSupported ? "is" : "isn't")} supported", "OK"); } private void OnDestroyJSONStore() { _pageDidalogService.DisplayAlertAsync("Destroy JSONStore Status", $"JSONStore was {(_sampleClient.Client.JSONStoreService.JSONStore.Destroy() ? "successfully" : "not")} destroyed", "OK"); } private void OnJSONStoreOpenCollection() { var collectionList = new List<WorklightJSONStoreCollection>(); var collection = _sampleClient.Client.JSONStoreService.JSONStoreCollection("people"); var searchFieldDict = new Dictionary<string, WorklightJSONStoreSearchFieldType>(); //var searchFied = _sampleClient.Client.JSONStoreService.JSONStore.se; searchFieldDict.Add("name", WorklightJSONStoreSearchFieldType.String); collection.SearchFields = searchFieldDict; searchFieldDict = collection.SearchFields; collectionList.Add(collection); _pageDidalogService.DisplayAlertAsync("JSONStore Open Collection Status", $"JSONStore Person Collection was {(_sampleClient.Client.JSONStoreService.JSONStore.OpenCollections(collectionList) ? "successfully" : "not")} opened", "OK"); } private void OnAddDataToJSONStore() { var data = new JArray(); var val = JObject.Parse(" {\"name\" : \"Chethan\", \"laptop\" : 23.546} "); var val2 = JObject.Parse(" {\"name\" : \"Ajay\", \"laptop\" : [ \"hellow\", 234.23, true] } "); var val3 = JObject.Parse(" {\"name\" : \"Srihari\", \"laptop\" : true} "); data.Add(val); data.Add(val2); data.Add(val3); var collection = _sampleClient.Client.JSONStoreService.JSONStore.GetCollectionByName("people"); if (collection != null) collection.AddData(data); else _pageDidalogService.DisplayAlertAsync("JSONStore addData", "Open JSONstore collection before attempting to add data", "OK"); } private void OnRetrieveAllDataFromJSONStore() { var collection = _sampleClient.Client.JSONStoreService.JSONStore.GetCollectionByName("people"); if (collection != null) { var outArr = collection.FindAllDocuments(); _pageDidalogService.DisplayAlertAsync("All JSONStore Data", $"JSONStore Person data is: {outArr.ToString()}", "OK"); } else _pageDidalogService.DisplayAlertAsync("JSONStore RetrieveData", "Open JSONstore collection before attempting to retrieve data", "OK"); } private void OnRetrieveFilteredDataFromJSONStore() { // JsonObject outArr = App.WorklightClient.client.JSONStoreService.JSONStoreCollection("people").FindDocumentByID(1); var queryParts = new WorklightJSONStoreQueryPart[1]; queryParts[0] = _sampleClient.Client.JSONStoreService.JSONStoreQueryPart(); queryParts[0].AddLike("name", "Chethan"); var collection = _sampleClient.Client.JSONStoreService.JSONStore.GetCollectionByName("people"); if (collection != null) { var outArr = collection.FindDocumentsWithQueryParts(queryParts); _pageDidalogService.DisplayAlertAsync("Filtered JSONStore Data", $"JSONStore Person data is {(outArr != null ? outArr.ToString() : "not available")}", "OK"); } else _pageDidalogService.DisplayAlertAsync("JSONStore RetrieveData", "Open JSONstore collection before attempting to retrieve data", "OK"); } private async void ShowWorking(int timeout = 15) { IsVisibleIndicator.Value = true; await Task.Delay(TimeSpan.FromSeconds(timeout)); if (IsVisibleIndicator.Value == true) { IsVisibleIndicator.Value = false; await _pageDidalogService.DisplayAlertAsync("Timeout", "Call timed out", "OK"); } } private void HandleResult(WorklightResult result, string title, bool ShowOnSuccess = false) { IsVisibleIndicator.Value = false; if (result.Success) { if (ShowOnSuccess) { var navigationParameters = new NavigationParameters { { "title", title }, {"result", result} }; _navigationService.NavigateAsync("ResultPage", navigationParameters); } else { _pageDidalogService.DisplayAlertAsync(title, result.Message, "OK"); } } else { var navigationParameters = new NavigationParameters { { "title", title }, {"result", result} }; _navigationService.NavigateAsync("ResultPage", navigationParameters); } } } } <file_sep>/MobileFirstSample/ViewModels/ResultPageViewModel.cs using Prism.Commands; using Prism.Mvvm; using System; using System.Collections.Generic; using System.Linq; namespace MobileFirstSample.ViewModels { public class ResultPageViewModel : BindableBase { public ResultPageViewModel() { } } } <file_sep>/MobileFirstSample.Droid/MainActivity.cs using System; using Android.App; using Android.Content; using Android.Content.PM; using Android.Runtime; using Android.Views; using Android.Widget; using Android.OS; using Prism.Unity; using Microsoft.Practices.Unity; using Worklight; using Worklight.Xamarin.Android; using Worklight.Push; using Worklight.Xamarin.Android.Push; namespace MobileFirstSample.Droid { [Activity(Label = "MobileFirstSample.Droid", Icon = "@drawable/icon", MainLauncher = true, ConfigurationChanges = ConfigChanges.ScreenSize | ConfigChanges.Orientation)] public class MainActivity : global::Xamarin.Forms.Platform.Android.FormsApplicationActivity { protected override void OnCreate(Bundle bundle) { base.OnCreate(bundle); global::Xamarin.Forms.Forms.Init(this, bundle); LoadApplication(new App(new AndroidInitializer { Activity = this })); } } public class AndroidInitializer : IPlatformInitializer { public Activity Activity { get; set; } public void RegisterTypes(IUnityContainer container) { container.RegisterInstance<IWorklightClient>(WorklightClient.CreateInstance(Activity)); container.RegisterInstance<IWorklightPush>(WorklightPush.Instance); } } } <file_sep>/MobileFirstSample/Models/WorklightResult.cs using System; namespace MobileFirstSample { public struct WorklightResult { public bool Success { get; set; } public string Message { get; set; } public string Response { get; set; } } } <file_sep>/MobileFirstSample/Models/CommandItem.cs using System; namespace MobileFirstSample { public class CommandItem { public string CommandName { get; set; } public string Image { get; set; } public Action Command { get; set; } } } <file_sep>/MobileFirstSample/Models/CustomChallengeHandler.cs using System; using System.Collections.Generic; using System.Diagnostics; using Newtonsoft.Json.Linq; using Worklight; namespace MobileFirstSample { public class CustomChallengeHandler : SecurityCheckChallengeHandler { public LoginFormInfo LoginFormParameters { get; set; } private bool _authSuccess = false; private bool _isAdapterAuth = false; private bool _shouldSubmitLoginForm = false; private bool _shouldSubmitAnswer = false; public JObject ChallengeAnswer = null; public CustomChallengeHandler(string realm) { SecurityCheck = realm; } public override string SecurityCheck{ get; set; } public override JObject GetChallengeAnswer() { return ChallengeAnswer; } public override bool ShouldSubmitChallengeAnswer() { return _shouldSubmitAnswer; } public override void HandleChallenge(object challenge) { Debug.WriteLine("We were challenged.. so we are handling it"); var parms = new Dictionary<String, String>(); var creds = new JObject(); creds.Add("username", "user"); creds.Add("password", "<PASSWORD>"); ChallengeAnswer = creds; _shouldSubmitAnswer = true; } public override void HandleSuccess(JObject identity) { Debug.WriteLine("Success " + identity.ToString()); } public override void HandleFailure(JObject error) { Debug.WriteLine("Failure " + error.ToString()); } } }<file_sep>/MobileFirstSample/Models/SampleClient.cs using System; using System.Diagnostics; using System.Text; using System.Threading.Tasks; using Newtonsoft.Json.Linq; using Worklight; using Worklight.Push; namespace MobileFirstSample { public class SampleClient { #region Fields private string _appRealm = "UserLogin"; #endregion #region Properties public IWorklightClient Client { get; private set; } public IWorklightPush Push { get; private set; } /// <summary> /// Gets a value indicating whether this instance is push supported. /// </summary> /// <value><c>true</c> if this instance is push supported; otherwise, <c>false</c>.</value> public bool IsPushSupported { get { try { return Push.IsPushSupported; } catch { return false; } } } #endregion #region Constuctors public SampleClient(IWorklightClient client, IWorklightPush push) { Client = client; Push = push; SecurityCheckChallengeHandler customChallengeHandler = new CustomChallengeHandler(_appRealm); Client.RegisterChallengeHandler(customChallengeHandler); push.Initialize(); } #endregion #region Async functions public async Task<WorklightResult> UnprotectedInvokeAsync() { var result = new WorklightResult(); try { var uriBuilder = new StringBuilder() .Append("/adapters") .Append("/ResourceAdapter") //Name of the adapter .Append("/publicData"); // Name of the adapter procedure WorklightResourceRequest resourceRequest = Client.ResourceRequest(new Uri(uriBuilder.ToString(), UriKind.Relative), "GET"); WorklightResponse response = await resourceRequest.Send(); result.Success = response.Success; //result.Message = (resp.Success) ? "Connected" : resp.Message; result.Response = response.ResponseText; } catch (Exception exception) { result.Success = false; result.Message = exception.Message; } return result; } public async Task<WorklightResult> ProtectedInvokeAsync() { var result = new WorklightResult(); try { StringBuilder uriBuilder = new StringBuilder() .Append("/adapters") .Append("/ResourceAdapter") //Name of the adapter .Append("/balance"); // Name of the adapter procedure WorklightResourceRequest resourceRequest = Client.ResourceRequest(new Uri(uriBuilder.ToString(), UriKind.Relative), "GET", "accessRestricted"); WorklightResponse response = await resourceRequest.Send(); result.Success = response.Success; //result.Message = (resp.Success) ? "Connected" : resp.Message; result.Response = response.Success ? "Your account balance is " + response.ResponseText : response.Message; } catch (Exception exception) { result.Success = false; result.Message = exception.Message; } return result; } public async Task<WorklightResult> RegisterAsync() { var result = new WorklightResult(); try { MFPPushMessageResponse response = await Push.RegisterDevice(new JObject()); result.Success = response.Success; result.Message = "Registered"; result.Response = (response.ResponseJSON != null) ? response.ResponseJSON.ToString() : ""; } catch (Exception exception) { result.Success = false; result.Message = exception.Message; } return result; } public async Task<WorklightResult> UnregisterAsync() { var result = new WorklightResult(); try { MFPPushMessageResponse response = await Push.UnregisterDevice(); result.Success = response.Success; result.Message = "Unregistered"; result.Response = (response.ResponseJSON != null) ? response.ResponseJSON.ToString() : ""; } catch (Exception exception) { result.Success = false; result.Message = exception.Message; } return result; } public async Task<WorklightResult> SubscribeAsync() { var result = new WorklightResult(); try { MFPPushMessageResponse response = await Push.Subscribe(new string[] { "Xamarin" }); result.Success = response.Success; result.Message = "Subscribed"; result.Response = (response.ResponseJSON != null) ? response.ResponseJSON.ToString() : ""; } catch (Exception exception) { result.Success = false; result.Message = exception.Message; } return result; } public async Task<WorklightResult> UnSubscribeAsync() { var result = new WorklightResult(); try { MFPPushMessageResponse response = await Push.Unsubscribe(new string[] { "Xamarin" }); result.Success = response.Success; result.Message = "Unsubscribed"; result.Response = (response.ResponseJSON != null) ? response.ResponseJSON.ToString() : ""; } catch (Exception exception) { result.Success = false; result.Message = exception.Message; } return result; } public async Task<WorklightResult> GetSubscriptionsAsync() { var result = new WorklightResult(); try { MFPPushMessageResponse response = await Push.GetSubscriptions(); result.Success = response.Success; result.Message = "All Subscriptions"; result.Response = (response.ResponseJSON != null) ? response.ResponseJSON.ToString() : ""; } catch (Exception exception) { result.Success = false; result.Message = exception.Message; } return result; } public async Task<WorklightResult> GetTagsAsync() { var result = new WorklightResult(); try { MFPPushMessageResponse response = await Push.GetTags(); result.Success = response.Success; result.Message = "All tags"; result.Response = (response.ResponseJSON != null) ? response.ResponseJSON.ToString() : ""; } catch (Exception exception) { result.Success = false; result.Message = exception.Message; } return result; } #endregion } }
19c72387cd60a9f81710eb47e5313b68261c2494
[ "C#" ]
7
C#
Daiki-Kawanuma/MobileFirstSample
65a8e46daeea36a84d4655f54fa55afc01f4698a
47792360b856d0c29fbe0174578218105fff2065
refs/heads/main
<file_sep>const path = require('path') const fs = require('fs') const exec = require('child_process').exec; const glob = require('glob') const tempfile = require('tempfile') function exec_evmone(code_file) { return new Promise(resolve => { command = path.normalize("evmone/build/bin/evmone-bench --benchmark_format=json --benchmark_color=false " + code_file + " 00 01") console.log("executing " + command) exec(command, (a, b, sdf) => { resolve(b.includes("iterations") && !b.includes("error_message")) }) }) } glob("tests/*.hex", null, async (err, files) => { let failed = 0 let passed = 0 for (let i = 0; i < files.length; i++) { let result = await exec_evmone(files[i]) if (!result) { failed++ console.log(" failed") } else { passed++ } } console.log("passed: " + passed.toString()) console.log("failed: " + failed.toString()) }) <file_sep>const { gen_calldatacopy, gen_equals, gen_return, gen_mstore, gen_mstore_multi, gen_push, gen_pop } = require('./evm_util.js') const { encode_value, gen_evm384_op, calc_num_limbs, encode_field_params, gen_mulmodmont384, gen_addmod384, gen_submod384, gen_muldmod384} = require("./evm384_util.js") function gen_testcase(operation, expected, x, y, mont_ctx) { let modulus = mont_ctx.mod let modinv = mont_ctx.mod_inv const buffering = 32 //mstoremulti currently only writes in multiples of 32 bytes (TODO fix that) const num_limbs = calc_num_limbs(modulus) const offset_out = 0 const offset_x = offset_out + 8 * num_limbs + buffering const offset_y = offset_x + 8 * num_limbs + buffering const offset_field_params = offset_y + 8 * num_limbs + buffering const offset_expected = offset_field_params + 8 * num_limbs + buffering const offset_equality_check_result = offset_expected + 8 * num_limbs + buffering // TODO validate field params here let ops = [ gen_mstore_multi(offset_expected, encode_value(expected, num_limbs)), gen_mstore_multi(offset_field_params, encode_field_params(modulus, modinv)), gen_mstore_multi(offset_x, encode_value(x, num_limbs)), gen_mstore_multi(offset_y, encode_value(y, num_limbs)), gen_mstore_multi(offset_out, encode_value(0, num_limbs))] let bench_iterations = 1; for (let i = 0; i < bench_iterations; i++) { ops = ops.concat(gen_evm384_op(operation, num_limbs, offset_out, offset_x, offset_y, offset_field_params)) } ops = ops.concat([ gen_equals(offset_equality_check_result, offset_out, offset_expected, num_limbs), gen_return(offset_equality_check_result, 1) ]) return ops.join("") } function gen_from_mont_test(val_norm, mont_ctx) { const val_mont = mont_ctx.to_mont(val_norm) return gen_testcase("mulmodmont384", val_norm, val_mont, 1n, mont_ctx) } function gen_to_mont_test(val_norm, mont_ctx) { const val_mont = mont_ctx.to_mont(val_norm) return gen_testcase("mulmodmont384", val_mont, val_norm, mont_ctx.r_squared, mont_ctx) } module.exports = { gen_testcase, gen_to_mont_test, gen_from_mont_test, } <file_sep># EVM1024 This repository contains a test suite and test runner for a new iteration on EVM384-v7 (see the previous [update](https://notes.ethereum.org/@poemm/evm384-update5)) that I am tentatively calling "EVM1024". EVM1024 differs from EVM384-v7 in the following ways: * The opcodes are called `ADDMOD1024`, `SUBMOD1024`, `MULMODMONT1024`. * The size of packed offsets is reduced to 2 bytes. * The input becomes the first 9 bytes of the stack value parameter and they are interpreted as `<num_limbs / 1byte><offset_result / 2bytes><offset_x / 2bytes><offset_y / 2bytes><offset_modinv/ 2bytes>` where all values are little-endian. * `num_limbs` must be a value between 1 and 16. * The size of values that are operated on now becomes `num_limbs * 8` (64 bit limbs) instead of 48bytes in EVM384-v7 * gas cost is TBD and based on future benchmarking/optimization. Likely it will be a step function with a base cost + a cost that scales quadratically per limb (for mulmmodmont1024) and a cost that scales linearly per limb (for addmod1024/submod1024) ### note on the test suite: Tests (under `tests`) are self-contained evm bytecode which emplace inputs and an expected value in memory, perform an EVM1024 operation (addmod/submod/mulmodmont) and return '01' if the computed result matches what is expected, or '00' if it does not. Translating these tests into proper state tests is tbd. ## Setup ``` > npm install > (git submodule update --init --recursive && \ cd evmone && \ mkdir build && \ cd build && \ cmake -DEVMONE_TESTING=ON .. && \ make) ``` ## Usage Run all tests: `npm run test` Regenerate tests: `npm run build` <file_sep>const { gen_push, uint16_to_be_hex, uint8_to_hex } = require("./evm_util.js") function calc_num_limbs(value) { return Math.ceil(value.toString(16).length / 16) } function reverse_endianness(val) { if (val.length % 2 != 0) { throw("value length must be even") } let parts = [] for (let i = 0; i < val.length; i += 2) { parts.push(val.slice(i, i + 2)) } parts.reverse() return parts.join("") } function encode_offsets(num_limbs, out, x, y, curve_params) { return uint8_to_hex(num_limbs) + uint16_to_be_hex(out) + uint16_to_be_hex(x) + uint16_to_be_hex(y) + uint16_to_be_hex(curve_params) } function encode_field_params(modulus, modinv) { let result = '' let mod_string = modulus.toString(16) let num_limbs = Math.ceil(mod_string.length / 16) if (num_limbs == 0 || num_limbs > 16) { throw("word size must be between 1 and 6 64-bit limbs") } result += encode_value(mod_string, num_limbs) if (typeof(modinv) == "bigint") { let modinv_string = modinv.toString(16) if (modinv_string.length > 16) { throw("modinv is a 64 bit number") } if (modinv_string.length % 2 != 0) { modinv_string = '0' + modinv_string } result += reverse_endianness(modinv_string) } else if (typeof(modinv) != 'undefined') { throw("modinv parameter must be a bigint") } return result } function encode_value(value, num_limbs) { let val_str = value.toString(16) let fill_len = (num_limbs * 16) - val_str.length return reverse_endianness("0".repeat(fill_len) + val_str) } function gen_evm384_op(operation, num_limbs, offset_out, offset_x, offset_y, offset_field_params) { let func = null if (operation == 'addmod384') { func = gen_addmod384 } else if (operation == 'submod384') { func = gen_submod384 } else if (operation == 'mulmodmont384') { func = gen_mulmodmont384 } else { throw("operation must be mulmodmont384, addmod384 or submod384") } return func(num_limbs, offset_out, offset_x, offset_y, offset_field_params) } const EVM384_OPS = { ADDMOD384: "c0", SUBMOD384: "c1", MULMODMONT384: "c2", } function gen_addmod384(num_limbs, offset_out, offset_x, offset_y, offset_mod) { return gen_push(encode_offsets(num_limbs, offset_out, offset_x, offset_y, offset_mod)) + EVM384_OPS.ADDMOD384 } function gen_submod384(num_limbs, offset_out, offset_x, offset_y, offset_mod) { return gen_push(encode_offsets(num_limbs, offset_out, offset_x, offset_y, offset_mod)) + EVM384_OPS.SUBMOD384 } function gen_mulmodmont384(num_limbs, offset_out, offset_x, offset_y, offset_mod) { return gen_push(encode_offsets(num_limbs, offset_out, offset_x, offset_y, offset_mod)) + EVM384_OPS.MULMODMONT384 } module.exports = { EVM384_OPS, encode_value, gen_evm384_op, encode_field_params, reverse_endianness, calc_num_limbs, } <file_sep>const assert = require('assert') function to_padded_hex(value) { if (typeof(value) === "number" || typeof(value) === "bigint") { value = value.toString(16) } else { assert(typeof(value) === "string") } if (value.length % 2 !== 0) { return "0" + value } return value } // convert a uint64 to a padded little endian hex string function uint16_to_be_hex(num) { result = num.toString(16) fill_length = 8 - result.length if (fill_length > 0) { result = "0".repeat(fill_length) + result } return result } function gen_mstore(offset, value) { return gen_push(value) + gen_push(offset) + "52" } function gen_mload() { return "51" } function gen_iszero() { return "15" } function gen_eq() { return "14" } function gen_or() { return "17" } function gen_shl() { return "1b" } function gen_shr() { return "1c" } function gen_jumpdest() { return "5b" } function gen_jumpi() { return "57" } function gen_callvalue() { return "34" } function gen_calldatacopy(offset_dst, offset_src, size) { return gen_push(size) + gen_push(offset_src) + gen_push(offset_dst) + "37" } function gen_return(offset, n_bytes) { return gen_push(n_bytes) + gen_push(offset) + "f3" } function gen_revert() { return "fd"; } function gen_with_immediate(base_op, value) { value = to_padded_hex(value) if (value.length > 64) { throw("push value size must not be larger than 32 bytes") } else if (value.length < 2) { throw("push value size must not be smaller than 1 byte") } return to_padded_hex(base_op + (value.length / 2) - 1) + value } function gen_push(value) { return gen_with_immediate(0x60, value) } function gen_dup(value) { assert(value >= 1 && value <= 16) return to_padded_hex(0x80 + value - 1) } function gen_swap(value) { assert(value >= 1 && value <= 16) return to_padded_hex(0x90 + value - 1) } function reverse_endianness(val) { if (val.length % 2 != 0) { throw("value length must be even") } let parts = [] for (let i = 0; i < val.length; i += 2) { parts.push(val.slice(i, i + 2)) } parts.reverse() return parts.join("") } // generate multiple mstores for arbitrary sized big-endian value function gen_mstore_multi(offset, value) { if (value.length <= 64) { return gen_mstore(offset, value) } const zero_fill_len = 64 - (value.length % 64) let filled_value = value + '0'.repeat(zero_fill_len) let result = [] for (let i = 0; i < filled_value.length / 64; i++) { result.push(gen_mstore(offset + i * 32, filled_value.slice(i * 64, (i + 1) * 64))) } return result.join("") } const constants = { OP_MSTORE8: "53", OP_SHA3: "20" } function gen_pop() { return '50' } function gen_sha3(offset, size) { return gen_push(size) + gen_push(offset) + constants.OP_SHA3 } function uint8_to_hex(val) { let val_str = val.toString(16) if (val_str.length > 2 || val > 255) { throw("invalid num for byte (>255)") } else if (val_str.length == 1) { return '0' + val_str } else { return val_str } } // compare values at memory in offset_val1 and offset_val2. write 1 (byte) to memory at offset_result if equal, 0 if not. function gen_equals(offset_result, offset_val1, offset_val2, num_limbs) { let result = [ gen_sha3(offset_val1, num_limbs * 8), gen_sha3(offset_val2, num_limbs * 8), gen_eq(), gen_push(offset_result), constants.OP_MSTORE8 ] return result.join("") } module.exports = { gen_push: gen_push, gen_pop: gen_pop, gen_dup: gen_dup, gen_swap: gen_swap, uint8_to_hex: uint8_to_hex, uint16_to_be_hex: uint16_to_be_hex, // store single 32 byte word at offset gen_mstore: gen_mstore, gen_mload: gen_mload, gen_iszero: gen_iszero, gen_eq: gen_eq, gen_or: gen_or, gen_shl: gen_shl, gen_shr: gen_shr, gen_jumpdest: gen_jumpdest, gen_jumpi: gen_jumpi, gen_callvalue: gen_callvalue, gen_calldatacopy: gen_calldatacopy, gen_return: gen_return, gen_revert: gen_revert, gen_equals: gen_equals, gen_mstore_multi: gen_mstore_multi, constants: constants, } <file_sep>const fs = require('fs') const path = require('path') const assert = require('assert') const { MontgomeryContext } = require("./mont_context.js") const { gen_from_mont_test, gen_to_mont_test, gen_testcase } = require('./gen_test.js') const test_x = 5n const test_y = 3n function gen_tests(name, modulus) { let mont_ctx = MontgomeryContext(modulus) const test_x_mont = mont_ctx.to_mont(test_x) const test_y_mont = mont_ctx.to_mont(test_y) assert.equal(test_x, mont_ctx.from_mont(test_x_mont)) assert.equal(test_y, mont_ctx.from_mont(test_y_mont)) let result = {} result[name + "-to_mont"] = gen_to_mont_test(test_x, mont_ctx) result[name + "-from_mont"] = gen_from_mont_test(test_y, mont_ctx) result[name + "-addmod384"] = gen_testcase("addmod384", (test_x_mont + test_y_mont) % mont_ctx.mod, test_x_mont, test_y_mont, mont_ctx) // TODO generate submod tests where x > y, y < x, y == x // TODO fix submod tests // result[name + "-submod384"] = gen_testcase("submod384", mont_ctx.submod(test_x_mont, test_y_mont), test_x_mont, test_y_mont, mont_ctx) result[name + "-mulmodmont384"] = gen_testcase("mulmodmont384", mont_ctx.montmul(test_x_mont, test_y_mont), test_x_mont, test_y_mont, mont_ctx) return result } function save_tests(directory, tests) { let entries = Object.entries(tests) for (let i = 0; i < entries.length; i++) { let entry = entries[i] fs.writeFileSync(path.join(path.normalize(directory), entry[0] + ".hex"), entry[1]) } } // pick a valid (odd) modulus for every limb size // test to_mont, from_mont, add/sub/mulmodmont const MAX_NUM_LIMBS = 16 console.log("generating tests") let tests = {} // TODO fix this generation and re-incorporate these tests // TODO check with limb-size = 1 for (let i = 2; i < MAX_NUM_LIMBS; i++) { mod = (1n << 64n * BigInt(i)) - 1n tests = Object.assign(tests, gen_tests("max-mod-"+i.toString(), mod)) } const bn128_curve_order = 21888242871839275222246405745257275088548364400416034343698204186575808495617n tests = Object.assign(tests, gen_tests("bn128_curve_order", bn128_curve_order)) const bls12381_modulus = 0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaaabn tests = Object.assign(tests, gen_tests("bls12381", bls12381_modulus)) save_tests("./tests", tests) console.log("tests saved to disk")
afd884568b1ce46bd4817185b918cdb055632a41
[ "JavaScript", "Markdown" ]
6
JavaScript
jwasinger/evm1024
981ad5b9d0cdcf7978681b3d11527262ad043402
5550ba6244cbf07a3e52407f0e129f5f4109f06c
refs/heads/master
<file_sep>// JavaScript Null Checks // variables to test var myNull = null; var myObject = {}; var myStringEmpty = ""; var myStringWhiteSpace = " "; var myStringHello = "hello"; var myIntZero = 0; var myIntOne = 1; var myBoolTrue = true; var myBoolFalse = false; var myObject = {}; var myUndefined; // string to hold results var outputString = ""; if (myNull == undefined) { outputString += "myNull == undefined" + "<br /><br />"; } if (myNull == null) { outputString += "myNull == null" + "<br /><br />"; } if (myNull === undefined) { outputString += "myNull === undefined" + "<br /><br />"; } if (myNull === null) { outputString += "myNull === null" + "<br /><br />"; } if (myNull != undefined) { outputString += "myNull != undefined" + "<br /><br />"; } if (myNull != null) { outputString += "myNull != null" + "<br /><br />"; } if (myNull !== undefined) { outputString += "myNull !== undefined" + "<br /><br />"; } if (myNull !== null) { outputString += "myNull !== null" + "<br /><br />"; } if (!myNull) { outputString += "!myNull" + "<br /><br />"; } /******************************************************************************** *********************************************************************************/ if (myObject == undefined) { outputString += "myObject == undefined" + "<br /><br />"; } if (myObject == null) { outputString += "myObject == null" + "<br /><br />"; } if (myObject === undefined) { outputString += "myObject === undefined" + "<br /><br />"; } if (myObject === null) { outputString += "myObject === null" + "<br /><br />"; } if (myObject != undefined) { outputString += "myObject != undefined" + "<br /><br />"; } if (myObject != null) { outputString += "myObject != null" + "<br /><br />"; } if (myObject !== undefined) { outputString += "myObject !== undefined" + "<br /><br />"; } if (myObject !== null) { outputString += "myObject !== null" + "<br /><br />"; } if (!myObject) { outputString += "!myObject" + "<br /><br />"; } /******************************************************************************** *********************************************************************************/ if (myStringEmpty == undefined) { outputString += "myStringEmpty == undefined" + "<br /><br />"; } if (myStringEmpty == null) { outputString += "myStringEmpty == null" + "<br /><br />"; } if (myStringEmpty === undefined) { outputString += "myStringEmpty === undefined" + "<br /><br />"; } if (myStringEmpty === null) { outputString += "myStringEmpty === null" + "<br /><br />"; } if (myStringEmpty != undefined) { outputString += "myStringEmpty != undefined" + "<br /><br />"; } if (myStringEmpty != null) { outputString += "myStringEmpty != null" + "<br /><br />"; } if (myStringEmpty !== undefined) { outputString += "myStringEmpty !== undefined" + "<br /><br />"; } if (myStringEmpty !== null) { outputString += "myStringEmpty !== null" + "<br /><br />"; } if (!myStringEmpty) { outputString += "!" + "<br /><br />"; } /******************************************************************************** *********************************************************************************/ if (myStringWhiteSpace == undefined) { outputString += "myStringWhiteSpace == undefined" + "<br /><br />"; } if (myStringWhiteSpace == null) { outputString += "myStringWhiteSpace == null" + "<br /><br />"; } if (myStringWhiteSpace === undefined) { outputString += "myStringWhiteSpace === undefined" + "<br /><br />"; } if (myStringWhiteSpace === null) { outputString += "myStringWhiteSpace === null" + "<br /><br />"; } if (myStringWhiteSpace != undefined) { outputString += "myStringWhiteSpace != undefined" + "<br /><br />"; } if (myStringWhiteSpace != null) { outputString += "myStringWhiteSpace != null" + "<br /><br />"; } if (myStringWhiteSpace !== undefined) { outputString += "myStringWhiteSpace !== undefined" + "<br /><br />"; } if (myStringWhiteSpace !== null) { outputString += "myStringWhiteSpace !== null" + "<br /><br />"; } if (!myStringWhiteSpace) { outputString += "!myStringWhiteSpace" + "<br /><br />"; } /******************************************************************************** *********************************************************************************/ if (myStringHello == undefined) { outputString += "myStringHello == undefined" + "<br /><br />"; } if (myStringHello == null) { outputString += "myStringHello == null" + "<br /><br />"; } if (myStringHello === undefined) { outputString += "myStringHello === undefined" + "<br /><br />"; } if (myStringHello === null) { outputString += "myStringHello === null" + "<br /><br />"; } if (myStringHello != undefined) { outputString += "myStringHello != undefined" + "<br /><br />"; } if (myStringHello != null) { outputString += "myStringHello != null" + "<br /><br />"; } if (myStringHello !== undefined) { outputString += "myStringHello !== undefined" + "<br /><br />"; } if (myStringHello !== null) { outputString += "myStringHello !== null" + "<br /><br />"; } if (!myStringHello) { outputString += "!myStringHello" + "<br /><br />"; } /******************************************************************************** *********************************************************************************/ if (myIntZero == undefined) { outputString += "myIntZero == undefined" + "<br /><br />"; } if (myIntZero == null) { outputString += "myIntZero == null" + "<br /><br />"; } if (myIntZero === undefined) { outputString += "myIntZero === undefined" + "<br /><br />"; } if (myIntZero === null) { outputString += "myIntZero === null" + "<br /><br />"; } if (myIntZero != undefined) { outputString += "myIntZero != undefined" + "<br /><br />"; } if (myIntZero != null) { outputString += "myIntZero != null" + "<br /><br />"; } if (myIntZero !== undefined) { outputString += "myIntZero !== undefined" + "<br /><br />"; } if (myIntZero !== null) { outputString += "myIntZero !== null" + "<br /><br />"; } if (!myIntZero) { outputString += "!myIntZero" + "<br /><br />"; } /******************************************************************************** *********************************************************************************/ if (myIntOne == undefined) { outputString += "myIntOne == undefined" + "<br /><br />"; } if (myIntOne == null) { outputString += "myIntOne == null" + "<br /><br />"; } if (myIntOne === undefined) { outputString += "myIntOne === undefined" + "<br /><br />"; } if (myIntOne === null) { outputString += "myIntOne === null" + "<br /><br />"; } if (myIntOne != undefined) { outputString += "myIntOne != undefined" + "<br /><br />"; } if (myIntOne != null) { outputString += "myIntOne != null" + "<br /><br />"; } if (myIntOne !== undefined) { outputString += "myIntOne !== undefined" + "<br /><br />"; } if (myIntOne !== null) { outputString += "myIntOne !== null" + "<br /><br />"; } if (!myIntOne) { outputString += "!myIntOne" + "<br /><br />"; } /******************************************************************************** *********************************************************************************/ if (myBoolTrue == undefined) { outputString += "myBoolTrue == undefined" + "<br /><br />"; } if (myBoolTrue == null) { outputString += "myBoolTrue == null" + "<br /><br />"; } if (myBoolTrue === undefined) { outputString += "myBoolTrue === undefined" + "<br /><br />"; } if (myBoolTrue === null) { outputString += "myBoolTrue === null" + "<br /><br />"; } if (myBoolTrue != undefined) { outputString += "myBoolTrue != undefined" + "<br /><br />"; } if (myBoolTrue != null) { outputString += "myBoolTrue != null" + "<br /><br />"; } if (myBoolTrue !== undefined) { outputString += "myBoolTrue !== undefined" + "<br /><br />"; } if (myBoolTrue !== null) { outputString += "myBoolTrue !== null" + "<br /><br />"; } if (!myBoolTrue) { outputString += "!myBoolTrue" + "<br /><br />"; } /******************************************************************************** *********************************************************************************/ if (myBoolFalse == undefined) { outputString += "myBoolFalse == undefined" + "<br /><br />"; } if (myBoolFalse == null) { outputString += "myBoolFalse == null" + "<br /><br />"; } if (myBoolFalse === undefined) { outputString += "myBoolFalse === undefined" + "<br /><br />"; } if (myBoolFalse === null) { outputString += "myBoolFalse === null" + "<br /><br />"; } if (myBoolFalse != undefined) { outputString += "myBoolFalse != undefined" + "<br /><br />"; } if (myBoolFalse != null) { outputString += "myBoolFalse != null" + "<br /><br />"; } if (myBoolFalse !== undefined) { outputString += "myBoolFalse !== undefined" + "<br /><br />"; } if (myBoolFalse !== null) { outputString += "myBoolFalse !== null" + "<br /><br />"; } if (!myBoolFalse) { outputString += "!myBoolFalse" + "<br /><br />"; } /******************************************************************************** *********************************************************************************/ if (myUndefined == undefined) { outputString += "myUndefined == undefined" + "<br /><br />"; } if (myUndefined == null) { outputString += "myUndefined == null" + "<br /><br />"; } if (myUndefined === undefined) { outputString += "myUndefined === undefined" + "<br /><br />"; } if (myUndefined === null) { outputString += "myUndefined === null" + "<br /><br />"; } if (myUndefined != undefined) { outputString += "myUndefined != undefined" + "<br /><br />"; } if (myUndefined != null) { outputString += "myUndefined != null" + "<br /><br />"; } if (myUndefined !== undefined) { outputString += "myUndefined !== undefined" + "<br /><br />"; } if (myUndefined !== null) { outputString += "myUndefined !== null" + "<br /><br />"; } if (!myUndefined) { outputString += "!" + "<br /><br />"; } /******************************************************************************** *********************************************************************************/ var output = document.getElementById("output"); output.innerHTML = outputString; <file_sep>-- Source: Azure Support, April 2016 -- Find Missing indexes -- generate commands to create missing indexes SELECT CONVERT (varchar, getdate(), 126) AS runtime, mig.index_group_handle, mid.index_handle, CONVERT (decimal (28,1), migs.avg_total_user_cost * migs.avg_user_impact * (migs.user_seeks + migs.user_scans)) AS improvement_measure, 'CREATE INDEX missing_index_' + CONVERT (varchar, mig.index_group_handle) + '_' + CONVERT (varchar, mid.index_handle) + ' ON ' + mid.statement + ' (' + ISNULL (mid.equality_columns,'') + CASE WHEN mid.equality_columns IS NOT NULL AND mid.inequality_columns IS NOT NULL THEN ',' ELSE '' END + ISNULL (mid.inequality_columns, '') + ')' + ISNULL (' INCLUDE (' + mid.included_columns + ')', '') AS create_index_statement, migs.*, mid.database_id, mid.[object_id] FROM sys.dm_db_missing_index_groups AS mig INNER JOIN sys.dm_db_missing_index_group_stats AS migs ON migs.group_handle = mig.index_group_handle INNER JOIN sys.dm_db_missing_index_details AS mid ON mig.index_handle = mid.index_handle ORDER BY migs.avg_total_user_cost * migs.avg_user_impact * (migs.user_seeks + migs.user_scans) DESC <file_sep>/* There is a table with data like the following: AAA AAA AAA BBB BBB CCC You would like the data to look like this: AAA, 1 AAA, 2 AAA, 3 BBB, 1 BBB, 2 CCC, 1 */ SELECT ColumnName, ROW_NUMBER() OVER (PARTITION BY ColumnName ORDER BY ColumnName) AS RunningCount FROM TableName<file_sep># utils Repository to hold helpful scripts. (note: used this before I used gists) <file_sep> -- get stats for the last hour -- run on instance select * from sys.dm_db_resource_stats -- must run on 'master' select * from sys.resource_stats order by start_time <file_sep>-- Source: Azure Support, April 2016 select * from sys.dm_exec_connections select * from sys.dm_exec_sessions select * from sys.dm_exec_requests select * from sys.dm_exec_query_stats SELECT TOP 20 query_stats.query_hash AS "Query Hash", SUM(query_stats.total_worker_time) / SUM(query_stats.execution_count) AS "Avg CPU Time", MIN(query_stats.statement_text) AS "Statement Text" FROM (SELECT QS.*, SUBSTRING(ST.text, (QS.statement_start_offset/2) + 1, ((CASE statement_end_offset WHEN -1 THEN DATALENGTH(ST.text) ELSE QS.statement_end_offset END - QS.statement_start_offset)/2) + 1) AS statement_text FROM sys.dm_exec_query_stats AS QS CROSS APPLY sys.dm_exec_sql_text(QS.sql_handle) as ST) as query_stats GROUP BY query_stats.query_hash ORDER BY 2 DESC; SELECT highest_cpu_queries.plan_handle, highest_cpu_queries.total_worker_time, q.dbid, q.objectid, q.number, q.encrypted, q.[text] FROM (SELECT TOP 50 qs.plan_handle, qs.total_worker_time FROM sys.dm_exec_query_stats qs ORDER BY qs.total_worker_time desc) AS highest_cpu_queries CROSS APPLY sys.dm_exec_sql_text(plan_handle) AS q ORDER BY highest_cpu_queries.total_worker_time DESC; /* select * from sys.dm_exec_sql_text */ /* select * from dbo.sys.dm_tran_locks */ <file_sep>-- Source: Azure Support, April 2016 -- Find Index Fragmentation Levels, create commands to Update Stats and Rebuild indexes -- Run against database to check the current indexes fragmentation levels. This query will create the commands you need to run to update stats and defrag indexes -- as a rule of thumb, run the ALTER INDEX commands against indexes with fragmentation levels of 30% or more. Do it sporadically, when needed. -- run update statistics more often (now, and at least once a week), and for all the tables/indexes, not just the ones that are over 30% fragmented SELECT DB_NAME() AS DBName ,OBJECT_NAME(ps.object_id) AS TableName ,i.name AS IndexName ,ips.index_type_desc ,ips.avg_fragmentation_in_percent , 'ALTER INDEX [' + i.name + '] ON [' + OBJECT_NAME(ps.object_id) + '] REBUILD' as Rebuild_Commands-- generate the commands to rebuild indexes --,ips.* --,'' spc --,ps.* FROM sys.dm_db_partition_stats ps INNER JOIN sys.indexes i ON ps.object_id = i.object_id AND ps.index_id = i.index_id CROSS APPLY sys.dm_db_index_physical_stats(DB_ID(), ps.object_id, ps.index_id, null, 'LIMITED') ips ORDER BY ips.avg_fragmentation_in_percent DESC
a6efdc5ecfe1d56f64494ab4d6ddb87cdc83c1ee
[ "JavaScript", "SQL", "Markdown" ]
7
JavaScript
aaronhoffman/utils
04f33dfdd84ecf5d46c1e8d9b066dc5fe35f44a3
1ed7e6d661b735d2efd3cdffd340cb4b5cf66e6b
refs/heads/master
<repo_name>brettski/Grack-Mod<file_sep>/minecraft/bcs2/grackmod/GrackSeedsWheat.java package bcs2.grackmod; import net.minecraft.block.Block; import net.minecraft.client.renderer.texture.IconRegister; import net.minecraft.creativetab.CreativeTabs; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.world.World; import net.minecraftforge.common.EnumPlantType; import net.minecraftforge.common.ForgeDirection; import net.minecraftforge.common.IPlantable; public class GrackSeedsWheat extends Item implements IPlantable { public GrackSeedsWheat(int id, int parentId, int soilId) { super(id); setMaxStackSize(64); setCreativeTab(CreativeTabs.tabMaterials); } public void registerIcons(IconRegister ir) { this.itemIcon = ir.registerIcon("grackmod:grack_seeds"); } public boolean onItemUse(ItemStack stack, EntityPlayer player, World world, int x, int y, int z, int par7, float par8, float par9, float par10) { if (par7 != 1) { return false; } else if (player.canPlayerEdit(x, y, z, par7, stack) && player.canPlayerEdit(x, y+1, z, par7, stack)) { int blockid = world.getBlockId(x, y, z); Block soil = Block.blocksList[blockid]; if (soil != null && soil.canSustainPlant(world, x, y, z, ForgeDirection.UP, this) && world.isAirBlock(x, y + 1, z)) { world.setBlock(x, y + 1, z, GrackMod.grackWheatCrop.blockID); --stack.stackSize; return true; } else { return false; } } else { return false; } } @Override public EnumPlantType getPlantType(World world, int x, int y, int z) { return EnumPlantType.Crop; } @Override public int getPlantID(World world, int x, int y, int z) { return GrackMod.grackWheatCrop.blockID; } @Override public int getPlantMetadata(World world, int x, int y, int z) { return 0; } } <file_sep>/minecraft/bcs2/grackmod/RecipesGrack.java package bcs2.grackmod; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import cpw.mods.fml.common.registry.GameRegistry; public class RecipesGrack { public static void getRecipes() { // Shapeless crafting GameRegistry.addShapelessRecipe(new ItemStack(GrackMod.grackDough), new ItemStack(GrackMod.grackWheat), new ItemStack(Item.bucketMilk), new ItemStack(Item.egg)); GameRegistry.addShapelessRecipe(new ItemStack(GrackMod.grackDough), new ItemStack(GrackMod.grackWheat), new ItemStack(Item.bucketWater), new ItemStack(Item.egg)); // crafting GameRegistry.addRecipe(new ItemStack(GrackMod.grackCompressed), "ggg", "ggg", "ggg", 'g', GrackMod.grackDust); GameRegistry.addRecipe(new ItemStack(GrackMod.grackHelmet), "ggg", "g g", 'g', GrackMod.grackIngot); GameRegistry.addRecipe(new ItemStack(GrackMod.grackChestplate), "g g", "ggg", "ggg", 'g', GrackMod.grackIngot); GameRegistry.addRecipe(new ItemStack(GrackMod.grackLeggings), "ggg", "g g", "g g", 'g', GrackMod.grackIngot); GameRegistry.addRecipe(new ItemStack(GrackMod.grackBoots), "g g", "g g", 'g', GrackMod.grackIngot); GameRegistry.addRecipe(new ItemStack(GrackMod.blockGrackBlock), "ggg", "ggg", "ggg", 'g', GrackMod.grackIngot); GameRegistry.addRecipe(new ItemStack(GrackMod.grackSword), " g ", " g ", " s ", 'g', GrackMod.grackIngot, 's', Item.stick); GameRegistry.addRecipe(new ItemStack(GrackMod.grackHoe), "gg ", " s ", " s ", 'g', GrackMod.grackIngot, 's', Item.stick); GameRegistry.addRecipe(new ItemStack(GrackMod.grackAxe), "gg ", "gs ", " s ", 'g', GrackMod.grackIngot, 's', Item.stick); GameRegistry.addRecipe(new ItemStack(GrackMod.grackPickaxe), "ggg", " s ", " s ", 'g', GrackMod.grackIngot, 's', Item.stick); GameRegistry.addRecipe(new ItemStack(GrackMod.grackShovel), " g ", " s ", " s ", 'g', GrackMod.grackIngot, 's', Item.stick); // smelting GameRegistry.addSmelting(GrackMod.grackCompressed.itemID, new ItemStack(GrackMod.grackIngot), 0.2f); GameRegistry.addSmelting(GrackMod.grackDough.itemID, new ItemStack(GrackMod.grackBread), 0.0f); } } <file_sep>/minecraft/bcs2/grackmod/ItemGrackAxe.java package bcs2.grackmod; import net.minecraft.creativetab.CreativeTabs; import net.minecraft.item.EnumToolMaterial; import net.minecraft.item.ItemAxe; public class ItemGrackAxe extends ItemAxe { public ItemGrackAxe(int Id, EnumToolMaterial Material) { super(Id, Material); setTextureName("grackmod:grack_axe"); setCreativeTab(CreativeTabs.tabTools); } } <file_sep>/minecraft/bcs2/grackmod/ItemGrackFood.java package bcs2.grackmod; import net.minecraft.client.renderer.texture.IconRegister; import net.minecraft.creativetab.CreativeTabs; import net.minecraft.item.ItemFood; public class ItemGrackFood extends ItemFood { public ItemGrackFood(int id, int amt, float saturationMod, boolean isWolfsFavoriteMeat) { super(id, amt, saturationMod, isWolfsFavoriteMeat); setCreativeTab(CreativeTabs.tabFood); } public void registerIcons(IconRegister ir) { if (this.itemID == GrackMod.grackDough.itemID) { this.itemIcon = ir.registerIcon("grackmod:grack_dough"); } else if (this.itemID == GrackMod.grackBread.itemID) { this.itemIcon = ir.registerIcon("grackmod:grack_bread"); } } /* public ItemFood setPotionEffect(int a, int b, int c, float d) { super.setPotionEffect(a, b, c, d); return this; } */ } <file_sep>/README.markdown ## Grack Mod *Grack is a Minecraft Forge mod for building items with Grack* This is the source for the Grack mod, not the mod itself. Download information is available under the version information below. #### Version 1.2.0 * Built with [Minecraft Forge](http://www.minecraftforge.net/) - [version 1.6.4(9.11.1.953)](http://files.minecraftforge.net) * Added * ore, dust, compressed, ingot, armor, dough, bread, wheat * File: * MD5: * SHA1: #### Version 1.0.0 * Built with [Minecraft Forge](http://www.minecraftforge.net/) - [version 1.6.4(9.11.1.953)](http://files.minecraftforge.net) <file_sep>/minecraft/bcs2/grackmod/GrackModGenerator.java package bcs2.grackmod; import java.util.Random; import net.minecraft.block.Block; import net.minecraft.world.World; import net.minecraft.world.chunk.IChunkProvider; import net.minecraft.world.gen.feature.WorldGenMinable; import cpw.mods.fml.common.IWorldGenerator; public class GrackModGenerator implements IWorldGenerator { @Override public void generate(Random random, int chunkX, int chunkZ, World world, IChunkProvider chunkGenerator, IChunkProvider chunkProvider) { genBlocks(world, random, chunkX*16, chunkZ*16); } public void genBlocks(World world, Random random, int chunkX, int chunkZ) { addBlock(GrackMod.blockOreGrack, world, random, chunkX, chunkZ, 16, 16, 8, 20, 10, 100); } /** * @param(0) block => The block to add * @param(1) world => The world to create the block in * @param(2) random => A Random object for retrieving random positions within the world to spawn the Block * @param(3) chunkX => X-Coordinate for the Generation method * @param(4) chunkZ => Z-Coordinate for the Generation method * @param(5) xMax => maximum X-Coordinate values for spawning on the X-Axis on a per chunk basis * @param(6) zMax => maximum Z-Coordinate values for spawning on the Z-Axis on a per chunk basis * @param(7) vain => The maximum size of a vein * @param(8) number => The Number of chances available for the Block to spawn per chunk * @param(9) yMin => Minimum Y-Coordinate height at which this block may spawn * @param(10) yMax => Maximum Y-Coordinate height at which this block may spawn */ public void addBlock(Block block, World world, Random random, int chunkX, int chunkZ, int xMax, int zMax, int vain, int number, int yMin, int yMax) { for (int i = 0; i < number; i++) { (new WorldGenMinable(block.blockID, vain)).generate(world, random, chunkX + random.nextInt(16), yMin + random.nextInt(yMax-yMin), chunkZ + random.nextInt(16)); } } } <file_sep>/minecraft/bcs2/grackmod/GrackArmor.java package bcs2.grackmod; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; import net.minecraft.client.renderer.texture.IconRegister; import net.minecraft.creativetab.CreativeTabs; import net.minecraft.entity.Entity; import net.minecraft.item.EnumArmorMaterial; import net.minecraft.item.ItemArmor; import net.minecraft.item.ItemStack; public class GrackArmor extends ItemArmor { int ArmorTypeId = -1; public GrackArmor(int id, EnumArmorMaterial par2EnumArmorMaterial, int par3, int par4) { super(id, par2EnumArmorMaterial, par3, par4); ArmorTypeId = par4; setCreativeTab(CreativeTabs.tabCombat); } @SideOnly(Side.CLIENT) public void registerIcons(IconRegister ir) { switch (ArmorTypeId) { case 0: this.itemIcon = ir.registerIcon("grackmod:grack_helmet"); break; case 1: this.itemIcon = ir.registerIcon("grackmod:grack_chestplate"); break; case 2: this.itemIcon = ir.registerIcon("grackmod:grack_leggings"); break; case 3: this.itemIcon = ir.registerIcon("grackmod:grack_boots"); break; } } public String getArmorTexture(ItemStack stack, Entity entity, int slot, int layer) { if (ArmorTypeId == 2) { return "grackmod:textures/models/armor/grack_armor_2.png"; } return "grackmod:textures/models/armor/grack_armor.png"; } }
e9ba7d768629432b3fa04733f9447b9041e7e81f
[ "Markdown", "Java" ]
7
Java
brettski/Grack-Mod
69d39d6e3460eb3ba0f450ffeeec8c9cd4beb236
b48143082d7f579566768e5988f9ac67741e12dd
refs/heads/master
<repo_name>baujathan/pyplay<file_sep>/script002.py #!/usr/bin/env python import math print math.sqrt(16) print math.pi <file_sep>/script001.py #!/usr/bin/env python ############ #Variables ############ x=10 y=2 ############ #Comment ############ ''' is this a comment ''' print (x+y) if x==10: print "x=10" date="11/12/2013" date_manip=date.split('/') print date_manip print date_manip[0] print date_manip[1] print date_manip[2] print ('Month: ' + date_manip[0]+ '. Day: ' + date_manip[1] + '. Year: ' + date_manip[2]) ############ #condition ############ x=11 print x==1 if (x==10): print ('x=10') else: print ('it would appear x is not ' , str(x)) print x ############ #Loops ############ counter = 0 while counter < 5: print counter counter += 1 for counter in range(0,5): print counter ############ #Lists ############ epic_programmer_list = ["<NAME>", "<NAME>", "<NAME>", "<NAME>", "<NAME>",] print "Epic programmers: " + epic_programmer_list[0] print "Epic programmers: " + epic_programmer_list[1] print "Epic programmers: " + epic_programmer_list[2] print "Epic programmers: " + epic_programmer_list[3] print "Epic programmers: " + epic_programmer_list[4] #epic_programmer_list[4] = "me" #print epic_programmer_list epic_programmer_list.append("Me") print epic_programmer_list[5] for programmer in epic_programmer_list: print "An epic programmer: " + programmer number_list=[1,2,3,4,5] empty_number_list=[] for x in number_list: # print number in number_list to the power of 2 print x**2 # fill empty number list is x^2 empty_number_list.append(x**2) print empty_number_list epic_programmer_dict = {'<NAME>' : '<EMAIL>', '<NAME>' : '<EMAIL>', '<NAME>' : '<EMAIL>', '<NAME>': '<EMAIL>', } print epic_programmer_dict epic_programmer_dict['<NAME>'] = '<EMAIL>' print 'New email for Tim: ' + epic_programmer_dict['<NAME>'] epic_programmer_dict['<NAME>']='<EMAIL>' print epic_programmer_dict del epic_programmer_dict['<NAME>'] print epic_programmer_dict def letsAdd( x, y): addition = x + y someValue=10 return addition print letsAdd(3,5) mustiprint=letsAdd( 3, 5) print mustiprint #print someValue #subract function def subtraction(r,q,l): subtract = r-q-l return subtract print subtraction(10,3,10) def mathme(r,q,l): maths = float(r)/float(q)*float(l) return maths print int(mathme(10.1,2.4,10.78)) print mathme(10.1,2.4,10.78) <file_sep>/script003.py #!/usr/bin/python #Import a single function from a module instead of the whole thing to save compute. from math import sqrt print sqrt(16)
bf91c2aec3a9f5d6fe47f6307b15afc25b18a5d7
[ "Python" ]
3
Python
baujathan/pyplay
3d7ac760838777c004c5412a5bc080ab70b2fc78
a8fbe2171226e887894d1e711ba6c907cc9928e1
refs/heads/main
<repo_name>Teaching-HTL-Leonding/chuck-norris-import-quiz-BastianHaider<file_sep>/ChuckNorrisQuiz/Program.cs using Microsoft.Data.SqlClient; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Design; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Logging; using System; using System.ComponentModel.DataAnnotations; using System.Net.Http; using System.Text.Json; using System.Text.Json.Serialization; var factory = new CookbookContextFactory(); using var dbContext = factory.CreateDbContext(args); HttpClient client = new(); if ("clear".Equals(args[0])) { await dbContext.Database.ExecuteSqlRawAsync("DELETE from Facts"); Console.WriteLine("DB was cleared"); } else { var numOfJokes = Convert.ToInt32(args[0]) >= 1 && Convert.ToInt32(args[0]) <= 10 ? Convert.ToInt32(args[0]) : 5; for (int i = 0; i < numOfJokes; i++) { try { HttpResponseMessage response = await client.GetAsync("https://api.chucknorris.io/jokes/random"); response.EnsureSuccessStatusCode(); string jsonString = await response.Content.ReadAsStringAsync(); var jsonObject = JsonSerializer.Deserialize<Fact>(jsonString); var newJoke = new Fact { ChuckNorrisId = jsonObject.Id.ToString(), Url = jsonObject.Url, Joke = jsonObject.Joke}; using var transaction = await dbContext.Database.BeginTransactionAsync(); try { dbContext.Jokes.Add(newJoke); await dbContext.SaveChangesAsync(); await transaction.CommitAsync(); } catch (SqlException ex) { Console.Error.WriteLine($"Error: {ex.Message}"); } } catch (HttpRequestException e) { Console.WriteLine("\nException Caught!"); Console.WriteLine("Message :{0} ", e.Message); } } Console.WriteLine($"Added {numOfJokes}/{numOfJokes} Jokes to the DB"); } public class Fact { public int Id { get; set; } [JsonPropertyName("id")] [MaxLength(40)] public string ChuckNorrisId { get; set; } [JsonPropertyName("url")] [MaxLength(1024)] public string Url { get; set; } [JsonPropertyName("value")] public string Joke { get; set; } } class CookbookContext : DbContext { public DbSet<Fact> Jokes { get; set; } #pragma warning disable CS8618 // Non-nullable field must contain a non-null value when exiting constructor. Consider declaring as nullable. public CookbookContext(DbContextOptions<CookbookContext> options) #pragma warning restore CS8618 // Non-nullable field must contain a non-null value when exiting constructor. Consider declaring as nullable. : base(options) { } } class CookbookContextFactory : IDesignTimeDbContextFactory<CookbookContext> { public CookbookContext CreateDbContext(string[]? args = null) { var configuration = new ConfigurationBuilder().AddJsonFile("appsettings.json").Build(); var optionsBuilder = new DbContextOptionsBuilder<CookbookContext>(); optionsBuilder // Uncomment the following line if you want to print generated // SQL statements on the console. //.UseLoggerFactory(LoggerFactory.Create(builder => builder.AddConsole())) .UseSqlServer(configuration["ConnectionStrings:DefaultConnection"]); return new CookbookContext(optionsBuilder.Options); } }
e96f817bdbda690fe0f845f060d6bf7621406570
[ "C#" ]
1
C#
Teaching-HTL-Leonding/chuck-norris-import-quiz-BastianHaider
0d41602973dcda4f1310f533b8f478cf72c18b26
272417dfc456b518f2df6353732da6ad631db826
refs/heads/master
<file_sep>class String def to_yuml_me_class "[#{self}]" end def append_char_at_the_beginning_if_not_blank(char) self.blank? ? '' : "#{char}#{self}" end end<file_sep>class Organisation < ActiveRecord::Base end<file_sep>class UserMailer #Code here end<file_sep>class User < ActiveRecord::Base with_options :class_name => "Project", :foreign_key => 'manager_id' do |as_manager| as_manager.has_many :managed_projects, :dependent => :destroy end has_many :friendships, :foreign_key => "from_id", :dependent => :destroy has_many :friends, :through => :friendships, :source => :to, :order => "friendships.created_at DESC" def business_method; end end<file_sep>class ProjectMailer #Code here end<file_sep>require File.dirname(__FILE__) + '/spec_helper' describe "Class diagram generator" do def show_generated_png(diagram) png_file_path = "#{File.dirname(__FILE__)}/class-diagram.png" diagram.to_png(png_file_path, ";dir:TB;scale:180;") File.file?(png_file_path).should be_true `open #{png_file_path}` end describe "Outputting with yuml.me" do before(:each) do @diagram = ClassDiagramGenerator.new.with_classes(User) end it "should save to a png file" do # show_generated_png diagram end it "can add a note" do @diagram.with_note("Hello World").to_yumlme_dsl.should include("[note: Hello World]") end end describe "When making a diagram for a Model class" do it "should generate a class diagram for a given Model, without displaying attributs by default" do diagram = ClassDiagramGenerator.new.with_classes(User) diagram.to_yumlme_dsl.should == "[User]" # show_generated_png diagram end it "should generate a class diagram for a given Model, with attributes " do diagram = ClassDiagramGenerator.new.with_classes(User) diagram.show_attributes.to_yumlme_dsl. should == "[User|first_name;last_name]" # show_generated_png diagram end it "should generate a diagram for a list of Models" do diagram = ClassDiagramGenerator.new.with_classes(User, Project) diagram.to_yumlme_dsl.should == "[User],[Project]" # show_generated_png diagram end it "should generate a diagram for an array of Models" do diagram = ClassDiagramGenerator.new.with_classes([User, Project]) diagram.to_yumlme_dsl.should == "[User],[Project]" # show_generated_png diagram end it "should find all Models using introspection" do diagram = ClassDiagramGenerator.new.show_debugging.with_all_model_classes("spec/app/models/*.rb") # show_generated_png diagram diagram.to_yumlme_dsl. should == "[Base],[Category],[Element],[Friendship],[Organisation],[Project],[ProjectMailer],[User],[UserMailer]" end it "should generate a diagram for Models whose filename follows a pattern" do diagram = ClassDiagramGenerator.new.with_all_model_classes("spec/app/models/*_mailer.rb") diagram.to_yumlme_dsl.should == "[ProjectMailer],[UserMailer]" # show_generated_png diagram end it "should generate a diagram for Models whose filename follows a pattern and excluding some file(s)" do diagram = ClassDiagramGenerator.new.with_all_model_classes("spec/app/models/*_mailer.rb", ["spec/app/models/user_mailer.rb"]) diagram.to_yumlme_dsl.should == "[ProjectMailer]" # show_generated_png diagram end it "should exclude ActiveRecord methods from public business logic methods list" do diagram = ClassDiagramGenerator.new.with_classes(User).show_public_methods # show_generated_png diagram diagram.to_yumlme_dsl. should == "[User|+business_method]" end it "should generate a diagram showing all the ancestors exluding ActiveRecord::Base" do diagram = ClassDiagramGenerator.new.with_classes(Project) diagram.show_inheritance.to_yumlme_dsl. should == "[Base]^-[Project]" end describe "Introspecting associations" do before :each do managed_projects_association = User.reflect_on_association(:managed_projects) @association = ActiveRecord::Metadata::Association.new(User, managed_projects_association) end describe ActiveRecord::Metadata::Association do it "should get informations about association using reflection" do @association.from_class_name.should == "User" @association.type.should == "has_many" @association.name.should == "managed_projects" @association.cardinality.should == "*" @association.to_class_name.should == "Project" end end describe ActiveRecord::Metadata do before :each do @associations_metadata = ActiveRecord::Metadata.new @associations_metadata.add_association @association end it "should add association to the corresponding graph" do @associations_metadata.include_link_for_association?(@association).should be_true end it "should compile a agregated_label_for_association" do @associations_metadata.agregated_label_for_association(@association).should == " managed" end end describe ActiveRecord::Metadata::Graph do before :each do @associations_graph = ActiveRecord::Metadata::Graph.new end it "should return true if there is link btw 2 nodes" do @associations_graph.add_edge "User", "Project" @associations_graph.should have_edge_between("User", "Project") @associations_graph.should_not have_edge_between("Project", "User") end it "should return false if one of the node does not exist" do @associations_graph.should_not have_edge_between("User", "Project") @associations_graph.should_not have_edge_between("Project", "User") end it "should collect association names and append them to a pretty & readable label sorted alphabetically" do @associations_graph.add_edge "User", "Project" @associations_graph.add_edge "User", "Project", "published_projects" @associations_graph.add_edge "User", "Project", "managed_projects" @associations_graph.add_edge "User", "Project", "non_charity_projects" @associations_graph.add_edge "User", "Project", "unpublished_projects" @associations_graph.add_edge "User", "Project", "some_other_stuffs" @associations_graph.label_for_edge("User", "Project"). should == " managed / non charity / published / some other stuffs / unpublished" end end it "should generate a class diagram for a given Model, with associations belong_to " do diagram = ClassDiagramGenerator.new.with_classes(Project, Category).show_associations diagram.to_yumlme_dsl. should == "[Project],[Project]-belongs_to >[Category],[Category],[Category]-has_many >*[Project]" # show_generated_png diagram end it "should generate a class diagram for a given Model, with associations has_many" do diagram = ClassDiagramGenerator.new.with_classes(Project, Element).show_associations # .show_debugging diagram.to_yumlme_dsl. should == "[Project],[Project]-has_many completed / expired / incomplete / money / unexpired >*[Element],[Element],[Element]-belongs_to >[Project]" # show_generated_png diagram end # has_one :child, :class_name => 'Friendship', :foreign_key => 'parent_id', :dependent => :delete # belongs_to :parent, :class_name => 'Friendship' it "should handle has_one association" do diagram = ClassDiagramGenerator.new.with_classes(Friendship).show_associations #.show_debugging diagram.to_yumlme_dsl.should == "[Friendship],[Friendship]-has_one child >1[Friendship],[Friendship]-belongs_to parent >[Friendship]" end it "should handle association has_many :through" do diagram = ClassDiagramGenerator.new.with_classes(User, Friendship).show_associations #.show_debugging diagram.to_yumlme_dsl.should include("[User]-has_through friends >*[User]") end it "should have maxium one association btw 2 models in order to not to make the diagram unreadable with arrows everywhere" do diagram = ClassDiagramGenerator.new.with_classes(User, Organisation, Project, Element).show_associations #.show_debugging diagram.to_yumlme_dsl.should == "[User],[User]-has_many managed >*[Project],[Organisation],[Project],[Project]-has_many completed / expired / incomplete / money / unexpired >*[Element],[Element],[Element]-belongs_to >[Project]" end end end describe "Class with public methods" do it "should generate a diagram for a Model with public methods, sorted alphabetically" do diagram = ClassDiagramGenerator.new.with_classes(ProjectsController) diagram.show_public_methods.to_yumlme_dsl. should == "[ProjectsController|+custom_action]" # show_generated_png diagram end it "should not show public methods of Rails base class" do diagram = ClassDiagramGenerator.new.with_classes(ActionController::Base) diagram.show_public_methods.to_yumlme_dsl. should == "[ActionController::Base]" end end describe "Making a diagram for Controller classes" do it "should get the hierarchy of a Controller without Object" do ProjectsController.hierarchy.should == [ActionController::Base, ApplicationController, ProjectsController] end it "should generate a diagram showing all the ancestors up to ActionController::Base" do diagram = ClassDiagramGenerator.new.with_classes(ProjectsController) diagram.show_inheritance.to_yumlme_dsl. should == "[ActionController::Base]^-[ApplicationController],[ApplicationController]^-[ProjectsController]" end it "should generate a diagram showing all the ancestors up to ActionController::Base and do not dupplicate super classes hierarchy" do diagram = ClassDiagramGenerator.new.with_classes(ProjectsController, UsersController) diagram.show_inheritance.to_yumlme_dsl. should == "[ActionController::Base]^-[ApplicationController],[ApplicationController]^-[ProjectsController],[ApplicationController]^-[UsersController]" end it "should find all controllers using introspection" do diagram = ClassDiagramGenerator.new.with_all_controller_classes("spec/app/controllers/**/*_controller.rb") # show_generated_png diagram diagram.to_yumlme_dsl. should == "[ProjectsController],[UsersController]" end # Process exception # undefined method `hierarchy' for Admin2::AccountingController:Module end end<file_sep># TODO Make it look like more ruby (Dir[File.dirname(__FILE__) + "/core_ext/*"] + Dir[File.dirname(__FILE__) + "/rails_ext/active_record/*"]).each do |path| require path end class ClassDiagramGenerator cattr_accessor :associations_metadata def initialize @style = "nofunky" @note= "" @classes = [] @options = ClassDiagramGenerator::Options.new ClassDiagramGenerator.associations_metadata = ActiveRecord::Metadata.new end # TODO Diagram style ? OPTIONS_LIST = %w[attributes public_methods inheritance associations association_types debugging] OPTIONS_LIST.each do |option| define_method("show_#{option}") do eval "@options.#{option} = true" self end define_method("hide_#{option}") do eval "@options.#{option} = false" self end end class Options OPTIONS_LIST.each do |option| attr_accessor option.to_sym end attr_accessor :classes end def with_note(note) @note = "[note: #{note}]" self end # Classes & introspection def with_classes (*klasses) @classes << klasses @classes = @classes.flatten self end def with_all_model_classes(pattern="app/models/**/*.rb", except_files=[]) files = Dir.glob(pattern) - except_files # files += Dir.glob("vendor/plugins/**/app/models/*.rb") if @options.plugins_models files.each do |file| model_name = File.basename(file, '.rb').camelize next if /_related/i =~ model_name @classes << get_model_class(model_name) end self end def get_model_class(model_name) begin model_name.constantize rescue LoadError STDERR.print "\t#{model_name} raised LoadError.\n" oldlen = model_path.length model_path.gsub!(/.*[\/\\]/, '') model_name = model_path.camelize if oldlen > model_path.length retry end STDERR.print "\tDone trying to remove slashes, skipping this model.\n" rescue NameError STDERR.print "\t#{model_name} raised NameError, skipping this model.\n" end end private :get_model_class def with_all_controller_classes(pattern="app/controllers/**/*_controller.rb", except_files=[]) begin files = Dir.glob(pattern) - except_files files.each { |file| @classes << get_controller_class(file) } rescue LoadError raise end self end def get_controller_class(file) model = file.sub(/^.*app\/controllers\//, '').sub(/\.rb$/, '').camelize parts = model.split('::') begin parts.inject(Object) {|klass, part| klass.const_get(part) } rescue LoadError Object.const_get(parts.last) end end private :get_controller_class # TODO Is it possible to move the generation code in another class? def to_yumlme_dsl # FIXME tmp FIX for modules # @classes -= [ActsAsRateable, AuthenticatedBase, Geocodeable, HasStatus, XmasProjectMethods] @options.classes = @classes # puts @classes if @options.debugging @yumlme_dsl = @note + @classes.map do |klass| unless @options.inheritance klass.to_yumlme_dsl(@options) else create_yuml_dsl_for_class_hierarchy(klass) end end.flatten.uniq.join(",") end def create_yuml_dsl_for_class_hierarchy(klass) hierarchy = klass.hierarchy hierarchy.delete(ActiveRecord::Base) # FIXME write a test for this line return klass.to_yumlme_dsl(@options) if hierarchy.size == 1 # TODO Make it look like ruby dsl = [] last_item_index = hierarchy.size - 1 hierarchy.each_with_index do |klass, index| if index < last_item_index super_class_dsl = klass.to_yumlme_dsl(@options) child_class_dsl = hierarchy[index+1].to_yumlme_dsl(@options) dsl << "#{super_class_dsl}^-#{child_class_dsl}" end end dsl end private :create_yuml_dsl_for_class_hierarchy def to_png(file, diagram_options="") output(file, "", diagram_options) end # http://yuml.me/diagram/class/[Customer]+->[Order].pdf def to_pdf(file, diagram_options="") self.output(file, ".pdf", diagram_options) end # def to_url( options, data, type ) #:nodoc: # opts = options.clone # diagram = opts.delete(:diagram) # if type.nil? # type = "" # else # type = ".#{type}" if type[0].chr != "." # end # "http://yuml.me/diagram/#{self.options_string(opts)}#{diagram}/#{data}#{type}" # end private def output(file, type="", diagram_options="") # http://yuml.me/diagram/nofunky;dir:TB;scale:120;/class/ # http://yuml.me/diagram/nofunky;dir:TB;scale:180;/class/ data = self.to_yumlme_dsl uri = "/diagram/#{@style}#{diagram_options}/class/#{data}#{type}" puts "*** #{uri}" if @options.debugging writer = STDOUT writer = open(file, "wb") unless file.nil? res = Net::HTTP.start("yuml.me", 80) {|http| http.get(URI.escape(uri)) } writer.write(res.body) writer.close end end<file_sep>class ActiveRecord::Base class << self def to_yumlme_dsl(options) @@options = options public_methods = if options.public_methods business_methods_separated_by_semi_column else "" end "#{self.name}#{attributes_separated_by_semi_column}#{public_methods}".to_yuml_me_class + associations_to_yumlme_dsl end private def attributes_separated_by_semi_column return "" unless @@options.attributes "|#{self.content_columns.map(&:name).join(';')}" end def business_methods_separated_by_semi_column business_logic_methods = self.public_instance_methods(false). reject{|m| m.start_with?("validate_associated_records_for_") || m.ends_with?("_ids") || m.include?("=") || m.starts_with?("create_") || m.starts_with?("build_") || m.starts_with?("autosave_associated_records_for_") || m.starts_with?("has_many_dependent_destroy_for_") || %w(to_param to_s to_xml tz).include?(m) } # Remove associations getter & setters association_names = self.reflect_on_all_associations.map{|a| a.name.to_s } business_logic_methods = business_logic_methods. reject{|m| association_names.include?(m) || association_names.include?("#{m}=")} "|" + business_logic_methods.sort.map{|m| "+#{m}"}.join(';') end def associations_to_yumlme_dsl return "" unless @@options.associations associations_list = [] self.reflect_on_all_associations.map do |association_reflection| association = ActiveRecord::Metadata::Association.new(self, association_reflection) next unless is_included_in_diagram_classes?(association.to_class_name) next if is_connected_to_a_class_not_included_in_diagram_through?(association.active_record_association_reflection) puts "#{association.from_class_name} - #{association.name} > #{association.to_class_name}" if @@options.debugging unless ClassDiagramGenerator.associations_metadata.include_link_for_association?(association) puts "adding association btw #{association.from_class_name} and #{association.to_class_name}\n\n" if @@options.debugging associations_list << association end ClassDiagramGenerator.associations_metadata.add_association association puts "Adding edge #{association.from_class_name} #{association.type} -> #{association.to_class_name}" if @@options.debugging end associations_list.map(&:yuml_me_label).join(",").append_char_at_the_beginning_if_not_blank(',') # puts "DSL for class #{self.name} = #{associations_dsl}\n\n" if @@options.debugging end def is_included_in_diagram_classes?(association_class_name) @@options.classes.map(&:name).include?(association_class_name) end def is_connected_to_a_class_not_included_in_diagram_through?(association) association.source_reflection && association.source_reflection.active_record && !is_included_in_diagram_classes?(association.source_reflection.active_record.class_name) end end end<file_sep>class Project < Base belongs_to :category has_many :money_elements, :class_name => "Element", :conditions => "1 = 1" has_many :incomplete_elements, :class_name => "Element", :conditions => "1 = 1" has_many :unexpired_elements, :class_name => "Element", :conditions => "1 = 1" has_many :completed_elements, :class_name => "Element", :conditions => "1 = 1" has_many :expired_elements, :class_name => "Element", :conditions => "1 = 1" end<file_sep>class Class def hierarchy (superclass && superclass != Object ? superclass.hierarchy : []) << self end def to_yumlme_dsl(options) return class_name_to_yuml_me unless options.public_methods return class_name_to_yuml_me if is_a_rails_base_class? "#{self.name}#{public_methods_separated_by_semi_column}".to_yuml_me_class end def class_name_to_yuml_me "#{self.name}".to_yuml_me_class end def public_methods_separated_by_semi_column # If the optional parameter is not <code>false</code>, the methods of # any ancestors are included. "|" + self.public_instance_methods(false).sort.map{|m| "+#{m}"}.join(';') end def is_a_rails_base_class? self == ActiveRecord::Base || self == ActionController::Base end end<file_sep>require 'rubygems' require 'spec' require 'sqlite3' require 'active_record' require 'action_controller' ActiveRecord::Base.establish_connection :adapter => 'sqlite3', :database => ':memory:' ActiveRecord::Migration.verbose = false ActiveRecord::Schema.define do create_table :projects, :force => true do |t| t.column :name, :string end create_table :users, :force => true do |t| t.column :first_name, :string t.column :last_name, :string end end require File.dirname(__FILE__) + '/../lib/class_diagram_generator' Dir[File.dirname(__FILE__) + "/app/models/*"].each do |path| Object.autoload(File.basename(path, ".rb").classify.to_sym, path) end class ApplicationController < ActionController::Base end Dir[File.dirname(__FILE__) + "/app/controllers/*"].each do |path| Object.autoload(File.basename(path, ".rb").classify.to_sym, path) end<file_sep>module ActiveRecord class Metadata ASSOCIATION_TYPES = %w[belongs_to has_one has_many has_through] def initialize @association_graphs = {} ASSOCIATION_TYPES.each { |type| @association_graphs[type] = Graph.new } end def add_association(diagram_association) @association_graphs[diagram_association.type]. add_edge(diagram_association.from_class_name, diagram_association.to_class_name, diagram_association.name) end def include_link_for_association?(diagram_association) @association_graphs[diagram_association.type]. has_edge_between?(diagram_association.from_class_name, diagram_association.to_class_name) end def agregated_label_for_association(diagram_association) @association_graphs[diagram_association.type]. label_for_edge(diagram_association.from_class_name, diagram_association.to_class_name) end class Association def initialize(from_class, active_record_association_reflection) @active_record_association_reflection = active_record_association_reflection @from_class_name = from_class.name @to_class_name = get_to_class_name @name = get_association_name @type, @cardinality = get_type_and_cardinality end attr_reader :active_record_association_reflection, :from_class_name, :name, :type, :cardinality, :to_class_name private def yuml_me_label agregated_label = ClassDiagramGenerator.associations_metadata.agregated_label_for_association(self) "[#{@from_class_name}]-#{@type}#{agregated_label} >#{@cardinality}[#{@to_class_name}]" end # TODO find better name def get_to_class_name if (@active_record_association_reflection.class_name.respond_to? 'underscore') @active_record_association_reflection.class_name.pluralize.singularize.camelize else @active_record_association_reflection.class_name end end def get_association_name @to_class_name == @active_record_association_reflection.name.to_s.singularize.camelize ? '' : @active_record_association_reflection.name.to_s end def get_type_and_cardinality @habtm ||= [] association_macro_type = @active_record_association_reflection.macro.to_s type = if association_macro_type == 'belongs_to' cardinality = "" "belongs_to" elsif association_macro_type == 'has_one' cardinality = "1" "has_one" elsif association_macro_type == 'has_many' && (! @active_record_association_reflection.options[:through]) cardinality = "*" "has_many" else # habtm or has_many, :through next if @habtm.include? [@active_record_association_reflection.class_name, @from_class_name, @name] @habtm << [@from_class_name, @active_record_association_reflection.class_name, @name] cardinality = "*" "has_through" end return type, cardinality end end class Graph def initialize @edges = {} @edge_labels = {} end # attr_reader :edges def add_edge(from, to, label="") @edges[from] ||= [] @edges[from] << to add_edge_label(from, to, label) end def add_edge_label(from, to, label) key = edge_label_key(from, to) @edge_labels[key] ||= [] @edge_labels[key] << humanize_label(label, to) unless label.blank? end private :add_edge_label def edge_label_key(from, to) "#{from}->#{to}" end private :edge_label_key def humanize_label(label, to) label.gsub("_" + to.downcase.pluralize, "").gsub("_", " ") end private :humanize_label def has_edge_between?(from, to) @edges.has_key?(from) && @edges[from].include?(to) end def label_for_edge(from, to) key = edge_label_key(from, to) return "" unless @edge_labels.has_key? key @edge_labels[key].sort.join(" / ").append_char_at_the_beginning_if_not_blank(' ') end end end end<file_sep>class Element < ActiveRecord::Base belongs_to :project end<file_sep>namespace :class_diagram do def doc_diagrams_folder folder = File.join(Dir.pwd, "doc/diagrams/") FileUtils.mkdir(folder) unless File.directory?(folder) folder end def load_controller_classes(except) # before Rails 2.3 require "app/controllers/application.rb" if File.exists?("app/controllers/application.rb") # from Rails >= 2.3.x require "app/controllers/application_controller.rb" if File.exists?("app/controllers/application_controller.rb") files = Dir.glob("app/controllers/**/*_controller.rb") - except files.each {|c| require c } end def except_files # FIXME convert a comma separated list to an array, there must be some examples around [ ENV['EXCEPT'] ] || [] end desc "generate controllers class diagram" task :controllers => :environment do load_controller_classes(except_files) png_file_path = doc_diagrams_folder + "controllers_class_diagram.png" ClassDiagramGenerator.new. with_all_controller_classes("app/controllers/**/*_controller.rb", except_files). show_inheritance. show_public_methods. to_png(png_file_path, ";dir:TB;") puts "generating diagram for controllers" `open #{png_file_path}` end desc "generate models class diagram" task :models => :environment do png_file_path = doc_diagrams_folder + "models_class_diagram.png" ClassDiagramGenerator.new. with_all_model_classes("app/models/**/*.rb", except_files). show_inheritance. show_associations. show_public_methods.show_debugging. with_note("Class diagram for all models"). to_png(png_file_path, ";dir:TB;scale:180;") puts "generating diagram for models" `open #{png_file_path}` end end <file_sep>source "http://rubygems.org" gem "sqlite3-ruby" gem "rspec", "1.3.0" gem "activerecord", "2.3.8" gem "activesupport", "2.3.8" gem "actionpack", "2.3.8" # echo 'rvm use ruby-1.8.7@class_diagram_generator' >> .rvmrc <file_sep>class ProjectsController < ApplicationController def custom_action end end<file_sep>class Friendship < ActiveRecord::Base belongs_to :from, :class_name => 'User' belongs_to :to, :class_name => 'User' has_one :child, :class_name => 'Friendship', :foreign_key => 'parent_id', :dependent => :delete belongs_to :parent, :class_name => 'Friendship' belongs_to :initiated_by, :class_name => 'User' end
8e69a14ccecf800ebc784f02dff3e4c33fdd5740
[ "Ruby" ]
17
Ruby
jmgarnier/class_diagram_generator
0b20738a2f777dca43d5873e7ea2e6b00f6ac128
fb231f311181a7e9962c473d7b93681d8044ce7a
refs/heads/master
<repo_name>asny23/slack-scripts<file_sep>/devide_emoji.sh #!/bin/sh # requirements: sips command # original file SOURCE='' # devided emojis filename will be DEST-n-m.DEST_EXT DEST='' DEST_EXT='png' # size of devided emoji CELL=128 # devided emojis for slack message EMOJICODE='' # for x in [1 129 257 385 513 641 769 897] for x in 0 1 2 3 4 5 6 7 do OFFSET_X=$(expr $CELL \* $x + 1) # for y in [1 129 257 385 513 641 769 897] for y in 0 1 2 3 4 5 6 7 do OFFSET_Y=$(expr $CELL \* $y + 1) # echo "OFFSET: $OFFSET_X $OFFSET_Y" sips -c $CELL $CELL --cropOffset $OFFSET_X $OFFSET_Y $SOURCE -o "$DEST-$(expr $x + 1)-$(expr $y + 1).$DEST_EXT" EMOJICODE=$EMOJICODE":$DEST-$(expr $x + 1)-$(expr $y + 1):" done EMOJICODE=$EMOJICODE"\n" done echo 'emoji code' echo $EMOJICODE <file_sep>/download-slack-emoji.sh #!/bin/bash # get token from https://api.slack.com/custom-integrations/legacy-tokens SLACK_TOKEN='' OUT_DIR='slack-images' if [ ! -d $OUT_DIR ] ; then mkdir $OUT_DIR fi curl -q -s "https://slack.com/api/emoji.list?token=$SLACK_TOKEN" | jq -Mr '.emoji | to_entries | .[] | select(.value | startswith("http")) | "\(.key) \(.value)"' | sort | while read name url; do fn="$name.${url##*.}" if [ -f $OUT_DIR/$fn ] ; then echo "$fn exists" else echo "$fn downloading" curl -q -s -o "$OUT_DIR/$fn" "$url" fi done
943afa7f6a14343207f006fa2cd533814a07c64e
[ "Shell" ]
2
Shell
asny23/slack-scripts
3efd14bde326277634e9e64286345c96c48e89c7
af7fca2de1bff5352b9ede413dbe2db4c2e23113
refs/heads/master
<repo_name>KaviyaSriBathrachalam/HTML_to_PDF-jsPDF-JAVaSCRIPT-<file_sep>/src/app/epdf/epdf.component.ts import { Component, OnInit } from '@angular/core'; import * as jsPDF from 'jspdf'; @Component({ selector: 'app-epdf', templateUrl: './epdf.component.html', styleUrls: ['./epdf.component.css'] }) export class EpdfComponent implements OnInit { constructor() { } ngOnInit() { } download() { let doc = new jsPDF(); doc.text('Hello world!', 10, 10) doc.save('a4.pdf') } }
75049da4b9792ccc979c01abef61e0fde9d50539
[ "TypeScript" ]
1
TypeScript
KaviyaSriBathrachalam/HTML_to_PDF-jsPDF-JAVaSCRIPT-
142f014102719ae7bfd9496e190b6c41b8f3eb84
b5f5f8b4f369eff053fd55bd4cb19d57bc778a21
refs/heads/master
<repo_name>Reggora/reggora-csharp<file_sep>/Reggora.Api/Requests/Lender/Orders/GetSubmissionRequest.cs using Newtonsoft.Json; using RestSharp; namespace Reggora.Api.Requests.Lender.Orders { public class GetSubmissionRequest : ReggoraRequest { public GetSubmissionRequest(string orderId, uint version, string reportType) : base( "lender/order-submission/{order_id}/{version}/{report_type}", Method.GET) { AddParameter("order_id", orderId, ParameterType.UrlSegment); AddParameter("version", version, ParameterType.UrlSegment); AddParameter("report_type", reportType, ParameterType.UrlSegment); } public new Response Execute(IRestClient client) { return Execute<Response>(client); } public byte[] Download(IRestClient client) { return client.DownloadData(this, true); } public class Response { [JsonProperty("error")] public string Error { get; set; } } } }<file_sep>/Reggora.Api/Requests/Lender/Evaults/GetDocumentRequest.cs using Newtonsoft.Json; using RestSharp; namespace Reggora.Api.Requests.Lender.Evaults { public class GetDocumentRequest : ReggoraRequest { public GetDocumentRequest(string evaultId, string documentId) : base("lender/evault/{evault_id}/{document_id}", Method.GET) { AddParameter("evault_id", evaultId, ParameterType.UrlSegment); AddParameter("document_id", documentId, ParameterType.UrlSegment); } } } <file_sep>/Reggora.Api/Storage/Lender/VendorStorage.cs using Reggora.Api.Entity; using Reggora.Api.Requests.Lender.Vendors; using Reggora.Api.Util; using System.Collections.Generic; namespace Reggora.Api.Storage.Lender { public class VendorStorage : Storage<Vendr, Api.Lender> { public VendorStorage(Api.Lender api) : base(api) { } public List<Vendr> All() { var result = new GetVendorsRequest().Execute(Api.Client); var fetchedVendors = result.Data.Vendors; List<Vendr> vendors = new List<Vendr>(); if (result.Status == 200) { for (int i = 0; i < fetchedVendors.Count; i++) { Vendr tempVendor = new Vendr(); tempVendor.UpdateFromRequest(Utils.DictionaryOfJsonFields(fetchedVendors[i])); vendors.Add(tempVendor); } } return vendors; } public override Vendr Get(string id) { Known.TryGetValue(id, out var returned); if (returned == null) { var result = new GetVendorRequest(id).Execute(Api.Client); if (result.Status == 200) { returned = new Vendr(); returned.UpdateFromRequest(Utils.DictionaryOfJsonFields(result.Data.Vendor)); Known.Add(returned.Id, returned); } } return returned; } public List<Vendr> GetByZone(List<string> zones, uint offset = 0, uint limit = 0, string ordering = "-created") { var result = new GetVendorsByZoneRequest(zones, offset, limit, ordering).Execute(Api.Client); var fetchedVendors = result.Data.Vendors; List<Vendr> vendors = new List<Vendr>(); if (result.Status == 200) { for (int i = 0; i < fetchedVendors.Count; i++) { Vendr tempVendor = new Vendr(); tempVendor.UpdateFromRequest(Utils.DictionaryOfJsonFields(fetchedVendors[i])); vendors.Add(tempVendor); } } return vendors; } public List<Vendr> GetByBranch(string branchId) { var result = new GetVendorsByBranchRequest(branchId).Execute(Api.Client); var fetchedVendors = result.Data.Vendors; List<Vendr> vendors = new List<Vendr>(); if (result.Status == 200) { for (int i = 0; i < fetchedVendors.Count; i++) { Vendr tempVendor = new Vendr(); tempVendor.UpdateFromRequest(Utils.DictionaryOfJsonFields(fetchedVendors[i])); vendors.Add(tempVendor); } } return vendors; } public override void Save(Vendr vendor) { } public string Create(Vendr vendor) { string response = null; var result = new InviteVendorRequest(vendor).Execute(Api.Client); if (result.Status == 200) { response = result.Data; vendor.Clean(); } return response; } public string Edit(Vendr vendor) { string response = ""; var result = new EditVendorRequest(vendor).Execute(Api.Client); if (result.Status == 200) { response = result.Data; vendor.Clean(); } return response; } public string Delete(string id) { string response = null; var result = new DeleteVendorRequest(id).Execute(Api.Client); if (result.Status == 200) { response = result.Data; } return response; } } } <file_sep>/Reggora.Api/Requests/Vendor/Order/GetVendorOrderRequest.cs using System.Collections.Generic; using Newtonsoft.Json; using RestSharp; namespace Reggora.Api.Requests.Vendor.Order { public class GetVendorOrderRequest : ReggoraRequest { public GetVendorOrderRequest(string orderId) : base("vendor/order/{order_id}", Method.GET) { AddParameter("order_id", orderId, ParameterType.UrlSegment); } public new Response Execute(IRestClient client) { return Execute<Response>(client); } public class Response { [JsonProperty("data")] public Order Data { get; set; } [JsonProperty("status")] public int Status { get; set; } public class Order { [JsonProperty("id")] public string Id { get; set; } [JsonProperty("status")] public string Status { get; set; } [JsonProperty("property_street")] public string PropertyStreet { get; set; } [JsonProperty("property_city")] public string PropertyCity { get; set; } [JsonProperty("property_state")] public string PropertyState { get; set; } [JsonProperty("property_zip")] public string PropertyZip { get; set; } [JsonProperty("priority")] public string Priority { get; set; } [JsonProperty("request_expiration")] public string RequestExpiration { get; set; } [JsonProperty("due_date")] public string DueDate { get; set; } [JsonProperty("lender")] public Lendr Lender { get; set; } [JsonProperty("loan_file")] public Loan LoanFile { get; set; } [JsonProperty("consumers")] public List<Consumer> Consumers { get; set; } [JsonProperty("schedule")] public Schdl Schedule { get; set; } [JsonProperty("evault")] public string Evault { get; set; } [JsonProperty("conversation")] public string Conversation { get; set; } [JsonProperty("products")] public List<Product> Products { get; set; } [JsonProperty("submissions")] public List<Submission> Submissions { get; set; } [JsonProperty("revisions")] public List<Revision> Revisions { get; set; } public class Lendr { [JsonProperty("id")] public string Id { get; set; } [JsonProperty("name")] public string Name { get; set; } } public class Loan { [JsonProperty("occupancy_type")] public string OccupancyType { get; set; } [JsonProperty("attachment_type")] public string AttachmentType { get; set; } [JsonProperty("agency_case_number")] public string AgencyCaseNumber { get; set; } [JsonProperty("loan_type")] public string LoanType { get; set; } [JsonProperty("number_of_units")] public string NumberOfUnits { get; set; } [JsonProperty("appraisal_type")] public string AppraisalType { get; set; } [JsonProperty("number")] public string Number { get; set; } } public class Consumer { [JsonProperty("full_name")] public string FullName { get; set; } [JsonProperty("role")] public string Role { get; set; } [JsonProperty("email")] public string Email { get; set; } [JsonProperty("home_phone")] public string HomePhone { get; set; } [JsonProperty("cell_phone")] public string CellPhone { get; set; } [JsonProperty("work_phone")] public string WorkPhone { get; set; } } public class Schdl { [JsonProperty("available_dates")] public List<string> AvailableDates { get; set; } } public class Product { [JsonProperty("description")] public string Description { get; set; } [JsonProperty("forms")] public List<string> Forms { get; set; } [JsonProperty("amount")] public uint Amount { get; set; } [JsonProperty("inspection_type")] public string InspectionType { get; set; } } public class Submission { [JsonProperty("created")] public string Created { get; set; } [JsonProperty("pdf_report")] public string PdfReport { get; set; } [JsonProperty("xml_report")] public string XmlReport { get; set; } [JsonProperty("invoice")] public string Invoice { get; set; } [JsonProperty("additional_files")] public List<string> AdditionalFiles { get; set; } [JsonProperty("version")] public uint Version { get; set; } } public class Revision { [JsonProperty("created")] public string Created { get; set; } [JsonProperty("updated")] public string Updated { get; set; } [JsonProperty("lender_resolved")] public string LenderResolved { get; set; } [JsonProperty("vendor_completed")] public string VendorCompleted { get; set; } [JsonProperty("text")] public string Text { get; set; } [JsonProperty("title")] public string Title { get; set; } } } } } }<file_sep>/Reggora.Api/Requests/Lender/App/CustomerAppLinkRequest.cs using Newtonsoft.Json; using Reggora.Api.Entity; using RestSharp; namespace Reggora.Api.Requests.Lender.App { public class CustomerAppLinkRequest : ReggoraRequest { public CustomerAppLinkRequest(string orderId, string consumerId, PaymentApp.LinkType paymentType) : base("lender/{order_id}/{consumer_id}/{link_type}", Method.GET) { AddParameter("order_id", orderId, ParameterType.UrlSegment); AddParameter("consumer_id", consumerId, ParameterType.UrlSegment); AddParameter("link_type", PaymentApp.LinkTypeToString(paymentType), ParameterType.UrlSegment); } public new Response Execute(IRestClient client) { return Execute<Response>(client); } public class Response { [JsonProperty("data")] public string Data { get; set; } [JsonProperty("error")] public string Error { get; set; } [JsonProperty("status")] public int Status { get; set; } } } } <file_sep>/Reggora.Api/Requests/Lender/Vendors/GetVendorsByZoneRequest.cs using System.Collections.Generic; using Newtonsoft.Json; using RestSharp; namespace Reggora.Api.Requests.Lender.Vendors { public class GetVendorsByZoneRequest : ReggoraRequest { public enum Ordering { Created } public uint Offset = 0; public uint Limit = 0; public Ordering Order = Ordering.Created; public GetVendorsByZoneRequest(List<string> zones, uint offset, uint limit, string ordering) : base("lender/vendors/by_zone", Method.POST) { AddParameter("offset", offset, ParameterType.QueryString); AddParameter("limit", limit, ParameterType.QueryString); AddParameter("order", ordering, ParameterType.QueryString); AddJsonBody(new Request { Zones = zones }); } public new Response Execute(IRestClient client) { return Execute<Response>(client); } private string OrderingToString() { switch (Order) { case Ordering.Created: return "-created"; } return ""; } public class Request { [JsonProperty("zones")] public List<string> Zones { get; set; } } public class Response { [JsonProperty("data")] public Nested Data { get; set; } [JsonProperty("status")] public int Status { get; set; } public class Nested { [JsonProperty("vendors")] public List<GetVendorRequest.Response.Vendor> Vendors { get; set; } } } } }<file_sep>/Reggora.Api/Storage/Vendor/ConversationManagementStorage.cs using Reggora.Api.Entity; using Reggora.Api.Requests.Vendor.Conversation; using Reggora.Api.Util; using System; namespace Reggora.Api.Storage.Vendor { public class ConversationManagementStorage : Storage<Conversation, Api.Vendor> { public ConversationManagementStorage(Api.Vendor api) : base(api) { } public override Conversation Get(string id) { Known.TryGetValue(id, out var returned); if (returned == null) { var result = new GetConversationRequest(id).Execute(Api.Client); if (result.Status == 200) { returned = new Conversation(); returned.UpdateFromRequest(Utils.DictionaryOfJsonFields(result.Data)); Known.Add(returned.Id, returned); } } return returned; } public string SendMessage(string conversationId, string message = "") { string response = ""; var result = new SendMessageRequest(conversationId, message).Execute(Api.Client); if (result.Status == 200) { response = result.Data; } return response; } public override void Save(Conversation entity) { throw new NotImplementedException(); } } } <file_sep>/Reggora.Api/Requests/Lender/Orders/GetSubmissionsRequest.cs using Newtonsoft.Json; using RestSharp; using System.Collections.Generic; namespace Reggora.Api.Requests.Lender.Orders { public class GetSubmissionsRequest : ReggoraRequest { public GetSubmissionsRequest(string orderId) : base("lender/order-submissions/{order_id}", Method.GET) { AddParameter("order_id", orderId, ParameterType.UrlSegment); } public new Response Execute(IRestClient client) { return Execute<Response>(client); } public class Response { [JsonProperty("data")] public NestedSubmission Data { get; set; } [JsonProperty("status")] public int Status { get; set; } public class NestedSubmission { [JsonProperty("submissions")] public List<Submission> Submissions { get; set; } } public class Submission { [JsonProperty("version")] public string Version { get; set; } [JsonProperty("pdf_report")] public string PdfReport { get; set; } [JsonProperty("xml_report")] public string XmlReport { get; set; } [JsonProperty("invoice")] public string Invoice { get; set; } } } } }<file_sep>/Reggora.Api/Requests/Lender/Vendors/EditVendorRequest.cs using Newtonsoft.Json; using Reggora.Api.Entity; using RestSharp; namespace Reggora.Api.Requests.Lender.Vendors { public class EditVendorRequest : ReggoraRequest { public EditVendorRequest(Vendr vendor) : base("lender/vendor/{vendor_id}", Method.PUT) { AddParameter("vendor_id", vendor.Id, ParameterType.UrlSegment); AddJsonBody(new Request { FirmName = vendor.FirmName, FirstName = vendor.FirstName, LastName = vendor.LastName, Email = vendor.Email, Phone = vendor.Phone }); } public class Request { [JsonProperty("firm_name")] public string FirmName { get; set; } [JsonProperty("firstname")] public string FirstName { get; set; } [JsonProperty("lastname")] public string LastName { get; set; } [JsonProperty("email")] public string Email { get; set; } [JsonProperty("phone")] public string Phone { get; set; } } public class Response { [JsonProperty("data")] public string Data { get; set; } [JsonProperty("status")] public int Status { get; set; } } } }<file_sep>/Reggora.Api/Storage/Lender/AppStoreage.cs using Reggora.Api.Entity; using Reggora.Api.Requests.Lender.App; using System; using System.Collections.Generic; namespace Reggora.Api.Storage.Lender { public class AppStorage : Storage<PaymentApp, Api.Lender> { public AppStorage(Api.Lender api) : base(api) { } public string SendPaymentApp(PaymentApp app) { string response = null; var result = new SendPaymentAppRequest(app).Execute(Api.Client); if (result.Status == 200) { response = result.Data; } else { response = result.Error; } return response; } public string SendSchedulingApp(List<string> consumerEmails, string orderId) { string response = null; var result = new SendSchedulingAppRequest(consumerEmails, orderId).Execute(Api.Client); if (result.Status == 200) { response = result.Data; } else { response = result.Error; } return response; } public string ConsumerAppLink(string orderId, string consumerId, PaymentApp.LinkType paymentType) { string response = null; var result = new CustomerAppLinkRequest(orderId, consumerId, paymentType).Execute(Api.Client); if (result.Status == 200) { response = result.Data; } else { response = result.Error; } return response; } public override PaymentApp Get(string id) { throw new NotImplementedException(); } public override void Save(PaymentApp entity) { throw new NotImplementedException(); } } } <file_sep>/Reggora.Api/Requests/Vendor/Conversation/SendMessageRequest.cs using System.Collections.Generic; using Newtonsoft.Json; using RestSharp; namespace Reggora.Api.Requests.Vendor.Conversation { public class SendMessageRequest : ReggoraRequest { public SendMessageRequest(string conversationId, string message) : base("vendor/conversation/{conversation_id}", Method.PUT) { AddParameter("conversation_id", conversationId, ParameterType.UrlSegment); } } }<file_sep>/Reggora.Api/Requests/Lender/Loans/DeleteLoanRequest.cs using RestSharp; namespace Reggora.Api.Requests.Lender.Loans { public class DeleteLoanRequest : ReggoraRequest { public DeleteLoanRequest(string loanId) : base("lender/loan/{loan_id}", Method.DELETE) { AddParameter("loan_id", loanId, ParameterType.UrlSegment); } } }<file_sep>/Reggora.Api/Requests/Lender/Products/GetProductRequest.cs using System.Collections.Generic; using Newtonsoft.Json; using Reggora.Api.Requests.Lender.Products; using RestSharp; namespace Reggora.Api.Requests.Lender.Products { public class GetProductRequest : ReggoraRequest { public GetProductRequest(string productId) : base("lender/product/{product_id}", Method.GET) { AddParameter("product_id", productId, ParameterType.UrlSegment); } public new Response Execute(IRestClient client) { return Execute<Response>(client); } public class Response { [JsonProperty("data")] public NestedProduct Data { get; set; } [JsonProperty("status")] public int Status { get; set; } public class NestedProduct { [JsonProperty("loan")] public Product Product { get; set; } } public class Product { [JsonProperty("id")] public string Id { get; set; } [JsonProperty("product_name")] public string ProductName { get; set; } [JsonProperty("amount")] public float Amount { get; set; } [JsonProperty("inspection_type")] public string InspectionType { get; set; } [JsonProperty("requested_forms")] public string RequestedForms { get; set; } } } } }<file_sep>/Reggora.Api/Requests/Lender/Orders/GetOrdersRequest.cs using System.Collections.Generic; using Newtonsoft.Json; using RestSharp; namespace Reggora.Api.Requests.Lender.Orders { public class GetOrdersRequest : ReggoraRequest { public enum Ordering { Created } public uint Offset = 0; public uint Limit = 0; public Ordering Order = Ordering.Created; public GetOrdersRequest(uint offset, uint limit, string ordering, string loanOfficer, string filters) : base("lender/orders", Method.GET) { AddParameter("offset", offset, ParameterType.QueryString); AddParameter("limit", limit, ParameterType.QueryString); AddParameter("order", ordering, ParameterType.QueryString); AddParameter("loan_officer", loanOfficer, ParameterType.QueryString); AddParameter("filter", filters, ParameterType.QueryString); } public new Response Execute(IRestClient client) { return Execute<Response>(client); } private string OrderingToString() { switch (Order) { case Ordering.Created: return "-created"; } return ""; } public class Response { [JsonProperty("data")] public NestedOrders Data { get; set; } [JsonProperty("status")] public int Status { get; set; } public class NestedOrders { [JsonProperty("orders")] public List<GetOrderRequest.Response.Order> Orders { get; set; } } } } }<file_sep>/Reggora.Api/Entity/EntityRelationship.cs namespace Reggora.Api.Entity { public class EntityRelationship<E> where E : Entity { public readonly E Entity; public EntityRelationship(E entity) { Entity = entity; } } }<file_sep>/Reggora.Api/Requests/Lender/Evaults/DeleteDocumentRequest.cs using Newtonsoft.Json; using RestSharp; namespace Reggora.Api.Requests.Lender.Evaults { public class DeleteDocumentRequest : ReggoraRequest { public DeleteDocumentRequest(string evaultId, string documentId) : base("lender/evault", Method.DELETE) { AddJsonBody(new Request { EvaultId = evaultId, DocumentId = documentId }); } public class Request { [JsonProperty("id")] public string EvaultId { get; set; } [JsonProperty("document_id")] public string DocumentId { get; set; } } public new Response Execute(IRestClient client) { return Execute<Response>(client); } public class Response { [JsonProperty("data")] public string Data { get; set; } [JsonProperty("status")] public int Status { get; set; } } } } <file_sep>/Reggora.Api/Requests/Vendor/Evault/GetDocumentRequest.cs using System.Collections.Generic; using Newtonsoft.Json; using RestSharp; namespace Reggora.Api.Requests.Vendor.Evault { class GetDocumentRequest : ReggoraRequest { public GetDocumentRequest(string evaultId, string documentId) : base("vendor/evault/{evault_id}/{document_id}", Method.GET) { AddParameter("evault_id", evaultId, ParameterType.UrlSegment); AddParameter("document_id", documentId, ParameterType.UrlSegment); } public new Response Execute(IRestClient client) { return Execute<Response>(client); } public byte[] Download(IRestClient client) { return client.DownloadData(this, true); } public class Response { [JsonProperty("error")] public string Error { get; set; } } } } <file_sep>/Reggora.Api/Requests/Lender/Vendors/DeleteVendorRequest.cs using Newtonsoft.Json; using RestSharp; namespace Reggora.Api.Requests.Lender.Vendors { public class DeleteVendorRequest : ReggoraRequest { public DeleteVendorRequest(string vendorId) : base("lender/vendor/{vendor_id}", Method.DELETE) { AddParameter("vendor_id", vendorId, ParameterType.UrlSegment); } public class Response { [JsonProperty("data")] public string Data { get; set; } [JsonProperty("status")] public int Status { get; set; } } } }<file_sep>/Reggora.Api/Requests/Vendor/Order/CancelVendorOrderRequest.cs using Newtonsoft.Json; using Reggora.Api.Entity; using Reggora.Api.Util; using RestSharp; namespace Reggora.Api.Requests.Vendor.Order { public class CancelVendorOrderRequest : ReggoraRequest { public CancelVendorOrderRequest(string orderId, string message) : base("vendor/order/{order_id}", Method.DELETE) { AddParameter("order_id", orderId, ParameterType.UrlSegment); AddJsonBody(new Request { Message = message }); } public class Request { [JsonProperty("message")] public string Message { get; set; } } } }<file_sep>/Reggora.Api/Entity/EntityManyRelationship.cs using Reggora.Api.Storage; namespace Reggora.Api.Entity { public class EntityManyRelationship<E, C, S> where E : Entity where C : ApiClient<C> where S : Storage<E, C>, new() { public readonly Storage<E, C> Known; public EntityManyRelationship() { Known = StorageFactory.Create<S, E, C>(); } } }<file_sep>/Reggora.Api/Storage/Vendor/EvaultManagementStorage.cs using Reggora.Api.Entity; using Reggora.Api.Requests.Vendor.Evault; using Reggora.Api.Util; using Syroot.Windows.IO; using System; using System.IO; namespace Reggora.Api.Storage.Vendor { public class EvaultManagementStorage : Storage<VendorEvault, Api.Vendor> { public EvaultManagementStorage(Api.Vendor api) : base(api) { } public override VendorEvault Get(string id) { Known.TryGetValue(id, out var returned); if (returned == null) { var result = new GetEvaultRequest(id).Execute(Api.Client); if (result.Status == 200) { returned = new VendorEvault(); returned.UpdateFromRequest(Utils.DictionaryOfJsonFields(result.Data)); Known.Add(returned.Id, returned); } } return returned; } public bool GetDocument(string evaultId, string documentId, string downloadPath) { if (downloadPath == "" || downloadPath == null) { downloadPath = new KnownFolder(KnownFolderType.Downloads).Path; } bool response = true; try { byte[] result = new GetDocumentRequest(evaultId, documentId).Download(Api.Client); FileStream fs = File.Create(downloadPath + "\\evault_" + evaultId); fs.Write(result, 0, result.Length); } catch (Exception e) { response = false; Console.WriteLine("Downloading Error message: {0}", e.ToString()); } return response; } public string UploadDocument(string evaultId, string filePath, string fileName = null) { string response = null; var result = new UploadDocumentRequest(evaultId, filePath, fileName).Execute(Api.Client); if (result.Status == 200) { response = result.Data; } return response; } public string DeleteDocument(string evaultId, string documentId) { string response = ""; var result = new DeleteDocumentRequest(evaultId, documentId).Execute(Api.Client); if (result.Status == 200) { response = result.Data; } return response; } public override void Save(VendorEvault entity) { throw new NotImplementedException(); } } } <file_sep>/Reggora.Api/Entity/EntityField.cs using System; using System.Collections.Generic; using Reggora.Api.Util; namespace Reggora.Api.Entity { public delegate void ChangedCallback(string propertyName); public class EntityField<T> { private readonly string _name; private readonly string _conversionType; private T _value; private bool _set = false; private ChangedCallback _callback; public T Value { get => _value; set { if (_set == false || !EqualityComparer<T>.Default.Equals(_value, value)) { _set = true; _callback.Invoke(_name); _value = value; } } } public EntityField(string name, ChangedCallback callback) { _name = name; _callback = callback; } public EntityField(string name, string conversionType, ChangedCallback callback) { _name = name; _conversionType = conversionType; _callback = callback; } public dynamic ConvertIncoming(dynamic value) { if (_conversionType != null) { if (typeof(T) == typeof(DateTime) || typeof(T) == typeof(DateTime?)) { return Utils.DateTimeFromString(value); } if (typeof(T) == typeof(Order.AllocationMode) || typeof(T) == typeof(Order.AllocationMode?)) { return Order.AllocationModeFromString(value); } if (typeof(T) == typeof(Order.PriorityType) || typeof(T) == typeof(Order.PriorityType?)) { return Order.PriorityTypeFromString(value); } if (typeof(T) == typeof(Product.Inspection) || typeof(T) == typeof(Product.Inspection?)) { return Product.InspectionFromString(value); } } return value; } public dynamic ConvertOutgoing(dynamic value) { if (_conversionType != null) { if (typeof(T) == typeof(DateTime) || typeof(T) == typeof(DateTime?)) { return Utils.DateToString(value); } if (typeof(T) == typeof(Order.AllocationMode) || typeof(T) == typeof(Order.AllocationMode?)) { return Order.AllocationModeToString(value); } if (typeof(T) == typeof(Order.PriorityType) || typeof(T) == typeof(Order.PriorityType?)) { return Order.PriorityTypeToString(value); } if (typeof(T) == typeof(Product.Inspection) || typeof(T) == typeof(Product.Inspection?)) { return Product.InspectionToString(value); } } return value; } } }<file_sep>/Reggora.Api/Entity/ChildEntity.cs namespace Reggora.Api.Entity { public abstract class ChildEntity : Entity { private readonly Entity _parent; public ChildEntity(Entity parent) { _parent = parent; } protected new void BuildField<T>(ref EntityField<T> field, string name) { field = new EntityField<T>(name, propertyName => _parent.DirtyFields.Add(propertyName)); } } }<file_sep>/Reggora.Api/Exceptions/InvalidParameterException.cs using System; namespace Reggora.Api.Exceptions { public class InvalidParameterException : ReggoraException { public InvalidParameterException(Exception innerError) : base( "Invalid Parameter -- Either the URL parameters or the request body parameters are invalid.", innerError) { } public InvalidParameterException(string message, Exception innerError) : base(message, innerError) { } } }<file_sep>/Reggora.Api/Reggora.cs using System; using System.Net; using Reggora.Api.Exceptions; namespace Reggora.Api { public class Reggora { public const string BaseUrl = "https://sandbox.reggora.io/"; public static Lender Lender(string username, string password, string integrationToken) { return new Lender(integrationToken).Authenticate(username, password); } public static Vendor Vendor(string email, string password, string integrationToken) { return new Vendor(integrationToken).Authenticate(email, password); } public static ReggoraException RaiseRequestErrorToException(HttpStatusCode code, Exception innerError) { switch (code) { case HttpStatusCode.BadRequest: return new BadRequestException(innerError); case HttpStatusCode.Unauthorized: return new AuthorizationException(innerError); case HttpStatusCode.Forbidden: return new InvalidParameterException(innerError); case HttpStatusCode.NotFound: return new NotFoundException(innerError); case HttpStatusCode.InternalServerError: return new InternalServerErrorException(innerError); } return new ReggoraException("Error executing request.", innerError); } } }<file_sep>/Reggora.Api/Requests/Lender/LenderAuthenticateRequest.cs namespace Reggora.Api.Requests.Lender { public class LenderAuthenticateRequest : AuthenticateRequest { public LenderAuthenticateRequest(string username, string password) : base("lender", username, password) { } } }<file_sep>/Reggora.Api/Requests/Lender/Orders/EditOrderRequest.cs using System.Collections.Generic; using Newtonsoft.Json; using Reggora.Api.Entity; using Reggora.Api.Util; using RestSharp; using RestSharp.Serializers.Newtonsoft.Json; namespace Reggora.Api.Requests.Lender.Orders { public class EditOrderRequest : ReggoraRequest { public EditOrderRequest(Order order, bool refresh) : base("lender/order/{order_id}", Method.PUT) { JsonSerializer = new NewtonsoftJsonSerializer(new JsonSerializer() { MissingMemberHandling = MissingMemberHandling.Ignore, NullValueHandling = NullValueHandling.Ignore, DefaultValueHandling = DefaultValueHandling.Include }); AddParameter("order_id", order.Id, ParameterType.UrlSegment); var request = new Request {Refresh = refresh}; Utils.DictionaryToJsonFields(request, order.GetDirtyFieldsForRequest()); List<string> productIds = new List<string>(); foreach(GetOrderRequest.Response.Order.Product product in order.Products) { productIds.Add(product.Id); } request.Products = productIds; AddJsonBody(request); } public class Request { [JsonProperty("allocation_type")] public string AllocationType { get; set; } [JsonProperty("priority")] public string Priority { get; set; } [JsonProperty("products")] public List<string> Products { get; set; } [JsonProperty("due_date")] public string DueDate { get; set; } [JsonProperty("additional_fees")] public List<AdditionalFee> AdditionalFees { get; set; } [JsonProperty("refresh")] public bool Refresh { get; set; } public class AdditionalFee { [JsonProperty("description")] public string Description { get; set; } [JsonProperty("amount")] public int Amount { get; set; } } } } }<file_sep>/Reggora.Api/Util/Utils.cs using System; using System.Collections.Generic; using Newtonsoft.Json; namespace Reggora.Api.Util { public static class Utils { public static Dictionary<string, dynamic> DictionaryOfJsonFields<T>(T obj) { var dictionary = new Dictionary<string, dynamic>(); foreach (var property in obj.GetType().GetProperties()) { foreach (var attribute in property.GetCustomAttributes(true)) { if (attribute is JsonPropertyAttribute jsonProperty) { dictionary.Add(jsonProperty.PropertyName, property.GetValue(obj)); } } } return dictionary; } public static void DictionaryToJsonFields<T>(T obj, Dictionary<string, dynamic> fields) { foreach (var property in obj.GetType().GetProperties()) { foreach (var attribute in property.GetCustomAttributes(true)) { if (attribute is JsonPropertyAttribute jsonProperty) { if (fields.ContainsKey(jsonProperty.PropertyName)) { property.SetValue(obj, fields[jsonProperty.PropertyName]); } } } } } public static List<string> ListOfJsonString(string listItems) { return JsonConvert.DeserializeObject<List<string>>(listItems); } public static string DateToString(DateTime? date) { if (date == null) { return ""; } return ((DateTime) (object) date).ToString("yyyy-MM-ddTHH:mm:ssZ"); } public static int? IntFromString(string integer) { if (integer != null) { return Int32.Parse(integer); } return null; } public static DateTime? DateTimeFromString(string date) { if (date != null) { try { return DateTime.Parse(date); } catch (FormatException) { } } return null; } } }<file_sep>/Reggora.Api/Requests/Lender/Users/DeleteUserRequest.cs using Newtonsoft.Json; using RestSharp; namespace Reggora.Api.Requests.Lender.Users { public class DeleteUserRequest : ReggoraRequest { public DeleteUserRequest(string userId) : base("lender/users/{user_id}", Method.DELETE) { AddParameter("user_id", userId, ParameterType.UrlSegment); } public class Response { [JsonProperty("data")] public string Data { get; set; } [JsonProperty("status")] public int Status { get; set; } } } }<file_sep>/Reggora.Api/Requests/Lender/Orders/PlaceOrderOnHoldRequest.cs using Newtonsoft.Json; using Reggora.Api.Entity; using RestSharp; namespace Reggora.Api.Requests.Lender.Orders { class PlaceOrderOnHoldRequest : ReggoraRequest { public PlaceOrderOnHoldRequest(string orderId, string reason) : base("lender/order/{order_id}/hold", Method.PUT) { AddParameter("order_id", orderId, ParameterType.UrlSegment); AddJsonBody(new Request { Reason = reason }); } public class Request { [JsonProperty("reason")] public string Reason { get; set; } } } } <file_sep>/Reggora.Api/Requests/Lender/Products/EditProductRequest.cs using Newtonsoft.Json; using Reggora.Api.Entity; using RestSharp; using Reggora.Api.Util; using RestSharp.Serializers.Newtonsoft.Json; namespace Reggora.Api.Requests.Lender.Products { public class EditProductRequest : ReggoraRequest { public EditProductRequest(Product product) : base("lender/product/{product_id}", Method.PUT) { AddParameter("product_id", product.Id, ParameterType.UrlSegment); AddJsonBody(new CreateProductRequest.Request { Name = product.ProductName, Amount = product.Amount.ToString("N2"), Inspection = Product.InspectionToString(product.InspectionType), RequestedForms = product.RequestForms }); } } }<file_sep>/Reggora.Api/Lender.cs using Reggora.Api.Authentication; using Reggora.Api.Requests.Lender; using Reggora.Api.Storage.Lender; namespace Reggora.Api { public class Lender : ApiClient<Lender> { public readonly LoanStorage Loans; public readonly OrderStorage Orders; public readonly ProductStorage Products; public readonly UserStorage Users; public readonly VendorStorage Vendors; public readonly AppStorage Apps; public readonly EvaultStorage Evaults; public Lender(string integrationToken) : base(integrationToken) { Loans = new LoanStorage(this); Orders = new OrderStorage(this); Products = new ProductStorage(this); Users = new UserStorage(this); Vendors = new VendorStorage(this); Apps = new AppStorage(this); Evaults = new EvaultStorage(this); } public override Lender Authenticate(string email, string password) { var response = new LenderAuthenticateRequest(email, password).Execute(Client); Client.Authenticator = new ReggoraJwtAuthenticator(IntegrationToken, response.Token); return this; } } }<file_sep>/Reggora.Api/Requests/Lender/Vendors/GetVendorsByBranchRequest.cs using System.Collections.Generic; using Newtonsoft.Json; using RestSharp; namespace Reggora.Api.Requests.Lender.Vendors { public class GetVendorsByBranchRequest : ReggoraRequest { public enum Ordering { Created } public uint Offset = 0; public uint Limit = 0; public Ordering Order = Ordering.Created; public GetVendorsByBranchRequest(string branchId) : base("lender/vendors/branch", Method.GET) { AddParameter("branch_id", branchId, ParameterType.QueryString); AddParameter("offset", Offset, ParameterType.QueryString); AddParameter("limit", Limit, ParameterType.QueryString); AddParameter("order", OrderingToString(), ParameterType.QueryString); } private string OrderingToString() { switch (Order) { case Ordering.Created: return "-created"; } return ""; } public new Response Execute(IRestClient client) { return Execute<Response>(client); } public class Response { [JsonProperty("data")] public Nested Data { get; set; } [JsonProperty("status")] public int Status { get; set; } public class Nested { [JsonProperty("vendors")] public List<GetVendorRequest.Response.Vendor> Vendors { get; set; } } } } }<file_sep>/Reggora.Api/Exceptions/NotFoundException.cs using System; namespace Reggora.Api.Exceptions { public class NotFoundException : ReggoraException { public NotFoundException(Exception innerError) : base( "Not Found -- The endpoint or object you are looking for does not exist.", innerError) { } public NotFoundException(string message, Exception innerError) : base(message, innerError) { } } }<file_sep>/Reggora.Api/Requests/Vendor/Evault/UploadDocumentRequest.cs using RestSharp; namespace Reggora.Api.Requests.Vendor.Evault { class UploadDocumentRequest : ReggoraRequest { public UploadDocumentRequest(string evaultId, string filePath, string fileName) : base("vendor/evault/{evault_id}", Method.PUT) { AddParameter("evault_id", evaultId, ParameterType.UrlSegment); if (fileName != null || fileName != "") { AddParameter("file_name", fileName); } AddFile("file", filePath, MimeMapping.MimeUtility.GetMimeMapping(filePath)); } } } <file_sep>/Reggora.Api/Storage/Vendor/OrderManagementStorage.cs using Reggora.Api.Entity; using Reggora.Api.Requests.Vendor.Order; using Reggora.Api.Util; using Syroot.Windows.IO; using System; using System.Collections.Generic; using System.IO; namespace Reggora.Api.Storage.Vendor { public class OrderManagementStorage : Storage<VendorOrder, Api.Vendor> { public OrderManagementStorage(Api.Vendor api) : base(api) { } public List<VendorOrder> All(uint offset = 0, uint limit = 0, List<string> Status = null) { string status = Status != null ? String.Join(",", Status.ToArray()) : null ; var result = new GetVendorOrdersRequest(offset, limit, status).Execute(Api.Client); var count = result.Data.Count; var fetchedOrders = result.Data.Orders; List<VendorOrder> orders = new List<VendorOrder>(); if (result.Status == 200) { for (int i = 0; i < fetchedOrders.Count; i++) { VendorOrder tempOrder = new VendorOrder(); tempOrder.UpdateFromRequest(Utils.DictionaryOfJsonFields(fetchedOrders[i])); orders.Add(tempOrder); } } return orders; } public override VendorOrder Get(string id) { Known.TryGetValue(id, out var returned); if (returned == null) { var result = new GetVendorOrderRequest(id).Execute(Api.Client); if (result.Status == 200) { returned = new VendorOrder(); returned.UpdateFromRequest(Utils.DictionaryOfJsonFields(result.Data)); Known.Add(returned.Id, returned); } } return returned; } public string VendorAcceptOrder(string orderId) { string response = ""; var result = new AcceptVendorOrderRequest(orderId).Execute(Api.Client); if (result.Status == 200) { response = result.Data; } return response; } public string CounterOffer(string orderId, DateTime? dueDate, float? fee) { string response = ""; var result = new CounterOfferRequest(orderId, dueDate, fee).Execute(Api.Client); if (result.Status == 200) { response = result.Data; } return response; } public string DenyOrder(string orderId, string denyReason = null) { string response = ""; var result = new DenyOrderRequest(orderId, denyReason).Execute(Api.Client); if (result.Status == 200) { response = result.Data; } return response; } public string SetInspectionDate(string orderId, DateTime? inspectionDate) { string response = ""; var result = new EditInspectionDateRequest(orderId, inspectionDate).Execute(Api.Client); if (result.Status == 200) { response = result.Data; } return response; } public string CompleteInspection(string orderId, DateTime? completedAt) { string response = ""; var result = new CompleteInspectionRequest(orderId, completedAt).Execute(Api.Client); if (result.Status == 200) { response = result.Data; } return response; } public string UploadSubmission(string orderId, string pdfFilePath, string xmlFilePath = null, string invoiceFilePath = null, string invoiceNumber = null) { string response = null; var result = new UploadSubmissionRequest(orderId, pdfFilePath, xmlFilePath, invoiceFilePath, invoiceNumber).Execute(Api.Client); if (result.Status == 200) { response = result.Data; } return response; } public bool DownloadSubmission(string orderId, uint submissionVersion, string documentType, string downloadPath) { if (downloadPath == "" || downloadPath == null) { downloadPath = new KnownFolder(KnownFolderType.Downloads).Path; } bool response = true; try { byte[] result = new DownloadSubmissionRequest(orderId, submissionVersion, documentType).Download(Api.Client); FileStream fs = File.Create(downloadPath + "\\submission_" + orderId); fs.Write(result, 0, result.Length); } catch (Exception e) { response = false; Console.WriteLine("Downloading Error message: {0}", e.ToString()); } return response; } public string VendorCancelOrder(string orderId, string message = "") { string response = null; var result = new CancelVendorOrderRequest(orderId, message).Execute(Api.Client); if (result.Status == 200) { response = result.Data; } return response; } public override void Save(VendorOrder entity) { throw new NotImplementedException(); } } } <file_sep>/Reggora.Api/Requests/Vendor/Order/GetVendorOrdersRequest.cs using System.Collections.Generic; using Newtonsoft.Json; using RestSharp; namespace Reggora.Api.Requests.Vendor.Order { public class GetVendorOrdersRequest : ReggoraRequest { public GetVendorOrdersRequest(uint offset, uint limit, string status) : base("vendor/orders", Method.GET) { AddParameter("offset", offset, ParameterType.QueryString); AddParameter("limit", limit, ParameterType.QueryString); if(status != null || status != "") { AddParameter("status", status, ParameterType.QueryString); } } public new Response Execute(IRestClient client) { return Execute<Response>(client); } public class Response { [JsonProperty("data")] public NestedData Data { get; set; } [JsonProperty("status")] public int Status { get; set; } public class NestedData { [JsonProperty("count")] public uint Count { get; set; } [JsonProperty("orders")] public List<GetVendorOrderRequest.Response.Order> Orders { get; set; } } } } }<file_sep>/Reggora.Api/Requests/Lender/App/SendPaymentAppRequest.cs using Newtonsoft.Json; using Reggora.Api.Entity; using Reggora.Api.Util; using RestSharp; namespace Reggora.Api.Requests.Lender.App { public class SendPaymentAppRequest : ReggoraRequest { public SendPaymentAppRequest(PaymentApp app) : base("lender/consumer/payment", Method.POST) { AddJsonBody(new Request { ConsumerEmail = app.ConsumerEmail, OrderId = app.OrderId, UserType = PaymentApp.UserTypeToString(app.UsrType), PaymentType = PaymentApp.PaymentTypeToString(app.PaymenType), Amount = app.Amount, FirstName = app.FirstName, LastName = app.LastName, Paid = app.Paid }); } public new Response Execute(IRestClient client) { return Execute<Response>(client); } public class Response { [JsonProperty("data")] public string Data { get; set; } [JsonProperty("error")] public string Error { get; set; } [JsonProperty("status")] public int Status { get; set; } } public class Request { [JsonProperty("consumer_email")] public string ConsumerEmail { get; set; } [JsonProperty("order_id")] public string OrderId { get; set; } [JsonProperty("user_type")] public string UserType { get; set; } [JsonProperty("payment_type")] public string PaymentType { get; set; } [JsonProperty("amount")] public float Amount { get; set; } [JsonProperty("firstname")] public string FirstName { get; set; } [JsonProperty("lastname")] public string LastName { get; set; } [JsonProperty("paid")] public bool Paid { get; set; } } } } <file_sep>/Reggora.Api/Requests/Vendor/Order/AcceptVendorOrderRequest.cs using RestSharp; namespace Reggora.Api.Requests.Vendor.Order { public class AcceptVendorOrderRequest : ReggoraRequest { public AcceptVendorOrderRequest(string orderId) : base("vendor/order/{order_id}/accept", Method.PUT) { AddParameter("order_id", orderId, ParameterType.UrlSegment); } } }<file_sep>/Reggora.Api/Requests/Vendor/Conversation/GetConversationRequest.cs using System.Collections.Generic; using Newtonsoft.Json; using RestSharp; namespace Reggora.Api.Requests.Vendor.Conversation { public class GetConversationRequest : ReggoraRequest { public GetConversationRequest(string conversationId) : base("vendor/conversation/{conversation_id}", Method.GET) { AddParameter("conversation_id", conversationId, ParameterType.UrlSegment); } public new Response Execute(IRestClient client) { return Execute<Response>(client); } public class Response { [JsonProperty("data")] public NestedData Data { get; set; } [JsonProperty("status")] public int Status { get; set; } public class NestedData { [JsonProperty("conversation")] public Conversation Conversation { get; set; } } public class Conversation { [JsonProperty("id")] public string Id { get; set; } [JsonProperty("vendor_users")] public List<User> VendorUsers { get; set; } [JsonProperty("lender_users")] public List<User> LenderUsers { get; set; } [JsonProperty("messages")] public List<Msg> Messages { get; set; } public class User { [JsonProperty("id")] public string Id { get; set; } [JsonProperty("name")] public string Name { get; set; } } public class Msg { [JsonProperty("id")] public string Id { get; set; } [JsonProperty("message")] public string Message { get; set; } [JsonProperty("sender")] public User Sender { get; set; } [JsonProperty("sent_time")] public string SentTime { get; set; } } } } } }<file_sep>/Reggora.Api/Requests/Vendor/Evault/DeleteDocumentRequest.cs using Newtonsoft.Json; using RestSharp; namespace Reggora.Api.Requests.Vendor.Evault { class DeleteDocumentRequest : ReggoraRequest { public DeleteDocumentRequest(string evaultId, string documentId) : base("vendor/evault/{evault_id}/{document_id}", Method.DELETE) { AddParameter("evault_id", evaultId, ParameterType.UrlSegment); AddParameter("document_id", documentId, ParameterType.UrlSegment); } } } <file_sep>/Reggora.Api/Requests/Lender/Evaults/UploadDocumentRequest.cs using Newtonsoft.Json; using RestSharp; namespace Reggora.Api.Requests.Lender.Evaults { public class UploadDocumentRequest : ReggoraRequest { public UploadDocumentRequest(string evaultId, string filePath) : base("lender/evault", Method.POST) { AddParameter("id", evaultId); AddFile("file", filePath, MimeMapping.MimeUtility.GetMimeMapping(filePath)); } public new Response Execute(IRestClient client) { return Execute<Response>(client); } public class Response { [JsonProperty("data")] public string Data { get; set; } [JsonProperty("status")] public int Status { get; set; } } } } <file_sep>/Reggora.Api/Requests/Lender/Models/Vendor.cs namespace Reggora.Api.Requests.Lender.Models { public class Vendor { public string Id; public string FirmName; public string Email; public string PhoneNumber; public bool AcceptingJobs; public LenderCoverage[] LenderCoverage = { }; } public class LenderCoverage { public int Country; public int State; public int Zip; } }<file_sep>/Reggora.Api/Requests/Lender/Loans/GetLoanRequest.cs using Newtonsoft.Json; using Reggora.Api.Requests.Lender.Models; using RestSharp; using System.Collections.Generic; namespace Reggora.Api.Requests.Lender.Loans { public class GetLoanRequest : ReggoraRequest { public GetLoanRequest(string loanId) : base("lender/loan/{loan_id}", Method.GET) { AddParameter("loan_id", loanId, ParameterType.UrlSegment); } public new Response Execute(IRestClient client) { return Execute<Response>(client); } public class Response { [JsonProperty("data")] public NestedLoan Data { get; set; } [JsonProperty("status")] public int Status { get; set; } public class NestedLoan { [JsonProperty("loan")] public Loan Loan { get; set; } } public class Loan { [JsonProperty("id")] public string Id { get; set; } [JsonProperty("loan_number")] public string LoanNumber { get; set; } [JsonProperty("loan_officer")] public Officer LoanOfficer { get; set; } [JsonProperty("appraisal_type")] public string AppraisalType { get; set; } [JsonProperty("due_date")] public string DueDate { get; set; } [JsonProperty("created")] public string Created { get; set; } [JsonProperty("updated")] public string Updated { get; set; } [JsonProperty("related_order")] public string RelatedOrder { get; set; } [JsonProperty("subject_property_address")] public string SubjectPropertyAddress { get; set; } [JsonProperty("subject_property_city")] public string SubjectPropertyCity { get; set; } [JsonProperty("subject_property_state")] public string SubjectPropertyState { get; set; } [JsonProperty("subject_property_zip")] public string SubjectPropertyZip { get; set; } [JsonProperty("case_number")] public string CaseNumber { get; set; } [JsonProperty("loan_type")] public string LoanType { get; set; } [JsonProperty("consumers")] public List<Consumer> Consumers { get; set; } public class Officer { [JsonProperty("id")] public string Id { get; set; } [JsonProperty("email")] public string Email { get; set; } [JsonProperty("phone_number")] public string PhoneNumber { get; set; } [JsonProperty("firstname")] public string FirstName { get; set; } [JsonProperty("lastname")] public string LastName { get; set; } } } } } }<file_sep>/Reggora.Api/Requests/Lender/Orders/CancelOrderRequest.cs using Reggora.Api.Entity; using RestSharp; namespace Reggora.Api.Requests.Lender.Orders { public class CancelOrderRequest : ReggoraRequest { public CancelOrderRequest(string orderId) : base("lender/order/{order_id}/cancel", Method.DELETE) { AddParameter("order_id", orderId, ParameterType.UrlSegment); } } }<file_sep>/Reggora.Api/Requests/ReggoraRequest.cs using Newtonsoft.Json; using RestSharp; using RestSharp.Serializers.Newtonsoft.Json; using RestRequest = RestSharp.RestRequest; namespace Reggora.Api.Requests { public abstract class ReggoraRequest : RestRequest { protected ReggoraRequest(string resource, Method method) : base(resource, method) { RequestFormat = DataFormat.Json; JsonSerializer = new NewtonsoftJsonSerializer(); } protected T Execute<T>(IRestClient client) where T : new() { var response = client.Execute<T>(this); var fullUrl = client.BuildUri(this); if (response.ErrorException != null) { throw Reggora.RaiseRequestErrorToException(response.StatusCode, response.ErrorException); } return response.Data; } public BasicResponse Execute(IRestClient client) { return Execute<BasicResponse>(client); } public class BasicResponse { [JsonProperty("data")] public string Data { get; set; } [JsonProperty("status")] public int Status { get; set; } } } }<file_sep>/Reggora.Api/Requests/Lender/Models/Consumer.cs using Newtonsoft.Json; namespace Reggora.Api.Requests.Lender.Models { public class Consumer { [JsonProperty("id")] public string Id { get; set; } [JsonProperty("full_name")] public string FullName { get; set; } [JsonProperty("role")] public string Role { get; set; } [JsonProperty("email")] public string Email { get; set; } [JsonProperty("home_phone")] public string HomePhone { get; set; } [JsonProperty("work_phone")] public string WorkPhone { get; set; } [JsonProperty("cell_phone")] public string CellPhone { get; set; } [JsonProperty("is_primary_contact")] public bool IsPrimaryContact { get; set; } } } <file_sep>/Reggora.Api/Requests/Lender/Loans/GetLoanSchemaRequest.cs using System; using System.Collections.Generic; using System.Text; namespace Reggora.Api.Requests.Lender.Loans { public class GetLoanSchemaRequest: ReggoraRequest { public GetLoanSchemaRequest() : base("lender/extended_loan", RestSharp.Method.GET) { } } } <file_sep>/Reggora.Api/Requests/Vendor/Order/EditInspectionDateRequest.cs using System; using System.Collections.Generic; using Newtonsoft.Json; using Reggora.Api.Util; using RestSharp; namespace Reggora.Api.Requests.Vendor.Order { public class EditInspectionDateRequest : ReggoraRequest { public EditInspectionDateRequest(string orderId, DateTime? inspectionDate) : base("vendor/order/{order_id}/set_inspection", Method.PUT) { AddParameter("order_id", orderId, ParameterType.UrlSegment); AddJsonBody(new Request { InspectionDate = Utils.DateToString(inspectionDate) }); } public class Request { [JsonProperty("inspection_date")] public string InspectionDate { get; set; } } } }<file_sep>/Reggora.Api/Requests/Vendor/Order/CompleteInspectionRequest.cs using System; using System.Collections.Generic; using Newtonsoft.Json; using Reggora.Api.Util; using RestSharp; namespace Reggora.Api.Requests.Vendor.Order { public class CompleteInspectionRequest : ReggoraRequest { public CompleteInspectionRequest(string orderId, DateTime? completedAt) : base("vendor/order/{order_id}/complete_inspection", Method.PUT) { AddParameter("order_id", orderId, ParameterType.UrlSegment); AddJsonBody(new Request { CompletedAt = Utils.DateToString(completedAt) }); } public class Request { [JsonProperty("inspection_completed")] public string CompletedAt { get; set; } } } }<file_sep>/Reggora.Api/Requests/Lender/Loans/EditLoanRequest.cs using Newtonsoft.Json; using Reggora.Api.Entity; using Reggora.Api.Util; using RestSharp; using RestSharp.Serializers.Newtonsoft.Json; namespace Reggora.Api.Requests.Lender.Loans { public class EditLoanRequest : ReggoraRequest { public EditLoanRequest(Loan loan) : base("lender/loan/{loan_id}", Method.PUT) { JsonSerializer = new NewtonsoftJsonSerializer(new JsonSerializer() { MissingMemberHandling = MissingMemberHandling.Ignore, NullValueHandling = NullValueHandling.Ignore, DefaultValueHandling = DefaultValueHandling.Include }); AddParameter("loan_id", loan.Id, ParameterType.UrlSegment); var request = new Request(); Utils.DictionaryToJsonFields(request, loan.GetDirtyFieldsForRequest()); AddJsonBody(request); } public class Request { [JsonProperty("loan_number")] public string LoanNumber { get; set; } [JsonProperty("appraisal_type")] public string AppraisalType { get; set; } [JsonProperty("due_date")] public string DueDate { get; set; } [JsonProperty("related_order")] public string RelatedOrder { get; set; } [JsonProperty("subject_property_address")] public string SubjectPropertyAddress { get; set; } [JsonProperty("subject_property_city")] public string SubjectPropertyCity { get; set; } [JsonProperty("subject_property_state")] public string SubjectPropertyState { get; set; } [JsonProperty("subject_property_zip")] public string SubjectPropertyZip { get; set; } [JsonProperty("case_number")] public string CaseNumber { get; set; } [JsonProperty("loan_type")] public string LoanType { get; set; } } } }<file_sep>/Reggora.Api/Authentication/ReggoraJwtAuthenticator.cs using RestSharp; using RestSharp.Authenticators; namespace Reggora.Api.Authentication { public class ReggoraJwtAuthenticator : IAuthenticator { private readonly string _authToken; private readonly string _integrationToken; public ReggoraJwtAuthenticator(string integrationToken, string authToken) { _integrationToken = integrationToken; _authToken = authToken; } public void Authenticate(IRestClient client, IRestRequest request) { request.AddParameter("Authorization", $"Bearer {_authToken}", ParameterType.HttpHeader); request.AddParameter("integration", _integrationToken, ParameterType.HttpHeader); } } }<file_sep>/Reggora.Api/Requests/Lender/Evaults/UploadPSRequest.cs using Newtonsoft.Json; using RestSharp; namespace Reggora.Api.Requests.Lender.Evaults { public class UploadPSRequest : ReggoraRequest { public UploadPSRequest(string orderId, string filePath, string documentName = null) : base("lender/p_and_s", Method.POST) { AddParameter("id", orderId); AddParameter("document_name", documentName); AddFile("file", filePath, MimeMapping.MimeUtility.GetMimeMapping(filePath)); } public new Response Execute(IRestClient client) { return Execute<Response>(client); } public class Response { [JsonProperty("data")] public string Data { get; set; } [JsonProperty("status")] public int Status { get; set; } } } } <file_sep>/Reggora.Api/Exceptions/ReggoraException.cs using System; using System.Runtime.Serialization; namespace Reggora.Api.Exceptions { public class ReggoraException : ApplicationException { public ReggoraException() { } protected ReggoraException(SerializationInfo info, StreamingContext context) : base(info, context) { } public ReggoraException(string message) : base(message) { } public ReggoraException(string message, Exception innerException) : base(message, innerException) { } } }<file_sep>/Reggora.Api/Requests/Lender/App/SendSchedulingAppRequest.cs using Newtonsoft.Json; using RestSharp; using System.Collections.Generic; namespace Reggora.Api.Requests.Lender.App { class SendSchedulingAppRequest : ReggoraRequest { public SendSchedulingAppRequest(List<string> consumerEmails, string orderId) : base("lender/consumer/scheduling", Method.POST) { AddJsonBody(new Request { ConsumerEmails = consumerEmails, OrderId = orderId }); } public new Response Execute(IRestClient client) { return Execute<Response>(client); } public class Response { [JsonProperty("data")] public string Data { get; set; } [JsonProperty("error")] public string Error { get; set; } [JsonProperty("status")] public int Status { get; set; } } public class Request { [JsonProperty("consumer_emails")] public List<string> ConsumerEmails { get; set; } [JsonProperty("order_id ")] public string OrderId { get; set; } } } } <file_sep>/Reggora.Api/Requests/Lender/Products/DeleteProductRequest.cs using Newtonsoft.Json; using RestSharp; namespace Reggora.Api.Requests.Lender.Products { public class DeleteProductRequest : ReggoraRequest { public DeleteProductRequest(string productId) : base("lender/product/{product_id}", Method.DELETE) { AddParameter("product_id", productId, ParameterType.UrlSegment); } public class Response { [JsonProperty("data")] public string Data { get; set; } [JsonProperty("status")] public int Status { get; set; } } } }<file_sep>/Reggora.Api/Storage/Storage.cs using System.Collections.Generic; using Reggora.Api.Util; namespace Reggora.Api.Storage { public abstract class Storage<T, C> where T : Entity.Entity { public ApiClient<C> Api { get; private set; } public readonly IDictionary<string, T> Known; public bool Dirty = false; public Storage() { Known = new EventEmittingDictionary<string, T>(() => Dirty = true); } public Storage(ApiClient<C> api) { Known = new EventEmittingDictionary<string, T>(() => Dirty = true); UseClient(api); } public void UseClient(ApiClient<C> api) { Api = api; } public abstract T Get(string id); public void Sync() { foreach (var entity in Known.Values) { if (entity.Dirty()) { Save(entity); } } } public abstract void Save(T entity); public void Clear(string id) { Known.Remove(id); } public void Clear() { Known.Clear(); } public void Clean() { Dirty = false; } } public class StorageFactory { public static T Create<T, E, C>() where E : Entity.Entity where T : Storage<E, C>, new() { return new T(); } } }<file_sep>/Reggora.Api/Requests/Vendor/Order/CounterOfferRequest.cs using System; using System.Collections.Generic; using Newtonsoft.Json; using Reggora.Api.Util; using RestSharp; namespace Reggora.Api.Requests.Vendor.Order { public class CounterOfferRequest : ReggoraRequest { public CounterOfferRequest(string orderId, DateTime? dueDate, float? fee) : base("vendor/order/{order_id}/counter", Method.PUT) { AddParameter("order_id", orderId, ParameterType.UrlSegment); AddJsonBody(new Request { DueDate = Utils.DateToString(dueDate), Fee = fee }); } public class Request { [JsonProperty("due_date")] public string DueDate { get; set; } [JsonProperty("fee")] public float? Fee { get; set; } } } }<file_sep>/Reggora.Api/Requests/Lender/Orders/GetOrderRequest.cs using System.Collections.Generic; using Newtonsoft.Json; using Reggora.Api.Requests.Lender.Models; using RestSharp; namespace Reggora.Api.Requests.Lender.Orders { public class GetOrderRequest : ReggoraRequest { public GetOrderRequest(string orderId) : base("lender/order/{order_id}", Method.GET) { AddParameter("order_id", orderId, ParameterType.UrlSegment); } public new Response Execute(IRestClient client) { return Execute<Response>(client); } public class Response { [JsonProperty("data")] public NestedOrder Data { get; set; } [JsonProperty("status")] public int Status { get; set; } public class NestedOrder { [JsonProperty("order")] public Order Order { get; set; } } public class Order { [JsonProperty("id")] public string Id { get; set; } [JsonProperty("status")] public string Status { get; set; } [JsonProperty("priority")] public string Priority { get; set; } [JsonProperty("due_date")] public string DueDate { get; set; } [JsonProperty("inspected_date")] public string InspectedDate { get; set; } [JsonProperty("accepted_vendor")] public Vendor AcceptedVendor { get; set; } [JsonProperty("created")] public string Created { get; set; } [JsonProperty("allocation_mode")] public string AllocationMode { get; set; } [JsonProperty("requested_vendors")] public List<Vendor> Vendors { get; set; } [JsonProperty("inspection_complete")] public bool InspectionComplete { get; set; } [JsonProperty("products")] public List<Product> Products { get; set; } [JsonProperty("loan_file")] public Loan LoanFile { get; set; } [JsonProperty("consumers")] public List<Consumer> Consumers { get; set; } public class Loan { [JsonProperty("id")] public string Id { get; set; } [JsonProperty("loan_number")] public string LoanNumber { get; set; } [JsonProperty("subject_property_address")] public string SubjectPropertyAddress { get; set; } [JsonProperty("subject_property_city")] public string SubjectPropertyCity { get; set; } [JsonProperty("subject_property_state")] public string SubjectPropertyState { get; set; } [JsonProperty("subject_property_zip")] public string SubjectPropertyZip { get; set; } } public class Vendor { [JsonProperty("id")] public string Id { get; set; } [JsonProperty("firm_name")] public string FirmName { get; set; } [JsonProperty("accepting_jobs")] public bool AcceptingJobs { get; set; } [JsonProperty("email")] public string Email { get; set; } [JsonProperty("name")] public string Name { get; set; } [JsonProperty("phone")] public string Phone { get; set; } } public class Product { [JsonProperty("id")] public string Id { get; set; } [JsonProperty("product_name")] public string ProductName { get; set; } [JsonProperty("amount")] public string Amount { get; set; } } } } } }<file_sep>/Reggora.Api/Requests/Lender/Models/Document.cs namespace Reggora.Api.Requests.Lender.Models { public class Document { public string Id; public string FileName; } }<file_sep>/Reggora.Api/Exceptions/AuthorizationException.cs using System; namespace Reggora.Api.Exceptions { public class AuthorizationException : ReggoraException { public AuthorizationException(Exception innerError) : base("Unauthorized -- Your Bearer Token is invalid.", innerError) { } public AuthorizationException(string message, Exception innerError) : base(message, innerError) { } } }<file_sep>/ReggoraLenderApi.Test/ReggoraTest.cs using Microsoft.VisualStudio.TestTools.UnitTesting; using Reggora.Api.Entity; using Reggora.Api; using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.IO; using System.Reflection; using System.Text; namespace ReggoraLenderApi.Test { [TestClass] public class ReggoraTest { private Lender lender; [TestInitialize] public void Initialize() { if (lender == null) { lender = new Lender(Config.GetProperty("lender.token", "")); Console.WriteLine("Authenticating..."); lender.Authenticate(Config.GetProperty("lender.email", ""), Config.GetProperty("lender.password", "")); } } public string RandomString(int size, bool lowerCase) { StringBuilder builder = new StringBuilder(); Random random = new Random(); char ch; for (int i = 0; i < size; i++) { ch = Convert.ToChar(Convert.ToInt32(Math.Floor(26 * random.NextDouble() + 65))); builder.Append(ch); } if (lowerCase) return builder.ToString().ToLower(); return builder.ToString(); } public string RandomNumber(int startNum = 100000, int endNum = 999999) { Random rnd = new Random(); int rand = rnd.Next(startNum, endNum); return rand.ToString(); } // Test Loan Requests public string CreateLoan(bool refresh = false) { if (!refresh && SampleObjects._loan != null) { SampleObjects._loan = lender.Loans.Get(SampleObjects._loan.Id); return SampleObjects._loan.Id; } Loan loan = new Loan() { Number = RandomString(7, false), Type = "FHA", Due = DateTime.Now.AddYears(1), PropertyAddress = "100 Mass Ave", PropertyCity = "Boston", PropertyState = "MA", PropertyZip = "02192", CaseNumber = "10029MA", AppraisalType = "Refinance" }; try { string createdLoanId = lender.Loans.Create(loan); SampleObjects._loan = lender.Loans.Get(createdLoanId); return createdLoanId; } catch (Exception e) { throw new Exception(e.ToString()); } } [TestMethod] public void AA_TestCreateLoan() { Console.WriteLine("Testing Loan Requests..."); string createdLoanId = CreateLoan(); Assert.IsNotNull( createdLoanId, "Expected an ID of new Loan"); } [TestMethod] public void AB_TestGetLoans() { var loans = lender.Loans.All(); Assert.IsInstanceOfType(loans, typeof(List<Loan>)); } [TestMethod] public void AC_TestGetLoan() { string expectedId = CreateLoan() ?? "5d56720d6dcf6d000d6e902c"; Loan loan = lender.Loans.Get(expectedId); Assert.AreEqual(expectedId, loan.Id, String.Format("Tried to get loan by ID:'{0}'; Actual ID of loan: {1}", expectedId, loan.Id)); } [TestMethod] public void AD_TestEditLoan() { CreateLoan(); Loan testLoan = SampleObjects._loan; string newLoanNumber = RandomString(7, false); testLoan.Number = newLoanNumber; try { string updatedLoanId = lender.Loans.Edit(testLoan); testLoan = lender.Loans.Get(updatedLoanId); SampleObjects._loan = testLoan; Assert.AreEqual(testLoan.Number, newLoanNumber, String.Format("Expected Loan Number:'{0}'; Loan Number: {1}", newLoanNumber, testLoan.Number)); } catch (Exception e) { throw new Exception(e.ToString()); } } [TestMethod] public void AE_TestDeleteLoan() { string deleteId = CreateLoan() ?? "5d56720d6dcf6d000d6e902c"; string response = lender.Loans.Delete(deleteId); SampleObjects._loan = null; Assert.IsNotNull(response, String.Format("Expected Success message of Deletion, Actual: {0}", response)); } // Test Order Requests public string CreateOrder(bool refresh = false) { string loanId = CreateLoan(true); string productId = CreateProduct(true); if (!refresh && SampleObjects._order != null) { SampleObjects._order = lender.Orders.Get(SampleObjects._order.Id); return SampleObjects._order.Id; } List<string> products = new List<string>(); products.Add(productId); Order order = new Order() { Allocation = Order.AllocationMode.Automatic, Loan = loanId, Priority = Order.PriorityType.Normal, ProductIds = products, Due = DateTime.Now.AddYears(1) }; try { string createdOrderId = lender.Orders.Create(order); SampleObjects._order = lender.Orders.Get(createdOrderId); return createdOrderId; } catch (Exception e) { throw new Exception(e.ToString()); } } [TestMethod] public void BA_TestCreateOrder() { Console.WriteLine("Testing Order Requests..."); string createdOrderId = CreateOrder(); Assert.IsNotNull(createdOrderId, "Expected an ID of new Order"); } [TestMethod] public void BB_TestGetOrders() { var orders = lender.Orders.All(); Assert.IsInstanceOfType(orders, typeof(List<Order>)); } [TestMethod] public void BC_TestGetOrder() { Console.WriteLine("Testing Get a Order..."); string expectedId = CreateOrder() ?? "5d5bc544586cbb000f5e171f"; Order order = lender.Orders.Get(expectedId); Assert.AreEqual(expectedId, order.Id, String.Format("Tried to get order by ID:'{0}'; Actual ID of order: {1}", expectedId, order.Id)); } [TestMethod] public void BD_TestEditOrder() { CreateOrder(); Order testOrder = SampleObjects._order; testOrder.Priority = Order.PriorityType.Rush; try { string updatedOrderId = lender.Orders.Edit(testOrder); testOrder = lender.Orders.Get(updatedOrderId); SampleObjects._order = testOrder; Assert.AreEqual(testOrder.Priority, Order.PriorityType.Rush); } catch (Exception e) { throw new Exception(e.ToString()); } } [TestMethod] public void BE_TestPlaceOrderOnHold() { string orderId = CreateOrder() ?? "5d5bc544586cbb000f5e171f"; string reason = "I'd like to wait to start this order."; string response = lender.Orders.OnHold(orderId, reason); Assert.IsNotNull(response, String.Format("Expected Success message of Placing Order On Hold, Actual: {0}", response)); } [TestMethod] public void BF_RemoveOrderHold() { string orderId = CreateOrder() ?? "5d5bc544586cbb000f5e171f"; string response = lender.Orders.RemoveHold(orderId); Assert.IsNotNull(response, String.Format("Expected Success message of Removing Order Hold, Actual: {0}", response)); } [TestMethod] public void BG_TestGetSubmissions() { string orderId = CreateOrder() ?? "5d5bc544586cbb000f5e171f"; var submissions = lender.Orders.Submissions(orderId); Assert.IsInstanceOfType(submissions, typeof(List<Submission>)); } [TestMethod] public void BH_TestDownloadSubmissionDoc() { string orderId = "5d38b049a27621000abd28ed"; uint version = 1; string reportType = "pdf_report"; string downloadPath = null; bool response = lender.Orders.DownloadSubmissionDoc(orderId, version, reportType, downloadPath); Assert.IsTrue(response); } [TestMethod] public void BI_TestCancelOrder() { string cancelId = CreateOrder() ?? "5d5bc544586cbb000f5e171f"; string response = lender.Orders.Cancel(cancelId); SampleObjects._order = null; Assert.IsNotNull(response, String.Format("Expected Success message of Deletion, Actual: {0}", response)); } //Test Product Requests public string CreateProduct(bool refresh = false) { if (!refresh && SampleObjects._product != null) { SampleObjects._product = lender.Products.Get(SampleObjects._product.Id); return SampleObjects._product.Id; } Product product = new Product() { ProductName = "Full Appraisal" + RandomString(3, true), Amount = 100.00f, InspectionType = Product.Inspection.Interior, RequestForms = "1004MC, BPO" }; try { string createdProductId = lender.Products.Create(product); SampleObjects._product = lender.Products.Get(createdProductId); return createdProductId; } catch (Exception e) { throw new Exception(e.ToString()); } } [TestMethod] public void CA_TestCreateProduct() { Console.WriteLine("Testing Product Requests..."); string createdProductId = CreateProduct(); Assert.IsNotNull(createdProductId, "Expected an ID of new Product"); } [TestMethod] public void CB_TestGetProducts() { var products = lender.Products.All(); Assert.IsInstanceOfType(products, typeof(List<Product>)); } [TestMethod] public void CC_TestGetProduct() { string expectedId = CreateProduct() ?? "5d4bd10434e305000c322368"; Product product = lender.Products.Get(expectedId); Assert.AreEqual(expectedId, product.Id, String.Format("Tried to get product by ID:'{0}'; Actual ID of product: {1}", expectedId, product.Id)); } [TestMethod] public void CD_TestEditProduct() { CreateProduct(); Product testProduct = SampleObjects._product; string newProductName = RandomString(7, false); testProduct.ProductName = newProductName; try { string updatedProductId = lender.Products.Edit(testProduct); testProduct = lender.Products.Get(updatedProductId); SampleObjects._product = testProduct; Assert.AreEqual(testProduct.ProductName, newProductName, String.Format("Expected Product Name:'{0}'; Actual Product Name: {1}", newProductName, testProduct.ProductName)); } catch (Exception e) { throw new Exception(e.ToString()); } } [TestMethod] public void CE_TestDeleteProduct() { string deleteId = CreateProduct() ?? "5d4bd10434e305000c322368"; string response = lender.Products.Delete(deleteId); SampleObjects._product = null; Assert.IsNotNull(response, String.Format("Expected Success message of Deletion, Actual: {0}", response)); } // Test User Requests public string CreateUser() { if (SampleObjects._user != null) { SampleObjects._user = lender.Users.Get(SampleObjects._user.Id); return SampleObjects._user.Id; } User user = new User() { Email = RandomString(4, true) + "@test.com", PhoneNumber = RandomNumber(), FirstName = "Fake", LastName = "Person" + RandomString(3, true), NmlsId = "MA", Role = "Admin" }; try { string createdUserId = lender.Users.Create(user); SampleObjects._user = lender.Users.Get(createdUserId); return createdUserId; } catch (Exception e) { throw new Exception(e.ToString()); } } [TestMethod] public void DA_TestCreateUser() { Console.WriteLine("Testing User Requests..."); string createdLoanId = CreateUser(); Assert.IsNotNull(createdLoanId, "Expected an ID of new User"); } [TestMethod] public void DB_TestGetUsers() { var users = lender.Users.All(); Assert.IsInstanceOfType(users, typeof(List<User>)); } [TestMethod] public void DC_TestGetUser() { string expectedId = CreateUser() ?? "5d5aa161cf56d4000de82465"; User user = lender.Users.Get(expectedId); Assert.AreEqual(expectedId, user.Id, String.Format("Tried to get user by ID:'{0}'; Actual ID of user: {1}", expectedId, user.Id)); } [TestMethod] public void DD_TestEditUser() { CreateUser(); User testUser = SampleObjects._user; string newPhoneNumber = RandomNumber(); testUser.PhoneNumber = newPhoneNumber; try { string updatedUserId = lender.Users.Edit(testUser); testUser = lender.Users.Get(updatedUserId); SampleObjects._user = testUser; Assert.AreEqual(testUser.PhoneNumber, newPhoneNumber, String.Format("Expected User Phone Number:'{0}'; Actual Phone Number: {1}", newPhoneNumber, testUser.PhoneNumber)); } catch (Exception e) { throw new Exception(e.ToString()); } } [TestMethod] public void DE_TestDeleteUser() { string deleteId = CreateUser() ?? "5d5aa161cf56d4000de82465"; string response = lender.Users.Delete(deleteId); SampleObjects._user = null; Assert.IsNotNull(response, String.Format("Expected Success message of Deletion, Actual: {0}", response)); } [TestMethod] public void DF_TestInviteUser() { User user = new User() { Email = RandomString(4, false) + "@test.com", PhoneNumber = RandomNumber(), FirstName = "Fake", LastName = "Person" + RandomString(3, true), Role = "Admin" }; try { string response = lender.Users.Invite(user); Assert.IsNotNull(response, String.Format("Expected Success message of Invitation, Actual: {0}", response)); } catch (Exception e) { throw new Exception(e.ToString()); } } //Test Vendor Requests public string CreateVendor() { if(SampleObjects._vendor != null) { return SampleObjects._vendor.Id; } Vendr vendor = new Vendr() { FirmName = "Appraisal Firm" + RandomNumber(1000, 10000), Email = "vendor_" + RandomString(4, true) + "@test.com", Phone = RandomNumber(), FirstName = "Fake", LastName = "Vendor" + RandomString(3, true) }; try { string createdVendorId = lender.Vendors.Create(vendor); SampleObjects._vendor = lender.Vendors.Get(createdVendorId); return createdVendorId; } catch (Exception e) { throw new Exception(e.ToString()); } } [TestMethod] public void EA_TestCreateVendor() { Console.WriteLine("Testing Vendor Requests..."); string createdVendorId = CreateVendor(); Assert.IsNotNull(createdVendorId, "Expected an ID of new Vendor"); } [TestMethod] public void EB_TestGetVendors() { var vendors = lender.Vendors.All(); Assert.IsInstanceOfType(vendors, typeof(List<Vendr>)); } [TestMethod] public void EC_TestGetVendor() { string expectedId = CreateVendor() ?? "5d5b714c586cbb000d3eecb5"; Vendr vendor = lender.Vendors.Get(expectedId); Assert.AreEqual(expectedId, vendor.Id, String.Format("Tried to get vendor by ID:'{0}'; Actual ID of vendor: {1}", expectedId, vendor.Id)); } [TestMethod] public void EB_TestGetVendorsByZones() { List<string> zones = new List<string> {}; var vendors = lender.Vendors.GetByZone(zones); Assert.IsInstanceOfType(vendors, typeof(List<Vendr>)); } [TestMethod] public void EC_TestGetVendorsByBranch() { string branchId = "5b58c8861e5f59000d4542af"; var vendors = lender.Vendors.GetByBranch(branchId); Assert.IsInstanceOfType(vendors, typeof(List<Vendr>)); } [TestMethod] public void ED_TestEditVendor() { CreateVendor(); Vendr testVendor = SampleObjects._vendor; string newPhone = RandomNumber(); testVendor.Phone = newPhone; try { string updatedVendorId = lender.Vendors.Edit(testVendor); testVendor = lender.Vendors.Get(updatedVendorId); SampleObjects._vendor = testVendor; Assert.AreEqual(testVendor.Phone, newPhone, String.Format("Expected Phone number:'{0}'; Actual Phone number: {1}", newPhone, testVendor.Phone)); } catch (Exception e) { throw new Exception(e.ToString()); } } [TestMethod] public void EE_TestDeleteVendor() { string deleteId = CreateVendor() ?? "5d5b714c586cbb000d3eecb5"; string response = lender.Vendors.Delete(deleteId); SampleObjects._vendor = null; Assert.IsNotNull(response, String.Format("Expected Success message of Deletion, Actual: {0}", response)); } // Schedule and Payment App Requests [TestMethod] public void FA_TestSendPaymentApp() { CreateUser(); CreateOrder(); PaymentApp app = new PaymentApp() { ConsumerEmail = SampleObjects._user.Email, OrderId = SampleObjects._order.Id, UsrType = PaymentApp.UserType.Manual, PaymenType = PaymentApp.PaymentType.Manual, Amount = 100.00f, FirstName = "Fake", LastName = "Person" + RandomString(3, true), Paid = false }; try { string response = lender.Apps.SendPaymentApp(app); Assert.IsNotNull(response, String.Format("Expected Success message of Sending Payment , Actual: {0}", response)); } catch (Exception e) { throw new Exception(e.ToString()); } } [TestMethod] public void FB_TestSendSchedulingApp() { CreateUser(); CreateOrder(); string orderId = SampleObjects._order.Id; List<string> consumerEmails = new List<string> { }; consumerEmails.Add(SampleObjects._user.Id); try { string response = lender.Apps.SendSchedulingApp(consumerEmails, orderId); Assert.IsNotNull(response, String.Format("Expected Success message of Sending Scheduling App, Actual: {0}", response)); } catch (Exception e) { throw new Exception(e.ToString()); } } [TestMethod] public void FC_TestConsumerAppLink() { CreateUser(); CreateOrder(); string orderId = SampleObjects._order.Id; string consumerId = SampleObjects._user.Id; PaymentApp.LinkType linkType = PaymentApp.LinkType.Payment; try { string response = lender.Apps.ConsumerAppLink(orderId, consumerId, linkType); Assert.IsNotNull(response, String.Format("Expected Success message of Getting Consumer Application Link, Actual: {0}", response)); } catch (Exception e) { throw new Exception(e.ToString()); } } // Evault Request public string InitEvault(bool refresh = false) { if (!refresh && SampleObjects._evault != null) { return SampleObjects._evault.Id; } try { string staticEvaultId = "5d4d06d6d28c2600109499c5"; SampleObjects._evault = lender.Evaults.Get(staticEvaultId); return SampleObjects._evault.Id; } catch (Exception e) { throw new Exception(e.ToString()); } } public string UploadDocument() { string evaultId = InitEvault(); string path = AppDomain.CurrentDomain.BaseDirectory; string sampleFile = Path.Combine(path, "..\\..\\..\\sample.pdf"); try { string documentId = lender.Evaults.UploadDocument(evaultId, sampleFile); InitEvault(true); return documentId; } catch (Exception e) { throw new Exception(e.ToString()); } } [TestMethod] public void GA_TestGetEvault() { InitEvault(); Assert.IsNotNull(SampleObjects._evault, String.Format("Expected Id of Evault, Actual: {0}", SampleObjects._evault.Id)); } //[TestMethod] //public void GB_TestGetDocument() //{ // try // { // string documentId = UploadDocument(); // string evaultId = SampleObjects._evault.Id; // lender.Evaults.GetDocument(evaultId, documentId); // } catch (Exception e) // { // throw new Exception(e.ToString()); // } //} [TestMethod] public void GC_TestUploadDocument() { string documentId = UploadDocument(); Assert.IsNotNull(documentId, String.Format("Expected Success message of Uploading document, Actual: {0}", documentId)); } [TestMethod] public void GD_TestUploadPS() { string orderId = CreateOrder(); string path = AppDomain.CurrentDomain.BaseDirectory; string sampleFile = Path.Combine(path, "..\\..\\..\\sample.pdf"); try { string response = lender.Evaults.UploadPS(orderId, sampleFile); Assert.IsNotNull(response, String.Format("Expected Success message of Uploading document, Actual: {0}", response)); } catch (Exception e) { throw new Exception(e.ToString()); } } [TestMethod] public void GE_TestDeleteDocument() { string deleteId = UploadDocument(); string evaultId = SampleObjects._evault.Id; string response = lender.Evaults.DeleteDocument(evaultId, deleteId); InitEvault(true); Assert.IsNotNull(response, String.Format("Expected Success message of Deletion, Actual: {0}", response)); } } public class SampleObjects { public static Loan _loan { get; set; } public static Order _order { get; set; } public static Product _product { get; set; } public static User _user { get; set; } public static Vendr _vendor { get; set; } public static Evault _evault { get; set; } } public class Config { public static string ConfigFileName = "example.conf"; private static IReadOnlyDictionary<string, string> KeyValues { get; set; } static Config() { try { string username = Environment.UserName; string fileContents = string.Empty; string path = AppDomain.CurrentDomain.BaseDirectory; if (path != null) { var configFilePath = Path.Combine(path, $"example.{username}.conf"); if (File.Exists(configFilePath)) { fileContents = File.ReadAllText(configFilePath); Console.WriteLine($"Using config at {configFilePath}"); } else { configFilePath = Path.Combine(path, ConfigFileName); if (File.Exists(configFilePath)) { fileContents = File.ReadAllText(configFilePath); Console.WriteLine($"Using config at {configFilePath}"); } } } LoadValues(fileContents); } catch (Exception e) { Console.WriteLine("Error configuring parser"); Console.WriteLine(e.Message); } } private static void LoadValues(string data) { Dictionary<string, string> newDictionairy = new Dictionary<string, string>(); foreach ( string rawLine in data.Split(new[] { "\r\n", "\n", Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries)) { string line = rawLine.Trim(); if (line.StartsWith("#") || !line.Contains("=")) continue; //It's a comment or not a key value pair. string[] splitLine = line.Split('=', 2); string key = splitLine[0].ToLower(); string value = splitLine[1]; if (!newDictionairy.ContainsKey(key)) { newDictionairy.Add(key, value); } } KeyValues = new ReadOnlyDictionary<string, string>(newDictionairy); } public static Boolean GetProperty(string property, bool defaultValue) { try { string d = ReadString(property); if (d == null) return defaultValue; return Convert.ToBoolean(d); } catch { return defaultValue; } } public static int GetProperty(string property, int defaultValue) { try { var value = ReadString(property); if (value == null) return defaultValue; return Convert.ToInt32(value); } catch { return defaultValue; } } public static string GetProperty(string property, string defaultValue) { return ReadString(property) ?? defaultValue; } private static string ReadString(string property) { property = property.ToLower(); if (!KeyValues.ContainsKey(property)) return null; return KeyValues[property]; } } } <file_sep>/Reggora.Api/Storage/Lender/ProductStorage.cs using Reggora.Api.Entity; using Reggora.Api.Requests.Lender.Products; using Reggora.Api.Util; using System.Collections.Generic; namespace Reggora.Api.Storage.Lender { public class ProductStorage : Storage<Product, Api.Lender> { public ProductStorage(Api.Lender api) : base(api) { } public List<Product> All() { var result = new GetProductsRequest().Execute(Api.Client); var fetchedProducts = result.Data.Products; List<Product> products = new List<Product>(); if (result.Status == 200) { for (int i = 0; i < fetchedProducts.Count; i++) { Product tempProduct = new Product(); tempProduct.UpdateFromRequest(Utils.DictionaryOfJsonFields(fetchedProducts[i])); products.Add(tempProduct); } } return products; } public override Product Get(string id) { Known.TryGetValue(id, out var returned); if (returned == null) { var result = new GetProductRequest(id).Execute(Api.Client); if (result.Status == 200) { returned = new Product(); returned.UpdateFromRequest(Utils.DictionaryOfJsonFields(result.Data.Product)); Known.Add(returned.Id, returned); } } return returned; } public override void Save(Product product) { } public string Create(Product product) { string response = null; var result = new CreateProductRequest(product).Execute(Api.Client); if (result.Status == 200) { response = result.Data; product.Clean(); } return response; } public string Edit(Product product) { string response = null; var result = new EditProductRequest(product).Execute(Api.Client); if (result.Status == 200) { response = result.Data; product.Clean(); } return response; } public string Delete(string id) { string response = null; var result = new DeleteProductRequest(id).Execute(Api.Client); if (result.Status == 200) { response = result.Data; } return response; } } } <file_sep>/Reggora.Api/Entity/Entity.cs using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using Reggora.Api.Requests; using Reggora.Api.Storage; using Reggora.Api.Util; namespace Reggora.Api.Entity { public abstract class Entity { public readonly Dictionary<string, object> Fields = new Dictionary<string, object>(); public readonly List<string> DirtyFields = new List<string>(); public bool Dirty() { return DirtyFields.Any(); } public void Clean() { DirtyFields.Clear(); } public void UpdateFromRequest(Dictionary<string, dynamic> fields) { foreach (KeyValuePair<string, dynamic> entry in fields) { if (Fields.TryGetValue(entry.Key, out var field)) { // do any conversion/casting from storage to object form (string -> date time) var converted = field.GetType() .GetMethod("ConvertIncoming", BindingFlags.Public | BindingFlags.Instance) ?.Invoke(field, new object[] {entry.Value}); var fieldValue = field.GetType() .GetField("_value", BindingFlags.NonPublic | BindingFlags.Instance); try { // set the property on the field using reflection because we have no way to cast to a EntityField<dynamic> at compile time fieldValue?.SetValue(field, converted); } catch (ArgumentException e) { throw new InvalidCastException( $"Cannot cast '{entry.Value.GetType()}' to {fieldValue?.FieldType}!"); } } } } public Dictionary<string, dynamic> GetDirtyFieldsForRequest() { var dictionary = new Dictionary<string, dynamic>(); foreach (var name in DirtyFields) { var field = Fields[name]; // get the property on the field using reflection because we have no way to cast to a EntityField<dynamic> at compile time var fieldValue = field.GetType() .GetField("_value", BindingFlags.NonPublic | BindingFlags.Instance); // do any conversion/casting from storage to object form (date time -> string) var converted = field.GetType() .GetMethod("ConvertOutgoing", BindingFlags.Public | BindingFlags.Instance)?.Invoke(Fields[name], new[] {fieldValue?.GetValue(field)}); dictionary.Add(name, converted); } return dictionary; } protected void BuildField<T>(ref EntityField<T> field, string name) { field = new EntityField<T>(name, propertyName => DirtyFields.Add(propertyName)); Fields.Add(name, field); } protected void BuildField<T>(ref EntityField<T> field, string conversionType, string name) { field = new EntityField<T>(name, conversionType, propertyName => DirtyFields.Add(propertyName)); Fields.Add(name, field); } protected void BuildRelationship<E>(ref EntityRelationship<E> relationship) where E : Entity, new() { relationship = new EntityRelationship<E>(new E()); } protected void BuildManyRelationship<E, C, S>(ref EntityManyRelationship<E, C, S> relationship) where E : Entity where C : ApiClient<C> where S : Storage<E, C>, new() { relationship = new EntityManyRelationship<E, C, S>(); } } }<file_sep>/Reggora.Api/Requests/Lender/Vendors/GetVendorRequest.cs using System.Collections.Generic; using Newtonsoft.Json; using RestSharp; namespace Reggora.Api.Requests.Lender.Vendors { public class GetVendorRequest : ReggoraRequest { public GetVendorRequest(string vendorId) : base("lender/vendor/{vendor_id}", Method.GET) { AddParameter("vendor_id", vendorId, ParameterType.UrlSegment); } public new Response Execute(IRestClient client) { return Execute<Response>(client); } public class Response { [JsonProperty("data")] public Nested Data { get; set; } [JsonProperty("status")] public int Status { get; set; } public class Nested { [JsonProperty("vendor")] public Vendor Vendor { get; set; } } public class Vendor { [JsonProperty("id")] public string Id { get; set; } [JsonProperty("firm_name")] public string FirmName { get; set; } [JsonProperty("name")] public string Name { get; set; } [JsonProperty("firstname")] public string FirstName { get; set; } [JsonProperty("lastname")] public string LastName { get; set; } [JsonProperty("email")] public string Email { get; set; } [JsonProperty("phone")] public string Phone { get; set; } [JsonProperty("accepting_jobs")] public bool AcceptingJobs { get; set; } [JsonProperty("lender_coverage")] public List<Coverage> LenderCoverage { get; set; } public class Coverage { [JsonProperty("county")] public string Country { get; set; } [JsonProperty("state")] public string State { get; set; } [JsonProperty("zip")] public string Zip { get; set; } } } } } }<file_sep>/Reggora.Api/Requests/Vendor/Order/DownloadSubmissionRequest.cs using System; using System.Collections.Generic; using Newtonsoft.Json; using Reggora.Api.Util; using RestSharp; namespace Reggora.Api.Requests.Vendor.Order { public class DownloadSubmissionRequest : ReggoraRequest { public DownloadSubmissionRequest(string orderId, uint submissionVersion, string documentType) : base( "vendor/submission/{order_id}/{submission_version}/{document_type}", Method.GET) { AddParameter("order_id", orderId, ParameterType.UrlSegment); AddParameter("submission_version", submissionVersion, ParameterType.UrlSegment); AddParameter("document_type", documentType, ParameterType.UrlSegment); } public new Response Execute(IRestClient client) { return Execute<Response>(client); } public byte[] Download(IRestClient client) { return client.DownloadData(this, true); } public class Response { [JsonProperty("error")] public string Error { get; set; } } } }<file_sep>/Reggora.Api/Requests/Lender/Evaults/GetEvaultRequest.cs using Newtonsoft.Json; using RestSharp; using System.Collections.Generic; namespace Reggora.Api.Requests.Lender.Evaults { public class GetEvaultRequest : ReggoraRequest { public GetEvaultRequest(string evaultId) : base("lender/evault/{evault_id}", Method.GET) { AddParameter("evault_id", evaultId, ParameterType.UrlSegment); } public new Response Execute(IRestClient client) { return Execute<Response>(client); } public class Response { [JsonProperty("data")] public Nested Data { get; set; } [JsonProperty("error")] public string Error { get; set; } [JsonProperty("status")] public int Status { get; set; } public class Nested { [JsonProperty("evault")] public Evlt Evault { get; set; } } public class Evlt { [JsonProperty("id")] public string Id { get; set; } [JsonProperty("documents")] public List<Document> Documents { get; set; } public class Document { [JsonProperty("document_id")] public string DocumentId { get; set; } [JsonProperty("document_name")] public string DocumentName { get; set; } [JsonProperty("upload_datetime")] public string UploadedAt { get; set; } } } } } } <file_sep>/Reggora.Api/Requests/Lender/Loans/CreateLoanRequest.cs using Newtonsoft.Json; using Reggora.Api.Entity; using Reggora.Api.Util; using RestSharp; namespace Reggora.Api.Requests.Lender.Loans { public class CreateLoanRequest : ReggoraRequest { public CreateLoanRequest(Loan loan) : base("lender/loan", Method.POST) { AddJsonBody(new Request { LoanNumber = loan.Number.ToString(), AppraisalType = loan.Type, DueDate = Utils.DateToString(loan.Due), SubjectPropertyAddress = loan.PropertyAddress, SubjectPropertyCity = loan.PropertyCity, SubjectPropertyState = loan.PropertyState, SubjectPropertyZip = loan.PropertyZip, CaseNumber = loan.Number.ToString(), LoanType = loan.Type }); } public class Request { [JsonProperty("loan_number")] public string LoanNumber { get; set; } [JsonProperty("appraisal_type")] public string AppraisalType { get; set; } [JsonProperty("due_date")] public string DueDate { get; set; } [JsonProperty("related_order")] public string RelatedOrder { get; set; } [JsonProperty("subject_property_address")] public string SubjectPropertyAddress { get; set; } [JsonProperty("subject_property_city")] public string SubjectPropertyCity { get; set; } [JsonProperty("subject_property_state")] public string SubjectPropertyState { get; set; } [JsonProperty("subject_property_zip")] public string SubjectPropertyZip { get; set; } [JsonProperty("case_number")] public string CaseNumber { get; set; } [JsonProperty("loan_type")] public string LoanType { get; set; } } } }<file_sep>/Reggora.Api/ApiClient.cs using RestSharp; namespace Reggora.Api { public abstract class ApiClient<T> { protected readonly string IntegrationToken; public readonly IRestClient Client; public ApiClient(string integrationToken) { IntegrationToken = integrationToken; Client = new RestClient(Reggora.BaseUrl); } public abstract T Authenticate(string email, string password); } }<file_sep>/Reggora.Api/Exceptions/BadRequestException.cs using System; namespace Reggora.Api.Exceptions { public class BadRequestException : ReggoraException { public BadRequestException(Exception innerError) : base("Bad Request -- Your request is invalid.", innerError) { } public BadRequestException(string message, Exception innerError) : base(message, innerError) { } } }<file_sep>/Reggora.Api/Requests/Vendor/VendorAuthenticateRequest.cs namespace Reggora.Api.Requests.Vendor { public class VendorAuthenticateRequest : AuthenticateRequest { public VendorAuthenticateRequest(string username, string password) : base("vendor", username, password) { } } }<file_sep>/Reggora.Api/Util/EventEmittingDictionary.cs using System.Collections.Generic; namespace Reggora.Api.Util { public class EventEmittingDictionary<K, V> : Dictionary<K, V> { public delegate void DictionaryChanged(); private readonly DictionaryChanged _modifyCallback; public EventEmittingDictionary(DictionaryChanged modifyCallback) { _modifyCallback = modifyCallback; } public new void Add(K key, V value) { base.Add(key, value); _modifyCallback?.Invoke(); } public new void Remove(K key) { base.Remove(key); _modifyCallback?.Invoke(); } public new void Clear() { base.Clear(); _modifyCallback?.Invoke(); } } }<file_sep>/Reggora.Api/Requests/Lender/Products/CreateProductRequest.cs using System.Collections.Generic; using Newtonsoft.Json; using Reggora.Api.Entity; using RestSharp; namespace Reggora.Api.Requests.Lender.Products { public class CreateProductRequest : ReggoraRequest { public CreateProductRequest(Product product) : base("lender/product", Method.POST) { AddJsonBody(new Request { Name = product.ProductName, Amount = product.Amount.ToString("N2"), Inspection = Product.InspectionToString(product.InspectionType), RequestedForms = product.RequestForms }); } public class Request { [JsonProperty("product_name")] public string Name { get; set; } [JsonProperty("amount")] public string Amount { get; set; } [JsonProperty("inspection_type")] public string Inspection { get; set; } [JsonProperty("requested_forms")] public string RequestedForms { get; set; } } } }<file_sep>/Reggora.Api/Requests/Vendor/Order/DenyOrderRequest.cs using Newtonsoft.Json; using RestSharp; namespace Reggora.Api.Requests.Vendor.Order { public class DenyOrderRequest : ReggoraRequest { public DenyOrderRequest(string orderId, string denyReason) : base("vendor/order/{order_id}/deny", Method.PUT) { AddParameter("order_id", orderId, ParameterType.UrlSegment); AddJsonBody(new Request { DenyReason = denyReason }); } public class Request { [JsonProperty("deny_reason")] public string DenyReason { get; set; } } } }<file_sep>/Reggora.Api/Requests/Lender/Models/AuthorizationRequest.cs using Newtonsoft.Json; namespace Reggora.Api.Requests.Lender.Models { public class AuthorizationRequest { [JsonProperty("username")] public string Username; [JsonProperty("password")] public string Password; } }<file_sep>/Reggora.Api/Requests/Lender/Loans/CreateExtendedLoanRequest.cs using Newtonsoft.Json; using System; using System.Collections.Generic; using System.Text; namespace Reggora.Api.Requests.Lender.Loans { public class CreateExtendedLoanRequest : ReggoraRequest { public CreateExtendedLoanRequest(Dictionary<string, object> loanParams) : base("lender/extended_loan", RestSharp.Method.POST) { AddJsonBody(new Request { Loan = loanParams }); } public class Request { [JsonProperty("loan")] public Dictionary<string, object> Loan { get; set; } } } } <file_sep>/Reggora.Api/Storage/Lender/UserStorage.cs using Reggora.Api.Entity; using Reggora.Api.Requests.Lender.Users; using Reggora.Api.Util; using System.Collections.Generic; namespace Reggora.Api.Storage.Lender { public class UserStorage : Storage<User, Api.Lender> { public UserStorage(Api.Lender api) : base(api) { } public string Create(User user) { string response = null; var result = new CreateUserRequest(user).Execute(Api.Client); if (result.Status == 200) { response = result.Data; user.Clean(); } return response; } public List<User> All() { var result = new GetUsersRequest().Execute(Api.Client); var fetchedUsers = result.Data; List<User> users = new List<User>(); if (result.Status == 200) { for (int i = 0; i < fetchedUsers.Count; i++) { User tempUser = new User(); tempUser.UpdateFromRequest(Utils.DictionaryOfJsonFields(fetchedUsers[i])); users.Add(tempUser); } } return users; } public override User Get(string id) { Known.TryGetValue(id, out var returned); if (returned == null) { var result = new GetUserRequest(id).Execute(Api.Client); if (result.Status == 200) { returned = new User(); returned.UpdateFromRequest(Utils.DictionaryOfJsonFields(result.Data)); Known.Add(returned.Id, returned); } } return returned; } public string Invite(User user) { string response = ""; var result = new InviteUserRequest(user).Execute(Api.Client); if (result.Status == 200) { response = result.Data; user.Clean(); } return response; } public override void Save(User user) { } public string Edit(User user) { string response = ""; var result = new EditUserRequest(user).Execute(Api.Client); if (result.Status == 200) { response = result.Data; user.Clean(); } return response; } public string Delete(string id) { string response = null; var result = new DeleteUserRequest(id).Execute(Api.Client); if (result.Status == 200) { response = result.Data; } return response; } } } <file_sep>/Reggora.Api/Storage/Lender/LoanStorage.cs using Reggora.Api.Entity; using Reggora.Api.Requests.Lender.Loans; using Reggora.Api.Util; using System.Collections.Generic; namespace Reggora.Api.Storage.Lender { public class LoanStorage : Storage<Loan, Api.Lender> { public LoanStorage(Api.Lender api) : base(api) { } public List<Loan> All(uint offset = 0, uint limit = 0, string ordering = "-created", string loanOfficer = null) { var result = new GetLoansRequest(offset, limit, ordering, loanOfficer).Execute(Api.Client); var fetchedLoans = result.Data.Loans; List<Loan> loans = new List<Loan>(); if (result.Status == 200) { for (int i = 0; i < fetchedLoans.Count; i++) { Loan tempLoan = new Loan(); tempLoan.UpdateFromRequest(Utils.DictionaryOfJsonFields(fetchedLoans[i])); loans.Add(tempLoan); } } return loans; } public override Loan Get(string id) { Known.TryGetValue(id, out var returned); if (returned == null) { var result = new GetLoanRequest(id).Execute(Api.Client); if (result.Status == 200) { returned = new Loan(); returned.UpdateFromRequest(Utils.DictionaryOfJsonFields(result.Data.Loan)); Known.Add(returned.Id, returned); } } return returned; } public override void Save(Loan loan) { var result = new EditLoanRequest(loan).Execute(Api.Client); if (result.Status == 200) { loan.Clean(); } } public string Create(Loan loan) { string response = ""; var result = new CreateLoanRequest(loan).Execute(Api.Client); if (result.Status == 200) { response = result.Data; loan.Clean(); } return response; } public string Edit(Loan loan) { string response = ""; var result = new EditLoanRequest(loan).Execute(Api.Client); if (result.Status == 200) { response = result.Data; loan.Clean(); } return response; } public string Delete(string id) { string response = null; var result = new DeleteLoanRequest(id).Execute(Api.Client); if (result.Status == 200) { response = result.Data; } return response; } /// <summary> /// Get Loan Schema (Extended) /// </summary> /// <returns>Return a list of all Loan fields</returns> public List<string> GetSchema() { List<string> response = new List<string>(); var result = new GetLoanSchemaRequest().Execute(Api.Client); if (result.Status == 200) { response = Utils.ListOfJsonString(result.Data); } return response; } /// <summary> ///Create a Loan with custom fields that are setup in the Settings tab within the lender platform. (Extended) /// </summary> /// <param name="loanParams">Loan fields name and value as a dictionary</param> /// <returns>ID of the created Loan</returns> public string Create(Dictionary<string, object> loanParams) { string response = ""; var result = new CreateExtendedLoanRequest(loanParams).Execute(Api.Client); if (result.Status == 200) { response = result.Data; } return response; } /// <summary> /// Edit a Loan with custom fields that are setup in the Settings tab within the lender platform. (Extended) /// </summary> /// <param name="loanID">Loan ID to be edited</param> /// <param name="loanParams">Loan fields name and value as a dictionary</param> /// <returns>ID of the edited Loan</returns> public string Edit(string loanID, Dictionary<string, object> loanParams) { string response = ""; var result = new EditExtendedLoanRequest(loanID, loanParams).Execute(Api.Client); if (result.Status == 200) { response = result.Data; } return response; } } }<file_sep>/Reggora.Api/Requests/Lender/Users/CreateUserRequest.cs using System; using System.Collections.Generic; using System.Linq; using Newtonsoft.Json; using Reggora.Api.Entity; using RestSharp; namespace Reggora.Api.Requests.Lender.Users { public class CreateUserRequest : ReggoraRequest { public CreateUserRequest(User user) : base("lender/users", Method.POST) { AddJsonBody(new Request { Email = user.Email, FirstName = user.FirstName, LastName = user.LastName, PhoneNumber = user.PhoneNumber, Branch = user.Branch, Role = user.Role, Nmls = user.NmlsId }); } public class Request { [JsonProperty("email")] public string Email { get; set; } [JsonProperty("firstname")] public string FirstName { get; set; } [JsonProperty("lastname")] public string LastName { get; set; } [JsonProperty("phone_number")] public string PhoneNumber { get; set; } [JsonProperty("branch_id")] public string Branch { get; set; } [JsonProperty("role")] public string Role { get; set; } [JsonProperty("nmls_id")] public string Nmls { get; set; } } } } <file_sep>/Reggora.Api/Requests/Lender/Models/User.cs namespace Reggora.Api.Requests.Lender.Models { public class User { public string Id; public string Email; public string PhoneNumber = ""; public string FirstName; public string LastName; public string NmlsId; public string Created = ""; public string Role = ""; public User[] MatchedUsers = { }; public bool? SupressNotifications = null; } }<file_sep>/Reggora.Api/Requests/Lender/Users/GetUserRequest.cs using System.Collections.Generic; using Newtonsoft.Json; using RestSharp; namespace Reggora.Api.Requests.Lender.Users { public class GetUserRequest : ReggoraRequest { public GetUserRequest(string userId) : base("lender/users/{user_id}", Method.GET) { AddParameter("user_id", userId, ParameterType.UrlSegment); } public new Response Execute(IRestClient client) { return Execute<Response>(client); } public class Response { [JsonProperty("data")] public User Data { get; set; } [JsonProperty("status")] public int Status { get; set; } public class User { [JsonProperty("id")] public string Id { get; set; } [JsonProperty("email")] public string Email { get; set; } [JsonProperty("phone_number")] public string PhoneNumber { get; set; } [JsonProperty("firstname")] public string FirstName { get; set; } [JsonProperty("lastname")] public string LastName { get; set; } [JsonProperty("nmls_id")] public string Nmls { get; set; } [JsonProperty("created")] public string Created { get; set; } [JsonProperty("role")] public string Role { get; set; } [JsonProperty("brnach_id")] public string BranchId { get; set; } [JsonProperty("matched_users")] public List<MatchedUser> MatchedUsers { get; set; } public class MatchedUser { [JsonProperty("id")] public string Id { get; set; } [JsonProperty("email")] public string Email { get; set; } [JsonProperty("firstname")] public string FirstName { get; set; } [JsonProperty("lastname")] public string LastName { get; set; } } } } } }<file_sep>/Reggora.Api/Entity/Entities.cs // // WARNING: T4 GENERATED CODE - DO NOT EDIT // using Reggora.Api.Requests.Lender.Evaults; using Reggora.Api.Requests.Lender.Models; using Reggora.Api.Requests.Lender.Orders; using Reggora.Api.Requests.Vendor.Conversation; using Reggora.Api.Requests.Vendor.Order; using System; using System.Collections.Generic; namespace Reggora.Api.Entity { public class Loan : Entity { public string Id { get => _id.Value; set => _id.Value = value; } public string Number { get => _number.Value; set => _number.Value = value; } public string Type { get => _type.Value; set => _type.Value = value; } public DateTime? Due { get => _due.Value; set => _due.Value = value; } public DateTime? Created { get => _created.Value; set => _created.Value = value; } public DateTime? Updated { get => _updated.Value; set => _updated.Value = value; } public string PropertyAddress { get => _propertyAddress.Value; set => _propertyAddress.Value = value; } public string PropertyCity { get => _propertyCity.Value; set => _propertyCity.Value = value; } public string PropertyState { get => _propertyState.Value; set => _propertyState.Value = value; } public string PropertyZip { get => _propertyZip.Value; set => _propertyZip.Value = value; } public string CaseNumber { get => _caseNumber.Value; set => _caseNumber.Value = value; } public string AppraisalType { get => _appraisalType.Value; set => _appraisalType.Value = value; } public List<Consumer> Consumers { get => _consumers.Value; set => _consumers.Value = value; } private readonly EntityField<string> _id; private readonly EntityField<string> _number; private readonly EntityField<string> _type; private readonly EntityField<DateTime?> _due; private readonly EntityField<DateTime?> _created; private readonly EntityField<DateTime?> _updated; private readonly EntityField<string> _propertyAddress; private readonly EntityField<string> _propertyCity; private readonly EntityField<string> _propertyState; private readonly EntityField<string> _propertyZip; private readonly EntityField<string> _caseNumber; private readonly EntityField<string> _appraisalType; private readonly EntityField<List<Consumer>> _consumers; public Loan() { BuildField(ref _id, "id"); BuildField(ref _number, "loan_number"); BuildField(ref _type, "loan_type"); BuildField(ref _due, "string", "due_date"); BuildField(ref _created, "string", "created"); BuildField(ref _updated, "string", "updated"); BuildField(ref _propertyAddress, "subject_property_address"); BuildField(ref _propertyCity, "subject_property_city"); BuildField(ref _propertyState, "subject_property_state"); BuildField(ref _propertyZip, "subject_property_zip"); BuildField(ref _caseNumber, "case_number"); BuildField(ref _appraisalType, "appraisal_type"); BuildField(ref _consumers, "consumers"); } } public class Order : Entity { public enum PriorityType { Normal, Rush, } public enum AllocationMode { Automatic, Manual, } public string Id { get => _id.Value; set => _id.Value = value; } public string Status { get => _status.Value; set => _status.Value = value; } public AllocationMode Allocation { get => _allocation.Value; set => _allocation.Value = value; } public string Loan { get => _loan.Value; set => _loan.Value = value; } public GetOrderRequest.Response.Order.Loan LoanFile { get => _loanFile.Value; set => _loanFile.Value = value; } public PriorityType? Priority { get => _priority.Value; set => _priority.Value = value; } public List<string> ProductIds { get => _productIds.Value; set => _productIds.Value = value; } public List<GetOrderRequest.Response.Order.Product> Products { get => _products.Value; set => _products.Value = value; } public DateTime? Due { get => _due.Value; set => _due.Value = value; } public DateTime? InspectedAt { get => _inspectedAt.Value; set => _inspectedAt.Value = value; } public DateTime? Created { get => _created.Value; set => _created.Value = value; } public Vendr AcceptedVendor { get => _acceptedVendor.Value; set => _acceptedVendor.Value = value; } public string Evault { get => _evault.Value; set => _evault.Value = value; } public List<CreateOrderRequest.Request.AdditionalFee> AdditionalFees { get => _additionalFees.Value; set => _additionalFees.Value = value; } public List<Consumer> Consumers { get => _consumers.Value; set => _consumers.Value = value; } public bool Inspected { get => _inspected.Value; set => _inspected.Value = value; } private readonly EntityField<string> _id; private readonly EntityField<string> _status; private readonly EntityField<AllocationMode> _allocation; private readonly EntityField<string> _loan; private readonly EntityField<GetOrderRequest.Response.Order.Loan> _loanFile; private readonly EntityField<PriorityType?> _priority; private readonly EntityField<List<string>> _productIds; private readonly EntityField<List<GetOrderRequest.Response.Order.Product>> _products; private readonly EntityField<DateTime?> _due; private readonly EntityField<DateTime?> _inspectedAt; private readonly EntityField<DateTime?> _created; private readonly EntityField<bool> _inspected; private readonly EntityField<Vendr> _acceptedVendor; private readonly EntityField<string> _evault; private readonly EntityField<List<CreateOrderRequest.Request.AdditionalFee>> _additionalFees; private readonly EntityField<List<Consumer>> _consumers; public Order() { BuildField(ref _id, "id"); BuildField(ref _status, "status"); BuildField(ref _allocation, "string", "allocation_type"); BuildField(ref _loan, "loan"); BuildField(ref _loanFile, "loan_file"); BuildField(ref _priority, "string", "priority"); BuildField(ref _productIds, "product_ids"); BuildField(ref _products, "products"); BuildField(ref _due, "string", "due_date"); BuildField(ref _inspectedAt, "string", "inspection_date"); BuildField(ref _created, "string", "created"); BuildField(ref _inspected, "inspection_complete"); BuildField(ref _acceptedVendor, "accepted_vendor"); BuildField(ref _evault, "evault"); BuildField(ref _additionalFees, "additional_fees"); BuildField(ref _consumers, "consumers"); } public static string PriorityTypeToString(PriorityType? value) { switch (value) { case PriorityType.Normal: return "Normal"; case PriorityType.Rush: return "Rush"; } throw new InvalidCastException($"Cannot cast '{typeof(PriorityType)}' to string!"); } public static PriorityType PriorityTypeFromString(string value) { switch (value.ToLowerInvariant()) { case "normal": return PriorityType.Normal; case "rush": return PriorityType.Rush; } throw new InvalidCastException($"Cannot cast string '{value}' to '{typeof(PriorityType)}'!"); } public static string AllocationModeToString(AllocationMode? value) { switch (value) { case AllocationMode.Automatic: return "automatically"; case AllocationMode.Manual: return "manually"; } throw new InvalidCastException($"Cannot cast '{typeof(AllocationMode)}' to string!"); } public static AllocationMode AllocationModeFromString(string value) { switch (value.ToLowerInvariant()) { case "automatically": return AllocationMode.Automatic; case "manually": return AllocationMode.Manual; } throw new InvalidCastException($"Cannot cast string '{value}' to '{typeof(AllocationMode)}'!"); } } public class Submission : Entity { public string Version { get => _version.Value; set => _version.Value = value; } public string PdfReport { get => _pdfReport.Value; set => _pdfReport.Value = value; } public string XmlReport { get => _xmlReport.Value; set => _xmlReport.Value = value; } public string Invoice { get => _invoice.Value; set => _invoice.Value = value; } private readonly EntityField<string> _version; private readonly EntityField<string> _pdfReport; private readonly EntityField<string> _xmlReport; private readonly EntityField<string> _invoice; public Submission() { BuildField(ref _version, "version"); BuildField(ref _pdfReport, "pdf_report"); BuildField(ref _xmlReport, "xml_eport"); BuildField(ref _invoice, "invoice"); } } public class Product : Entity { public enum Inspection { Interior, Exterior } public string Id { get => _id.Value; set => _id.Value = value; } public string ProductName { get => _productName.Value; set => _productName.Value = value; } public float Amount { get => _amount.Value; set => _amount.Value = value; } public Inspection InspectionType { get => _inspectionType.Value; set => _inspectionType.Value = value; } public string RequestForms { get => _requestForms.Value; set => _requestForms.Value = value; } private readonly EntityField<string> _id; private readonly EntityField<string> _productName; private readonly EntityField<float> _amount; private readonly EntityField<Inspection> _inspectionType; private readonly EntityField<string> _requestForms; public Product() { BuildField(ref _id, "id"); BuildField(ref _productName, "product_name"); BuildField(ref _amount, "amount"); BuildField(ref _inspectionType, "string", "inspection_type"); BuildField(ref _requestForms, "requested_forms"); } public static string InspectionToString(Inspection inspection) { switch (inspection) { case Inspection.Interior: return "interior"; case Inspection.Exterior: return "exterior"; } return ""; } public static Inspection InspectionFromString(string value) { switch (value.ToLowerInvariant()) { case "interior": return Inspection.Interior; case "exterior": return Inspection.Exterior; } throw new InvalidCastException($"Cannot cast string '{value}' to '{typeof(Inspection)}'!"); } } public class User : Entity { public string Id { get => _id.Value; set => _id.Value = value; } public string Email { get => _email.Value; set => _email.Value = value; } public string PhoneNumber { get => _phoneNumber.Value; set => _phoneNumber.Value = value; } public string FirstName { get => _firstName.Value; set => _firstName.Value = value; } public string LastName { get => _lastName.Value; set => _lastName.Value = value; } public string NmlsId { get => _nmlsId.Value; set => _nmlsId.Value = value; } public DateTime? Created { get => _created.Value; set => _created.Value = value; } public string Role { get => _role.Value; set => _role.Value = value; } public string Branch { get => _branchId.Value; set => _branchId.Value = value; } private readonly EntityField<string> _id; private readonly EntityField<string> _email; private readonly EntityField<string> _phoneNumber; private readonly EntityField<string> _firstName; private readonly EntityField<string> _lastName; private readonly EntityField<string> _nmlsId; private readonly EntityField<DateTime?> _created; private readonly EntityField<string> _role; private readonly EntityField<string> _branchId; public User() { BuildField(ref _id, "id"); BuildField(ref _email, "email"); BuildField(ref _phoneNumber, "phone_number"); BuildField(ref _firstName, "string", "firstname"); BuildField(ref _lastName, "string", "lastname"); BuildField(ref _nmlsId, "string", "nmls_id"); BuildField(ref _created, "string", "created"); BuildField(ref _role, "string", "role"); BuildField(ref _branchId, "string", "brnach_id"); } } public class Vendr : Entity { public string Id { get => _id.Value; set => _id.Value = value; } public string FirmName { get => _firmName.Value; set => _firmName.Value = value; } public string Email { get => _email.Value; set => _email.Value = value; } public string Phone { get => _phone.Value; set => _phone.Value = value; } public string FirstName { get => _firstName.Value; set => _firstName.Value = value; } public string LastName { get => _lastName.Value; set => _lastName.Value = value; } public string Name { get => _name.Value; set => _name.Value = value; } public bool AcceptingJobs { get => _acceptingJobs.Value; set => _acceptingJobs.Value = value; } private readonly EntityField<string> _id; private readonly EntityField<string> _firmName; private readonly EntityField<string> _email; private readonly EntityField<string> _phone; private readonly EntityField<string> _firstName; private readonly EntityField<string> _lastName; private readonly EntityField<string> _name; private readonly EntityField<bool> _acceptingJobs; public Vendr() { BuildField(ref _id, "id"); BuildField(ref _firmName, "firm_name"); BuildField(ref _email, "email"); BuildField(ref _phone, "phone"); BuildField(ref _firstName, "firstname"); BuildField(ref _lastName, "lastname"); BuildField(ref _name, "name"); BuildField(ref _acceptingJobs, "accepting_jobs"); } } public class PaymentApp : Entity { public enum PaymentType { Manual, Stripe, } public enum UserType { Manual, Consumer, } public enum LinkType { Payment, Scheduling, Both } public string ConsumerEmail { get => _consumerEmail.Value; set => _consumerEmail.Value = value; } public string OrderId { get => _orderId.Value; set => _orderId.Value = value; } public UserType UsrType { get => _userType.Value; set => _userType.Value = value; } public PaymentType PaymenType { get => _paymenType.Value; set => _paymenType.Value = value; } public float Amount { get => _amount.Value; set => _amount.Value = value; } public string FirstName { get => _firstName.Value; set => _firstName.Value = value; } public string LastName { get => _lastName.Value; set => _lastName.Value = value; } public bool Paid { get => _paid.Value; set => _paid.Value = value; } private readonly EntityField<string> _consumerEmail; private readonly EntityField<string> _orderId; private readonly EntityField<UserType> _userType; private readonly EntityField<PaymentType> _paymenType; private readonly EntityField<float> _amount; private readonly EntityField<string> _firstName; private readonly EntityField<string> _lastName; private readonly EntityField<bool> _paid; public PaymentApp() { BuildField(ref _consumerEmail, "consumer_email"); BuildField(ref _orderId, "order_id"); BuildField(ref _userType, "user_type"); BuildField(ref _paymenType, "payment_type"); BuildField(ref _amount, "amount"); BuildField(ref _firstName, "firstname"); BuildField(ref _lastName, "lastname"); BuildField(ref _paid, "paid"); } public static string PaymentTypeToString(PaymentType? value) { switch (value) { case PaymentType.Manual: return "manual"; case PaymentType.Stripe: return "stripe"; } throw new InvalidCastException($"Cannot cast '{typeof(PaymentType)}' to string!"); } public static string UserTypeToString(UserType? value) { switch (value) { case UserType.Manual: return "manual"; case UserType.Consumer: return "consumer"; } throw new InvalidCastException($"Cannot cast '{typeof(UserType)}' to string!"); } public static string LinkTypeToString(LinkType? value) { switch (value) { case LinkType.Payment: return "payment"; case LinkType.Scheduling: return "scheduling"; case LinkType.Both: return "payment,scheduling"; } throw new InvalidCastException($"Cannot cast '{typeof(LinkType)}' to string!"); } } public class Evault : Entity { public string Id { get => _id.Value; set => _id.Value = value; } public List<GetEvaultRequest.Response.Evlt.Document> Documents { get => _documents.Value; set => _documents.Value = value; } private readonly EntityField<string> _id; private readonly EntityField<List<GetEvaultRequest.Response.Evlt.Document>> _documents; public Evault() { BuildField(ref _id, "id"); BuildField(ref _documents, "documents"); } } public class VendorOrder : Entity { public string Id { get => _id.Value; set => _id.Value = value; } public string Status { get => _status.Value; set => _status.Value = value; } public string PropertyStreet { get => _propertyStreet.Value; set => _propertyStreet.Value = value; } public string PropertyCity { get => _propertyCity.Value; set => _propertyCity.Value = value; } public string PropertyState { get => _propertyState.Value; set => _propertyState.Value = value; } public string PropertyZip { get => _propertyZip.Value; set => _propertyZip.Value = value; } public string Priority { get => _priority.Value; set => _priority.Value = value; } public string RequestExpiration { get => _requestExpiration.Value; set => _requestExpiration.Value = value; } public string DueDate { get => _dueDate.Value; set => _dueDate.Value = value; } public GetVendorOrderRequest.Response.Order.Lendr lender { get => _lender.Value; set => _lender.Value = value; } public GetVendorOrderRequest.Response.Order.Loan LoanFile { get => _loanFile.Value; set => _loanFile.Value = value; } public List<GetVendorOrderRequest.Response.Order.Consumer> Consumers { get => _consumers.Value; set => _consumers.Value = value; } public List<GetVendorOrderRequest.Response.Order.Schdl> Schedule { get => _schedule.Value; set => _schedule.Value = value; } public string Evault { get => _evault.Value; set => _evault.Value = value; } public string Conversation { get => _conversation.Value; set => _conversation.Value = value; } public List<GetVendorOrderRequest.Response.Order.Product> Products { get => _products.Value; set => _products.Value = value; } public List<GetVendorOrderRequest.Response.Order.Submission> Submissions { get => _submissions.Value; set => _submissions.Value = value; } public List<GetVendorOrderRequest.Response.Order.Revision> Revisions { get => _revisions.Value; set => _revisions.Value = value; } private readonly EntityField<string> _id; private readonly EntityField<string> _status; private readonly EntityField<string> _propertyStreet; private readonly EntityField<string> _propertyCity; private readonly EntityField<string> _propertyState; private readonly EntityField<string> _propertyZip; private readonly EntityField<string> _priority; private readonly EntityField<string> _requestExpiration; private readonly EntityField<string> _dueDate; private readonly EntityField<GetVendorOrderRequest.Response.Order.Lendr> _lender; private readonly EntityField<GetVendorOrderRequest.Response.Order.Loan> _loanFile; private readonly EntityField<List<GetVendorOrderRequest.Response.Order.Consumer>> _consumers; private readonly EntityField<List<GetVendorOrderRequest.Response.Order.Schdl>> _schedule; private readonly EntityField<List<GetVendorOrderRequest.Response.Order.Product>> _products; private readonly EntityField<List<GetVendorOrderRequest.Response.Order.Submission>> _submissions; private readonly EntityField<List<GetVendorOrderRequest.Response.Order.Revision>> _revisions; private readonly EntityField<string> _evault; private readonly EntityField<string> _conversation; public VendorOrder() { BuildField(ref _id, "id"); BuildField(ref _status, "status"); BuildField(ref _propertyStreet, "property_street"); BuildField(ref _propertyCity, "property_city"); BuildField(ref _propertyState, "property_state"); BuildField(ref _propertyZip, "property_zip"); BuildField(ref _priority, "priority"); BuildField(ref _requestExpiration, "request_expiration"); BuildField(ref _dueDate, "due_date"); BuildField(ref _lender, "lender"); BuildField(ref _loanFile, "loan_file"); BuildField(ref _consumers, "consumers"); BuildField(ref _schedule, "schedule"); BuildField(ref _products, "products"); BuildField(ref _submissions, "submissions"); BuildField(ref _revisions, "revisions"); BuildField(ref _evault, "evault"); BuildField(ref _conversation, "conversation"); } } public class Conversation : Entity { public string Id { get => _id.Value; set => _id.Value = value; } public List<GetConversationRequest.Response.Conversation.User> VendorUsers { get => _vendorUsers.Value; set => _vendorUsers.Value = value; } public List<GetConversationRequest.Response.Conversation.User> LenderUsers { get => _lenderUsers.Value; set => _lenderUsers.Value = value; } public List<GetConversationRequest.Response.Conversation.Msg> Messages { get => _messages.Value; set => _messages.Value = value; } private readonly EntityField<string> _id; private readonly EntityField<List<GetConversationRequest.Response.Conversation.User>> _vendorUsers; private readonly EntityField<List<GetConversationRequest.Response.Conversation.User>> _lenderUsers; private readonly EntityField<List<GetConversationRequest.Response.Conversation.Msg>> _messages; public Conversation() { BuildField(ref _id, "id"); BuildField(ref _vendorUsers, "vendor_users"); BuildField(ref _lenderUsers, "lender_users"); BuildField(ref _messages, "messages"); } } public class VendorEvault : Entity { public string Id { get => _id.Value; set => _id.Value = value; } public List<GetEvaultRequest.Response.Evlt.Document> Documents { get => _documents.Value; set => _documents.Value = value; } private readonly EntityField<string> _id; private readonly EntityField<List<GetEvaultRequest.Response.Evlt.Document>> _documents; public VendorEvault() { BuildField(ref _id, "id"); BuildField(ref _documents, "documents"); } } } <file_sep>/Reggora.Api/Requests/Lender/Models/Product.cs using System.Collections.Generic; namespace Reggora.Api.Requests.Lender.Models { public class Product { public string Id; public string ProductName; public float Amount; public Inspection InspectionType; public List<string> RequestForms; public IDictionary<string, float> GeographicPricing = new Dictionary<string, float>(); public enum Inspection { Interior, Exterior } public static string InspectionToString(Inspection inspection) { switch (inspection) { case Inspection.Interior: return "interior"; case Inspection.Exterior: return "exterior"; } return ""; } } }<file_sep>/Reggora.Api/Requests/Vendor/Evault/GetEvaultRequest.cs using System.Collections.Generic; using Newtonsoft.Json; using RestSharp; namespace Reggora.Api.Requests.Vendor.Evault { class GetEvaultRequest : ReggoraRequest { public GetEvaultRequest(string evaultId) : base("vendor/evault/{evault_id}", Method.GET) { AddParameter("evault_id", evaultId, ParameterType.UrlSegment); } public new Response Execute(IRestClient client) { return Execute<Response>(client); } public class Response { [JsonProperty("data")] public NestedData Data { get; set; } [JsonProperty("status")] public int Status { get; set; } public class NestedData { [JsonProperty("id")] public string Id { get; set; } [JsonProperty("documents")] public List<Document> Documents { get; set; } } public class Document { [JsonProperty("document_name")] public string DocumentName { get; set; } [JsonProperty("document_id")] public string DocumentId { get; set; } [JsonProperty("upload_datetime")] public string UploadDatetime { get; set; } } } } } <file_sep>/Reggora.Api/Requests/Vendor/Models/AuthorizationRequest.cs using Newtonsoft.Json; namespace Reggora.Api.Requests.Vendor.Models { public class AuthorizationRequest { [JsonProperty("email")] public string Email; [JsonProperty("password")] public string Password; } }<file_sep>/ReggoraVendorApi.Test/ReggoraTest.cs using Microsoft.VisualStudio.TestTools.UnitTesting; using Reggora.Api; using Reggora.Api.Entity; using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.IO; using System.Text; namespace ReggoraVendorApi.Test { [TestClass] public class ReggoraTest { private Vendor vendor; private string orderId = "5d617e55e577d1000e90c996"; private string evaultId = "5c4f16764672bb00105ea5f9"; private string documentId = null; [TestInitialize] public void Initialize() { if (vendor == null) { vendor = new Vendor(Config.GetProperty("vendor.token", "")); Console.WriteLine("Authenticating..."); vendor.Authenticate(Config.GetProperty("vendor.email", ""), Config.GetProperty("vendor.password", "")); } } [TestMethod] public void AA_TestGetVendorOrder() { Console.WriteLine("Testing Get a Order of vendor..."); string expectedId = this.orderId; try { VendorOrder order = vendor.VendorOrders.Get(expectedId); Assert.AreEqual(expectedId, order.Id, String.Format("Tried to get order by ID:'{0}'; Actual ID of order: {1}", expectedId, order.Id)); } catch (Exception e) { throw new Exception(e.ToString()); } } [TestMethod] public void AB_TestGetVendorOrders() { uint offset = 0; uint limit = 0; List<string> status = new List<string> { "created", "finding_appraisers", "accepted", "inspection_scheduled", "inspection_completed", "submitted", "revisions_requested" }; try { var orders = vendor.VendorOrders.All(offset, limit, status); Assert.IsInstanceOfType(orders, typeof(List<VendorOrder>)); } catch (Exception e) { throw new Exception(e.ToString()); } } [TestMethod] public void AC_TestAcceptVendorOrder() { string orderId = this.orderId; string response = vendor.VendorOrders.VendorAcceptOrder(orderId); Assert.IsNotNull(response, String.Format("Expected Success message of Accpetance, Actual: {0}", response)); } [TestMethod] public void AD_TestCounterOffer() { string orderId = this.orderId; DateTime dueDate = DateTime.Now.AddYears(1); float fee = 345.67f; string response = vendor.VendorOrders.CounterOffer(orderId, dueDate, fee); Assert.AreEqual(orderId, response, String.Format("Counter Offer for Order['{0}']; Actual ID of response: {1}", orderId, response)); } [TestMethod] public void AE_TestDenyOrder() { string orderId = this.orderId; string denyReason = "deny_reason': 'I am on vacation until next Tuesday"; string response = vendor.VendorOrders.DenyOrder(orderId, denyReason); Assert.AreEqual(orderId, response, String.Format("Deny Order for Order['{0}']; Actual ID of response: {1}", orderId, response)); } [TestMethod] public void AF_TestSetInspectionDate() { string orderId = this.orderId; DateTime inspectionDate = DateTime.Now.AddYears(1); string response = vendor.VendorOrders.SetInspectionDate(orderId, inspectionDate); Assert.AreEqual(orderId, response, String.Format("Setting Inspection Date for Order['{0}']; Actual ID of response: {1}", orderId, response)); } [TestMethod] public void AG_TestCompleteInspection() { string orderId = this.orderId; DateTime completedAt = DateTime.Now.AddYears(1); string response = vendor.VendorOrders.CompleteInspection(orderId, completedAt); Assert.AreEqual(orderId, response, String.Format("Complete Inspection Date for Order['{0}']; Actual ID of response: {1}", orderId, response)); } [TestMethod] public void AH_TestUploadSubmission() { string orderId = this.orderId; string path = AppDomain.CurrentDomain.BaseDirectory; string samplePdfFile = Path.Combine(path, "\\sample.pdf"); string sampleXmlFile = Path.Combine(path, "\\sample.xml"); string sampleInvoiceFile = Path.Combine(path, "\\sample.pdf"); string invoiceNumber = null; try { var response = vendor.VendorOrders.UploadSubmission(orderId, samplePdfFile, sampleXmlFile, sampleInvoiceFile, invoiceNumber); Assert.IsNotNull(response); } catch (Exception e) { throw new Exception(e.ToString()); } } [TestMethod] public void AI_TestDownloadSubmissionDoc() { string orderId = this.orderId; uint submissionVersion = 1; string documentType = "pdf"; // "xml", "invoice" string downloadPath = null; bool response = vendor.VendorOrders.DownloadSubmission(orderId, submissionVersion, documentType, downloadPath); Assert.IsTrue(response); } [TestMethod] public void AJ_TestCancelVendorOrder() { string orderId = this.orderId; string message = "I decided to quit the appraisal industry to follow my dreams of becoming a musician"; string response = vendor.VendorOrders.VendorCancelOrder(orderId, message); Assert.IsNotNull(response, String.Format("Expected Success message of Cancellation, Actual: {0}", response)); } [TestMethod] public void BA_TestGetConverstion() { string conversationId = "5c4f16764672bb00105ea5f9"; var conversation = vendor.Conversations.Get(conversationId); Assert.IsInstanceOfType(conversation, typeof(Conversation)); } [TestMethod] public void BB_TestSendMessage() { string conversationId = "5c4f16764672bb00105ea5f9"; string message = "Don't you just love reggora?"; var response = vendor.Conversations.SendMessage(conversationId, message); Assert.AreEqual(conversationId, response, String.Format("Send Message for Conversation['{0}']; Actual ID of response: {1}", conversationId, response)); } public string UploadDocument() { if (documentId != null) { return documentId; } string evaultId = this.evaultId; string path = AppDomain.CurrentDomain.BaseDirectory; string sampleFile = Path.Combine(path, "\\sample.pdf"); string fileName = "SampleFile"; try { string response = vendor.Evaults.UploadDocument(evaultId, sampleFile, fileName); documentId = response; return response; } catch (Exception e) { throw new Exception(e.ToString()); } } [TestMethod] public void CA_TestGetEvault() { string evaultId = this.evaultId; var evault = vendor.Evaults.Get(evaultId); Assert.IsInstanceOfType(evault, typeof(VendorEvault)); } [TestMethod] public void CB_TestGetDocument() { string documentId = UploadDocument(); bool response = false; if (documentId != null) { string evaultId = this.evaultId; string downloadPath = null; response = vendor.Evaults.GetDocument(evaultId, documentId, downloadPath); } Assert.IsTrue(response); } [TestMethod] public void CC_TestUploadDocument() { string documentId = UploadDocument(); Assert.IsNotNull(documentId, String.Format("Id of Uploaded document, Actual: {0}", documentId)); } [TestMethod] public void CD_TestDeleteDocument() { string documentId = UploadDocument(); string response = null; if(documentId != null) { string evaultId = this.evaultId; response = vendor.Evaults.DeleteDocument(evaultId, documentId); } Assert.IsNotNull(response, String.Format("Expected Success message of Deletion, Actual: {0}", response)); } } public class SampleObjects { public static Loan _loan { get; set; } public static Order _order { get; set; } public static Product _product { get; set; } public static User _user { get; set; } public static Vendr _vendor { get; set; } public static Evault _evault { get; set; } } public class Config { public static string ConfigFileName = "example.conf"; private static IReadOnlyDictionary<string, string> KeyValues { get; set; } static Config() { try { string username = Environment.UserName; string fileContents = string.Empty; string path = AppDomain.CurrentDomain.BaseDirectory; if (path != null) { var configFilePath = Path.Combine(path, $"example.{username}.conf"); if (File.Exists(configFilePath)) { fileContents = File.ReadAllText(configFilePath); Console.WriteLine($"Using config at {configFilePath}"); } else { configFilePath = Path.Combine(path, ConfigFileName); if (File.Exists(configFilePath)) { fileContents = File.ReadAllText(configFilePath); Console.WriteLine($"Using config at {configFilePath}"); } } } LoadValues(fileContents); } catch (Exception e) { Console.WriteLine("Error configuring parser"); Console.WriteLine(e.Message); } } private static void LoadValues(string data) { Dictionary<string, string> newDictionairy = new Dictionary<string, string>(); foreach ( string rawLine in data.Split(new[] { "\r\n", "\n", Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries)) { string line = rawLine.Trim(); if (line.StartsWith("#") || !line.Contains("=")) continue; //It's a comment or not a key value pair. string[] splitLine = line.Split('=', 2); string key = splitLine[0].ToLower(); string value = splitLine[1]; if (!newDictionairy.ContainsKey(key)) { newDictionairy.Add(key, value); } } KeyValues = new ReadOnlyDictionary<string, string>(newDictionairy); } public static Boolean GetProperty(string property, bool defaultValue) { try { string d = ReadString(property); if (d == null) return defaultValue; return Convert.ToBoolean(d); } catch { return defaultValue; } } public static int GetProperty(string property, int defaultValue) { try { var value = ReadString(property); if (value == null) return defaultValue; return Convert.ToInt32(value); } catch { return defaultValue; } } public static string GetProperty(string property, string defaultValue) { return ReadString(property) ?? defaultValue; } private static string ReadString(string property) { property = property.ToLower(); if (!KeyValues.ContainsKey(property)) return null; return KeyValues[property]; } } } <file_sep>/Reggora.Api/Storage/Lender/OrderStorage.cs using Reggora.Api.Entity; using Reggora.Api.Requests; using Reggora.Api.Requests.Lender.Orders; using Reggora.Api.Util; using Syroot.Windows.IO; using System; using System.Collections.Generic; using System.IO; namespace Reggora.Api.Storage.Lender { public class OrderStorage : Storage<Order, Api.Lender> { public OrderStorage(Api.Lender api) : base(api) { } public List<Order> All(uint offset = 0, uint limit = 0, string ordering = "-created", string loanOfficer = null, string filters = "") { var result = new GetOrdersRequest(offset, limit, ordering, loanOfficer, filters).Execute(Api.Client); var fetchedOrders = result.Data.Orders; List<Order> orders = new List<Order>(); if (result.Status == 200) { for (int i = 0; i < fetchedOrders.Count; i++) { Order tempOrder = new Order(); tempOrder.UpdateFromRequest(Utils.DictionaryOfJsonFields(fetchedOrders[i])); orders.Add(tempOrder); } } return orders; } public override Order Get(string id) { Known.TryGetValue(id, out var returned); if (returned == null) { var result = new GetOrderRequest(id).Execute(Api.Client); if (result.Status == 200) { returned = new Order(); returned.UpdateFromRequest(Utils.DictionaryOfJsonFields(result.Data.Order)); Known.Add(returned.Id, returned); } } return returned; } public void Save(Order order, bool refresh) { var result = new EditOrderRequest(order, refresh).Execute(Api.Client); if (result.Status == 200) { order.Clean(); } } public override void Save(Order order) { Save(order, false); } public string Create(Order order) { string response = null; var result = new CreateOrderRequest(order).Execute(Api.Client); if (result.Status == 200) { response = result.Data; order.Clean(); } return response; } public string Edit(Order order) { string response = ""; var result = new EditOrderRequest(order, false).Execute(Api.Client); if (result.Status == 200) { response = result.Data; order.Clean(); } return response; } public string Cancel(string orderId) { string response = null; var result = new CancelOrderRequest(orderId).Execute(Api.Client); if (result.Status == 200) { response = result.Data; } return response; } public string OnHold(string orderId, string reason) { string response = null; var result = new PlaceOrderOnHoldRequest(orderId, reason).Execute(Api.Client); if (result.Status == 200) { response = result.Data; } return response; } public string RemoveHold(string orderId) { string response = null; var result = new RemoveOrderHoldRequest(orderId).Execute(Api.Client); if (result.Status == 200) { response = result.Data; } return response; } public List<Submission> Submissions(string orderId) { var result = new GetSubmissionsRequest(orderId).Execute(Api.Client); var fetchedSubmissions = result.Data.Submissions; List<Submission> submissions = new List<Submission>(); if (result.Status == 200) { for (int i = 0; i < fetchedSubmissions.Count; i++) { Submission tempSubmission = new Submission(); tempSubmission.UpdateFromRequest(Utils.DictionaryOfJsonFields(fetchedSubmissions[i])); submissions.Add(tempSubmission); } } return submissions; } public bool DownloadSubmissionDoc(string orderId, uint version, string reportType, string downloadPath) { if(downloadPath == "" || downloadPath == null) { downloadPath = new KnownFolder(KnownFolderType.Downloads).Path; } bool response = true; try { byte[] result = new GetSubmissionRequest(orderId, version, reportType).Download(Api.Client); FileStream fs = File.Create(downloadPath + "\\" + orderId); fs.Write(result, 0, result.Length); } catch (Exception e) { response = false; Console.WriteLine("Downloading Error message: {0}", e.ToString()); } return response; } } }<file_sep>/Reggora.Api/Requests/Lender/Loans/GetLoansRequest.cs using System.Collections.Generic; using Newtonsoft.Json; using RestSharp; namespace Reggora.Api.Requests.Lender.Loans { public class GetLoansRequest : ReggoraRequest { public enum Ordering { Created } public uint Offset = 0; public uint Limit = 0; public Ordering Order = Ordering.Created; public string LoanOfficer = null; public GetLoansRequest(uint offset, uint limit, string ordering, string loanOfficer) : base("lender/loans", Method.GET) { AddParameter("offset", offset, ParameterType.QueryString); AddParameter("limit", limit, ParameterType.QueryString); AddParameter("order", ordering, ParameterType.QueryString); if (LoanOfficer != null) { AddParameter("loan_officer", loanOfficer, ParameterType.QueryString); } } public new Response Execute(IRestClient client) { return Execute<Response>(client); } private string OrderingToString() { switch (Order) { case Ordering.Created: return "-created"; } return ""; } public class Response { [JsonProperty("data")] //public List<GetLoanRequest.Response.Loan> Data { get; set; } public NestedLoans Data { get; set; } [JsonProperty("status")] public int Status { get; set; } public class NestedLoans { [JsonProperty("loans")] public List<GetLoanRequest.Response.Loan> Loans { get; set; } } } } }<file_sep>/Reggora.Api/Storage/Lender/EvaultStorage.cs using Reggora.Api.Entity; using Reggora.Api.Requests.Lender.Evaults; using Reggora.Api.Util; using System; using System.Collections.Generic; namespace Reggora.Api.Storage.Lender { public class EvaultStorage : Storage<Evault, Api.Lender> { public EvaultStorage(Api.Lender api) : base(api) { } public override Evault Get(string id) { Known.TryGetValue(id, out var returned); if (returned == null) { var result = new GetEvaultRequest(id).Execute(Api.Client); if (result.Status == 200) { returned = new Evault(); returned.UpdateFromRequest(Utils.DictionaryOfJsonFields(result.Data.Evault)); Known.Add(returned.Id, returned); } } return returned; } public void GetDocument(string evaultId, string documentId) { new GetDocumentRequest(evaultId, documentId).Execute(Api.Client); } public string UploadDocument(string evaultId, string filePath) { string response = null; var result = new UploadDocumentRequest(evaultId, filePath).Execute(Api.Client); if (result.Status == 200) { response = result.Data; } return response; } public string UploadPS(string orderId, string filePath, string documentName = null) { string response = null; var result = new UploadPSRequest(orderId, filePath, documentName).Execute(Api.Client); if (result.Status == 200) { response = result.Data; } return response; } public string DeleteDocument(string evaultId, string documentId) { string response = null; var result = new DeleteDocumentRequest(evaultId, documentId).Execute(Api.Client); if (result.Status == 200) { response = result.Data; } return response; } public override void Save(Evault entity) { throw new NotImplementedException(); } } } <file_sep>/Reggora.Api/Requests/Lender/Orders/CreateOrderRequest.cs using System.Collections.Generic; using Newtonsoft.Json; using Reggora.Api.Entity; using Reggora.Api.Util; using RestSharp; namespace Reggora.Api.Requests.Lender.Orders { public class CreateOrderRequest : ReggoraRequest { public CreateOrderRequest(Order order) : base("lender/order", Method.POST) { AddJsonBody(new Request { Allocation = Order.AllocationModeToString(order.Allocation), Loan = order.Loan, Products = order.ProductIds, Priority = Order.PriorityTypeToString(order.Priority), DueDate = Utils.DateToString(order.Due), AdditionalFees = order.AdditionalFees ?? new List<Request.AdditionalFee>() }); } public class Request { [JsonProperty("allocation_type")] public string Allocation { get; set; } [JsonProperty("loan")] public string Loan { get; set; } [JsonProperty("priority")] public string Priority { get; set; } [JsonProperty("products")] public List<string> Products { get; set; } [JsonProperty("due_date")] public string DueDate { get; set; } [JsonProperty("additional_fees")] public List<AdditionalFee> AdditionalFees { get; set; } public class AdditionalFee { [JsonProperty("description")] public string Description { get; set; } [JsonProperty("amount")] public int Amount { get; set; } } } } }<file_sep>/README.md # Reggora ## Welcome to `Reggora` api! ### `Reggora C# library` works for `Lender` and `Vendor` APIs supported by [Reggora](https://sandbox.reggora.io/). ## Dependencies - NuGet (5.2.0) - NuGet Packages Response: If downloaded successfully, `true`, otherwise, `false` - MimeMapping v1.0.1.14 - Newtonsoft.Json v12.0.2 - RestSharp v106.6.10 - RestSharp.Newtonsoft.Json v1.5.1 - Syroot.Windows.IO.KnownFolders v1.2.1 - Microsoft.NETCore.App (2.2.0) ## Building and importing Library - You can get library by building `Reggora.Api` - Once the building is done, you can see the library `Reggora.Api.dll` in `Reggora.Api\bin\Release\netcoreapp2.2` directory. - You can import this library from adding `Reference`. ## Usage for Lender API - Initializing Library ```c# private Lender lender = new Lender(integrationToken); lender.Authenticate(lenderUserName, lenderPassword); ``` - Make a Request - Loans - Get all Loans [View detail](https://sandbox.reggora.io/#get-all-loans) ``` uint Offset = 0; uint Limit = 0; string ordering = "-created"; string loanOfficer = null; List<Loan> loans = lender.Loans.All(Offset, limit, ordering, loanOfficer); ``` Response: List of `Loan` - Get a Loan [View detail](https://sandbox.reggora.io/#get-loan) ``` Loan loan = lender.Loans.Get(string loanId); ``` - Delete a Loan [View detail](https://sandbox.reggora.io/#delete-loan) ``` string response = lender.Loans.Delete(string loanId); ``` Response: "Loan deleted." - Create a Loan [View detail](https://sandbox.reggora.io/#create-a-loan) ``` Loan loan = new Loan() { Number = "1", Type = "FHA", Due = DateTime.Now.AddYears(1), PropertyAddress = "100 Mass Ave", PropertyCity = "Boston", PropertyState = "MA", PropertyZip = "02192", CaseNumber = "10029MA", AppraisalType = "Refinance" }; string response = lender.Loans.Create(loan); ``` Resposne: Id of created Loan - Edit a Loan [View detail](https://sandbox.reggora.io/#edit-a-loan) ``` loan.Number = "newLoanNumber"; string response = lender.Loans.Edit(loan); ``` Resposne: Id of updated Loan - Orders - Get All Orders [View detail](https://sandbox.reggora.io/#get-all-orders) ``` uint Offset = 0; uint Limit = 0; string ordering = "-created"; string loanOfficer = null; string filters = ""; List<Order> orders = lender.Orders.All(Offset, limit, ordering, loanOfficer); ``` Response: List of `Order` - Get an Order [View detail](https://sandbox.reggora.io/#get-order) ``` Order order = lender.Orders.Get(string orderId); ``` - Cancel Order [View detail](https://sandbox.reggora.io/#cancel-order) ``` string response = lender.Orders.Cancel(string orderId); ``` Response: "Order has been canceled." - Create an Order [View detail](https://sandbox.reggora.io/#create-an-order) ``` ** AllocationMode: Automatic, Manual ** ** PriorityType: Normal, Rush ** Order order = new Order() { Allocation = Order.AllocationMode.Automatic, Loan = loanId, Priority = Order.PriorityType.Normal, ProductIds = productIds, Due = DateTime.Now.AddYears(1) }; string response = lender.Orders.Create(order); ``` Response: Id of created Order - Edit an Order [View detail](https://sandbox.reggora.io/#edit-an-order) ``` ** AllocationMode: Automatic, Manual ** ** PriorityType: Normal, Rush ** order.Priority = Order.PriorityType.Rush; lender.Orders.Edit(order); ``` Response: Id of updated Order - Place Order On Hold [View detail](https://sandbox.reggora.io/#place-order-on-hold) ``` string response = lender.Orders.OnHold(orderId, reason); ``` Response: "Order has been updated" - Remove Order Hold [View detail](https://sandbox.reggora.io/#remove-order-hold) ``` string response = lender.Orders.RemoveHold(orderId); ``` Response: "Order has been updated" - eVault - Get eVault by ID [View detail](https://sandbox.reggora.io/#get-evault-by-id) ``` Evault evault = lender.Evaults.Get(evaultId); ``` - Get Document [View detail](https://sandbox.reggora.io/#get-document) ``` lender.Evaults.GetDocument(evaultId, documentId); ``` Response: File object of document - Upload Document [View detail](https://sandbox.reggora.io/#upload-document) ``` string evaultId = "5d4d06d6d28c2600109499c5"; string documentFilePath = "F:\document.pdf"; string response = lender.Evaults.UploadDocument(evaultId, documentFilePath); ``` Response: Id of uploaded document - Upload P&S [View detail](https://sandbox.reggora.io/#upload-p-amp-s) ``` string orderId = "5d5bc544586cbb000f5e171f"; string documentFilePath = "F:\document.pdf"; string response = lender.Evaults.UploadDocument(evaultId, documentFilePath); ``` Response: Id of uploaded P&S document - Delete Document [View detail](https://sandbox.reggora.io/#delete-document) ``` string response = lender.Evaults.DeleteDocument(evaultId, documentId); ``` Response: "Your document has been deleted" - Products - Get All Products [View detail](https://sandbox.reggora.io/#get-all-products) ``` List<Product> products = lender.Products.All(); ``` Response: List of `Product` - Get a Product [View detail](https://sandbox.reggora.io/#get-product) ``` Product product = lender.Products.Get(productId); ``` - Delete Product [View detail](https://sandbox.reggora.io/#delete-product) ``` string response = lender.Products.Delete(productId); ``` Response: "Your product has been deleted" - Create a Product [View detail](https://sandbox.reggora.io/#create-a-product) ``` ** InspectionType: Interior, Exterior ** Product product = new Product() { ProductName = "Full Appraisal", Amount = 100.00f, InspectionType = Product.Inspection.Interior, RequestForms = "1004MC, BPO" }; string response = lender.Products.Create(product); ``` Response: Id of created product - Edit a Product [View detail](https://sandbox.reggora.io/#edit-a-product) ``` product.ProductName = newProductName; string response = lender.Products.Edit(product); ``` Response: Id of updated product - Submissions - Get All Submissions [View detail](https://sandbox.reggora.io/#get-all-submissions) ``` string orderId = "5d5bc544586cbb000f5e171f"; List<Submission> submissions = lender.Orders.Submissions(orderId); ``` Response: List of `Submission` - Download Submission Document [View detail](https://sandbox.reggora.io/#download-submission-document) ``` ** reportType: "pdf_report", "xml_report", "invoice" string orderId = "5d5bc544586cbb000f5e171f"; uint version = 1; string reportType = "pdf_report"; string downloadPath = null; // If downloadPath is `null`, document will be download `Downloads` path by default bool response = lender.Orders.DownloadSubmissionDoc(orderId, version, reportType, downloadPath); ``` Response: If downloaded successfully, `true`, otherwise, `false` - Users - Get All Users [View details](https://sandbox.reggora.io/#get-all-users) ``` List<User> users = lender.Users.All(); ``` Response: List of `User` - Get User By ID [View detail](https://sandbox.reggora.io/#get-user-by-id) ``` User user = lender.Users.Get(expectedId); ``` - Invite User [View detail](https://sandbox.reggora.io/#invite-user) ``` User user = new User() { Email = "<EMAIL>", PhoneNumber = "12345678", FirstName = "Fake", LastName = "Person", Role = "Admin" }; string response = lender.Users.Invite(user); ``` Response: "Your invite has been sent" - Create User [View detail](https://sandbox.reggora.io/#create-user) ``` User user = new User() { Email = "<EMAIL>", PhoneNumber = "12345678", FirstName = "Fake", LastName = "Person", NmlsId = "MA", Role = "Admin" }; string response = lender.Users.Create(user); ``` Response: Id of created user - Edit User [View detail](https://sandbox.reggora.io/#edit-user) ``` string response = lender.Users.Edit(userId); ``` Response: Id of updated user - Delete User [View detail](https://sandbox.reggora.io/#delete-user) ``` string response = lender.Users.Delete(deleteId); ``` Response: "Your user has been deleted" - Vendors - Get All Vendors [View detail](https://sandbox.reggora.io/#get-all-vendors) ``` var vendors = lender.Vendors.All(); ``` - Get Vendors By Zone [View detail](https://sandbox.reggora.io/#get-vendors-by-zone) ``` List<string> zones = new List<string> { "02806", "02807", "03102" }; uint offset = 0; uint limit = 0; string ordering = "-created"; List<Vendr> vendors = lender.Vendors.GetByZone(zones, offset, limit, ordering); ``` Response: List of `Vendr` - Get Vendors By Branch [View detail](https://sandbox.reggora.io/#get-vendors-by-branch) ``` List<Vendr> vendors = lender.Vendors.GetByBranch(branchId); ``` Response: List of `Vendr` - Get Vendor By ID [View detail](https://sandbox.reggora.io/#get-vendor-by-id) ``` Vendr vendor = lender.Vendors.Get(vendorId); ``` - Add Vendor [View detail](https://sandbox.reggora.io/#add-vendor) ``` Vendr vendor = new Vendr() { FirmName = "Appraisal Firm", Email = "<EMAIL>", Phone = "12345678", FirstName = "Fake", LastName = "Vendor" }; string response = lender.Vendors.Create(vendor); ``` Response: Id of added vendor - Edit Vendor [View detail](https://sandbox.reggora.io/#edit-vendor) ``` vendor.Phone = newPhoneNumber; string response = lender.Vendors.Edit(vendor); ``` Response: Id of updated vendor - Delete Vendor [View detali](https://sandbox.reggora.io/#delete-vendor) ``` string resposne = lender.Vendors.Delete(deleteId); ``` Resposne: "Your vendor has been removed" - Schedule & Payment App - Send Payment App [View detail](https://sandbox.reggora.io/#send-payment-app) ``` ** UsrType: Manual, Consumer ** ** PaymenType: Manual, Stripe ** PaymentApp app = new PaymentApp() { ConsumerEmail = "<EMAIL>", OrderId = "5c33c6b1681f110034effc72", UsrType = PaymentApp.UserType.Manual, PaymenType = PaymentApp.PaymentType.Manual, Amount = 100.00f, FirstName = "Fake", LastName = "Person", Paid = false }; string rsponse = lender.Apps.SendPaymentApp(app); ``` Response = "Payment app sent." - Send Scheduling App [View detail](https://sandbox.reggora.io/#send-scheduling-app) ``` List<string> consumerEmails = new List<string> { "<EMAIL>"}; string orderId = "5c33c6b1681f110034effc72"; string response = lender.Apps.SendSchedulingApp(consumerEmails, orderId); ``` Response: "Scheduling app sent." - Consumer Application Link [View detail](https://sandbox.reggora.io/#consumer-application-link) ``` ** linkType: Payment, Scheduling, Both ** string orderId = "5c33c6b1681f110034effc72"; string consumerId = "5c33c716681f110034effc73"; PaymentApp.LinkType linkType = PaymentApp.LinkType.Payment; string response = lender.Apps.ConsumerAppLink(orderId, consumerId, linkType); ``` Response: "https://devconnect.reggora.com/schedule/.eJw1yjEOgCAMBdC7dJYE6i9WL2OAQuKgJBon492dfPN7qJ9Wz3UzWkiMUZoWnYMV-DFEFuSJaaDSj-ve_xgbGqvCcbLqoCZOq49OMhQhRUMN9H7l7hoK.B8-lmAvVwbOAqLz_-uzL8JIGXgA?iframe=true&override=payment" ## Usage for Vendor API - Initializing Library ```c# private Vendor vendor = new Vendor(integrationToken); vendor.Authenticate(vendorUserName, vendorPassword); ``` - Make a Request - Order Management - Get a Order By Id [View detail](https://sandbox.reggora.io/#vendor-get-order-by-id) ``` string orderId = "5c2e718cb61f76001adf9871"; VendorOrder order = vendor.VendorOrders.Get(orderId); ``` - Get all Orders [View detail](https://sandbox.reggora.io/#vendor-get-all-orders) ``` uint Offset = 0; uint Limit = 0; List<string> status = new List<string> { "created", "finding_appraisers", "accepted", "inspection_scheduled", "inspection_completed", "submitted", "revisions_requested" }; var orders = vendor.VendorOrders.All(offset, limit, status); ``` Response: List of `VendorOrder` - Accept Order [View detail](https://sandbox.reggora.io/#accept-order) ``` string orderId = "5c2e718cb61f76001adf9871"; string response = vendor.VendorOrders.VendorAcceptOrder(orderId); ``` Response: Id of order - Counter Offer [View detail](https://sandbox.reggora.io/#counter-offer) ``` string orderId = "5c2e718cb61f76001adf9871"; DateTime dueDate = DateTime.Now.AddYears(1); float fee = 345.67f; string response = vendor.VendorOrders.CounterOffer(orderId, dueDate, fee); ``` Response: Id of order - Deny Order [View detail](https://sandbox.reggora.io/#deny-order) ``` string orderId = "5c2e718cb61f76001adf9871"; string denyReason = "deny_reason': 'I am on vacation until next Tuesday"; string response = vendor.VendorOrders.DenyOrder(orderId, denyReason); ``` Response: Id of order - Set Inspection Date [View detail](https://sandbox.reggora.io/#set-inspection-date) ``` string orderId = "5c2e718cb61f76001adf9871"; DateTime inspectionDate = DateTime.Now.AddYears(1); string response = vendor.VendorOrders.SetInspectionDate(orderId, inspectionDate); ``` Response: Id of order - Complete Inspection [View detail](https://sandbox.reggora.io/#complete-inspection) ``` string orderId = "5c2e718cb61f76001adf9871"; DateTime completedAt = DateTime.Now.AddYears(1); string response = vendor.VendorOrders.CompleteInspection(orderId, completedAt); ``` Response: Id of order - Upload Submission [View detail](https://sandbox.reggora.io/#upload-submission) ``` string orderId = "5c2e718cb61f76001adf9871"; string pdfFile = "samplePdfFilePath"; string xmlFile = "sampleXmlFilePath"; // optional string invoiceFile = "sampleInvoiceFile"; // Required if no invoiceNumber string invoiceNumber = null; // Required if no invoiceFile var response = vendor.VendorOrders.UploadSubmission(orderId, pdfFile, xmlFile, invoiceFile, invoiceNumber); ``` Response: BASE64 - Download Submission [View detail](https://sandbox.reggora.io/#download-submission) ``` ** documentType: "pdf", "xml", "invoice" string orderId = "5c2e718cb61f76001adf9871"; uint submissionVersion = 1; string documentType = "pdf" string downloadPath = null; // If downloadPath is `null`, document will be download `Downloads` path by default bool response = vendor.VendorOrders.DownloadSubmission(orderId, submissionVersion, documentType, downloadPath); ``` Response: If downloaded successfully, `true`, otherwise, `false` - Vendor Cancel Order [View detail](https://sandbox.reggora.io/#vendor-cancel-order) ``` string orderId = "5c2e718cb61f76001adf9871"; string message = "I decided to quit the appraisal industry to follow my dreams of becoming a musician"; string response = vendor.VendorOrders.VendorCancelOrder(orderId, message); ``` Response: "This order has been cancelled" - Conversation Management - Get Conversation [View detail](https://sandbox.reggora.io/#get-conversation) ``` string conversationId = "5c4f16764672bb00105ea5f9"; Conversation conversation = vendor.Conversations.Get(conversationId); ``` - Send Message [View detail](https://sandbox.reggora.io/#send-message) ``` string conversationId = "5c4f16764672bb00105ea5f9"; string message = "Don't you just love reggora?"; var response = vendor.Conversations.SendMessage(conversationId, message); ``` Response: Id of conversation - eVault Management - Vendor Get eVault by ID [View detail](https://sandbox.reggora.io/#vendor-get-evault-by-id) ``` string evaultId = "5c4f16764672bb00105ea5f9"; VendorEvault evault = vendor.Evaults.Get(evaultId); ``` - Vendor Get Document [View detail](https://sandbox.reggora.io/#vendor-get-document) ``` string documentId = "24bab39a-4404-11e8-ba10-02420a050006"; string evaultId = "5c4f16764672bb00105ea5f9"; string downloadPath = null; bool response = vendor.Evaults.GetDocument(evaultId, documentId, downloadPath); ``` Response: If downloaded successfully, `true`, otherwise, `false` - Vendor Upload Document [View detail](https://sandbox.reggora.io/#vendor-upload-document) ``` string evaultId = "5c4f16764672bb00105ea5f9"; string file = "sample.pdf"; string fileName = "SampleFile"; // optional string response = vendor.Evaults.UploadDocument(evaultId, file, fileName); ``` Response: Id of uploaded document - Vendor Delete Document [View detail](https://sandbox.reggora.io/#vendor-delete-document) ``` string evaultId = "5c4f16764672bb00105ea5f9"; string documentId = "24bab39a-4404-11e8-ba10-02420a050006"; response = vendor.Evaults.DeleteDocument(evaultId, documentId); ``` Response: "Your document has been deleted"<file_sep>/Reggora.Api/Requests/AuthenticateRequest.cs using Newtonsoft.Json; using RestSharp; namespace Reggora.Api.Requests { public abstract class AuthenticateRequest : ReggoraRequest { protected AuthenticateRequest(string type, string username, string password) : base($"{type}/auth", Method.POST) { AddJsonBody(new Request { Username = username, Password = <PASSWORD> }); } public new Response Execute(IRestClient client) { return Execute<Response>(client); } public class Request { [JsonProperty("username")] public string Username; [JsonProperty("password")] public string Password; } public class Response { [JsonProperty("token")] public string Token { get; set; } } } }<file_sep>/Reggora.Api/Requests/Vendor/Order/UploadSubmissionRequest.cs using RestSharp; namespace Reggora.Api.Requests.Vendor.Order { public class UploadSubmissionRequest : ReggoraRequest { public UploadSubmissionRequest(string orderId, string pdfFilePath, string xmlFilePath, string invoiceFilePath, string invoiceNumber) : base("vendor/submission/{order_id}", Method.PUT) { AddParameter("order_id", orderId, ParameterType.UrlSegment); AddFile("pdf_file", pdfFilePath, MimeMapping.MimeUtility.GetMimeMapping(pdfFilePath)); if (xmlFilePath != null) { AddFile("xml_file", xmlFilePath, MimeMapping.MimeUtility.GetMimeMapping(xmlFilePath)); } if (invoiceFilePath != null) { AddFile("invoice_file", invoiceFilePath, MimeMapping.MimeUtility.GetMimeMapping(invoiceFilePath)); } if (invoiceNumber != null) { AddParameter("invoice_number", invoiceNumber); } } } }<file_sep>/Reggora.Api/Vendor.cs using Reggora.Api.Authentication; using Reggora.Api.Requests.Vendor; using Reggora.Api.Storage.Vendor; namespace Reggora.Api { public class Vendor : ApiClient<Vendor> { public readonly OrderManagementStorage VendorOrders; public readonly ConversationManagementStorage Conversations; public readonly EvaultManagementStorage Evaults; public Vendor(string integrationToken) : base(integrationToken) { VendorOrders = new OrderManagementStorage(this); Conversations = new ConversationManagementStorage(this); Evaults = new EvaultManagementStorage(this); } public override Vendor Authenticate(string email, string password) { var response = new VendorAuthenticateRequest(email, password).Execute(Client); Client.Authenticator = new ReggoraJwtAuthenticator(IntegrationToken, response.Token); return this; } } }<file_sep>/Reggora.Api/Exceptions/InternalServerErrorException.cs using System; namespace Reggora.Api.Exceptions { public class InternalServerErrorException : ReggoraException { public InternalServerErrorException(Exception innerError) : base( "Internal Server Error -- We had a problem with our server. Try again later.", innerError) { } public InternalServerErrorException(string message, Exception innerError) : base(message, innerError) { } } }
c4b955bea1cc923fd48e23dca28d43065f9e7a99
[ "Markdown", "C#" ]
95
C#
Reggora/reggora-csharp
a786bf2ed7eb150a7807073fb40018626cedb7d9
ef1f361c92dca2181f2cbe5c2bfae65ec75d3425
refs/heads/master
<repo_name>dreizehnutters/EFBP<file_sep>/simulation/El-Farol-Bar/simulation-worker.js self.importScripts("../framework/simulation-worker-core.js"); self.importScripts("simulation.js"); if (sim.model.objectTypes) { sim.model.objectTypes.forEach( function (objT) { self.importScripts( objT + ".js"); }); } if (sim.model.eventTypes) { sim.model.eventTypes.forEach( function (evtT) { self.importScripts( evtT + ".js"); }); } if (sim.model.activityTypes) { sim.model.activityTypes.forEach( function (actT) { self.importScripts( actT + ".js"); }); } //================================================================= sim.initializeSimulator(); onmessage = function (e) { if (e.data.runExperiment) sim.runExperiment(); else { if (e.data.endTime) sim.scenario.simulationEndTime = e.data.endTime; sim.runScenario( true); // run in worker thread } } <file_sep>/simulation/El-Farol-Bar/simulation.js /******************************************************* Simulation Parameters ********************************************************/ sim.scenario.simulationEndTime = 1000; sim.scenario.randomSeed = 42; sim.scenario.createLog = false; sim.config.visualize = false; sim.config.userInteractive = false; /******************************************************* Simulation Model ********************************************************/ sim.model.time = "discrete"; sim.model.name = "El-Farol-Bar Simulation"; sim.model.title = sim.model.name; sim.model.objectTypes = ["Bar", "Person", "Strategie"]; sim.model.eventTypes = ["Force2Decide"]; sim.model.v.numOfStrats = 1; sim.model.v.memorizeSize = 100; sim.model.v.numOfPpl = 100; sim.model.v.OCthreshold = 0.6; sim.model.v.decimalPoints = 6; sim.model.v.learningRate = 0.00005; /******************************************************* Define Initial State ********************************************************/ sim.scenario.initialState.objects = { "1": {typeName: "Bar", name:"bar", shortLabel:"bar", overcThr: parseInt(sim.model.v.numOfPpl * sim.model.v.OCthreshold ), visitors: 56, initOC: 56 >= parseInt(sim.model.v.numOfPpl * sim.model.v.OCthreshold)} }; // Setup the initial state of the simulation scenario sim.scenario.setupInitialState = function () { sim.stat.timesPersonWent = {}; var initMem = Array(sim.model.v.memorizeSize).fill().map(() => rand.uniformInt(1,sim.model.v.numOfPpl)); for (var i = sim.model.v.numOfPpl+1; i >= 2; i--) { var initStart = []; for (var j = 0; j < sim.model.v.numOfStrats ; j++) { initStart.push(new Strategie({name: "Strat", id: (200+i*sim.model.v.numOfStrats)+j, strat: Array(sim.model.v.memorizeSize).fill().map(() => parseFloat(rand.uniform(-1,1).toPrecision(sim.model.v.decimalPoints)))})) } sim.addObject(new Person({typeName: "Person", id: i, name:"person"+(i-1), shortLabel: "per", memorie: initMem, strategie: initStart})); sim.stat.timesPersonWent[i] = 0; } }; sim.scenario.initialState.events = [ {typeName: "Force2Decide", occTime:1} ]; /******************************************************* Define Output Statistics Variables ********************************************************/ sim.model.statistics = { "attendanceHist": {range:"Decimal", label:"attendance in %", initialValue: 0, showTimeSeries: true, computeOnlyAtEnd: false, expression: function () { return parseFloat(cLASS["Bar"].instances[1].visitors/100); }}, "ocline": {range:"Decimal", label:"OC line", initialValue: 0, showTimeSeries: true, computeOnlyAtEnd: false, expression: function () { return parseFloat(sim.model.v.numOfPpl * sim.model.v.OCthreshold/100); }}, "maxAtt": {objectType: "Bar", objectIdRef: 1, property:"visitors", range:"NonNegativeInteger", label:"max attendance", aggregationFunction: "max"}, "minAtr": {objectType:"Bar", objectIdRef: 1, property:"visitors", range:"NonNegativeInteger", label:"min attendance", aggregationFunction: "min"}, "avgAtt": {objectType:"Bar", objectIdRef: 1, property:"visitors",range:"NonNegativeInteger", label:"avg attendance", aggregationFunction: "avg"}, "overcTime": {range:"Decimal", label:"OC proportion", initialValue: 0, showTimeSeries: false, computeOnlyAtEnd: true, expression: function () { console.log("attendance histogramm") console.log(sim.stat.timesPersonWent); return ((sim.stat.overcTime+cLASS["Bar"].instances[1].initOC)/sim.scenario.simulationEndTime); } } };<file_sep>/README.md # EFBP Multi-Agent simulation of the El Farol Bar Problem using RL <file_sep>/simulation/El-Farol-Bar/Force2Decide.js var Force2Decide = new cLASS({ Name: "Force2Decide", shortLabel: "W", supertypeName: "eVENT", properties: {}, methods: { "onEvent": function () { var population= cLASS["Person"].instances; var elFarol = cLASS["Bar"].instances[1]; //var time = this.occTime; //cleanUp elFarol.visitors = 0; // let persons decide to go or not Object.keys(population).forEach( function ( objId ) { elFarol.visitors += population[objId].decide(elFarol.overcThr)}); sim.stat.overcTime += elFarol.isOC(); //console.log(window.URL.createObjectURL(new Blob([cLASS["Person"].instances[12].strategie[0].strat[2].toSource()], {type:'text/plain'}))); //console.log(cLASS["Person"].instances[12].strategie[0].strat[2]) //inform population what happend Object.keys(population).forEach( function ( objId ) { population[objId].updateStrategie(elFarol.visitors)}); return []; } } }); Force2Decide.recurrence = function () { return 1; }; <file_sep>/simulation/El-Farol-Bar/Strategie.js var Strategie = new cLASS({ Name: "Strategie", supertypeName: "oBJECT", properties: { "strat": { range: "Decimal", maxCard: sim.model.v.memorizeSize, label: "a Strategie", shortLabel: "strat"} }, methods:{ "evaluate": function( memorie ){ // O = (w1,w2,w3) // M = (m1,m2,m3) // n = ((w1*m1 + w2*m2 + w3*m3) // d = (w1 + w2 + w3)) // return n/d return (((this.strat.reduce(function(r,a,i){return r+a*memorie[i]},0)))/((this.strat.reduce((a, z) => a+z, 0)))); } }, }); <file_sep>/simulation/El-Farol-Bar/Person.js var Person = new cLASS({ Name: "Person", supertypeName: "oBJECT", properties: { "memorie": {range: "PositiveInteger", maxCard: sim.model.v.memorizeSize, label: "Memorysize", shortLabel: "memsize"}, "strategie": {range: "Strategie", maxCard: sim.model.v.numOfStrats, label: "Strategies", shortLabel: "strats"}, "prediction": {range: "PositiveInteger", label: "pred", shortLabel:"lasp"} }, methods:{ "decide": function ( overcThr ) { //this.prediction = Math.abs(parseInt(this.strategie[0].evaluate(this.memorie))); this.prediction = this.strategie[0].evaluate(this.memorie); if (this.prediction < overcThr) { sim.stat.timesPersonWent[this.id] += 1; return true; } else { return false } }, "updateStrategie": function ( visitors ) { // delta = alpha * (actual - prediction) var delta = parseFloat((sim.model.v.learningRate*(visitors - this.prediction)).toPrecision(sim.model.v.decimalPoints)); // delta = alpha * (prediction - actual) //var delta = parseFloat((sim.model.v.learningRate*(this.prediction - visitors)).toPrecision(sim.model.v.decimalPoints)); var mem = this.memorie; //w_i = w_i + alpha((actual*(w_i*memorie_i)/prediction) - (w_i*memorie_i)) //this.strategie[0].strat = this.strategie[0].strat.map(function (w,index){return parseFloat((w+sim.model.v.learningRate*((visitors*(w*mem[index])/this.prediction)-(w*mem[index]))).toFixed(sim.model.v.decimalPoints))}, this); //w_i = w+atan2(w_i, delta) this.strategie[0].strat = this.strategie[0].strat.map(function (w){return parseFloat((w-Math.atan2(w,delta)).toFixed(sim.model.v.decimalPoints))},this); //this.strategie[0].strat = this.strategie[0].strat.map(function (w){return parseFloat(sim.model.v.learningRate*(Math.atan2(w,delta)).toFixed(sim.model.v.decimalPoints))},this); // w_i = w_i - alpha * (prediction - actual) * stimulus_i //this.strategie[0].strat = this.strategie[0].strat.map(function (w, idx){return parseFloat((w+delta*mem[idx]).toPrecision(sim.model.v.decimalPoints))}); // w_i = w_i - delta //this.strategie[0].strat = this.strategie[0].strat.map(function (w){return parseFloat((w-delta).toPrecision(sim.model.v.decimalPoints))}); //update memorie this.memorie = this.memorie.slice(1); this.memorie.push(visitors); } }, });
0ed8e34fd59559129439558eea16e67c391a5748
[ "JavaScript", "Markdown" ]
6
JavaScript
dreizehnutters/EFBP
8e60c86343297b14b716d80c75205fcf347abbde
b42d3c693e67602b4d5baeccc19257f9b3ec0110
refs/heads/main
<repo_name>jamesETsmith/ablog_test.github.io<file_sep>/pyscf_api_docs/pyscf.cc.rst pyscf.cc package ================ Submodules ---------- pyscf.cc.addons module ---------------------- .. automodule:: pyscf.cc.addons :members: :undoc-members: :show-inheritance: pyscf.cc.ccd module ------------------- .. automodule:: pyscf.cc.ccd :members: :undoc-members: :show-inheritance: pyscf.cc.ccsd module -------------------- .. automodule:: pyscf.cc.ccsd :members: :undoc-members: :show-inheritance: pyscf.cc.ccsd\_lambda module ---------------------------- .. automodule:: pyscf.cc.ccsd_lambda :members: :undoc-members: :show-inheritance: pyscf.cc.ccsd\_rdm module ------------------------- .. automodule:: pyscf.cc.ccsd_rdm :members: :undoc-members: :show-inheritance: pyscf.cc.ccsd\_rdm\_slow module ------------------------------- .. automodule:: pyscf.cc.ccsd_rdm_slow :members: :undoc-members: :show-inheritance: pyscf.cc.ccsd\_t module ----------------------- .. automodule:: pyscf.cc.ccsd_t :members: :undoc-members: :show-inheritance: pyscf.cc.ccsd\_t\_lambda\_slow module ------------------------------------- .. automodule:: pyscf.cc.ccsd_t_lambda_slow :members: :undoc-members: :show-inheritance: pyscf.cc.ccsd\_t\_rdm\_slow module ---------------------------------- .. automodule:: pyscf.cc.ccsd_t_rdm_slow :members: :undoc-members: :show-inheritance: pyscf.cc.ccsd\_t\_slow module ----------------------------- .. automodule:: pyscf.cc.ccsd_t_slow :members: :undoc-members: :show-inheritance: pyscf.cc.dfccsd module ---------------------- .. automodule:: pyscf.cc.dfccsd :members: :undoc-members: :show-inheritance: pyscf.cc.eom\_gccsd module -------------------------- .. automodule:: pyscf.cc.eom_gccsd :members: :undoc-members: :show-inheritance: pyscf.cc.eom\_rccsd module -------------------------- .. automodule:: pyscf.cc.eom_rccsd :members: :undoc-members: :show-inheritance: pyscf.cc.eom\_rccsd\_hybrid module ---------------------------------- .. automodule:: pyscf.cc.eom_rccsd_hybrid :members: :undoc-members: :show-inheritance: pyscf.cc.eom\_uccsd module -------------------------- .. automodule:: pyscf.cc.eom_uccsd :members: :undoc-members: :show-inheritance: pyscf.cc.gccsd module --------------------- .. automodule:: pyscf.cc.gccsd :members: :undoc-members: :show-inheritance: pyscf.cc.gccsd\_lambda module ----------------------------- .. automodule:: pyscf.cc.gccsd_lambda :members: :undoc-members: :show-inheritance: pyscf.cc.gccsd\_rdm module -------------------------- .. automodule:: pyscf.cc.gccsd_rdm :members: :undoc-members: :show-inheritance: pyscf.cc.gccsd\_t module ------------------------ .. automodule:: pyscf.cc.gccsd_t :members: :undoc-members: :show-inheritance: pyscf.cc.gccsd\_t\_lambda module -------------------------------- .. automodule:: pyscf.cc.gccsd_t_lambda :members: :undoc-members: :show-inheritance: pyscf.cc.gccsd\_t\_rdm module ----------------------------- .. automodule:: pyscf.cc.gccsd_t_rdm :members: :undoc-members: :show-inheritance: pyscf.cc.gccsd\_t\_slow module ------------------------------ .. automodule:: pyscf.cc.gccsd_t_slow :members: :undoc-members: :show-inheritance: pyscf.cc.gintermediates module ------------------------------ .. automodule:: pyscf.cc.gintermediates :members: :undoc-members: :show-inheritance: pyscf.cc.rccsd module --------------------- .. automodule:: pyscf.cc.rccsd :members: :undoc-members: :show-inheritance: pyscf.cc.rccsd\_hybrid module ----------------------------- .. automodule:: pyscf.cc.rccsd_hybrid :members: :undoc-members: :show-inheritance: pyscf.cc.rccsd\_lambda module ----------------------------- .. automodule:: pyscf.cc.rccsd_lambda :members: :undoc-members: :show-inheritance: pyscf.cc.rccsd\_slow module --------------------------- .. automodule:: pyscf.cc.rccsd_slow :members: :undoc-members: :show-inheritance: pyscf.cc.rintermediates module ------------------------------ .. automodule:: pyscf.cc.rintermediates :members: :undoc-members: :show-inheritance: pyscf.cc.uccsd module --------------------- .. automodule:: pyscf.cc.uccsd :members: :undoc-members: :show-inheritance: pyscf.cc.uccsd\_lambda module ----------------------------- .. automodule:: pyscf.cc.uccsd_lambda :members: :undoc-members: :show-inheritance: pyscf.cc.uccsd\_rdm module -------------------------- .. automodule:: pyscf.cc.uccsd_rdm :members: :undoc-members: :show-inheritance: pyscf.cc.uccsd\_slow module --------------------------- .. automodule:: pyscf.cc.uccsd_slow :members: :undoc-members: :show-inheritance: pyscf.cc.uccsd\_t module ------------------------ .. automodule:: pyscf.cc.uccsd_t :members: :undoc-members: :show-inheritance: pyscf.cc.uccsd\_t\_lambda module -------------------------------- .. automodule:: pyscf.cc.uccsd_t_lambda :members: :undoc-members: :show-inheritance: pyscf.cc.uccsd\_t\_rdm module ----------------------------- .. automodule:: pyscf.cc.uccsd_t_rdm :members: :undoc-members: :show-inheritance: pyscf.cc.uccsd\_t\_slow module ------------------------------ .. automodule:: pyscf.cc.uccsd_t_slow :members: :undoc-members: :show-inheritance: pyscf.cc.uintermediates module ------------------------------ .. automodule:: pyscf.cc.uintermediates :members: :undoc-members: :show-inheritance: pyscf.cc.uintermediates\_slow module ------------------------------------ .. automodule:: pyscf.cc.uintermediates_slow :members: :undoc-members: :show-inheritance: Module contents --------------- .. automodule:: pyscf.cc :members: :undoc-members: :show-inheritance: <file_sep>/prep_for_commit.sh #!/bin/bash # rm -rf docs mv _website docs touch docs/.nojekyll<file_sep>/pyscf_api_docs/pyscf.gw.rst pyscf.gw package ================ Submodules ---------- pyscf.gw.gw module ------------------ .. automodule:: pyscf.gw.gw :members: :undoc-members: :show-inheritance: pyscf.gw.gw\_slow module ------------------------ .. automodule:: pyscf.gw.gw_slow :members: :undoc-members: :show-inheritance: Module contents --------------- .. automodule:: pyscf.gw :members: :undoc-members: :show-inheritance: <file_sep>/pyscf_api_docs/pyscf.mrpt.rst pyscf.mrpt package ================== Submodules ---------- pyscf.mrpt.nevpt2 module ------------------------ .. automodule:: pyscf.mrpt.nevpt2 :members: :undoc-members: :show-inheritance: Module contents --------------- .. automodule:: pyscf.mrpt :members: :undoc-members: :show-inheritance: <file_sep>/posts/post_01.md --- blogpost: true date: Apr 15, 2019 author: <NAME> location: World category: Update tags: software language: English --- # Update 4/15/2019 This year, PySCF will celebrate the 5th anniversary of its first commit. In this short period, PySCF has changed from being a single-group code to one relied on daily by over 100 research teams in academia and industry across the world. The PySCF paper was one of the 10 most downloaded articles in WIREs Computational Molecular Science in 2018! Today we are excited to announce a new model for managing the future development and directions of the code. This responsibility will now fall to the PySCF board of directors. The initial board members will be: - <NAME>, Columbia and Flatiron Institute - <NAME>, Caltech - <NAME>, UC Boulder - <NAME>, Ohio State - <NAME>, Tencent Quantum Laboratory The aims of the board will be to: 1. maintain the continued high quality of the existing codebase 2. assess proposals for new features and pull requests 3. coordinate development and education across the community 4. ensure adequate funding for these efforts Stay tuned for more updates soon on our new activities!<file_sep>/docs/_sources/pyscf_api_docs/pyscf.qmmm.rst.txt pyscf.qmmm package ================== Submodules ---------- pyscf.qmmm.itrf module ---------------------- .. automodule:: pyscf.qmmm.itrf :members: :undoc-members: :show-inheritance: pyscf.qmmm.mm\_mole module -------------------------- .. automodule:: pyscf.qmmm.mm_mole :members: :undoc-members: :show-inheritance: Module contents --------------- .. automodule:: pyscf.qmmm :members: :undoc-members: :show-inheritance: <file_sep>/pyscf_api_docs/pyscf.hci.rst pyscf.hci package ================= Submodules ---------- pyscf.hci.hci module -------------------- .. automodule:: pyscf.hci.hci :members: :undoc-members: :show-inheritance: Module contents --------------- .. automodule:: pyscf.hci :members: :undoc-members: :show-inheritance: <file_sep>/pyscf_api_docs/pyscf.grad.rst pyscf.grad package ================== Submodules ---------- pyscf.grad.casci module ----------------------- .. automodule:: pyscf.grad.casci :members: :undoc-members: :show-inheritance: pyscf.grad.casscf module ------------------------ .. automodule:: pyscf.grad.casscf :members: :undoc-members: :show-inheritance: pyscf.grad.ccsd module ---------------------- .. automodule:: pyscf.grad.ccsd :members: :undoc-members: :show-inheritance: pyscf.grad.ccsd\_slow module ---------------------------- .. automodule:: pyscf.grad.ccsd_slow :members: :undoc-members: :show-inheritance: pyscf.grad.ccsd\_t module ------------------------- .. automodule:: pyscf.grad.ccsd_t :members: :undoc-members: :show-inheritance: pyscf.grad.cisd module ---------------------- .. automodule:: pyscf.grad.cisd :members: :undoc-members: :show-inheritance: pyscf.grad.dhf module --------------------- .. automodule:: pyscf.grad.dhf :members: :undoc-members: :show-inheritance: pyscf.grad.mp2 module --------------------- .. automodule:: pyscf.grad.mp2 :members: :undoc-members: :show-inheritance: pyscf.grad.rhf module --------------------- .. automodule:: pyscf.grad.rhf :members: :undoc-members: :show-inheritance: pyscf.grad.rks module --------------------- .. automodule:: pyscf.grad.rks :members: :undoc-members: :show-inheritance: pyscf.grad.rohf module ---------------------- .. automodule:: pyscf.grad.rohf :members: :undoc-members: :show-inheritance: pyscf.grad.roks module ---------------------- .. automodule:: pyscf.grad.roks :members: :undoc-members: :show-inheritance: pyscf.grad.tdrhf module ----------------------- .. automodule:: pyscf.grad.tdrhf :members: :undoc-members: :show-inheritance: pyscf.grad.tdrks module ----------------------- .. automodule:: pyscf.grad.tdrks :members: :undoc-members: :show-inheritance: pyscf.grad.tduhf module ----------------------- .. automodule:: pyscf.grad.tduhf :members: :undoc-members: :show-inheritance: pyscf.grad.tduks module ----------------------- .. automodule:: pyscf.grad.tduks :members: :undoc-members: :show-inheritance: pyscf.grad.uccsd module ----------------------- .. automodule:: pyscf.grad.uccsd :members: :undoc-members: :show-inheritance: pyscf.grad.uccsd\_t module -------------------------- .. automodule:: pyscf.grad.uccsd_t :members: :undoc-members: :show-inheritance: pyscf.grad.ucisd module ----------------------- .. automodule:: pyscf.grad.ucisd :members: :undoc-members: :show-inheritance: pyscf.grad.uhf module --------------------- .. automodule:: pyscf.grad.uhf :members: :undoc-members: :show-inheritance: pyscf.grad.uks module --------------------- .. automodule:: pyscf.grad.uks :members: :undoc-members: :show-inheritance: pyscf.grad.ump2 module ---------------------- .. automodule:: pyscf.grad.ump2 :members: :undoc-members: :show-inheritance: Module contents --------------- .. automodule:: pyscf.grad :members: :undoc-members: :show-inheritance: <file_sep>/docs/pyscf_api_docs/pyscf.pbc.gto/index.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <meta name="viewport" content="width=device-width,initial-scale=1"> <meta http-equiv="x-ua-compatible" content="ie=edge"> <meta name="lang:clipboard.copy" content="Copy to clipboard"> <meta name="lang:clipboard.copied" content="Copied to clipboard"> <meta name="lang:search.language" content="en"> <meta name="lang:search.pipeline.stopwords" content="True"> <meta name="lang:search.pipeline.trimmer" content="True"> <meta name="lang:search.result.none" content="No matching documents"> <meta name="lang:search.result.one" content="1 matching document"> <meta name="lang:search.result.other" content="# matching documents"> <meta name="lang:search.tokenizer" content="[\s\-]+"> <link href="https://fonts.gstatic.com/" rel="preconnect" crossorigin> <link href="https://fonts.googleapis.com/css?family=Roboto+Mono:400,500,700|Roboto:300,400,400i,700&display=fallback" rel="stylesheet"> <style> body, input { font-family: "Roboto", "Helvetica Neue", Helvetica, Arial, sans-serif } code, kbd, pre { font-family: "Roboto Mono", "Courier New", Courier, monospace } </style> <link rel="stylesheet" href="../../_static/stylesheets/application.css"/> <link rel="stylesheet" href="../../_static/stylesheets/application-palette.css"/> <link rel="stylesheet" href="../../_static/stylesheets/application-fixes.css"/> <link rel="stylesheet" href="../../_static/fonts/material-icons.css"/> <meta name="theme-color" content="#3f51b5"> <script src="../../_static/javascripts/modernizr.js"></script> <title>pyscf.pbc.gto package &#8212; PySCF documentation</title> <link rel="stylesheet" href="../../_static/pygments.css" type="text/css" /> <link rel="stylesheet" href="../../_static/material.css" type="text/css" /> <script id="documentation_options" data-url_root="../../" src="../../_static/documentation_options.js"></script> <script src="../../_static/jquery.js"></script> <script src="../../_static/underscore.js"></script> <script src="../../_static/doctools.js"></script> <script async="async" src="https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.7/latest.js?config=TeX-AMS-MML_HTMLorMML"></script> <link rel="author" title="About these documents" href="../../about/" /> <link rel="index" title="Index" href="../../genindex/" /> <link rel="search" title="Search" href="../../search/" /> <link rel="next" title="pyscf.pbc.gto.basis package" href="../pyscf.pbc.gto.basis/" /> <link rel="prev" title="pyscf.pbc.grad package" href="../pyscf.pbc.grad/" /> <style type="text/css"> ul.ablog-archive { list-style: none; overflow: auto; margin-left: 0px; } ul.ablog-archive li { float: left; margin-right: 5px; font-size: 80%; } ul.postlist a { font-style: italic; } ul.postlist-style-disc { list-style-type: disc; } ul.postlist-style-none { list-style-type: none; } ul.postlist-style-circle { list-style-type: circle; } </style> </head> <body dir=ltr data-md-color-primary=indigo data-md-color-accent=yellow> <svg class="md-svg"> <defs data-children-count="0"> <svg xmlns="http://www.w3.org/2000/svg" width="416" height="448" viewBox="0 0 416 448" id="__github"><path fill="currentColor" d="M160 304q0 10-3.125 20.5t-10.75 19T128 352t-18.125-8.5-10.75-19T96 304t3.125-20.5 10.75-19T128 256t18.125 8.5 10.75 19T160 304zm160 0q0 10-3.125 20.5t-10.75 19T288 352t-18.125-8.5-10.75-19T256 304t3.125-20.5 10.75-19T288 256t18.125 8.5 10.75 19T320 304zm40 0q0-30-17.25-51T296 232q-10.25 0-48.75 5.25Q229.5 240 208 240t-39.25-2.75Q130.75 232 120 232q-29.5 0-46.75 21T56 304q0 22 8 38.375t20.25 25.75 30.5 15 35 7.375 37.25 1.75h42q20.5 0 37.25-1.75t35-7.375 30.5-15 20.25-25.75T360 304zm56-44q0 51.75-15.25 82.75-9.5 19.25-26.375 33.25t-35.25 21.5-42.5 11.875-42.875 5.5T212 416q-19.5 0-35.5-.75t-36.875-3.125-38.125-7.5-34.25-12.875T37 371.5t-21.5-28.75Q0 312 0 260q0-59.25 34-99-6.75-20.5-6.75-42.5 0-29 12.75-54.5 27 0 47.5 9.875t47.25 30.875Q171.5 96 212 96q37 0 70 8 26.25-20.5 46.75-30.25T376 64q12.75 25.5 12.75 54.5 0 21.75-6.75 42 34 40 34 99.5z"/></svg> </defs> </svg> <input class="md-toggle" data-md-toggle="drawer" type="checkbox" id="__drawer"> <input class="md-toggle" data-md-toggle="search" type="checkbox" id="__search"> <label class="md-overlay" data-md-component="overlay" for="__drawer"></label> <a href="#pyscf_api_docs/pyscf.pbc.gto" tabindex="1" class="md-skip"> Skip to content </a> <header class="md-header" data-md-component="header"> <nav class="md-header-nav md-grid"> <div class="md-flex navheader"> <div class="md-flex__cell md-flex__cell--shrink"> <a href="../../" title="PySCF documentation" class="md-header-nav__button md-logo"> &nbsp; </a> </div> <div class="md-flex__cell md-flex__cell--shrink"> <label class="md-icon md-icon--menu md-header-nav__button" for="__drawer"></label> </div> <div class="md-flex__cell md-flex__cell--stretch"> <div class="md-flex__ellipsis md-header-nav__title" data-md-component="title"> <span class="md-header-nav__topic">PySCF Docs</span> <span class="md-header-nav__topic"> pyscf.pbc.gto package </span> </div> </div> <div class="md-flex__cell md-flex__cell--shrink"> <label class="md-icon md-icon--search md-header-nav__button" for="__search"></label> <div class="md-search" data-md-component="search" role="dialog"> <label class="md-search__overlay" for="__search"></label> <div class="md-search__inner" role="search"> <form class="md-search__form" action="../../search/" method="GET" name="search"> <input type="text" class="md-search__input" name="q" placeholder="Search" autocapitalize="off" autocomplete="off" spellcheck="false" data-md-component="query" data-md-state="active"> <label class="md-icon md-search__icon" for="__search"></label> <button type="reset" class="md-icon md-search__icon" data-md-component="reset" tabindex="-1"> &#xE5CD; </button> </form> <div class="md-search__output"> <div class="md-search__scrollwrap" data-md-scrollfix> <div class="md-search-result" data-md-component="result"> <div class="md-search-result__meta"> Type to start searching </div> <ol class="md-search-result__list"></ol> </div> </div> </div> </div> </div> </div> <script src="../../_static/javascripts/version_dropdown.js"></script> <script> var json_loc = "../../"versions.json"", target_loc = "../../../", text = "Versions"; $( document ).ready( add_version_dropdown(json_loc, target_loc, text)); </script> </div> </nav> </header> <div class="md-container"> <nav class="md-tabs" data-md-component="tabs"> <div class="md-tabs__inner md-grid"> <ul class="md-tabs__list"> <li class="md-tabs__item"><a href="../../" class="md-tabs__link">PySCF documentation</a></li> <li class="md-tabs__item"><a href="../../about/" class="md-tabs__link">About</a></li> <li class="md-tabs__item"><a href="../../blog_wrapper/" class="md-tabs__link">Blog</a></li> <li class="md-tabs__item"><a href="../modules/" class="md-tabs__link">API Docs</a></li> <li class="md-tabs__item"><a href="../pyscf/" class="md-tabs__link">pyscf package</a></li> <li class="md-tabs__item"><a href="../pyscf.pbc/" class="md-tabs__link">pyscf.pbc package</a></li> </ul> </div> </nav> <main class="md-main"> <div class="md-main__inner md-grid" data-md-component="container"> <div class="md-sidebar md-sidebar--primary" data-md-component="navigation"> <div class="md-sidebar__scrollwrap"> <div class="md-sidebar__inner"> <nav class="md-nav md-nav--primary" data-md-level="0"> <label class="md-nav__title md-nav__title--site" for="__drawer"> <a href="../../" title="PySCF documentation" class="md-nav__button md-logo"> <img src="../../_static/" alt=" logo" width="48" height="48"> </a> <a href="../../" title="PySCF documentation">PySCF Docs</a> </label> <ul class="md-nav__list"> <li class="md-nav__item"> <a href="../../about/" class="md-nav__link">About</a> </li> <li class="md-nav__item"> <a href="../../blog_wrapper/" class="md-nav__link">Blog</a> </li> <li class="md-nav__item"> <a href="../pyscf/" class="md-nav__link">API Docs</a> <ul class="md-nav__list"> <li class="md-nav__item"> <a href="../pyscf/#subpackages" class="md-nav__link">Subpackages</a> </li> <li class="md-nav__item"> <a href="../pyscf/#submodules" class="md-nav__link">Submodules</a> </li> <li class="md-nav__item"> <a href="../pyscf/#module-pyscf.post_scf" class="md-nav__link">pyscf.post_scf module</a> </li> <li class="md-nav__item"> <a href="../pyscf/#module-pyscf" class="md-nav__link">Module contents</a> </li></ul> </li> </ul> </nav> </div> </div> </div> <div class="md-sidebar md-sidebar--secondary" data-md-component="toc"> <div class="md-sidebar__scrollwrap"> <div class="md-sidebar__inner"> <nav class="md-nav md-nav--secondary"> <label class="md-nav__title" for="__toc">Contents</label> <ul class="md-nav__list" data-md-scrollfix=""> <li class="md-nav__item"><a href="#pyscf-api-docs-pyscf-pbc-gto--page-root" class="md-nav__link">pyscf.pbc.gto package</a><nav class="md-nav"> <ul class="md-nav__list"> <li class="md-nav__item"><a href="#subpackages" class="md-nav__link">Subpackages</a> </li> <li class="md-nav__item"><a href="#submodules" class="md-nav__link">Submodules</a> </li> <li class="md-nav__item"><a href="#module-pyscf.pbc.gto.cell" class="md-nav__link">pyscf.pbc.gto.cell module</a> </li> <li class="md-nav__item"><a href="#module-pyscf.pbc.gto.ecp" class="md-nav__link">pyscf.pbc.gto.ecp module</a> </li> <li class="md-nav__item"><a href="#module-pyscf.pbc.gto.eval_gto" class="md-nav__link">pyscf.pbc.gto.eval_gto module</a> </li> <li class="md-nav__item"><a href="#module-pyscf.pbc.gto" class="md-nav__link">Module contents</a> </li></ul> </nav> </li> <li class="md-nav__item"><a class="md-nav__extra_link" href="../../_sources/pyscf_api_docs/pyscf.pbc.gto.rst.txt">Show Source</a> </li> <li id="searchbox" class="md-nav__item"></li> </ul> </nav> </div> </div> </div> <div class="md-content"> <article class="md-content__inner md-typeset" role="main"> <div class="section" id="pyscf-pbc-gto-package"> <h1>pyscf.pbc.gto package<a class="headerlink" href="#pyscf-pbc-gto-package" title="Permalink to this headline">¶</a></h1> <div class="section" id="subpackages"> <h2>Subpackages<a class="headerlink" href="#subpackages" title="Permalink to this headline">¶</a></h2> <div class="toctree-wrapper compound"> <ul> <li class="toctree-l1"><a class="reference internal" href="../pyscf.pbc.gto.basis/">pyscf.pbc.gto.basis package</a><ul> <li class="toctree-l2"><a class="reference internal" href="../pyscf.pbc.gto.basis/#submodules">Submodules</a></li> <li class="toctree-l2"><a class="reference internal" href="../pyscf.pbc.gto.basis/#module-pyscf.pbc.gto.basis.parse_cp2k">pyscf.pbc.gto.basis.parse_cp2k module</a></li> <li class="toctree-l2"><a class="reference internal" href="../pyscf.pbc.gto.basis/#module-pyscf.pbc.gto.basis.split_BASIS_MOLOPT">pyscf.pbc.gto.basis.split_BASIS_MOLOPT module</a></li> <li class="toctree-l2"><a class="reference internal" href="../pyscf.pbc.gto.basis/#module-pyscf.pbc.gto.basis.split_GTH_BASIS_SETS">pyscf.pbc.gto.basis.split_GTH_BASIS_SETS module</a></li> <li class="toctree-l2"><a class="reference internal" href="../pyscf.pbc.gto.basis/#module-pyscf.pbc.gto.basis.split_HFX_BASIS">pyscf.pbc.gto.basis.split_HFX_BASIS module</a></li> <li class="toctree-l2"><a class="reference internal" href="../pyscf.pbc.gto.basis/#module-pyscf.pbc.gto.basis">Module contents</a></li> </ul> </li> <li class="toctree-l1"><a class="reference internal" href="../pyscf.pbc.gto.pseudo/">pyscf.pbc.gto.pseudo package</a><ul> <li class="toctree-l2"><a class="reference internal" href="../pyscf.pbc.gto.pseudo/#submodules">Submodules</a></li> <li class="toctree-l2"><a class="reference internal" href="../pyscf.pbc.gto.pseudo/#module-pyscf.pbc.gto.pseudo.parse_cp2k">pyscf.pbc.gto.pseudo.parse_cp2k module</a></li> <li class="toctree-l2"><a class="reference internal" href="../pyscf.pbc.gto.pseudo/#module-pyscf.pbc.gto.pseudo.pp">pyscf.pbc.gto.pseudo.pp module</a></li> <li class="toctree-l2"><a class="reference internal" href="../pyscf.pbc.gto.pseudo/#module-pyscf.pbc.gto.pseudo.pp_int">pyscf.pbc.gto.pseudo.pp_int module</a></li> <li class="toctree-l2"><a class="reference internal" href="../pyscf.pbc.gto.pseudo/#module-pyscf.pbc.gto.pseudo.split_GTH_POTENTIALS">pyscf.pbc.gto.pseudo.split_GTH_POTENTIALS module</a></li> <li class="toctree-l2"><a class="reference internal" href="../pyscf.pbc.gto.pseudo/#module-pyscf.pbc.gto.pseudo">Module contents</a></li> </ul> </li> </ul> </div> </div> <div class="section" id="submodules"> <h2>Submodules<a class="headerlink" href="#submodules" title="Permalink to this headline">¶</a></h2> </div> <div class="section" id="module-pyscf.pbc.gto.cell"> <span id="pyscf-pbc-gto-cell-module"></span><h2>pyscf.pbc.gto.cell module<a class="headerlink" href="#module-pyscf.pbc.gto.cell" title="Permalink to this headline">¶</a></h2> <dl class="py function"> <dt id="pyscf.pbc.gto.cell.C"> <code class="sig-prename descclassname">pyscf.pbc.gto.cell.</code><code class="sig-name descname">C</code><span class="sig-paren">(</span><em class="sig-param"><span class="o">**</span><span class="n">kwargs</span></em><span class="sig-paren">)</span><a class="headerlink" href="#pyscf.pbc.gto.cell.C" title="Permalink to this definition">¶</a></dt> <dd><p>This is a shortcut to build up Cell object.</p> <p>Examples:</p> <div class="doctest highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">from</span> <span class="nn">pyscf.pbc</span> <span class="kn">import</span> <span class="n">gto</span> <span class="gp">&gt;&gt;&gt; </span><span class="n">cell</span> <span class="o">=</span> <span class="n">gto</span><span class="o">.</span><span class="n">M</span><span class="p">(</span><span class="n">a</span><span class="o">=</span><span class="n">numpy</span><span class="o">.</span><span class="n">eye</span><span class="p">(</span><span class="mi">3</span><span class="p">)</span><span class="o">*</span><span class="mi">4</span><span class="p">,</span> <span class="n">atom</span><span class="o">=</span><span class="s1">&#39;He 1 1 1&#39;</span><span class="p">,</span> <span class="n">basis</span><span class="o">=</span><span class="s1">&#39;6-31g&#39;</span><span class="p">)</span> </pre></div> </div> </dd></dl> <dl class="py class"> <dt id="pyscf.pbc.gto.cell.Cell"> <em class="property">class </em><code class="sig-prename descclassname">pyscf.pbc.gto.cell.</code><code class="sig-name descname">Cell</code><span class="sig-paren">(</span><em class="sig-param"><span class="o">**</span><span class="n">kwargs</span></em><span class="sig-paren">)</span><a class="headerlink" href="#pyscf.pbc.gto.cell.Cell" title="Permalink to this definition">¶</a></dt> <dd><p>Bases: <a class="reference internal" href="../pyscf.gto/#pyscf.gto.mole.Mole" title="pyscf.gto.mole.Mole"><code class="xref py py-class docutils literal notranslate"><span class="pre">pyscf.gto.mole.Mole</span></code></a></p> <p>A Cell object holds the basic information of a crystal.</p> <dl> <dt>Attributes:</dt><dd><dl class="simple"> <dt>a<span class="classifier">(3,3) ndarray</span></dt><dd><p>Lattice primitive vectors. Each row represents a lattice vector Reciprocal lattice vectors are given by b1,b2,b3 = 2 pi inv(a).T</p> </dd> <dt>mesh<span class="classifier">(3,) list of ints</span></dt><dd><p>The number G-vectors along each direction. The default value is estimated based on <a class="reference internal" href="#pyscf.pbc.gto.cell.Cell.precision" title="pyscf.pbc.gto.cell.Cell.precision"><code class="xref py py-attr docutils literal notranslate"><span class="pre">precision</span></code></a></p> </dd> <dt>pseudo<span class="classifier">dict or str</span></dt><dd><p>To define pseudopotential.</p> </dd> <dt>precision<span class="classifier">float</span></dt><dd><p>To control Ewald sums and lattice sums accuracy</p> </dd> <dt>rcut<span class="classifier">float</span></dt><dd><p>Cutoff radius (unit Bohr) in lattice summation. The default value is estimated based on the required <a class="reference internal" href="#pyscf.pbc.gto.cell.Cell.precision" title="pyscf.pbc.gto.cell.Cell.precision"><code class="xref py py-attr docutils literal notranslate"><span class="pre">precision</span></code></a>.</p> </dd> <dt>ke_cutoff<span class="classifier">float</span></dt><dd><p>If set, defines a spherical cutoff of planewaves, with .5 * G**2 &lt; ke_cutoff The default value is estimated based on <a class="reference internal" href="#pyscf.pbc.gto.cell.Cell.precision" title="pyscf.pbc.gto.cell.Cell.precision"><code class="xref py py-attr docutils literal notranslate"><span class="pre">precision</span></code></a></p> </dd> <dt>dimension<span class="classifier">int</span></dt><dd><p>Periodic dimensions. Default is 3</p> </dd> <dt>low_dim_ft_type<span class="classifier">str</span></dt><dd><p>For semi-empirical periodic systems, whether to calculate integrals at the non-PBC dimension using the sampled mesh grids in infinity vacuum (inf_vacuum) or truncated Coulomb potential (analytic_2d_1). Unless explicitly specified, analytic_2d_1 is used for 2D system and inf_vacuum is assumed for 1D and 0D.</p> </dd> </dl> <p>** Following attributes (for experts) are automatically generated. **</p> <dl class="simple"> <dt>ew_eta, ew_cut<span class="classifier">float</span></dt><dd><p>The Ewald ‘eta’ and ‘cut’ parameters. See <a class="reference internal" href="#pyscf.pbc.gto.cell.get_ewald_params" title="pyscf.pbc.gto.cell.get_ewald_params"><code class="xref py py-func docutils literal notranslate"><span class="pre">get_ewald_params()</span></code></a></p> </dd> </dl> </dd> </dl> <p>(See other attributes in <code class="xref py py-class docutils literal notranslate"><span class="pre">Mole</span></code>)</p> <p>Examples:</p> <div class="doctest highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">mol</span> <span class="o">=</span> <span class="n">Mole</span><span class="p">(</span><span class="n">atom</span><span class="o">=</span><span class="s1">&#39;H^2 0 0 0; H 0 0 1.1&#39;</span><span class="p">,</span> <span class="n">basis</span><span class="o">=</span><span class="s1">&#39;sto3g&#39;</span><span class="p">)</span> <span class="gp">&gt;&gt;&gt; </span><span class="n">cl</span> <span class="o">=</span> <span class="n">Cell</span><span class="p">()</span> <span class="gp">&gt;&gt;&gt; </span><span class="n">cl</span><span class="o">.</span><span class="n">build</span><span class="p">(</span><span class="n">a</span><span class="o">=</span><span class="s1">&#39;3 0 0; 0 3 0; 0 0 3&#39;</span><span class="p">,</span> <span class="n">atom</span><span class="o">=</span><span class="s1">&#39;C 1 1 1&#39;</span><span class="p">,</span> <span class="n">basis</span><span class="o">=</span><span class="s1">&#39;sto3g&#39;</span><span class="p">)</span> <span class="gp">&gt;&gt;&gt; </span><span class="nb">print</span><span class="p">(</span><span class="n">cl</span><span class="o">.</span><span class="n">atom_symbol</span><span class="p">(</span><span class="mi">0</span><span class="p">))</span> <span class="go">C</span> </pre></div> </div> <dl class="py method"> <dt id="pyscf.pbc.gto.cell.Cell.Gv"> <em class="property">property </em><code class="sig-name descname">Gv</code><a class="headerlink" href="#pyscf.pbc.gto.cell.Cell.Gv" title="Permalink to this definition">¶</a></dt> <dd></dd></dl> <dl class="py method"> <dt id="pyscf.pbc.gto.cell.Cell.ao2mo"> <code class="sig-name descname">ao2mo</code><span class="sig-paren">(</span><em class="sig-param"><span class="n">mo_coeffs</span></em>, <em class="sig-param"><span class="n">intor</span><span class="o">=</span><span class="default_value">'int2e'</span></em>, <em class="sig-param"><span class="n">erifile</span><span class="o">=</span><span class="default_value">None</span></em>, <em class="sig-param"><span class="n">dataname</span><span class="o">=</span><span class="default_value">'eri_mo'</span></em>, <em class="sig-param"><span class="o">**</span><span class="n">kwargs</span></em><span class="sig-paren">)</span><a class="headerlink" href="#pyscf.pbc.gto.cell.Cell.ao2mo" title="Permalink to this definition">¶</a></dt> <dd><p>Integral transformation for arbitrary orbitals and arbitrary integrals. See more detalied documentation in func:<cite>ao2mo.kernel</cite>.</p> <dl class="simple"> <dt>Args:</dt><dd><dl class="simple"> <dt>mo_coeffs (an np array or a list of arrays)<span class="classifier">A matrix of orbital</span></dt><dd><p>coefficients if it is a numpy ndarray, or four sets of orbital coefficients, corresponding to the four indices of (ij|kl).</p> </dd> </dl> </dd> <dt>Kwargs:</dt><dd><dl class="simple"> <dt>erifile (str or h5py File or h5py Group object)<span class="classifier">The file/object</span></dt><dd><p>to store the transformed integrals. If not given, the return value is an array (in memory) of the transformed integrals.</p> </dd> <dt>dataname<span class="classifier">str</span></dt><dd><p><em>Note</em> this argument is effective if erifile is given. The dataset name in the erifile (ref the hierarchy of HDF5 format <a class="reference external" href="http://www.hdfgroup.org/HDF5/doc1.6/UG/09_Groups.html">http://www.hdfgroup.org/HDF5/doc1.6/UG/09_Groups.html</a>). By assigning different dataname, the existed integral file can be reused. If the erifile contains the specified dataname, the old integrals will be replaced by the new one under the key dataname.</p> </dd> <dt>intor (str)<span class="classifier">integral name Name of the 2-electron integral. Ref</span></dt><dd><p>to <code class="xref py py-func docutils literal notranslate"><span class="pre">getints_by_shell()</span></code> for the complete list of available 2-electron integral names</p> </dd> </dl> </dd> <dt>Returns:</dt><dd><p>An array of transformed integrals if erifile is not given. Otherwise, return the file/fileobject if erifile is assigned.</p> </dd> </dl> <p>Examples:</p> <div class="doctest highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">import</span> <span class="nn">pyscf</span> <span class="gp">&gt;&gt;&gt; </span><span class="n">mol</span> <span class="o">=</span> <span class="n">pyscf</span><span class="o">.</span><span class="n">M</span><span class="p">(</span><span class="n">atom</span><span class="o">=</span><span class="s1">&#39;O 0 0 0; H 0 1 0; H 0 0 1&#39;</span><span class="p">,</span> <span class="n">basis</span><span class="o">=</span><span class="s1">&#39;sto3g&#39;</span><span class="p">)</span> <span class="gp">&gt;&gt;&gt; </span><span class="n">mo1</span> <span class="o">=</span> <span class="n">numpy</span><span class="o">.</span><span class="n">random</span><span class="o">.</span><span class="n">random</span><span class="p">((</span><span class="n">mol</span><span class="o">.</span><span class="n">nao_nr</span><span class="p">(),</span> <span class="mi">10</span><span class="p">))</span> <span class="gp">&gt;&gt;&gt; </span><span class="n">mo2</span> <span class="o">=</span> <span class="n">numpy</span><span class="o">.</span><span class="n">random</span><span class="o">.</span><span class="n">random</span><span class="p">((</span><span class="n">mol</span><span class="o">.</span><span class="n">nao_nr</span><span class="p">(),</span> <span class="mi">8</span><span class="p">))</span> </pre></div> </div> <div class="doctest highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">eri1</span> <span class="o">=</span> <span class="n">mol</span><span class="o">.</span><span class="n">ao2mo</span><span class="p">(</span><span class="n">mo1</span><span class="p">)</span> <span class="gp">&gt;&gt;&gt; </span><span class="nb">print</span><span class="p">(</span><span class="n">eri1</span><span class="o">.</span><span class="n">shape</span><span class="p">)</span> <span class="go">(55, 55)</span> </pre></div> </div> <div class="doctest highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">eri1</span> <span class="o">=</span> <span class="n">mol</span><span class="o">.</span><span class="n">ao2mo</span><span class="p">(</span><span class="n">mo1</span><span class="p">,</span> <span class="n">compact</span><span class="o">=</span><span class="kc">False</span><span class="p">)</span> <span class="gp">&gt;&gt;&gt; </span><span class="nb">print</span><span class="p">(</span><span class="n">eri1</span><span class="o">.</span><span class="n">shape</span><span class="p">)</span> <span class="go">(100, 100)</span> </pre></div> </div> <div class="doctest highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">eri1</span> <span class="o">=</span> <span class="n">mol</span><span class="o">.</span><span class="n">ao2mo</span><span class="p">(</span><span class="n">eri</span><span class="p">,</span> <span class="p">(</span><span class="n">mo1</span><span class="p">,</span><span class="n">mo2</span><span class="p">,</span><span class="n">mo2</span><span class="p">,</span><span class="n">mo2</span><span class="p">))</span> <span class="gp">&gt;&gt;&gt; </span><span class="nb">print</span><span class="p">(</span><span class="n">eri1</span><span class="o">.</span><span class="n">shape</span><span class="p">)</span> <span class="go">(80, 36)</span> </pre></div> </div> <div class="doctest highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">eri1</span> <span class="o">=</span> <span class="n">mol</span><span class="o">.</span><span class="n">ao2mo</span><span class="p">(</span><span class="n">eri</span><span class="p">,</span> <span class="p">(</span><span class="n">mo1</span><span class="p">,</span><span class="n">mo2</span><span class="p">,</span><span class="n">mo2</span><span class="p">,</span><span class="n">mo2</span><span class="p">),</span> <span class="n">erifile</span><span class="o">=</span><span class="s1">&#39;water.h5&#39;</span><span class="p">)</span> </pre></div> </div> </dd></dl> <dl class="py method"> <dt id="pyscf.pbc.gto.cell.Cell.bas_rcut"> <code class="sig-name descname">bas_rcut</code><span class="sig-paren">(</span><em class="sig-param"><span class="n">bas_id</span></em>, <em class="sig-param"><span class="n">precision</span><span class="o">=</span><span class="default_value">1e-08</span></em><span class="sig-paren">)</span><a class="headerlink" href="#pyscf.pbc.gto.cell.Cell.bas_rcut" title="Permalink to this definition">¶</a></dt> <dd><p>Estimate the largest distance between the function and its image to reach the precision in overlap</p> <p>precision ~ int g(r-0) g(r-Rcut)</p> </dd></dl> <dl class="py method"> <dt id="pyscf.pbc.gto.cell.Cell.build"> <code class="sig-name descname">build</code><span class="sig-paren">(</span><em class="sig-param"><span class="n">dump_input</span><span class="o">=</span><span class="default_value">True</span></em>, <em class="sig-param"><span class="n">parse_arg</span><span class="o">=</span><span class="default_value">True</span></em>, <em class="sig-param"><span class="n">a</span><span class="o">=</span><span class="default_value">None</span></em>, <em class="sig-param"><span class="n">mesh</span><span class="o">=</span><span class="default_value">None</span></em>, <em class="sig-param"><span class="n">ke_cutoff</span><span class="o">=</span><span class="default_value">None</span></em>, <em class="sig-param"><span class="n">precision</span><span class="o">=</span><span class="default_value">None</span></em>, <em class="sig-param"><span class="n">nimgs</span><span class="o">=</span><span class="default_value">None</span></em>, <em class="sig-param"><span class="n">ew_eta</span><span class="o">=</span><span class="default_value">None</span></em>, <em class="sig-param"><span class="n">ew_cut</span><span class="o">=</span><span class="default_value">None</span></em>, <em class="sig-param"><span class="n">pseudo</span><span class="o">=</span><span class="default_value">None</span></em>, <em class="sig-param"><span class="n">basis</span><span class="o">=</span><span class="default_value">None</span></em>, <em class="sig-param"><span class="n">h</span><span class="o">=</span><span class="default_value">None</span></em>, <em class="sig-param"><span class="n">dimension</span><span class="o">=</span><span class="default_value">None</span></em>, <em class="sig-param"><span class="n">rcut</span><span class="o">=</span><span class="default_value">None</span></em>, <em class="sig-param"><span class="n">ecp</span><span class="o">=</span><span class="default_value">None</span></em>, <em class="sig-param"><span class="n">low_dim_ft_type</span><span class="o">=</span><span class="default_value">None</span></em>, <em class="sig-param"><span class="o">*</span><span class="n">args</span></em>, <em class="sig-param"><span class="o">**</span><span class="n">kwargs</span></em><span class="sig-paren">)</span><a class="headerlink" href="#pyscf.pbc.gto.cell.Cell.build" title="Permalink to this definition">¶</a></dt> <dd><p>Setup Mole molecule and Cell and initialize some control parameters. Whenever you change the value of the attributes of <a class="reference internal" href="#pyscf.pbc.gto.cell.Cell" title="pyscf.pbc.gto.cell.Cell"><code class="xref py py-class docutils literal notranslate"><span class="pre">Cell</span></code></a>, you need call this function to refresh the internal data of Cell.</p> <dl class="simple"> <dt>Kwargs:</dt><dd><dl class="simple"> <dt>a<span class="classifier">(3,3) ndarray</span></dt><dd><p>The real-space unit cell lattice vectors. Each row represents a lattice vector.</p> </dd> <dt>mesh<span class="classifier">(3,) ndarray of ints</span></dt><dd><p>The number of <em>positive</em> G-vectors along each direction.</p> </dd> <dt>ke_cutoff<span class="classifier">float</span></dt><dd><p>If set, defines a spherical cutoff of planewaves, with .5 * G**2 &lt; ke_cutoff The default value is estimated based on <a class="reference internal" href="#pyscf.pbc.gto.cell.Cell.precision" title="pyscf.pbc.gto.cell.Cell.precision"><code class="xref py py-attr docutils literal notranslate"><span class="pre">precision</span></code></a></p> </dd> <dt>precision<span class="classifier">float</span></dt><dd><p>To control Ewald sums and lattice sums accuracy</p> </dd> <dt>nimgs<span class="classifier">(3,) ndarray of ints</span></dt><dd><p>Number of repeated images in lattice summation to produce periodicity. This value can be estimated based on the required precision. It’s recommended NOT making changes to this value.</p> </dd> <dt>rcut<span class="classifier">float</span></dt><dd><p>Cutoff radius (unit Bohr) in lattice summation to produce periodicity. The value can be estimated based on the required precision. It’s recommended NOT making changes to this value.</p> </dd> <dt>ew_eta, ew_cut<span class="classifier">float</span></dt><dd><p>Parameters eta and cut to converge Ewald summation. See <a class="reference internal" href="#pyscf.pbc.gto.cell.get_ewald_params" title="pyscf.pbc.gto.cell.get_ewald_params"><code class="xref py py-func docutils literal notranslate"><span class="pre">get_ewald_params()</span></code></a></p> </dd> <dt>pseudo<span class="classifier">dict or str</span></dt><dd><p>To define pseudopotential.</p> </dd> <dt>ecp<span class="classifier">dict or str</span></dt><dd><p>To define ECP type pseudopotential.</p> </dd> <dt>h<span class="classifier">(3,3) ndarray</span></dt><dd><p>a.T. Deprecated</p> </dd> <dt>dimension<span class="classifier">int</span></dt><dd><p>Default is 3</p> </dd> <dt>low_dim_ft_type<span class="classifier">str</span></dt><dd><p>For semi-empirical periodic systems, whether to calculate integrals at the non-PBC dimension using the sampled mesh grids in infinity vacuum (inf_vacuum) or truncated Coulomb potential (analytic_2d_1). Unless explicitly specified, analytic_2d_1 is used for 2D system and inf_vacuum is assumed for 1D and 0D.</p> </dd> </dl> </dd> </dl> </dd></dl> <dl class="py method"> <dt id="pyscf.pbc.gto.cell.Cell.copy"> <code class="sig-name descname">copy</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#pyscf.pbc.gto.cell.Cell.copy" title="Permalink to this definition">¶</a></dt> <dd><p>Deepcopy of the given <code class="xref py py-class docutils literal notranslate"><span class="pre">Mole</span></code> object</p> </dd></dl> <dl class="py method"> <dt id="pyscf.pbc.gto.cell.Cell.drop_exponent"> <em class="property">property </em><code class="sig-name descname">drop_exponent</code><a class="headerlink" href="#pyscf.pbc.gto.cell.Cell.drop_exponent" title="Permalink to this definition">¶</a></dt> <dd></dd></dl> <dl class="py method"> <dt id="pyscf.pbc.gto.cell.Cell.dumps"> <code class="sig-name descname">dumps</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#pyscf.pbc.gto.cell.Cell.dumps" title="Permalink to this definition">¶</a></dt> <dd><p>Serialize Cell object to a JSON formatted str.</p> </dd></dl> <dl class="py method"> <dt id="pyscf.pbc.gto.cell.Cell.energy_nuc"> <code class="sig-name descname">energy_nuc</code><span class="sig-paren">(</span><em class="sig-param"><span class="n">ew_eta</span><span class="o">=</span><span class="default_value">None</span></em>, <em class="sig-param"><span class="n">ew_cut</span><span class="o">=</span><span class="default_value">None</span></em><span class="sig-paren">)</span><a class="headerlink" href="#pyscf.pbc.gto.cell.Cell.energy_nuc" title="Permalink to this definition">¶</a></dt> <dd><p>Perform real (R) and reciprocal (G) space Ewald sum for the energy.</p> <p>Formulation of Martin, App. F2.</p> <dl class="simple"> <dt>Returns:</dt><dd><dl class="simple"> <dt>float</dt><dd><p>The Ewald energy consisting of overlap, self, and G-space sum.</p> </dd> </dl> </dd> <dt>See Also:</dt><dd><p>pyscf.pbc.gto.get_ewald_params</p> </dd> </dl> </dd></dl> <dl class="py method"> <dt id="pyscf.pbc.gto.cell.Cell.eval_ao"> <code class="sig-name descname">eval_ao</code><span class="sig-paren">(</span><em class="sig-param"><span class="n">eval_name</span></em>, <em class="sig-param"><span class="n">coords</span></em>, <em class="sig-param"><span class="n">comp</span><span class="o">=</span><span class="default_value">None</span></em>, <em class="sig-param"><span class="n">kpts</span><span class="o">=</span><span class="default_value">None</span></em>, <em class="sig-param"><span class="n">kpt</span><span class="o">=</span><span class="default_value">None</span></em>, <em class="sig-param"><span class="n">shls_slice</span><span class="o">=</span><span class="default_value">None</span></em>, <em class="sig-param"><span class="n">non0tab</span><span class="o">=</span><span class="default_value">None</span></em>, <em class="sig-param"><span class="n">ao_loc</span><span class="o">=</span><span class="default_value">None</span></em>, <em class="sig-param"><span class="n">out</span><span class="o">=</span><span class="default_value">None</span></em><span class="sig-paren">)</span><a class="headerlink" href="#pyscf.pbc.gto.cell.Cell.eval_ao" title="Permalink to this definition">¶</a></dt> <dd><p>Evaluate PBC-AO function value on the given grids,</p> <dl> <dt>Args:</dt><dd><p>eval_name : str</p> <blockquote> <div><table class="docutils align-default"> <colgroup> <col style="width: 49%" /> <col style="width: 51%" /> </colgroup> <thead> <tr class="row-odd"><th class="head"><p>Function</p></th> <th class="head"><p>Expression</p></th> </tr> </thead> <tbody> <tr class="row-even"><td><p>“GTOval_sph”</p></td> <td><p>sum_T exp(ik*T) <a href="#id1"><span class="problematic" id="id2">|</span></a>AO&gt;</p></td> </tr> <tr class="row-odd"><td><p>“GTOval_ip_sph”</p></td> <td><p>nabla sum_T exp(ik*T) <a href="#id3"><span class="problematic" id="id4">|</span></a>AO&gt;</p></td> </tr> <tr class="row-even"><td><p>“GTOval_cart”</p></td> <td><p>sum_T exp(ik*T) <a href="#id5"><span class="problematic" id="id6">|</span></a>AO&gt;</p></td> </tr> <tr class="row-odd"><td><p>“GTOval_ip_cart”</p></td> <td><p>nabla sum_T exp(ik*T) <a href="#id7"><span class="problematic" id="id8">|</span></a>AO&gt;</p></td> </tr> </tbody> </table> </div></blockquote> <dl class="simple"> <dt>atm<span class="classifier">int32 ndarray</span></dt><dd><p>libcint integral function argument</p> </dd> <dt>bas<span class="classifier">int32 ndarray</span></dt><dd><p>libcint integral function argument</p> </dd> <dt>env<span class="classifier">float64 ndarray</span></dt><dd><p>libcint integral function argument</p> </dd> <dt>coords<span class="classifier">2D array, shape (N,3)</span></dt><dd><p>The coordinates of the grids.</p> </dd> </dl> </dd> <dt>Kwargs:</dt><dd><dl class="simple"> <dt>shls_slice<span class="classifier">2-element list</span></dt><dd><p>(shl_start, shl_end). If given, only part of AOs (shl_start &lt;= shell_id &lt; shl_end) are evaluated. By default, all shells defined in cell will be evaluated.</p> </dd> <dt>non0tab<span class="classifier">2D bool array</span></dt><dd><p>mask array to indicate whether the AO values are zero. The mask array can be obtained by calling <code class="xref py py-func docutils literal notranslate"><span class="pre">dft.gen_grid.make_mask()</span></code></p> </dd> <dt>out<span class="classifier">ndarray</span></dt><dd><p>If provided, results are written into this array.</p> </dd> </dl> </dd> <dt>Returns:</dt><dd><p>A list of 2D (or 3D) arrays to hold the AO values on grids. Each element of the list corresponds to a k-point and it has the shape (N,nao) Or shape (*,N,nao).</p> </dd> </dl> <p>Examples:</p> <div class="doctest highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">cell</span> <span class="o">=</span> <span class="n">pbc</span><span class="o">.</span><span class="n">gto</span><span class="o">.</span><span class="n">M</span><span class="p">(</span><span class="n">a</span><span class="o">=</span><span class="n">numpy</span><span class="o">.</span><span class="n">eye</span><span class="p">(</span><span class="mi">3</span><span class="p">)</span><span class="o">*</span><span class="mi">4</span><span class="p">,</span> <span class="n">atom</span><span class="o">=</span><span class="s1">&#39;He 1 1 1&#39;</span><span class="p">,</span> <span class="n">basis</span><span class="o">=</span><span class="s1">&#39;6-31g&#39;</span><span class="p">)</span> <span class="gp">&gt;&gt;&gt; </span><span class="n">coords</span> <span class="o">=</span> <span class="n">cell</span><span class="o">.</span><span class="n">get_uniform_grids</span><span class="p">([</span><span class="mi">20</span><span class="p">,</span><span class="mi">20</span><span class="p">,</span><span class="mi">20</span><span class="p">])</span> <span class="gp">&gt;&gt;&gt; </span><span class="n">kpts</span> <span class="o">=</span> <span class="n">cell</span><span class="o">.</span><span class="n">make_kpts</span><span class="p">([</span><span class="mi">3</span><span class="p">,</span><span class="mi">3</span><span class="p">,</span><span class="mi">3</span><span class="p">])</span> <span class="gp">&gt;&gt;&gt; </span><span class="n">ao_value</span> <span class="o">=</span> <span class="n">cell</span><span class="o">.</span><span class="n">pbc_eval_gto</span><span class="p">(</span><span class="s2">&quot;GTOval_sph&quot;</span><span class="p">,</span> <span class="n">coords</span><span class="p">,</span> <span class="n">kpts</span><span class="p">)</span> <span class="gp">&gt;&gt;&gt; </span><span class="nb">len</span><span class="p">(</span><span class="n">ao_value</span><span class="p">)</span> <span class="go">27</span> <span class="gp">&gt;&gt;&gt; </span><span class="n">ao_value</span><span class="p">[</span><span class="mi">0</span><span class="p">]</span><span class="o">.</span><span class="n">shape</span> <span class="go">(100, 2)</span> <span class="gp">&gt;&gt;&gt; </span><span class="n">ao_value</span> <span class="o">=</span> <span class="n">cell</span><span class="o">.</span><span class="n">pbc_eval_gto</span><span class="p">(</span><span class="s2">&quot;GTOval_ig_sph&quot;</span><span class="p">,</span> <span class="n">coords</span><span class="p">,</span> <span class="n">kpts</span><span class="p">,</span> <span class="n">comp</span><span class="o">=</span><span class="mi">3</span><span class="p">)</span> <span class="gp">&gt;&gt;&gt; </span><span class="nb">print</span><span class="p">(</span><span class="n">ao_value</span><span class="o">.</span><span class="n">shape</span><span class="p">)</span> <span class="gp">&gt;&gt;&gt; </span><span class="nb">len</span><span class="p">(</span><span class="n">ao_value</span><span class="p">)</span> <span class="go">27</span> <span class="gp">&gt;&gt;&gt; </span><span class="n">ao_value</span><span class="p">[</span><span class="mi">0</span><span class="p">]</span><span class="o">.</span><span class="n">shape</span> <span class="go">(3, 100, 2)</span> </pre></div> </div> </dd></dl> <dl class="py method"> <dt id="pyscf.pbc.gto.cell.Cell.eval_gto"> <code class="sig-name descname">eval_gto</code><span class="sig-paren">(</span><em class="sig-param"><span class="n">eval_name</span></em>, <em class="sig-param"><span class="n">coords</span></em>, <em class="sig-param"><span class="n">comp</span><span class="o">=</span><span class="default_value">None</span></em>, <em class="sig-param"><span class="n">kpts</span><span class="o">=</span><span class="default_value">None</span></em>, <em class="sig-param"><span class="n">kpt</span><span class="o">=</span><span class="default_value">None</span></em>, <em class="sig-param"><span class="n">shls_slice</span><span class="o">=</span><span class="default_value">None</span></em>, <em class="sig-param"><span class="n">non0tab</span><span class="o">=</span><span class="default_value">None</span></em>, <em class="sig-param"><span class="n">ao_loc</span><span class="o">=</span><span class="default_value">None</span></em>, <em class="sig-param"><span class="n">out</span><span class="o">=</span><span class="default_value">None</span></em><span class="sig-paren">)</span><a class="headerlink" href="#pyscf.pbc.gto.cell.Cell.eval_gto" title="Permalink to this definition">¶</a></dt> <dd><p>Evaluate PBC-AO function value on the given grids,</p> <dl> <dt>Args:</dt><dd><p>eval_name : str</p> <blockquote> <div><table class="docutils align-default"> <colgroup> <col style="width: 49%" /> <col style="width: 51%" /> </colgroup> <thead> <tr class="row-odd"><th class="head"><p>Function</p></th> <th class="head"><p>Expression</p></th> </tr> </thead> <tbody> <tr class="row-even"><td><p>“GTOval_sph”</p></td> <td><p>sum_T exp(ik*T) <a href="#id9"><span class="problematic" id="id10">|</span></a>AO&gt;</p></td> </tr> <tr class="row-odd"><td><p>“GTOval_ip_sph”</p></td> <td><p>nabla sum_T exp(ik*T) <a href="#id11"><span class="problematic" id="id12">|</span></a>AO&gt;</p></td> </tr> <tr class="row-even"><td><p>“GTOval_cart”</p></td> <td><p>sum_T exp(ik*T) <a href="#id13"><span class="problematic" id="id14">|</span></a>AO&gt;</p></td> </tr> <tr class="row-odd"><td><p>“GTOval_ip_cart”</p></td> <td><p>nabla sum_T exp(ik*T) <a href="#id15"><span class="problematic" id="id16">|</span></a>AO&gt;</p></td> </tr> </tbody> </table> </div></blockquote> <dl class="simple"> <dt>atm<span class="classifier">int32 ndarray</span></dt><dd><p>libcint integral function argument</p> </dd> <dt>bas<span class="classifier">int32 ndarray</span></dt><dd><p>libcint integral function argument</p> </dd> <dt>env<span class="classifier">float64 ndarray</span></dt><dd><p>libcint integral function argument</p> </dd> <dt>coords<span class="classifier">2D array, shape (N,3)</span></dt><dd><p>The coordinates of the grids.</p> </dd> </dl> </dd> <dt>Kwargs:</dt><dd><dl class="simple"> <dt>shls_slice<span class="classifier">2-element list</span></dt><dd><p>(shl_start, shl_end). If given, only part of AOs (shl_start &lt;= shell_id &lt; shl_end) are evaluated. By default, all shells defined in cell will be evaluated.</p> </dd> <dt>non0tab<span class="classifier">2D bool array</span></dt><dd><p>mask array to indicate whether the AO values are zero. The mask array can be obtained by calling <code class="xref py py-func docutils literal notranslate"><span class="pre">dft.gen_grid.make_mask()</span></code></p> </dd> <dt>out<span class="classifier">ndarray</span></dt><dd><p>If provided, results are written into this array.</p> </dd> </dl> </dd> <dt>Returns:</dt><dd><p>A list of 2D (or 3D) arrays to hold the AO values on grids. Each element of the list corresponds to a k-point and it has the shape (N,nao) Or shape (*,N,nao).</p> </dd> </dl> <p>Examples:</p> <div class="doctest highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">cell</span> <span class="o">=</span> <span class="n">pbc</span><span class="o">.</span><span class="n">gto</span><span class="o">.</span><span class="n">M</span><span class="p">(</span><span class="n">a</span><span class="o">=</span><span class="n">numpy</span><span class="o">.</span><span class="n">eye</span><span class="p">(</span><span class="mi">3</span><span class="p">)</span><span class="o">*</span><span class="mi">4</span><span class="p">,</span> <span class="n">atom</span><span class="o">=</span><span class="s1">&#39;He 1 1 1&#39;</span><span class="p">,</span> <span class="n">basis</span><span class="o">=</span><span class="s1">&#39;6-31g&#39;</span><span class="p">)</span> <span class="gp">&gt;&gt;&gt; </span><span class="n">coords</span> <span class="o">=</span> <span class="n">cell</span><span class="o">.</span><span class="n">get_uniform_grids</span><span class="p">([</span><span class="mi">20</span><span class="p">,</span><span class="mi">20</span><span class="p">,</span><span class="mi">20</span><span class="p">])</span> <span class="gp">&gt;&gt;&gt; </span><span class="n">kpts</span> <span class="o">=</span> <span class="n">cell</span><span class="o">.</span><span class="n">make_kpts</span><span class="p">([</span><span class="mi">3</span><span class="p">,</span><span class="mi">3</span><span class="p">,</span><span class="mi">3</span><span class="p">])</span> <span class="gp">&gt;&gt;&gt; </span><span class="n">ao_value</span> <span class="o">=</span> <span class="n">cell</span><span class="o">.</span><span class="n">pbc_eval_gto</span><span class="p">(</span><span class="s2">&quot;GTOval_sph&quot;</span><span class="p">,</span> <span class="n">coords</span><span class="p">,</span> <span class="n">kpts</span><span class="p">)</span> <span class="gp">&gt;&gt;&gt; </span><span class="nb">len</span><span class="p">(</span><span class="n">ao_value</span><span class="p">)</span> <span class="go">27</span> <span class="gp">&gt;&gt;&gt; </span><span class="n">ao_value</span><span class="p">[</span><span class="mi">0</span><span class="p">]</span><span class="o">.</span><span class="n">shape</span> <span class="go">(100, 2)</span> <span class="gp">&gt;&gt;&gt; </span><span class="n">ao_value</span> <span class="o">=</span> <span class="n">cell</span><span class="o">.</span><span class="n">pbc_eval_gto</span><span class="p">(</span><span class="s2">&quot;GTOval_ig_sph&quot;</span><span class="p">,</span> <span class="n">coords</span><span class="p">,</span> <span class="n">kpts</span><span class="p">,</span> <span class="n">comp</span><span class="o">=</span><span class="mi">3</span><span class="p">)</span> <span class="gp">&gt;&gt;&gt; </span><span class="nb">print</span><span class="p">(</span><span class="n">ao_value</span><span class="o">.</span><span class="n">shape</span><span class="p">)</span> <span class="gp">&gt;&gt;&gt; </span><span class="nb">len</span><span class="p">(</span><span class="n">ao_value</span><span class="p">)</span> <span class="go">27</span> <span class="gp">&gt;&gt;&gt; </span><span class="n">ao_value</span><span class="p">[</span><span class="mi">0</span><span class="p">]</span><span class="o">.</span><span class="n">shape</span> <span class="go">(3, 100, 2)</span> </pre></div> </div> </dd></dl> <dl class="py method"> <dt id="pyscf.pbc.gto.cell.Cell.ew_cut"> <em class="property">property </em><code class="sig-name descname">ew_cut</code><a class="headerlink" href="#pyscf.pbc.gto.cell.Cell.ew_cut" title="Permalink to this definition">¶</a></dt> <dd></dd></dl> <dl class="py method"> <dt id="pyscf.pbc.gto.cell.Cell.ew_eta"> <em class="property">property </em><code class="sig-name descname">ew_eta</code><a class="headerlink" href="#pyscf.pbc.gto.cell.Cell.ew_eta" title="Permalink to this definition">¶</a></dt> <dd></dd></dl> <dl class="py method"> <dt id="pyscf.pbc.gto.cell.Cell.ewald"> <code class="sig-name descname">ewald</code><span class="sig-paren">(</span><em class="sig-param"><span class="n">ew_eta</span><span class="o">=</span><span class="default_value">None</span></em>, <em class="sig-param"><span class="n">ew_cut</span><span class="o">=</span><span class="default_value">None</span></em><span class="sig-paren">)</span><a class="headerlink" href="#pyscf.pbc.gto.cell.Cell.ewald" title="Permalink to this definition">¶</a></dt> <dd><p>Perform real (R) and reciprocal (G) space Ewald sum for the energy.</p> <p>Formulation of Martin, App. F2.</p> <dl class="simple"> <dt>Returns:</dt><dd><dl class="simple"> <dt>float</dt><dd><p>The Ewald energy consisting of overlap, self, and G-space sum.</p> </dd> </dl> </dd> <dt>See Also:</dt><dd><p>pyscf.pbc.gto.get_ewald_params</p> </dd> </dl> </dd></dl> <dl class="py attribute"> <dt id="pyscf.pbc.gto.cell.Cell.exp_to_discard"> <code class="sig-name descname">exp_to_discard</code><em class="property"> = None</em><a class="headerlink" href="#pyscf.pbc.gto.cell.Cell.exp_to_discard" title="Permalink to this definition">¶</a></dt> <dd></dd></dl> <dl class="py method"> <dt id="pyscf.pbc.gto.cell.Cell.format_basis"> <code class="sig-name descname">format_basis</code><span class="sig-paren">(</span><em class="sig-param"><span class="n">basis_tab</span></em><span class="sig-paren">)</span><a class="headerlink" href="#pyscf.pbc.gto.cell.Cell.format_basis" title="Permalink to this definition">¶</a></dt> <dd><p>Convert the input <code class="xref py py-attr docutils literal notranslate"><span class="pre">Cell.basis</span></code> to the internal data format:</p> <div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="p">{</span> <span class="n">atom</span><span class="p">:</span> <span class="p">(</span><span class="n">l</span><span class="p">,</span> <span class="n">kappa</span><span class="p">,</span> <span class="p">((</span><span class="o">-</span><span class="n">exp</span><span class="p">,</span> <span class="n">c_1</span><span class="p">,</span> <span class="n">c_2</span><span class="p">,</span> <span class="o">..</span><span class="p">),</span> <span class="n">nprim</span><span class="p">,</span> <span class="n">nctr</span><span class="p">,</span> <span class="n">ptr</span><span class="o">-</span><span class="n">exps</span><span class="p">,</span> <span class="n">ptr</span><span class="o">-</span><span class="n">contraction</span><span class="o">-</span><span class="n">coeff</span><span class="p">)),</span> <span class="o">...</span> <span class="p">}</span> </pre></div> </div> <dl class="simple"> <dt>Args:</dt><dd><dl class="simple"> <dt>basis_tab<span class="classifier">dict</span></dt><dd><p>Similar to <code class="xref py py-attr docutils literal notranslate"><span class="pre">Cell.basis</span></code>, it <strong>cannot</strong> be a str</p> </dd> </dl> </dd> <dt>Returns:</dt><dd><p>Formated <code class="xref py py-attr docutils literal notranslate"><span class="pre">basis</span></code></p> </dd> </dl> <p>Examples:</p> <div class="doctest highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">pbc</span><span class="o">.</span><span class="n">format_basis</span><span class="p">({</span><span class="s1">&#39;H&#39;</span><span class="p">:</span><span class="s1">&#39;gth-szv&#39;</span><span class="p">})</span> <span class="go">{&#39;H&#39;: [[0,</span> <span class="go"> (8.3744350009, -0.0283380461),</span> <span class="go"> (1.8058681460, -0.1333810052),</span> <span class="go"> (0.4852528328, -0.3995676063),</span> <span class="go"> (0.1658236932, -0.5531027541)]]}</span> </pre></div> </div> </dd></dl> <dl class="py method"> <dt id="pyscf.pbc.gto.cell.Cell.format_pseudo"> <code class="sig-name descname">format_pseudo</code><span class="sig-paren">(</span><em class="sig-param"><span class="n">pseudo_tab</span></em><span class="sig-paren">)</span><a class="headerlink" href="#pyscf.pbc.gto.cell.Cell.format_pseudo" title="Permalink to this definition">¶</a></dt> <dd><p>Convert the input <code class="xref py py-attr docutils literal notranslate"><span class="pre">Cell.pseudo</span></code> (dict) to the internal data format:</p> <div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="p">{</span> <span class="n">atom</span><span class="p">:</span> <span class="p">(</span> <span class="p">(</span><span class="n">nelec_s</span><span class="p">,</span> <span class="n">nele_p</span><span class="p">,</span> <span class="n">nelec_d</span><span class="p">,</span> <span class="o">...</span><span class="p">),</span> <span class="n">rloc</span><span class="p">,</span> <span class="n">nexp</span><span class="p">,</span> <span class="p">(</span><span class="n">cexp_1</span><span class="p">,</span> <span class="n">cexp_2</span><span class="p">,</span> <span class="o">...</span><span class="p">,</span> <span class="n">cexp_nexp</span><span class="p">),</span> <span class="n">nproj_types</span><span class="p">,</span> <span class="p">(</span><span class="n">r1</span><span class="p">,</span> <span class="n">nproj1</span><span class="p">,</span> <span class="p">(</span> <span class="p">(</span><span class="n">hproj1</span><span class="p">[</span><span class="mi">1</span><span class="p">,</span><span class="mi">1</span><span class="p">],</span> <span class="n">hproj1</span><span class="p">[</span><span class="mi">1</span><span class="p">,</span><span class="mi">2</span><span class="p">],</span> <span class="o">...</span><span class="p">,</span> <span class="n">hproj1</span><span class="p">[</span><span class="mi">1</span><span class="p">,</span><span class="n">nproj1</span><span class="p">]),</span> <span class="p">(</span><span class="n">hproj1</span><span class="p">[</span><span class="mi">2</span><span class="p">,</span><span class="mi">1</span><span class="p">],</span> <span class="n">hproj1</span><span class="p">[</span><span class="mi">2</span><span class="p">,</span><span class="mi">2</span><span class="p">],</span> <span class="o">...</span><span class="p">,</span> <span class="n">hproj1</span><span class="p">[</span><span class="mi">2</span><span class="p">,</span><span class="n">nproj1</span><span class="p">]),</span> <span class="o">...</span> <span class="p">(</span><span class="n">hproj1</span><span class="p">[</span><span class="n">nproj1</span><span class="p">,</span><span class="mi">1</span><span class="p">],</span> <span class="n">hproj1</span><span class="p">[</span><span class="n">nproj1</span><span class="p">,</span><span class="mi">2</span><span class="p">],</span> <span class="o">...</span> <span class="p">)</span> <span class="p">)),</span> <span class="p">(</span><span class="n">r2</span><span class="p">,</span> <span class="n">nproj2</span><span class="p">,</span> <span class="p">(</span> <span class="p">(</span><span class="n">hproj2</span><span class="p">[</span><span class="mi">1</span><span class="p">,</span><span class="mi">1</span><span class="p">],</span> <span class="n">hproj2</span><span class="p">[</span><span class="mi">1</span><span class="p">,</span><span class="mi">2</span><span class="p">],</span> <span class="o">...</span><span class="p">,</span> <span class="n">hproj2</span><span class="p">[</span><span class="mi">1</span><span class="p">,</span><span class="n">nproj1</span><span class="p">]),</span> <span class="o">...</span> <span class="p">)</span> <span class="p">)</span> <span class="p">)</span> <span class="o">...</span> <span class="p">}</span> </pre></div> </div> <dl class="simple"> <dt>Args:</dt><dd><dl class="simple"> <dt>pseudo_tab<span class="classifier">dict</span></dt><dd><p>Similar to <code class="xref py py-attr docutils literal notranslate"><span class="pre">Cell.pseudo</span></code> (a dict), it <strong>cannot</strong> be a str</p> </dd> </dl> </dd> <dt>Returns:</dt><dd><p>Formatted <code class="xref py py-attr docutils literal notranslate"><span class="pre">pseudo</span></code></p> </dd> </dl> <p>Examples:</p> <div class="doctest highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">pbc</span><span class="o">.</span><span class="n">format_pseudo</span><span class="p">({</span><span class="s1">&#39;H&#39;</span><span class="p">:</span><span class="s1">&#39;gth-blyp&#39;</span><span class="p">,</span> <span class="s1">&#39;He&#39;</span><span class="p">:</span> <span class="s1">&#39;gth-pade&#39;</span><span class="p">})</span> <span class="go">{&#39;H&#39;: [[1],</span> <span class="go"> 0.2, 2, [-4.19596147, 0.73049821], 0],</span> <span class="go"> &#39;He&#39;: [[2],</span> <span class="go"> 0.2, 2, [-9.1120234, 1.69836797], 0]}</span> </pre></div> </div> </dd></dl> <dl class="py method"> <dt id="pyscf.pbc.gto.cell.Cell.from_ase"> <code class="sig-name descname">from_ase</code><span class="sig-paren">(</span><em class="sig-param"><span class="n">ase_atom</span></em><span class="sig-paren">)</span><a class="headerlink" href="#pyscf.pbc.gto.cell.Cell.from_ase" title="Permalink to this definition">¶</a></dt> <dd><p>Update cell based on given ase atom object</p> <p>Examples:</p> <div class="doctest highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">from</span> <span class="nn">ase.lattice</span> <span class="kn">import</span> <span class="n">bulk</span> <span class="gp">&gt;&gt;&gt; </span><span class="n">cell</span><span class="o">.</span><span class="n">from_ase</span><span class="p">(</span><span class="n">bulk</span><span class="p">(</span><span class="s1">&#39;C&#39;</span><span class="p">,</span> <span class="s1">&#39;diamond&#39;</span><span class="p">,</span> <span class="n">a</span><span class="o">=</span><span class="n">LATTICE_CONST</span><span class="p">))</span> </pre></div> </div> </dd></dl> <dl class="py method"> <dt id="pyscf.pbc.gto.cell.Cell.gen_uniform_grids"> <code class="sig-name descname">gen_uniform_grids</code><span class="sig-paren">(</span><em class="sig-param"><span class="n">mesh</span><span class="o">=</span><span class="default_value">None</span></em>, <em class="sig-param"><span class="o">**</span><span class="n">kwargs</span></em><span class="sig-paren">)</span><a class="headerlink" href="#pyscf.pbc.gto.cell.Cell.gen_uniform_grids" title="Permalink to this definition">¶</a></dt> <dd><p>Generate a uniform real-space grid consistent w/ samp thm; see MH (3.19).</p> <dl class="simple"> <dt>Args:</dt><dd><p>cell : instance of <a class="reference internal" href="#pyscf.pbc.gto.cell.Cell" title="pyscf.pbc.gto.cell.Cell"><code class="xref py py-class docutils literal notranslate"><span class="pre">Cell</span></code></a></p> </dd> <dt>Returns:</dt><dd><dl class="simple"> <dt>coords<span class="classifier">(ngx*ngy*ngz, 3) ndarray</span></dt><dd><p>The real-space grid point coordinates.</p> </dd> </dl> </dd> </dl> </dd></dl> <dl class="py method"> <dt id="pyscf.pbc.gto.cell.Cell.get_Gv"> <code class="sig-name descname">get_Gv</code><span class="sig-paren">(</span><em class="sig-param"><span class="n">mesh</span><span class="o">=</span><span class="default_value">None</span></em>, <em class="sig-param"><span class="o">**</span><span class="n">kwargs</span></em><span class="sig-paren">)</span><a class="headerlink" href="#pyscf.pbc.gto.cell.Cell.get_Gv" title="Permalink to this definition">¶</a></dt> <dd><p>Calculate three-dimensional G-vectors for the cell; see MH (3.8).</p> <p>Indices along each direction go as [0…N-1, -N…-1] to follow FFT convention.</p> <dl class="simple"> <dt>Args:</dt><dd><p>cell : instance of <a class="reference internal" href="#pyscf.pbc.gto.cell.Cell" title="pyscf.pbc.gto.cell.Cell"><code class="xref py py-class docutils literal notranslate"><span class="pre">Cell</span></code></a></p> </dd> <dt>Returns:</dt><dd><dl class="simple"> <dt>Gv<span class="classifier">(ngrids, 3) ndarray of floats</span></dt><dd><p>The array of G-vectors.</p> </dd> </dl> </dd> </dl> </dd></dl> <dl class="py method"> <dt id="pyscf.pbc.gto.cell.Cell.get_Gv_weights"> <code class="sig-name descname">get_Gv_weights</code><span class="sig-paren">(</span><em class="sig-param"><span class="n">mesh</span><span class="o">=</span><span class="default_value">None</span></em>, <em class="sig-param"><span class="o">**</span><span class="n">kwargs</span></em><span class="sig-paren">)</span><a class="headerlink" href="#pyscf.pbc.gto.cell.Cell.get_Gv_weights" title="Permalink to this definition">¶</a></dt> <dd><p>Calculate G-vectors and weights.</p> <dl class="simple"> <dt>Returns:</dt><dd><dl class="simple"> <dt>Gv<span class="classifier">(ngris, 3) ndarray of floats</span></dt><dd><p>The array of G-vectors.</p> </dd> </dl> </dd> </dl> </dd></dl> <dl class="py method"> <dt id="pyscf.pbc.gto.cell.Cell.get_SI"> <code class="sig-name descname">get_SI</code><span class="sig-paren">(</span><em class="sig-param"><span class="n">Gv</span><span class="o">=</span><span class="default_value">None</span></em><span class="sig-paren">)</span><a class="headerlink" href="#pyscf.pbc.gto.cell.Cell.get_SI" title="Permalink to this definition">¶</a></dt> <dd><p>Calculate the structure factor (0D, 1D, 2D, 3D) for all atoms; see MH (3.34).</p> <dl> <dt>Args:</dt><dd><p>cell : instance of <a class="reference internal" href="#pyscf.pbc.gto.cell.Cell" title="pyscf.pbc.gto.cell.Cell"><code class="xref py py-class docutils literal notranslate"><span class="pre">Cell</span></code></a></p> <dl class="simple"> <dt>Gv<span class="classifier">(N,3) array</span></dt><dd><p>G vectors</p> </dd> </dl> </dd> <dt>Returns:</dt><dd><dl class="simple"> <dt>SI<span class="classifier">(natm, ngrids) ndarray, dtype=np.complex128</span></dt><dd><p>The structure factor for each atom at each G-vector.</p> </dd> </dl> </dd> </dl> </dd></dl> <dl class="py method"> <dt id="pyscf.pbc.gto.cell.Cell.get_abs_kpts"> <code class="sig-name descname">get_abs_kpts</code><span class="sig-paren">(</span><em class="sig-param"><span class="n">scaled_kpts</span></em><span class="sig-paren">)</span><a class="headerlink" href="#pyscf.pbc.gto.cell.Cell.get_abs_kpts" title="Permalink to this definition">¶</a></dt> <dd><p>Get absolute k-points (in 1/Bohr), given “scaled” k-points in fractions of lattice vectors.</p> <dl class="simple"> <dt>Args:</dt><dd><p>scaled_kpts : (nkpts, 3) ndarray of floats</p> </dd> <dt>Returns:</dt><dd><p>abs_kpts : (nkpts, 3) ndarray of floats</p> </dd> </dl> </dd></dl> <dl class="py method"> <dt id="pyscf.pbc.gto.cell.Cell.get_bounding_sphere"> <code class="sig-name descname">get_bounding_sphere</code><span class="sig-paren">(</span><em class="sig-param"><span class="n">rcut</span></em><span class="sig-paren">)</span><a class="headerlink" href="#pyscf.pbc.gto.cell.Cell.get_bounding_sphere" title="Permalink to this definition">¶</a></dt> <dd><p>Finds all the lattice points within a sphere of radius rcut.</p> <p>Defines a parallelipiped given by -N_x &lt;= n_x &lt;= N_x, with x in [1,3] See Martin p. 85</p> <dl class="simple"> <dt>Args:</dt><dd><dl class="simple"> <dt>rcut<span class="classifier">number</span></dt><dd><p>real space cut-off for interaction</p> </dd> </dl> </dd> <dt>Returns:</dt><dd><p>cut : ndarray of 3 ints defining N_x</p> </dd> </dl> </dd></dl> <dl class="py method"> <dt id="pyscf.pbc.gto.cell.Cell.get_ewald_params"> <code class="sig-name descname">get_ewald_params</code><span class="sig-paren">(</span><em class="sig-param"><span class="n">precision</span><span class="o">=</span><span class="default_value">1e-08</span></em>, <em class="sig-param"><span class="n">mesh</span><span class="o">=</span><span class="default_value">None</span></em><span class="sig-paren">)</span><a class="headerlink" href="#pyscf.pbc.gto.cell.Cell.get_ewald_params" title="Permalink to this definition">¶</a></dt> <dd><p>Choose a reasonable value of Ewald ‘eta’ and ‘cut’ parameters. eta^2 is the exponent coefficient of the model Gaussian charge for nucleus at R: frac{eta^3}{pi^1.5} e^{-eta^2 (r-R)^2}</p> <p>Choice is based on largest G vector and desired relative precision.</p> <p>The relative error in the G-space sum is given by</p> <blockquote> <div><p>precision ~ 4pi Gmax^2 e^{(-Gmax^2)/(4 eta^2)}</p> </div></blockquote> <p>which determines eta. Then, real-space cutoff is determined by (exp. factors only)</p> <blockquote> <div><p>precision ~ erfc(eta*rcut) / rcut ~ e^{(-eta**2 rcut*2)}</p> </div></blockquote> <dl class="simple"> <dt>Returns:</dt><dd><dl class="simple"> <dt>ew_eta, ew_cut<span class="classifier">float</span></dt><dd><p>The Ewald ‘eta’ and ‘cut’ parameters.</p> </dd> </dl> </dd> </dl> </dd></dl> <dl class="py method"> <dt id="pyscf.pbc.gto.cell.Cell.get_kpts"> <code class="sig-name descname">get_kpts</code><span class="sig-paren">(</span><em class="sig-param"><span class="n">nks</span></em>, <em class="sig-param"><span class="n">wrap_around</span><span class="o">=</span><span class="default_value">False</span></em>, <em class="sig-param"><span class="n">with_gamma_point</span><span class="o">=</span><span class="default_value">True</span></em>, <em class="sig-param"><span class="n">scaled_center</span><span class="o">=</span><span class="default_value">None</span></em><span class="sig-paren">)</span><a class="headerlink" href="#pyscf.pbc.gto.cell.Cell.get_kpts" title="Permalink to this definition">¶</a></dt> <dd><p>Given number of kpoints along x,y,z , generate kpoints</p> <dl class="simple"> <dt>Args:</dt><dd><p>nks : (3,) ndarray</p> </dd> <dt>Kwargs:</dt><dd><dl class="simple"> <dt>wrap_around<span class="classifier">bool</span></dt><dd><p>To ensure all kpts are in first Brillouin zone.</p> </dd> <dt>with_gamma_point<span class="classifier">bool</span></dt><dd><p>Whether to shift Monkhorst-pack grid to include gamma-point.</p> </dd> <dt>scaled_center<span class="classifier">(3,) array</span></dt><dd><p>Shift all points in the Monkhorst-pack grid to be centered on scaled_center, given as the zeroth index of the returned kpts. Scaled meaning that the k-points are scaled to a grid from [-1,1] x [-1,1] x [-1,1]</p> </dd> </dl> </dd> <dt>Returns:</dt><dd><p>kpts in absolute value (unit 1/Bohr). Gamma point is placed at the first place in the k-points list</p> </dd> </dl> <p>Examples:</p> <div class="doctest highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">cell</span><span class="o">.</span><span class="n">make_kpts</span><span class="p">((</span><span class="mi">4</span><span class="p">,</span><span class="mi">4</span><span class="p">,</span><span class="mi">4</span><span class="p">))</span> </pre></div> </div> </dd></dl> <dl class="py method"> <dt id="pyscf.pbc.gto.cell.Cell.get_lattice_Ls"> <code class="sig-name descname">get_lattice_Ls</code><span class="sig-paren">(</span><em class="sig-param"><span class="n">nimgs</span><span class="o">=</span><span class="default_value">None</span></em>, <em class="sig-param"><span class="n">rcut</span><span class="o">=</span><span class="default_value">None</span></em>, <em class="sig-param"><span class="n">dimension</span><span class="o">=</span><span class="default_value">None</span></em>, <em class="sig-param"><span class="n">discard</span><span class="o">=</span><span class="default_value">True</span></em><span class="sig-paren">)</span><a class="headerlink" href="#pyscf.pbc.gto.cell.Cell.get_lattice_Ls" title="Permalink to this definition">¶</a></dt> <dd><p>Get the (Cartesian, unitful) lattice translation vectors for nearby images. The translation vectors can be used for the lattice summation.</p> </dd></dl> <dl class="py method"> <dt id="pyscf.pbc.gto.cell.Cell.get_nimgs"> <code class="sig-name descname">get_nimgs</code><span class="sig-paren">(</span><em class="sig-param"><span class="n">precision</span><span class="o">=</span><span class="default_value">None</span></em><span class="sig-paren">)</span><a class="headerlink" href="#pyscf.pbc.gto.cell.Cell.get_nimgs" title="Permalink to this definition">¶</a></dt> <dd><p>Choose number of basis function images in lattice sums to include for given precision in overlap, using</p> <p>precision ~ int r^l e^{-alpha r^2} (r-rcut)^l e^{-alpha (r-rcut)^2} ~ (rcut^2/(2alpha))^l e^{alpha/2 rcut^2}</p> <p>where alpha is the smallest exponent in the basis. Note that assumes an isolated exponent in the middle of the box, so it adds one additional lattice vector to be safe.</p> </dd></dl> <dl class="py method"> <dt id="pyscf.pbc.gto.cell.Cell.get_scaled_kpts"> <code class="sig-name descname">get_scaled_kpts</code><span class="sig-paren">(</span><em class="sig-param"><span class="n">abs_kpts</span></em><span class="sig-paren">)</span><a class="headerlink" href="#pyscf.pbc.gto.cell.Cell.get_scaled_kpts" title="Permalink to this definition">¶</a></dt> <dd><p>Get scaled k-points, given absolute k-points in 1/Bohr.</p> <dl class="simple"> <dt>Args:</dt><dd><p>abs_kpts : (nkpts, 3) ndarray of floats</p> </dd> <dt>Returns:</dt><dd><p>scaled_kpts : (nkpts, 3) ndarray of floats</p> </dd> </dl> </dd></dl> <dl class="py method"> <dt id="pyscf.pbc.gto.cell.Cell.get_uniform_grids"> <code class="sig-name descname">get_uniform_grids</code><span class="sig-paren">(</span><em class="sig-param"><span class="n">mesh</span><span class="o">=</span><span class="default_value">None</span></em>, <em class="sig-param"><span class="o">**</span><span class="n">kwargs</span></em><span class="sig-paren">)</span><a class="headerlink" href="#pyscf.pbc.gto.cell.Cell.get_uniform_grids" title="Permalink to this definition">¶</a></dt> <dd><p>Generate a uniform real-space grid consistent w/ samp thm; see MH (3.19).</p> <dl class="simple"> <dt>Args:</dt><dd><p>cell : instance of <a class="reference internal" href="#pyscf.pbc.gto.cell.Cell" title="pyscf.pbc.gto.cell.Cell"><code class="xref py py-class docutils literal notranslate"><span class="pre">Cell</span></code></a></p> </dd> <dt>Returns:</dt><dd><dl class="simple"> <dt>coords<span class="classifier">(ngx*ngy*ngz, 3) ndarray</span></dt><dd><p>The real-space grid point coordinates.</p> </dd> </dl> </dd> </dl> </dd></dl> <dl class="py method"> <dt id="pyscf.pbc.gto.cell.Cell.gs"> <em class="property">property </em><code class="sig-name descname">gs</code><a class="headerlink" href="#pyscf.pbc.gto.cell.Cell.gs" title="Permalink to this definition">¶</a></dt> <dd></dd></dl> <dl class="py method"> <dt id="pyscf.pbc.gto.cell.Cell.h"> <em class="property">property </em><code class="sig-name descname">h</code><a class="headerlink" href="#pyscf.pbc.gto.cell.Cell.h" title="Permalink to this definition">¶</a></dt> <dd></dd></dl> <dl class="py method"> <dt id="pyscf.pbc.gto.cell.Cell.has_ecp"> <code class="sig-name descname">has_ecp</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#pyscf.pbc.gto.cell.Cell.has_ecp" title="Permalink to this definition">¶</a></dt> <dd><p>Whether pseudo potential is used in the system.</p> </dd></dl> <dl class="py method"> <dt id="pyscf.pbc.gto.cell.Cell.kernel"> <code class="sig-name descname">kernel</code><span class="sig-paren">(</span><em class="sig-param"><span class="n">dump_input</span><span class="o">=</span><span class="default_value">True</span></em>, <em class="sig-param"><span class="n">parse_arg</span><span class="o">=</span><span class="default_value">True</span></em>, <em class="sig-param"><span class="n">a</span><span class="o">=</span><span class="default_value">None</span></em>, <em class="sig-param"><span class="n">mesh</span><span class="o">=</span><span class="default_value">None</span></em>, <em class="sig-param"><span class="n">ke_cutoff</span><span class="o">=</span><span class="default_value">None</span></em>, <em class="sig-param"><span class="n">precision</span><span class="o">=</span><span class="default_value">None</span></em>, <em class="sig-param"><span class="n">nimgs</span><span class="o">=</span><span class="default_value">None</span></em>, <em class="sig-param"><span class="n">ew_eta</span><span class="o">=</span><span class="default_value">None</span></em>, <em class="sig-param"><span class="n">ew_cut</span><span class="o">=</span><span class="default_value">None</span></em>, <em class="sig-param"><span class="n">pseudo</span><span class="o">=</span><span class="default_value">None</span></em>, <em class="sig-param"><span class="n">basis</span><span class="o">=</span><span class="default_value">None</span></em>, <em class="sig-param"><span class="n">h</span><span class="o">=</span><span class="default_value">None</span></em>, <em class="sig-param"><span class="n">dimension</span><span class="o">=</span><span class="default_value">None</span></em>, <em class="sig-param"><span class="n">rcut</span><span class="o">=</span><span class="default_value">None</span></em>, <em class="sig-param"><span class="n">ecp</span><span class="o">=</span><span class="default_value">None</span></em>, <em class="sig-param"><span class="n">low_dim_ft_type</span><span class="o">=</span><span class="default_value">None</span></em>, <em class="sig-param"><span class="o">*</span><span class="n">args</span></em>, <em class="sig-param"><span class="o">**</span><span class="n">kwargs</span></em><span class="sig-paren">)</span><a class="headerlink" href="#pyscf.pbc.gto.cell.Cell.kernel" title="Permalink to this definition">¶</a></dt> <dd><p>Setup Mole molecule and Cell and initialize some control parameters. Whenever you change the value of the attributes of <a class="reference internal" href="#pyscf.pbc.gto.cell.Cell" title="pyscf.pbc.gto.cell.Cell"><code class="xref py py-class docutils literal notranslate"><span class="pre">Cell</span></code></a>, you need call this function to refresh the internal data of Cell.</p> <dl class="simple"> <dt>Kwargs:</dt><dd><dl class="simple"> <dt>a<span class="classifier">(3,3) ndarray</span></dt><dd><p>The real-space unit cell lattice vectors. Each row represents a lattice vector.</p> </dd> <dt>mesh<span class="classifier">(3,) ndarray of ints</span></dt><dd><p>The number of <em>positive</em> G-vectors along each direction.</p> </dd> <dt>ke_cutoff<span class="classifier">float</span></dt><dd><p>If set, defines a spherical cutoff of planewaves, with .5 * G**2 &lt; ke_cutoff The default value is estimated based on <a class="reference internal" href="#pyscf.pbc.gto.cell.Cell.precision" title="pyscf.pbc.gto.cell.Cell.precision"><code class="xref py py-attr docutils literal notranslate"><span class="pre">precision</span></code></a></p> </dd> <dt>precision<span class="classifier">float</span></dt><dd><p>To control Ewald sums and lattice sums accuracy</p> </dd> <dt>nimgs<span class="classifier">(3,) ndarray of ints</span></dt><dd><p>Number of repeated images in lattice summation to produce periodicity. This value can be estimated based on the required precision. It’s recommended NOT making changes to this value.</p> </dd> <dt>rcut<span class="classifier">float</span></dt><dd><p>Cutoff radius (unit Bohr) in lattice summation to produce periodicity. The value can be estimated based on the required precision. It’s recommended NOT making changes to this value.</p> </dd> <dt>ew_eta, ew_cut<span class="classifier">float</span></dt><dd><p>Parameters eta and cut to converge Ewald summation. See <a class="reference internal" href="#pyscf.pbc.gto.cell.get_ewald_params" title="pyscf.pbc.gto.cell.get_ewald_params"><code class="xref py py-func docutils literal notranslate"><span class="pre">get_ewald_params()</span></code></a></p> </dd> <dt>pseudo<span class="classifier">dict or str</span></dt><dd><p>To define pseudopotential.</p> </dd> <dt>ecp<span class="classifier">dict or str</span></dt><dd><p>To define ECP type pseudopotential.</p> </dd> <dt>h<span class="classifier">(3,3) ndarray</span></dt><dd><p>a.T. Deprecated</p> </dd> <dt>dimension<span class="classifier">int</span></dt><dd><p>Default is 3</p> </dd> <dt>low_dim_ft_type<span class="classifier">str</span></dt><dd><p>For semi-empirical periodic systems, whether to calculate integrals at the non-PBC dimension using the sampled mesh grids in infinity vacuum (inf_vacuum) or truncated Coulomb potential (analytic_2d_1). Unless explicitly specified, analytic_2d_1 is used for 2D system and inf_vacuum is assumed for 1D and 0D.</p> </dd> </dl> </dd> </dl> </dd></dl> <dl class="py method"> <dt id="pyscf.pbc.gto.cell.Cell.lattice_vectors"> <code class="sig-name descname">lattice_vectors</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#pyscf.pbc.gto.cell.Cell.lattice_vectors" title="Permalink to this definition">¶</a></dt> <dd><p>Convert the primitive lattice vectors.</p> <p>Return 3x3 array in which each row represents one direction of the lattice vectors (unit in Bohr)</p> </dd></dl> <dl class="py method"> <dt id="pyscf.pbc.gto.cell.Cell.loads"> <code class="sig-name descname">loads</code><span class="sig-paren">(</span><em class="sig-param"><span class="n">molstr</span></em><span class="sig-paren">)</span><a class="headerlink" href="#pyscf.pbc.gto.cell.Cell.loads" title="Permalink to this definition">¶</a></dt> <dd><p>Deserialize a str containing a JSON document to a Cell object.</p> </dd></dl> <dl class="py method"> <dt id="pyscf.pbc.gto.cell.Cell.loads_"> <code class="sig-name descname">loads_</code><span class="sig-paren">(</span><em class="sig-param"><span class="n">molstr</span></em><span class="sig-paren">)</span><a class="headerlink" href="#pyscf.pbc.gto.cell.Cell.loads_" title="Permalink to this definition">¶</a></dt> <dd></dd></dl> <dl class="py method"> <dt id="pyscf.pbc.gto.cell.Cell.make_ecp_env"> <code class="sig-name descname">make_ecp_env</code><span class="sig-paren">(</span><em class="sig-param"><span class="n">_atm</span></em>, <em class="sig-param"><span class="n">_ecp</span></em>, <em class="sig-param"><span class="n">pre_env</span><span class="o">=</span><span class="default_value">[]</span></em><span class="sig-paren">)</span><a class="headerlink" href="#pyscf.pbc.gto.cell.Cell.make_ecp_env" title="Permalink to this definition">¶</a></dt> <dd><p>Generate the input arguments _ecpbas for ECP integrals</p> </dd></dl> <dl class="py method"> <dt id="pyscf.pbc.gto.cell.Cell.make_kpts"> <code class="sig-name descname">make_kpts</code><span class="sig-paren">(</span><em class="sig-param"><span class="n">nks</span></em>, <em class="sig-param"><span class="n">wrap_around</span><span class="o">=</span><span class="default_value">False</span></em>, <em class="sig-param"><span class="n">with_gamma_point</span><span class="o">=</span><span class="default_value">True</span></em>, <em class="sig-param"><span class="n">scaled_center</span><span class="o">=</span><span class="default_value">None</span></em><span class="sig-paren">)</span><a class="headerlink" href="#pyscf.pbc.gto.cell.Cell.make_kpts" title="Permalink to this definition">¶</a></dt> <dd><p>Given number of kpoints along x,y,z , generate kpoints</p> <dl class="simple"> <dt>Args:</dt><dd><p>nks : (3,) ndarray</p> </dd> <dt>Kwargs:</dt><dd><dl class="simple"> <dt>wrap_around<span class="classifier">bool</span></dt><dd><p>To ensure all kpts are in first Brillouin zone.</p> </dd> <dt>with_gamma_point<span class="classifier">bool</span></dt><dd><p>Whether to shift Monkhorst-pack grid to include gamma-point.</p> </dd> <dt>scaled_center<span class="classifier">(3,) array</span></dt><dd><p>Shift all points in the Monkhorst-pack grid to be centered on scaled_center, given as the zeroth index of the returned kpts. Scaled meaning that the k-points are scaled to a grid from [-1,1] x [-1,1] x [-1,1]</p> </dd> </dl> </dd> <dt>Returns:</dt><dd><p>kpts in absolute value (unit 1/Bohr). Gamma point is placed at the first place in the k-points list</p> </dd> </dl> <p>Examples:</p> <div class="doctest highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">cell</span><span class="o">.</span><span class="n">make_kpts</span><span class="p">((</span><span class="mi">4</span><span class="p">,</span><span class="mi">4</span><span class="p">,</span><span class="mi">4</span><span class="p">))</span> </pre></div> </div> </dd></dl> <dl class="py method"> <dt id="pyscf.pbc.gto.cell.Cell.mesh"> <em class="property">property </em><code class="sig-name descname">mesh</code><a class="headerlink" href="#pyscf.pbc.gto.cell.Cell.mesh" title="Permalink to this definition">¶</a></dt> <dd></dd></dl> <dl class="py method"> <dt id="pyscf.pbc.gto.cell.Cell.nelec"> <em class="property">property </em><code class="sig-name descname">nelec</code><a class="headerlink" href="#pyscf.pbc.gto.cell.Cell.nelec" title="Permalink to this definition">¶</a></dt> <dd></dd></dl> <dl class="py method"> <dt id="pyscf.pbc.gto.cell.Cell.nimgs"> <em class="property">property </em><code class="sig-name descname">nimgs</code><a class="headerlink" href="#pyscf.pbc.gto.cell.Cell.nimgs" title="Permalink to this definition">¶</a></dt> <dd></dd></dl> <dl class="py method"> <dt id="pyscf.pbc.gto.cell.Cell.pack"> <code class="sig-name descname">pack</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#pyscf.pbc.gto.cell.Cell.pack" title="Permalink to this definition">¶</a></dt> <dd><p>Pack the input args of <a class="reference internal" href="#pyscf.pbc.gto.cell.Cell" title="pyscf.pbc.gto.cell.Cell"><code class="xref py py-class docutils literal notranslate"><span class="pre">Cell</span></code></a> to a dict, which can be serialized with <code class="xref py py-mod docutils literal notranslate"><span class="pre">pickle</span></code></p> </dd></dl> <dl class="py method"> <dt id="pyscf.pbc.gto.cell.Cell.pbc_eval_ao"> <code class="sig-name descname">pbc_eval_ao</code><span class="sig-paren">(</span><em class="sig-param"><span class="n">eval_name</span></em>, <em class="sig-param"><span class="n">coords</span></em>, <em class="sig-param"><span class="n">comp</span><span class="o">=</span><span class="default_value">None</span></em>, <em class="sig-param"><span class="n">kpts</span><span class="o">=</span><span class="default_value">None</span></em>, <em class="sig-param"><span class="n">kpt</span><span class="o">=</span><span class="default_value">None</span></em>, <em class="sig-param"><span class="n">shls_slice</span><span class="o">=</span><span class="default_value">None</span></em>, <em class="sig-param"><span class="n">non0tab</span><span class="o">=</span><span class="default_value">None</span></em>, <em class="sig-param"><span class="n">ao_loc</span><span class="o">=</span><span class="default_value">None</span></em>, <em class="sig-param"><span class="n">out</span><span class="o">=</span><span class="default_value">None</span></em><span class="sig-paren">)</span><a class="headerlink" href="#pyscf.pbc.gto.cell.Cell.pbc_eval_ao" title="Permalink to this definition">¶</a></dt> <dd><p>Evaluate PBC-AO function value on the given grids,</p> <dl> <dt>Args:</dt><dd><p>eval_name : str</p> <blockquote> <div><table class="docutils align-default"> <colgroup> <col style="width: 49%" /> <col style="width: 51%" /> </colgroup> <thead> <tr class="row-odd"><th class="head"><p>Function</p></th> <th class="head"><p>Expression</p></th> </tr> </thead> <tbody> <tr class="row-even"><td><p>“GTOval_sph”</p></td> <td><p>sum_T exp(ik*T) <a href="#id17"><span class="problematic" id="id18">|</span></a>AO&gt;</p></td> </tr> <tr class="row-odd"><td><p>“GTOval_ip_sph”</p></td> <td><p>nabla sum_T exp(ik*T) <a href="#id19"><span class="problematic" id="id20">|</span></a>AO&gt;</p></td> </tr> <tr class="row-even"><td><p>“GTOval_cart”</p></td> <td><p>sum_T exp(ik*T) <a href="#id21"><span class="problematic" id="id22">|</span></a>AO&gt;</p></td> </tr> <tr class="row-odd"><td><p>“GTOval_ip_cart”</p></td> <td><p>nabla sum_T exp(ik*T) <a href="#id23"><span class="problematic" id="id24">|</span></a>AO&gt;</p></td> </tr> </tbody> </table> </div></blockquote> <dl class="simple"> <dt>atm<span class="classifier">int32 ndarray</span></dt><dd><p>libcint integral function argument</p> </dd> <dt>bas<span class="classifier">int32 ndarray</span></dt><dd><p>libcint integral function argument</p> </dd> <dt>env<span class="classifier">float64 ndarray</span></dt><dd><p>libcint integral function argument</p> </dd> <dt>coords<span class="classifier">2D array, shape (N,3)</span></dt><dd><p>The coordinates of the grids.</p> </dd> </dl> </dd> <dt>Kwargs:</dt><dd><dl class="simple"> <dt>shls_slice<span class="classifier">2-element list</span></dt><dd><p>(shl_start, shl_end). If given, only part of AOs (shl_start &lt;= shell_id &lt; shl_end) are evaluated. By default, all shells defined in cell will be evaluated.</p> </dd> <dt>non0tab<span class="classifier">2D bool array</span></dt><dd><p>mask array to indicate whether the AO values are zero. The mask array can be obtained by calling <code class="xref py py-func docutils literal notranslate"><span class="pre">dft.gen_grid.make_mask()</span></code></p> </dd> <dt>out<span class="classifier">ndarray</span></dt><dd><p>If provided, results are written into this array.</p> </dd> </dl> </dd> <dt>Returns:</dt><dd><p>A list of 2D (or 3D) arrays to hold the AO values on grids. Each element of the list corresponds to a k-point and it has the shape (N,nao) Or shape (*,N,nao).</p> </dd> </dl> <p>Examples:</p> <div class="doctest highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">cell</span> <span class="o">=</span> <span class="n">pbc</span><span class="o">.</span><span class="n">gto</span><span class="o">.</span><span class="n">M</span><span class="p">(</span><span class="n">a</span><span class="o">=</span><span class="n">numpy</span><span class="o">.</span><span class="n">eye</span><span class="p">(</span><span class="mi">3</span><span class="p">)</span><span class="o">*</span><span class="mi">4</span><span class="p">,</span> <span class="n">atom</span><span class="o">=</span><span class="s1">&#39;He 1 1 1&#39;</span><span class="p">,</span> <span class="n">basis</span><span class="o">=</span><span class="s1">&#39;6-31g&#39;</span><span class="p">)</span> <span class="gp">&gt;&gt;&gt; </span><span class="n">coords</span> <span class="o">=</span> <span class="n">cell</span><span class="o">.</span><span class="n">get_uniform_grids</span><span class="p">([</span><span class="mi">20</span><span class="p">,</span><span class="mi">20</span><span class="p">,</span><span class="mi">20</span><span class="p">])</span> <span class="gp">&gt;&gt;&gt; </span><span class="n">kpts</span> <span class="o">=</span> <span class="n">cell</span><span class="o">.</span><span class="n">make_kpts</span><span class="p">([</span><span class="mi">3</span><span class="p">,</span><span class="mi">3</span><span class="p">,</span><span class="mi">3</span><span class="p">])</span> <span class="gp">&gt;&gt;&gt; </span><span class="n">ao_value</span> <span class="o">=</span> <span class="n">cell</span><span class="o">.</span><span class="n">pbc_eval_gto</span><span class="p">(</span><span class="s2">&quot;GTOval_sph&quot;</span><span class="p">,</span> <span class="n">coords</span><span class="p">,</span> <span class="n">kpts</span><span class="p">)</span> <span class="gp">&gt;&gt;&gt; </span><span class="nb">len</span><span class="p">(</span><span class="n">ao_value</span><span class="p">)</span> <span class="go">27</span> <span class="gp">&gt;&gt;&gt; </span><span class="n">ao_value</span><span class="p">[</span><span class="mi">0</span><span class="p">]</span><span class="o">.</span><span class="n">shape</span> <span class="go">(100, 2)</span> <span class="gp">&gt;&gt;&gt; </span><span class="n">ao_value</span> <span class="o">=</span> <span class="n">cell</span><span class="o">.</span><span class="n">pbc_eval_gto</span><span class="p">(</span><span class="s2">&quot;GTOval_ig_sph&quot;</span><span class="p">,</span> <span class="n">coords</span><span class="p">,</span> <span class="n">kpts</span><span class="p">,</span> <span class="n">comp</span><span class="o">=</span><span class="mi">3</span><span class="p">)</span> <span class="gp">&gt;&gt;&gt; </span><span class="nb">print</span><span class="p">(</span><span class="n">ao_value</span><span class="o">.</span><span class="n">shape</span><span class="p">)</span> <span class="gp">&gt;&gt;&gt; </span><span class="nb">len</span><span class="p">(</span><span class="n">ao_value</span><span class="p">)</span> <span class="go">27</span> <span class="gp">&gt;&gt;&gt; </span><span class="n">ao_value</span><span class="p">[</span><span class="mi">0</span><span class="p">]</span><span class="o">.</span><span class="n">shape</span> <span class="go">(3, 100, 2)</span> </pre></div> </div> </dd></dl> <dl class="py method"> <dt id="pyscf.pbc.gto.cell.Cell.pbc_eval_gto"> <code class="sig-name descname">pbc_eval_gto</code><span class="sig-paren">(</span><em class="sig-param"><span class="n">eval_name</span></em>, <em class="sig-param"><span class="n">coords</span></em>, <em class="sig-param"><span class="n">comp</span><span class="o">=</span><span class="default_value">None</span></em>, <em class="sig-param"><span class="n">kpts</span><span class="o">=</span><span class="default_value">None</span></em>, <em class="sig-param"><span class="n">kpt</span><span class="o">=</span><span class="default_value">None</span></em>, <em class="sig-param"><span class="n">shls_slice</span><span class="o">=</span><span class="default_value">None</span></em>, <em class="sig-param"><span class="n">non0tab</span><span class="o">=</span><span class="default_value">None</span></em>, <em class="sig-param"><span class="n">ao_loc</span><span class="o">=</span><span class="default_value">None</span></em>, <em class="sig-param"><span class="n">out</span><span class="o">=</span><span class="default_value">None</span></em><span class="sig-paren">)</span><a class="headerlink" href="#pyscf.pbc.gto.cell.Cell.pbc_eval_gto" title="Permalink to this definition">¶</a></dt> <dd><p>Evaluate PBC-AO function value on the given grids,</p> <dl> <dt>Args:</dt><dd><p>eval_name : str</p> <blockquote> <div><table class="docutils align-default"> <colgroup> <col style="width: 49%" /> <col style="width: 51%" /> </colgroup> <thead> <tr class="row-odd"><th class="head"><p>Function</p></th> <th class="head"><p>Expression</p></th> </tr> </thead> <tbody> <tr class="row-even"><td><p>“GTOval_sph”</p></td> <td><p>sum_T exp(ik*T) <a href="#id25"><span class="problematic" id="id26">|</span></a>AO&gt;</p></td> </tr> <tr class="row-odd"><td><p>“GTOval_ip_sph”</p></td> <td><p>nabla sum_T exp(ik*T) <a href="#id27"><span class="problematic" id="id28">|</span></a>AO&gt;</p></td> </tr> <tr class="row-even"><td><p>“GTOval_cart”</p></td> <td><p>sum_T exp(ik*T) <a href="#id29"><span class="problematic" id="id30">|</span></a>AO&gt;</p></td> </tr> <tr class="row-odd"><td><p>“GTOval_ip_cart”</p></td> <td><p>nabla sum_T exp(ik*T) <a href="#id31"><span class="problematic" id="id32">|</span></a>AO&gt;</p></td> </tr> </tbody> </table> </div></blockquote> <dl class="simple"> <dt>atm<span class="classifier">int32 ndarray</span></dt><dd><p>libcint integral function argument</p> </dd> <dt>bas<span class="classifier">int32 ndarray</span></dt><dd><p>libcint integral function argument</p> </dd> <dt>env<span class="classifier">float64 ndarray</span></dt><dd><p>libcint integral function argument</p> </dd> <dt>coords<span class="classifier">2D array, shape (N,3)</span></dt><dd><p>The coordinates of the grids.</p> </dd> </dl> </dd> <dt>Kwargs:</dt><dd><dl class="simple"> <dt>shls_slice<span class="classifier">2-element list</span></dt><dd><p>(shl_start, shl_end). If given, only part of AOs (shl_start &lt;= shell_id &lt; shl_end) are evaluated. By default, all shells defined in cell will be evaluated.</p> </dd> <dt>non0tab<span class="classifier">2D bool array</span></dt><dd><p>mask array to indicate whether the AO values are zero. The mask array can be obtained by calling <code class="xref py py-func docutils literal notranslate"><span class="pre">dft.gen_grid.make_mask()</span></code></p> </dd> <dt>out<span class="classifier">ndarray</span></dt><dd><p>If provided, results are written into this array.</p> </dd> </dl> </dd> <dt>Returns:</dt><dd><p>A list of 2D (or 3D) arrays to hold the AO values on grids. Each element of the list corresponds to a k-point and it has the shape (N,nao) Or shape (*,N,nao).</p> </dd> </dl> <p>Examples:</p> <div class="doctest highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">cell</span> <span class="o">=</span> <span class="n">pbc</span><span class="o">.</span><span class="n">gto</span><span class="o">.</span><span class="n">M</span><span class="p">(</span><span class="n">a</span><span class="o">=</span><span class="n">numpy</span><span class="o">.</span><span class="n">eye</span><span class="p">(</span><span class="mi">3</span><span class="p">)</span><span class="o">*</span><span class="mi">4</span><span class="p">,</span> <span class="n">atom</span><span class="o">=</span><span class="s1">&#39;He 1 1 1&#39;</span><span class="p">,</span> <span class="n">basis</span><span class="o">=</span><span class="s1">&#39;6-31g&#39;</span><span class="p">)</span> <span class="gp">&gt;&gt;&gt; </span><span class="n">coords</span> <span class="o">=</span> <span class="n">cell</span><span class="o">.</span><span class="n">get_uniform_grids</span><span class="p">([</span><span class="mi">20</span><span class="p">,</span><span class="mi">20</span><span class="p">,</span><span class="mi">20</span><span class="p">])</span> <span class="gp">&gt;&gt;&gt; </span><span class="n">kpts</span> <span class="o">=</span> <span class="n">cell</span><span class="o">.</span><span class="n">make_kpts</span><span class="p">([</span><span class="mi">3</span><span class="p">,</span><span class="mi">3</span><span class="p">,</span><span class="mi">3</span><span class="p">])</span> <span class="gp">&gt;&gt;&gt; </span><span class="n">ao_value</span> <span class="o">=</span> <span class="n">cell</span><span class="o">.</span><span class="n">pbc_eval_gto</span><span class="p">(</span><span class="s2">&quot;GTOval_sph&quot;</span><span class="p">,</span> <span class="n">coords</span><span class="p">,</span> <span class="n">kpts</span><span class="p">)</span> <span class="gp">&gt;&gt;&gt; </span><span class="nb">len</span><span class="p">(</span><span class="n">ao_value</span><span class="p">)</span> <span class="go">27</span> <span class="gp">&gt;&gt;&gt; </span><span class="n">ao_value</span><span class="p">[</span><span class="mi">0</span><span class="p">]</span><span class="o">.</span><span class="n">shape</span> <span class="go">(100, 2)</span> <span class="gp">&gt;&gt;&gt; </span><span class="n">ao_value</span> <span class="o">=</span> <span class="n">cell</span><span class="o">.</span><span class="n">pbc_eval_gto</span><span class="p">(</span><span class="s2">&quot;GTOval_ig_sph&quot;</span><span class="p">,</span> <span class="n">coords</span><span class="p">,</span> <span class="n">kpts</span><span class="p">,</span> <span class="n">comp</span><span class="o">=</span><span class="mi">3</span><span class="p">)</span> <span class="gp">&gt;&gt;&gt; </span><span class="nb">print</span><span class="p">(</span><span class="n">ao_value</span><span class="o">.</span><span class="n">shape</span><span class="p">)</span> <span class="gp">&gt;&gt;&gt; </span><span class="nb">len</span><span class="p">(</span><span class="n">ao_value</span><span class="p">)</span> <span class="go">27</span> <span class="gp">&gt;&gt;&gt; </span><span class="n">ao_value</span><span class="p">[</span><span class="mi">0</span><span class="p">]</span><span class="o">.</span><span class="n">shape</span> <span class="go">(3, 100, 2)</span> </pre></div> </div> </dd></dl> <dl class="py method"> <dt id="pyscf.pbc.gto.cell.Cell.pbc_intor"> <code class="sig-name descname">pbc_intor</code><span class="sig-paren">(</span><em class="sig-param"><span class="n">intor</span></em>, <em class="sig-param"><span class="n">comp</span><span class="o">=</span><span class="default_value">None</span></em>, <em class="sig-param"><span class="n">hermi</span><span class="o">=</span><span class="default_value">0</span></em>, <em class="sig-param"><span class="n">kpts</span><span class="o">=</span><span class="default_value">None</span></em>, <em class="sig-param"><span class="n">kpt</span><span class="o">=</span><span class="default_value">None</span></em>, <em class="sig-param"><span class="n">shls_slice</span><span class="o">=</span><span class="default_value">None</span></em>, <em class="sig-param"><span class="o">**</span><span class="n">kwargs</span></em><span class="sig-paren">)</span><a class="headerlink" href="#pyscf.pbc.gto.cell.Cell.pbc_intor" title="Permalink to this definition">¶</a></dt> <dd><p>One-electron integrals with PBC.</p> <div class="math notranslate nohighlight"> \[\sum_T \int \mu(r) * [intor] * \nu (r-T) dr\]</div> <p>See also Mole.intor</p> </dd></dl> <dl class="py attribute"> <dt id="pyscf.pbc.gto.cell.Cell.precision"> <code class="sig-name descname">precision</code><em class="property"> = 1e-08</em><a class="headerlink" href="#pyscf.pbc.gto.cell.Cell.precision" title="Permalink to this definition">¶</a></dt> <dd></dd></dl> <dl class="py method"> <dt id="pyscf.pbc.gto.cell.Cell.rcut"> <em class="property">property </em><code class="sig-name descname">rcut</code><a class="headerlink" href="#pyscf.pbc.gto.cell.Cell.rcut" title="Permalink to this definition">¶</a></dt> <dd></dd></dl> <dl class="py method"> <dt id="pyscf.pbc.gto.cell.Cell.reciprocal_vectors"> <code class="sig-name descname">reciprocal_vectors</code><span class="sig-paren">(</span><em class="sig-param"><span class="n">norm_to</span><span class="o">=</span><span class="default_value">6.283185307179586</span></em><span class="sig-paren">)</span><a class="headerlink" href="#pyscf.pbc.gto.cell.Cell.reciprocal_vectors" title="Permalink to this definition">¶</a></dt> <dd><div class="math notranslate nohighlight"> \[\begin{split}\begin{align} \mathbf{b_1} &amp;= 2\pi \frac{\mathbf{a_2} \times \mathbf{a_3}}{\mathbf{a_1} \cdot (\mathbf{a_2} \times \mathbf{a_3})} \\ \mathbf{b_2} &amp;= 2\pi \frac{\mathbf{a_3} \times \mathbf{a_1}}{\mathbf{a_2} \cdot (\mathbf{a_3} \times \mathbf{a_1})} \\ \mathbf{b_3} &amp;= 2\pi \frac{\mathbf{a_1} \times \mathbf{a_2}}{\mathbf{a_3} \cdot (\mathbf{a_1} \times \mathbf{a_2})} \end{align}\end{split}\]</div> </dd></dl> <dl class="py method"> <dt id="pyscf.pbc.gto.cell.Cell.to_mol"> <code class="sig-name descname">to_mol</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#pyscf.pbc.gto.cell.Cell.to_mol" title="Permalink to this definition">¶</a></dt> <dd><p>Return a Mole object using the same atoms and basis functions as the Cell object.</p> </dd></dl> <dl class="py method"> <dt id="pyscf.pbc.gto.cell.Cell.tot_electrons"> <code class="sig-name descname">tot_electrons</code><span class="sig-paren">(</span><em class="sig-param"><span class="n">nkpts</span><span class="o">=</span><span class="default_value">1</span></em><span class="sig-paren">)</span><a class="headerlink" href="#pyscf.pbc.gto.cell.Cell.tot_electrons" title="Permalink to this definition">¶</a></dt> <dd><p>Total number of electrons</p> </dd></dl> <dl class="py method"> <dt id="pyscf.pbc.gto.cell.Cell.unpack"> <code class="sig-name descname">unpack</code><span class="sig-paren">(</span><em class="sig-param"><span class="n">moldic</span></em><span class="sig-paren">)</span><a class="headerlink" href="#pyscf.pbc.gto.cell.Cell.unpack" title="Permalink to this definition">¶</a></dt> <dd><p>Convert the packed dict to a <a class="reference internal" href="#pyscf.pbc.gto.cell.Cell" title="pyscf.pbc.gto.cell.Cell"><code class="xref py py-class docutils literal notranslate"><span class="pre">Cell</span></code></a> object, to generate the input arguments for <a class="reference internal" href="#pyscf.pbc.gto.cell.Cell" title="pyscf.pbc.gto.cell.Cell"><code class="xref py py-class docutils literal notranslate"><span class="pre">Cell</span></code></a> object.</p> </dd></dl> <dl class="py method"> <dt id="pyscf.pbc.gto.cell.Cell.unpack_"> <code class="sig-name descname">unpack_</code><span class="sig-paren">(</span><em class="sig-param"><span class="n">moldic</span></em><span class="sig-paren">)</span><a class="headerlink" href="#pyscf.pbc.gto.cell.Cell.unpack_" title="Permalink to this definition">¶</a></dt> <dd></dd></dl> <dl class="py method"> <dt id="pyscf.pbc.gto.cell.Cell.vol"> <em class="property">property </em><code class="sig-name descname">vol</code><a class="headerlink" href="#pyscf.pbc.gto.cell.Cell.vol" title="Permalink to this definition">¶</a></dt> <dd></dd></dl> </dd></dl> <dl class="py function"> <dt id="pyscf.pbc.gto.cell.M"> <code class="sig-prename descclassname">pyscf.pbc.gto.cell.</code><code class="sig-name descname">M</code><span class="sig-paren">(</span><em class="sig-param"><span class="o">**</span><span class="n">kwargs</span></em><span class="sig-paren">)</span><a class="headerlink" href="#pyscf.pbc.gto.cell.M" title="Permalink to this definition">¶</a></dt> <dd><p>This is a shortcut to build up Cell object.</p> <p>Examples:</p> <div class="doctest highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">from</span> <span class="nn">pyscf.pbc</span> <span class="kn">import</span> <span class="n">gto</span> <span class="gp">&gt;&gt;&gt; </span><span class="n">cell</span> <span class="o">=</span> <span class="n">gto</span><span class="o">.</span><span class="n">M</span><span class="p">(</span><span class="n">a</span><span class="o">=</span><span class="n">numpy</span><span class="o">.</span><span class="n">eye</span><span class="p">(</span><span class="mi">3</span><span class="p">)</span><span class="o">*</span><span class="mi">4</span><span class="p">,</span> <span class="n">atom</span><span class="o">=</span><span class="s1">&#39;He 1 1 1&#39;</span><span class="p">,</span> <span class="n">basis</span><span class="o">=</span><span class="s1">&#39;6-31g&#39;</span><span class="p">)</span> </pre></div> </div> </dd></dl> <dl class="py function"> <dt id="pyscf.pbc.gto.cell.bas_rcut"> <code class="sig-prename descclassname">pyscf.pbc.gto.cell.</code><code class="sig-name descname">bas_rcut</code><span class="sig-paren">(</span><em class="sig-param"><span class="n">cell</span></em>, <em class="sig-param"><span class="n">bas_id</span></em>, <em class="sig-param"><span class="n">precision</span><span class="o">=</span><span class="default_value">1e-08</span></em><span class="sig-paren">)</span><a class="headerlink" href="#pyscf.pbc.gto.cell.bas_rcut" title="Permalink to this definition">¶</a></dt> <dd><p>Estimate the largest distance between the function and its image to reach the precision in overlap</p> <p>precision ~ int g(r-0) g(r-Rcut)</p> </dd></dl> <dl class="py function"> <dt id="pyscf.pbc.gto.cell.classify_ecp_pseudo"> <code class="sig-prename descclassname">pyscf.pbc.gto.cell.</code><code class="sig-name descname">classify_ecp_pseudo</code><span class="sig-paren">(</span><em class="sig-param"><span class="n">cell</span></em>, <em class="sig-param"><span class="n">ecp</span></em>, <em class="sig-param"><span class="n">pp</span></em><span class="sig-paren">)</span><a class="headerlink" href="#pyscf.pbc.gto.cell.classify_ecp_pseudo" title="Permalink to this definition">¶</a></dt> <dd></dd></dl> <dl class="py function"> <dt id="pyscf.pbc.gto.cell.conc_cell"> <code class="sig-prename descclassname">pyscf.pbc.gto.cell.</code><code class="sig-name descname">conc_cell</code><span class="sig-paren">(</span><em class="sig-param"><span class="n">cell1</span></em>, <em class="sig-param"><span class="n">cell2</span></em><span class="sig-paren">)</span><a class="headerlink" href="#pyscf.pbc.gto.cell.conc_cell" title="Permalink to this definition">¶</a></dt> <dd><p>Concatenate two Cell objects.</p> </dd></dl> <dl class="py function"> <dt id="pyscf.pbc.gto.cell.copy"> <code class="sig-prename descclassname">pyscf.pbc.gto.cell.</code><code class="sig-name descname">copy</code><span class="sig-paren">(</span><em class="sig-param"><span class="n">cell</span></em><span class="sig-paren">)</span><a class="headerlink" href="#pyscf.pbc.gto.cell.copy" title="Permalink to this definition">¶</a></dt> <dd><p>Deepcopy of the given <a class="reference internal" href="#pyscf.pbc.gto.cell.Cell" title="pyscf.pbc.gto.cell.Cell"><code class="xref py py-class docutils literal notranslate"><span class="pre">Cell</span></code></a> object</p> </dd></dl> <dl class="py function"> <dt id="pyscf.pbc.gto.cell.dumps"> <code class="sig-prename descclassname">pyscf.pbc.gto.cell.</code><code class="sig-name descname">dumps</code><span class="sig-paren">(</span><em class="sig-param"><span class="n">cell</span></em><span class="sig-paren">)</span><a class="headerlink" href="#pyscf.pbc.gto.cell.dumps" title="Permalink to this definition">¶</a></dt> <dd><p>Serialize Cell object to a JSON formatted str.</p> </dd></dl> <dl class="py function"> <dt id="pyscf.pbc.gto.cell.energy_nuc"> <code class="sig-prename descclassname">pyscf.pbc.gto.cell.</code><code class="sig-name descname">energy_nuc</code><span class="sig-paren">(</span><em class="sig-param"><span class="n">cell</span></em>, <em class="sig-param"><span class="n">ew_eta</span><span class="o">=</span><span class="default_value">None</span></em>, <em class="sig-param"><span class="n">ew_cut</span><span class="o">=</span><span class="default_value">None</span></em><span class="sig-paren">)</span><a class="headerlink" href="#pyscf.pbc.gto.cell.energy_nuc" title="Permalink to this definition">¶</a></dt> <dd><p>Perform real (R) and reciprocal (G) space Ewald sum for the energy.</p> <p>Formulation of Martin, App. F2.</p> <dl class="simple"> <dt>Returns:</dt><dd><dl class="simple"> <dt>float</dt><dd><p>The Ewald energy consisting of overlap, self, and G-space sum.</p> </dd> </dl> </dd> <dt>See Also:</dt><dd><p>pyscf.pbc.gto.get_ewald_params</p> </dd> </dl> </dd></dl> <dl class="py function"> <dt id="pyscf.pbc.gto.cell.error_for_ke_cutoff"> <code class="sig-prename descclassname">pyscf.pbc.gto.cell.</code><code class="sig-name descname">error_for_ke_cutoff</code><span class="sig-paren">(</span><em class="sig-param"><span class="n">cell</span></em>, <em class="sig-param"><span class="n">ke_cutoff</span></em><span class="sig-paren">)</span><a class="headerlink" href="#pyscf.pbc.gto.cell.error_for_ke_cutoff" title="Permalink to this definition">¶</a></dt> <dd></dd></dl> <dl class="py function"> <dt id="pyscf.pbc.gto.cell.estimate_ke_cutoff"> <code class="sig-prename descclassname">pyscf.pbc.gto.cell.</code><code class="sig-name descname">estimate_ke_cutoff</code><span class="sig-paren">(</span><em class="sig-param"><span class="n">cell</span></em>, <em class="sig-param"><span class="n">precision</span><span class="o">=</span><span class="default_value">1e-08</span></em><span class="sig-paren">)</span><a class="headerlink" href="#pyscf.pbc.gto.cell.estimate_ke_cutoff" title="Permalink to this definition">¶</a></dt> <dd><p>Energy cutoff estimation</p> </dd></dl> <dl class="py function"> <dt id="pyscf.pbc.gto.cell.ewald"> <code class="sig-prename descclassname">pyscf.pbc.gto.cell.</code><code class="sig-name descname">ewald</code><span class="sig-paren">(</span><em class="sig-param"><span class="n">cell</span></em>, <em class="sig-param"><span class="n">ew_eta</span><span class="o">=</span><span class="default_value">None</span></em>, <em class="sig-param"><span class="n">ew_cut</span><span class="o">=</span><span class="default_value">None</span></em><span class="sig-paren">)</span><a class="headerlink" href="#pyscf.pbc.gto.cell.ewald" title="Permalink to this definition">¶</a></dt> <dd><p>Perform real (R) and reciprocal (G) space Ewald sum for the energy.</p> <p>Formulation of Martin, App. F2.</p> <dl class="simple"> <dt>Returns:</dt><dd><dl class="simple"> <dt>float</dt><dd><p>The Ewald energy consisting of overlap, self, and G-space sum.</p> </dd> </dl> </dd> <dt>See Also:</dt><dd><p>pyscf.pbc.gto.get_ewald_params</p> </dd> </dl> </dd></dl> <dl class="py function"> <dt id="pyscf.pbc.gto.cell.format_basis"> <code class="sig-prename descclassname">pyscf.pbc.gto.cell.</code><code class="sig-name descname">format_basis</code><span class="sig-paren">(</span><em class="sig-param"><span class="n">basis_tab</span></em><span class="sig-paren">)</span><a class="headerlink" href="#pyscf.pbc.gto.cell.format_basis" title="Permalink to this definition">¶</a></dt> <dd><p>Convert the input <code class="xref py py-attr docutils literal notranslate"><span class="pre">Cell.basis</span></code> to the internal data format:</p> <div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="p">{</span> <span class="n">atom</span><span class="p">:</span> <span class="p">(</span><span class="n">l</span><span class="p">,</span> <span class="n">kappa</span><span class="p">,</span> <span class="p">((</span><span class="o">-</span><span class="n">exp</span><span class="p">,</span> <span class="n">c_1</span><span class="p">,</span> <span class="n">c_2</span><span class="p">,</span> <span class="o">..</span><span class="p">),</span> <span class="n">nprim</span><span class="p">,</span> <span class="n">nctr</span><span class="p">,</span> <span class="n">ptr</span><span class="o">-</span><span class="n">exps</span><span class="p">,</span> <span class="n">ptr</span><span class="o">-</span><span class="n">contraction</span><span class="o">-</span><span class="n">coeff</span><span class="p">)),</span> <span class="o">...</span> <span class="p">}</span> </pre></div> </div> <dl class="simple"> <dt>Args:</dt><dd><dl class="simple"> <dt>basis_tab<span class="classifier">dict</span></dt><dd><p>Similar to <code class="xref py py-attr docutils literal notranslate"><span class="pre">Cell.basis</span></code>, it <strong>cannot</strong> be a str</p> </dd> </dl> </dd> <dt>Returns:</dt><dd><p>Formated <code class="xref py py-attr docutils literal notranslate"><span class="pre">basis</span></code></p> </dd> </dl> <p>Examples:</p> <div class="doctest highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">pbc</span><span class="o">.</span><span class="n">format_basis</span><span class="p">({</span><span class="s1">&#39;H&#39;</span><span class="p">:</span><span class="s1">&#39;gth-szv&#39;</span><span class="p">})</span> <span class="go">{&#39;H&#39;: [[0,</span> <span class="go"> (8.3744350009, -0.0283380461),</span> <span class="go"> (1.8058681460, -0.1333810052),</span> <span class="go"> (0.4852528328, -0.3995676063),</span> <span class="go"> (0.1658236932, -0.5531027541)]]}</span> </pre></div> </div> </dd></dl> <dl class="py function"> <dt id="pyscf.pbc.gto.cell.format_pseudo"> <code class="sig-prename descclassname">pyscf.pbc.gto.cell.</code><code class="sig-name descname">format_pseudo</code><span class="sig-paren">(</span><em class="sig-param"><span class="n">pseudo_tab</span></em><span class="sig-paren">)</span><a class="headerlink" href="#pyscf.pbc.gto.cell.format_pseudo" title="Permalink to this definition">¶</a></dt> <dd><p>Convert the input <code class="xref py py-attr docutils literal notranslate"><span class="pre">Cell.pseudo</span></code> (dict) to the internal data format:</p> <div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="p">{</span> <span class="n">atom</span><span class="p">:</span> <span class="p">(</span> <span class="p">(</span><span class="n">nelec_s</span><span class="p">,</span> <span class="n">nele_p</span><span class="p">,</span> <span class="n">nelec_d</span><span class="p">,</span> <span class="o">...</span><span class="p">),</span> <span class="n">rloc</span><span class="p">,</span> <span class="n">nexp</span><span class="p">,</span> <span class="p">(</span><span class="n">cexp_1</span><span class="p">,</span> <span class="n">cexp_2</span><span class="p">,</span> <span class="o">...</span><span class="p">,</span> <span class="n">cexp_nexp</span><span class="p">),</span> <span class="n">nproj_types</span><span class="p">,</span> <span class="p">(</span><span class="n">r1</span><span class="p">,</span> <span class="n">nproj1</span><span class="p">,</span> <span class="p">(</span> <span class="p">(</span><span class="n">hproj1</span><span class="p">[</span><span class="mi">1</span><span class="p">,</span><span class="mi">1</span><span class="p">],</span> <span class="n">hproj1</span><span class="p">[</span><span class="mi">1</span><span class="p">,</span><span class="mi">2</span><span class="p">],</span> <span class="o">...</span><span class="p">,</span> <span class="n">hproj1</span><span class="p">[</span><span class="mi">1</span><span class="p">,</span><span class="n">nproj1</span><span class="p">]),</span> <span class="p">(</span><span class="n">hproj1</span><span class="p">[</span><span class="mi">2</span><span class="p">,</span><span class="mi">1</span><span class="p">],</span> <span class="n">hproj1</span><span class="p">[</span><span class="mi">2</span><span class="p">,</span><span class="mi">2</span><span class="p">],</span> <span class="o">...</span><span class="p">,</span> <span class="n">hproj1</span><span class="p">[</span><span class="mi">2</span><span class="p">,</span><span class="n">nproj1</span><span class="p">]),</span> <span class="o">...</span> <span class="p">(</span><span class="n">hproj1</span><span class="p">[</span><span class="n">nproj1</span><span class="p">,</span><span class="mi">1</span><span class="p">],</span> <span class="n">hproj1</span><span class="p">[</span><span class="n">nproj1</span><span class="p">,</span><span class="mi">2</span><span class="p">],</span> <span class="o">...</span> <span class="p">)</span> <span class="p">)),</span> <span class="p">(</span><span class="n">r2</span><span class="p">,</span> <span class="n">nproj2</span><span class="p">,</span> <span class="p">(</span> <span class="p">(</span><span class="n">hproj2</span><span class="p">[</span><span class="mi">1</span><span class="p">,</span><span class="mi">1</span><span class="p">],</span> <span class="n">hproj2</span><span class="p">[</span><span class="mi">1</span><span class="p">,</span><span class="mi">2</span><span class="p">],</span> <span class="o">...</span><span class="p">,</span> <span class="n">hproj2</span><span class="p">[</span><span class="mi">1</span><span class="p">,</span><span class="n">nproj1</span><span class="p">]),</span> <span class="o">...</span> <span class="p">)</span> <span class="p">)</span> <span class="p">)</span> <span class="o">...</span> <span class="p">}</span> </pre></div> </div> <dl class="simple"> <dt>Args:</dt><dd><dl class="simple"> <dt>pseudo_tab<span class="classifier">dict</span></dt><dd><p>Similar to <code class="xref py py-attr docutils literal notranslate"><span class="pre">Cell.pseudo</span></code> (a dict), it <strong>cannot</strong> be a str</p> </dd> </dl> </dd> <dt>Returns:</dt><dd><p>Formatted <code class="xref py py-attr docutils literal notranslate"><span class="pre">pseudo</span></code></p> </dd> </dl> <p>Examples:</p> <div class="doctest highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">pbc</span><span class="o">.</span><span class="n">format_pseudo</span><span class="p">({</span><span class="s1">&#39;H&#39;</span><span class="p">:</span><span class="s1">&#39;gth-blyp&#39;</span><span class="p">,</span> <span class="s1">&#39;He&#39;</span><span class="p">:</span> <span class="s1">&#39;gth-pade&#39;</span><span class="p">})</span> <span class="go">{&#39;H&#39;: [[1],</span> <span class="go"> 0.2, 2, [-4.19596147, 0.73049821], 0],</span> <span class="go"> &#39;He&#39;: [[2],</span> <span class="go"> 0.2, 2, [-9.1120234, 1.69836797], 0]}</span> </pre></div> </div> </dd></dl> <dl class="py function"> <dt id="pyscf.pbc.gto.cell.gen_uniform_grids"> <code class="sig-prename descclassname">pyscf.pbc.gto.cell.</code><code class="sig-name descname">gen_uniform_grids</code><span class="sig-paren">(</span><em class="sig-param"><span class="n">cell</span></em>, <em class="sig-param"><span class="n">mesh</span><span class="o">=</span><span class="default_value">None</span></em>, <em class="sig-param"><span class="o">**</span><span class="n">kwargs</span></em><span class="sig-paren">)</span><a class="headerlink" href="#pyscf.pbc.gto.cell.gen_uniform_grids" title="Permalink to this definition">¶</a></dt> <dd><p>Generate a uniform real-space grid consistent w/ samp thm; see MH (3.19).</p> <dl class="simple"> <dt>Args:</dt><dd><p>cell : instance of <a class="reference internal" href="#pyscf.pbc.gto.cell.Cell" title="pyscf.pbc.gto.cell.Cell"><code class="xref py py-class docutils literal notranslate"><span class="pre">Cell</span></code></a></p> </dd> <dt>Returns:</dt><dd><dl class="simple"> <dt>coords<span class="classifier">(ngx*ngy*ngz, 3) ndarray</span></dt><dd><p>The real-space grid point coordinates.</p> </dd> </dl> </dd> </dl> </dd></dl> <dl class="py function"> <dt id="pyscf.pbc.gto.cell.get_Gv"> <code class="sig-prename descclassname">pyscf.pbc.gto.cell.</code><code class="sig-name descname">get_Gv</code><span class="sig-paren">(</span><em class="sig-param"><span class="n">cell</span></em>, <em class="sig-param"><span class="n">mesh</span><span class="o">=</span><span class="default_value">None</span></em>, <em class="sig-param"><span class="o">**</span><span class="n">kwargs</span></em><span class="sig-paren">)</span><a class="headerlink" href="#pyscf.pbc.gto.cell.get_Gv" title="Permalink to this definition">¶</a></dt> <dd><p>Calculate three-dimensional G-vectors for the cell; see MH (3.8).</p> <p>Indices along each direction go as [0…N-1, -N…-1] to follow FFT convention.</p> <dl class="simple"> <dt>Args:</dt><dd><p>cell : instance of <a class="reference internal" href="#pyscf.pbc.gto.cell.Cell" title="pyscf.pbc.gto.cell.Cell"><code class="xref py py-class docutils literal notranslate"><span class="pre">Cell</span></code></a></p> </dd> <dt>Returns:</dt><dd><dl class="simple"> <dt>Gv<span class="classifier">(ngrids, 3) ndarray of floats</span></dt><dd><p>The array of G-vectors.</p> </dd> </dl> </dd> </dl> </dd></dl> <dl class="py function"> <dt id="pyscf.pbc.gto.cell.get_Gv_weights"> <code class="sig-prename descclassname">pyscf.pbc.gto.cell.</code><code class="sig-name descname">get_Gv_weights</code><span class="sig-paren">(</span><em class="sig-param"><span class="n">cell</span></em>, <em class="sig-param"><span class="n">mesh</span><span class="o">=</span><span class="default_value">None</span></em>, <em class="sig-param"><span class="o">**</span><span class="n">kwargs</span></em><span class="sig-paren">)</span><a class="headerlink" href="#pyscf.pbc.gto.cell.get_Gv_weights" title="Permalink to this definition">¶</a></dt> <dd><p>Calculate G-vectors and weights.</p> <dl class="simple"> <dt>Returns:</dt><dd><dl class="simple"> <dt>Gv<span class="classifier">(ngris, 3) ndarray of floats</span></dt><dd><p>The array of G-vectors.</p> </dd> </dl> </dd> </dl> </dd></dl> <dl class="py function"> <dt id="pyscf.pbc.gto.cell.get_SI"> <code class="sig-prename descclassname">pyscf.pbc.gto.cell.</code><code class="sig-name descname">get_SI</code><span class="sig-paren">(</span><em class="sig-param"><span class="n">cell</span></em>, <em class="sig-param"><span class="n">Gv</span><span class="o">=</span><span class="default_value">None</span></em><span class="sig-paren">)</span><a class="headerlink" href="#pyscf.pbc.gto.cell.get_SI" title="Permalink to this definition">¶</a></dt> <dd><p>Calculate the structure factor (0D, 1D, 2D, 3D) for all atoms; see MH (3.34).</p> <dl> <dt>Args:</dt><dd><p>cell : instance of <a class="reference internal" href="#pyscf.pbc.gto.cell.Cell" title="pyscf.pbc.gto.cell.Cell"><code class="xref py py-class docutils literal notranslate"><span class="pre">Cell</span></code></a></p> <dl class="simple"> <dt>Gv<span class="classifier">(N,3) array</span></dt><dd><p>G vectors</p> </dd> </dl> </dd> <dt>Returns:</dt><dd><dl class="simple"> <dt>SI<span class="classifier">(natm, ngrids) ndarray, dtype=np.complex128</span></dt><dd><p>The structure factor for each atom at each G-vector.</p> </dd> </dl> </dd> </dl> </dd></dl> <dl class="py function"> <dt id="pyscf.pbc.gto.cell.get_bounding_sphere"> <code class="sig-prename descclassname">pyscf.pbc.gto.cell.</code><code class="sig-name descname">get_bounding_sphere</code><span class="sig-paren">(</span><em class="sig-param"><span class="n">cell</span></em>, <em class="sig-param"><span class="n">rcut</span></em><span class="sig-paren">)</span><a class="headerlink" href="#pyscf.pbc.gto.cell.get_bounding_sphere" title="Permalink to this definition">¶</a></dt> <dd><p>Finds all the lattice points within a sphere of radius rcut.</p> <p>Defines a parallelipiped given by -N_x &lt;= n_x &lt;= N_x, with x in [1,3] See Martin p. 85</p> <dl class="simple"> <dt>Args:</dt><dd><dl class="simple"> <dt>rcut<span class="classifier">number</span></dt><dd><p>real space cut-off for interaction</p> </dd> </dl> </dd> <dt>Returns:</dt><dd><p>cut : ndarray of 3 ints defining N_x</p> </dd> </dl> </dd></dl> <dl class="py function"> <dt id="pyscf.pbc.gto.cell.get_ewald_params"> <code class="sig-prename descclassname">pyscf.pbc.gto.cell.</code><code class="sig-name descname">get_ewald_params</code><span class="sig-paren">(</span><em class="sig-param"><span class="n">cell</span></em>, <em class="sig-param"><span class="n">precision</span><span class="o">=</span><span class="default_value">1e-08</span></em>, <em class="sig-param"><span class="n">mesh</span><span class="o">=</span><span class="default_value">None</span></em><span class="sig-paren">)</span><a class="headerlink" href="#pyscf.pbc.gto.cell.get_ewald_params" title="Permalink to this definition">¶</a></dt> <dd><p>Choose a reasonable value of Ewald ‘eta’ and ‘cut’ parameters. eta^2 is the exponent coefficient of the model Gaussian charge for nucleus at R: frac{eta^3}{pi^1.5} e^{-eta^2 (r-R)^2}</p> <p>Choice is based on largest G vector and desired relative precision.</p> <p>The relative error in the G-space sum is given by</p> <blockquote> <div><p>precision ~ 4pi Gmax^2 e^{(-Gmax^2)/(4 eta^2)}</p> </div></blockquote> <p>which determines eta. Then, real-space cutoff is determined by (exp. factors only)</p> <blockquote> <div><p>precision ~ erfc(eta*rcut) / rcut ~ e^{(-eta**2 rcut*2)}</p> </div></blockquote> <dl class="simple"> <dt>Returns:</dt><dd><dl class="simple"> <dt>ew_eta, ew_cut<span class="classifier">float</span></dt><dd><p>The Ewald ‘eta’ and ‘cut’ parameters.</p> </dd> </dl> </dd> </dl> </dd></dl> <dl class="py function"> <dt id="pyscf.pbc.gto.cell.get_nimgs"> <code class="sig-prename descclassname">pyscf.pbc.gto.cell.</code><code class="sig-name descname">get_nimgs</code><span class="sig-paren">(</span><em class="sig-param"><span class="n">cell</span></em>, <em class="sig-param"><span class="n">precision</span><span class="o">=</span><span class="default_value">None</span></em><span class="sig-paren">)</span><a class="headerlink" href="#pyscf.pbc.gto.cell.get_nimgs" title="Permalink to this definition">¶</a></dt> <dd><p>Choose number of basis function images in lattice sums to include for given precision in overlap, using</p> <p>precision ~ int r^l e^{-alpha r^2} (r-rcut)^l e^{-alpha (r-rcut)^2} ~ (rcut^2/(2alpha))^l e^{alpha/2 rcut^2}</p> <p>where alpha is the smallest exponent in the basis. Note that assumes an isolated exponent in the middle of the box, so it adds one additional lattice vector to be safe.</p> </dd></dl> <dl class="py function"> <dt id="pyscf.pbc.gto.cell.get_uniform_grids"> <code class="sig-prename descclassname">pyscf.pbc.gto.cell.</code><code class="sig-name descname">get_uniform_grids</code><span class="sig-paren">(</span><em class="sig-param"><span class="n">cell</span></em>, <em class="sig-param"><span class="n">mesh</span><span class="o">=</span><span class="default_value">None</span></em>, <em class="sig-param"><span class="o">**</span><span class="n">kwargs</span></em><span class="sig-paren">)</span><a class="headerlink" href="#pyscf.pbc.gto.cell.get_uniform_grids" title="Permalink to this definition">¶</a></dt> <dd><p>Generate a uniform real-space grid consistent w/ samp thm; see MH (3.19).</p> <dl class="simple"> <dt>Args:</dt><dd><p>cell : instance of <a class="reference internal" href="#pyscf.pbc.gto.cell.Cell" title="pyscf.pbc.gto.cell.Cell"><code class="xref py py-class docutils literal notranslate"><span class="pre">Cell</span></code></a></p> </dd> <dt>Returns:</dt><dd><dl class="simple"> <dt>coords<span class="classifier">(ngx*ngy*ngz, 3) ndarray</span></dt><dd><p>The real-space grid point coordinates.</p> </dd> </dl> </dd> </dl> </dd></dl> <dl class="py function"> <dt id="pyscf.pbc.gto.cell.intor_cross"> <code class="sig-prename descclassname">pyscf.pbc.gto.cell.</code><code class="sig-name descname">intor_cross</code><span class="sig-paren">(</span><em class="sig-param"><span class="n">intor</span></em>, <em class="sig-param"><span class="n">cell1</span></em>, <em class="sig-param"><span class="n">cell2</span></em>, <em class="sig-param"><span class="n">comp</span><span class="o">=</span><span class="default_value">None</span></em>, <em class="sig-param"><span class="n">hermi</span><span class="o">=</span><span class="default_value">0</span></em>, <em class="sig-param"><span class="n">kpts</span><span class="o">=</span><span class="default_value">None</span></em>, <em class="sig-param"><span class="n">kpt</span><span class="o">=</span><span class="default_value">None</span></em>, <em class="sig-param"><span class="n">shls_slice</span><span class="o">=</span><span class="default_value">None</span></em>, <em class="sig-param"><span class="o">**</span><span class="n">kwargs</span></em><span class="sig-paren">)</span><a class="headerlink" href="#pyscf.pbc.gto.cell.intor_cross" title="Permalink to this definition">¶</a></dt> <dd><p>1-electron integrals from two cells like</p> <div class="math notranslate nohighlight"> \[\langle \mu | intor | \nu \rangle, \mu \in cell1, \nu \in cell2\]</div> </dd></dl> <dl class="py function"> <dt id="pyscf.pbc.gto.cell.loads"> <code class="sig-prename descclassname">pyscf.pbc.gto.cell.</code><code class="sig-name descname">loads</code><span class="sig-paren">(</span><em class="sig-param"><span class="n">cellstr</span></em><span class="sig-paren">)</span><a class="headerlink" href="#pyscf.pbc.gto.cell.loads" title="Permalink to this definition">¶</a></dt> <dd><p>Deserialize a str containing a JSON document to a Cell object.</p> </dd></dl> <dl class="py function"> <dt id="pyscf.pbc.gto.cell.make_kpts"> <code class="sig-prename descclassname">pyscf.pbc.gto.cell.</code><code class="sig-name descname">make_kpts</code><span class="sig-paren">(</span><em class="sig-param"><span class="n">cell</span></em>, <em class="sig-param"><span class="n">nks</span></em>, <em class="sig-param"><span class="n">wrap_around</span><span class="o">=</span><span class="default_value">False</span></em>, <em class="sig-param"><span class="n">with_gamma_point</span><span class="o">=</span><span class="default_value">True</span></em>, <em class="sig-param"><span class="n">scaled_center</span><span class="o">=</span><span class="default_value">None</span></em><span class="sig-paren">)</span><a class="headerlink" href="#pyscf.pbc.gto.cell.make_kpts" title="Permalink to this definition">¶</a></dt> <dd><p>Given number of kpoints along x,y,z , generate kpoints</p> <dl class="simple"> <dt>Args:</dt><dd><p>nks : (3,) ndarray</p> </dd> <dt>Kwargs:</dt><dd><dl class="simple"> <dt>wrap_around<span class="classifier">bool</span></dt><dd><p>To ensure all kpts are in first Brillouin zone.</p> </dd> <dt>with_gamma_point<span class="classifier">bool</span></dt><dd><p>Whether to shift Monkhorst-pack grid to include gamma-point.</p> </dd> <dt>scaled_center<span class="classifier">(3,) array</span></dt><dd><p>Shift all points in the Monkhorst-pack grid to be centered on scaled_center, given as the zeroth index of the returned kpts. Scaled meaning that the k-points are scaled to a grid from [-1,1] x [-1,1] x [-1,1]</p> </dd> </dl> </dd> <dt>Returns:</dt><dd><p>kpts in absolute value (unit 1/Bohr). Gamma point is placed at the first place in the k-points list</p> </dd> </dl> <p>Examples:</p> <div class="doctest highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">cell</span><span class="o">.</span><span class="n">make_kpts</span><span class="p">((</span><span class="mi">4</span><span class="p">,</span><span class="mi">4</span><span class="p">,</span><span class="mi">4</span><span class="p">))</span> </pre></div> </div> </dd></dl> <dl class="py function"> <dt id="pyscf.pbc.gto.cell.make_pseudo_env"> <code class="sig-prename descclassname">pyscf.pbc.gto.cell.</code><code class="sig-name descname">make_pseudo_env</code><span class="sig-paren">(</span><em class="sig-param"><span class="n">cell</span></em>, <em class="sig-param"><span class="n">_atm</span></em>, <em class="sig-param"><span class="n">_pseudo</span></em>, <em class="sig-param"><span class="n">pre_env</span><span class="o">=</span><span class="default_value">[]</span></em><span class="sig-paren">)</span><a class="headerlink" href="#pyscf.pbc.gto.cell.make_pseudo_env" title="Permalink to this definition">¶</a></dt> <dd></dd></dl> <dl class="py function"> <dt id="pyscf.pbc.gto.cell.pack"> <code class="sig-prename descclassname">pyscf.pbc.gto.cell.</code><code class="sig-name descname">pack</code><span class="sig-paren">(</span><em class="sig-param"><span class="n">cell</span></em><span class="sig-paren">)</span><a class="headerlink" href="#pyscf.pbc.gto.cell.pack" title="Permalink to this definition">¶</a></dt> <dd><p>Pack the input args of <a class="reference internal" href="#pyscf.pbc.gto.cell.Cell" title="pyscf.pbc.gto.cell.Cell"><code class="xref py py-class docutils literal notranslate"><span class="pre">Cell</span></code></a> to a dict, which can be serialized with <code class="xref py py-mod docutils literal notranslate"><span class="pre">pickle</span></code></p> </dd></dl> <dl class="py function"> <dt id="pyscf.pbc.gto.cell.tot_electrons"> <code class="sig-prename descclassname">pyscf.pbc.gto.cell.</code><code class="sig-name descname">tot_electrons</code><span class="sig-paren">(</span><em class="sig-param"><span class="n">cell</span></em>, <em class="sig-param"><span class="n">nkpts</span><span class="o">=</span><span class="default_value">1</span></em><span class="sig-paren">)</span><a class="headerlink" href="#pyscf.pbc.gto.cell.tot_electrons" title="Permalink to this definition">¶</a></dt> <dd><p>Total number of electrons</p> </dd></dl> <dl class="py function"> <dt id="pyscf.pbc.gto.cell.unpack"> <code class="sig-prename descclassname">pyscf.pbc.gto.cell.</code><code class="sig-name descname">unpack</code><span class="sig-paren">(</span><em class="sig-param"><span class="n">celldic</span></em><span class="sig-paren">)</span><a class="headerlink" href="#pyscf.pbc.gto.cell.unpack" title="Permalink to this definition">¶</a></dt> <dd><p>Convert the packed dict to a <a class="reference internal" href="#pyscf.pbc.gto.cell.Cell" title="pyscf.pbc.gto.cell.Cell"><code class="xref py py-class docutils literal notranslate"><span class="pre">Cell</span></code></a> object, to generate the input arguments for <a class="reference internal" href="#pyscf.pbc.gto.cell.Cell" title="pyscf.pbc.gto.cell.Cell"><code class="xref py py-class docutils literal notranslate"><span class="pre">Cell</span></code></a> object.</p> </dd></dl> </div> <div class="section" id="module-pyscf.pbc.gto.ecp"> <span id="pyscf-pbc-gto-ecp-module"></span><h2>pyscf.pbc.gto.ecp module<a class="headerlink" href="#module-pyscf.pbc.gto.ecp" title="Permalink to this headline">¶</a></h2> <p>Short range part of ECP under PBC</p> <dl class="py function"> <dt id="pyscf.pbc.gto.ecp.ecp_int"> <code class="sig-prename descclassname">pyscf.pbc.gto.ecp.</code><code class="sig-name descname">ecp_int</code><span class="sig-paren">(</span><em class="sig-param"><span class="n">cell</span></em>, <em class="sig-param"><span class="n">kpts</span><span class="o">=</span><span class="default_value">None</span></em><span class="sig-paren">)</span><a class="headerlink" href="#pyscf.pbc.gto.ecp.ecp_int" title="Permalink to this definition">¶</a></dt> <dd></dd></dl> </div> <div class="section" id="module-pyscf.pbc.gto.eval_gto"> <span id="pyscf-pbc-gto-eval-gto-module"></span><h2>pyscf.pbc.gto.eval_gto module<a class="headerlink" href="#module-pyscf.pbc.gto.eval_gto" title="Permalink to this headline">¶</a></h2> <dl class="py function"> <dt id="pyscf.pbc.gto.eval_gto.eval_gto"> <code class="sig-prename descclassname">pyscf.pbc.gto.eval_gto.</code><code class="sig-name descname">eval_gto</code><span class="sig-paren">(</span><em class="sig-param"><span class="n">cell</span></em>, <em class="sig-param"><span class="n">eval_name</span></em>, <em class="sig-param"><span class="n">coords</span></em>, <em class="sig-param"><span class="n">comp</span><span class="o">=</span><span class="default_value">None</span></em>, <em class="sig-param"><span class="n">kpts</span><span class="o">=</span><span class="default_value">None</span></em>, <em class="sig-param"><span class="n">kpt</span><span class="o">=</span><span class="default_value">None</span></em>, <em class="sig-param"><span class="n">shls_slice</span><span class="o">=</span><span class="default_value">None</span></em>, <em class="sig-param"><span class="n">non0tab</span><span class="o">=</span><span class="default_value">None</span></em>, <em class="sig-param"><span class="n">ao_loc</span><span class="o">=</span><span class="default_value">None</span></em>, <em class="sig-param"><span class="n">out</span><span class="o">=</span><span class="default_value">None</span></em><span class="sig-paren">)</span><a class="headerlink" href="#pyscf.pbc.gto.eval_gto.eval_gto" title="Permalink to this definition">¶</a></dt> <dd><p>Evaluate PBC-AO function value on the given grids,</p> <dl> <dt>Args:</dt><dd><p>eval_name : str</p> <blockquote> <div><table class="docutils align-default"> <colgroup> <col style="width: 49%" /> <col style="width: 51%" /> </colgroup> <thead> <tr class="row-odd"><th class="head"><p>Function</p></th> <th class="head"><p>Expression</p></th> </tr> </thead> <tbody> <tr class="row-even"><td><p>“GTOval_sph”</p></td> <td><p>sum_T exp(ik*T) <a href="#id33"><span class="problematic" id="id34">|</span></a>AO&gt;</p></td> </tr> <tr class="row-odd"><td><p>“GTOval_ip_sph”</p></td> <td><p>nabla sum_T exp(ik*T) <a href="#id35"><span class="problematic" id="id36">|</span></a>AO&gt;</p></td> </tr> <tr class="row-even"><td><p>“GTOval_cart”</p></td> <td><p>sum_T exp(ik*T) <a href="#id37"><span class="problematic" id="id38">|</span></a>AO&gt;</p></td> </tr> <tr class="row-odd"><td><p>“GTOval_ip_cart”</p></td> <td><p>nabla sum_T exp(ik*T) <a href="#id39"><span class="problematic" id="id40">|</span></a>AO&gt;</p></td> </tr> </tbody> </table> </div></blockquote> <dl class="simple"> <dt>atm<span class="classifier">int32 ndarray</span></dt><dd><p>libcint integral function argument</p> </dd> <dt>bas<span class="classifier">int32 ndarray</span></dt><dd><p>libcint integral function argument</p> </dd> <dt>env<span class="classifier">float64 ndarray</span></dt><dd><p>libcint integral function argument</p> </dd> <dt>coords<span class="classifier">2D array, shape (N,3)</span></dt><dd><p>The coordinates of the grids.</p> </dd> </dl> </dd> <dt>Kwargs:</dt><dd><dl class="simple"> <dt>shls_slice<span class="classifier">2-element list</span></dt><dd><p>(shl_start, shl_end). If given, only part of AOs (shl_start &lt;= shell_id &lt; shl_end) are evaluated. By default, all shells defined in cell will be evaluated.</p> </dd> <dt>non0tab<span class="classifier">2D bool array</span></dt><dd><p>mask array to indicate whether the AO values are zero. The mask array can be obtained by calling <code class="xref py py-func docutils literal notranslate"><span class="pre">dft.gen_grid.make_mask()</span></code></p> </dd> <dt>out<span class="classifier">ndarray</span></dt><dd><p>If provided, results are written into this array.</p> </dd> </dl> </dd> <dt>Returns:</dt><dd><p>A list of 2D (or 3D) arrays to hold the AO values on grids. Each element of the list corresponds to a k-point and it has the shape (N,nao) Or shape (*,N,nao).</p> </dd> </dl> <p>Examples:</p> <div class="doctest highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">cell</span> <span class="o">=</span> <span class="n">pbc</span><span class="o">.</span><span class="n">gto</span><span class="o">.</span><span class="n">M</span><span class="p">(</span><span class="n">a</span><span class="o">=</span><span class="n">numpy</span><span class="o">.</span><span class="n">eye</span><span class="p">(</span><span class="mi">3</span><span class="p">)</span><span class="o">*</span><span class="mi">4</span><span class="p">,</span> <span class="n">atom</span><span class="o">=</span><span class="s1">&#39;He 1 1 1&#39;</span><span class="p">,</span> <span class="n">basis</span><span class="o">=</span><span class="s1">&#39;6-31g&#39;</span><span class="p">)</span> <span class="gp">&gt;&gt;&gt; </span><span class="n">coords</span> <span class="o">=</span> <span class="n">cell</span><span class="o">.</span><span class="n">get_uniform_grids</span><span class="p">([</span><span class="mi">20</span><span class="p">,</span><span class="mi">20</span><span class="p">,</span><span class="mi">20</span><span class="p">])</span> <span class="gp">&gt;&gt;&gt; </span><span class="n">kpts</span> <span class="o">=</span> <span class="n">cell</span><span class="o">.</span><span class="n">make_kpts</span><span class="p">([</span><span class="mi">3</span><span class="p">,</span><span class="mi">3</span><span class="p">,</span><span class="mi">3</span><span class="p">])</span> <span class="gp">&gt;&gt;&gt; </span><span class="n">ao_value</span> <span class="o">=</span> <span class="n">cell</span><span class="o">.</span><span class="n">pbc_eval_gto</span><span class="p">(</span><span class="s2">&quot;GTOval_sph&quot;</span><span class="p">,</span> <span class="n">coords</span><span class="p">,</span> <span class="n">kpts</span><span class="p">)</span> <span class="gp">&gt;&gt;&gt; </span><span class="nb">len</span><span class="p">(</span><span class="n">ao_value</span><span class="p">)</span> <span class="go">27</span> <span class="gp">&gt;&gt;&gt; </span><span class="n">ao_value</span><span class="p">[</span><span class="mi">0</span><span class="p">]</span><span class="o">.</span><span class="n">shape</span> <span class="go">(100, 2)</span> <span class="gp">&gt;&gt;&gt; </span><span class="n">ao_value</span> <span class="o">=</span> <span class="n">cell</span><span class="o">.</span><span class="n">pbc_eval_gto</span><span class="p">(</span><span class="s2">&quot;GTOval_ig_sph&quot;</span><span class="p">,</span> <span class="n">coords</span><span class="p">,</span> <span class="n">kpts</span><span class="p">,</span> <span class="n">comp</span><span class="o">=</span><span class="mi">3</span><span class="p">)</span> <span class="gp">&gt;&gt;&gt; </span><span class="nb">print</span><span class="p">(</span><span class="n">ao_value</span><span class="o">.</span><span class="n">shape</span><span class="p">)</span> <span class="gp">&gt;&gt;&gt; </span><span class="nb">len</span><span class="p">(</span><span class="n">ao_value</span><span class="p">)</span> <span class="go">27</span> <span class="gp">&gt;&gt;&gt; </span><span class="n">ao_value</span><span class="p">[</span><span class="mi">0</span><span class="p">]</span><span class="o">.</span><span class="n">shape</span> <span class="go">(3, 100, 2)</span> </pre></div> </div> </dd></dl> <dl class="py function"> <dt id="pyscf.pbc.gto.eval_gto.pbc_eval_gto"> <code class="sig-prename descclassname">pyscf.pbc.gto.eval_gto.</code><code class="sig-name descname">pbc_eval_gto</code><span class="sig-paren">(</span><em class="sig-param"><span class="n">cell</span></em>, <em class="sig-param"><span class="n">eval_name</span></em>, <em class="sig-param"><span class="n">coords</span></em>, <em class="sig-param"><span class="n">comp</span><span class="o">=</span><span class="default_value">None</span></em>, <em class="sig-param"><span class="n">kpts</span><span class="o">=</span><span class="default_value">None</span></em>, <em class="sig-param"><span class="n">kpt</span><span class="o">=</span><span class="default_value">None</span></em>, <em class="sig-param"><span class="n">shls_slice</span><span class="o">=</span><span class="default_value">None</span></em>, <em class="sig-param"><span class="n">non0tab</span><span class="o">=</span><span class="default_value">None</span></em>, <em class="sig-param"><span class="n">ao_loc</span><span class="o">=</span><span class="default_value">None</span></em>, <em class="sig-param"><span class="n">out</span><span class="o">=</span><span class="default_value">None</span></em><span class="sig-paren">)</span><a class="headerlink" href="#pyscf.pbc.gto.eval_gto.pbc_eval_gto" title="Permalink to this definition">¶</a></dt> <dd><p>Evaluate PBC-AO function value on the given grids,</p> <dl> <dt>Args:</dt><dd><p>eval_name : str</p> <blockquote> <div><table class="docutils align-default"> <colgroup> <col style="width: 49%" /> <col style="width: 51%" /> </colgroup> <thead> <tr class="row-odd"><th class="head"><p>Function</p></th> <th class="head"><p>Expression</p></th> </tr> </thead> <tbody> <tr class="row-even"><td><p>“GTOval_sph”</p></td> <td><p>sum_T exp(ik*T) <a href="#id41"><span class="problematic" id="id42">|</span></a>AO&gt;</p></td> </tr> <tr class="row-odd"><td><p>“GTOval_ip_sph”</p></td> <td><p>nabla sum_T exp(ik*T) <a href="#id43"><span class="problematic" id="id44">|</span></a>AO&gt;</p></td> </tr> <tr class="row-even"><td><p>“GTOval_cart”</p></td> <td><p>sum_T exp(ik*T) <a href="#id45"><span class="problematic" id="id46">|</span></a>AO&gt;</p></td> </tr> <tr class="row-odd"><td><p>“GTOval_ip_cart”</p></td> <td><p>nabla sum_T exp(ik*T) <a href="#id47"><span class="problematic" id="id48">|</span></a>AO&gt;</p></td> </tr> </tbody> </table> </div></blockquote> <dl class="simple"> <dt>atm<span class="classifier">int32 ndarray</span></dt><dd><p>libcint integral function argument</p> </dd> <dt>bas<span class="classifier">int32 ndarray</span></dt><dd><p>libcint integral function argument</p> </dd> <dt>env<span class="classifier">float64 ndarray</span></dt><dd><p>libcint integral function argument</p> </dd> <dt>coords<span class="classifier">2D array, shape (N,3)</span></dt><dd><p>The coordinates of the grids.</p> </dd> </dl> </dd> <dt>Kwargs:</dt><dd><dl class="simple"> <dt>shls_slice<span class="classifier">2-element list</span></dt><dd><p>(shl_start, shl_end). If given, only part of AOs (shl_start &lt;= shell_id &lt; shl_end) are evaluated. By default, all shells defined in cell will be evaluated.</p> </dd> <dt>non0tab<span class="classifier">2D bool array</span></dt><dd><p>mask array to indicate whether the AO values are zero. The mask array can be obtained by calling <code class="xref py py-func docutils literal notranslate"><span class="pre">dft.gen_grid.make_mask()</span></code></p> </dd> <dt>out<span class="classifier">ndarray</span></dt><dd><p>If provided, results are written into this array.</p> </dd> </dl> </dd> <dt>Returns:</dt><dd><p>A list of 2D (or 3D) arrays to hold the AO values on grids. Each element of the list corresponds to a k-point and it has the shape (N,nao) Or shape (*,N,nao).</p> </dd> </dl> <p>Examples:</p> <div class="doctest highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">cell</span> <span class="o">=</span> <span class="n">pbc</span><span class="o">.</span><span class="n">gto</span><span class="o">.</span><span class="n">M</span><span class="p">(</span><span class="n">a</span><span class="o">=</span><span class="n">numpy</span><span class="o">.</span><span class="n">eye</span><span class="p">(</span><span class="mi">3</span><span class="p">)</span><span class="o">*</span><span class="mi">4</span><span class="p">,</span> <span class="n">atom</span><span class="o">=</span><span class="s1">&#39;He 1 1 1&#39;</span><span class="p">,</span> <span class="n">basis</span><span class="o">=</span><span class="s1">&#39;6-31g&#39;</span><span class="p">)</span> <span class="gp">&gt;&gt;&gt; </span><span class="n">coords</span> <span class="o">=</span> <span class="n">cell</span><span class="o">.</span><span class="n">get_uniform_grids</span><span class="p">([</span><span class="mi">20</span><span class="p">,</span><span class="mi">20</span><span class="p">,</span><span class="mi">20</span><span class="p">])</span> <span class="gp">&gt;&gt;&gt; </span><span class="n">kpts</span> <span class="o">=</span> <span class="n">cell</span><span class="o">.</span><span class="n">make_kpts</span><span class="p">([</span><span class="mi">3</span><span class="p">,</span><span class="mi">3</span><span class="p">,</span><span class="mi">3</span><span class="p">])</span> <span class="gp">&gt;&gt;&gt; </span><span class="n">ao_value</span> <span class="o">=</span> <span class="n">cell</span><span class="o">.</span><span class="n">pbc_eval_gto</span><span class="p">(</span><span class="s2">&quot;GTOval_sph&quot;</span><span class="p">,</span> <span class="n">coords</span><span class="p">,</span> <span class="n">kpts</span><span class="p">)</span> <span class="gp">&gt;&gt;&gt; </span><span class="nb">len</span><span class="p">(</span><span class="n">ao_value</span><span class="p">)</span> <span class="go">27</span> <span class="gp">&gt;&gt;&gt; </span><span class="n">ao_value</span><span class="p">[</span><span class="mi">0</span><span class="p">]</span><span class="o">.</span><span class="n">shape</span> <span class="go">(100, 2)</span> <span class="gp">&gt;&gt;&gt; </span><span class="n">ao_value</span> <span class="o">=</span> <span class="n">cell</span><span class="o">.</span><span class="n">pbc_eval_gto</span><span class="p">(</span><span class="s2">&quot;GTOval_ig_sph&quot;</span><span class="p">,</span> <span class="n">coords</span><span class="p">,</span> <span class="n">kpts</span><span class="p">,</span> <span class="n">comp</span><span class="o">=</span><span class="mi">3</span><span class="p">)</span> <span class="gp">&gt;&gt;&gt; </span><span class="nb">print</span><span class="p">(</span><span class="n">ao_value</span><span class="o">.</span><span class="n">shape</span><span class="p">)</span> <span class="gp">&gt;&gt;&gt; </span><span class="nb">len</span><span class="p">(</span><span class="n">ao_value</span><span class="p">)</span> <span class="go">27</span> <span class="gp">&gt;&gt;&gt; </span><span class="n">ao_value</span><span class="p">[</span><span class="mi">0</span><span class="p">]</span><span class="o">.</span><span class="n">shape</span> <span class="go">(3, 100, 2)</span> </pre></div> </div> </dd></dl> </div> <div class="section" id="module-pyscf.pbc.gto"> <span id="module-contents"></span><h2>Module contents<a class="headerlink" href="#module-pyscf.pbc.gto" title="Permalink to this headline">¶</a></h2> </div> </div> <div class="section"> </div> </article> </div> </div> </main> </div> <footer class="md-footer"> <div class="md-footer-nav"> <nav class="md-footer-nav__inner md-grid"> <a href="../pyscf.pbc.grad/" title="pyscf.pbc.grad package" class="md-flex md-footer-nav__link md-footer-nav__link--prev" rel="prev"> <div class="md-flex__cell md-flex__cell--shrink"> <i class="md-icon md-icon--arrow-back md-footer-nav__button"></i> </div> <div class="md-flex__cell md-flex__cell--stretch md-footer-nav__title"> <span class="md-flex__ellipsis"> <span class="md-footer-nav__direction"> Previous </span> pyscf.pbc.grad package </span> </div> </a> <a href="../pyscf.pbc.gto.basis/" title="pyscf.pbc.gto.basis package" class="md-flex md-footer-nav__link md-footer-nav__link--next" rel="next"> <div class="md-flex__cell md-flex__cell--stretch md-footer-nav__title"><span class="md-flex__ellipsis"> <span class="md-footer-nav__direction"> Next </span> pyscf.pbc.gto.basis package </span> </div> <div class="md-flex__cell md-flex__cell--shrink"><i class="md-icon md-icon--arrow-forward md-footer-nav__button"></i> </div> </a> </nav> </div> <div class="md-footer-meta md-typeset"> <div class="md-footer-meta__inner md-grid"> <div class="md-footer-copyright"> <div class="md-footer-copyright__highlight"> &#169; Copyright 2021, <NAME>. </div> Created using <a href="http://www.sphinx-doc.org/">Sphinx</a> 3.4.3. and <a href="https://github.com/bashtage/sphinx-material/">Material for Sphinx</a> </div> </div> </div> </footer> <script src="../../_static/javascripts/application.js"></script> <script>app.initialize({version: "1.0.4", url: {base: ".."}})</script> </body> </html><file_sep>/docs/pyscf_api_docs/pyscf.mcscf/index.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <meta name="viewport" content="width=device-width,initial-scale=1"> <meta http-equiv="x-ua-compatible" content="ie=edge"> <meta name="lang:clipboard.copy" content="Copy to clipboard"> <meta name="lang:clipboard.copied" content="Copied to clipboard"> <meta name="lang:search.language" content="en"> <meta name="lang:search.pipeline.stopwords" content="True"> <meta name="lang:search.pipeline.trimmer" content="True"> <meta name="lang:search.result.none" content="No matching documents"> <meta name="lang:search.result.one" content="1 matching document"> <meta name="lang:search.result.other" content="# matching documents"> <meta name="lang:search.tokenizer" content="[\s\-]+"> <link href="https://fonts.gstatic.com/" rel="preconnect" crossorigin> <link href="https://fonts.googleapis.com/css?family=Roboto+Mono:400,500,700|Roboto:300,400,400i,700&display=fallback" rel="stylesheet"> <style> body, input { font-family: "Roboto", "Helvetica Neue", Helvetica, Arial, sans-serif } code, kbd, pre { font-family: "Roboto Mono", "Courier New", Courier, monospace } </style> <link rel="stylesheet" href="../../_static/stylesheets/application.css"/> <link rel="stylesheet" href="../../_static/stylesheets/application-palette.css"/> <link rel="stylesheet" href="../../_static/stylesheets/application-fixes.css"/> <link rel="stylesheet" href="../../_static/fonts/material-icons.css"/> <meta name="theme-color" content="#3f51b5"> <script src="../../_static/javascripts/modernizr.js"></script> <title>pyscf.mcscf package &#8212; PySCF documentation</title> <link rel="stylesheet" href="../../_static/pygments.css" type="text/css" /> <link rel="stylesheet" href="../../_static/material.css" type="text/css" /> <script id="documentation_options" data-url_root="../../" src="../../_static/documentation_options.js"></script> <script src="../../_static/jquery.js"></script> <script src="../../_static/underscore.js"></script> <script src="../../_static/doctools.js"></script> <script async="async" src="https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.7/latest.js?config=TeX-AMS-MML_HTMLorMML"></script> <link rel="author" title="About these documents" href="../../about/" /> <link rel="index" title="Index" href="../../genindex/" /> <link rel="search" title="Search" href="../../search/" /> <link rel="next" title="pyscf.mp package" href="../pyscf.mp/" /> <link rel="prev" title="pyscf.lo package" href="../pyscf.lo/" /> <style type="text/css"> ul.ablog-archive { list-style: none; overflow: auto; margin-left: 0px; } ul.ablog-archive li { float: left; margin-right: 5px; font-size: 80%; } ul.postlist a { font-style: italic; } ul.postlist-style-disc { list-style-type: disc; } ul.postlist-style-none { list-style-type: none; } ul.postlist-style-circle { list-style-type: circle; } </style> </head> <body dir=ltr data-md-color-primary=indigo data-md-color-accent=yellow> <svg class="md-svg"> <defs data-children-count="0"> <svg xmlns="http://www.w3.org/2000/svg" width="416" height="448" viewBox="0 0 416 448" id="__github"><path fill="currentColor" d="M160 304q0 10-3.125 20.5t-10.75 19T128 352t-18.125-8.5-10.75-19T96 304t3.125-20.5 10.75-19T128 256t18.125 8.5 10.75 19T160 304zm160 0q0 10-3.125 20.5t-10.75 19T288 352t-18.125-8.5-10.75-19T256 304t3.125-20.5 10.75-19T288 256t18.125 8.5 10.75 19T320 304zm40 0q0-30-17.25-51T296 232q-10.25 0-48.75 5.25Q229.5 240 208 240t-39.25-2.75Q130.75 232 120 232q-29.5 0-46.75 21T56 304q0 22 8 38.375t20.25 25.75 30.5 15 35 7.375 37.25 1.75h42q20.5 0 37.25-1.75t35-7.375 30.5-15 20.25-25.75T360 304zm56-44q0 51.75-15.25 82.75-9.5 19.25-26.375 33.25t-35.25 21.5-42.5 11.875-42.875 5.5T212 416q-19.5 0-35.5-.75t-36.875-3.125-38.125-7.5-34.25-12.875T37 371.5t-21.5-28.75Q0 312 0 260q0-59.25 34-99-6.75-20.5-6.75-42.5 0-29 12.75-54.5 27 0 47.5 9.875t47.25 30.875Q171.5 96 212 96q37 0 70 8 26.25-20.5 46.75-30.25T376 64q12.75 25.5 12.75 54.5 0 21.75-6.75 42 34 40 34 99.5z"/></svg> </defs> </svg> <input class="md-toggle" data-md-toggle="drawer" type="checkbox" id="__drawer"> <input class="md-toggle" data-md-toggle="search" type="checkbox" id="__search"> <label class="md-overlay" data-md-component="overlay" for="__drawer"></label> <a href="#pyscf_api_docs/pyscf.mcscf" tabindex="1" class="md-skip"> Skip to content </a> <header class="md-header" data-md-component="header"> <nav class="md-header-nav md-grid"> <div class="md-flex navheader"> <div class="md-flex__cell md-flex__cell--shrink"> <a href="../../" title="PySCF documentation" class="md-header-nav__button md-logo"> &nbsp; </a> </div> <div class="md-flex__cell md-flex__cell--shrink"> <label class="md-icon md-icon--menu md-header-nav__button" for="__drawer"></label> </div> <div class="md-flex__cell md-flex__cell--stretch"> <div class="md-flex__ellipsis md-header-nav__title" data-md-component="title"> <span class="md-header-nav__topic">PySCF Docs</span> <span class="md-header-nav__topic"> pyscf.mcscf package </span> </div> </div> <div class="md-flex__cell md-flex__cell--shrink"> <label class="md-icon md-icon--search md-header-nav__button" for="__search"></label> <div class="md-search" data-md-component="search" role="dialog"> <label class="md-search__overlay" for="__search"></label> <div class="md-search__inner" role="search"> <form class="md-search__form" action="../../search/" method="GET" name="search"> <input type="text" class="md-search__input" name="q" placeholder="Search" autocapitalize="off" autocomplete="off" spellcheck="false" data-md-component="query" data-md-state="active"> <label class="md-icon md-search__icon" for="__search"></label> <button type="reset" class="md-icon md-search__icon" data-md-component="reset" tabindex="-1"> &#xE5CD; </button> </form> <div class="md-search__output"> <div class="md-search__scrollwrap" data-md-scrollfix> <div class="md-search-result" data-md-component="result"> <div class="md-search-result__meta"> Type to start searching </div> <ol class="md-search-result__list"></ol> </div> </div> </div> </div> </div> </div> <script src="../../_static/javascripts/version_dropdown.js"></script> <script> var json_loc = "../../"versions.json"", target_loc = "../../../", text = "Versions"; $( document ).ready( add_version_dropdown(json_loc, target_loc, text)); </script> </div> </nav> </header> <div class="md-container"> <nav class="md-tabs" data-md-component="tabs"> <div class="md-tabs__inner md-grid"> <ul class="md-tabs__list"> <li class="md-tabs__item"><a href="../../" class="md-tabs__link">PySCF documentation</a></li> <li class="md-tabs__item"><a href="../../about/" class="md-tabs__link">About</a></li> <li class="md-tabs__item"><a href="../../blog_wrapper/" class="md-tabs__link">Blog</a></li> <li class="md-tabs__item"><a href="../modules/" class="md-tabs__link">API Docs</a></li> <li class="md-tabs__item"><a href="../pyscf/" class="md-tabs__link">pyscf package</a></li> </ul> </div> </nav> <main class="md-main"> <div class="md-main__inner md-grid" data-md-component="container"> <div class="md-sidebar md-sidebar--primary" data-md-component="navigation"> <div class="md-sidebar__scrollwrap"> <div class="md-sidebar__inner"> <nav class="md-nav md-nav--primary" data-md-level="0"> <label class="md-nav__title md-nav__title--site" for="__drawer"> <a href="../../" title="PySCF documentation" class="md-nav__button md-logo"> <img src="../../_static/" alt=" logo" width="48" height="48"> </a> <a href="../../" title="PySCF documentation">PySCF Docs</a> </label> <ul class="md-nav__list"> <li class="md-nav__item"> <a href="../../about/" class="md-nav__link">About</a> </li> <li class="md-nav__item"> <a href="../../blog_wrapper/" class="md-nav__link">Blog</a> </li> <li class="md-nav__item"> <a href="../pyscf/" class="md-nav__link">API Docs</a> <ul class="md-nav__list"> <li class="md-nav__item"> <a href="../pyscf/#subpackages" class="md-nav__link">Subpackages</a> </li> <li class="md-nav__item"> <a href="../pyscf/#submodules" class="md-nav__link">Submodules</a> </li> <li class="md-nav__item"> <a href="../pyscf/#module-pyscf.post_scf" class="md-nav__link">pyscf.post_scf module</a> </li> <li class="md-nav__item"> <a href="../pyscf/#module-pyscf" class="md-nav__link">Module contents</a> </li></ul> </li> </ul> </nav> </div> </div> </div> <div class="md-sidebar md-sidebar--secondary" data-md-component="toc"> <div class="md-sidebar__scrollwrap"> <div class="md-sidebar__inner"> <nav class="md-nav md-nav--secondary"> <label class="md-nav__title" for="__toc">Contents</label> <ul class="md-nav__list" data-md-scrollfix=""> <li class="md-nav__item"><a href="#pyscf-api-docs-pyscf-mcscf--page-root" class="md-nav__link">pyscf.mcscf package</a><nav class="md-nav"> <ul class="md-nav__list"> <li class="md-nav__item"><a href="#submodules" class="md-nav__link">Submodules</a> </li> <li class="md-nav__item"><a href="#module-pyscf.mcscf.PiOS" class="md-nav__link">pyscf.mcscf.PiOS module</a> </li> <li class="md-nav__item"><a href="#module-pyscf.mcscf.addons" class="md-nav__link">pyscf.mcscf.addons module</a> </li> <li class="md-nav__item"><a href="#module-pyscf.mcscf.avas" class="md-nav__link">pyscf.mcscf.avas module</a> </li> <li class="md-nav__item"><a href="#module-pyscf.mcscf.casci" class="md-nav__link">pyscf.mcscf.casci module</a> </li> <li class="md-nav__item"><a href="#module-pyscf.mcscf.casci_symm" class="md-nav__link">pyscf.mcscf.casci_symm module</a> </li> <li class="md-nav__item"><a href="#module-pyscf.mcscf.chkfile" class="md-nav__link">pyscf.mcscf.chkfile module</a> </li> <li class="md-nav__item"><a href="#module-pyscf.mcscf.df" class="md-nav__link">pyscf.mcscf.df module</a> </li> <li class="md-nav__item"><a href="#module-pyscf.mcscf.dmet_cas" class="md-nav__link">pyscf.mcscf.dmet_cas module</a> </li> <li class="md-nav__item"><a href="#module-pyscf.mcscf.mc1step" class="md-nav__link">pyscf.mcscf.mc1step module</a> </li> <li class="md-nav__item"><a href="#module-pyscf.mcscf.mc1step_symm" class="md-nav__link">pyscf.mcscf.mc1step_symm module</a> </li> <li class="md-nav__item"><a href="#module-pyscf.mcscf.mc2step" class="md-nav__link">pyscf.mcscf.mc2step module</a> </li> <li class="md-nav__item"><a href="#module-pyscf.mcscf.mc_ao2mo" class="md-nav__link">pyscf.mcscf.mc_ao2mo module</a> </li> <li class="md-nav__item"><a href="#module-pyscf.mcscf.newton_casscf" class="md-nav__link">pyscf.mcscf.newton_casscf module</a> </li> <li class="md-nav__item"><a href="#module-pyscf.mcscf.newton_casscf_symm" class="md-nav__link">pyscf.mcscf.newton_casscf_symm module</a> </li> <li class="md-nav__item"><a href="#module-pyscf.mcscf.ucasci" class="md-nav__link">pyscf.mcscf.ucasci module</a> </li> <li class="md-nav__item"><a href="#module-pyscf.mcscf.umc1step" class="md-nav__link">pyscf.mcscf.umc1step module</a> </li> <li class="md-nav__item"><a href="#module-pyscf.mcscf.umc2step" class="md-nav__link">pyscf.mcscf.umc2step module</a> </li> <li class="md-nav__item"><a href="#module-pyscf.mcscf.umc_ao2mo" class="md-nav__link">pyscf.mcscf.umc_ao2mo module</a> </li> <li class="md-nav__item"><a href="#module-pyscf.mcscf" class="md-nav__link">Module contents</a> </li></ul> </nav> </li> <li class="md-nav__item"><a class="md-nav__extra_link" href="../../_sources/pyscf_api_docs/pyscf.mcscf.rst.txt">Show Source</a> </li> <li id="searchbox" class="md-nav__item"></li> </ul> </nav> </div> </div> </div> <div class="md-content"> <article class="md-content__inner md-typeset" role="main"> <div class="section" id="pyscf-mcscf-package"> <h1>pyscf.mcscf package<a class="headerlink" href="#pyscf-mcscf-package" title="Permalink to this headline">¶</a></h1> <div class="section" id="submodules"> <h2>Submodules<a class="headerlink" href="#submodules" title="Permalink to this headline">¶</a></h2> </div> <div class="section" id="module-pyscf.mcscf.PiOS"> <span id="pyscf-mcscf-pios-module"></span><h2>pyscf.mcscf.PiOS module<a class="headerlink" href="#module-pyscf.mcscf.PiOS" title="Permalink to this headline">¶</a></h2> <p>When using results of this code for publications, please cite the following paper: “Constructing molecular pi-orbital active spaces for multireference calculations of conjugated systems”</p> <blockquote> <div><ol class="upperalpha simple" start="5"> <li><ol class="upperalpha simple" start="18"> <li><p>Sayfutyarova and <NAME>, J. Chem. Theory Comput., 15, 1679 (2019).</p></li> </ol> </li> </ol> </div></blockquote> <dl class="py function"> <dt id="pyscf.mcscf.PiOS.Atoms_w_Coords"> <code class="sig-prename descclassname">pyscf.mcscf.PiOS.</code><code class="sig-name descname">Atoms_w_Coords</code><span class="sig-paren">(</span><em class="sig-param"><span class="n">mol</span></em><span class="sig-paren">)</span><a class="headerlink" href="#pyscf.mcscf.PiOS.Atoms_w_Coords" title="Permalink to this definition">¶</a></dt> <dd><p>collect info about atoms’ positions</p> </dd></dl> <dl class="py function"> <dt id="pyscf.mcscf.PiOS.FindValenceAoIndices"> <code class="sig-prename descclassname">pyscf.mcscf.PiOS.</code><code class="sig-name descname">FindValenceAoIndices</code><span class="sig-paren">(</span><em class="sig-param"><span class="n">iAt</span></em>, <em class="sig-param"><span class="n">Shells</span></em>, <em class="sig-param"><span class="n">TargetL</span></em><span class="sig-paren">)</span><a class="headerlink" href="#pyscf.mcscf.PiOS.FindValenceAoIndices" title="Permalink to this definition">¶</a></dt> <dd></dd></dl> <dl class="py function"> <dt id="pyscf.mcscf.PiOS.GetCovalentRadius"> <code class="sig-prename descclassname">pyscf.mcscf.PiOS.</code><code class="sig-name descname">GetCovalentRadius</code><span class="sig-paren">(</span><em class="sig-param"><span class="n">At</span></em><span class="sig-paren">)</span><a class="headerlink" href="#pyscf.mcscf.PiOS.GetCovalentRadius" title="Permalink to this definition">¶</a></dt> <dd></dd></dl> <dl class="py function"> <dt id="pyscf.mcscf.PiOS.GetNumPiElec"> <code class="sig-prename descclassname">pyscf.mcscf.PiOS.</code><code class="sig-name descname">GetNumPiElec</code><span class="sig-paren">(</span><em class="sig-param"><span class="n">iAt</span></em>, <em class="sig-param"><span class="n">Elements</span></em>, <em class="sig-param"><span class="n">Coords</span></em><span class="sig-paren">)</span><a class="headerlink" href="#pyscf.mcscf.PiOS.GetNumPiElec" title="Permalink to this definition">¶</a></dt> <dd></dd></dl> <dl class="py function"> <dt id="pyscf.mcscf.PiOS.GetPzOrientation"> <code class="sig-prename descclassname">pyscf.mcscf.PiOS.</code><code class="sig-name descname">GetPzOrientation</code><span class="sig-paren">(</span><em class="sig-param"><span class="n">iTargetAtoms</span></em>, <em class="sig-param"><span class="n">Coords_</span></em>, <em class="sig-param"><span class="n">Elements_</span></em><span class="sig-paren">)</span><a class="headerlink" href="#pyscf.mcscf.PiOS.GetPzOrientation" title="Permalink to this definition">¶</a></dt> <dd></dd></dl> <dl class="py function"> <dt id="pyscf.mcscf.PiOS.MakeIaosRaw"> <code class="sig-prename descclassname">pyscf.mcscf.PiOS.</code><code class="sig-name descname">MakeIaosRaw</code><span class="sig-paren">(</span><em class="sig-param"><span class="n">COcc</span></em>, <em class="sig-param"><span class="n">S1</span></em>, <em class="sig-param"><span class="n">S2</span></em>, <em class="sig-param"><span class="n">S12</span></em><span class="sig-paren">)</span><a class="headerlink" href="#pyscf.mcscf.PiOS.MakeIaosRaw" title="Permalink to this definition">¶</a></dt> <dd></dd></dl> <dl class="py function"> <dt id="pyscf.mcscf.PiOS.MakeOverlappingOrbSubspace"> <code class="sig-prename descclassname">pyscf.mcscf.PiOS.</code><code class="sig-name descname">MakeOverlappingOrbSubspace</code><span class="sig-paren">(</span><em class="sig-param"><span class="n">Space</span></em>, <em class="sig-param"><span class="n">Name</span></em>, <em class="sig-param"><span class="n">COrb</span></em>, <em class="sig-param"><span class="n">nOrbExpected</span></em>, <em class="sig-param"><span class="n">CTargetIb</span></em>, <em class="sig-param"><span class="n">S1</span></em>, <em class="sig-param"><span class="n">Fock</span></em><span class="sig-paren">)</span><a class="headerlink" href="#pyscf.mcscf.PiOS.MakeOverlappingOrbSubspace" title="Permalink to this definition">¶</a></dt> <dd></dd></dl> <dl class="py function"> <dt id="pyscf.mcscf.PiOS.MakePiOS"> <code class="sig-prename descclassname">pyscf.mcscf.PiOS.</code><code class="sig-name descname">MakePiOS</code><span class="sig-paren">(</span><em class="sig-param"><span class="n">mol</span></em>, <em class="sig-param"><span class="n">mf</span></em>, <em class="sig-param"><span class="n">PiAtomsList</span></em>, <em class="sig-param"><span class="n">nPiOcc</span><span class="o">=</span><span class="default_value">None</span></em>, <em class="sig-param"><span class="n">nPiVirt</span><span class="o">=</span><span class="default_value">None</span></em><span class="sig-paren">)</span><a class="headerlink" href="#pyscf.mcscf.PiOS.MakePiOS" title="Permalink to this definition">¶</a></dt> <dd></dd></dl> <dl class="py function"> <dt id="pyscf.mcscf.PiOS.MakePiSystemOrbitals"> <code class="sig-prename descclassname">pyscf.mcscf.PiOS.</code><code class="sig-name descname">MakePiSystemOrbitals</code><span class="sig-paren">(</span><em class="sig-param"><span class="n">TargetName</span></em>, <em class="sig-param"><span class="n">iTargetAtomsForPlane_</span></em>, <em class="sig-param"><span class="n">iTargetAtomsForBasis_</span></em>, <em class="sig-param"><span class="n">Elements</span></em>, <em class="sig-param"><span class="n">Coords</span></em>, <em class="sig-param"><span class="n">CIb</span></em>, <em class="sig-param"><span class="n">Shells</span></em>, <em class="sig-param"><span class="n">S1</span></em>, <em class="sig-param"><span class="n">S12</span></em>, <em class="sig-param"><span class="n">S2</span></em>, <em class="sig-param"><span class="n">Fock</span></em>, <em class="sig-param"><span class="n">COcc</span></em>, <em class="sig-param"><span class="n">CVir</span></em><span class="sig-paren">)</span><a class="headerlink" href="#pyscf.mcscf.PiOS.MakePiSystemOrbitals" title="Permalink to this definition">¶</a></dt> <dd></dd></dl> <dl class="py function"> <dt id="pyscf.mcscf.PiOS.MakePzMinaoVectors"> <code class="sig-prename descclassname">pyscf.mcscf.PiOS.</code><code class="sig-name descname">MakePzMinaoVectors</code><span class="sig-paren">(</span><em class="sig-param"><span class="n">iTargetAtoms</span></em>, <em class="sig-param"><span class="n">vPz</span></em>, <em class="sig-param"><span class="n">Shells</span></em><span class="sig-paren">)</span><a class="headerlink" href="#pyscf.mcscf.PiOS.MakePzMinaoVectors" title="Permalink to this definition">¶</a></dt> <dd></dd></dl> <dl class="py function"> <dt id="pyscf.mcscf.PiOS.MakeShells"> <code class="sig-prename descclassname">pyscf.mcscf.PiOS.</code><code class="sig-name descname">MakeShells</code><span class="sig-paren">(</span><em class="sig-param"><span class="n">mol</span></em>, <em class="sig-param"><span class="n">Elements</span></em><span class="sig-paren">)</span><a class="headerlink" href="#pyscf.mcscf.PiOS.MakeShells" title="Permalink to this definition">¶</a></dt> <dd><p>collect MINAO basis set data for all elements</p> </dd></dl> <dl class="py function"> <dt id="pyscf.mcscf.PiOS.MakeShellsForElement"> <code class="sig-prename descclassname">pyscf.mcscf.PiOS.</code><code class="sig-name descname">MakeShellsForElement</code><span class="sig-paren">(</span><em class="sig-param"><span class="n">mol</span></em>, <em class="sig-param"><span class="n">Element</span></em><span class="sig-paren">)</span><a class="headerlink" href="#pyscf.mcscf.PiOS.MakeShellsForElement" title="Permalink to this definition">¶</a></dt> <dd><p>make a list with MINAO basis set data for a given element in the mol object</p> </dd></dl> <dl class="py function"> <dt id="pyscf.mcscf.PiOS.MakeSmh"> <code class="sig-prename descclassname">pyscf.mcscf.PiOS.</code><code class="sig-name descname">MakeSmh</code><span class="sig-paren">(</span><em class="sig-param"><span class="n">S</span></em><span class="sig-paren">)</span><a class="headerlink" href="#pyscf.mcscf.PiOS.MakeSmh" title="Permalink to this definition">¶</a></dt> <dd></dd></dl> <dl class="py function"> <dt id="pyscf.mcscf.PiOS.SemiCanonicalize"> <code class="sig-prename descclassname">pyscf.mcscf.PiOS.</code><code class="sig-name descname">SemiCanonicalize</code><span class="sig-paren">(</span><em class="sig-param"><span class="n">COut</span></em>, <em class="sig-param"><span class="n">Fock</span></em>, <em class="sig-param"><span class="n">S1</span></em>, <em class="sig-param"><span class="n">Name</span></em>, <em class="sig-param"><span class="n">Print</span><span class="o">=</span><span class="default_value">True</span></em><span class="sig-paren">)</span><a class="headerlink" href="#pyscf.mcscf.PiOS.SemiCanonicalize" title="Permalink to this definition">¶</a></dt> <dd></dd></dl> <dl class="py function"> <dt id="pyscf.mcscf.PiOS.mdot"> <code class="sig-prename descclassname">pyscf.mcscf.PiOS.</code><code class="sig-name descname">mdot</code><span class="sig-paren">(</span><em class="sig-param"><span class="o">*</span><span class="n">args</span></em><span class="sig-paren">)</span><a class="headerlink" href="#pyscf.mcscf.PiOS.mdot" title="Permalink to this definition">¶</a></dt> <dd><p>chained matrix product: mdot(A,B,C,..) = A*B*C*… No attempt is made to optimize the contraction order.</p> </dd></dl> <dl class="py function"> <dt id="pyscf.mcscf.PiOS.rmsd"> <code class="sig-prename descclassname">pyscf.mcscf.PiOS.</code><code class="sig-name descname">rmsd</code><span class="sig-paren">(</span><em class="sig-param"><span class="n">a</span></em>, <em class="sig-param"><span class="n">b</span><span class="o">=</span><span class="default_value">None</span></em><span class="sig-paren">)</span><a class="headerlink" href="#pyscf.mcscf.PiOS.rmsd" title="Permalink to this definition">¶</a></dt> <dd></dd></dl> </div> <div class="section" id="module-pyscf.mcscf.addons"> <span id="pyscf-mcscf-addons-module"></span><h2>pyscf.mcscf.addons module<a class="headerlink" href="#module-pyscf.mcscf.addons" title="Permalink to this headline">¶</a></h2> <dl class="py class"> <dt id="pyscf.mcscf.addons.StateAverageFCISolver"> <em class="property">class </em><code class="sig-prename descclassname">pyscf.mcscf.addons.</code><code class="sig-name descname">StateAverageFCISolver</code><a class="headerlink" href="#pyscf.mcscf.addons.StateAverageFCISolver" title="Permalink to this definition">¶</a></dt> <dd><p>Bases: <code class="xref py py-class docutils literal notranslate"><span class="pre">object</span></code></p> </dd></dl> <dl class="py class"> <dt id="pyscf.mcscf.addons.StateAverageMCSCFSolver"> <em class="property">class </em><code class="sig-prename descclassname">pyscf.mcscf.addons.</code><code class="sig-name descname">StateAverageMCSCFSolver</code><a class="headerlink" href="#pyscf.mcscf.addons.StateAverageMCSCFSolver" title="Permalink to this definition">¶</a></dt> <dd><p>Bases: <code class="xref py py-class docutils literal notranslate"><span class="pre">object</span></code></p> </dd></dl> <dl class="py class"> <dt id="pyscf.mcscf.addons.StateSpecificFCISolver"> <em class="property">class </em><code class="sig-prename descclassname">pyscf.mcscf.addons.</code><code class="sig-name descname">StateSpecificFCISolver</code><a class="headerlink" href="#pyscf.mcscf.addons.StateSpecificFCISolver" title="Permalink to this definition">¶</a></dt> <dd><p>Bases: <code class="xref py py-class docutils literal notranslate"><span class="pre">object</span></code></p> </dd></dl> <dl class="py function"> <dt id="pyscf.mcscf.addons.cas_natorb"> <code class="sig-prename descclassname">pyscf.mcscf.addons.</code><code class="sig-name descname">cas_natorb</code><span class="sig-paren">(</span><em class="sig-param"><span class="n">casscf</span></em>, <em class="sig-param"><span class="n">mo_coeff</span><span class="o">=</span><span class="default_value">None</span></em>, <em class="sig-param"><span class="n">ci</span><span class="o">=</span><span class="default_value">None</span></em>, <em class="sig-param"><span class="n">sort</span><span class="o">=</span><span class="default_value">False</span></em><span class="sig-paren">)</span><a class="headerlink" href="#pyscf.mcscf.addons.cas_natorb" title="Permalink to this definition">¶</a></dt> <dd><p>Natrual orbitals in CAS space</p> </dd></dl> <dl class="py function"> <dt id="pyscf.mcscf.addons.caslst_by_irrep"> <code class="sig-prename descclassname">pyscf.mcscf.addons.</code><code class="sig-name descname">caslst_by_irrep</code><span class="sig-paren">(</span><em class="sig-param"><span class="n">casscf</span></em>, <em class="sig-param"><span class="n">mo_coeff</span></em>, <em class="sig-param"><span class="n">cas_irrep_nocc</span></em>, <em class="sig-param"><span class="n">cas_irrep_ncore</span><span class="o">=</span><span class="default_value">None</span></em>, <em class="sig-param"><span class="n">s</span><span class="o">=</span><span class="default_value">None</span></em>, <em class="sig-param"><span class="n">base</span><span class="o">=</span><span class="default_value">1</span></em><span class="sig-paren">)</span><a class="headerlink" href="#pyscf.mcscf.addons.caslst_by_irrep" title="Permalink to this definition">¶</a></dt> <dd><p>Given number of active orbitals for each irrep, return the orbital indices of active space</p> <dl> <dt>Args:</dt><dd><p>casscf : an <code class="xref py py-class docutils literal notranslate"><span class="pre">CASSCF</span></code> or <code class="xref py py-class docutils literal notranslate"><span class="pre">CASCI</span></code> object</p> <dl class="simple"> <dt>cas_irrep_nocc<span class="classifier">list or dict</span></dt><dd><p>Number of active orbitals for each irrep. It can be a dict, eg {‘A1’: 2, ‘B2’: 4} to indicate the active space size based on irrep names, or {0: 2, 3: 4} for irrep Id, or a list [2, 0, 0, 4] (identical to {0: 2, 3: 4}) in which the list index is served as the irrep Id.</p> </dd> </dl> </dd> <dt>Kwargs:</dt><dd><dl class="simple"> <dt>cas_irrep_ncore<span class="classifier">list or dict</span></dt><dd><p>Number of closed shells for each irrep. It can be a dict, eg {‘A1’: 6, ‘B2’: 4} to indicate the closed shells based on irrep names, or {0: 6, 3: 4} for irrep Id, or a list [6, 0, 0, 4] (identical to {0: 6, 3: 4}) in which the list index is served as the irrep Id. If cas_irrep_ncore is not given, the program will generate a guess based on the lowest <code class="xref py py-attr docutils literal notranslate"><span class="pre">CASCI.ncore</span></code> orbitals.</p> </dd> <dt>s<span class="classifier">ndarray</span></dt><dd><p>overlap matrix</p> </dd> <dt>base<span class="classifier">int</span></dt><dd><p>0-based (C-like) or 1-based (Fortran-like) caslst</p> </dd> </dl> </dd> <dt>Returns:</dt><dd><p>A list of orbital indices</p> </dd> </dl> <p>Examples:</p> <div class="doctest highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">from</span> <span class="nn">pyscf</span> <span class="kn">import</span> <span class="n">gto</span><span class="p">,</span> <span class="n">scf</span><span class="p">,</span> <span class="n">mcscf</span> <span class="gp">&gt;&gt;&gt; </span><span class="n">mol</span> <span class="o">=</span> <span class="n">gto</span><span class="o">.</span><span class="n">M</span><span class="p">(</span><span class="n">atom</span><span class="o">=</span><span class="s1">&#39;N 0 0 0; N 0 0 1&#39;</span><span class="p">,</span> <span class="n">basis</span><span class="o">=</span><span class="s1">&#39;ccpvtz&#39;</span><span class="p">,</span> <span class="n">symmetry</span><span class="o">=</span><span class="kc">True</span><span class="p">,</span> <span class="n">verbose</span><span class="o">=</span><span class="mi">0</span><span class="p">)</span> <span class="gp">&gt;&gt;&gt; </span><span class="n">mf</span> <span class="o">=</span> <span class="n">scf</span><span class="o">.</span><span class="n">RHF</span><span class="p">(</span><span class="n">mol</span><span class="p">)</span> <span class="gp">&gt;&gt;&gt; </span><span class="n">mf</span><span class="o">.</span><span class="n">kernel</span><span class="p">()</span> <span class="gp">&gt;&gt;&gt; </span><span class="n">mc</span> <span class="o">=</span> <span class="n">mcscf</span><span class="o">.</span><span class="n">CASSCF</span><span class="p">(</span><span class="n">mf</span><span class="p">,</span> <span class="mi">12</span><span class="p">,</span> <span class="mi">4</span><span class="p">)</span> <span class="gp">&gt;&gt;&gt; </span><span class="n">mcscf</span><span class="o">.</span><span class="n">caslst_by_irrep</span><span class="p">(</span><span class="n">mc</span><span class="p">,</span> <span class="n">mf</span><span class="o">.</span><span class="n">mo_coeff</span><span class="p">,</span> <span class="p">{</span><span class="s1">&#39;E1gx&#39;</span><span class="p">:</span><span class="mi">4</span><span class="p">,</span> <span class="s1">&#39;E1gy&#39;</span><span class="p">:</span><span class="mi">4</span><span class="p">,</span> <span class="s1">&#39;E1ux&#39;</span><span class="p">:</span><span class="mi">2</span><span class="p">,</span> <span class="s1">&#39;E1uy&#39;</span><span class="p">:</span><span class="mi">2</span><span class="p">})</span> <span class="go">[5, 7, 8, 10, 11, 14, 15, 20, 25, 26, 31, 32]</span> </pre></div> </div> </dd></dl> <dl class="py function"> <dt id="pyscf.mcscf.addons.get_fock"> <code class="sig-prename descclassname">pyscf.mcscf.addons.</code><code class="sig-name descname">get_fock</code><span class="sig-paren">(</span><em class="sig-param"><span class="n">casscf</span></em>, <em class="sig-param"><span class="n">mo_coeff</span><span class="o">=</span><span class="default_value">None</span></em>, <em class="sig-param"><span class="n">ci</span><span class="o">=</span><span class="default_value">None</span></em><span class="sig-paren">)</span><a class="headerlink" href="#pyscf.mcscf.addons.get_fock" title="Permalink to this definition">¶</a></dt> <dd><p>Generalized Fock matrix in AO representation</p> </dd></dl> <dl class="py function"> <dt id="pyscf.mcscf.addons.make_rdm1"> <code class="sig-prename descclassname">pyscf.mcscf.addons.</code><code class="sig-name descname">make_rdm1</code><span class="sig-paren">(</span><em class="sig-param"><span class="n">casscf</span></em>, <em class="sig-param"><span class="n">mo_coeff</span><span class="o">=</span><span class="default_value">None</span></em>, <em class="sig-param"><span class="n">ci</span><span class="o">=</span><span class="default_value">None</span></em>, <em class="sig-param"><span class="o">**</span><span class="n">kwargs</span></em><span class="sig-paren">)</span><a class="headerlink" href="#pyscf.mcscf.addons.make_rdm1" title="Permalink to this definition">¶</a></dt> <dd><p>One-particle densit matrix in AO representation</p> <dl class="simple"> <dt>Args:</dt><dd><p>casscf : an <code class="xref py py-class docutils literal notranslate"><span class="pre">CASSCF</span></code> or <code class="xref py py-class docutils literal notranslate"><span class="pre">CASCI</span></code> object</p> </dd> <dt>Kwargs:</dt><dd><dl class="simple"> <dt>ci<span class="classifier">ndarray</span></dt><dd><p>CAS space FCI coefficients. If not given, take casscf.ci.</p> </dd> <dt>mo_coeff<span class="classifier">ndarray</span></dt><dd><p>Orbital coefficients. If not given, take casscf.mo_coeff.</p> </dd> </dl> </dd> </dl> <p>Examples:</p> <div class="doctest highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">import</span> <span class="nn">scipy.linalg</span> <span class="gp">&gt;&gt;&gt; </span><span class="kn">from</span> <span class="nn">pyscf</span> <span class="kn">import</span> <span class="n">gto</span><span class="p">,</span> <span class="n">scf</span><span class="p">,</span> <span class="n">mcscf</span> <span class="gp">&gt;&gt;&gt; </span><span class="n">mol</span> <span class="o">=</span> <span class="n">gto</span><span class="o">.</span><span class="n">M</span><span class="p">(</span><span class="n">atom</span><span class="o">=</span><span class="s1">&#39;N 0 0 0; N 0 0 1&#39;</span><span class="p">,</span> <span class="n">basis</span><span class="o">=</span><span class="s1">&#39;sto-3g&#39;</span><span class="p">,</span> <span class="n">verbose</span><span class="o">=</span><span class="mi">0</span><span class="p">)</span> <span class="gp">&gt;&gt;&gt; </span><span class="n">mf</span> <span class="o">=</span> <span class="n">scf</span><span class="o">.</span><span class="n">RHF</span><span class="p">(</span><span class="n">mol</span><span class="p">)</span> <span class="gp">&gt;&gt;&gt; </span><span class="n">res</span> <span class="o">=</span> <span class="n">mf</span><span class="o">.</span><span class="n">scf</span><span class="p">()</span> <span class="gp">&gt;&gt;&gt; </span><span class="n">mc</span> <span class="o">=</span> <span class="n">mcscf</span><span class="o">.</span><span class="n">CASSCF</span><span class="p">(</span><span class="n">mf</span><span class="p">,</span> <span class="mi">6</span><span class="p">,</span> <span class="mi">6</span><span class="p">)</span> <span class="gp">&gt;&gt;&gt; </span><span class="n">res</span> <span class="o">=</span> <span class="n">mc</span><span class="o">.</span><span class="n">kernel</span><span class="p">()</span> <span class="gp">&gt;&gt;&gt; </span><span class="n">natocc</span> <span class="o">=</span> <span class="n">numpy</span><span class="o">.</span><span class="n">linalg</span><span class="o">.</span><span class="n">eigh</span><span class="p">(</span><span class="n">mcscf</span><span class="o">.</span><span class="n">make_rdm1</span><span class="p">(</span><span class="n">mc</span><span class="p">),</span> <span class="n">mf</span><span class="o">.</span><span class="n">get_ovlp</span><span class="p">(),</span> <span class="nb">type</span><span class="o">=</span><span class="mi">2</span><span class="p">)[</span><span class="mi">0</span><span class="p">]</span> <span class="gp">&gt;&gt;&gt; </span><span class="nb">print</span><span class="p">(</span><span class="n">natocc</span><span class="p">)</span> <span class="go">[ 0.0121563 0.0494735 0.0494735 1.95040395 1.95040395 1.98808879</span> <span class="go"> 2. 2. 2. 2. ]</span> </pre></div> </div> </dd></dl> <dl class="py function"> <dt id="pyscf.mcscf.addons.make_rdm12"> <code class="sig-prename descclassname">pyscf.mcscf.addons.</code><code class="sig-name descname">make_rdm12</code><span class="sig-paren">(</span><em class="sig-param"><span class="n">casscf</span></em>, <em class="sig-param"><span class="n">mo_coeff</span><span class="o">=</span><span class="default_value">None</span></em>, <em class="sig-param"><span class="n">ci</span><span class="o">=</span><span class="default_value">None</span></em><span class="sig-paren">)</span><a class="headerlink" href="#pyscf.mcscf.addons.make_rdm12" title="Permalink to this definition">¶</a></dt> <dd></dd></dl> <dl class="py function"> <dt id="pyscf.mcscf.addons.make_rdm1s"> <code class="sig-prename descclassname">pyscf.mcscf.addons.</code><code class="sig-name descname">make_rdm1s</code><span class="sig-paren">(</span><em class="sig-param"><span class="n">casscf</span></em>, <em class="sig-param"><span class="n">mo_coeff</span><span class="o">=</span><span class="default_value">None</span></em>, <em class="sig-param"><span class="n">ci</span><span class="o">=</span><span class="default_value">None</span></em>, <em class="sig-param"><span class="o">**</span><span class="n">kwargs</span></em><span class="sig-paren">)</span><a class="headerlink" href="#pyscf.mcscf.addons.make_rdm1s" title="Permalink to this definition">¶</a></dt> <dd><p>Alpha and beta one-particle densit matrices in AO representation</p> </dd></dl> <dl class="py function"> <dt id="pyscf.mcscf.addons.map2hf"> <code class="sig-prename descclassname">pyscf.mcscf.addons.</code><code class="sig-name descname">map2hf</code><span class="sig-paren">(</span><em class="sig-param"><span class="n">casscf</span></em>, <em class="sig-param"><span class="n">mf_mo</span><span class="o">=</span><span class="default_value">None</span></em>, <em class="sig-param"><span class="n">base</span><span class="o">=</span><span class="default_value">1</span></em>, <em class="sig-param"><span class="n">tol</span><span class="o">=</span><span class="default_value">0.4</span></em><span class="sig-paren">)</span><a class="headerlink" href="#pyscf.mcscf.addons.map2hf" title="Permalink to this definition">¶</a></dt> <dd><p>The overlap between the CASSCF optimized orbitals and the canonical HF orbitals.</p> </dd></dl> <dl class="py function"> <dt id="pyscf.mcscf.addons.project_init_guess"> <code class="sig-prename descclassname">pyscf.mcscf.addons.</code><code class="sig-name descname">project_init_guess</code><span class="sig-paren">(</span><em class="sig-param"><span class="n">casscf</span></em>, <em class="sig-param"><span class="n">init_mo</span></em>, <em class="sig-param"><span class="n">prev_mol</span><span class="o">=</span><span class="default_value">None</span></em><span class="sig-paren">)</span><a class="headerlink" href="#pyscf.mcscf.addons.project_init_guess" title="Permalink to this definition">¶</a></dt> <dd><p>Project the given initial guess to the current CASSCF problem. The projected initial guess has two parts. The core orbitals are directly taken from the Hartree-Fock orbitals, and the active orbitals are projected from the given initial guess.</p> <dl> <dt>Args:</dt><dd><p>casscf : an <code class="xref py py-class docutils literal notranslate"><span class="pre">CASSCF</span></code> or <code class="xref py py-class docutils literal notranslate"><span class="pre">CASCI</span></code> object</p> <dl class="simple"> <dt>init_mo<span class="classifier">ndarray or list of ndarray</span></dt><dd><p>Initial guess orbitals which are not orth-normal for the current molecule. When the casscf is UHF-CASSCF, the init_mo needs to be a list of two ndarrays, for alpha and beta orbitals</p> </dd> </dl> </dd> <dt>Kwargs:</dt><dd><dl> <dt>prev_mol<span class="classifier">an instance of <code class="xref py py-class docutils literal notranslate"><span class="pre">Mole</span></code></span></dt><dd><p>If given, the inital guess orbitals are associated to the geometry and basis of prev_mol. Otherwise, the orbitals are based of the geometry and basis of casscf.mol</p> </dd> </dl> </dd> <dt>Returns:</dt><dd><p>New orthogonal initial guess orbitals with the core taken from Hartree-Fock orbitals and projected active space from original initial guess orbitals</p> </dd> </dl> <p>Examples:</p> <div class="highlight-python notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">numpy</span> <span class="kn">from</span> <span class="nn">pyscf</span> <span class="kn">import</span> <span class="n">gto</span><span class="p">,</span> <span class="n">scf</span><span class="p">,</span> <span class="n">mcscf</span> <span class="n">mol</span> <span class="o">=</span> <span class="n">gto</span><span class="o">.</span><span class="n">Mole</span><span class="p">()</span> <span class="n">mol</span><span class="o">.</span><span class="n">build</span><span class="p">(</span><span class="n">atom</span><span class="o">=</span><span class="s1">&#39;H 0 0 0; F 0 0 0.8&#39;</span><span class="p">,</span> <span class="n">basis</span><span class="o">=</span><span class="s1">&#39;ccpvdz&#39;</span><span class="p">,</span> <span class="n">verbose</span><span class="o">=</span><span class="mi">0</span><span class="p">)</span> <span class="n">mf</span> <span class="o">=</span> <span class="n">scf</span><span class="o">.</span><span class="n">RHF</span><span class="p">(</span><span class="n">mol</span><span class="p">)</span> <span class="n">mf</span><span class="o">.</span><span class="n">scf</span><span class="p">()</span> <span class="n">mc</span> <span class="o">=</span> <span class="n">mcscf</span><span class="o">.</span><span class="n">CASSCF</span><span class="p">(</span><span class="n">mf</span><span class="p">,</span> <span class="mi">6</span><span class="p">,</span> <span class="mi">6</span><span class="p">)</span> <span class="n">mo</span> <span class="o">=</span> <span class="n">mcscf</span><span class="o">.</span><span class="n">sort_mo</span><span class="p">(</span><span class="n">mc</span><span class="p">,</span> <span class="n">mf</span><span class="o">.</span><span class="n">mo_coeff</span><span class="p">,</span> <span class="p">[</span><span class="mi">3</span><span class="p">,</span><span class="mi">4</span><span class="p">,</span><span class="mi">5</span><span class="p">,</span><span class="mi">6</span><span class="p">,</span><span class="mi">8</span><span class="p">,</span><span class="mi">9</span><span class="p">])</span> <span class="nb">print</span><span class="p">(</span><span class="s1">&#39;E(0.8) = </span><span class="si">%.12f</span><span class="s1">&#39;</span> <span class="o">%</span> <span class="n">mc</span><span class="o">.</span><span class="n">kernel</span><span class="p">(</span><span class="n">mo</span><span class="p">)[</span><span class="mi">0</span><span class="p">])</span> <span class="n">init_mo</span> <span class="o">=</span> <span class="n">mc</span><span class="o">.</span><span class="n">mo_coeff</span> <span class="k">for</span> <span class="n">b</span> <span class="ow">in</span> <span class="n">numpy</span><span class="o">.</span><span class="n">arange</span><span class="p">(</span><span class="mf">1.0</span><span class="p">,</span> <span class="mf">3.</span><span class="p">,</span> <span class="o">.</span><span class="mi">2</span><span class="p">):</span> <span class="n">mol</span><span class="o">.</span><span class="n">atom</span> <span class="o">=</span> <span class="p">[[</span><span class="s1">&#39;H&#39;</span><span class="p">,</span> <span class="p">(</span><span class="mi">0</span><span class="p">,</span> <span class="mi">0</span><span class="p">,</span> <span class="mi">0</span><span class="p">)],</span> <span class="p">[</span><span class="s1">&#39;F&#39;</span><span class="p">,</span> <span class="p">(</span><span class="mi">0</span><span class="p">,</span> <span class="mi">0</span><span class="p">,</span> <span class="n">b</span><span class="p">)]]</span> <span class="n">mol</span><span class="o">.</span><span class="n">build</span><span class="p">(</span><span class="mi">0</span><span class="p">,</span> <span class="mi">0</span><span class="p">)</span> <span class="n">mf</span> <span class="o">=</span> <span class="n">scf</span><span class="o">.</span><span class="n">RHF</span><span class="p">(</span><span class="n">mol</span><span class="p">)</span> <span class="n">mf</span><span class="o">.</span><span class="n">scf</span><span class="p">()</span> <span class="n">mc</span> <span class="o">=</span> <span class="n">mcscf</span><span class="o">.</span><span class="n">CASSCF</span><span class="p">(</span><span class="n">mf</span><span class="p">,</span> <span class="mi">6</span><span class="p">,</span> <span class="mi">6</span><span class="p">)</span> <span class="n">mo</span> <span class="o">=</span> <span class="n">mcscf</span><span class="o">.</span><span class="n">project_init_guess</span><span class="p">(</span><span class="n">mc</span><span class="p">,</span> <span class="n">init_mo</span><span class="p">)</span> <span class="nb">print</span><span class="p">(</span><span class="s1">&#39;E(</span><span class="si">%2.1f</span><span class="s1">) = </span><span class="si">%.12f</span><span class="s1">&#39;</span> <span class="o">%</span> <span class="p">(</span><span class="n">b</span><span class="p">,</span> <span class="n">mc</span><span class="o">.</span><span class="n">kernel</span><span class="p">(</span><span class="n">mo</span><span class="p">)[</span><span class="mi">0</span><span class="p">]))</span> <span class="n">init_mo</span> <span class="o">=</span> <span class="n">mc</span><span class="o">.</span><span class="n">mo_coeff</span> </pre></div> </div> </dd></dl> <dl class="py function"> <dt id="pyscf.mcscf.addons.select_mo_by_irrep"> <code class="sig-prename descclassname">pyscf.mcscf.addons.</code><code class="sig-name descname">select_mo_by_irrep</code><span class="sig-paren">(</span><em class="sig-param"><span class="n">casscf</span></em>, <em class="sig-param"><span class="n">cas_occ_num</span></em>, <em class="sig-param"><span class="n">mo</span><span class="o">=</span><span class="default_value">None</span></em>, <em class="sig-param"><span class="n">base</span><span class="o">=</span><span class="default_value">1</span></em><span class="sig-paren">)</span><a class="headerlink" href="#pyscf.mcscf.addons.select_mo_by_irrep" title="Permalink to this definition">¶</a></dt> <dd></dd></dl> <dl class="py function"> <dt id="pyscf.mcscf.addons.sort_mo"> <code class="sig-prename descclassname">pyscf.mcscf.addons.</code><code class="sig-name descname">sort_mo</code><span class="sig-paren">(</span><em class="sig-param"><span class="n">casscf</span></em>, <em class="sig-param"><span class="n">mo_coeff</span></em>, <em class="sig-param"><span class="n">caslst</span></em>, <em class="sig-param"><span class="n">base</span><span class="o">=</span><span class="default_value">1</span></em><span class="sig-paren">)</span><a class="headerlink" href="#pyscf.mcscf.addons.sort_mo" title="Permalink to this definition">¶</a></dt> <dd><p>Pick orbitals for CAS space</p> <dl> <dt>Args:</dt><dd><p>casscf : an <code class="xref py py-class docutils literal notranslate"><span class="pre">CASSCF</span></code> or <code class="xref py py-class docutils literal notranslate"><span class="pre">CASCI</span></code> object</p> <dl class="simple"> <dt>mo_coeff<span class="classifier">ndarray or a list of ndarray</span></dt><dd><p>Orbitals for CASSCF initial guess. In the UHF-CASSCF, it’s a list of two orbitals, for alpha and beta spin.</p> </dd> <dt>caslst<span class="classifier">list of int or nested list of int</span></dt><dd><p>A list of orbital indices to represent the CAS space. In the UHF-CASSCF, it’s consist of two lists, for alpha and beta spin.</p> </dd> </dl> </dd> <dt>Kwargs:</dt><dd><dl class="simple"> <dt>base<span class="classifier">int</span></dt><dd><p>0-based (C-style) or 1-based (Fortran-style) caslst</p> </dd> </dl> </dd> <dt>Returns:</dt><dd><p>An reoreded mo_coeff, which put the orbitals given by caslst in the CAS space</p> </dd> </dl> <p>Examples:</p> <div class="doctest highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">from</span> <span class="nn">pyscf</span> <span class="kn">import</span> <span class="n">gto</span><span class="p">,</span> <span class="n">scf</span><span class="p">,</span> <span class="n">mcscf</span> <span class="gp">&gt;&gt;&gt; </span><span class="n">mol</span> <span class="o">=</span> <span class="n">gto</span><span class="o">.</span><span class="n">M</span><span class="p">(</span><span class="n">atom</span><span class="o">=</span><span class="s1">&#39;N 0 0 0; N 0 0 1&#39;</span><span class="p">,</span> <span class="n">basis</span><span class="o">=</span><span class="s1">&#39;ccpvdz&#39;</span><span class="p">,</span> <span class="n">verbose</span><span class="o">=</span><span class="mi">0</span><span class="p">)</span> <span class="gp">&gt;&gt;&gt; </span><span class="n">mf</span> <span class="o">=</span> <span class="n">scf</span><span class="o">.</span><span class="n">RHF</span><span class="p">(</span><span class="n">mol</span><span class="p">)</span> <span class="gp">&gt;&gt;&gt; </span><span class="n">mf</span><span class="o">.</span><span class="n">scf</span><span class="p">()</span> <span class="gp">&gt;&gt;&gt; </span><span class="n">mc</span> <span class="o">=</span> <span class="n">mcscf</span><span class="o">.</span><span class="n">CASSCF</span><span class="p">(</span><span class="n">mf</span><span class="p">,</span> <span class="mi">4</span><span class="p">,</span> <span class="mi">4</span><span class="p">)</span> <span class="gp">&gt;&gt;&gt; </span><span class="n">cas_list</span> <span class="o">=</span> <span class="p">[</span><span class="mi">5</span><span class="p">,</span><span class="mi">6</span><span class="p">,</span><span class="mi">8</span><span class="p">,</span><span class="mi">9</span><span class="p">]</span> <span class="c1"># pi orbitals</span> <span class="gp">&gt;&gt;&gt; </span><span class="n">mo</span> <span class="o">=</span> <span class="n">mc</span><span class="o">.</span><span class="n">sort_mo</span><span class="p">(</span><span class="n">cas_list</span><span class="p">)</span> <span class="gp">&gt;&gt;&gt; </span><span class="n">mc</span><span class="o">.</span><span class="n">kernel</span><span class="p">(</span><span class="n">mo</span><span class="p">)[</span><span class="mi">0</span><span class="p">]</span> <span class="go">-109.007378939813691</span> </pre></div> </div> </dd></dl> <dl class="py function"> <dt id="pyscf.mcscf.addons.sort_mo_by_irrep"> <code class="sig-prename descclassname">pyscf.mcscf.addons.</code><code class="sig-name descname">sort_mo_by_irrep</code><span class="sig-paren">(</span><em class="sig-param"><span class="n">casscf</span></em>, <em class="sig-param"><span class="n">mo_coeff</span></em>, <em class="sig-param"><span class="n">cas_irrep_nocc</span></em>, <em class="sig-param"><span class="n">cas_irrep_ncore</span><span class="o">=</span><span class="default_value">None</span></em>, <em class="sig-param"><span class="n">s</span><span class="o">=</span><span class="default_value">None</span></em><span class="sig-paren">)</span><a class="headerlink" href="#pyscf.mcscf.addons.sort_mo_by_irrep" title="Permalink to this definition">¶</a></dt> <dd><p>Given number of active orbitals for each irrep, construct the mo initial guess for CASSCF</p> <dl> <dt>Args:</dt><dd><p>casscf : an <code class="xref py py-class docutils literal notranslate"><span class="pre">CASSCF</span></code> or <code class="xref py py-class docutils literal notranslate"><span class="pre">CASCI</span></code> object</p> <dl class="simple"> <dt>cas_irrep_nocc<span class="classifier">list or dict</span></dt><dd><p>Number of active orbitals for each irrep. It can be a dict, eg {‘A1’: 2, ‘B2’: 4} to indicate the active space size based on irrep names, or {0: 2, 3: 4} for irrep Id, or a list [2, 0, 0, 4] (identical to {0: 2, 3: 4}) in which the list index is served as the irrep Id.</p> </dd> </dl> </dd> <dt>Kwargs:</dt><dd><dl class="simple"> <dt>cas_irrep_ncore<span class="classifier">list or dict</span></dt><dd><p>Number of closed shells for each irrep. It can be a dict, eg {‘A1’: 6, ‘B2’: 4} to indicate the closed shells based on irrep names, or {0: 6, 3: 4} for irrep Id, or a list [6, 0, 0, 4] (identical to {0: 6, 3: 4}) in which the list index is served as the irrep Id. If cas_irrep_ncore is not given, the program will generate a guess based on the lowest <code class="xref py py-attr docutils literal notranslate"><span class="pre">CASCI.ncore</span></code> orbitals.</p> </dd> <dt>s<span class="classifier">ndarray</span></dt><dd><p>overlap matrix</p> </dd> </dl> </dd> <dt>Returns:</dt><dd><p>sorted orbitals, ordered as [c,..,c,a,..,a,v,..,v]</p> </dd> </dl> <p>Examples:</p> <div class="doctest highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">from</span> <span class="nn">pyscf</span> <span class="kn">import</span> <span class="n">gto</span><span class="p">,</span> <span class="n">scf</span><span class="p">,</span> <span class="n">mcscf</span> <span class="gp">&gt;&gt;&gt; </span><span class="n">mol</span> <span class="o">=</span> <span class="n">gto</span><span class="o">.</span><span class="n">M</span><span class="p">(</span><span class="n">atom</span><span class="o">=</span><span class="s1">&#39;N 0 0 0; N 0 0 1&#39;</span><span class="p">,</span> <span class="n">basis</span><span class="o">=</span><span class="s1">&#39;ccpvtz&#39;</span><span class="p">,</span> <span class="n">symmetry</span><span class="o">=</span><span class="kc">True</span><span class="p">,</span> <span class="n">verbose</span><span class="o">=</span><span class="mi">0</span><span class="p">)</span> <span class="gp">&gt;&gt;&gt; </span><span class="n">mf</span> <span class="o">=</span> <span class="n">scf</span><span class="o">.</span><span class="n">RHF</span><span class="p">(</span><span class="n">mol</span><span class="p">)</span> <span class="gp">&gt;&gt;&gt; </span><span class="n">mf</span><span class="o">.</span><span class="n">kernel</span><span class="p">()</span> <span class="gp">&gt;&gt;&gt; </span><span class="n">mc</span> <span class="o">=</span> <span class="n">mcscf</span><span class="o">.</span><span class="n">CASSCF</span><span class="p">(</span><span class="n">mf</span><span class="p">,</span> <span class="mi">12</span><span class="p">,</span> <span class="mi">4</span><span class="p">)</span> <span class="gp">&gt;&gt;&gt; </span><span class="n">mo</span> <span class="o">=</span> <span class="n">mc</span><span class="o">.</span><span class="n">sort_mo_by_irrep</span><span class="p">({</span><span class="s1">&#39;E1gx&#39;</span><span class="p">:</span><span class="mi">4</span><span class="p">,</span> <span class="s1">&#39;E1gy&#39;</span><span class="p">:</span><span class="mi">4</span><span class="p">,</span> <span class="s1">&#39;E1ux&#39;</span><span class="p">:</span><span class="mi">2</span><span class="p">,</span> <span class="s1">&#39;E1uy&#39;</span><span class="p">:</span><span class="mi">2</span><span class="p">})</span> <span class="gp">&gt;&gt;&gt; </span><span class="c1"># Same to mo = sort_mo_by_irrep(mc, mf.mo_coeff, {2: 4, 3: 4, 6: 2, 7: 2})</span> <span class="gp">&gt;&gt;&gt; </span><span class="c1"># Same to mo = sort_mo_by_irrep(mc, mf.mo_coeff, [0, 0, 4, 4, 0, 0, 2, 2])</span> <span class="gp">&gt;&gt;&gt; </span><span class="n">mc</span><span class="o">.</span><span class="n">kernel</span><span class="p">(</span><span class="n">mo</span><span class="p">)[</span><span class="mi">0</span><span class="p">]</span> <span class="go">-108.162863845084</span> </pre></div> </div> </dd></dl> <dl class="py function"> <dt id="pyscf.mcscf.addons.spin_square"> <code class="sig-prename descclassname">pyscf.mcscf.addons.</code><code class="sig-name descname">spin_square</code><span class="sig-paren">(</span><em class="sig-param"><span class="n">casscf</span></em>, <em class="sig-param"><span class="n">mo_coeff</span><span class="o">=</span><span class="default_value">None</span></em>, <em class="sig-param"><span class="n">ci</span><span class="o">=</span><span class="default_value">None</span></em>, <em class="sig-param"><span class="n">ovlp</span><span class="o">=</span><span class="default_value">None</span></em><span class="sig-paren">)</span><a class="headerlink" href="#pyscf.mcscf.addons.spin_square" title="Permalink to this definition">¶</a></dt> <dd><p>Spin square of the UHF-CASSCF wavefunction</p> <dl class="simple"> <dt>Returns:</dt><dd><p>A list of two floats. The first is the expectation value of S^2. The second is the corresponding 2S+1</p> </dd> </dl> <p>Examples:</p> <div class="doctest highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">from</span> <span class="nn">pyscf</span> <span class="kn">import</span> <span class="n">gto</span><span class="p">,</span> <span class="n">scf</span><span class="p">,</span> <span class="n">mcscf</span> <span class="gp">&gt;&gt;&gt; </span><span class="n">mol</span> <span class="o">=</span> <span class="n">gto</span><span class="o">.</span><span class="n">M</span><span class="p">(</span><span class="n">atom</span><span class="o">=</span><span class="s1">&#39;O 0 0 0; O 0 0 1&#39;</span><span class="p">,</span> <span class="n">basis</span><span class="o">=</span><span class="s1">&#39;sto-3g&#39;</span><span class="p">,</span> <span class="n">spin</span><span class="o">=</span><span class="mi">2</span><span class="p">,</span> <span class="n">verbose</span><span class="o">=</span><span class="mi">0</span><span class="p">)</span> <span class="gp">&gt;&gt;&gt; </span><span class="n">mf</span> <span class="o">=</span> <span class="n">scf</span><span class="o">.</span><span class="n">UHF</span><span class="p">(</span><span class="n">mol</span><span class="p">)</span> <span class="gp">&gt;&gt;&gt; </span><span class="n">res</span> <span class="o">=</span> <span class="n">mf</span><span class="o">.</span><span class="n">scf</span><span class="p">()</span> <span class="gp">&gt;&gt;&gt; </span><span class="n">mc</span> <span class="o">=</span> <span class="n">mcscf</span><span class="o">.</span><span class="n">CASSCF</span><span class="p">(</span><span class="n">mf</span><span class="p">,</span> <span class="mi">4</span><span class="p">,</span> <span class="mi">6</span><span class="p">)</span> <span class="gp">&gt;&gt;&gt; </span><span class="n">res</span> <span class="o">=</span> <span class="n">mc</span><span class="o">.</span><span class="n">kernel</span><span class="p">()</span> <span class="gp">&gt;&gt;&gt; </span><span class="nb">print</span><span class="p">(</span><span class="s1">&#39;S^2 = </span><span class="si">%.7f</span><span class="s1">, 2S+1 = </span><span class="si">%.7f</span><span class="s1">&#39;</span> <span class="o">%</span> <span class="n">mcscf</span><span class="o">.</span><span class="n">spin_square</span><span class="p">(</span><span class="n">mc</span><span class="p">))</span> <span class="go">S^2 = 3.9831589, 2S+1 = 4.1149284</span> </pre></div> </div> </dd></dl> <dl class="py function"> <dt id="pyscf.mcscf.addons.state_average"> <code class="sig-prename descclassname">pyscf.mcscf.addons.</code><code class="sig-name descname">state_average</code><span class="sig-paren">(</span><em class="sig-param"><span class="n">casscf</span></em>, <em class="sig-param"><span class="n">weights</span><span class="o">=</span><span class="default_value">(0.5, 0.5)</span></em>, <em class="sig-param"><span class="n">wfnsym</span><span class="o">=</span><span class="default_value">None</span></em><span class="sig-paren">)</span><a class="headerlink" href="#pyscf.mcscf.addons.state_average" title="Permalink to this definition">¶</a></dt> <dd><p>State average over the energy. The energy funcitonal is E = w1&lt;psi1|H|psi1&gt; + w2&lt;psi2|H|psi2&gt; + …</p> <p>Note we may need change the FCI solver to</p> <p>mc.fcisolver = fci.solver(mol, False)</p> <p>before calling state_average_(mc), to mix the singlet and triplet states</p> <p>MRH, 04/08/2019: Instead of turning casscf._finalize into an instance attribute that points to the previous casscf object, I’m going to make a whole new child class. This will have the added benefit of making state_average and <a href="#id1"><span class="problematic" id="id2">state_average_</span></a> actually behave differently for the first time (until now they <em>both</em> modified the casscf object inplace). I’m also going to assign the weights argument as a member of the mc child class because an accurate second-order CASSCF algorithm for state-averaged calculations requires that the gradient and Hessian be computed for CI vectors of each root individually and then multiplied by that root’s weight. The second derivatives computed by newton_casscf.py need to be extended to state-averaged calculations in order to be used as intermediates for calculations of the gradient of a single root in the context of the SA-CASSCF method; see: Mol. Phys. 99, 103 (2001).</p> </dd></dl> <dl class="py function"> <dt id="pyscf.mcscf.addons.state_average_"> <code class="sig-prename descclassname">pyscf.mcscf.addons.</code><code class="sig-name descname">state_average_</code><span class="sig-paren">(</span><em class="sig-param"><span class="n">casscf</span></em>, <em class="sig-param"><span class="n">weights</span><span class="o">=</span><span class="default_value">(0.5, 0.5)</span></em><span class="sig-paren">)</span><a class="headerlink" href="#pyscf.mcscf.addons.state_average_" title="Permalink to this definition">¶</a></dt> <dd><p>Inplace version of state_average</p> </dd></dl> <dl class="py function"> <dt id="pyscf.mcscf.addons.state_average_mix"> <code class="sig-prename descclassname">pyscf.mcscf.addons.</code><code class="sig-name descname">state_average_mix</code><span class="sig-paren">(</span><em class="sig-param"><span class="n">casscf</span></em>, <em class="sig-param"><span class="n">fcisolvers</span></em>, <em class="sig-param"><span class="n">weights</span><span class="o">=</span><span class="default_value">(0.5, 0.5)</span></em><span class="sig-paren">)</span><a class="headerlink" href="#pyscf.mcscf.addons.state_average_mix" title="Permalink to this definition">¶</a></dt> <dd><p>State-average CASSCF over multiple FCI solvers.</p> </dd></dl> <dl class="py function"> <dt id="pyscf.mcscf.addons.state_average_mix_"> <code class="sig-prename descclassname">pyscf.mcscf.addons.</code><code class="sig-name descname">state_average_mix_</code><span class="sig-paren">(</span><em class="sig-param"><span class="n">casscf</span></em>, <em class="sig-param"><span class="n">fcisolvers</span></em>, <em class="sig-param"><span class="n">weights</span><span class="o">=</span><span class="default_value">(0.5, 0.5)</span></em><span class="sig-paren">)</span><a class="headerlink" href="#pyscf.mcscf.addons.state_average_mix_" title="Permalink to this definition">¶</a></dt> <dd><p>Inplace version of state_average</p> </dd></dl> <dl class="py function"> <dt id="pyscf.mcscf.addons.state_specific"> <code class="sig-prename descclassname">pyscf.mcscf.addons.</code><code class="sig-name descname">state_specific</code><span class="sig-paren">(</span><em class="sig-param"><span class="n">casscf</span></em>, <em class="sig-param"><span class="n">state</span><span class="o">=</span><span class="default_value">1</span></em>, <em class="sig-param"><span class="n">wfnsym</span><span class="o">=</span><span class="default_value">None</span></em><span class="sig-paren">)</span><a class="headerlink" href="#pyscf.mcscf.addons.state_specific" title="Permalink to this definition">¶</a></dt> <dd><p>For excited state</p> <dl class="simple"> <dt>Kwargs:</dt><dd><p>state : int 0 for ground state; 1 for first excited state.</p> </dd> </dl> </dd></dl> <dl class="py function"> <dt id="pyscf.mcscf.addons.state_specific_"> <code class="sig-prename descclassname">pyscf.mcscf.addons.</code><code class="sig-name descname">state_specific_</code><span class="sig-paren">(</span><em class="sig-param"><span class="n">casscf</span></em>, <em class="sig-param"><span class="n">state</span><span class="o">=</span><span class="default_value">1</span></em>, <em class="sig-param"><span class="n">wfnsym</span><span class="o">=</span><span class="default_value">None</span></em><span class="sig-paren">)</span><a class="headerlink" href="#pyscf.mcscf.addons.state_specific_" title="Permalink to this definition">¶</a></dt> <dd><p>For excited state</p> <dl class="simple"> <dt>Kwargs:</dt><dd><p>state : int 0 for ground state; 1 for first excited state.</p> </dd> </dl> </dd></dl> </div> <div class="section" id="module-pyscf.mcscf.avas"> <span id="pyscf-mcscf-avas-module"></span><h2>pyscf.mcscf.avas module<a class="headerlink" href="#module-pyscf.mcscf.avas" title="Permalink to this headline">¶</a></h2> <p>Automated construction of molecular active spaces from atomic valence orbitals. Ref. arXiv:1701.07862 [physics.chem-ph]</p> <dl class="py function"> <dt id="pyscf.mcscf.avas.avas"> <code class="sig-prename descclassname">pyscf.mcscf.avas.</code><code class="sig-name descname">avas</code><span class="sig-paren">(</span><em class="sig-param"><span class="n">mf</span></em>, <em class="sig-param"><span class="n">aolabels</span></em>, <em class="sig-param"><span class="n">threshold</span><span class="o">=</span><span class="default_value">0.2</span></em>, <em class="sig-param"><span class="n">minao</span><span class="o">=</span><span class="default_value">'minao'</span></em>, <em class="sig-param"><span class="n">with_iao</span><span class="o">=</span><span class="default_value">False</span></em>, <em class="sig-param"><span class="n">openshell_option</span><span class="o">=</span><span class="default_value">2</span></em>, <em class="sig-param"><span class="n">canonicalize</span><span class="o">=</span><span class="default_value">True</span></em>, <em class="sig-param"><span class="n">ncore</span><span class="o">=</span><span class="default_value">0</span></em>, <em class="sig-param"><span class="n">verbose</span><span class="o">=</span><span class="default_value">None</span></em><span class="sig-paren">)</span><a class="headerlink" href="#pyscf.mcscf.avas.avas" title="Permalink to this definition">¶</a></dt> <dd><p>AVAS method to construct mcscf active space. Ref. arXiv:1701.07862 [physics.chem-ph]</p> <dl> <dt>Args:</dt><dd><p>mf : an <code class="xref py py-class docutils literal notranslate"><span class="pre">SCF</span></code> object</p> <dl class="simple"> <dt>aolabels<span class="classifier">string or a list of strings</span></dt><dd><p>AO labels for AO active space</p> </dd> </dl> </dd> <dt>Kwargs:</dt><dd><dl class="simple"> <dt>threshold<span class="classifier">float</span></dt><dd><p>Tructing threshold of the AO-projector above which AOs are kept in the active space.</p> </dd> <dt>minao<span class="classifier">str</span></dt><dd><p>A reference AOs for AVAS.</p> </dd> <dt>with_iao<span class="classifier">bool</span></dt><dd><p>Whether to use IAO localization to construct the reference active AOs.</p> </dd> <dt>openshell_option<span class="classifier">int</span></dt><dd><p>How to handle singly-occupied orbitals in the active space. The singly-occupied orbitals are projected as part of alpha orbitals if openshell_option=2, or completely kept in active space if openshell_option=3. See Section III.E option 2 or 3 of the reference paper for more details.</p> </dd> <dt>canonicalize<span class="classifier">bool</span></dt><dd><p>Orbitals defined in AVAS method are local orbitals. Symmetrizing the core, active and virtual space.</p> </dd> <dt>ncore<span class="classifier">integer</span></dt><dd><p>Number of core orbitals to exclude from the AVAS method.</p> </dd> </dl> </dd> <dt>Returns:</dt><dd><p>active-space-size, #-active-electrons, orbital-initial-guess-for-CASCI/CASSCF</p> </dd> </dl> <p>Examples:</p> <div class="doctest highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">from</span> <span class="nn">pyscf</span> <span class="kn">import</span> <span class="n">gto</span><span class="p">,</span> <span class="n">scf</span><span class="p">,</span> <span class="n">mcscf</span> <span class="gp">&gt;&gt;&gt; </span><span class="kn">from</span> <span class="nn">pyscf.mcscf</span> <span class="kn">import</span> <span class="n">avas</span> <span class="gp">&gt;&gt;&gt; </span><span class="n">mol</span> <span class="o">=</span> <span class="n">gto</span><span class="o">.</span><span class="n">M</span><span class="p">(</span><span class="n">atom</span><span class="o">=</span><span class="s1">&#39;Cr 0 0 0; Cr 0 0 1.6&#39;</span><span class="p">,</span> <span class="n">basis</span><span class="o">=</span><span class="s1">&#39;ccpvtz&#39;</span><span class="p">)</span> <span class="gp">&gt;&gt;&gt; </span><span class="n">mf</span> <span class="o">=</span> <span class="n">scf</span><span class="o">.</span><span class="n">RHF</span><span class="p">(</span><span class="n">mol</span><span class="p">)</span><span class="o">.</span><span class="n">run</span><span class="p">()</span> <span class="gp">&gt;&gt;&gt; </span><span class="n">ncas</span><span class="p">,</span> <span class="n">nelecas</span><span class="p">,</span> <span class="n">mo</span> <span class="o">=</span> <span class="n">avas</span><span class="o">.</span><span class="n">avas</span><span class="p">(</span><span class="n">mf</span><span class="p">,</span> <span class="p">[</span><span class="s1">&#39;Cr 3d&#39;</span><span class="p">,</span> <span class="s1">&#39;Cr 4s&#39;</span><span class="p">])</span> <span class="gp">&gt;&gt;&gt; </span><span class="n">mc</span> <span class="o">=</span> <span class="n">mcscf</span><span class="o">.</span><span class="n">CASSCF</span><span class="p">(</span><span class="n">mf</span><span class="p">,</span> <span class="n">ncas</span><span class="p">,</span> <span class="n">nelecas</span><span class="p">)</span><span class="o">.</span><span class="n">run</span><span class="p">(</span><span class="n">mo</span><span class="p">)</span> </pre></div> </div> </dd></dl> <dl class="py function"> <dt id="pyscf.mcscf.avas.kernel"> <code class="sig-prename descclassname">pyscf.mcscf.avas.</code><code class="sig-name descname">kernel</code><span class="sig-paren">(</span><em class="sig-param"><span class="n">mf</span></em>, <em class="sig-param"><span class="n">aolabels</span></em>, <em class="sig-param"><span class="n">threshold</span><span class="o">=</span><span class="default_value">0.2</span></em>, <em class="sig-param"><span class="n">minao</span><span class="o">=</span><span class="default_value">'minao'</span></em>, <em class="sig-param"><span class="n">with_iao</span><span class="o">=</span><span class="default_value">False</span></em>, <em class="sig-param"><span class="n">openshell_option</span><span class="o">=</span><span class="default_value">2</span></em>, <em class="sig-param"><span class="n">canonicalize</span><span class="o">=</span><span class="default_value">True</span></em>, <em class="sig-param"><span class="n">ncore</span><span class="o">=</span><span class="default_value">0</span></em>, <em class="sig-param"><span class="n">verbose</span><span class="o">=</span><span class="default_value">None</span></em><span class="sig-paren">)</span><a class="headerlink" href="#pyscf.mcscf.avas.kernel" title="Permalink to this definition">¶</a></dt> <dd><p>AVAS method to construct mcscf active space. Ref. arXiv:1701.07862 [physics.chem-ph]</p> <dl> <dt>Args:</dt><dd><p>mf : an <code class="xref py py-class docutils literal notranslate"><span class="pre">SCF</span></code> object</p> <dl class="simple"> <dt>aolabels<span class="classifier">string or a list of strings</span></dt><dd><p>AO labels for AO active space</p> </dd> </dl> </dd> <dt>Kwargs:</dt><dd><dl class="simple"> <dt>threshold<span class="classifier">float</span></dt><dd><p>Tructing threshold of the AO-projector above which AOs are kept in the active space.</p> </dd> <dt>minao<span class="classifier">str</span></dt><dd><p>A reference AOs for AVAS.</p> </dd> <dt>with_iao<span class="classifier">bool</span></dt><dd><p>Whether to use IAO localization to construct the reference active AOs.</p> </dd> <dt>openshell_option<span class="classifier">int</span></dt><dd><p>How to handle singly-occupied orbitals in the active space. The singly-occupied orbitals are projected as part of alpha orbitals if openshell_option=2, or completely kept in active space if openshell_option=3. See Section III.E option 2 or 3 of the reference paper for more details.</p> </dd> <dt>canonicalize<span class="classifier">bool</span></dt><dd><p>Orbitals defined in AVAS method are local orbitals. Symmetrizing the core, active and virtual space.</p> </dd> <dt>ncore<span class="classifier">integer</span></dt><dd><p>Number of core orbitals to exclude from the AVAS method.</p> </dd> </dl> </dd> <dt>Returns:</dt><dd><p>active-space-size, #-active-electrons, orbital-initial-guess-for-CASCI/CASSCF</p> </dd> </dl> <p>Examples:</p> <div class="doctest highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">from</span> <span class="nn">pyscf</span> <span class="kn">import</span> <span class="n">gto</span><span class="p">,</span> <span class="n">scf</span><span class="p">,</span> <span class="n">mcscf</span> <span class="gp">&gt;&gt;&gt; </span><span class="kn">from</span> <span class="nn">pyscf.mcscf</span> <span class="kn">import</span> <span class="n">avas</span> <span class="gp">&gt;&gt;&gt; </span><span class="n">mol</span> <span class="o">=</span> <span class="n">gto</span><span class="o">.</span><span class="n">M</span><span class="p">(</span><span class="n">atom</span><span class="o">=</span><span class="s1">&#39;Cr 0 0 0; Cr 0 0 1.6&#39;</span><span class="p">,</span> <span class="n">basis</span><span class="o">=</span><span class="s1">&#39;ccpvtz&#39;</span><span class="p">)</span> <span class="gp">&gt;&gt;&gt; </span><span class="n">mf</span> <span class="o">=</span> <span class="n">scf</span><span class="o">.</span><span class="n">RHF</span><span class="p">(</span><span class="n">mol</span><span class="p">)</span><span class="o">.</span><span class="n">run</span><span class="p">()</span> <span class="gp">&gt;&gt;&gt; </span><span class="n">ncas</span><span class="p">,</span> <span class="n">nelecas</span><span class="p">,</span> <span class="n">mo</span> <span class="o">=</span> <span class="n">avas</span><span class="o">.</span><span class="n">avas</span><span class="p">(</span><span class="n">mf</span><span class="p">,</span> <span class="p">[</span><span class="s1">&#39;Cr 3d&#39;</span><span class="p">,</span> <span class="s1">&#39;Cr 4s&#39;</span><span class="p">])</span> <span class="gp">&gt;&gt;&gt; </span><span class="n">mc</span> <span class="o">=</span> <span class="n">mcscf</span><span class="o">.</span><span class="n">CASSCF</span><span class="p">(</span><span class="n">mf</span><span class="p">,</span> <span class="n">ncas</span><span class="p">,</span> <span class="n">nelecas</span><span class="p">)</span><span class="o">.</span><span class="n">run</span><span class="p">(</span><span class="n">mo</span><span class="p">)</span> </pre></div> </div> </dd></dl> </div> <div class="section" id="module-pyscf.mcscf.casci"> <span id="pyscf-mcscf-casci-module"></span><h2>pyscf.mcscf.casci module<a class="headerlink" href="#module-pyscf.mcscf.casci" title="Permalink to this headline">¶</a></h2> <dl class="py class"> <dt id="pyscf.mcscf.casci.CASCI"> <em class="property">class </em><code class="sig-prename descclassname">pyscf.mcscf.casci.</code><code class="sig-name descname">CASCI</code><span class="sig-paren">(</span><em class="sig-param"><span class="n">mf_or_mol</span></em>, <em class="sig-param"><span class="n">ncas</span></em>, <em class="sig-param"><span class="n">nelecas</span></em>, <em class="sig-param"><span class="n">ncore</span><span class="o">=</span><span class="default_value">None</span></em><span class="sig-paren">)</span><a class="headerlink" href="#pyscf.mcscf.casci.CASCI" title="Permalink to this definition">¶</a></dt> <dd><p>Bases: <a class="reference internal" href="../pyscf.lib/#pyscf.lib.misc.StreamObject" title="pyscf.lib.misc.StreamObject"><code class="xref py py-class docutils literal notranslate"><span class="pre">pyscf.lib.misc.StreamObject</span></code></a></p> <dl> <dt>Args:</dt><dd><dl class="simple"> <dt>mf_or_mol<span class="classifier">SCF object or Mole object</span></dt><dd><p>SCF or Mole to define the problem size.</p> </dd> <dt>ncas<span class="classifier">int</span></dt><dd><p>Number of active orbitals.</p> </dd> <dt>nelecas<span class="classifier">int or a pair of int</span></dt><dd><p>Number of electrons in active space.</p> </dd> </dl> </dd> <dt>Kwargs:</dt><dd><dl class="simple"> <dt>ncore<span class="classifier">int</span></dt><dd><p>Number of doubly occupied core orbitals. If not presented, this parameter can be automatically determined.</p> </dd> </dl> </dd> <dt>Attributes:</dt><dd><dl> <dt>verbose<span class="classifier">int</span></dt><dd><p>Print level. Default value equals to <code class="xref py py-class docutils literal notranslate"><span class="pre">Mole.verbose</span></code>.</p> </dd> <dt>max_memory<span class="classifier">float or int</span></dt><dd><p>Allowed memory in MB. Default value equals to <code class="xref py py-class docutils literal notranslate"><span class="pre">Mole.max_memory</span></code>.</p> </dd> <dt>ncas<span class="classifier">int</span></dt><dd><p>Active space size.</p> </dd> <dt>nelecas<span class="classifier">tuple of int</span></dt><dd><p>Active (nelec_alpha, nelec_beta)</p> </dd> <dt>ncore<span class="classifier">int or tuple of int</span></dt><dd><p>Core electron number. In UHF-CASSCF, it’s a tuple to indicate the different core eletron numbers.</p> </dd> <dt>natorb<span class="classifier">bool</span></dt><dd><p>Whether to transform natural orbitals in active space. Note: when CASCI/CASSCF are combined with DMRG solver or selected CI solver, enabling this parameter may slightly change the total energy. False by default.</p> </dd> <dt>canonicalization<span class="classifier">bool</span></dt><dd><p>Whether to canonicalize orbitals in core and external space against the general Fock matrix. The orbitals in active space are NOT transformed by default. To get the natural orbitals in active space, the attribute .natorb needs to be enabled. True by default.</p> </dd> <dt>sorting_mo_energy<span class="classifier">bool</span></dt><dd><p>Whether to sort the orbitals based on the diagonal elements of the general Fock matrix. Default is False.</p> </dd> <dt>fcisolver<span class="classifier">an instance of <code class="xref py py-class docutils literal notranslate"><span class="pre">FCISolver</span></code></span></dt><dd><p>The pyscf.fci module provides several FCISolver for different scenario. Generally, fci.direct_spin1.FCISolver can be used for all RHF-CASSCF. However, a proper FCISolver can provide better performance and better numerical stability. One can either use <code class="xref py py-func docutils literal notranslate"><span class="pre">fci.solver()</span></code> function to pick the FCISolver by the program or manually assigen the FCISolver to this attribute, e.g.</p> <div class="doctest highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">from</span> <span class="nn">pyscf</span> <span class="kn">import</span> <span class="n">fci</span> <span class="gp">&gt;&gt;&gt; </span><span class="n">mc</span> <span class="o">=</span> <span class="n">mcscf</span><span class="o">.</span><span class="n">CASSCF</span><span class="p">(</span><span class="n">mf</span><span class="p">,</span> <span class="mi">4</span><span class="p">,</span> <span class="mi">4</span><span class="p">)</span> <span class="gp">&gt;&gt;&gt; </span><span class="n">mc</span><span class="o">.</span><span class="n">fcisolver</span> <span class="o">=</span> <span class="n">fci</span><span class="o">.</span><span class="n">solver</span><span class="p">(</span><span class="n">mol</span><span class="p">,</span> <span class="n">singlet</span><span class="o">=</span><span class="kc">True</span><span class="p">)</span> <span class="gp">&gt;&gt;&gt; </span><span class="n">mc</span><span class="o">.</span><span class="n">fcisolver</span> <span class="o">=</span> <span class="n">fci</span><span class="o">.</span><span class="n">direct_spin1</span><span class="o">.</span><span class="n">FCISolver</span><span class="p">(</span><span class="n">mol</span><span class="p">)</span> </pre></div> </div> <p>You can control FCISolver by setting e.g.:</p> <div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">mc</span><span class="o">.</span><span class="n">fcisolver</span><span class="o">.</span><span class="n">max_cycle</span> <span class="o">=</span> <span class="mi">30</span> <span class="gp">&gt;&gt;&gt; </span><span class="n">mc</span><span class="o">.</span><span class="n">fcisolver</span><span class="o">.</span><span class="n">conv_tol</span> <span class="o">=</span> <span class="mf">1e-7</span> </pre></div> </div> <p>For more details of the parameter for FCISolver, See <code class="xref py py-mod docutils literal notranslate"><span class="pre">fci</span></code>.</p> </dd> </dl> </dd> </dl> <p>Saved results</p> <blockquote> <div><dl class="simple"> <dt>e_tot<span class="classifier">float</span></dt><dd><p>Total MCSCF energy (electronic energy plus nuclear repulsion)</p> </dd> <dt>e_cas<span class="classifier">float</span></dt><dd><p>CAS space FCI energy</p> </dd> <dt>ci<span class="classifier">ndarray</span></dt><dd><p>CAS space FCI coefficients</p> </dd> <dt>mo_coeff<span class="classifier">ndarray</span></dt><dd><p>When canonicalization is specified, the orbitals are canonical orbitals which make the general Fock matrix (Fock operator on top of MCSCF 1-particle density matrix) diagonalized within each subspace (core, active, external). If natorb (natural orbitals in active space) is specified, the active segment of the mo_coeff is natural orbitls.</p> </dd> <dt>mo_energy<span class="classifier">ndarray</span></dt><dd><p>Diagonal elements of general Fock matrix (in mo_coeff representation).</p> </dd> <dt>mo_occ<span class="classifier">ndarray</span></dt><dd><p>Occupation numbers of natural orbitals if natorb is specified.</p> </dd> </dl> </div></blockquote> <p>Examples:</p> <div class="doctest highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">from</span> <span class="nn">pyscf</span> <span class="kn">import</span> <span class="n">gto</span><span class="p">,</span> <span class="n">scf</span><span class="p">,</span> <span class="n">mcscf</span> <span class="gp">&gt;&gt;&gt; </span><span class="n">mol</span> <span class="o">=</span> <span class="n">gto</span><span class="o">.</span><span class="n">M</span><span class="p">(</span><span class="n">atom</span><span class="o">=</span><span class="s1">&#39;N 0 0 0; N 0 0 1&#39;</span><span class="p">,</span> <span class="n">basis</span><span class="o">=</span><span class="s1">&#39;ccpvdz&#39;</span><span class="p">,</span> <span class="n">verbose</span><span class="o">=</span><span class="mi">0</span><span class="p">)</span> <span class="gp">&gt;&gt;&gt; </span><span class="n">mf</span> <span class="o">=</span> <span class="n">scf</span><span class="o">.</span><span class="n">RHF</span><span class="p">(</span><span class="n">mol</span><span class="p">)</span> <span class="gp">&gt;&gt;&gt; </span><span class="n">mf</span><span class="o">.</span><span class="n">scf</span><span class="p">()</span> <span class="gp">&gt;&gt;&gt; </span><span class="n">mc</span> <span class="o">=</span> <span class="n">mcscf</span><span class="o">.</span><span class="n">CASCI</span><span class="p">(</span><span class="n">mf</span><span class="p">,</span> <span class="mi">6</span><span class="p">,</span> <span class="mi">6</span><span class="p">)</span> <span class="gp">&gt;&gt;&gt; </span><span class="n">mc</span><span class="o">.</span><span class="n">kernel</span><span class="p">()[</span><span class="mi">0</span><span class="p">]</span> <span class="go">-108.980200816243354</span> </pre></div> </div> <dl class="py method"> <dt id="pyscf.mcscf.casci.CASCI.Gradients"> <code class="sig-name descname">Gradients</code><span class="sig-paren">(</span><em class="sig-param"><span class="o">*</span><span class="n">args</span></em>, <em class="sig-param"><span class="o">**</span><span class="n">kwargs</span></em><span class="sig-paren">)</span><a class="headerlink" href="#pyscf.mcscf.casci.CASCI.Gradients" title="Permalink to this definition">¶</a></dt> <dd><p>Non-relativistic restricted Hartree-Fock gradients</p> </dd></dl> <dl class="py method"> <dt id="pyscf.mcscf.casci.CASCI.analyze"> <code class="sig-name descname">analyze</code><span class="sig-paren">(</span><em class="sig-param"><span class="n">mo_coeff</span><span class="o">=</span><span class="default_value">None</span></em>, <em class="sig-param"><span class="n">ci</span><span class="o">=</span><span class="default_value">None</span></em>, <em class="sig-param"><span class="n">verbose</span><span class="o">=</span><span class="default_value">None</span></em>, <em class="sig-param"><span class="n">large_ci_tol</span><span class="o">=</span><span class="default_value">0.1</span></em>, <em class="sig-param"><span class="n">with_meta_lowdin</span><span class="o">=</span><span class="default_value">True</span></em>, <em class="sig-param"><span class="o">**</span><span class="n">kwargs</span></em><span class="sig-paren">)</span><a class="headerlink" href="#pyscf.mcscf.casci.CASCI.analyze" title="Permalink to this definition">¶</a></dt> <dd></dd></dl> <dl class="py method"> <dt id="pyscf.mcscf.casci.CASCI.ao2mo"> <code class="sig-name descname">ao2mo</code><span class="sig-paren">(</span><em class="sig-param"><span class="n">mo_coeff</span><span class="o">=</span><span class="default_value">None</span></em><span class="sig-paren">)</span><a class="headerlink" href="#pyscf.mcscf.casci.CASCI.ao2mo" title="Permalink to this definition">¶</a></dt> <dd><p>Compute the active space two-particle Hamiltonian.</p> </dd></dl> <dl class="py method"> <dt id="pyscf.mcscf.casci.CASCI.as_scanner"> <code class="sig-name descname">as_scanner</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#pyscf.mcscf.casci.CASCI.as_scanner" title="Permalink to this definition">¶</a></dt> <dd><p>Generating a scanner for CASCI PES.</p> <p>The returned solver is a function. This function requires one argument “mol” as input and returns total CASCI energy.</p> <p>The solver will automatically use the results of last calculation as the initial guess of the new calculation. All parameters of MCSCF object are automatically applied in the solver.</p> <p>Note scanner has side effects. It may change many underlying objects (_scf, with_df, with_x2c, …) during calculation.</p> <p>Examples:</p> <div class="doctest highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">from</span> <span class="nn">pyscf</span> <span class="kn">import</span> <span class="n">gto</span><span class="p">,</span> <span class="n">scf</span><span class="p">,</span> <span class="n">mcscf</span> <span class="gp">&gt;&gt;&gt; </span><span class="n">mf</span> <span class="o">=</span> <span class="n">scf</span><span class="o">.</span><span class="n">RHF</span><span class="p">(</span><span class="n">gto</span><span class="o">.</span><span class="n">Mole</span><span class="p">()</span><span class="o">.</span><span class="n">set</span><span class="p">(</span><span class="n">verbose</span><span class="o">=</span><span class="mi">0</span><span class="p">))</span> <span class="gp">&gt;&gt;&gt; </span><span class="n">mc_scanner</span> <span class="o">=</span> <span class="n">mcscf</span><span class="o">.</span><span class="n">CASCI</span><span class="p">(</span><span class="n">mf</span><span class="p">,</span> <span class="mi">4</span><span class="p">,</span> <span class="mi">4</span><span class="p">)</span><span class="o">.</span><span class="n">as_scanner</span><span class="p">()</span> <span class="gp">&gt;&gt;&gt; </span><span class="n">mc_scanner</span><span class="p">(</span><span class="n">gto</span><span class="o">.</span><span class="n">M</span><span class="p">(</span><span class="n">atom</span><span class="o">=</span><span class="s1">&#39;N 0 0 0; N 0 0 1.1&#39;</span><span class="p">))</span> <span class="gp">&gt;&gt;&gt; </span><span class="n">mc_scanner</span><span class="p">(</span><span class="n">gto</span><span class="o">.</span><span class="n">M</span><span class="p">(</span><span class="n">atom</span><span class="o">=</span><span class="s1">&#39;N 0 0 0; N 0 0 1.5&#39;</span><span class="p">))</span> </pre></div> </div> </dd></dl> <dl class="py attribute"> <dt id="pyscf.mcscf.casci.CASCI.canonicalization"> <code class="sig-name descname">canonicalization</code><em class="property"> = True</em><a class="headerlink" href="#pyscf.mcscf.casci.CASCI.canonicalization" title="Permalink to this definition">¶</a></dt> <dd></dd></dl> <dl class="py method"> <dt id="pyscf.mcscf.casci.CASCI.canonicalize"> <code class="sig-name descname">canonicalize</code><span class="sig-paren">(</span><em class="sig-param"><span class="n">mo_coeff</span><span class="o">=</span><span class="default_value">None</span></em>, <em class="sig-param"><span class="n">ci</span><span class="o">=</span><span class="default_value">None</span></em>, <em class="sig-param"><span class="n">eris</span><span class="o">=</span><span class="default_value">None</span></em>, <em class="sig-param"><span class="n">sort</span><span class="o">=</span><span class="default_value">False</span></em>, <em class="sig-param"><span class="n">cas_natorb</span><span class="o">=</span><span class="default_value">False</span></em>, <em class="sig-param"><span class="n">casdm1</span><span class="o">=</span><span class="default_value">None</span></em>, <em class="sig-param"><span class="n">verbose</span><span class="o">=</span><span class="default_value">3</span></em>, <em class="sig-param"><span class="n">with_meta_lowdin</span><span class="o">=</span><span class="default_value">True</span></em><span class="sig-paren">)</span><a class="headerlink" href="#pyscf.mcscf.casci.CASCI.canonicalize" title="Permalink to this definition">¶</a></dt> <dd><p>Canonicalized CASCI/CASSCF orbitals of effecitive Fock matrix and update CI coefficients accordingly.</p> <p>Effective Fock matrix is built with one-particle density matrix (see also <code class="xref py py-func docutils literal notranslate"><span class="pre">mcscf.casci.get_fock()</span></code>). For state-average CASCI/CASSCF object, the canonicalized orbitals are based on the state-average density matrix. To obtain canonicalized orbitals for an individual state, you need to pass “casdm1” of the specific state to this function.</p> <dl class="simple"> <dt>Args:</dt><dd><p>mc: a CASSCF/CASCI object or RHF object</p> </dd> <dt>Kwargs:</dt><dd><dl class="simple"> <dt>mo_coeff (ndarray): orbitals that span the core, active and external</dt><dd><p>space.</p> </dd> <dt>ci (ndarray): CI coefficients (or objects to represent the CI</dt><dd><p>wavefunctions in DMRG/QMC-MCSCF calculations).</p> </dd> <dt>eris: Integrals for the MCSCF object. Input this object to reduce the</dt><dd><p>overhead of computing integrals. It can be generated by <code class="xref py py-func docutils literal notranslate"><span class="pre">mc.ao2mo()</span></code> method.</p> </dd> <dt>sort (bool): Whether the canonicalized orbitals are sorted based on</dt><dd><p>the orbital energy (diagonal part of the effective Fock matrix) within each subspace (core, active, external). If point group symmetry is not available in the system, orbitals are always sorted. When point group symmetry is available, sort=False will preserve the symmetry label of input orbitals and only sort the orbitals in each symmetry sector. sort=True will reorder all orbitals over all symmetry sectors in each subspace and the symmetry labels may be changed.</p> </dd> <dt>cas_natorb (bool): Whether to transform active orbitals to natual</dt><dd><p>orbitals. If enabled, the output orbitals in active space are transformed to natural orbitals and CI coefficients are updated accordingly.</p> </dd> <dt>casdm1 (ndarray): 1-particle density matrix in active space. This</dt><dd><p>density matrix is used to build effective fock matrix. Without input casdm1, the density matrix is computed with the input ci coefficients/object. If neither ci nor casdm1 were given, density matrix is computed by <code class="xref py py-func docutils literal notranslate"><span class="pre">mc.fcisolver.make_rdm1()</span></code> method. For state-average CASCI/CASCF calculation, this results in a set of canonicalized orbitals of state-average effective Fock matrix. To canonicalize the orbitals for one particular state, you can assign the density matrix of that state to the kwarg casdm1.</p> </dd> </dl> </dd> <dt>Returns:</dt><dd><p>A tuple, (natural orbitals, CI coefficients, orbital energies) The orbital energies are the diagonal terms of effective Fock matrix.</p> </dd> </dl> </dd></dl> <dl class="py method"> <dt id="pyscf.mcscf.casci.CASCI.canonicalize_"> <code class="sig-name descname">canonicalize_</code><span class="sig-paren">(</span><em class="sig-param"><span class="n">mo_coeff</span><span class="o">=</span><span class="default_value">None</span></em>, <em class="sig-param"><span class="n">ci</span><span class="o">=</span><span class="default_value">None</span></em>, <em class="sig-param"><span class="n">eris</span><span class="o">=</span><span class="default_value">None</span></em>, <em class="sig-param"><span class="n">sort</span><span class="o">=</span><span class="default_value">False</span></em>, <em class="sig-param"><span class="n">cas_natorb</span><span class="o">=</span><span class="default_value">False</span></em>, <em class="sig-param"><span class="n">casdm1</span><span class="o">=</span><span class="default_value">None</span></em>, <em class="sig-param"><span class="n">verbose</span><span class="o">=</span><span class="default_value">None</span></em>, <em class="sig-param"><span class="n">with_meta_lowdin</span><span class="o">=</span><span class="default_value">True</span></em><span class="sig-paren">)</span><a class="headerlink" href="#pyscf.mcscf.casci.CASCI.canonicalize_" title="Permalink to this definition">¶</a></dt> <dd><p>Canonicalized CASCI/CASSCF orbitals of effecitive Fock matrix and update CI coefficients accordingly.</p> <p>Effective Fock matrix is built with one-particle density matrix (see also <code class="xref py py-func docutils literal notranslate"><span class="pre">mcscf.casci.get_fock()</span></code>). For state-average CASCI/CASSCF object, the canonicalized orbitals are based on the state-average density matrix. To obtain canonicalized orbitals for an individual state, you need to pass “casdm1” of the specific state to this function.</p> <dl class="simple"> <dt>Args:</dt><dd><p>mc: a CASSCF/CASCI object or RHF object</p> </dd> <dt>Kwargs:</dt><dd><dl class="simple"> <dt>mo_coeff (ndarray): orbitals that span the core, active and external</dt><dd><p>space.</p> </dd> <dt>ci (ndarray): CI coefficients (or objects to represent the CI</dt><dd><p>wavefunctions in DMRG/QMC-MCSCF calculations).</p> </dd> <dt>eris: Integrals for the MCSCF object. Input this object to reduce the</dt><dd><p>overhead of computing integrals. It can be generated by <code class="xref py py-func docutils literal notranslate"><span class="pre">mc.ao2mo()</span></code> method.</p> </dd> <dt>sort (bool): Whether the canonicalized orbitals are sorted based on</dt><dd><p>the orbital energy (diagonal part of the effective Fock matrix) within each subspace (core, active, external). If point group symmetry is not available in the system, orbitals are always sorted. When point group symmetry is available, sort=False will preserve the symmetry label of input orbitals and only sort the orbitals in each symmetry sector. sort=True will reorder all orbitals over all symmetry sectors in each subspace and the symmetry labels may be changed.</p> </dd> <dt>cas_natorb (bool): Whether to transform active orbitals to natual</dt><dd><p>orbitals. If enabled, the output orbitals in active space are transformed to natural orbitals and CI coefficients are updated accordingly.</p> </dd> <dt>casdm1 (ndarray): 1-particle density matrix in active space. This</dt><dd><p>density matrix is used to build effective fock matrix. Without input casdm1, the density matrix is computed with the input ci coefficients/object. If neither ci nor casdm1 were given, density matrix is computed by <code class="xref py py-func docutils literal notranslate"><span class="pre">mc.fcisolver.make_rdm1()</span></code> method. For state-average CASCI/CASCF calculation, this results in a set of canonicalized orbitals of state-average effective Fock matrix. To canonicalize the orbitals for one particular state, you can assign the density matrix of that state to the kwarg casdm1.</p> </dd> </dl> </dd> <dt>Returns:</dt><dd><p>A tuple, (natural orbitals, CI coefficients, orbital energies) The orbital energies are the diagonal terms of effective Fock matrix.</p> </dd> </dl> </dd></dl> <dl class="py method"> <dt id="pyscf.mcscf.casci.CASCI.cas_natorb"> <code class="sig-name descname">cas_natorb</code><span class="sig-paren">(</span><em class="sig-param"><span class="n">mo_coeff</span><span class="o">=</span><span class="default_value">None</span></em>, <em class="sig-param"><span class="n">ci</span><span class="o">=</span><span class="default_value">None</span></em>, <em class="sig-param"><span class="n">eris</span><span class="o">=</span><span class="default_value">None</span></em>, <em class="sig-param"><span class="n">sort</span><span class="o">=</span><span class="default_value">False</span></em>, <em class="sig-param"><span class="n">casdm1</span><span class="o">=</span><span class="default_value">None</span></em>, <em class="sig-param"><span class="n">verbose</span><span class="o">=</span><span class="default_value">None</span></em>, <em class="sig-param"><span class="n">with_meta_lowdin</span><span class="o">=</span><span class="default_value">True</span></em><span class="sig-paren">)</span><a class="headerlink" href="#pyscf.mcscf.casci.CASCI.cas_natorb" title="Permalink to this definition">¶</a></dt> <dd><p>Transform active orbitals to natrual orbitals, and update the CI wfn accordingly</p> <dl class="simple"> <dt>Args:</dt><dd><p>mc : a CASSCF/CASCI object or RHF object</p> </dd> <dt>Kwargs:</dt><dd><dl class="simple"> <dt>sort<span class="classifier">bool</span></dt><dd><p>Sort natural orbitals wrt the occupancy.</p> </dd> </dl> </dd> <dt>Returns:</dt><dd><p>A tuple, the first item is natural orbitals, the second is updated CI coefficients, the third is the natural occupancy associated to the natural orbitals.</p> </dd> </dl> </dd></dl> <dl class="py method"> <dt id="pyscf.mcscf.casci.CASCI.cas_natorb_"> <code class="sig-name descname">cas_natorb_</code><span class="sig-paren">(</span><em class="sig-param"><span class="n">mo_coeff</span><span class="o">=</span><span class="default_value">None</span></em>, <em class="sig-param"><span class="n">ci</span><span class="o">=</span><span class="default_value">None</span></em>, <em class="sig-param"><span class="n">eris</span><span class="o">=</span><span class="default_value">None</span></em>, <em class="sig-param"><span class="n">sort</span><span class="o">=</span><span class="default_value">False</span></em>, <em class="sig-param"><span class="n">casdm1</span><span class="o">=</span><span class="default_value">None</span></em>, <em class="sig-param"><span class="n">verbose</span><span class="o">=</span><span class="default_value">None</span></em>, <em class="sig-param"><span class="n">with_meta_lowdin</span><span class="o">=</span><span class="default_value">True</span></em><span class="sig-paren">)</span><a class="headerlink" href="#pyscf.mcscf.casci.CASCI.cas_natorb_" title="Permalink to this definition">¶</a></dt> <dd><p>Transform active orbitals to natrual orbitals, and update the CI wfn accordingly</p> <dl class="simple"> <dt>Args:</dt><dd><p>mc : a CASSCF/CASCI object or RHF object</p> </dd> <dt>Kwargs:</dt><dd><dl class="simple"> <dt>sort<span class="classifier">bool</span></dt><dd><p>Sort natural orbitals wrt the occupancy.</p> </dd> </dl> </dd> <dt>Returns:</dt><dd><p>A tuple, the first item is natural orbitals, the second is updated CI coefficients, the third is the natural occupancy associated to the natural orbitals.</p> </dd> </dl> </dd></dl> <dl class="py method"> <dt id="pyscf.mcscf.casci.CASCI.casci"> <code class="sig-name descname">casci</code><span class="sig-paren">(</span><em class="sig-param"><span class="n">mo_coeff</span><span class="o">=</span><span class="default_value">None</span></em>, <em class="sig-param"><span class="n">ci0</span><span class="o">=</span><span class="default_value">None</span></em>, <em class="sig-param"><span class="n">verbose</span><span class="o">=</span><span class="default_value">None</span></em><span class="sig-paren">)</span><a class="headerlink" href="#pyscf.mcscf.casci.CASCI.casci" title="Permalink to this definition">¶</a></dt> <dd></dd></dl> <dl class="py method"> <dt id="pyscf.mcscf.casci.CASCI.density_fit"> <code class="sig-name descname">density_fit</code><span class="sig-paren">(</span><em class="sig-param"><span class="n">auxbasis</span><span class="o">=</span><span class="default_value">None</span></em>, <em class="sig-param"><span class="n">with_df</span><span class="o">=</span><span class="default_value">None</span></em><span class="sig-paren">)</span><a class="headerlink" href="#pyscf.mcscf.casci.CASCI.density_fit" title="Permalink to this definition">¶</a></dt> <dd></dd></dl> <dl class="py method"> <dt id="pyscf.mcscf.casci.CASCI.dump_flags"> <code class="sig-name descname">dump_flags</code><span class="sig-paren">(</span><em class="sig-param"><span class="n">verbose</span><span class="o">=</span><span class="default_value">None</span></em><span class="sig-paren">)</span><a class="headerlink" href="#pyscf.mcscf.casci.CASCI.dump_flags" title="Permalink to this definition">¶</a></dt> <dd></dd></dl> <dl class="py method"> <dt id="pyscf.mcscf.casci.CASCI.energy_nuc"> <code class="sig-name descname">energy_nuc</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#pyscf.mcscf.casci.CASCI.energy_nuc" title="Permalink to this definition">¶</a></dt> <dd></dd></dl> <dl class="py method"> <dt id="pyscf.mcscf.casci.CASCI.fix_spin"> <code class="sig-name descname">fix_spin</code><span class="sig-paren">(</span><em class="sig-param"><span class="n">shift</span><span class="o">=</span><span class="default_value">0.2</span></em>, <em class="sig-param"><span class="n">ss</span><span class="o">=</span><span class="default_value">None</span></em><span class="sig-paren">)</span><a class="headerlink" href="#pyscf.mcscf.casci.CASCI.fix_spin" title="Permalink to this definition">¶</a></dt> <dd><p>Use level shift to control FCI solver spin.</p> <div class="math notranslate nohighlight"> \[(H + shift*S^2) |\Psi\rangle = E |\Psi\rangle\]</div> <dl class="simple"> <dt>Kwargs:</dt><dd><dl class="simple"> <dt>shift<span class="classifier">float</span></dt><dd><p>Energy penalty for states which have wrong spin</p> </dd> <dt>ss<span class="classifier">number</span></dt><dd><p>S^2 expection value == s*(s+1)</p> </dd> </dl> </dd> </dl> </dd></dl> <dl class="py method"> <dt id="pyscf.mcscf.casci.CASCI.fix_spin_"> <code class="sig-name descname">fix_spin_</code><span class="sig-paren">(</span><em class="sig-param"><span class="n">shift</span><span class="o">=</span><span class="default_value">0.2</span></em>, <em class="sig-param"><span class="n">ss</span><span class="o">=</span><span class="default_value">None</span></em><span class="sig-paren">)</span><a class="headerlink" href="#pyscf.mcscf.casci.CASCI.fix_spin_" title="Permalink to this definition">¶</a></dt> <dd><p>Use level shift to control FCI solver spin.</p> <div class="math notranslate nohighlight"> \[(H + shift*S^2) |\Psi\rangle = E |\Psi\rangle\]</div> <dl class="simple"> <dt>Kwargs:</dt><dd><dl class="simple"> <dt>shift<span class="classifier">float</span></dt><dd><p>Energy penalty for states which have wrong spin</p> </dd> <dt>ss<span class="classifier">number</span></dt><dd><p>S^2 expection value == s*(s+1)</p> </dd> </dl> </dd> </dl> </dd></dl> <dl class="py method"> <dt id="pyscf.mcscf.casci.CASCI.get_fock"> <code class="sig-name descname">get_fock</code><span class="sig-paren">(</span><em class="sig-param"><span class="n">mo_coeff</span><span class="o">=</span><span class="default_value">None</span></em>, <em class="sig-param"><span class="n">ci</span><span class="o">=</span><span class="default_value">None</span></em>, <em class="sig-param"><span class="n">eris</span><span class="o">=</span><span class="default_value">None</span></em>, <em class="sig-param"><span class="n">casdm1</span><span class="o">=</span><span class="default_value">None</span></em>, <em class="sig-param"><span class="n">verbose</span><span class="o">=</span><span class="default_value">None</span></em><span class="sig-paren">)</span><a class="headerlink" href="#pyscf.mcscf.casci.CASCI.get_fock" title="Permalink to this definition">¶</a></dt> <dd></dd></dl> <dl class="py method"> <dt id="pyscf.mcscf.casci.CASCI.get_h1cas"> <code class="sig-name descname">get_h1cas</code><span class="sig-paren">(</span><em class="sig-param"><span class="n">mo_coeff</span><span class="o">=</span><span class="default_value">None</span></em>, <em class="sig-param"><span class="n">ncas</span><span class="o">=</span><span class="default_value">None</span></em>, <em class="sig-param"><span class="n">ncore</span><span class="o">=</span><span class="default_value">None</span></em><span class="sig-paren">)</span><a class="headerlink" href="#pyscf.mcscf.casci.CASCI.get_h1cas" title="Permalink to this definition">¶</a></dt> <dd><p>CAS sapce one-electron hamiltonian</p> <dl class="simple"> <dt>Args:</dt><dd><p>casci : a CASSCF/CASCI object or RHF object</p> </dd> <dt>Returns:</dt><dd><p>A tuple, the first is the effective one-electron hamiltonian defined in CAS space, the second is the electronic energy from core.</p> </dd> </dl> </dd></dl> <dl class="py method"> <dt id="pyscf.mcscf.casci.CASCI.get_h1eff"> <code class="sig-name descname">get_h1eff</code><span class="sig-paren">(</span><em class="sig-param"><span class="n">mo_coeff</span><span class="o">=</span><span class="default_value">None</span></em>, <em class="sig-param"><span class="n">ncas</span><span class="o">=</span><span class="default_value">None</span></em>, <em class="sig-param"><span class="n">ncore</span><span class="o">=</span><span class="default_value">None</span></em><span class="sig-paren">)</span><a class="headerlink" href="#pyscf.mcscf.casci.CASCI.get_h1eff" title="Permalink to this definition">¶</a></dt> <dd><p>CAS sapce one-electron hamiltonian</p> <dl class="simple"> <dt>Args:</dt><dd><p>casci : a CASSCF/CASCI object or RHF object</p> </dd> <dt>Returns:</dt><dd><p>A tuple, the first is the effective one-electron hamiltonian defined in CAS space, the second is the electronic energy from core.</p> </dd> </dl> </dd></dl> <dl class="py method"> <dt id="pyscf.mcscf.casci.CASCI.get_h2cas"> <code class="sig-name descname">get_h2cas</code><span class="sig-paren">(</span><em class="sig-param"><span class="n">mo_coeff</span><span class="o">=</span><span class="default_value">None</span></em><span class="sig-paren">)</span><a class="headerlink" href="#pyscf.mcscf.casci.CASCI.get_h2cas" title="Permalink to this definition">¶</a></dt> <dd><p>Compute the active space two-particle Hamiltonian.</p> <p>Note It is different to get_h2eff when df.approx_hessian is applied, in which get_h2eff function returns the DF integrals while get_h2cas returns the regular 2-electron integrals.</p> </dd></dl> <dl class="py method"> <dt id="pyscf.mcscf.casci.CASCI.get_h2eff"> <code class="sig-name descname">get_h2eff</code><span class="sig-paren">(</span><em class="sig-param"><span class="n">mo_coeff</span><span class="o">=</span><span class="default_value">None</span></em><span class="sig-paren">)</span><a class="headerlink" href="#pyscf.mcscf.casci.CASCI.get_h2eff" title="Permalink to this definition">¶</a></dt> <dd><p>Compute the active space two-particle Hamiltonian.</p> <p>Note It is different to get_h2cas when df.approx_hessian is applied. in which get_h2eff function returns the DF integrals while get_h2cas returns the regular 2-electron integrals.</p> </dd></dl> <dl class="py method"> <dt id="pyscf.mcscf.casci.CASCI.get_hcore"> <code class="sig-name descname">get_hcore</code><span class="sig-paren">(</span><em class="sig-param"><span class="n">mol</span><span class="o">=</span><span class="default_value">None</span></em><span class="sig-paren">)</span><a class="headerlink" href="#pyscf.mcscf.casci.CASCI.get_hcore" title="Permalink to this definition">¶</a></dt> <dd></dd></dl> <dl class="py method"> <dt id="pyscf.mcscf.casci.CASCI.get_jk"> <code class="sig-name descname">get_jk</code><span class="sig-paren">(</span><em class="sig-param"><span class="n">mol</span></em>, <em class="sig-param"><span class="n">dm</span></em>, <em class="sig-param"><span class="n">hermi</span><span class="o">=</span><span class="default_value">1</span></em>, <em class="sig-param"><span class="n">with_j</span><span class="o">=</span><span class="default_value">True</span></em>, <em class="sig-param"><span class="n">with_k</span><span class="o">=</span><span class="default_value">True</span></em>, <em class="sig-param"><span class="n">omega</span><span class="o">=</span><span class="default_value">None</span></em><span class="sig-paren">)</span><a class="headerlink" href="#pyscf.mcscf.casci.CASCI.get_jk" title="Permalink to this definition">¶</a></dt> <dd><p>Compute J, K matrices for all input density matrices</p> <dl> <dt>Args:</dt><dd><p>mol : an instance of <code class="xref py py-class docutils literal notranslate"><span class="pre">Mole</span></code></p> <dl class="simple"> <dt>dm<span class="classifier">ndarray or list of ndarrays</span></dt><dd><p>A density matrix or a list of density matrices</p> </dd> </dl> </dd> <dt>Kwargs:</dt><dd><dl> <dt>hermi<span class="classifier">int</span></dt><dd><p>Whether J, K matrix is hermitian</p> <div class="line-block"> <div class="line">0 : not hermitian and not symmetric</div> <div class="line">1 : hermitian or symmetric</div> <div class="line">2 : anti-hermitian</div> </div> </dd> <dt>vhfopt :</dt><dd><p>A class which holds precomputed quantities to optimize the computation of J, K matrices</p> </dd> <dt>with_j<span class="classifier">boolean</span></dt><dd><p>Whether to compute J matrices</p> </dd> <dt>with_k<span class="classifier">boolean</span></dt><dd><p>Whether to compute K matrices</p> </dd> <dt>omega<span class="classifier">float</span></dt><dd><p>Parameter of range-seperated Coulomb operator: erf( omega * r12 ) / r12. If specified, integration are evaluated based on the long-range part of the range-seperated Coulomb operator.</p> </dd> </dl> </dd> <dt>Returns:</dt><dd><p>Depending on the given dm, the function returns one J and one K matrix, or a list of J matrices and a list of K matrices, corresponding to the input density matrices.</p> </dd> </dl> <p>Examples:</p> <div class="doctest highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">from</span> <span class="nn">pyscf</span> <span class="kn">import</span> <span class="n">gto</span><span class="p">,</span> <span class="n">scf</span> <span class="gp">&gt;&gt;&gt; </span><span class="kn">from</span> <span class="nn">pyscf.scf</span> <span class="kn">import</span> <span class="n">_vhf</span> <span class="gp">&gt;&gt;&gt; </span><span class="n">mol</span> <span class="o">=</span> <span class="n">gto</span><span class="o">.</span><span class="n">M</span><span class="p">(</span><span class="n">atom</span><span class="o">=</span><span class="s1">&#39;H 0 0 0; H 0 0 1.1&#39;</span><span class="p">)</span> <span class="gp">&gt;&gt;&gt; </span><span class="n">dms</span> <span class="o">=</span> <span class="n">numpy</span><span class="o">.</span><span class="n">random</span><span class="o">.</span><span class="n">random</span><span class="p">((</span><span class="mi">3</span><span class="p">,</span><span class="n">mol</span><span class="o">.</span><span class="n">nao_nr</span><span class="p">(),</span><span class="n">mol</span><span class="o">.</span><span class="n">nao_nr</span><span class="p">()))</span> <span class="gp">&gt;&gt;&gt; </span><span class="n">j</span><span class="p">,</span> <span class="n">k</span> <span class="o">=</span> <span class="n">scf</span><span class="o">.</span><span class="n">hf</span><span class="o">.</span><span class="n">get_jk</span><span class="p">(</span><span class="n">mol</span><span class="p">,</span> <span class="n">dms</span><span class="p">,</span> <span class="n">hermi</span><span class="o">=</span><span class="mi">0</span><span class="p">)</span> <span class="gp">&gt;&gt;&gt; </span><span class="nb">print</span><span class="p">(</span><span class="n">j</span><span class="o">.</span><span class="n">shape</span><span class="p">)</span> <span class="go">(3, 2, 2)</span> </pre></div> </div> </dd></dl> <dl class="py method"> <dt id="pyscf.mcscf.casci.CASCI.get_veff"> <code class="sig-name descname">get_veff</code><span class="sig-paren">(</span><em class="sig-param"><span class="n">mol</span><span class="o">=</span><span class="default_value">None</span></em>, <em class="sig-param"><span class="n">dm</span><span class="o">=</span><span class="default_value">None</span></em>, <em class="sig-param"><span class="n">hermi</span><span class="o">=</span><span class="default_value">1</span></em><span class="sig-paren">)</span><a class="headerlink" href="#pyscf.mcscf.casci.CASCI.get_veff" title="Permalink to this definition">¶</a></dt> <dd><p>Hartree-Fock potential matrix for the given density matrix</p> <dl> <dt>Args:</dt><dd><p>mol : an instance of <code class="xref py py-class docutils literal notranslate"><span class="pre">Mole</span></code></p> <dl class="simple"> <dt>dm<span class="classifier">ndarray or list of ndarrays</span></dt><dd><p>A density matrix or a list of density matrices</p> </dd> </dl> </dd> <dt>Kwargs:</dt><dd><dl> <dt>dm_last<span class="classifier">ndarray or a list of ndarrays or 0</span></dt><dd><p>The density matrix baseline. If not 0, this function computes the increment of HF potential w.r.t. the reference HF potential matrix.</p> </dd> <dt>vhf_last<span class="classifier">ndarray or a list of ndarrays or 0</span></dt><dd><p>The reference HF potential matrix.</p> </dd> <dt>hermi<span class="classifier">int</span></dt><dd><p>Whether J, K matrix is hermitian</p> <div class="line-block"> <div class="line">0 : no hermitian or symmetric</div> <div class="line">1 : hermitian</div> <div class="line">2 : anti-hermitian</div> </div> </dd> <dt>vhfopt :</dt><dd><p>A class which holds precomputed quantities to optimize the computation of J, K matrices</p> </dd> </dl> </dd> <dt>Returns:</dt><dd><p>matrix Vhf = 2*J - K. Vhf can be a list matrices, corresponding to the input density matrices.</p> </dd> </dl> <p>Examples:</p> <div class="doctest highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">import</span> <span class="nn">numpy</span> <span class="gp">&gt;&gt;&gt; </span><span class="kn">from</span> <span class="nn">pyscf</span> <span class="kn">import</span> <span class="n">gto</span><span class="p">,</span> <span class="n">scf</span> <span class="gp">&gt;&gt;&gt; </span><span class="kn">from</span> <span class="nn">pyscf.scf</span> <span class="kn">import</span> <span class="n">_vhf</span> <span class="gp">&gt;&gt;&gt; </span><span class="n">mol</span> <span class="o">=</span> <span class="n">gto</span><span class="o">.</span><span class="n">M</span><span class="p">(</span><span class="n">atom</span><span class="o">=</span><span class="s1">&#39;H 0 0 0; H 0 0 1.1&#39;</span><span class="p">)</span> <span class="gp">&gt;&gt;&gt; </span><span class="n">dm0</span> <span class="o">=</span> <span class="n">numpy</span><span class="o">.</span><span class="n">random</span><span class="o">.</span><span class="n">random</span><span class="p">((</span><span class="n">mol</span><span class="o">.</span><span class="n">nao_nr</span><span class="p">(),</span><span class="n">mol</span><span class="o">.</span><span class="n">nao_nr</span><span class="p">()))</span> <span class="gp">&gt;&gt;&gt; </span><span class="n">vhf0</span> <span class="o">=</span> <span class="n">scf</span><span class="o">.</span><span class="n">hf</span><span class="o">.</span><span class="n">get_veff</span><span class="p">(</span><span class="n">mol</span><span class="p">,</span> <span class="n">dm0</span><span class="p">,</span> <span class="n">hermi</span><span class="o">=</span><span class="mi">0</span><span class="p">)</span> <span class="gp">&gt;&gt;&gt; </span><span class="n">dm1</span> <span class="o">=</span> <span class="n">numpy</span><span class="o">.</span><span class="n">random</span><span class="o">.</span><span class="n">random</span><span class="p">((</span><span class="n">mol</span><span class="o">.</span><span class="n">nao_nr</span><span class="p">(),</span><span class="n">mol</span><span class="o">.</span><span class="n">nao_nr</span><span class="p">()))</span> <span class="gp">&gt;&gt;&gt; </span><span class="n">vhf1</span> <span class="o">=</span> <span class="n">scf</span><span class="o">.</span><span class="n">hf</span><span class="o">.</span><span class="n">get_veff</span><span class="p">(</span><span class="n">mol</span><span class="p">,</span> <span class="n">dm1</span><span class="p">,</span> <span class="n">hermi</span><span class="o">=</span><span class="mi">0</span><span class="p">)</span> <span class="gp">&gt;&gt;&gt; </span><span class="n">vhf2</span> <span class="o">=</span> <span class="n">scf</span><span class="o">.</span><span class="n">hf</span><span class="o">.</span><span class="n">get_veff</span><span class="p">(</span><span class="n">mol</span><span class="p">,</span> <span class="n">dm1</span><span class="p">,</span> <span class="n">dm_last</span><span class="o">=</span><span class="n">dm0</span><span class="p">,</span> <span class="n">vhf_last</span><span class="o">=</span><span class="n">vhf0</span><span class="p">,</span> <span class="n">hermi</span><span class="o">=</span><span class="mi">0</span><span class="p">)</span> <span class="gp">&gt;&gt;&gt; </span><span class="n">numpy</span><span class="o">.</span><span class="n">allclose</span><span class="p">(</span><span class="n">vhf1</span><span class="p">,</span> <span class="n">vhf2</span><span class="p">)</span> <span class="go">True</span> </pre></div> </div> </dd></dl> <dl class="py method"> <dt id="pyscf.mcscf.casci.CASCI.h1e_for_cas"> <code class="sig-name descname">h1e_for_cas</code><span class="sig-paren">(</span><em class="sig-param"><span class="n">mo_coeff</span><span class="o">=</span><span class="default_value">None</span></em>, <em class="sig-param"><span class="n">ncas</span><span class="o">=</span><span class="default_value">None</span></em>, <em class="sig-param"><span class="n">ncore</span><span class="o">=</span><span class="default_value">None</span></em><span class="sig-paren">)</span><a class="headerlink" href="#pyscf.mcscf.casci.CASCI.h1e_for_cas" title="Permalink to this definition">¶</a></dt> <dd><p>CAS sapce one-electron hamiltonian</p> <dl class="simple"> <dt>Args:</dt><dd><p>casci : a CASSCF/CASCI object or RHF object</p> </dd> <dt>Returns:</dt><dd><p>A tuple, the first is the effective one-electron hamiltonian defined in CAS space, the second is the electronic energy from core.</p> </dd> </dl> </dd></dl> <dl class="py method"> <dt id="pyscf.mcscf.casci.CASCI.kernel"> <code class="sig-name descname">kernel</code><span class="sig-paren">(</span><em class="sig-param"><span class="n">mo_coeff</span><span class="o">=</span><span class="default_value">None</span></em>, <em class="sig-param"><span class="n">ci0</span><span class="o">=</span><span class="default_value">None</span></em>, <em class="sig-param"><span class="n">verbose</span><span class="o">=</span><span class="default_value">None</span></em><span class="sig-paren">)</span><a class="headerlink" href="#pyscf.mcscf.casci.CASCI.kernel" title="Permalink to this definition">¶</a></dt> <dd><dl class="simple"> <dt>Returns:</dt><dd><p>Five elements, they are total energy, active space CI energy, the active space FCI wavefunction coefficients or DMRG wavefunction ID, the MCSCF canonical orbital coefficients, the MCSCF canonical orbital coefficients.</p> </dd> </dl> <p>They are attributes of mcscf object, which can be accessed by .e_tot, .e_cas, .ci, .mo_coeff, .mo_energy</p> </dd></dl> <dl class="py method"> <dt id="pyscf.mcscf.casci.CASCI.make_rdm1"> <code class="sig-name descname">make_rdm1</code><span class="sig-paren">(</span><em class="sig-param"><span class="n">mo_coeff</span><span class="o">=</span><span class="default_value">None</span></em>, <em class="sig-param"><span class="n">ci</span><span class="o">=</span><span class="default_value">None</span></em>, <em class="sig-param"><span class="n">ncas</span><span class="o">=</span><span class="default_value">None</span></em>, <em class="sig-param"><span class="n">nelecas</span><span class="o">=</span><span class="default_value">None</span></em>, <em class="sig-param"><span class="n">ncore</span><span class="o">=</span><span class="default_value">None</span></em>, <em class="sig-param"><span class="o">**</span><span class="n">kwargs</span></em><span class="sig-paren">)</span><a class="headerlink" href="#pyscf.mcscf.casci.CASCI.make_rdm1" title="Permalink to this definition">¶</a></dt> <dd><p>One-particle density matrix in AO representation</p> </dd></dl> <dl class="py method"> <dt id="pyscf.mcscf.casci.CASCI.make_rdm1s"> <code class="sig-name descname">make_rdm1s</code><span class="sig-paren">(</span><em class="sig-param"><span class="n">mo_coeff</span><span class="o">=</span><span class="default_value">None</span></em>, <em class="sig-param"><span class="n">ci</span><span class="o">=</span><span class="default_value">None</span></em>, <em class="sig-param"><span class="n">ncas</span><span class="o">=</span><span class="default_value">None</span></em>, <em class="sig-param"><span class="n">nelecas</span><span class="o">=</span><span class="default_value">None</span></em>, <em class="sig-param"><span class="n">ncore</span><span class="o">=</span><span class="default_value">None</span></em>, <em class="sig-param"><span class="o">**</span><span class="n">kwargs</span></em><span class="sig-paren">)</span><a class="headerlink" href="#pyscf.mcscf.casci.CASCI.make_rdm1s" title="Permalink to this definition">¶</a></dt> <dd><p>One-particle density matrices for alpha and beta spin on AO basis</p> </dd></dl> <dl class="py attribute"> <dt id="pyscf.mcscf.casci.CASCI.natorb"> <code class="sig-name descname">natorb</code><em class="property"> = False</em><a class="headerlink" href="#pyscf.mcscf.casci.CASCI.natorb" title="Permalink to this definition">¶</a></dt> <dd></dd></dl> <dl class="py method"> <dt id="pyscf.mcscf.casci.CASCI.ncore"> <em class="property">property </em><code class="sig-name descname">ncore</code><a class="headerlink" href="#pyscf.mcscf.casci.CASCI.ncore" title="Permalink to this definition">¶</a></dt> <dd></dd></dl> <dl class="py method"> <dt id="pyscf.mcscf.casci.CASCI.nuc_grad_method"> <code class="sig-name descname">nuc_grad_method</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#pyscf.mcscf.casci.CASCI.nuc_grad_method" title="Permalink to this definition">¶</a></dt> <dd></dd></dl> <dl class="py method"> <dt id="pyscf.mcscf.casci.CASCI.reset"> <code class="sig-name descname">reset</code><span class="sig-paren">(</span><em class="sig-param"><span class="n">mol</span><span class="o">=</span><span class="default_value">None</span></em><span class="sig-paren">)</span><a class="headerlink" href="#pyscf.mcscf.casci.CASCI.reset" title="Permalink to this definition">¶</a></dt> <dd></dd></dl> <dl class="py method"> <dt id="pyscf.mcscf.casci.CASCI.sfx2c1e"> <code class="sig-name descname">sfx2c1e</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#pyscf.mcscf.casci.CASCI.sfx2c1e" title="Permalink to this definition">¶</a></dt> <dd></dd></dl> <dl class="py method"> <dt id="pyscf.mcscf.casci.CASCI.sort_mo"> <code class="sig-name descname">sort_mo</code><span class="sig-paren">(</span><em class="sig-param"><span class="n">caslst</span></em>, <em class="sig-param"><span class="n">mo_coeff</span><span class="o">=</span><span class="default_value">None</span></em>, <em class="sig-param"><span class="n">base</span><span class="o">=</span><span class="default_value">1</span></em><span class="sig-paren">)</span><a class="headerlink" href="#pyscf.mcscf.casci.CASCI.sort_mo" title="Permalink to this definition">¶</a></dt> <dd><p>Pick orbitals for CAS space</p> <dl> <dt>Args:</dt><dd><p>casscf : an <code class="xref py py-class docutils literal notranslate"><span class="pre">CASSCF</span></code> or <a class="reference internal" href="#pyscf.mcscf.casci.CASCI" title="pyscf.mcscf.casci.CASCI"><code class="xref py py-class docutils literal notranslate"><span class="pre">CASCI</span></code></a> object</p> <dl class="simple"> <dt>mo_coeff<span class="classifier">ndarray or a list of ndarray</span></dt><dd><p>Orbitals for CASSCF initial guess. In the UHF-CASSCF, it’s a list of two orbitals, for alpha and beta spin.</p> </dd> <dt>caslst<span class="classifier">list of int or nested list of int</span></dt><dd><p>A list of orbital indices to represent the CAS space. In the UHF-CASSCF, it’s consist of two lists, for alpha and beta spin.</p> </dd> </dl> </dd> <dt>Kwargs:</dt><dd><dl class="simple"> <dt>base<span class="classifier">int</span></dt><dd><p>0-based (C-style) or 1-based (Fortran-style) caslst</p> </dd> </dl> </dd> <dt>Returns:</dt><dd><p>An reoreded mo_coeff, which put the orbitals given by caslst in the CAS space</p> </dd> </dl> <p>Examples:</p> <div class="doctest highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">from</span> <span class="nn">pyscf</span> <span class="kn">import</span> <span class="n">gto</span><span class="p">,</span> <span class="n">scf</span><span class="p">,</span> <span class="n">mcscf</span> <span class="gp">&gt;&gt;&gt; </span><span class="n">mol</span> <span class="o">=</span> <span class="n">gto</span><span class="o">.</span><span class="n">M</span><span class="p">(</span><span class="n">atom</span><span class="o">=</span><span class="s1">&#39;N 0 0 0; N 0 0 1&#39;</span><span class="p">,</span> <span class="n">basis</span><span class="o">=</span><span class="s1">&#39;ccpvdz&#39;</span><span class="p">,</span> <span class="n">verbose</span><span class="o">=</span><span class="mi">0</span><span class="p">)</span> <span class="gp">&gt;&gt;&gt; </span><span class="n">mf</span> <span class="o">=</span> <span class="n">scf</span><span class="o">.</span><span class="n">RHF</span><span class="p">(</span><span class="n">mol</span><span class="p">)</span> <span class="gp">&gt;&gt;&gt; </span><span class="n">mf</span><span class="o">.</span><span class="n">scf</span><span class="p">()</span> <span class="gp">&gt;&gt;&gt; </span><span class="n">mc</span> <span class="o">=</span> <span class="n">mcscf</span><span class="o">.</span><span class="n">CASSCF</span><span class="p">(</span><span class="n">mf</span><span class="p">,</span> <span class="mi">4</span><span class="p">,</span> <span class="mi">4</span><span class="p">)</span> <span class="gp">&gt;&gt;&gt; </span><span class="n">cas_list</span> <span class="o">=</span> <span class="p">[</span><span class="mi">5</span><span class="p">,</span><span class="mi">6</span><span class="p">,</span><span class="mi">8</span><span class="p">,</span><span class="mi">9</span><span class="p">]</span> <span class="c1"># pi orbitals</span> <span class="gp">&gt;&gt;&gt; </span><span class="n">mo</span> <span class="o">=</span> <span class="n">mc</span><span class="o">.</span><span class="n">sort_mo</span><span class="p">(</span><span class="n">cas_list</span><span class="p">)</span> <span class="gp">&gt;&gt;&gt; </span><span class="n">mc</span><span class="o">.</span><span class="n">kernel</span><span class="p">(</span><span class="n">mo</span><span class="p">)[</span><span class="mi">0</span><span class="p">]</span> <span class="go">-109.007378939813691</span> </pre></div> </div> </dd></dl> <dl class="py attribute"> <dt id="pyscf.mcscf.casci.CASCI.sorting_mo_energy"> <code class="sig-name descname">sorting_mo_energy</code><em class="property"> = False</em><a class="headerlink" href="#pyscf.mcscf.casci.CASCI.sorting_mo_energy" title="Permalink to this definition">¶</a></dt> <dd></dd></dl> <dl class="py method"> <dt id="pyscf.mcscf.casci.CASCI.state_average"> <code class="sig-name descname">state_average</code><span class="sig-paren">(</span><em class="sig-param"><span class="n">weights</span><span class="o">=</span><span class="default_value">(0.5, 0.5)</span></em><span class="sig-paren">)</span><a class="headerlink" href="#pyscf.mcscf.casci.CASCI.state_average" title="Permalink to this definition">¶</a></dt> <dd><p>State average over the energy. The energy funcitonal is E = w1&lt;psi1|H|psi1&gt; + w2&lt;psi2|H|psi2&gt; + …</p> <p>Note we may need change the FCI solver to</p> <p>mc.fcisolver = fci.solver(mol, False)</p> <p>before calling state_average_(mc), to mix the singlet and triplet states</p> <p>MRH, 04/08/2019: Instead of turning casscf._finalize into an instance attribute that points to the previous casscf object, I’m going to make a whole new child class. This will have the added benefit of making state_average and <a href="#id3"><span class="problematic" id="id4">state_average_</span></a> actually behave differently for the first time (until now they <em>both</em> modified the casscf object inplace). I’m also going to assign the weights argument as a member of the mc child class because an accurate second-order CASSCF algorithm for state-averaged calculations requires that the gradient and Hessian be computed for CI vectors of each root individually and then multiplied by that root’s weight. The second derivatives computed by newton_casscf.py need to be extended to state-averaged calculations in order to be used as intermediates for calculations of the gradient of a single root in the context of the SA-CASSCF method; see: Mol. Phys. 99, 103 (2001).</p> </dd></dl> <dl class="py method"> <dt id="pyscf.mcscf.casci.CASCI.state_average_"> <code class="sig-name descname">state_average_</code><span class="sig-paren">(</span><em class="sig-param"><span class="n">weights</span><span class="o">=</span><span class="default_value">(0.5, 0.5)</span></em><span class="sig-paren">)</span><a class="headerlink" href="#pyscf.mcscf.casci.CASCI.state_average_" title="Permalink to this definition">¶</a></dt> <dd><p>State average over the energy. The energy funcitonal is E = w1&lt;psi1|H|psi1&gt; + w2&lt;psi2|H|psi2&gt; + …</p> <p>Note we may need change the FCI solver to</p> <p>mc.fcisolver = fci.solver(mol, False)</p> <p>before calling state_average_(mc), to mix the singlet and triplet states</p> <p>MRH, 04/08/2019: Instead of turning casscf._finalize into an instance attribute that points to the previous casscf object, I’m going to make a whole new child class. This will have the added benefit of making state_average and <a href="#id5"><span class="problematic" id="id6">state_average_</span></a> actually behave differently for the first time (until now they <em>both</em> modified the casscf object inplace). I’m also going to assign the weights argument as a member of the mc child class because an accurate second-order CASSCF algorithm for state-averaged calculations requires that the gradient and Hessian be computed for CI vectors of each root individually and then multiplied by that root’s weight. The second derivatives computed by newton_casscf.py need to be extended to state-averaged calculations in order to be used as intermediates for calculations of the gradient of a single root in the context of the SA-CASSCF method; see: Mol. Phys. 99, 103 (2001).</p> </dd></dl> <dl class="py method"> <dt id="pyscf.mcscf.casci.CASCI.state_specific_"> <code class="sig-name descname">state_specific_</code><span class="sig-paren">(</span><em class="sig-param"><span class="n">state</span><span class="o">=</span><span class="default_value">1</span></em><span class="sig-paren">)</span><a class="headerlink" href="#pyscf.mcscf.casci.CASCI.state_specific_" title="Permalink to this definition">¶</a></dt> <dd><p>For excited state</p> <dl class="simple"> <dt>Kwargs:</dt><dd><p>state : int 0 for ground state; 1 for first excited state.</p> </dd> </dl> </dd></dl> <dl class="py method"> <dt id="pyscf.mcscf.casci.CASCI.x2c"> <code class="sig-name descname">x2c</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#pyscf.mcscf.casci.CASCI.x2c" title="Permalink to this definition">¶</a></dt> <dd></dd></dl> <dl class="py method"> <dt id="pyscf.mcscf.casci.CASCI.x2c1e"> <code class="sig-name descname">x2c1e</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#pyscf.mcscf.casci.CASCI.x2c1e" title="Permalink to this definition">¶</a></dt> <dd></dd></dl> </dd></dl> <dl class="py function"> <dt id="pyscf.mcscf.casci.analyze"> <code class="sig-prename descclassname">pyscf.mcscf.casci.</code><code class="sig-name descname">analyze</code><span class="sig-paren">(</span><em class="sig-param"><span class="n">casscf</span></em>, <em class="sig-param"><span class="n">mo_coeff</span><span class="o">=</span><span class="default_value">None</span></em>, <em class="sig-param"><span class="n">ci</span><span class="o">=</span><span class="default_value">None</span></em>, <em class="sig-param"><span class="n">verbose</span><span class="o">=</span><span class="default_value">None</span></em>, <em class="sig-param"><span class="n">large_ci_tol</span><span class="o">=</span><span class="default_value">0.1</span></em>, <em class="sig-param"><span class="n">with_meta_lowdin</span><span class="o">=</span><span class="default_value">True</span></em>, <em class="sig-param"><span class="o">**</span><span class="n">kwargs</span></em><span class="sig-paren">)</span><a class="headerlink" href="#pyscf.mcscf.casci.analyze" title="Permalink to this definition">¶</a></dt> <dd></dd></dl> <dl class="py function"> <dt id="pyscf.mcscf.casci.as_scanner"> <code class="sig-prename descclassname">pyscf.mcscf.casci.</code><code class="sig-name descname">as_scanner</code><span class="sig-paren">(</span><em class="sig-param"><span class="n">mc</span></em><span class="sig-paren">)</span><a class="headerlink" href="#pyscf.mcscf.casci.as_scanner" title="Permalink to this definition">¶</a></dt> <dd><p>Generating a scanner for CASCI PES.</p> <p>The returned solver is a function. This function requires one argument “mol” as input and returns total CASCI energy.</p> <p>The solver will automatically use the results of last calculation as the initial guess of the new calculation. All parameters of MCSCF object are automatically applied in the solver.</p> <p>Note scanner has side effects. It may change many underlying objects (_scf, with_df, with_x2c, …) during calculation.</p> <p>Examples:</p> <div class="doctest highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">from</span> <span class="nn">pyscf</span> <span class="kn">import</span> <span class="n">gto</span><span class="p">,</span> <span class="n">scf</span><span class="p">,</span> <span class="n">mcscf</span> <span class="gp">&gt;&gt;&gt; </span><span class="n">mf</span> <span class="o">=</span> <span class="n">scf</span><span class="o">.</span><span class="n">RHF</span><span class="p">(</span><span class="n">gto</span><span class="o">.</span><span class="n">Mole</span><span class="p">()</span><span class="o">.</span><span class="n">set</span><span class="p">(</span><span class="n">verbose</span><span class="o">=</span><span class="mi">0</span><span class="p">))</span> <span class="gp">&gt;&gt;&gt; </span><span class="n">mc_scanner</span> <span class="o">=</span> <span class="n">mcscf</span><span class="o">.</span><span class="n">CASCI</span><span class="p">(</span><span class="n">mf</span><span class="p">,</span> <span class="mi">4</span><span class="p">,</span> <span class="mi">4</span><span class="p">)</span><span class="o">.</span><span class="n">as_scanner</span><span class="p">()</span> <span class="gp">&gt;&gt;&gt; </span><span class="n">mc_scanner</span><span class="p">(</span><span class="n">gto</span><span class="o">.</span><span class="n">M</span><span class="p">(</span><span class="n">atom</span><span class="o">=</span><span class="s1">&#39;N 0 0 0; N 0 0 1.1&#39;</span><span class="p">))</span> <span class="gp">&gt;&gt;&gt; </span><span class="n">mc_scanner</span><span class="p">(</span><span class="n">gto</span><span class="o">.</span><span class="n">M</span><span class="p">(</span><span class="n">atom</span><span class="o">=</span><span class="s1">&#39;N 0 0 0; N 0 0 1.5&#39;</span><span class="p">))</span> </pre></div> </div> </dd></dl> <dl class="py function"> <dt id="pyscf.mcscf.casci.canonicalize"> <code class="sig-prename descclassname">pyscf.mcscf.casci.</code><code class="sig-name descname">canonicalize</code><span class="sig-paren">(</span><em class="sig-param"><span class="n">mc</span></em>, <em class="sig-param"><span class="n">mo_coeff</span><span class="o">=</span><span class="default_value">None</span></em>, <em class="sig-param"><span class="n">ci</span><span class="o">=</span><span class="default_value">None</span></em>, <em class="sig-param"><span class="n">eris</span><span class="o">=</span><span class="default_value">None</span></em>, <em class="sig-param"><span class="n">sort</span><span class="o">=</span><span class="default_value">False</span></em>, <em class="sig-param"><span class="n">cas_natorb</span><span class="o">=</span><span class="default_value">False</span></em>, <em class="sig-param"><span class="n">casdm1</span><span class="o">=</span><span class="default_value">None</span></em>, <em class="sig-param"><span class="n">verbose</span><span class="o">=</span><span class="default_value">3</span></em>, <em class="sig-param"><span class="n">with_meta_lowdin</span><span class="o">=</span><span class="default_value">True</span></em><span class="sig-paren">)</span><a class="headerlink" href="#pyscf.mcscf.casci.canonicalize" title="Permalink to this definition">¶</a></dt> <dd><p>Canonicalized CASCI/CASSCF orbitals of effecitive Fock matrix and update CI coefficients accordingly.</p> <p>Effective Fock matrix is built with one-particle density matrix (see also <code class="xref py py-func docutils literal notranslate"><span class="pre">mcscf.casci.get_fock()</span></code>). For state-average CASCI/CASSCF object, the canonicalized orbitals are based on the state-average density matrix. To obtain canonicalized orbitals for an individual state, you need to pass “casdm1” of the specific state to this function.</p> <dl class="simple"> <dt>Args:</dt><dd><p>mc: a CASSCF/CASCI object or RHF object</p> </dd> <dt>Kwargs:</dt><dd><dl class="simple"> <dt>mo_coeff (ndarray): orbitals that span the core, active and external</dt><dd><p>space.</p> </dd> <dt>ci (ndarray): CI coefficients (or objects to represent the CI</dt><dd><p>wavefunctions in DMRG/QMC-MCSCF calculations).</p> </dd> <dt>eris: Integrals for the MCSCF object. Input this object to reduce the</dt><dd><p>overhead of computing integrals. It can be generated by <code class="xref py py-func docutils literal notranslate"><span class="pre">mc.ao2mo()</span></code> method.</p> </dd> <dt>sort (bool): Whether the canonicalized orbitals are sorted based on</dt><dd><p>the orbital energy (diagonal part of the effective Fock matrix) within each subspace (core, active, external). If point group symmetry is not available in the system, orbitals are always sorted. When point group symmetry is available, sort=False will preserve the symmetry label of input orbitals and only sort the orbitals in each symmetry sector. sort=True will reorder all orbitals over all symmetry sectors in each subspace and the symmetry labels may be changed.</p> </dd> <dt>cas_natorb (bool): Whether to transform active orbitals to natual</dt><dd><p>orbitals. If enabled, the output orbitals in active space are transformed to natural orbitals and CI coefficients are updated accordingly.</p> </dd> <dt>casdm1 (ndarray): 1-particle density matrix in active space. This</dt><dd><p>density matrix is used to build effective fock matrix. Without input casdm1, the density matrix is computed with the input ci coefficients/object. If neither ci nor casdm1 were given, density matrix is computed by <code class="xref py py-func docutils literal notranslate"><span class="pre">mc.fcisolver.make_rdm1()</span></code> method. For state-average CASCI/CASCF calculation, this results in a set of canonicalized orbitals of state-average effective Fock matrix. To canonicalize the orbitals for one particular state, you can assign the density matrix of that state to the kwarg casdm1.</p> </dd> </dl> </dd> <dt>Returns:</dt><dd><p>A tuple, (natural orbitals, CI coefficients, orbital energies) The orbital energies are the diagonal terms of effective Fock matrix.</p> </dd> </dl> </dd></dl> <dl class="py function"> <dt id="pyscf.mcscf.casci.cas_natorb"> <code class="sig-prename descclassname">pyscf.mcscf.casci.</code><code class="sig-name descname">cas_natorb</code><span class="sig-paren">(</span><em class="sig-param"><span class="n">mc</span></em>, <em class="sig-param"><span class="n">mo_coeff</span><span class="o">=</span><span class="default_value">None</span></em>, <em class="sig-param"><span class="n">ci</span><span class="o">=</span><span class="default_value">None</span></em>, <em class="sig-param"><span class="n">eris</span><span class="o">=</span><span class="default_value">None</span></em>, <em class="sig-param"><span class="n">sort</span><span class="o">=</span><span class="default_value">False</span></em>, <em class="sig-param"><span class="n">casdm1</span><span class="o">=</span><span class="default_value">None</span></em>, <em class="sig-param"><span class="n">verbose</span><span class="o">=</span><span class="default_value">None</span></em>, <em class="sig-param"><span class="n">with_meta_lowdin</span><span class="o">=</span><span class="default_value">True</span></em><span class="sig-paren">)</span><a class="headerlink" href="#pyscf.mcscf.casci.cas_natorb" title="Permalink to this definition">¶</a></dt> <dd><p>Transform active orbitals to natrual orbitals, and update the CI wfn accordingly</p> <dl class="simple"> <dt>Args:</dt><dd><p>mc : a CASSCF/CASCI object or RHF object</p> </dd> <dt>Kwargs:</dt><dd><dl class="simple"> <dt>sort<span class="classifier">bool</span></dt><dd><p>Sort natural orbitals wrt the occupancy.</p> </dd> </dl> </dd> <dt>Returns:</dt><dd><p>A tuple, the first item is natural orbitals, the second is updated CI coefficients, the third is the natural occupancy associated to the natural orbitals.</p> </dd> </dl> </dd></dl> <dl class="py function"> <dt id="pyscf.mcscf.casci.get_fock"> <code class="sig-prename descclassname">pyscf.mcscf.casci.</code><code class="sig-name descname">get_fock</code><span class="sig-paren">(</span><em class="sig-param"><span class="n">mc</span></em>, <em class="sig-param"><span class="n">mo_coeff</span><span class="o">=</span><span class="default_value">None</span></em>, <em class="sig-param"><span class="n">ci</span><span class="o">=</span><span class="default_value">None</span></em>, <em class="sig-param"><span class="n">eris</span><span class="o">=</span><span class="default_value">None</span></em>, <em class="sig-param"><span class="n">casdm1</span><span class="o">=</span><span class="default_value">None</span></em>, <em class="sig-param"><span class="n">verbose</span><span class="o">=</span><span class="default_value">None</span></em><span class="sig-paren">)</span><a class="headerlink" href="#pyscf.mcscf.casci.get_fock" title="Permalink to this definition">¶</a></dt> <dd><p>Effective one-electron Fock matrix in AO representation f = sum_{pq} E_{pq} F_{pq} F_{pq} = h_{pq} + sum_{rs} [(pq|rs)-(ps|rq)] DM_{sr}</p> <p>Ref. <NAME>., 91, 31 Chem. Phys. 48, 157</p> <p>For state-average CASCI/CASSCF object, the effective fock matrix is based on the state-average density matrix. To obtain Fock matrix of a specific state in the state-average calculations, you can pass “casdm1” of the specific state to this function.</p> <dl class="simple"> <dt>Args:</dt><dd><p>mc: a CASSCF/CASCI object or RHF object</p> </dd> <dt>Kwargs:</dt><dd><dl class="simple"> <dt>mo_coeff (ndarray): orbitals that span the core, active and external</dt><dd><p>space.</p> </dd> <dt>ci (ndarray): CI coefficients (or objects to represent the CI</dt><dd><p>wavefunctions in DMRG/QMC-MCSCF calculations).</p> </dd> <dt>eris: Integrals for the MCSCF object. Input this object to reduce the</dt><dd><p>overhead of computing integrals. It can be generated by <code class="xref py py-func docutils literal notranslate"><span class="pre">mc.ao2mo()</span></code> method.</p> </dd> <dt>casdm1 (ndarray): 1-particle density matrix in active space. Without</dt><dd><p>input casdm1, the density matrix is computed with the input ci coefficients/object. If neither ci nor casdm1 were given, density matrix is computed by <code class="xref py py-func docutils literal notranslate"><span class="pre">mc.fcisolver.make_rdm1()</span></code> method. For state-average CASCI/CASCF calculation, this results in the effective Fock matrix based on the state-average density matrix. To obtain the effective Fock matrix for one particular state, you can assign the density matrix of that state to the kwarg casdm1.</p> </dd> </dl> </dd> <dt>Returns:</dt><dd><p>Fock matrix</p> </dd> </dl> </dd></dl> <dl class="py function"> <dt id="pyscf.mcscf.casci.h1e_for_cas"> <code class="sig-prename descclassname">pyscf.mcscf.casci.</code><code class="sig-name descname">h1e_for_cas</code><span class="sig-paren">(</span><em class="sig-param"><span class="n">casci</span></em>, <em class="sig-param"><span class="n">mo_coeff</span><span class="o">=</span><span class="default_value">None</span></em>, <em class="sig-param"><span class="n">ncas</span><span class="o">=</span><span class="default_value">None</span></em>, <em class="sig-param"><span class="n">ncore</span><span class="o">=</span><span class="default_value">None</span></em><span class="sig-paren">)</span><a class="headerlink" href="#pyscf.mcscf.casci.h1e_for_cas" title="Permalink to this definition">¶</a></dt> <dd><p>CAS sapce one-electron hamiltonian</p> <dl class="simple"> <dt>Args:</dt><dd><p>casci : a CASSCF/CASCI object or RHF object</p> </dd> <dt>Returns:</dt><dd><p>A tuple, the first is the effective one-electron hamiltonian defined in CAS space, the second is the electronic energy from core.</p> </dd> </dl> </dd></dl> <dl class="py function"> <dt id="pyscf.mcscf.casci.kernel"> <code class="sig-prename descclassname">pyscf.mcscf.casci.</code><code class="sig-name descname">kernel</code><span class="sig-paren">(</span><em class="sig-param"><span class="n">casci</span></em>, <em class="sig-param"><span class="n">mo_coeff</span><span class="o">=</span><span class="default_value">None</span></em>, <em class="sig-param"><span class="n">ci0</span><span class="o">=</span><span class="default_value">None</span></em>, <em class="sig-param"><span class="n">verbose</span><span class="o">=</span><span class="default_value">3</span></em><span class="sig-paren">)</span><a class="headerlink" href="#pyscf.mcscf.casci.kernel" title="Permalink to this definition">¶</a></dt> <dd><p>CASCI solver</p> </dd></dl> </div> <div class="section" id="module-pyscf.mcscf.casci_symm"> <span id="pyscf-mcscf-casci-symm-module"></span><h2>pyscf.mcscf.casci_symm module<a class="headerlink" href="#module-pyscf.mcscf.casci_symm" title="Permalink to this headline">¶</a></h2> <dl class="py attribute"> <dt id="pyscf.mcscf.casci_symm.CASCI"> <code class="sig-prename descclassname">pyscf.mcscf.casci_symm.</code><code class="sig-name descname">CASCI</code><a class="headerlink" href="#pyscf.mcscf.casci_symm.CASCI" title="Permalink to this definition">¶</a></dt> <dd><p>alias of <a class="reference internal" href="#pyscf.mcscf.casci_symm.SymAdaptedCASCI" title="pyscf.mcscf.casci_symm.SymAdaptedCASCI"><code class="xref py py-class docutils literal notranslate"><span class="pre">pyscf.mcscf.casci_symm.SymAdaptedCASCI</span></code></a></p> </dd></dl> <dl class="py class"> <dt id="pyscf.mcscf.casci_symm.SymAdaptedCASCI"> <em class="property">class </em><code class="sig-prename descclassname">pyscf.mcscf.casci_symm.</code><code class="sig-name descname">SymAdaptedCASCI</code><span class="sig-paren">(</span><em class="sig-param"><span class="n">mf_or_mol</span></em>, <em class="sig-param"><span class="n">ncas</span></em>, <em class="sig-param"><span class="n">nelecas</span></em>, <em class="sig-param"><span class="n">ncore</span><span class="o">=</span><span class="default_value">None</span></em><span class="sig-paren">)</span><a class="headerlink" href="#pyscf.mcscf.casci_symm.SymAdaptedCASCI" title="Permalink to this definition">¶</a></dt> <dd><p>Bases: <a class="reference internal" href="#pyscf.mcscf.casci.CASCI" title="pyscf.mcscf.casci.CASCI"><code class="xref py py-class docutils literal notranslate"><span class="pre">pyscf.mcscf.casci.CASCI</span></code></a></p> <dl class="py method"> <dt id="pyscf.mcscf.casci_symm.SymAdaptedCASCI.kernel"> <code class="sig-name descname">kernel</code><span class="sig-paren">(</span><em class="sig-param"><span class="n">mo_coeff</span><span class="o">=</span><span class="default_value">None</span></em>, <em class="sig-param"><span class="n">ci0</span><span class="o">=</span><span class="default_value">None</span></em>, <em class="sig-param"><span class="n">verbose</span><span class="o">=</span><span class="default_value">None</span></em><span class="sig-paren">)</span><a class="headerlink" href="#pyscf.mcscf.casci_symm.SymAdaptedCASCI.kernel" title="Permalink to this definition">¶</a></dt> <dd><dl class="simple"> <dt>Returns:</dt><dd><p>Five elements, they are total energy, active space CI energy, the active space FCI wavefunction coefficients or DMRG wavefunction ID, the MCSCF canonical orbital coefficients, the MCSCF canonical orbital coefficients.</p> </dd> </dl> <p>They are attributes of mcscf object, which can be accessed by .e_tot, .e_cas, .ci, .mo_coeff, .mo_energy</p> </dd></dl> <dl class="py method"> <dt id="pyscf.mcscf.casci_symm.SymAdaptedCASCI.sort_mo_by_irrep"> <code class="sig-name descname">sort_mo_by_irrep</code><span class="sig-paren">(</span><em class="sig-param"><span class="n">cas_irrep_nocc</span></em>, <em class="sig-param"><span class="n">cas_irrep_ncore</span><span class="o">=</span><span class="default_value">None</span></em>, <em class="sig-param"><span class="n">mo_coeff</span><span class="o">=</span><span class="default_value">None</span></em>, <em class="sig-param"><span class="n">s</span><span class="o">=</span><span class="default_value">None</span></em><span class="sig-paren">)</span><a class="headerlink" href="#pyscf.mcscf.casci_symm.SymAdaptedCASCI.sort_mo_by_irrep" title="Permalink to this definition">¶</a></dt> <dd><p>Select active space based on symmetry information. See also <a class="reference internal" href="#pyscf.mcscf.addons.sort_mo_by_irrep" title="pyscf.mcscf.addons.sort_mo_by_irrep"><code class="xref py py-func docutils literal notranslate"><span class="pre">pyscf.mcscf.addons.sort_mo_by_irrep()</span></code></a></p> </dd></dl> <dl class="py method"> <dt id="pyscf.mcscf.casci_symm.SymAdaptedCASCI.wfnsym"> <em class="property">property </em><code class="sig-name descname">wfnsym</code><a class="headerlink" href="#pyscf.mcscf.casci_symm.SymAdaptedCASCI.wfnsym" title="Permalink to this definition">¶</a></dt> <dd></dd></dl> </dd></dl> <dl class="py function"> <dt id="pyscf.mcscf.casci_symm.eig"> <code class="sig-prename descclassname">pyscf.mcscf.casci_symm.</code><code class="sig-name descname">eig</code><span class="sig-paren">(</span><em class="sig-param"><span class="n">mat</span></em>, <em class="sig-param"><span class="n">orbsym</span></em><span class="sig-paren">)</span><a class="headerlink" href="#pyscf.mcscf.casci_symm.eig" title="Permalink to this definition">¶</a></dt> <dd></dd></dl> <dl class="py function"> <dt id="pyscf.mcscf.casci_symm.label_symmetry_"> <code class="sig-prename descclassname">pyscf.mcscf.casci_symm.</code><code class="sig-name descname">label_symmetry_</code><span class="sig-paren">(</span><em class="sig-param"><span class="n">mc</span></em>, <em class="sig-param"><span class="n">mo_coeff</span></em>, <em class="sig-param"><span class="n">ci0</span><span class="o">=</span><span class="default_value">None</span></em><span class="sig-paren">)</span><a class="headerlink" href="#pyscf.mcscf.casci_symm.label_symmetry_" title="Permalink to this definition">¶</a></dt> <dd></dd></dl> </div> <div class="section" id="module-pyscf.mcscf.chkfile"> <span id="pyscf-mcscf-chkfile-module"></span><h2>pyscf.mcscf.chkfile module<a class="headerlink" href="#module-pyscf.mcscf.chkfile" title="Permalink to this headline">¶</a></h2> <dl class="py function"> <dt id="pyscf.mcscf.chkfile.dump_mcscf"> <code class="sig-prename descclassname">pyscf.mcscf.chkfile.</code><code class="sig-name descname">dump_mcscf</code><span class="sig-paren">(</span><em class="sig-param"><span class="n">mc</span></em>, <em class="sig-param"><span class="n">chkfile</span><span class="o">=</span><span class="default_value">None</span></em>, <em class="sig-param"><span class="n">key</span><span class="o">=</span><span class="default_value">'mcscf'</span></em>, <em class="sig-param"><span class="n">e_tot</span><span class="o">=</span><span class="default_value">None</span></em>, <em class="sig-param"><span class="n">mo_coeff</span><span class="o">=</span><span class="default_value">None</span></em>, <em class="sig-param"><span class="n">ncore</span><span class="o">=</span><span class="default_value">None</span></em>, <em class="sig-param"><span class="n">ncas</span><span class="o">=</span><span class="default_value">None</span></em>, <em class="sig-param"><span class="n">mo_occ</span><span class="o">=</span><span class="default_value">None</span></em>, <em class="sig-param"><span class="n">mo_energy</span><span class="o">=</span><span class="default_value">None</span></em>, <em class="sig-param"><span class="n">e_cas</span><span class="o">=</span><span class="default_value">None</span></em>, <em class="sig-param"><span class="n">ci_vector</span><span class="o">=</span><span class="default_value">None</span></em>, <em class="sig-param"><span class="n">casdm1</span><span class="o">=</span><span class="default_value">None</span></em>, <em class="sig-param"><span class="n">overwrite_mol</span><span class="o">=</span><span class="default_value">True</span></em><span class="sig-paren">)</span><a class="headerlink" href="#pyscf.mcscf.chkfile.dump_mcscf" title="Permalink to this definition">¶</a></dt> <dd><p>Save CASCI/CASSCF calculation results or intermediates in chkfile.</p> </dd></dl> <dl class="py function"> <dt id="pyscf.mcscf.chkfile.load_mcscf"> <code class="sig-prename descclassname">pyscf.mcscf.chkfile.</code><code class="sig-name descname">load_mcscf</code><span class="sig-paren">(</span><em class="sig-param"><span class="n">chkfile</span></em><span class="sig-paren">)</span><a class="headerlink" href="#pyscf.mcscf.chkfile.load_mcscf" title="Permalink to this definition">¶</a></dt> <dd></dd></dl> </div> <div class="section" id="module-pyscf.mcscf.df"> <span id="pyscf-mcscf-df-module"></span><h2>pyscf.mcscf.df module<a class="headerlink" href="#module-pyscf.mcscf.df" title="Permalink to this headline">¶</a></h2> <dl class="py function"> <dt id="pyscf.mcscf.df.approx_hessian"> <code class="sig-prename descclassname">pyscf.mcscf.df.</code><code class="sig-name descname">approx_hessian</code><span class="sig-paren">(</span><em class="sig-param"><span class="n">casscf</span></em>, <em class="sig-param"><span class="n">auxbasis</span><span class="o">=</span><span class="default_value">None</span></em>, <em class="sig-param"><span class="n">with_df</span><span class="o">=</span><span class="default_value">None</span></em><span class="sig-paren">)</span><a class="headerlink" href="#pyscf.mcscf.df.approx_hessian" title="Permalink to this definition">¶</a></dt> <dd><p>Approximate the orbital hessian with density fitting integrals</p> <p>Note this function has no effects if the input casscf object is DF-CASSCF. It only modifies the orbital hessian of normal CASSCF object.</p> <dl class="simple"> <dt>Args:</dt><dd><p>casscf : an CASSCF object</p> </dd> <dt>Kwargs:</dt><dd><dl class="simple"> <dt>auxbasis<span class="classifier">str or basis dict</span></dt><dd><p>Same format to the input attribute mol.basis. The default basis ‘weigend+etb’ means weigend-coulomb-fit basis for light elements and even-tempered basis for heavy elements.</p> </dd> </dl> </dd> <dt>Returns:</dt><dd><p>A CASSCF object with approximated JK contraction for orbital hessian</p> </dd> </dl> <p>Examples:</p> <div class="doctest highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">mol</span> <span class="o">=</span> <span class="n">gto</span><span class="o">.</span><span class="n">M</span><span class="p">(</span><span class="n">atom</span><span class="o">=</span><span class="s1">&#39;H 0 0 0; F 0 0 1&#39;</span><span class="p">,</span> <span class="n">basis</span><span class="o">=</span><span class="s1">&#39;ccpvdz&#39;</span><span class="p">,</span> <span class="n">verbose</span><span class="o">=</span><span class="mi">0</span><span class="p">)</span> <span class="gp">&gt;&gt;&gt; </span><span class="n">mf</span> <span class="o">=</span> <span class="n">scf</span><span class="o">.</span><span class="n">RHF</span><span class="p">(</span><span class="n">mol</span><span class="p">)</span> <span class="gp">&gt;&gt;&gt; </span><span class="n">mf</span><span class="o">.</span><span class="n">scf</span><span class="p">()</span> <span class="gp">&gt;&gt;&gt; </span><span class="n">mc</span> <span class="o">=</span> <span class="n">mcscf</span><span class="o">.</span><span class="n">approx_hessian</span><span class="p">(</span><span class="n">mcscf</span><span class="o">.</span><span class="n">CASSCF</span><span class="p">(</span><span class="n">mf</span><span class="p">,</span> <span class="mi">4</span><span class="p">,</span> <span class="mi">4</span><span class="p">))</span> <span class="go">-100.06458716530391</span> </pre></div> </div> </dd></dl> <dl class="py function"> <dt id="pyscf.mcscf.df.density_fit"> <code class="sig-prename descclassname">pyscf.mcscf.df.</code><code class="sig-name descname">density_fit</code><span class="sig-paren">(</span><em class="sig-param"><span class="n">casscf</span></em>, <em class="sig-param"><span class="n">auxbasis</span><span class="o">=</span><span class="default_value">None</span></em>, <em class="sig-param"><span class="n">with_df</span><span class="o">=</span><span class="default_value">None</span></em><span class="sig-paren">)</span><a class="headerlink" href="#pyscf.mcscf.df.density_fit" title="Permalink to this definition">¶</a></dt> <dd><p>Generate DF-CASSCF for given CASSCF object. It is done by overwriting three CASSCF member functions:</p> <blockquote> <div><ul class="simple"> <li><p>casscf.ao2mo which generates MO integrals</p></li> <li><p>casscf.get_veff which generate JK from core density matrix</p></li> <li><p>casscf.get_jk which</p></li> </ul> </div></blockquote> <dl class="simple"> <dt>Args:</dt><dd><p>casscf : an CASSCF object</p> </dd> <dt>Kwargs:</dt><dd><dl class="simple"> <dt>auxbasis<span class="classifier">str or basis dict</span></dt><dd><p>Same format to the input attribute mol.basis. If auxbasis is None, auxiliary basis based on AO basis (if possible) or even-tempered Gaussian basis will be used.</p> </dd> </dl> </dd> <dt>Returns:</dt><dd><p>An CASSCF object with a modified J, K matrix constructor which uses density fitting integrals to compute J and K</p> </dd> </dl> <p>Examples:</p> <div class="doctest highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">mol</span> <span class="o">=</span> <span class="n">gto</span><span class="o">.</span><span class="n">M</span><span class="p">(</span><span class="n">atom</span><span class="o">=</span><span class="s1">&#39;H 0 0 0; F 0 0 1&#39;</span><span class="p">,</span> <span class="n">basis</span><span class="o">=</span><span class="s1">&#39;ccpvdz&#39;</span><span class="p">,</span> <span class="n">verbose</span><span class="o">=</span><span class="mi">0</span><span class="p">)</span> <span class="gp">&gt;&gt;&gt; </span><span class="n">mf</span> <span class="o">=</span> <span class="n">scf</span><span class="o">.</span><span class="n">RHF</span><span class="p">(</span><span class="n">mol</span><span class="p">)</span> <span class="gp">&gt;&gt;&gt; </span><span class="n">mf</span><span class="o">.</span><span class="n">scf</span><span class="p">()</span> <span class="gp">&gt;&gt;&gt; </span><span class="n">mc</span> <span class="o">=</span> <span class="n">DFCASSCF</span><span class="p">(</span><span class="n">mf</span><span class="p">,</span> <span class="mi">4</span><span class="p">,</span> <span class="mi">4</span><span class="p">)</span> <span class="go">-100.05994191570504</span> </pre></div> </div> </dd></dl> <dl class="py function"> <dt id="pyscf.mcscf.df.prange"> <code class="sig-prename descclassname">pyscf.mcscf.df.</code><code class="sig-name descname">prange</code><span class="sig-paren">(</span><em class="sig-param"><span class="n">start</span></em>, <em class="sig-param"><span class="n">end</span></em>, <em class="sig-param"><span class="n">step</span></em><span class="sig-paren">)</span><a class="headerlink" href="#pyscf.mcscf.df.prange" title="Permalink to this definition">¶</a></dt> <dd></dd></dl> </div> <div class="section" id="module-pyscf.mcscf.dmet_cas"> <span id="pyscf-mcscf-dmet-cas-module"></span><h2>pyscf.mcscf.dmet_cas module<a class="headerlink" href="#module-pyscf.mcscf.dmet_cas" title="Permalink to this headline">¶</a></h2> <dl class="py function"> <dt id="pyscf.mcscf.dmet_cas.dmet_cas"> <code class="sig-prename descclassname">pyscf.mcscf.dmet_cas.</code><code class="sig-name descname">dmet_cas</code><span class="sig-paren">(</span><em class="sig-param"><span class="n">mf</span></em>, <em class="sig-param"><span class="n">dm</span></em>, <em class="sig-param"><span class="n">aolabels_or_baslst</span></em>, <em class="sig-param"><span class="n">threshold</span><span class="o">=</span><span class="default_value">0.05</span></em>, <em class="sig-param"><span class="n">occ_cutoff</span><span class="o">=</span><span class="default_value">1e-06</span></em>, <em class="sig-param"><span class="n">base</span><span class="o">=</span><span class="default_value">0</span></em>, <em class="sig-param"><span class="n">orth_method</span><span class="o">=</span><span class="default_value">'meta_lowdin'</span></em>, <em class="sig-param"><span class="n">s</span><span class="o">=</span><span class="default_value">None</span></em>, <em class="sig-param"><span class="n">canonicalize</span><span class="o">=</span><span class="default_value">True</span></em>, <em class="sig-param"><span class="n">freeze_imp</span><span class="o">=</span><span class="default_value">False</span></em>, <em class="sig-param"><span class="n">verbose</span><span class="o">=</span><span class="default_value">None</span></em><span class="sig-paren">)</span><a class="headerlink" href="#pyscf.mcscf.dmet_cas.dmet_cas" title="Permalink to this definition">¶</a></dt> <dd><p>DMET method to generate CASSCF initial guess. Ref. arXiv:1701.07862 [physics.chem-ph]</p> <dl> <dt>Args:</dt><dd><p>mf : an <code class="xref py py-class docutils literal notranslate"><span class="pre">SCF</span></code> object</p> <dl class="simple"> <dt>dm<span class="classifier">2D np.array or a list of 2D array</span></dt><dd><p>Density matrix</p> </dd> <dt>aolabels_or_baslst<span class="classifier">string or a list of strings or a list of index</span></dt><dd><p>AO labels or indices</p> </dd> </dl> </dd> <dt>Kwargs:</dt><dd><dl class="simple"> <dt>threshold<span class="classifier">float</span></dt><dd><p>Entanglement threshold of DMET bath. If the occupancy of an orbital is less than threshold, the orbital is considered as bath orbtial. If occ is greater than (1-threshold), the orbitals are taken for core determinant.</p> </dd> <dt>base<span class="classifier">int</span></dt><dd><p>0-based (C-style) or 1-based (Fortran-style) for baslst if baslst is index list</p> </dd> <dt>orth_method<span class="classifier">str</span></dt><dd><p>It can be one of ‘lowdin’ and ‘meta_lowdin’</p> </dd> <dt>s<span class="classifier">2D array</span></dt><dd><p>AO overlap matrix. This option is mainly used for custom Hamilatonian.</p> </dd> <dt>canonicalize<span class="classifier">bool</span></dt><dd><p>Orbitals defined in AVAS method are local orbitals. Symmetrizing the core, active and virtual space.</p> </dd> </dl> </dd> <dt>Returns:</dt><dd><p>active-space-size, #-active-electrons, orbital-initial-guess-for-CASCI/CASSCF</p> </dd> </dl> <p>Examples:</p> <div class="doctest highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">from</span> <span class="nn">pyscf</span> <span class="kn">import</span> <span class="n">gto</span><span class="p">,</span> <span class="n">scf</span><span class="p">,</span> <span class="n">mcscf</span> <span class="gp">&gt;&gt;&gt; </span><span class="kn">from</span> <span class="nn">pyscf.mcscf</span> <span class="kn">import</span> <span class="n">dmet_cas</span> <span class="gp">&gt;&gt;&gt; </span><span class="n">mol</span> <span class="o">=</span> <span class="n">gto</span><span class="o">.</span><span class="n">M</span><span class="p">(</span><span class="n">atom</span><span class="o">=</span><span class="s1">&#39;Cr 0 0 0; Cr 0 0 1.6&#39;</span><span class="p">,</span> <span class="n">basis</span><span class="o">=</span><span class="s1">&#39;ccpvtz&#39;</span><span class="p">)</span> <span class="gp">&gt;&gt;&gt; </span><span class="n">mf</span> <span class="o">=</span> <span class="n">scf</span><span class="o">.</span><span class="n">RHF</span><span class="p">(</span><span class="n">mol</span><span class="p">)</span><span class="o">.</span><span class="n">run</span><span class="p">()</span> <span class="gp">&gt;&gt;&gt; </span><span class="n">ncas</span><span class="p">,</span> <span class="n">nelecas</span><span class="p">,</span> <span class="n">mo</span> <span class="o">=</span> <span class="n">dmet_cas</span><span class="o">.</span><span class="n">dmet_cas</span><span class="p">(</span><span class="n">mf</span><span class="p">,</span> <span class="p">[</span><span class="s1">&#39;Cr 3d&#39;</span><span class="p">,</span> <span class="s1">&#39;Cr 4s&#39;</span><span class="p">])</span> <span class="gp">&gt;&gt;&gt; </span><span class="n">mc</span> <span class="o">=</span> <span class="n">mcscf</span><span class="o">.</span><span class="n">CASSCF</span><span class="p">(</span><span class="n">mf</span><span class="p">,</span> <span class="n">ncas</span><span class="p">,</span> <span class="n">nelecas</span><span class="p">)</span><span class="o">.</span><span class="n">run</span><span class="p">(</span><span class="n">mo</span><span class="p">)</span> </pre></div> </div> </dd></dl> <dl class="py function"> <dt id="pyscf.mcscf.dmet_cas.guess_cas"> <code class="sig-prename descclassname">pyscf.mcscf.dmet_cas.</code><code class="sig-name descname">guess_cas</code><span class="sig-paren">(</span><em class="sig-param"><span class="n">mf</span></em>, <em class="sig-param"><span class="n">dm</span></em>, <em class="sig-param"><span class="n">aolabels_or_baslst</span></em>, <em class="sig-param"><span class="n">threshold</span><span class="o">=</span><span class="default_value">0.05</span></em>, <em class="sig-param"><span class="n">occ_cutoff</span><span class="o">=</span><span class="default_value">1e-06</span></em>, <em class="sig-param"><span class="n">base</span><span class="o">=</span><span class="default_value">0</span></em>, <em class="sig-param"><span class="n">orth_method</span><span class="o">=</span><span class="default_value">'meta_lowdin'</span></em>, <em class="sig-param"><span class="n">s</span><span class="o">=</span><span class="default_value">None</span></em>, <em class="sig-param"><span class="n">canonicalize</span><span class="o">=</span><span class="default_value">True</span></em>, <em class="sig-param"><span class="n">freeze_imp</span><span class="o">=</span><span class="default_value">False</span></em>, <em class="sig-param"><span class="n">verbose</span><span class="o">=</span><span class="default_value">None</span></em><span class="sig-paren">)</span><a class="headerlink" href="#pyscf.mcscf.dmet_cas.guess_cas" title="Permalink to this definition">¶</a></dt> <dd><p>DMET method to generate CASSCF initial guess. Ref. arXiv:1701.07862 [physics.chem-ph]</p> <dl> <dt>Args:</dt><dd><p>mf : an <code class="xref py py-class docutils literal notranslate"><span class="pre">SCF</span></code> object</p> <dl class="simple"> <dt>dm<span class="classifier">2D np.array or a list of 2D array</span></dt><dd><p>Density matrix</p> </dd> <dt>aolabels_or_baslst<span class="classifier">string or a list of strings or a list of index</span></dt><dd><p>AO labels or indices</p> </dd> </dl> </dd> <dt>Kwargs:</dt><dd><dl class="simple"> <dt>threshold<span class="classifier">float</span></dt><dd><p>Entanglement threshold of DMET bath. If the occupancy of an orbital is less than threshold, the orbital is considered as bath orbtial. If occ is greater than (1-threshold), the orbitals are taken for core determinant.</p> </dd> <dt>base<span class="classifier">int</span></dt><dd><p>0-based (C-style) or 1-based (Fortran-style) for baslst if baslst is index list</p> </dd> <dt>orth_method<span class="classifier">str</span></dt><dd><p>It can be one of ‘lowdin’ and ‘meta_lowdin’</p> </dd> <dt>s<span class="classifier">2D array</span></dt><dd><p>AO overlap matrix. This option is mainly used for custom Hamilatonian.</p> </dd> <dt>canonicalize<span class="classifier">bool</span></dt><dd><p>Orbitals defined in AVAS method are local orbitals. Symmetrizing the core, active and virtual space.</p> </dd> </dl> </dd> <dt>Returns:</dt><dd><p>active-space-size, #-active-electrons, orbital-initial-guess-for-CASCI/CASSCF</p> </dd> </dl> <p>Examples:</p> <div class="doctest highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">from</span> <span class="nn">pyscf</span> <span class="kn">import</span> <span class="n">gto</span><span class="p">,</span> <span class="n">scf</span><span class="p">,</span> <span class="n">mcscf</span> <span class="gp">&gt;&gt;&gt; </span><span class="kn">from</span> <span class="nn">pyscf.mcscf</span> <span class="kn">import</span> <span class="n">dmet_cas</span> <span class="gp">&gt;&gt;&gt; </span><span class="n">mol</span> <span class="o">=</span> <span class="n">gto</span><span class="o">.</span><span class="n">M</span><span class="p">(</span><span class="n">atom</span><span class="o">=</span><span class="s1">&#39;Cr 0 0 0; Cr 0 0 1.6&#39;</span><span class="p">,</span> <span class="n">basis</span><span class="o">=</span><span class="s1">&#39;ccpvtz&#39;</span><span class="p">)</span> <span class="gp">&gt;&gt;&gt; </span><span class="n">mf</span> <span class="o">=</span> <span class="n">scf</span><span class="o">.</span><span class="n">RHF</span><span class="p">(</span><span class="n">mol</span><span class="p">)</span><span class="o">.</span><span class="n">run</span><span class="p">()</span> <span class="gp">&gt;&gt;&gt; </span><span class="n">ncas</span><span class="p">,</span> <span class="n">nelecas</span><span class="p">,</span> <span class="n">mo</span> <span class="o">=</span> <span class="n">dmet_cas</span><span class="o">.</span><span class="n">dmet_cas</span><span class="p">(</span><span class="n">mf</span><span class="p">,</span> <span class="p">[</span><span class="s1">&#39;Cr 3d&#39;</span><span class="p">,</span> <span class="s1">&#39;Cr 4s&#39;</span><span class="p">])</span> <span class="gp">&gt;&gt;&gt; </span><span class="n">mc</span> <span class="o">=</span> <span class="n">mcscf</span><span class="o">.</span><span class="n">CASSCF</span><span class="p">(</span><span class="n">mf</span><span class="p">,</span> <span class="n">ncas</span><span class="p">,</span> <span class="n">nelecas</span><span class="p">)</span><span class="o">.</span><span class="n">run</span><span class="p">(</span><span class="n">mo</span><span class="p">)</span> </pre></div> </div> </dd></dl> <dl class="py function"> <dt id="pyscf.mcscf.dmet_cas.kernel"> <code class="sig-prename descclassname">pyscf.mcscf.dmet_cas.</code><code class="sig-name descname">kernel</code><span class="sig-paren">(</span><em class="sig-param"><span class="n">mf</span></em>, <em class="sig-param"><span class="n">dm</span></em>, <em class="sig-param"><span class="n">aolabels_or_baslst</span></em>, <em class="sig-param"><span class="n">threshold</span><span class="o">=</span><span class="default_value">0.05</span></em>, <em class="sig-param"><span class="n">occ_cutoff</span><span class="o">=</span><span class="default_value">1e-06</span></em>, <em class="sig-param"><span class="n">base</span><span class="o">=</span><span class="default_value">0</span></em>, <em class="sig-param"><span class="n">orth_method</span><span class="o">=</span><span class="default_value">'meta_lowdin'</span></em>, <em class="sig-param"><span class="n">s</span><span class="o">=</span><span class="default_value">None</span></em>, <em class="sig-param"><span class="n">canonicalize</span><span class="o">=</span><span class="default_value">True</span></em>, <em class="sig-param"><span class="n">freeze_imp</span><span class="o">=</span><span class="default_value">False</span></em>, <em class="sig-param"><span class="n">verbose</span><span class="o">=</span><span class="default_value">None</span></em><span class="sig-paren">)</span><a class="headerlink" href="#pyscf.mcscf.dmet_cas.kernel" title="Permalink to this definition">¶</a></dt> <dd><p>DMET method to generate CASSCF initial guess. Ref. arXiv:1701.07862 [physics.chem-ph]</p> <dl> <dt>Args:</dt><dd><p>mf : an <code class="xref py py-class docutils literal notranslate"><span class="pre">SCF</span></code> object</p> <dl class="simple"> <dt>dm<span class="classifier">2D np.array or a list of 2D array</span></dt><dd><p>Density matrix</p> </dd> <dt>aolabels_or_baslst<span class="classifier">string or a list of strings or a list of index</span></dt><dd><p>AO labels or indices</p> </dd> </dl> </dd> <dt>Kwargs:</dt><dd><dl class="simple"> <dt>threshold<span class="classifier">float</span></dt><dd><p>Entanglement threshold of DMET bath. If the occupancy of an orbital is less than threshold, the orbital is considered as bath orbtial. If occ is greater than (1-threshold), the orbitals are taken for core determinant.</p> </dd> <dt>base<span class="classifier">int</span></dt><dd><p>0-based (C-style) or 1-based (Fortran-style) for baslst if baslst is index list</p> </dd> <dt>orth_method<span class="classifier">str</span></dt><dd><p>It can be one of ‘lowdin’ and ‘meta_lowdin’</p> </dd> <dt>s<span class="classifier">2D array</span></dt><dd><p>AO overlap matrix. This option is mainly used for custom Hamilatonian.</p> </dd> <dt>canonicalize<span class="classifier">bool</span></dt><dd><p>Orbitals defined in AVAS method are local orbitals. Symmetrizing the core, active and virtual space.</p> </dd> </dl> </dd> <dt>Returns:</dt><dd><p>active-space-size, #-active-electrons, orbital-initial-guess-for-CASCI/CASSCF</p> </dd> </dl> <p>Examples:</p> <div class="doctest highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">from</span> <span class="nn">pyscf</span> <span class="kn">import</span> <span class="n">gto</span><span class="p">,</span> <span class="n">scf</span><span class="p">,</span> <span class="n">mcscf</span> <span class="gp">&gt;&gt;&gt; </span><span class="kn">from</span> <span class="nn">pyscf.mcscf</span> <span class="kn">import</span> <span class="n">dmet_cas</span> <span class="gp">&gt;&gt;&gt; </span><span class="n">mol</span> <span class="o">=</span> <span class="n">gto</span><span class="o">.</span><span class="n">M</span><span class="p">(</span><span class="n">atom</span><span class="o">=</span><span class="s1">&#39;Cr 0 0 0; Cr 0 0 1.6&#39;</span><span class="p">,</span> <span class="n">basis</span><span class="o">=</span><span class="s1">&#39;ccpvtz&#39;</span><span class="p">)</span> <span class="gp">&gt;&gt;&gt; </span><span class="n">mf</span> <span class="o">=</span> <span class="n">scf</span><span class="o">.</span><span class="n">RHF</span><span class="p">(</span><span class="n">mol</span><span class="p">)</span><span class="o">.</span><span class="n">run</span><span class="p">()</span> <span class="gp">&gt;&gt;&gt; </span><span class="n">ncas</span><span class="p">,</span> <span class="n">nelecas</span><span class="p">,</span> <span class="n">mo</span> <span class="o">=</span> <span class="n">dmet_cas</span><span class="o">.</span><span class="n">dmet_cas</span><span class="p">(</span><span class="n">mf</span><span class="p">,</span> <span class="p">[</span><span class="s1">&#39;Cr 3d&#39;</span><span class="p">,</span> <span class="s1">&#39;Cr 4s&#39;</span><span class="p">])</span> <span class="gp">&gt;&gt;&gt; </span><span class="n">mc</span> <span class="o">=</span> <span class="n">mcscf</span><span class="o">.</span><span class="n">CASSCF</span><span class="p">(</span><span class="n">mf</span><span class="p">,</span> <span class="n">ncas</span><span class="p">,</span> <span class="n">nelecas</span><span class="p">)</span><span class="o">.</span><span class="n">run</span><span class="p">(</span><span class="n">mo</span><span class="p">)</span> </pre></div> </div> </dd></dl> <dl class="py function"> <dt id="pyscf.mcscf.dmet_cas.search_for_degeneracy"> <code class="sig-prename descclassname">pyscf.mcscf.dmet_cas.</code><code class="sig-name descname">search_for_degeneracy</code><span class="sig-paren">(</span><em class="sig-param"><span class="n">e</span></em><span class="sig-paren">)</span><a class="headerlink" href="#pyscf.mcscf.dmet_cas.search_for_degeneracy" title="Permalink to this definition">¶</a></dt> <dd></dd></dl> <dl class="py function"> <dt id="pyscf.mcscf.dmet_cas.symmetrize"> <code class="sig-prename descclassname">pyscf.mcscf.dmet_cas.</code><code class="sig-name descname">symmetrize</code><span class="sig-paren">(</span><em class="sig-param"><span class="n">mol</span></em>, <em class="sig-param"><span class="n">e</span></em>, <em class="sig-param"><span class="n">c</span></em>, <em class="sig-param"><span class="n">s</span></em>, <em class="sig-param"><span class="n">log</span></em><span class="sig-paren">)</span><a class="headerlink" href="#pyscf.mcscf.dmet_cas.symmetrize" title="Permalink to this definition">¶</a></dt> <dd></dd></dl> </div> <div class="section" id="module-pyscf.mcscf.mc1step"> <span id="pyscf-mcscf-mc1step-module"></span><h2>pyscf.mcscf.mc1step module<a class="headerlink" href="#module-pyscf.mcscf.mc1step" title="Permalink to this headline">¶</a></h2> <dl class="py class"> <dt id="pyscf.mcscf.mc1step.CASSCF"> <em class="property">class </em><code class="sig-prename descclassname">pyscf.mcscf.mc1step.</code><code class="sig-name descname">CASSCF</code><span class="sig-paren">(</span><em class="sig-param"><span class="n">mf_or_mol</span></em>, <em class="sig-param"><span class="n">ncas</span></em>, <em class="sig-param"><span class="n">nelecas</span></em>, <em class="sig-param"><span class="n">ncore</span><span class="o">=</span><span class="default_value">None</span></em>, <em class="sig-param"><span class="n">frozen</span><span class="o">=</span><span class="default_value">None</span></em><span class="sig-paren">)</span><a class="headerlink" href="#pyscf.mcscf.mc1step.CASSCF" title="Permalink to this definition">¶</a></dt> <dd><p>Bases: <a class="reference internal" href="#pyscf.mcscf.casci.CASCI" title="pyscf.mcscf.casci.CASCI"><code class="xref py py-class docutils literal notranslate"><span class="pre">pyscf.mcscf.casci.CASCI</span></code></a></p> <dl> <dt>Args:</dt><dd><dl class="simple"> <dt>mf_or_mol<span class="classifier">SCF object or Mole object</span></dt><dd><p>SCF or Mole to define the problem size.</p> </dd> <dt>ncas<span class="classifier">int</span></dt><dd><p>Number of active orbitals.</p> </dd> <dt>nelecas<span class="classifier">int or a pair of int</span></dt><dd><p>Number of electrons in active space.</p> </dd> </dl> </dd> <dt>Kwargs:</dt><dd><dl class="simple"> <dt>ncore<span class="classifier">int</span></dt><dd><p>Number of doubly occupied core orbitals. If not presented, this parameter can be automatically determined.</p> </dd> </dl> </dd> <dt>Attributes:</dt><dd><dl> <dt>verbose<span class="classifier">int</span></dt><dd><p>Print level. Default value equals to <code class="xref py py-class docutils literal notranslate"><span class="pre">Mole.verbose</span></code>.</p> </dd> <dt>max_memory<span class="classifier">float or int</span></dt><dd><p>Allowed memory in MB. Default value equals to <code class="xref py py-class docutils literal notranslate"><span class="pre">Mole.max_memory</span></code>.</p> </dd> <dt>ncas<span class="classifier">int</span></dt><dd><p>Active space size.</p> </dd> <dt>nelecas<span class="classifier">tuple of int</span></dt><dd><p>Active (nelec_alpha, nelec_beta)</p> </dd> <dt>ncore<span class="classifier">int or tuple of int</span></dt><dd><p>Core electron number. In UHF-CASSCF, it’s a tuple to indicate the different core eletron numbers.</p> </dd> <dt>natorb<span class="classifier">bool</span></dt><dd><p>Whether to transform natural orbitals in active space. Note: when CASCI/CASSCF are combined with DMRG solver or selected CI solver, enabling this parameter may slightly change the total energy. False by default.</p> </dd> <dt>canonicalization<span class="classifier">bool</span></dt><dd><p>Whether to canonicalize orbitals in core and external space against the general Fock matrix. The orbitals in active space are NOT transformed by default. To get the natural orbitals in active space, the attribute .natorb needs to be enabled. True by default.</p> </dd> <dt>sorting_mo_energy<span class="classifier">bool</span></dt><dd><p>Whether to sort the orbitals based on the diagonal elements of the general Fock matrix. Default is False.</p> </dd> <dt>fcisolver<span class="classifier">an instance of <code class="xref py py-class docutils literal notranslate"><span class="pre">FCISolver</span></code></span></dt><dd><p>The pyscf.fci module provides several FCISolver for different scenario. Generally, fci.direct_spin1.FCISolver can be used for all RHF-CASSCF. However, a proper FCISolver can provide better performance and better numerical stability. One can either use <code class="xref py py-func docutils literal notranslate"><span class="pre">fci.solver()</span></code> function to pick the FCISolver by the program or manually assigen the FCISolver to this attribute, e.g.</p> <div class="doctest highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">from</span> <span class="nn">pyscf</span> <span class="kn">import</span> <span class="n">fci</span> <span class="gp">&gt;&gt;&gt; </span><span class="n">mc</span> <span class="o">=</span> <span class="n">mcscf</span><span class="o">.</span><span class="n">CASSCF</span><span class="p">(</span><span class="n">mf</span><span class="p">,</span> <span class="mi">4</span><span class="p">,</span> <span class="mi">4</span><span class="p">)</span> <span class="gp">&gt;&gt;&gt; </span><span class="n">mc</span><span class="o">.</span><span class="n">fcisolver</span> <span class="o">=</span> <span class="n">fci</span><span class="o">.</span><span class="n">solver</span><span class="p">(</span><span class="n">mol</span><span class="p">,</span> <span class="n">singlet</span><span class="o">=</span><span class="kc">True</span><span class="p">)</span> <span class="gp">&gt;&gt;&gt; </span><span class="n">mc</span><span class="o">.</span><span class="n">fcisolver</span> <span class="o">=</span> <span class="n">fci</span><span class="o">.</span><span class="n">direct_spin1</span><span class="o">.</span><span class="n">FCISolver</span><span class="p">(</span><span class="n">mol</span><span class="p">)</span> </pre></div> </div> <p>You can control FCISolver by setting e.g.:</p> <div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">mc</span><span class="o">.</span><span class="n">fcisolver</span><span class="o">.</span><span class="n">max_cycle</span> <span class="o">=</span> <span class="mi">30</span> <span class="gp">&gt;&gt;&gt; </span><span class="n">mc</span><span class="o">.</span><span class="n">fcisolver</span><span class="o">.</span><span class="n">conv_tol</span> <span class="o">=</span> <span class="mf">1e-7</span> </pre></div> </div> <p>For more details of the parameter for FCISolver, See <code class="xref py py-mod docutils literal notranslate"><span class="pre">fci</span></code>.</p> </dd> </dl> </dd> </dl> <p>Saved results</p> <blockquote> <div><dl class="simple"> <dt>e_tot<span class="classifier">float</span></dt><dd><p>Total MCSCF energy (electronic energy plus nuclear repulsion)</p> </dd> <dt>e_cas<span class="classifier">float</span></dt><dd><p>CAS space FCI energy</p> </dd> <dt>ci<span class="classifier">ndarray</span></dt><dd><p>CAS space FCI coefficients</p> </dd> <dt>mo_coeff<span class="classifier">ndarray</span></dt><dd><p>When canonicalization is specified, the orbitals are canonical orbitals which make the general Fock matrix (Fock operator on top of MCSCF 1-particle density matrix) diagonalized within each subspace (core, active, external). If natorb (natural orbitals in active space) is specified, the active segment of the mo_coeff is natural orbitls.</p> </dd> <dt>mo_energy<span class="classifier">ndarray</span></dt><dd><p>Diagonal elements of general Fock matrix (in mo_coeff representation).</p> </dd> <dt>mo_occ<span class="classifier">ndarray</span></dt><dd><p>Occupation numbers of natural orbitals if natorb is specified.</p> </dd> </dl> </div></blockquote> <p>Examples:</p> <div class="doctest highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">from</span> <span class="nn">pyscf</span> <span class="kn">import</span> <span class="n">gto</span><span class="p">,</span> <span class="n">scf</span><span class="p">,</span> <span class="n">mcscf</span> <span class="gp">&gt;&gt;&gt; </span><span class="n">mol</span> <span class="o">=</span> <span class="n">gto</span><span class="o">.</span><span class="n">M</span><span class="p">(</span><span class="n">atom</span><span class="o">=</span><span class="s1">&#39;N 0 0 0; N 0 0 1&#39;</span><span class="p">,</span> <span class="n">basis</span><span class="o">=</span><span class="s1">&#39;ccpvdz&#39;</span><span class="p">,</span> <span class="n">verbose</span><span class="o">=</span><span class="mi">0</span><span class="p">)</span> <span class="gp">&gt;&gt;&gt; </span><span class="n">mf</span> <span class="o">=</span> <span class="n">scf</span><span class="o">.</span><span class="n">RHF</span><span class="p">(</span><span class="n">mol</span><span class="p">)</span> <span class="gp">&gt;&gt;&gt; </span><span class="n">mf</span><span class="o">.</span><span class="n">scf</span><span class="p">()</span> <span class="gp">&gt;&gt;&gt; </span><span class="n">mc</span> <span class="o">=</span> <span class="n">mcscf</span><span class="o">.</span><span class="n">CASCI</span><span class="p">(</span><span class="n">mf</span><span class="p">,</span> <span class="mi">6</span><span class="p">,</span> <span class="mi">6</span><span class="p">)</span> <span class="gp">&gt;&gt;&gt; </span><span class="n">mc</span><span class="o">.</span><span class="n">kernel</span><span class="p">()[</span><span class="mi">0</span><span class="p">]</span> <span class="go">-108.980200816243354</span> <span class="go">CASSCF</span> </pre></div> </div> <p>Extra attributes for CASSCF:</p> <blockquote> <div><dl> <dt>conv_tol<span class="classifier">float</span></dt><dd><p>Converge threshold. Default is 1e-7</p> </dd> <dt>conv_tol_grad<span class="classifier">float</span></dt><dd><p>Converge threshold for CI gradients and orbital rotation gradients. Default is 1e-4</p> </dd> <dt>max_stepsize<span class="classifier">float</span></dt><dd><p>The step size for orbital rotation. Small step (0.005 - 0.05) is prefered. Default is 0.03.</p> </dd> <dt>max_cycle_macro<span class="classifier">int</span></dt><dd><p>Max number of macro iterations. Default is 50.</p> </dd> <dt>max_cycle_micro<span class="classifier">int</span></dt><dd><p>Max number of micro iterations in each macro iteration. Depending on systems, increasing this value might reduce the total macro iterations. Generally, 2 - 5 steps should be enough. Default is 3.</p> </dd> <dt>ah_level_shift<span class="classifier">float, for AH solver.</span></dt><dd><p>Level shift for the Davidson diagonalization in AH solver. Default is 1e-8.</p> </dd> <dt>ah_conv_tol<span class="classifier">float, for AH solver.</span></dt><dd><p>converge threshold for AH solver. Default is 1e-12.</p> </dd> <dt>ah_max_cycle<span class="classifier">float, for AH solver.</span></dt><dd><p>Max number of iterations allowd in AH solver. Default is 30.</p> </dd> <dt>ah_lindep<span class="classifier">float, for AH solver.</span></dt><dd><p>Linear dependence threshold for AH solver. Default is 1e-14.</p> </dd> <dt>ah_start_tol<span class="classifier">flat, for AH solver.</span></dt><dd><p>In AH solver, the orbital rotation is started without completely solving the AH problem. This value is to control the start point. Default is 0.2.</p> </dd> <dt>ah_start_cycle<span class="classifier">int, for AH solver.</span></dt><dd><p>In AH solver, the orbital rotation is started without completely solving the AH problem. This value is to control the start point. Default is 2.</p> <p><code class="docutils literal notranslate"><span class="pre">ah_conv_tol</span></code>, <code class="docutils literal notranslate"><span class="pre">ah_max_cycle</span></code>, <code class="docutils literal notranslate"><span class="pre">ah_lindep</span></code>, <code class="docutils literal notranslate"><span class="pre">ah_start_tol</span></code> and <code class="docutils literal notranslate"><span class="pre">ah_start_cycle</span></code> can affect the accuracy and performance of CASSCF solver. Lower <code class="docutils literal notranslate"><span class="pre">ah_conv_tol</span></code> and <code class="docutils literal notranslate"><span class="pre">ah_lindep</span></code> might improve the accuracy of CASSCF optimization, but decrease the performance.</p> <div class="doctest highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">from</span> <span class="nn">pyscf</span> <span class="kn">import</span> <span class="n">gto</span><span class="p">,</span> <span class="n">scf</span><span class="p">,</span> <span class="n">mcscf</span> <span class="gp">&gt;&gt;&gt; </span><span class="n">mol</span> <span class="o">=</span> <span class="n">gto</span><span class="o">.</span><span class="n">M</span><span class="p">(</span><span class="n">atom</span><span class="o">=</span><span class="s1">&#39;N 0 0 0; N 0 0 1&#39;</span><span class="p">,</span> <span class="n">basis</span><span class="o">=</span><span class="s1">&#39;ccpvdz&#39;</span><span class="p">,</span> <span class="n">verbose</span><span class="o">=</span><span class="mi">0</span><span class="p">)</span> <span class="gp">&gt;&gt;&gt; </span><span class="n">mf</span> <span class="o">=</span> <span class="n">scf</span><span class="o">.</span><span class="n">UHF</span><span class="p">(</span><span class="n">mol</span><span class="p">)</span> <span class="gp">&gt;&gt;&gt; </span><span class="n">mf</span><span class="o">.</span><span class="n">scf</span><span class="p">()</span> <span class="gp">&gt;&gt;&gt; </span><span class="n">mc</span> <span class="o">=</span> <span class="n">mcscf</span><span class="o">.</span><span class="n">CASSCF</span><span class="p">(</span><span class="n">mf</span><span class="p">,</span> <span class="mi">6</span><span class="p">,</span> <span class="mi">6</span><span class="p">)</span> <span class="gp">&gt;&gt;&gt; </span><span class="n">mc</span><span class="o">.</span><span class="n">conv_tol</span> <span class="o">=</span> <span class="mf">1e-10</span> <span class="gp">&gt;&gt;&gt; </span><span class="n">mc</span><span class="o">.</span><span class="n">ah_conv_tol</span> <span class="o">=</span> <span class="mf">1e-5</span> <span class="gp">&gt;&gt;&gt; </span><span class="n">mc</span><span class="o">.</span><span class="n">kernel</span><span class="p">()[</span><span class="mi">0</span><span class="p">]</span> <span class="go">-109.044401898486001</span> <span class="gp">&gt;&gt;&gt; </span><span class="n">mc</span><span class="o">.</span><span class="n">ah_conv_tol</span> <span class="o">=</span> <span class="mf">1e-10</span> <span class="gp">&gt;&gt;&gt; </span><span class="n">mc</span><span class="o">.</span><span class="n">kernel</span><span class="p">()[</span><span class="mi">0</span><span class="p">]</span> <span class="go">-109.044401887945668</span> </pre></div> </div> </dd> <dt>chkfile<span class="classifier">str</span></dt><dd><p>Checkpoint file to save the intermediate orbitals during the CASSCF optimization. Default is the checkpoint file of mean field object.</p> </dd> <dt>ci_response_space<span class="classifier">int</span></dt><dd><p>subspace size to solve the CI vector response. Default is 3.</p> </dd> <dt>callback<span class="classifier">function(envs_dict) =&gt; None</span></dt><dd><p>callback function takes one dict as the argument which is generated by the builtin function <code class="xref py py-func docutils literal notranslate"><span class="pre">locals()</span></code>, so that the callback function can access all local variables in the current envrionment.</p> </dd> <dt>scale_restoration<span class="classifier">float</span></dt><dd><p>When a step of orbital rotation moves out of trust region, the orbital optimization will be restored to previous state and the step size of the orbital rotation needs to be reduced. scale_restoration controls how much to scale down the step size.</p> </dd> </dl> </div></blockquote> <p>Saved results</p> <blockquote> <div><dl class="simple"> <dt>e_tot<span class="classifier">float</span></dt><dd><p>Total MCSCF energy (electronic energy plus nuclear repulsion)</p> </dd> <dt>e_cas<span class="classifier">float</span></dt><dd><p>CAS space FCI energy</p> </dd> <dt>ci<span class="classifier">ndarray</span></dt><dd><p>CAS space FCI coefficients</p> </dd> <dt>mo_coeff<span class="classifier">ndarray</span></dt><dd><p>Optimized CASSCF orbitals coefficients. When canonicalization is specified, the returned orbitals make the general Fock matrix (Fock operator on top of MCSCF 1-particle density matrix) diagonalized within each subspace (core, active, external). If natorb (natural orbitals in active space) is enabled, the active segment of mo_coeff is transformed to natural orbitals.</p> </dd> <dt>mo_energy<span class="classifier">ndarray</span></dt><dd><p>Diagonal elements of general Fock matrix (in mo_coeff representation).</p> </dd> </dl> </div></blockquote> <p>Examples:</p> <div class="doctest highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">from</span> <span class="nn">pyscf</span> <span class="kn">import</span> <span class="n">gto</span><span class="p">,</span> <span class="n">scf</span><span class="p">,</span> <span class="n">mcscf</span> <span class="gp">&gt;&gt;&gt; </span><span class="n">mol</span> <span class="o">=</span> <span class="n">gto</span><span class="o">.</span><span class="n">M</span><span class="p">(</span><span class="n">atom</span><span class="o">=</span><span class="s1">&#39;N 0 0 0; N 0 0 1&#39;</span><span class="p">,</span> <span class="n">basis</span><span class="o">=</span><span class="s1">&#39;ccpvdz&#39;</span><span class="p">,</span> <span class="n">verbose</span><span class="o">=</span><span class="mi">0</span><span class="p">)</span> <span class="gp">&gt;&gt;&gt; </span><span class="n">mf</span> <span class="o">=</span> <span class="n">scf</span><span class="o">.</span><span class="n">RHF</span><span class="p">(</span><span class="n">mol</span><span class="p">)</span> <span class="gp">&gt;&gt;&gt; </span><span class="n">mf</span><span class="o">.</span><span class="n">scf</span><span class="p">()</span> <span class="gp">&gt;&gt;&gt; </span><span class="n">mc</span> <span class="o">=</span> <span class="n">mcscf</span><span class="o">.</span><span class="n">CASSCF</span><span class="p">(</span><span class="n">mf</span><span class="p">,</span> <span class="mi">6</span><span class="p">,</span> <span class="mi">6</span><span class="p">)</span> <span class="gp">&gt;&gt;&gt; </span><span class="n">mc</span><span class="o">.</span><span class="n">kernel</span><span class="p">()[</span><span class="mi">0</span><span class="p">]</span> <span class="go">-109.044401882238134</span> </pre></div> </div> <dl class="py method"> <dt id="pyscf.mcscf.mc1step.CASSCF.Gradients"> <code class="sig-name descname">Gradients</code><span class="sig-paren">(</span><em class="sig-param"><span class="o">*</span><span class="n">args</span></em>, <em class="sig-param"><span class="o">**</span><span class="n">kwargs</span></em><span class="sig-paren">)</span><a class="headerlink" href="#pyscf.mcscf.mc1step.CASSCF.Gradients" title="Permalink to this definition">¶</a></dt> <dd><p>Non-relativistic restricted Hartree-Fock gradients</p> </dd></dl> <dl class="py attribute"> <dt id="pyscf.mcscf.mc1step.CASSCF.ah_conv_tol"> <code class="sig-name descname">ah_conv_tol</code><em class="property"> = 1e-12</em><a class="headerlink" href="#pyscf.mcscf.mc1step.CASSCF.ah_conv_tol" title="Permalink to this definition">¶</a></dt> <dd></dd></dl> <dl class="py attribute"> <dt id="pyscf.mcscf.mc1step.CASSCF.ah_grad_trust_region"> <code class="sig-name descname">ah_grad_trust_region</code><em class="property"> = 3.0</em><a class="headerlink" href="#pyscf.mcscf.mc1step.CASSCF.ah_grad_trust_region" title="Permalink to this definition">¶</a></dt> <dd></dd></dl> <dl class="py attribute"> <dt id="pyscf.mcscf.mc1step.CASSCF.ah_level_shift"> <code class="sig-name descname">ah_level_shift</code><em class="property"> = 1e-08</em><a class="headerlink" href="#pyscf.mcscf.mc1step.CASSCF.ah_level_shift" title="Permalink to this definition">¶</a></dt> <dd></dd></dl> <dl class="py attribute"> <dt id="pyscf.mcscf.mc1step.CASSCF.ah_lindep"> <code class="sig-name descname">ah_lindep</code><em class="property"> = 1e-14</em><a class="headerlink" href="#pyscf.mcscf.mc1step.CASSCF.ah_lindep" title="Permalink to this definition">¶</a></dt> <dd></dd></dl> <dl class="py attribute"> <dt id="pyscf.mcscf.mc1step.CASSCF.ah_max_cycle"> <code class="sig-name descname">ah_max_cycle</code><em class="property"> = 30</em><a class="headerlink" href="#pyscf.mcscf.mc1step.CASSCF.ah_max_cycle" title="Permalink to this definition">¶</a></dt> <dd></dd></dl> <dl class="py method"> <dt id="pyscf.mcscf.mc1step.CASSCF.ah_scheduler"> <code class="sig-name descname">ah_scheduler</code><span class="sig-paren">(</span><em class="sig-param"><span class="n">envs</span></em><span class="sig-paren">)</span><a class="headerlink" href="#pyscf.mcscf.mc1step.CASSCF.ah_scheduler" title="Permalink to this definition">¶</a></dt> <dd></dd></dl> <dl class="py attribute"> <dt id="pyscf.mcscf.mc1step.CASSCF.ah_start_cycle"> <code class="sig-name descname">ah_start_cycle</code><em class="property"> = 3</em><a class="headerlink" href="#pyscf.mcscf.mc1step.CASSCF.ah_start_cycle" title="Permalink to this definition">¶</a></dt> <dd></dd></dl> <dl class="py attribute"> <dt id="pyscf.mcscf.mc1step.CASSCF.ah_start_tol"> <code class="sig-name descname">ah_start_tol</code><em class="property"> = 2.5</em><a class="headerlink" href="#pyscf.mcscf.mc1step.CASSCF.ah_start_tol" title="Permalink to this definition">¶</a></dt> <dd></dd></dl> <dl class="py method"> <dt id="pyscf.mcscf.mc1step.CASSCF.ao2mo"> <code class="sig-name descname">ao2mo</code><span class="sig-paren">(</span><em class="sig-param"><span class="n">mo_coeff</span><span class="o">=</span><span class="default_value">None</span></em><span class="sig-paren">)</span><a class="headerlink" href="#pyscf.mcscf.mc1step.CASSCF.ao2mo" title="Permalink to this definition">¶</a></dt> <dd><p>Compute the active space two-particle Hamiltonian.</p> </dd></dl> <dl class="py attribute"> <dt id="pyscf.mcscf.mc1step.CASSCF.ao2mo_level"> <code class="sig-name descname">ao2mo_level</code><em class="property"> = 2</em><a class="headerlink" href="#pyscf.mcscf.mc1step.CASSCF.ao2mo_level" title="Permalink to this definition">¶</a></dt> <dd></dd></dl> <dl class="py method"> <dt id="pyscf.mcscf.mc1step.CASSCF.approx_hessian"> <code class="sig-name descname">approx_hessian</code><span class="sig-paren">(</span><em class="sig-param"><span class="n">auxbasis</span><span class="o">=</span><span class="default_value">None</span></em>, <em class="sig-param"><span class="n">with_df</span><span class="o">=</span><span class="default_value">None</span></em><span class="sig-paren">)</span><a class="headerlink" href="#pyscf.mcscf.mc1step.CASSCF.approx_hessian" title="Permalink to this definition">¶</a></dt> <dd></dd></dl> <dl class="py method"> <dt id="pyscf.mcscf.mc1step.CASSCF.as_scanner"> <code class="sig-name descname">as_scanner</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#pyscf.mcscf.mc1step.CASSCF.as_scanner" title="Permalink to this definition">¶</a></dt> <dd><p>Generating a scanner for CASSCF PES.</p> <p>The returned solver is a function. This function requires one argument “mol” as input and returns total CASSCF energy.</p> <p>The solver will automatically use the results of last calculation as the initial guess of the new calculation. All parameters of MCSCF object (conv_tol, max_memory etc) are automatically applied in the solver.</p> <p>Note scanner has side effects. It may change many underlying objects (_scf, with_df, with_x2c, …) during calculation.</p> <p>Examples:</p> <div class="doctest highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">from</span> <span class="nn">pyscf</span> <span class="kn">import</span> <span class="n">gto</span><span class="p">,</span> <span class="n">scf</span><span class="p">,</span> <span class="n">mcscf</span> <span class="gp">&gt;&gt;&gt; </span><span class="n">mol</span> <span class="o">=</span> <span class="n">gto</span><span class="o">.</span><span class="n">M</span><span class="p">(</span><span class="n">atom</span><span class="o">=</span><span class="s1">&#39;N 0 0 0; N 0 0 1.2&#39;</span><span class="p">,</span> <span class="n">verbose</span><span class="o">=</span><span class="mi">0</span><span class="p">)</span> <span class="gp">&gt;&gt;&gt; </span><span class="n">mc_scanner</span> <span class="o">=</span> <span class="n">mcscf</span><span class="o">.</span><span class="n">CASSCF</span><span class="p">(</span><span class="n">scf</span><span class="o">.</span><span class="n">RHF</span><span class="p">(</span><span class="n">mol</span><span class="p">),</span> <span class="mi">4</span><span class="p">,</span> <span class="mi">4</span><span class="p">)</span><span class="o">.</span><span class="n">as_scanner</span><span class="p">()</span> <span class="gp">&gt;&gt;&gt; </span><span class="n">e</span> <span class="o">=</span> <span class="n">mc_scanner</span><span class="p">(</span><span class="n">gto</span><span class="o">.</span><span class="n">M</span><span class="p">(</span><span class="n">atom</span><span class="o">=</span><span class="s1">&#39;N 0 0 0; N 0 0 1.1&#39;</span><span class="p">))</span> <span class="gp">&gt;&gt;&gt; </span><span class="n">e</span> <span class="o">=</span> <span class="n">mc_scanner</span><span class="p">(</span><span class="n">gto</span><span class="o">.</span><span class="n">M</span><span class="p">(</span><span class="n">atom</span><span class="o">=</span><span class="s1">&#39;N 0 0 0; N 0 0 1.5&#39;</span><span class="p">))</span> </pre></div> </div> </dd></dl> <dl class="py attribute"> <dt id="pyscf.mcscf.mc1step.CASSCF.canonicalization"> <code class="sig-name descname">canonicalization</code><em class="property"> = True</em><a class="headerlink" href="#pyscf.mcscf.mc1step.CASSCF.canonicalization" title="Permalink to this definition">¶</a></dt> <dd></dd></dl> <dl class="py method"> <dt id="pyscf.mcscf.mc1step.CASSCF.casci"> <code class="sig-name descname">casci</code><span class="sig-paren">(</span><em class="sig-param"><span class="n">mo_coeff</span></em>, <em class="sig-param"><span class="n">ci0</span><span class="o">=</span><span class="default_value">None</span></em>, <em class="sig-param"><span class="n">eris</span><span class="o">=</span><span class="default_value">None</span></em>, <em class="sig-param"><span class="n">verbose</span><span class="o">=</span><span class="default_value">None</span></em>, <em class="sig-param"><span class="n">envs</span><span class="o">=</span><span class="default_value">None</span></em><span class="sig-paren">)</span><a class="headerlink" href="#pyscf.mcscf.mc1step.CASSCF.casci" title="Permalink to this definition">¶</a></dt> <dd></dd></dl> <dl class="py attribute"> <dt id="pyscf.mcscf.mc1step.CASSCF.chk_ci"> <code class="sig-name descname">chk_ci</code><em class="property"> = False</em><a class="headerlink" href="#pyscf.mcscf.mc1step.CASSCF.chk_ci" title="Permalink to this definition">¶</a></dt> <dd></dd></dl> <dl class="py attribute"> <dt id="pyscf.mcscf.mc1step.CASSCF.ci_grad_trust_region"> <code class="sig-name descname">ci_grad_trust_region</code><em class="property"> = 3.0</em><a class="headerlink" href="#pyscf.mcscf.mc1step.CASSCF.ci_grad_trust_region" title="Permalink to this definition">¶</a></dt> <dd></dd></dl> <dl class="py attribute"> <dt id="pyscf.mcscf.mc1step.CASSCF.ci_response_space"> <code class="sig-name descname">ci_response_space</code><em class="property"> = 4</em><a class="headerlink" href="#pyscf.mcscf.mc1step.CASSCF.ci_response_space" title="Permalink to this definition">¶</a></dt> <dd></dd></dl> <dl class="py method"> <dt id="pyscf.mcscf.mc1step.CASSCF.ci_update_dep"> <em class="property">property </em><code class="sig-name descname">ci_update_dep</code><a class="headerlink" href="#pyscf.mcscf.mc1step.CASSCF.ci_update_dep" title="Permalink to this definition">¶</a></dt> <dd></dd></dl> <dl class="py attribute"> <dt id="pyscf.mcscf.mc1step.CASSCF.conv_tol"> <code class="sig-name descname">conv_tol</code><em class="property"> = 1e-07</em><a class="headerlink" href="#pyscf.mcscf.mc1step.CASSCF.conv_tol" title="Permalink to this definition">¶</a></dt> <dd></dd></dl> <dl class="py attribute"> <dt id="pyscf.mcscf.mc1step.CASSCF.conv_tol_grad"> <code class="sig-name descname">conv_tol_grad</code><em class="property"> = None</em><a class="headerlink" href="#pyscf.mcscf.mc1step.CASSCF.conv_tol_grad" title="Permalink to this definition">¶</a></dt> <dd></dd></dl> <dl class="py method"> <dt id="pyscf.mcscf.mc1step.CASSCF.dump_chk"> <code class="sig-name descname">dump_chk</code><span class="sig-paren">(</span><em class="sig-param"><span class="n">envs</span></em><span class="sig-paren">)</span><a class="headerlink" href="#pyscf.mcscf.mc1step.CASSCF.dump_chk" title="Permalink to this definition">¶</a></dt> <dd></dd></dl> <dl class="py method"> <dt id="pyscf.mcscf.mc1step.CASSCF.dump_flags"> <code class="sig-name descname">dump_flags</code><span class="sig-paren">(</span><em class="sig-param"><span class="n">verbose</span><span class="o">=</span><span class="default_value">None</span></em><span class="sig-paren">)</span><a class="headerlink" href="#pyscf.mcscf.mc1step.CASSCF.dump_flags" title="Permalink to this definition">¶</a></dt> <dd></dd></dl> <dl class="py method"> <dt id="pyscf.mcscf.mc1step.CASSCF.gen_g_hop"> <code class="sig-name descname">gen_g_hop</code><span class="sig-paren">(</span><em class="sig-param"><span class="n">mo</span></em>, <em class="sig-param"><span class="n">u</span></em>, <em class="sig-param"><span class="n">casdm1</span></em>, <em class="sig-param"><span class="n">casdm2</span></em>, <em class="sig-param"><span class="n">eris</span></em><span class="sig-paren">)</span><a class="headerlink" href="#pyscf.mcscf.mc1step.CASSCF.gen_g_hop" title="Permalink to this definition">¶</a></dt> <dd></dd></dl> <dl class="py method"> <dt id="pyscf.mcscf.mc1step.CASSCF.get_grad"> <code class="sig-name descname">get_grad</code><span class="sig-paren">(</span><em class="sig-param"><span class="n">mo_coeff</span><span class="o">=</span><span class="default_value">None</span></em>, <em class="sig-param"><span class="n">casdm1_casdm2</span><span class="o">=</span><span class="default_value">None</span></em>, <em class="sig-param"><span class="n">eris</span><span class="o">=</span><span class="default_value">None</span></em><span class="sig-paren">)</span><a class="headerlink" href="#pyscf.mcscf.mc1step.CASSCF.get_grad" title="Permalink to this definition">¶</a></dt> <dd><p>Orbital gradients</p> </dd></dl> <dl class="py method"> <dt id="pyscf.mcscf.mc1step.CASSCF.get_h2cas"> <code class="sig-name descname">get_h2cas</code><span class="sig-paren">(</span><em class="sig-param"><span class="n">mo_coeff</span><span class="o">=</span><span class="default_value">None</span></em><span class="sig-paren">)</span><a class="headerlink" href="#pyscf.mcscf.mc1step.CASSCF.get_h2cas" title="Permalink to this definition">¶</a></dt> <dd><p>Computing active space two-particle Hamiltonian.</p> <p>Note It is different to get_h2eff when df.approx_hessian is applied, in which get_h2eff function returns the DF integrals while get_h2cas returns the regular 2-electron integrals.</p> </dd></dl> <dl class="py method"> <dt id="pyscf.mcscf.mc1step.CASSCF.get_h2eff"> <code class="sig-name descname">get_h2eff</code><span class="sig-paren">(</span><em class="sig-param"><span class="n">mo_coeff</span><span class="o">=</span><span class="default_value">None</span></em><span class="sig-paren">)</span><a class="headerlink" href="#pyscf.mcscf.mc1step.CASSCF.get_h2eff" title="Permalink to this definition">¶</a></dt> <dd><p>Computing active space two-particle Hamiltonian.</p> <p>Note It is different to get_h2cas when df.approx_hessian is applied, in which get_h2eff function returns the DF integrals while get_h2cas returns the regular 2-electron integrals.</p> </dd></dl> <dl class="py method"> <dt id="pyscf.mcscf.mc1step.CASSCF.grad_update_dep"> <em class="property">property </em><code class="sig-name descname">grad_update_dep</code><a class="headerlink" href="#pyscf.mcscf.mc1step.CASSCF.grad_update_dep" title="Permalink to this definition">¶</a></dt> <dd></dd></dl> <dl class="py attribute"> <dt id="pyscf.mcscf.mc1step.CASSCF.internal_rotation"> <code class="sig-name descname">internal_rotation</code><em class="property"> = False</em><a class="headerlink" href="#pyscf.mcscf.mc1step.CASSCF.internal_rotation" title="Permalink to this definition">¶</a></dt> <dd></dd></dl> <dl class="py method"> <dt id="pyscf.mcscf.mc1step.CASSCF.kernel"> <code class="sig-name descname">kernel</code><span class="sig-paren">(</span><em class="sig-param">mo_coeff=None</em>, <em class="sig-param">ci0=None</em>, <em class="sig-param">callback=None</em>, <em class="sig-param">_kern=&lt;function kernel&gt;</em><span class="sig-paren">)</span><a class="headerlink" href="#pyscf.mcscf.mc1step.CASSCF.kernel" title="Permalink to this definition">¶</a></dt> <dd><dl class="simple"> <dt>Returns:</dt><dd><p>Five elements, they are total energy, active space CI energy, the active space FCI wavefunction coefficients or DMRG wavefunction ID, the MCSCF canonical orbital coefficients, the MCSCF canonical orbital coefficients.</p> </dd> </dl> <p>They are attributes of mcscf object, which can be accessed by .e_tot, .e_cas, .ci, .mo_coeff, .mo_energy</p> </dd></dl> <dl class="py attribute"> <dt id="pyscf.mcscf.mc1step.CASSCF.kf_interval"> <code class="sig-name descname">kf_interval</code><em class="property"> = 4</em><a class="headerlink" href="#pyscf.mcscf.mc1step.CASSCF.kf_interval" title="Permalink to this definition">¶</a></dt> <dd></dd></dl> <dl class="py attribute"> <dt id="pyscf.mcscf.mc1step.CASSCF.kf_trust_region"> <code class="sig-name descname">kf_trust_region</code><em class="property"> = 3.0</em><a class="headerlink" href="#pyscf.mcscf.mc1step.CASSCF.kf_trust_region" title="Permalink to this definition">¶</a></dt> <dd></dd></dl> <dl class="py method"> <dt id="pyscf.mcscf.mc1step.CASSCF.max_cycle"> <em class="property">property </em><code class="sig-name descname">max_cycle</code><a class="headerlink" href="#pyscf.mcscf.mc1step.CASSCF.max_cycle" title="Permalink to this definition">¶</a></dt> <dd></dd></dl> <dl class="py attribute"> <dt id="pyscf.mcscf.mc1step.CASSCF.max_cycle_macro"> <code class="sig-name descname">max_cycle_macro</code><em class="property"> = 50</em><a class="headerlink" href="#pyscf.mcscf.mc1step.CASSCF.max_cycle_macro" title="Permalink to this definition">¶</a></dt> <dd></dd></dl> <dl class="py attribute"> <dt id="pyscf.mcscf.mc1step.CASSCF.max_cycle_micro"> <code class="sig-name descname">max_cycle_micro</code><em class="property"> = 4</em><a class="headerlink" href="#pyscf.mcscf.mc1step.CASSCF.max_cycle_micro" title="Permalink to this definition">¶</a></dt> <dd></dd></dl> <dl class="py method"> <dt id="pyscf.mcscf.mc1step.CASSCF.max_orb_stepsize"> <em class="property">property </em><code class="sig-name descname">max_orb_stepsize</code><a class="headerlink" href="#pyscf.mcscf.mc1step.CASSCF.max_orb_stepsize" title="Permalink to this definition">¶</a></dt> <dd></dd></dl> <dl class="py attribute"> <dt id="pyscf.mcscf.mc1step.CASSCF.max_stepsize"> <code class="sig-name descname">max_stepsize</code><em class="property"> = 0.02</em><a class="headerlink" href="#pyscf.mcscf.mc1step.CASSCF.max_stepsize" title="Permalink to this definition">¶</a></dt> <dd></dd></dl> <dl class="py method"> <dt id="pyscf.mcscf.mc1step.CASSCF.max_stepsize_scheduler"> <code class="sig-name descname">max_stepsize_scheduler</code><span class="sig-paren">(</span><em class="sig-param"><span class="n">envs</span></em><span class="sig-paren">)</span><a class="headerlink" href="#pyscf.mcscf.mc1step.CASSCF.max_stepsize_scheduler" title="Permalink to this definition">¶</a></dt> <dd></dd></dl> <dl class="py method"> <dt id="pyscf.mcscf.mc1step.CASSCF.mc1step"> <code class="sig-name descname">mc1step</code><span class="sig-paren">(</span><em class="sig-param"><span class="n">mo_coeff</span><span class="o">=</span><span class="default_value">None</span></em>, <em class="sig-param"><span class="n">ci0</span><span class="o">=</span><span class="default_value">None</span></em>, <em class="sig-param"><span class="n">callback</span><span class="o">=</span><span class="default_value">None</span></em><span class="sig-paren">)</span><a class="headerlink" href="#pyscf.mcscf.mc1step.CASSCF.mc1step" title="Permalink to this definition">¶</a></dt> <dd></dd></dl> <dl class="py method"> <dt id="pyscf.mcscf.mc1step.CASSCF.mc2step"> <code class="sig-name descname">mc2step</code><span class="sig-paren">(</span><em class="sig-param"><span class="n">mo_coeff</span><span class="o">=</span><span class="default_value">None</span></em>, <em class="sig-param"><span class="n">ci0</span><span class="o">=</span><span class="default_value">None</span></em>, <em class="sig-param"><span class="n">callback</span><span class="o">=</span><span class="default_value">None</span></em><span class="sig-paren">)</span><a class="headerlink" href="#pyscf.mcscf.mc1step.CASSCF.mc2step" title="Permalink to this definition">¶</a></dt> <dd></dd></dl> <dl class="py method"> <dt id="pyscf.mcscf.mc1step.CASSCF.micro_cycle_scheduler"> <code class="sig-name descname">micro_cycle_scheduler</code><span class="sig-paren">(</span><em class="sig-param"><span class="n">envs</span></em><span class="sig-paren">)</span><a class="headerlink" href="#pyscf.mcscf.mc1step.CASSCF.micro_cycle_scheduler" title="Permalink to this definition">¶</a></dt> <dd></dd></dl> <dl class="py attribute"> <dt id="pyscf.mcscf.mc1step.CASSCF.natorb"> <code class="sig-name descname">natorb</code><em class="property"> = False</em><a class="headerlink" href="#pyscf.mcscf.mc1step.CASSCF.natorb" title="Permalink to this definition">¶</a></dt> <dd></dd></dl> <dl class="py method"> <dt id="pyscf.mcscf.mc1step.CASSCF.newton"> <code class="sig-name descname">newton</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#pyscf.mcscf.mc1step.CASSCF.newton" title="Permalink to this definition">¶</a></dt> <dd></dd></dl> <dl class="py method"> <dt id="pyscf.mcscf.mc1step.CASSCF.nuc_grad_method"> <code class="sig-name descname">nuc_grad_method</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#pyscf.mcscf.mc1step.CASSCF.nuc_grad_method" title="Permalink to this definition">¶</a></dt> <dd></dd></dl> <dl class="py method"> <dt id="pyscf.mcscf.mc1step.CASSCF.pack_uniq_var"> <code class="sig-name descname">pack_uniq_var</code><span class="sig-paren">(</span><em class="sig-param"><span class="n">mat</span></em><span class="sig-paren">)</span><a class="headerlink" href="#pyscf.mcscf.mc1step.CASSCF.pack_uniq_var" title="Permalink to this definition">¶</a></dt> <dd></dd></dl> <dl class="py method"> <dt id="pyscf.mcscf.mc1step.CASSCF.rotate_mo"> <code class="sig-name descname">rotate_mo</code><span class="sig-paren">(</span><em class="sig-param"><span class="n">mo</span></em>, <em class="sig-param"><span class="n">u</span></em>, <em class="sig-param"><span class="n">log</span><span class="o">=</span><span class="default_value">None</span></em><span class="sig-paren">)</span><a class="headerlink" href="#pyscf.mcscf.mc1step.CASSCF.rotate_mo" title="Permalink to this definition">¶</a></dt> <dd><p>Rotate orbitals with the given unitary matrix</p> </dd></dl> <dl class="py method"> <dt id="pyscf.mcscf.mc1step.CASSCF.rotate_orb_cc"> <code class="sig-name descname">rotate_orb_cc</code><span class="sig-paren">(</span><em class="sig-param"><span class="n">mo</span></em>, <em class="sig-param"><span class="n">fcivec</span></em>, <em class="sig-param"><span class="n">fcasdm1</span></em>, <em class="sig-param"><span class="n">fcasdm2</span></em>, <em class="sig-param"><span class="n">eris</span></em>, <em class="sig-param"><span class="n">x0_guess</span><span class="o">=</span><span class="default_value">None</span></em>, <em class="sig-param"><span class="n">conv_tol_grad</span><span class="o">=</span><span class="default_value">0.0001</span></em>, <em class="sig-param"><span class="n">max_stepsize</span><span class="o">=</span><span class="default_value">None</span></em>, <em class="sig-param"><span class="n">verbose</span><span class="o">=</span><span class="default_value">None</span></em><span class="sig-paren">)</span><a class="headerlink" href="#pyscf.mcscf.mc1step.CASSCF.rotate_orb_cc" title="Permalink to this definition">¶</a></dt> <dd></dd></dl> <dl class="py attribute"> <dt id="pyscf.mcscf.mc1step.CASSCF.scale_restoration"> <code class="sig-name descname">scale_restoration</code><em class="property"> = 0.5</em><a class="headerlink" href="#pyscf.mcscf.mc1step.CASSCF.scale_restoration" title="Permalink to this definition">¶</a></dt> <dd></dd></dl> <dl class="py method"> <dt id="pyscf.mcscf.mc1step.CASSCF.solve_approx_ci"> <code class="sig-name descname">solve_approx_ci</code><span class="sig-paren">(</span><em class="sig-param"><span class="n">h1</span></em>, <em class="sig-param"><span class="n">h2</span></em>, <em class="sig-param"><span class="n">ci0</span></em>, <em class="sig-param"><span class="n">ecore</span></em>, <em class="sig-param"><span class="n">e_cas</span></em>, <em class="sig-param"><span class="n">envs</span></em><span class="sig-paren">)</span><a class="headerlink" href="#pyscf.mcscf.mc1step.CASSCF.solve_approx_ci" title="Permalink to this definition">¶</a></dt> <dd><p>Solve CI eigenvalue/response problem approximately</p> </dd></dl> <dl class="py attribute"> <dt id="pyscf.mcscf.mc1step.CASSCF.sorting_mo_energy"> <code class="sig-name descname">sorting_mo_energy</code><em class="property"> = False</em><a class="headerlink" href="#pyscf.mcscf.mc1step.CASSCF.sorting_mo_energy" title="Permalink to this definition">¶</a></dt> <dd></dd></dl> <dl class="py method"> <dt id="pyscf.mcscf.mc1step.CASSCF.uniq_var_indices"> <code class="sig-name descname">uniq_var_indices</code><span class="sig-paren">(</span><em class="sig-param"><span class="n">nmo</span></em>, <em class="sig-param"><span class="n">ncore</span></em>, <em class="sig-param"><span class="n">ncas</span></em>, <em class="sig-param"><span class="n">frozen</span></em><span class="sig-paren">)</span><a class="headerlink" href="#pyscf.mcscf.mc1step.CASSCF.uniq_var_indices" title="Permalink to this definition">¶</a></dt> <dd></dd></dl> <dl class="py method"> <dt id="pyscf.mcscf.mc1step.CASSCF.unpack_uniq_var"> <code class="sig-name descname">unpack_uniq_var</code><span class="sig-paren">(</span><em class="sig-param"><span class="n">v</span></em><span class="sig-paren">)</span><a class="headerlink" href="#pyscf.mcscf.mc1step.CASSCF.unpack_uniq_var" title="Permalink to this definition">¶</a></dt> <dd></dd></dl> <dl class="py method"> <dt id="pyscf.mcscf.mc1step.CASSCF.update"> <code class="sig-name descname">update</code><span class="sig-paren">(</span><em class="sig-param"><span class="n">chkfile</span><span class="o">=</span><span class="default_value">None</span></em><span class="sig-paren">)</span><a class="headerlink" href="#pyscf.mcscf.mc1step.CASSCF.update" title="Permalink to this definition">¶</a></dt> <dd></dd></dl> <dl class="py method"> <dt id="pyscf.mcscf.mc1step.CASSCF.update_ao2mo"> <code class="sig-name descname">update_ao2mo</code><span class="sig-paren">(</span><em class="sig-param"><span class="n">mo</span></em><span class="sig-paren">)</span><a class="headerlink" href="#pyscf.mcscf.mc1step.CASSCF.update_ao2mo" title="Permalink to this definition">¶</a></dt> <dd></dd></dl> <dl class="py method"> <dt id="pyscf.mcscf.mc1step.CASSCF.update_casdm"> <code class="sig-name descname">update_casdm</code><span class="sig-paren">(</span><em class="sig-param"><span class="n">mo</span></em>, <em class="sig-param"><span class="n">u</span></em>, <em class="sig-param"><span class="n">fcivec</span></em>, <em class="sig-param"><span class="n">e_cas</span></em>, <em class="sig-param"><span class="n">eris</span></em>, <em class="sig-param"><span class="n">envs</span><span class="o">=</span><span class="default_value">{}</span></em><span class="sig-paren">)</span><a class="headerlink" href="#pyscf.mcscf.mc1step.CASSCF.update_casdm" title="Permalink to this definition">¶</a></dt> <dd></dd></dl> <dl class="py method"> <dt id="pyscf.mcscf.mc1step.CASSCF.update_from_chk"> <code class="sig-name descname">update_from_chk</code><span class="sig-paren">(</span><em class="sig-param"><span class="n">chkfile</span><span class="o">=</span><span class="default_value">None</span></em><span class="sig-paren">)</span><a class="headerlink" href="#pyscf.mcscf.mc1step.CASSCF.update_from_chk" title="Permalink to this definition">¶</a></dt> <dd></dd></dl> <dl class="py method"> <dt id="pyscf.mcscf.mc1step.CASSCF.update_jk_in_ah"> <code class="sig-name descname">update_jk_in_ah</code><span class="sig-paren">(</span><em class="sig-param"><span class="n">mo</span></em>, <em class="sig-param"><span class="n">r</span></em>, <em class="sig-param"><span class="n">casdm1</span></em>, <em class="sig-param"><span class="n">eris</span></em><span class="sig-paren">)</span><a class="headerlink" href="#pyscf.mcscf.mc1step.CASSCF.update_jk_in_ah" title="Permalink to this definition">¶</a></dt> <dd></dd></dl> <dl class="py method"> <dt id="pyscf.mcscf.mc1step.CASSCF.update_rotate_matrix"> <code class="sig-name descname">update_rotate_matrix</code><span class="sig-paren">(</span><em class="sig-param"><span class="n">dx</span></em>, <em class="sig-param"><span class="n">u0</span><span class="o">=</span><span class="default_value">1</span></em><span class="sig-paren">)</span><a class="headerlink" href="#pyscf.mcscf.mc1step.CASSCF.update_rotate_matrix" title="Permalink to this definition">¶</a></dt> <dd></dd></dl> <dl class="py attribute"> <dt id="pyscf.mcscf.mc1step.CASSCF.with_dep4"> <code class="sig-name descname">with_dep4</code><em class="property"> = False</em><a class="headerlink" href="#pyscf.mcscf.mc1step.CASSCF.with_dep4" title="Permalink to this definition">¶</a></dt> <dd></dd></dl> </dd></dl> <dl class="py function"> <dt id="pyscf.mcscf.mc1step.as_scanner"> <code class="sig-prename descclassname">pyscf.mcscf.mc1step.</code><code class="sig-name descname">as_scanner</code><span class="sig-paren">(</span><em class="sig-param"><span class="n">mc</span></em><span class="sig-paren">)</span><a class="headerlink" href="#pyscf.mcscf.mc1step.as_scanner" title="Permalink to this definition">¶</a></dt> <dd><p>Generating a scanner for CASSCF PES.</p> <p>The returned solver is a function. This function requires one argument “mol” as input and returns total CASSCF energy.</p> <p>The solver will automatically use the results of last calculation as the initial guess of the new calculation. All parameters of MCSCF object (conv_tol, max_memory etc) are automatically applied in the solver.</p> <p>Note scanner has side effects. It may change many underlying objects (_scf, with_df, with_x2c, …) during calculation.</p> <p>Examples:</p> <div class="doctest highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">from</span> <span class="nn">pyscf</span> <span class="kn">import</span> <span class="n">gto</span><span class="p">,</span> <span class="n">scf</span><span class="p">,</span> <span class="n">mcscf</span> <span class="gp">&gt;&gt;&gt; </span><span class="n">mol</span> <span class="o">=</span> <span class="n">gto</span><span class="o">.</span><span class="n">M</span><span class="p">(</span><span class="n">atom</span><span class="o">=</span><span class="s1">&#39;N 0 0 0; N 0 0 1.2&#39;</span><span class="p">,</span> <span class="n">verbose</span><span class="o">=</span><span class="mi">0</span><span class="p">)</span> <span class="gp">&gt;&gt;&gt; </span><span class="n">mc_scanner</span> <span class="o">=</span> <span class="n">mcscf</span><span class="o">.</span><span class="n">CASSCF</span><span class="p">(</span><span class="n">scf</span><span class="o">.</span><span class="n">RHF</span><span class="p">(</span><span class="n">mol</span><span class="p">),</span> <span class="mi">4</span><span class="p">,</span> <span class="mi">4</span><span class="p">)</span><span class="o">.</span><span class="n">as_scanner</span><span class="p">()</span> <span class="gp">&gt;&gt;&gt; </span><span class="n">e</span> <span class="o">=</span> <span class="n">mc_scanner</span><span class="p">(</span><span class="n">gto</span><span class="o">.</span><span class="n">M</span><span class="p">(</span><span class="n">atom</span><span class="o">=</span><span class="s1">&#39;N 0 0 0; N 0 0 1.1&#39;</span><span class="p">))</span> <span class="gp">&gt;&gt;&gt; </span><span class="n">e</span> <span class="o">=</span> <span class="n">mc_scanner</span><span class="p">(</span><span class="n">gto</span><span class="o">.</span><span class="n">M</span><span class="p">(</span><span class="n">atom</span><span class="o">=</span><span class="s1">&#39;N 0 0 0; N 0 0 1.5&#39;</span><span class="p">))</span> </pre></div> </div> </dd></dl> <dl class="py function"> <dt id="pyscf.mcscf.mc1step.expmat"> <code class="sig-prename descclassname">pyscf.mcscf.mc1step.</code><code class="sig-name descname">expmat</code><span class="sig-paren">(</span><em class="sig-param"><span class="n">a</span></em><span class="sig-paren">)</span><a class="headerlink" href="#pyscf.mcscf.mc1step.expmat" title="Permalink to this definition">¶</a></dt> <dd></dd></dl> <dl class="py function"> <dt id="pyscf.mcscf.mc1step.gen_g_hop"> <code class="sig-prename descclassname">pyscf.mcscf.mc1step.</code><code class="sig-name descname">gen_g_hop</code><span class="sig-paren">(</span><em class="sig-param"><span class="n">casscf</span></em>, <em class="sig-param"><span class="n">mo</span></em>, <em class="sig-param"><span class="n">u</span></em>, <em class="sig-param"><span class="n">casdm1</span></em>, <em class="sig-param"><span class="n">casdm2</span></em>, <em class="sig-param"><span class="n">eris</span></em><span class="sig-paren">)</span><a class="headerlink" href="#pyscf.mcscf.mc1step.gen_g_hop" title="Permalink to this definition">¶</a></dt> <dd></dd></dl> <dl class="py function"> <dt id="pyscf.mcscf.mc1step.kernel"> <code class="sig-prename descclassname">pyscf.mcscf.mc1step.</code><code class="sig-name descname">kernel</code><span class="sig-paren">(</span><em class="sig-param"><span class="n">casscf</span></em>, <em class="sig-param"><span class="n">mo_coeff</span></em>, <em class="sig-param"><span class="n">tol</span><span class="o">=</span><span class="default_value">1e-07</span></em>, <em class="sig-param"><span class="n">conv_tol_grad</span><span class="o">=</span><span class="default_value">None</span></em>, <em class="sig-param"><span class="n">ci0</span><span class="o">=</span><span class="default_value">None</span></em>, <em class="sig-param"><span class="n">callback</span><span class="o">=</span><span class="default_value">None</span></em>, <em class="sig-param"><span class="n">verbose</span><span class="o">=</span><span class="default_value">3</span></em>, <em class="sig-param"><span class="n">dump_chk</span><span class="o">=</span><span class="default_value">True</span></em><span class="sig-paren">)</span><a class="headerlink" href="#pyscf.mcscf.mc1step.kernel" title="Permalink to this definition">¶</a></dt> <dd><p>quasi-newton CASSCF optimization driver</p> </dd></dl> <dl class="py function"> <dt id="pyscf.mcscf.mc1step.rotate_orb_cc"> <code class="sig-prename descclassname">pyscf.mcscf.mc1step.</code><code class="sig-name descname">rotate_orb_cc</code><span class="sig-paren">(</span><em class="sig-param"><span class="n">casscf</span></em>, <em class="sig-param"><span class="n">mo</span></em>, <em class="sig-param"><span class="n">fcivec</span></em>, <em class="sig-param"><span class="n">fcasdm1</span></em>, <em class="sig-param"><span class="n">fcasdm2</span></em>, <em class="sig-param"><span class="n">eris</span></em>, <em class="sig-param"><span class="n">x0_guess</span><span class="o">=</span><span class="default_value">None</span></em>, <em class="sig-param"><span class="n">conv_tol_grad</span><span class="o">=</span><span class="default_value">0.0001</span></em>, <em class="sig-param"><span class="n">max_stepsize</span><span class="o">=</span><span class="default_value">None</span></em>, <em class="sig-param"><span class="n">verbose</span><span class="o">=</span><span class="default_value">None</span></em><span class="sig-paren">)</span><a class="headerlink" href="#pyscf.mcscf.mc1step.rotate_orb_cc" title="Permalink to this definition">¶</a></dt> <dd></dd></dl> </div> <div class="section" id="module-pyscf.mcscf.mc1step_symm"> <span id="pyscf-mcscf-mc1step-symm-module"></span><h2>pyscf.mcscf.mc1step_symm module<a class="headerlink" href="#module-pyscf.mcscf.mc1step_symm" title="Permalink to this headline">¶</a></h2> <dl class="py attribute"> <dt id="pyscf.mcscf.mc1step_symm.CASSCF"> <code class="sig-prename descclassname">pyscf.mcscf.mc1step_symm.</code><code class="sig-name descname">CASSCF</code><a class="headerlink" href="#pyscf.mcscf.mc1step_symm.CASSCF" title="Permalink to this definition">¶</a></dt> <dd><p>alias of <a class="reference internal" href="#pyscf.mcscf.mc1step_symm.SymAdaptedCASSCF" title="pyscf.mcscf.mc1step_symm.SymAdaptedCASSCF"><code class="xref py py-class docutils literal notranslate"><span class="pre">pyscf.mcscf.mc1step_symm.SymAdaptedCASSCF</span></code></a></p> </dd></dl> <dl class="py class"> <dt id="pyscf.mcscf.mc1step_symm.SymAdaptedCASSCF"> <em class="property">class </em><code class="sig-prename descclassname">pyscf.mcscf.mc1step_symm.</code><code class="sig-name descname">SymAdaptedCASSCF</code><span class="sig-paren">(</span><em class="sig-param"><span class="n">mf_or_mol</span></em>, <em class="sig-param"><span class="n">ncas</span></em>, <em class="sig-param"><span class="n">nelecas</span></em>, <em class="sig-param"><span class="n">ncore</span><span class="o">=</span><span class="default_value">None</span></em>, <em class="sig-param"><span class="n">frozen</span><span class="o">=</span><span class="default_value">None</span></em><span class="sig-paren">)</span><a class="headerlink" href="#pyscf.mcscf.mc1step_symm.SymAdaptedCASSCF" title="Permalink to this definition">¶</a></dt> <dd><p>Bases: <a class="reference internal" href="#pyscf.mcscf.mc1step.CASSCF" title="pyscf.mcscf.mc1step.CASSCF"><code class="xref py py-class docutils literal notranslate"><span class="pre">pyscf.mcscf.mc1step.CASSCF</span></code></a></p> <dl> <dt>Args:</dt><dd><dl class="simple"> <dt>mf_or_mol<span class="classifier">SCF object or Mole object</span></dt><dd><p>SCF or Mole to define the problem size.</p> </dd> <dt>ncas<span class="classifier">int</span></dt><dd><p>Number of active orbitals.</p> </dd> <dt>nelecas<span class="classifier">int or a pair of int</span></dt><dd><p>Number of electrons in active space.</p> </dd> </dl> </dd> <dt>Kwargs:</dt><dd><dl class="simple"> <dt>ncore<span class="classifier">int</span></dt><dd><p>Number of doubly occupied core orbitals. If not presented, this parameter can be automatically determined.</p> </dd> </dl> </dd> <dt>Attributes:</dt><dd><dl> <dt>verbose<span class="classifier">int</span></dt><dd><p>Print level. Default value equals to <code class="xref py py-class docutils literal notranslate"><span class="pre">Mole.verbose</span></code>.</p> </dd> <dt>max_memory<span class="classifier">float or int</span></dt><dd><p>Allowed memory in MB. Default value equals to <code class="xref py py-class docutils literal notranslate"><span class="pre">Mole.max_memory</span></code>.</p> </dd> <dt>ncas<span class="classifier">int</span></dt><dd><p>Active space size.</p> </dd> <dt>nelecas<span class="classifier">tuple of int</span></dt><dd><p>Active (nelec_alpha, nelec_beta)</p> </dd> <dt>ncore<span class="classifier">int or tuple of int</span></dt><dd><p>Core electron number. In UHF-CASSCF, it’s a tuple to indicate the different core eletron numbers.</p> </dd> <dt>natorb<span class="classifier">bool</span></dt><dd><p>Whether to transform natural orbitals in active space. Note: when CASCI/CASSCF are combined with DMRG solver or selected CI solver, enabling this parameter may slightly change the total energy. False by default.</p> </dd> <dt>canonicalization<span class="classifier">bool</span></dt><dd><p>Whether to canonicalize orbitals in core and external space against the general Fock matrix. The orbitals in active space are NOT transformed by default. To get the natural orbitals in active space, the attribute .natorb needs to be enabled. True by default.</p> </dd> <dt>sorting_mo_energy<span class="classifier">bool</span></dt><dd><p>Whether to sort the orbitals based on the diagonal elements of the general Fock matrix. Default is False.</p> </dd> <dt>fcisolver<span class="classifier">an instance of <code class="xref py py-class docutils literal notranslate"><span class="pre">FCISolver</span></code></span></dt><dd><p>The pyscf.fci module provides several FCISolver for different scenario. Generally, fci.direct_spin1.FCISolver can be used for all RHF-CASSCF. However, a proper FCISolver can provide better performance and better numerical stability. One can either use <code class="xref py py-func docutils literal notranslate"><span class="pre">fci.solver()</span></code> function to pick the FCISolver by the program or manually assigen the FCISolver to this attribute, e.g.</p> <div class="doctest highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">from</span> <span class="nn">pyscf</span> <span class="kn">import</span> <span class="n">fci</span> <span class="gp">&gt;&gt;&gt; </span><span class="n">mc</span> <span class="o">=</span> <span class="n">mcscf</span><span class="o">.</span><span class="n">CASSCF</span><span class="p">(</span><span class="n">mf</span><span class="p">,</span> <span class="mi">4</span><span class="p">,</span> <span class="mi">4</span><span class="p">)</span> <span class="gp">&gt;&gt;&gt; </span><span class="n">mc</span><span class="o">.</span><span class="n">fcisolver</span> <span class="o">=</span> <span class="n">fci</span><span class="o">.</span><span class="n">solver</span><span class="p">(</span><span class="n">mol</span><span class="p">,</span> <span class="n">singlet</span><span class="o">=</span><span class="kc">True</span><span class="p">)</span> <span class="gp">&gt;&gt;&gt; </span><span class="n">mc</span><span class="o">.</span><span class="n">fcisolver</span> <span class="o">=</span> <span class="n">fci</span><span class="o">.</span><span class="n">direct_spin1</span><span class="o">.</span><span class="n">FCISolver</span><span class="p">(</span><span class="n">mol</span><span class="p">)</span> </pre></div> </div> <p>You can control FCISolver by setting e.g.:</p> <div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">mc</span><span class="o">.</span><span class="n">fcisolver</span><span class="o">.</span><span class="n">max_cycle</span> <span class="o">=</span> <span class="mi">30</span> <span class="gp">&gt;&gt;&gt; </span><span class="n">mc</span><span class="o">.</span><span class="n">fcisolver</span><span class="o">.</span><span class="n">conv_tol</span> <span class="o">=</span> <span class="mf">1e-7</span> </pre></div> </div> <p>For more details of the parameter for FCISolver, See <code class="xref py py-mod docutils literal notranslate"><span class="pre">fci</span></code>.</p> </dd> </dl> </dd> </dl> <p>Saved results</p> <blockquote> <div><dl class="simple"> <dt>e_tot<span class="classifier">float</span></dt><dd><p>Total MCSCF energy (electronic energy plus nuclear repulsion)</p> </dd> <dt>e_cas<span class="classifier">float</span></dt><dd><p>CAS space FCI energy</p> </dd> <dt>ci<span class="classifier">ndarray</span></dt><dd><p>CAS space FCI coefficients</p> </dd> <dt>mo_coeff<span class="classifier">ndarray</span></dt><dd><p>When canonicalization is specified, the orbitals are canonical orbitals which make the general Fock matrix (Fock operator on top of MCSCF 1-particle density matrix) diagonalized within each subspace (core, active, external). If natorb (natural orbitals in active space) is specified, the active segment of the mo_coeff is natural orbitls.</p> </dd> <dt>mo_energy<span class="classifier">ndarray</span></dt><dd><p>Diagonal elements of general Fock matrix (in mo_coeff representation).</p> </dd> <dt>mo_occ<span class="classifier">ndarray</span></dt><dd><p>Occupation numbers of natural orbitals if natorb is specified.</p> </dd> </dl> </div></blockquote> <p>Examples:</p> <div class="doctest highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">from</span> <span class="nn">pyscf</span> <span class="kn">import</span> <span class="n">gto</span><span class="p">,</span> <span class="n">scf</span><span class="p">,</span> <span class="n">mcscf</span> <span class="gp">&gt;&gt;&gt; </span><span class="n">mol</span> <span class="o">=</span> <span class="n">gto</span><span class="o">.</span><span class="n">M</span><span class="p">(</span><span class="n">atom</span><span class="o">=</span><span class="s1">&#39;N 0 0 0; N 0 0 1&#39;</span><span class="p">,</span> <span class="n">basis</span><span class="o">=</span><span class="s1">&#39;ccpvdz&#39;</span><span class="p">,</span> <span class="n">verbose</span><span class="o">=</span><span class="mi">0</span><span class="p">)</span> <span class="gp">&gt;&gt;&gt; </span><span class="n">mf</span> <span class="o">=</span> <span class="n">scf</span><span class="o">.</span><span class="n">RHF</span><span class="p">(</span><span class="n">mol</span><span class="p">)</span> <span class="gp">&gt;&gt;&gt; </span><span class="n">mf</span><span class="o">.</span><span class="n">scf</span><span class="p">()</span> <span class="gp">&gt;&gt;&gt; </span><span class="n">mc</span> <span class="o">=</span> <span class="n">mcscf</span><span class="o">.</span><span class="n">CASCI</span><span class="p">(</span><span class="n">mf</span><span class="p">,</span> <span class="mi">6</span><span class="p">,</span> <span class="mi">6</span><span class="p">)</span> <span class="gp">&gt;&gt;&gt; </span><span class="n">mc</span><span class="o">.</span><span class="n">kernel</span><span class="p">()[</span><span class="mi">0</span><span class="p">]</span> <span class="go">-108.980200816243354</span> <span class="go">CASSCF</span> </pre></div> </div> <p>Extra attributes for CASSCF:</p> <blockquote> <div><dl> <dt>conv_tol<span class="classifier">float</span></dt><dd><p>Converge threshold. Default is 1e-7</p> </dd> <dt>conv_tol_grad<span class="classifier">float</span></dt><dd><p>Converge threshold for CI gradients and orbital rotation gradients. Default is 1e-4</p> </dd> <dt>max_stepsize<span class="classifier">float</span></dt><dd><p>The step size for orbital rotation. Small step (0.005 - 0.05) is prefered. Default is 0.03.</p> </dd> <dt>max_cycle_macro<span class="classifier">int</span></dt><dd><p>Max number of macro iterations. Default is 50.</p> </dd> <dt>max_cycle_micro<span class="classifier">int</span></dt><dd><p>Max number of micro iterations in each macro iteration. Depending on systems, increasing this value might reduce the total macro iterations. Generally, 2 - 5 steps should be enough. Default is 3.</p> </dd> <dt>ah_level_shift<span class="classifier">float, for AH solver.</span></dt><dd><p>Level shift for the Davidson diagonalization in AH solver. Default is 1e-8.</p> </dd> <dt>ah_conv_tol<span class="classifier">float, for AH solver.</span></dt><dd><p>converge threshold for AH solver. Default is 1e-12.</p> </dd> <dt>ah_max_cycle<span class="classifier">float, for AH solver.</span></dt><dd><p>Max number of iterations allowd in AH solver. Default is 30.</p> </dd> <dt>ah_lindep<span class="classifier">float, for AH solver.</span></dt><dd><p>Linear dependence threshold for AH solver. Default is 1e-14.</p> </dd> <dt>ah_start_tol<span class="classifier">flat, for AH solver.</span></dt><dd><p>In AH solver, the orbital rotation is started without completely solving the AH problem. This value is to control the start point. Default is 0.2.</p> </dd> <dt>ah_start_cycle<span class="classifier">int, for AH solver.</span></dt><dd><p>In AH solver, the orbital rotation is started without completely solving the AH problem. This value is to control the start point. Default is 2.</p> <p><code class="docutils literal notranslate"><span class="pre">ah_conv_tol</span></code>, <code class="docutils literal notranslate"><span class="pre">ah_max_cycle</span></code>, <code class="docutils literal notranslate"><span class="pre">ah_lindep</span></code>, <code class="docutils literal notranslate"><span class="pre">ah_start_tol</span></code> and <code class="docutils literal notranslate"><span class="pre">ah_start_cycle</span></code> can affect the accuracy and performance of CASSCF solver. Lower <code class="docutils literal notranslate"><span class="pre">ah_conv_tol</span></code> and <code class="docutils literal notranslate"><span class="pre">ah_lindep</span></code> might improve the accuracy of CASSCF optimization, but decrease the performance.</p> <div class="doctest highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">from</span> <span class="nn">pyscf</span> <span class="kn">import</span> <span class="n">gto</span><span class="p">,</span> <span class="n">scf</span><span class="p">,</span> <span class="n">mcscf</span> <span class="gp">&gt;&gt;&gt; </span><span class="n">mol</span> <span class="o">=</span> <span class="n">gto</span><span class="o">.</span><span class="n">M</span><span class="p">(</span><span class="n">atom</span><span class="o">=</span><span class="s1">&#39;N 0 0 0; N 0 0 1&#39;</span><span class="p">,</span> <span class="n">basis</span><span class="o">=</span><span class="s1">&#39;ccpvdz&#39;</span><span class="p">,</span> <span class="n">verbose</span><span class="o">=</span><span class="mi">0</span><span class="p">)</span> <span class="gp">&gt;&gt;&gt; </span><span class="n">mf</span> <span class="o">=</span> <span class="n">scf</span><span class="o">.</span><span class="n">UHF</span><span class="p">(</span><span class="n">mol</span><span class="p">)</span> <span class="gp">&gt;&gt;&gt; </span><span class="n">mf</span><span class="o">.</span><span class="n">scf</span><span class="p">()</span> <span class="gp">&gt;&gt;&gt; </span><span class="n">mc</span> <span class="o">=</span> <span class="n">mcscf</span><span class="o">.</span><span class="n">CASSCF</span><span class="p">(</span><span class="n">mf</span><span class="p">,</span> <span class="mi">6</span><span class="p">,</span> <span class="mi">6</span><span class="p">)</span> <span class="gp">&gt;&gt;&gt; </span><span class="n">mc</span><span class="o">.</span><span class="n">conv_tol</span> <span class="o">=</span> <span class="mf">1e-10</span> <span class="gp">&gt;&gt;&gt; </span><span class="n">mc</span><span class="o">.</span><span class="n">ah_conv_tol</span> <span class="o">=</span> <span class="mf">1e-5</span> <span class="gp">&gt;&gt;&gt; </span><span class="n">mc</span><span class="o">.</span><span class="n">kernel</span><span class="p">()[</span><span class="mi">0</span><span class="p">]</span> <span class="go">-109.044401898486001</span> <span class="gp">&gt;&gt;&gt; </span><span class="n">mc</span><span class="o">.</span><span class="n">ah_conv_tol</span> <span class="o">=</span> <span class="mf">1e-10</span> <span class="gp">&gt;&gt;&gt; </span><span class="n">mc</span><span class="o">.</span><span class="n">kernel</span><span class="p">()[</span><span class="mi">0</span><span class="p">]</span> <span class="go">-109.044401887945668</span> </pre></div> </div> </dd> <dt>chkfile<span class="classifier">str</span></dt><dd><p>Checkpoint file to save the intermediate orbitals during the CASSCF optimization. Default is the checkpoint file of mean field object.</p> </dd> <dt>ci_response_space<span class="classifier">int</span></dt><dd><p>subspace size to solve the CI vector response. Default is 3.</p> </dd> <dt>callback<span class="classifier">function(envs_dict) =&gt; None</span></dt><dd><p>callback function takes one dict as the argument which is generated by the builtin function <code class="xref py py-func docutils literal notranslate"><span class="pre">locals()</span></code>, so that the callback function can access all local variables in the current envrionment.</p> </dd> <dt>scale_restoration<span class="classifier">float</span></dt><dd><p>When a step of orbital rotation moves out of trust region, the orbital optimization will be restored to previous state and the step size of the orbital rotation needs to be reduced. scale_restoration controls how much to scale down the step size.</p> </dd> </dl> </div></blockquote> <p>Saved results</p> <blockquote> <div><dl class="simple"> <dt>e_tot<span class="classifier">float</span></dt><dd><p>Total MCSCF energy (electronic energy plus nuclear repulsion)</p> </dd> <dt>e_cas<span class="classifier">float</span></dt><dd><p>CAS space FCI energy</p> </dd> <dt>ci<span class="classifier">ndarray</span></dt><dd><p>CAS space FCI coefficients</p> </dd> <dt>mo_coeff<span class="classifier">ndarray</span></dt><dd><p>Optimized CASSCF orbitals coefficients. When canonicalization is specified, the returned orbitals make the general Fock matrix (Fock operator on top of MCSCF 1-particle density matrix) diagonalized within each subspace (core, active, external). If natorb (natural orbitals in active space) is enabled, the active segment of mo_coeff is transformed to natural orbitals.</p> </dd> <dt>mo_energy<span class="classifier">ndarray</span></dt><dd><p>Diagonal elements of general Fock matrix (in mo_coeff representation).</p> </dd> </dl> </div></blockquote> <p>Examples:</p> <div class="doctest highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">from</span> <span class="nn">pyscf</span> <span class="kn">import</span> <span class="n">gto</span><span class="p">,</span> <span class="n">scf</span><span class="p">,</span> <span class="n">mcscf</span> <span class="gp">&gt;&gt;&gt; </span><span class="n">mol</span> <span class="o">=</span> <span class="n">gto</span><span class="o">.</span><span class="n">M</span><span class="p">(</span><span class="n">atom</span><span class="o">=</span><span class="s1">&#39;N 0 0 0; N 0 0 1&#39;</span><span class="p">,</span> <span class="n">basis</span><span class="o">=</span><span class="s1">&#39;ccpvdz&#39;</span><span class="p">,</span> <span class="n">verbose</span><span class="o">=</span><span class="mi">0</span><span class="p">)</span> <span class="gp">&gt;&gt;&gt; </span><span class="n">mf</span> <span class="o">=</span> <span class="n">scf</span><span class="o">.</span><span class="n">RHF</span><span class="p">(</span><span class="n">mol</span><span class="p">)</span> <span class="gp">&gt;&gt;&gt; </span><span class="n">mf</span><span class="o">.</span><span class="n">scf</span><span class="p">()</span> <span class="gp">&gt;&gt;&gt; </span><span class="n">mc</span> <span class="o">=</span> <span class="n">mcscf</span><span class="o">.</span><span class="n">CASSCF</span><span class="p">(</span><span class="n">mf</span><span class="p">,</span> <span class="mi">6</span><span class="p">,</span> <span class="mi">6</span><span class="p">)</span> <span class="gp">&gt;&gt;&gt; </span><span class="n">mc</span><span class="o">.</span><span class="n">kernel</span><span class="p">()[</span><span class="mi">0</span><span class="p">]</span> <span class="go">-109.044401882238134</span> </pre></div> </div> <dl class="py method"> <dt id="pyscf.mcscf.mc1step_symm.SymAdaptedCASSCF.kernel"> <code class="sig-name descname">kernel</code><span class="sig-paren">(</span><em class="sig-param"><span class="n">mo_coeff</span><span class="o">=</span><span class="default_value">None</span></em>, <em class="sig-param"><span class="n">ci0</span><span class="o">=</span><span class="default_value">None</span></em>, <em class="sig-param"><span class="n">callback</span><span class="o">=</span><span class="default_value">None</span></em>, <em class="sig-param"><span class="n">_kern</span><span class="o">=</span><span class="default_value">None</span></em><span class="sig-paren">)</span><a class="headerlink" href="#pyscf.mcscf.mc1step_symm.SymAdaptedCASSCF.kernel" title="Permalink to this definition">¶</a></dt> <dd><dl class="simple"> <dt>Returns:</dt><dd><p>Five elements, they are total energy, active space CI energy, the active space FCI wavefunction coefficients or DMRG wavefunction ID, the MCSCF canonical orbital coefficients, the MCSCF canonical orbital coefficients.</p> </dd> </dl> <p>They are attributes of mcscf object, which can be accessed by .e_tot, .e_cas, .ci, .mo_coeff, .mo_energy</p> </dd></dl> <dl class="py method"> <dt id="pyscf.mcscf.mc1step_symm.SymAdaptedCASSCF.mc1step"> <code class="sig-name descname">mc1step</code><span class="sig-paren">(</span><em class="sig-param"><span class="n">mo_coeff</span><span class="o">=</span><span class="default_value">None</span></em>, <em class="sig-param"><span class="n">ci0</span><span class="o">=</span><span class="default_value">None</span></em>, <em class="sig-param"><span class="n">callback</span><span class="o">=</span><span class="default_value">None</span></em><span class="sig-paren">)</span><a class="headerlink" href="#pyscf.mcscf.mc1step_symm.SymAdaptedCASSCF.mc1step" title="Permalink to this definition">¶</a></dt> <dd></dd></dl> <dl class="py method"> <dt id="pyscf.mcscf.mc1step_symm.SymAdaptedCASSCF.mc2step"> <code class="sig-name descname">mc2step</code><span class="sig-paren">(</span><em class="sig-param"><span class="n">mo_coeff</span><span class="o">=</span><span class="default_value">None</span></em>, <em class="sig-param"><span class="n">ci0</span><span class="o">=</span><span class="default_value">None</span></em>, <em class="sig-param"><span class="n">callback</span><span class="o">=</span><span class="default_value">None</span></em><span class="sig-paren">)</span><a class="headerlink" href="#pyscf.mcscf.mc1step_symm.SymAdaptedCASSCF.mc2step" title="Permalink to this definition">¶</a></dt> <dd></dd></dl> <dl class="py method"> <dt id="pyscf.mcscf.mc1step_symm.SymAdaptedCASSCF.newton"> <code class="sig-name descname">newton</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#pyscf.mcscf.mc1step_symm.SymAdaptedCASSCF.newton" title="Permalink to this definition">¶</a></dt> <dd></dd></dl> <dl class="py method"> <dt id="pyscf.mcscf.mc1step_symm.SymAdaptedCASSCF.rotate_mo"> <code class="sig-name descname">rotate_mo</code><span class="sig-paren">(</span><em class="sig-param"><span class="n">mo</span></em>, <em class="sig-param"><span class="n">u</span></em>, <em class="sig-param"><span class="n">log</span><span class="o">=</span><span class="default_value">None</span></em><span class="sig-paren">)</span><a class="headerlink" href="#pyscf.mcscf.mc1step_symm.SymAdaptedCASSCF.rotate_mo" title="Permalink to this definition">¶</a></dt> <dd><p>Rotate orbitals with the given unitary matrix</p> </dd></dl> <dl class="py method"> <dt id="pyscf.mcscf.mc1step_symm.SymAdaptedCASSCF.sort_mo_by_irrep"> <code class="sig-name descname">sort_mo_by_irrep</code><span class="sig-paren">(</span><em class="sig-param"><span class="n">cas_irrep_nocc</span></em>, <em class="sig-param"><span class="n">cas_irrep_ncore</span><span class="o">=</span><span class="default_value">None</span></em>, <em class="sig-param"><span class="n">mo_coeff</span><span class="o">=</span><span class="default_value">None</span></em>, <em class="sig-param"><span class="n">s</span><span class="o">=</span><span class="default_value">None</span></em><span class="sig-paren">)</span><a class="headerlink" href="#pyscf.mcscf.mc1step_symm.SymAdaptedCASSCF.sort_mo_by_irrep" title="Permalink to this definition">¶</a></dt> <dd><p>Select active space based on symmetry information. See also <a class="reference internal" href="#pyscf.mcscf.addons.sort_mo_by_irrep" title="pyscf.mcscf.addons.sort_mo_by_irrep"><code class="xref py py-func docutils literal notranslate"><span class="pre">pyscf.mcscf.addons.sort_mo_by_irrep()</span></code></a></p> </dd></dl> <dl class="py method"> <dt id="pyscf.mcscf.mc1step_symm.SymAdaptedCASSCF.uniq_var_indices"> <code class="sig-name descname">uniq_var_indices</code><span class="sig-paren">(</span><em class="sig-param"><span class="n">nmo</span></em>, <em class="sig-param"><span class="n">ncore</span></em>, <em class="sig-param"><span class="n">ncas</span></em>, <em class="sig-param"><span class="n">frozen</span></em><span class="sig-paren">)</span><a class="headerlink" href="#pyscf.mcscf.mc1step_symm.SymAdaptedCASSCF.uniq_var_indices" title="Permalink to this definition">¶</a></dt> <dd></dd></dl> <dl class="py method"> <dt id="pyscf.mcscf.mc1step_symm.SymAdaptedCASSCF.wfnsym"> <em class="property">property </em><code class="sig-name descname">wfnsym</code><a class="headerlink" href="#pyscf.mcscf.mc1step_symm.SymAdaptedCASSCF.wfnsym" title="Permalink to this definition">¶</a></dt> <dd></dd></dl> </dd></dl> </div> <div class="section" id="module-pyscf.mcscf.mc2step"> <span id="pyscf-mcscf-mc2step-module"></span><h2>pyscf.mcscf.mc2step module<a class="headerlink" href="#module-pyscf.mcscf.mc2step" title="Permalink to this headline">¶</a></h2> <dl class="py function"> <dt id="pyscf.mcscf.mc2step.kernel"> <code class="sig-prename descclassname">pyscf.mcscf.mc2step.</code><code class="sig-name descname">kernel</code><span class="sig-paren">(</span><em class="sig-param"><span class="n">casscf</span></em>, <em class="sig-param"><span class="n">mo_coeff</span></em>, <em class="sig-param"><span class="n">tol</span><span class="o">=</span><span class="default_value">1e-07</span></em>, <em class="sig-param"><span class="n">conv_tol_grad</span><span class="o">=</span><span class="default_value">None</span></em>, <em class="sig-param"><span class="n">ci0</span><span class="o">=</span><span class="default_value">None</span></em>, <em class="sig-param"><span class="n">callback</span><span class="o">=</span><span class="default_value">None</span></em>, <em class="sig-param"><span class="n">verbose</span><span class="o">=</span><span class="default_value">None</span></em>, <em class="sig-param"><span class="n">dump_chk</span><span class="o">=</span><span class="default_value">True</span></em><span class="sig-paren">)</span><a class="headerlink" href="#pyscf.mcscf.mc2step.kernel" title="Permalink to this definition">¶</a></dt> <dd></dd></dl> </div> <div class="section" id="module-pyscf.mcscf.mc_ao2mo"> <span id="pyscf-mcscf-mc-ao2mo-module"></span><h2>pyscf.mcscf.mc_ao2mo module<a class="headerlink" href="#module-pyscf.mcscf.mc_ao2mo" title="Permalink to this headline">¶</a></h2> <dl class="py function"> <dt id="pyscf.mcscf.mc_ao2mo.prange"> <code class="sig-prename descclassname">pyscf.mcscf.mc_ao2mo.</code><code class="sig-name descname">prange</code><span class="sig-paren">(</span><em class="sig-param"><span class="n">start</span></em>, <em class="sig-param"><span class="n">end</span></em>, <em class="sig-param"><span class="n">step</span></em><span class="sig-paren">)</span><a class="headerlink" href="#pyscf.mcscf.mc_ao2mo.prange" title="Permalink to this definition">¶</a></dt> <dd></dd></dl> <dl class="py function"> <dt id="pyscf.mcscf.mc_ao2mo.trans_e1_incore"> <code class="sig-prename descclassname">pyscf.mcscf.mc_ao2mo.</code><code class="sig-name descname">trans_e1_incore</code><span class="sig-paren">(</span><em class="sig-param"><span class="n">eri_ao</span></em>, <em class="sig-param"><span class="n">mo</span></em>, <em class="sig-param"><span class="n">ncore</span></em>, <em class="sig-param"><span class="n">ncas</span></em><span class="sig-paren">)</span><a class="headerlink" href="#pyscf.mcscf.mc_ao2mo.trans_e1_incore" title="Permalink to this definition">¶</a></dt> <dd></dd></dl> <dl class="py function"> <dt id="pyscf.mcscf.mc_ao2mo.trans_e1_outcore"> <code class="sig-prename descclassname">pyscf.mcscf.mc_ao2mo.</code><code class="sig-name descname">trans_e1_outcore</code><span class="sig-paren">(</span><em class="sig-param"><span class="n">mol</span></em>, <em class="sig-param"><span class="n">mo</span></em>, <em class="sig-param"><span class="n">ncore</span></em>, <em class="sig-param"><span class="n">ncas</span></em>, <em class="sig-param"><span class="n">erifile</span></em>, <em class="sig-param"><span class="n">max_memory</span><span class="o">=</span><span class="default_value">None</span></em>, <em class="sig-param"><span class="n">level</span><span class="o">=</span><span class="default_value">1</span></em>, <em class="sig-param"><span class="n">verbose</span><span class="o">=</span><span class="default_value">2</span></em><span class="sig-paren">)</span><a class="headerlink" href="#pyscf.mcscf.mc_ao2mo.trans_e1_outcore" title="Permalink to this definition">¶</a></dt> <dd></dd></dl> </div> <div class="section" id="module-pyscf.mcscf.newton_casscf"> <span id="pyscf-mcscf-newton-casscf-module"></span><h2>pyscf.mcscf.newton_casscf module<a class="headerlink" href="#module-pyscf.mcscf.newton_casscf" title="Permalink to this headline">¶</a></h2> <p>Second order CASSCF</p> <dl class="py class"> <dt id="pyscf.mcscf.newton_casscf.CASSCF"> <em class="property">class </em><code class="sig-prename descclassname">pyscf.mcscf.newton_casscf.</code><code class="sig-name descname">CASSCF</code><span class="sig-paren">(</span><em class="sig-param"><span class="n">mf_or_mol</span></em>, <em class="sig-param"><span class="n">ncas</span></em>, <em class="sig-param"><span class="n">nelecas</span></em>, <em class="sig-param"><span class="n">ncore</span><span class="o">=</span><span class="default_value">None</span></em>, <em class="sig-param"><span class="n">frozen</span><span class="o">=</span><span class="default_value">None</span></em><span class="sig-paren">)</span><a class="headerlink" href="#pyscf.mcscf.newton_casscf.CASSCF" title="Permalink to this definition">¶</a></dt> <dd><p>Bases: <a class="reference internal" href="#pyscf.mcscf.mc1step.CASSCF" title="pyscf.mcscf.mc1step.CASSCF"><code class="xref py py-class docutils literal notranslate"><span class="pre">pyscf.mcscf.mc1step.CASSCF</span></code></a></p> <dl> <dt>Args:</dt><dd><dl class="simple"> <dt>mf_or_mol<span class="classifier">SCF object or Mole object</span></dt><dd><p>SCF or Mole to define the problem size.</p> </dd> <dt>ncas<span class="classifier">int</span></dt><dd><p>Number of active orbitals.</p> </dd> <dt>nelecas<span class="classifier">int or a pair of int</span></dt><dd><p>Number of electrons in active space.</p> </dd> </dl> </dd> <dt>Kwargs:</dt><dd><dl class="simple"> <dt>ncore<span class="classifier">int</span></dt><dd><p>Number of doubly occupied core orbitals. If not presented, this parameter can be automatically determined.</p> </dd> </dl> </dd> <dt>Attributes:</dt><dd><dl> <dt>verbose<span class="classifier">int</span></dt><dd><p>Print level. Default value equals to <code class="xref py py-class docutils literal notranslate"><span class="pre">Mole.verbose</span></code>.</p> </dd> <dt>max_memory<span class="classifier">float or int</span></dt><dd><p>Allowed memory in MB. Default value equals to <code class="xref py py-class docutils literal notranslate"><span class="pre">Mole.max_memory</span></code>.</p> </dd> <dt>ncas<span class="classifier">int</span></dt><dd><p>Active space size.</p> </dd> <dt>nelecas<span class="classifier">tuple of int</span></dt><dd><p>Active (nelec_alpha, nelec_beta)</p> </dd> <dt>ncore<span class="classifier">int or tuple of int</span></dt><dd><p>Core electron number. In UHF-CASSCF, it’s a tuple to indicate the different core eletron numbers.</p> </dd> <dt>natorb<span class="classifier">bool</span></dt><dd><p>Whether to transform natural orbitals in active space. Note: when CASCI/CASSCF are combined with DMRG solver or selected CI solver, enabling this parameter may slightly change the total energy. False by default.</p> </dd> <dt>canonicalization<span class="classifier">bool</span></dt><dd><p>Whether to canonicalize orbitals in core and external space against the general Fock matrix. The orbitals in active space are NOT transformed by default. To get the natural orbitals in active space, the attribute .natorb needs to be enabled. True by default.</p> </dd> <dt>sorting_mo_energy<span class="classifier">bool</span></dt><dd><p>Whether to sort the orbitals based on the diagonal elements of the general Fock matrix. Default is False.</p> </dd> <dt>fcisolver<span class="classifier">an instance of <code class="xref py py-class docutils literal notranslate"><span class="pre">FCISolver</span></code></span></dt><dd><p>The pyscf.fci module provides several FCISolver for different scenario. Generally, fci.direct_spin1.FCISolver can be used for all RHF-CASSCF. However, a proper FCISolver can provide better performance and better numerical stability. One can either use <code class="xref py py-func docutils literal notranslate"><span class="pre">fci.solver()</span></code> function to pick the FCISolver by the program or manually assigen the FCISolver to this attribute, e.g.</p> <div class="doctest highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">from</span> <span class="nn">pyscf</span> <span class="kn">import</span> <span class="n">fci</span> <span class="gp">&gt;&gt;&gt; </span><span class="n">mc</span> <span class="o">=</span> <span class="n">mcscf</span><span class="o">.</span><span class="n">CASSCF</span><span class="p">(</span><span class="n">mf</span><span class="p">,</span> <span class="mi">4</span><span class="p">,</span> <span class="mi">4</span><span class="p">)</span> <span class="gp">&gt;&gt;&gt; </span><span class="n">mc</span><span class="o">.</span><span class="n">fcisolver</span> <span class="o">=</span> <span class="n">fci</span><span class="o">.</span><span class="n">solver</span><span class="p">(</span><span class="n">mol</span><span class="p">,</span> <span class="n">singlet</span><span class="o">=</span><span class="kc">True</span><span class="p">)</span> <span class="gp">&gt;&gt;&gt; </span><span class="n">mc</span><span class="o">.</span><span class="n">fcisolver</span> <span class="o">=</span> <span class="n">fci</span><span class="o">.</span><span class="n">direct_spin1</span><span class="o">.</span><span class="n">FCISolver</span><span class="p">(</span><span class="n">mol</span><span class="p">)</span> </pre></div> </div> <p>You can control FCISolver by setting e.g.:</p> <div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">mc</span><span class="o">.</span><span class="n">fcisolver</span><span class="o">.</span><span class="n">max_cycle</span> <span class="o">=</span> <span class="mi">30</span> <span class="gp">&gt;&gt;&gt; </span><span class="n">mc</span><span class="o">.</span><span class="n">fcisolver</span><span class="o">.</span><span class="n">conv_tol</span> <span class="o">=</span> <span class="mf">1e-7</span> </pre></div> </div> <p>For more details of the parameter for FCISolver, See <code class="xref py py-mod docutils literal notranslate"><span class="pre">fci</span></code>.</p> </dd> </dl> </dd> </dl> <p>Saved results</p> <blockquote> <div><dl class="simple"> <dt>e_tot<span class="classifier">float</span></dt><dd><p>Total MCSCF energy (electronic energy plus nuclear repulsion)</p> </dd> <dt>e_cas<span class="classifier">float</span></dt><dd><p>CAS space FCI energy</p> </dd> <dt>ci<span class="classifier">ndarray</span></dt><dd><p>CAS space FCI coefficients</p> </dd> <dt>mo_coeff<span class="classifier">ndarray</span></dt><dd><p>When canonicalization is specified, the orbitals are canonical orbitals which make the general Fock matrix (Fock operator on top of MCSCF 1-particle density matrix) diagonalized within each subspace (core, active, external). If natorb (natural orbitals in active space) is specified, the active segment of the mo_coeff is natural orbitls.</p> </dd> <dt>mo_energy<span class="classifier">ndarray</span></dt><dd><p>Diagonal elements of general Fock matrix (in mo_coeff representation).</p> </dd> <dt>mo_occ<span class="classifier">ndarray</span></dt><dd><p>Occupation numbers of natural orbitals if natorb is specified.</p> </dd> </dl> </div></blockquote> <p>Examples:</p> <div class="doctest highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">from</span> <span class="nn">pyscf</span> <span class="kn">import</span> <span class="n">gto</span><span class="p">,</span> <span class="n">scf</span><span class="p">,</span> <span class="n">mcscf</span> <span class="gp">&gt;&gt;&gt; </span><span class="n">mol</span> <span class="o">=</span> <span class="n">gto</span><span class="o">.</span><span class="n">M</span><span class="p">(</span><span class="n">atom</span><span class="o">=</span><span class="s1">&#39;N 0 0 0; N 0 0 1&#39;</span><span class="p">,</span> <span class="n">basis</span><span class="o">=</span><span class="s1">&#39;ccpvdz&#39;</span><span class="p">,</span> <span class="n">verbose</span><span class="o">=</span><span class="mi">0</span><span class="p">)</span> <span class="gp">&gt;&gt;&gt; </span><span class="n">mf</span> <span class="o">=</span> <span class="n">scf</span><span class="o">.</span><span class="n">RHF</span><span class="p">(</span><span class="n">mol</span><span class="p">)</span> <span class="gp">&gt;&gt;&gt; </span><span class="n">mf</span><span class="o">.</span><span class="n">scf</span><span class="p">()</span> <span class="gp">&gt;&gt;&gt; </span><span class="n">mc</span> <span class="o">=</span> <span class="n">mcscf</span><span class="o">.</span><span class="n">CASCI</span><span class="p">(</span><span class="n">mf</span><span class="p">,</span> <span class="mi">6</span><span class="p">,</span> <span class="mi">6</span><span class="p">)</span> <span class="gp">&gt;&gt;&gt; </span><span class="n">mc</span><span class="o">.</span><span class="n">kernel</span><span class="p">()[</span><span class="mi">0</span><span class="p">]</span> <span class="go">-108.980200816243354</span> <span class="go">CASSCF</span> </pre></div> </div> <p>Extra attributes for CASSCF:</p> <blockquote> <div><dl> <dt>conv_tol<span class="classifier">float</span></dt><dd><p>Converge threshold. Default is 1e-7</p> </dd> <dt>conv_tol_grad<span class="classifier">float</span></dt><dd><p>Converge threshold for CI gradients and orbital rotation gradients. Default is 1e-4</p> </dd> <dt>max_stepsize<span class="classifier">float</span></dt><dd><p>The step size for orbital rotation. Small step (0.005 - 0.05) is prefered. (see notes in max_cycle_micro_inner attribute) Default is 0.03.</p> </dd> <dt>max_cycle_macro<span class="classifier">int</span></dt><dd><p>Max number of macro iterations. Default is 50.</p> </dd> <dt>max_cycle_micro<span class="classifier">int</span></dt><dd><p>Max number of micro (CIAH) iterations in each macro iteration.</p> </dd> <dt>ah_level_shift<span class="classifier">float, for AH solver.</span></dt><dd><p>Level shift for the Davidson diagonalization in AH solver. Default is 1e-8.</p> </dd> <dt>ah_conv_tol<span class="classifier">float, for AH solver.</span></dt><dd><p>converge threshold for AH solver. Default is 1e-12.</p> </dd> <dt>ah_max_cycle<span class="classifier">float, for AH solver.</span></dt><dd><p>Max number of iterations allowd in AH solver. Default is 30.</p> </dd> <dt>ah_lindep<span class="classifier">float, for AH solver.</span></dt><dd><p>Linear dependence threshold for AH solver. Default is 1e-14.</p> </dd> <dt>ah_start_tol<span class="classifier">flat, for AH solver.</span></dt><dd><p>In AH solver, the orbital rotation is started without completely solving the AH problem. This value is to control the start point. Default is 0.2.</p> </dd> <dt>ah_start_cycle<span class="classifier">int, for AH solver.</span></dt><dd><p>In AH solver, the orbital rotation is started without completely solving the AH problem. This value is to control the start point. Default is 2.</p> <p><code class="docutils literal notranslate"><span class="pre">ah_conv_tol</span></code>, <code class="docutils literal notranslate"><span class="pre">ah_max_cycle</span></code>, <code class="docutils literal notranslate"><span class="pre">ah_lindep</span></code>, <code class="docutils literal notranslate"><span class="pre">ah_start_tol</span></code> and <code class="docutils literal notranslate"><span class="pre">ah_start_cycle</span></code> can affect the accuracy and performance of CASSCF solver. Lower <code class="docutils literal notranslate"><span class="pre">ah_conv_tol</span></code> and <code class="docutils literal notranslate"><span class="pre">ah_lindep</span></code> might improve the accuracy of CASSCF optimization, but decrease the performance.</p> <div class="doctest highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">from</span> <span class="nn">pyscf</span> <span class="kn">import</span> <span class="n">gto</span><span class="p">,</span> <span class="n">scf</span><span class="p">,</span> <span class="n">mcscf</span> <span class="gp">&gt;&gt;&gt; </span><span class="n">mol</span> <span class="o">=</span> <span class="n">gto</span><span class="o">.</span><span class="n">M</span><span class="p">(</span><span class="n">atom</span><span class="o">=</span><span class="s1">&#39;N 0 0 0; N 0 0 1&#39;</span><span class="p">,</span> <span class="n">basis</span><span class="o">=</span><span class="s1">&#39;ccpvdz&#39;</span><span class="p">,</span> <span class="n">verbose</span><span class="o">=</span><span class="mi">0</span><span class="p">)</span> <span class="gp">&gt;&gt;&gt; </span><span class="n">mf</span> <span class="o">=</span> <span class="n">scf</span><span class="o">.</span><span class="n">UHF</span><span class="p">(</span><span class="n">mol</span><span class="p">)</span> <span class="gp">&gt;&gt;&gt; </span><span class="n">mf</span><span class="o">.</span><span class="n">scf</span><span class="p">()</span> <span class="gp">&gt;&gt;&gt; </span><span class="n">mc</span> <span class="o">=</span> <span class="n">mcscf</span><span class="o">.</span><span class="n">CASSCF</span><span class="p">(</span><span class="n">mf</span><span class="p">,</span> <span class="mi">6</span><span class="p">,</span> <span class="mi">6</span><span class="p">)</span> <span class="gp">&gt;&gt;&gt; </span><span class="n">mc</span><span class="o">.</span><span class="n">conv_tol</span> <span class="o">=</span> <span class="mf">1e-10</span> <span class="gp">&gt;&gt;&gt; </span><span class="n">mc</span><span class="o">.</span><span class="n">ah_conv_tol</span> <span class="o">=</span> <span class="mf">1e-5</span> <span class="gp">&gt;&gt;&gt; </span><span class="n">mc</span><span class="o">.</span><span class="n">kernel</span><span class="p">()</span> <span class="go">-109.044401898486001</span> <span class="gp">&gt;&gt;&gt; </span><span class="n">mc</span><span class="o">.</span><span class="n">ah_conv_tol</span> <span class="o">=</span> <span class="mf">1e-10</span> <span class="gp">&gt;&gt;&gt; </span><span class="n">mc</span><span class="o">.</span><span class="n">kernel</span><span class="p">()</span> <span class="go">-109.044401887945668</span> </pre></div> </div> </dd> <dt>chkfile<span class="classifier">str</span></dt><dd><p>Checkpoint file to save the intermediate orbitals during the CASSCF optimization. Default is the checkpoint file of mean field object.</p> </dd> <dt>callback<span class="classifier">function(envs_dict) =&gt; None</span></dt><dd><p>callback function takes one dict as the argument which is generated by the builtin function <code class="xref py py-func docutils literal notranslate"><span class="pre">locals()</span></code>, so that the callback function can access all local variables in the current envrionment.</p> </dd> </dl> </div></blockquote> <p>Saved results</p> <blockquote> <div><dl class="simple"> <dt>e_tot<span class="classifier">float</span></dt><dd><p>Total MCSCF energy (electronic energy plus nuclear repulsion)</p> </dd> <dt>ci<span class="classifier">ndarray</span></dt><dd><p>CAS space FCI coefficients</p> </dd> <dt>converged<span class="classifier">bool</span></dt><dd><p>It indicates CASSCF optimization converged or not.</p> </dd> <dt>mo_coeff<span class="classifier">ndarray</span></dt><dd><p>Optimized CASSCF orbitals coefficients</p> </dd> </dl> </div></blockquote> <p>Examples:</p> <div class="doctest highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">from</span> <span class="nn">pyscf</span> <span class="kn">import</span> <span class="n">gto</span><span class="p">,</span> <span class="n">scf</span><span class="p">,</span> <span class="n">mcscf</span> <span class="gp">&gt;&gt;&gt; </span><span class="n">mol</span> <span class="o">=</span> <span class="n">gto</span><span class="o">.</span><span class="n">M</span><span class="p">(</span><span class="n">atom</span><span class="o">=</span><span class="s1">&#39;N 0 0 0; N 0 0 1&#39;</span><span class="p">,</span> <span class="n">basis</span><span class="o">=</span><span class="s1">&#39;ccpvdz&#39;</span><span class="p">,</span> <span class="n">verbose</span><span class="o">=</span><span class="mi">0</span><span class="p">)</span> <span class="gp">&gt;&gt;&gt; </span><span class="n">mf</span> <span class="o">=</span> <span class="n">scf</span><span class="o">.</span><span class="n">RHF</span><span class="p">(</span><span class="n">mol</span><span class="p">)</span> <span class="gp">&gt;&gt;&gt; </span><span class="n">mf</span><span class="o">.</span><span class="n">scf</span><span class="p">()</span> <span class="gp">&gt;&gt;&gt; </span><span class="n">mc</span> <span class="o">=</span> <span class="n">mcscf</span><span class="o">.</span><span class="n">CASSCF</span><span class="p">(</span><span class="n">mf</span><span class="p">,</span> <span class="mi">6</span><span class="p">,</span> <span class="mi">6</span><span class="p">)</span> <span class="gp">&gt;&gt;&gt; </span><span class="n">mc</span><span class="o">.</span><span class="n">kernel</span><span class="p">()[</span><span class="mi">0</span><span class="p">]</span> <span class="go">-109.044401882238134</span> </pre></div> </div> <dl class="py method"> <dt id="pyscf.mcscf.newton_casscf.CASSCF.casci"> <code class="sig-name descname">casci</code><span class="sig-paren">(</span><em class="sig-param"><span class="n">mo_coeff</span></em>, <em class="sig-param"><span class="n">ci0</span><span class="o">=</span><span class="default_value">None</span></em>, <em class="sig-param"><span class="n">eris</span><span class="o">=</span><span class="default_value">None</span></em>, <em class="sig-param"><span class="n">verbose</span><span class="o">=</span><span class="default_value">None</span></em>, <em class="sig-param"><span class="n">envs</span><span class="o">=</span><span class="default_value">None</span></em><span class="sig-paren">)</span><a class="headerlink" href="#pyscf.mcscf.newton_casscf.CASSCF.casci" title="Permalink to this definition">¶</a></dt> <dd></dd></dl> <dl class="py method"> <dt id="pyscf.mcscf.newton_casscf.CASSCF.dump_flags"> <code class="sig-name descname">dump_flags</code><span class="sig-paren">(</span><em class="sig-param"><span class="n">verbose</span><span class="o">=</span><span class="default_value">None</span></em><span class="sig-paren">)</span><a class="headerlink" href="#pyscf.mcscf.newton_casscf.CASSCF.dump_flags" title="Permalink to this definition">¶</a></dt> <dd></dd></dl> <dl class="py method"> <dt id="pyscf.mcscf.newton_casscf.CASSCF.get_h2cas"> <code class="sig-name descname">get_h2cas</code><span class="sig-paren">(</span><em class="sig-param"><span class="n">mo_coeff</span><span class="o">=</span><span class="default_value">None</span></em><span class="sig-paren">)</span><a class="headerlink" href="#pyscf.mcscf.newton_casscf.CASSCF.get_h2cas" title="Permalink to this definition">¶</a></dt> <dd><p>Computing active space two-particle Hamiltonian.</p> <p>Note It is different to get_h2eff when df.approx_hessian is applied, in which get_h2eff function returns the DF integrals while get_h2cas returns the regular 2-electron integrals.</p> </dd></dl> <dl class="py method"> <dt id="pyscf.mcscf.newton_casscf.CASSCF.get_h2eff"> <code class="sig-name descname">get_h2eff</code><span class="sig-paren">(</span><em class="sig-param"><span class="n">mo_coeff</span><span class="o">=</span><span class="default_value">None</span></em><span class="sig-paren">)</span><a class="headerlink" href="#pyscf.mcscf.newton_casscf.CASSCF.get_h2eff" title="Permalink to this definition">¶</a></dt> <dd><p>Computing active space two-particle Hamiltonian.</p> <p>Note It is different to get_h2cas when df.approx_hessian is applied, in which get_h2eff function returns the DF integrals while get_h2cas returns the regular 2-electron integrals.</p> </dd></dl> <dl class="py method"> <dt id="pyscf.mcscf.newton_casscf.CASSCF.kernel"> <code class="sig-name descname">kernel</code><span class="sig-paren">(</span><em class="sig-param"><span class="n">mo_coeff</span><span class="o">=</span><span class="default_value">None</span></em>, <em class="sig-param"><span class="n">ci0</span><span class="o">=</span><span class="default_value">None</span></em>, <em class="sig-param"><span class="n">callback</span><span class="o">=</span><span class="default_value">None</span></em><span class="sig-paren">)</span><a class="headerlink" href="#pyscf.mcscf.newton_casscf.CASSCF.kernel" title="Permalink to this definition">¶</a></dt> <dd><dl class="simple"> <dt>Returns:</dt><dd><p>Five elements, they are total energy, active space CI energy, the active space FCI wavefunction coefficients or DMRG wavefunction ID, the MCSCF canonical orbital coefficients, the MCSCF canonical orbital coefficients.</p> </dd> </dl> <p>They are attributes of mcscf object, which can be accessed by .e_tot, .e_cas, .ci, .mo_coeff, .mo_energy</p> </dd></dl> <dl class="py method"> <dt id="pyscf.mcscf.newton_casscf.CASSCF.update_ao2mo"> <code class="sig-name descname">update_ao2mo</code><span class="sig-paren">(</span><em class="sig-param"><span class="n">mo</span></em><span class="sig-paren">)</span><a class="headerlink" href="#pyscf.mcscf.newton_casscf.CASSCF.update_ao2mo" title="Permalink to this definition">¶</a></dt> <dd></dd></dl> </dd></dl> <dl class="py function"> <dt id="pyscf.mcscf.newton_casscf.extract_rotation"> <code class="sig-prename descclassname">pyscf.mcscf.newton_casscf.</code><code class="sig-name descname">extract_rotation</code><span class="sig-paren">(</span><em class="sig-param"><span class="n">casscf</span></em>, <em class="sig-param"><span class="n">dr</span></em>, <em class="sig-param"><span class="n">u</span></em>, <em class="sig-param"><span class="n">ci0</span></em><span class="sig-paren">)</span><a class="headerlink" href="#pyscf.mcscf.newton_casscf.extract_rotation" title="Permalink to this definition">¶</a></dt> <dd></dd></dl> <dl class="py function"> <dt id="pyscf.mcscf.newton_casscf.gen_g_hop"> <code class="sig-prename descclassname">pyscf.mcscf.newton_casscf.</code><code class="sig-name descname">gen_g_hop</code><span class="sig-paren">(</span><em class="sig-param"><span class="n">casscf</span></em>, <em class="sig-param"><span class="n">mo</span></em>, <em class="sig-param"><span class="n">ci0</span></em>, <em class="sig-param"><span class="n">eris</span></em>, <em class="sig-param"><span class="n">verbose</span><span class="o">=</span><span class="default_value">None</span></em><span class="sig-paren">)</span><a class="headerlink" href="#pyscf.mcscf.newton_casscf.gen_g_hop" title="Permalink to this definition">¶</a></dt> <dd></dd></dl> <dl class="py function"> <dt id="pyscf.mcscf.newton_casscf.kernel"> <code class="sig-prename descclassname">pyscf.mcscf.newton_casscf.</code><code class="sig-name descname">kernel</code><span class="sig-paren">(</span><em class="sig-param"><span class="n">casscf</span></em>, <em class="sig-param"><span class="n">mo_coeff</span></em>, <em class="sig-param"><span class="n">tol</span><span class="o">=</span><span class="default_value">1e-07</span></em>, <em class="sig-param"><span class="n">conv_tol_grad</span><span class="o">=</span><span class="default_value">None</span></em>, <em class="sig-param"><span class="n">ci0</span><span class="o">=</span><span class="default_value">None</span></em>, <em class="sig-param"><span class="n">callback</span><span class="o">=</span><span class="default_value">None</span></em>, <em class="sig-param"><span class="n">verbose</span><span class="o">=</span><span class="default_value">3</span></em>, <em class="sig-param"><span class="n">dump_chk</span><span class="o">=</span><span class="default_value">True</span></em><span class="sig-paren">)</span><a class="headerlink" href="#pyscf.mcscf.newton_casscf.kernel" title="Permalink to this definition">¶</a></dt> <dd><p>Second order CASSCF driver</p> </dd></dl> <dl class="py function"> <dt id="pyscf.mcscf.newton_casscf.update_orb_ci"> <code class="sig-prename descclassname">pyscf.mcscf.newton_casscf.</code><code class="sig-name descname">update_orb_ci</code><span class="sig-paren">(</span><em class="sig-param"><span class="n">casscf</span></em>, <em class="sig-param"><span class="n">mo</span></em>, <em class="sig-param"><span class="n">ci0</span></em>, <em class="sig-param"><span class="n">eris</span></em>, <em class="sig-param"><span class="n">x0_guess</span><span class="o">=</span><span class="default_value">None</span></em>, <em class="sig-param"><span class="n">conv_tol_grad</span><span class="o">=</span><span class="default_value">0.0001</span></em>, <em class="sig-param"><span class="n">max_stepsize</span><span class="o">=</span><span class="default_value">None</span></em>, <em class="sig-param"><span class="n">verbose</span><span class="o">=</span><span class="default_value">None</span></em><span class="sig-paren">)</span><a class="headerlink" href="#pyscf.mcscf.newton_casscf.update_orb_ci" title="Permalink to this definition">¶</a></dt> <dd></dd></dl> </div> <div class="section" id="module-pyscf.mcscf.newton_casscf_symm"> <span id="pyscf-mcscf-newton-casscf-symm-module"></span><h2>pyscf.mcscf.newton_casscf_symm module<a class="headerlink" href="#module-pyscf.mcscf.newton_casscf_symm" title="Permalink to this headline">¶</a></h2> <dl class="py class"> <dt id="pyscf.mcscf.newton_casscf_symm.CASSCF"> <em class="property">class </em><code class="sig-prename descclassname">pyscf.mcscf.newton_casscf_symm.</code><code class="sig-name descname">CASSCF</code><span class="sig-paren">(</span><em class="sig-param"><span class="n">mf_or_mol</span></em>, <em class="sig-param"><span class="n">ncas</span></em>, <em class="sig-param"><span class="n">nelecas</span></em>, <em class="sig-param"><span class="n">ncore</span><span class="o">=</span><span class="default_value">None</span></em>, <em class="sig-param"><span class="n">frozen</span><span class="o">=</span><span class="default_value">None</span></em><span class="sig-paren">)</span><a class="headerlink" href="#pyscf.mcscf.newton_casscf_symm.CASSCF" title="Permalink to this definition">¶</a></dt> <dd><p>Bases: <a class="reference internal" href="#pyscf.mcscf.newton_casscf.CASSCF" title="pyscf.mcscf.newton_casscf.CASSCF"><code class="xref py py-class docutils literal notranslate"><span class="pre">pyscf.mcscf.newton_casscf.CASSCF</span></code></a></p> <dl> <dt>Args:</dt><dd><dl class="simple"> <dt>mf_or_mol<span class="classifier">SCF object or Mole object</span></dt><dd><p>SCF or Mole to define the problem size.</p> </dd> <dt>ncas<span class="classifier">int</span></dt><dd><p>Number of active orbitals.</p> </dd> <dt>nelecas<span class="classifier">int or a pair of int</span></dt><dd><p>Number of electrons in active space.</p> </dd> </dl> </dd> <dt>Kwargs:</dt><dd><dl class="simple"> <dt>ncore<span class="classifier">int</span></dt><dd><p>Number of doubly occupied core orbitals. If not presented, this parameter can be automatically determined.</p> </dd> </dl> </dd> <dt>Attributes:</dt><dd><dl> <dt>verbose<span class="classifier">int</span></dt><dd><p>Print level. Default value equals to <code class="xref py py-class docutils literal notranslate"><span class="pre">Mole.verbose</span></code>.</p> </dd> <dt>max_memory<span class="classifier">float or int</span></dt><dd><p>Allowed memory in MB. Default value equals to <code class="xref py py-class docutils literal notranslate"><span class="pre">Mole.max_memory</span></code>.</p> </dd> <dt>ncas<span class="classifier">int</span></dt><dd><p>Active space size.</p> </dd> <dt>nelecas<span class="classifier">tuple of int</span></dt><dd><p>Active (nelec_alpha, nelec_beta)</p> </dd> <dt>ncore<span class="classifier">int or tuple of int</span></dt><dd><p>Core electron number. In UHF-CASSCF, it’s a tuple to indicate the different core eletron numbers.</p> </dd> <dt>natorb<span class="classifier">bool</span></dt><dd><p>Whether to transform natural orbitals in active space. Note: when CASCI/CASSCF are combined with DMRG solver or selected CI solver, enabling this parameter may slightly change the total energy. False by default.</p> </dd> <dt>canonicalization<span class="classifier">bool</span></dt><dd><p>Whether to canonicalize orbitals in core and external space against the general Fock matrix. The orbitals in active space are NOT transformed by default. To get the natural orbitals in active space, the attribute .natorb needs to be enabled. True by default.</p> </dd> <dt>sorting_mo_energy<span class="classifier">bool</span></dt><dd><p>Whether to sort the orbitals based on the diagonal elements of the general Fock matrix. Default is False.</p> </dd> <dt>fcisolver<span class="classifier">an instance of <code class="xref py py-class docutils literal notranslate"><span class="pre">FCISolver</span></code></span></dt><dd><p>The pyscf.fci module provides several FCISolver for different scenario. Generally, fci.direct_spin1.FCISolver can be used for all RHF-CASSCF. However, a proper FCISolver can provide better performance and better numerical stability. One can either use <code class="xref py py-func docutils literal notranslate"><span class="pre">fci.solver()</span></code> function to pick the FCISolver by the program or manually assigen the FCISolver to this attribute, e.g.</p> <div class="doctest highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">from</span> <span class="nn">pyscf</span> <span class="kn">import</span> <span class="n">fci</span> <span class="gp">&gt;&gt;&gt; </span><span class="n">mc</span> <span class="o">=</span> <span class="n">mcscf</span><span class="o">.</span><span class="n">CASSCF</span><span class="p">(</span><span class="n">mf</span><span class="p">,</span> <span class="mi">4</span><span class="p">,</span> <span class="mi">4</span><span class="p">)</span> <span class="gp">&gt;&gt;&gt; </span><span class="n">mc</span><span class="o">.</span><span class="n">fcisolver</span> <span class="o">=</span> <span class="n">fci</span><span class="o">.</span><span class="n">solver</span><span class="p">(</span><span class="n">mol</span><span class="p">,</span> <span class="n">singlet</span><span class="o">=</span><span class="kc">True</span><span class="p">)</span> <span class="gp">&gt;&gt;&gt; </span><span class="n">mc</span><span class="o">.</span><span class="n">fcisolver</span> <span class="o">=</span> <span class="n">fci</span><span class="o">.</span><span class="n">direct_spin1</span><span class="o">.</span><span class="n">FCISolver</span><span class="p">(</span><span class="n">mol</span><span class="p">)</span> </pre></div> </div> <p>You can control FCISolver by setting e.g.:</p> <div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">mc</span><span class="o">.</span><span class="n">fcisolver</span><span class="o">.</span><span class="n">max_cycle</span> <span class="o">=</span> <span class="mi">30</span> <span class="gp">&gt;&gt;&gt; </span><span class="n">mc</span><span class="o">.</span><span class="n">fcisolver</span><span class="o">.</span><span class="n">conv_tol</span> <span class="o">=</span> <span class="mf">1e-7</span> </pre></div> </div> <p>For more details of the parameter for FCISolver, See <code class="xref py py-mod docutils literal notranslate"><span class="pre">fci</span></code>.</p> </dd> </dl> </dd> </dl> <p>Saved results</p> <blockquote> <div><dl class="simple"> <dt>e_tot<span class="classifier">float</span></dt><dd><p>Total MCSCF energy (electronic energy plus nuclear repulsion)</p> </dd> <dt>e_cas<span class="classifier">float</span></dt><dd><p>CAS space FCI energy</p> </dd> <dt>ci<span class="classifier">ndarray</span></dt><dd><p>CAS space FCI coefficients</p> </dd> <dt>mo_coeff<span class="classifier">ndarray</span></dt><dd><p>When canonicalization is specified, the orbitals are canonical orbitals which make the general Fock matrix (Fock operator on top of MCSCF 1-particle density matrix) diagonalized within each subspace (core, active, external). If natorb (natural orbitals in active space) is specified, the active segment of the mo_coeff is natural orbitls.</p> </dd> <dt>mo_energy<span class="classifier">ndarray</span></dt><dd><p>Diagonal elements of general Fock matrix (in mo_coeff representation).</p> </dd> <dt>mo_occ<span class="classifier">ndarray</span></dt><dd><p>Occupation numbers of natural orbitals if natorb is specified.</p> </dd> </dl> </div></blockquote> <p>Examples:</p> <div class="doctest highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">from</span> <span class="nn">pyscf</span> <span class="kn">import</span> <span class="n">gto</span><span class="p">,</span> <span class="n">scf</span><span class="p">,</span> <span class="n">mcscf</span> <span class="gp">&gt;&gt;&gt; </span><span class="n">mol</span> <span class="o">=</span> <span class="n">gto</span><span class="o">.</span><span class="n">M</span><span class="p">(</span><span class="n">atom</span><span class="o">=</span><span class="s1">&#39;N 0 0 0; N 0 0 1&#39;</span><span class="p">,</span> <span class="n">basis</span><span class="o">=</span><span class="s1">&#39;ccpvdz&#39;</span><span class="p">,</span> <span class="n">verbose</span><span class="o">=</span><span class="mi">0</span><span class="p">)</span> <span class="gp">&gt;&gt;&gt; </span><span class="n">mf</span> <span class="o">=</span> <span class="n">scf</span><span class="o">.</span><span class="n">RHF</span><span class="p">(</span><span class="n">mol</span><span class="p">)</span> <span class="gp">&gt;&gt;&gt; </span><span class="n">mf</span><span class="o">.</span><span class="n">scf</span><span class="p">()</span> <span class="gp">&gt;&gt;&gt; </span><span class="n">mc</span> <span class="o">=</span> <span class="n">mcscf</span><span class="o">.</span><span class="n">CASCI</span><span class="p">(</span><span class="n">mf</span><span class="p">,</span> <span class="mi">6</span><span class="p">,</span> <span class="mi">6</span><span class="p">)</span> <span class="gp">&gt;&gt;&gt; </span><span class="n">mc</span><span class="o">.</span><span class="n">kernel</span><span class="p">()[</span><span class="mi">0</span><span class="p">]</span> <span class="go">-108.980200816243354</span> <span class="go">CASSCF</span> </pre></div> </div> <p>Extra attributes for CASSCF:</p> <blockquote> <div><dl> <dt>conv_tol<span class="classifier">float</span></dt><dd><p>Converge threshold. Default is 1e-7</p> </dd> <dt>conv_tol_grad<span class="classifier">float</span></dt><dd><p>Converge threshold for CI gradients and orbital rotation gradients. Default is 1e-4</p> </dd> <dt>max_stepsize<span class="classifier">float</span></dt><dd><p>The step size for orbital rotation. Small step (0.005 - 0.05) is prefered. (see notes in max_cycle_micro_inner attribute) Default is 0.03.</p> </dd> <dt>max_cycle_macro<span class="classifier">int</span></dt><dd><p>Max number of macro iterations. Default is 50.</p> </dd> <dt>max_cycle_micro<span class="classifier">int</span></dt><dd><p>Max number of micro (CIAH) iterations in each macro iteration.</p> </dd> <dt>ah_level_shift<span class="classifier">float, for AH solver.</span></dt><dd><p>Level shift for the Davidson diagonalization in AH solver. Default is 1e-8.</p> </dd> <dt>ah_conv_tol<span class="classifier">float, for AH solver.</span></dt><dd><p>converge threshold for AH solver. Default is 1e-12.</p> </dd> <dt>ah_max_cycle<span class="classifier">float, for AH solver.</span></dt><dd><p>Max number of iterations allowd in AH solver. Default is 30.</p> </dd> <dt>ah_lindep<span class="classifier">float, for AH solver.</span></dt><dd><p>Linear dependence threshold for AH solver. Default is 1e-14.</p> </dd> <dt>ah_start_tol<span class="classifier">flat, for AH solver.</span></dt><dd><p>In AH solver, the orbital rotation is started without completely solving the AH problem. This value is to control the start point. Default is 0.2.</p> </dd> <dt>ah_start_cycle<span class="classifier">int, for AH solver.</span></dt><dd><p>In AH solver, the orbital rotation is started without completely solving the AH problem. This value is to control the start point. Default is 2.</p> <p><code class="docutils literal notranslate"><span class="pre">ah_conv_tol</span></code>, <code class="docutils literal notranslate"><span class="pre">ah_max_cycle</span></code>, <code class="docutils literal notranslate"><span class="pre">ah_lindep</span></code>, <code class="docutils literal notranslate"><span class="pre">ah_start_tol</span></code> and <code class="docutils literal notranslate"><span class="pre">ah_start_cycle</span></code> can affect the accuracy and performance of CASSCF solver. Lower <code class="docutils literal notranslate"><span class="pre">ah_conv_tol</span></code> and <code class="docutils literal notranslate"><span class="pre">ah_lindep</span></code> might improve the accuracy of CASSCF optimization, but decrease the performance.</p> <div class="doctest highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">from</span> <span class="nn">pyscf</span> <span class="kn">import</span> <span class="n">gto</span><span class="p">,</span> <span class="n">scf</span><span class="p">,</span> <span class="n">mcscf</span> <span class="gp">&gt;&gt;&gt; </span><span class="n">mol</span> <span class="o">=</span> <span class="n">gto</span><span class="o">.</span><span class="n">M</span><span class="p">(</span><span class="n">atom</span><span class="o">=</span><span class="s1">&#39;N 0 0 0; N 0 0 1&#39;</span><span class="p">,</span> <span class="n">basis</span><span class="o">=</span><span class="s1">&#39;ccpvdz&#39;</span><span class="p">,</span> <span class="n">verbose</span><span class="o">=</span><span class="mi">0</span><span class="p">)</span> <span class="gp">&gt;&gt;&gt; </span><span class="n">mf</span> <span class="o">=</span> <span class="n">scf</span><span class="o">.</span><span class="n">UHF</span><span class="p">(</span><span class="n">mol</span><span class="p">)</span> <span class="gp">&gt;&gt;&gt; </span><span class="n">mf</span><span class="o">.</span><span class="n">scf</span><span class="p">()</span> <span class="gp">&gt;&gt;&gt; </span><span class="n">mc</span> <span class="o">=</span> <span class="n">mcscf</span><span class="o">.</span><span class="n">CASSCF</span><span class="p">(</span><span class="n">mf</span><span class="p">,</span> <span class="mi">6</span><span class="p">,</span> <span class="mi">6</span><span class="p">)</span> <span class="gp">&gt;&gt;&gt; </span><span class="n">mc</span><span class="o">.</span><span class="n">conv_tol</span> <span class="o">=</span> <span class="mf">1e-10</span> <span class="gp">&gt;&gt;&gt; </span><span class="n">mc</span><span class="o">.</span><span class="n">ah_conv_tol</span> <span class="o">=</span> <span class="mf">1e-5</span> <span class="gp">&gt;&gt;&gt; </span><span class="n">mc</span><span class="o">.</span><span class="n">kernel</span><span class="p">()</span> <span class="go">-109.044401898486001</span> <span class="gp">&gt;&gt;&gt; </span><span class="n">mc</span><span class="o">.</span><span class="n">ah_conv_tol</span> <span class="o">=</span> <span class="mf">1e-10</span> <span class="gp">&gt;&gt;&gt; </span><span class="n">mc</span><span class="o">.</span><span class="n">kernel</span><span class="p">()</span> <span class="go">-109.044401887945668</span> </pre></div> </div> </dd> <dt>chkfile<span class="classifier">str</span></dt><dd><p>Checkpoint file to save the intermediate orbitals during the CASSCF optimization. Default is the checkpoint file of mean field object.</p> </dd> <dt>callback<span class="classifier">function(envs_dict) =&gt; None</span></dt><dd><p>callback function takes one dict as the argument which is generated by the builtin function <code class="xref py py-func docutils literal notranslate"><span class="pre">locals()</span></code>, so that the callback function can access all local variables in the current envrionment.</p> </dd> </dl> </div></blockquote> <p>Saved results</p> <blockquote> <div><dl class="simple"> <dt>e_tot<span class="classifier">float</span></dt><dd><p>Total MCSCF energy (electronic energy plus nuclear repulsion)</p> </dd> <dt>ci<span class="classifier">ndarray</span></dt><dd><p>CAS space FCI coefficients</p> </dd> <dt>converged<span class="classifier">bool</span></dt><dd><p>It indicates CASSCF optimization converged or not.</p> </dd> <dt>mo_coeff<span class="classifier">ndarray</span></dt><dd><p>Optimized CASSCF orbitals coefficients</p> </dd> </dl> </div></blockquote> <p>Examples:</p> <div class="doctest highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">from</span> <span class="nn">pyscf</span> <span class="kn">import</span> <span class="n">gto</span><span class="p">,</span> <span class="n">scf</span><span class="p">,</span> <span class="n">mcscf</span> <span class="gp">&gt;&gt;&gt; </span><span class="n">mol</span> <span class="o">=</span> <span class="n">gto</span><span class="o">.</span><span class="n">M</span><span class="p">(</span><span class="n">atom</span><span class="o">=</span><span class="s1">&#39;N 0 0 0; N 0 0 1&#39;</span><span class="p">,</span> <span class="n">basis</span><span class="o">=</span><span class="s1">&#39;ccpvdz&#39;</span><span class="p">,</span> <span class="n">verbose</span><span class="o">=</span><span class="mi">0</span><span class="p">)</span> <span class="gp">&gt;&gt;&gt; </span><span class="n">mf</span> <span class="o">=</span> <span class="n">scf</span><span class="o">.</span><span class="n">RHF</span><span class="p">(</span><span class="n">mol</span><span class="p">)</span> <span class="gp">&gt;&gt;&gt; </span><span class="n">mf</span><span class="o">.</span><span class="n">scf</span><span class="p">()</span> <span class="gp">&gt;&gt;&gt; </span><span class="n">mc</span> <span class="o">=</span> <span class="n">mcscf</span><span class="o">.</span><span class="n">CASSCF</span><span class="p">(</span><span class="n">mf</span><span class="p">,</span> <span class="mi">6</span><span class="p">,</span> <span class="mi">6</span><span class="p">)</span> <span class="gp">&gt;&gt;&gt; </span><span class="n">mc</span><span class="o">.</span><span class="n">kernel</span><span class="p">()[</span><span class="mi">0</span><span class="p">]</span> <span class="go">-109.044401882238134</span> </pre></div> </div> <dl class="py method"> <dt id="pyscf.mcscf.newton_casscf_symm.CASSCF.kernel"> <code class="sig-name descname">kernel</code><span class="sig-paren">(</span><em class="sig-param"><span class="n">mo_coeff</span><span class="o">=</span><span class="default_value">None</span></em>, <em class="sig-param"><span class="n">ci0</span><span class="o">=</span><span class="default_value">None</span></em>, <em class="sig-param"><span class="n">callback</span><span class="o">=</span><span class="default_value">None</span></em>, <em class="sig-param"><span class="n">_kern</span><span class="o">=</span><span class="default_value">None</span></em><span class="sig-paren">)</span><a class="headerlink" href="#pyscf.mcscf.newton_casscf_symm.CASSCF.kernel" title="Permalink to this definition">¶</a></dt> <dd><dl class="simple"> <dt>Returns:</dt><dd><p>Five elements, they are total energy, active space CI energy, the active space FCI wavefunction coefficients or DMRG wavefunction ID, the MCSCF canonical orbital coefficients, the MCSCF canonical orbital coefficients.</p> </dd> </dl> <p>They are attributes of mcscf object, which can be accessed by .e_tot, .e_cas, .ci, .mo_coeff, .mo_energy</p> </dd></dl> <dl class="py method"> <dt id="pyscf.mcscf.newton_casscf_symm.CASSCF.rotate_mo"> <code class="sig-name descname">rotate_mo</code><span class="sig-paren">(</span><em class="sig-param"><span class="n">mo</span></em>, <em class="sig-param"><span class="n">u</span></em>, <em class="sig-param"><span class="n">log</span><span class="o">=</span><span class="default_value">None</span></em><span class="sig-paren">)</span><a class="headerlink" href="#pyscf.mcscf.newton_casscf_symm.CASSCF.rotate_mo" title="Permalink to this definition">¶</a></dt> <dd><p>Rotate orbitals with the given unitary matrix</p> </dd></dl> <dl class="py method"> <dt id="pyscf.mcscf.newton_casscf_symm.CASSCF.uniq_var_indices"> <code class="sig-name descname">uniq_var_indices</code><span class="sig-paren">(</span><em class="sig-param"><span class="n">nmo</span></em>, <em class="sig-param"><span class="n">ncore</span></em>, <em class="sig-param"><span class="n">ncas</span></em>, <em class="sig-param"><span class="n">frozen</span></em><span class="sig-paren">)</span><a class="headerlink" href="#pyscf.mcscf.newton_casscf_symm.CASSCF.uniq_var_indices" title="Permalink to this definition">¶</a></dt> <dd></dd></dl> </dd></dl> </div> <div class="section" id="module-pyscf.mcscf.ucasci"> <span id="pyscf-mcscf-ucasci-module"></span><h2>pyscf.mcscf.ucasci module<a class="headerlink" href="#module-pyscf.mcscf.ucasci" title="Permalink to this headline">¶</a></h2> <p>UCASCI (CASCI with non-degenerated alpha and beta orbitals, typically UHF orbitals)</p> <dl class="py attribute"> <dt id="pyscf.mcscf.ucasci.CASCI"> <code class="sig-prename descclassname">pyscf.mcscf.ucasci.</code><code class="sig-name descname">CASCI</code><a class="headerlink" href="#pyscf.mcscf.ucasci.CASCI" title="Permalink to this definition">¶</a></dt> <dd><p>alias of <a class="reference internal" href="#pyscf.mcscf.ucasci.UCASCI" title="pyscf.mcscf.ucasci.UCASCI"><code class="xref py py-class docutils literal notranslate"><span class="pre">pyscf.mcscf.ucasci.UCASCI</span></code></a></p> </dd></dl> <dl class="py class"> <dt id="pyscf.mcscf.ucasci.UCASCI"> <em class="property">class </em><code class="sig-prename descclassname">pyscf.mcscf.ucasci.</code><code class="sig-name descname">UCASCI</code><span class="sig-paren">(</span><em class="sig-param"><span class="n">mf_or_mol</span></em>, <em class="sig-param"><span class="n">ncas</span></em>, <em class="sig-param"><span class="n">nelecas</span></em>, <em class="sig-param"><span class="n">ncore</span><span class="o">=</span><span class="default_value">None</span></em><span class="sig-paren">)</span><a class="headerlink" href="#pyscf.mcscf.ucasci.UCASCI" title="Permalink to this definition">¶</a></dt> <dd><p>Bases: <a class="reference internal" href="#pyscf.mcscf.casci.CASCI" title="pyscf.mcscf.casci.CASCI"><code class="xref py py-class docutils literal notranslate"><span class="pre">pyscf.mcscf.casci.CASCI</span></code></a></p> <dl class="py method"> <dt id="pyscf.mcscf.ucasci.UCASCI.analyze"> <code class="sig-name descname">analyze</code><span class="sig-paren">(</span><em class="sig-param"><span class="n">mo_coeff</span><span class="o">=</span><span class="default_value">None</span></em>, <em class="sig-param"><span class="n">ci</span><span class="o">=</span><span class="default_value">None</span></em>, <em class="sig-param"><span class="n">verbose</span><span class="o">=</span><span class="default_value">None</span></em>, <em class="sig-param"><span class="n">large_ci_tol</span><span class="o">=</span><span class="default_value">0.1</span></em>, <em class="sig-param"><span class="n">with_meta_lowdin</span><span class="o">=</span><span class="default_value">True</span></em>, <em class="sig-param"><span class="o">**</span><span class="n">kwargs</span></em><span class="sig-paren">)</span><a class="headerlink" href="#pyscf.mcscf.ucasci.UCASCI.analyze" title="Permalink to this definition">¶</a></dt> <dd></dd></dl> <dl class="py method"> <dt id="pyscf.mcscf.ucasci.UCASCI.ao2mo"> <code class="sig-name descname">ao2mo</code><span class="sig-paren">(</span><em class="sig-param"><span class="n">mo_coeff</span><span class="o">=</span><span class="default_value">None</span></em><span class="sig-paren">)</span><a class="headerlink" href="#pyscf.mcscf.ucasci.UCASCI.ao2mo" title="Permalink to this definition">¶</a></dt> <dd><p>Compute the active space two-particle Hamiltonian.</p> </dd></dl> <dl class="py method"> <dt id="pyscf.mcscf.ucasci.UCASCI.cas_natorb"> <code class="sig-name descname">cas_natorb</code><span class="sig-paren">(</span><em class="sig-param"><span class="n">mo_coeff</span><span class="o">=</span><span class="default_value">None</span></em>, <em class="sig-param"><span class="n">ci0</span><span class="o">=</span><span class="default_value">None</span></em><span class="sig-paren">)</span><a class="headerlink" href="#pyscf.mcscf.ucasci.UCASCI.cas_natorb" title="Permalink to this definition">¶</a></dt> <dd><p>Transform active orbitals to natrual orbitals, and update the CI wfn accordingly</p> <dl class="simple"> <dt>Args:</dt><dd><p>mc : a CASSCF/CASCI object or RHF object</p> </dd> <dt>Kwargs:</dt><dd><dl class="simple"> <dt>sort<span class="classifier">bool</span></dt><dd><p>Sort natural orbitals wrt the occupancy.</p> </dd> </dl> </dd> <dt>Returns:</dt><dd><p>A tuple, the first item is natural orbitals, the second is updated CI coefficients, the third is the natural occupancy associated to the natural orbitals.</p> </dd> </dl> </dd></dl> <dl class="py method"> <dt id="pyscf.mcscf.ucasci.UCASCI.cas_natorb_"> <code class="sig-name descname">cas_natorb_</code><span class="sig-paren">(</span><em class="sig-param"><span class="n">mo_coeff</span><span class="o">=</span><span class="default_value">None</span></em>, <em class="sig-param"><span class="n">ci0</span><span class="o">=</span><span class="default_value">None</span></em><span class="sig-paren">)</span><a class="headerlink" href="#pyscf.mcscf.ucasci.UCASCI.cas_natorb_" title="Permalink to this definition">¶</a></dt> <dd><p>Transform active orbitals to natrual orbitals, and update the CI wfn accordingly</p> <dl class="simple"> <dt>Args:</dt><dd><p>mc : a CASSCF/CASCI object or RHF object</p> </dd> <dt>Kwargs:</dt><dd><dl class="simple"> <dt>sort<span class="classifier">bool</span></dt><dd><p>Sort natural orbitals wrt the occupancy.</p> </dd> </dl> </dd> <dt>Returns:</dt><dd><p>A tuple, the first item is natural orbitals, the second is updated CI coefficients, the third is the natural occupancy associated to the natural orbitals.</p> </dd> </dl> </dd></dl> <dl class="py method"> <dt id="pyscf.mcscf.ucasci.UCASCI.casci"> <code class="sig-name descname">casci</code><span class="sig-paren">(</span><em class="sig-param"><span class="n">mo_coeff</span><span class="o">=</span><span class="default_value">None</span></em>, <em class="sig-param"><span class="n">ci0</span><span class="o">=</span><span class="default_value">None</span></em><span class="sig-paren">)</span><a class="headerlink" href="#pyscf.mcscf.ucasci.UCASCI.casci" title="Permalink to this definition">¶</a></dt> <dd></dd></dl> <dl class="py method"> <dt id="pyscf.mcscf.ucasci.UCASCI.dump_flags"> <code class="sig-name descname">dump_flags</code><span class="sig-paren">(</span><em class="sig-param"><span class="n">verbose</span><span class="o">=</span><span class="default_value">None</span></em><span class="sig-paren">)</span><a class="headerlink" href="#pyscf.mcscf.ucasci.UCASCI.dump_flags" title="Permalink to this definition">¶</a></dt> <dd></dd></dl> <dl class="py attribute"> <dt id="pyscf.mcscf.ucasci.UCASCI.fix_spin"> <code class="sig-name descname">fix_spin</code><em class="property"> = None</em><a class="headerlink" href="#pyscf.mcscf.ucasci.UCASCI.fix_spin" title="Permalink to this definition">¶</a></dt> <dd></dd></dl> <dl class="py attribute"> <dt id="pyscf.mcscf.ucasci.UCASCI.fix_spin_"> <code class="sig-name descname">fix_spin_</code><em class="property"> = None</em><a class="headerlink" href="#pyscf.mcscf.ucasci.UCASCI.fix_spin_" title="Permalink to this definition">¶</a></dt> <dd></dd></dl> <dl class="py method"> <dt id="pyscf.mcscf.ucasci.UCASCI.get_h1cas"> <code class="sig-name descname">get_h1cas</code><span class="sig-paren">(</span><em class="sig-param"><span class="n">mo_coeff</span><span class="o">=</span><span class="default_value">None</span></em>, <em class="sig-param"><span class="n">ncas</span><span class="o">=</span><span class="default_value">None</span></em>, <em class="sig-param"><span class="n">ncore</span><span class="o">=</span><span class="default_value">None</span></em><span class="sig-paren">)</span><a class="headerlink" href="#pyscf.mcscf.ucasci.UCASCI.get_h1cas" title="Permalink to this definition">¶</a></dt> <dd><p>CAS sapce one-electron hamiltonian for UHF-CASCI or UHF-CASSCF</p> <dl class="simple"> <dt>Args:</dt><dd><p>casci : a U-CASSCF/U-CASCI object or UHF object</p> </dd> </dl> </dd></dl> <dl class="py method"> <dt id="pyscf.mcscf.ucasci.UCASCI.get_h1eff"> <code class="sig-name descname">get_h1eff</code><span class="sig-paren">(</span><em class="sig-param"><span class="n">mo_coeff</span><span class="o">=</span><span class="default_value">None</span></em>, <em class="sig-param"><span class="n">ncas</span><span class="o">=</span><span class="default_value">None</span></em>, <em class="sig-param"><span class="n">ncore</span><span class="o">=</span><span class="default_value">None</span></em><span class="sig-paren">)</span><a class="headerlink" href="#pyscf.mcscf.ucasci.UCASCI.get_h1eff" title="Permalink to this definition">¶</a></dt> <dd><p>CAS sapce one-electron hamiltonian for UHF-CASCI or UHF-CASSCF</p> <dl class="simple"> <dt>Args:</dt><dd><p>casci : a U-CASSCF/U-CASCI object or UHF object</p> </dd> </dl> </dd></dl> <dl class="py method"> <dt id="pyscf.mcscf.ucasci.UCASCI.get_h2cas"> <code class="sig-name descname">get_h2cas</code><span class="sig-paren">(</span><em class="sig-param"><span class="n">mo_coeff</span><span class="o">=</span><span class="default_value">None</span></em><span class="sig-paren">)</span><a class="headerlink" href="#pyscf.mcscf.ucasci.UCASCI.get_h2cas" title="Permalink to this definition">¶</a></dt> <dd><p>Compute the active space two-particle Hamiltonian.</p> <p>Note It is different to get_h2eff when df.approx_hessian is applied, in which get_h2eff function returns the DF integrals while get_h2cas returns the regular 2-electron integrals.</p> </dd></dl> <dl class="py method"> <dt id="pyscf.mcscf.ucasci.UCASCI.get_h2eff"> <code class="sig-name descname">get_h2eff</code><span class="sig-paren">(</span><em class="sig-param"><span class="n">mo_coeff</span><span class="o">=</span><span class="default_value">None</span></em><span class="sig-paren">)</span><a class="headerlink" href="#pyscf.mcscf.ucasci.UCASCI.get_h2eff" title="Permalink to this definition">¶</a></dt> <dd><p>Compute the active space two-particle Hamiltonian.</p> <p>Note It is different to get_h2cas when df.approx_hessian is applied. in which get_h2eff function returns the DF integrals while get_h2cas returns the regular 2-electron integrals.</p> </dd></dl> <dl class="py method"> <dt id="pyscf.mcscf.ucasci.UCASCI.get_hcore"> <code class="sig-name descname">get_hcore</code><span class="sig-paren">(</span><em class="sig-param"><span class="n">mol</span><span class="o">=</span><span class="default_value">None</span></em><span class="sig-paren">)</span><a class="headerlink" href="#pyscf.mcscf.ucasci.UCASCI.get_hcore" title="Permalink to this definition">¶</a></dt> <dd></dd></dl> <dl class="py method"> <dt id="pyscf.mcscf.ucasci.UCASCI.get_veff"> <code class="sig-name descname">get_veff</code><span class="sig-paren">(</span><em class="sig-param"><span class="n">mol</span><span class="o">=</span><span class="default_value">None</span></em>, <em class="sig-param"><span class="n">dm</span><span class="o">=</span><span class="default_value">None</span></em>, <em class="sig-param"><span class="n">hermi</span><span class="o">=</span><span class="default_value">1</span></em><span class="sig-paren">)</span><a class="headerlink" href="#pyscf.mcscf.ucasci.UCASCI.get_veff" title="Permalink to this definition">¶</a></dt> <dd><p>Hartree-Fock potential matrix for the given density matrix</p> <dl> <dt>Args:</dt><dd><p>mol : an instance of <code class="xref py py-class docutils literal notranslate"><span class="pre">Mole</span></code></p> <dl class="simple"> <dt>dm<span class="classifier">ndarray or list of ndarrays</span></dt><dd><p>A density matrix or a list of density matrices</p> </dd> </dl> </dd> <dt>Kwargs:</dt><dd><dl> <dt>dm_last<span class="classifier">ndarray or a list of ndarrays or 0</span></dt><dd><p>The density matrix baseline. If not 0, this function computes the increment of HF potential w.r.t. the reference HF potential matrix.</p> </dd> <dt>vhf_last<span class="classifier">ndarray or a list of ndarrays or 0</span></dt><dd><p>The reference HF potential matrix.</p> </dd> <dt>hermi<span class="classifier">int</span></dt><dd><p>Whether J, K matrix is hermitian</p> <div class="line-block"> <div class="line">0 : no hermitian or symmetric</div> <div class="line">1 : hermitian</div> <div class="line">2 : anti-hermitian</div> </div> </dd> <dt>vhfopt :</dt><dd><p>A class which holds precomputed quantities to optimize the computation of J, K matrices</p> </dd> </dl> </dd> <dt>Returns:</dt><dd><p>matrix Vhf = 2*J - K. Vhf can be a list matrices, corresponding to the input density matrices.</p> </dd> </dl> <p>Examples:</p> <div class="doctest highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">import</span> <span class="nn">numpy</span> <span class="gp">&gt;&gt;&gt; </span><span class="kn">from</span> <span class="nn">pyscf</span> <span class="kn">import</span> <span class="n">gto</span><span class="p">,</span> <span class="n">scf</span> <span class="gp">&gt;&gt;&gt; </span><span class="kn">from</span> <span class="nn">pyscf.scf</span> <span class="kn">import</span> <span class="n">_vhf</span> <span class="gp">&gt;&gt;&gt; </span><span class="n">mol</span> <span class="o">=</span> <span class="n">gto</span><span class="o">.</span><span class="n">M</span><span class="p">(</span><span class="n">atom</span><span class="o">=</span><span class="s1">&#39;H 0 0 0; H 0 0 1.1&#39;</span><span class="p">)</span> <span class="gp">&gt;&gt;&gt; </span><span class="n">dm0</span> <span class="o">=</span> <span class="n">numpy</span><span class="o">.</span><span class="n">random</span><span class="o">.</span><span class="n">random</span><span class="p">((</span><span class="n">mol</span><span class="o">.</span><span class="n">nao_nr</span><span class="p">(),</span><span class="n">mol</span><span class="o">.</span><span class="n">nao_nr</span><span class="p">()))</span> <span class="gp">&gt;&gt;&gt; </span><span class="n">vhf0</span> <span class="o">=</span> <span class="n">scf</span><span class="o">.</span><span class="n">hf</span><span class="o">.</span><span class="n">get_veff</span><span class="p">(</span><span class="n">mol</span><span class="p">,</span> <span class="n">dm0</span><span class="p">,</span> <span class="n">hermi</span><span class="o">=</span><span class="mi">0</span><span class="p">)</span> <span class="gp">&gt;&gt;&gt; </span><span class="n">dm1</span> <span class="o">=</span> <span class="n">numpy</span><span class="o">.</span><span class="n">random</span><span class="o">.</span><span class="n">random</span><span class="p">((</span><span class="n">mol</span><span class="o">.</span><span class="n">nao_nr</span><span class="p">(),</span><span class="n">mol</span><span class="o">.</span><span class="n">nao_nr</span><span class="p">()))</span> <span class="gp">&gt;&gt;&gt; </span><span class="n">vhf1</span> <span class="o">=</span> <span class="n">scf</span><span class="o">.</span><span class="n">hf</span><span class="o">.</span><span class="n">get_veff</span><span class="p">(</span><span class="n">mol</span><span class="p">,</span> <span class="n">dm1</span><span class="p">,</span> <span class="n">hermi</span><span class="o">=</span><span class="mi">0</span><span class="p">)</span> <span class="gp">&gt;&gt;&gt; </span><span class="n">vhf2</span> <span class="o">=</span> <span class="n">scf</span><span class="o">.</span><span class="n">hf</span><span class="o">.</span><span class="n">get_veff</span><span class="p">(</span><span class="n">mol</span><span class="p">,</span> <span class="n">dm1</span><span class="p">,</span> <span class="n">dm_last</span><span class="o">=</span><span class="n">dm0</span><span class="p">,</span> <span class="n">vhf_last</span><span class="o">=</span><span class="n">vhf0</span><span class="p">,</span> <span class="n">hermi</span><span class="o">=</span><span class="mi">0</span><span class="p">)</span> <span class="gp">&gt;&gt;&gt; </span><span class="n">numpy</span><span class="o">.</span><span class="n">allclose</span><span class="p">(</span><span class="n">vhf1</span><span class="p">,</span> <span class="n">vhf2</span><span class="p">)</span> <span class="go">True</span> </pre></div> </div> </dd></dl> <dl class="py method"> <dt id="pyscf.mcscf.ucasci.UCASCI.h1e_for_cas"> <code class="sig-name descname">h1e_for_cas</code><span class="sig-paren">(</span><em class="sig-param"><span class="n">mo_coeff</span><span class="o">=</span><span class="default_value">None</span></em>, <em class="sig-param"><span class="n">ncas</span><span class="o">=</span><span class="default_value">None</span></em>, <em class="sig-param"><span class="n">ncore</span><span class="o">=</span><span class="default_value">None</span></em><span class="sig-paren">)</span><a class="headerlink" href="#pyscf.mcscf.ucasci.UCASCI.h1e_for_cas" title="Permalink to this definition">¶</a></dt> <dd><p>CAS sapce one-electron hamiltonian for UHF-CASCI or UHF-CASSCF</p> <dl class="simple"> <dt>Args:</dt><dd><p>casci : a U-CASSCF/U-CASCI object or UHF object</p> </dd> </dl> </dd></dl> <dl class="py method"> <dt id="pyscf.mcscf.ucasci.UCASCI.kernel"> <code class="sig-name descname">kernel</code><span class="sig-paren">(</span><em class="sig-param"><span class="n">mo_coeff</span><span class="o">=</span><span class="default_value">None</span></em>, <em class="sig-param"><span class="n">ci0</span><span class="o">=</span><span class="default_value">None</span></em><span class="sig-paren">)</span><a class="headerlink" href="#pyscf.mcscf.ucasci.UCASCI.kernel" title="Permalink to this definition">¶</a></dt> <dd><dl class="simple"> <dt>Returns:</dt><dd><p>Five elements, they are total energy, active space CI energy, the active space FCI wavefunction coefficients or DMRG wavefunction ID, the MCSCF canonical orbital coefficients, the MCSCF canonical orbital coefficients.</p> </dd> </dl> <p>They are attributes of mcscf object, which can be accessed by .e_tot, .e_cas, .ci, .mo_coeff, .mo_energy</p> </dd></dl> <dl class="py method"> <dt id="pyscf.mcscf.ucasci.UCASCI.make_rdm1"> <code class="sig-name descname">make_rdm1</code><span class="sig-paren">(</span><em class="sig-param"><span class="n">mo_coeff</span><span class="o">=</span><span class="default_value">None</span></em>, <em class="sig-param"><span class="n">ci</span><span class="o">=</span><span class="default_value">None</span></em>, <em class="sig-param"><span class="n">ncas</span><span class="o">=</span><span class="default_value">None</span></em>, <em class="sig-param"><span class="n">nelecas</span><span class="o">=</span><span class="default_value">None</span></em>, <em class="sig-param"><span class="n">ncore</span><span class="o">=</span><span class="default_value">None</span></em>, <em class="sig-param"><span class="o">**</span><span class="n">kwargs</span></em><span class="sig-paren">)</span><a class="headerlink" href="#pyscf.mcscf.ucasci.UCASCI.make_rdm1" title="Permalink to this definition">¶</a></dt> <dd><p>One-particle density matrix in AO representation</p> </dd></dl> <dl class="py method"> <dt id="pyscf.mcscf.ucasci.UCASCI.make_rdm1s"> <code class="sig-name descname">make_rdm1s</code><span class="sig-paren">(</span><em class="sig-param"><span class="n">mo_coeff</span><span class="o">=</span><span class="default_value">None</span></em>, <em class="sig-param"><span class="n">ci</span><span class="o">=</span><span class="default_value">None</span></em>, <em class="sig-param"><span class="n">ncas</span><span class="o">=</span><span class="default_value">None</span></em>, <em class="sig-param"><span class="n">nelecas</span><span class="o">=</span><span class="default_value">None</span></em>, <em class="sig-param"><span class="n">ncore</span><span class="o">=</span><span class="default_value">None</span></em>, <em class="sig-param"><span class="o">**</span><span class="n">kwargs</span></em><span class="sig-paren">)</span><a class="headerlink" href="#pyscf.mcscf.ucasci.UCASCI.make_rdm1s" title="Permalink to this definition">¶</a></dt> <dd><p>One-particle density matrices for alpha and beta spin on AO basis</p> </dd></dl> <dl class="py method"> <dt id="pyscf.mcscf.ucasci.UCASCI.ncore"> <em class="property">property </em><code class="sig-name descname">ncore</code><a class="headerlink" href="#pyscf.mcscf.ucasci.UCASCI.ncore" title="Permalink to this definition">¶</a></dt> <dd></dd></dl> <dl class="py method"> <dt id="pyscf.mcscf.ucasci.UCASCI.sort_mo"> <code class="sig-name descname">sort_mo</code><span class="sig-paren">(</span><em class="sig-param"><span class="n">caslst</span></em>, <em class="sig-param"><span class="n">mo_coeff</span><span class="o">=</span><span class="default_value">None</span></em>, <em class="sig-param"><span class="n">base</span><span class="o">=</span><span class="default_value">1</span></em><span class="sig-paren">)</span><a class="headerlink" href="#pyscf.mcscf.ucasci.UCASCI.sort_mo" title="Permalink to this definition">¶</a></dt> <dd><p>Pick orbitals for CAS space</p> <dl> <dt>Args:</dt><dd><p>casscf : an <code class="xref py py-class docutils literal notranslate"><span class="pre">CASSCF</span></code> or <a class="reference internal" href="#pyscf.mcscf.ucasci.CASCI" title="pyscf.mcscf.ucasci.CASCI"><code class="xref py py-class docutils literal notranslate"><span class="pre">CASCI</span></code></a> object</p> <dl class="simple"> <dt>mo_coeff<span class="classifier">ndarray or a list of ndarray</span></dt><dd><p>Orbitals for CASSCF initial guess. In the UHF-CASSCF, it’s a list of two orbitals, for alpha and beta spin.</p> </dd> <dt>caslst<span class="classifier">list of int or nested list of int</span></dt><dd><p>A list of orbital indices to represent the CAS space. In the UHF-CASSCF, it’s consist of two lists, for alpha and beta spin.</p> </dd> </dl> </dd> <dt>Kwargs:</dt><dd><dl class="simple"> <dt>base<span class="classifier">int</span></dt><dd><p>0-based (C-style) or 1-based (Fortran-style) caslst</p> </dd> </dl> </dd> <dt>Returns:</dt><dd><p>An reoreded mo_coeff, which put the orbitals given by caslst in the CAS space</p> </dd> </dl> <p>Examples:</p> <div class="doctest highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">from</span> <span class="nn">pyscf</span> <span class="kn">import</span> <span class="n">gto</span><span class="p">,</span> <span class="n">scf</span><span class="p">,</span> <span class="n">mcscf</span> <span class="gp">&gt;&gt;&gt; </span><span class="n">mol</span> <span class="o">=</span> <span class="n">gto</span><span class="o">.</span><span class="n">M</span><span class="p">(</span><span class="n">atom</span><span class="o">=</span><span class="s1">&#39;N 0 0 0; N 0 0 1&#39;</span><span class="p">,</span> <span class="n">basis</span><span class="o">=</span><span class="s1">&#39;ccpvdz&#39;</span><span class="p">,</span> <span class="n">verbose</span><span class="o">=</span><span class="mi">0</span><span class="p">)</span> <span class="gp">&gt;&gt;&gt; </span><span class="n">mf</span> <span class="o">=</span> <span class="n">scf</span><span class="o">.</span><span class="n">RHF</span><span class="p">(</span><span class="n">mol</span><span class="p">)</span> <span class="gp">&gt;&gt;&gt; </span><span class="n">mf</span><span class="o">.</span><span class="n">scf</span><span class="p">()</span> <span class="gp">&gt;&gt;&gt; </span><span class="n">mc</span> <span class="o">=</span> <span class="n">mcscf</span><span class="o">.</span><span class="n">CASSCF</span><span class="p">(</span><span class="n">mf</span><span class="p">,</span> <span class="mi">4</span><span class="p">,</span> <span class="mi">4</span><span class="p">)</span> <span class="gp">&gt;&gt;&gt; </span><span class="n">cas_list</span> <span class="o">=</span> <span class="p">[</span><span class="mi">5</span><span class="p">,</span><span class="mi">6</span><span class="p">,</span><span class="mi">8</span><span class="p">,</span><span class="mi">9</span><span class="p">]</span> <span class="c1"># pi orbitals</span> <span class="gp">&gt;&gt;&gt; </span><span class="n">mo</span> <span class="o">=</span> <span class="n">mc</span><span class="o">.</span><span class="n">sort_mo</span><span class="p">(</span><span class="n">cas_list</span><span class="p">)</span> <span class="gp">&gt;&gt;&gt; </span><span class="n">mc</span><span class="o">.</span><span class="n">kernel</span><span class="p">(</span><span class="n">mo</span><span class="p">)[</span><span class="mi">0</span><span class="p">]</span> <span class="go">-109.007378939813691</span> </pre></div> </div> </dd></dl> <dl class="py method"> <dt id="pyscf.mcscf.ucasci.UCASCI.spin_square"> <code class="sig-name descname">spin_square</code><span class="sig-paren">(</span><em class="sig-param"><span class="n">fcivec</span><span class="o">=</span><span class="default_value">None</span></em>, <em class="sig-param"><span class="n">mo_coeff</span><span class="o">=</span><span class="default_value">None</span></em>, <em class="sig-param"><span class="n">ovlp</span><span class="o">=</span><span class="default_value">None</span></em><span class="sig-paren">)</span><a class="headerlink" href="#pyscf.mcscf.ucasci.UCASCI.spin_square" title="Permalink to this definition">¶</a></dt> <dd></dd></dl> </dd></dl> <dl class="py function"> <dt id="pyscf.mcscf.ucasci.extract_orbs"> <code class="sig-prename descclassname">pyscf.mcscf.ucasci.</code><code class="sig-name descname">extract_orbs</code><span class="sig-paren">(</span><em class="sig-param"><span class="n">mo_coeff</span></em>, <em class="sig-param"><span class="n">ncas</span></em>, <em class="sig-param"><span class="n">nelecas</span></em>, <em class="sig-param"><span class="n">ncore</span></em><span class="sig-paren">)</span><a class="headerlink" href="#pyscf.mcscf.ucasci.extract_orbs" title="Permalink to this definition">¶</a></dt> <dd></dd></dl> <dl class="py function"> <dt id="pyscf.mcscf.ucasci.h1e_for_cas"> <code class="sig-prename descclassname">pyscf.mcscf.ucasci.</code><code class="sig-name descname">h1e_for_cas</code><span class="sig-paren">(</span><em class="sig-param"><span class="n">casci</span></em>, <em class="sig-param"><span class="n">mo_coeff</span><span class="o">=</span><span class="default_value">None</span></em>, <em class="sig-param"><span class="n">ncas</span><span class="o">=</span><span class="default_value">None</span></em>, <em class="sig-param"><span class="n">ncore</span><span class="o">=</span><span class="default_value">None</span></em><span class="sig-paren">)</span><a class="headerlink" href="#pyscf.mcscf.ucasci.h1e_for_cas" title="Permalink to this definition">¶</a></dt> <dd><p>CAS sapce one-electron hamiltonian for UHF-CASCI or UHF-CASSCF</p> <dl class="simple"> <dt>Args:</dt><dd><p>casci : a U-CASSCF/U-CASCI object or UHF object</p> </dd> </dl> </dd></dl> <dl class="py function"> <dt id="pyscf.mcscf.ucasci.kernel"> <code class="sig-prename descclassname">pyscf.mcscf.ucasci.</code><code class="sig-name descname">kernel</code><span class="sig-paren">(</span><em class="sig-param"><span class="n">casci</span></em>, <em class="sig-param"><span class="n">mo_coeff</span><span class="o">=</span><span class="default_value">None</span></em>, <em class="sig-param"><span class="n">ci0</span><span class="o">=</span><span class="default_value">None</span></em>, <em class="sig-param"><span class="n">verbose</span><span class="o">=</span><span class="default_value">3</span></em><span class="sig-paren">)</span><a class="headerlink" href="#pyscf.mcscf.ucasci.kernel" title="Permalink to this definition">¶</a></dt> <dd><p>UHF-CASCI solver</p> </dd></dl> </div> <div class="section" id="module-pyscf.mcscf.umc1step"> <span id="pyscf-mcscf-umc1step-module"></span><h2>pyscf.mcscf.umc1step module<a class="headerlink" href="#module-pyscf.mcscf.umc1step" title="Permalink to this headline">¶</a></h2> <p>UCASSCF (CASSCF without spin-degeneracy between alpha and beta orbitals) 1-step optimization algorithm</p> <dl class="py attribute"> <dt id="pyscf.mcscf.umc1step.CASSCF"> <code class="sig-prename descclassname">pyscf.mcscf.umc1step.</code><code class="sig-name descname">CASSCF</code><a class="headerlink" href="#pyscf.mcscf.umc1step.CASSCF" title="Permalink to this definition">¶</a></dt> <dd><p>alias of <a class="reference internal" href="#pyscf.mcscf.umc1step.UCASSCF" title="pyscf.mcscf.umc1step.UCASSCF"><code class="xref py py-class docutils literal notranslate"><span class="pre">pyscf.mcscf.umc1step.UCASSCF</span></code></a></p> </dd></dl> <dl class="py class"> <dt id="pyscf.mcscf.umc1step.UCASSCF"> <em class="property">class </em><code class="sig-prename descclassname">pyscf.mcscf.umc1step.</code><code class="sig-name descname">UCASSCF</code><span class="sig-paren">(</span><em class="sig-param"><span class="n">mf_or_mol</span></em>, <em class="sig-param"><span class="n">ncas</span></em>, <em class="sig-param"><span class="n">nelecas</span></em>, <em class="sig-param"><span class="n">ncore</span><span class="o">=</span><span class="default_value">None</span></em>, <em class="sig-param"><span class="n">frozen</span><span class="o">=</span><span class="default_value">None</span></em><span class="sig-paren">)</span><a class="headerlink" href="#pyscf.mcscf.umc1step.UCASSCF" title="Permalink to this definition">¶</a></dt> <dd><p>Bases: <a class="reference internal" href="#pyscf.mcscf.ucasci.UCASCI" title="pyscf.mcscf.ucasci.UCASCI"><code class="xref py py-class docutils literal notranslate"><span class="pre">pyscf.mcscf.ucasci.UCASCI</span></code></a></p> <dl class="py attribute"> <dt id="pyscf.mcscf.umc1step.UCASSCF.ah_conv_tol"> <code class="sig-name descname">ah_conv_tol</code><em class="property"> = 1e-12</em><a class="headerlink" href="#pyscf.mcscf.umc1step.UCASSCF.ah_conv_tol" title="Permalink to this definition">¶</a></dt> <dd></dd></dl> <dl class="py attribute"> <dt id="pyscf.mcscf.umc1step.UCASSCF.ah_grad_trust_region"> <code class="sig-name descname">ah_grad_trust_region</code><em class="property"> = 3.0</em><a class="headerlink" href="#pyscf.mcscf.umc1step.UCASSCF.ah_grad_trust_region" title="Permalink to this definition">¶</a></dt> <dd></dd></dl> <dl class="py attribute"> <dt id="pyscf.mcscf.umc1step.UCASSCF.ah_level_shift"> <code class="sig-name descname">ah_level_shift</code><em class="property"> = 1e-08</em><a class="headerlink" href="#pyscf.mcscf.umc1step.UCASSCF.ah_level_shift" title="Permalink to this definition">¶</a></dt> <dd></dd></dl> <dl class="py attribute"> <dt id="pyscf.mcscf.umc1step.UCASSCF.ah_lindep"> <code class="sig-name descname">ah_lindep</code><em class="property"> = 1e-14</em><a class="headerlink" href="#pyscf.mcscf.umc1step.UCASSCF.ah_lindep" title="Permalink to this definition">¶</a></dt> <dd></dd></dl> <dl class="py attribute"> <dt id="pyscf.mcscf.umc1step.UCASSCF.ah_max_cycle"> <code class="sig-name descname">ah_max_cycle</code><em class="property"> = 30</em><a class="headerlink" href="#pyscf.mcscf.umc1step.UCASSCF.ah_max_cycle" title="Permalink to this definition">¶</a></dt> <dd></dd></dl> <dl class="py attribute"> <dt id="pyscf.mcscf.umc1step.UCASSCF.ah_start_cycle"> <code class="sig-name descname">ah_start_cycle</code><em class="property"> = 3</em><a class="headerlink" href="#pyscf.mcscf.umc1step.UCASSCF.ah_start_cycle" title="Permalink to this definition">¶</a></dt> <dd></dd></dl> <dl class="py attribute"> <dt id="pyscf.mcscf.umc1step.UCASSCF.ah_start_tol"> <code class="sig-name descname">ah_start_tol</code><em class="property"> = 2.5</em><a class="headerlink" href="#pyscf.mcscf.umc1step.UCASSCF.ah_start_tol" title="Permalink to this definition">¶</a></dt> <dd></dd></dl> <dl class="py method"> <dt id="pyscf.mcscf.umc1step.UCASSCF.ao2mo"> <code class="sig-name descname">ao2mo</code><span class="sig-paren">(</span><em class="sig-param"><span class="n">mo_coeff</span><span class="o">=</span><span class="default_value">None</span></em><span class="sig-paren">)</span><a class="headerlink" href="#pyscf.mcscf.umc1step.UCASSCF.ao2mo" title="Permalink to this definition">¶</a></dt> <dd><p>Compute the active space two-particle Hamiltonian.</p> </dd></dl> <dl class="py method"> <dt id="pyscf.mcscf.umc1step.UCASSCF.approx_cas_integral"> <code class="sig-name descname">approx_cas_integral</code><span class="sig-paren">(</span><em class="sig-param"><span class="n">mo</span></em>, <em class="sig-param"><span class="n">u</span></em>, <em class="sig-param"><span class="n">eris</span></em><span class="sig-paren">)</span><a class="headerlink" href="#pyscf.mcscf.umc1step.UCASSCF.approx_cas_integral" title="Permalink to this definition">¶</a></dt> <dd></dd></dl> <dl class="py method"> <dt id="pyscf.mcscf.umc1step.UCASSCF.casci"> <code class="sig-name descname">casci</code><span class="sig-paren">(</span><em class="sig-param"><span class="n">mo_coeff</span></em>, <em class="sig-param"><span class="n">ci0</span><span class="o">=</span><span class="default_value">None</span></em>, <em class="sig-param"><span class="n">eris</span><span class="o">=</span><span class="default_value">None</span></em>, <em class="sig-param"><span class="n">verbose</span><span class="o">=</span><span class="default_value">None</span></em>, <em class="sig-param"><span class="n">envs</span><span class="o">=</span><span class="default_value">None</span></em><span class="sig-paren">)</span><a class="headerlink" href="#pyscf.mcscf.umc1step.UCASSCF.casci" title="Permalink to this definition">¶</a></dt> <dd></dd></dl> <dl class="py attribute"> <dt id="pyscf.mcscf.umc1step.UCASSCF.chk_ci"> <code class="sig-name descname">chk_ci</code><em class="property"> = False</em><a class="headerlink" href="#pyscf.mcscf.umc1step.UCASSCF.chk_ci" title="Permalink to this definition">¶</a></dt> <dd></dd></dl> <dl class="py attribute"> <dt id="pyscf.mcscf.umc1step.UCASSCF.ci_response_space"> <code class="sig-name descname">ci_response_space</code><em class="property"> = 4</em><a class="headerlink" href="#pyscf.mcscf.umc1step.UCASSCF.ci_response_space" title="Permalink to this definition">¶</a></dt> <dd></dd></dl> <dl class="py attribute"> <dt id="pyscf.mcscf.umc1step.UCASSCF.conv_tol"> <code class="sig-name descname">conv_tol</code><em class="property"> = 1e-07</em><a class="headerlink" href="#pyscf.mcscf.umc1step.UCASSCF.conv_tol" title="Permalink to this definition">¶</a></dt> <dd></dd></dl> <dl class="py attribute"> <dt id="pyscf.mcscf.umc1step.UCASSCF.conv_tol_grad"> <code class="sig-name descname">conv_tol_grad</code><em class="property"> = None</em><a class="headerlink" href="#pyscf.mcscf.umc1step.UCASSCF.conv_tol_grad" title="Permalink to this definition">¶</a></dt> <dd></dd></dl> <dl class="py method"> <dt id="pyscf.mcscf.umc1step.UCASSCF.dump_chk"> <code class="sig-name descname">dump_chk</code><span class="sig-paren">(</span><em class="sig-param"><span class="n">envs</span></em><span class="sig-paren">)</span><a class="headerlink" href="#pyscf.mcscf.umc1step.UCASSCF.dump_chk" title="Permalink to this definition">¶</a></dt> <dd></dd></dl> <dl class="py method"> <dt id="pyscf.mcscf.umc1step.UCASSCF.dump_flags"> <code class="sig-name descname">dump_flags</code><span class="sig-paren">(</span><em class="sig-param"><span class="n">verbose</span><span class="o">=</span><span class="default_value">None</span></em><span class="sig-paren">)</span><a class="headerlink" href="#pyscf.mcscf.umc1step.UCASSCF.dump_flags" title="Permalink to this definition">¶</a></dt> <dd></dd></dl> <dl class="py method"> <dt id="pyscf.mcscf.umc1step.UCASSCF.gen_g_hop"> <code class="sig-name descname">gen_g_hop</code><span class="sig-paren">(</span><em class="sig-param"><span class="o">*</span><span class="n">args</span></em><span class="sig-paren">)</span><a class="headerlink" href="#pyscf.mcscf.umc1step.UCASSCF.gen_g_hop" title="Permalink to this definition">¶</a></dt> <dd></dd></dl> <dl class="py method"> <dt id="pyscf.mcscf.umc1step.UCASSCF.get_h2cas"> <code class="sig-name descname">get_h2cas</code><span class="sig-paren">(</span><em class="sig-param"><span class="n">mo_coeff</span><span class="o">=</span><span class="default_value">None</span></em><span class="sig-paren">)</span><a class="headerlink" href="#pyscf.mcscf.umc1step.UCASSCF.get_h2cas" title="Permalink to this definition">¶</a></dt> <dd><p>Compute the active space two-particle Hamiltonian.</p> <p>Note It is different to get_h2eff when df.approx_hessian is applied, in which get_h2eff function returns the DF integrals while get_h2cas returns the regular 2-electron integrals.</p> </dd></dl> <dl class="py method"> <dt id="pyscf.mcscf.umc1step.UCASSCF.get_h2eff"> <code class="sig-name descname">get_h2eff</code><span class="sig-paren">(</span><em class="sig-param"><span class="n">mo_coeff</span><span class="o">=</span><span class="default_value">None</span></em><span class="sig-paren">)</span><a class="headerlink" href="#pyscf.mcscf.umc1step.UCASSCF.get_h2eff" title="Permalink to this definition">¶</a></dt> <dd><p>Computing active space two-particle Hamiltonian.</p> </dd></dl> <dl class="py attribute"> <dt id="pyscf.mcscf.umc1step.UCASSCF.internal_rotation"> <code class="sig-name descname">internal_rotation</code><em class="property"> = False</em><a class="headerlink" href="#pyscf.mcscf.umc1step.UCASSCF.internal_rotation" title="Permalink to this definition">¶</a></dt> <dd></dd></dl> <dl class="py method"> <dt id="pyscf.mcscf.umc1step.UCASSCF.kernel"> <code class="sig-name descname">kernel</code><span class="sig-paren">(</span><em class="sig-param">mo_coeff=None</em>, <em class="sig-param">ci0=None</em>, <em class="sig-param">callback=None</em>, <em class="sig-param">_kern=&lt;function kernel&gt;</em><span class="sig-paren">)</span><a class="headerlink" href="#pyscf.mcscf.umc1step.UCASSCF.kernel" title="Permalink to this definition">¶</a></dt> <dd><dl class="simple"> <dt>Returns:</dt><dd><p>Five elements, they are total energy, active space CI energy, the active space FCI wavefunction coefficients or DMRG wavefunction ID, the MCSCF canonical orbital coefficients, the MCSCF canonical orbital coefficients.</p> </dd> </dl> <p>They are attributes of mcscf object, which can be accessed by .e_tot, .e_cas, .ci, .mo_coeff, .mo_energy</p> </dd></dl> <dl class="py attribute"> <dt id="pyscf.mcscf.umc1step.UCASSCF.kf_interval"> <code class="sig-name descname">kf_interval</code><em class="property"> = 4</em><a class="headerlink" href="#pyscf.mcscf.umc1step.UCASSCF.kf_interval" title="Permalink to this definition">¶</a></dt> <dd></dd></dl> <dl class="py attribute"> <dt id="pyscf.mcscf.umc1step.UCASSCF.kf_trust_region"> <code class="sig-name descname">kf_trust_region</code><em class="property"> = 3.0</em><a class="headerlink" href="#pyscf.mcscf.umc1step.UCASSCF.kf_trust_region" title="Permalink to this definition">¶</a></dt> <dd></dd></dl> <dl class="py attribute"> <dt id="pyscf.mcscf.umc1step.UCASSCF.max_cycle_macro"> <code class="sig-name descname">max_cycle_macro</code><em class="property"> = 50</em><a class="headerlink" href="#pyscf.mcscf.umc1step.UCASSCF.max_cycle_macro" title="Permalink to this definition">¶</a></dt> <dd></dd></dl> <dl class="py attribute"> <dt id="pyscf.mcscf.umc1step.UCASSCF.max_cycle_micro"> <code class="sig-name descname">max_cycle_micro</code><em class="property"> = 4</em><a class="headerlink" href="#pyscf.mcscf.umc1step.UCASSCF.max_cycle_micro" title="Permalink to this definition">¶</a></dt> <dd></dd></dl> <dl class="py method"> <dt id="pyscf.mcscf.umc1step.UCASSCF.max_orb_stepsize"> <em class="property">property </em><code class="sig-name descname">max_orb_stepsize</code><a class="headerlink" href="#pyscf.mcscf.umc1step.UCASSCF.max_orb_stepsize" title="Permalink to this definition">¶</a></dt> <dd></dd></dl> <dl class="py attribute"> <dt id="pyscf.mcscf.umc1step.UCASSCF.max_stepsize"> <code class="sig-name descname">max_stepsize</code><em class="property"> = 0.02</em><a class="headerlink" href="#pyscf.mcscf.umc1step.UCASSCF.max_stepsize" title="Permalink to this definition">¶</a></dt> <dd></dd></dl> <dl class="py method"> <dt id="pyscf.mcscf.umc1step.UCASSCF.max_stepsize_scheduler"> <code class="sig-name descname">max_stepsize_scheduler</code><span class="sig-paren">(</span><em class="sig-param"><span class="n">envs</span></em><span class="sig-paren">)</span><a class="headerlink" href="#pyscf.mcscf.umc1step.UCASSCF.max_stepsize_scheduler" title="Permalink to this definition">¶</a></dt> <dd></dd></dl> <dl class="py method"> <dt id="pyscf.mcscf.umc1step.UCASSCF.mc1step"> <code class="sig-name descname">mc1step</code><span class="sig-paren">(</span><em class="sig-param"><span class="n">mo_coeff</span><span class="o">=</span><span class="default_value">None</span></em>, <em class="sig-param"><span class="n">ci0</span><span class="o">=</span><span class="default_value">None</span></em>, <em class="sig-param"><span class="n">callback</span><span class="o">=</span><span class="default_value">None</span></em><span class="sig-paren">)</span><a class="headerlink" href="#pyscf.mcscf.umc1step.UCASSCF.mc1step" title="Permalink to this definition">¶</a></dt> <dd></dd></dl> <dl class="py method"> <dt id="pyscf.mcscf.umc1step.UCASSCF.mc2step"> <code class="sig-name descname">mc2step</code><span class="sig-paren">(</span><em class="sig-param"><span class="n">mo_coeff</span><span class="o">=</span><span class="default_value">None</span></em>, <em class="sig-param"><span class="n">ci0</span><span class="o">=</span><span class="default_value">None</span></em>, <em class="sig-param"><span class="n">callback</span><span class="o">=</span><span class="default_value">None</span></em><span class="sig-paren">)</span><a class="headerlink" href="#pyscf.mcscf.umc1step.UCASSCF.mc2step" title="Permalink to this definition">¶</a></dt> <dd></dd></dl> <dl class="py method"> <dt id="pyscf.mcscf.umc1step.UCASSCF.micro_cycle_scheduler"> <code class="sig-name descname">micro_cycle_scheduler</code><span class="sig-paren">(</span><em class="sig-param"><span class="n">envs</span></em><span class="sig-paren">)</span><a class="headerlink" href="#pyscf.mcscf.umc1step.UCASSCF.micro_cycle_scheduler" title="Permalink to this definition">¶</a></dt> <dd></dd></dl> <dl class="py attribute"> <dt id="pyscf.mcscf.umc1step.UCASSCF.natorb"> <code class="sig-name descname">natorb</code><em class="property"> = False</em><a class="headerlink" href="#pyscf.mcscf.umc1step.UCASSCF.natorb" title="Permalink to this definition">¶</a></dt> <dd></dd></dl> <dl class="py method"> <dt id="pyscf.mcscf.umc1step.UCASSCF.pack_uniq_var"> <code class="sig-name descname">pack_uniq_var</code><span class="sig-paren">(</span><em class="sig-param"><span class="n">mat</span></em><span class="sig-paren">)</span><a class="headerlink" href="#pyscf.mcscf.umc1step.UCASSCF.pack_uniq_var" title="Permalink to this definition">¶</a></dt> <dd></dd></dl> <dl class="py method"> <dt id="pyscf.mcscf.umc1step.UCASSCF.rotate_mo"> <code class="sig-name descname">rotate_mo</code><span class="sig-paren">(</span><em class="sig-param"><span class="n">mo</span></em>, <em class="sig-param"><span class="n">u</span></em>, <em class="sig-param"><span class="n">log</span><span class="o">=</span><span class="default_value">None</span></em><span class="sig-paren">)</span><a class="headerlink" href="#pyscf.mcscf.umc1step.UCASSCF.rotate_mo" title="Permalink to this definition">¶</a></dt> <dd><p>Rotate orbitals with the given unitary matrix</p> </dd></dl> <dl class="py method"> <dt id="pyscf.mcscf.umc1step.UCASSCF.rotate_orb_cc"> <code class="sig-name descname">rotate_orb_cc</code><span class="sig-paren">(</span><em class="sig-param"><span class="n">mo</span></em>, <em class="sig-param"><span class="n">fcivec</span></em>, <em class="sig-param"><span class="n">fcasdm1</span></em>, <em class="sig-param"><span class="n">fcasdm2</span></em>, <em class="sig-param"><span class="n">eris</span></em>, <em class="sig-param"><span class="n">x0_guess</span><span class="o">=</span><span class="default_value">None</span></em>, <em class="sig-param"><span class="n">conv_tol_grad</span><span class="o">=</span><span class="default_value">0.0001</span></em>, <em class="sig-param"><span class="n">max_stepsize</span><span class="o">=</span><span class="default_value">None</span></em>, <em class="sig-param"><span class="n">verbose</span><span class="o">=</span><span class="default_value">None</span></em><span class="sig-paren">)</span><a class="headerlink" href="#pyscf.mcscf.umc1step.UCASSCF.rotate_orb_cc" title="Permalink to this definition">¶</a></dt> <dd></dd></dl> <dl class="py method"> <dt id="pyscf.mcscf.umc1step.UCASSCF.solve_approx_ci"> <code class="sig-name descname">solve_approx_ci</code><span class="sig-paren">(</span><em class="sig-param"><span class="n">h1</span></em>, <em class="sig-param"><span class="n">h2</span></em>, <em class="sig-param"><span class="n">ci0</span></em>, <em class="sig-param"><span class="n">ecore</span></em>, <em class="sig-param"><span class="n">e_cas</span></em><span class="sig-paren">)</span><a class="headerlink" href="#pyscf.mcscf.umc1step.UCASSCF.solve_approx_ci" title="Permalink to this definition">¶</a></dt> <dd><p>Solve CI eigenvalue/response problem approximately</p> </dd></dl> <dl class="py method"> <dt id="pyscf.mcscf.umc1step.UCASSCF.uniq_var_indices"> <code class="sig-name descname">uniq_var_indices</code><span class="sig-paren">(</span><em class="sig-param"><span class="n">nmo</span></em>, <em class="sig-param"><span class="n">ncore</span></em>, <em class="sig-param"><span class="n">ncas</span></em>, <em class="sig-param"><span class="n">frozen</span></em><span class="sig-paren">)</span><a class="headerlink" href="#pyscf.mcscf.umc1step.UCASSCF.uniq_var_indices" title="Permalink to this definition">¶</a></dt> <dd></dd></dl> <dl class="py method"> <dt id="pyscf.mcscf.umc1step.UCASSCF.unpack_uniq_var"> <code class="sig-name descname">unpack_uniq_var</code><span class="sig-paren">(</span><em class="sig-param"><span class="n">v</span></em><span class="sig-paren">)</span><a class="headerlink" href="#pyscf.mcscf.umc1step.UCASSCF.unpack_uniq_var" title="Permalink to this definition">¶</a></dt> <dd></dd></dl> <dl class="py method"> <dt id="pyscf.mcscf.umc1step.UCASSCF.update_casdm"> <code class="sig-name descname">update_casdm</code><span class="sig-paren">(</span><em class="sig-param"><span class="n">mo</span></em>, <em class="sig-param"><span class="n">u</span></em>, <em class="sig-param"><span class="n">fcivec</span></em>, <em class="sig-param"><span class="n">e_cas</span></em>, <em class="sig-param"><span class="n">eris</span></em><span class="sig-paren">)</span><a class="headerlink" href="#pyscf.mcscf.umc1step.UCASSCF.update_casdm" title="Permalink to this definition">¶</a></dt> <dd></dd></dl> <dl class="py method"> <dt id="pyscf.mcscf.umc1step.UCASSCF.update_jk_in_ah"> <code class="sig-name descname">update_jk_in_ah</code><span class="sig-paren">(</span><em class="sig-param"><span class="n">mo</span></em>, <em class="sig-param"><span class="n">r</span></em>, <em class="sig-param"><span class="n">casdm1s</span></em>, <em class="sig-param"><span class="n">eris</span></em><span class="sig-paren">)</span><a class="headerlink" href="#pyscf.mcscf.umc1step.UCASSCF.update_jk_in_ah" title="Permalink to this definition">¶</a></dt> <dd></dd></dl> <dl class="py method"> <dt id="pyscf.mcscf.umc1step.UCASSCF.update_rotate_matrix"> <code class="sig-name descname">update_rotate_matrix</code><span class="sig-paren">(</span><em class="sig-param"><span class="n">dx</span></em>, <em class="sig-param"><span class="n">u0</span><span class="o">=</span><span class="default_value">1</span></em><span class="sig-paren">)</span><a class="headerlink" href="#pyscf.mcscf.umc1step.UCASSCF.update_rotate_matrix" title="Permalink to this definition">¶</a></dt> <dd></dd></dl> <dl class="py attribute"> <dt id="pyscf.mcscf.umc1step.UCASSCF.with_dep4"> <code class="sig-name descname">with_dep4</code><em class="property"> = False</em><a class="headerlink" href="#pyscf.mcscf.umc1step.UCASSCF.with_dep4" title="Permalink to this definition">¶</a></dt> <dd></dd></dl> </dd></dl> <dl class="py function"> <dt id="pyscf.mcscf.umc1step.gen_g_hop"> <code class="sig-prename descclassname">pyscf.mcscf.umc1step.</code><code class="sig-name descname">gen_g_hop</code><span class="sig-paren">(</span><em class="sig-param"><span class="n">casscf</span></em>, <em class="sig-param"><span class="n">mo</span></em>, <em class="sig-param"><span class="n">u</span></em>, <em class="sig-param"><span class="n">casdm1s</span></em>, <em class="sig-param"><span class="n">casdm2s</span></em>, <em class="sig-param"><span class="n">eris</span></em><span class="sig-paren">)</span><a class="headerlink" href="#pyscf.mcscf.umc1step.gen_g_hop" title="Permalink to this definition">¶</a></dt> <dd></dd></dl> <dl class="py function"> <dt id="pyscf.mcscf.umc1step.kernel"> <code class="sig-prename descclassname">pyscf.mcscf.umc1step.</code><code class="sig-name descname">kernel</code><span class="sig-paren">(</span><em class="sig-param"><span class="n">casscf</span></em>, <em class="sig-param"><span class="n">mo_coeff</span></em>, <em class="sig-param"><span class="n">tol</span><span class="o">=</span><span class="default_value">1e-07</span></em>, <em class="sig-param"><span class="n">conv_tol_grad</span><span class="o">=</span><span class="default_value">None</span></em>, <em class="sig-param"><span class="n">ci0</span><span class="o">=</span><span class="default_value">None</span></em>, <em class="sig-param"><span class="n">callback</span><span class="o">=</span><span class="default_value">None</span></em>, <em class="sig-param"><span class="n">verbose</span><span class="o">=</span><span class="default_value">None</span></em>, <em class="sig-param"><span class="n">dump_chk</span><span class="o">=</span><span class="default_value">True</span></em><span class="sig-paren">)</span><a class="headerlink" href="#pyscf.mcscf.umc1step.kernel" title="Permalink to this definition">¶</a></dt> <dd></dd></dl> </div> <div class="section" id="module-pyscf.mcscf.umc2step"> <span id="pyscf-mcscf-umc2step-module"></span><h2>pyscf.mcscf.umc2step module<a class="headerlink" href="#module-pyscf.mcscf.umc2step" title="Permalink to this headline">¶</a></h2> <p>UCASSCF (CASSCF without spin-degeneracy between alpha and beta orbitals) 2-step optimization algorithm</p> <dl class="py function"> <dt id="pyscf.mcscf.umc2step.kernel"> <code class="sig-prename descclassname">pyscf.mcscf.umc2step.</code><code class="sig-name descname">kernel</code><span class="sig-paren">(</span><em class="sig-param"><span class="n">casscf</span></em>, <em class="sig-param"><span class="n">mo_coeff</span></em>, <em class="sig-param"><span class="n">tol</span><span class="o">=</span><span class="default_value">1e-07</span></em>, <em class="sig-param"><span class="n">conv_tol_grad</span><span class="o">=</span><span class="default_value">None</span></em>, <em class="sig-param"><span class="n">ci0</span><span class="o">=</span><span class="default_value">None</span></em>, <em class="sig-param"><span class="n">callback</span><span class="o">=</span><span class="default_value">None</span></em>, <em class="sig-param"><span class="n">verbose</span><span class="o">=</span><span class="default_value">None</span></em>, <em class="sig-param"><span class="n">dump_chk</span><span class="o">=</span><span class="default_value">True</span></em><span class="sig-paren">)</span><a class="headerlink" href="#pyscf.mcscf.umc2step.kernel" title="Permalink to this definition">¶</a></dt> <dd></dd></dl> </div> <div class="section" id="module-pyscf.mcscf.umc_ao2mo"> <span id="pyscf-mcscf-umc-ao2mo-module"></span><h2>pyscf.mcscf.umc_ao2mo module<a class="headerlink" href="#module-pyscf.mcscf.umc_ao2mo" title="Permalink to this headline">¶</a></h2> <p>MO integrals for UCASSCF methods</p> <dl class="py function"> <dt id="pyscf.mcscf.umc_ao2mo.trans_e1_incore"> <code class="sig-prename descclassname">pyscf.mcscf.umc_ao2mo.</code><code class="sig-name descname">trans_e1_incore</code><span class="sig-paren">(</span><em class="sig-param"><span class="n">eri_ao</span></em>, <em class="sig-param"><span class="n">mo</span></em>, <em class="sig-param"><span class="n">ncore</span></em>, <em class="sig-param"><span class="n">ncas</span></em><span class="sig-paren">)</span><a class="headerlink" href="#pyscf.mcscf.umc_ao2mo.trans_e1_incore" title="Permalink to this definition">¶</a></dt> <dd></dd></dl> <dl class="py function"> <dt id="pyscf.mcscf.umc_ao2mo.trans_e1_outcore"> <code class="sig-prename descclassname">pyscf.mcscf.umc_ao2mo.</code><code class="sig-name descname">trans_e1_outcore</code><span class="sig-paren">(</span><em class="sig-param"><span class="n">mol</span></em>, <em class="sig-param"><span class="n">mo</span></em>, <em class="sig-param"><span class="n">ncore</span></em>, <em class="sig-param"><span class="n">ncas</span></em>, <em class="sig-param"><span class="n">max_memory</span><span class="o">=</span><span class="default_value">None</span></em>, <em class="sig-param"><span class="n">ioblk_size</span><span class="o">=</span><span class="default_value">512</span></em>, <em class="sig-param"><span class="n">verbose</span><span class="o">=</span><span class="default_value">2</span></em><span class="sig-paren">)</span><a class="headerlink" href="#pyscf.mcscf.umc_ao2mo.trans_e1_outcore" title="Permalink to this definition">¶</a></dt> <dd></dd></dl> </div> <div class="section" id="module-pyscf.mcscf"> <span id="module-contents"></span><h2>Module contents<a class="headerlink" href="#module-pyscf.mcscf" title="Permalink to this headline">¶</a></h2> <p>CASCI and CASSCF</p> <p>When using results of this code for publications, please cite the following paper: “A general second order complete active space self-consistent-field solver for large-scale systems”, <NAME>, <NAME>, and <NAME>, Chem. Phys. Lett. 683, 291 (2017).</p> <p>Simple usage:</p> <div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">from</span> <span class="nn">pyscf</span> <span class="kn">import</span> <span class="n">gto</span><span class="p">,</span> <span class="n">scf</span><span class="p">,</span> <span class="n">mcscf</span> <span class="gp">&gt;&gt;&gt; </span><span class="n">mol</span> <span class="o">=</span> <span class="n">gto</span><span class="o">.</span><span class="n">M</span><span class="p">(</span><span class="n">atom</span><span class="o">=</span><span class="s1">&#39;N 0 0 0; N 0 0 1&#39;</span><span class="p">,</span> <span class="n">basis</span><span class="o">=</span><span class="s1">&#39;ccpvdz&#39;</span><span class="p">,</span> <span class="n">verbose</span><span class="o">=</span><span class="mi">0</span><span class="p">)</span> <span class="gp">&gt;&gt;&gt; </span><span class="n">mf</span> <span class="o">=</span> <span class="n">scf</span><span class="o">.</span><span class="n">RHF</span><span class="p">(</span><span class="n">mol</span><span class="p">)</span><span class="o">.</span><span class="n">run</span><span class="p">()</span> <span class="gp">&gt;&gt;&gt; </span><span class="n">mc</span> <span class="o">=</span> <span class="n">mcscf</span><span class="o">.</span><span class="n">CASCI</span><span class="p">(</span><span class="n">mf</span><span class="p">,</span> <span class="mi">6</span><span class="p">,</span> <span class="mi">6</span><span class="p">)</span> <span class="gp">&gt;&gt;&gt; </span><span class="n">mc</span><span class="o">.</span><span class="n">kernel</span><span class="p">()[</span><span class="mi">0</span><span class="p">]</span> <span class="go">-108.980200816243354</span> <span class="gp">&gt;&gt;&gt; </span><span class="n">mc</span> <span class="o">=</span> <span class="n">mcscf</span><span class="o">.</span><span class="n">CASSCF</span><span class="p">(</span><span class="n">mf</span><span class="p">,</span> <span class="mi">6</span><span class="p">,</span> <span class="mi">6</span><span class="p">)</span> <span class="gp">&gt;&gt;&gt; </span><span class="n">mc</span><span class="o">.</span><span class="n">kernel</span><span class="p">()[</span><span class="mi">0</span><span class="p">]</span> <span class="go">-109.044401882238134</span> <span class="gp">&gt;&gt;&gt; </span><span class="n">mc</span> <span class="o">=</span> <span class="n">mcscf</span><span class="o">.</span><span class="n">CASSCF</span><span class="p">(</span><span class="n">mf</span><span class="p">,</span> <span class="mi">4</span><span class="p">,</span> <span class="mi">4</span><span class="p">)</span> <span class="gp">&gt;&gt;&gt; </span><span class="n">cas_list</span> <span class="o">=</span> <span class="p">[</span><span class="mi">5</span><span class="p">,</span><span class="mi">6</span><span class="p">,</span><span class="mi">8</span><span class="p">,</span><span class="mi">9</span><span class="p">]</span> <span class="c1"># pick orbitals for CAS space, 1-based indices</span> <span class="gp">&gt;&gt;&gt; </span><span class="n">mo</span> <span class="o">=</span> <span class="n">mcscf</span><span class="o">.</span><span class="n">sort_mo</span><span class="p">(</span><span class="n">mc</span><span class="p">,</span> <span class="n">mf</span><span class="o">.</span><span class="n">mo_coeff</span><span class="p">,</span> <span class="n">cas_list</span><span class="p">)</span> <span class="gp">&gt;&gt;&gt; </span><span class="n">mc</span><span class="o">.</span><span class="n">kernel</span><span class="p">(</span><span class="n">mo</span><span class="p">)[</span><span class="mi">0</span><span class="p">]</span> <span class="go">-109.007378939813691</span> </pre></div> </div> <p><code class="xref py py-func docutils literal notranslate"><span class="pre">mcscf.CASSCF()</span></code> or <code class="xref py py-func docutils literal notranslate"><span class="pre">mcscf.CASCI()</span></code> returns a proper instance of CASSCF/CASCI class. There are some parameters to control the CASSCF/CASCI method.</p> <blockquote> <div><dl> <dt>verbose<span class="classifier">int</span></dt><dd><p>Print level. Default value equals to <code class="xref py py-class docutils literal notranslate"><span class="pre">Mole.verbose</span></code>.</p> </dd> <dt>max_memory<span class="classifier">float or int</span></dt><dd><p>Allowed memory in MB. Default value equals to <code class="xref py py-class docutils literal notranslate"><span class="pre">Mole.max_memory</span></code>.</p> </dd> <dt>ncas<span class="classifier">int</span></dt><dd><p>Active space size.</p> </dd> <dt>nelecas<span class="classifier">tuple of int</span></dt><dd><p>Active (nelec_alpha, nelec_beta)</p> </dd> <dt>ncore<span class="classifier">int or tuple of int</span></dt><dd><p>Core electron number. In UHF-CASSCF, it’s a tuple to indicate the different core eletron numbers.</p> </dd> <dt>natorb<span class="classifier">bool</span></dt><dd><p>Whether to restore the natural orbital during CASSCF optimization. Default is not.</p> </dd> <dt>canonicalization<span class="classifier">bool</span></dt><dd><p>Whether to canonicalize orbitals. Default is True.</p> </dd> <dt>fcisolver<span class="classifier">an instance of <code class="xref py py-class docutils literal notranslate"><span class="pre">FCISolver</span></code></span></dt><dd><p>The pyscf.fci module provides several FCISolver for different scenario. Generally, fci.direct_spin1.FCISolver can be used for all RHF-CASSCF. However, a proper FCISolver can provide better performance and better numerical stability. One can either use <code class="xref py py-func docutils literal notranslate"><span class="pre">fci.solver()</span></code> function to pick the FCISolver by the program or manually assigen the FCISolver to this attribute, e.g.</p> <div class="doctest highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">from</span> <span class="nn">pyscf</span> <span class="kn">import</span> <span class="n">fci</span> <span class="gp">&gt;&gt;&gt; </span><span class="n">mc</span> <span class="o">=</span> <span class="n">mcscf</span><span class="o">.</span><span class="n">CASSCF</span><span class="p">(</span><span class="n">mf</span><span class="p">,</span> <span class="mi">4</span><span class="p">,</span> <span class="mi">4</span><span class="p">)</span> <span class="gp">&gt;&gt;&gt; </span><span class="n">mc</span><span class="o">.</span><span class="n">fcisolver</span> <span class="o">=</span> <span class="n">fci</span><span class="o">.</span><span class="n">solver</span><span class="p">(</span><span class="n">mol</span><span class="p">,</span> <span class="n">singlet</span><span class="o">=</span><span class="kc">True</span><span class="p">)</span> <span class="gp">&gt;&gt;&gt; </span><span class="n">mc</span><span class="o">.</span><span class="n">fcisolver</span> <span class="o">=</span> <span class="n">fci</span><span class="o">.</span><span class="n">direct_spin1</span><span class="o">.</span><span class="n">FCISolver</span><span class="p">(</span><span class="n">mol</span><span class="p">)</span> </pre></div> </div> <p>You can control FCISolver by setting e.g.:</p> <div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">mc</span><span class="o">.</span><span class="n">fcisolver</span><span class="o">.</span><span class="n">max_cycle</span> <span class="o">=</span> <span class="mi">30</span> <span class="gp">&gt;&gt;&gt; </span><span class="n">mc</span><span class="o">.</span><span class="n">fcisolver</span><span class="o">.</span><span class="n">conv_tol</span> <span class="o">=</span> <span class="mf">1e-7</span> </pre></div> </div> <p>For more details of the parameter for FCISolver, See <code class="xref py py-mod docutils literal notranslate"><span class="pre">fci</span></code>.</p> <p>By replacing this fcisolver, you can easily use the CASCI/CASSCF solver with other FCI replacements, such as DMRG, QMC. See <code class="xref py py-mod docutils literal notranslate"><span class="pre">dmrgscf</span></code> and <code class="xref py py-mod docutils literal notranslate"><span class="pre">fciqmcscf</span></code>.</p> </dd> </dl> </div></blockquote> <p>The Following attributes are used for CASSCF</p> <blockquote> <div><dl> <dt>conv_tol<span class="classifier">float</span></dt><dd><p>Converge threshold. Default is 1e-7</p> </dd> <dt>conv_tol_grad<span class="classifier">float</span></dt><dd><p>Converge threshold for CI gradients and orbital rotation gradients. Default is 1e-4</p> </dd> <dt>max_stepsize<span class="classifier">float</span></dt><dd><p>The step size for orbital rotation. Small step size is prefered. Default is 0.03. (NOTE although the default step size is small enough for many systems, it happens that the orbital optimizor crosses the barriar of local minimum and converge to the neighbour solution, e.g. the CAS(4,4) for C2H4 in the test files. In these systems, adjusting max_stepsize, max_ci_stepsize and max_cycle_micro, max_cycle_micro_inner and ah_start_tol may be helpful)</p> <div class="doctest highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">mc</span> <span class="o">=</span> <span class="n">mcscf</span><span class="o">.</span><span class="n">CASSCF</span><span class="p">(</span><span class="n">mf</span><span class="p">,</span> <span class="mi">6</span><span class="p">,</span> <span class="mi">6</span><span class="p">)</span> <span class="gp">&gt;&gt;&gt; </span><span class="n">mc</span><span class="o">.</span><span class="n">max_stepsize</span> <span class="o">=</span> <span class="o">.</span><span class="mi">01</span> <span class="gp">&gt;&gt;&gt; </span><span class="n">mc</span><span class="o">.</span><span class="n">max_cycle_micro</span> <span class="o">=</span> <span class="mi">1</span> <span class="gp">&gt;&gt;&gt; </span><span class="n">mc</span><span class="o">.</span><span class="n">max_cycle_macro</span> <span class="o">=</span> <span class="mi">100</span> <span class="gp">&gt;&gt;&gt; </span><span class="n">mc</span><span class="o">.</span><span class="n">max_cycle_micro_inner</span> <span class="o">=</span> <span class="mi">1</span> <span class="gp">&gt;&gt;&gt; </span><span class="n">mc</span><span class="o">.</span><span class="n">ah_start_tol</span> <span class="o">=</span> <span class="mf">1e-6</span> </pre></div> </div> </dd> <dt>max_ci_stepsize<span class="classifier">float</span></dt><dd><p>The max size for approximate CI updates. The approximate updates are used in 1-step algorithm, to estimate the change of CI wavefunction wrt the orbital rotation. Small step size is prefered. Default is 0.01.</p> </dd> <dt>max_cycle_macro<span class="classifier">int</span></dt><dd><p>Max number of macro iterations. Default is 50.</p> </dd> <dt>max_cycle_micro<span class="classifier">int</span></dt><dd><p>Max number of micro iterations in each macro iteration. Depending on systems, increasing this value might reduce the total macro iterations. Generally, 2 - 3 steps should be enough. Default is 2.</p> </dd> <dt>max_cycle_micro_inner<span class="classifier">int</span></dt><dd><p>Max number of steps for the orbital rotations allowed for the augmented hessian solver. It can affect the actual size of orbital rotation. Even with a small max_stepsize, a few max_cycle_micro_inner can accumulate the rotation and leads to a significant change of the CAS space. Depending on systems, increasing this value migh reduce the total number of macro iterations. The value between 2 - 8 is preferred. Default is 4.</p> </dd> <dt>frozen<span class="classifier">int or list</span></dt><dd><p>If integer is given, the inner-most orbitals are excluded from optimization. Given the orbital indices (0-based) in a list, any doubly occupied core orbitals, active orbitals and external orbitals can be frozen.</p> </dd> <dt>ah_level_shift<span class="classifier">float, for AH solver.</span></dt><dd><p>Level shift for the Davidson diagonalization in AH solver. Default is 0.</p> </dd> <dt>ah_conv_tol<span class="classifier">float, for AH solver.</span></dt><dd><p>converge threshold for Davidson diagonalization in AH solver. Default is 1e-8.</p> </dd> <dt>ah_max_cycle<span class="classifier">float, for AH solver.</span></dt><dd><p>Max number of iterations allowd in AH solver. Default is 20.</p> </dd> <dt>ah_lindep<span class="classifier">float, for AH solver.</span></dt><dd><p>Linear dependence threshold for AH solver. Default is 1e-16.</p> </dd> <dt>ah_start_tol<span class="classifier">flat, for AH solver.</span></dt><dd><p>In AH solver, the orbital rotation is started without completely solving the AH problem. This value is to control the start point. Default is 1e-4.</p> </dd> <dt>ah_start_cycle<span class="classifier">int, for AH solver.</span></dt><dd><p>In AH solver, the orbital rotation is started without completely solving the AH problem. This value is to control the start point. Default is 3.</p> <p><code class="docutils literal notranslate"><span class="pre">ah_conv_tol</span></code>, <code class="docutils literal notranslate"><span class="pre">ah_max_cycle</span></code>, <code class="docutils literal notranslate"><span class="pre">ah_lindep</span></code>, <code class="docutils literal notranslate"><span class="pre">ah_start_tol</span></code> and <code class="docutils literal notranslate"><span class="pre">ah_start_cycle</span></code> can affect the accuracy and performance of CASSCF solver. Lower <code class="docutils literal notranslate"><span class="pre">ah_conv_tol</span></code> and <code class="docutils literal notranslate"><span class="pre">ah_lindep</span></code> can improve the accuracy of CASSCF optimization, but slow down the performance.</p> <div class="doctest highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">from</span> <span class="nn">pyscf</span> <span class="kn">import</span> <span class="n">gto</span><span class="p">,</span> <span class="n">scf</span><span class="p">,</span> <span class="n">mcscf</span> <span class="gp">&gt;&gt;&gt; </span><span class="n">mol</span> <span class="o">=</span> <span class="n">gto</span><span class="o">.</span><span class="n">M</span><span class="p">(</span><span class="n">atom</span><span class="o">=</span><span class="s1">&#39;N 0 0 0; N 0 0 1&#39;</span><span class="p">,</span> <span class="n">basis</span><span class="o">=</span><span class="s1">&#39;ccpvdz&#39;</span><span class="p">,</span> <span class="n">verbose</span><span class="o">=</span><span class="mi">0</span><span class="p">)</span> <span class="gp">&gt;&gt;&gt; </span><span class="n">mf</span> <span class="o">=</span> <span class="n">scf</span><span class="o">.</span><span class="n">UHF</span><span class="p">(</span><span class="n">mol</span><span class="p">)</span> <span class="gp">&gt;&gt;&gt; </span><span class="n">mf</span><span class="o">.</span><span class="n">scf</span><span class="p">()</span> <span class="gp">&gt;&gt;&gt; </span><span class="n">mc</span> <span class="o">=</span> <span class="n">mcscf</span><span class="o">.</span><span class="n">CASSCF</span><span class="p">(</span><span class="n">mf</span><span class="p">,</span> <span class="mi">6</span><span class="p">,</span> <span class="mi">6</span><span class="p">)</span> <span class="gp">&gt;&gt;&gt; </span><span class="n">mc</span><span class="o">.</span><span class="n">conv_tol</span> <span class="o">=</span> <span class="mf">1e-10</span> <span class="gp">&gt;&gt;&gt; </span><span class="n">mc</span><span class="o">.</span><span class="n">ah_conv_tol</span> <span class="o">=</span> <span class="mf">1e-5</span> <span class="gp">&gt;&gt;&gt; </span><span class="n">mc</span><span class="o">.</span><span class="n">kernel</span><span class="p">()</span> <span class="go">-109.044401898486001</span> <span class="gp">&gt;&gt;&gt; </span><span class="n">mc</span><span class="o">.</span><span class="n">ah_conv_tol</span> <span class="o">=</span> <span class="mf">1e-10</span> <span class="gp">&gt;&gt;&gt; </span><span class="n">mc</span><span class="o">.</span><span class="n">kernel</span><span class="p">()</span> <span class="go">-109.044401887945668</span> </pre></div> </div> </dd> <dt>chkfile<span class="classifier">str</span></dt><dd><p>Checkpoint file to save the intermediate orbitals during the CASSCF optimization. Default is the checkpoint file of mean field object.</p> </dd> </dl> </div></blockquote> <p>Saved results</p> <blockquote> <div><dl class="simple"> <dt>e_tot<span class="classifier">float</span></dt><dd><p>Total MCSCF energy (electronic energy plus nuclear repulsion)</p> </dd> <dt>ci<span class="classifier">ndarray</span></dt><dd><p>CAS space FCI coefficients</p> </dd> <dt>converged<span class="classifier">bool, for CASSCF only</span></dt><dd><p>It indicates CASSCF optimization converged or not.</p> </dd> <dt>mo_energy: ndarray,</dt><dd><p>Diagonal elements of general Fock matrix</p> </dd> <dt>mo_coeff<span class="classifier">ndarray, for CASSCF only</span></dt><dd><p>Optimized CASSCF orbitals coefficients Note the orbitals are NOT natural orbitals by default. There are two inbuilt methods to convert the mo_coeff to natural orbitals. 1. Set .natorb attribute. It can be used before calculation. 2. call .cas_natorb_ method after the calculation to in-place convert the orbitals</p> </dd> </dl> </div></blockquote> <dl class="py function"> <dt id="pyscf.mcscf.CASCI"> <code class="sig-prename descclassname">pyscf.mcscf.</code><code class="sig-name descname">CASCI</code><span class="sig-paren">(</span><em class="sig-param"><span class="n">mf_or_mol</span></em>, <em class="sig-param"><span class="n">ncas</span></em>, <em class="sig-param"><span class="n">nelecas</span></em>, <em class="sig-param"><span class="n">ncore</span><span class="o">=</span><span class="default_value">None</span></em><span class="sig-paren">)</span><a class="headerlink" href="#pyscf.mcscf.CASCI" title="Permalink to this definition">¶</a></dt> <dd></dd></dl> <dl class="py function"> <dt id="pyscf.mcscf.CASSCF"> <code class="sig-prename descclassname">pyscf.mcscf.</code><code class="sig-name descname">CASSCF</code><span class="sig-paren">(</span><em class="sig-param"><span class="n">mf_or_mol</span></em>, <em class="sig-param"><span class="n">ncas</span></em>, <em class="sig-param"><span class="n">nelecas</span></em>, <em class="sig-param"><span class="n">ncore</span><span class="o">=</span><span class="default_value">None</span></em>, <em class="sig-param"><span class="n">frozen</span><span class="o">=</span><span class="default_value">None</span></em><span class="sig-paren">)</span><a class="headerlink" href="#pyscf.mcscf.CASSCF" title="Permalink to this definition">¶</a></dt> <dd></dd></dl> <dl class="py function"> <dt id="pyscf.mcscf.DFCASCI"> <code class="sig-prename descclassname">pyscf.mcscf.</code><code class="sig-name descname">DFCASCI</code><span class="sig-paren">(</span><em class="sig-param"><span class="n">mf_or_mol</span></em>, <em class="sig-param"><span class="n">ncas</span></em>, <em class="sig-param"><span class="n">nelecas</span></em>, <em class="sig-param"><span class="n">auxbasis</span><span class="o">=</span><span class="default_value">None</span></em>, <em class="sig-param"><span class="n">ncore</span><span class="o">=</span><span class="default_value">None</span></em><span class="sig-paren">)</span><a class="headerlink" href="#pyscf.mcscf.DFCASCI" title="Permalink to this definition">¶</a></dt> <dd></dd></dl> <dl class="py function"> <dt id="pyscf.mcscf.DFCASSCF"> <code class="sig-prename descclassname">pyscf.mcscf.</code><code class="sig-name descname">DFCASSCF</code><span class="sig-paren">(</span><em class="sig-param"><span class="n">mf_or_mol</span></em>, <em class="sig-param"><span class="n">ncas</span></em>, <em class="sig-param"><span class="n">nelecas</span></em>, <em class="sig-param"><span class="n">auxbasis</span><span class="o">=</span><span class="default_value">None</span></em>, <em class="sig-param"><span class="n">ncore</span><span class="o">=</span><span class="default_value">None</span></em>, <em class="sig-param"><span class="n">frozen</span><span class="o">=</span><span class="default_value">None</span></em><span class="sig-paren">)</span><a class="headerlink" href="#pyscf.mcscf.DFCASSCF" title="Permalink to this definition">¶</a></dt> <dd></dd></dl> <dl class="py function"> <dt id="pyscf.mcscf.RCASCI"> <code class="sig-prename descclassname">pyscf.mcscf.</code><code class="sig-name descname">RCASCI</code><span class="sig-paren">(</span><em class="sig-param"><span class="n">mf_or_mol</span></em>, <em class="sig-param"><span class="n">ncas</span></em>, <em class="sig-param"><span class="n">nelecas</span></em>, <em class="sig-param"><span class="n">ncore</span><span class="o">=</span><span class="default_value">None</span></em><span class="sig-paren">)</span><a class="headerlink" href="#pyscf.mcscf.RCASCI" title="Permalink to this definition">¶</a></dt> <dd></dd></dl> <dl class="py function"> <dt id="pyscf.mcscf.RCASSCF"> <code class="sig-prename descclassname">pyscf.mcscf.</code><code class="sig-name descname">RCASSCF</code><span class="sig-paren">(</span><em class="sig-param"><span class="n">mf_or_mol</span></em>, <em class="sig-param"><span class="n">ncas</span></em>, <em class="sig-param"><span class="n">nelecas</span></em>, <em class="sig-param"><span class="n">ncore</span><span class="o">=</span><span class="default_value">None</span></em>, <em class="sig-param"><span class="n">frozen</span><span class="o">=</span><span class="default_value">None</span></em><span class="sig-paren">)</span><a class="headerlink" href="#pyscf.mcscf.RCASSCF" title="Permalink to this definition">¶</a></dt> <dd></dd></dl> <dl class="py function"> <dt id="pyscf.mcscf.UCASCI"> <code class="sig-prename descclassname">pyscf.mcscf.</code><code class="sig-name descname">UCASCI</code><span class="sig-paren">(</span><em class="sig-param"><span class="n">mf_or_mol</span></em>, <em class="sig-param"><span class="n">ncas</span></em>, <em class="sig-param"><span class="n">nelecas</span></em>, <em class="sig-param"><span class="n">ncore</span><span class="o">=</span><span class="default_value">None</span></em><span class="sig-paren">)</span><a class="headerlink" href="#pyscf.mcscf.UCASCI" title="Permalink to this definition">¶</a></dt> <dd></dd></dl> <dl class="py function"> <dt id="pyscf.mcscf.UCASSCF"> <code class="sig-prename descclassname">pyscf.mcscf.</code><code class="sig-name descname">UCASSCF</code><span class="sig-paren">(</span><em class="sig-param"><span class="n">mf_or_mol</span></em>, <em class="sig-param"><span class="n">ncas</span></em>, <em class="sig-param"><span class="n">nelecas</span></em>, <em class="sig-param"><span class="n">ncore</span><span class="o">=</span><span class="default_value">None</span></em>, <em class="sig-param"><span class="n">frozen</span><span class="o">=</span><span class="default_value">None</span></em><span class="sig-paren">)</span><a class="headerlink" href="#pyscf.mcscf.UCASSCF" title="Permalink to this definition">¶</a></dt> <dd></dd></dl> <dl class="py function"> <dt id="pyscf.mcscf.density_fit"> <code class="sig-prename descclassname">pyscf.mcscf.</code><code class="sig-name descname">density_fit</code><span class="sig-paren">(</span><em class="sig-param"><span class="n">mc</span></em>, <em class="sig-param"><span class="n">auxbasis</span><span class="o">=</span><span class="default_value">None</span></em>, <em class="sig-param"><span class="n">with_df</span><span class="o">=</span><span class="default_value">None</span></em><span class="sig-paren">)</span><a class="headerlink" href="#pyscf.mcscf.density_fit" title="Permalink to this definition">¶</a></dt> <dd></dd></dl> <dl class="py function"> <dt id="pyscf.mcscf.newton"> <code class="sig-prename descclassname">pyscf.mcscf.</code><code class="sig-name descname">newton</code><span class="sig-paren">(</span><em class="sig-param"><span class="n">mc</span></em><span class="sig-paren">)</span><a class="headerlink" href="#pyscf.mcscf.newton" title="Permalink to this definition">¶</a></dt> <dd></dd></dl> </div> </div> <div class="section"> </div> </article> </div> </div> </main> </div> <footer class="md-footer"> <div class="md-footer-nav"> <nav class="md-footer-nav__inner md-grid"> <a href="../pyscf.lo/" title="pyscf.lo package" class="md-flex md-footer-nav__link md-footer-nav__link--prev" rel="prev"> <div class="md-flex__cell md-flex__cell--shrink"> <i class="md-icon md-icon--arrow-back md-footer-nav__button"></i> </div> <div class="md-flex__cell md-flex__cell--stretch md-footer-nav__title"> <span class="md-flex__ellipsis"> <span class="md-footer-nav__direction"> Previous </span> pyscf.lo package </span> </div> </a> <a href="../pyscf.mp/" title="pyscf.mp package" class="md-flex md-footer-nav__link md-footer-nav__link--next" rel="next"> <div class="md-flex__cell md-flex__cell--stretch md-footer-nav__title"><span class="md-flex__ellipsis"> <span class="md-footer-nav__direction"> Next </span> pyscf.mp package </span> </div> <div class="md-flex__cell md-flex__cell--shrink"><i class="md-icon md-icon--arrow-forward md-footer-nav__button"></i> </div> </a> </nav> </div> <div class="md-footer-meta md-typeset"> <div class="md-footer-meta__inner md-grid"> <div class="md-footer-copyright"> <div class="md-footer-copyright__highlight"> &#169; Copyright 2021, <NAME>. </div> Created using <a href="http://www.sphinx-doc.org/">Sphinx</a> 3.4.3. and <a href="https://github.com/bashtage/sphinx-material/">Material for Sphinx</a> </div> </div> </div> </footer> <script src="../../_static/javascripts/application.js"></script> <script>app.initialize({version: "1.0.4", url: {base: ".."}})</script> </body> </html><file_sep>/docs/_sources/pyscf_api_docs/pyscf.pbc.lib.rst.txt pyscf.pbc.lib package ===================== Submodules ---------- pyscf.pbc.lib.arnoldi module ---------------------------- .. automodule:: pyscf.pbc.lib.arnoldi :members: :undoc-members: :show-inheritance: pyscf.pbc.lib.chkfile module ---------------------------- .. automodule:: pyscf.pbc.lib.chkfile :members: :undoc-members: :show-inheritance: pyscf.pbc.lib.kpts\_helper module --------------------------------- .. automodule:: pyscf.pbc.lib.kpts_helper :members: :undoc-members: :show-inheritance: pyscf.pbc.lib.linalg\_helper module ----------------------------------- .. automodule:: pyscf.pbc.lib.linalg_helper :members: :undoc-members: :show-inheritance: Module contents --------------- .. automodule:: pyscf.pbc.lib :members: :undoc-members: :show-inheritance: <file_sep>/docs/_sources/pyscf_api_docs/pyscf.prop.esr.rst.txt pyscf.prop.esr package ====================== Submodules ---------- pyscf.prop.esr.uhf module ------------------------- .. automodule:: pyscf.prop.esr.uhf :members: :undoc-members: :show-inheritance: pyscf.prop.esr.uks module ------------------------- .. automodule:: pyscf.prop.esr.uks :members: :undoc-members: :show-inheritance: Module contents --------------- .. automodule:: pyscf.prop.esr :members: :undoc-members: :show-inheritance: <file_sep>/pyscf_api_docs/pyscf.lib.rst pyscf.lib package ================= Submodules ---------- pyscf.lib.chkfile module ------------------------ .. automodule:: pyscf.lib.chkfile :members: :undoc-members: :show-inheritance: pyscf.lib.diis module --------------------- .. automodule:: pyscf.lib.diis :members: :undoc-members: :show-inheritance: pyscf.lib.exceptions module --------------------------- .. automodule:: pyscf.lib.exceptions :members: :undoc-members: :show-inheritance: pyscf.lib.linalg\_helper module ------------------------------- .. automodule:: pyscf.lib.linalg_helper :members: :undoc-members: :show-inheritance: pyscf.lib.logger module ----------------------- .. automodule:: pyscf.lib.logger :members: :undoc-members: :show-inheritance: pyscf.lib.misc module --------------------- .. automodule:: pyscf.lib.misc :members: :undoc-members: :show-inheritance: pyscf.lib.numpy\_helper module ------------------------------ .. automodule:: pyscf.lib.numpy_helper :members: :undoc-members: :show-inheritance: pyscf.lib.parameters module --------------------------- .. automodule:: pyscf.lib.parameters :members: :undoc-members: :show-inheritance: pyscf.lib.tblis\_einsum module ------------------------------ .. automodule:: pyscf.lib.tblis_einsum :members: :undoc-members: :show-inheritance: Module contents --------------- .. automodule:: pyscf.lib :members: :undoc-members: :show-inheritance: <file_sep>/docs/_sources/pyscf_api_docs/pyscf.tdscf.rst.txt pyscf.tdscf package =================== Submodules ---------- pyscf.tdscf.common\_slow module ------------------------------- .. automodule:: pyscf.tdscf.common_slow :members: :undoc-members: :show-inheritance: pyscf.tdscf.proxy module ------------------------ .. automodule:: pyscf.tdscf.proxy :members: :undoc-members: :show-inheritance: pyscf.tdscf.rhf module ---------------------- .. automodule:: pyscf.tdscf.rhf :members: :undoc-members: :show-inheritance: pyscf.tdscf.rhf\_slow module ---------------------------- .. automodule:: pyscf.tdscf.rhf_slow :members: :undoc-members: :show-inheritance: pyscf.tdscf.rks module ---------------------- .. automodule:: pyscf.tdscf.rks :members: :undoc-members: :show-inheritance: pyscf.tdscf.uhf module ---------------------- .. automodule:: pyscf.tdscf.uhf :members: :undoc-members: :show-inheritance: pyscf.tdscf.uks module ---------------------- .. automodule:: pyscf.tdscf.uks :members: :undoc-members: :show-inheritance: Module contents --------------- .. automodule:: pyscf.tdscf :members: :undoc-members: :show-inheritance: <file_sep>/pyscf_api_docs/pyscf.pbc.mpitools.rst pyscf.pbc.mpitools package ========================== Submodules ---------- pyscf.pbc.mpitools.mpi module ----------------------------- .. automodule:: pyscf.pbc.mpitools.mpi :members: :undoc-members: :show-inheritance: pyscf.pbc.mpitools.mpi\_blksize module -------------------------------------- .. automodule:: pyscf.pbc.mpitools.mpi_blksize :members: :undoc-members: :show-inheritance: pyscf.pbc.mpitools.mpi\_helper module ------------------------------------- .. automodule:: pyscf.pbc.mpitools.mpi_helper :members: :undoc-members: :show-inheritance: pyscf.pbc.mpitools.mpi\_load\_balancer module --------------------------------------------- .. automodule:: pyscf.pbc.mpitools.mpi_load_balancer :members: :undoc-members: :show-inheritance: pyscf.pbc.mpitools.mpi\_pool module ----------------------------------- .. automodule:: pyscf.pbc.mpitools.mpi_pool :members: :undoc-members: :show-inheritance: Module contents --------------- .. automodule:: pyscf.pbc.mpitools :members: :undoc-members: :show-inheritance: <file_sep>/make_fresh.sh #!/bin/bash ablog clean rm -r .doctrees ablog build<file_sep>/docs/_sources/pyscf_api_docs/pyscf.eph.rst.txt pyscf.eph package ================= Submodules ---------- pyscf.eph.eph\_fd module ------------------------ .. automodule:: pyscf.eph.eph_fd :members: :undoc-members: :show-inheritance: pyscf.eph.rhf module -------------------- .. automodule:: pyscf.eph.rhf :members: :undoc-members: :show-inheritance: pyscf.eph.rks module -------------------- .. automodule:: pyscf.eph.rks :members: :undoc-members: :show-inheritance: pyscf.eph.uhf module -------------------- .. automodule:: pyscf.eph.uhf :members: :undoc-members: :show-inheritance: pyscf.eph.uks module -------------------- .. automodule:: pyscf.eph.uks :members: :undoc-members: :show-inheritance: Module contents --------------- .. automodule:: pyscf.eph :members: :undoc-members: :show-inheritance: <file_sep>/docs/_sources/pyscf_api_docs/pyscf.prop.hfc.rst.txt pyscf.prop.hfc package ====================== Submodules ---------- pyscf.prop.hfc.dhf module ------------------------- .. automodule:: pyscf.prop.hfc.dhf :members: :undoc-members: :show-inheritance: pyscf.prop.hfc.uhf module ------------------------- .. automodule:: pyscf.prop.hfc.uhf :members: :undoc-members: :show-inheritance: pyscf.prop.hfc.uks module ------------------------- .. automodule:: pyscf.prop.hfc.uks :members: :undoc-members: :show-inheritance: Module contents --------------- .. automodule:: pyscf.prop.hfc :members: :undoc-members: :show-inheritance: <file_sep>/pyscf_api_docs/pyscf.dft.xc.rst pyscf.dft.xc package ==================== Submodules ---------- pyscf.dft.xc.utils module ------------------------- .. automodule:: pyscf.dft.xc.utils :members: :undoc-members: :show-inheritance: Module contents --------------- .. automodule:: pyscf.dft.xc :members: :undoc-members: :show-inheritance: <file_sep>/pyscf_api_docs/pyscf.ccn.rst pyscf.ccn package ================= Submodules ---------- pyscf.ccn.cc module ------------------- .. automodule:: pyscf.ccn.cc :members: :undoc-members: :show-inheritance: pyscf.ccn.equations module -------------------------- .. automodule:: pyscf.ccn.equations :members: :undoc-members: :show-inheritance: pyscf.ccn.pyscf\_helpers module ------------------------------- .. automodule:: pyscf.ccn.pyscf_helpers :members: :undoc-members: :show-inheritance: pyscf.ccn.test module --------------------- .. automodule:: pyscf.ccn.test :members: :undoc-members: :show-inheritance: pyscf.ccn.util module --------------------- .. automodule:: pyscf.ccn.util :members: :undoc-members: :show-inheritance: Module contents --------------- .. automodule:: pyscf.ccn :members: :undoc-members: :show-inheritance: <file_sep>/docs/_sources/pyscf_api_docs/pyscf.hessian.rst.txt pyscf.hessian package ===================== Submodules ---------- pyscf.hessian.rhf module ------------------------ .. automodule:: pyscf.hessian.rhf :members: :undoc-members: :show-inheritance: pyscf.hessian.rks module ------------------------ .. automodule:: pyscf.hessian.rks :members: :undoc-members: :show-inheritance: pyscf.hessian.thermo module --------------------------- .. automodule:: pyscf.hessian.thermo :members: :undoc-members: :show-inheritance: pyscf.hessian.uhf module ------------------------ .. automodule:: pyscf.hessian.uhf :members: :undoc-members: :show-inheritance: pyscf.hessian.uks module ------------------------ .. automodule:: pyscf.hessian.uks :members: :undoc-members: :show-inheritance: Module contents --------------- .. automodule:: pyscf.hessian :members: :undoc-members: :show-inheritance: <file_sep>/docs/_sources/pyscf_api_docs/pyscf.df.hessian.rst.txt pyscf.df.hessian package ======================== Submodules ---------- pyscf.df.hessian.rhf module --------------------------- .. automodule:: pyscf.df.hessian.rhf :members: :undoc-members: :show-inheritance: pyscf.df.hessian.rks module --------------------------- .. automodule:: pyscf.df.hessian.rks :members: :undoc-members: :show-inheritance: pyscf.df.hessian.uhf module --------------------------- .. automodule:: pyscf.df.hessian.uhf :members: :undoc-members: :show-inheritance: pyscf.df.hessian.uks module --------------------------- .. automodule:: pyscf.df.hessian.uks :members: :undoc-members: :show-inheritance: Module contents --------------- .. automodule:: pyscf.df.hessian :members: :undoc-members: :show-inheritance: <file_sep>/docs/_sources/pyscf_api_docs/pyscf.sgx.rst.txt pyscf.sgx package ================= Submodules ---------- pyscf.sgx.sgx module -------------------- .. automodule:: pyscf.sgx.sgx :members: :undoc-members: :show-inheritance: pyscf.sgx.sgx\_jk module ------------------------ .. automodule:: pyscf.sgx.sgx_jk :members: :undoc-members: :show-inheritance: Module contents --------------- .. automodule:: pyscf.sgx :members: :undoc-members: :show-inheritance: <file_sep>/docs/_sources/pyscf_api_docs/pyscf.extras.rst.txt pyscf.extras package ==================== Subpackages ----------- .. toctree:: :maxdepth: 4 pyscf.extras.mbd Module contents --------------- .. automodule:: pyscf.extras :members: :undoc-members: :show-inheritance: <file_sep>/docs/_sources/pyscf_api_docs/pyscf.adc.rst.txt pyscf.adc package ================= Submodules ---------- pyscf.adc.uadc module --------------------- .. automodule:: pyscf.adc.uadc :members: :undoc-members: :show-inheritance: pyscf.adc.uadc\_ao2mo module ---------------------------- .. automodule:: pyscf.adc.uadc_ao2mo :members: :undoc-members: :show-inheritance: Module contents --------------- .. automodule:: pyscf.adc :members: :undoc-members: :show-inheritance: <file_sep>/pyscf_api_docs/pyscf.pbc.mpicc.rst pyscf.pbc.mpicc package ======================= Submodules ---------- pyscf.pbc.mpicc.kccsd\_rhf module --------------------------------- .. automodule:: pyscf.pbc.mpicc.kccsd_rhf :members: :undoc-members: :show-inheritance: pyscf.pbc.mpicc.kintermediates\_rhf module ------------------------------------------ .. automodule:: pyscf.pbc.mpicc.kintermediates_rhf :members: :undoc-members: :show-inheritance: pyscf.pbc.mpicc.mpi\_kpoint\_helper module ------------------------------------------ .. automodule:: pyscf.pbc.mpicc.mpi_kpoint_helper :members: :undoc-members: :show-inheritance: Module contents --------------- .. automodule:: pyscf.pbc.mpicc :members: :undoc-members: :show-inheritance: <file_sep>/docs/_sources/pyscf_api_docs/pyscf.ao2mo.rst.txt pyscf.ao2mo package =================== Submodules ---------- pyscf.ao2mo.addons module ------------------------- .. automodule:: pyscf.ao2mo.addons :members: :undoc-members: :show-inheritance: pyscf.ao2mo.incore module ------------------------- .. automodule:: pyscf.ao2mo.incore :members: :undoc-members: :show-inheritance: pyscf.ao2mo.outcore module -------------------------- .. automodule:: pyscf.ao2mo.outcore :members: :undoc-members: :show-inheritance: pyscf.ao2mo.r\_outcore module ----------------------------- .. automodule:: pyscf.ao2mo.r_outcore :members: :undoc-members: :show-inheritance: pyscf.ao2mo.semi\_incore module ------------------------------- .. automodule:: pyscf.ao2mo.semi_incore :members: :undoc-members: :show-inheritance: Module contents --------------- .. automodule:: pyscf.ao2mo :members: :undoc-members: :show-inheritance: <file_sep>/docs/_sources/pyscf_api_docs/pyscf.prop.rotational_gtensor.rst.txt pyscf.prop.rotational\_gtensor package ====================================== Submodules ---------- pyscf.prop.rotational\_gtensor.rhf module ----------------------------------------- .. automodule:: pyscf.prop.rotational_gtensor.rhf :members: :undoc-members: :show-inheritance: pyscf.prop.rotational\_gtensor.rks module ----------------------------------------- .. automodule:: pyscf.prop.rotational_gtensor.rks :members: :undoc-members: :show-inheritance: pyscf.prop.rotational\_gtensor.uhf module ----------------------------------------- .. automodule:: pyscf.prop.rotational_gtensor.uhf :members: :undoc-members: :show-inheritance: pyscf.prop.rotational\_gtensor.uks module ----------------------------------------- .. automodule:: pyscf.prop.rotational_gtensor.uks :members: :undoc-members: :show-inheritance: Module contents --------------- .. automodule:: pyscf.prop.rotational_gtensor :members: :undoc-members: :show-inheritance: <file_sep>/docs/_sources/pyscf_api_docs/pyscf.pbc.prop.rst.txt pyscf.pbc.prop package ====================== Subpackages ----------- .. toctree:: :maxdepth: 4 pyscf.pbc.prop.efg pyscf.pbc.prop.polarizability Module contents --------------- .. automodule:: pyscf.pbc.prop :members: :undoc-members: :show-inheritance: <file_sep>/pyscf_api_docs/pyscf.pbc.rst pyscf.pbc package ================= Subpackages ----------- .. toctree:: :maxdepth: 4 pyscf.pbc.ao2mo pyscf.pbc.cc pyscf.pbc.ci pyscf.pbc.df pyscf.pbc.dft pyscf.pbc.eph pyscf.pbc.geomopt pyscf.pbc.grad pyscf.pbc.gto pyscf.pbc.gw pyscf.pbc.lib pyscf.pbc.mp pyscf.pbc.mpicc pyscf.pbc.mpitools pyscf.pbc.prop pyscf.pbc.scf pyscf.pbc.tddft pyscf.pbc.tdscf pyscf.pbc.tools pyscf.pbc.x2c Module contents --------------- .. automodule:: pyscf.pbc :members: :undoc-members: :show-inheritance: <file_sep>/pyscf_api_docs/pyscf.x2c.rst pyscf.x2c package ================= Submodules ---------- pyscf.x2c.sfx2c1e module ------------------------ .. automodule:: pyscf.x2c.sfx2c1e :members: :undoc-members: :show-inheritance: pyscf.x2c.sfx2c1e\_grad module ------------------------------ .. automodule:: pyscf.x2c.sfx2c1e_grad :members: :undoc-members: :show-inheritance: pyscf.x2c.sfx2c1e\_hess module ------------------------------ .. automodule:: pyscf.x2c.sfx2c1e_hess :members: :undoc-members: :show-inheritance: pyscf.x2c.x2c module -------------------- .. automodule:: pyscf.x2c.x2c :members: :undoc-members: :show-inheritance: Module contents --------------- .. automodule:: pyscf.x2c :members: :undoc-members: :show-inheritance: <file_sep>/docs/_sources/pyscf_api_docs/pyscf.pbc.gto.rst.txt pyscf.pbc.gto package ===================== Subpackages ----------- .. toctree:: :maxdepth: 4 pyscf.pbc.gto.basis pyscf.pbc.gto.pseudo Submodules ---------- pyscf.pbc.gto.cell module ------------------------- .. automodule:: pyscf.pbc.gto.cell :members: :undoc-members: :show-inheritance: pyscf.pbc.gto.ecp module ------------------------ .. automodule:: pyscf.pbc.gto.ecp :members: :undoc-members: :show-inheritance: pyscf.pbc.gto.eval\_gto module ------------------------------ .. automodule:: pyscf.pbc.gto.eval_gto :members: :undoc-members: :show-inheritance: Module contents --------------- .. automodule:: pyscf.pbc.gto :members: :undoc-members: :show-inheritance: <file_sep>/docs/_sources/pyscf_api_docs/pyscf.pbc.mp.rst.txt pyscf.pbc.mp package ==================== Submodules ---------- pyscf.pbc.mp.kmp2 module ------------------------ .. automodule:: pyscf.pbc.mp.kmp2 :members: :undoc-members: :show-inheritance: pyscf.pbc.mp.kump2 module ------------------------- .. automodule:: pyscf.pbc.mp.kump2 :members: :undoc-members: :show-inheritance: pyscf.pbc.mp.mp2 module ----------------------- .. automodule:: pyscf.pbc.mp.mp2 :members: :undoc-members: :show-inheritance: Module contents --------------- .. automodule:: pyscf.pbc.mp :members: :undoc-members: :show-inheritance: <file_sep>/pyscf_api_docs/pyscf.df.rst pyscf.df package ================ Subpackages ----------- .. toctree:: :maxdepth: 4 pyscf.df.grad pyscf.df.hessian Submodules ---------- pyscf.df.addons module ---------------------- .. automodule:: pyscf.df.addons :members: :undoc-members: :show-inheritance: pyscf.df.df module ------------------ .. automodule:: pyscf.df.df :members: :undoc-members: :show-inheritance: pyscf.df.df\_jk module ---------------------- .. automodule:: pyscf.df.df_jk :members: :undoc-members: :show-inheritance: pyscf.df.incore module ---------------------- .. automodule:: pyscf.df.incore :members: :undoc-members: :show-inheritance: pyscf.df.outcore module ----------------------- .. automodule:: pyscf.df.outcore :members: :undoc-members: :show-inheritance: pyscf.df.r\_incore module ------------------------- .. automodule:: pyscf.df.r_incore :members: :undoc-members: :show-inheritance: Module contents --------------- .. automodule:: pyscf.df :members: :undoc-members: :show-inheritance: <file_sep>/docs/_sources/pyscf_api_docs/pyscf.solvent.rst.txt pyscf.solvent package ===================== Submodules ---------- pyscf.solvent.ddcosmo module ---------------------------- .. automodule:: pyscf.solvent.ddcosmo :members: :undoc-members: :show-inheritance: pyscf.solvent.ddcosmo\_grad module ---------------------------------- .. automodule:: pyscf.solvent.ddcosmo_grad :members: :undoc-members: :show-inheritance: pyscf.solvent.ddpcm module -------------------------- .. automodule:: pyscf.solvent.ddpcm :members: :undoc-members: :show-inheritance: pyscf.solvent.pol\_embed module ------------------------------- .. automodule:: pyscf.solvent.pol_embed :members: :undoc-members: :show-inheritance: Module contents --------------- .. automodule:: pyscf.solvent :members: :undoc-members: :show-inheritance: <file_sep>/docs/_sources/pyscf_api_docs/pyscf.doci.rst.txt pyscf.doci package ================== Submodules ---------- pyscf.doci.doci\_mcscf module ----------------------------- .. automodule:: pyscf.doci.doci_mcscf :members: :undoc-members: :show-inheritance: pyscf.doci.doci\_slow module ---------------------------- .. automodule:: pyscf.doci.doci_slow :members: :undoc-members: :show-inheritance: Module contents --------------- .. automodule:: pyscf.doci :members: :undoc-members: :show-inheritance: <file_sep>/pyscf_api_docs/pyscf.dft.rst pyscf.dft package ================= Subpackages ----------- .. toctree:: :maxdepth: 4 pyscf.dft.xc Submodules ---------- pyscf.dft.dks module -------------------- .. automodule:: pyscf.dft.dks :members: :undoc-members: :show-inheritance: pyscf.dft.gen\_grid module -------------------------- .. automodule:: pyscf.dft.gen_grid :members: :undoc-members: :show-inheritance: pyscf.dft.gen\_libxc\_param module ---------------------------------- .. automodule:: pyscf.dft.gen_libxc_param :members: :undoc-members: :show-inheritance: pyscf.dft.gen\_xcfun\_param module ---------------------------------- .. automodule:: pyscf.dft.gen_xcfun_param :members: :undoc-members: :show-inheritance: pyscf.dft.gks module -------------------- .. automodule:: pyscf.dft.gks :members: :undoc-members: :show-inheritance: pyscf.dft.gks\_symm module -------------------------- .. automodule:: pyscf.dft.gks_symm :members: :undoc-members: :show-inheritance: pyscf.dft.libxc module ---------------------- .. automodule:: pyscf.dft.libxc :members: :undoc-members: :show-inheritance: pyscf.dft.numint module ----------------------- .. automodule:: pyscf.dft.numint :members: :undoc-members: :show-inheritance: pyscf.dft.r\_numint module -------------------------- .. automodule:: pyscf.dft.r_numint :members: :undoc-members: :show-inheritance: pyscf.dft.radi module --------------------- .. automodule:: pyscf.dft.radi :members: :undoc-members: :show-inheritance: pyscf.dft.rks module -------------------- .. automodule:: pyscf.dft.rks :members: :undoc-members: :show-inheritance: pyscf.dft.rks\_symm module -------------------------- .. automodule:: pyscf.dft.rks_symm :members: :undoc-members: :show-inheritance: pyscf.dft.roks module --------------------- .. automodule:: pyscf.dft.roks :members: :undoc-members: :show-inheritance: pyscf.dft.sap module -------------------- .. automodule:: pyscf.dft.sap :members: :undoc-members: :show-inheritance: pyscf.dft.sap\_data module -------------------------- .. automodule:: pyscf.dft.sap_data :members: :undoc-members: :show-inheritance: pyscf.dft.uks module -------------------- .. automodule:: pyscf.dft.uks :members: :undoc-members: :show-inheritance: pyscf.dft.uks\_symm module -------------------------- .. automodule:: pyscf.dft.uks_symm :members: :undoc-members: :show-inheritance: pyscf.dft.xcfun module ---------------------- .. automodule:: pyscf.dft.xcfun :members: :undoc-members: :show-inheritance: Module contents --------------- .. automodule:: pyscf.dft :members: :undoc-members: :show-inheritance: <file_sep>/docs/_sources/pyscf_api_docs/pyscf.pbc.df.rst.txt pyscf.pbc.df package ==================== Submodules ---------- pyscf.pbc.df.aft module ----------------------- .. automodule:: pyscf.pbc.df.aft :members: :undoc-members: :show-inheritance: pyscf.pbc.df.aft\_ao2mo module ------------------------------ .. automodule:: pyscf.pbc.df.aft_ao2mo :members: :undoc-members: :show-inheritance: pyscf.pbc.df.aft\_jk module --------------------------- .. automodule:: pyscf.pbc.df.aft_jk :members: :undoc-members: :show-inheritance: pyscf.pbc.df.df module ---------------------- .. automodule:: pyscf.pbc.df.df :members: :undoc-members: :show-inheritance: pyscf.pbc.df.df\_ao2mo module ----------------------------- .. automodule:: pyscf.pbc.df.df_ao2mo :members: :undoc-members: :show-inheritance: pyscf.pbc.df.df\_jk module -------------------------- .. automodule:: pyscf.pbc.df.df_jk :members: :undoc-members: :show-inheritance: pyscf.pbc.df.fft module ----------------------- .. automodule:: pyscf.pbc.df.fft :members: :undoc-members: :show-inheritance: pyscf.pbc.df.fft\_ao2mo module ------------------------------ .. automodule:: pyscf.pbc.df.fft_ao2mo :members: :undoc-members: :show-inheritance: pyscf.pbc.df.fft\_jk module --------------------------- .. automodule:: pyscf.pbc.df.fft_jk :members: :undoc-members: :show-inheritance: pyscf.pbc.df.ft\_ao module -------------------------- .. automodule:: pyscf.pbc.df.ft_ao :members: :undoc-members: :show-inheritance: pyscf.pbc.df.incore module -------------------------- .. automodule:: pyscf.pbc.df.incore :members: :undoc-members: :show-inheritance: pyscf.pbc.df.mdf module ----------------------- .. automodule:: pyscf.pbc.df.mdf :members: :undoc-members: :show-inheritance: pyscf.pbc.df.mdf\_ao2mo module ------------------------------ .. automodule:: pyscf.pbc.df.mdf_ao2mo :members: :undoc-members: :show-inheritance: pyscf.pbc.df.mdf\_jk module --------------------------- .. automodule:: pyscf.pbc.df.mdf_jk :members: :undoc-members: :show-inheritance: pyscf.pbc.df.outcore module --------------------------- .. automodule:: pyscf.pbc.df.outcore :members: :undoc-members: :show-inheritance: Module contents --------------- .. automodule:: pyscf.pbc.df :members: :undoc-members: :show-inheritance: <file_sep>/docs/_sources/about.md.txt # About ## People ### Board of directors - <NAME>, Columbia and Flatiron Institute - <NAME>, Caltech - <NAME>, UC Boulder - <NAME>, Ohio State - <NAME>, Tencent Quantum Laboratory ### Maintainers - <NAME>, Caltech - <NAME>, Caltech - <NAME>, UC Boulder - <NAME>, Flatiron Institute - <NAME>, Flatiron Institute ## Funding The development of PySCF has been and continues to be generously supported by a number of funding agencies. Most of the molecular quantum chemistry software infrastructure was developed with support from the US National Science Foundation, through grants CHE-1650436 and ACI-1657286. The periodic mean-field infrastructure was developed with support from ACI-1657286. The excited-state periodic coupled cluster methods were developed with support from the US Department of Energy, Office of Science, through the grants DE-SC0010530 and DE-SC0008624. Additional support for the extended-system methods has been provided by the Simons Foundation through the Simons Collaboration on the Many Electron Problem, a Simons Investigatorship in Theoretical Physics, the Princeton Center for Theoretical Science, and startup funds from Princeton University and the California Institute of Technology. ## Citing PySCF If you use PySCF in your published research, we ask that you please cite the relevant papers: ### General - [PySCF: the Python-based simulations of chemistry framework](http://dx.doi.org/10.1002/wcms.1340), <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, and <NAME>, WIREs Comput. Mol. Sci. 8, e1340 (2018) - [Libcint: An efficient general integral library for Gaussian basis functions](http://dx.doi.org/10.1002/jcc.23981), <NAME>, J. Comp. Chem. 36, 1664 (2015) ### CASSCF - [A general second order complete active space self-consistent-field solver for large-scale systems](http://www.sciencedirect.com/science/article/pii/S0009261417302166), <NAME>, <NAME>, and <NAME>, Chem. Phys. Lett. 683, 291 (2017) [Bibtex] ### Periodic boundary conditions - [Gaussian-Based Coupled-Cluster Theory for the Ground-State and Band Structure of Solids](https://pubs.acs.org/doi/10.1021/acs.jctc.7b00049) <NAME>, <NAME>, <NAME>, and <NAME>, J. Chem. Theory Comput. 13, 1209 (2017) [Bibtex] - [Gaussian and plane-wave mixed density fitting for periodic systems](https://aip.scitation.org/doi/10.1063/1.4998644) <NAME>, <NAME>, <NAME>, <NAME>, J. Chem. Phys. 147, 164119 (2017) [Bibtex] <file_sep>/pyscf_api_docs/pyscf.geomopt.rst pyscf.geomopt package ===================== Submodules ---------- pyscf.geomopt.addons module --------------------------- .. automodule:: pyscf.geomopt.addons :members: :undoc-members: :show-inheritance: pyscf.geomopt.berny\_solver module ---------------------------------- .. automodule:: pyscf.geomopt.berny_solver :members: :undoc-members: :show-inheritance: pyscf.geomopt.geometric\_solver module -------------------------------------- .. automodule:: pyscf.geomopt.geometric_solver :members: :undoc-members: :show-inheritance: Module contents --------------- .. automodule:: pyscf.geomopt :members: :undoc-members: :show-inheritance: <file_sep>/docs/_sources/pyscf_api_docs/pyscf.rst.txt pyscf package ============= Subpackages ----------- .. toctree:: :maxdepth: 4 pyscf.adc pyscf.ao2mo pyscf.cc pyscf.ccn pyscf.ci pyscf.cornell_shci pyscf.data pyscf.df pyscf.dft pyscf.dftd3 pyscf.doci pyscf.eph pyscf.extras pyscf.fci pyscf.geomopt pyscf.grad pyscf.gto pyscf.gw pyscf.hci pyscf.hessian pyscf.lib pyscf.lo pyscf.mcscf pyscf.mp pyscf.mrpt pyscf.pbc pyscf.prop pyscf.qmmm pyscf.rt pyscf.scf pyscf.semiempirical pyscf.sgx pyscf.solvent pyscf.soscf pyscf.symm pyscf.tddft pyscf.tdscf pyscf.tools pyscf.x2c Submodules ---------- pyscf.post\_scf module ---------------------- .. automodule:: pyscf.post_scf :members: :undoc-members: :show-inheritance: Module contents --------------- .. automodule:: pyscf :members: :undoc-members: :show-inheritance: <file_sep>/pyscf_api_docs/pyscf.extras.mbd.rst pyscf.extras.mbd package ======================== Submodules ---------- pyscf.extras.mbd.mbd module --------------------------- .. automodule:: pyscf.extras.mbd.mbd :members: :undoc-members: :show-inheritance: pyscf.extras.mbd.vdw\_param module ---------------------------------- .. automodule:: pyscf.extras.mbd.vdw_param :members: :undoc-members: :show-inheritance: Module contents --------------- .. automodule:: pyscf.extras.mbd :members: :undoc-members: :show-inheritance: <file_sep>/index.rst .. PySCF index file, created by `ablog start` on Mon Feb 8 20:10:55 2021. You can adapt this file completely to your liking, but it should at least contain the root `toctree` directive. Welcome to the PySCF Website! ================================= The Python-based Simulations of Chemistry Framework PySCF is an open-source collection of electronic structure modules powered by Python. The package aims to provide a simple, lightweight, and efficient platform for quantum chemistry calculations and methodology development. Here is a list of most recent posts: .. postlist:: 5 :excerpts: .. `toctree` directive, below, contains list of non-post `.rst` files. This is how they appear in Navigation sidebar. Note that directive also contains `:hidden:` option so that it is not included inside the page. Posts are excluded from this directive so that they aren't double listed in the sidebar both under Navigation and Recent Posts. .. toctree:: :hidden: :maxdepth: 1 about.md Blog <blog_wrapper.rst> API Docs <pyscf_api_docs/pyscf.rst> <file_sep>/pyscf_api_docs/pyscf.prop.efg.rst pyscf.prop.efg package ====================== Submodules ---------- pyscf.prop.efg.dhf module ------------------------- .. automodule:: pyscf.prop.efg.dhf :members: :undoc-members: :show-inheritance: pyscf.prop.efg.rhf module ------------------------- .. automodule:: pyscf.prop.efg.rhf :members: :undoc-members: :show-inheritance: pyscf.prop.efg.uhf module ------------------------- .. automodule:: pyscf.prop.efg.uhf :members: :undoc-members: :show-inheritance: Module contents --------------- .. automodule:: pyscf.prop.efg :members: :undoc-members: :show-inheritance: <file_sep>/docs/_sources/pyscf_api_docs/pyscf.pbc.eph.rst.txt pyscf.pbc.eph package ===================== Submodules ---------- pyscf.pbc.eph.eph\_fd module ---------------------------- .. automodule:: pyscf.pbc.eph.eph_fd :members: :undoc-members: :show-inheritance: Module contents --------------- .. automodule:: pyscf.pbc.eph :members: :undoc-members: :show-inheritance: <file_sep>/pyscf_api_docs/pyscf.prop.magnetizability.rst pyscf.prop.magnetizability package ================================== Submodules ---------- pyscf.prop.magnetizability.rhf module ------------------------------------- .. automodule:: pyscf.prop.magnetizability.rhf :members: :undoc-members: :show-inheritance: pyscf.prop.magnetizability.rks module ------------------------------------- .. automodule:: pyscf.prop.magnetizability.rks :members: :undoc-members: :show-inheritance: pyscf.prop.magnetizability.uhf module ------------------------------------- .. automodule:: pyscf.prop.magnetizability.uhf :members: :undoc-members: :show-inheritance: pyscf.prop.magnetizability.uks module ------------------------------------- .. automodule:: pyscf.prop.magnetizability.uks :members: :undoc-members: :show-inheritance: Module contents --------------- .. automodule:: pyscf.prop.magnetizability :members: :undoc-members: :show-inheritance: <file_sep>/docs/_sources/pyscf_api_docs/pyscf.lo.rst.txt pyscf.lo package ================ Submodules ---------- pyscf.lo.boys module -------------------- .. automodule:: pyscf.lo.boys :members: :undoc-members: :show-inheritance: pyscf.lo.edmiston module ------------------------ .. automodule:: pyscf.lo.edmiston :members: :undoc-members: :show-inheritance: pyscf.lo.iao module ------------------- .. automodule:: pyscf.lo.iao :members: :undoc-members: :show-inheritance: pyscf.lo.ibo module ------------------- .. automodule:: pyscf.lo.ibo :members: :undoc-members: :show-inheritance: pyscf.lo.nao module ------------------- .. automodule:: pyscf.lo.nao :members: :undoc-members: :show-inheritance: pyscf.lo.orth module -------------------- .. automodule:: pyscf.lo.orth :members: :undoc-members: :show-inheritance: pyscf.lo.pipek module --------------------- .. automodule:: pyscf.lo.pipek :members: :undoc-members: :show-inheritance: pyscf.lo.vvo module ------------------- .. automodule:: pyscf.lo.vvo :members: :undoc-members: :show-inheritance: Module contents --------------- .. automodule:: pyscf.lo :members: :undoc-members: :show-inheritance: <file_sep>/docs/_sources/pyscf_api_docs/pyscf.pbc.tdscf.rst.txt pyscf.pbc.tdscf package ======================= Submodules ---------- pyscf.pbc.tdscf.kproxy module ----------------------------- .. automodule:: pyscf.pbc.tdscf.kproxy :members: :undoc-members: :show-inheritance: pyscf.pbc.tdscf.kproxy\_supercell module ---------------------------------------- .. automodule:: pyscf.pbc.tdscf.kproxy_supercell :members: :undoc-members: :show-inheritance: pyscf.pbc.tdscf.krhf module --------------------------- .. automodule:: pyscf.pbc.tdscf.krhf :members: :undoc-members: :show-inheritance: pyscf.pbc.tdscf.krhf\_slow module --------------------------------- .. automodule:: pyscf.pbc.tdscf.krhf_slow :members: :undoc-members: :show-inheritance: pyscf.pbc.tdscf.krhf\_slow\_gamma module ---------------------------------------- .. automodule:: pyscf.pbc.tdscf.krhf_slow_gamma :members: :undoc-members: :show-inheritance: pyscf.pbc.tdscf.krhf\_slow\_supercell module -------------------------------------------- .. automodule:: pyscf.pbc.tdscf.krhf_slow_supercell :members: :undoc-members: :show-inheritance: pyscf.pbc.tdscf.krks module --------------------------- .. automodule:: pyscf.pbc.tdscf.krks :members: :undoc-members: :show-inheritance: pyscf.pbc.tdscf.kuhf module --------------------------- .. automodule:: pyscf.pbc.tdscf.kuhf :members: :undoc-members: :show-inheritance: pyscf.pbc.tdscf.kuks module --------------------------- .. automodule:: pyscf.pbc.tdscf.kuks :members: :undoc-members: :show-inheritance: pyscf.pbc.tdscf.proxy module ---------------------------- .. automodule:: pyscf.pbc.tdscf.proxy :members: :undoc-members: :show-inheritance: pyscf.pbc.tdscf.rhf module -------------------------- .. automodule:: pyscf.pbc.tdscf.rhf :members: :undoc-members: :show-inheritance: pyscf.pbc.tdscf.rhf\_slow module -------------------------------- .. automodule:: pyscf.pbc.tdscf.rhf_slow :members: :undoc-members: :show-inheritance: pyscf.pbc.tdscf.rks module -------------------------- .. automodule:: pyscf.pbc.tdscf.rks :members: :undoc-members: :show-inheritance: pyscf.pbc.tdscf.uhf module -------------------------- .. automodule:: pyscf.pbc.tdscf.uhf :members: :undoc-members: :show-inheritance: pyscf.pbc.tdscf.uks module -------------------------- .. automodule:: pyscf.pbc.tdscf.uks :members: :undoc-members: :show-inheritance: Module contents --------------- .. automodule:: pyscf.pbc.tdscf :members: :undoc-members: :show-inheritance: <file_sep>/docs/_sources/pyscf_api_docs/pyscf.prop.nsr.rst.txt pyscf.prop.nsr package ====================== Submodules ---------- pyscf.prop.nsr.rhf module ------------------------- .. automodule:: pyscf.prop.nsr.rhf :members: :undoc-members: :show-inheritance: pyscf.prop.nsr.rks module ------------------------- .. automodule:: pyscf.prop.nsr.rks :members: :undoc-members: :show-inheritance: pyscf.prop.nsr.uhf module ------------------------- .. automodule:: pyscf.prop.nsr.uhf :members: :undoc-members: :show-inheritance: pyscf.prop.nsr.uks module ------------------------- .. automodule:: pyscf.prop.nsr.uks :members: :undoc-members: :show-inheritance: Module contents --------------- .. automodule:: pyscf.prop.nsr :members: :undoc-members: :show-inheritance: <file_sep>/docs/_sources/pyscf_api_docs/pyscf.fci.rst.txt pyscf.fci package ================= Submodules ---------- pyscf.fci.addons module ----------------------- .. automodule:: pyscf.fci.addons :members: :undoc-members: :show-inheritance: pyscf.fci.cistring module ------------------------- .. automodule:: pyscf.fci.cistring :members: :undoc-members: :show-inheritance: pyscf.fci.direct\_ep module --------------------------- .. automodule:: pyscf.fci.direct_ep :members: :undoc-members: :show-inheritance: pyscf.fci.direct\_nosym module ------------------------------ .. automodule:: pyscf.fci.direct_nosym :members: :undoc-members: :show-inheritance: pyscf.fci.direct\_spin0 module ------------------------------ .. automodule:: pyscf.fci.direct_spin0 :members: :undoc-members: :show-inheritance: pyscf.fci.direct\_spin0\_symm module ------------------------------------ .. automodule:: pyscf.fci.direct_spin0_symm :members: :undoc-members: :show-inheritance: pyscf.fci.direct\_spin1 module ------------------------------ .. automodule:: pyscf.fci.direct_spin1 :members: :undoc-members: :show-inheritance: pyscf.fci.direct\_spin1\_symm module ------------------------------------ .. automodule:: pyscf.fci.direct_spin1_symm :members: :undoc-members: :show-inheritance: pyscf.fci.direct\_uhf module ---------------------------- .. automodule:: pyscf.fci.direct_uhf :members: :undoc-members: :show-inheritance: pyscf.fci.fci\_slow module -------------------------- .. automodule:: pyscf.fci.fci_slow :members: :undoc-members: :show-inheritance: pyscf.fci.rdm module -------------------- .. automodule:: pyscf.fci.rdm :members: :undoc-members: :show-inheritance: pyscf.fci.selected\_ci module ----------------------------- .. automodule:: pyscf.fci.selected_ci :members: :undoc-members: :show-inheritance: pyscf.fci.selected\_ci\_slow module ----------------------------------- .. automodule:: pyscf.fci.selected_ci_slow :members: :undoc-members: :show-inheritance: pyscf.fci.selected\_ci\_spin0 module ------------------------------------ .. automodule:: pyscf.fci.selected_ci_spin0 :members: :undoc-members: :show-inheritance: pyscf.fci.selected\_ci\_spin0\_symm module ------------------------------------------ .. automodule:: pyscf.fci.selected_ci_spin0_symm :members: :undoc-members: :show-inheritance: pyscf.fci.selected\_ci\_symm module ----------------------------------- .. automodule:: pyscf.fci.selected_ci_symm :members: :undoc-members: :show-inheritance: pyscf.fci.spin\_op module ------------------------- .. automodule:: pyscf.fci.spin_op :members: :undoc-members: :show-inheritance: Module contents --------------- .. automodule:: pyscf.fci :members: :undoc-members: :show-inheritance: <file_sep>/pyscf_api_docs/pyscf.tools.rst pyscf.tools package =================== Submodules ---------- pyscf.tools.c60struct module ---------------------------- .. automodule:: pyscf.tools.c60struct :members: :undoc-members: :show-inheritance: pyscf.tools.chgcar module ------------------------- .. automodule:: pyscf.tools.chgcar :members: :undoc-members: :show-inheritance: pyscf.tools.chkfile\_util module -------------------------------- .. automodule:: pyscf.tools.chkfile_util :members: :undoc-members: :show-inheritance: pyscf.tools.cubegen module -------------------------- .. automodule:: pyscf.tools.cubegen :members: :undoc-members: :show-inheritance: pyscf.tools.dump\_mat module ---------------------------- .. automodule:: pyscf.tools.dump_mat :members: :undoc-members: :show-inheritance: pyscf.tools.fcidump module -------------------------- .. automodule:: pyscf.tools.fcidump :members: :undoc-members: :show-inheritance: pyscf.tools.mo\_mapping module ------------------------------ .. automodule:: pyscf.tools.mo_mapping :members: :undoc-members: :show-inheritance: pyscf.tools.molden module ------------------------- .. automodule:: pyscf.tools.molden :members: :undoc-members: :show-inheritance: pyscf.tools.rhf\_newtonraphson module ------------------------------------- .. automodule:: pyscf.tools.rhf_newtonraphson :members: :undoc-members: :show-inheritance: pyscf.tools.ring module ----------------------- .. automodule:: pyscf.tools.ring :members: :undoc-members: :show-inheritance: pyscf.tools.wfn\_format module ------------------------------ .. automodule:: pyscf.tools.wfn_format :members: :undoc-members: :show-inheritance: Module contents --------------- .. automodule:: pyscf.tools :members: :undoc-members: :show-inheritance: <file_sep>/docs/_sources/pyscf_api_docs/pyscf.pbc.gto.pseudo.rst.txt pyscf.pbc.gto.pseudo package ============================ Submodules ---------- pyscf.pbc.gto.pseudo.parse\_cp2k module --------------------------------------- .. automodule:: pyscf.pbc.gto.pseudo.parse_cp2k :members: :undoc-members: :show-inheritance: pyscf.pbc.gto.pseudo.pp module ------------------------------ .. automodule:: pyscf.pbc.gto.pseudo.pp :members: :undoc-members: :show-inheritance: pyscf.pbc.gto.pseudo.pp\_int module ----------------------------------- .. automodule:: pyscf.pbc.gto.pseudo.pp_int :members: :undoc-members: :show-inheritance: pyscf.pbc.gto.pseudo.split\_GTH\_POTENTIALS module -------------------------------------------------- .. automodule:: pyscf.pbc.gto.pseudo.split_GTH_POTENTIALS :members: :undoc-members: :show-inheritance: Module contents --------------- .. automodule:: pyscf.pbc.gto.pseudo :members: :undoc-members: :show-inheritance: <file_sep>/pyscf_api_docs/pyscf.prop.polarizability.rst pyscf.prop.polarizability package ================================= Submodules ---------- pyscf.prop.polarizability.rhf module ------------------------------------ .. automodule:: pyscf.prop.polarizability.rhf :members: :undoc-members: :show-inheritance: pyscf.prop.polarizability.rks module ------------------------------------ .. automodule:: pyscf.prop.polarizability.rks :members: :undoc-members: :show-inheritance: pyscf.prop.polarizability.uhf module ------------------------------------ .. automodule:: pyscf.prop.polarizability.uhf :members: :undoc-members: :show-inheritance: pyscf.prop.polarizability.uks module ------------------------------------ .. automodule:: pyscf.prop.polarizability.uks :members: :undoc-members: :show-inheritance: Module contents --------------- .. automodule:: pyscf.prop.polarizability :members: :undoc-members: :show-inheritance: <file_sep>/docs/_sources/pyscf_api_docs/pyscf.pbc.gto.basis.rst.txt pyscf.pbc.gto.basis package =========================== Submodules ---------- pyscf.pbc.gto.basis.parse\_cp2k module -------------------------------------- .. automodule:: pyscf.pbc.gto.basis.parse_cp2k :members: :undoc-members: :show-inheritance: pyscf.pbc.gto.basis.split\_BASIS\_MOLOPT module ----------------------------------------------- .. automodule:: pyscf.pbc.gto.basis.split_BASIS_MOLOPT :members: :undoc-members: :show-inheritance: pyscf.pbc.gto.basis.split\_GTH\_BASIS\_SETS module -------------------------------------------------- .. automodule:: pyscf.pbc.gto.basis.split_GTH_BASIS_SETS :members: :undoc-members: :show-inheritance: pyscf.pbc.gto.basis.split\_HFX\_BASIS module -------------------------------------------- .. automodule:: pyscf.pbc.gto.basis.split_HFX_BASIS :members: :undoc-members: :show-inheritance: Module contents --------------- .. automodule:: pyscf.pbc.gto.basis :members: :undoc-members: :show-inheritance: <file_sep>/docs/_sources/pyscf_api_docs/pyscf.prop.gtensor.rst.txt pyscf.prop.gtensor package ========================== Submodules ---------- pyscf.prop.gtensor.dhf module ----------------------------- .. automodule:: pyscf.prop.gtensor.dhf :members: :undoc-members: :show-inheritance: pyscf.prop.gtensor.uhf module ----------------------------- .. automodule:: pyscf.prop.gtensor.uhf :members: :undoc-members: :show-inheritance: pyscf.prop.gtensor.uks module ----------------------------- .. automodule:: pyscf.prop.gtensor.uks :members: :undoc-members: :show-inheritance: Module contents --------------- .. automodule:: pyscf.prop.gtensor :members: :undoc-members: :show-inheritance: <file_sep>/pyscf_api_docs/pyscf.pbc.cc.rst pyscf.pbc.cc package ==================== Submodules ---------- pyscf.pbc.cc.ccsd module ------------------------ .. automodule:: pyscf.pbc.cc.ccsd :members: :undoc-members: :show-inheritance: pyscf.pbc.cc.eom\_kccsd\_ghf module ----------------------------------- .. automodule:: pyscf.pbc.cc.eom_kccsd_ghf :members: :undoc-members: :show-inheritance: pyscf.pbc.cc.eom\_kccsd\_rhf module ----------------------------------- .. automodule:: pyscf.pbc.cc.eom_kccsd_rhf :members: :undoc-members: :show-inheritance: pyscf.pbc.cc.eom\_kccsd\_rhf\_ea module --------------------------------------- .. automodule:: pyscf.pbc.cc.eom_kccsd_rhf_ea :members: :undoc-members: :show-inheritance: pyscf.pbc.cc.eom\_kccsd\_rhf\_ip module --------------------------------------- .. automodule:: pyscf.pbc.cc.eom_kccsd_rhf_ip :members: :undoc-members: :show-inheritance: pyscf.pbc.cc.eom\_kccsd\_uhf module ----------------------------------- .. automodule:: pyscf.pbc.cc.eom_kccsd_uhf :members: :undoc-members: :show-inheritance: pyscf.pbc.cc.kccsd module ------------------------- .. automodule:: pyscf.pbc.cc.kccsd :members: :undoc-members: :show-inheritance: pyscf.pbc.cc.kccsd\_rhf module ------------------------------ .. automodule:: pyscf.pbc.cc.kccsd_rhf :members: :undoc-members: :show-inheritance: pyscf.pbc.cc.kccsd\_t module ---------------------------- .. automodule:: pyscf.pbc.cc.kccsd_t :members: :undoc-members: :show-inheritance: pyscf.pbc.cc.kccsd\_t\_rhf module --------------------------------- .. automodule:: pyscf.pbc.cc.kccsd_t_rhf :members: :undoc-members: :show-inheritance: pyscf.pbc.cc.kccsd\_t\_rhf\_slow module --------------------------------------- .. automodule:: pyscf.pbc.cc.kccsd_t_rhf_slow :members: :undoc-members: :show-inheritance: pyscf.pbc.cc.kccsd\_uhf module ------------------------------ .. automodule:: pyscf.pbc.cc.kccsd_uhf :members: :undoc-members: :show-inheritance: pyscf.pbc.cc.kintermediates module ---------------------------------- .. automodule:: pyscf.pbc.cc.kintermediates :members: :undoc-members: :show-inheritance: pyscf.pbc.cc.kintermediates\_rhf module --------------------------------------- .. automodule:: pyscf.pbc.cc.kintermediates_rhf :members: :undoc-members: :show-inheritance: pyscf.pbc.cc.kintermediates\_uhf module --------------------------------------- .. automodule:: pyscf.pbc.cc.kintermediates_uhf :members: :undoc-members: :show-inheritance: pyscf.pbc.cc.kuccsd\_rdm module ------------------------------- .. automodule:: pyscf.pbc.cc.kuccsd_rdm :members: :undoc-members: :show-inheritance: Module contents --------------- .. automodule:: pyscf.pbc.cc :members: :undoc-members: :show-inheritance: <file_sep>/docs/_sources/pyscf_api_docs/pyscf.rt.rst.txt pyscf.rt package ================ Submodules ---------- pyscf.rt.tdfields module ------------------------ .. automodule:: pyscf.rt.tdfields :members: :undoc-members: :show-inheritance: pyscf.rt.tdscf module --------------------- .. automodule:: pyscf.rt.tdscf :members: :undoc-members: :show-inheritance: Module contents --------------- .. automodule:: pyscf.rt :members: :undoc-members: :show-inheritance: <file_sep>/pyscf_api_docs/pyscf.dftd3.rst pyscf.dftd3 package =================== Submodules ---------- pyscf.dftd3.itrf module ----------------------- .. automodule:: pyscf.dftd3.itrf :members: :undoc-members: :show-inheritance: Module contents --------------- .. automodule:: pyscf.dftd3 :members: :undoc-members: :show-inheritance: <file_sep>/pyscf_api_docs/pyscf.pbc.scf.rst pyscf.pbc.scf package ===================== Submodules ---------- pyscf.pbc.scf.addons module --------------------------- .. automodule:: pyscf.pbc.scf.addons :members: :undoc-members: :show-inheritance: pyscf.pbc.scf.chkfile module ---------------------------- .. automodule:: pyscf.pbc.scf.chkfile :members: :undoc-members: :show-inheritance: pyscf.pbc.scf.cphf module ------------------------- .. automodule:: pyscf.pbc.scf.cphf :members: :undoc-members: :show-inheritance: pyscf.pbc.scf.ghf module ------------------------ .. automodule:: pyscf.pbc.scf.ghf :members: :undoc-members: :show-inheritance: pyscf.pbc.scf.hf module ----------------------- .. automodule:: pyscf.pbc.scf.hf :members: :undoc-members: :show-inheritance: pyscf.pbc.scf.kghf module ------------------------- .. automodule:: pyscf.pbc.scf.kghf :members: :undoc-members: :show-inheritance: pyscf.pbc.scf.khf module ------------------------ .. automodule:: pyscf.pbc.scf.khf :members: :undoc-members: :show-inheritance: pyscf.pbc.scf.krohf module -------------------------- .. automodule:: pyscf.pbc.scf.krohf :members: :undoc-members: :show-inheritance: pyscf.pbc.scf.kuhf module ------------------------- .. automodule:: pyscf.pbc.scf.kuhf :members: :undoc-members: :show-inheritance: pyscf.pbc.scf.newton\_ah module ------------------------------- .. automodule:: pyscf.pbc.scf.newton_ah :members: :undoc-members: :show-inheritance: pyscf.pbc.scf.rohf module ------------------------- .. automodule:: pyscf.pbc.scf.rohf :members: :undoc-members: :show-inheritance: pyscf.pbc.scf.scfint module --------------------------- .. automodule:: pyscf.pbc.scf.scfint :members: :undoc-members: :show-inheritance: pyscf.pbc.scf.stability module ------------------------------ .. automodule:: pyscf.pbc.scf.stability :members: :undoc-members: :show-inheritance: pyscf.pbc.scf.uhf module ------------------------ .. automodule:: pyscf.pbc.scf.uhf :members: :undoc-members: :show-inheritance: Module contents --------------- .. automodule:: pyscf.pbc.scf :members: :undoc-members: :show-inheritance: <file_sep>/pyscf_api_docs/pyscf.gto.rst pyscf.gto package ================= Subpackages ----------- .. toctree:: :maxdepth: 4 pyscf.gto.basis Submodules ---------- pyscf.gto.cmd\_args module -------------------------- .. automodule:: pyscf.gto.cmd_args :members: :undoc-members: :show-inheritance: pyscf.gto.ecp module -------------------- .. automodule:: pyscf.gto.ecp :members: :undoc-members: :show-inheritance: pyscf.gto.eval\_gto module -------------------------- .. automodule:: pyscf.gto.eval_gto :members: :undoc-members: :show-inheritance: pyscf.gto.ft\_ao module ----------------------- .. automodule:: pyscf.gto.ft_ao :members: :undoc-members: :show-inheritance: pyscf.gto.mole module --------------------- .. automodule:: pyscf.gto.mole :members: :undoc-members: :show-inheritance: pyscf.gto.moleintor module -------------------------- .. automodule:: pyscf.gto.moleintor :members: :undoc-members: :show-inheritance: pyscf.gto.pp\_int module ------------------------ .. automodule:: pyscf.gto.pp_int :members: :undoc-members: :show-inheritance: Module contents --------------- .. automodule:: pyscf.gto :members: :undoc-members: :show-inheritance: <file_sep>/docs/_sources/pyscf_api_docs/pyscf.pbc.gw.rst.txt pyscf.pbc.gw package ==================== Submodules ---------- pyscf.pbc.gw.gw\_slow module ---------------------------- .. automodule:: pyscf.pbc.gw.gw_slow :members: :undoc-members: :show-inheritance: pyscf.pbc.gw.kgw\_slow module ----------------------------- .. automodule:: pyscf.pbc.gw.kgw_slow :members: :undoc-members: :show-inheritance: pyscf.pbc.gw.kgw\_slow\_supercell module ---------------------------------------- .. automodule:: pyscf.pbc.gw.kgw_slow_supercell :members: :undoc-members: :show-inheritance: Module contents --------------- .. automodule:: pyscf.pbc.gw :members: :undoc-members: :show-inheritance: <file_sep>/docs/_sources/pyscf_api_docs/pyscf.pbc.ci.rst.txt pyscf.pbc.ci package ==================== Submodules ---------- pyscf.pbc.ci.cisd module ------------------------ .. automodule:: pyscf.pbc.ci.cisd :members: :undoc-members: :show-inheritance: pyscf.pbc.ci.kcis\_rhf module ----------------------------- .. automodule:: pyscf.pbc.ci.kcis_rhf :members: :undoc-members: :show-inheritance: Module contents --------------- .. automodule:: pyscf.pbc.ci :members: :undoc-members: :show-inheritance: <file_sep>/pyscf_api_docs/pyscf.cornell_shci.rst pyscf.cornell\_shci package =========================== Submodules ---------- pyscf.cornell\_shci.shci module ------------------------------- .. automodule:: pyscf.cornell_shci.shci :members: :undoc-members: :show-inheritance: pyscf.cornell\_shci.symmetry module ----------------------------------- .. automodule:: pyscf.cornell_shci.symmetry :members: :undoc-members: :show-inheritance: Module contents --------------- .. automodule:: pyscf.cornell_shci :members: :undoc-members: :show-inheritance: <file_sep>/pyscf_api_docs/pyscf.semiempirical.rst pyscf.semiempirical package =========================== Submodules ---------- pyscf.semiempirical.am1 module ------------------------------ .. automodule:: pyscf.semiempirical.am1 :members: :undoc-members: :show-inheritance: pyscf.semiempirical.mindo3 module --------------------------------- .. automodule:: pyscf.semiempirical.mindo3 :members: :undoc-members: :show-inheritance: pyscf.semiempirical.mopac\_param module --------------------------------------- .. automodule:: pyscf.semiempirical.mopac_param :members: :undoc-members: :show-inheritance: pyscf.semiempirical.rmindo3\_grad module ---------------------------------------- .. automodule:: pyscf.semiempirical.rmindo3_grad :members: :undoc-members: :show-inheritance: pyscf.semiempirical.umindo3\_grad module ---------------------------------------- .. automodule:: pyscf.semiempirical.umindo3_grad :members: :undoc-members: :show-inheritance: Module contents --------------- .. automodule:: pyscf.semiempirical :members: :undoc-members: :show-inheritance: <file_sep>/docs/_sources/pyscf_api_docs/pyscf.scf.rst.txt pyscf.scf package ================= Submodules ---------- pyscf.scf.addons module ----------------------- .. automodule:: pyscf.scf.addons :members: :undoc-members: :show-inheritance: pyscf.scf.atom\_hf module ------------------------- .. automodule:: pyscf.scf.atom_hf :members: :undoc-members: :show-inheritance: pyscf.scf.chkfile module ------------------------ .. automodule:: pyscf.scf.chkfile :members: :undoc-members: :show-inheritance: pyscf.scf.cphf module --------------------- .. automodule:: pyscf.scf.cphf :members: :undoc-members: :show-inheritance: pyscf.scf.dhf module -------------------- .. automodule:: pyscf.scf.dhf :members: :undoc-members: :show-inheritance: pyscf.scf.diis module --------------------- .. automodule:: pyscf.scf.diis :members: :undoc-members: :show-inheritance: pyscf.scf.ghf module -------------------- .. automodule:: pyscf.scf.ghf :members: :undoc-members: :show-inheritance: pyscf.scf.ghf\_symm module -------------------------- .. automodule:: pyscf.scf.ghf_symm :members: :undoc-members: :show-inheritance: pyscf.scf.hf module ------------------- .. automodule:: pyscf.scf.hf :members: :undoc-members: :show-inheritance: pyscf.scf.hf\_symm module ------------------------- .. automodule:: pyscf.scf.hf_symm :members: :undoc-members: :show-inheritance: pyscf.scf.jk module ------------------- .. automodule:: pyscf.scf.jk :members: :undoc-members: :show-inheritance: pyscf.scf.newton\_ah module --------------------------- .. automodule:: pyscf.scf.newton_ah :members: :undoc-members: :show-inheritance: pyscf.scf.rohf module --------------------- .. automodule:: pyscf.scf.rohf :members: :undoc-members: :show-inheritance: pyscf.scf.stability module -------------------------- .. automodule:: pyscf.scf.stability :members: :undoc-members: :show-inheritance: pyscf.scf.stability\_slow module -------------------------------- .. automodule:: pyscf.scf.stability_slow :members: :undoc-members: :show-inheritance: pyscf.scf.ucphf module ---------------------- .. automodule:: pyscf.scf.ucphf :members: :undoc-members: :show-inheritance: pyscf.scf.uhf module -------------------- .. automodule:: pyscf.scf.uhf :members: :undoc-members: :show-inheritance: pyscf.scf.uhf\_symm module -------------------------- .. automodule:: pyscf.scf.uhf_symm :members: :undoc-members: :show-inheritance: pyscf.scf.x2c module -------------------- .. automodule:: pyscf.scf.x2c :members: :undoc-members: :show-inheritance: Module contents --------------- .. automodule:: pyscf.scf :members: :undoc-members: :show-inheritance: <file_sep>/pyscf_api_docs/pyscf.ci.rst pyscf.ci package ================ Submodules ---------- pyscf.ci.addons module ---------------------- .. automodule:: pyscf.ci.addons :members: :undoc-members: :show-inheritance: pyscf.ci.cisd module -------------------- .. automodule:: pyscf.ci.cisd :members: :undoc-members: :show-inheritance: pyscf.ci.gcisd module --------------------- .. automodule:: pyscf.ci.gcisd :members: :undoc-members: :show-inheritance: pyscf.ci.ucisd module --------------------- .. automodule:: pyscf.ci.ucisd :members: :undoc-members: :show-inheritance: Module contents --------------- .. automodule:: pyscf.ci :members: :undoc-members: :show-inheritance: <file_sep>/docs/_sources/pyscf_api_docs/pyscf.prop.ssc.rst.txt pyscf.prop.ssc package ====================== Submodules ---------- pyscf.prop.ssc.dhf module ------------------------- .. automodule:: pyscf.prop.ssc.dhf :members: :undoc-members: :show-inheritance: pyscf.prop.ssc.rhf module ------------------------- .. automodule:: pyscf.prop.ssc.rhf :members: :undoc-members: :show-inheritance: pyscf.prop.ssc.rks module ------------------------- .. automodule:: pyscf.prop.ssc.rks :members: :undoc-members: :show-inheritance: pyscf.prop.ssc.uhf module ------------------------- .. automodule:: pyscf.prop.ssc.uhf :members: :undoc-members: :show-inheritance: pyscf.prop.ssc.uks module ------------------------- .. automodule:: pyscf.prop.ssc.uks :members: :undoc-members: :show-inheritance: Module contents --------------- .. automodule:: pyscf.prop.ssc :members: :undoc-members: :show-inheritance: <file_sep>/pyscf_api_docs/pyscf.prop.zfs.rst pyscf.prop.zfs package ====================== Submodules ---------- pyscf.prop.zfs.uhf module ------------------------- .. automodule:: pyscf.prop.zfs.uhf :members: :undoc-members: :show-inheritance: Module contents --------------- .. automodule:: pyscf.prop.zfs :members: :undoc-members: :show-inheritance: <file_sep>/docs/pyscf_api_docs/pyscf.tools/index.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <meta name="viewport" content="width=device-width,initial-scale=1"> <meta http-equiv="x-ua-compatible" content="ie=edge"> <meta name="lang:clipboard.copy" content="Copy to clipboard"> <meta name="lang:clipboard.copied" content="Copied to clipboard"> <meta name="lang:search.language" content="en"> <meta name="lang:search.pipeline.stopwords" content="True"> <meta name="lang:search.pipeline.trimmer" content="True"> <meta name="lang:search.result.none" content="No matching documents"> <meta name="lang:search.result.one" content="1 matching document"> <meta name="lang:search.result.other" content="# matching documents"> <meta name="lang:search.tokenizer" content="[\s\-]+"> <link href="https://fonts.gstatic.com/" rel="preconnect" crossorigin> <link href="https://fonts.googleapis.com/css?family=Roboto+Mono:400,500,700|Roboto:300,400,400i,700&display=fallback" rel="stylesheet"> <style> body, input { font-family: "Roboto", "Helvetica Neue", Helvetica, Arial, sans-serif } code, kbd, pre { font-family: "Roboto Mono", "Courier New", Courier, monospace } </style> <link rel="stylesheet" href="../../_static/stylesheets/application.css"/> <link rel="stylesheet" href="../../_static/stylesheets/application-palette.css"/> <link rel="stylesheet" href="../../_static/stylesheets/application-fixes.css"/> <link rel="stylesheet" href="../../_static/fonts/material-icons.css"/> <meta name="theme-color" content="#3f51b5"> <script src="../../_static/javascripts/modernizr.js"></script> <title>pyscf.tools package &#8212; PySCF documentation</title> <link rel="stylesheet" href="../../_static/pygments.css" type="text/css" /> <link rel="stylesheet" href="../../_static/material.css" type="text/css" /> <script id="documentation_options" data-url_root="../../" src="../../_static/documentation_options.js"></script> <script src="../../_static/jquery.js"></script> <script src="../../_static/underscore.js"></script> <script src="../../_static/doctools.js"></script> <script async="async" src="https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.7/latest.js?config=TeX-AMS-MML_HTMLorMML"></script> <link rel="author" title="About these documents" href="../../about/" /> <link rel="index" title="Index" href="../../genindex/" /> <link rel="search" title="Search" href="../../search/" /> <link rel="next" title="pyscf.x2c package" href="../pyscf.x2c/" /> <link rel="prev" title="pyscf.tdscf package" href="../pyscf.tdscf/" /> <style type="text/css"> ul.ablog-archive { list-style: none; overflow: auto; margin-left: 0px; } ul.ablog-archive li { float: left; margin-right: 5px; font-size: 80%; } ul.postlist a { font-style: italic; } ul.postlist-style-disc { list-style-type: disc; } ul.postlist-style-none { list-style-type: none; } ul.postlist-style-circle { list-style-type: circle; } </style> </head> <body dir=ltr data-md-color-primary=indigo data-md-color-accent=yellow> <svg class="md-svg"> <defs data-children-count="0"> <svg xmlns="http://www.w3.org/2000/svg" width="416" height="448" viewBox="0 0 416 448" id="__github"><path fill="currentColor" d="M160 304q0 10-3.125 20.5t-10.75 19T128 352t-18.125-8.5-10.75-19T96 304t3.125-20.5 10.75-19T128 256t18.125 8.5 10.75 19T160 304zm160 0q0 10-3.125 20.5t-10.75 19T288 352t-18.125-8.5-10.75-19T256 304t3.125-20.5 10.75-19T288 256t18.125 8.5 10.75 19T320 304zm40 0q0-30-17.25-51T296 232q-10.25 0-48.75 5.25Q229.5 240 208 240t-39.25-2.75Q130.75 232 120 232q-29.5 0-46.75 21T56 304q0 22 8 38.375t20.25 25.75 30.5 15 35 7.375 37.25 1.75h42q20.5 0 37.25-1.75t35-7.375 30.5-15 20.25-25.75T360 304zm56-44q0 51.75-15.25 82.75-9.5 19.25-26.375 33.25t-35.25 21.5-42.5 11.875-42.875 5.5T212 416q-19.5 0-35.5-.75t-36.875-3.125-38.125-7.5-34.25-12.875T37 371.5t-21.5-28.75Q0 312 0 260q0-59.25 34-99-6.75-20.5-6.75-42.5 0-29 12.75-54.5 27 0 47.5 9.875t47.25 30.875Q171.5 96 212 96q37 0 70 8 26.25-20.5 46.75-30.25T376 64q12.75 25.5 12.75 54.5 0 21.75-6.75 42 34 40 34 99.5z"/></svg> </defs> </svg> <input class="md-toggle" data-md-toggle="drawer" type="checkbox" id="__drawer"> <input class="md-toggle" data-md-toggle="search" type="checkbox" id="__search"> <label class="md-overlay" data-md-component="overlay" for="__drawer"></label> <a href="#pyscf_api_docs/pyscf.tools" tabindex="1" class="md-skip"> Skip to content </a> <header class="md-header" data-md-component="header"> <nav class="md-header-nav md-grid"> <div class="md-flex navheader"> <div class="md-flex__cell md-flex__cell--shrink"> <a href="../../" title="PySCF documentation" class="md-header-nav__button md-logo"> &nbsp; </a> </div> <div class="md-flex__cell md-flex__cell--shrink"> <label class="md-icon md-icon--menu md-header-nav__button" for="__drawer"></label> </div> <div class="md-flex__cell md-flex__cell--stretch"> <div class="md-flex__ellipsis md-header-nav__title" data-md-component="title"> <span class="md-header-nav__topic">PySCF Docs</span> <span class="md-header-nav__topic"> pyscf.tools package </span> </div> </div> <div class="md-flex__cell md-flex__cell--shrink"> <label class="md-icon md-icon--search md-header-nav__button" for="__search"></label> <div class="md-search" data-md-component="search" role="dialog"> <label class="md-search__overlay" for="__search"></label> <div class="md-search__inner" role="search"> <form class="md-search__form" action="../../search/" method="GET" name="search"> <input type="text" class="md-search__input" name="q" placeholder="Search" autocapitalize="off" autocomplete="off" spellcheck="false" data-md-component="query" data-md-state="active"> <label class="md-icon md-search__icon" for="__search"></label> <button type="reset" class="md-icon md-search__icon" data-md-component="reset" tabindex="-1"> &#xE5CD; </button> </form> <div class="md-search__output"> <div class="md-search__scrollwrap" data-md-scrollfix> <div class="md-search-result" data-md-component="result"> <div class="md-search-result__meta"> Type to start searching </div> <ol class="md-search-result__list"></ol> </div> </div> </div> </div> </div> </div> <script src="../../_static/javascripts/version_dropdown.js"></script> <script> var json_loc = "../../"versions.json"", target_loc = "../../../", text = "Versions"; $( document ).ready( add_version_dropdown(json_loc, target_loc, text)); </script> </div> </nav> </header> <div class="md-container"> <nav class="md-tabs" data-md-component="tabs"> <div class="md-tabs__inner md-grid"> <ul class="md-tabs__list"> <li class="md-tabs__item"><a href="../../" class="md-tabs__link">PySCF documentation</a></li> <li class="md-tabs__item"><a href="../../about/" class="md-tabs__link">About</a></li> <li class="md-tabs__item"><a href="../../blog_wrapper/" class="md-tabs__link">Blog</a></li> <li class="md-tabs__item"><a href="../modules/" class="md-tabs__link">API Docs</a></li> <li class="md-tabs__item"><a href="../pyscf/" class="md-tabs__link">pyscf package</a></li> </ul> </div> </nav> <main class="md-main"> <div class="md-main__inner md-grid" data-md-component="container"> <div class="md-sidebar md-sidebar--primary" data-md-component="navigation"> <div class="md-sidebar__scrollwrap"> <div class="md-sidebar__inner"> <nav class="md-nav md-nav--primary" data-md-level="0"> <label class="md-nav__title md-nav__title--site" for="__drawer"> <a href="../../" title="PySCF documentation" class="md-nav__button md-logo"> <img src="../../_static/" alt=" logo" width="48" height="48"> </a> <a href="../../" title="PySCF documentation">PySCF Docs</a> </label> <ul class="md-nav__list"> <li class="md-nav__item"> <a href="../../about/" class="md-nav__link">About</a> </li> <li class="md-nav__item"> <a href="../../blog_wrapper/" class="md-nav__link">Blog</a> </li> <li class="md-nav__item"> <a href="../pyscf/" class="md-nav__link">API Docs</a> <ul class="md-nav__list"> <li class="md-nav__item"> <a href="../pyscf/#subpackages" class="md-nav__link">Subpackages</a> </li> <li class="md-nav__item"> <a href="../pyscf/#submodules" class="md-nav__link">Submodules</a> </li> <li class="md-nav__item"> <a href="../pyscf/#module-pyscf.post_scf" class="md-nav__link">pyscf.post_scf module</a> </li> <li class="md-nav__item"> <a href="../pyscf/#module-pyscf" class="md-nav__link">Module contents</a> </li></ul> </li> </ul> </nav> </div> </div> </div> <div class="md-sidebar md-sidebar--secondary" data-md-component="toc"> <div class="md-sidebar__scrollwrap"> <div class="md-sidebar__inner"> <nav class="md-nav md-nav--secondary"> <label class="md-nav__title" for="__toc">Contents</label> <ul class="md-nav__list" data-md-scrollfix=""> <li class="md-nav__item"><a href="#pyscf-api-docs-pyscf-tools--page-root" class="md-nav__link">pyscf.tools package</a><nav class="md-nav"> <ul class="md-nav__list"> <li class="md-nav__item"><a href="#submodules" class="md-nav__link">Submodules</a> </li> <li class="md-nav__item"><a href="#module-pyscf.tools.c60struct" class="md-nav__link">pyscf.tools.c60struct module</a> </li> <li class="md-nav__item"><a href="#module-pyscf.tools.chgcar" class="md-nav__link">pyscf.tools.chgcar module</a> </li> <li class="md-nav__item"><a href="#module-pyscf.tools.chkfile_util" class="md-nav__link">pyscf.tools.chkfile_util module</a> </li> <li class="md-nav__item"><a href="#module-pyscf.tools.cubegen" class="md-nav__link">pyscf.tools.cubegen module</a> </li> <li class="md-nav__item"><a href="#module-pyscf.tools.dump_mat" class="md-nav__link">pyscf.tools.dump_mat module</a> </li> <li class="md-nav__item"><a href="#module-pyscf.tools.fcidump" class="md-nav__link">pyscf.tools.fcidump module</a> </li> <li class="md-nav__item"><a href="#module-pyscf.tools.mo_mapping" class="md-nav__link">pyscf.tools.mo_mapping module</a> </li> <li class="md-nav__item"><a href="#module-pyscf.tools.molden" class="md-nav__link">pyscf.tools.molden module</a> </li> <li class="md-nav__item"><a href="#pyscf-tools-rhf-newtonraphson-module" class="md-nav__link">pyscf.tools.rhf_newtonraphson module</a> </li> <li class="md-nav__item"><a href="#module-pyscf.tools.ring" class="md-nav__link">pyscf.tools.ring module</a> </li> <li class="md-nav__item"><a href="#module-pyscf.tools.wfn_format" class="md-nav__link">pyscf.tools.wfn_format module</a> </li> <li class="md-nav__item"><a href="#module-pyscf.tools" class="md-nav__link">Module contents</a> </li></ul> </nav> </li> <li class="md-nav__item"><a class="md-nav__extra_link" href="../../_sources/pyscf_api_docs/pyscf.tools.rst.txt">Show Source</a> </li> <li id="searchbox" class="md-nav__item"></li> </ul> </nav> </div> </div> </div> <div class="md-content"> <article class="md-content__inner md-typeset" role="main"> <div class="section" id="pyscf-tools-package"> <h1>pyscf.tools package<a class="headerlink" href="#pyscf-tools-package" title="Permalink to this headline">¶</a></h1> <div class="section" id="submodules"> <h2>Submodules<a class="headerlink" href="#submodules" title="Permalink to this headline">¶</a></h2> </div> <div class="section" id="module-pyscf.tools.c60struct"> <span id="pyscf-tools-c60struct-module"></span><h2>pyscf.tools.c60struct module<a class="headerlink" href="#module-pyscf.tools.c60struct" title="Permalink to this headline">¶</a></h2> <dl class="py function"> <dt id="pyscf.tools.c60struct.make12"> <code class="sig-prename descclassname">pyscf.tools.c60struct.</code><code class="sig-name descname">make12</code><span class="sig-paren">(</span><em class="sig-param"><span class="n">b</span></em><span class="sig-paren">)</span><a class="headerlink" href="#pyscf.tools.c60struct.make12" title="Permalink to this definition">¶</a></dt> <dd></dd></dl> <dl class="py function"> <dt id="pyscf.tools.c60struct.make20"> <code class="sig-prename descclassname">pyscf.tools.c60struct.</code><code class="sig-name descname">make20</code><span class="sig-paren">(</span><em class="sig-param"><span class="n">b</span></em><span class="sig-paren">)</span><a class="headerlink" href="#pyscf.tools.c60struct.make20" title="Permalink to this definition">¶</a></dt> <dd></dd></dl> <dl class="py function"> <dt id="pyscf.tools.c60struct.make60"> <code class="sig-prename descclassname">pyscf.tools.c60struct.</code><code class="sig-name descname">make60</code><span class="sig-paren">(</span><em class="sig-param"><span class="n">b5</span></em>, <em class="sig-param"><span class="n">b6</span></em><span class="sig-paren">)</span><a class="headerlink" href="#pyscf.tools.c60struct.make60" title="Permalink to this definition">¶</a></dt> <dd></dd></dl> <dl class="py function"> <dt id="pyscf.tools.c60struct.r2edge"> <code class="sig-prename descclassname">pyscf.tools.c60struct.</code><code class="sig-name descname">r2edge</code><span class="sig-paren">(</span><em class="sig-param"><span class="n">ang</span></em>, <em class="sig-param"><span class="n">r</span></em><span class="sig-paren">)</span><a class="headerlink" href="#pyscf.tools.c60struct.r2edge" title="Permalink to this definition">¶</a></dt> <dd></dd></dl> <dl class="py function"> <dt id="pyscf.tools.c60struct.rotmaty"> <code class="sig-prename descclassname">pyscf.tools.c60struct.</code><code class="sig-name descname">rotmaty</code><span class="sig-paren">(</span><em class="sig-param"><span class="n">ang</span></em><span class="sig-paren">)</span><a class="headerlink" href="#pyscf.tools.c60struct.rotmaty" title="Permalink to this definition">¶</a></dt> <dd></dd></dl> <dl class="py function"> <dt id="pyscf.tools.c60struct.rotmatz"> <code class="sig-prename descclassname">pyscf.tools.c60struct.</code><code class="sig-name descname">rotmatz</code><span class="sig-paren">(</span><em class="sig-param"><span class="n">ang</span></em><span class="sig-paren">)</span><a class="headerlink" href="#pyscf.tools.c60struct.rotmatz" title="Permalink to this definition">¶</a></dt> <dd></dd></dl> </div> <div class="section" id="module-pyscf.tools.chgcar"> <span id="pyscf-tools-chgcar-module"></span><h2>pyscf.tools.chgcar module<a class="headerlink" href="#module-pyscf.tools.chgcar" title="Permalink to this headline">¶</a></h2> <p>Vasp CHGCAR file format</p> <p>See also <a class="reference external" href="https://cms.mpi.univie.ac.at/vasp/vasp/CHGCAR_file.html">https://cms.mpi.univie.ac.at/vasp/vasp/CHGCAR_file.html</a></p> <dl class="py class"> <dt id="pyscf.tools.chgcar.CHGCAR"> <em class="property">class </em><code class="sig-prename descclassname">pyscf.tools.chgcar.</code><code class="sig-name descname">CHGCAR</code><span class="sig-paren">(</span><em class="sig-param"><span class="n">cell</span></em>, <em class="sig-param"><span class="n">nx</span><span class="o">=</span><span class="default_value">60</span></em>, <em class="sig-param"><span class="n">ny</span><span class="o">=</span><span class="default_value">60</span></em>, <em class="sig-param"><span class="n">nz</span><span class="o">=</span><span class="default_value">60</span></em>, <em class="sig-param"><span class="n">resolution</span><span class="o">=</span><span class="default_value">None</span></em>, <em class="sig-param"><span class="n">margin</span><span class="o">=</span><span class="default_value">3.0</span></em><span class="sig-paren">)</span><a class="headerlink" href="#pyscf.tools.chgcar.CHGCAR" title="Permalink to this definition">¶</a></dt> <dd><p>Bases: <a class="reference internal" href="#pyscf.tools.cubegen.Cube" title="pyscf.tools.cubegen.Cube"><code class="xref py py-class docutils literal notranslate"><span class="pre">pyscf.tools.cubegen.Cube</span></code></a></p> <p>Read-write of the Vasp CHGCAR files</p> <dl class="py method"> <dt id="pyscf.tools.chgcar.CHGCAR.get_coords"> <code class="sig-name descname">get_coords</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#pyscf.tools.chgcar.CHGCAR.get_coords" title="Permalink to this definition">¶</a></dt> <dd><p>Result: set of coordinates to compute a field which is to be stored in the file.</p> </dd></dl> <dl class="py method"> <dt id="pyscf.tools.chgcar.CHGCAR.read"> <code class="sig-name descname">read</code><span class="sig-paren">(</span><em class="sig-param"><span class="n">chgcar_file</span></em><span class="sig-paren">)</span><a class="headerlink" href="#pyscf.tools.chgcar.CHGCAR.read" title="Permalink to this definition">¶</a></dt> <dd></dd></dl> <dl class="py method"> <dt id="pyscf.tools.chgcar.CHGCAR.write"> <code class="sig-name descname">write</code><span class="sig-paren">(</span><em class="sig-param"><span class="n">field</span></em>, <em class="sig-param"><span class="n">fname</span></em>, <em class="sig-param"><span class="n">comment</span><span class="o">=</span><span class="default_value">None</span></em><span class="sig-paren">)</span><a class="headerlink" href="#pyscf.tools.chgcar.CHGCAR.write" title="Permalink to this definition">¶</a></dt> <dd><p>Result: .vasp file with the field in the file fname.</p> </dd></dl> </dd></dl> <dl class="py function"> <dt id="pyscf.tools.chgcar.density"> <code class="sig-prename descclassname">pyscf.tools.chgcar.</code><code class="sig-name descname">density</code><span class="sig-paren">(</span><em class="sig-param"><span class="n">cell</span></em>, <em class="sig-param"><span class="n">outfile</span></em>, <em class="sig-param"><span class="n">dm</span></em>, <em class="sig-param"><span class="n">nx</span><span class="o">=</span><span class="default_value">60</span></em>, <em class="sig-param"><span class="n">ny</span><span class="o">=</span><span class="default_value">60</span></em>, <em class="sig-param"><span class="n">nz</span><span class="o">=</span><span class="default_value">60</span></em>, <em class="sig-param"><span class="n">resolution</span><span class="o">=</span><span class="default_value">None</span></em><span class="sig-paren">)</span><a class="headerlink" href="#pyscf.tools.chgcar.density" title="Permalink to this definition">¶</a></dt> <dd><p>Calculates electron density and write out in CHGCAR format.</p> <dl class="simple"> <dt>Args:</dt><dd><dl class="simple"> <dt>cell<span class="classifier">Mole or Cell object</span></dt><dd><p>Mole or pbc Cell. If Mole object is given, the program will guess a cubic lattice for the molecule.</p> </dd> <dt>outfile<span class="classifier">str</span></dt><dd><p>Name of Cube file to be written.</p> </dd> <dt>dm<span class="classifier">ndarray</span></dt><dd><p>Density matrix of molecule.</p> </dd> </dl> </dd> <dt>Kwargs:</dt><dd><dl class="simple"> <dt>nx<span class="classifier">int</span></dt><dd><p>Number of grid point divisions in x direction. Note this is function of the molecule’s size; a larger molecule will have a coarser representation than a smaller one for the same value.</p> </dd> <dt>ny<span class="classifier">int</span></dt><dd><p>Number of grid point divisions in y direction.</p> </dd> <dt>nz<span class="classifier">int</span></dt><dd><p>Number of grid point divisions in z direction.</p> </dd> </dl> </dd> <dt>Returns:</dt><dd><p>No return value. This function outputs a VASP chgcarlike file (with phase if desired)…it can be opened in VESTA or VMD or many other softwares</p> </dd> </dl> <p>Examples:</p> <div class="doctest highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="c1"># generates the first MO from the list of mo_coefficents </span> <span class="gp">&gt;&gt;&gt; </span><span class="kn">from</span> <span class="nn">pyscf.pbc</span> <span class="kn">import</span> <span class="n">gto</span><span class="p">,</span> <span class="n">scf</span> <span class="gp">&gt;&gt;&gt; </span><span class="kn">from</span> <span class="nn">pyscf.tools</span> <span class="kn">import</span> <span class="n">chgcar</span> <span class="gp">&gt;&gt;&gt; </span><span class="n">cell</span> <span class="o">=</span> <span class="n">gto</span><span class="o">.</span><span class="n">M</span><span class="p">(</span><span class="n">atom</span><span class="o">=</span><span class="s1">&#39;H 0 0 0; H 0 0 1&#39;</span><span class="p">,</span> <span class="n">a</span><span class="o">=</span><span class="n">numpy</span><span class="o">.</span><span class="n">eye</span><span class="p">(</span><span class="mi">3</span><span class="p">)</span><span class="o">*</span><span class="mi">3</span><span class="p">)</span> <span class="gp">&gt;&gt;&gt; </span><span class="n">mf</span> <span class="o">=</span> <span class="n">scf</span><span class="o">.</span><span class="n">RHF</span><span class="p">(</span><span class="n">cell</span><span class="p">)</span><span class="o">.</span><span class="n">run</span><span class="p">()</span> <span class="gp">&gt;&gt;&gt; </span><span class="n">chgcar</span><span class="o">.</span><span class="n">density</span><span class="p">(</span><span class="n">cell</span><span class="p">,</span> <span class="s1">&#39;h2.CHGCAR&#39;</span><span class="p">,</span> <span class="n">mf</span><span class="o">.</span><span class="n">make_rdm1</span><span class="p">())</span> </pre></div> </div> </dd></dl> <dl class="py function"> <dt id="pyscf.tools.chgcar.orbital"> <code class="sig-prename descclassname">pyscf.tools.chgcar.</code><code class="sig-name descname">orbital</code><span class="sig-paren">(</span><em class="sig-param"><span class="n">cell</span></em>, <em class="sig-param"><span class="n">outfile</span></em>, <em class="sig-param"><span class="n">coeff</span></em>, <em class="sig-param"><span class="n">nx</span><span class="o">=</span><span class="default_value">60</span></em>, <em class="sig-param"><span class="n">ny</span><span class="o">=</span><span class="default_value">60</span></em>, <em class="sig-param"><span class="n">nz</span><span class="o">=</span><span class="default_value">60</span></em>, <em class="sig-param"><span class="n">resolution</span><span class="o">=</span><span class="default_value">None</span></em><span class="sig-paren">)</span><a class="headerlink" href="#pyscf.tools.chgcar.orbital" title="Permalink to this definition">¶</a></dt> <dd><p>Calculate orbital value on real space grid and write out in CHGCAR format.</p> <dl class="simple"> <dt>Args:</dt><dd><dl class="simple"> <dt>cell<span class="classifier">Mole or Cell object</span></dt><dd><p>Mole or pbc Cell. If Mole object is given, the program will guess a cubic lattice for the molecule.</p> </dd> <dt>outfile<span class="classifier">str</span></dt><dd><p>Name of Cube file to be written.</p> </dd> <dt>dm<span class="classifier">ndarray</span></dt><dd><p>Density matrix of molecule.</p> </dd> </dl> </dd> <dt>Kwargs:</dt><dd><dl class="simple"> <dt>nx<span class="classifier">int</span></dt><dd><p>Number of grid point divisions in x direction. Note this is function of the molecule’s size; a larger molecule will have a coarser representation than a smaller one for the same value.</p> </dd> <dt>ny<span class="classifier">int</span></dt><dd><p>Number of grid point divisions in y direction.</p> </dd> <dt>nz<span class="classifier">int</span></dt><dd><p>Number of grid point divisions in z direction.</p> </dd> </dl> </dd> <dt>Returns:</dt><dd><p>No return value. This function outputs a VASP chgcarlike file (with phase if desired)…it can be opened in VESTA or VMD or many other softwares</p> </dd> </dl> <p>Examples:</p> <div class="doctest highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="c1"># generates the first MO from the list of mo_coefficents </span> <span class="gp">&gt;&gt;&gt; </span><span class="kn">from</span> <span class="nn">pyscf.pbc</span> <span class="kn">import</span> <span class="n">gto</span><span class="p">,</span> <span class="n">scf</span> <span class="gp">&gt;&gt;&gt; </span><span class="kn">from</span> <span class="nn">pyscf.tools</span> <span class="kn">import</span> <span class="n">chgcar</span> <span class="gp">&gt;&gt;&gt; </span><span class="n">cell</span> <span class="o">=</span> <span class="n">gto</span><span class="o">.</span><span class="n">M</span><span class="p">(</span><span class="n">atom</span><span class="o">=</span><span class="s1">&#39;H 0 0 0; H 0 0 1&#39;</span><span class="p">,</span> <span class="n">a</span><span class="o">=</span><span class="n">numpy</span><span class="o">.</span><span class="n">eye</span><span class="p">(</span><span class="mi">3</span><span class="p">)</span><span class="o">*</span><span class="mi">3</span><span class="p">)</span> <span class="gp">&gt;&gt;&gt; </span><span class="n">mf</span> <span class="o">=</span> <span class="n">scf</span><span class="o">.</span><span class="n">RHF</span><span class="p">(</span><span class="n">cell</span><span class="p">)</span><span class="o">.</span><span class="n">run</span><span class="p">()</span> <span class="gp">&gt;&gt;&gt; </span><span class="n">chgcar</span><span class="o">.</span><span class="n">orbital</span><span class="p">(</span><span class="n">cell</span><span class="p">,</span> <span class="s1">&#39;h2_mo1.CHGCAR&#39;</span><span class="p">,</span> <span class="n">mf</span><span class="o">.</span><span class="n">mo_coeff</span><span class="p">[:,</span><span class="mi">0</span><span class="p">])</span> </pre></div> </div> </dd></dl> </div> <div class="section" id="module-pyscf.tools.chkfile_util"> <span id="pyscf-tools-chkfile-util-module"></span><h2>pyscf.tools.chkfile_util module<a class="headerlink" href="#module-pyscf.tools.chkfile_util" title="Permalink to this headline">¶</a></h2> <dl class="py function"> <dt id="pyscf.tools.chkfile_util.dump_mo"> <code class="sig-prename descclassname">pyscf.tools.chkfile_util.</code><code class="sig-name descname">dump_mo</code><span class="sig-paren">(</span><em class="sig-param"><span class="n">filename</span></em>, <em class="sig-param"><span class="n">key</span><span class="o">=</span><span class="default_value">'scf'</span></em><span class="sig-paren">)</span><a class="headerlink" href="#pyscf.tools.chkfile_util.dump_mo" title="Permalink to this definition">¶</a></dt> <dd><p>Read scf/mcscf information from chkfile, then dump the orbital coefficients.</p> </dd></dl> <dl class="py function"> <dt id="pyscf.tools.chkfile_util.molden"> <code class="sig-prename descclassname">pyscf.tools.chkfile_util.</code><code class="sig-name descname">molden</code><span class="sig-paren">(</span><em class="sig-param"><span class="n">filename</span></em>, <em class="sig-param"><span class="n">key</span><span class="o">=</span><span class="default_value">'scf'</span></em><span class="sig-paren">)</span><a class="headerlink" href="#pyscf.tools.chkfile_util.molden" title="Permalink to this definition">¶</a></dt> <dd><p>Read scf/mcscf information from chkfile, then convert the scf/mcscf orbitals to molden format.</p> </dd></dl> <dl class="py function"> <dt id="pyscf.tools.chkfile_util.mulliken"> <code class="sig-prename descclassname">pyscf.tools.chkfile_util.</code><code class="sig-name descname">mulliken</code><span class="sig-paren">(</span><em class="sig-param"><span class="n">filename</span></em>, <em class="sig-param"><span class="n">key</span><span class="o">=</span><span class="default_value">'scf'</span></em><span class="sig-paren">)</span><a class="headerlink" href="#pyscf.tools.chkfile_util.mulliken" title="Permalink to this definition">¶</a></dt> <dd><p>Reading scf/mcscf information from chkfile, then do Mulliken population analysis for the density matrix</p> </dd></dl> </div> <div class="section" id="module-pyscf.tools.cubegen"> <span id="pyscf-tools-cubegen-module"></span><h2>pyscf.tools.cubegen module<a class="headerlink" href="#module-pyscf.tools.cubegen" title="Permalink to this headline">¶</a></h2> <p>Gaussian cube file format. Reference: <a class="reference external" href="http://paulbourke.net/dataformats/cube/">http://paulbourke.net/dataformats/cube/</a> <a class="reference external" href="https://h5cube-spec.readthedocs.io/en/latest/cubeformat.html">https://h5cube-spec.readthedocs.io/en/latest/cubeformat.html</a> <a class="reference external" href="http://gaussian.com/cubegen/">http://gaussian.com/cubegen/</a></p> <p>The output cube file has the following format</p> <p>Comment line Comment line N_atom Ox Oy Oz # number of atoms, followed by the coordinates of the origin N1 vx1 vy1 vz1 # number of grids along each axis, followed by the step size in x/y/z direction. N2 vx2 vy2 vz2 # … N3 vx3 vy3 vz3 # … Atom1 Z1 x y z # Atomic number, charge, and coordinates of the atom … # … AtomN ZN x y z # … Data on grids # (N1*N2) lines of records, each line has N3 elements</p> <dl class="py class"> <dt id="pyscf.tools.cubegen.Cube"> <em class="property">class </em><code class="sig-prename descclassname">pyscf.tools.cubegen.</code><code class="sig-name descname">Cube</code><span class="sig-paren">(</span><em class="sig-param"><span class="n">mol</span></em>, <em class="sig-param"><span class="n">nx</span><span class="o">=</span><span class="default_value">80</span></em>, <em class="sig-param"><span class="n">ny</span><span class="o">=</span><span class="default_value">80</span></em>, <em class="sig-param"><span class="n">nz</span><span class="o">=</span><span class="default_value">80</span></em>, <em class="sig-param"><span class="n">resolution</span><span class="o">=</span><span class="default_value">None</span></em>, <em class="sig-param"><span class="n">margin</span><span class="o">=</span><span class="default_value">3.0</span></em>, <em class="sig-param"><span class="n">origin</span><span class="o">=</span><span class="default_value">None</span></em>, <em class="sig-param"><span class="n">extent</span><span class="o">=</span><span class="default_value">None</span></em><span class="sig-paren">)</span><a class="headerlink" href="#pyscf.tools.cubegen.Cube" title="Permalink to this definition">¶</a></dt> <dd><p>Bases: <code class="xref py py-class docutils literal notranslate"><span class="pre">object</span></code></p> <p>Read-write of the Gaussian CUBE files</p> <dl class="simple"> <dt>Attributes:</dt><dd><dl class="simple"> <dt>nx<span class="classifier">int</span></dt><dd><p>Number of grid point divisions in x direction. Note this is function of the molecule’s size; a larger molecule will have a coarser representation than a smaller one for the same value. Conflicts to keyword resolution.</p> </dd> <dt>ny<span class="classifier">int</span></dt><dd><p>Number of grid point divisions in y direction.</p> </dd> <dt>nz<span class="classifier">int</span></dt><dd><p>Number of grid point divisions in z direction.</p> </dd> <dt>resolution: float</dt><dd><p>Resolution of the mesh grid in the cube box. If resolution is given in the input, the input nx/ny/nz have no effects. The value of nx/ny/nz will be determined by the resolution and the cube box size. The unit is Bohr.</p> </dd> </dl> </dd> </dl> <dl class="py method"> <dt id="pyscf.tools.cubegen.Cube.get_coords"> <code class="sig-name descname">get_coords</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#pyscf.tools.cubegen.Cube.get_coords" title="Permalink to this definition">¶</a></dt> <dd><p>Result: set of coordinates to compute a field which is to be stored in the file.</p> </dd></dl> <dl class="py method"> <dt id="pyscf.tools.cubegen.Cube.get_ngrids"> <code class="sig-name descname">get_ngrids</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#pyscf.tools.cubegen.Cube.get_ngrids" title="Permalink to this definition">¶</a></dt> <dd></dd></dl> <dl class="py method"> <dt id="pyscf.tools.cubegen.Cube.get_volume_element"> <code class="sig-name descname">get_volume_element</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#pyscf.tools.cubegen.Cube.get_volume_element" title="Permalink to this definition">¶</a></dt> <dd></dd></dl> <dl class="py method"> <dt id="pyscf.tools.cubegen.Cube.read"> <code class="sig-name descname">read</code><span class="sig-paren">(</span><em class="sig-param"><span class="n">cube_file</span></em><span class="sig-paren">)</span><a class="headerlink" href="#pyscf.tools.cubegen.Cube.read" title="Permalink to this definition">¶</a></dt> <dd></dd></dl> <dl class="py method"> <dt id="pyscf.tools.cubegen.Cube.write"> <code class="sig-name descname">write</code><span class="sig-paren">(</span><em class="sig-param"><span class="n">field</span></em>, <em class="sig-param"><span class="n">fname</span></em>, <em class="sig-param"><span class="n">comment</span><span class="o">=</span><span class="default_value">None</span></em><span class="sig-paren">)</span><a class="headerlink" href="#pyscf.tools.cubegen.Cube.write" title="Permalink to this definition">¶</a></dt> <dd><p>Result: .cube file with the field in the file fname.</p> </dd></dl> </dd></dl> <dl class="py function"> <dt id="pyscf.tools.cubegen.density"> <code class="sig-prename descclassname">pyscf.tools.cubegen.</code><code class="sig-name descname">density</code><span class="sig-paren">(</span><em class="sig-param"><span class="n">mol</span></em>, <em class="sig-param"><span class="n">outfile</span></em>, <em class="sig-param"><span class="n">dm</span></em>, <em class="sig-param"><span class="n">nx</span><span class="o">=</span><span class="default_value">80</span></em>, <em class="sig-param"><span class="n">ny</span><span class="o">=</span><span class="default_value">80</span></em>, <em class="sig-param"><span class="n">nz</span><span class="o">=</span><span class="default_value">80</span></em>, <em class="sig-param"><span class="n">resolution</span><span class="o">=</span><span class="default_value">None</span></em>, <em class="sig-param"><span class="n">margin</span><span class="o">=</span><span class="default_value">3.0</span></em><span class="sig-paren">)</span><a class="headerlink" href="#pyscf.tools.cubegen.density" title="Permalink to this definition">¶</a></dt> <dd><p>Calculates electron density and write out in cube format.</p> <dl class="simple"> <dt>Args:</dt><dd><dl class="simple"> <dt>mol<span class="classifier">Mole</span></dt><dd><p>Molecule to calculate the electron density for.</p> </dd> <dt>outfile<span class="classifier">str</span></dt><dd><p>Name of Cube file to be written.</p> </dd> <dt>dm<span class="classifier">ndarray</span></dt><dd><p>Density matrix of molecule.</p> </dd> </dl> </dd> <dt>Kwargs:</dt><dd><dl class="simple"> <dt>nx<span class="classifier">int</span></dt><dd><p>Number of grid point divisions in x direction. Note this is function of the molecule’s size; a larger molecule will have a coarser representation than a smaller one for the same value. Conflicts to keyword resolution.</p> </dd> <dt>ny<span class="classifier">int</span></dt><dd><p>Number of grid point divisions in y direction.</p> </dd> <dt>nz<span class="classifier">int</span></dt><dd><p>Number of grid point divisions in z direction.</p> </dd> <dt>resolution: float</dt><dd><p>Resolution of the mesh grid in the cube box. If resolution is given in the input, the input nx/ny/nz have no effects. The value of nx/ny/nz will be determined by the resolution and the cube box size.</p> </dd> </dl> </dd> </dl> </dd></dl> <dl class="py function"> <dt id="pyscf.tools.cubegen.mep"> <code class="sig-prename descclassname">pyscf.tools.cubegen.</code><code class="sig-name descname">mep</code><span class="sig-paren">(</span><em class="sig-param"><span class="n">mol</span></em>, <em class="sig-param"><span class="n">outfile</span></em>, <em class="sig-param"><span class="n">dm</span></em>, <em class="sig-param"><span class="n">nx</span><span class="o">=</span><span class="default_value">80</span></em>, <em class="sig-param"><span class="n">ny</span><span class="o">=</span><span class="default_value">80</span></em>, <em class="sig-param"><span class="n">nz</span><span class="o">=</span><span class="default_value">80</span></em>, <em class="sig-param"><span class="n">resolution</span><span class="o">=</span><span class="default_value">None</span></em>, <em class="sig-param"><span class="n">margin</span><span class="o">=</span><span class="default_value">3.0</span></em><span class="sig-paren">)</span><a class="headerlink" href="#pyscf.tools.cubegen.mep" title="Permalink to this definition">¶</a></dt> <dd><p>Calculates the molecular electrostatic potential (MEP) and write out in cube format.</p> <dl class="simple"> <dt>Args:</dt><dd><dl class="simple"> <dt>mol<span class="classifier">Mole</span></dt><dd><p>Molecule to calculate the electron density for.</p> </dd> <dt>outfile<span class="classifier">str</span></dt><dd><p>Name of Cube file to be written.</p> </dd> <dt>dm<span class="classifier">ndarray</span></dt><dd><p>Density matrix of molecule.</p> </dd> </dl> </dd> <dt>Kwargs:</dt><dd><dl class="simple"> <dt>nx<span class="classifier">int</span></dt><dd><p>Number of grid point divisions in x direction. Note this is function of the molecule’s size; a larger molecule will have a coarser representation than a smaller one for the same value. Conflicts to keyword resolution.</p> </dd> <dt>ny<span class="classifier">int</span></dt><dd><p>Number of grid point divisions in y direction.</p> </dd> <dt>nz<span class="classifier">int</span></dt><dd><p>Number of grid point divisions in z direction.</p> </dd> <dt>resolution: float</dt><dd><p>Resolution of the mesh grid in the cube box. If resolution is given in the input, the input nx/ny/nz have no effects. The value of nx/ny/nz will be determined by the resolution and the cube box size.</p> </dd> </dl> </dd> </dl> </dd></dl> <dl class="py function"> <dt id="pyscf.tools.cubegen.orbital"> <code class="sig-prename descclassname">pyscf.tools.cubegen.</code><code class="sig-name descname">orbital</code><span class="sig-paren">(</span><em class="sig-param"><span class="n">mol</span></em>, <em class="sig-param"><span class="n">outfile</span></em>, <em class="sig-param"><span class="n">coeff</span></em>, <em class="sig-param"><span class="n">nx</span><span class="o">=</span><span class="default_value">80</span></em>, <em class="sig-param"><span class="n">ny</span><span class="o">=</span><span class="default_value">80</span></em>, <em class="sig-param"><span class="n">nz</span><span class="o">=</span><span class="default_value">80</span></em>, <em class="sig-param"><span class="n">resolution</span><span class="o">=</span><span class="default_value">None</span></em>, <em class="sig-param"><span class="n">margin</span><span class="o">=</span><span class="default_value">3.0</span></em><span class="sig-paren">)</span><a class="headerlink" href="#pyscf.tools.cubegen.orbital" title="Permalink to this definition">¶</a></dt> <dd><p>Calculate orbital value on real space grid and write out in cube format.</p> <dl class="simple"> <dt>Args:</dt><dd><dl class="simple"> <dt>mol<span class="classifier">Mole</span></dt><dd><p>Molecule to calculate the electron density for.</p> </dd> <dt>outfile<span class="classifier">str</span></dt><dd><p>Name of Cube file to be written.</p> </dd> <dt>coeff<span class="classifier">1D array</span></dt><dd><p>coeff coefficient.</p> </dd> </dl> </dd> <dt>Kwargs:</dt><dd><dl class="simple"> <dt>nx<span class="classifier">int</span></dt><dd><p>Number of grid point divisions in x direction. Note this is function of the molecule’s size; a larger molecule will have a coarser representation than a smaller one for the same value. Conflicts to keyword resolution.</p> </dd> <dt>ny<span class="classifier">int</span></dt><dd><p>Number of grid point divisions in y direction.</p> </dd> <dt>nz<span class="classifier">int</span></dt><dd><p>Number of grid point divisions in z direction.</p> </dd> <dt>resolution: float</dt><dd><p>Resolution of the mesh grid in the cube box. If resolution is given in the input, the input nx/ny/nz have no effects. The value of nx/ny/nz will be determined by the resolution and the cube box size.</p> </dd> </dl> </dd> </dl> </dd></dl> </div> <div class="section" id="module-pyscf.tools.dump_mat"> <span id="pyscf-tools-dump-mat-module"></span><h2>pyscf.tools.dump_mat module<a class="headerlink" href="#module-pyscf.tools.dump_mat" title="Permalink to this headline">¶</a></h2> <dl class="py function"> <dt id="pyscf.tools.dump_mat.dump_mo"> <code class="sig-prename descclassname">pyscf.tools.dump_mat.</code><code class="sig-name descname">dump_mo</code><span class="sig-paren">(</span><em class="sig-param"><span class="n">mol</span></em>, <em class="sig-param"><span class="n">c</span></em>, <em class="sig-param"><span class="n">label</span><span class="o">=</span><span class="default_value">None</span></em>, <em class="sig-param"><span class="n">ncol</span><span class="o">=</span><span class="default_value">5</span></em>, <em class="sig-param"><span class="n">digits</span><span class="o">=</span><span class="default_value">5</span></em>, <em class="sig-param"><span class="n">start</span><span class="o">=</span><span class="default_value">0</span></em><span class="sig-paren">)</span><a class="headerlink" href="#pyscf.tools.dump_mat.dump_mo" title="Permalink to this definition">¶</a></dt> <dd><p>Format print for orbitals</p> <dl class="simple"> <dt>Args:</dt><dd><dl class="simple"> <dt>stdout<span class="classifier">file object</span></dt><dd><p>eg sys.stdout, or stdout = open(‘/path/to/file’) or mol.stdout if mol is an object initialized from <code class="xref py py-class docutils literal notranslate"><span class="pre">gto.Mole</span></code></p> </dd> <dt>c<span class="classifier">numpy.ndarray</span></dt><dd><p>Orbitals, each column is an orbital</p> </dd> </dl> </dd> <dt>Kwargs:</dt><dd><dl class="simple"> <dt>label<span class="classifier">list of strings</span></dt><dd><p>Row labels (default is AO labels)</p> </dd> </dl> </dd> </dl> <p>Examples:</p> <div class="doctest highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">from</span> <span class="nn">pyscf</span> <span class="kn">import</span> <span class="n">gto</span> <span class="gp">&gt;&gt;&gt; </span><span class="n">mol</span> <span class="o">=</span> <span class="n">gto</span><span class="o">.</span><span class="n">M</span><span class="p">(</span><span class="n">atom</span><span class="o">=</span><span class="s1">&#39;C 0 0 0&#39;</span><span class="p">)</span> <span class="gp">&gt;&gt;&gt; </span><span class="n">mo</span> <span class="o">=</span> <span class="n">numpy</span><span class="o">.</span><span class="n">eye</span><span class="p">(</span><span class="n">mol</span><span class="o">.</span><span class="n">nao_nr</span><span class="p">())</span> <span class="gp">&gt;&gt;&gt; </span><span class="n">dump_mo</span><span class="p">(</span><span class="n">mol</span><span class="p">,</span> <span class="n">mo</span><span class="p">)</span> <span class="go"> #0 #1 #2 #3 #4 #5 #6 #7 #8 </span> <span class="go">0 C 1s 1.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00</span> <span class="go">0 C 2s 0.00 1.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00</span> <span class="go">0 C 3s 0.00 0.00 1.00 0.00 0.00 0.00 0.00 0.00 0.00</span> <span class="go">0 C 2px 0.00 0.00 0.00 1.00 0.00 0.00 0.00 0.00 0.00</span> <span class="go">0 C 2py 0.00 0.00 0.00 0.00 1.00 0.00 0.00 0.00 0.00</span> <span class="go">0 C 2pz 0.00 0.00 0.00 0.00 0.00 1.00 0.00 0.00 0.00</span> <span class="go">0 C 3px 0.00 0.00 0.00 0.00 0.00 0.00 1.00 0.00 0.00</span> <span class="go">0 C 3py 0.00 0.00 0.00 0.00 0.00 0.00 0.00 1.00 0.00</span> <span class="go">0 C 3pz 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 1.00</span> </pre></div> </div> </dd></dl> <dl class="py function"> <dt id="pyscf.tools.dump_mat.dump_rec"> <code class="sig-prename descclassname">pyscf.tools.dump_mat.</code><code class="sig-name descname">dump_rec</code><span class="sig-paren">(</span><em class="sig-param"><span class="n">stdout</span></em>, <em class="sig-param"><span class="n">c</span></em>, <em class="sig-param"><span class="n">label</span><span class="o">=</span><span class="default_value">None</span></em>, <em class="sig-param"><span class="n">label2</span><span class="o">=</span><span class="default_value">None</span></em>, <em class="sig-param"><span class="n">ncol</span><span class="o">=</span><span class="default_value">5</span></em>, <em class="sig-param"><span class="n">digits</span><span class="o">=</span><span class="default_value">5</span></em>, <em class="sig-param"><span class="n">start</span><span class="o">=</span><span class="default_value">0</span></em><span class="sig-paren">)</span><a class="headerlink" href="#pyscf.tools.dump_mat.dump_rec" title="Permalink to this definition">¶</a></dt> <dd><p>Print an array in rectangular format</p> <dl class="simple"> <dt>Args:</dt><dd><dl class="simple"> <dt>stdout<span class="classifier">file object</span></dt><dd><p>eg sys.stdout, or stdout = open(‘/path/to/file’) or mol.stdout if mol is an object initialized from <code class="xref py py-class docutils literal notranslate"><span class="pre">gto.Mole</span></code></p> </dd> <dt>c<span class="classifier">numpy.ndarray</span></dt><dd><p>coefficients</p> </dd> </dl> </dd> <dt>Kwargs:</dt><dd><dl class="simple"> <dt>label<span class="classifier">list of strings</span></dt><dd><p>Row labels (default is 1,2,3,4,…)</p> </dd> <dt>label2<span class="classifier">list of strings</span></dt><dd><p>Col labels (default is 1,2,3,4,…)</p> </dd> <dt>ncol<span class="classifier">int</span></dt><dd><p>Number of columns in the format output (default 5)</p> </dd> <dt>digits<span class="classifier">int</span></dt><dd><p>Number of digits of precision for floating point output (default 5)</p> </dd> <dt>start<span class="classifier">int</span></dt><dd><p>The number to start to count the index (default 0)</p> </dd> </dl> </dd> </dl> <p>Examples:</p> <div class="doctest highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">import</span> <span class="nn">sys</span><span class="o">,</span> <span class="nn">numpy</span> <span class="gp">&gt;&gt;&gt; </span><span class="n">dm</span> <span class="o">=</span> <span class="n">numpy</span><span class="o">.</span><span class="n">eye</span><span class="p">(</span><span class="mi">3</span><span class="p">)</span> <span class="gp">&gt;&gt;&gt; </span><span class="n">dump_rec</span><span class="p">(</span><span class="n">sys</span><span class="o">.</span><span class="n">stdout</span><span class="p">,</span> <span class="n">dm</span><span class="p">)</span> <span class="go"> #0 #1 #2 </span> <span class="go">0 1.00000 0.00000 0.00000</span> <span class="go">1 0.00000 1.00000 0.00000</span> <span class="go">2 0.00000 0.00000 1.00000</span> <span class="gp">&gt;&gt;&gt; </span><span class="kn">from</span> <span class="nn">pyscf</span> <span class="kn">import</span> <span class="n">gto</span> <span class="gp">&gt;&gt;&gt; </span><span class="n">mol</span> <span class="o">=</span> <span class="n">gto</span><span class="o">.</span><span class="n">M</span><span class="p">(</span><span class="n">atom</span><span class="o">=</span><span class="s1">&#39;C 0 0 0&#39;</span><span class="p">)</span> <span class="gp">&gt;&gt;&gt; </span><span class="n">dm</span> <span class="o">=</span> <span class="n">numpy</span><span class="o">.</span><span class="n">eye</span><span class="p">(</span><span class="n">mol</span><span class="o">.</span><span class="n">nao_nr</span><span class="p">())</span> <span class="gp">&gt;&gt;&gt; </span><span class="n">dump_rec</span><span class="p">(</span><span class="n">sys</span><span class="o">.</span><span class="n">stdout</span><span class="p">,</span> <span class="n">dm</span><span class="p">,</span> <span class="n">label</span><span class="o">=</span><span class="n">mol</span><span class="o">.</span><span class="n">ao_labels</span><span class="p">(),</span> <span class="n">ncol</span><span class="o">=</span><span class="mi">9</span><span class="p">,</span> <span class="n">digits</span><span class="o">=</span><span class="mi">2</span><span class="p">)</span> <span class="go"> #0 #1 #2 #3 #4 #5 #6 #7 #8 </span> <span class="go">0 C 1s 1.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00</span> <span class="go">0 C 2s 0.00 1.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00</span> <span class="go">0 C 3s 0.00 0.00 1.00 0.00 0.00 0.00 0.00 0.00 0.00</span> <span class="go">0 C 2px 0.00 0.00 0.00 1.00 0.00 0.00 0.00 0.00 0.00</span> <span class="go">0 C 2py 0.00 0.00 0.00 0.00 1.00 0.00 0.00 0.00 0.00</span> <span class="go">0 C 2pz 0.00 0.00 0.00 0.00 0.00 1.00 0.00 0.00 0.00</span> <span class="go">0 C 3px 0.00 0.00 0.00 0.00 0.00 0.00 1.00 0.00 0.00</span> <span class="go">0 C 3py 0.00 0.00 0.00 0.00 0.00 0.00 0.00 1.00 0.00</span> <span class="go">0 C 3pz 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 1.00</span> </pre></div> </div> </dd></dl> <dl class="py function"> <dt id="pyscf.tools.dump_mat.dump_tri"> <code class="sig-prename descclassname">pyscf.tools.dump_mat.</code><code class="sig-name descname">dump_tri</code><span class="sig-paren">(</span><em class="sig-param"><span class="n">stdout</span></em>, <em class="sig-param"><span class="n">c</span></em>, <em class="sig-param"><span class="n">label</span><span class="o">=</span><span class="default_value">None</span></em>, <em class="sig-param"><span class="n">ncol</span><span class="o">=</span><span class="default_value">5</span></em>, <em class="sig-param"><span class="n">digits</span><span class="o">=</span><span class="default_value">5</span></em>, <em class="sig-param"><span class="n">start</span><span class="o">=</span><span class="default_value">0</span></em><span class="sig-paren">)</span><a class="headerlink" href="#pyscf.tools.dump_mat.dump_tri" title="Permalink to this definition">¶</a></dt> <dd><p>Format print for the lower triangular part of an array</p> <dl class="simple"> <dt>Args:</dt><dd><dl class="simple"> <dt>stdout<span class="classifier">file object</span></dt><dd><p>eg sys.stdout, or stdout = open(‘/path/to/file’) or mol.stdout if mol is an object initialized from <code class="xref py py-class docutils literal notranslate"><span class="pre">gto.Mole</span></code></p> </dd> <dt>c<span class="classifier">numpy.ndarray</span></dt><dd><p>coefficients</p> </dd> </dl> </dd> <dt>Kwargs:</dt><dd><dl class="simple"> <dt>label<span class="classifier">list of strings</span></dt><dd><p>Row labels (default is 1,2,3,4,…)</p> </dd> <dt>ncol<span class="classifier">int</span></dt><dd><p>Number of columns in the format output (default 5)</p> </dd> <dt>digits<span class="classifier">int</span></dt><dd><p>Number of digits of precision for floating point output (default 5)</p> </dd> <dt>start<span class="classifier">int</span></dt><dd><p>The number to start to count the index (default 0)</p> </dd> </dl> </dd> </dl> <p>Examples:</p> <div class="doctest highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">import</span> <span class="nn">sys</span><span class="o">,</span> <span class="nn">numpy</span> <span class="gp">&gt;&gt;&gt; </span><span class="n">dm</span> <span class="o">=</span> <span class="n">numpy</span><span class="o">.</span><span class="n">eye</span><span class="p">(</span><span class="mi">3</span><span class="p">)</span> <span class="gp">&gt;&gt;&gt; </span><span class="n">dump_tri</span><span class="p">(</span><span class="n">sys</span><span class="o">.</span><span class="n">stdout</span><span class="p">,</span> <span class="n">dm</span><span class="p">)</span> <span class="go"> #0 #1 #2 </span> <span class="go">0 1.00000</span> <span class="go">1 0.00000 1.00000</span> <span class="go">2 0.00000 0.00000 1.00000</span> <span class="gp">&gt;&gt;&gt; </span><span class="kn">from</span> <span class="nn">pyscf</span> <span class="kn">import</span> <span class="n">gto</span> <span class="gp">&gt;&gt;&gt; </span><span class="n">mol</span> <span class="o">=</span> <span class="n">gto</span><span class="o">.</span><span class="n">M</span><span class="p">(</span><span class="n">atom</span><span class="o">=</span><span class="s1">&#39;C 0 0 0&#39;</span><span class="p">)</span> <span class="gp">&gt;&gt;&gt; </span><span class="n">dm</span> <span class="o">=</span> <span class="n">numpy</span><span class="o">.</span><span class="n">eye</span><span class="p">(</span><span class="n">mol</span><span class="o">.</span><span class="n">nao_nr</span><span class="p">())</span> <span class="gp">&gt;&gt;&gt; </span><span class="n">dump_tri</span><span class="p">(</span><span class="n">sys</span><span class="o">.</span><span class="n">stdout</span><span class="p">,</span> <span class="n">dm</span><span class="p">,</span> <span class="n">label</span><span class="o">=</span><span class="n">mol</span><span class="o">.</span><span class="n">ao_labels</span><span class="p">(),</span> <span class="n">ncol</span><span class="o">=</span><span class="mi">9</span><span class="p">,</span> <span class="n">digits</span><span class="o">=</span><span class="mi">2</span><span class="p">)</span> <span class="go"> #0 #1 #2 #3 #4 #5 #6 #7 #8 </span> <span class="go">0 C 1s 1.00</span> <span class="go">0 C 2s 0.00 1.00</span> <span class="go">0 C 3s 0.00 0.00 1.00</span> <span class="go">0 C 2px 0.00 0.00 0.00 1.00</span> <span class="go">0 C 2py 0.00 0.00 0.00 0.00 1.00</span> <span class="go">0 C 2pz 0.00 0.00 0.00 0.00 0.00 1.00</span> <span class="go">0 C 3px 0.00 0.00 0.00 0.00 0.00 0.00 1.00</span> <span class="go">0 C 3py 0.00 0.00 0.00 0.00 0.00 0.00 0.00 1.00</span> <span class="go">0 C 3pz 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 1.00</span> </pre></div> </div> </dd></dl> </div> <div class="section" id="module-pyscf.tools.fcidump"> <span id="pyscf-tools-fcidump-module"></span><h2>pyscf.tools.fcidump module<a class="headerlink" href="#module-pyscf.tools.fcidump" title="Permalink to this headline">¶</a></h2> <p>FCIDUMP functions (write, read) for real Hamiltonian</p> <dl class="py function"> <dt id="pyscf.tools.fcidump.from_chkfile"> <code class="sig-prename descclassname">pyscf.tools.fcidump.</code><code class="sig-name descname">from_chkfile</code><span class="sig-paren">(</span><em class="sig-param"><span class="n">filename</span></em>, <em class="sig-param"><span class="n">chkfile</span></em>, <em class="sig-param"><span class="n">tol</span><span class="o">=</span><span class="default_value">1e-15</span></em>, <em class="sig-param"><span class="n">float_format</span><span class="o">=</span><span class="default_value">' %.16g'</span></em>, <em class="sig-param"><span class="n">molpro_orbsym</span><span class="o">=</span><span class="default_value">False</span></em><span class="sig-paren">)</span><a class="headerlink" href="#pyscf.tools.fcidump.from_chkfile" title="Permalink to this definition">¶</a></dt> <dd><p>Read SCF results from PySCF chkfile and transform 1-electron, 2-electron integrals using the SCF orbitals. The transformed integrals is written to FCIDUMP</p> <dl class="simple"> <dt>Kwargs:</dt><dd><dl class="simple"> <dt>molpro_orbsym (bool): Whether to dump the orbsym in Molpro orbsym</dt><dd><p>convention as documented in <a class="reference external" href="https://www.molpro.net/info/current/doc/manual/node36.html">https://www.molpro.net/info/current/doc/manual/node36.html</a></p> </dd> </dl> </dd> </dl> </dd></dl> <dl class="py function"> <dt id="pyscf.tools.fcidump.from_integrals"> <code class="sig-prename descclassname">pyscf.tools.fcidump.</code><code class="sig-name descname">from_integrals</code><span class="sig-paren">(</span><em class="sig-param"><span class="n">filename</span></em>, <em class="sig-param"><span class="n">h1e</span></em>, <em class="sig-param"><span class="n">h2e</span></em>, <em class="sig-param"><span class="n">nmo</span></em>, <em class="sig-param"><span class="n">nelec</span></em>, <em class="sig-param"><span class="n">nuc</span><span class="o">=</span><span class="default_value">0</span></em>, <em class="sig-param"><span class="n">ms</span><span class="o">=</span><span class="default_value">0</span></em>, <em class="sig-param"><span class="n">orbsym</span><span class="o">=</span><span class="default_value">None</span></em>, <em class="sig-param"><span class="n">tol</span><span class="o">=</span><span class="default_value">1e-15</span></em>, <em class="sig-param"><span class="n">float_format</span><span class="o">=</span><span class="default_value">' %.16g'</span></em><span class="sig-paren">)</span><a class="headerlink" href="#pyscf.tools.fcidump.from_integrals" title="Permalink to this definition">¶</a></dt> <dd><p>Convert the given 1-electron and 2-electron integrals to FCIDUMP format</p> </dd></dl> <dl class="py function"> <dt id="pyscf.tools.fcidump.from_mo"> <code class="sig-prename descclassname">pyscf.tools.fcidump.</code><code class="sig-name descname">from_mo</code><span class="sig-paren">(</span><em class="sig-param"><span class="n">mol</span></em>, <em class="sig-param"><span class="n">filename</span></em>, <em class="sig-param"><span class="n">mo_coeff</span></em>, <em class="sig-param"><span class="n">orbsym</span><span class="o">=</span><span class="default_value">None</span></em>, <em class="sig-param"><span class="n">tol</span><span class="o">=</span><span class="default_value">1e-15</span></em>, <em class="sig-param"><span class="n">float_format</span><span class="o">=</span><span class="default_value">' %.16g'</span></em>, <em class="sig-param"><span class="n">molpro_orbsym</span><span class="o">=</span><span class="default_value">False</span></em><span class="sig-paren">)</span><a class="headerlink" href="#pyscf.tools.fcidump.from_mo" title="Permalink to this definition">¶</a></dt> <dd><p>Use the given MOs to transfrom the 1-electron and 2-electron integrals then dump them to FCIDUMP.</p> <dl class="simple"> <dt>Kwargs:</dt><dd><dl class="simple"> <dt>molpro_orbsym (bool): Whether to dump the orbsym in Molpro orbsym</dt><dd><p>convention as documented in <a class="reference external" href="https://www.molpro.net/info/current/doc/manual/node36.html">https://www.molpro.net/info/current/doc/manual/node36.html</a></p> </dd> </dl> </dd> </dl> </dd></dl> <dl class="py function"> <dt id="pyscf.tools.fcidump.from_scf"> <code class="sig-prename descclassname">pyscf.tools.fcidump.</code><code class="sig-name descname">from_scf</code><span class="sig-paren">(</span><em class="sig-param"><span class="n">mf</span></em>, <em class="sig-param"><span class="n">filename</span></em>, <em class="sig-param"><span class="n">tol</span><span class="o">=</span><span class="default_value">1e-15</span></em>, <em class="sig-param"><span class="n">float_format</span><span class="o">=</span><span class="default_value">' %.16g'</span></em>, <em class="sig-param"><span class="n">molpro_orbsym</span><span class="o">=</span><span class="default_value">False</span></em><span class="sig-paren">)</span><a class="headerlink" href="#pyscf.tools.fcidump.from_scf" title="Permalink to this definition">¶</a></dt> <dd><p>Use the given SCF object to transfrom the 1-electron and 2-electron integrals then dump them to FCIDUMP.</p> <dl class="simple"> <dt>Kwargs:</dt><dd><dl class="simple"> <dt>molpro_orbsym (bool): Whether to dump the orbsym in Molpro orbsym</dt><dd><p>convention as documented in <a class="reference external" href="https://www.molpro.net/info/current/doc/manual/node36.html">https://www.molpro.net/info/current/doc/manual/node36.html</a></p> </dd> </dl> </dd> </dl> </dd></dl> <dl class="py function"> <dt id="pyscf.tools.fcidump.read"> <code class="sig-prename descclassname">pyscf.tools.fcidump.</code><code class="sig-name descname">read</code><span class="sig-paren">(</span><em class="sig-param"><span class="n">filename</span></em>, <em class="sig-param"><span class="n">molpro_orbsym</span><span class="o">=</span><span class="default_value">False</span></em><span class="sig-paren">)</span><a class="headerlink" href="#pyscf.tools.fcidump.read" title="Permalink to this definition">¶</a></dt> <dd><p>Parse FCIDUMP. Return a dictionary to hold the integrals and parameters with keys: H1, H2, ECORE, NORB, NELEC, MS, ORBSYM, ISYM</p> <dl class="simple"> <dt>Kwargs:</dt><dd><dl class="simple"> <dt>molpro_orbsym (bool): Whether the orbsym in the FCIDUMP file is in</dt><dd><p>Molpro orbsym convention as documented in <a class="reference external" href="https://www.molpro.net/info/current/doc/manual/node36.html">https://www.molpro.net/info/current/doc/manual/node36.html</a> In return, orbsym is converted to pyscf symmetry convention</p> </dd> </dl> </dd> </dl> </dd></dl> <dl class="py function"> <dt id="pyscf.tools.fcidump.scf_from_fcidump"> <code class="sig-prename descclassname">pyscf.tools.fcidump.</code><code class="sig-name descname">scf_from_fcidump</code><span class="sig-paren">(</span><em class="sig-param"><span class="n">mf</span></em>, <em class="sig-param"><span class="n">filename</span></em>, <em class="sig-param"><span class="n">molpro_orbsym</span><span class="o">=</span><span class="default_value">False</span></em><span class="sig-paren">)</span><a class="headerlink" href="#pyscf.tools.fcidump.scf_from_fcidump" title="Permalink to this definition">¶</a></dt> <dd><p>Update the SCF object with the quantities defined in FCIDUMP file</p> </dd></dl> <dl class="py function"> <dt id="pyscf.tools.fcidump.to_scf"> <code class="sig-prename descclassname">pyscf.tools.fcidump.</code><code class="sig-name descname">to_scf</code><span class="sig-paren">(</span><em class="sig-param"><span class="n">filename</span></em>, <em class="sig-param"><span class="n">molpro_orbsym</span><span class="o">=</span><span class="default_value">False</span></em>, <em class="sig-param"><span class="n">mf</span><span class="o">=</span><span class="default_value">None</span></em>, <em class="sig-param"><span class="o">**</span><span class="n">kwargs</span></em><span class="sig-paren">)</span><a class="headerlink" href="#pyscf.tools.fcidump.to_scf" title="Permalink to this definition">¶</a></dt> <dd><p>Use the Hamiltonians defined by FCIDUMP to build an SCF object</p> </dd></dl> <dl class="py function"> <dt id="pyscf.tools.fcidump.write_eri"> <code class="sig-prename descclassname">pyscf.tools.fcidump.</code><code class="sig-name descname">write_eri</code><span class="sig-paren">(</span><em class="sig-param"><span class="n">fout</span></em>, <em class="sig-param"><span class="n">eri</span></em>, <em class="sig-param"><span class="n">nmo</span></em>, <em class="sig-param"><span class="n">tol</span><span class="o">=</span><span class="default_value">1e-15</span></em>, <em class="sig-param"><span class="n">float_format</span><span class="o">=</span><span class="default_value">' %.16g'</span></em><span class="sig-paren">)</span><a class="headerlink" href="#pyscf.tools.fcidump.write_eri" title="Permalink to this definition">¶</a></dt> <dd></dd></dl> <dl class="py function"> <dt id="pyscf.tools.fcidump.write_hcore"> <code class="sig-prename descclassname">pyscf.tools.fcidump.</code><code class="sig-name descname">write_hcore</code><span class="sig-paren">(</span><em class="sig-param"><span class="n">fout</span></em>, <em class="sig-param"><span class="n">h</span></em>, <em class="sig-param"><span class="n">nmo</span></em>, <em class="sig-param"><span class="n">tol</span><span class="o">=</span><span class="default_value">1e-15</span></em>, <em class="sig-param"><span class="n">float_format</span><span class="o">=</span><span class="default_value">' %.16g'</span></em><span class="sig-paren">)</span><a class="headerlink" href="#pyscf.tools.fcidump.write_hcore" title="Permalink to this definition">¶</a></dt> <dd></dd></dl> <dl class="py function"> <dt id="pyscf.tools.fcidump.write_head"> <code class="sig-prename descclassname">pyscf.tools.fcidump.</code><code class="sig-name descname">write_head</code><span class="sig-paren">(</span><em class="sig-param"><span class="n">fout</span></em>, <em class="sig-param"><span class="n">nmo</span></em>, <em class="sig-param"><span class="n">nelec</span></em>, <em class="sig-param"><span class="n">ms</span><span class="o">=</span><span class="default_value">0</span></em>, <em class="sig-param"><span class="n">orbsym</span><span class="o">=</span><span class="default_value">None</span></em><span class="sig-paren">)</span><a class="headerlink" href="#pyscf.tools.fcidump.write_head" title="Permalink to this definition">¶</a></dt> <dd></dd></dl> </div> <div class="section" id="module-pyscf.tools.mo_mapping"> <span id="pyscf-tools-mo-mapping-module"></span><h2>pyscf.tools.mo_mapping module<a class="headerlink" href="#module-pyscf.tools.mo_mapping" title="Permalink to this headline">¶</a></h2> <dl class="py function"> <dt id="pyscf.tools.mo_mapping.mo_1to1map"> <code class="sig-prename descclassname">pyscf.tools.mo_mapping.</code><code class="sig-name descname">mo_1to1map</code><span class="sig-paren">(</span><em class="sig-param"><span class="n">s</span></em><span class="sig-paren">)</span><a class="headerlink" href="#pyscf.tools.mo_mapping.mo_1to1map" title="Permalink to this definition">¶</a></dt> <dd><p>Given &lt;i|j&gt;, search for the 1-to-1 mapping between i and j.</p> <dl class="simple"> <dt>Returns:</dt><dd><p>a list [j-close-to-i for i in &lt;bra|]</p> </dd> </dl> </dd></dl> <dl class="py function"> <dt id="pyscf.tools.mo_mapping.mo_comps"> <code class="sig-prename descclassname">pyscf.tools.mo_mapping.</code><code class="sig-name descname">mo_comps</code><span class="sig-paren">(</span><em class="sig-param"><span class="n">aolabels_or_baslst</span></em>, <em class="sig-param"><span class="n">mol</span></em>, <em class="sig-param"><span class="n">mo_coeff</span></em>, <em class="sig-param"><span class="n">cart</span><span class="o">=</span><span class="default_value">False</span></em>, <em class="sig-param"><span class="n">orth_method</span><span class="o">=</span><span class="default_value">'meta_lowdin'</span></em><span class="sig-paren">)</span><a class="headerlink" href="#pyscf.tools.mo_mapping.mo_comps" title="Permalink to this definition">¶</a></dt> <dd><p>Given AO(s), show how the AO(s) are distributed in MOs.</p> <dl class="simple"> <dt>Args:</dt><dd><dl class="simple"> <dt>aolabels_or_baslst<span class="classifier">filter function or AO labels or AO index</span></dt><dd><p>If it’s a function, the AO indices are the items for which the function return value is true.</p> </dd> </dl> </dd> <dt>Kwargs:</dt><dd><dl class="simple"> <dt>cart<span class="classifier">bool</span></dt><dd><p>whether the orbital coefficients are based on cartesian basis.</p> </dd> <dt>orth_method<span class="classifier">str</span></dt><dd><p>The localization method to generated orthogonal AO upon which the AO contribution are computed. It can be one of ‘meta_lowdin’, ‘lowdin’ or ‘nao’.</p> </dd> </dl> </dd> <dt>Returns:</dt><dd><p>A list of float to indicate the total contributions (normalized to 1) of localized AOs</p> </dd> </dl> <p>Examples:</p> <div class="doctest highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">from</span> <span class="nn">pyscf</span> <span class="kn">import</span> <span class="n">gto</span><span class="p">,</span> <span class="n">scf</span> <span class="gp">&gt;&gt;&gt; </span><span class="kn">from</span> <span class="nn">pyscf.tools</span> <span class="kn">import</span> <span class="n">mo_mapping</span> <span class="gp">&gt;&gt;&gt; </span><span class="n">mol</span> <span class="o">=</span> <span class="n">gto</span><span class="o">.</span><span class="n">M</span><span class="p">(</span><span class="n">atom</span><span class="o">=</span><span class="s1">&#39;H 0 0 0; F 0 0 1&#39;</span><span class="p">,</span> <span class="n">basis</span><span class="o">=</span><span class="s1">&#39;6-31g&#39;</span><span class="p">)</span> <span class="gp">&gt;&gt;&gt; </span><span class="n">mf</span> <span class="o">=</span> <span class="n">scf</span><span class="o">.</span><span class="n">RHF</span><span class="p">(</span><span class="n">mol</span><span class="p">)</span><span class="o">.</span><span class="n">run</span><span class="p">()</span> <span class="gp">&gt;&gt;&gt; </span><span class="n">comp</span> <span class="o">=</span> <span class="n">mo_mapping</span><span class="o">.</span><span class="n">mo_comps</span><span class="p">(</span><span class="s1">&#39;F 2s&#39;</span><span class="p">,</span> <span class="n">mol</span><span class="p">,</span> <span class="n">mf</span><span class="o">.</span><span class="n">mo_coeff</span><span class="p">)</span> <span class="gp">&gt;&gt;&gt; </span><span class="nb">print</span><span class="p">(</span><span class="s1">&#39;MO-id F-2s components&#39;</span><span class="p">)</span> <span class="gp">&gt;&gt;&gt; </span><span class="k">for</span> <span class="n">i</span><span class="p">,</span><span class="n">c</span> <span class="ow">in</span> <span class="nb">enumerate</span><span class="p">(</span><span class="n">comp</span><span class="p">):</span> <span class="gp">... </span> <span class="nb">print</span><span class="p">(</span><span class="s1">&#39;</span><span class="si">%-3d</span><span class="s1"> </span><span class="si">%.10f</span><span class="s1">&#39;</span> <span class="o">%</span> <span class="p">(</span><span class="n">i</span><span class="p">,</span> <span class="n">c</span><span class="p">))</span> <span class="go">MO-id components</span> <span class="go">0 0.0000066344</span> <span class="go">1 0.8796915532</span> <span class="go">2 0.0590259826</span> <span class="go">3 0.0000000000</span> <span class="go">4 0.0000000000</span> <span class="go">5 0.0435028851</span> <span class="go">6 0.0155889103</span> <span class="go">7 0.0000000000</span> <span class="go">8 0.0000000000</span> <span class="go">9 0.0000822361</span> <span class="go">10 0.0021017982</span> </pre></div> </div> </dd></dl> <dl class="py function"> <dt id="pyscf.tools.mo_mapping.mo_map"> <code class="sig-prename descclassname">pyscf.tools.mo_mapping.</code><code class="sig-name descname">mo_map</code><span class="sig-paren">(</span><em class="sig-param"><span class="n">mol1</span></em>, <em class="sig-param"><span class="n">mo1</span></em>, <em class="sig-param"><span class="n">mol2</span></em>, <em class="sig-param"><span class="n">mo2</span></em>, <em class="sig-param"><span class="n">base</span><span class="o">=</span><span class="default_value">0</span></em>, <em class="sig-param"><span class="n">tol</span><span class="o">=</span><span class="default_value">0.5</span></em><span class="sig-paren">)</span><a class="headerlink" href="#pyscf.tools.mo_mapping.mo_map" title="Permalink to this definition">¶</a></dt> <dd><p>Given two orbitals, based on their overlap &lt;i|j&gt;, search all orbital-pairs which have significant overlap.</p> <dl class="simple"> <dt>Returns:</dt><dd><p>Two lists. First list is the orbital-pair indices, second is the overlap value.</p> </dd> </dl> </dd></dl> </div> <div class="section" id="module-pyscf.tools.molden"> <span id="pyscf-tools-molden-module"></span><h2>pyscf.tools.molden module<a class="headerlink" href="#module-pyscf.tools.molden" title="Permalink to this headline">¶</a></h2> <dl class="py function"> <dt id="pyscf.tools.molden.dump_scf"> <code class="sig-prename descclassname">pyscf.tools.molden.</code><code class="sig-name descname">dump_scf</code><span class="sig-paren">(</span><em class="sig-param"><span class="n">mf</span></em>, <em class="sig-param"><span class="n">filename</span></em>, <em class="sig-param"><span class="n">ignore_h</span><span class="o">=</span><span class="default_value">True</span></em><span class="sig-paren">)</span><a class="headerlink" href="#pyscf.tools.molden.dump_scf" title="Permalink to this definition">¶</a></dt> <dd></dd></dl> <dl class="py function"> <dt id="pyscf.tools.molden.from_chkfile"> <code class="sig-prename descclassname">pyscf.tools.molden.</code><code class="sig-name descname">from_chkfile</code><span class="sig-paren">(</span><em class="sig-param"><span class="n">filename</span></em>, <em class="sig-param"><span class="n">chkfile</span></em>, <em class="sig-param"><span class="n">key</span><span class="o">=</span><span class="default_value">'scf/mo_coeff'</span></em>, <em class="sig-param"><span class="n">ignore_h</span><span class="o">=</span><span class="default_value">True</span></em><span class="sig-paren">)</span><a class="headerlink" href="#pyscf.tools.molden.from_chkfile" title="Permalink to this definition">¶</a></dt> <dd></dd></dl> <dl class="py function"> <dt id="pyscf.tools.molden.from_mcscf"> <code class="sig-prename descclassname">pyscf.tools.molden.</code><code class="sig-name descname">from_mcscf</code><span class="sig-paren">(</span><em class="sig-param"><span class="n">mc</span></em>, <em class="sig-param"><span class="n">filename</span></em>, <em class="sig-param"><span class="n">ignore_h</span><span class="o">=</span><span class="default_value">True</span></em>, <em class="sig-param"><span class="n">cas_natorb</span><span class="o">=</span><span class="default_value">False</span></em><span class="sig-paren">)</span><a class="headerlink" href="#pyscf.tools.molden.from_mcscf" title="Permalink to this definition">¶</a></dt> <dd></dd></dl> <dl class="py function"> <dt id="pyscf.tools.molden.from_mo"> <code class="sig-prename descclassname">pyscf.tools.molden.</code><code class="sig-name descname">from_mo</code><span class="sig-paren">(</span><em class="sig-param"><span class="n">mol</span></em>, <em class="sig-param"><span class="n">filename</span></em>, <em class="sig-param"><span class="n">mo_coeff</span></em>, <em class="sig-param"><span class="n">spin</span><span class="o">=</span><span class="default_value">'Alpha'</span></em>, <em class="sig-param"><span class="n">symm</span><span class="o">=</span><span class="default_value">None</span></em>, <em class="sig-param"><span class="n">ene</span><span class="o">=</span><span class="default_value">None</span></em>, <em class="sig-param"><span class="n">occ</span><span class="o">=</span><span class="default_value">None</span></em>, <em class="sig-param"><span class="n">ignore_h</span><span class="o">=</span><span class="default_value">True</span></em><span class="sig-paren">)</span><a class="headerlink" href="#pyscf.tools.molden.from_mo" title="Permalink to this definition">¶</a></dt> <dd><p>Dump the given MOs in Molden format</p> </dd></dl> <dl class="py function"> <dt id="pyscf.tools.molden.from_scf"> <code class="sig-prename descclassname">pyscf.tools.molden.</code><code class="sig-name descname">from_scf</code><span class="sig-paren">(</span><em class="sig-param"><span class="n">mf</span></em>, <em class="sig-param"><span class="n">filename</span></em>, <em class="sig-param"><span class="n">ignore_h</span><span class="o">=</span><span class="default_value">True</span></em><span class="sig-paren">)</span><a class="headerlink" href="#pyscf.tools.molden.from_scf" title="Permalink to this definition">¶</a></dt> <dd><p>Dump the given SCF object in Molden format</p> </dd></dl> <dl class="py function"> <dt id="pyscf.tools.molden.header"> <code class="sig-prename descclassname">pyscf.tools.molden.</code><code class="sig-name descname">header</code><span class="sig-paren">(</span><em class="sig-param"><span class="n">mol</span></em>, <em class="sig-param"><span class="n">fout</span></em>, <em class="sig-param"><span class="n">ignore_h</span><span class="o">=</span><span class="default_value">True</span></em><span class="sig-paren">)</span><a class="headerlink" href="#pyscf.tools.molden.header" title="Permalink to this definition">¶</a></dt> <dd></dd></dl> <dl class="py function"> <dt id="pyscf.tools.molden.load"> <code class="sig-prename descclassname">pyscf.tools.molden.</code><code class="sig-name descname">load</code><span class="sig-paren">(</span><em class="sig-param"><span class="n">moldenfile</span></em>, <em class="sig-param"><span class="n">verbose</span><span class="o">=</span><span class="default_value">0</span></em><span class="sig-paren">)</span><a class="headerlink" href="#pyscf.tools.molden.load" title="Permalink to this definition">¶</a></dt> <dd><p>Extract mol and orbitals from molden file</p> </dd></dl> <dl class="py function"> <dt id="pyscf.tools.molden.orbital_coeff"> <code class="sig-prename descclassname">pyscf.tools.molden.</code><code class="sig-name descname">orbital_coeff</code><span class="sig-paren">(</span><em class="sig-param"><span class="n">mol</span></em>, <em class="sig-param"><span class="n">fout</span></em>, <em class="sig-param"><span class="n">mo_coeff</span></em>, <em class="sig-param"><span class="n">spin</span><span class="o">=</span><span class="default_value">'Alpha'</span></em>, <em class="sig-param"><span class="n">symm</span><span class="o">=</span><span class="default_value">None</span></em>, <em class="sig-param"><span class="n">ene</span><span class="o">=</span><span class="default_value">None</span></em>, <em class="sig-param"><span class="n">occ</span><span class="o">=</span><span class="default_value">None</span></em>, <em class="sig-param"><span class="n">ignore_h</span><span class="o">=</span><span class="default_value">True</span></em><span class="sig-paren">)</span><a class="headerlink" href="#pyscf.tools.molden.orbital_coeff" title="Permalink to this definition">¶</a></dt> <dd></dd></dl> <dl class="py function"> <dt id="pyscf.tools.molden.order_ao_index"> <code class="sig-prename descclassname">pyscf.tools.molden.</code><code class="sig-name descname">order_ao_index</code><span class="sig-paren">(</span><em class="sig-param"><span class="n">mol</span></em><span class="sig-paren">)</span><a class="headerlink" href="#pyscf.tools.molden.order_ao_index" title="Permalink to this definition">¶</a></dt> <dd></dd></dl> <dl class="py function"> <dt id="pyscf.tools.molden.parse"> <code class="sig-prename descclassname">pyscf.tools.molden.</code><code class="sig-name descname">parse</code><span class="sig-paren">(</span><em class="sig-param"><span class="n">moldenfile</span></em>, <em class="sig-param"><span class="n">verbose</span><span class="o">=</span><span class="default_value">0</span></em><span class="sig-paren">)</span><a class="headerlink" href="#pyscf.tools.molden.parse" title="Permalink to this definition">¶</a></dt> <dd><p>Extract mol and orbitals from molden file</p> </dd></dl> <dl class="py function"> <dt id="pyscf.tools.molden.read"> <code class="sig-prename descclassname">pyscf.tools.molden.</code><code class="sig-name descname">read</code><span class="sig-paren">(</span><em class="sig-param"><span class="n">moldenfile</span></em>, <em class="sig-param"><span class="n">verbose</span><span class="o">=</span><span class="default_value">0</span></em><span class="sig-paren">)</span><a class="headerlink" href="#pyscf.tools.molden.read" title="Permalink to this definition">¶</a></dt> <dd><p>Extract mol and orbitals from molden file</p> </dd></dl> <dl class="py function"> <dt id="pyscf.tools.molden.remove_high_l"> <code class="sig-prename descclassname">pyscf.tools.molden.</code><code class="sig-name descname">remove_high_l</code><span class="sig-paren">(</span><em class="sig-param"><span class="n">mol</span></em>, <em class="sig-param"><span class="n">mo_coeff</span><span class="o">=</span><span class="default_value">None</span></em><span class="sig-paren">)</span><a class="headerlink" href="#pyscf.tools.molden.remove_high_l" title="Permalink to this definition">¶</a></dt> <dd><p>Remove high angular momentum (l &gt;= 5) functions before dumping molden file. If molden function raised error message <code class="docutils literal notranslate"><span class="pre">RuntimeError</span> <span class="pre">l=5</span> <span class="pre">is</span> <span class="pre">not</span> <span class="pre">supported</span></code>, you can use this function to format orbitals.</p> <p>Note the formated orbitals may have normalization problem. Some visualization tool will complain about the orbital normalization error.</p> <p>Examples:</p> <div class="doctest highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">mol1</span><span class="p">,</span> <span class="n">orb1</span> <span class="o">=</span> <span class="n">remove_high_l</span><span class="p">(</span><span class="n">mol</span><span class="p">,</span> <span class="n">mf</span><span class="o">.</span><span class="n">mo_coeff</span><span class="p">)</span> <span class="gp">&gt;&gt;&gt; </span><span class="n">molden</span><span class="o">.</span><span class="n">from_mo</span><span class="p">(</span><span class="n">mol1</span><span class="p">,</span> <span class="n">outputfile</span><span class="p">,</span> <span class="n">orb1</span><span class="p">)</span> </pre></div> </div> </dd></dl> </div> <div class="section" id="pyscf-tools-rhf-newtonraphson-module"> <h2>pyscf.tools.rhf_newtonraphson module<a class="headerlink" href="#pyscf-tools-rhf-newtonraphson-module" title="Permalink to this headline">¶</a></h2> </div> <div class="section" id="module-pyscf.tools.ring"> <span id="pyscf-tools-ring-module"></span><h2>pyscf.tools.ring module<a class="headerlink" href="#module-pyscf.tools.ring" title="Permalink to this headline">¶</a></h2> <dl class="py function"> <dt id="pyscf.tools.ring.make"> <code class="sig-prename descclassname">pyscf.tools.ring.</code><code class="sig-name descname">make</code><span class="sig-paren">(</span><em class="sig-param"><span class="n">nat</span></em>, <em class="sig-param"><span class="n">b</span><span class="o">=</span><span class="default_value">1.0</span></em><span class="sig-paren">)</span><a class="headerlink" href="#pyscf.tools.ring.make" title="Permalink to this definition">¶</a></dt> <dd></dd></dl> </div> <div class="section" id="module-pyscf.tools.wfn_format"> <span id="pyscf-tools-wfn-format-module"></span><h2>pyscf.tools.wfn_format module<a class="headerlink" href="#module-pyscf.tools.wfn_format" title="Permalink to this headline">¶</a></h2> <p>GAMESS WFN File format</p> <dl class="py function"> <dt id="pyscf.tools.wfn_format.write_ci"> <code class="sig-prename descclassname">pyscf.tools.wfn_format.</code><code class="sig-name descname">write_ci</code><span class="sig-paren">(</span><em class="sig-param"><span class="n">fout</span></em>, <em class="sig-param"><span class="n">fcivec</span></em>, <em class="sig-param"><span class="n">norb</span></em>, <em class="sig-param"><span class="n">nelec</span></em>, <em class="sig-param"><span class="n">ncore</span><span class="o">=</span><span class="default_value">0</span></em><span class="sig-paren">)</span><a class="headerlink" href="#pyscf.tools.wfn_format.write_ci" title="Permalink to this definition">¶</a></dt> <dd></dd></dl> <dl class="py function"> <dt id="pyscf.tools.wfn_format.write_mo"> <code class="sig-prename descclassname">pyscf.tools.wfn_format.</code><code class="sig-name descname">write_mo</code><span class="sig-paren">(</span><em class="sig-param"><span class="n">fout</span></em>, <em class="sig-param"><span class="n">mol</span></em>, <em class="sig-param"><span class="n">mo_coeff</span></em>, <em class="sig-param"><span class="n">mo_energy</span><span class="o">=</span><span class="default_value">None</span></em>, <em class="sig-param"><span class="n">mo_occ</span><span class="o">=</span><span class="default_value">None</span></em><span class="sig-paren">)</span><a class="headerlink" href="#pyscf.tools.wfn_format.write_mo" title="Permalink to this definition">¶</a></dt> <dd></dd></dl> </div> <div class="section" id="module-pyscf.tools"> <span id="module-contents"></span><h2>Module contents<a class="headerlink" href="#module-pyscf.tools" title="Permalink to this headline">¶</a></h2> </div> </div> <div class="section"> </div> </article> </div> </div> </main> </div> <footer class="md-footer"> <div class="md-footer-nav"> <nav class="md-footer-nav__inner md-grid"> <a href="../pyscf.tdscf/" title="pyscf.tdscf package" class="md-flex md-footer-nav__link md-footer-nav__link--prev" rel="prev"> <div class="md-flex__cell md-flex__cell--shrink"> <i class="md-icon md-icon--arrow-back md-footer-nav__button"></i> </div> <div class="md-flex__cell md-flex__cell--stretch md-footer-nav__title"> <span class="md-flex__ellipsis"> <span class="md-footer-nav__direction"> Previous </span> pyscf.tdscf package </span> </div> </a> <a href="../pyscf.x2c/" title="pyscf.x2c package" class="md-flex md-footer-nav__link md-footer-nav__link--next" rel="next"> <div class="md-flex__cell md-flex__cell--stretch md-footer-nav__title"><span class="md-flex__ellipsis"> <span class="md-footer-nav__direction"> Next </span> pyscf.x2c package </span> </div> <div class="md-flex__cell md-flex__cell--shrink"><i class="md-icon md-icon--arrow-forward md-footer-nav__button"></i> </div> </a> </nav> </div> <div class="md-footer-meta md-typeset"> <div class="md-footer-meta__inner md-grid"> <div class="md-footer-copyright"> <div class="md-footer-copyright__highlight"> &#169; Copyright 2021, <NAME>. </div> Created using <a href="http://www.sphinx-doc.org/">Sphinx</a> 3.4.3. and <a href="https://github.com/bashtage/sphinx-material/">Material for Sphinx</a> </div> </div> </div> </footer> <script src="../../_static/javascripts/application.js"></script> <script>app.initialize({version: "1.0.4", url: {base: ".."}})</script> </body> </html><file_sep>/pyscf_api_docs/pyscf.prop.nmr.rst pyscf.prop.nmr package ====================== Submodules ---------- pyscf.prop.nmr.dhf module ------------------------- .. automodule:: pyscf.prop.nmr.dhf :members: :undoc-members: :show-inheritance: pyscf.prop.nmr.rhf module ------------------------- .. automodule:: pyscf.prop.nmr.rhf :members: :undoc-members: :show-inheritance: pyscf.prop.nmr.rks module ------------------------- .. automodule:: pyscf.prop.nmr.rks :members: :undoc-members: :show-inheritance: pyscf.prop.nmr.uhf module ------------------------- .. automodule:: pyscf.prop.nmr.uhf :members: :undoc-members: :show-inheritance: pyscf.prop.nmr.uks module ------------------------- .. automodule:: pyscf.prop.nmr.uks :members: :undoc-members: :show-inheritance: Module contents --------------- .. automodule:: pyscf.prop.nmr :members: :undoc-members: :show-inheritance: <file_sep>/pyscf_api_docs/pyscf.soscf.rst pyscf.soscf package =================== Submodules ---------- pyscf.soscf.ciah module ----------------------- .. automodule:: pyscf.soscf.ciah :members: :undoc-members: :show-inheritance: pyscf.soscf.newton\_ah module ----------------------------- .. automodule:: pyscf.soscf.newton_ah :members: :undoc-members: :show-inheritance: Module contents --------------- .. automodule:: pyscf.soscf :members: :undoc-members: :show-inheritance: <file_sep>/docs/_sources/pyscf_api_docs/pyscf.df.grad.rst.txt pyscf.df.grad package ===================== Submodules ---------- pyscf.df.grad.rhf module ------------------------ .. automodule:: pyscf.df.grad.rhf :members: :undoc-members: :show-inheritance: pyscf.df.grad.rks module ------------------------ .. automodule:: pyscf.df.grad.rks :members: :undoc-members: :show-inheritance: pyscf.df.grad.uhf module ------------------------ .. automodule:: pyscf.df.grad.uhf :members: :undoc-members: :show-inheritance: pyscf.df.grad.uks module ------------------------ .. automodule:: pyscf.df.grad.uks :members: :undoc-members: :show-inheritance: Module contents --------------- .. automodule:: pyscf.df.grad :members: :undoc-members: :show-inheritance: <file_sep>/pyscf_api_docs/pyscf.pbc.ao2mo.rst pyscf.pbc.ao2mo package ======================= Submodules ---------- pyscf.pbc.ao2mo.eris module --------------------------- .. automodule:: pyscf.pbc.ao2mo.eris :members: :undoc-members: :show-inheritance: Module contents --------------- .. automodule:: pyscf.pbc.ao2mo :members: :undoc-members: :show-inheritance: <file_sep>/pyscf_api_docs/pyscf.pbc.tools.rst pyscf.pbc.tools package ======================= Submodules ---------- pyscf.pbc.tools.k2gamma module ------------------------------ .. automodule:: pyscf.pbc.tools.k2gamma :members: :undoc-members: :show-inheritance: pyscf.pbc.tools.lattice module ------------------------------ .. automodule:: pyscf.pbc.tools.lattice :members: :undoc-members: :show-inheritance: pyscf.pbc.tools.make\_test\_cell module --------------------------------------- .. automodule:: pyscf.pbc.tools.make_test_cell :members: :undoc-members: :show-inheritance: pyscf.pbc.tools.pbc module -------------------------- .. automodule:: pyscf.pbc.tools.pbc :members: :undoc-members: :show-inheritance: pyscf.pbc.tools.pyscf\_ase module --------------------------------- .. automodule:: pyscf.pbc.tools.pyscf_ase :members: :undoc-members: :show-inheritance: pyscf.pbc.tools.pywannier90 module ---------------------------------- .. automodule:: pyscf.pbc.tools.pywannier90 :members: :undoc-members: :show-inheritance: pyscf.pbc.tools.tril module --------------------------- .. automodule:: pyscf.pbc.tools.tril :members: :undoc-members: :show-inheritance: Module contents --------------- .. automodule:: pyscf.pbc.tools :members: :undoc-members: :show-inheritance: <file_sep>/docs/_sources/pyscf_api_docs/pyscf.pbc.prop.efg.rst.txt pyscf.pbc.prop.efg package ========================== Submodules ---------- pyscf.pbc.prop.efg.rhf module ----------------------------- .. automodule:: pyscf.pbc.prop.efg.rhf :members: :undoc-members: :show-inheritance: Module contents --------------- .. automodule:: pyscf.pbc.prop.efg :members: :undoc-members: :show-inheritance: <file_sep>/docs/_sources/pyscf_api_docs/pyscf.data.rst.txt pyscf.data package ================== Submodules ---------- pyscf.data.elements module -------------------------- .. automodule:: pyscf.data.elements :members: :undoc-members: :show-inheritance: pyscf.data.gyro module ---------------------- .. automodule:: pyscf.data.gyro :members: :undoc-members: :show-inheritance: pyscf.data.nist module ---------------------- .. automodule:: pyscf.data.nist :members: :undoc-members: :show-inheritance: pyscf.data.nucprop module ------------------------- .. automodule:: pyscf.data.nucprop :members: :undoc-members: :show-inheritance: pyscf.data.radii module ----------------------- .. automodule:: pyscf.data.radii :members: :undoc-members: :show-inheritance: Module contents --------------- .. automodule:: pyscf.data :members: :undoc-members: :show-inheritance: <file_sep>/docs/_sources/pyscf_api_docs/pyscf.prop.freq.rst.txt pyscf.prop.freq package ======================= Submodules ---------- pyscf.prop.freq.rhf module -------------------------- .. automodule:: pyscf.prop.freq.rhf :members: :undoc-members: :show-inheritance: pyscf.prop.freq.rks module -------------------------- .. automodule:: pyscf.prop.freq.rks :members: :undoc-members: :show-inheritance: pyscf.prop.freq.uhf module -------------------------- .. automodule:: pyscf.prop.freq.uhf :members: :undoc-members: :show-inheritance: pyscf.prop.freq.uks module -------------------------- .. automodule:: pyscf.prop.freq.uks :members: :undoc-members: :show-inheritance: Module contents --------------- .. automodule:: pyscf.prop.freq :members: :undoc-members: :show-inheritance: <file_sep>/pyscf_api_docs/pyscf.gto.basis.rst pyscf.gto.basis package ======================= Submodules ---------- pyscf.gto.basis.dyall\_dz module -------------------------------- .. automodule:: pyscf.gto.basis.dyall_dz :members: :undoc-members: :show-inheritance: pyscf.gto.basis.dyall\_qz module -------------------------------- .. automodule:: pyscf.gto.basis.dyall_qz :members: :undoc-members: :show-inheritance: pyscf.gto.basis.dyall\_tz module -------------------------------- .. automodule:: pyscf.gto.basis.dyall_tz :members: :undoc-members: :show-inheritance: pyscf.gto.basis.dzp\_dunning module ----------------------------------- .. automodule:: pyscf.gto.basis.dzp_dunning :members: :undoc-members: :show-inheritance: pyscf.gto.basis.faegre\_dz module --------------------------------- .. automodule:: pyscf.gto.basis.faegre_dz :members: :undoc-members: :show-inheritance: pyscf.gto.basis.iglo3 module ---------------------------- .. automodule:: pyscf.gto.basis.iglo3 :members: :undoc-members: :show-inheritance: pyscf.gto.basis.minao module ---------------------------- .. automodule:: pyscf.gto.basis.minao :members: :undoc-members: :show-inheritance: pyscf.gto.basis.parse\_bfd\_pp module ------------------------------------- .. automodule:: pyscf.gto.basis.parse_bfd_pp :members: :undoc-members: :show-inheritance: pyscf.gto.basis.parse\_gaussian module -------------------------------------- .. automodule:: pyscf.gto.basis.parse_gaussian :members: :undoc-members: :show-inheritance: pyscf.gto.basis.parse\_molpro module ------------------------------------ .. automodule:: pyscf.gto.basis.parse_molpro :members: :undoc-members: :show-inheritance: pyscf.gto.basis.parse\_nwchem module ------------------------------------ .. automodule:: pyscf.gto.basis.parse_nwchem :members: :undoc-members: :show-inheritance: Module contents --------------- .. automodule:: pyscf.gto.basis :members: :undoc-members: :show-inheritance: <file_sep>/pyscf_api_docs/pyscf.symm.rst pyscf.symm package ================== Submodules ---------- pyscf.symm.Dmatrix module ------------------------- .. automodule:: pyscf.symm.Dmatrix :members: :undoc-members: :show-inheritance: pyscf.symm.addons module ------------------------ .. automodule:: pyscf.symm.addons :members: :undoc-members: :show-inheritance: pyscf.symm.basis module ----------------------- .. automodule:: pyscf.symm.basis :members: :undoc-members: :show-inheritance: pyscf.symm.cg module -------------------- .. automodule:: pyscf.symm.cg :members: :undoc-members: :show-inheritance: pyscf.symm.geom module ---------------------- .. automodule:: pyscf.symm.geom :members: :undoc-members: :show-inheritance: pyscf.symm.param module ----------------------- .. automodule:: pyscf.symm.param :members: :undoc-members: :show-inheritance: pyscf.symm.sph module --------------------- .. automodule:: pyscf.symm.sph :members: :undoc-members: :show-inheritance: Module contents --------------- .. automodule:: pyscf.symm :members: :undoc-members: :show-inheritance: <file_sep>/docs/_sources/pyscf_api_docs/pyscf.mp.rst.txt pyscf.mp package ================ Submodules ---------- pyscf.mp.dfmp2 module --------------------- .. automodule:: pyscf.mp.dfmp2 :members: :undoc-members: :show-inheritance: pyscf.mp.gmp2 module -------------------- .. automodule:: pyscf.mp.gmp2 :members: :undoc-members: :show-inheritance: pyscf.mp.mp2 module ------------------- .. automodule:: pyscf.mp.mp2 :members: :undoc-members: :show-inheritance: pyscf.mp.mp2f12\_slow module ---------------------------- .. automodule:: pyscf.mp.mp2f12_slow :members: :undoc-members: :show-inheritance: pyscf.mp.ump2 module -------------------- .. automodule:: pyscf.mp.ump2 :members: :undoc-members: :show-inheritance: Module contents --------------- .. automodule:: pyscf.mp :members: :undoc-members: :show-inheritance: <file_sep>/docs/_sources/requirements.txt pyscf ablog myst-parser sphinx-material<file_sep>/docs/_sources/pyscf_api_docs/pyscf.pbc.prop.polarizability.rst.txt pyscf.pbc.prop.polarizability package ===================================== Submodules ---------- pyscf.pbc.prop.polarizability.rhf module ---------------------------------------- .. automodule:: pyscf.pbc.prop.polarizability.rhf :members: :undoc-members: :show-inheritance: pyscf.pbc.prop.polarizability.rks module ---------------------------------------- .. automodule:: pyscf.pbc.prop.polarizability.rks :members: :undoc-members: :show-inheritance: Module contents --------------- .. automodule:: pyscf.pbc.prop.polarizability :members: :undoc-members: :show-inheritance: <file_sep>/pyscf_api_docs/pyscf.pbc.grad.rst pyscf.pbc.grad package ====================== Submodules ---------- pyscf.pbc.grad.krhf module -------------------------- .. automodule:: pyscf.pbc.grad.krhf :members: :undoc-members: :show-inheritance: pyscf.pbc.grad.krks module -------------------------- .. automodule:: pyscf.pbc.grad.krks :members: :undoc-members: :show-inheritance: pyscf.pbc.grad.kuhf module -------------------------- .. automodule:: pyscf.pbc.grad.kuhf :members: :undoc-members: :show-inheritance: pyscf.pbc.grad.kuks module -------------------------- .. automodule:: pyscf.pbc.grad.kuks :members: :undoc-members: :show-inheritance: Module contents --------------- .. automodule:: pyscf.pbc.grad :members: :undoc-members: :show-inheritance: <file_sep>/docs/_sources/pyscf_api_docs/pyscf.prop.rst.txt pyscf.prop package ================== Subpackages ----------- .. toctree:: :maxdepth: 4 pyscf.prop.efg pyscf.prop.esr pyscf.prop.freq pyscf.prop.gtensor pyscf.prop.hfc pyscf.prop.magnetizability pyscf.prop.nmr pyscf.prop.nsr pyscf.prop.polarizability pyscf.prop.rotational_gtensor pyscf.prop.ssc pyscf.prop.zfs Module contents --------------- .. automodule:: pyscf.prop :members: :undoc-members: :show-inheritance: <file_sep>/pyscf_api_docs/pyscf.mcscf.rst pyscf.mcscf package =================== Submodules ---------- pyscf.mcscf.PiOS module ----------------------- .. automodule:: pyscf.mcscf.PiOS :members: :undoc-members: :show-inheritance: pyscf.mcscf.addons module ------------------------- .. automodule:: pyscf.mcscf.addons :members: :undoc-members: :show-inheritance: pyscf.mcscf.avas module ----------------------- .. automodule:: pyscf.mcscf.avas :members: :undoc-members: :show-inheritance: pyscf.mcscf.casci module ------------------------ .. automodule:: pyscf.mcscf.casci :members: :undoc-members: :show-inheritance: pyscf.mcscf.casci\_symm module ------------------------------ .. automodule:: pyscf.mcscf.casci_symm :members: :undoc-members: :show-inheritance: pyscf.mcscf.chkfile module -------------------------- .. automodule:: pyscf.mcscf.chkfile :members: :undoc-members: :show-inheritance: pyscf.mcscf.df module --------------------- .. automodule:: pyscf.mcscf.df :members: :undoc-members: :show-inheritance: pyscf.mcscf.dmet\_cas module ---------------------------- .. automodule:: pyscf.mcscf.dmet_cas :members: :undoc-members: :show-inheritance: pyscf.mcscf.mc1step module -------------------------- .. automodule:: pyscf.mcscf.mc1step :members: :undoc-members: :show-inheritance: pyscf.mcscf.mc1step\_symm module -------------------------------- .. automodule:: pyscf.mcscf.mc1step_symm :members: :undoc-members: :show-inheritance: pyscf.mcscf.mc2step module -------------------------- .. automodule:: pyscf.mcscf.mc2step :members: :undoc-members: :show-inheritance: pyscf.mcscf.mc\_ao2mo module ---------------------------- .. automodule:: pyscf.mcscf.mc_ao2mo :members: :undoc-members: :show-inheritance: pyscf.mcscf.newton\_casscf module --------------------------------- .. automodule:: pyscf.mcscf.newton_casscf :members: :undoc-members: :show-inheritance: pyscf.mcscf.newton\_casscf\_symm module --------------------------------------- .. automodule:: pyscf.mcscf.newton_casscf_symm :members: :undoc-members: :show-inheritance: pyscf.mcscf.ucasci module ------------------------- .. automodule:: pyscf.mcscf.ucasci :members: :undoc-members: :show-inheritance: pyscf.mcscf.umc1step module --------------------------- .. automodule:: pyscf.mcscf.umc1step :members: :undoc-members: :show-inheritance: pyscf.mcscf.umc2step module --------------------------- .. automodule:: pyscf.mcscf.umc2step :members: :undoc-members: :show-inheritance: pyscf.mcscf.umc\_ao2mo module ----------------------------- .. automodule:: pyscf.mcscf.umc_ao2mo :members: :undoc-members: :show-inheritance: Module contents --------------- .. automodule:: pyscf.mcscf :members: :undoc-members: :show-inheritance: <file_sep>/docs/_sources/pyscf_api_docs/pyscf.pbc.dft.rst.txt pyscf.pbc.dft package ===================== Submodules ---------- pyscf.pbc.dft.cdft module ------------------------- .. automodule:: pyscf.pbc.dft.cdft :members: :undoc-members: :show-inheritance: pyscf.pbc.dft.gen\_grid module ------------------------------ .. automodule:: pyscf.pbc.dft.gen_grid :members: :undoc-members: :show-inheritance: pyscf.pbc.dft.krks module ------------------------- .. automodule:: pyscf.pbc.dft.krks :members: :undoc-members: :show-inheritance: pyscf.pbc.dft.kroks module -------------------------- .. automodule:: pyscf.pbc.dft.kroks :members: :undoc-members: :show-inheritance: pyscf.pbc.dft.kuks module ------------------------- .. automodule:: pyscf.pbc.dft.kuks :members: :undoc-members: :show-inheritance: pyscf.pbc.dft.multigrid module ------------------------------ .. automodule:: pyscf.pbc.dft.multigrid :members: :undoc-members: :show-inheritance: pyscf.pbc.dft.numint module --------------------------- .. automodule:: pyscf.pbc.dft.numint :members: :undoc-members: :show-inheritance: pyscf.pbc.dft.rks module ------------------------ .. automodule:: pyscf.pbc.dft.rks :members: :undoc-members: :show-inheritance: pyscf.pbc.dft.roks module ------------------------- .. automodule:: pyscf.pbc.dft.roks :members: :undoc-members: :show-inheritance: pyscf.pbc.dft.uks module ------------------------ .. automodule:: pyscf.pbc.dft.uks :members: :undoc-members: :show-inheritance: Module contents --------------- .. automodule:: pyscf.pbc.dft :members: :undoc-members: :show-inheritance:
af7031297533203a3b4e14f2462a0d5e15c13536
[ "HTML", "reStructuredText", "Markdown", "Text", "Shell" ]
86
reStructuredText
jamesETsmith/ablog_test.github.io
aaf48db23ecaf01db1c9f36690ce102b4cdc10c6
01d046bd5bc40ec64f23b342a124f817dda74b30
refs/heads/master
<file_sep>package edu.temple.spinnercolor; import android.content.Intent; import android.content.res.Resources; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.AdapterView; import android.widget.GridView; import static edu.temple.spinnercolor.R.id.grid_view; public class PaletteActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_palette); final GridView mygrid = (GridView) findViewById(grid_view); final View mylayout = findViewById(R.id.activity_palette); final String[] myColors = {"White", "Red", "Yellow", "Green", "Blue", "Black", "Cyan", "Magenta", "Green", "Gray"}; Resources res = getResources(); String[] colorLabels = res.getStringArray(R.array.color_array); CustomAdapter adapter = new CustomAdapter(this,myColors,colorLabels); mygrid.setAdapter(adapter); mygrid.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { //mylayout.setBackgroundColor(Color.parseColor(((TextView) view).getText().toString())); Intent intent = new Intent(PaletteActivity.this, CanvasActivity.class); //pass the data from this activity to canvas intent.putExtra("color_key", myColors[position]); startActivity(intent); } }); /* mygrid.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { mylayout.setBackgroundColor(Color.parseColor(((TextView) view).getText().toString())); String color = parent.getSelectedItem().toString(); Intent intent = new Intent(PaletteActivity.this, CanvasActivity.class); //pass the data from this activity to canvas intent.putExtra("colorStuff", myColors[position]); startActivity(intent); } @Override public void onNothingSelected(AdapterView<?> parent) { } }); */ } } <file_sep>package edu.temple.spinnercolor; import android.content.Intent; import android.graphics.Color; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.widget.RelativeLayout; public class CanvasActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_canvas); RelativeLayout view = (RelativeLayout) findViewById(R.id.activity_canvas); //get the intent used to launch this instance of activity Intent received = getIntent(); String dataReceived = received.getStringExtra("color_key"); view.setBackgroundColor(Color.parseColor(dataReceived)); } }
918695ad2ae84b0222897a2a003d840a90454459
[ "Java" ]
2
Java
Frankiskandar/SpinnerColorPicker
470102acd7857ba76ee1a0387abb9228479764a8
7238b1cbdd7e14937ea7a43b767bedf39204ad00
refs/heads/master
<repo_name>akhabali/talend-components<file_sep>/salesforce/pom.xml <?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation=" http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <parent> <groupId>org.talend.components</groupId> <artifactId>talend-components</artifactId> <version>0.0.1-SNAPSHOT</version> </parent> <artifactId>salesforce</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>jar</packaging> <name>Talend component :: Salesforce</name> <description>A suite of Talend component for Salesforce</description> <dependencies> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <scope>provided</scope> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-api</artifactId> <scope>provided</scope> </dependency> <!-- salesforce dependencies--> <dependency> <groupId>com.force.api</groupId> <artifactId>force-wsc</artifactId> <version>39.0.5</version> </dependency> <dependency> <groupId>com.force.api</groupId> <artifactId>force-partner-api</artifactId> <version>42.0.0</version> </dependency> <dependency> <groupId>net.sourceforge.javacsv</groupId> <artifactId>javacsv</artifactId> <version>2.0</version> </dependency> <dependency> <groupId>org.antlr</groupId> <artifactId>antlr4-runtime</artifactId> <version>4.6</version> </dependency> <!-- test --> <dependency> <groupId>org.talend.sdk.component</groupId> <artifactId>component-runtime-manager</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>org.talend.sdk.component</groupId> <artifactId>component-runtime-junit</artifactId> <scope>provided</scope> </dependency> <dependency> <groupId>org.talend.sdk.component</groupId> <artifactId>component-runtime-http-junit</artifactId> <scope>provided</scope> </dependency> <dependency> <groupId>org.junit.jupiter</groupId> <artifactId>junit-jupiter-api</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-simple</artifactId> <scope>provided</scope> </dependency> </dependencies> </project> <file_sep>/jdbc/src/main/java/org/talend/components/jdbc/package-info.java @Components(family = "Jdbc", categories = "Databases") @Icon(value = Icon.IconType.CUSTOM, custom = "JDBC") package org.talend.components.jdbc; import org.talend.sdk.component.api.component.Components; import org.talend.sdk.component.api.component.Icon; <file_sep>/pom.xml <?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation=" http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>org.talend.components</groupId> <artifactId>talend-components</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>pom</packaging> <name>Talend Components</name> <description>A suite of Talend components</description> <properties> <tacokit.api.version>1.0.2-SNAPSHOT</tacokit.api.version> <tacokit.api.impl.version>1.0.1-SNAPSHOT</tacokit.api.impl.version> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <talend.documentation.htmlAndPdf>false</talend.documentation.htmlAndPdf> <junit-platform-surefire-provider.version>1.2.0</junit-platform-surefire-provider.version> <junit5.version>5.2.0</junit5.version> <talend.component.studioHome>C:\\Users\\akhabali\\dev\\TalendStudio\\7.0.1\\TOS_DI-20180530_1932-V7.1.1SNAPSHOT </talend.component.studioHome> </properties> <modules> <module>salesforce</module> <module>jdbc</module> </modules> <dependencyManagement> <dependencies> <dependency> <groupId>org.talend.sdk.component</groupId> <artifactId>component-api</artifactId> <version>${tacokit.api.version}</version> <scope>provided</scope> </dependency> <dependency> <groupId>org.talend.sdk.component</groupId> <artifactId>component-runtime-junit</artifactId> <version>${tacokit.api.impl.version}</version> <scope>test</scope> <exclusions> <exclusion> <groupId>junit</groupId> <artifactId>junit</artifactId> </exclusion> </exclusions> </dependency> <dependency> <groupId>org.talend.sdk.component</groupId> <artifactId>component-runtime-http-junit</artifactId> <version>${tacokit.api.impl.version}</version> <scope>test</scope> </dependency> <dependency> <groupId>org.talend.sdk.component</groupId> <artifactId>component-runtime-manager</artifactId> <version>${tacokit.api.impl.version}</version> <scope>test</scope> </dependency> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <version>1.16.20</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-api</artifactId> <version>1.7.25</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-simple</artifactId> <version>1.7.25</version> </dependency> <dependency> <groupId>org.junit.jupiter</groupId> <artifactId>junit-jupiter-api</artifactId> <version>${junit5.version}</version> </dependency> </dependencies> </dependencyManagement> <dependencies> <dependency> <groupId>org.talend.sdk.component</groupId> <artifactId>component-api</artifactId> </dependency> </dependencies> <build> <extensions> <extension> <groupId>org.talend.sdk.component</groupId> <artifactId>talend-component-maven-plugin</artifactId> <version>${tacokit.api.impl.version}</version> </extension> </extensions> <plugins> <plugin> <groupId>org.talend.sdk.component</groupId> <artifactId>talend-component-maven-plugin</artifactId> <version>${tacokit.api.impl.version}</version> <executions> <execution> <id>dependencies</id> <phase>process-classes</phase> <goals> <goal>dependencies</goal> </goals> </execution> <execution> <id>validate</id> <phase>prepare-package</phase> <goals> <goal>validate</goal> </goals> </execution> <execution> <id>documentation</id> <phase>prepare-package</phase> <goals> <goal>asciidoc</goal> </goals> <configuration> <formats> <html>${project.build.directory}/doc.html</html> </formats> </configuration> </execution> </executions> <configuration> </configuration> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <version>3.7.0</version> <configuration> <source>1.8</source> <target>1.8</target> <forceJavacCompilerUse>true</forceJavacCompilerUse> <compilerId>javac</compilerId> <fork>true</fork> <compilerArgs> <arg>-parameters</arg> </compilerArgs> </configuration> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-surefire-plugin</artifactId> <version>2.21.0</version> <configuration> <forkCount>1</forkCount> <!-- never use 0, it affects too much test behavior to be accurate --> <trimStackTrace>false</trimStackTrace> <runOrder>alphabetical</runOrder> </configuration> <dependencies> <dependency> <groupId>org.junit.platform</groupId> <artifactId>junit-platform-surefire-provider</artifactId> <version>${junit-platform-surefire-provider.version}</version> </dependency> <dependency> <groupId>org.junit.jupiter</groupId> <artifactId>junit-jupiter-engine</artifactId> <version>${junit5.version}</version> </dependency> <dependency> <groupId>org.junit.vintage</groupId> <artifactId>junit-vintage-engine</artifactId> <version>${junit5.version}</version> </dependency> </dependencies> </plugin> </plugins> </build> <repositories> <repository> <id>oss-snapshot</id> <url>https://oss.sonatype.org/content/repositories/snapshots/</url> <snapshots> <enabled>true</enabled> </snapshots> <releases> <enabled>false</enabled> </releases> </repository> <repository> <id>oss-releases</id> <url>https://oss.sonatype.org/content/repositories/releases/</url> <snapshots> <enabled>false</enabled> </snapshots> <releases> <enabled>true</enabled> </releases> </repository> </repositories> <pluginRepositories> <pluginRepository> <id>oss</id> <url>https://oss.sonatype.org/content/repositories/snapshots/</url> <snapshots> <enabled>true</enabled> </snapshots> <releases> <enabled>false</enabled> </releases> </pluginRepository> </pluginRepositories> </project> <file_sep>/salesforce/src/test/java/org/talend/components/salesforce/service/BasicDatastoreServiceTest.java package org.talend.components.salesforce.service; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNotNull; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; import org.talend.components.salesforce.datastore.BasicDataStore; import org.talend.sdk.component.api.service.configuration.LocalConfiguration; import org.talend.sdk.component.api.service.healthcheck.HealthCheckStatus; import org.talend.sdk.component.junit.BaseComponentsHandler; import org.talend.sdk.component.junit.http.api.HttpApiHandler; import org.talend.sdk.component.junit.http.junit5.HttpApi; import org.talend.sdk.component.junit.http.junit5.HttpApiInject; import org.talend.sdk.component.junit5.Injected; import org.talend.sdk.component.junit5.WithComponents; import org.talend.sdk.component.maven.MavenDecrypter; import org.talend.sdk.component.maven.Server; @WithComponents("org.talend.components.salesforce") //@HttpApi(logLevel = "DEBUG", useSsl = true) public class BasicDatastoreServiceTest { // static { // System.setProperty("talend.junit.http.capture", "true"); // } @Injected private BaseComponentsHandler componentsHandler; // @HttpApiInject // private HttpApiHandler<?> httpApiHandler; private final static MavenDecrypter mavenDecrypter = new MavenDecrypter(); private static Server serverWithPassword; private static Server serverWithSecuritykey; @BeforeAll static void init() { serverWithPassword = mavenDecrypter.find("salesforce-password"); serverWithSecuritykey = mavenDecrypter.find("salesforce-securitykey"); } @Test void validateBasicConnectionOK() { final BasicDatastoreService service = componentsHandler.findService(BasicDatastoreService.class); final Messages i18n = componentsHandler.findService(Messages.class); final LocalConfiguration configuration = componentsHandler.findService(LocalConfiguration.class); final BasicDataStore datasore = new BasicDataStore(); datasore.setUserId(serverWithPassword.getUsername()); datasore.setPassword(serverWithPassword.getPassword()); datasore.setSecurityKey(serverWithSecuritykey.getPassword()); final HealthCheckStatus status = service.validateBasicConnection(datasore, i18n, configuration); assertEquals(i18n.healthCheckOk(), status.getComment()); assertEquals(HealthCheckStatus.Status.OK, status.getStatus()); } @Test void validateBasicConnectionFailed() { final BasicDatastoreService service = componentsHandler.findService(BasicDatastoreService.class); final Messages i18n = componentsHandler.findService(Messages.class); final LocalConfiguration configuration = componentsHandler.findService(LocalConfiguration.class); final HealthCheckStatus status = service.validateBasicConnection(new BasicDataStore(), i18n, configuration); assertNotNull(status); assertEquals(HealthCheckStatus.Status.KO, status.getStatus()); assertFalse(status.getComment().isEmpty()); } } <file_sep>/salesforce/src/main/java/org/talend/components/salesforce/service/BasicDatastoreService.java package org.talend.components.salesforce.service; import static org.talend.sdk.component.api.service.healthcheck.HealthCheckStatus.Status.KO; import static org.talend.sdk.component.api.service.healthcheck.HealthCheckStatus.Status.OK; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.net.Proxy; import java.net.ProxySelector; import java.net.URI; import java.util.Iterator; import java.util.Properties; import javax.xml.namespace.QName; import com.sforce.async.AsyncApiException; import com.sforce.async.BulkConnection; import com.sforce.soap.partner.PartnerConnection; import com.sforce.soap.partner.fault.ApiFault; import com.sforce.ws.ConnectionException; import com.sforce.ws.ConnectorConfig; import com.sforce.ws.SessionRenewer; import org.talend.components.salesforce.datastore.BasicDataStore; import org.talend.sdk.component.api.configuration.Option; import org.talend.sdk.component.api.service.Service; import org.talend.sdk.component.api.service.configuration.LocalConfiguration; import org.talend.sdk.component.api.service.healthcheck.HealthCheck; import org.talend.sdk.component.api.service.healthcheck.HealthCheckStatus; import lombok.extern.slf4j.Slf4j; @Slf4j @Service public class BasicDatastoreService { private static final int DEFAULT_TIMEOUT = 60000; private static final String CONFIG_FILE_lOCATION_KEY = "org.talend.component.salesforce.config.file"; private static final String RETIRED_ENDPOINT = "www.salesforce.com"; private static final String ACTIVE_ENDPOINT = "login.salesforce.com"; private static final String DEFAULT_API_VERSION = "42.0"; public static final String URL = "https://" + ACTIVE_ENDPOINT + "/services/Soap/u/" + DEFAULT_API_VERSION; @HealthCheck("basic.healthcheck") public HealthCheckStatus validateBasicConnection(@Option final BasicDataStore datastore, Messages i18n, LocalConfiguration configuration) { try { connect(datastore, configuration); } catch (ConnectionException ex) { String error; if (ApiFault.class.isInstance(ex)) { final ApiFault fault = ApiFault.class.cast(ex); error = fault.getExceptionCode() + " " + fault.getExceptionMessage(); } else { error = ex.getMessage(); } return new HealthCheckStatus(KO, i18n.healthCheckFailed(error)); } return new HealthCheckStatus(OK, i18n.healthCheckOk()); } private Properties loadCustomConfiguration(final LocalConfiguration configuration) { final String configFile = configuration.get(CONFIG_FILE_lOCATION_KEY); try (InputStream is = configFile != null && !configFile.isEmpty() ? (new FileInputStream(configFile)) : null) { if (is != null) { return new Properties() {{ load(is); }}; } } catch (IOException e) { log.warn("not found the property file, will use the default value for endpoint and timeout", e); } return null; } public PartnerConnection connect(final BasicDataStore datastore, final LocalConfiguration localConfiguration) throws ConnectionException { final Properties props = loadCustomConfiguration(localConfiguration); final Integer timeout = (props != null) ? Integer.parseInt(props.getProperty("timeout", String.valueOf(DEFAULT_TIMEOUT))) : DEFAULT_TIMEOUT; String endpoint = props != null ? props.getProperty("endpoint", URL) : URL; if (endpoint.contains(RETIRED_ENDPOINT)) { endpoint = endpoint.replaceFirst(RETIRED_ENDPOINT, ACTIVE_ENDPOINT); } final String ep = endpoint; ConnectorConfig config = new ConnectorConfig() { @Override public Proxy getProxy() { final Iterator<Proxy> pxyIt = ProxySelector.getDefault().select(URI.create(ep)).iterator(); return pxyIt.hasNext() ? pxyIt.next() : super.getProxy(); } }; config.setAuthEndpoint(endpoint); config.setUsername(datastore.getUserId()); String password = <PASSWORD>.<PASSWORD>(); String securityKey = datastore.getSecurityKey(); if (securityKey != null && !securityKey.trim().isEmpty()) { password = <PASSWORD> + securityKey; } config.setPassword(<PASSWORD>); config.setConnectionTimeout(timeout); config.setCompression(true);// This should only be false when doing debugging. config.setUseChunkedPost(true); config.setValidateSchema(false); // Notes on how to test this // http://thysmichels.com/2014/02/15/salesforce-wsc-partner-connection-session-renew-when-session-timeout/ config.setSessionRenewer((SessionRenewer) connectorConfig -> { log.debug("renewing session..."); SessionRenewer.SessionRenewalHeader header = new SessionRenewer.SessionRenewalHeader(); connectorConfig.setSessionId(null); PartnerConnection connection; connection = new PartnerConnection(connectorConfig); header.name = new QName("urn:partner.soap.sforce.com", "SessionHeader"); header.headerElement = connection.getSessionHeader(); log.debug("session renewed!"); return header; }); return new PartnerConnection(config); } public BulkConnection bulkConnect(final BasicDataStore datastore, final LocalConfiguration configuration) throws AsyncApiException, ConnectionException { final PartnerConnection partnerConnection = connect(datastore, configuration); final ConnectorConfig partnerConfig = partnerConnection.getConfig(); ConnectorConfig bulkConfig = new ConnectorConfig(); bulkConfig.setSessionId(partnerConfig.getSessionId()); // For session renew bulkConfig.setSessionRenewer(partnerConfig.getSessionRenewer()); bulkConfig.setUsername(partnerConfig.getUsername()); bulkConfig.setPassword(<PASSWORD>Config.getPassword()); /* * The endpoint for the Bulk API service is the same as for the normal SOAP uri until the /Soap/ part. From here * it's '/async/versionNumber' */ String soapEndpoint = partnerConfig.getServiceEndpoint(); // set it by a default property file // Service endpoint should be like this: // https://ap1.salesforce.com/services/Soap/u/37.0/00D90000000eSq3 String apiVersion = soapEndpoint.substring(soapEndpoint.lastIndexOf("/services/Soap/u/") + 17); apiVersion = apiVersion.substring(0, apiVersion.indexOf("/")); String restEndpoint = soapEndpoint.substring(0, soapEndpoint.indexOf("Soap/")) + "async/" + apiVersion; bulkConfig.setRestEndpoint(restEndpoint); bulkConfig.setCompression(true);// This should only be false when doing debugging. bulkConfig.setTraceMessage(false); bulkConfig.setValidateSchema(false); return new BulkConnection(bulkConfig); } } <file_sep>/README.md # talend-components Some talend components
974034c288168203eaf2a06a412fa11ce452a5e7
[ "Markdown", "Java", "Maven POM" ]
6
Maven POM
akhabali/talend-components
35ed8cb85c8df50cdeff5381fe64c3347b6f8b41
c399737195082ad2772e00d0bdd08db18b8a3691
refs/heads/master
<file_sep><?php class Address extends Widget{ public function getData(){ return array("street"=>"123 Washington St","state"=>"CA","city"=>"Sunnyvale"); } } ?><file_sep><?php class Widget{ var $request; function __construct($request){ $this->request= $request; } public function getData(){ return array(); } } ?><file_sep>stupidMVC ========== This project helps you start with a very light weight MVC, with Mustache templating to start with Usage ---------- Once you download this mvc put it in your htdocs (or where ever you want ). You should see a folder structure like this <pre> My-Folder/ |-application/ | |-helpers/ | | |-Mustache.php | | |-Route.php | | |-Router.php | | |-Page.php | | |-Widget.php | | | |-model/ | | |-Index.php | | | |-view/ | | |-templates/ | | |-index.mustache | |-widgets/ | |-Address.php | |-test/ | |-TestWidget.php | |-static/ | |-css/ | | |-test.css | | | |-images/ | | | |-js/ | |-.DS_Store |-.htaccess |-README </pre> Now you can put your Models inside the model folder , views in the view folder etc. You can add new entrypoints in the entrypoints.json file This should help you get started with the web application For details about mustache see http://mustache.github.com/ Requirements ------------- Turn Mod rewrite on - on your apache I am working with php v 5.3+ (not sure if this is backwards compatible please test it yourself and let me know) Add this to httpd.conf <pre> &lt;Directory "/path/to/StupidMVC"&gt; AllowOverride all Order Deny,Allow Allow from all &lt;/Directory&gt; </pre> How Things Work ================ entrypoints.json ----------------- This files define all permissible entry points and the model classes , views, widgets to be used for rendering content with respect to that entrypoint. This file has to be in the serialised JSON format . (use double quotes to stringify stuff , single quote means invalid JSON) if there is any error in this file the application will not work. Models ------- Models reside in the Models Folder The Model class (say "Index.php") is assumed to have a class that has the same name as the file, ignoring the file extension(so for "Index.php" , the class name should be "Index" for "TestClass.inc" the class name should be "TestClass" ). This class should extend the class "Page". Override the "gatData" method of "Page" class to return the data to the mustache template (view). Widgets -------- Widgets reside in the widgets folder Widgets are smaller modules that can be included in pages just by including them in the respective entrypoint config in the entrypoints.json file The Widgets have a similar naming requirement to the Models , and the Widgets should extend the class "Widget". Data can be returned by the widgets by overriding the "getData" method. widgets data can be accessed in the mustache templates like this <pre> {{#widgets}} {{address.street_name}} {{/widgets}} </pre> View ----- View templates (extension ".mustache") reside in the view folder For details about mustache see http://mustache.github.com/ See the example config for the entry point "index" and try to figure out its model classes and widgets , view and you should get an understanding of how things work . Serving Static Files --------------------- Put all the static files in the static folder ( you can create any path in the static folder ). and they will be served from urls like these "http://localhost/static/css/test.css" (see index.mustache it has a css example) <file_sep><?php class TestWidget extends Widget{ public function getData(){ return array("data"=>"test data"); } } ?><file_sep><?php class Index extends Page{ public function getData(){ $data = array('name' => "Web User"); return $data; } } ?><file_sep><?php include 'Route.php'; class Router { var $routing_table; var $template_engine; function __construct($routing_table,$template_engine){ $this->routing_table = $routing_table; $this->template_engine= $template_engine; } private function getRoute($entrypoint){ $route_info = $this->routing_table[$entrypoint]; $route= new Route($route_info); return $route; } public function dispatch($entrypoint){ $route= $this->getRoute($entrypoint); $view_path = $route->getView(); $model_path = $route->getModel(); $model_class_name = $route->getModelClassName(); $widgets = $route->getWidgets(); if(file_exists($view_path) && file_exists($model_path)){ $view_template = file_get_contents($view_path); include($model_path); $page = new $model_class_name($_REQUEST); if(!$page){ $page = new Page($_REQUEST); } $page_data = $page->getData(); $page_data["widgets"]= array(); foreach($widgets as $widget_name=>$widget_path ){ if(file_exists($widget_path)){ include_once($widget_path); $widget = new $widget_name($_REQUEST); if(!$widget){ continue; } $page_data["widgets"][strtolower($widget_name)]= $widget->getData(); } } if(empty($page_data["widgets"])){ unset($page_data["widgets"]); } echo $this->template_engine->render($view_template,$page_data); }else{ header("HTTP/1.0 404 Not Found"); exit; } } } ?><file_sep><?php class Route{ var $model; var $view; var $modelClass; var $widgets; function __construct($route_array=array()){ if(!isset($route_array["model"])|| !isset($route_array["view"])){ header("HTTP/1.0 404 Not Found"); exit; }else{ $this->model = "model/".$route_array["model"]; $this->view = "view/".$route_array["view"]; $this->widgets = array(); foreach($route_array["widgets"] as $widget_path){ $widget_name_arr = explode("/",$widget_path); $widget_name = $widget_name_arr[count($widget_name_arr)-1]; $widget_name = explode(".",$widget_name); $widget_name = $widget_name[0]; $this->widgets[$widget_name] = "widgets/".$widget_path; } $model_class_name_arr= explode(".",$route_array["model"]); $this->modelClass=$model_class_name_arr[0]; } } public function getModel(){ return $this->model; } public function getView(){ return $this->view; } public function getModelClassName(){ return $this->modelClass; } public function getWidgets(){ return $this->widgets; } } ?><file_sep><?php class Page{ var $request; function __construct($request){ $this->request = $request; } public function getData(){ return array(); } } ?><file_sep><?php ob_start(); include_once 'helpers/Mustache.php'; include_once 'helpers/Router.php'; include_once 'helpers/Route.php'; include_once 'helpers/Page.php'; include_once 'helpers/Widget.php'; try { $entrypoint = $_SERVER['REQUEST_URI']; $entrypoint = explode("?",$entrypoint); $entrypoint = $entrypoint[0]; $routing_table_path = "entrypoints.json"; $routing_table_content = file_get_contents($routing_table_path); $routingtable = json_decode($routing_table_content,true); $mustache = new Mustache(); $router = new Router($routingtable,$mustache); $route=$router->dispatch($entrypoint); } catch (Exception $e) { } ob_flush(); ?>
68c33cdb486814147fa40387ee6643d740c02e05
[ "Markdown", "PHP" ]
9
PHP
oude3c/stupidMVC
d8d5bcd882837174f750b9245c89b8139c06f0e1
b362cfa18abeee1ef0a0e43383ffcb05a3007441
refs/heads/main
<file_sep>Nt-Injector Here is my first software that I code in C#. Hi, I'm Toffelz and this is my first software that I coded in C# on Visual Studio Code Community 2019. This software honestly is useless, it has no purpose but I will bring updates anyway because it tis a bit of software that I use to practice what I am learning in C# because I am only a beginner. <file_sep>using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using Nt_Injector.Properties; using DiscordRpcDemo; using System.Diagnostics; namespace Cour_Csharp_pour_nt { public partial class Form1 : Form { private DiscordRpc.EventHandlers handlers; private DiscordRpc.RichPresence presence; public Form1() { InitializeComponent(); Commande.Text = ""; } private void Debile_Click(object sender, EventArgs e) { lblHelloWorld.Text = "Maximale"; MessageBox.Show("Vous avez bien rendu bête Nt Games au niveau maximale", "Nt Injector 1.2 By : Toffelz"); Debile.Enabled = false; Commande.Text = "Le niveau de débiliter de Nt Games est au niveau Maximale"; pictureBox1.Image = Resources.Capture; } private void Spawn_Click(object sender, EventArgs e) { MessageBox.Show("Commande effectuer avec succés !","Nt Injector 1.2 By : Toffelz"); Debile.Enabled = true; Despawn.Enabled = true; Spawn.Enabled = false; pictureBox1.Image = Resources.nt_games_normal; Commande.Text = "Nt Games a été spawn avec succés !"; lblHelloWorld.Text = "Moyenne"; endormir.Enabled = true; reveiller.Enabled = true; buttonrandom.Enabled = true; } private void Despawn_Click(object sender, EventArgs e) { MessageBox.Show("Commande effectuer avec succés !", "Nt Injector 1.2 By : Toffelz"); Debile.Enabled = false; Despawn.Enabled = false; Spawn.Enabled = true; Commande.Text = "Nt Games a été despawn avec succés !"; lblHelloWorld.Text = "Inconnu"; reveiller.Enabled = false; endormir.Enabled = false; StatutNt2.Text = "Inconnu"; pictureBox1.Image = null; buttonrandom.Enabled = false; } private void Form1_Load(object sender, EventArgs e) { this.handlers = default(DiscordRpc.EventHandlers); DiscordRpc.Initialize("872513064325513246", ref this.handlers, true, null); this.handlers = default(DiscordRpc.EventHandlers); DiscordRpc.Initialize("872513064325513246", ref this.handlers, true, null); this.presence.details = "Nt Injector By : Toffelz"; this.presence.state = "Thanks to Nt Games !"; this.presence.largeImageKey = "logo_nt_injector"; this.presence.smallImageKey = "versionlogo"; this.presence.largeImageText = "Nt Injector"; this.presence.smallImageText = "Version : 1.2"; DiscordRpc.UpdatePresence(ref this.presence); } private void endormir_Click(object sender, EventArgs e) { Commande.Text = "Vous avez endormie Nt Games !"; endormir.Enabled = false; MessageBox.Show("Vous avez endormie Nt Games !", "Nt Injector 1.2 By : Toffelz"); StatutNt2.Text = "Endormie"; reveiller.Enabled = true; pictureBox1.Image = Resources.fonction_endormir_nt; } private void reveiller_Click(object sender, EventArgs e) { Commande.Text = "Vous avez reveiller Nt Games !"; reveiller.Enabled = false; endormir.Enabled = true; MessageBox.Show("Vous avez reveiller Nt Games !", "Nt Injector 1.2 By : Toffelz"); StatutNt2.Text = "Reveiller"; pictureBox1.Image = Resources.nt_games_normal; } private void bouttonrandom_Click(object sender, EventArgs e) { MessageBox.Show("Shoji la grosse merde !", "Nt Injector 1.2 By : Toffelz"); } private void PatchNote_Click(object sender, EventArgs e) { MessageBox.Show("Patch note Mise à Jour 1.2" + "\n" + "-Ajout de l'onglet Paramètre" + "\n" + "-Ajout de Credit" + "\n" + "-Ajout d'une checkbox permettant de désactiver le chat" + "\n" + "-Ajout d'un bouton Random" + "\n" + "-Ajout de bouton qui ramène au chaine Ytb de Toffelz et Nt Games", "Nt Injector 1.2 By : Toffelz"); } private void Disable_CheckedChanged(object sender, EventArgs e) { if (Disable.Checked) { Commande.Visible = false; } else { Commande.Visible = true; } } private void ToffelzYtb_Click(object sender, EventArgs e) { Process.Start("https://www.youtube.com/channel/UChB7vhqp5cNOfJ34f4K-0Mg"); } private void NtYtb_Click(object sender, EventArgs e) { Process.Start("https://www.youtube.com/channel/UCqI3x47OlUfndU3b9VhAwwQ"); } private void BouttonYoussef_Click(object sender, EventArgs e) { MessageBox.Show("Youssef le bg" , "Nt Injector 1.2 By : Toffelz"); } } }
d8e492a689172e7a9b9a2d5816821a259077c504
[ "Markdown", "C#" ]
2
Markdown
ToffelzWiiU/Nt-Injector
7f72b1a3de9d5ae6695f1abf54f32ced58fca232
3da9841bd828332ca50450356afa1d0da6c3d6fc
refs/heads/master
<file_sep>const request = require('request'); const fs = require('fs'); const db = require('./db'); const log = require('./log'); const wake = require('./wake'); const moment = require('moment'); const sharp = require('sharp'); let lastCollectAll = null; const lastQueryDev = {}; /* расписание для каждого устройства. id: [интервал_сбора_даных_в_часах_днём, интервал_сбора_даных_в_часах_ночью] */ const intervals = { 2: [6, 0], 3: [6, 0], 4: [0, 0] } const main = async () => { try { const devices = await getState(); for (let device of devices) { mainDev(device); } } catch (err) { log(err); } } const mainDev = async (dev) => { if (lastQueryDev[dev.devid] === undefined) { lastQueryDev[dev.devid] = null } const r = getRarity(dev.devid); if ((dev.charge >= 0.9) || ((r !== null) && (new Date() - lastQueryDev[dev.devid] >= (3600000 * r)))) { if (dev.up === null) { console.log(`${new Date().toJSON()} uncertain state ${dev.devid}`); } else if (dev.up) { getData(dev.devid); } else { try { await wake(dev.devid); getData(dev.devid); } catch (err) { log(err); } } if (dev.charge >= 0.8) { setTimeout(() => { console.log(`sending NOSLEEP for ${dev.devid}`); sendNoSleepSig(dev.devid); }, 240000); } } } const getRarity = (devid) => { let night = 0; const h = new Date().getHours(); if ((h > 19) || (h < 7)) { night = 1; } return intervals[devid] && intervals[devid][night] ? intervals[devid][night] : null; } const getState = () => { return new Promise((resolve, reject) => { request('http://geoworks.pro:3000/state', (error, resp, body) => { if (resp && resp.statusCode === 200) { const devices = []; try { devices.push(...JSON.parse(body)); } catch(e) {} resolve(devices); } else { reject(new Error('no valid answer')); } }); }); } const getData = async (id) => { console.log(`${new Date().toJSON()} try get data ${id}`); try { await getPhoto(id); } catch (e) { log(e); } try { db.addSensors(await getSensors(id)); } catch (e) { log(e); } lastQueryDev[id] = new Date(); } const getPhoto = (deviceID) => { return new Promise((resolve, reject) => { request(`http://geoworks.pro:3000/${deviceID}/photo`, {encoding: 'binary'}, (error, resp, body) => { if (error) { reject(error) } else if (resp.headers['content-type'] === 'image/jpeg') { const photoName = moment().utc().format('YYYY-MM-DDTHH:mm:ss'); const photoPath = `${__dirname}/../app-new-web/static/photos/${deviceID}/${photoName}.jpg`; const thumbPath = `${__dirname}/../app-new-web/static/photos/${deviceID}/thumb/${photoName}.jpg`; fs.writeFile(photoPath, body, 'binary', (err) => { if (err) { reject(err) } else { sharp(photoPath).resize(80).toFile(thumbPath, (err) => { if (err) { reject(err) } else { resolve() } }); } }); } else { reject(JSON.parse(body).error); } }); }); } const getSensors = (deviceID) => { return new Promise((resolve, reject) => { request(`http://geoworks.pro:3000/${deviceID}/sensors`, (error, resp, body) => { try { const respObj = JSON.parse(body); if (respObj.ok && respObj.sensors) { respObj.sensors.devid = deviceID; if (respObj.sensors.date) { respObj.sensors.origDate = respObj.sensors.date; respObj.sensors.date = moment().utc().toJSON(); } resolve(respObj.sensors); } else { reject(new Error(`sensors ${deviceID} failure`)); } } catch (e) { reject(new Error('no valid answer')); } }); }); } const sendNoSleepSig = (devid) => { return new Promise((resolve, reject) => { request(`http://geoworks.pro:3000/${devid}/nosleep`, (error, resp, body) => { if (resp && resp.statusCode === 200) { resolve(); } else { reject(new Error(`can't send nsoleep sig for ${devid}`)); } }); }); } const onStart = async () => { main(); setInterval(main, 300 * 1000); } onStart(); <file_sep>const { MongoClient } = require('mongodb'); let db; MongoClient.connect('mongodb://localhost:27017/exapp', function(err, dblink) { if (err) { console.error(err); } db = dblink; }); module.exports.addSensors = (data) => { db.collection('sensors').insertOne(data); } /* module.exports.stream = { date: (devid, date) => { db.collection('stream').updateOne( { devid }, { $set: { date } }, { upsert: true } ) }, live: (devid, live) => { db.collection('stream').updateOne( { devid }, { $set: { live } }, { upsert: true } ); } } module.exports.resetLive = (devs) => { for (let dev of devs) { module.exports.stream.live(dev, false); } } */<file_sep>/* делает превью всем изображениям в определённой директории. Использовалось, когда нужно было сделать превью уже имеющимся фоткам. */ const fs = require('fs'); const sharp = require('sharp'); const dir = '../app-new-web/static/photos/4/'; const resizePhoto = (file) => { return new Promise((resolve, reject) => { sharp(dir + file).resize(80).toFile(dir + `thumb/` + file, (err) => { if (err) { reject(err) } else { resolve() } }); }) } const main = () => { fs.readdir(dir, (err, filesarr) => { if (filesarr) { filesarr = filesarr.sort().filter(f => f.indexOf('.jpg') > 0) } (async () => { for (let file of filesarr) { try { await resizePhoto(file); console.log('ok ' + file); } catch (e) { console.log('NOT ' + file) } } })() }); } main();
f8b920907db7341d7b7bf2bf0dd48adf436e1f55
[ "JavaScript" ]
3
JavaScript
sanygus/app-new
5870ad01f434f32c13da043fed62ea9eb2bee5cf
ba492971989795c73e5584c31f03470cf6174ded
refs/heads/master
<repo_name>nkrajew/ds_salary_proj<file_sep>/model_building.py # -*- coding: utf-8 -*- """ Created on Thu Sep 24 13:05:05 2020 @author: nkraj """ import pandas as pd import matplotlib.pyplot as plt import numpy as np df = pd.read_csv('eda_data.csv') # choose relevant columns df_model = df[['avg_salary', 'Rating', 'Type of ownership', 'Industry', 'Sector', 'Revenue', 'hourly', 'job_state', 'age', 'python_yn', 'spark_yn', 'aws_yn', 'excel_yn', 'SQL_yn', 'tableau_yn', 'job_simp', 'seniority', 'desc_len']] # get dummy data df_dum = pd.get_dummies(df_model) # train test split from sklearn.model_selection import train_test_split X = df_dum.drop('avg_salary',axis=1) y = df_dum['avg_salary'].values X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42) # multiple linear regression import statsmodels.api as sm X_sm = X = sm.add_constant(X) model=sm.OLS(y, X_sm) model.fit().summary() # use sklearn from sklearn.linear_model import LinearRegression, Lasso from sklearn.model_selection import cross_val_score lm = LinearRegression() lm.fit(X_train, y_train) # using MAE to show how far off on average we are np.mean(cross_val_score(lm, X_train, y_train, scoring='neg_mean_absolute_error', cv=2)) # lasso regression lm_l = Lasso(alpha=0.02) lm_l.fit(X_train,y_train) np.mean(cross_val_score(lm_l, X_train, y_train, scoring='neg_mean_absolute_error', cv=5)) alpha = [] error = [] for i in range(1,100): alpha.append(i/100) lml = Lasso(alpha=(i/10)) error.append(np.mean(cross_val_score(lml, X_train, y_train, scoring='neg_mean_absolute_error', cv=5))) plt.plot(alpha,error) err = tuple(zip(alpha,error)) df_err = pd.DataFrame(err, columns=['alpha', 'error']) df_err[df_err.error == max(df_err.error)] # random forest from sklearn.ensemble import RandomForestRegressor rf = RandomForestRegressor() np.mean(cross_val_score(rf, X_train, y_train, scoring = 'neg_mean_absolute_error', cv=5)) # tune using GridSearchCV from sklearn.model_selection import GridSearchCV params = { 'n_estimators': range(10,300,10), 'criterion': ['mae'] } gs = GridSearchCV(rf, params, scoring='neg_mean_absolute_error', cv=3) gs.fit(X_train, y_train) gs.best_score_ gs.best_estimator_ # test ensembles tpred_lm = lm.predict(X_test) tpred_lml = lm_l.predict(X_test) tpred_rf = gs.best_estimator_.predict(X_test) from sklearn.metrics import mean_absolute_error mean_absolute_error(y_test, tpred_lm) mean_absolute_error(y_test, tpred_lml) mean_absolute_error(y_test, tpred_rf) mean_absolute_error(y_test, (tpred_lm+tpred_rf)/2) # productionize model # start by pickling the model import pickle pickl = {'model': gs.best_estimator_} pickle.dump(pickl, open('model_file' + ".p", "wb")) file_name = "model_file.p" with open(file_name, 'rb') as pickled: data = pickle.load(pickled) model = data['model'] # test that it worked model.predict(X_test.iloc[1,:].values.reshape(1,-1)) list(X_test.iloc[1,:]) <file_sep>/README.md # Data Science Salary Estimator: Project Overview *Disclaimer: This project is **strongly** based off of Ken Jee's tutorial. Much of the code used is his with minor tweaks by me to better incorporate the data I pulled.* - Created a data science salary estimation tool (MAE ~$25K) which could help data scientists negotiate their income when they are offered a job. - Scraped 1000 job descriptions from glassdoor using Python and Selenium. - Engineered features from the job description text. - Optimized Linear, Lasso, and Random Forest regressors using GridSearchCV to find the best model to productionize. - Productionized the model by building a client facing API using Flask. ## Project Tutorial Resource Again, this project is based on the tutorial by <NAME>. The link to his video and GitHub are below. \ **YouTube Tutorial:** https://www.youtube.com/playlist?list=PL2zq7klxX5ASFejJj80ob9ZAnBHdz5O1t \ **GitHub Repo:** https://github.com/PlayingNumbers/ds_salary_proj ## Code and Resources Used **Python Version:** 3.7\ **Packages:** pandas, numpy, sklearn, matplotlib, seaborn, selenium, flask, json, pickle\ **Web Requirements:** `pip install -r requirements.txt` \ **Glassdoor Scraper:** https://github.com/arapfaik/scraping-glassdoor-selenium \ **Flask Article:** https://towardsdatascience.com/productionize-a-machine-learning-model-with-flask-and-heroku-8201260503d2 \ ## Web Scraping By using the glassdoor scraper linked above (and making my own modifications) I scraped 1000 job postings from glassdoor.com. The following data fields were collected: - Job Title - Salary Estimate - Job Description - Rating - Company - Location - Company Headquarters *note: (returned all -1 so ignored)* - Company Size - Company Founded Date - Type of Ownership - Industry - Sector - Revenue - Competitors *note: (returned all -1 so ignored)* ## Data Cleaning I cleaned the data after scraping in order to use it in my models. Most of the parsing followed the tutorial with a few tweaks. Listed below are the changes that were made to the data: - Parsed numeric data out of salary - Made indicator column for if salary was quoted hourly - Removed rows located in England - Parsed rating out of company text - Made a new column for company state - Transformed founded date into age of company - Made columns for if different skills were listed in the job description: - Python - R - Excel - AWS - Spark - SQL - Tableau - Created columns for simplified job title, seniority, and description length ## EDA Explored data distributions, values counts, and various pivots. Below are some examples of my findings. \ ![alt text](https://github.com/nkrajew/ds_salary_proj/blob/master/images/pivot.PNG "Pivot Table") ![alt text](https://github.com/nkrajew/ds_salary_proj/blob/master/images/corr_2.PNG "Correlations") ![alt text](https://github.com/nkrajew/ds_salary_proj/blob/master/images/state_jobs_resize.PNG "Correlations") ## Model Building #### Data Manipulation 1. Transformed categorical variables into dummy variables. 2. Split the data into train and test sets (test size = 20%). #### Evaluation Metric Following along with Ken Jee, I chose Mean Absolute Error to evaluate the models. The decision was made because MAE is easy to interpret. Furthermore, outliers are not that extreme for this type of prediciton model. #### Models Three different models were built:\ **Multiple Linear Regression** – Baseline model (built using both statsmodels and sklearn). **Lasso Regression** – The sparse data from the many categorical variables suggest that a normalized regression (like lasso) would be effective. **Random Forest** – Due to the sparsity in the data, Random Forest would be another good model to use. ## Model Performance The Random Forest model outperformed the other approaches, however, the difference in results was not as drastic for me as it was for Ken in his tutorial: Random Forest : MAE = 24.98 Lasso Regression: MAE = 26.22 Linear Regression: MAE = 26.83 ## Productionization I built a Flask API endpoint that was hosted on a local webserver by following along with <NAME>'s and the TDS tutorial in the reference section above. The API endpoint takes in a request with a list of values from a job listing and returns an estimated salary.
aeb9ee0fe34ad4b8232d56588aaf4e9a6f1b0ffa
[ "Markdown", "Python" ]
2
Python
nkrajew/ds_salary_proj
4385dee685032f60e1ac9f1b563211ce85aa3d22
eb70ec86dab2974adc9a87c37936bb8efb843d83
refs/heads/master
<repo_name>tipu002/imtipu_static_php<file_sep>/index.php <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <title>Blak | Multi-Purpose HTML5 Template </title> <meta name="keywords" content="" /> <meta name="description" content=""> <meta name="author" content=""> <!-- Mobile view --> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <!-- Favicon --> <link rel="shortcut icon" href="images/favicon.ico"> <?php include('partials/css.php'); ?> </head> <body data-spy="scroll" data-target="#menu"> <div class="over-loader loader-live"> <div class="loader"> <div class="loader-item style4"> <div class="cube1"></div> <div class="cube2"></div> </div> </div> </div> <!--end loading--> <div class="one-page-has-left dark-style dark-icon align-left"> <div id="section1"></div> <div class="header-section absolute pin-style"> <div class="container"> <div class="mod-menu"> <div class="row"> <div class="col-sm-2"> <a href="#" title="" class="logo text-left left-padd"> <img src="images/logo/logo.png" alt=""> </a> </div> <div class="divider-line solid light-2 opacity-2"></div> <br/> <div class="col-sm-10"> <div class="main-nav"> <ul class="nav navbar-nav top-nav"> <li class="visible-xs menu-icon"> <a href="javascript:void(0)" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#menu" aria-expanded="false"> <i aria-hidden="true" class="fa fa-bars"></i> </a> </li> </ul> <div id="menu" class="collapse"> <ul class="nav navbar-nav"> <li class="active"> <a href="#section1" title="About us">Home</a> <span class="arrow"></span> <ul> <li> <a href="#" title="">Home style 1</a> </li> <li> <a href="#" title="">Home style 2</a> </li> <li> <a href="#" title="">Home style 3</a> <span class="arrow"></span> <ul> <li> <a href="#" title="">Creative</a> </li> <li> <a href="#" title="">Classic</a> </li> <li> <a href="#" title="">Business</a> </li> </ul> </li> </ul> </li> <li> <a href="#section2" title="">Services</a> </li> <li> <a href="#section3" title="">About us</a> <span class="arrow"></span> <ul> <li> <a href="#" title="">About Style 1</a> </li> <li> <a href="#" title="">About Style 2</a> </li> <li> <a href="#" title="">About Style 3</a> <span class="arrow"></span> <ul> <li> <a href="#" title="">Company</a> </li> <li> <a href="#" title="">Offers</a> </li> <li> <a href="#" title="">Skills</a> </li> </ul> </li> </ul> </li> <li> <a href="#section4" title="">Team</a> </li> <li> <a href="#section5" title="">Testimonials</a> </li> <li class="right"> <a href="#section6" title="">Contact</a> <span class="arrow"></span> <ul> <li> <a href="#" title="">Contact style 1</a> </li> <li> <a href="#" title="">Contact style 2</a> </li> <li> <a href="#" title="">Contact style 3</a> <span class="arrow"></span> <ul> <li> <a href="#" title="">Address Address</a> </li> <li> <a href="#" title="">Maps</a> </li> <li> <a href="#" title="">Forms</a> </li> </ul> </li> </ul> </li> </ul> </div> </div> </div> </div> </div> </div> </div> </div> <!--end menu--> <div class="wrapper-main"> <!-- START REVOLUTION SLIDER 5.0 --> <div class="slide-tmargin"> <div class="slidermaxwidth"> <div class="rev_slider_wrapper"> <!-- START REVOLUTION SLIDER 5.0 auto mode --> <div id="rev_slider" class="rev_slider" data-version="5.0"> <ul> <!-- SLIDE --> <li data-index="rs-1" data-transition="fade"> <!-- MAIN IMAGE --> <img src="http://via.placeholder.com/2000x1300" alt="" width="1920" height="1280"> <!-- LAYER NR. 1 --> <div class="tp-caption NotGeneric-Title uppercase tp-resizeme rs-parallaxlevel-0" id="slide-1-layer-1" data-x="['center','center','center','center']" data-hoffset="['0','0','0','0']" data-y="['middle','middle','middle','middle']" data-voffset="['-10','0','-22','-29']" data-fontsize="['70','70','70','50']" data-lineheight="['70','70','70','50']" data-width="none" data-height="none" data-whitespace="nowrap" data-transform_idle="o:1;" data-transform_in="z:0;rX:0deg;rY:0;rZ:0;sX:1.5;sY:1.5;skX:0;skY:0;opacity:0;s:1500;e:Power3.easeInOut;" data-transform_out="y:[100%];s:1000;e:Power2.easeInOut;s:1000;e:Power2.easeInOut;" data-mask_in="x:0px;y:0px;" data-mask_out="x:inherit;y:inherit;" data-start="1000" data-splitin="none" data-splitout="none" data-responsive_offset="on" style="z-index: 7; white-space: nowrap;">Creative & Modern </div> <!-- LAYER NR. 2 --> <div class="tp-caption NotGeneric-SubTitle uppercase tp-resizeme rs-parallaxlevel-0" id="slide-1-layer-2" data-x="['center','center','center','center']" data-hoffset="['0','0','0','0']" data-y="['middle','middle','middle','middle']" data-voffset="['42','52','28','13']" data-width="none" data-height="none" data-whitespace="nowrap" data-transform_idle="o:1;" data-transform_in="y:[100%];z:0;rX:0deg;rY:0;rZ:0;sX:1;sY:1;skX:0;skY:0;opacity:0;s:1500;e:Power4.easeInOut;" data-transform_out="y:[100%];s:1000;e:Power2.easeInOut;s:1000;e:Power2.easeInOut;" data-mask_in="x:0px;y:[100%];s:inherit;e:inherit;" data-mask_out="x:inherit;y:inherit;s:inherit;e:inherit;" data-start="1000" data-splitin="none" data-splitout="none" data-responsive_offset="on" style="z-index: 8; white-space: nowrap;">get unlimited many more features </div> <!-- LAYER NR. 3 --> <div class="tp-caption NotGeneric-CallToAction rev-btn rs-parallaxlevel-0" id="slide-1-layer-3" data-x="['center','center','center','center']" data-hoffset="['0','0','0','0']" data-y="['middle','middle','middle','middle']" data-voffset="['124','124','80','65']" data-width="none" data-height="none" data-whitespace="nowrap" data-transform_idle="o:1;" data-transform_hover="o:1;rX:0;rY:0;rZ:0;z:0;s:300;e:Power1.easeInOut;" data-style_hover="c:rgba(255, 255, 255, 1.00);bc:rgba(255, 255, 255, 1.00);cursor:pointer;" data-transform_in="y:50px;opacity:0;s:1500;e:Power4.easeInOut;" data-transform_out="y:[175%];s:1000;e:Power2.easeInOut;s:1000;e:Power2.easeInOut;" data-mask_out="x:inherit;y:inherit;s:inherit;e:inherit;" data-start="1250" data-splitin="none" data-splitout="none" data-actions='[{"event":"click","action":"scrollbelow","offset":"0px"}]' data-responsive_offset="on" data-responsive="off" style="z-index: 9; white-space: nowrap;outline:none;box-shadow:none;box-sizing:border-box;-moz-box-sizing:border-box;-webkit-box-sizing:border-box;">Purchase Now </div> </li> <!-- SLIDE --> <li data-index="rs-2" data-transition="slideremovedown"> <!-- MAIN IMAGE --> <img src="http://via.placeholder.com/2000x1300" alt="" width="1920" height="1280"> <!-- LAYER NR. 1 --> <div class="tp-caption NotGeneric-Title uppercase tp-resizeme rs-parallaxlevel-0" id="slide-2-layer-1" data-x="['center','center','center','center']" data-hoffset="['0','0','0','0']" data-y="['middle','middle','middle','middle']" data-voffset="['-10','0','-22','-29']" data-fontsize="['70','70','70','50']" data-lineheight="['70','70','70','50']" data-width="none" data-height="none" data-whitespace="nowrap" data-transform_idle="o:1;" data-transform_in="z:0;rX:0deg;rY:0;rZ:0;sX:1.5;sY:1.5;skX:0;skY:0;opacity:0;s:1500;e:Power3.easeInOut;" data-transform_out="y:[100%];s:1000;e:Power2.easeInOut;s:1000;e:Power2.easeInOut;" data-mask_in="x:0px;y:0px;" data-mask_out="x:inherit;y:inherit;" data-start="1000" data-splitin="none" data-splitout="none" data-responsive_offset="on" style="z-index: 7; white-space: nowrap;"> Classic Styles </div> <!-- LAYER NR. 2 --> <div class="tp-caption NotGeneric-SubTitle uppercase tp-resizeme rs-parallaxlevel-0" id="slide-3-layer-2" data-x="['center','center','center','center']" data-hoffset="['0','0','0','0']" data-y="['middle','middle','middle','middle']" data-voffset="['42','52','28','13']" data-width="none" data-height="none" data-whitespace="nowrap" data-transform_idle="o:1;" data-transform_in="y:[100%];z:0;rX:0deg;rY:0;rZ:0;sX:1;sY:1;skX:0;skY:0;opacity:0;s:1500;e:Power4.easeInOut;" data-transform_out="y:[100%];s:1000;e:Power2.easeInOut;s:1000;e:Power2.easeInOut;" data-mask_in="x:0px;y:[100%];s:inherit;e:inherit;" data-mask_out="x:inherit;y:inherit;s:inherit;e:inherit;" data-start="1000" data-splitin="none" data-splitout="none" data-responsive_offset="on" style="z-index: 8; white-space: nowrap;">get unlimited many more features </div> <!-- LAYER NR. 3 --> <div class="tp-caption NotGeneric-CallToAction rev-btn rs-parallaxlevel-0" id="slide-4-layer-3" data-x="['center','center','center','center']" data-hoffset="['0','0','0','0']" data-y="['middle','middle','middle','middle']" data-voffset="['124','124','80','65']" data-width="none" data-height="none" data-whitespace="nowrap" data-transform_idle="o:1;" data-transform_hover="o:1;rX:0;rY:0;rZ:0;z:0;s:300;e:Power1.easeInOut;" data-style_hover="c:rgba(255, 255, 255, 1.00);bc:rgba(255, 255, 255, 1.00);cursor:pointer;" data-transform_in="y:50px;opacity:0;s:1500;e:Power4.easeInOut;" data-transform_out="y:[175%];s:1000;e:Power2.easeInOut;s:1000;e:Power2.easeInOut;" data-mask_out="x:inherit;y:inherit;s:inherit;e:inherit;" data-start="1250" data-splitin="none" data-splitout="none" data-actions='[{"event":"click","action":"scrollbelow","offset":"0px"}]' data-responsive_offset="on" data-responsive="off" style="z-index: 9; white-space: nowrap;outline:none;box-shadow:none;box-sizing:border-box;-moz-box-sizing:border-box;-webkit-box-sizing:border-box;">Purchase Now </div> </li> </ul> </div> <!-- END REVOLUTION SLIDER --> </div> </div> <!-- END REVOLUTION SLIDER WRAPPER --> </div> <div class="clearfix"></div> <!-- END OF SLIDER WRAPPER --> <div id="section2"></div> <section class="sec-padding-3"> <div class="container"> <div class="row slider-btn-4"> <div class="col-md-6"> <img src="http://via.placeholder.com/1100x720" alt="" class="img-responsive"/> </div> <!--end item--> <div class="col-md-6"> <div class="ce-feature-box-14 text-left"> <div class="col-sm-12 nopadding"> <div class="sec-title-container less-padding-6 text-left"> <h2 class="font-weight-6 less-mar-1 line-height-4">Who we are and what we do for Your Business</h2> <div class="ce-title-line align-left"></div> </div> </div> <div class="clearfix"></div> <!--end title--> <br/> <h6 class="raleway">Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Suspendisse et justo. Praesent mattis elite justo . </h6> <br/> <p>Praesent mattis commodo augue Aliquam ornare hendrerit augue Cras tellus In pulvinar lectus a est Curabitur eget orci Cras laoreet ligula. Etiam sit amet dolor. Vestibulum ante ipsum primis in faucibus.</p> <p>Praesent mattis commodo augue Aliquam ornare hendrerit augue Cras tellus In pulvinar lectus a est Curabitur eget orci Cras laoreet ligula. Etiam sit amet dolor. Vestibulum ante ipsum primis.</p> <div class="clearfix"></div> <br/> <br/> <a class="btn btn-dark btn-round btn-medium uppercase" href="#"><i class="fa fa-play-circle" aria-hidden="true"></i> Read more</a> </div> </div> <!--end item--> </div> </div> </section> <div class="clearfix"></div> <!-- end section --> <div id="section3"></div> <section class="sec-padding-3 section-light"> <div class="container"> <div class="row"> <div class="col-md-4 margin-bottom"> <h5 class="font-weight-4 less-mar-1 line-height-4 ce-title-top-text">Get Awesome Features</h5> <h2 class="font-weight-6 less-mar-1 line-height-5">what we do for Successful Business</h2> <div class="ce-title-line align-left"></div> <div class="clearfix"></div> <br/> <p>Praesent mattis commodo augue Aliquam ornare hendrerit augue Cras tellus In pulvinar lectus a est Curabitur eget orci Cras laoreet ligula. Etiam. </p> <div class="clearfix"></div> <br/><br/> <a class="btn btn-dark btn-medium btn-round uppercase" href="#"><i class="fa fa-play-circle" aria-hidden="true"></i> Read more</a></div> <!--end item--> <div class="col-md-8 nopadding padding-left-4 "> <div class="col-md-6 margin-bottom"> <div class="ce-feature-box-71 text-left"> <img src="http://via.placeholder.com/800x460" alt="" class="img-responsive"/> <div class="clearfix"></div> <br/> <div class="text-box"> <div class="top-line"></div> <h5 class="title font-weight-5">Who We are & what We do</h5> <p>Praesent mattis commodo augue Aliquam ornare hendrerit augue Cras tellus In pulvinar lectus a est Curabitur eget orci Cras .</p> </div> </div> </div> <!--end item--> <div class="col-md-6 margin-bottom"> <div class="ce-feature-box-71 text-left"> <img src="http://via.placeholder.com/800x460" alt="" class="img-responsive"/> <div class="clearfix"></div> <br/> <div class="text-box"> <div class="top-line"></div> <h5 class="title font-weight-5">Our Goals and success</h5> <p>Praesent mattis commodo augue Aliquam ornare hendrerit augue Cras tellus In pulvinar lectus a est Curabitur eget orci Cras .</p> </div> </div> </div> <!--end item--> </div> <!--end item--> </div> </div> </section> <div class="clearfix"></div> <!-- end section --> <div id="section4"></div> <section class="sec-padding-3"> <div class="container"> <div class="row"> <div class="col-sm-12"> <div class="sec-title-container text-center"> <h5 class="font-weight-4 less-mar-1 line-height-4 ce-title-top-text">We are the best Creative Team</h5> <h2 class="font-weight-6 less-mar-1 line-height-5">Meet Our Creative Team and<br/> Get Awesome Service</h2> <div class="ce-title-line"></div> </div> </div> <div class="clearfix"></div> <!--end title--> <div class="col-md-3 col-sm-6 col-xs-12 margin-bottom"> <div class="ce-feature-box-22"> <div class="main-box"> <div class="img-box"> <div class="overlay"> <p class="small-text text-center">Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Suspendisse et justo. </p> <br/> <ul class="sc-icons"> <li><a href="#"><i class="fa fa-twitter"></i></a></li> <li><a href="#"><i class="fa fa-facebook"></i></a></li> <li><a href="#"><i class="fa fa-google-plus"></i></a></li> <li><a href="#"><i class="fa fa-linkedin"></i></a></li> </ul> </div> <img src="http://via.placeholder.com/700x900" alt="" class="img-responsive"/> </div> <div class="text-box text-center"> <h5 class="nopadding title">Matthew</h5> <p class="subtext">Founder and CEO</p> </div> </div> </div> <!--end feature box--> </div> <!--end item--> <div class="col-md-3 col-sm-6 col-xs-12 margin-bottom"> <div class="ce-feature-box-22"> <div class="main-box"> <div class="img-box"> <div class="overlay"> <p class="small-text text-center">Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Suspendisse et justo. </p> <br/> <ul class="sc-icons"> <li><a href="#"><i class="fa fa-twitter"></i></a></li> <li><a href="#"><i class="fa fa-facebook"></i></a></li> <li><a href="#"><i class="fa fa-google-plus"></i></a></li> <li><a href="#"><i class="fa fa-linkedin"></i></a></li> </ul> </div> <img src="http://via.placeholder.com/700x900" alt="" class="img-responsive"/> </div> <div class="text-box text-center"> <h5 class="nopadding title">Margaret</h5> <p class="subtext">UI Designer</p> </div> </div> </div> <!--end feature box--> </div> <!--end item--> <div class="col-md-3 col-sm-6 col-xs-12 margin-bottom"> <div class="ce-feature-box-22"> <div class="main-box"> <div class="img-box"> <div class="overlay"> <p class="small-text text-center">Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Suspendisse et justo. </p> <br/> <ul class="sc-icons"> <li><a href="#"><i class="fa fa-twitter"></i></a></li> <li><a href="#"><i class="fa fa-facebook"></i></a></li> <li><a href="#"><i class="fa fa-google-plus"></i></a></li> <li><a href="#"><i class="fa fa-linkedin"></i></a></li> </ul> </div> <img src="http://via.placeholder.com/700x900" alt="" class="img-responsive"/> </div> <div class="text-box text-center"> <h5 class="nopadding title">Benjamin</h5> <p class="subtext">Marketing</p> </div> </div> </div> <!--end feature box--> </div> <!--end item--> <div class="col-md-3 col-sm-6 col-xs-12 margin-bottom"> <div class="ce-feature-box-22"> <div class="main-box"> <div class="img-box"> <div class="overlay"> <p class="small-text text-center">Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Suspendisse et justo. </p> <br/> <ul class="sc-icons"> <li><a href="#"><i class="fa fa-twitter"></i></a></li> <li><a href="#"><i class="fa fa-facebook"></i></a></li> <li><a href="#"><i class="fa fa-google-plus"></i></a></li> <li><a href="#"><i class="fa fa-linkedin"></i></a></li> </ul> </div> <img src="http://via.placeholder.com/700x900" alt="" class="img-responsive"/> </div> <div class="text-box text-center"> <h5 class="nopadding title">Jennifer</h5> <p class="subtext">Support</p> </div> </div> </div> <!--end feature box--> </div> <!--end item--> </div> </div> </section> <div class="clearfix"></div> <!-- end section --> <div id="section5"></div> <div class="divider-line solid light-2"></div> <div class="clearfix"></div> <section class="section-side-image section-light sec-padding-3 clearfix"> <div class="img-holder col-md-12 col-sm-12 pull-left"> <div class="background-imgholder" style="background:url(http://via.placeholder.com/2000x1500);"><img class="nodisplay-image" src="http://via.placeholder.com/2000x1500" alt=""/> </div> </div> <div class="container"> <div class="row"> <div class="col-sm-12"> <div class="sec-title-container text-center"> <h5 class="font-weight-4 less-mar-1 line-height-4 opacity-8">What our people and clients says</h5> <h2 class="font-weight-6 less-mar-1 line-height-5">Our Customers and people Says<br/> we deliver quality products </h2> <div class="ce-title-line"></div> </div> </div> <div class="clearfix"></div> <!--end title--> <div class="col-md-4"> <div class="ce-feature-box-6 margin-bottom"> <div class="text-box text-center"> <div class="img-box"><div class="imgbox-xlarge round center overflow-hidden"><img src="http://via.placeholder.com/300x300" alt="" class="img-responsive"/></div></div> <div class="clearfix"></div> <br/> <p>Elit odio erat vel eget consectetuer adipiscing elit Suspendisse et justo Praesent mattis commodo.</p> <div class="clearfix"></div> <br/> <h5 class="less-mar-1 title montserrat">Matthew</h5> <span class="text-primary">Manager</span> </div> </div> </div> <!--end item--> <div class="col-md-4"> <div class="ce-feature-box-6 margin-bottom"> <div class="text-box text-center"> <div class="img-box"><div class="imgbox-xlarge round center overflow-hidden"><img src="http://via.placeholder.com/300x300" alt="" class="img-responsive"/></div></div> <div class="clearfix"></div> <br/> <p>Elit odio erat vel eget consectetuer adipiscing elit Suspendisse et justo Praesent mattis commodo.</p> <div class="clearfix"></div> <br/> <h5 class="less-mar-1 title montserrat">Margaret</h5> <span class="text-primary">Developer</span> </div> </div> </div> <!--end item--> <div class="col-md-4"> <div class="ce-feature-box-6 margin-bottom"> <div class="text-box text-center"> <div class="img-box"> <div class="imgbox-xlarge round center overflow-hidden"><img src="http://via.placeholder.com/300x300" alt="" class="img-responsive"/></div></div> <div class="clearfix"></div> <br/> <p>Elit odio erat vel eget consectetuer adipiscing elit Suspendisse et justo Praesent mattis commodo.</p> <div class="clearfix"></div> <br/> <h5 class="less-mar-1 title montserrat">Jennifer</h5> <span class="text-primary">Designer</span> </div> </div> </div> <!--end item--> </div> </div> </section> <div class=" clearfix"></div> <!--end section--> <div id="section6"></div> <section class="section-side-image section-dark sec-padding clearfix"> <div class="img-holder col-md-12 col-sm-12 pull-left"> <div class="background-imgholder" style="background:url(http://via.placeholder.com/1500x1000);"><img class="nodisplay-image" src="http://via.placeholder.com/1500x1000" alt=""/> </div> </div> <div class="container"> <div class="row"> <div class="col-md-7 col-sm-12 col-xs-12"> <div class="col-sm-12"> <div class="sec-title-container less-padding-1 text-left"> <h5 class="font-weight-4 less-mar-1 line-height-4 text-white opacity-6">Feel free to contact us</h5> <h2 class="font-weight-6 less-mar-1 line-height-5 text-white">Get in Touch With Us and <br/>Get Fast Service</h2> <div class="ce-title-line align-left"></div> </div> </div> <div class="clearfix"></div> <!--end title--> <div class="text-box white padding-4"> <div class="one_half"> <div class="cforms_sty3"> <div id="form_status"></div> <form type="POST" id="gsr-contact" onSubmit="return valid_datas( this );"> <label class="label">Name <em>*</em></label> <label class="input"> <input type="text" name="name" id="name"> </label> <div class="clearfix"></div> <label class="label">E-mail <em>*</em></label> <label class="input"> <input type="email" name="email" id="email"> </label> <!-- <div class="clearfix"></div> <label class="label">Phone <em>*</em></label> <label class="input"> <input type="text" name="phone" id="phone"> </label> --> <div class="clearfix"></div> <label class="label">Subject <em>*</em></label> <label class="input"> <input type="text" name="subject" id="subject"> </label> <div class="clearfix"></div> <label class="label">Message <em>*</em></label> <label class="textarea"> <textarea rows="5" name="message" id="message"></textarea> </label> <div class="clearfix"></div> <input type="hidden" name="token" value="<PASSWORD>" /> <button type="submit" class="button">Send Message</button> </form> </div> </div></div><!-- end .smart-wrap section --> <!-- end .smart-forms section --> </div> <!--end item--> </div> </div> </section> <div class=" clearfix"></div> <!--end section--> <a href="#" class="scrollup"></a><!-- end scroll to top of the page--> <!-- Scripts --> <script src="/assets/js/jquery/jquery.js"></script> <script src="/assets/js/bootstrap/bootstrap.min.js"></script> <script src="/assets/js/less/less.min.js" data-env="development"></script> <!-- Scripts END --> <!-- Template scripts --> <script src="/assets/js/megamenu/js/main.js"></script> <script src="/assets/js/megamenu/js/onepage.js"></script> <script src="/assets/js/tabs/js/responsive-tabs.min.js" type="text/javascript"></script> <!-- REVOLUTION JS FILES --> <script type="text/javascript" src="/assets/js/revolution-slider/js/jquery.themepunch.tools.min.js"></script> <script type="text/javascript" src="/assets/js/revolution-slider/js/jquery.themepunch.revolution.min.js"></script> <!-- SLIDER REVOLUTION 5.0 EXTENSIONS (Load Extensions only on Local File Systems ! The following part can be removed on Server for On Demand Loading) --> <script type="text/javascript" src="/assets/js/revolution-slider/js/extensions/revolution.extension.actions.min.js"></script> <script type="text/javascript" src="/assets/js/revolution-slider/js/extensions/revolution.extension.carousel.min.js"></script> <script type="text/javascript" src="/assets/js/revolution-slider/js/extensions/revolution.extension.kenburn.min.js"></script> <script type="text/javascript" src="/assets/js/revolution-slider/js/extensions/revolution.extension.layeranimation.min.js"></script> <script type="text/javascript" src="/assets/js/revolution-slider/js/extensions/revolution.extension.migration.min.js"></script> <script type="text/javascript" src="/assets/js/revolution-slider/js/extensions/revolution.extension.navigation.min.js"></script> <script type="text/javascript" src="/assets/js/revolution-slider/js/extensions/revolution.extension.parallax.min.js"></script> <script type="text/javascript" src="/assets/js/revolution-slider/js/extensions/revolution.extension.slideanims.min.js"></script> <script type="text/javascript" src="/assets/js/revolution-slider/js/extensions/revolution.extension.video.min.js"></script> <script type="text/javascript"> var tpj=jQuery; var revapi4; tpj(document).ready(function() { if(tpj("#rev_slider").revolution == undefined){ revslider_showDoubleJqueryError("#rev_slider"); }else{ revapi4 = tpj("#rev_slider").show().revolution({ sliderType:"standard", jsFileLocation:"js/revolution-slider/js/", sliderLayout:"auto", dottedOverlay:"none", delay:9000, navigation: { keyboardNavigation:"off", keyboard_direction: "horizontal", mouseScrollNavigation:"off", onHoverStop:"off", arrows: { style:"erinyen", enable:true, hide_onmobile:false, hide_under:100, hide_onleave:true, hide_delay:200, hide_delay_mobile:1200, tmp:'', left: { h_align:"left", v_align:"center", h_offset:80, v_offset:0 }, right: { h_align:"right", v_align:"center", h_offset:80, v_offset:0 } } , touch:{ touchenabled:"on", swipe_threshold: 75, swipe_min_touches: 1, swipe_direction: "horizontal", drag_block_vertical: false } , }, viewPort: { enable:true, outof:"pause", visible_area:"80%" }, responsiveLevels:[1240,1024,778,480], gridwidth:[1240,1024,778,480], gridheight:[700,730,600,420], lazyType:"smart", parallax: { type:"mouse", origo:"slidercenter", speed:2000, levels:[2,3,4,5,6,7,12,16,10,50], }, shadow:0, spinner:"off", stopLoop:"off", stopAfterLoops:-1, stopAtSlide:-1, shuffle:"off", autoHeight:"off", hideThumbsOnMobile:"off", hideSliderAtLimit:0, hideCaptionAtLimit:0, hideAllCaptionAtLilmit:0, disableProgressBar:"on", debugMode:false, fallbacks: { simplifyAll:"off", nextSlideOnWindowFocus:"off", disableFocusListener:false, } }); } }); /*ready*/ </script> <script> $(window).load(function(){ setTimeout(function(){ $('.loader-live').fadeOut(); },1000); }) </script> <script src="js/owl-carousel/owl.carousel.js"></script> <script src="js/owl-carousel/custom.js"></script> <script src="js/owl-carousel/owl.carousel.js"></script> <script src="js/functions/functions.js"></script> </body> </html>
63ad4a862105fc1345cdf6bf5b66f52f99f41886
[ "PHP" ]
1
PHP
tipu002/imtipu_static_php
78472f552bd77c460e74a2f26409c5c7aeb9bbb5
36398e78235497c6e4a3c563682c0fe5388efdf1
refs/heads/master
<repo_name>NikitaG/WikiArticleExtractor<file_sep>/main.py import bz2 import json import os import psycopg2 import time from collections import namedtuple def _json_object_hook(d): return namedtuple('X', d.keys())(*d.values()) def json2obj(data): return json.loads(data) conn = psycopg2.connect(host="localhost",database="articleLocation", user="postgres", password="<PASSWORD>") sql = """INSERT INTO public."ArticleLocationTmp"(type, "wikiId", title, longitude, latitude, "precision", heritage) VALUES (%s, %s, %s, %s, %s, %s, %s);""" def connect(): """ Connect to the PostgreSQL database server """ conn = None try: # print('Connecting to the PostgreSQL database...') conn = psycopg2.connect(host="localhost",database="articleLocation", user="postgres", password="<PASSWORD>") # create a cursor cur = conn.cursor() # execute a statement print('PostgreSQL database version:') cur.execute('SELECT version()') # display the PostgreSQL database server version db_version = cur.fetchone() print(db_version) # close the communication with the PostgreSQL cur.close() except (Exception, psycopg2.DatabaseError) as error: print(error) finally: if conn is not None: conn.close() print('Database connection closed.') f = bz2.BZ2File('wikidata.json.bz2', 'r') if os.path.exists("error.txt"): os.remove("error.txt") def logError(error, json, coordinates = None): pass #with open("error.txt", "a") as myfile: # myfile.write("{} {} {}\n".format('Error '+ error, str(json)[:50], coordinates or "")) def logInfo(json): print('Info', json) pass def processFile(file): counter = 0 locations = 0 totalSize = 0 now = time.time() for line in file: counter += 1 totalSize += len(line) line = line.decode('utf-8') if counter % 100 == 0: e = time.time() - now print("Rows processed:", counter, counter / e, e, totalSize/1024/1024/e) json = convert(line) if not json: continue try: obj = extract(json()) except: obj = None if not obj: continue locations += 1 #print(line) yield obj print("Total:", counter, "\t with locations: ", locations) def convert(json): if not json or json[0] != "{": return None return lambda: json2obj(json[:-2]) def extract(json): if 'labels' not in json or \ 'en' not in json['labels']: logError("Label not found", json) return None if 'P625' not in json['claims']: #logInfo(json) return None title = json['labels']['en']['value'] coordinates = json['claims']['P625'] location = None if(len(coordinates) > 1): for c in coordinates: if location is None or (c['mainsnak']['datavalue']['value']['precision'] or 0.1) < (location['precision'] or 0.1): location = c['mainsnak']['datavalue']['value'] logError("More than one coordinate", json, coordinates) #print("Multiple coordinates: ", coordinates) else: location = coordinates[0]['mainsnak']['datavalue']['value'] heritage = 'P1435' in json['claims'] return {'type': json['type'], 'id': json['id'], 'title': title, 'location': location, 'heritage': heritage } def addData(obj): # create a new cursor cur = conn.cursor() # execute the INSERT statement # (type, "wikiId", title, longitude, latitude, "precision", heritage) cur.execute(sql, (obj['type'], obj['id'], obj['title'], obj['location']['longitude'], obj['location']['latitude'], obj['location']['precision'], obj['heritage'])) # commit the changes to the database conn.commit() pass i = 0 for line in processFile(f): i += 1 #if i < 58129: # continue #addData(line) if i % 1000 == 0: print("Row added", i) #if i == 5: break; print("Row added", i) # st = "\n".join([ json2obj(x[:-2]) for x in lines if x]) # print(st["claims"]["P625"][0]) <file_sep>/src/filereader.py import fileinput import logging import os import sys import time import subprocess suffixes = ['B', 'KB', 'MB', 'GB', 'TB', 'PB'] class FileReader: def __init__(self, input_file): if not os.path.exists(input_file): raise FileNotFoundError if input_file == '-': input = sys.stdin else: # input = io.BufferedReader(gzip.open(input_file)) self.__pigz = subprocess.Popen(('pigz -d -c '+input_file).split(), stdout=subprocess.PIPE) input = self.__pigz.stdout#fileinput.hook_compressed(input_file, "r") self.__input = input def execute(self, jobs_queue, spool_length): logging.info("Starting reading file...") id = 0 size = 0 start = time.time() counter = Counter(10) jobs = [] for line in self.__input: id += 1 job = (id, line) size += len(line) jobs.append(job) if id % 1000 == 0: elapsed, start = time.time() - start, time.time() self.__commit_jobs(counter, jobs_queue, jobs, size, elapsed) size = 0 jobs = [] if id % 10000 == 0: logging.info(counter.get_info())#"Queue: {}, Out: {}".format(jobs_queue.qsize(), spool_length()))) self.close() self.__commit_jobs(counter, jobs_queue, jobs, size, time.time() - start) logging.info(counter.get_info("<EOF>"))#"Queue: {}, Out: {}".format(jobs_queue.qsize(), spool_length()))) logging.info("Reading file finished.") def close(self): self.__input.close() def __commit_jobs(self, counter, jobs_queue, jobs, size, elapsed): s = time.time() jobs_queue.put(jobs) e = time.time() - s if e > 1: logging.debug("\t-> Wait: {}".format(e)) counter.count(len(jobs), size, elapsed) class Counter: def __init__(self, buffer_size): self.__total_count = 0 self.__total_size = 0 self.__total_time = 0 self.__running_count = [0] self.__running_size = [0] self.__running_timer = [0] self.buffer_size = buffer_size def __rotate(self, l, n): return l[n:] + l[:n] def __normalize_metrics(self): while len(self.__running_count) > self.buffer_size: self.__running_count.pop(0) while len(self.__running_size) > self.buffer_size: self.__running_size.pop(0) while len(self.__running_timer) > self.buffer_size: self.__running_timer.pop(0) def count(self, count, size, elapsed): self.__total_count += count self.__total_size += size self.__total_time += elapsed self.__running_count.append(count) self.__running_size.append(size) self.__running_timer.append(elapsed) self.__normalize_metrics() def get_info(self, add_string = ""): template = '{:6.2f}s. Total: {} items, {}. Avg speed: {:6.2f} items and {}. {}' count = sum(self.__running_count) size = sum(self.__running_size) timing = sum(self.__running_timer) return template.format(self.__total_time, self.__total_count, self.humansize(self.__total_size), count / timing, self.humansize(size / timing), add_string) def humansize(self, nbytes): i = 0 while nbytes >= 1024 and i < len(suffixes) - 1: nbytes /= 1024. i += 1 f = ('%.2f' % nbytes).rstrip('0').rstrip('.') return '%s %s' % (f, suffixes[i]) <file_sep>/src/jsonMetadataProcessor.py import logging import time import ujson import cProfile exclude = {'Q5','Q515', 'Q577', 'Q532', 'Q486972','Q6256', 'Q3624078','Q35657', 'Q28872924', 'Q47018901', 'Q10373548', 'Q7854', 'Q33146843', 'Q16521','Q4167410', 'Q11424', 'Q482994', 'Q484170', 'Q747074', 'Q4167836', 'Q13406463', 'Q3863', 'Q11266439'} class JsonMetadataProcessor: def __init__(self, id): self.__id = id self.process = None #self.profile = cProfile.Profile() #self.profile.enable() pass def execute(self, jobs_queue, output_queue): logging.info("JsonProcessor #{} is starting...".format(self.__id)) while True: jobs = jobs_queue.get() if jobs: for job in jobs: job_id = job[0] line = job[1].decode('utf-8') if not line or line[0] != "{": continue obj = self.convert(line[:-2]) if not obj: continue try: metadata = self.extract_info(obj) except Exception as error: metadata = None logging.error("Error in extraction_info: {}".format(error)) if not metadata: continue output_queue.put(('metadata', metadata)) else: break #self.profile.disable() #self.profile.print_stats("tottime") logging.info("JsonProcessor #{} completed.".format(self.__id)) def extract_info(self, json): # if json['id'] not in exclude: # return None if 'en' not in json['labels']: return None instances = self.__extract_claim_value_id(json, "P31") # if bool(instances & exclude): # return None subclasses = self.__extract_claim_value_id(json,"P279") label = json['labels']['en']['value'] if 'en' in json['labels'] else None labelRu = json['labels']['ru']['value'] if 'ru' in json['labels'] else None descr = json['descriptions']['en']['value'] if 'en' in json['descriptions'] else None descrRu = json['descriptions']['ru']['value'] if 'ru' in json['descriptions'] else None return {'id': json['id'], 'label_en': label, 'label_ru': labelRu, 'description_en': descr, 'description_ru': descrRu, 'instances': list(instances), 'subclasses': list(subclasses)} def __extract_claim_value_id(self, json, claim_id): if claim_id not in json['claims']: return set() return set([x['mainsnak']['datavalue']['value']['id'] for x in json['claims'][claim_id]]) def __claim_values(self, json, claim_id): if claim_id not in json['claims']: return [] return [x['mainsnak']['datavalue']['value'] for x in json['claims'][claim_id]] def convert(self, json_string): try: if json_string[:14] != '{"type":"item"': return None js = ujson.loads(json_string) return js except Exception as error: logging.error("Couldn't convert json: {}".format(error)) return None <file_sep>/src/locationExtractor.py import logging import time from multiprocessing import Queue, Process as Instance # from threading import Thread as Instance # from queue import Queue from databaseMetadataWriter import DatabaseWriter, DatabaseConfig from filereader import FileReader from jsonProcessor import JsonProcessor from jsonMetadataProcessor import JsonMetadataProcessor config = DatabaseConfig(host="localhost", database="articleLocation", table="wiki_data_location", user="postgres", password="<PASSWORD>") json_processor_class = JsonProcessor def process_dump(input_file, out_file, workers_count): """ :param input_file: name of the wikipedia dump file; '-' to read from stdin :param out_file: directory where to store extracted data, or '-' for stdout :param workers_count: number of extraction processes to spawn. """ logging.info("Starting map reduce processes...") workers_count = max(1, workers_count) maxsize = 10 * workers_count # output queue output_queue = Queue(maxsize=maxsize) # input queue jobs_queue = Queue(maxsize=maxsize) file_reader = FileReader(input_file) database_writer = DatabaseWriter(config, buffer_size=1000) # database_writer.check_connection() workers = [] for i in range(workers_count): worker = json_processor_class(i) extractor = Instance(target=worker.execute, args=(jobs_queue, output_queue)) extractor.daemon = True # only live while parent process lives extractor.start() worker.process = extractor workers.append(worker) output = Instance(target=database_writer.execute, args=(output_queue,)) output.start() output_queue_size = lambda: output_queue.qsize() # map job that sorts and prints output map = Instance(target=file_reader.execute, args=(jobs_queue, output_queue_size)) map.start() map.join() logging.info("Completing workers...") for _ in workers: jobs_queue.put(None) for w in workers: w.process.join() logging.info("Completing database writer...") output_queue.put(None) output.join() def main(): createLogger(False, True) input_file = '../wikidata.json.gz'#'../wikidata.json.bz2' output_path = '' threads = 8 process_dump(input_file, output_path, threads) def readFile(): import bz2 with bz2.BZ2File('../wikidata.json.bz2', 'rb') as f: i = 0 start = time.time() total = 0 while True: i += 1 l = len(f.read(1024 * 1024)) if l == 0: break; total += l print("{:6.2f}.".format((total // 1024 // 1024) / (time.time() - start))) print(total / 1024 / 1024 / 1024) def createLogger(quiet, debug): fh = logging.FileHandler("wikidata.log") fh.setLevel(logging.ERROR) logging.basicConfig(format='%(asctime)s %(message)s', datefmt='%m/%d/%Y %I:%M:%S %p', level=logging.DEBUG, handlers=[fh, logging.StreamHandler()]) logger = logging.getLogger() if not quiet: logger.setLevel(logging.INFO) if debug: logger.setLevel(logging.DEBUG) return logger if __name__ == '__main__': # readFile() main() <file_sep>/src/jsonProcessor.py import logging import time import ujson import cProfile cities = {'Q515', 'Q532', 'Q486972'} countries = {'Q6256', 'Q3624078'} regions = {'Q35657', 'Q28872924'} class JsonProcessor: def __init__(self, id): self.__id = id self.process = None self.subclasses = 0 #self.profile = cProfile.Profile() #self.profile.enable() pass def execute(self, jobs_queue, output_queue): logging.info("JsonProcessor #{} is starting...".format(self.__id)) while True: jobs = jobs_queue.get() if jobs: for job in jobs: job_id = job[0] line = job[1].decode('utf-8') if not line or line[0] != "{": continue obj = self.convert(line[:-2]) if not obj: continue try: location = self.extract_info(obj) except Exception as error: location = None logging.error("Error in extraction_info: {}".format(error)) if not location: continue # output_queue.put(('location', location)) if self.subclasses % 1000 == 0: logging.info("Total subclasses: {}.".format(self.subclasses)) else: break #self.profile.disable() #self.profile.print_stats("tottime") logging.info("JsonProcessor #{} completed. Total subclasses: {}".format(self.__id, self.subclasses)) def extract_info(self, json): if 'P279' in json['claims']: self.subclasses += 1 if 'labels' not in json or \ 'en' not in json['labels']: # logging.debug("Label not found", json) return None if 'P625' not in json['claims']: # coordinates not found return None title = json['labels']['en']['value'] decription = json['descriptions']['en']['value'] if 'en' in json['descriptions'] else None coordinates = json['claims']['P625'] location = None if (len(coordinates) > 1): for c in coordinates: if location is None or (c['mainsnak']['datavalue']['value']['precision'] or 0.1) < ( location['precision'] or 0.1): location = c['mainsnak']['datavalue']['value'] # logging.debug("More than one coordinate found.") else: if 'datavalue' in coordinates[0]['mainsnak']: location = coordinates[0]['mainsnak']['datavalue']['value'] else: logging.error('Invalid location: '+ str(coordinates) ) if location['globe'] != 'http://www.wikidata.org/entity/Q2': return None heritage = 'P1435' in json['claims'] images = self.__claim_values(json, "P18") imagesList = list(images) if images else None p31 = self.__extract_claim_value_id(json, "P31") p3134 = self.__claim_values(json, "P3134") tourist_attraction, archaeological_sites = 'Q570116' in p31, 'Q839954' in p31 city, region, country = bool(cities & p31), bool(regions & p31), bool(countries & p31) trip_advisor_id = list(p3134) if p3134 else None wikiLinks = list(filter(lambda x: "site" in x and x["site"][:2] == 'en', json["sitelinks"])) if "sitelinks" in json else None return {'type': json['type'], 'id': json['id'], 'title': title, 'description': decription, 'images': imagesList, 'location': location, 'heritage': heritage, 'tourist_attraction': tourist_attraction, 'archaeological_sites': archaeological_sites, 'city': city, 'region': region, 'country': country, 'trip_advisor_id': trip_advisor_id, 'wiki_links': wikiLinks } def __extract_claim_value_id(self, json, claim_id): if claim_id not in json['claims']: return set() return set([x['mainsnak']['datavalue']['value']['id'] for x in json['claims'][claim_id]]) def __claim_values(self, json, claim_id): if claim_id not in json['claims']: return [] return [x['mainsnak']['datavalue']['value'] for x in json['claims'][claim_id]] def convert(self, json_string): try: if json_string[:14] != '{"type":"item"': return None js = ujson.loads(json_string) return js except Exception as error: logging.error("Couldn't convert json: {}".format(error)) return None <file_sep>/test.py import subprocess bzip = subprocess.Popen('pigz -d -c /Users/nikitagolovkin/Projects/wikiConverter/data/latest-all.json.gz'.split(), stdout=subprocess.PIPE) #grep = subprocess.Popen('grep ntp'.split(), stdin=ls.stdout, stdout=subprocess.PIPE) #ls.stdout.close() #output = grep.communicate()[0] #ls.wait() print(bzip.stdout.readline()) print(bzip.stdout.readline()) #print(ls.communicate()[0])<file_sep>/src/databaseMetadataWriter.py import logging import time import psycopg2 import psycopg2.extras class DatabaseWriter: @property def connection(self): if not self.__connection: config = self.__config logging.debug('Connecting to the PostgreSQL database...') self.__connection = psycopg2.connect(host=config.host, database=config.database, user=config.user, password=config.password) return self.__connection def __init__(self, config, id=0, buffer_size=100): self.__id = id self.__config = config self.__connection = None columns = ["id", "label_en", "label_ru", "description_en", "description_ru", "subclasses", "instances"] # values = ["%s" for _ in columns] self.__sql = "INSERT INTO public.{} ({}) VALUES %s; ".format(config.table, ",".join(columns)) self.__buffer = [] self.__buffer_size = buffer_size self.__totalRecords = 0 def check_connection(self): """ Connect to the PostgreSQL database server """ try: # create a cursor cur = self.connection.cursor() # execute a statement cur.execute('SELECT version()') # display the PostgreSQL database server version db_version = cur.fetchone() logging.info('PostgreSQL database version: {}'.format(db_version)) # close the communication with the PostgreSQL cur.close() except (Exception, psycopg2.DatabaseError) as error: logging.error(error) finally: pass def execute(self, output_queue): logging.info("DatabaseWriter #{} is starting...".format(self.__id)) properties = {} with open('properties.json', 'w') as file: while True: item = output_queue.get() if item: if item[0] == 'metadata': self.__addObject(item[1]) item = None else: break self.__commit_buffer() logging.info("DatabaseWriter #{} finished.".format(self.__id)) def __addObject(self, obj): self.__buffer.append(( self.__id_to_int(obj['id']), obj['label_en'], obj['label_ru'], obj['description_en'], obj['description_ru'], list(map(self.__id_to_int, obj['subclasses'])), list(map(self.__id_to_int, obj['instances'])))) if len(self.__buffer) >= self.__buffer_size: self.__commit_buffer() def __id_to_int(self, ids): return int(ids[1:]) def __commit_buffer(self): if not self.__buffer: return try: # create a new cursor cur = self.connection.cursor() psycopg2.extras.execute_values(cur, self.__sql, self.__buffer, page_size=self.__buffer_size) self.__totalRecords += len(self.__buffer) self.__buffer = [] logging.debug("Database buffer committed. Total records: {}".format(self.__totalRecords)) # execute the INSERT statement # (type, "wikiId", title, longitude, latitude, "precision", heritage) # cur.execute(self.__sql, ) # commit the changes to the database self.connection.commit() except Exception as error: logging.error(error) raise error class DatabaseConfig: def __init__(self, host, database, table, user, password): self.host = host self.database = database self.table = table self.user = user self.password = <PASSWORD> <file_sep>/WikiCoordinateExtractor.py def process(Extractor, text): #"".index("{{") pass def output(Extractor, text): print(Extractor.title)
8cadbe941dfb84d93d64578ec4608d98c9c43a02
[ "Python" ]
8
Python
NikitaG/WikiArticleExtractor
b7fb2d8cce060f04b998c785f9e61d68dabf480e
a2c2faeba0149f54c7b76a9127b1efe2273de4f9
refs/heads/master
<file_sep># BOM Digi-Key Plugin This module contains the and table files for accessing Digi-Key from [bom_manager](../bom_manager/README.md). <file_sep># # BOM Manager Digi-Key Plugin # # ## License # # MIT License # # Copyright (c) 2019 <NAME> # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in all # copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. # # # Coding Standars: # # <------------------------------------------- 100 characters -----------------------------------> # # * All code and docmenation lines must be on lines of 100 characters or less. # * In general, the coding guidelines for PEP 8 are used. # * Comments: # * All code comments are written in [Markdown](https://en.wikipedia.org/wiki/Markdown). # * Code is organized into blocks are preceeded by comment that explains the code block. # * For methods, a comment of the form `# CLASS_NAME.METHOD_NAME():` is before each method # definition. This is to disambiguate overloaded methods that implemented in different classes. # * Class/Function standards: # * Indentation levels are multiples of 4 spaces and continuation lines have 2 more spaces. # * All classes are listed alphabetically. # * All methods within a class are listed alphabetically. # * No duck typing! All function/method arguments are checked for compatibale types. # * Inside a method, *self* is usually replaced with more descriptive variable name. # * Generally, single character strings are in single quotes (`'`) and multi characters in double # quotes (`"`). Empty strings are represented as `""`. Strings with multiple double quotes # can be enclosed in single quotes. # * Lint with: # # flake8 --max-line-length=100 digikey.py | fgrep -v :3:1: from argparse import ArgumentParser from bom_manager import bom from bom_manager.tracing import trace, trace_level_set, tracing_get import bs4 # type: ignore import glob import os import requests import time from typing import Any, Dict, List, Optional, TextIO, Tuple, Union Match = Tuple[str, str, int, str, str, str] # main(): def main() -> int: # Create the *digikey* object and process it: # Parse the command line: parser: ArgumentParser = ArgumentParser(description="Digi-Key Collection Constructor.") parser.add_argument("-v", "--verbose", action="count", help="Set tracing level (defaults to 0 which is off).") parsed_arguments: Dict[str, Any] = vars(parser.parse_args()) verbose_count: int = 0 if parsed_arguments["verbose"] is None else parsed_arguments["verbose"] trace_level_set(verbose_count) gui: bom.Gui = bom.Gui() digikey: Digikey = Digikey() digikey.process(gui) result: int = 0 return result # Is this used any more??!!! # url_load(): @trace(1) def collection_get(collections: bom.Collections, searches_root: str, gui: bom.Gui) -> "DigikeyCollection": digikey_collection: DigikeyCollection = DigikeyCollection(collections, searches_root, gui) return digikey_collection # Digikey: class Digikey: # Digikey.__init__(): @trace(1) def __init__(self) -> None: # Extract the *digikey_package_directory* name: # top_directory = "/home/wayne/public_html/projects/bom_digikey_plugin" digikey_py_file_name = __file__ tracing: str = tracing_get() if tracing: print(f"{tracing}__file__='{__file__}'") assert digikey_py_file_name.endswith("digikey.py") digikey_package_directory: str = os.path.split(digikey_py_file_name)[0] init_py_file_name: str = os.path.join(digikey_package_directory, "__init__.py") if tracing: print(f"{tracing}digikey_py_file_name='{digikey_py_file_name}'") print(f"{tracing}digikey_package_directory='{digikey_package_directory}'") print(f"{tracing}init_py_file_name='{init_py_file_name}'") # Compute the various needed directory and file names: assert os.path.isfile(init_py_file_name) root_directory: str = os.path.join(digikey_package_directory, "ROOT") # csvs_directory: str = os.path.join(digikey_package_directory, "CSVS") csvs_directory: str = "/home/wayne/public_html/projects/bom_digikey_plugin/CSVS" miscellaneous_directory: str = os.path.join(digikey_package_directory, "MISC") products_html_file_name: str = os.path.join(miscellaneous_directory, "www.digikey.com_products_en.html") if tracing: print(f"{tracing}root_directory='{root_directory}'") print(f"{tracing}csvs_directory='{csvs_directory}'") print(f"{tracing}products_html_file_name='{products_html_file_name}'") # Make sure everything exists: assert os.path.isdir(root_directory) assert os.path.isdir(miscellaneous_directory) assert os.path.isfile(products_html_file_name) # If *csvs_directory* does not exits, create it: if not os.path.isdir(csvs_directory): os.makedirs(csvs_directory) # Stuff various file names into *digikey* (i.e. *self*): # digikey = self self.products_html_file_name: str = products_html_file_name self.root_directory: str = root_directory self.csvs_directory: str = csvs_directory # Digikey.__str__(): def __str__(self): return "Digikey()" # Digikey.collection_extract(): def collection_extract(self, hrefs_table: Dict[str, List[Match]]) -> bom.Collection: # Now we construct *collection* which is a *bom.Collection* that contains a list of # *DigkeyDirectory*'s (which are sub-classed from *bom.Directory*. Each of those # nested *DigikeyDirectory*'s contains a further list of *DigikeyTable*'s. # # The sorted keys from *hrefs_table* are alphabetized by '*base*/*id*' an look basically # as follows: # # None/-1 # Null => Root directory # audio-products/10 # *items* < 0 => directory # audio-product/accessories/159 # audio-products-buzzers-and-sirends/157 # audio-products-buzzer-ellements-piezo-benders/160 # audio-products-microphones/159 # audio-products-speakers/156 # battery-products/6 # *items* < 0 => directory # battery-products-accessories/87 # battery-products-batteries-non-rechargeable-primary/90 # battery-products-batteries-rechargeable-secondary/91 # battery-products-battery-chargers/85 # battery-products-battery-holders-clips-contacts/86 # battery-products-battery-packas/89 # battery-products-cigarette-ligheter-assemblies/88 # boxes-enclosures-rackes/27 # boxes-enclosures-rackes-backplanes/587 # .... # # We need to group all the entries that match "audio-products" together, # all the entries that matach *battery-products* together, etc. # # Drilling down another level, each *key* (i.e. '*base*/*id*') can have multiple # entries. We scan through these entries to extract the information we want: # # HRef[0]:key='' # Match[0]: '', -1, # 'See All', '', # 'https://www.digikey.com/products/en/') # HRef[1]:key='audio-products/10' # Match[0]: 'audio-products', 10, # 'Audio Products', '', # 'https://www.digikey.com/products/en/audio-products/10') # Match[1]: 'audio-products', 10, # 'Audio Products', '', # 'https://www.digikey.com/products/en/audio-products/10') # Match[2]: 'audio-products', 10, # 'Audio Products', '', # 'https://www.digikey.com/products/en/audio-products/10') # Match[3]: 'audio-products', 10, # 'Audio Products', '', # 'https://www.digikey.com/products/en/audio-products/10') # Match[4]: 'audio-products', 10, # 'Audio Products', '', # 'https://www.digikey.com/products/en/audio-products/10') # Match[5]: 'audio-products', 10, # '613 New Products', '', # 'https://www.digikey.com/products/en/audio-products/10') # HRef[2]:key='audio-products/accessories/159' # Match[0]: 'audio-products-accessories', 159, # 'Accessories', '', # 'https://www.digikey.com/products/en/audio-products/accessories/159') # Match[1]: 'audio-products-accessories', 159, # 'Accessories', '(295 items)', # 'https://www.digikey.com/products/en/audio-products/accessories/159') # ... # Grab some values from *digikey* (i.e. *self*): digikey: Digikey = self root_directory: str = digikey.root_directory searches_root: str = "" gui: bom.Gui = bom.Gui() # Create the *collection* (*collections* is temporary and is not really used): collection_directories: List[str] = list() partial_load: bool = False collections: bom.Collections = bom.Collections("Collections", collection_directories, searches_root, partial_load, gui) collection: bom.Collection = bom.Collection("Digi-Key", collections, root_directory, searches_root, gui) # parent = collection assert collections.has_child(collection) # Create the sorted *hrefs_table_keys*. The first 20 entries look like: hrefs_table_keys: List[Tuple[int, str]] = list(enumerate(sorted(hrefs_table.keys()))) # Sweep through sorted *hrefs* and process each *matches* lists: current_directory: Optional[DigikeyDirectory] = None href_index: int hrefs_key: str tracing: str = tracing_get() for href_index, hrefs_key in hrefs_table_keys: matches: List[Match] = hrefs_table[hrefs_key] if tracing: print(f"{tracing}HRef[{href_index}]: '{hrefs_key}' len(matches)={len(matches)}") # There are one or more *matches*. We'll take the first *a_content* that is non-null # and treat that as the *name*. The number of *items* is taken from the first # *li_content* that end with " items)". We visit *matches* in reverse order to work # around an obscure issue that is not worth describing. If you feeling figuring it # out, please remove the call to `reversed()`: name: Optional[str] = None items: int = -1 url: Optional[str] = None match_index: int match: Match for match_index, match in enumerate(reversed(sorted(matches))): # Unpack *match*: href: str base: str id: int a_conent: str li_content: str href, base, id, a_content, li_content, url = match assert href == "" or href == hrefs_key, f"href='{href}' hrefs_key='{hrefs_key}'" if tracing: print(f"Match[{match_index}]: " f"'{base}', {id}, '{a_content}', '{li_content}', '{url}'") # Fill in *name* and *items*: if name is not None and not a_content.startswith("See"): name = a_content.strip(" \t\n") items_pattern: str = " items)" if items < 0 and li_content.endswith(" items)"): open_parenthesis_index: int = li_content.find('(') items = int(li_content[open_parenthesis_index+1:-len(items_pattern)]) break # Dispatch based on *name* and *items*: if name is None: # We already created *root_directory* so there is nothing to do here: pass elif items < 0: # We have a new *DigikeyDirectory* to create and make the *current_directory*. assert isinstance(url, str) current_directory = DigikeyDirectory(name, collection, id, url) else: # We create a new *DigikeyTable* that is appended to *current_directory*. # Note: the initializer automatically appends *table* to *current_directory*: assert current_directory is not None assert isinstance(url, str) DigikeyTable(name, current_directory, base, id, href, url) # *collection* is in its first incarnation and ready for reorganization: return collection # Digikey.collection_reorganize(): @trace(1) def collection_reorganize(self, collection: bom.Collection) -> None: # Verify argument types: assert isinstance(collection, bom.Collection) # Extract a sorted list of *directories* from *collection*: directories: List[bom.Node] = collection.children_get() directories.sort(key=lambda directory: directory.name) # print("len(directories)={0}".format(len(directories))) directory_index: int directory: bom.Node tracing: str = tracing_get() for directory_index, directory in enumerate(directories): assert isinstance(directory, DigikeyDirectory) if tracing: print(f"Directory[{directory_index}]: '{directory.name}'") directory.reorganize() # Digikey.collection_verify(): @trace(1) def collection_verify(self, digikey_collection: bom.Collection, hrefs_table: Dict[str, List[Match]]) -> None: # For testing only, grab all of the *directories* and *tables* from *root_directory*, # count them up, and validate that the sizes all match: directories: List[bom.Directory] = digikey_collection.directories_get() directories_size: int = len(directories) tables: List[bom.Table] = digikey_collection.tables_get() tables_size: int = len(tables) hrefs_table_size: int = len(hrefs_table) # Verify that we did not loose anything during extraction: tracing: str = tracing_get() if tracing: print(f"{tracing}directories_size={directories_size}") print(f"{tracing}tables_size={tables_size}") print(f"{tracing}hrefs_table_size={hrefs_table_size}") # For debugging only: if hrefs_table_size != directories_size + tables_size: # Make a copy of *hrefs_table*: hrefs_table_copy: Dict[str, List[Match]] = hrefs_table.copy() # Remove all of the *tables* from *hrefs_table_copy*: errors: int = 0 url_prefix: str = "https://www.digikey.com/products/en/" url_prefix_size: int = len(url_prefix) table: bom.Table for table in tables: table_key: str = table.url[url_prefix_size:] if table_key in hrefs_table_copy: del hrefs_table_copy[table_key] else: errors += 1 print(f"{tracing}table_key='{table_key}' not found") # Remove all of the *directories* from * *hrefs_table_copy*: directory: bom.Directory for directory in directories: assert isinstance(directory, DigikeyDirectory) directory_key: str = directory.url[url_prefix_size:] if directory_key in hrefs_table_copy: del hrefs_table_copy[directory_key] else: errors += 1 print(f"{tracing}directory_key='{directory_key}' not found") # Print out the remaining unumatched keys: print(f"{tracing}hrefs_table_copy.keys={list(hrefs_table_copy.keys())}") assert errors == 0, f"{errors} Error found" # Digikey.csvs_download(): @trace(1) def csvs_download(self, collection: bom.Collection, tracing: str = "") -> int: # Grab the *csvs_directory* from *digikey* (i.e. *self*): digikey: Digikey = self csvs_directory: str = digikey.csvs_directory # Fetch example `.csv` files for each table in *collection*: downloads_count: int = 0 for directory in collection.children_get(): downloads_count = directory.csvs_download(csvs_directory, downloads_count) return downloads_count # Digikey.read_and_process(): @trace(1) def csvs_read_and_process(self, collection: bom.Collection, bind: bool, gui: bom.Gui) -> None: # Grab the *csvs_directory* from *digikey* (i.e. *self*): digikey: Digikey = self csvs_directory: str = digikey.csvs_directory # Fetch example `.csv` files for each table in *collection*: directory: bom.Node for directory in collection.children_get(): assert isinstance(directory, bom.Directory) directory.csv_read_and_process(csvs_directory, bind, gui) @staticmethod # Digikey.hrefs_table_show(): def hrefs_table_show(hrefs_table: Dict[str, List[Match]], limit: int) -> None: # Iterate over a sorted *hrefs_table_keys*: hrefs_table_keys: List[str] = sorted(hrefs_table.keys()) index: int hrefs_table_key: str tracing: str = tracing_get() for index, hrefs_table_key in enumerate(hrefs_table_keys): matches: List[Match] = hrefs_table[hrefs_table_key] print(f"{tracing}HRef[{index}]:key='{hrefs_table_key}'") match_index: int match: Match for match_index, match in enumerate(matches): # Unpack *match*: href: str base: str id: int a_content: str li_content: str url: str href, base, id, a_content, li_content, url = match print(f"{tracing} Match[{match_index}]: '{href}', '{base}', {id},") print(f"{tracing} '{a_content}', '{li_content}',") print(f"{tracing} '{url}')") if index >= limit: break # Digikey.process(): @trace(0) def process(self, gui: bom.Gui) -> None: # This starts with the top level page from Digi-Key.com: # # https://www.digikey.com/products/en # # Which is manually copied qout of the web browser and stored into the file named # *digikey_products_html_file_name*: # Read the `.html` file that contains the top level origanziation and convert it # into a Beautiful *soup* tree: digikey: Digikey = self soup: bs4.BeautifulSoup = digikey.soup_read() # Sweep through the *soup* tree and get a href information stuffed into *href_tables*: hrefs_table: Dict[str, List[Match]] = digikey.soup_extract(soup) # Extract the *digikey_collection* structure using *hrefs_table*: collection: bom.Collection = digikey.collection_extract(hrefs_table) digikey.collection_verify(collection, hrefs_table) # Reorganize and verify *collection*: digikey.collection_reorganize(collection) # Make sure we have an example `.csv` file for each table in *collection*: tracing: str = tracing_get() print(f"{tracing}&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&") downloads_count: int = digikey.csvs_download(collection) if tracing: print(f"{tracing}downloads_count={downloads_count}") # Clear out the root directory and repoulate it with updated tables: digikey.root_directory_clear() digikey.csvs_read_and_process(collection, True, gui) # Digikey.root_directory_clear(): @trace(1) def root_directory_clear(self) -> None: # Scan the *root_directory* of *digikey* (i.e. *self*) for all sub files and directories: digikey: Digikey = self root_directory: str = digikey.root_directory file_names: List[str] = glob.glob(root_directory + "/**", recursive=True) # Sort *file_name* them so that the longest names come first (i.e. -negative length). file_names.sort(key=lambda file_name: -len(file_name)) # Visit each *file_name* in *file_names* and delete them (if appropriate): file_name_index: int file_name: str tracing: str = tracing_get() for file_name_index, file_name in enumerate(file_names): # Hang onto the `README.md` and the top level directory (i.e. *file_name[:-1]*): delete: bool = not (file_name.endswith("README.md") or file_name[:-1] == root_directory) # *delete* *file_name* if appropiate: if delete: # *file_name* is a directory: if os.path.isdir(file_name): if tracing: print(f"{tracing}File[file_name_index]: Remove file '{file_name}'") os.rmdir(file_name) else: # *file_name* is a file: if tracing: print(f"{tracing}File[{file_name_index}]: Remove directory '{file_name}'") os.remove(file_name) else: # *file_name* is to be kept: if tracing: print(f"{tracing}[{file_name_index}]: Keep '{file_name}'") # Digikey.soup_extract(): def soup_extract(self, soup: bs4.BeautifulSoup) -> Dict[str, List[Match]]: # Now we use the *bs4* module to screen scrape the information we want from *soup*. # We are interested in sections of HTML that looks as follows: # # <LI> # <A class="..." href="*href*"> # *a_content* # </A> # *li_content* # </LI> # # where: # # * *href*: is a hypertext link reference of the form: # # /products/en/*base*/*id*?*search* # # * "*?search*": *?search* is some optional search arguments that can safely be ignored. # * "/*id*": *id* is a decimal number that is 1-to-1 with the *base*. The *id* is used # by Digikey for specifying were to start. When the *href* specifies a directory # this is simply not present. # * "*base*": *base* is a hyphen separeted list of words (i.e. "audio-products", # "audio_products-speakers", etc.) Note: most of the words are lower case, but # there are a few that are mixed upper/lower case. # * The prefix "/products/en" is present for each *href* and can be ignored. # # * *a_content*: *a_content* is the human readable name for the *href* and is typically # of the form "Audio Products", "Audio Products - Speakers", etc. This is typically # considerd to be the *title* of the table or directory. # # * *li_content*: *li_content* is frequently empty, but sometimes specifies the # number of items in the associated table. It is of the form "(*items* Items)" # where *items* is a decimal number. We only care about the decimal number. # # The output of scanning the *soup* is *hrefs_table*, which is a list *matches*, where the # each *match* is a 5-tuple containing: # # (*base*, *id*, *a_content_text*, *li_content_text*, *url*) # # *id* is -1 if there was no "/*id*" present in the *href*. # print(" =>Digikey.soup_extract(...)") # Start with an empty *hrefs_table*: hrefs_table: Dict[str, List[Match]] = dict() url_prefix: str = "/products/en/" url_prefix_size: int = len(url_prefix) match: Match matches: List[Match] # Find all of the <A HRef="..."> tags in *soup*: a: bs4.element.Tag for a in soup.find_all("a"): # We are only interested in *href*'s that start with *url_prefix*: href: Optional[str] = a.get("href") if href is not None and href.startswith(url_prefix) and href != url_prefix: # Strip off the "?*search" from *href*: question_mark_index: int = href.find('?') if question_mark_index >= 0: href = href[:question_mark_index] # Strip the *url_prefix* from the beginning of *href*: href = href[url_prefix_size:] # Split out the *base* and *id* (if it exists): # print("href3='{0}'".format(href)) slash_index: int = href.rfind('/') base: str id: int = -1 if slash_index >= 0: # *id* exists, so store it as a positive integer: base = href[:slash_index].replace('/', '-') # print("href[slash_index+1:]='{0}'".format(href[slash_index+1:])) id = int(href[slash_index+1:]) else: # *id* does not exist, so store -1 into *id*: base = href id = -1 # Construct *a_contents_text* from the contents of *a* tag. In general this # text is a reasonable human readable summary of what the table/directory is about: a_contents_text: str = "" a_conent: bs4.element.Tag for a_content in a.contents: if isinstance(a_content, bs4.element.NavigableString): a_contents_text += a_content.string a_contents_text = a_contents_text.strip() # Construct the *li* content which is the text between the end of the </A> # tag and the </LI> tag. In general, we only care if there is a class # attribute in the <A> tag (i.e. <A class="..." href="...".) # Sometimes the <A> tag is nested in an <LI> tag. This text when present # will frequently have the basic form of "...(*items* items)...". li_contents_text: str = "" xclass: bs4.element.Tag = a.get("class") if xclass is not None: # We have a `class="..."` attribute, so now look for the *parent* *li* tag: parent: bs4.element = a.parent assert isinstance(parent, bs4.element.Tag) if parent.name == "li": # We have an *li* tag, so extract its contents into *li_contents_text*: li_contents: bs4.element = parent.contents li_content: bs4.element.NavigableString for li_content in li_contents: if isinstance(li_content, bs4.element.NavigableString): li_contents_text += li_content.string li_contents_text = li_contents_text.strip() # Now stuff *base*, *id*, *a_contents_text*, *li_contents_text*, and *url* # into *hrefs_table* using *href* as the key. Since same *href* can occur multiple # times in the *soup* we store everything in a the *matches* list containing # a *match* of 5-tuples: # href_key = f"{base}/{id}" if href in hrefs_table: matches = hrefs_table[href] else: matches = list() hrefs_table[href] = matches url: str = "https://www.digikey.com/products/en/" + href # if base.startswith("capacitors"): # print("url='{0}'".format(url)) match = (href, base, id, a_contents_text, li_contents_text, url) matches.append(match) # We are done scraping information out of the the *soup*. Everything we need is # now in *hrefs_table*. # print(" <=Digikey.soup_extract(...)") return hrefs_table # Digikey.soup_read(): def soup_read(self) -> bs4.BeautifulSoup: # Read in the *digikey_product_html_file_name* file into *html_text*. This # file is obtained by going to `https://www.digkey.com/` and clickd on the # `[View All]` link next to `Products`. This page is saved from the web browser # in the file named *digikey_product_html_file_name*: # Grab some values from *digikey* (i.e. *self*): digikey: Digikey = self products_html_file_name: str = digikey.products_html_file_name # Read *products_html_file_name* in and convert it into *soup*: html_file: TextIO soup: Optional[bs4.BeautifulSoup] = None with open(products_html_file_name) as html_file: html_text: str = html_file.read() # Parse *html_text* into a *soup*: soup = bs4.BeautifulSoup(html_text, features="lxml") # To aid in reading the HTML, write the *soup* back out to the `/tmp` directory # in a prettified form: prettified_html_file_name: str = "/tmp/prettified.html" with open(prettified_html_file_name, "w") as html_file: html_file.write(soup.prettify()) assert isinstance(soup, bs4.BeautifulSoup) return soup # DigikeyCollection(): class DigikeyCollection(bom.Collection): # DigikeyCollection.__init__(): @trace(1) def __init__(self, collections: bom.Collections, searches_root: str, gui: bom.Gui) -> None: # Compute the path to the *collection_root*: digikey_py_file_path: str = __file__ digikey_directory: str digikey_py: str digikey_directory, digikey_py = os.path.split(digikey_py_file_path) collection_root: str = os.path.join(digikey_directory, "ROOT") tracing: str = tracing_get() if tracing: print(f"{tracing}digikey_py_file_path=>'{digikey_py_file_path}'") print(f"{tracing}digikey_directory='{digikey_directory}'") print(f"{tracing}collection_root='{collection_root}'") assert os.path.isdir(collection_root) # Initialize *digikey_collection* (i.e. *self*): super().__init__("Digi-Key", collections, collection_root, searches_root, gui) digikey_collection: DigikeyCollection = self assert digikey_collection.name == "Digi-Key" # DigikeyCollection.__str__(): def __str__(self) -> str: # digikey_collection = self return f"DigikeyCollection('Digi-Key')" # DigikeyCollection.csv_fetch(): @trace(1) def csv_fetch(self, search_url: str, csv_file_name: str) -> bool: # Construct the header values that need to be sent with the *search_url*: authority_text: str = "www.digikey.com" accept_text: str = ( "text/html,application/xhtml+xml,application/xml;" "q=0.9,image/webp,image/apng,*/*;" "q=0.8,application/signed-exchange;" "v=b3" ) accept_encoding_text: str = "gzip, deflate, br" cookie_text: str = ( "i10c.bdddb=c2-f0103ZLNqAeI3BH6yYOfG7TZlRtCrMwzKDQfPMtvESnCuVjBtyWjJ1l" "kqXtKsvswxDrjRHdkESNCtx04RiOfGqfIlRUHqt1qPnlkPolfJSiIRsomx0RhMqeKlRtT3" "jxvKEOjKMDfJSvUoxo6uXWaGVZkqoAhloxqQlofPwYkJcS6fhQ6tzOgotZkQMtHDyjnA4lk" "PHeIKNnroxoY8XJKBvefrzwFru4qPnlkPglfJSiIRvjBTuTfbEZkqMupstsvz8qkl7wWr3i" "HtspjsuTFBve9SHoHqjyTKIPfPM3uiiAioxo6uXOfGvdfq4tFloxqPnlkPcxyESnCuVjBt1" "VmBvHmsYoHqjxVKDq3fhvfJSiIRsoBsxOftucfqRoMRjxVKDq3BuEMuNnHoyM9oz3aGv4ul" "RtCrMsvP8tJOPeoESNGw2q6tZSiN2ZkQQxHxjxVOHukKMDjOQlCtXnGt4OfqujoqMtrpt3y" "KDQjVMffM3iHtsolozT7WqeklSRGloXqPDHZHCUfJSiIRvjBTuTfQeKKYMtHlpVtKDQfPM2" "uESnCuVm6tZOfGK1fqRoIOjxvKDrfQvYkvNnuJsojozTaLW" ) # Construct *headers*: headers: Dict[str, str] = { "authority": authority_text, "accept": accept_text, "accept-encoding": accept_encoding_text, "cookie": cookie_text } # Attempt the fetch the contents of *search_url* using *headers*: try: response: requests.Response = requests.get(search_url, headers=headers) response.raise_for_status() except requests.exceptions.HTTPError as http_error: assert False, f"HTTP error occurred '{http_error}'" except Exception as error: assert False, f"Other exception occurred: '{error}'" # Now parse the resulting *html_text* using a *soup* to find the *csv_url*: html_text: str = str(response.content) soup: Optional[bs4.BeautifulSoup] = bs4.BeautifulSoup(html_text, features="lxml") assert soup is not None tracing: str = tracing_get() # print(f"{tracing}type(soup)=", type(soup)) pairs: List[str] = [] pairs_text: Optional[str] = None if tracing: print(f"{tracing}here 2b") formtag: bs4.element.Tag for form_tag in soup.find_all("form"): name: str = form_tag.get("name") if name == "downloadform": # We found it: if tracing: print(f"{tracing}form_tag={form_tag}") index: int input_tag: bs4.element.Tag for index, input_tag in enumerate(form_tag.children): # print(input_tag) input_tag_name: Optional[str] = input_tag.name if isinstance(input_tag_name, str) and input_tag_name.lower() == "input": input_name: str = input_tag.get("name") input_value: str = input_tag.get("value") input_value = input_value.replace(",", "%2C") input_value = input_value.replace('|', "%7C") input_value = input_value.replace(' ', "+") pair: str = f"{input_name}={input_value}" if tracing: print(f"{tracing}input_name='{input_name}'") print(f"{tracing}input_value='{input_value}'") print(f"{tracing}pair='{pair}'") pairs.append(pair) pairs_text = '&'.join(pairs) if tracing: print(f"{tracing}pairs_text='{pairs_text}'") assert isinstance(pairs_text, str) # Construct the *csv_url*: csv_url: str = "https://www.digikey.com/product-search/download.csv?" + pairs_text if tracing: print(f"{tracing}csv_url='{csv_url}'") # Construct the text strings fort the *headers*: authority_text = "www.digikey.com" accept_text = ( "text/html,application/xhtml+xml,application/xml;" "q=0.9,image/webp,image/apng,*/*;" "q=0.8,application/signed-exchange;" "v=b3" ) accept_encoding_text = "gzip, deflate, br" cookie_text = ( "i10c.bdddb=" "c2-94990ugmJW7kVZcVNxn4faE4FqDhn8MKnfIFvs7GjpBeKHE8KVv5aK34FQDgF" "PFsXXF9jma8opCeDMnVIOKCaK34GOHjEJSFoCA9oxF4ir7hqL8asJs4nXy9FlJEI" "8MujcFW5Bx9imDEGHDADOsEK9ptrlIgAEuIjcp4olPJUjxXDMDVJwtzfuy9FDXE5" "sHKoXGhrj3FpmCGDMDuQJs4aLb7AqsbFDhdjcF4pJ4EdrmbIMZLbAQfaK34GOHbF" "nHKo1rzjl24jP7lrHDaiYHK2ly9FlJEADMKpXFmomx9imCGDMDqccn4fF4hAqIgF" "JHKRcFFjl24iR7gIfTvaJs4aLb4FqHfADzJnXF9jqd4iR7gIfz8t0TzfKyAnpDgp" "8MKEmA9og3hdrCbLvCdJSn4FJ6EFlIGEHKOjcp8sm14iRBkMT8asNwBmF3jEvJfA" "DwJtgD4oL1Eps7gsLJaKJvfaK34FQDgFfcFocAAMr27pmCGDMD17GivaK34GOGbF" "nHKomypOTx9imDEGHDADOsTpF39ArqeADwFoceWjl24jP7gIHDbDPRzfwy9JlIlA" "DTFocAEP" ) # Construct *headers*: headers = { "authority": authority_text, "accept": accept_text, "accept-encoding": accept_encoding_text, "cookie": cookie_text } # Attempt the fetch the contents of *csv_fetch_url* using *headers*: if tracing: print(f"{tracing}A:Fetching '{csv_url}' extracted '{search_url}' contents:") try: response = requests.get(csv_url, headers=headers) response.raise_for_status() except requests.exceptions.HTTPError as http_error: assert False, f"HTTP error occurred '{http_error}'" except Exception as error: assert False, f"Other exception occurred: '{error}'" # Now write *csv_text* out to *csv_file_name*: csv_text: str = str(response.content) csv_file: TextIO with open(csv_file_name, "w") as csv_file: csv_file.write(csv_text) if tracing: print(f"{tracing}Wrote out '{csv_file_name}'") # Wrap up any requested *tracing* and return *result*; result: bool = True return result # DigikeyCollection.panel_update(): @trace(1) def panel_update(self, gui: bom.Gui) -> None: digikey_collection: DigikeyCollection = self gui.collection_panel_update(digikey_collection) # DigikeyDirectory: class DigikeyDirectory(bom.Directory): # DigikeyDirectory.__init__(): def __init__(self, name: str, parent: "Union[bom.Collection, DigikeyDirectory]", id: int, url: str) -> None: # Initialize the parent class for *digikey_directory* (i.e. *self*): super().__init__(name, parent) # Stuff values into *digikey_table* (i.e. *self*): # digikey_directory: DigikeyDirectory = self self.id: int = id self.url: str = url # DigikeyDirectory.__str__(): def __str__(self) -> str: digikey_directory: DigikeyDirectory = self name: str = "??" if hasattr(digikey_directory, "name"): name = digikey_directory.name return f"DigikeyDirectory('{name}')" # DigikeyDirectory.csvs_download(): @trace(1) def csvs_download(self, csvs_directory: str, downloads_count: int) -> int: # Grab some values from *digikey_directory* (i.e. *self*): digikey_directory: DigikeyDirectory = self children: List[bom.Node] = digikey_directory.children_get() sub_node: bom.Node for sub_node in children: downloads_count += sub_node.csvs_download(csvs_directory, downloads_count) return downloads_count # DigikeyDirectory.csv_read_and_process(): @trace(1) def csv_read_and_process(self, csvs_directory: str, bind: bool, gui: bom.Gui) -> None: # Process each *sub_node* of *digikey_directory* (i.e. *self*): digikey_directory: DigikeyDirectory = self sub_node: bom.Node for sub_node in digikey_directory.children_get(): assert isinstance(sub_node, bom.Node) sub_node.csv_read_and_process(csvs_directory, bind, gui) # DigikeyDirectory.reorganize(): @trace(1) def reorganize(self) -> None: # This lovely piece of code takes a *DigikeyDirectory* (i.e. *self*) and attempts # to further partition it into some smaller directories. # A *title* can be of form: # # "Level 1 Only" # "Level 1 - Level 2" # "Level 1 - Level 2 -Level 3" # ... # This routine finds all *title*'s that have the initial " - " and rearranges the # *digikey_directory* so that all the tables that have the same "Level 1" prefix # in their *title* are grouped together. # Step 1: The first step is to build *groups_table* than is a table that contains a list # of "Level 1" keys with a list of *DigikeyTable*'s as the value. Thus, # # "Level 1a" # "Level 1b - Level2a" # "Level 1c - Level2b" # "Level 1c - Level2c" # "Level 1d" # "Level 1e - Level2d" # "Level 1e - Level2e" # "Level 1e - Level2f" # "Level 1e # # Will basically generate the following table: # # {"Level 1b": ["Level2a"] # "Level 1c": ["Level2b", "Level2c"], # "Level 1e": ["Level2d", "Level2e", "Level2f"} # # Where the lists actually contain the appropriate *DigikeyTable* objects rather # than simple strings. Notice that we throw the "Level 1b" entry out since it # only has one match. This operation takes place in Step3. # Start with *digikey_directory* (i.e. *self*) and construct *groups_table* # by scanning through *children*: digikey_directory: DigikeyDirectory = self # name: str = digikey_directory.name groups_table: Dict[str, List[bom.Table]] = dict() children: List[bom.Node] = sorted(digikey_directory.children_get(), key=lambda table: table.name) table_index: int table: bom.Node tables_list: List[bom.Table] tracing: str = tracing_get() for table_index, table in enumerate(children): # Grab some values from *table*: assert isinstance(table, DigikeyTable) name: str = table.name id: int = table.id base: str = table.base url: str = table.url # Search for the first " - " in *name*.: hypen_index: int = name.find(" - ") if hypen_index >= 0: # We found "Level1 - ...", so split it into *group_name* (i.e. "Level1") # and *sub_group_name* (i.e. "...") group_name: str = name[:hypen_index].strip() sub_group_name: str = name[hypen_index+3:].strip() if tracing: print(f"{tracing}[{table_index}]:'{name}'=>'{group_name}'/'{sub_group_name}") # Load *group_title* into *groups_table* and make sure we have a *tables_list* # in there: if group_name in groups_table: tables_list = groups_table[group_name] else: tables_list = list() groups_table[group_name] = tables_list # Finally, tack *table* onto *tables_list*: tables_list.append(table) # This deals with a fairly obscure case where it is possible to have both a table and # directory with the same name. This is called the table/directory match problem. # An example would help: # # Fiber Optic Connectors # Fiber Optic Connectors - Accessories # Fiber Optic Connectors - Contacts # Fiber Optic Connectors - Housings # # Conceptually, we want to change the first line to "Fiber Optic_Connectors - Others". # The code does this by finding the table, and just adding it to the appropriate # group list in *groups_table*. Later below, we detect that there is no hypen in the # title and magically add " - Others" to the title. Yes, this is obscure: digikey_table: bom.Node for digikey_table in digikey_directory.children_get(): assert isinstance(digikey_table, DigikeyTable) digikey_table_name: str = digikey_table.name if digikey_table_name in groups_table: tables_list = groups_table[digikey_table_name] tables_list.append(digikey_table) # print("Print '{0}' is a table/directory matach".format(table_title)) # Ignore any *group_title* that only has one match (i.e *len(tables_list)* <= 1): group_titles_to_delete = list() for group_title, tables_list in groups_table.items(): if len(tables_list) <= 1: # print("groups_table['{0}'] only has one match; delete it".format(group_title)) group_titles_to_delete.append(group_title) for group_title in group_titles_to_delete: del groups_table[group_title] # Now sweep through *digikey_directory* deleting the *tables* that are going to # be reinserted in the *sub_directories*: for group_title, tables_list in groups_table.items(): for table_index, table in enumerate(tables_list): digikey_directory.remove(table) # Now create a *sub_directory* for each *group_title* in *groups_table*: for index, group_name in enumerate(sorted(groups_table.keys())): tables_list = groups_table[group_name] # Convert *group_title* to *directory_name*: # directory_name = digikey_directory.title2file_name(group_title) # print(" Group_Title[{0}]'{1}':".format(group_title_index, group_title)) # Create the *sub_directory*: # sub_directory_path = digikey_directory.path + "/" + directory_name sub_directory = DigikeyDirectory(group_name, digikey_directory, id, url) # Note: *DigikeyDirectory()* automatically appends to the # *digikey_directory* parent: # Now create a new *sub_table* for each *table* in *tables_list*: tables_list.sort(key=lambda table: table.name) for table_index, table in enumerate(tables_list): assert isinstance(table, DigikeyTable) # Extract the *sub_group_title* again: name = table.name hyphen_index = name.find(" - ") # When *hyphen_index* is < 0, we are dealing with table/directory match problem # (see above); otherwise, just grab the stuff to the right of the hyphen: if hyphen_index >= 0: # sub_group_title = name[hyphen_index+3:].strip() pass else: # sub_group_title = "Others" # print(" Creating 'Others' title for group '{0}'".format(title)) pass # Create the new *sub_table*: # path = sub_directory_path # url = table.url href = "" DigikeyTable(name, sub_directory, base, id, href, url) # Note: *DigikeyTable()* automatically appends *sub_table* to the parent # *sub_directory*: # Sort *sub_directory* just for fun. It probably does not do much of anything: # sub_directory.sort(lambda title: title.name) # Again, sort *digikey_directory* even though it is unlikely to change anything: # digikey_directory.sort(lambda table: table.name) # digikey_directory.show(" ") # DigikeyDirectory.show(): def show(self, indent: str) -> None: # digikey_directory: DigikeyDirectory = self # children: List[bom.Node] = digikey_directory.children_get() # node_index: int # node: bom.Node # for node_index, node in enumerate(children): # if isinstance(node, DigikeyDirectory): # print(f"{indent}[{node_index}] D:'{node.title}' '{node.path}'") # node.show(indent + " ") # elif isinstance(node, DigikeyTable): # print(f"{indent}[{node_index}] T:'{node.title}' '{node.path}'") # else: # assert False assert False, "This code is broken" # DigikeyDirectory.table_get(): def table_get(self) -> str: digikey_directory: DigikeyDirectory = self assert False, "This should use Encode instead" return digikey_directory.file_name2title() # DigikeyTable: class DigikeyTable(bom.Table): # DigikeyTable.__init__(): def __init__(self, name: str, parent: DigikeyDirectory, base: str, id: int, href: str, url: str,) -> None: # Initialize the parent class: super().__init__(name, parent, url) # Stuff values into *digikey_table* (i.e. *self*): # digikey_table = self self.base: str = base self.id: int = id self.href: str = href self.url: str = url # DigikeyTable.__str__(): def __str__(self) -> str: digikey_table: DigikeyTable = self name: str = "??" if hasattr(digikey_table, "name"): name = digikey_table.name return f"DigikeyTable('{name}')" # DigikeyTable.csvs_download(): @trace(1) def csvs_download(self, csvs_directory: str, downloads_count: int) -> int: digikey_table: DigikeyTable = self base: str = digikey_table.base id: int = digikey_table.id csv_file_name: str = csvs_directory + "/" + base + ".csv" tracing: str = tracing_get() if tracing: print(f"{tracing}csv_file_name='{csv_file_name}'") if not os.path.isfile(csv_file_name): # The first download happens immediately and the subsequent ones are delayed by # 60 seconds: if downloads_count >= 1: print("Waiting 60 seconds....") time.sleep(60) # Compute the *url*, *parameters*, and *headers* needed for the *request*: url: str = "https://www.digikey.com/product-search/download.csv" parameters: Dict[str, str] = { "FV": "ffe{0:05x}".format(id), "quantity": "0", "ColumnSort": "0", "page": "1", "pageSize": "500" } headers: Dict[str, str] = { "authority": "www.digikey.com", "accept-encoding": "gzip, deflate, br", "cookie": ("i10c.bdddb=" "c2-94990ugmJW7kVZcVNxn4faE4FqDhn8MKnfIFvs7GjpBeKHE8KVv5aK34FQDgF" "PFsXXF9jma8opCeDMnVIOKCaK34GOHjEJSFoCA9oxF4ir7hqL8asJs4nXy9FlJEI" "8MujcFW5Bx9imDEGHDADOsEK9ptrlIgAEuIjcp4olPJUjxXDMDVJwtzfuy9FDXE5" "sHKoXGhrj3FpmCGDMDuQJs4aLb7AqsbFDhdjcF4pJ4EdrmbIMZLbAQfaK34GOHbF" "nHKo1rzjl24jP7lrHDaiYHK2ly9FlJEADMKpXFmomx9imCGDMDqccn4fF4hAqIgF" "JHKRcFFjl24iR7gIfTvaJs4aLb4FqHfADzJnXF9jqd4iR7gIfz8t0TzfKyAnpDgp" "8MKEmA9og3hdrCbLvCdJSn4FJ6EFlIGEHKOjcp8sm14iRBkMT8asNwBmF3jEvJfA" "DwJtgD4oL1Eps7gsLJaKJvfaK34FQDgFfcFocAAMr27pmCGDMD17GivaK34GOGbF" "nHKomypOTx9imDEGHDADOsTpF39ArqeADwFoceWjl24jP7gIHDbDPRzfwy9JlIlA" "DTFocAEP") } # Perform the download: if tracing: print(f"{tracing}DigikeyTable.csvs_download: '{csv_file_name}':{id}") response: requests.Response = requests.get(url, params=parameters, headers=headers) # print(f"response.headers={response.headers}") # print(f"rsponse.content='{response.content}") # response_encoding: str = response.encoding content: str = response.text # Write the content out to *csv_file_name*: csv_file: TextIO with open(csv_file_name, "w") as csv_file: csv_file.write(content) downloads_count += 1 return downloads_count # DigikeyTable.csv_full_name_get(): @trace(1) def csv_full_name_get(self) -> str: # Grab some values from *digikey_table* (i.e. *self*): digikey_table = self base: str = digikey_table.base # collection = digikey_table.collection # Compute the *csv_full_name* and return it: # collection_root: str = collection.collection_root # csvs_root = os.path.join(collection_root, os.path.join("..", "CSVS")) csvs_root: str = "/home/wayne/public_html/projects/bom_digikey_plugin/CSVS" csv_full_name: str = os.path.join(csvs_root, base + ".csv") return csv_full_name # DigikeyTable.file_save(): @trace(1) def file_save(self) -> None: digikey_table: DigikeyTable = self tracing: str = tracing_get() if tracing: comments: List[bom.TableComment] = digikey_table.comments parameters: List[bom.Parameter] = digikey_table.parameters print(f"{tracing}len(comments)={len(comments)}") print(f"{tracing}len(parameters)={len(parameters)}") # Convert *digikey_table* (i.e. *self*) into a single *xml_text* string: xml_lines: List[str] = list() digikey_table.xml_lines_append(xml_lines, "") xml_lines.append("") xml_text: str = '\n'.join(xml_lines) # Compute the *xml_file_name*: collection: Optional[bom.Collection] = digikey_table.collection assert isinstance(collection, bom.Collection) collection_root: str = collection.collection_root relative_path: str = digikey_table.relative_path xml_file_name: str = os.path.join(collection_root, relative_path + ".xml") if tracing: print(f"{tracing}collection_root='{collection_root}'") print(f"{tracing}relative_path='{relative_path}'") print(f"{tracing}xml_file_name='{xml_file_name}'") # Write out *xml_text* to *xml_file_name*: digikey_table.directory_create(collection_root) xml_file: TextIO with open(xml_file_name, "w") as xml_file: xml_file.write(xml_text) # assert False, f"XML file '{xml_file_name}' written" # DigikeyTable.title_get(): def title_get(self) -> str: digikey_table: DigikeyTable = self assert False, "Should use encode instead" return digikey_table.file_name2title() # DigikeyTable.xml_lines_append(): def xml_lines_append(self, xml_lines: List[str], indent: str) -> None: # Grab some values from *digikey_table* (i.e. *self*): digikey_table: DigikeyTable = self name: str = digikey_table.name parameters: List[bom.Parameter] = digikey_table.parameters url: str = digikey_table.url # Start with the `<DigikeyTable ... >` tag: xml_lines.append(f'{indent}<DigikeyTable ' f'name="{bom.Encode.to_attribute(name)}"' f'url="{bom.Encode.to_attribute(url)}"' f'>') # Append the *parameters*: xml_lines.append(f'{indent} <Parameters>') next_indent: str = indent + " " for parameter in parameters: parameter.xml_lines_append(xml_lines, next_indent) xml_lines.append(f'{indent} </Parameters>') # Close out `</DigikeyTable>` tag: xml_lines.append(f'{indent}</DigikeyTable>') if __name__ == "__main__": main()
4a10bb1cdc9534d718362253e211b05c7146e556
[ "Markdown", "Python" ]
2
Markdown
waynegramlich/bom_digikey_plugin
6199be26b770b9a0b82aeec5d06af514af3f2f90
dd29179a0bc0119f26a535493f4de65f83aaf17d
refs/heads/master
<file_sep>#include <stdio.h> #include <stdlib.h> struct node { void *data; struct node *right; struct node *left; }; struct list { struct node *front; struct node *back; }; struct node *create_node(void *x); struct list create_list(); int is_empty(struct list *l); void push_front(struct list *l, void *x); void pop_front(struct list *l); void push_back(struct list *l, void *x); void pop_back(struct list *l); void delete(struct list *l); void print_list(struct list *l, void (*print_node)(void *)); void print_int(void *x) { printf("%d", *(int*)(x)); } void print_dloat(void *x) { printf("%f", *(float*)(x)); } int main() { struct list my_list = create_list(); int i = 1; for (i = 1; i <= 5; i++) { int *x; x = malloc(sizeof(int)); *x = -i; push_front(&my_list, x); x = malloc(sizeof(int)); *x = i; push_back(&my_list, x); print_list(&my_list, print_int); } printf("Popping front:\n"); pop_front(&my_list); print_list(&my_list, print_int); printf("Popping back:\n"); pop_back(&my_list); print_list(&my_list, print_int); printf("Deleting:\n"); delete(&my_list); print_list(&my_list, print_int); return 0; } struct node *create_node(void *x) { struct node *new_node = malloc(sizeof(struct node)); new_node->data = x; new_node->right = NULL; new_node->left = NULL; return new_node; } struct list create_list() { struct list new_list; new_list.front = NULL; new_list.back = NULL; return new_list; } int is_empty(struct list *l) { return (l->front == NULL && l->back == NULL); } void push_front(struct list *l, void *x) { struct node *new_node = create_node(x); if (is_empty(l)) { l->front = new_node; l->back = new_node; } else { new_node->right = l->front; l->front->left = new_node; l->front = new_node; } return; } void pop_front(struct list *l) { if (!is_empty(l)) { struct node *tmp = l->front; l->front = tmp->right; if (l->front == NULL) l->back = NULL; else l->front->left = NULL; free(tmp->data); free(tmp); } return; } void push_back(struct list *l, void *x) { struct node *new_node = create_node(x); if (is_empty(l)) { l->front = new_node; l->back = new_node; } else { new_node->left = l->back; l->back->right = new_node; l->back = new_node; } return; } void pop_back(struct list *l) { if (!is_empty(l)) { struct node *tmp = l->back; l->back = tmp->left; if (l->back == NULL) l->front = NULL; else l->back->right = NULL; free(tmp->data); free(tmp); } return; } void delete(struct list *l) { while (l->front != NULL) pop_front(l); } void print_list(struct list *l, void (*print_node)(void *)) { if (is_empty(l)) { printf("List is empty!\n"); } else { struct node *runner = l->front; printf("NULL <-> "); while (runner != NULL) { print_node(runner->data); printf(" <-> "); runner = runner->right; } printf("NULL\n"); } return; }
22a4095b32a2c416bcf9bae8ca8ee7f93f175a4c
[ "C" ]
1
C
ian-howell/double-list
bf4e12c6eb79d079f4b67e6d4095b12402594f26
cad9c052cc0295521eb62c95af143f22e4353f2f
refs/heads/master
<file_sep>$(function() { // 注册 (function() { var $registModal = $('#regist-modal'), $registSure = $('#regist-sure'), $registCancel = $('#regist-cancel'), $toLogin = $('#to-login'); $registModal.ToggleModal($.noop, function() { $('#username').val(''); $('#phone').val(''); $('#password').val(''); }); $('#username,#phone,#password').bind('keydown', function(e) { if (e.keyCode == 13) { regist(); } }); function regist() { var username = $.trim($('#username').val()), phone = $.trim($('#phone').val()), password = $.trim($('#password').val()); if (!username) { ZUtil.error('用户名不能为空'); return false; } else if (username.length > 30) { ZUtil.error('用户名最多30个字符'); return false; } var reg = /^1(3|5|7|8)\d{9}$/; if (!reg.test(phone)) { ZUtil.error('手机号不合法'); return false; } if (!password) { ZUtil.error('密码不能为空'); return false; } else if (password.length < 6) { ZUtil.error('密码最少6位'); return false; } else if (password.length > 12) { ZUtil.error('密码最多12位'); return false; } $.ajax({ url : base_url + 'user/regist', type : 'post', data : { username : username, phone : phone, password : <PASSWORD> }, success : function(result) { var data = result.data || {}; if (data.code == 1) { ZUtil.success('注册成功'); setTimeout(function() { location.href = location.href; }, 2000); } else { ZUtil.error(data.msg || '服务器异常'); } } }); } $registSure.bind('click', function() { regist(); }); $registCancel.bind('click', function() { location.href = base_url + 'main/index'; }); $toLogin.bind('click', function() { $registModal.trigger('hide'); $loginContainer.trigger('show'); }); // 登录 var $loginContainer = $('#login-container'), $loginSure = $('#login-sure'), $loginCancel = $('#login-cancel'), $toRegist = $('#to-regist'); $loginContainer.ToggleModal($.noop, function() { $('#login-phone').val(''); $('#login-password').val(''); }); function login(phone, password) { $.ajax({ url : base_url + 'user/login', type : 'post', data : { phone : phone, password : <PASSWORD> }, success : function(result) { if (result.data) { ZUtil.success('登录成功'); setTimeout(function() { location.href = location.href; }, 2000); } else { ZUtil.error('手机号或密码不正确'); } } }); } $loginSure.bind('click', function() { var phone = $.trim($('#login-phone').val()), password = $.trim($('#login-password').val()); if (!phone) { ZUtil.error('手机号不能为空'); return false; } if (!password) { ZUtil.error('密码不能为空'); return false; } login(phone, password); }); $('#login-phone,#login-password').bind('keydown', function(e) { if (e.keyCode == 13) { $loginSure.click(); } }); $loginCancel.bind('click', function() { location.href = base_url + 'main/index'; }); $toRegist.bind('click', function() { $loginContainer.trigger('hide'); $registModal.trigger('show'); }); })(); // 自动弹出登录框 /*if (['1', '2'].indexOf(role) == -1) { ZUtil.error('您没有权限进入该页面'); $('#login-container').trigger('show'); $('.main-body,.nav-head').remove(); return false; }*/ var $contentLoading = $('.content-loading'); // 一级菜单 $('.menu > li > p').bind('click', function() { var $p = $(this), $otherLis = $p.parent().siblings(); // 删除其它一级菜单active $otherLis.find('.sub-menu').removeClass('active'); // 切换 var $subMenu = $p.next('.sub-menu'); if($subMenu.hasClass('active')) { $subMenu.removeClass('active'); } else { $subMenu.addClass('active'); } }); $('.sub-menu p').bind('click', function() { var $p = $(this); // 删除其它二级菜单active $p.parent().siblings().find('p').removeClass('active'); $p.closest('.sub-menu').parent().siblings().find('.sub-menu p').removeClass('active'); // 切换 $p.addClass('active'); $.ajax({ url : base_url + $p.attr('data-url'), beforeSend : function() { $contentLoading.removeClass('hide'); }, complete : function() { $contentLoading.addClass('hide'); }, success : function(data) { $('#content-body').html(data); } }); }); });<file_sep># itjpt 爱推荐平台 <file_sep>package com.itjpt.enums; public class StatusConst { public static final String VALID = "Y"; public static final String INVALID = "N"; }<file_sep>// 分页查询课程 function loadList(param) { var $container = param.container, opt = { url : base_url + 'product/page/byParam', type : 'post', success : function(result) { var list = result.data.list || [], html = ''; for (var i = 0, length = list.length; i < length; i++) { var product = list[i], id = product.id, name = product.name, count = product.count, price = product.price, urls = product.imgUrls || []; html += '<div class="product-item">' + '<a href="' + base_url + 'product/user/detail?id=' + id + '" target="_blank">' + '<img src="' + base_img + urls[0] + '" />' + '</a>' + '<div class="p5 product-desc">' + '<p class="tf product-name">' + name + '</p>' + '<div class="clearfix product-extral">' + '<span class="pull-left tf col-6">库存:' + count + '</span>' + '<span class="pull-right text-right tf col-6 product-price">' + price + '(¥)</span>' + '</div>' + '</div>' + '</div>'; } $container.append(html); } }; opt = $.extend(true, opt, param); $container.empty(); $container.Scroll(opt); } var ImageObj = { user : base_url + 'resources/imgs/default_user.jpg' }; $._ajax = $.ajax; // 改变ajax $.ajax = function(opt) { var success = opt.success || $.noop, param = $.extend(true, {}, opt); param.success = function(result) { if (result == 401) { // 自动弹出登录框 $('#to-login').trigger('show'); ZUtil.error('请登录后再操作'); } else { success(result); } } $._ajax(param); };
ff65cdbee2e7bb3b7bd423525527f535c3bdd566
[ "JavaScript", "Java", "Markdown" ]
4
JavaScript
1791317931/itjpt
3cd3462c1d7e81fc5e4fa44534d0cd0ee78f2382
0b7bc6013071f3dcc02993ef91c5d7091d81524b
refs/heads/master
<repo_name>nexeh/recipeApp<file_sep>/public/js/controllers/main.js angular.module('recipeApp.recipe', []) // inject the Recipe service factory into our controller .controller('mainController', ['$scope','$http','RecipeService', function($scope, $http, RecipeService) { $scope.formData = {}; $scope.loading = true; // GET ===================================================================== // when landing on the page, get all recipe and show them // use the service to get all the recipe RecipeService.get() .success(function(data) { $scope.recipes = data; $scope.loading = false; }); // CREATE ================================================================== // when submitting the add form, send the text to the node API $scope.createRecipe = function() { // validate the formData to make sure that something is there // if form is empty, nothing will happen if ($scope.formData.title != undefined) { $scope.loading = true; // call the create function from our service (returns a promise object) RecipeService.create($scope.formData) // if successful creation, call our get function to get all the new recipe .success(function(data) { $scope.loading = false; $scope.formData = {}; // clear the form so our user is ready to enter another $scope.recipes = data; // assign our new list of recipe }); } }; // DELETE ================================================================== // delete a todo after checking it $scope.deleteRecipe = function(id) { $scope.loading = true; RecipeService.delete(id) // if successful creation, call our get function to get all the new recipe .success(function(data) { $scope.loading = false; $scope.recipes = data; // assign our new list of recipe }); }; }]);<file_sep>/public/js/login/login.service.js angular.module('recipeApp.login.loginService', []) .factory('LoginService', ['$http',function($http) { var LoginService = {}; LoginService.user; LoginService.login = function(loginForm) { return $http({ method : 'POST', url : 'login', data : $.param(loginForm), headers : { 'Content-Type': 'application/x-www-form-urlencoded' } }); }; LoginService.setUser = function (currentUser) { LoginService.user = currentUser; }; LoginService.logout = function (currentUser) { LoginService.user = undefined; }; LoginService.isLoggedIn = function () { return LoginService.user !== undefined; }; return LoginService; }]);<file_sep>/public/js/core.js angular.module('recipeApp', [ 'recipeApp.recipe', 'recipeApp.recipe.recipeService', 'recipeApp.recipe.recipeController', 'recipeApp.recipe.recipeListController', 'recipeApp.recipe.ingredient.ingredientController', 'recipeApp.recipe.ingredient.ingredientDirective', 'recipeApp.header.headerController', 'recipeApp.routes' ]); <file_sep>/app/routes.js var Recipe = require('./models/recipe'); function getRecipes(res){ Recipe.find(function(err, recipes) { // if there is an error retrieving, send the error. nothing after res.send(err) will execute if (err) res.send(err) res.json(recipes); // return all recipes in JSON format }); }; module.exports = function(app, passport) { // api --------------------------------------------------------------------- // get all recipes app.get('/api/recipe', function(req, res) { // use mongoose to get all recipes in the database getRecipes(res); }); // create recipe and send back all recipes after creation app.post('/api/recipe', function(req, res) { console.log('req.body', req.body); // create a recipe, information comes from AJAX request from Angular Recipe.create({ title : req.body.title, description : req.body.description, ingredients: req.body.ingredients, instructions: req.body.instructions }, function(err, recipe) { if (err) res.send(err); // get and return all the recipes after you create another getRecipes(res); }); }); // delete a recipe app.delete('/api/recipe/:recipe_id', function(req, res) { Recipe.remove({ _id : req.params.recipe_id }, function(err, recipe) { if (err) res.send(err); getRecipes(res); }); }); // ===================================== // LOGIN =============================== // ===================================== // show the login form app.get('/login', function(req, res) { // render the page and pass in any flash data if it exists res.sendfile('./public/js/login/login.tmpl.html'); }); // process the login form app.post('/login', function(req, res, next) { console.log("Login AUTH!"); passport.authenticate('local-login', function(err, user, info) { if (err) { return next(err); } // Redirect if it fails if (!user) { return res.redirect('/login'); } req.logIn(user, function(err) { if (err) { return next(err); } console.log('user: ', user); // Redirect if it succeeds return res.send(user); }); })(req, res, next); }); app.get('/signup', function(req, res) { // render the page and pass in any flash data if it exists res.sendfile('./public/js/login/signup.tmpl.html'); }); // process the signup form app.post('/signup', passport.authenticate('local-signup', { successRedirect : '/profile', // redirect to the secure profile section failureRedirect : '/signup', // redirect back to the signup page if there is an error failureFlash : true // allow flash messages })); // ===================================== // LOGOUT ============================== // ===================================== app.get('/logout', function(req, res) { req.logout(); res.redirect('/'); }); // ===================================== // PROFILE SECTION ===================== // ===================================== // we will want this protected so you have to be logged in to visit // we will use route middleware to verify this (the isLoggedIn function) app.get('/profile', isLoggedIn, function(req, res) { res.sendfile('./public/js/profile/profile.tmpl.html'); }); // ===================================== // GOOGLE ROUTES ======================= // ===================================== // send to google to do the authentication // profile gets us their basic information including their name // email gets their emails app.get('/auth/google', passport.authenticate('google', { scope : ['profile', 'email'] })); // the callback after google has authenticated the user app.get('/auth/google/callback', passport.authenticate('google', { successRedirect : '/profile', failureRedirect : '/' })); // application ------------------------------------------------------------- app.get('*', function(req, res) { console.log('Application Router: Catch all fired. Returning: ./public' + req.originalUrl); res.sendfile('./public' + req.originalUrl); // load the single view file (angular will handle the page changes on the front-end) }); // route middleware to make sure a user is logged in function isLoggedIn(req, res, next) { // if user is authenticated in the session, carry on if (req.isAuthenticated()) { return next(); } // if they aren't redirect them to the home page res.redirect('/'); } };<file_sep>/public/js/login/login.controller.js angular.module('recipeApp.login.loginController', ['recipeApp.login.loginService']) .controller('loginController', ['$scope', '$http', 'LoginService', function($scope, $http, LoginService) { $scope.loginForm = {}; $scope.isLoggedIn = false; $scope.login = function () { console.log('login controller: login function'); LoginService.login($scope.loginForm) .success(function(data) { console.log(data); $scope.loginForm = {}; $scope.isLoggedIn = true; $scope.user = data; }); }; }]);<file_sep>/public/js/marketing/frontPage.tmpl.html <!-- Full Width Image Header --> <header class="header-image"> <div class="headline"> <div class="container"> <h1>Recipe & Meal Planning</h1> <h2>All in one application</h2> </div> </div> </header> <!-- Page Content --> <div class="container"> <hr class="featurette-divider"> <!-- First Feature --> <div class="featurette" id="about"> <img class="featurette-image img-circle img-responsive pull-right" src="http://placehold.it/500x500"> <h2 class="featurette-heading">Manage Your Recipes <span class="text-muted">Import, Input, and receive recipes</span> </h2> <p class="lead">Donec ullamcorper nulla non metus auctor fringilla. Vestibulum id ligula porta felis euismod semper. Praesent commodo cursus magna, vel scelerisque nisl consectetur. Fusce dapibus, tellus ac cursus commodo.</p> </div> <hr class="featurette-divider"> <!-- Second Feature --> <div class="featurette" id="services"> <img class="featurette-image img-circle img-responsive pull-left" src="http://placehold.it/500x500"> <h2 class="featurette-heading">Plan your menu <span class="text-muted">Know exactly what is for dinner.</span> </h2> <p class="lead">Donec ullamcorper nulla non metus auctor fringilla. Vestibulum id ligula porta felis euismod semper. Praesent commodo cursus magna, vel scelerisque nisl consectetur. Fusce dapibus, tellus ac cursus commodo.</p> </div> <hr class="featurette-divider"> <!-- Third Feature --> <div class="featurette" id="contact"> <img class="featurette-image img-circle img-responsive pull-right" src="http://placehold.it/500x500"> <h2 class="featurette-heading">Create Shopping Lists <span class="text-muted">Save time and money</span> </h2> <p class="lead">Donec ullamcorper nulla non metus auctor fringilla. Vestibulum id ligula porta felis euismod semper. Praesent commodo cursus magna, vel scelerisque nisl consectetur. Fusce dapibus, tellus ac cursus commodo.</p> </div> <hr class="featurette-divider"> </div><file_sep>/app/models/recipe.js var mongoose = require('mongoose'); mongoose.set('debug', true); module.exports = mongoose.model('Recipe', { title : { type : String, default: ''}, description: { type : String, default: ''}, ingredients: { type : Array, default: []}, instructions: { type : Array, default: []}, favorite: { type: Boolean, default: false} // Nutrition facts // preptime, cook time, serves // category: desert, dinner. ect });<file_sep>/public/js/recipe/ingredient/ingredient.controller.js angular.module('recipeApp.recipe.ingredient.ingredientController', []) .controller('ingredientController', ['$scope', function($scope) { $scope.cookingMeasurements = [ {name: "Teaspoon"}, {name: "Tablespoon"}, {name: "dash"}, {name: "a pinch"}, {name: "cup"}, {name: "Pound"}, {name: "ounces"}, {name: "Pint"}, {name: "Quart"}, {name: "Gallon"}, {name: "ml"}, {name: "liter"}, {name: "grams"}, {name: "kilogram"} ]; }]);<file_sep>/public/js/recipe/recipe.controller.js angular.module('recipeApp.recipe.recipeController', ['recipeApp.recipe.recipeService']) .controller('recipeController', ['$scope', 'RecipeService', '$location', function($scope, RecipeService, $location) { $scope.recipeForm = { ingredients: [{}], instructions: [{}] }; $scope.changeIngredient = function(index) { if (index == $scope.recipeForm.ingredients.length -1) { $scope.addIngredient(); } }; $scope.changeInstruction = function(index) { if (index == $scope.recipeForm.instructions.length -1) { $scope.addInstruction(); } }; $scope.addIngredient = function () { $scope.recipeForm.ingredients.push({}); }; $scope.addInstruction = function () { $scope.recipeForm.instructions.push({}); }; $scope.saveRecipe = function () { RecipeService.create($scope.recipeForm); $location.path('/recipes') }; }]);
3018f11d7db0f88b2488287f21657b107398cfc6
[ "JavaScript", "HTML" ]
9
JavaScript
nexeh/recipeApp
cdb9e97a2a2769281e6c1ffa117f21f6d33b2d7a
d36bc5e25bed7e91b414bf56053dbd26d00e0d51
refs/heads/master
<file_sep>#ifndef SHOP_H #define SHOP_H #include <algorithm> #include <iostream> #include <vector> #include <boost/uuid/uuid.hpp> #include "character.h" #include "equipment.h" struct Customer { boost::uuids::uuid id; bool allowed; }; bool operator==(const Customer& lhs, const Customer& rhs); class Shop { std::vector<Equipment> m_items; std::vector<Customer> m_customers; public: Shop(); void AddEquipment(const Equipment& equipment); void AddCustomer(const Character& customer, bool allowed); void BuyEquipment(Character& character, uint equipmentNr); void print() const; std::vector<Equipment> items() const; std::vector<Customer> customers() const; }; #endif // SHOP_H <file_sep>var searchData= [ ['money_10',['Money',['../class_money.html',1,'']]] ]; <file_sep>var searchData= [ ['character_0',['Character',['../class_character.html',1,'']]], ['customer_1',['Customer',['../struct_customer.html',1,'']]] ]; <file_sep>cmake_minimum_required(VERSION 3.12) project(Opgave_1-5) set (CMAKE_CXX_STANDARD 11) FIND_PACKAGE( Boost 1.40 COMPONENTS program_options REQUIRED ) INCLUDE_DIRECTORIES( ${Boost_INCLUDE_DIR} ) add_executable(opgave_1-5 main.cpp party.cpp party.h character.cpp character.h shop.cpp shop.h equipment.cpp equipment.h money.cpp money.h) TARGET_LINK_LIBRARIES(opgave_1-5 LINK_PUBLIC ${Boost_LIBRARIES} ) <file_sep>#ifndef EQUIPMENT_H #define EQUIPMENT_H #include "money.h" #include <boost/algorithm/string.hpp> #include <iostream> #include <string> #include <vector> enum EquipmentType { Weapon, Ammo, Armor, Trinket, Consumable }; class Equipment { private: std::string m_name; Money m_price = Money(0); EquipmentType m_type; float m_weight; std::string m_description; bool m_ready; public: Equipment(std::string name, Money price, EquipmentType type, float weight, std::string description, bool ready); std::string getName() const; Money getPrice() const; EquipmentType getType() const; std::string getTypeString() const; float getWeight() const; std::string getDescription() const; bool getReady() const; void changeEquipmentReadyState(); void print() const; }; bool operator==(const Equipment& lhs, const Equipment& rhs); std::vector<Equipment> testEquipment(); #endif // EQUIPMENT_H <file_sep># RPG Classes # Dette repository vil blive brugt til at lære hvordan man bruger klasser i C++. DOCS: https://mathiasgredal.github.io/RPG_Classes/ ## Logbog ### 2020/03/13 I dag gik vi igang med et projekt omkring hvordan man bruger klasser i c++, først gik vi igennem teorien ved brug af internetlæringsvideoer på youtube, da det foregik hjemmefra. Da videoerne var ret lange, blev de set på 1,75x hastighed. Herefter blev opgavebeskrivelsen læst hvorefter opgave 1 blev lavet. Det foregik ved først at sætte et repository op på både Github og Bitbucket. Herefter blev projektet lavet og IDE blev sat op med filerne nødvendige for at løse opgaven. Der blev først lavet en klass hvor de forskellige metoder og medlemvariabler blev sat op. For at gemme dataen blev der lavet en struct ved navn Character, hvori der blev gemt navn, xp og level. I party klassen blev der lavet en vector til at holde charactersne. Inden hver funktion blev lavet, så blev der skrevet nogle få kommentare til hvordan funktionen skulle forløbe, herefter blev implementeringen lavet. Der blev desvære taget brug af en goto i funktionen read_xp_level. Til sorteringen blev den indbyggede std::sort brugt. Der blev også brugt Boost, til nogle funktioner f.eks. til at konverterer strenge til små bogstaver og til at trimme strenge. ### 2020/03/17 I dag blev opgaverne 2, 3 og 4 lavet, som bestod af at implementere klasserne `Equipment`, `Character` og `Shop`. Først blev der defineret de forskellige private medlemsvariabler som klassen skulle bruge, hvorefter der blev lavet nogle offentlige Getter funktioner. Disse funktioner gør at man nemmere kan vælge hvordan dataen i klassen kan modificeres og sørge for at dataen ikke lige pludslig kommer i en ulovlig tilstand fordi en variabel blev ændret uhensigtsmæssigt. Getteren samt print metoden blev sat som ```const ```, så man ved at metoden ikke kan ændre på dataen, og derfor er den sikker at kalde fra en anden funktion, som har fået en konst reference, hvilket tages brug af i den for løkke som bruges til at printe alt equipment for en character. For at genererer de id hver character har, så bruges Boost biblioteket. I equipment klassen blev der brugt en enum, til at holde styr på hvilken type udstyr det var. Det gode ved en enum klasse er at de forskellige typer at klart defineret og samlet. Dog er det svært at printe navnet ud for dem, og man har derfor brug for en hjælpefunktion med en switch som tager en enum ind og returnere en streng. For at teste programmet blev der lavet en simpel while loop, hvor man kan indtaste en kommando og så bliver den tilhørende funktion kaldet. Her kan man også indtaste print funktionerne for at se hvordan dataen bliver ændret. ### 2020/03/20 I dag blev opgave 5 påbegyndt og der blev implementeret metoder til at konstruere en ``Money `` klasse samt at få fat i antallet at penge i både bronze, sølv og guld form. Der blev også lavet metoder til at tilføje penge samt at printe antallet at penge ud i en form hvor tallene er mindst muligt, altså der vil aldrig blive printet mere end 100 bronze eller sølvstykker ud. I starten af dagen blev der spildt noget tid i forsøg på at bruge GMP biblioteket for at få adgang til multipræcisionstal i c++, dog blev det droppet da programmet ikke ville kompilere. Der blev også kigget på programmeringsparadigmer. #### Øvelse procedural programmering - Undersøg begræbet modulær programmering og sammenlign med C++ - Modulær programmering er en måde at opdele programmet i små udskiftelige moduler som står for en meget specifik del af programmet og fungerer uafhængigt fra resten af programmet. Dette er godt fordi at programstrukturen bliver mere overskuelig og man kan nemmere undgå fejl, samtidig er det også nemmere at arbejde flere da de forskellige moduler skal kunne fungere uafhængigt med et veldefineret interface. Man kan gøre brug af dette paradigme i C++ ved hjælp af klasser og namespaces. - Undersøg begrebet *"Side effect"* og sammenlign det med C++ - En side effect er når en funktion eller metode ændrer en ekstern state. Dette er ikke godt at have for det reducerer hvor genbrugelig koden er og det gør også sværere at forstå hvad en funktion helt præcis gør. I c++ kan man sætte en funktion som const, og så ved man at der ikke bliver modificeret noget data når funktionen bliver kaldet. #### Øvelse objekt orienteret programmering - Forskelle mellem procedural og objekt orienteret programmering - Procedural programmering bruger funktioner og moduler hvor objekt orienteret programmering bruger objekter og metoder - Fordele ved objekt orienteret programmering - Man er mere skalerbart og kan være nemmere at dele op i moduler og for at udvikle videre behøver man ikke at kende hele programstrukturen. Man kan også nemmere arbejde parallelt #### Eksempel på objekt orienteret programmering: ```c++ struct Customer { boost::uuids::uuid id; bool allowed; }; bool operator==(const Customer& lhs, const Customer& rhs); // Der er en klasse som hedder Shop og holder styr på hvilket equipment der er i butikken // Shoppen behøver ikke at bekymre sig om implementeringen af equipment. class Shop { // en klasses variabler er som udgangspunkt private, derfor er følgende medlemsvariabler private og kan kun blive modificeret af klassens metoder. std::vector<Equipment> m_items; std::vector<Customer> m_customers; public: // Her er konstruktøren til klassen, og står for at danne instanser af denne klasse. Shop(); void AddEquipment(const Equipment& equipment); void AddCustomer(const Character& customer, bool allowed); void BuyEquipment(Character& character, uint equipmentNr); // Når print er erklæreret konst så ved man at den ikke har nogle side-effects void print() const; std::vector<Equipment> items() const; std::vector<Customer> customers() const; }; ``` ### 2020/03/25 I dag arbejdede vi med klassediagrammer. Jeg brugte starten af timen på at afslutte opgave fra sidste gang og tilføjede lidt kommentare til eksemplet og lavede en snippet på bitbucket. Herefter valgte jeg at lave et klassediagram til opgave 2-4 med doxygen. Jeg brugte den manuelle metode til at konfigurere doxygen, dog genererede den ikke diagrammerne efter at have fulgt guiden på bitbucket, da jeg glemte at slå HAVE_DOT til. Jeg gik så igang med at afslutte opgave 5, ved at implementere en funktion til at trække penge ud og til at konstruere et objekt ud fra en streng. #### Klassediagram til opgave 2-4 ##### Character ![](class_character_graph.png) Her ses et klassediagram over Character klassen, som er den grå boks i bunden. Øverst ses medlemsvariablerne og nederst ses metoderne. I denne klasse er alle medlemsvariablerne private og alle metoderne offentligte, hvilket ses ved om der er enten et plus eller et minus som henholdsvis står for offentlig eller privat. Man kunne dog også have haft private metoder, men de metoder som man kunne have lavet private, blev omdannet til hjælpefunktioner som ligger uden for klassen. Ud over de variabler der er inde i den grå boks, så er der også nogle pile fra de andre bokse. Her ses der en equipment vector ved navn m_equipment, der bliver også brugt en streng fra stl. ##### Shop ![](class_shop_graph.png) ### 2020/03/27 I dag nået jeg ikke så meget, da jeg har lavet mange af skal opgaverne og der var kun udvidelse af klasserne eller et textadventure tilbage. Jeg startede med textadventure opgaven og startede med at overveje hvordan jeg ville starte på opgaven, men jeg besluttede bare at fortsætte med at udvide de andre klasser i stedet hvor jeg gik igang med at lave CMake filerne om så jeg kunne bruge moneyklassen i de andre klasser. Efter jeg havde gjort det gik jeg igang med operator overloading så jeg nemt kunne addere 2 money objekter.<file_sep>#include "character.h" Character::Character(std::string name, Money moneyBalance, float maxLoad, std::vector<Equipment> equipment, boost::uuids::uuid uuid) { boost::trim(name); assert(("Name cannot be empty", name != "")); assert(("MaxLoad must be positive", maxLoad >= 0)); m_name = name; m_moneyBalance = moneyBalance; m_maxLoad = maxLoad; m_equipment = equipment; } void Character::print() { std::cout << "##### CHARACTER OVERVIEW #####\n"; std::cout << "\t Name: " << name() << std::endl; std::cout << "\t Id: " << uuid() << " $\n"; std::cout << "\t Max Load: " << maxLoad() << " kg\n"; std::cout << "\t Current Load: " << currentLoad() << std::endl; std::cout << "\t Money Balance: " << moneyBalance() << std::endl; std::cout << "\t Equipment:" << std::endl; for (const auto& equipment : getEquipment()) { std::cout << "\t"; equipment.print(); } std::cout << "##############################" << std::endl; } std::string Character::name() const { return m_name; } boost::uuids::uuid Character::uuid() const { return m_uuid; } Money Character::moneyBalance() const { return m_moneyBalance; } std::vector<Equipment> Character::getEquipment() const { return m_equipment; } float Character::maxLoad() const { return m_maxLoad; } float Character::currentLoad() const { float load = 0; for (const auto& equipment : m_equipment) load += equipment.getWeight(); return load; } void Character::addMoneyToBalance(Money money) { m_moneyBalance += money; } bool afford(const Character& character, Money money) { return (character.moneyBalance().getBronzePieces() - money.getBronzePieces() >= 0); } void Character::takeMoneyFromBalance(Money money) { if (afford(*this, money)) m_moneyBalance -= money; else std::cout << "Cant draw money because you dont have enough money!" << std::endl; } void Character::setMaxLoad(float maxLoad) { m_maxLoad = maxLoad; } bool capacity(const Character& character, float extraweight) { return character.currentLoad() + extraweight > character.maxLoad(); } void Character::addEquipment(Equipment equipment) { if (capacity(*this, equipment.getWeight())) std::cout << "Cant add equipment, because it is exceeding max weight." << std::endl; else m_equipment.push_back(equipment); } <file_sep>#include "party.h" Party::Party() { characters.push_back({ "Bob", 5, 2 }); characters.push_back({ "John", 2, 2 }); characters.push_back({ "Doris", 8, 5 }); } void Party::read_names() { // Print Add names for the party members. // Press enter when adding a new name. // when finished writing names, just add the name "end" std::cout << "Add the names for the party members" << std::endl; std::string inputName = ""; std::vector<std::string> inputNames; do { std::cout << "\t- "; getline(std::cin, inputName); if (inputName != "\0") { characters.push_back({ inputName, 0, 0 }); inputNames.push_back(inputName); } std::cout << std::endl; } while (inputName != "\0"); std::cout << "Added the following names to the party list: "; for (const auto& name : inputNames) { std::cout << name << ", "; } std::cout << std::endl; } void Party::read_xp_level() { // Print Add XP and Lvl for each party member // Press enter to use the existing values for the member // Write XP first and lvl second, seperate the values by comma. std::cout << "Add XP and Lvl for each party member" << std::endl; std::string inputString = ""; for (Character& character : characters) { // I know this is bad code soory begin: std::cout << "\t- "; getline(std::cin, inputString); if (inputString != "\0") { // Now we need to split the string by the delimiter ',' and remove whitespace // Then we have to parse the 2 strings into ints. // If it fails we should print only ints and retry input for that character int delimiterPos = inputString.find(','); std::string xpString = inputString.substr(0, delimiterPos); std::string levelString = inputString.substr(delimiterPos + 1); boost::trim(xpString); boost::trim(levelString); int xp; int lvl; try { xp = std::stoi(xpString); lvl = std::stoi(levelString); } catch (...) { std::cout << "ERROR: You are only allowed to input numbers" << std::endl; goto begin; // SOORRRRYYYY } character.xp = xp; character.level = lvl; } std::cout << std::endl; } } void Party::print() { std::cout << "##### CHARACTERS #####" << std::endl; for (const Character& character : characters) { std::cout << "- " << character.name << " has " << character.xp << " and level " << character.level << std::endl; } std::cout << "######################" << std::endl; } void Party::sort() { std::sort(characters.begin(), characters.end(), [](Character rhs, Character lhs) { boost::algorithm::to_lower(rhs.name); boost::algorithm::to_lower(lhs.name); return rhs.name < lhs.name; }); } <file_sep>var searchData= [ ['money_13',['Money',['../class_money.html#a6d90d2785bbe8cdef23c02d6455c1a39',1,'Money']]] ]; <file_sep>cmake_minimum_required(VERSION 3.12) project(RPG_Classes) set (CMAKE_CXX_STANDARD 11) add_subdirectory(Opgave_1-5) #add_subdirectory(Opgave_2-4) #add_subdirectory(Opgave_5) <file_sep>#include "equipment.h" Equipment::Equipment(std::string name, Money price, EquipmentType type, float weight, std::string description, bool ready) { boost::trim(name); assert(("Name cannot be empty", name != "")); assert(("Price must be positive", price.getBronzePieces() >= 0)); assert(("Weight must be positive", weight >= 0)); m_name = name; m_price = price; m_type = type; m_weight = weight; m_description = description; m_ready = ready; } std::string Equipment::getName() const { return m_name; } Money Equipment::getPrice() const { return m_price; } EquipmentType Equipment::getType() const { return m_type; } std::string Equipment::getTypeString() const { switch (m_type) { case Weapon: return "Weapon"; case Ammo: return "Ammo"; case Armor: return "Armor"; case Trinket: return "Trinket"; case Consumable: return "Consumable"; } } float Equipment::getWeight() const { return m_weight; } std::string Equipment::getDescription() const { return m_description; } bool Equipment::getReady() const { return m_ready; } void Equipment::changeEquipmentReadyState() { m_ready = !m_ready; } void Equipment::print() const { std::cout << "EQUIPMENT OVERVIEW:\n"; std::cout << "\t Name: " << m_name << std::endl; std::cout << "\t Price: " << m_price << " $\n"; std::cout << "\t Weight: " << m_weight << " kg\n"; std::cout << "\t Type: " << getTypeString() << std::endl; std::cout << "\t Description: " << m_description << std::endl; std::cout << "\t Ready: " << m_ready << "\n" << std::endl; } std::vector<Equipment> testEquipment() { return { Equipment("Axe", 100, EquipmentType::Weapon, 3, "Can i axe you a question?", false), Equipment("Gambeson", 250, EquipmentType::Armor, 8, "Padded jacket for protection, and some warmth around the heart.", false), Equipment("Flaming Arrows", 10, EquipmentType::Ammo, 0.35f, "5 flaming arrows, wear protective gloves when storing them.", false), Equipment("Corona", 5, EquipmentType::Consumable, 0.5f, "An interesting name for a beer.", false), Equipment("Skullcup", 5, EquipmentType::Trinket, 0.3f, "The perfect cup for some Corona.", false) }; } bool operator==(const Equipment& lhs, const Equipment& rhs) { return lhs.getName() == rhs.getName() && // lhs.getType() == rhs.getType() && // lhs.getPrice() == rhs.getPrice() && // lhs.getReady() == rhs.getReady() && // lhs.getWeight() == rhs.getWeight() && // lhs.getDescription() == rhs.getDescription(); } <file_sep>#include "shop.h" std::vector<Equipment> Shop::items() const { return m_items; } std::vector<Customer> Shop::customers() const { return m_customers; } Shop::Shop() { } void Shop::AddEquipment(const Equipment& equipment) { m_items.push_back(equipment); } void Shop::AddCustomer(const Character& customer, bool allowed) { m_customers.push_back({ customer.uuid(), allowed }); } void Shop::BuyEquipment(Character& character, uint equipmentNr) { Equipment equipment = m_items.at(equipmentNr); // Do we own the equipment if (std::find(m_items.begin(), m_items.end(), equipment) == m_items.end()) { std::cout << "The requested equipment is not a part of this shops inventory, " "so it cannot be bought here." << std::endl; return; } // Do we know the customer and are they allowed Customer customer = { character.uuid(), true }; if (std::find(m_customers.begin(), m_customers.end(), customer) == m_customers.end()) { // Either the customer wasn't allowed, or the customer wasn't found. We do another search to find out. customer.allowed = false; if (std::find(m_customers.begin(), m_customers.end(), customer) == m_customers.end()) std::cout << "The customer was not found in the customerlist, so they cannot buy here." << std::endl; else std::cout << "The customer is not allowed in the store, so they cannot buy here." << std::endl; return; } // Can the customer afford the equipment if (!afford(character, equipment.getPrice())) { std::cout << "The customer cannot afford this item." << std::endl; return; } // Can the customer carry the equipment if (capacity(character, equipment.getWeight())) { std::cout << "The customer cannot carry this item, because it weighs too much." << std::endl; return; } // Now we can sell the equipment character.takeMoneyFromBalance(equipment.getPrice()); character.addEquipment(equipment); m_items.erase(std::find(m_items.begin(), m_items.end(), equipment)); } int getAllowedCustomersCount(const Shop& shop) { int count = 0; for (const auto& customer : shop.customers()) count += customer.allowed; return count; } int getDisallowedCustomersCount(const Shop& shop) { int count = 0; for (const auto& customer : shop.customers()) count += !customer.allowed; return count; } void Shop::print() const { std::cout << "##### SHOP OVERVIEW #####\n"; std::cout << "\t Allowed Customers: " << getAllowedCustomersCount(*this) << "\n"; std::cout << "\t Disallowed Customers: " << getDisallowedCustomersCount(*this) << "\n"; std::cout << "\t Inventory:" << std::endl; for (uint i = 0; i < m_items.size(); i++) { std::cout << " " << i << ". "; m_items.at(i).print(); } std::cout << "#########################" << std::endl; } bool operator==(const Customer& lhs, const Customer& rhs) { return (lhs.id == rhs.id && lhs.allowed == rhs.allowed); } <file_sep>var searchData= [ ['money_3',['Money',['../class_money.html',1,'Money'],['../class_money.html#a6d90d2785bbe8cdef23c02d6455c1a39',1,'Money::Money()']]] ]; <file_sep>#include "party.h" #include <iostream> #include <string> int main() { Party party; std::string inputCommand; do { std::cout << "\n> "; std::cin >> inputCommand; std::cin.get(); if (inputCommand == "print") party.print(); else if (inputCommand == "read_names") party.read_names(); else if (inputCommand == "read_xp_level") party.read_xp_level(); else if (inputCommand == "sort") party.sort(); else std::cout << "Command not found try again"; } while (inputCommand != "quit"); return 0; } <file_sep>#include "money.h" long fromGold(double goldPieces) { double bronzePieces = goldPieces * 10000; if (fmod(bronzePieces, 1) > 0.01) { std::cout << "the number of goldpieces specified cannot be represented as an integer of bronzepieces" << std::endl; throw; } return bronzePieces; } long fromSilver(double silverPieces) { double bronzePieces = silverPieces * 100; if (fmod(bronzePieces, 1) > 0.01) { std::cout << "the number of silverpieces specified cannot be represented as an integer of bronzepieces" << std::endl; throw; } return bronzePieces; } Money::Money(long bronzePieces, double silverPieces, double goldPieces) { m_bronzePieces = bronzePieces + fromSilver(silverPieces) + fromGold(goldPieces); } /// /// \brief This creates a money class from a string, typically from the print function /// \param moneyString just the string eg. 10gp 46sp 3cp /// Money::Money(std::string moneyString) { // Split string by type std::string goldString = moneyString.substr(0, moneyString.find("gp")); std::string silverString = moneyString.substr(moneyString.find("gp ") + 3, moneyString.find("sp")); std::string bronzeString = moneyString.substr(moneyString.find("sp ") + 3, moneyString.find("cp") - 2); *this = Money(stoi(bronzeString), stof(silverString), stof(goldString)); std::cout << moneyString << " = "; print(); } long Money::getBronzePieces() const { return m_bronzePieces; } double Money::getSilverPieces() const { return m_bronzePieces / 100.; } double Money::getGoldPieces() const { return m_bronzePieces / 10000.; } void Money::addBronzePieces(long bronzePieces) { m_bronzePieces += bronzePieces; } void Money::addSilverPieces(double silverPieces) { m_bronzePieces += fromSilver(silverPieces); } void Money::addGoldPieces(double goldPieces) { m_bronzePieces += fromGold(goldPieces); } void Money::subtractBronzePieces(long bronzePieces) { m_bronzePieces -= bronzePieces; } void Money::subtractSilverPieces(double silverPieces) { m_bronzePieces -= fromSilver(silverPieces); } void Money::subtractGoldPieces(double goldPieces) { m_bronzePieces -= fromGold(goldPieces); } Money operator+(const Money& lhs, const Money& rhs) { return Money(lhs.getBronzePieces() + rhs.getBronzePieces()); } Money operator-(const Money& lhs, const Money& rhs) { return Money(lhs.getBronzePieces() - rhs.getBronzePieces()); } Money operator+=(const Money& lhs, const Money& rhs) { return Money(lhs.getBronzePieces() + rhs.getBronzePieces()); } Money operator-=(const Money& lhs, const Money& rhs) { return Money(lhs.getBronzePieces() + rhs.getBronzePieces()); } std::string Money::toString() const { std::ostringstream oss; long gold = floor(m_bronzePieces / 10000.); long silver = floor((m_bronzePieces % 10000) / 100.); long bronze = m_bronzePieces - gold * 10000 - silver * 100; oss << gold << "gp " << silver << "sp " << bronze << "cp"; return oss.str(); } void Money::print() { std::cout << toString() << std::endl; } std::ostream& operator<<(std::ostream& os, const Money& obj) { os << obj.toString(); return os; } bool operator==(const Money& lhs, const Money& rhs) { return (lhs.getBronzePieces() == rhs.getBronzePieces()); } <file_sep>#ifndef CHARACTER_H #define CHARACTER_H #include <iostream> #include <string> #include <vector> // Used to generate UUIDs for characters #include <boost/uuid/uuid.hpp> #include <boost/uuid/uuid_generators.hpp> #include <boost/uuid/uuid_io.hpp> // Used for trimming strings #include <boost/algorithm/string.hpp> #include "equipment.h" #include "money.h" class Character { private: std::string m_name; boost::uuids::uuid m_uuid; Money m_moneyBalance = Money(0); float m_maxLoad; std::vector<Equipment> m_equipment; public: Character(std::string name, Money moneyBalance = Money(0), float maxLoad = 25, std::vector<Equipment> equipment = {}, boost::uuids::uuid uuid = boost::uuids::random_generator()()); void print(); // Getters std::string name() const; boost::uuids::uuid uuid() const; Money moneyBalance() const; float maxLoad() const; float currentLoad() const; std::vector<Equipment> getEquipment() const; // Setters void addMoneyToBalance(Money money); void takeMoneyFromBalance(Money moneyBalance); void setMaxLoad(float maxLoad); void addEquipment(Equipment equipment); }; bool afford(const Character& character, Money money); bool capacity(const Character& character, float extraweight); #endif // CHARACTER_H <file_sep>var searchData= [ ['character_7',['Character',['../class_character.html',1,'']]], ['customer_8',['Customer',['../struct_customer.html',1,'']]] ]; <file_sep>var searchData= [ ['shop_6',['Shop',['../class_shop.html',1,'']]] ]; <file_sep>#ifndef PARTY_H #define PARTY_H #include <iostream> #include <string> #include <vector> #include <boost/algorithm/string.hpp> struct Character { std::string name; int xp; int level; }; class Party { public: Party(); void read_names(); void read_xp_level(); void print(); void sort(); private: std::vector<Character> characters; }; #endif // PARTY_H <file_sep>#ifndef MONEY_H #define MONEY_H #include <cstdlib> #include <iostream> #include <math.h> #include <sstream> #include <string> class Money { long m_bronzePieces = 0; public: Money(long bronzePieces, double silverPieces = 0, double goldPieces = 0); Money(std::string moneyString); void print(); // Det virker som meget kodedublikering at have alle disse funktioner som næsten gør det samme, long getBronzePieces() const; double getSilverPieces() const; double getGoldPieces() const; void addSilverPieces(double silverPieces); void addBronzePieces(long bronzePieces); void addGoldPieces(double goldPieces); void subtractBronzePieces(long bronzePieces); void subtractSilverPieces(double silverPieces); void subtractGoldPieces(double goldPieces); std::string toString() const; }; Money operator+(const Money& lhs, const Money& rhs); Money operator-(const Money& lhs, const Money& rhs); Money operator+=(const Money& lhs, const Money& rhs); Money operator-=(const Money& lhs, const Money& rhs); std::ostream& operator<<(std::ostream& os, const Money& obj); bool operator==(const Money& lhs, const Money& rhs); #endif // MONEY_H <file_sep>var searchData= [ ['party_4',['Party',['../class_party.html',1,'']]] ];
df90661efc0295911728788d5175e9659249d7c8
[ "JavaScript", "CMake", "C++", "Markdown" ]
21
C++
mathiasgredal/RPG_Classes
c47a064bfb476ee7f66b098f8c4ff16e201f207d
eb3ba3163f27971bf7b61c1c88399301aa341158
refs/heads/master
<repo_name>SIRTTS/hcPortal<file_sep>/src/main/webapp/app/entities/vs-body-temperature/vs-body-temperature-info.component.html <div class="modal-header"> <h4 class="info-modal-title" id="body_temperature-info" jhiTranslate="hcPortalApp.info.body_temperature">Body Temperature</h4> </div> <div class="info-modal"> <h6> The normal human body temperature range is typically stated as 36.5–37.5 °C .Individual body temperature depends upon the age, exertion, infection, sex, time of day, and reproductive status of the subject, the place in the body at which the measurement is made, the subject's state of consciousness (waking or sleeping), activity level, and emotional state. </h6> </div> <div class="modal-footer info-modal-footer"> <button type="button" class="close" data-dismiss="modal" aria-hidden="true" (click)="clear()">&times;</button> </div> <file_sep>/src/main/webapp/app/entities/diabetes-sugar-test/index.ts export * from './diabetes-sugar-test.model'; export * from './diabetes-sugar-test-popup.service'; export * from './diabetes-sugar-test.service'; export * from './diabetes-sugar-test-dialog.component'; export * from './diabetes-sugar-test-delete-dialog.component'; export * from './diabetes-sugar-test-detail.component'; export * from './diabetes-sugar-test.component'; export * from './diabetes-sugar-test.route'; export * from './diabetes-sugar-test-info.component'; <file_sep>/src/main/java/com/sirtts/service/dto/MenstrualCycleDTO.java package com.sirtts.service.dto; import java.time.LocalDateTime; import javax.validation.constraints.*; import java.io.Serializable; import java.util.Objects; /** * A DTO for the MenstrualCycle entity. */ public class MenstrualCycleDTO implements Serializable { private String id; private String userid; @NotNull private LocalDateTime startDate; @NotNull private LocalDateTime endDate; public String getId() { return id; } public void setId(String id) { this.id = id; } public String getUserid() { return userid; } public void setUserid(String userid) { this.userid = userid; } public LocalDateTime getStartDate() { return startDate; } public void setStartDate(LocalDateTime startDate) { this.startDate = startDate; } public LocalDateTime getEndDate() { return endDate; } public void setEndDate(LocalDateTime endDate) { this.endDate = endDate; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } MenstrualCycleDTO menstrualCycleDTO = (MenstrualCycleDTO) o; if(menstrualCycleDTO.getId() == null || getId() == null) { return false; } return Objects.equals(getId(), menstrualCycleDTO.getId()); } @Override public int hashCode() { return Objects.hashCode(getId()); } @Override public String toString() { return "MenstrualCycleDTO{" + "id=" + getId() + ", userid='" + getUserid() + "'" + ", startDate='" + getStartDate() + "'" + ", endDate='" + getEndDate() + "'" + "}"; } } <file_sep>/src/main/webapp/app/entities/menstrual-cycle/menstrual-cycle-popup.service.ts import { Injectable, Component } from '@angular/core'; import { Router } from '@angular/router'; import { NgbModal, NgbModalRef } from '@ng-bootstrap/ng-bootstrap'; import { HttpResponse } from '@angular/common/http'; import { MenstrualCycle } from './menstrual-cycle.model'; import { MenstrualCycleService } from './menstrual-cycle.service'; import {DatePipe} from '@angular/common'; @Injectable() export class MenstrualCyclePopupService { private ngbModalRef: NgbModalRef; constructor( private datePipe: DatePipe, private modalService: NgbModal, private router: Router, private menstrualCycleService: MenstrualCycleService ) { this.ngbModalRef = null; } open(component: Component, id?: number | any): Promise<NgbModalRef> { return new Promise<NgbModalRef>((resolve, reject) => { const isOpen = this.ngbModalRef !== null; if (isOpen) { resolve(this.ngbModalRef); } if (id) { this.menstrualCycleService.find(id) .subscribe((menstrualCycleResponse: HttpResponse<MenstrualCycle>) => { const menstrualCycle: MenstrualCycle = menstrualCycleResponse.body; menstrualCycle.startDate = this.datePipe .transform(menstrualCycle.startDate, 'yyyy-MM-ddTHH:mm:ss'); menstrualCycle.endDate = this.datePipe .transform(menstrualCycle.endDate, 'yyyy-MM-ddTHH:mm:ss'); this.ngbModalRef = this.menstrualCycleModalRef(component, menstrualCycle); resolve(this.ngbModalRef); }); } else { // setTimeout used as a workaround for getting ExpressionChangedAfterItHasBeenCheckedError setTimeout(() => { this.ngbModalRef = this.menstrualCycleModalRef(component, new MenstrualCycle()); resolve(this.ngbModalRef); }, 0); } }); } menstrualCycleModalRef(component: Component, menstrualCycle: MenstrualCycle): NgbModalRef { const modalRef = this.modalService.open(component, { size: 'lg', backdrop: 'static'}); modalRef.componentInstance.menstrualCycle = menstrualCycle; modalRef.result.then((result) => { this.router.navigate([{ outlets: { popup: null }}], { replaceUrl: true, queryParamsHandling: 'merge' }); this.ngbModalRef = null; }, (reason) => { this.router.navigate([{ outlets: { popup: null }}], { replaceUrl: true, queryParamsHandling: 'merge' }); this.ngbModalRef = null; }); return modalRef; } } <file_sep>/src/main/webapp/app/entities/entity.module.ts import { NgModule, CUSTOM_ELEMENTS_SCHEMA } from '@angular/core'; import { HcPortalVsSpo2Module } from './vs-spo-2/vs-spo-2.module'; import { HcPortalVsRespiratoryRateModule } from './vs-respiratory-rate/vs-respiratory-rate.module'; import { HcPortalVsHeartRateModule } from './vs-heart-rate/vs-heart-rate.module'; import { HcPortalVsBodyTemperatureModule } from './vs-body-temperature/vs-body-temperature.module'; import { HcPortalVsBloodPressureModule } from './vs-blood-pressure/vs-blood-pressure.module'; import { HcPortalMenstrualCycleModule } from './menstrual-cycle/menstrual-cycle.module'; import { HcPortalDiabetesSugarTestModule } from './diabetes-sugar-test/diabetes-sugar-test.module'; import { HcPortalBloodTestModule } from './blood-test/blood-test.module'; import { HcPortalDentistVisitModule } from './dentist-visit/dentist-visit.module'; import { HcPortalDentistNextVisitModule } from './dentist-next-visit/dentist-next-visit.module'; import {HcPortalDrPatientsModule} from './dr-patients/dr-patients.module'; import {HcPortalPtDoctorsModule} from './pt-doctors/pt-doctors.module'; /* jhipster-needle-add-entity-module-import - JHipster will add entity modules imports here */ @NgModule({ imports: [ HcPortalVsSpo2Module, HcPortalVsRespiratoryRateModule, HcPortalVsHeartRateModule, HcPortalVsBodyTemperatureModule, HcPortalVsBloodPressureModule, HcPortalMenstrualCycleModule, HcPortalDiabetesSugarTestModule, HcPortalBloodTestModule, HcPortalDentistVisitModule, HcPortalDentistNextVisitModule, HcPortalDrPatientsModule, HcPortalPtDoctorsModule /* jhipster-needle-add-entity-module - JHipster will add entity modules here */ ], declarations: [], entryComponents: [], providers: [], schemas: [CUSTOM_ELEMENTS_SCHEMA] }) export class HcPortalEntityModule {} <file_sep>/src/test/java/com/sirtts/web/rest/VsHeartRateResourceIntTest.java package com.sirtts.web.rest; import com.sirtts.HcPortalApp; import com.sirtts.domain.VsHeartRate; import com.sirtts.repository.VsHeartRateRepository; import com.sirtts.service.VsHeartRateService; import com.sirtts.service.dto.VsHeartRateDTO; import com.sirtts.service.mapper.VsHeartRateMapper; import com.sirtts.web.rest.errors.ExceptionTranslator; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.MockitoAnnotations; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.data.web.PageableHandlerMethodArgumentResolver; import org.springframework.http.MediaType; import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.setup.MockMvcBuilders; import java.time.ZoneOffset; import java.time.LocalDateTime; import java.util.List; import static com.sirtts.web.rest.TestUtil.createFormattingConversionService; import static org.assertj.core.api.Assertions.assertThat; import static org.hamcrest.Matchers.hasItem; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; /** * Test class for the VsHeartRateResource REST controller. * * @see VsHeartRateResource */ @RunWith(SpringRunner.class) @SpringBootTest(classes = HcPortalApp.class) public class VsHeartRateResourceIntTest { private static final String DEFAULT_USERID = "AAAAAAAAAA"; private static final String UPDATED_USERID = "BBBBBBBBBB"; private static final Double DEFAULT_BPM = 1D; private static final Double UPDATED_BPM = 2D; private static final LocalDateTime DEFAULT_MEASURMENTDATE = LocalDateTime.ofEpochSecond(1L,0,ZoneOffset.UTC); private static final LocalDateTime UPDATED_MEASURMENTDATE = LocalDateTime.ofEpochSecond(1L,0,ZoneOffset.UTC); @Autowired private VsHeartRateRepository vsHeartRateRepository; @Autowired private VsHeartRateMapper vsHeartRateMapper; @Autowired private VsHeartRateService vsHeartRateService; @Autowired private MappingJackson2HttpMessageConverter jacksonMessageConverter; @Autowired private PageableHandlerMethodArgumentResolver pageableArgumentResolver; @Autowired private ExceptionTranslator exceptionTranslator; private MockMvc restVsHeartRateMockMvc; private VsHeartRate vsHeartRate; @Before public void setup() { MockitoAnnotations.initMocks(this); final VsHeartRateResource vsHeartRateResource = new VsHeartRateResource(vsHeartRateService); this.restVsHeartRateMockMvc = MockMvcBuilders.standaloneSetup(vsHeartRateResource) .setCustomArgumentResolvers(pageableArgumentResolver) .setControllerAdvice(exceptionTranslator) .setConversionService(createFormattingConversionService()) .setMessageConverters(jacksonMessageConverter).build(); } /** * Create an entity for this test. * * This is a static method, as tests for other entities might also need it, * if they test an entity which requires the current entity. */ public static VsHeartRate createEntity() { VsHeartRate vsHeartRate = new VsHeartRate() .userid(DEFAULT_USERID) .bpm(DEFAULT_BPM) .measurmentdate(DEFAULT_MEASURMENTDATE); return vsHeartRate; } @Before public void initTest() { vsHeartRateRepository.deleteAll(); vsHeartRate = createEntity(); } @Test public void createVsHeartRate() throws Exception { int databaseSizeBeforeCreate = vsHeartRateRepository.findAll().size(); // Create the VsHeartRate VsHeartRateDTO vsHeartRateDTO = vsHeartRateMapper.toDto(vsHeartRate); restVsHeartRateMockMvc.perform(post("/api/vs-heart-rates") .contentType(TestUtil.APPLICATION_JSON_UTF8) .content(TestUtil.convertObjectToJsonBytes(vsHeartRateDTO))) .andExpect(status().isCreated()); // Validate the VsHeartRate in the database List<VsHeartRate> vsHeartRateList = vsHeartRateRepository.findAll(); assertThat(vsHeartRateList).hasSize(databaseSizeBeforeCreate + 1); VsHeartRate testVsHeartRate = vsHeartRateList.get(vsHeartRateList.size() - 1); assertThat(testVsHeartRate.getUserid()).isEqualTo(DEFAULT_USERID); assertThat(testVsHeartRate.getBpm()).isEqualTo(DEFAULT_BPM); assertThat(testVsHeartRate.getMeasurmentdate()).isEqualTo(DEFAULT_MEASURMENTDATE); } @Test public void createVsHeartRateWithExistingId() throws Exception { int databaseSizeBeforeCreate = vsHeartRateRepository.findAll().size(); // Create the VsHeartRate with an existing ID vsHeartRate.setId("existing_id"); VsHeartRateDTO vsHeartRateDTO = vsHeartRateMapper.toDto(vsHeartRate); // An entity with an existing ID cannot be created, so this API call must fail restVsHeartRateMockMvc.perform(post("/api/vs-heart-rates") .contentType(TestUtil.APPLICATION_JSON_UTF8) .content(TestUtil.convertObjectToJsonBytes(vsHeartRateDTO))) .andExpect(status().isBadRequest()); // Validate the VsHeartRate in the database List<VsHeartRate> vsHeartRateList = vsHeartRateRepository.findAll(); assertThat(vsHeartRateList).hasSize(databaseSizeBeforeCreate); } @Test public void checkBpmIsRequired() throws Exception { int databaseSizeBeforeTest = vsHeartRateRepository.findAll().size(); // set the field null vsHeartRate.setBpm(null); // Create the VsHeartRate, which fails. VsHeartRateDTO vsHeartRateDTO = vsHeartRateMapper.toDto(vsHeartRate); restVsHeartRateMockMvc.perform(post("/api/vs-heart-rates") .contentType(TestUtil.APPLICATION_JSON_UTF8) .content(TestUtil.convertObjectToJsonBytes(vsHeartRateDTO))) .andExpect(status().isBadRequest()); List<VsHeartRate> vsHeartRateList = vsHeartRateRepository.findAll(); assertThat(vsHeartRateList).hasSize(databaseSizeBeforeTest); } @Test public void checkMeasurmentdateIsRequired() throws Exception { int databaseSizeBeforeTest = vsHeartRateRepository.findAll().size(); // set the field null vsHeartRate.setMeasurmentdate(null); // Create the VsHeartRate, which fails. VsHeartRateDTO vsHeartRateDTO = vsHeartRateMapper.toDto(vsHeartRate); restVsHeartRateMockMvc.perform(post("/api/vs-heart-rates") .contentType(TestUtil.APPLICATION_JSON_UTF8) .content(TestUtil.convertObjectToJsonBytes(vsHeartRateDTO))) .andExpect(status().isBadRequest()); List<VsHeartRate> vsHeartRateList = vsHeartRateRepository.findAll(); assertThat(vsHeartRateList).hasSize(databaseSizeBeforeTest); } @Test public void getAllVsHeartRates() throws Exception { // Initialize the database vsHeartRateRepository.save(vsHeartRate); // Get all the vsHeartRateList restVsHeartRateMockMvc.perform(get("/api/vs-heart-rates?sort=id,desc")) .andExpect(status().isOk()) .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE)) .andExpect(jsonPath("$.[*].id").value(hasItem(vsHeartRate.getId()))) .andExpect(jsonPath("$.[*].userid").value(hasItem(DEFAULT_USERID.toString()))) .andExpect(jsonPath("$.[*].bpm").value(hasItem(DEFAULT_BPM.doubleValue()))) .andExpect(jsonPath("$.[*].measurmentdate").value(hasItem(DEFAULT_MEASURMENTDATE.toString()))); } @Test public void getVsHeartRate() throws Exception { // Initialize the database vsHeartRateRepository.save(vsHeartRate); // Get the vsHeartRate restVsHeartRateMockMvc.perform(get("/api/vs-heart-rates/{id}", vsHeartRate.getId())) .andExpect(status().isOk()) .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE)) .andExpect(jsonPath("$.id").value(vsHeartRate.getId())) .andExpect(jsonPath("$.userid").value(DEFAULT_USERID.toString())) .andExpect(jsonPath("$.bpm").value(DEFAULT_BPM.doubleValue())) .andExpect(jsonPath("$.measurmentdate").value(DEFAULT_MEASURMENTDATE.toString())); } @Test public void getNonExistingVsHeartRate() throws Exception { // Get the vsHeartRate restVsHeartRateMockMvc.perform(get("/api/vs-heart-rates/{id}", Long.MAX_VALUE)) .andExpect(status().isNotFound()); } @Test public void updateVsHeartRate() throws Exception { // Initialize the database vsHeartRateRepository.save(vsHeartRate); int databaseSizeBeforeUpdate = vsHeartRateRepository.findAll().size(); // Update the vsHeartRate VsHeartRate updatedVsHeartRate = vsHeartRateRepository.findOne(vsHeartRate.getId()); updatedVsHeartRate .userid(UPDATED_USERID) .bpm(UPDATED_BPM) .measurmentdate(UPDATED_MEASURMENTDATE); VsHeartRateDTO vsHeartRateDTO = vsHeartRateMapper.toDto(updatedVsHeartRate); restVsHeartRateMockMvc.perform(put("/api/vs-heart-rates") .contentType(TestUtil.APPLICATION_JSON_UTF8) .content(TestUtil.convertObjectToJsonBytes(vsHeartRateDTO))) .andExpect(status().isOk()); // Validate the VsHeartRate in the database List<VsHeartRate> vsHeartRateList = vsHeartRateRepository.findAll(); assertThat(vsHeartRateList).hasSize(databaseSizeBeforeUpdate); VsHeartRate testVsHeartRate = vsHeartRateList.get(vsHeartRateList.size() - 1); assertThat(testVsHeartRate.getUserid()).isEqualTo(UPDATED_USERID); assertThat(testVsHeartRate.getBpm()).isEqualTo(UPDATED_BPM); assertThat(testVsHeartRate.getMeasurmentdate()).isEqualTo(UPDATED_MEASURMENTDATE); } @Test public void updateNonExistingVsHeartRate() throws Exception { int databaseSizeBeforeUpdate = vsHeartRateRepository.findAll().size(); // Create the VsHeartRate VsHeartRateDTO vsHeartRateDTO = vsHeartRateMapper.toDto(vsHeartRate); // If the entity doesn't have an ID, it will be created instead of just being updated restVsHeartRateMockMvc.perform(put("/api/vs-heart-rates") .contentType(TestUtil.APPLICATION_JSON_UTF8) .content(TestUtil.convertObjectToJsonBytes(vsHeartRateDTO))) .andExpect(status().isCreated()); // Validate the VsHeartRate in the database List<VsHeartRate> vsHeartRateList = vsHeartRateRepository.findAll(); assertThat(vsHeartRateList).hasSize(databaseSizeBeforeUpdate + 1); } @Test public void deleteVsHeartRate() throws Exception { // Initialize the database vsHeartRateRepository.save(vsHeartRate); int databaseSizeBeforeDelete = vsHeartRateRepository.findAll().size(); // Get the vsHeartRate restVsHeartRateMockMvc.perform(delete("/api/vs-heart-rates/{id}", vsHeartRate.getId()) .accept(TestUtil.APPLICATION_JSON_UTF8)) .andExpect(status().isOk()); // Validate the database is empty List<VsHeartRate> vsHeartRateList = vsHeartRateRepository.findAll(); assertThat(vsHeartRateList).hasSize(databaseSizeBeforeDelete - 1); } @Test public void equalsVerifier() throws Exception { TestUtil.equalsVerifier(VsHeartRate.class); VsHeartRate vsHeartRate1 = new VsHeartRate(); vsHeartRate1.setId("id1"); VsHeartRate vsHeartRate2 = new VsHeartRate(); vsHeartRate2.setId(vsHeartRate1.getId()); assertThat(vsHeartRate1).isEqualTo(vsHeartRate2); vsHeartRate2.setId("id2"); assertThat(vsHeartRate1).isNotEqualTo(vsHeartRate2); vsHeartRate1.setId(null); assertThat(vsHeartRate1).isNotEqualTo(vsHeartRate2); } @Test public void dtoEqualsVerifier() throws Exception { TestUtil.equalsVerifier(VsHeartRateDTO.class); VsHeartRateDTO vsHeartRateDTO1 = new VsHeartRateDTO(); vsHeartRateDTO1.setId("id1"); VsHeartRateDTO vsHeartRateDTO2 = new VsHeartRateDTO(); assertThat(vsHeartRateDTO1).isNotEqualTo(vsHeartRateDTO2); vsHeartRateDTO2.setId(vsHeartRateDTO1.getId()); assertThat(vsHeartRateDTO1).isEqualTo(vsHeartRateDTO2); vsHeartRateDTO2.setId("id2"); assertThat(vsHeartRateDTO1).isNotEqualTo(vsHeartRateDTO2); vsHeartRateDTO1.setId(null); assertThat(vsHeartRateDTO1).isNotEqualTo(vsHeartRateDTO2); } } <file_sep>/src/main/webapp/app/entities/dentist-visit/dentist-visit-detail.component.ts import { Component, OnInit, OnDestroy } from '@angular/core'; import { ActivatedRoute } from '@angular/router'; import { HttpResponse } from '@angular/common/http'; import { Subscription } from 'rxjs/Subscription'; import { JhiEventManager } from 'ng-jhipster'; import { DentistVisit } from './dentist-visit.model'; import { DentistVisitService } from './dentist-visit.service'; @Component({ selector: 'jhi-dentist-visit-detail', templateUrl: './dentist-visit-detail.component.html' }) export class DentistVisitDetailComponent implements OnInit, OnDestroy { dentistVisit: DentistVisit; private subscription: Subscription; private eventSubscriber: Subscription; constructor( private eventManager: JhiEventManager, private dentistVisitService: DentistVisitService, private route: ActivatedRoute ) { } ngOnInit() { this.subscription = this.route.params.subscribe((params) => { this.load(params['id']); }); this.registerChangeInDentistVisits(); } load(id) { this.dentistVisitService.find(id) .subscribe((dentistVisitResponse: HttpResponse<DentistVisit>) => { this.dentistVisit = dentistVisitResponse.body; }); } previousState() { window.history.back(); } ngOnDestroy() { this.subscription.unsubscribe(); this.eventManager.destroy(this.eventSubscriber); } registerChangeInDentistVisits() { this.eventSubscriber = this.eventManager.subscribe( 'dentistVisitListModification', (response) => this.load(this.dentistVisit.id) ); } } <file_sep>/src/main/java/com/sirtts/repository/DentistVisitRepository.java package com.sirtts.repository; import com.sirtts.domain.DentistVisit; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.stereotype.Repository; import org.springframework.data.mongodb.repository.MongoRepository; import java.time.LocalDateTime; /** * Spring Data MongoDB repository for the DentistVisit entity. */ @SuppressWarnings("unused") @Repository public interface DentistVisitRepository extends MongoRepository<DentistVisit, String> { Page<DentistVisit> findAllByUseridInAndAndMeasurmentdateBetweenOrderByMeasurmentdateDesc(String[] userids, LocalDateTime startDate, LocalDateTime endDate, Pageable pageable); } <file_sep>/src/main/webapp/app/entities/dentist-visit/dentist-visit.service.ts import { Injectable } from '@angular/core'; import { HttpClient, HttpResponse } from '@angular/common/http'; import { Observable } from 'rxjs/Observable'; import { SERVER_API_URL } from '../../app.constants'; import { JhiDateUtils } from 'ng-jhipster'; import { DentistVisit } from './dentist-visit.model'; import { createRequestOption } from '../../shared'; export type EntityResponseType = HttpResponse<DentistVisit>; @Injectable() export class DentistVisitService { private resourceUrl = SERVER_API_URL + 'api/dentist-visits'; constructor(private http: HttpClient, private dateUtils: JhiDateUtils) { } create(dentistVisit: DentistVisit): Observable<EntityResponseType> { const copy = this.convert(dentistVisit); return this.http.post<DentistVisit>(this.resourceUrl, copy, { observe: 'response' }) .map((res: EntityResponseType) => this.convertResponse(res)); } update(dentistVisit: DentistVisit): Observable<EntityResponseType> { const copy = this.convert(dentistVisit); return this.http.put<DentistVisit>(this.resourceUrl, copy, { observe: 'response' }) .map((res: EntityResponseType) => this.convertResponse(res)); } find(id: string): Observable<EntityResponseType> { return this.http.get<DentistVisit>(`${this.resourceUrl}/${id}`, { observe: 'response'}) .map((res: EntityResponseType) => this.convertResponse(res)); } query(req?: any): Observable<HttpResponse<DentistVisit[]>> { const options = createRequestOption(req); return this.http.get<DentistVisit[]>(`${this.resourceUrl}/byUserid/`, { params: options, observe: 'response' }) .map((res: HttpResponse<DentistVisit[]>) => this.convertArrayResponse(res)); } delete(id: string): Observable<HttpResponse<any>> { return this.http.delete<any>(`${this.resourceUrl}/${id}`, { observe: 'response'}); } private convertResponse(res: EntityResponseType): EntityResponseType { const body: DentistVisit = this.convertItemFromServer(res.body); return res.clone({body}); } private convertArrayResponse(res: HttpResponse<DentistVisit[]>): HttpResponse<DentistVisit[]> { const jsonResponse: DentistVisit[] = res.body; const body: DentistVisit[] = []; for (let i = 0; i < jsonResponse.length; i++) { body.push(this.convertItemFromServer(jsonResponse[i])); } return res.clone({body}); } /** * Convert a returned JSON object to DentistVisit. */ private convertItemFromServer(dentistVisit: DentistVisit): DentistVisit { const copy: DentistVisit = Object.assign({}, dentistVisit); copy.measurmentdate = this.dateUtils .convertDateTimeFromServer(dentistVisit.measurmentdate); return copy; } /** * Convert a DentistVisit to a JSON which can be sent to the server. */ private convert(dentistVisit: DentistVisit): DentistVisit { const copy: DentistVisit = Object.assign({}, dentistVisit); return copy; } } <file_sep>/src/main/java/com/sirtts/service/impl/VsRespiratoryRateServiceImpl.java package com.sirtts.service.impl; import com.sirtts.security.SecurityUtils; import com.sirtts.service.VsRespiratoryRateService; import com.sirtts.domain.VsRespiratoryRate; import com.sirtts.repository.VsRespiratoryRateRepository; import com.sirtts.service.dto.VsRespiratoryRateDTO; import com.sirtts.service.mapper.VsRespiratoryRateMapper; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.stereotype.Service; import java.time.LocalDateTime; import java.time.ZoneOffset; /** * Service Implementation for managing VsRespiratoryRate. */ @Service public class VsRespiratoryRateServiceImpl implements VsRespiratoryRateService { private final Logger log = LoggerFactory.getLogger(VsRespiratoryRateServiceImpl.class); private final VsRespiratoryRateRepository vsRespiratoryRateRepository; private final VsRespiratoryRateMapper vsRespiratoryRateMapper; public VsRespiratoryRateServiceImpl(VsRespiratoryRateRepository vsRespiratoryRateRepository, VsRespiratoryRateMapper vsRespiratoryRateMapper) { this.vsRespiratoryRateRepository = vsRespiratoryRateRepository; this.vsRespiratoryRateMapper = vsRespiratoryRateMapper; } /** * Save a vsRespiratoryRate. * * @param vsRespiratoryRateDTO the entity to save * @return the persisted entity */ @Override public VsRespiratoryRateDTO save(VsRespiratoryRateDTO vsRespiratoryRateDTO) { log.debug("Request to save VsRespiratoryRate : {}", vsRespiratoryRateDTO); if(vsRespiratoryRateDTO.getUserid() == null){ vsRespiratoryRateDTO.setUserid(SecurityUtils.getCurrentUserLogin().get().toString()); } VsRespiratoryRate vsRespiratoryRate = vsRespiratoryRateMapper.toEntity(vsRespiratoryRateDTO); vsRespiratoryRate = vsRespiratoryRateRepository.save(vsRespiratoryRate); return vsRespiratoryRateMapper.toDto(vsRespiratoryRate); } /** * Get all the vsRespiratoryRates. * * @param pageable the pagination information * @return the list of entities */ @Override public Page<VsRespiratoryRateDTO> findAll(Pageable pageable) { log.debug("Request to get all VsRespiratoryRates"); return vsRespiratoryRateRepository.findAll(pageable) .map(vsRespiratoryRateMapper::toDto); } /** * Get all the vsRespiratoryRates by userid. * * @param pageable the pagination information * @return the list of entities */ @Override public Page<VsRespiratoryRateDTO> findAllByUserid(String[] userids, String startDate, String endDate, Pageable pageable) { log.debug("Request to get all VsRespiratoryRates"); if(userids == null) { userids = new String[1]; userids[0] = SecurityUtils.getCurrentUserLogin().get();; } LocalDateTime start,end; if(startDate == null) start = LocalDateTime.ofEpochSecond(Integer.MIN_VALUE,0, ZoneOffset.UTC); else start = LocalDateTime.parse(startDate+"T00:00:00"); if(endDate == null) end = LocalDateTime.ofEpochSecond(Integer.MAX_VALUE,0, ZoneOffset.UTC); else end = LocalDateTime.parse(endDate+"T23:59:59"); return vsRespiratoryRateRepository.findAllByUseridInAndAndMeasurmentdateBetweenOrderByMeasurmentdateDesc(userids,start, end, pageable) .map(vsRespiratoryRateMapper::toDto); } /** * Get one vsRespiratoryRate by id. * * @param id the id of the entity * @return the entity */ @Override public VsRespiratoryRateDTO findOne(String id) { log.debug("Request to get VsRespiratoryRate : {}", id); VsRespiratoryRate vsRespiratoryRate = vsRespiratoryRateRepository.findOne(id); return vsRespiratoryRateMapper.toDto(vsRespiratoryRate); } /** * Delete the vsRespiratoryRate by id. * * @param id the id of the entity */ @Override public void delete(String id) { log.debug("Request to delete VsRespiratoryRate : {}", id); vsRespiratoryRateRepository.delete(id); } } <file_sep>/src/main/java/com/sirtts/service/mapper/DentistVisitMapper.java package com.sirtts.service.mapper; import com.sirtts.domain.*; import com.sirtts.service.dto.DentistVisitDTO; import org.mapstruct.*; /** * Mapper for the entity DentistVisit and its DTO DentistVisitDTO. */ @Mapper(componentModel = "spring", uses = {}) public interface DentistVisitMapper extends EntityMapper<DentistVisitDTO, DentistVisit> { } <file_sep>/src/main/webapp/app/entities/blood-test/index.ts export * from './blood-test.model'; export * from './blood-test-popup.service'; export * from './blood-test.service'; export * from './blood-test-dialog.component'; export * from './blood-test-delete-dialog.component'; export * from './blood-test-detail.component'; export * from './blood-test.component'; export * from './blood-test.route'; export * from './blood-test-info.component'; <file_sep>/src/main/java/com/sirtts/web/rest/DentistNextVisitResource.java package com.sirtts.web.rest; import com.codahale.metrics.annotation.Timed; import com.sirtts.service.DentistNextVisitService; import com.sirtts.web.rest.errors.BadRequestAlertException; import com.sirtts.web.rest.util.HeaderUtil; import com.sirtts.web.rest.util.PaginationUtil; import com.sirtts.service.dto.DentistNextVisitDTO; import io.github.jhipster.web.util.ResponseUtil; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; import javax.validation.Valid; import java.net.URI; import java.net.URISyntaxException; import java.util.List; import java.util.Optional; /** * REST controller for managing DentistNextVisit. */ @RestController @RequestMapping("/api") public class DentistNextVisitResource { private final Logger log = LoggerFactory.getLogger(DentistNextVisitResource.class); private static final String ENTITY_NAME = "dentistNextVisit"; private final DentistNextVisitService dentistNextVisitService; public DentistNextVisitResource(DentistNextVisitService dentistNextVisitService) { this.dentistNextVisitService = dentistNextVisitService; } /** * POST /dentist-next-visits : Create a new dentistNextVisit. * * @param dentistNextVisitDTO the dentistNextVisitDTO to create * @return the ResponseEntity with status 201 (Created) and with body the new dentistNextVisitDTO, or with status 400 (Bad Request) if the dentistNextVisit has already an ID * @throws URISyntaxException if the Location URI syntax is incorrect */ @PostMapping("/dentist-next-visits") @Timed public ResponseEntity<DentistNextVisitDTO> createDentistNextVisit(@Valid @RequestBody DentistNextVisitDTO dentistNextVisitDTO) throws URISyntaxException { log.debug("REST request to save DentistNextVisit : {}", dentistNextVisitDTO); if (dentistNextVisitDTO.getId() != null) { throw new BadRequestAlertException("A new dentistNextVisit cannot already have an ID", ENTITY_NAME, "idexists"); } DentistNextVisitDTO result = dentistNextVisitService.save(dentistNextVisitDTO); return ResponseEntity.created(new URI("/api/dentist-next-visits/" + result.getId())) .headers(HeaderUtil.createEntityCreationAlert(ENTITY_NAME, result.getId().toString())) .body(result); } /** * PUT /dentist-next-visits : Updates an existing dentistNextVisit. * * @param dentistNextVisitDTO the dentistNextVisitDTO to update * @return the ResponseEntity with status 200 (OK) and with body the updated dentistNextVisitDTO, * or with status 400 (Bad Request) if the dentistNextVisitDTO is not valid, * or with status 500 (Internal Server Error) if the dentistNextVisitDTO couldn't be updated * @throws URISyntaxException if the Location URI syntax is incorrect */ @PutMapping("/dentist-next-visits") @Timed public ResponseEntity<DentistNextVisitDTO> updateDentistNextVisit(@Valid @RequestBody DentistNextVisitDTO dentistNextVisitDTO) throws URISyntaxException { log.debug("REST request to update DentistNextVisit : {}", dentistNextVisitDTO); if (dentistNextVisitDTO.getId() == null) { return createDentistNextVisit(dentistNextVisitDTO); } DentistNextVisitDTO result = dentistNextVisitService.save(dentistNextVisitDTO); return ResponseEntity.ok() .headers(HeaderUtil.createEntityUpdateAlert(ENTITY_NAME, dentistNextVisitDTO.getId().toString())) .body(result); } /** * GET /dentist-next-visits : get all the dentistNextVisits. * * @param pageable the pagination information * @return the ResponseEntity with status 200 (OK) and the list of dentistNextVisits in body */ @GetMapping("/dentist-next-visits") @Timed public ResponseEntity<List<DentistNextVisitDTO>> getAllDentistNextVisits(Pageable pageable) { log.debug("REST request to get a page of DentistNextVisits"); Page<DentistNextVisitDTO> page = dentistNextVisitService.findAll(pageable); HttpHeaders headers = PaginationUtil.generatePaginationHttpHeaders(page, "/api/dentist-next-visits"); return new ResponseEntity<>(page.getContent(), headers, HttpStatus.OK); } /** * GET /dentist-next-visits /byUserid : get all the dentistNextVisits by userid. * * @param pageable the pagination information * @return the ResponseEntity with status 200 (OK) and the list of dentistNextVisits in body */ @GetMapping("/dentist-next-visits/byUserid") @Timed public ResponseEntity<List<DentistNextVisitDTO>> getAllDentistNextVisitsByUserid(String[] userids, String startDate, String endDate, Pageable pageable) { log.debug("REST request to get a page of DentistVisits by userid"); Page<DentistNextVisitDTO> page = dentistNextVisitService.findAllByUserid(userids, startDate, endDate, pageable); HttpHeaders headers = PaginationUtil.generatePaginationHttpHeaders(page, "/api/dentist-next-visits/byUserid"); return new ResponseEntity<>(page.getContent(), headers, HttpStatus.OK); } /** * GET /dentist-next-visits/:id : get the "id" dentistNextVisit. * * @param id the id of the dentistNextVisitDTO to retrieve * @return the ResponseEntity with status 200 (OK) and with body the dentistNextVisitDTO, or with status 404 (Not Found) */ @GetMapping("/dentist-next-visits/{id}") @Timed public ResponseEntity<DentistNextVisitDTO> getDentistNextVisit(@PathVariable String id) { log.debug("REST request to get DentistNextVisit : {}", id); DentistNextVisitDTO dentistNextVisitDTO = dentistNextVisitService.findOne(id); return ResponseUtil.wrapOrNotFound(Optional.ofNullable(dentistNextVisitDTO)); } /** * DELETE /dentist-next-visits/:id : delete the "id" dentistNextVisit. * * @param id the id of the dentistNextVisitDTO to delete * @return the ResponseEntity with status 200 (OK) */ @DeleteMapping("/dentist-next-visits/{id}") @Timed public ResponseEntity<Void> deleteDentistNextVisit(@PathVariable String id) { log.debug("REST request to delete DentistNextVisit : {}", id); dentistNextVisitService.delete(id); return ResponseEntity.ok().headers(HeaderUtil.createEntityDeletionAlert(ENTITY_NAME, id)).build(); } } <file_sep>/src/main/webapp/app/entities/diabetes-sugar-test/diabetes-sugar-test-detail.component.ts import { Component, OnInit, OnDestroy } from '@angular/core'; import { ActivatedRoute } from '@angular/router'; import { HttpResponse } from '@angular/common/http'; import { Subscription } from 'rxjs/Subscription'; import { JhiEventManager } from 'ng-jhipster'; import { DiabetesSugarTest } from './diabetes-sugar-test.model'; import { DiabetesSugarTestService } from './diabetes-sugar-test.service'; @Component({ selector: 'jhi-diabetes-sugar-test-detail', templateUrl: './diabetes-sugar-test-detail.component.html' }) export class DiabetesSugarTestDetailComponent implements OnInit, OnDestroy { diabetesSugarTest: DiabetesSugarTest; private subscription: Subscription; private eventSubscriber: Subscription; constructor( private eventManager: JhiEventManager, private diabetesSugarTestService: DiabetesSugarTestService, private route: ActivatedRoute ) { } ngOnInit() { this.subscription = this.route.params.subscribe((params) => { this.load(params['id']); }); this.registerChangeInDiabetesSugarTests(); } load(id) { this.diabetesSugarTestService.find(id) .subscribe((diabetesSugarTestResponse: HttpResponse<DiabetesSugarTest>) => { this.diabetesSugarTest = diabetesSugarTestResponse.body; }); } previousState() { window.history.back(); } ngOnDestroy() { this.subscription.unsubscribe(); this.eventManager.destroy(this.eventSubscriber); } registerChangeInDiabetesSugarTests() { this.eventSubscriber = this.eventManager.subscribe( 'diabetesSugarTestListModification', (response) => this.load(this.diabetesSugarTest.id) ); } } <file_sep>/src/main/webapp/app/entities/vs-heart-rate/vs-heart-rate-detail.component.ts import { Component, OnInit, OnDestroy } from '@angular/core'; import { ActivatedRoute } from '@angular/router'; import { HttpResponse } from '@angular/common/http'; import { Subscription } from 'rxjs/Subscription'; import { JhiEventManager } from 'ng-jhipster'; import { VsHeartRate } from './vs-heart-rate.model'; import { VsHeartRateService } from './vs-heart-rate.service'; @Component({ selector: 'jhi-vs-heart-rate-detail', templateUrl: './vs-heart-rate-detail.component.html' }) export class VsHeartRateDetailComponent implements OnInit, OnDestroy { vsHeartRate: VsHeartRate; private subscription: Subscription; private eventSubscriber: Subscription; constructor( private eventManager: JhiEventManager, private vsHeartRateService: VsHeartRateService, private route: ActivatedRoute ) { } ngOnInit() { this.subscription = this.route.params.subscribe((params) => { this.load(params['id']); }); this.registerChangeInVsHeartRates(); } load(id) { this.vsHeartRateService.find(id) .subscribe((vsHeartRateResponse: HttpResponse<VsHeartRate>) => { this.vsHeartRate = vsHeartRateResponse.body; }); } previousState() { window.history.back(); } ngOnDestroy() { this.subscription.unsubscribe(); this.eventManager.destroy(this.eventSubscriber); } registerChangeInVsHeartRates() { this.eventSubscriber = this.eventManager.subscribe( 'vsHeartRateListModification', (response) => this.load(this.vsHeartRate.id) ); } } <file_sep>/src/main/java/com/sirtts/domain/DentistVisit.java package com.sirtts.domain; import org.springframework.data.annotation.Id; import org.springframework.data.mongodb.core.mapping.Field; import org.springframework.data.mongodb.core.mapping.Document; import javax.validation.constraints.*; import java.io.Serializable; import java.time.LocalDateTime; import java.util.Objects; /** * A DentistVisit. */ @Document(collection = "dentist_visit") public class DentistVisit extends AbstractAuditingEntity implements Serializable { private static final long serialVersionUID = 1L; @Id private String id; @Field("userid") private String userid; @Field("teethcleaning") private Boolean teethcleaning; @Field("whitening") private Boolean whitening; @Field("restoration") private Boolean restoration; @Field("crowns") private Boolean crowns; @Field("bridges") private Boolean bridges; @Field("braces") private Boolean braces; @Field("endodontictherapy") private Boolean endodontictherapy; @Field("periodontaltherapy") private Boolean periodontaltherapy; @Field("extraction") private Boolean extraction; @Field("oralsurgery") private Boolean oralsurgery; @Field("notes") private String notes; @NotNull @Field("measurmentdate") private LocalDateTime measurmentdate; // jhipster-needle-entity-add-field - JHipster will add fields here, do not remove public String getId() { return id; } public void setId(String id) { this.id = id; } public String getUserid() { return userid; } public DentistVisit userid(String userid) { this.userid = userid; return this; } public void setUserid(String userid) { this.userid = userid; } public Boolean isTeethcleaning() { return teethcleaning; } public DentistVisit teethcleaning(Boolean teethcleaning) { this.teethcleaning = teethcleaning; return this; } public void setTeethcleaning(Boolean teethcleaning) { this.teethcleaning = teethcleaning; } public Boolean isWhitening() { return whitening; } public DentistVisit whitening(Boolean whitening) { this.whitening = whitening; return this; } public void setWhitening(Boolean whitening) { this.whitening = whitening; } public Boolean isRestoration() { return restoration; } public DentistVisit restoration(Boolean restoration) { this.restoration = restoration; return this; } public void setRestoration(Boolean restoration) { this.restoration = restoration; } public Boolean isCrowns() { return crowns; } public DentistVisit crowns(Boolean crowns) { this.crowns = crowns; return this; } public void setCrowns(Boolean crowns) { this.crowns = crowns; } public Boolean isBridges() { return bridges; } public DentistVisit bridges(Boolean bridges) { this.bridges = bridges; return this; } public void setBridges(Boolean bridges) { this.bridges = bridges; } public Boolean isBraces() { return braces; } public DentistVisit braces(Boolean braces) { this.braces = braces; return this; } public void setBraces(Boolean braces) { this.braces = braces; } public Boolean isEndodontictherapy() { return endodontictherapy; } public DentistVisit endodontictherapy(Boolean endodontictherapy) { this.endodontictherapy = endodontictherapy; return this; } public void setEndodontictherapy(Boolean endodontictherapy) { this.endodontictherapy = endodontictherapy; } public Boolean isPeriodontaltherapy() { return periodontaltherapy; } public DentistVisit periodontaltherapy(Boolean periodontaltherapy) { this.periodontaltherapy = periodontaltherapy; return this; } public void setPeriodontaltherapy(Boolean periodontaltherapy) { this.periodontaltherapy = periodontaltherapy; } public Boolean isExtraction() { return extraction; } public DentistVisit extraction(Boolean extraction) { this.extraction = extraction; return this; } public void setExtraction(Boolean extraction) { this.extraction = extraction; } public Boolean isOralsurgery() { return oralsurgery; } public DentistVisit oralsurgery(Boolean oralsurgery) { this.oralsurgery = oralsurgery; return this; } public void setOralsurgery(Boolean oralsurgery) { this.oralsurgery = oralsurgery; } public String getNotes() { return notes; } public DentistVisit notes(String notes) { this.notes = notes; return this; } public void setNotes(String notes) { this.notes = notes; } public LocalDateTime getMeasurmentdate() { return measurmentdate; } public DentistVisit measurmentdate(LocalDateTime measurmentdate) { this.measurmentdate = measurmentdate; return this; } public void setMeasurmentdate(LocalDateTime measurmentdate) { this.measurmentdate = measurmentdate; } // jhipster-needle-entity-add-getters-setters - JHipster will add getters and setters here, do not remove @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } DentistVisit dentistVisit = (DentistVisit) o; if (dentistVisit.getId() == null || getId() == null) { return false; } return Objects.equals(getId(), dentistVisit.getId()); } @Override public int hashCode() { return Objects.hashCode(getId()); } @Override public String toString() { return "DentistVisit{" + "id=" + getId() + ", userid='" + getUserid() + "'" + ", teethcleaning='" + isTeethcleaning() + "'" + ", whitening='" + isWhitening() + "'" + ", restoration='" + isRestoration() + "'" + ", crowns='" + isCrowns() + "'" + ", bridges='" + isBridges() + "'" + ", braces='" + isBraces() + "'" + ", endodontictherapy='" + isEndodontictherapy() + "'" + ", periodontaltherapy='" + isPeriodontaltherapy() + "'" + ", extraction='" + isExtraction() + "'" + ", oralsurgery='" + isOralsurgery() + "'" + ", notes='" + getNotes() + "'" + ", measurmentdate='" + getMeasurmentdate() + "'" + "}"; } } <file_sep>/src/main/webapp/app/entities/dentist-next-visit/dentist-next-visit.module.ts import { NgModule, CUSTOM_ELEMENTS_SCHEMA } from '@angular/core'; import { RouterModule } from '@angular/router'; import { HcPortalSharedModule } from '../../shared'; import { DentistNextVisitService, DentistNextVisitPopupService, DentistNextVisitComponent, DentistNextVisitDetailComponent, DentistNextVisitDialogComponent, DentistNextVisitPopupComponent, DentistNextVisitDeletePopupComponent, DentistNextVisitDeleteDialogComponent, dentistNextVisitRoute, dentistNextVisitPopupRoute, DentistNextVisitResolvePagingParams, } from './'; const ENTITY_STATES = [ ...dentistNextVisitRoute, ...dentistNextVisitPopupRoute, ]; @NgModule({ imports: [ HcPortalSharedModule, RouterModule.forChild(ENTITY_STATES) ], declarations: [ DentistNextVisitComponent, DentistNextVisitDetailComponent, DentistNextVisitDialogComponent, DentistNextVisitDeleteDialogComponent, DentistNextVisitPopupComponent, DentistNextVisitDeletePopupComponent, ], entryComponents: [ DentistNextVisitComponent, DentistNextVisitDialogComponent, DentistNextVisitPopupComponent, DentistNextVisitDeleteDialogComponent, DentistNextVisitDeletePopupComponent, ], providers: [ DentistNextVisitService, DentistNextVisitPopupService, DentistNextVisitResolvePagingParams, ], schemas: [CUSTOM_ELEMENTS_SCHEMA] }) export class HcPortalDentistNextVisitModule {} <file_sep>/src/main/webapp/app/entities/vs-spo-2/vs-spo-2-info.component.html <div class="modal-header"> <h4 class="info-modal-title" id="spo2-info" jhiTranslate="hcPortalApp.info.spo2">SpO2</h4> </div> <div class="info-modal"> <h6>SpO2 is an estimate of arterial oxygen saturation, or SaO2, which refers to the amount of oxygenated haemoglobin in the blood. Haemoglobin is a protein that carries oxygen in the blood. It is found inside red blood cells and gives them their red colour.</h6> </div> <div class="modal-footer info-modal-footer"> <button type="button" class="close" data-dismiss="modal" aria-hidden="true" (click)="clear()">&times;</button> </div> <file_sep>/src/main/webapp/app/entities/dentist-next-visit/index.ts export * from './dentist-next-visit.model'; export * from './dentist-next-visit-popup.service'; export * from './dentist-next-visit.service'; export * from './dentist-next-visit-dialog.component'; export * from './dentist-next-visit-delete-dialog.component'; export * from './dentist-next-visit-detail.component'; export * from './dentist-next-visit.component'; export * from './dentist-next-visit.route'; <file_sep>/src/main/java/com/sirtts/domain/MenstrualCycle.java package com.sirtts.domain; import org.springframework.data.annotation.Id; import org.springframework.data.mongodb.core.mapping.Field; import org.springframework.data.mongodb.core.mapping.Document; import javax.validation.constraints.*; import java.io.Serializable; import java.time.LocalDateTime; import java.util.Objects; /** * A MenstrualCycle. */ @Document(collection = "menstrual_cycle") public class MenstrualCycle extends AbstractAuditingEntity implements Serializable { private static final long serialVersionUID = 1L; @Id private String id; @Field("userid") private String userid; @NotNull @Field("start_date") private LocalDateTime startDate; @NotNull @Field("end_date") private LocalDateTime endDate; // jhipster-needle-entity-add-field - JHipster will add fields here, do not remove public String getId() { return id; } public void setId(String id) { this.id = id; } public String getUserid() { return userid; } public MenstrualCycle userid(String userid) { this.userid = userid; return this; } public void setUserid(String userid) { this.userid = userid; } public LocalDateTime getStartDate() { return startDate; } public MenstrualCycle startDate(LocalDateTime startDate) { this.startDate = startDate; return this; } public void setStartDate(LocalDateTime startDate) { this.startDate = startDate; } public LocalDateTime getEndDate() { return endDate; } public MenstrualCycle endDate(LocalDateTime endDate) { this.endDate = endDate; return this; } public void setEndDate(LocalDateTime endDate) { this.endDate = endDate; } // jhipster-needle-entity-add-getters-setters - JHipster will add getters and setters here, do not remove @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } MenstrualCycle menstrualCycle = (MenstrualCycle) o; if (menstrualCycle.getId() == null || getId() == null) { return false; } return Objects.equals(getId(), menstrualCycle.getId()); } @Override public int hashCode() { return Objects.hashCode(getId()); } @Override public String toString() { return "MenstrualCycle{" + "id=" + getId() + ", userid='" + getUserid() + "'" + ", startDate='" + getStartDate() + "'" + ", endDate='" + getEndDate() + "'" + "}"; } } <file_sep>/src/main/webapp/app/entities/vs-body-temperature/vs-body-temperature-delete-dialog.component.ts import { Component, OnInit, OnDestroy } from '@angular/core'; import { ActivatedRoute } from '@angular/router'; import { NgbActiveModal } from '@ng-bootstrap/ng-bootstrap'; import { JhiEventManager } from 'ng-jhipster'; import { VsBodyTemperature } from './vs-body-temperature.model'; import { VsBodyTemperaturePopupService } from './vs-body-temperature-popup.service'; import { VsBodyTemperatureService } from './vs-body-temperature.service'; @Component({ selector: 'jhi-vs-body-temperature-delete-dialog', templateUrl: './vs-body-temperature-delete-dialog.component.html' }) export class VsBodyTemperatureDeleteDialogComponent { vsBodyTemperature: VsBodyTemperature; constructor( private vsBodyTemperatureService: VsBodyTemperatureService, public activeModal: NgbActiveModal, private eventManager: JhiEventManager ) { } clear() { this.activeModal.dismiss('cancel'); } confirmDelete(id: string) { this.vsBodyTemperatureService.delete(id).subscribe((response) => { this.eventManager.broadcast({ name: 'vsBodyTemperatureListModification', content: 'Deleted an vsBodyTemperature' }); this.activeModal.dismiss(true); }); } } @Component({ selector: 'jhi-vs-body-temperature-delete-popup', template: '' }) export class VsBodyTemperatureDeletePopupComponent implements OnInit, OnDestroy { routeSub: any; constructor( private route: ActivatedRoute, private vsBodyTemperaturePopupService: VsBodyTemperaturePopupService ) {} ngOnInit() { this.routeSub = this.route.params.subscribe((params) => { this.vsBodyTemperaturePopupService .open(VsBodyTemperatureDeleteDialogComponent as Component, params['id']); }); } ngOnDestroy() { this.routeSub.unsubscribe(); } } <file_sep>/src/main/webapp/app/entities/dentist-visit/dentist-visit.module.ts import {NgModule, CUSTOM_ELEMENTS_SCHEMA} from '@angular/core'; import {RouterModule} from '@angular/router'; import {HcPortalSharedModule} from '../../shared'; import { DentistVisitService, DentistVisitPopupService, DentistVisitComponent, DentistVisitDetailComponent, DentistVisitDialogComponent, DentistVisitPopupComponent, DentistVisitDeletePopupComponent, DentistVisitDeleteDialogComponent, dentistVisitRoute, dentistVisitPopupRoute, DentistVisitResolvePagingParams, DentistVisitInfoComponent, DentistVisitInfoPopupComponent } from './'; const ENTITY_STATES = [ ...dentistVisitRoute, ...dentistVisitPopupRoute, ]; @NgModule({ imports: [ HcPortalSharedModule, RouterModule.forChild(ENTITY_STATES) ], declarations: [ DentistVisitComponent, DentistVisitDetailComponent, DentistVisitDialogComponent, DentistVisitDeleteDialogComponent, DentistVisitPopupComponent, DentistVisitDeletePopupComponent, DentistVisitInfoComponent, DentistVisitInfoPopupComponent ], entryComponents: [ DentistVisitComponent, DentistVisitDialogComponent, DentistVisitPopupComponent, DentistVisitDeleteDialogComponent, DentistVisitDeletePopupComponent, DentistVisitInfoComponent, DentistVisitInfoPopupComponent ], providers: [ DentistVisitService, DentistVisitPopupService, DentistVisitResolvePagingParams, ], schemas: [CUSTOM_ELEMENTS_SCHEMA] }) export class HcPortalDentistVisitModule { } <file_sep>/src/main/webapp/app/entities/dr-patients/index.ts export * from './dr-patients.model'; export * from './dr-patients-popup.service'; export * from './dr-patients.service'; export * from './dr-patients-dialog.component'; export * from './dr-patients-remove-dialog.component'; export * from './dr-patients-detail.component'; export * from './dr-patients.component'; export * from './dr-patients.route'; export * from './dr-patients-info.component'; <file_sep>/src/main/webapp/app/entities/menstrual-cycle/menstrual-cycle-info.component.ts import {Component, OnInit, OnDestroy} from '@angular/core'; import {ActivatedRoute} from '@angular/router'; import {NgbActiveModal} from '@ng-bootstrap/ng-bootstrap'; import {MenstrualCyclePopupService} from './menstrual-cycle-popup.service'; @Component({ selector: 'jhi-menstrual-cycle-info', templateUrl: './menstrual-cycle-info.component.html' }) export class MenstrualCycleInfoComponent implements OnInit { constructor( public activeModal: NgbActiveModal, ) { } ngOnInit() { } clear() { this.activeModal.dismiss('cancel'); } } @Component({ selector: 'jhi-menstrual-cycle-info-popup', template: '' }) export class MenstrualCycleInfoPopupComponent implements OnInit, OnDestroy { routeSub: any; constructor( private route: ActivatedRoute, private menstrualCyclePopupService: MenstrualCyclePopupService ) { } ngOnInit() { this.routeSub = this.route.params.subscribe(() => { this.menstrualCyclePopupService.open(MenstrualCycleInfoComponent as Component); }); } ngOnDestroy() { this.routeSub.unsubscribe(); } } <file_sep>/src/main/webapp/app/entities/diabetes-sugar-test/diabetes-sugar-test-info.component.html <div class="modal-header"> <h4 class="info-modal-title" id="blood_sugar-info" jhiTranslate="hcPortalApp.info.blood_sugar">Blood Sugar</h4> </div> <div class="info-modal"> <h6> Commonly referred to as diabetes, is a group of metabolic disorders in which there are high blood sugar levels over a prolonged period. Symptoms of high blood sugar include frequent urination, increased thirst, and increased hunger. </h6> </div> <div class="modal-footer info-modal-footer"> <button type="button" class="close" data-dismiss="modal" aria-hidden="true" (click)="clear()">&times;</button> </div> <file_sep>/src/main/webapp/app/entities/vs-respiratory-rate/index.ts export * from './vs-respiratory-rate.model'; export * from './vs-respiratory-rate-popup.service'; export * from './vs-respiratory-rate.service'; export * from './vs-respiratory-rate-dialog.component'; export * from './vs-respiratory-rate-delete-dialog.component'; export * from './vs-respiratory-rate-detail.component'; export * from './vs-respiratory-rate.component'; export * from './vs-respiratory-rate.route'; export * from './vs-respiratory-rate-info.component'; <file_sep>/src/main/java/com/sirtts/repository/BloodTestRepository.java package com.sirtts.repository; import com.sirtts.domain.BloodTest; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.stereotype.Repository; import org.springframework.data.mongodb.repository.MongoRepository; import java.time.LocalDateTime; /** * Spring Data MongoDB repository for the BloodTest entity. */ @SuppressWarnings("unused") @Repository public interface BloodTestRepository extends MongoRepository<BloodTest, String> { Page<BloodTest> findAllByUseridInAndAndMeasurmentdateBetweenOrderByMeasurmentdateDesc(String[] userids, LocalDateTime startDate, LocalDateTime endDate, Pageable pageable); } <file_sep>/src/main/webapp/app/entities/dr-patients/dr-patients.module.ts import {NgModule, CUSTOM_ELEMENTS_SCHEMA} from '@angular/core'; import {RouterModule} from '@angular/router'; import {HcPortalSharedModule} from '../../shared'; import { DrPatientsService, DrPatientsPopupService, DrPatientsComponent, DrPatientsDetailComponent, DrPatientsDetailPopupComponent, DrPatientsDialogComponent, DrPatientsPopupComponent, DrPatientsRemovePopupComponent, DrPatientsRemoveDialogComponent, DrPatientsRoute, DrPatientsPopupRoute, DrPatientsResolvePagingParams, DrPatientsInfoComponent, DrPatientsInfoPopupComponent } from './'; const ENTITY_STATES = [ ...DrPatientsRoute, ...DrPatientsPopupRoute, ]; @NgModule({ imports: [ HcPortalSharedModule, RouterModule.forChild(ENTITY_STATES) ], declarations: [ DrPatientsComponent, DrPatientsDetailComponent, DrPatientsDialogComponent, DrPatientsRemoveDialogComponent, DrPatientsPopupComponent, DrPatientsRemovePopupComponent, DrPatientsInfoComponent, DrPatientsInfoPopupComponent, DrPatientsDetailPopupComponent ], entryComponents: [ DrPatientsComponent, DrPatientsDialogComponent, DrPatientsPopupComponent, DrPatientsRemoveDialogComponent, DrPatientsRemovePopupComponent, DrPatientsInfoComponent, DrPatientsInfoPopupComponent, DrPatientsDetailPopupComponent ], providers: [ DrPatientsService, DrPatientsPopupService, DrPatientsResolvePagingParams, ], schemas: [CUSTOM_ELEMENTS_SCHEMA] }) export class HcPortalDrPatientsModule { } <file_sep>/src/main/java/com/sirtts/service/dto/package-info.java /** * Data Transfer Objects. */ package com.sirtts.service.dto; <file_sep>/src/main/webapp/app/entities/vs-blood-pressure/vs-blood-pressure-dialog.component.ts import { Component, OnInit, OnDestroy } from '@angular/core'; import { ActivatedRoute } from '@angular/router'; import { HttpResponse, HttpErrorResponse } from '@angular/common/http'; import { Observable } from 'rxjs/Observable'; import { NgbActiveModal } from '@ng-bootstrap/ng-bootstrap'; import { JhiEventManager } from 'ng-jhipster'; import { VsBloodPressure } from './vs-blood-pressure.model'; import { VsBloodPressurePopupService } from './vs-blood-pressure-popup.service'; import { VsBloodPressureService } from './vs-blood-pressure.service'; @Component({ selector: 'jhi-vs-blood-pressure-dialog', templateUrl: './vs-blood-pressure-dialog.component.html' }) export class VsBloodPressureDialogComponent implements OnInit { vsBloodPressure: VsBloodPressure; isSaving: boolean; measurmentdateDp: any; constructor( public activeModal: NgbActiveModal, private vsBloodPressureService: VsBloodPressureService, private eventManager: JhiEventManager ) { } ngOnInit() { this.isSaving = false; } clear() { this.activeModal.dismiss('cancel'); } save() { this.isSaving = true; if (this.vsBloodPressure.id !== undefined) { this.subscribeToSaveResponse( this.vsBloodPressureService.update(this.vsBloodPressure)); } else { this.subscribeToSaveResponse( this.vsBloodPressureService.create(this.vsBloodPressure)); } } private subscribeToSaveResponse(result: Observable<HttpResponse<VsBloodPressure>>) { result.subscribe((res: HttpResponse<VsBloodPressure>) => this.onSaveSuccess(res.body), (res: HttpErrorResponse) => this.onSaveError()); } private onSaveSuccess(result: VsBloodPressure) { this.eventManager.broadcast({ name: 'vsBloodPressureListModification', content: 'OK'}); this.isSaving = false; this.activeModal.dismiss(result); } private onSaveError() { this.isSaving = false; } } @Component({ selector: 'jhi-vs-blood-pressure-popup', template: '' }) export class VsBloodPressurePopupComponent implements OnInit, OnDestroy { routeSub: any; constructor( private route: ActivatedRoute, private vsBloodPressurePopupService: VsBloodPressurePopupService ) {} ngOnInit() { this.routeSub = this.route.params.subscribe((params) => { if ( params['id'] ) { this.vsBloodPressurePopupService .open(VsBloodPressureDialogComponent as Component, params['id']); } else { this.vsBloodPressurePopupService .open(VsBloodPressureDialogComponent as Component); } }); } ngOnDestroy() { this.routeSub.unsubscribe(); } } <file_sep>/src/main/java/com/sirtts/web/rest/DiabetesSugarTestResource.java package com.sirtts.web.rest; import com.codahale.metrics.annotation.Timed; import com.sirtts.service.DiabetesSugarTestService; import com.sirtts.web.rest.errors.BadRequestAlertException; import com.sirtts.web.rest.util.HeaderUtil; import com.sirtts.web.rest.util.PaginationUtil; import com.sirtts.service.dto.DiabetesSugarTestDTO; import io.github.jhipster.web.util.ResponseUtil; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; import javax.validation.Valid; import java.net.URI; import java.net.URISyntaxException; import java.util.List; import java.util.Optional; /** * REST controller for managing DiabetesSugarTest. */ @RestController @RequestMapping("/api") public class DiabetesSugarTestResource { private final Logger log = LoggerFactory.getLogger(DiabetesSugarTestResource.class); private static final String ENTITY_NAME = "diabetesSugarTest"; private final DiabetesSugarTestService diabetesSugarTestService; public DiabetesSugarTestResource(DiabetesSugarTestService diabetesSugarTestService) { this.diabetesSugarTestService = diabetesSugarTestService; } /** * POST /diabetes-sugar-tests : Create a new diabetesSugarTest. * * @param diabetesSugarTestDTO the diabetesSugarTestDTO to create * @return the ResponseEntity with status 201 (Created) and with body the new diabetesSugarTestDTO, or with status 400 (Bad Request) if the diabetesSugarTest has already an ID * @throws URISyntaxException if the Location URI syntax is incorrect */ @PostMapping("/diabetes-sugar-tests") @Timed public ResponseEntity<DiabetesSugarTestDTO> createDiabetesSugarTest(@Valid @RequestBody DiabetesSugarTestDTO diabetesSugarTestDTO) throws URISyntaxException { log.debug("REST request to save DiabetesSugarTest : {}", diabetesSugarTestDTO); if (diabetesSugarTestDTO.getId() != null) { throw new BadRequestAlertException("A new diabetesSugarTest cannot already have an ID", ENTITY_NAME, "idexists"); } DiabetesSugarTestDTO result = diabetesSugarTestService.save(diabetesSugarTestDTO); return ResponseEntity.created(new URI("/api/diabetes-sugar-tests/" + result.getId())) .headers(HeaderUtil.createEntityCreationAlert(ENTITY_NAME, result.getId().toString())) .body(result); } /** * PUT /diabetes-sugar-tests : Updates an existing diabetesSugarTest. * * @param diabetesSugarTestDTO the diabetesSugarTestDTO to update * @return the ResponseEntity with status 200 (OK) and with body the updated diabetesSugarTestDTO, * or with status 400 (Bad Request) if the diabetesSugarTestDTO is not valid, * or with status 500 (Internal Server Error) if the diabetesSugarTestDTO couldn't be updated * @throws URISyntaxException if the Location URI syntax is incorrect */ @PutMapping("/diabetes-sugar-tests") @Timed public ResponseEntity<DiabetesSugarTestDTO> updateDiabetesSugarTest(@Valid @RequestBody DiabetesSugarTestDTO diabetesSugarTestDTO) throws URISyntaxException { log.debug("REST request to update DiabetesSugarTest : {}", diabetesSugarTestDTO); if (diabetesSugarTestDTO.getId() == null) { return createDiabetesSugarTest(diabetesSugarTestDTO); } DiabetesSugarTestDTO result = diabetesSugarTestService.save(diabetesSugarTestDTO); return ResponseEntity.ok() .headers(HeaderUtil.createEntityUpdateAlert(ENTITY_NAME, diabetesSugarTestDTO.getId().toString())) .body(result); } /** * GET /diabetes-sugar-tests : get all the diabetesSugarTests. * * @param pageable the pagination information * @return the ResponseEntity with status 200 (OK) and the list of diabetesSugarTests in body */ @GetMapping("/diabetes-sugar-tests") @Timed public ResponseEntity<List<DiabetesSugarTestDTO>> getAllDiabetesSugarTests(Pageable pageable) { log.debug("REST request to get a page of DiabetesSugarTests"); Page<DiabetesSugarTestDTO> page = diabetesSugarTestService.findAll(pageable); HttpHeaders headers = PaginationUtil.generatePaginationHttpHeaders(page, "/api/diabetes-sugar-tests"); return new ResponseEntity<>(page.getContent(), headers, HttpStatus.OK); } /** * GET /diabetes-sugar-tests/byUserid : get all the diabetesSugarTests by userid. * * @param pageable the pagination information * @return the ResponseEntity with status 200 (OK) and the list of diabetesSugarTests in body */ @GetMapping("/diabetes-sugar-tests/byUserid") @Timed public ResponseEntity<List<DiabetesSugarTestDTO>> getAllDiabetesSugarTestsByUserid(String[] userids, String startDate, String endDate, Pageable pageable) { log.debug("REST request to get a page of DiabetesSugarTests by userid"); Page<DiabetesSugarTestDTO> page = diabetesSugarTestService.findAllByUserid(userids, startDate, endDate, pageable); HttpHeaders headers = PaginationUtil.generatePaginationHttpHeaders(page, "/api/diabetes-sugar-tests/byUserid"); return new ResponseEntity<>(page.getContent(), headers, HttpStatus.OK); } /** * GET /diabetes-sugar-tests/:id : get the "id" diabetesSugarTest. * * @param id the id of the diabetesSugarTestDTO to retrieve * @return the ResponseEntity with status 200 (OK) and with body the diabetesSugarTestDTO, or with status 404 (Not Found) */ @GetMapping("/diabetes-sugar-tests/{id}") @Timed public ResponseEntity<DiabetesSugarTestDTO> getDiabetesSugarTest(@PathVariable String id) { log.debug("REST request to get DiabetesSugarTest : {}", id); DiabetesSugarTestDTO diabetesSugarTestDTO = diabetesSugarTestService.findOne(id); return ResponseUtil.wrapOrNotFound(Optional.ofNullable(diabetesSugarTestDTO)); } /** * DELETE /diabetes-sugar-tests/:id : delete the "id" diabetesSugarTest. * * @param id the id of the diabetesSugarTestDTO to delete * @return the ResponseEntity with status 200 (OK) */ @DeleteMapping("/diabetes-sugar-tests/{id}") @Timed public ResponseEntity<Void> deleteDiabetesSugarTest(@PathVariable String id) { log.debug("REST request to delete DiabetesSugarTest : {}", id); diabetesSugarTestService.delete(id); return ResponseEntity.ok().headers(HeaderUtil.createEntityDeletionAlert(ENTITY_NAME, id)).build(); } } <file_sep>/src/main/webapp/app/entities/diabetes-sugar-test/diabetes-sugar-test-info.component.ts import {Component, OnInit, OnDestroy} from '@angular/core'; import {ActivatedRoute} from '@angular/router'; import {NgbActiveModal} from '@ng-bootstrap/ng-bootstrap'; import {DiabetesSugarTestPopupService} from './diabetes-sugar-test-popup.service'; @Component({ selector: 'jhi-diabetes-sugar-test-info', templateUrl: './diabetes-sugar-test-info.component.html' }) export class DiabetesSugarTestInfoComponent implements OnInit { constructor( public activeModal: NgbActiveModal, ) { } ngOnInit() { } clear() { this.activeModal.dismiss('cancel'); } } @Component({ selector: 'jhi-diabetes-sugar-test-info-popup', template: '' }) export class DiabetesSugarTestInfoPopupComponent implements OnInit, OnDestroy { routeSub: any; constructor( private route: ActivatedRoute, private diabetesSugarTestPopupService: DiabetesSugarTestPopupService ) { } ngOnInit() { this.routeSub = this.route.params.subscribe(() => { this.diabetesSugarTestPopupService.open(DiabetesSugarTestInfoComponent as Component); }); } ngOnDestroy() { this.routeSub.unsubscribe(); } } <file_sep>/src/main/java/com/sirtts/service/mapper/VsBloodPressureMapper.java package com.sirtts.service.mapper; import com.sirtts.domain.*; import com.sirtts.service.dto.VsBloodPressureDTO; import org.mapstruct.*; /** * Mapper for the entity VsBloodPressure and its DTO VsBloodPressureDTO. */ @Mapper(componentModel = "spring", uses = {}) public interface VsBloodPressureMapper extends EntityMapper<VsBloodPressureDTO, VsBloodPressure> { } <file_sep>/src/main/webapp/app/entities/dentist-visit/dentist-visit.model.ts import { BaseEntity } from './../../shared'; export class DentistVisit implements BaseEntity { constructor( public id?: string, public userid?: string, public teethcleaning?: boolean, public whitening?: boolean, public restoration?: boolean, public crowns?: boolean, public bridges?: boolean, public braces?: boolean, public endodontictherapy?: boolean, public periodontaltherapy?: boolean, public extraction?: boolean, public oralsurgery?: boolean, public notes?: string, public measurmentdate?: any, ) { this.teethcleaning = false; this.whitening = false; this.restoration = false; this.crowns = false; this.bridges = false; this.braces = false; this.endodontictherapy = false; this.periodontaltherapy = false; this.extraction = false; this.oralsurgery = false; } } <file_sep>/src/test/java/com/sirtts/web/rest/VsSpo2ResourceIntTest.java package com.sirtts.web.rest; import com.sirtts.HcPortalApp; import com.sirtts.domain.VsSpo2; import com.sirtts.repository.VsSpo2Repository; import com.sirtts.service.VsSpo2Service; import com.sirtts.service.dto.VsSpo2DTO; import com.sirtts.service.mapper.VsSpo2Mapper; import com.sirtts.web.rest.errors.ExceptionTranslator; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.MockitoAnnotations; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.data.web.PageableHandlerMethodArgumentResolver; import org.springframework.http.MediaType; import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.setup.MockMvcBuilders; import java.time.ZoneOffset; import java.time.LocalDateTime; import java.util.List; import static com.sirtts.web.rest.TestUtil.createFormattingConversionService; import static org.assertj.core.api.Assertions.assertThat; import static org.hamcrest.Matchers.hasItem; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; /** * Test class for the VsSpo2Resource REST controller. * * @see VsSpo2Resource */ @RunWith(SpringRunner.class) @SpringBootTest(classes = HcPortalApp.class) public class VsSpo2ResourceIntTest { private static final String DEFAULT_USERID = "AAAAAAAAAA"; private static final String UPDATED_USERID = "BBBBBBBBBB"; private static final Double DEFAULT_PERCENT = 1D; private static final Double UPDATED_PERCENT = 2D; private static final LocalDateTime DEFAULT_MEASURMENTDATE = LocalDateTime.ofEpochSecond(1L,0,ZoneOffset.UTC); private static final LocalDateTime UPDATED_MEASURMENTDATE = LocalDateTime.ofEpochSecond(1L,0,ZoneOffset.UTC); @Autowired private VsSpo2Repository vsSpo2Repository; @Autowired private VsSpo2Mapper vsSpo2Mapper; @Autowired private VsSpo2Service vsSpo2Service; @Autowired private MappingJackson2HttpMessageConverter jacksonMessageConverter; @Autowired private PageableHandlerMethodArgumentResolver pageableArgumentResolver; @Autowired private ExceptionTranslator exceptionTranslator; private MockMvc restVsSpo2MockMvc; private VsSpo2 vsSpo2; @Before public void setup() { MockitoAnnotations.initMocks(this); final VsSpo2Resource vsSpo2Resource = new VsSpo2Resource(vsSpo2Service); this.restVsSpo2MockMvc = MockMvcBuilders.standaloneSetup(vsSpo2Resource) .setCustomArgumentResolvers(pageableArgumentResolver) .setControllerAdvice(exceptionTranslator) .setConversionService(createFormattingConversionService()) .setMessageConverters(jacksonMessageConverter).build(); } /** * Create an entity for this test. * * This is a static method, as tests for other entities might also need it, * if they test an entity which requires the current entity. */ public static VsSpo2 createEntity() { VsSpo2 vsSpo2 = new VsSpo2() .userid(DEFAULT_USERID) .percent(DEFAULT_PERCENT) .measurmentdate(DEFAULT_MEASURMENTDATE); return vsSpo2; } @Before public void initTest() { vsSpo2Repository.deleteAll(); vsSpo2 = createEntity(); } @Test public void createVsSpo2() throws Exception { int databaseSizeBeforeCreate = vsSpo2Repository.findAll().size(); // Create the VsSpo2 VsSpo2DTO vsSpo2DTO = vsSpo2Mapper.toDto(vsSpo2); restVsSpo2MockMvc.perform(post("/api/vs-spo-2-s") .contentType(TestUtil.APPLICATION_JSON_UTF8) .content(TestUtil.convertObjectToJsonBytes(vsSpo2DTO))) .andExpect(status().isCreated()); // Validate the VsSpo2 in the database List<VsSpo2> vsSpo2List = vsSpo2Repository.findAll(); assertThat(vsSpo2List).hasSize(databaseSizeBeforeCreate + 1); VsSpo2 testVsSpo2 = vsSpo2List.get(vsSpo2List.size() - 1); assertThat(testVsSpo2.getUserid()).isEqualTo(DEFAULT_USERID); assertThat(testVsSpo2.getPercent()).isEqualTo(DEFAULT_PERCENT); assertThat(testVsSpo2.getMeasurmentdate()).isEqualTo(DEFAULT_MEASURMENTDATE); } @Test public void createVsSpo2WithExistingId() throws Exception { int databaseSizeBeforeCreate = vsSpo2Repository.findAll().size(); // Create the VsSpo2 with an existing ID vsSpo2.setId("existing_id"); VsSpo2DTO vsSpo2DTO = vsSpo2Mapper.toDto(vsSpo2); // An entity with an existing ID cannot be created, so this API call must fail restVsSpo2MockMvc.perform(post("/api/vs-spo-2-s") .contentType(TestUtil.APPLICATION_JSON_UTF8) .content(TestUtil.convertObjectToJsonBytes(vsSpo2DTO))) .andExpect(status().isBadRequest()); // Validate the VsSpo2 in the database List<VsSpo2> vsSpo2List = vsSpo2Repository.findAll(); assertThat(vsSpo2List).hasSize(databaseSizeBeforeCreate); } @Test public void checkPercentIsRequired() throws Exception { int databaseSizeBeforeTest = vsSpo2Repository.findAll().size(); // set the field null vsSpo2.setPercent(null); // Create the VsSpo2, which fails. VsSpo2DTO vsSpo2DTO = vsSpo2Mapper.toDto(vsSpo2); restVsSpo2MockMvc.perform(post("/api/vs-spo-2-s") .contentType(TestUtil.APPLICATION_JSON_UTF8) .content(TestUtil.convertObjectToJsonBytes(vsSpo2DTO))) .andExpect(status().isBadRequest()); List<VsSpo2> vsSpo2List = vsSpo2Repository.findAll(); assertThat(vsSpo2List).hasSize(databaseSizeBeforeTest); } @Test public void checkMeasurmentdateIsRequired() throws Exception { int databaseSizeBeforeTest = vsSpo2Repository.findAll().size(); // set the field null vsSpo2.setMeasurmentdate(null); // Create the VsSpo2, which fails. VsSpo2DTO vsSpo2DTO = vsSpo2Mapper.toDto(vsSpo2); restVsSpo2MockMvc.perform(post("/api/vs-spo-2-s") .contentType(TestUtil.APPLICATION_JSON_UTF8) .content(TestUtil.convertObjectToJsonBytes(vsSpo2DTO))) .andExpect(status().isBadRequest()); List<VsSpo2> vsSpo2List = vsSpo2Repository.findAll(); assertThat(vsSpo2List).hasSize(databaseSizeBeforeTest); } @Test public void getAllVsSpo2S() throws Exception { // Initialize the database vsSpo2Repository.save(vsSpo2); // Get all the vsSpo2List restVsSpo2MockMvc.perform(get("/api/vs-spo-2-s?sort=id,desc")) .andExpect(status().isOk()) .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE)) .andExpect(jsonPath("$.[*].id").value(hasItem(vsSpo2.getId()))) .andExpect(jsonPath("$.[*].userid").value(hasItem(DEFAULT_USERID.toString()))) .andExpect(jsonPath("$.[*].percent").value(hasItem(DEFAULT_PERCENT.doubleValue()))) .andExpect(jsonPath("$.[*].measurmentdate").value(hasItem(DEFAULT_MEASURMENTDATE.toString()))); } @Test public void getVsSpo2() throws Exception { // Initialize the database vsSpo2Repository.save(vsSpo2); // Get the vsSpo2 restVsSpo2MockMvc.perform(get("/api/vs-spo-2-s/{id}", vsSpo2.getId())) .andExpect(status().isOk()) .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE)) .andExpect(jsonPath("$.id").value(vsSpo2.getId())) .andExpect(jsonPath("$.userid").value(DEFAULT_USERID.toString())) .andExpect(jsonPath("$.percent").value(DEFAULT_PERCENT.doubleValue())) .andExpect(jsonPath("$.measurmentdate").value(DEFAULT_MEASURMENTDATE.toString())); } @Test public void getNonExistingVsSpo2() throws Exception { // Get the vsSpo2 restVsSpo2MockMvc.perform(get("/api/vs-spo-2-s/{id}", Long.MAX_VALUE)) .andExpect(status().isNotFound()); } @Test public void updateVsSpo2() throws Exception { // Initialize the database vsSpo2Repository.save(vsSpo2); int databaseSizeBeforeUpdate = vsSpo2Repository.findAll().size(); // Update the vsSpo2 VsSpo2 updatedVsSpo2 = vsSpo2Repository.findOne(vsSpo2.getId()); updatedVsSpo2 .userid(UPDATED_USERID) .percent(UPDATED_PERCENT) .measurmentdate(UPDATED_MEASURMENTDATE); VsSpo2DTO vsSpo2DTO = vsSpo2Mapper.toDto(updatedVsSpo2); restVsSpo2MockMvc.perform(put("/api/vs-spo-2-s") .contentType(TestUtil.APPLICATION_JSON_UTF8) .content(TestUtil.convertObjectToJsonBytes(vsSpo2DTO))) .andExpect(status().isOk()); // Validate the VsSpo2 in the database List<VsSpo2> vsSpo2List = vsSpo2Repository.findAll(); assertThat(vsSpo2List).hasSize(databaseSizeBeforeUpdate); VsSpo2 testVsSpo2 = vsSpo2List.get(vsSpo2List.size() - 1); assertThat(testVsSpo2.getUserid()).isEqualTo(UPDATED_USERID); assertThat(testVsSpo2.getPercent()).isEqualTo(UPDATED_PERCENT); assertThat(testVsSpo2.getMeasurmentdate()).isEqualTo(UPDATED_MEASURMENTDATE); } @Test public void updateNonExistingVsSpo2() throws Exception { int databaseSizeBeforeUpdate = vsSpo2Repository.findAll().size(); // Create the VsSpo2 VsSpo2DTO vsSpo2DTO = vsSpo2Mapper.toDto(vsSpo2); // If the entity doesn't have an ID, it will be created instead of just being updated restVsSpo2MockMvc.perform(put("/api/vs-spo-2-s") .contentType(TestUtil.APPLICATION_JSON_UTF8) .content(TestUtil.convertObjectToJsonBytes(vsSpo2DTO))) .andExpect(status().isCreated()); // Validate the VsSpo2 in the database List<VsSpo2> vsSpo2List = vsSpo2Repository.findAll(); assertThat(vsSpo2List).hasSize(databaseSizeBeforeUpdate + 1); } @Test public void deleteVsSpo2() throws Exception { // Initialize the database vsSpo2Repository.save(vsSpo2); int databaseSizeBeforeDelete = vsSpo2Repository.findAll().size(); // Get the vsSpo2 restVsSpo2MockMvc.perform(delete("/api/vs-spo-2-s/{id}", vsSpo2.getId()) .accept(TestUtil.APPLICATION_JSON_UTF8)) .andExpect(status().isOk()); // Validate the database is empty List<VsSpo2> vsSpo2List = vsSpo2Repository.findAll(); assertThat(vsSpo2List).hasSize(databaseSizeBeforeDelete - 1); } @Test public void equalsVerifier() throws Exception { TestUtil.equalsVerifier(VsSpo2.class); VsSpo2 vsSpo21 = new VsSpo2(); vsSpo21.setId("id1"); VsSpo2 vsSpo22 = new VsSpo2(); vsSpo22.setId(vsSpo21.getId()); assertThat(vsSpo21).isEqualTo(vsSpo22); vsSpo22.setId("id2"); assertThat(vsSpo21).isNotEqualTo(vsSpo22); vsSpo21.setId(null); assertThat(vsSpo21).isNotEqualTo(vsSpo22); } @Test public void dtoEqualsVerifier() throws Exception { TestUtil.equalsVerifier(VsSpo2DTO.class); VsSpo2DTO vsSpo2DTO1 = new VsSpo2DTO(); vsSpo2DTO1.setId("id1"); VsSpo2DTO vsSpo2DTO2 = new VsSpo2DTO(); assertThat(vsSpo2DTO1).isNotEqualTo(vsSpo2DTO2); vsSpo2DTO2.setId(vsSpo2DTO1.getId()); assertThat(vsSpo2DTO1).isEqualTo(vsSpo2DTO2); vsSpo2DTO2.setId("id2"); assertThat(vsSpo2DTO1).isNotEqualTo(vsSpo2DTO2); vsSpo2DTO1.setId(null); assertThat(vsSpo2DTO1).isNotEqualTo(vsSpo2DTO2); } } <file_sep>/src/test/javascript/spec/app/entities/vs-spo-2/vs-spo-2-detail.component.spec.ts /* tslint:disable max-line-length */ import { ComponentFixture, TestBed, async } from '@angular/core/testing'; import { HttpResponse } from '@angular/common/http'; import { Observable } from 'rxjs/Observable'; import { HcPortalTestModule } from '../../../test.module'; import { VsSpo2DetailComponent } from '../../../../../../main/webapp/app/entities/vs-spo-2/vs-spo-2-detail.component'; import { VsSpo2Service } from '../../../../../../main/webapp/app/entities/vs-spo-2/vs-spo-2.service'; import { VsSpo2 } from '../../../../../../main/webapp/app/entities/vs-spo-2/vs-spo-2.model'; describe('Component Tests', () => { describe('VsSpo2 Management Detail Component', () => { let comp: VsSpo2DetailComponent; let fixture: ComponentFixture<VsSpo2DetailComponent>; let service: VsSpo2Service; beforeEach(async(() => { TestBed.configureTestingModule({ imports: [HcPortalTestModule], declarations: [VsSpo2DetailComponent], providers: [ VsSpo2Service ] }) .overrideTemplate(VsSpo2DetailComponent, '') .compileComponents(); })); beforeEach(() => { fixture = TestBed.createComponent(VsSpo2DetailComponent); comp = fixture.componentInstance; service = fixture.debugElement.injector.get(VsSpo2Service); }); describe('OnInit', () => { it('Should call load all on init', () => { // GIVEN spyOn(service, 'find').and.returnValue(Observable.of(new HttpResponse({ body: new VsSpo2('123') }))); // WHEN comp.ngOnInit(); // THEN expect(service.find).toHaveBeenCalledWith('123'); expect(comp.vsSpo2).toEqual(jasmine.objectContaining({id: '123'})); }); }); }); }); <file_sep>/src/main/webapp/app/entities/vs-blood-pressure/vs-blood-pressure-delete-dialog.component.ts import { Component, OnInit, OnDestroy } from '@angular/core'; import { ActivatedRoute } from '@angular/router'; import { NgbActiveModal } from '@ng-bootstrap/ng-bootstrap'; import { JhiEventManager } from 'ng-jhipster'; import { VsBloodPressure } from './vs-blood-pressure.model'; import { VsBloodPressurePopupService } from './vs-blood-pressure-popup.service'; import { VsBloodPressureService } from './vs-blood-pressure.service'; @Component({ selector: 'jhi-vs-blood-pressure-delete-dialog', templateUrl: './vs-blood-pressure-delete-dialog.component.html' }) export class VsBloodPressureDeleteDialogComponent { vsBloodPressure: VsBloodPressure; constructor( private vsBloodPressureService: VsBloodPressureService, public activeModal: NgbActiveModal, private eventManager: JhiEventManager ) { } clear() { this.activeModal.dismiss('cancel'); } confirmDelete(id: string) { this.vsBloodPressureService.delete(id).subscribe((response) => { this.eventManager.broadcast({ name: 'vsBloodPressureListModification', content: 'Deleted an vsBloodPressure' }); this.activeModal.dismiss(true); }); } } @Component({ selector: 'jhi-vs-blood-pressure-delete-popup', template: '' }) export class VsBloodPressureDeletePopupComponent implements OnInit, OnDestroy { routeSub: any; constructor( private route: ActivatedRoute, private vsBloodPressurePopupService: VsBloodPressurePopupService ) {} ngOnInit() { this.routeSub = this.route.params.subscribe((params) => { this.vsBloodPressurePopupService .open(VsBloodPressureDeleteDialogComponent as Component, params['id']); }); } ngOnDestroy() { this.routeSub.unsubscribe(); } } <file_sep>/src/main/webapp/app/entities/blood-test/blood-test.route.ts import {Injectable} from '@angular/core'; import {Resolve, ActivatedRouteSnapshot, RouterStateSnapshot, Routes} from '@angular/router'; import {JhiPaginationUtil} from 'ng-jhipster'; import {UserRouteAccessService} from '../../shared'; import {BloodTestComponent} from './blood-test.component'; import {BloodTestDetailComponent} from './blood-test-detail.component'; import {BloodTestPopupComponent} from './blood-test-dialog.component'; import {BloodTestDeletePopupComponent} from './blood-test-delete-dialog.component'; import {BloodTestInfoPopupComponent} from './blood-test-info.component'; @Injectable() export class BloodTestResolvePagingParams implements Resolve<any> { constructor(private paginationUtil: JhiPaginationUtil) { } resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) { const page = route.queryParams['page'] ? route.queryParams['page'] : '1'; const sort = route.queryParams['sort'] ? route.queryParams['sort'] : 'id,asc'; return { page: this.paginationUtil.parsePage(page), predicate: this.paginationUtil.parsePredicate(sort), ascending: this.paginationUtil.parseAscending(sort) }; } } export const bloodTestRoute: Routes = [ { path: 'blood-test', component: BloodTestComponent, resolve: { 'pagingParams': BloodTestResolvePagingParams }, data: { authorities: ['ROLE_USER'], pageTitle: 'hcPortalApp.bloodTest.home.title' }, canActivate: [UserRouteAccessService] }, { path: 'blood-test/:id', component: BloodTestDetailComponent, data: { authorities: ['ROLE_USER'], pageTitle: 'hcPortalApp.bloodTest.home.title' }, canActivate: [UserRouteAccessService] }, { path: 'blood-test/patient/blood-test/:id', component: BloodTestDetailComponent, data: { authorities: ['ROLE_DOCTOR'], pageTitle: 'hcPortalApp.bloodTest.home.title' }, canActivate: [UserRouteAccessService] }, { path: 'blood-test/patient/:login', component: BloodTestComponent, resolve: { 'pagingParams': BloodTestResolvePagingParams }, data: { authorities: ['ROLE_DOCTOR'], pageTitle: 'hcPortalApp.bloodTest.home.title' }, canActivate: [UserRouteAccessService] } ]; export const bloodTestPopupRoute: Routes = [ { path: 'blood-test-new', component: BloodTestPopupComponent, data: { authorities: ['ROLE_USER'], pageTitle: 'hcPortalApp.bloodTest.home.title' }, canActivate: [UserRouteAccessService], outlet: 'popup' }, { path: 'blood-test/:id/edit', component: BloodTestPopupComponent, data: { authorities: ['ROLE_USER'], pageTitle: 'hcPortalApp.bloodTest.home.title' }, canActivate: [UserRouteAccessService], outlet: 'popup' }, { path: 'blood-test/:id/delete', component: BloodTestDeletePopupComponent, data: { authorities: ['ROLE_USER'], pageTitle: 'hcPortalApp.bloodTest.home.title' }, canActivate: [UserRouteAccessService], outlet: 'popup' }, { path: 'blood-test-info', component: BloodTestInfoPopupComponent, data: { authorities: ['ROLE_USER'], pageTitle: 'hcPortalApp.bloodTest.home.title' }, canActivate: [UserRouteAccessService], outlet: 'popup' } ]; <file_sep>/src/main/webapp/app/entities/vs-spo-2/vs-spo-2.model.ts import { BaseEntity } from './../../shared'; export class VsSpo2 implements BaseEntity { constructor( public id?: string, public userid?: string, public percent?: number, public measurmentdate?: any, ) { } } <file_sep>/src/main/webapp/app/app.module.ts import './vendor.ts'; import {NgModule, Injector} from '@angular/core'; import {BrowserModule} from '@angular/platform-browser'; import {HTTP_INTERCEPTORS} from '@angular/common/http'; import {Ng2Webstorage, LocalStorageService, SessionStorageService} from 'ngx-webstorage'; import {JhiEventManager} from 'ng-jhipster'; import {AuthInterceptor} from './blocks/interceptor/auth.interceptor'; import {AuthExpiredInterceptor} from './blocks/interceptor/auth-expired.interceptor'; import {ErrorHandlerInterceptor} from './blocks/interceptor/errorhandler.interceptor'; import {NotificationInterceptor} from './blocks/interceptor/notification.interceptor'; import {HcPortalSharedModule, UserRouteAccessService} from './shared'; import {HcPortalAppRoutingModule} from './app-routing.module'; import {HcPortalHomeModule} from './home/home.module'; import {HcPortalAdminModule} from './admin/admin.module'; import {HcPortalAccountModule} from './account/account.module'; import {HcPortalEntityModule} from './entities/entity.module'; import {PaginationConfig} from './blocks/config/uib-pagination.config'; import {NgbActiveModal} from '@ng-bootstrap/ng-bootstrap'; import {ChartsModule} from 'ng2-charts'; // jhipster-needle-angular-add-module-import JHipster will add new module here import { JhiMainComponent, NavbarComponent, FooterComponent, ProfileService, PageRibbonComponent, ActiveMenuDirective, ErrorComponent } from './layouts'; @NgModule({ imports: [ BrowserModule, HcPortalAppRoutingModule, Ng2Webstorage.forRoot({prefix: 'jhi', separator: '-'}), HcPortalSharedModule, HcPortalHomeModule, HcPortalAdminModule, HcPortalAccountModule, HcPortalEntityModule, ChartsModule // jhipster-needle-angular-add-module JHipster will add new module here ], declarations: [ JhiMainComponent, NavbarComponent, ErrorComponent, PageRibbonComponent, ActiveMenuDirective, FooterComponent ], providers: [ ProfileService, PaginationConfig, UserRouteAccessService, NgbActiveModal, { provide: HTTP_INTERCEPTORS, useClass: AuthInterceptor, multi: true, deps: [ LocalStorageService, SessionStorageService ] }, { provide: HTTP_INTERCEPTORS, useClass: AuthExpiredInterceptor, multi: true, deps: [ Injector ] }, { provide: HTTP_INTERCEPTORS, useClass: ErrorHandlerInterceptor, multi: true, deps: [ JhiEventManager ] }, { provide: HTTP_INTERCEPTORS, useClass: NotificationInterceptor, multi: true, deps: [ Injector ] } ], bootstrap: [JhiMainComponent] }) export class HcPortalAppModule { } <file_sep>/src/main/webapp/app/entities/diabetes-sugar-test/diabetes-sugar-test.route.ts import {Injectable} from '@angular/core'; import {Resolve, ActivatedRouteSnapshot, RouterStateSnapshot, Routes} from '@angular/router'; import {JhiPaginationUtil} from 'ng-jhipster'; import {UserRouteAccessService} from '../../shared'; import {DiabetesSugarTestComponent} from './diabetes-sugar-test.component'; import {DiabetesSugarTestDetailComponent} from './diabetes-sugar-test-detail.component'; import {DiabetesSugarTestPopupComponent} from './diabetes-sugar-test-dialog.component'; import {DiabetesSugarTestDeletePopupComponent} from './diabetes-sugar-test-delete-dialog.component'; import {DiabetesSugarTestInfoPopupComponent} from './diabetes-sugar-test-info.component'; @Injectable() export class DiabetesSugarTestResolvePagingParams implements Resolve<any> { constructor(private paginationUtil: JhiPaginationUtil) { } resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) { const page = route.queryParams['page'] ? route.queryParams['page'] : '1'; const sort = route.queryParams['sort'] ? route.queryParams['sort'] : 'id,asc'; return { page: this.paginationUtil.parsePage(page), predicate: this.paginationUtil.parsePredicate(sort), ascending: this.paginationUtil.parseAscending(sort) }; } } export const diabetesSugarTestRoute: Routes = [ { path: 'diabetes-sugar-test', component: DiabetesSugarTestComponent, resolve: { 'pagingParams': DiabetesSugarTestResolvePagingParams }, data: { authorities: ['ROLE_USER'], pageTitle: 'hcPortalApp.diabetesSugarTest.home.title' }, canActivate: [UserRouteAccessService] }, { path: 'diabetes-sugar-test/:id', component: DiabetesSugarTestDetailComponent, data: { authorities: ['ROLE_USER'], pageTitle: 'hcPortalApp.diabetesSugarTest.home.title' }, canActivate: [UserRouteAccessService] }, { path: 'diabetes-sugar-test/patient/diabetes-sugar-test/:id', component: DiabetesSugarTestDetailComponent, data: { authorities: ['ROLE_DOCTOR'], pageTitle: 'hcPortalApp.diabetesSugarTest.home.title' }, canActivate: [UserRouteAccessService] }, { path: 'diabetes-sugar-test/patient/:login', component: DiabetesSugarTestComponent, resolve: { 'pagingParams': DiabetesSugarTestResolvePagingParams }, data: { authorities: ['ROLE_DOCTOR'], pageTitle: 'hcPortalApp.diabetesSugarTest.home.title' }, canActivate: [UserRouteAccessService] } ]; export const diabetesSugarTestPopupRoute: Routes = [ { path: 'diabetes-sugar-test-new', component: DiabetesSugarTestPopupComponent, data: { authorities: ['ROLE_USER'], pageTitle: 'hcPortalApp.diabetesSugarTest.home.title' }, canActivate: [UserRouteAccessService], outlet: 'popup' }, { path: 'diabetes-sugar-test/:id/edit', component: DiabetesSugarTestPopupComponent, data: { authorities: ['ROLE_USER'], pageTitle: 'hcPortalApp.diabetesSugarTest.home.title' }, canActivate: [UserRouteAccessService], outlet: 'popup' }, { path: 'diabetes-sugar-test/:id/delete', component: DiabetesSugarTestDeletePopupComponent, data: { authorities: ['ROLE_USER'], pageTitle: 'hcPortalApp.diabetesSugarTest.home.title' }, canActivate: [UserRouteAccessService], outlet: 'popup' }, { path: 'diabetes-sugar-test-info', component: DiabetesSugarTestInfoPopupComponent, data: { authorities: ['ROLE_USER'], pageTitle: 'hcPortalApp.diabetesSugarTest.home.title' }, canActivate: [UserRouteAccessService], outlet: 'popup' } ]; <file_sep>/src/main/java/com/sirtts/service/mapper/MenstrualCycleMapper.java package com.sirtts.service.mapper; import com.sirtts.domain.*; import com.sirtts.service.dto.MenstrualCycleDTO; import org.mapstruct.*; /** * Mapper for the entity MenstrualCycle and its DTO MenstrualCycleDTO. */ @Mapper(componentModel = "spring", uses = {}) public interface MenstrualCycleMapper extends EntityMapper<MenstrualCycleDTO, MenstrualCycle> { } <file_sep>/src/main/webapp/app/entities/blood-test/blood-test.model.ts import { BaseEntity } from './../../shared'; export class BloodTest implements BaseEntity { constructor( public id?: string, public userid?: string, public hydroxyprogesterone17?: number, public hydroxyvitaminD25?: number, public acetoacetate?: number, public acidity?: number, public alcohol?: number, public ammonia?: number, public amylase?: number, public ascorbicAcid?: number, public bicarbonate?: number, public bilirubin?: number, public bloodVolume?: number, public calcium?: number, public carbonDioxidePressure?: number, public carbonMonoxide?: number, public cD4CellCount?: number, public ceruloplasmin?: number, public chloride?: number, public completeBloodCellCount?: number, public copper?: number, public creatineKinase?: number, public creatineKinaseIsoenzymes?: number, public creatinine?: number, public electrolytes?: number, public erythrocyteSedimentationRate?: number, public glucose?: number, public hematocrit?: number, public hemoglobin?: number, public iron?: number, public ironBindingCapacity?: number, public lactate?: number, public lacticDehydrogenase?: number, public lead?: number, public lipase?: number, public zinc?: number, public lipidsCholesterol?: number, public lipidsTriglycerides?: number, public magnesium?: number, public meanCorpuscularHemoglobin?: number, public meanCorpuscularHemoglobinConcentration?: number, public meanCorpuscularVolume?: number, public osmolality?: number, public oxygenPressure?: number, public oxygenSaturation?: number, public phosphataseProstatic?: number, public phosphatase?: number, public phosphorus?: number, public plateletCount?: number, public potassium?: number, public prostateSpecificAntigen?: number, public proteinsTotal?: number, public proteinsAlbumin?: number, public proteinsGlobulin?: number, public prothrombin?: number, public pyruvicAcid?: number, public redBloodCellCount?: number, public sodium?: number, public thyroidStimulatingHormone?: number, public transaminaseAlanine?: number, public transaminaseAspartate?: number, public ureaNitrogen?: number, public bUNCreatinineRatio?: number, public uricAcid?: number, public vitaminA?: number, public wBC?: number, public whiteBloodCellCount?: number, public measurmentdate?: any, ) { } } <file_sep>/src/main/webapp/app/entities/vs-heart-rate/vs-heart-rate.module.ts import {NgModule, CUSTOM_ELEMENTS_SCHEMA} from '@angular/core'; import {RouterModule} from '@angular/router'; import {ChartsModule} from 'ng2-charts'; import {HcPortalSharedModule} from '../../shared'; import { VsHeartRateService, VsHeartRatePopupService, VsHeartRateComponent, VsHeartRateDetailComponent, VsHeartRateDialogComponent, VsHeartRatePopupComponent, VsHeartRateDeletePopupComponent, VsHeartRateDeleteDialogComponent, vsHeartRateRoute, vsHeartRatePopupRoute, VsHeartRateResolvePagingParams, VsHeartRateInfoComponent, VsHeartRateInfoPopupComponent, } from './'; const ENTITY_STATES = [ ...vsHeartRateRoute, ...vsHeartRatePopupRoute, ]; @NgModule({ imports: [ HcPortalSharedModule, ChartsModule, RouterModule.forChild(ENTITY_STATES) ], declarations: [ VsHeartRateComponent, VsHeartRateDetailComponent, VsHeartRateDialogComponent, VsHeartRateDeleteDialogComponent, VsHeartRatePopupComponent, VsHeartRateDeletePopupComponent, VsHeartRateInfoComponent, VsHeartRateInfoPopupComponent, ], entryComponents: [ VsHeartRateComponent, VsHeartRateDialogComponent, VsHeartRatePopupComponent, VsHeartRateDeleteDialogComponent, VsHeartRateDeletePopupComponent, VsHeartRateInfoComponent, VsHeartRateInfoPopupComponent, ], providers: [ VsHeartRateService, VsHeartRatePopupService, VsHeartRateResolvePagingParams, ], schemas: [CUSTOM_ELEMENTS_SCHEMA] }) export class HcPortalVsHeartRateModule { } <file_sep>/src/main/webapp/app/entities/pt-doctors/index.ts export * from './pt-doctors.model'; export * from './pt-doctors-popup.service'; export * from './pt-doctors.service'; export * from './pt-doctors.component'; export * from './pt-doctors.route'; export * from './pt-doctors-info.component'; <file_sep>/src/main/webapp/app/entities/vs-spo-2/vs-spo-2.route.ts import {Injectable} from '@angular/core'; import {Resolve, ActivatedRouteSnapshot, RouterStateSnapshot, Routes} from '@angular/router'; import {JhiPaginationUtil} from 'ng-jhipster'; import {UserRouteAccessService} from '../../shared'; import {VsSpo2Component} from './vs-spo-2.component'; import {VsSpo2DetailComponent} from './vs-spo-2-detail.component'; import {VsSpo2PopupComponent} from './vs-spo-2-dialog.component'; import {VsSpo2DeletePopupComponent} from './vs-spo-2-delete-dialog.component'; import {VsSpo2InfoPopupComponent} from './vs-spo-2-info.component'; @Injectable() export class VsSpo2ResolvePagingParams implements Resolve<any> { constructor(private paginationUtil: JhiPaginationUtil) { } resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) { const page = route.queryParams['page'] ? route.queryParams['page'] : '1'; const sort = route.queryParams['sort'] ? route.queryParams['sort'] : 'id,asc'; return { page: this.paginationUtil.parsePage(page), predicate: this.paginationUtil.parsePredicate(sort), ascending: this.paginationUtil.parseAscending(sort) }; } } export const vsSpo2Route: Routes = [ { path: 'vs-spo-2', component: VsSpo2Component, resolve: { 'pagingParams': VsSpo2ResolvePagingParams }, data: { authorities: ['ROLE_USER'], pageTitle: 'hcPortalApp.vsSpo2.home.title' }, canActivate: [UserRouteAccessService] }, { path: 'vs-spo-2/:id', component: VsSpo2DetailComponent, data: { authorities: ['ROLE_USER'], pageTitle: 'hcPortalApp.vsSpo2.home.title' }, canActivate: [UserRouteAccessService] }, { path: 'vs-spo-2/patient/vs-spo-2/:id', component: VsSpo2DetailComponent, data: { authorities: ['ROLE_DOCTOR'], pageTitle: 'hcPortalApp.vsSpo2.home.title' }, canActivate: [UserRouteAccessService] }, { path: 'vs-spo-2/patient/:login', component: VsSpo2Component, resolve: { 'pagingParams': VsSpo2ResolvePagingParams }, data: { authorities: ['ROLE_DOCTOR'], pageTitle: 'hcPortalApp.vsSpo2.home.title' }, canActivate: [UserRouteAccessService] } ]; export const vsSpo2PopupRoute: Routes = [ { path: 'vs-spo-2-new', component: VsSpo2PopupComponent, data: { authorities: ['ROLE_USER'], pageTitle: 'hcPortalApp.vsSpo2.home.title' }, canActivate: [UserRouteAccessService], outlet: 'popup' }, { path: 'vs-spo-2/:id/edit', component: VsSpo2PopupComponent, data: { authorities: ['ROLE_USER'], pageTitle: 'hcPortalApp.vsSpo2.home.title' }, canActivate: [UserRouteAccessService], outlet: 'popup' }, { path: 'vs-spo-2/:id/delete', component: VsSpo2DeletePopupComponent, data: { authorities: ['ROLE_USER'], pageTitle: 'hcPortalApp.vsSpo2.home.title' }, canActivate: [UserRouteAccessService], outlet: 'popup' }, { path: 'vs-spo-2-info', component: VsSpo2InfoPopupComponent, data: { authorities: ['ROLE_USER'], pageTitle: 'hcPortalApp.vsSpo2.home.title' }, canActivate: [UserRouteAccessService], outlet: 'popup' } ]; <file_sep>/src/main/webapp/app/entities/dr-patients/dr-patients-info.component.ts import {Component, OnInit, OnDestroy} from '@angular/core'; import {ActivatedRoute} from '@angular/router'; import {NgbActiveModal} from '@ng-bootstrap/ng-bootstrap'; import {DrPatientsPopupService} from './dr-patients-popup.service'; @Component({ selector: 'jhi-dr-patients-info', templateUrl: './dr-patients-info.component.html' }) export class DrPatientsInfoComponent implements OnInit { constructor( public activeModal: NgbActiveModal, ) { } ngOnInit() { } clear() { this.activeModal.dismiss('cancel'); } } @Component({ selector: 'jhi-dr-patients-info-popup', template: '' }) export class DrPatientsInfoPopupComponent implements OnInit, OnDestroy { routeSub: any; constructor( private route: ActivatedRoute, private drPatientsPopupService: DrPatientsPopupService ) { } ngOnInit() { this.routeSub = this.route.params.subscribe(() => { this.drPatientsPopupService.open(DrPatientsInfoComponent as Component); }); } ngOnDestroy() { this.routeSub.unsubscribe(); } } <file_sep>/src/main/webapp/app/entities/vs-heart-rate/index.ts export * from './vs-heart-rate.model'; export * from './vs-heart-rate-popup.service'; export * from './vs-heart-rate.service'; export * from './vs-heart-rate-dialog.component'; export * from './vs-heart-rate-delete-dialog.component'; export * from './vs-heart-rate-detail.component'; export * from './vs-heart-rate.component'; export * from './vs-heart-rate.route'; export * from './vs-heart-rate-info.component'; <file_sep>/src/main/webapp/app/entities/pt-doctors/pt-doctors.module.ts import {NgModule, CUSTOM_ELEMENTS_SCHEMA} from '@angular/core'; import {RouterModule} from '@angular/router'; import {HcPortalSharedModule} from '../../shared'; import { PtDoctorsService, PtDoctorsPopupService, PtDoctorsComponent, PtDoctorsRoute, PtDoctorsPopupRoute, PtDoctorsResolvePagingParams, PtDoctorsInfoComponent, PtDoctorsInfoPopupComponent } from './'; const ENTITY_STATES = [ ...PtDoctorsRoute, ...PtDoctorsPopupRoute, ]; @NgModule({ imports: [ HcPortalSharedModule, RouterModule.forChild(ENTITY_STATES) ], declarations: [ PtDoctorsComponent, PtDoctorsInfoComponent, PtDoctorsInfoPopupComponent, ], entryComponents: [ PtDoctorsComponent, PtDoctorsInfoComponent, PtDoctorsInfoPopupComponent, ], providers: [ PtDoctorsService, PtDoctorsPopupService, PtDoctorsResolvePagingParams, ], schemas: [CUSTOM_ELEMENTS_SCHEMA] }) export class HcPortalPtDoctorsModule { } <file_sep>/src/main/webapp/app/entities/dr-patients/dr-patients-dialog.component.ts import { Component, OnInit, OnDestroy, Input } from '@angular/core'; import { ActivatedRoute } from '@angular/router'; import { HttpResponse, HttpErrorResponse } from '@angular/common/http'; import { Observable } from 'rxjs/Observable'; import { NgbActiveModal } from '@ng-bootstrap/ng-bootstrap'; import { JhiEventManager } from 'ng-jhipster'; import { DrPatients } from './dr-patients.model'; import { DrPatientsPopupService } from './dr-patients-popup.service'; import { DrPatientsService } from './dr-patients.service'; import { Principal } from '../../shared'; @Component({ selector: 'jhi-dr-patients-dialog', templateUrl: './dr-patients-dialog.component.html' }) export class DrPatientsDialogComponent implements OnInit { drPatients: DrPatients; isSaving: boolean; @Input() email: string; constructor( public activeModal: NgbActiveModal, private drPatientsService: DrPatientsService, private principal: Principal, private eventManager: JhiEventManager ) { } ngOnInit() { this.isSaving = false; } clear() { this.activeModal.dismiss('cancel'); } save() { this.isSaving = true; this.subscribeToSaveResponse(this.drPatientsService.add(this.principal.getId(), this.email)); } private subscribeToSaveResponse(result: Observable<HttpResponse<DrPatients>>) { result.subscribe((res: HttpResponse<DrPatients>) => this.onSaveSuccess(res.body), (res: HttpErrorResponse) => this.onSaveError()); } private onSaveSuccess(result: DrPatients) { this.eventManager.broadcast({ name: 'DrPatientsListModification', content: 'OK' }); this.isSaving = false; this.activeModal.dismiss(result); } private onSaveError() { this.isSaving = false; } } @Component({ selector: 'jhi-dr-patients-popup', template: '' }) export class DrPatientsPopupComponent implements OnInit, OnDestroy { routeSub: any; constructor( private route: ActivatedRoute, private drPatientsPopupService: DrPatientsPopupService ) { } ngOnInit() { this.routeSub = this.route.params.subscribe((params) => { if (params['id']) { this.drPatientsPopupService .open(DrPatientsDialogComponent as Component, params['id']); } else { this.drPatientsPopupService .open(DrPatientsDialogComponent as Component); } }); } ngOnDestroy() { this.routeSub.unsubscribe(); } } <file_sep>/src/main/java/com/sirtts/security/AuthoritiesConstants.java package com.sirtts.security; /** * Constants for Spring Security authorities. */ public final class AuthoritiesConstants { public static final String ADMIN = "ROLE_ADMIN"; public static final String USER = "ROLE_USER"; public static final String ANONYMOUS = "ROLE_ANONYMOUS"; public static final String DOCTOR = "ROLE_DOCTOR"; public static final String MALE = "ROLE_MALE"; public static final String FEMALE = "ROLE_FEMALE"; private AuthoritiesConstants() { } } <file_sep>/src/main/webapp/app/entities/vs-body-temperature/vs-body-temperature-detail.component.ts import { Component, OnInit, OnDestroy } from '@angular/core'; import { ActivatedRoute } from '@angular/router'; import { HttpResponse } from '@angular/common/http'; import { Subscription } from 'rxjs/Subscription'; import { JhiEventManager } from 'ng-jhipster'; import { VsBodyTemperature } from './vs-body-temperature.model'; import { VsBodyTemperatureService } from './vs-body-temperature.service'; @Component({ selector: 'jhi-vs-body-temperature-detail', templateUrl: './vs-body-temperature-detail.component.html' }) export class VsBodyTemperatureDetailComponent implements OnInit, OnDestroy { vsBodyTemperature: VsBodyTemperature; private subscription: Subscription; private eventSubscriber: Subscription; constructor( private eventManager: JhiEventManager, private vsBodyTemperatureService: VsBodyTemperatureService, private route: ActivatedRoute ) { } ngOnInit() { this.subscription = this.route.params.subscribe((params) => { this.load(params['id']); }); this.registerChangeInVsBodyTemperatures(); } load(id) { this.vsBodyTemperatureService.find(id) .subscribe((vsBodyTemperatureResponse: HttpResponse<VsBodyTemperature>) => { this.vsBodyTemperature = vsBodyTemperatureResponse.body; }); } previousState() { window.history.back(); } ngOnDestroy() { this.subscription.unsubscribe(); this.eventManager.destroy(this.eventSubscriber); } registerChangeInVsBodyTemperatures() { this.eventSubscriber = this.eventManager.subscribe( 'vsBodyTemperatureListModification', (response) => this.load(this.vsBodyTemperature.id) ); } } <file_sep>/src/main/webapp/app/entities/vs-spo-2/vs-spo-2-delete-dialog.component.ts import { Component, OnInit, OnDestroy } from '@angular/core'; import { ActivatedRoute } from '@angular/router'; import { NgbActiveModal } from '@ng-bootstrap/ng-bootstrap'; import { JhiEventManager } from 'ng-jhipster'; import { VsSpo2 } from './vs-spo-2.model'; import { VsSpo2PopupService } from './vs-spo-2-popup.service'; import { VsSpo2Service } from './vs-spo-2.service'; @Component({ selector: 'jhi-vs-spo-2-delete-dialog', templateUrl: './vs-spo-2-delete-dialog.component.html' }) export class VsSpo2DeleteDialogComponent { vsSpo2: VsSpo2; constructor( private vsSpo2Service: VsSpo2Service, public activeModal: NgbActiveModal, private eventManager: JhiEventManager ) { } clear() { this.activeModal.dismiss('cancel'); } confirmDelete(id: string) { this.vsSpo2Service.delete(id).subscribe((response) => { this.eventManager.broadcast({ name: 'vsSpo2ListModification', content: 'Deleted an vsSpo2' }); this.activeModal.dismiss(true); }); } } @Component({ selector: 'jhi-vs-spo-2-delete-popup', template: '' }) export class VsSpo2DeletePopupComponent implements OnInit, OnDestroy { routeSub: any; constructor( private route: ActivatedRoute, private vsSpo2PopupService: VsSpo2PopupService ) {} ngOnInit() { this.routeSub = this.route.params.subscribe((params) => { this.vsSpo2PopupService .open(VsSpo2DeleteDialogComponent as Component, params['id']); }); } ngOnDestroy() { this.routeSub.unsubscribe(); } } <file_sep>/src/main/webapp/app/entities/menstrual-cycle/menstrual-cycle-detail.component.ts import { Component, OnInit, OnDestroy } from '@angular/core'; import { ActivatedRoute } from '@angular/router'; import { HttpResponse } from '@angular/common/http'; import { Subscription } from 'rxjs/Subscription'; import { JhiEventManager } from 'ng-jhipster'; import { MenstrualCycle } from './menstrual-cycle.model'; import { MenstrualCycleService } from './menstrual-cycle.service'; @Component({ selector: 'jhi-menstrual-cycle-detail', templateUrl: './menstrual-cycle-detail.component.html' }) export class MenstrualCycleDetailComponent implements OnInit, OnDestroy { menstrualCycle: MenstrualCycle; private subscription: Subscription; private eventSubscriber: Subscription; constructor( private eventManager: JhiEventManager, private menstrualCycleService: MenstrualCycleService, private route: ActivatedRoute ) { } ngOnInit() { this.subscription = this.route.params.subscribe((params) => { this.load(params['id']); }); this.registerChangeInMenstrualCycles(); } load(id) { this.menstrualCycleService.find(id) .subscribe((menstrualCycleResponse: HttpResponse<MenstrualCycle>) => { this.menstrualCycle = menstrualCycleResponse.body; }); } previousState() { window.history.back(); } ngOnDestroy() { this.subscription.unsubscribe(); this.eventManager.destroy(this.eventSubscriber); } registerChangeInMenstrualCycles() { this.eventSubscriber = this.eventManager.subscribe( 'menstrualCycleListModification', (response) => this.load(this.menstrualCycle.id) ); } } <file_sep>/src/main/webapp/app/entities/vs-blood-pressure/index.ts export * from './vs-blood-pressure.model'; export * from './vs-blood-pressure-popup.service'; export * from './vs-blood-pressure.service'; export * from './vs-blood-pressure-dialog.component'; export * from './vs-blood-pressure-delete-dialog.component'; export * from './vs-blood-pressure-detail.component'; export * from './vs-blood-pressure.component'; export * from './vs-blood-pressure.route'; export * from './vs-blood-pressure-info.component'; <file_sep>/src/main/webapp/app/entities/menstrual-cycle/menstrual-cycle.model.ts import { BaseEntity } from './../../shared'; export class MenstrualCycle implements BaseEntity { constructor( public id?: string, public userid?: string, public startDate?: any, public endDate?: any, ) { } } <file_sep>/src/main/webapp/app/entities/vs-body-temperature/vs-body-temperature-info.component.ts import {Component, OnInit, OnDestroy} from '@angular/core'; import {ActivatedRoute} from '@angular/router'; import {NgbActiveModal} from '@ng-bootstrap/ng-bootstrap'; import {VsBodyTemperaturePopupService} from './vs-body-temperature-popup.service'; @Component({ selector: 'jhi-vs-body-temperature-info', templateUrl: './vs-body-temperature-info.component.html' }) export class VsBodyTemperatureInfoComponent implements OnInit { constructor( public activeModal: NgbActiveModal, ) { } ngOnInit() { } clear() { this.activeModal.dismiss('cancel'); } } @Component({ selector: 'jhi-vs-body-temperature-info-popup', template: '' }) export class VsBodyTemperatureInfoPopupComponent implements OnInit, OnDestroy { routeSub: any; constructor( private route: ActivatedRoute, private vsBodyTemperaturePopupService: VsBodyTemperaturePopupService ) { } ngOnInit() { this.routeSub = this.route.params.subscribe(() => { this.vsBodyTemperaturePopupService.open(VsBodyTemperatureInfoComponent as Component); }); } ngOnDestroy() { this.routeSub.unsubscribe(); } } <file_sep>/src/main/webapp/app/entities/vs-respiratory-rate/vs-respiratory-rate.module.ts import {NgModule, CUSTOM_ELEMENTS_SCHEMA} from '@angular/core'; import {RouterModule} from '@angular/router'; import {ChartsModule} from 'ng2-charts'; import {HcPortalSharedModule} from '../../shared'; import { VsRespiratoryRateService, VsRespiratoryRatePopupService, VsRespiratoryRateComponent, VsRespiratoryRateDetailComponent, VsRespiratoryRateDialogComponent, VsRespiratoryRatePopupComponent, VsRespiratoryRateDeletePopupComponent, VsRespiratoryRateDeleteDialogComponent, vsRespiratoryRateRoute, vsRespiratoryRatePopupRoute, VsRespiratoryRateResolvePagingParams, VsRespiratoryRateInfoComponent, VsRespiratoryRateInfoPopupComponent } from './'; const ENTITY_STATES = [ ...vsRespiratoryRateRoute, ...vsRespiratoryRatePopupRoute, ]; @NgModule({ imports: [ HcPortalSharedModule, ChartsModule, RouterModule.forChild(ENTITY_STATES) ], declarations: [ VsRespiratoryRateComponent, VsRespiratoryRateDetailComponent, VsRespiratoryRateDialogComponent, VsRespiratoryRateDeleteDialogComponent, VsRespiratoryRatePopupComponent, VsRespiratoryRateDeletePopupComponent, VsRespiratoryRateInfoComponent, VsRespiratoryRateInfoPopupComponent ], entryComponents: [ VsRespiratoryRateComponent, VsRespiratoryRateDialogComponent, VsRespiratoryRatePopupComponent, VsRespiratoryRateDeleteDialogComponent, VsRespiratoryRateDeletePopupComponent, VsRespiratoryRateInfoComponent, VsRespiratoryRateInfoPopupComponent ], providers: [ VsRespiratoryRateService, VsRespiratoryRatePopupService, VsRespiratoryRateResolvePagingParams, ], schemas: [CUSTOM_ELEMENTS_SCHEMA] }) export class HcPortalVsRespiratoryRateModule { } <file_sep>/src/main/webapp/app/entities/menstrual-cycle/menstrual-cycle-delete-dialog.component.ts import { Component, OnInit, OnDestroy } from '@angular/core'; import { ActivatedRoute } from '@angular/router'; import { NgbActiveModal } from '@ng-bootstrap/ng-bootstrap'; import { JhiEventManager } from 'ng-jhipster'; import { MenstrualCycle } from './menstrual-cycle.model'; import { MenstrualCyclePopupService } from './menstrual-cycle-popup.service'; import { MenstrualCycleService } from './menstrual-cycle.service'; @Component({ selector: 'jhi-menstrual-cycle-delete-dialog', templateUrl: './menstrual-cycle-delete-dialog.component.html' }) export class MenstrualCycleDeleteDialogComponent { menstrualCycle: MenstrualCycle; constructor( private menstrualCycleService: MenstrualCycleService, public activeModal: NgbActiveModal, private eventManager: JhiEventManager ) { } clear() { this.activeModal.dismiss('cancel'); } confirmDelete(id: string) { this.menstrualCycleService.delete(id).subscribe((response) => { this.eventManager.broadcast({ name: 'menstrualCycleListModification', content: 'Deleted an menstrualCycle' }); this.activeModal.dismiss(true); }); } } @Component({ selector: 'jhi-menstrual-cycle-delete-popup', template: '' }) export class MenstrualCycleDeletePopupComponent implements OnInit, OnDestroy { routeSub: any; constructor( private route: ActivatedRoute, private menstrualCyclePopupService: MenstrualCyclePopupService ) {} ngOnInit() { this.routeSub = this.route.params.subscribe((params) => { this.menstrualCyclePopupService .open(MenstrualCycleDeleteDialogComponent as Component, params['id']); }); } ngOnDestroy() { this.routeSub.unsubscribe(); } } <file_sep>/src/main/webapp/app/entities/vs-body-temperature/index.ts export * from './vs-body-temperature.model'; export * from './vs-body-temperature-popup.service'; export * from './vs-body-temperature.service'; export * from './vs-body-temperature-dialog.component'; export * from './vs-body-temperature-delete-dialog.component'; export * from './vs-body-temperature-detail.component'; export * from './vs-body-temperature.component'; export * from './vs-body-temperature.route'; export * from './vs-body-temperature-info.component'; <file_sep>/src/main/java/com/sirtts/config/audit/package-info.java /** * Audit specific code. */ package com.sirtts.config.audit; <file_sep>/src/test/java/com/sirtts/web/rest/VsBodyTemperatureResourceIntTest.java package com.sirtts.web.rest; import com.sirtts.HcPortalApp; import com.sirtts.domain.VsBodyTemperature; import com.sirtts.repository.VsBodyTemperatureRepository; import com.sirtts.service.VsBodyTemperatureService; import com.sirtts.service.dto.VsBodyTemperatureDTO; import com.sirtts.service.mapper.VsBodyTemperatureMapper; import com.sirtts.web.rest.errors.ExceptionTranslator; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.MockitoAnnotations; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.data.web.PageableHandlerMethodArgumentResolver; import org.springframework.http.MediaType; import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.setup.MockMvcBuilders; import java.time.ZoneOffset; import java.time.LocalDateTime; import java.util.List; import static com.sirtts.web.rest.TestUtil.createFormattingConversionService; import static org.assertj.core.api.Assertions.assertThat; import static org.hamcrest.Matchers.hasItem; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; /** * Test class for the VsBodyTemperatureResource REST controller. * * @see VsBodyTemperatureResource */ @RunWith(SpringRunner.class) @SpringBootTest(classes = HcPortalApp.class) public class VsBodyTemperatureResourceIntTest { private static final String DEFAULT_USERID = "AAAAAAAAAA"; private static final String UPDATED_USERID = "BBBBBBBBBB"; private static final Double DEFAULT_CELSIUS = 1D; private static final Double UPDATED_CELSIUS = 2D; private static final LocalDateTime DEFAULT_MEASURMENTDATE = LocalDateTime.ofEpochSecond(1L,0,ZoneOffset.UTC); private static final LocalDateTime UPDATED_MEASURMENTDATE = LocalDateTime.ofEpochSecond(1L,0,ZoneOffset.UTC); @Autowired private VsBodyTemperatureRepository vsBodyTemperatureRepository; @Autowired private VsBodyTemperatureMapper vsBodyTemperatureMapper; @Autowired private VsBodyTemperatureService vsBodyTemperatureService; @Autowired private MappingJackson2HttpMessageConverter jacksonMessageConverter; @Autowired private PageableHandlerMethodArgumentResolver pageableArgumentResolver; @Autowired private ExceptionTranslator exceptionTranslator; private MockMvc restVsBodyTemperatureMockMvc; private VsBodyTemperature vsBodyTemperature; @Before public void setup() { MockitoAnnotations.initMocks(this); final VsBodyTemperatureResource vsBodyTemperatureResource = new VsBodyTemperatureResource(vsBodyTemperatureService); this.restVsBodyTemperatureMockMvc = MockMvcBuilders.standaloneSetup(vsBodyTemperatureResource) .setCustomArgumentResolvers(pageableArgumentResolver) .setControllerAdvice(exceptionTranslator) .setConversionService(createFormattingConversionService()) .setMessageConverters(jacksonMessageConverter).build(); } /** * Create an entity for this test. * * This is a static method, as tests for other entities might also need it, * if they test an entity which requires the current entity. */ public static VsBodyTemperature createEntity() { VsBodyTemperature vsBodyTemperature = new VsBodyTemperature() .userid(DEFAULT_USERID) .celsius(DEFAULT_CELSIUS) .measurmentdate(DEFAULT_MEASURMENTDATE); return vsBodyTemperature; } @Before public void initTest() { vsBodyTemperatureRepository.deleteAll(); vsBodyTemperature = createEntity(); } @Test public void createVsBodyTemperature() throws Exception { int databaseSizeBeforeCreate = vsBodyTemperatureRepository.findAll().size(); // Create the VsBodyTemperature VsBodyTemperatureDTO vsBodyTemperatureDTO = vsBodyTemperatureMapper.toDto(vsBodyTemperature); restVsBodyTemperatureMockMvc.perform(post("/api/vs-body-temperatures") .contentType(TestUtil.APPLICATION_JSON_UTF8) .content(TestUtil.convertObjectToJsonBytes(vsBodyTemperatureDTO))) .andExpect(status().isCreated()); // Validate the VsBodyTemperature in the database List<VsBodyTemperature> vsBodyTemperatureList = vsBodyTemperatureRepository.findAll(); assertThat(vsBodyTemperatureList).hasSize(databaseSizeBeforeCreate + 1); VsBodyTemperature testVsBodyTemperature = vsBodyTemperatureList.get(vsBodyTemperatureList.size() - 1); assertThat(testVsBodyTemperature.getUserid()).isEqualTo(DEFAULT_USERID); assertThat(testVsBodyTemperature.getCelsius()).isEqualTo(DEFAULT_CELSIUS); assertThat(testVsBodyTemperature.getMeasurmentdate()).isEqualTo(DEFAULT_MEASURMENTDATE); } @Test public void createVsBodyTemperatureWithExistingId() throws Exception { int databaseSizeBeforeCreate = vsBodyTemperatureRepository.findAll().size(); // Create the VsBodyTemperature with an existing ID vsBodyTemperature.setId("existing_id"); VsBodyTemperatureDTO vsBodyTemperatureDTO = vsBodyTemperatureMapper.toDto(vsBodyTemperature); // An entity with an existing ID cannot be created, so this API call must fail restVsBodyTemperatureMockMvc.perform(post("/api/vs-body-temperatures") .contentType(TestUtil.APPLICATION_JSON_UTF8) .content(TestUtil.convertObjectToJsonBytes(vsBodyTemperatureDTO))) .andExpect(status().isBadRequest()); // Validate the VsBodyTemperature in the database List<VsBodyTemperature> vsBodyTemperatureList = vsBodyTemperatureRepository.findAll(); assertThat(vsBodyTemperatureList).hasSize(databaseSizeBeforeCreate); } @Test public void checkCelsiusIsRequired() throws Exception { int databaseSizeBeforeTest = vsBodyTemperatureRepository.findAll().size(); // set the field null vsBodyTemperature.setCelsius(null); // Create the VsBodyTemperature, which fails. VsBodyTemperatureDTO vsBodyTemperatureDTO = vsBodyTemperatureMapper.toDto(vsBodyTemperature); restVsBodyTemperatureMockMvc.perform(post("/api/vs-body-temperatures") .contentType(TestUtil.APPLICATION_JSON_UTF8) .content(TestUtil.convertObjectToJsonBytes(vsBodyTemperatureDTO))) .andExpect(status().isBadRequest()); List<VsBodyTemperature> vsBodyTemperatureList = vsBodyTemperatureRepository.findAll(); assertThat(vsBodyTemperatureList).hasSize(databaseSizeBeforeTest); } @Test public void checkMeasurmentdateIsRequired() throws Exception { int databaseSizeBeforeTest = vsBodyTemperatureRepository.findAll().size(); // set the field null vsBodyTemperature.setMeasurmentdate(null); // Create the VsBodyTemperature, which fails. VsBodyTemperatureDTO vsBodyTemperatureDTO = vsBodyTemperatureMapper.toDto(vsBodyTemperature); restVsBodyTemperatureMockMvc.perform(post("/api/vs-body-temperatures") .contentType(TestUtil.APPLICATION_JSON_UTF8) .content(TestUtil.convertObjectToJsonBytes(vsBodyTemperatureDTO))) .andExpect(status().isBadRequest()); List<VsBodyTemperature> vsBodyTemperatureList = vsBodyTemperatureRepository.findAll(); assertThat(vsBodyTemperatureList).hasSize(databaseSizeBeforeTest); } @Test public void getAllVsBodyTemperatures() throws Exception { // Initialize the database vsBodyTemperatureRepository.save(vsBodyTemperature); // Get all the vsBodyTemperatureList restVsBodyTemperatureMockMvc.perform(get("/api/vs-body-temperatures?sort=id,desc")) .andExpect(status().isOk()) .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE)) .andExpect(jsonPath("$.[*].id").value(hasItem(vsBodyTemperature.getId()))) .andExpect(jsonPath("$.[*].userid").value(hasItem(DEFAULT_USERID.toString()))) .andExpect(jsonPath("$.[*].celsius").value(hasItem(DEFAULT_CELSIUS.doubleValue()))) .andExpect(jsonPath("$.[*].measurmentdate").value(hasItem(DEFAULT_MEASURMENTDATE.toString()))); } @Test public void getVsBodyTemperature() throws Exception { // Initialize the database vsBodyTemperatureRepository.save(vsBodyTemperature); // Get the vsBodyTemperature restVsBodyTemperatureMockMvc.perform(get("/api/vs-body-temperatures/{id}", vsBodyTemperature.getId())) .andExpect(status().isOk()) .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE)) .andExpect(jsonPath("$.id").value(vsBodyTemperature.getId())) .andExpect(jsonPath("$.userid").value(DEFAULT_USERID.toString())) .andExpect(jsonPath("$.celsius").value(DEFAULT_CELSIUS.doubleValue())) .andExpect(jsonPath("$.measurmentdate").value(DEFAULT_MEASURMENTDATE.toString())); } @Test public void getNonExistingVsBodyTemperature() throws Exception { // Get the vsBodyTemperature restVsBodyTemperatureMockMvc.perform(get("/api/vs-body-temperatures/{id}", Long.MAX_VALUE)) .andExpect(status().isNotFound()); } @Test public void updateVsBodyTemperature() throws Exception { // Initialize the database vsBodyTemperatureRepository.save(vsBodyTemperature); int databaseSizeBeforeUpdate = vsBodyTemperatureRepository.findAll().size(); // Update the vsBodyTemperature VsBodyTemperature updatedVsBodyTemperature = vsBodyTemperatureRepository.findOne(vsBodyTemperature.getId()); updatedVsBodyTemperature .userid(UPDATED_USERID) .celsius(UPDATED_CELSIUS) .measurmentdate(UPDATED_MEASURMENTDATE); VsBodyTemperatureDTO vsBodyTemperatureDTO = vsBodyTemperatureMapper.toDto(updatedVsBodyTemperature); restVsBodyTemperatureMockMvc.perform(put("/api/vs-body-temperatures") .contentType(TestUtil.APPLICATION_JSON_UTF8) .content(TestUtil.convertObjectToJsonBytes(vsBodyTemperatureDTO))) .andExpect(status().isOk()); // Validate the VsBodyTemperature in the database List<VsBodyTemperature> vsBodyTemperatureList = vsBodyTemperatureRepository.findAll(); assertThat(vsBodyTemperatureList).hasSize(databaseSizeBeforeUpdate); VsBodyTemperature testVsBodyTemperature = vsBodyTemperatureList.get(vsBodyTemperatureList.size() - 1); assertThat(testVsBodyTemperature.getUserid()).isEqualTo(UPDATED_USERID); assertThat(testVsBodyTemperature.getCelsius()).isEqualTo(UPDATED_CELSIUS); assertThat(testVsBodyTemperature.getMeasurmentdate()).isEqualTo(UPDATED_MEASURMENTDATE); } @Test public void updateNonExistingVsBodyTemperature() throws Exception { int databaseSizeBeforeUpdate = vsBodyTemperatureRepository.findAll().size(); // Create the VsBodyTemperature VsBodyTemperatureDTO vsBodyTemperatureDTO = vsBodyTemperatureMapper.toDto(vsBodyTemperature); // If the entity doesn't have an ID, it will be created instead of just being updated restVsBodyTemperatureMockMvc.perform(put("/api/vs-body-temperatures") .contentType(TestUtil.APPLICATION_JSON_UTF8) .content(TestUtil.convertObjectToJsonBytes(vsBodyTemperatureDTO))) .andExpect(status().isCreated()); // Validate the VsBodyTemperature in the database List<VsBodyTemperature> vsBodyTemperatureList = vsBodyTemperatureRepository.findAll(); assertThat(vsBodyTemperatureList).hasSize(databaseSizeBeforeUpdate + 1); } @Test public void deleteVsBodyTemperature() throws Exception { // Initialize the database vsBodyTemperatureRepository.save(vsBodyTemperature); int databaseSizeBeforeDelete = vsBodyTemperatureRepository.findAll().size(); // Get the vsBodyTemperature restVsBodyTemperatureMockMvc.perform(delete("/api/vs-body-temperatures/{id}", vsBodyTemperature.getId()) .accept(TestUtil.APPLICATION_JSON_UTF8)) .andExpect(status().isOk()); // Validate the database is empty List<VsBodyTemperature> vsBodyTemperatureList = vsBodyTemperatureRepository.findAll(); assertThat(vsBodyTemperatureList).hasSize(databaseSizeBeforeDelete - 1); } @Test public void equalsVerifier() throws Exception { TestUtil.equalsVerifier(VsBodyTemperature.class); VsBodyTemperature vsBodyTemperature1 = new VsBodyTemperature(); vsBodyTemperature1.setId("id1"); VsBodyTemperature vsBodyTemperature2 = new VsBodyTemperature(); vsBodyTemperature2.setId(vsBodyTemperature1.getId()); assertThat(vsBodyTemperature1).isEqualTo(vsBodyTemperature2); vsBodyTemperature2.setId("id2"); assertThat(vsBodyTemperature1).isNotEqualTo(vsBodyTemperature2); vsBodyTemperature1.setId(null); assertThat(vsBodyTemperature1).isNotEqualTo(vsBodyTemperature2); } @Test public void dtoEqualsVerifier() throws Exception { TestUtil.equalsVerifier(VsBodyTemperatureDTO.class); VsBodyTemperatureDTO vsBodyTemperatureDTO1 = new VsBodyTemperatureDTO(); vsBodyTemperatureDTO1.setId("id1"); VsBodyTemperatureDTO vsBodyTemperatureDTO2 = new VsBodyTemperatureDTO(); assertThat(vsBodyTemperatureDTO1).isNotEqualTo(vsBodyTemperatureDTO2); vsBodyTemperatureDTO2.setId(vsBodyTemperatureDTO1.getId()); assertThat(vsBodyTemperatureDTO1).isEqualTo(vsBodyTemperatureDTO2); vsBodyTemperatureDTO2.setId("id2"); assertThat(vsBodyTemperatureDTO1).isNotEqualTo(vsBodyTemperatureDTO2); vsBodyTemperatureDTO1.setId(null); assertThat(vsBodyTemperatureDTO1).isNotEqualTo(vsBodyTemperatureDTO2); } } <file_sep>/src/main/webapp/app/entities/vs-heart-rate/vs-heart-rate-dialog.component.ts import { Component, OnInit, OnDestroy } from '@angular/core'; import { ActivatedRoute } from '@angular/router'; import { HttpResponse, HttpErrorResponse } from '@angular/common/http'; import { Observable } from 'rxjs/Observable'; import { NgbActiveModal } from '@ng-bootstrap/ng-bootstrap'; import { JhiEventManager } from 'ng-jhipster'; import { VsHeartRate } from './vs-heart-rate.model'; import { VsHeartRatePopupService } from './vs-heart-rate-popup.service'; import { VsHeartRateService } from './vs-heart-rate.service'; @Component({ selector: 'jhi-vs-heart-rate-dialog', templateUrl: './vs-heart-rate-dialog.component.html' }) export class VsHeartRateDialogComponent implements OnInit { vsHeartRate: VsHeartRate; isSaving: boolean; measurmentdateDp: any; constructor( public activeModal: NgbActiveModal, private vsHeartRateService: VsHeartRateService, private eventManager: JhiEventManager ) { } ngOnInit() { this.isSaving = false; } clear() { this.activeModal.dismiss('cancel'); } save() { this.isSaving = true; if (this.vsHeartRate.id !== undefined) { this.subscribeToSaveResponse( this.vsHeartRateService.update(this.vsHeartRate)); } else { this.subscribeToSaveResponse( this.vsHeartRateService.create(this.vsHeartRate)); } } private subscribeToSaveResponse(result: Observable<HttpResponse<VsHeartRate>>) { result.subscribe((res: HttpResponse<VsHeartRate>) => this.onSaveSuccess(res.body), (res: HttpErrorResponse) => this.onSaveError()); } private onSaveSuccess(result: VsHeartRate) { this.eventManager.broadcast({ name: 'vsHeartRateListModification', content: 'OK'}); this.isSaving = false; this.activeModal.dismiss(result); } private onSaveError() { this.isSaving = false; } } @Component({ selector: 'jhi-vs-heart-rate-popup', template: '' }) export class VsHeartRatePopupComponent implements OnInit, OnDestroy { routeSub: any; constructor( private route: ActivatedRoute, private vsHeartRatePopupService: VsHeartRatePopupService ) {} ngOnInit() { this.routeSub = this.route.params.subscribe((params) => { if ( params['id'] ) { this.vsHeartRatePopupService .open(VsHeartRateDialogComponent as Component, params['id']); } else { this.vsHeartRatePopupService .open(VsHeartRateDialogComponent as Component); } }); } ngOnDestroy() { this.routeSub.unsubscribe(); } } <file_sep>/src/main/webapp/app/entities/blood-test/blood-test-delete-dialog.component.ts import { Component, OnInit, OnDestroy } from '@angular/core'; import { ActivatedRoute } from '@angular/router'; import { NgbActiveModal } from '@ng-bootstrap/ng-bootstrap'; import { JhiEventManager } from 'ng-jhipster'; import { BloodTest } from './blood-test.model'; import { BloodTestPopupService } from './blood-test-popup.service'; import { BloodTestService } from './blood-test.service'; @Component({ selector: 'jhi-blood-test-delete-dialog', templateUrl: './blood-test-delete-dialog.component.html' }) export class BloodTestDeleteDialogComponent { bloodTest: BloodTest; constructor( private bloodTestService: BloodTestService, public activeModal: NgbActiveModal, private eventManager: JhiEventManager ) { } clear() { this.activeModal.dismiss('cancel'); } confirmDelete(id: string) { this.bloodTestService.delete(id).subscribe((response) => { this.eventManager.broadcast({ name: 'bloodTestListModification', content: 'Deleted an bloodTest' }); this.activeModal.dismiss(true); }); } } @Component({ selector: 'jhi-blood-test-delete-popup', template: '' }) export class BloodTestDeletePopupComponent implements OnInit, OnDestroy { routeSub: any; constructor( private route: ActivatedRoute, private bloodTestPopupService: BloodTestPopupService ) {} ngOnInit() { this.routeSub = this.route.params.subscribe((params) => { this.bloodTestPopupService .open(BloodTestDeleteDialogComponent as Component, params['id']); }); } ngOnDestroy() { this.routeSub.unsubscribe(); } } <file_sep>/src/main/webapp/app/entities/vs-body-temperature/vs-body-temperature.module.ts import {NgModule, CUSTOM_ELEMENTS_SCHEMA} from '@angular/core'; import {RouterModule} from '@angular/router'; import {ChartsModule} from 'ng2-charts'; import {HcPortalSharedModule} from '../../shared'; import { VsBodyTemperatureService, VsBodyTemperaturePopupService, VsBodyTemperatureComponent, VsBodyTemperatureDetailComponent, VsBodyTemperatureDialogComponent, VsBodyTemperaturePopupComponent, VsBodyTemperatureDeletePopupComponent, VsBodyTemperatureDeleteDialogComponent, vsBodyTemperatureRoute, vsBodyTemperaturePopupRoute, VsBodyTemperatureResolvePagingParams, VsBodyTemperatureInfoComponent, VsBodyTemperatureInfoPopupComponent } from './'; const ENTITY_STATES = [ ...vsBodyTemperatureRoute, ...vsBodyTemperaturePopupRoute, ]; @NgModule({ imports: [ HcPortalSharedModule, ChartsModule, RouterModule.forChild(ENTITY_STATES) ], declarations: [ VsBodyTemperatureComponent, VsBodyTemperatureDetailComponent, VsBodyTemperatureDialogComponent, VsBodyTemperatureDeleteDialogComponent, VsBodyTemperaturePopupComponent, VsBodyTemperatureDeletePopupComponent, VsBodyTemperatureInfoComponent, VsBodyTemperatureInfoPopupComponent ], entryComponents: [ VsBodyTemperatureComponent, VsBodyTemperatureDialogComponent, VsBodyTemperaturePopupComponent, VsBodyTemperatureDeleteDialogComponent, VsBodyTemperatureDeletePopupComponent, VsBodyTemperatureInfoComponent, VsBodyTemperatureInfoPopupComponent ], providers: [ VsBodyTemperatureService, VsBodyTemperaturePopupService, VsBodyTemperatureResolvePagingParams, ], schemas: [CUSTOM_ELEMENTS_SCHEMA] }) export class HcPortalVsBodyTemperatureModule { } <file_sep>/src/main/webapp/app/entities/dentist-next-visit/dentist-next-visit.route.ts import { Injectable } from '@angular/core'; import { Resolve, ActivatedRouteSnapshot, RouterStateSnapshot, Routes } from '@angular/router'; import { JhiPaginationUtil } from 'ng-jhipster'; import { UserRouteAccessService } from '../../shared'; import { DentistNextVisitComponent } from './dentist-next-visit.component'; import { DentistNextVisitDetailComponent } from './dentist-next-visit-detail.component'; import { DentistNextVisitPopupComponent } from './dentist-next-visit-dialog.component'; import { DentistNextVisitDeletePopupComponent } from './dentist-next-visit-delete-dialog.component'; @Injectable() export class DentistNextVisitResolvePagingParams implements Resolve<any> { constructor(private paginationUtil: JhiPaginationUtil) {} resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) { const page = route.queryParams['page'] ? route.queryParams['page'] : '1'; const sort = route.queryParams['sort'] ? route.queryParams['sort'] : 'id,asc'; return { page: this.paginationUtil.parsePage(page), predicate: this.paginationUtil.parsePredicate(sort), ascending: this.paginationUtil.parseAscending(sort) }; } } export const dentistNextVisitRoute: Routes = [ { path: 'dentist-next-visit', component: DentistNextVisitComponent, resolve: { 'pagingParams': DentistNextVisitResolvePagingParams }, data: { authorities: ['ROLE_USER'], pageTitle: 'hcPortalApp.dentistNextVisit.home.title' }, canActivate: [UserRouteAccessService] }, { path: 'dentist-next-visit/:id', component: DentistNextVisitDetailComponent, data: { authorities: ['ROLE_USER'], pageTitle: 'hcPortalApp.dentistNextVisit.home.title' }, canActivate: [UserRouteAccessService] } ]; export const dentistNextVisitPopupRoute: Routes = [ { path: 'dentist-next-visit-new', component: DentistNextVisitPopupComponent, data: { authorities: ['ROLE_USER'], pageTitle: 'hcPortalApp.dentistNextVisit.home.title' }, canActivate: [UserRouteAccessService], outlet: 'popup' }, { path: 'dentist-next-visit/:id/edit', component: DentistNextVisitPopupComponent, data: { authorities: ['ROLE_USER'], pageTitle: 'hcPortalApp.dentistNextVisit.home.title' }, canActivate: [UserRouteAccessService], outlet: 'popup' }, { path: 'dentist-next-visit/:id/delete', component: DentistNextVisitDeletePopupComponent, data: { authorities: ['ROLE_USER'], pageTitle: 'hcPortalApp.dentistNextVisit.home.title' }, canActivate: [UserRouteAccessService], outlet: 'popup' } ]; <file_sep>/src/main/webapp/app/entities/blood-test/blood-test-info.component.ts import {Component, OnInit, OnDestroy} from '@angular/core'; import {ActivatedRoute} from '@angular/router'; import {NgbActiveModal} from '@ng-bootstrap/ng-bootstrap'; import {BloodTestPopupService} from './blood-test-popup.service'; @Component({ selector: 'jhi-blood-test-info', templateUrl: './blood-test-info.component.html' }) export class BloodTestInfoComponent implements OnInit { constructor( public activeModal: NgbActiveModal, ) { } ngOnInit() { } clear() { this.activeModal.dismiss('cancel'); } } @Component({ selector: 'jhi-blood-test-info-popup', template: '' }) export class BloodTestInfoPopupComponent implements OnInit, OnDestroy { routeSub: any; constructor( private route: ActivatedRoute, private bloodTestPopupService: BloodTestPopupService ) { } ngOnInit() { this.routeSub = this.route.params.subscribe(() => { this.bloodTestPopupService.open(BloodTestInfoComponent as Component); }); } ngOnDestroy() { this.routeSub.unsubscribe(); } } <file_sep>/src/main/webapp/app/entities/pt-doctors/pt-doctors.route.ts import {Injectable} from '@angular/core'; import {Resolve, ActivatedRouteSnapshot, RouterStateSnapshot, Routes} from '@angular/router'; import {JhiPaginationUtil} from 'ng-jhipster'; import {UserRouteAccessService} from '../../shared'; import {PtDoctorsComponent} from './pt-doctors.component'; import {PtDoctorsInfoPopupComponent} from './pt-doctors-info.component'; @Injectable() export class PtDoctorsResolvePagingParams implements Resolve<any> { constructor(private paginationUtil: JhiPaginationUtil) { } resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) { const page = route.queryParams['page'] ? route.queryParams['page'] : '1'; const sort = route.queryParams['sort'] ? route.queryParams['sort'] : 'id,asc'; return { page: this.paginationUtil.parsePage(page), predicate: this.paginationUtil.parsePredicate(sort), ascending: this.paginationUtil.parseAscending(sort) }; } } export const PtDoctorsRoute: Routes = [ { path: 'pt-doctors', component: PtDoctorsComponent, resolve: { 'pagingParams': PtDoctorsResolvePagingParams }, data: { authorities: ['ROLE_USER'], pageTitle: 'hcPortalApp.ptDoctors.home.title' }, canActivate: [UserRouteAccessService] } ]; export const PtDoctorsPopupRoute: Routes = [ { path: 'pt-doctors-info', component: PtDoctorsInfoPopupComponent, data: { authorities: ['ROLE_USER'], pageTitle: 'hcPortalApp.ptDoctors.home.title' }, canActivate: [UserRouteAccessService], outlet: 'popup' } ]; <file_sep>/src/main/webapp/app/entities/dentist-visit/index.ts export * from './dentist-visit.model'; export * from './dentist-visit-popup.service'; export * from './dentist-visit.service'; export * from './dentist-visit-dialog.component'; export * from './dentist-visit-delete-dialog.component'; export * from './dentist-visit-detail.component'; export * from './dentist-visit.component'; export * from './dentist-visit.route'; export * from './dentist-visit-info.component'; <file_sep>/src/main/java/com/sirtts/service/mapper/VsBodyTemperatureMapper.java package com.sirtts.service.mapper; import com.sirtts.domain.*; import com.sirtts.service.dto.VsBodyTemperatureDTO; import org.mapstruct.*; /** * Mapper for the entity VsBodyTemperature and its DTO VsBodyTemperatureDTO. */ @Mapper(componentModel = "spring", uses = {}) public interface VsBodyTemperatureMapper extends EntityMapper<VsBodyTemperatureDTO, VsBodyTemperature> { } <file_sep>/src/main/webapp/app/entities/vs-spo-2/index.ts export * from './vs-spo-2.model'; export * from './vs-spo-2-popup.service'; export * from './vs-spo-2.service'; export * from './vs-spo-2-dialog.component'; export * from './vs-spo-2-delete-dialog.component'; export * from './vs-spo-2-detail.component'; export * from './vs-spo-2.component'; export * from './vs-spo-2.route'; export * from './vs-spo-2-info.component'; <file_sep>/src/main/webapp/app/entities/menstrual-cycle/index.ts export * from './menstrual-cycle.model'; export * from './menstrual-cycle-popup.service'; export * from './menstrual-cycle.service'; export * from './menstrual-cycle-dialog.component'; export * from './menstrual-cycle-delete-dialog.component'; export * from './menstrual-cycle-detail.component'; export * from './menstrual-cycle.component'; export * from './menstrual-cycle.route'; export * from './menstrual-cycle-info.component'; <file_sep>/src/main/webapp/app/entities/blood-test/blood-test.module.ts import {NgModule, CUSTOM_ELEMENTS_SCHEMA} from '@angular/core'; import {RouterModule} from '@angular/router'; import {HcPortalSharedModule} from '../../shared'; import { BloodTestService, BloodTestPopupService, BloodTestComponent, BloodTestDetailComponent, BloodTestDialogComponent, BloodTestPopupComponent, BloodTestDeletePopupComponent, BloodTestDeleteDialogComponent, bloodTestRoute, bloodTestPopupRoute, BloodTestResolvePagingParams, BloodTestInfoComponent, BloodTestInfoPopupComponent } from './'; const ENTITY_STATES = [ ...bloodTestRoute, ...bloodTestPopupRoute, ]; @NgModule({ imports: [ HcPortalSharedModule, RouterModule.forChild(ENTITY_STATES) ], declarations: [ BloodTestComponent, BloodTestDetailComponent, BloodTestDialogComponent, BloodTestDeleteDialogComponent, BloodTestPopupComponent, BloodTestDeletePopupComponent, BloodTestInfoComponent, BloodTestInfoPopupComponent ], entryComponents: [ BloodTestComponent, BloodTestDialogComponent, BloodTestPopupComponent, BloodTestDeleteDialogComponent, BloodTestDeletePopupComponent, BloodTestInfoComponent, BloodTestInfoPopupComponent ], providers: [ BloodTestService, BloodTestPopupService, BloodTestResolvePagingParams, ], schemas: [CUSTOM_ELEMENTS_SCHEMA] }) export class HcPortalBloodTestModule { } <file_sep>/src/main/webapp/app/entities/diabetes-sugar-test/diabetes-sugar-test.module.ts import {NgModule, CUSTOM_ELEMENTS_SCHEMA} from '@angular/core'; import {RouterModule} from '@angular/router'; import {ChartsModule} from 'ng2-charts'; import {HcPortalSharedModule} from '../../shared'; import { DiabetesSugarTestService, DiabetesSugarTestPopupService, DiabetesSugarTestComponent, DiabetesSugarTestDetailComponent, DiabetesSugarTestDialogComponent, DiabetesSugarTestPopupComponent, DiabetesSugarTestDeletePopupComponent, DiabetesSugarTestDeleteDialogComponent, diabetesSugarTestRoute, diabetesSugarTestPopupRoute, DiabetesSugarTestResolvePagingParams, DiabetesSugarTestInfoComponent, DiabetesSugarTestInfoPopupComponent } from './'; const ENTITY_STATES = [ ...diabetesSugarTestRoute, ...diabetesSugarTestPopupRoute, ]; @NgModule({ imports: [ HcPortalSharedModule, ChartsModule, RouterModule.forChild(ENTITY_STATES) ], declarations: [ DiabetesSugarTestComponent, DiabetesSugarTestDetailComponent, DiabetesSugarTestDialogComponent, DiabetesSugarTestDeleteDialogComponent, DiabetesSugarTestPopupComponent, DiabetesSugarTestDeletePopupComponent, DiabetesSugarTestInfoComponent, DiabetesSugarTestInfoPopupComponent ], entryComponents: [ DiabetesSugarTestComponent, DiabetesSugarTestDialogComponent, DiabetesSugarTestPopupComponent, DiabetesSugarTestDeleteDialogComponent, DiabetesSugarTestDeletePopupComponent, DiabetesSugarTestInfoComponent, DiabetesSugarTestInfoPopupComponent ], providers: [ DiabetesSugarTestService, DiabetesSugarTestPopupService, DiabetesSugarTestResolvePagingParams, ], schemas: [CUSTOM_ELEMENTS_SCHEMA] }) export class HcPortalDiabetesSugarTestModule { } <file_sep>/src/main/webapp/app/entities/vs-spo-2/vs-spo-2.module.ts import {NgModule, CUSTOM_ELEMENTS_SCHEMA} from '@angular/core'; import {RouterModule} from '@angular/router'; import {ChartsModule} from 'ng2-charts'; import {HcPortalSharedModule} from '../../shared'; import { VsSpo2Service, VsSpo2PopupService, VsSpo2Component, VsSpo2DetailComponent, VsSpo2DialogComponent, VsSpo2PopupComponent, VsSpo2DeletePopupComponent, VsSpo2DeleteDialogComponent, vsSpo2Route, vsSpo2PopupRoute, VsSpo2ResolvePagingParams, VsSpo2InfoComponent, VsSpo2InfoPopupComponent } from './'; const ENTITY_STATES = [ ...vsSpo2Route, ...vsSpo2PopupRoute, ]; @NgModule({ imports: [ HcPortalSharedModule, ChartsModule, RouterModule.forChild(ENTITY_STATES) ], declarations: [ VsSpo2Component, VsSpo2DetailComponent, VsSpo2DialogComponent, VsSpo2DeleteDialogComponent, VsSpo2PopupComponent, VsSpo2DeletePopupComponent, VsSpo2InfoComponent, VsSpo2InfoPopupComponent ], entryComponents: [ VsSpo2Component, VsSpo2DialogComponent, VsSpo2PopupComponent, VsSpo2DeleteDialogComponent, VsSpo2DeletePopupComponent, VsSpo2InfoComponent, VsSpo2InfoPopupComponent ], providers: [ VsSpo2Service, VsSpo2PopupService, VsSpo2ResolvePagingParams, ], schemas: [CUSTOM_ELEMENTS_SCHEMA] }) export class HcPortalVsSpo2Module { } <file_sep>/src/main/webapp/app/entities/vs-respiratory-rate/vs-respiratory-rate.service.ts import { Injectable } from '@angular/core'; import { HttpClient, HttpResponse } from '@angular/common/http'; import { Observable } from 'rxjs/Observable'; import { SERVER_API_URL } from '../../app.constants'; import { JhiDateUtils } from 'ng-jhipster'; import { VsRespiratoryRate } from './vs-respiratory-rate.model'; import { createRequestOption } from '../../shared'; export type EntityResponseType = HttpResponse<VsRespiratoryRate>; @Injectable() export class VsRespiratoryRateService { private resourceUrl = SERVER_API_URL + 'api/vs-respiratory-rates'; constructor(private http: HttpClient, private dateUtils: JhiDateUtils) { } create(vsRespiratoryRate: VsRespiratoryRate): Observable<EntityResponseType> { const copy = this.convert(vsRespiratoryRate); return this.http.post<VsRespiratoryRate>(this.resourceUrl, copy, { observe: 'response' }) .map((res: EntityResponseType) => this.convertResponse(res)); } update(vsRespiratoryRate: VsRespiratoryRate): Observable<EntityResponseType> { const copy = this.convert(vsRespiratoryRate); return this.http.put<VsRespiratoryRate>(this.resourceUrl, copy, { observe: 'response' }) .map((res: EntityResponseType) => this.convertResponse(res)); } find(id: string): Observable<EntityResponseType> { return this.http.get<VsRespiratoryRate>(`${this.resourceUrl}/${id}`, { observe: 'response'}) .map((res: EntityResponseType) => this.convertResponse(res)); } query(req?: any): Observable<HttpResponse<VsRespiratoryRate[]>> { const options = createRequestOption(req); return this.http.get<VsRespiratoryRate[]>(`${this.resourceUrl}/byUserid/`, { params: options, observe: 'response' }) .map((res: HttpResponse<VsRespiratoryRate[]>) => this.convertArrayResponse(res)); } delete(id: string): Observable<HttpResponse<any>> { return this.http.delete<any>(`${this.resourceUrl}/${id}`, { observe: 'response'}); } private convertResponse(res: EntityResponseType): EntityResponseType { const body: VsRespiratoryRate = this.convertItemFromServer(res.body); return res.clone({body}); } private convertArrayResponse(res: HttpResponse<VsRespiratoryRate[]>): HttpResponse<VsRespiratoryRate[]> { const jsonResponse: VsRespiratoryRate[] = res.body; const body: VsRespiratoryRate[] = []; for (let i = 0; i < jsonResponse.length; i++) { body.push(this.convertItemFromServer(jsonResponse[i])); } return res.clone({body}); } /** * Convert a returned JSON object to VsRespiratoryRate. */ private convertItemFromServer(vsRespiratoryRate: VsRespiratoryRate): VsRespiratoryRate { const copy: VsRespiratoryRate = Object.assign({}, vsRespiratoryRate); copy.measurmentdate = this.dateUtils .convertDateTimeFromServer(vsRespiratoryRate.measurmentdate); return copy; } /** * Convert a VsRespiratoryRate to a JSON which can be sent to the server. */ private convert(vsRespiratoryRate: VsRespiratoryRate): VsRespiratoryRate { const copy: VsRespiratoryRate = Object.assign({}, vsRespiratoryRate); return copy; } } <file_sep>/src/main/webapp/app/entities/vs-blood-pressure/vs-blood-pressure.module.ts import {NgModule, CUSTOM_ELEMENTS_SCHEMA} from '@angular/core'; import {RouterModule} from '@angular/router'; import {ChartsModule} from 'ng2-charts'; import {HcPortalSharedModule} from '../../shared'; import { VsBloodPressureService, VsBloodPressurePopupService, VsBloodPressureComponent, VsBloodPressureDetailComponent, VsBloodPressureDialogComponent, VsBloodPressurePopupComponent, VsBloodPressureDeletePopupComponent, VsBloodPressureDeleteDialogComponent, vsBloodPressureRoute, vsBloodPressurePopupRoute, VsBloodPressureResolvePagingParams, VsBloodPressureInfoComponent, VsBloodPressureInfoPopupComponent } from './'; const ENTITY_STATES = [ ...vsBloodPressureRoute, ...vsBloodPressurePopupRoute, ]; @NgModule({ imports: [ HcPortalSharedModule, ChartsModule, RouterModule.forChild(ENTITY_STATES) ], declarations: [ VsBloodPressureComponent, VsBloodPressureDetailComponent, VsBloodPressureDialogComponent, VsBloodPressureDeleteDialogComponent, VsBloodPressurePopupComponent, VsBloodPressureDeletePopupComponent, VsBloodPressureInfoComponent, VsBloodPressureInfoPopupComponent ], entryComponents: [ VsBloodPressureComponent, VsBloodPressureDialogComponent, VsBloodPressurePopupComponent, VsBloodPressureDeleteDialogComponent, VsBloodPressureDeletePopupComponent, VsBloodPressureInfoComponent, VsBloodPressureInfoPopupComponent ], providers: [ VsBloodPressureService, VsBloodPressurePopupService, VsBloodPressureResolvePagingParams, ], schemas: [CUSTOM_ELEMENTS_SCHEMA] }) export class HcPortalVsBloodPressureModule { } <file_sep>/src/main/webapp/app/entities/vs-blood-pressure/vs-blood-pressure-detail.component.html <div *ngIf="vsBloodPressure"> <h2><span jhiTranslate="hcPortalApp.vsBloodPressure.detail.title">Vs Blood Pressure</span> {{vsBloodPressure.id}}</h2> <hr> <jhi-alert-error></jhi-alert-error> <dl class="row-md jh-entity-details"> <dt><span jhiTranslate="hcPortalApp.vsBloodPressure.userid">Userid</span></dt> <dd> <span>{{vsBloodPressure.userid}}</span> </dd> <dt><span jhiTranslate="hcPortalApp.vsBloodPressure.systolic">Systolic</span></dt> <dd> <span>{{vsBloodPressure.systolic}}</span> </dd> <dt><span jhiTranslate="hcPortalApp.vsBloodPressure.diastolic">Diastolic</span></dt> <dd> <span>{{vsBloodPressure.diastolic}}</span> </dd> <dt><span jhiTranslate="hcPortalApp.vsBloodPressure.measurmentdate">Measurmentdate</span></dt> <dd> <span>{{vsBloodPressure.measurmentdate | date:'medium'}}</span> </dd> </dl> <button type="submit" (click)="previousState()" class="btn btn-info"> <span class="fa fa-arrow-left"></span>&nbsp;<span jhiTranslate="entity.action.back"> Back</span> </button> </div> <file_sep>/src/main/webapp/app/entities/vs-body-temperature/vs-body-temperature-popup.service.ts import { Injectable, Component } from '@angular/core'; import { Router } from '@angular/router'; import { NgbModal, NgbModalRef } from '@ng-bootstrap/ng-bootstrap'; import { HttpResponse } from '@angular/common/http'; import { VsBodyTemperature } from './vs-body-temperature.model'; import { VsBodyTemperatureService } from './vs-body-temperature.service'; import {DatePipe} from '@angular/common'; @Injectable() export class VsBodyTemperaturePopupService { private ngbModalRef: NgbModalRef; constructor( private datePipe: DatePipe, private modalService: NgbModal, private router: Router, private vsBodyTemperatureService: VsBodyTemperatureService ) { this.ngbModalRef = null; } open(component: Component, id?: number | any): Promise<NgbModalRef> { return new Promise<NgbModalRef>((resolve, reject) => { const isOpen = this.ngbModalRef !== null; if (isOpen) { resolve(this.ngbModalRef); } if (id) { this.vsBodyTemperatureService.find(id) .subscribe((vsBodyTemperatureResponse: HttpResponse<VsBodyTemperature>) => { const vsBodyTemperature: VsBodyTemperature = vsBodyTemperatureResponse.body; vsBodyTemperature.measurmentdate = this.datePipe .transform(vsBodyTemperature.measurmentdate, 'yyyy-MM-ddTHH:mm:ss'); this.ngbModalRef = this.vsBodyTemperatureModalRef(component, vsBodyTemperature); resolve(this.ngbModalRef); }); } else { // setTimeout used as a workaround for getting ExpressionChangedAfterItHasBeenCheckedError setTimeout(() => { this.ngbModalRef = this.vsBodyTemperatureModalRef(component, new VsBodyTemperature()); resolve(this.ngbModalRef); }, 0); } }); } vsBodyTemperatureModalRef(component: Component, vsBodyTemperature: VsBodyTemperature): NgbModalRef { const modalRef = this.modalService.open(component, { size: 'lg', backdrop: 'static'}); modalRef.componentInstance.vsBodyTemperature = vsBodyTemperature; modalRef.result.then((result) => { this.router.navigate([{ outlets: { popup: null }}], { replaceUrl: true, queryParamsHandling: 'merge' }); this.ngbModalRef = null; }, (reason) => { this.router.navigate([{ outlets: { popup: null }}], { replaceUrl: true, queryParamsHandling: 'merge' }); this.ngbModalRef = null; }); return modalRef; } } <file_sep>/src/main/webapp/app/entities/dr-patients/dr-patients-detail.component.ts import { Component, OnInit, OnDestroy } from '@angular/core'; import { ActivatedRoute, Router } from '@angular/router'; import { NgbActiveModal } from '@ng-bootstrap/ng-bootstrap'; import { DrPatientsPopupService } from './dr-patients-popup.service'; @Component({ selector: 'jhi-dr-patients-detail', templateUrl: './dr-patients-detail.component.html' }) export class DrPatientsDetailComponent implements OnInit { detailItems = []; login: string; name: string; constructor( public activeModal: NgbActiveModal, private router: Router ) { this.detailItems.push( { name: 'SpO2', link: '../vs-spo-2/patient/' }, { name: 'Respiratory Rate', link: '../vs-respiratory-rate/patient/' }, { name: 'Heart Rate', link: '../vs-heart-rate/patient/' }, { name: 'Body Temperature', link: '../vs-body-temperature/patient/' }, { name: 'Blood Pressure', link: '../vs-blood-pressure/patient/' }, { name: 'Blood Sugar Tests', link: '../diabetes-sugar-test/patient/' }, { name: 'Blood Tests', link: '../blood-test/patient/' } ); } ngOnInit() { } clear() { this.activeModal.dismiss('cancel'); } navigate(url) { this.router.navigate([url, this.login]); } } @Component({ selector: 'jhi-dr-patients-detail-popup', template: '' }) export class DrPatientsDetailPopupComponent implements OnInit, OnDestroy { routeSub: any; constructor( private route: ActivatedRoute, private drPatientsPopupService: DrPatientsPopupService ) { } ngOnInit() { this.routeSub = this.route.params.subscribe((params) => { this.drPatientsPopupService.open(DrPatientsDetailComponent as Component); DrPatientsDetailComponent.prototype.login = params['id']; DrPatientsDetailComponent.prototype.name = params['name']; }); } ngOnDestroy() { this.routeSub.unsubscribe(); } } <file_sep>/src/main/java/com/sirtts/service/impl/VsBodyTemperatureServiceImpl.java package com.sirtts.service.impl; import com.sirtts.security.SecurityUtils; import com.sirtts.service.VsBodyTemperatureService; import com.sirtts.domain.VsBodyTemperature; import com.sirtts.repository.VsBodyTemperatureRepository; import com.sirtts.service.dto.VsBodyTemperatureDTO; import com.sirtts.service.mapper.VsBodyTemperatureMapper; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.stereotype.Service; import java.time.LocalDateTime; import java.time.ZoneOffset; /** * Service Implementation for managing VsBodyTemperature. */ @Service public class VsBodyTemperatureServiceImpl implements VsBodyTemperatureService { private final Logger log = LoggerFactory.getLogger(VsBodyTemperatureServiceImpl.class); private final VsBodyTemperatureRepository vsBodyTemperatureRepository; private final VsBodyTemperatureMapper vsBodyTemperatureMapper; public VsBodyTemperatureServiceImpl(VsBodyTemperatureRepository vsBodyTemperatureRepository, VsBodyTemperatureMapper vsBodyTemperatureMapper) { this.vsBodyTemperatureRepository = vsBodyTemperatureRepository; this.vsBodyTemperatureMapper = vsBodyTemperatureMapper; } /** * Save a vsBodyTemperature. * * @param vsBodyTemperatureDTO the entity to save * @return the persisted entity */ @Override public VsBodyTemperatureDTO save(VsBodyTemperatureDTO vsBodyTemperatureDTO) { log.debug("Request to save VsBodyTemperature : {}", vsBodyTemperatureDTO); if(vsBodyTemperatureDTO.getUserid() == null){ vsBodyTemperatureDTO.setUserid(SecurityUtils.getCurrentUserLogin().get().toString()); } VsBodyTemperature vsBodyTemperature = vsBodyTemperatureMapper.toEntity(vsBodyTemperatureDTO); vsBodyTemperature = vsBodyTemperatureRepository.save(vsBodyTemperature); return vsBodyTemperatureMapper.toDto(vsBodyTemperature); } /** * Get all the vsBodyTemperatures. * * @param pageable the pagination information * @return the list of entities */ @Override public Page<VsBodyTemperatureDTO> findAll(Pageable pageable) { log.debug("Request to get all VsBodyTemperatures"); return vsBodyTemperatureRepository.findAll(pageable) .map(vsBodyTemperatureMapper::toDto); } /** * Get all the vsBodyTemperatures by userid. * * @param pageable the pagination information * @return the list of entities */ @Override public Page<VsBodyTemperatureDTO> findAllByUserid(String[] userids, String startDate, String endDate, Pageable pageable) { log.debug("Request to get all VsBodyTemperatures"); if(userids == null) { userids = new String[1]; userids[0] = SecurityUtils.getCurrentUserLogin().get();; } LocalDateTime start,end; if(startDate == null) start = LocalDateTime.ofEpochSecond(Integer.MIN_VALUE,0, ZoneOffset.UTC); else start = LocalDateTime.parse(startDate+"T00:00:00"); if(endDate == null) end = LocalDateTime.ofEpochSecond(Integer.MAX_VALUE,0, ZoneOffset.UTC); else end = LocalDateTime.parse(endDate+"T23:59:59"); return vsBodyTemperatureRepository.findAllByUseridInAndAndMeasurmentdateBetweenOrderByMeasurmentdateDesc(userids, start, end, pageable) .map(vsBodyTemperatureMapper::toDto); } /** * Get one vsBodyTemperature by id. * * @param id the id of the entity * @return the entity */ @Override public VsBodyTemperatureDTO findOne(String id) { log.debug("Request to get VsBodyTemperature : {}", id); VsBodyTemperature vsBodyTemperature = vsBodyTemperatureRepository.findOne(id); return vsBodyTemperatureMapper.toDto(vsBodyTemperature); } /** * Delete the vsBodyTemperature by id. * * @param id the id of the entity */ @Override public void delete(String id) { log.debug("Request to delete VsBodyTemperature : {}", id); vsBodyTemperatureRepository.delete(id); } } <file_sep>/src/main/java/com/sirtts/service/mapper/VsRespiratoryRateMapper.java package com.sirtts.service.mapper; import com.sirtts.domain.*; import com.sirtts.service.dto.VsRespiratoryRateDTO; import org.mapstruct.*; /** * Mapper for the entity VsRespiratoryRate and its DTO VsRespiratoryRateDTO. */ @Mapper(componentModel = "spring", uses = {}) public interface VsRespiratoryRateMapper extends EntityMapper<VsRespiratoryRateDTO, VsRespiratoryRate> { } <file_sep>/src/main/webapp/app/entities/vs-blood-pressure/vs-blood-pressure.route.ts import {Injectable} from '@angular/core'; import {Resolve, ActivatedRouteSnapshot, RouterStateSnapshot, Routes} from '@angular/router'; import {JhiPaginationUtil} from 'ng-jhipster'; import {UserRouteAccessService} from '../../shared'; import {VsBloodPressureComponent} from './vs-blood-pressure.component'; import {VsBloodPressureDetailComponent} from './vs-blood-pressure-detail.component'; import {VsBloodPressurePopupComponent} from './vs-blood-pressure-dialog.component'; import {VsBloodPressureDeletePopupComponent} from './vs-blood-pressure-delete-dialog.component'; import {VsBloodPressureInfoPopupComponent} from './vs-blood-pressure-info.component'; @Injectable() export class VsBloodPressureResolvePagingParams implements Resolve<any> { constructor(private paginationUtil: JhiPaginationUtil) { } resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) { const page = route.queryParams['page'] ? route.queryParams['page'] : '1'; const sort = route.queryParams['sort'] ? route.queryParams['sort'] : 'id,asc'; return { page: this.paginationUtil.parsePage(page), predicate: this.paginationUtil.parsePredicate(sort), ascending: this.paginationUtil.parseAscending(sort) }; } } export const vsBloodPressureRoute: Routes = [ { path: 'vs-blood-pressure', component: VsBloodPressureComponent, resolve: { 'pagingParams': VsBloodPressureResolvePagingParams }, data: { authorities: ['ROLE_USER'], pageTitle: 'hcPortalApp.vsBloodPressure.home.title' }, canActivate: [UserRouteAccessService] }, { path: 'vs-blood-pressure/:id', component: VsBloodPressureDetailComponent, data: { authorities: ['ROLE_USER'], pageTitle: 'hcPortalApp.vsBloodPressure.home.title' }, canActivate: [UserRouteAccessService] }, { path: 'vs-blood-pressure/patient/vs-blood-pressure/:id', component: VsBloodPressureDetailComponent, data: { authorities: ['ROLE_DOCTOR'], pageTitle: 'hcPortalApp.vsBloodPressure.home.title' }, canActivate: [UserRouteAccessService] }, { path: 'vs-blood-pressure/patient/:login', component: VsBloodPressureComponent, resolve: { 'pagingParams': VsBloodPressureResolvePagingParams }, data: { authorities: ['ROLE_DOCTOR'], pageTitle: 'hcPortalApp.vsBloodPressure.home.title' }, canActivate: [UserRouteAccessService] } ]; export const vsBloodPressurePopupRoute: Routes = [ { path: 'vs-blood-pressure-new', component: VsBloodPressurePopupComponent, data: { authorities: ['ROLE_USER'], pageTitle: 'hcPortalApp.vsBloodPressure.home.title' }, canActivate: [UserRouteAccessService], outlet: 'popup' }, { path: 'vs-blood-pressure/:id/edit', component: VsBloodPressurePopupComponent, data: { authorities: ['ROLE_USER'], pageTitle: 'hcPortalApp.vsBloodPressure.home.title' }, canActivate: [UserRouteAccessService], outlet: 'popup' }, { path: 'vs-blood-pressure/:id/delete', component: VsBloodPressureDeletePopupComponent, data: { authorities: ['ROLE_USER'], pageTitle: 'hcPortalApp.vsBloodPressure.home.title' }, canActivate: [UserRouteAccessService], outlet: 'popup' }, { path: 'vs-blood-pressure-info', component: VsBloodPressureInfoPopupComponent, data: { authorities: ['ROLE_USER'], pageTitle: 'hcPortalApp.vsBloodPressure.home.title' }, canActivate: [UserRouteAccessService], outlet: 'popup' } ]; <file_sep>/src/main/java/com/sirtts/service/BloodTestService.java package com.sirtts.service; import com.sirtts.service.dto.BloodTestDTO; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import java.util.List; /** * Service Interface for managing BloodTest. */ public interface BloodTestService { /** * Save a bloodTest. * * @param bloodTestDTO the entity to save * @return the persisted entity */ BloodTestDTO save(BloodTestDTO bloodTestDTO); /** * Get all the bloodTests. * * @param pageable the pagination information * @return the list of entities */ Page<BloodTestDTO> findAll(Pageable pageable); /** * Get all the bloodTests by userid. * * @param pageable the pagination information * @return the list of entities */ Page<BloodTestDTO> findAllByUserid(String[] userids, String startDate, String endDate, Pageable pageable); /** * Get the "id" bloodTest. * * @param id the id of the entity * @return the entity */ BloodTestDTO findOne(String id); /** * Delete the "id" bloodTest. * * @param id the id of the entity */ void delete(String id); /** * Get the bloodTest columns. * * @return the entity */ List findColumns(); } <file_sep>/src/main/webapp/app/entities/menstrual-cycle/menstrual-cycle.route.ts import {Injectable} from '@angular/core'; import {Resolve, ActivatedRouteSnapshot, RouterStateSnapshot, Routes} from '@angular/router'; import {JhiPaginationUtil} from 'ng-jhipster'; import {UserRouteAccessService} from '../../shared'; import {MenstrualCycleComponent} from './menstrual-cycle.component'; import {MenstrualCycleDetailComponent} from './menstrual-cycle-detail.component'; import {MenstrualCyclePopupComponent} from './menstrual-cycle-dialog.component'; import {MenstrualCycleDeletePopupComponent} from './menstrual-cycle-delete-dialog.component'; import {MenstrualCycleInfoPopupComponent} from './menstrual-cycle-info.component'; @Injectable() export class MenstrualCycleResolvePagingParams implements Resolve<any> { constructor(private paginationUtil: JhiPaginationUtil) { } resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) { const page = route.queryParams['page'] ? route.queryParams['page'] : '1'; const sort = route.queryParams['sort'] ? route.queryParams['sort'] : 'id,asc'; return { page: this.paginationUtil.parsePage(page), predicate: this.paginationUtil.parsePredicate(sort), ascending: this.paginationUtil.parseAscending(sort) }; } } export const menstrualCycleRoute: Routes = [ { path: 'menstrual-cycle', component: MenstrualCycleComponent, resolve: { 'pagingParams': MenstrualCycleResolvePagingParams }, data: { authorities: ['ROLE_FEMALE'], pageTitle: 'hcPortalApp.menstrualCycle.home.title' }, canActivate: [UserRouteAccessService] }, { path: 'menstrual-cycle/:id', component: MenstrualCycleDetailComponent, data: { authorities: ['ROLE_FEMALE'], pageTitle: 'hcPortalApp.menstrualCycle.home.title' }, canActivate: [UserRouteAccessService] }, { path: 'menstrual-cycle/patient/menstrual-cycle/:id', component: MenstrualCycleDetailComponent, data: { authorities: ['ROLE_DOCTOR'], pageTitle: 'hcPortalApp.menstrualCycle.home.title' }, canActivate: [UserRouteAccessService] }, { path: 'menstrual-cycle/patient/:login', component: MenstrualCycleComponent, resolve: { 'pagingParams': MenstrualCycleResolvePagingParams }, data: { authorities: ['ROLE_DOCTOR'], pageTitle: 'hcPortalApp.menstrualCycle.home.title' }, canActivate: [UserRouteAccessService] } ]; export const menstrualCyclePopupRoute: Routes = [ { path: 'menstrual-cycle-new', component: MenstrualCyclePopupComponent, data: { authorities: ['ROLE_FEMALE'], pageTitle: 'hcPortalApp.menstrualCycle.home.title' }, canActivate: [UserRouteAccessService], outlet: 'popup' }, { path: 'menstrual-cycle/:id/edit', component: MenstrualCyclePopupComponent, data: { authorities: ['ROLE_FEMALE'], pageTitle: 'hcPortalApp.menstrualCycle.home.title' }, canActivate: [UserRouteAccessService], outlet: 'popup' }, { path: 'menstrual-cycle/:id/delete', component: MenstrualCycleDeletePopupComponent, data: { authorities: ['ROLE_FEMALE'], pageTitle: 'hcPortalApp.menstrualCycle.home.title' }, canActivate: [UserRouteAccessService], outlet: 'popup' }, { path: 'menstrual-cycle-info', component: MenstrualCycleInfoPopupComponent, data: { authorities: ['ROLE_FEMALE'], pageTitle: 'hcPortalApp.menstrualCycle.home.title' }, canActivate: [UserRouteAccessService], outlet: 'popup' } ]; <file_sep>/src/test/java/com/sirtts/web/rest/DentistNextVisitResourceIntTest.java package com.sirtts.web.rest; import com.sirtts.HcPortalApp; import com.sirtts.domain.DentistNextVisit; import com.sirtts.repository.DentistNextVisitRepository; import com.sirtts.service.DentistNextVisitService; import com.sirtts.service.dto.DentistNextVisitDTO; import com.sirtts.service.mapper.DentistNextVisitMapper; import com.sirtts.web.rest.errors.ExceptionTranslator; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.MockitoAnnotations; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.data.web.PageableHandlerMethodArgumentResolver; import org.springframework.http.MediaType; import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.setup.MockMvcBuilders; import java.time.ZoneOffset; import java.time.LocalDateTime; import java.util.List; import static com.sirtts.web.rest.TestUtil.createFormattingConversionService; import static org.assertj.core.api.Assertions.assertThat; import static org.hamcrest.Matchers.hasItem; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; /** * Test class for the DentistNextVisitResource REST controller. * * @see DentistNextVisitResource */ @RunWith(SpringRunner.class) @SpringBootTest(classes = HcPortalApp.class) public class DentistNextVisitResourceIntTest { private static final String DEFAULT_USERID = "AAAAAAAAAA"; private static final String UPDATED_USERID = "BBBBBBBBBB"; private static final LocalDateTime DEFAULT_MEASURMENTDATE = LocalDateTime.ofEpochSecond(1L,0,ZoneOffset.UTC); private static final LocalDateTime UPDATED_MEASURMENTDATE = LocalDateTime.ofEpochSecond(1L,0,ZoneOffset.UTC); @Autowired private DentistNextVisitRepository dentistNextVisitRepository; @Autowired private DentistNextVisitMapper dentistNextVisitMapper; @Autowired private DentistNextVisitService dentistNextVisitService; @Autowired private MappingJackson2HttpMessageConverter jacksonMessageConverter; @Autowired private PageableHandlerMethodArgumentResolver pageableArgumentResolver; @Autowired private ExceptionTranslator exceptionTranslator; private MockMvc restDentistNextVisitMockMvc; private DentistNextVisit dentistNextVisit; @Before public void setup() { MockitoAnnotations.initMocks(this); final DentistNextVisitResource dentistNextVisitResource = new DentistNextVisitResource(dentistNextVisitService); this.restDentistNextVisitMockMvc = MockMvcBuilders.standaloneSetup(dentistNextVisitResource) .setCustomArgumentResolvers(pageableArgumentResolver) .setControllerAdvice(exceptionTranslator) .setConversionService(createFormattingConversionService()) .setMessageConverters(jacksonMessageConverter).build(); } /** * Create an entity for this test. * * This is a static method, as tests for other entities might also need it, * if they test an entity which requires the current entity. */ public static DentistNextVisit createEntity() { DentistNextVisit dentistNextVisit = new DentistNextVisit() .userid(DEFAULT_USERID) .measurmentdate(DEFAULT_MEASURMENTDATE); return dentistNextVisit; } @Before public void initTest() { dentistNextVisitRepository.deleteAll(); dentistNextVisit = createEntity(); } @Test public void createDentistNextVisit() throws Exception { int databaseSizeBeforeCreate = dentistNextVisitRepository.findAll().size(); // Create the DentistNextVisit DentistNextVisitDTO dentistNextVisitDTO = dentistNextVisitMapper.toDto(dentistNextVisit); restDentistNextVisitMockMvc.perform(post("/api/dentist-next-visits") .contentType(TestUtil.APPLICATION_JSON_UTF8) .content(TestUtil.convertObjectToJsonBytes(dentistNextVisitDTO))) .andExpect(status().isCreated()); // Validate the DentistNextVisit in the database List<DentistNextVisit> dentistNextVisitList = dentistNextVisitRepository.findAll(); assertThat(dentistNextVisitList).hasSize(databaseSizeBeforeCreate + 1); DentistNextVisit testDentistNextVisit = dentistNextVisitList.get(dentistNextVisitList.size() - 1); assertThat(testDentistNextVisit.getUserid()).isEqualTo(DEFAULT_USERID); assertThat(testDentistNextVisit.getMeasurmentdate()).isEqualTo(DEFAULT_MEASURMENTDATE); } @Test public void createDentistNextVisitWithExistingId() throws Exception { int databaseSizeBeforeCreate = dentistNextVisitRepository.findAll().size(); // Create the DentistNextVisit with an existing ID dentistNextVisit.setId("existing_id"); DentistNextVisitDTO dentistNextVisitDTO = dentistNextVisitMapper.toDto(dentistNextVisit); // An entity with an existing ID cannot be created, so this API call must fail restDentistNextVisitMockMvc.perform(post("/api/dentist-next-visits") .contentType(TestUtil.APPLICATION_JSON_UTF8) .content(TestUtil.convertObjectToJsonBytes(dentistNextVisitDTO))) .andExpect(status().isBadRequest()); // Validate the DentistNextVisit in the database List<DentistNextVisit> dentistNextVisitList = dentistNextVisitRepository.findAll(); assertThat(dentistNextVisitList).hasSize(databaseSizeBeforeCreate); } @Test public void checkMeasurmentdateIsRequired() throws Exception { int databaseSizeBeforeTest = dentistNextVisitRepository.findAll().size(); // set the field null dentistNextVisit.setMeasurmentdate(null); // Create the DentistNextVisit, which fails. DentistNextVisitDTO dentistNextVisitDTO = dentistNextVisitMapper.toDto(dentistNextVisit); restDentistNextVisitMockMvc.perform(post("/api/dentist-next-visits") .contentType(TestUtil.APPLICATION_JSON_UTF8) .content(TestUtil.convertObjectToJsonBytes(dentistNextVisitDTO))) .andExpect(status().isBadRequest()); List<DentistNextVisit> dentistNextVisitList = dentistNextVisitRepository.findAll(); assertThat(dentistNextVisitList).hasSize(databaseSizeBeforeTest); } @Test public void getAllDentistNextVisits() throws Exception { // Initialize the database dentistNextVisitRepository.save(dentistNextVisit); // Get all the dentistNextVisitList restDentistNextVisitMockMvc.perform(get("/api/dentist-next-visits?sort=id,desc")) .andExpect(status().isOk()) .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE)) .andExpect(jsonPath("$.[*].id").value(hasItem(dentistNextVisit.getId()))) .andExpect(jsonPath("$.[*].userid").value(hasItem(DEFAULT_USERID.toString()))) .andExpect(jsonPath("$.[*].measurmentdate").value(hasItem(DEFAULT_MEASURMENTDATE.toString()))); } @Test public void getDentistNextVisit() throws Exception { // Initialize the database dentistNextVisitRepository.save(dentistNextVisit); // Get the dentistNextVisit restDentistNextVisitMockMvc.perform(get("/api/dentist-next-visits/{id}", dentistNextVisit.getId())) .andExpect(status().isOk()) .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE)) .andExpect(jsonPath("$.id").value(dentistNextVisit.getId())) .andExpect(jsonPath("$.userid").value(DEFAULT_USERID.toString())) .andExpect(jsonPath("$.measurmentdate").value(DEFAULT_MEASURMENTDATE.toString())); } @Test public void getNonExistingDentistNextVisit() throws Exception { // Get the dentistNextVisit restDentistNextVisitMockMvc.perform(get("/api/dentist-next-visits/{id}", Long.MAX_VALUE)) .andExpect(status().isNotFound()); } @Test public void updateDentistNextVisit() throws Exception { // Initialize the database dentistNextVisitRepository.save(dentistNextVisit); int databaseSizeBeforeUpdate = dentistNextVisitRepository.findAll().size(); // Update the dentistNextVisit DentistNextVisit updatedDentistNextVisit = dentistNextVisitRepository.findOne(dentistNextVisit.getId()); updatedDentistNextVisit .userid(UPDATED_USERID) .measurmentdate(UPDATED_MEASURMENTDATE); DentistNextVisitDTO dentistNextVisitDTO = dentistNextVisitMapper.toDto(updatedDentistNextVisit); restDentistNextVisitMockMvc.perform(put("/api/dentist-next-visits") .contentType(TestUtil.APPLICATION_JSON_UTF8) .content(TestUtil.convertObjectToJsonBytes(dentistNextVisitDTO))) .andExpect(status().isOk()); // Validate the DentistNextVisit in the database List<DentistNextVisit> dentistNextVisitList = dentistNextVisitRepository.findAll(); assertThat(dentistNextVisitList).hasSize(databaseSizeBeforeUpdate); DentistNextVisit testDentistNextVisit = dentistNextVisitList.get(dentistNextVisitList.size() - 1); assertThat(testDentistNextVisit.getUserid()).isEqualTo(UPDATED_USERID); assertThat(testDentistNextVisit.getMeasurmentdate()).isEqualTo(UPDATED_MEASURMENTDATE); } @Test public void updateNonExistingDentistNextVisit() throws Exception { int databaseSizeBeforeUpdate = dentistNextVisitRepository.findAll().size(); // Create the DentistNextVisit DentistNextVisitDTO dentistNextVisitDTO = dentistNextVisitMapper.toDto(dentistNextVisit); // If the entity doesn't have an ID, it will be created instead of just being updated restDentistNextVisitMockMvc.perform(put("/api/dentist-next-visits") .contentType(TestUtil.APPLICATION_JSON_UTF8) .content(TestUtil.convertObjectToJsonBytes(dentistNextVisitDTO))) .andExpect(status().isCreated()); // Validate the DentistNextVisit in the database List<DentistNextVisit> dentistNextVisitList = dentistNextVisitRepository.findAll(); assertThat(dentistNextVisitList).hasSize(databaseSizeBeforeUpdate + 1); } @Test public void deleteDentistNextVisit() throws Exception { // Initialize the database dentistNextVisitRepository.save(dentistNextVisit); int databaseSizeBeforeDelete = dentistNextVisitRepository.findAll().size(); // Get the dentistNextVisit restDentistNextVisitMockMvc.perform(delete("/api/dentist-next-visits/{id}", dentistNextVisit.getId()) .accept(TestUtil.APPLICATION_JSON_UTF8)) .andExpect(status().isOk()); // Validate the database is empty List<DentistNextVisit> dentistNextVisitList = dentistNextVisitRepository.findAll(); assertThat(dentistNextVisitList).hasSize(databaseSizeBeforeDelete - 1); } @Test public void equalsVerifier() throws Exception { TestUtil.equalsVerifier(DentistNextVisit.class); DentistNextVisit dentistNextVisit1 = new DentistNextVisit(); dentistNextVisit1.setId("id1"); DentistNextVisit dentistNextVisit2 = new DentistNextVisit(); dentistNextVisit2.setId(dentistNextVisit1.getId()); assertThat(dentistNextVisit1).isEqualTo(dentistNextVisit2); dentistNextVisit2.setId("id2"); assertThat(dentistNextVisit1).isNotEqualTo(dentistNextVisit2); dentistNextVisit1.setId(null); assertThat(dentistNextVisit1).isNotEqualTo(dentistNextVisit2); } @Test public void dtoEqualsVerifier() throws Exception { TestUtil.equalsVerifier(DentistNextVisitDTO.class); DentistNextVisitDTO dentistNextVisitDTO1 = new DentistNextVisitDTO(); dentistNextVisitDTO1.setId("id1"); DentistNextVisitDTO dentistNextVisitDTO2 = new DentistNextVisitDTO(); assertThat(dentistNextVisitDTO1).isNotEqualTo(dentistNextVisitDTO2); dentistNextVisitDTO2.setId(dentistNextVisitDTO1.getId()); assertThat(dentistNextVisitDTO1).isEqualTo(dentistNextVisitDTO2); dentistNextVisitDTO2.setId("id2"); assertThat(dentistNextVisitDTO1).isNotEqualTo(dentistNextVisitDTO2); dentistNextVisitDTO1.setId(null); assertThat(dentistNextVisitDTO1).isNotEqualTo(dentistNextVisitDTO2); } } <file_sep>/src/main/java/com/sirtts/service/impl/VsSpo2ServiceImpl.java package com.sirtts.service.impl; import com.sirtts.security.SecurityUtils; import com.sirtts.service.VsSpo2Service; import com.sirtts.domain.VsSpo2; import com.sirtts.repository.VsSpo2Repository; import com.sirtts.service.dto.VsSpo2DTO; import com.sirtts.service.mapper.VsSpo2Mapper; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.stereotype.Service; import java.time.LocalDateTime; import java.time.ZoneOffset; /** * Service Implementation for managing VsSpo2. */ @Service public class VsSpo2ServiceImpl implements VsSpo2Service { private final Logger log = LoggerFactory.getLogger(VsSpo2ServiceImpl.class); private final VsSpo2Repository vsSpo2Repository; private final VsSpo2Mapper vsSpo2Mapper; public VsSpo2ServiceImpl(VsSpo2Repository vsSpo2Repository, VsSpo2Mapper vsSpo2Mapper) { this.vsSpo2Repository = vsSpo2Repository; this.vsSpo2Mapper = vsSpo2Mapper; } /** * Save a vsSpo2. * * @param vsSpo2DTO the entity to save * @return the persisted entity */ @Override public VsSpo2DTO save(VsSpo2DTO vsSpo2DTO) { log.debug("Request to save VsSpo2 : {}", vsSpo2DTO); if(vsSpo2DTO.getUserid() == null){ vsSpo2DTO.setUserid(SecurityUtils.getCurrentUserLogin().get().toString()); } VsSpo2 vsSpo2 = vsSpo2Mapper.toEntity(vsSpo2DTO); vsSpo2 = vsSpo2Repository.save(vsSpo2); return vsSpo2Mapper.toDto(vsSpo2); } /** * Get all the vsSpo2S. * * @param pageable the pagination information * @return the list of entities */ @Override public Page<VsSpo2DTO> findAll(Pageable pageable) { log.debug("Request to get all VsSpo2S"); return vsSpo2Repository.findAll(pageable) .map(vsSpo2Mapper::toDto); } /** * Get all the vsSpo2S by userid. * * @param pageable the pagination information * @return the list of entities */ @Override public Page<VsSpo2DTO> findAllByUserid(String[] userids, String startDate, String endDate, Pageable pageable) { log.debug("Request to get all VsSpo2S"); if(userids == null) { userids = new String[1]; userids[0] = SecurityUtils.getCurrentUserLogin().get();; } LocalDateTime start,end; if(startDate == null) start = LocalDateTime.ofEpochSecond(Integer.MIN_VALUE,0, ZoneOffset.UTC); else start = LocalDateTime.parse(startDate+"T00:00:00"); if(endDate == null) end = LocalDateTime.ofEpochSecond(Integer.MAX_VALUE,0, ZoneOffset.UTC); else end = LocalDateTime.parse(endDate+"T23:59:59"); return vsSpo2Repository.findAllByUseridInAndAndMeasurmentdateBetweenOrderByMeasurmentdateDesc(userids, start, end, pageable) .map(vsSpo2Mapper::toDto); } /** * Get one vsSpo2 by id. * * @param id the id of the entity * @return the entity */ @Override public VsSpo2DTO findOne(String id) { log.debug("Request to get VsSpo2 : {}", id); VsSpo2 vsSpo2 = vsSpo2Repository.findOne(id); return vsSpo2Mapper.toDto(vsSpo2); } /** * Delete the vsSpo2 by id. * * @param id the id of the entity */ @Override public void delete(String id) { log.debug("Request to delete VsSpo2 : {}", id); vsSpo2Repository.delete(id); } } <file_sep>/src/main/webapp/app/entities/diabetes-sugar-test/diabetes-sugar-test-dialog.component.ts import { Component, OnInit, OnDestroy } from '@angular/core'; import { ActivatedRoute } from '@angular/router'; import { HttpResponse, HttpErrorResponse } from '@angular/common/http'; import { Observable } from 'rxjs/Observable'; import { NgbActiveModal } from '@ng-bootstrap/ng-bootstrap'; import { JhiEventManager } from 'ng-jhipster'; import { DiabetesSugarTest } from './diabetes-sugar-test.model'; import { DiabetesSugarTestPopupService } from './diabetes-sugar-test-popup.service'; import { DiabetesSugarTestService } from './diabetes-sugar-test.service'; @Component({ selector: 'jhi-diabetes-sugar-test-dialog', templateUrl: './diabetes-sugar-test-dialog.component.html' }) export class DiabetesSugarTestDialogComponent implements OnInit { diabetesSugarTest: DiabetesSugarTest; isSaving: boolean; constructor( public activeModal: NgbActiveModal, private diabetesSugarTestService: DiabetesSugarTestService, private eventManager: JhiEventManager ) { } ngOnInit() { this.isSaving = false; } clear() { this.activeModal.dismiss('cancel'); } save() { this.isSaving = true; if (this.diabetesSugarTest.id !== undefined) { this.subscribeToSaveResponse( this.diabetesSugarTestService.update(this.diabetesSugarTest)); } else { this.subscribeToSaveResponse( this.diabetesSugarTestService.create(this.diabetesSugarTest)); } } private subscribeToSaveResponse(result: Observable<HttpResponse<DiabetesSugarTest>>) { result.subscribe((res: HttpResponse<DiabetesSugarTest>) => this.onSaveSuccess(res.body), (res: HttpErrorResponse) => this.onSaveError()); } private onSaveSuccess(result: DiabetesSugarTest) { this.eventManager.broadcast({ name: 'diabetesSugarTestListModification', content: 'OK'}); this.isSaving = false; this.activeModal.dismiss(result); } private onSaveError() { this.isSaving = false; } } @Component({ selector: 'jhi-diabetes-sugar-test-popup', template: '' }) export class DiabetesSugarTestPopupComponent implements OnInit, OnDestroy { routeSub: any; constructor( private route: ActivatedRoute, private diabetesSugarTestPopupService: DiabetesSugarTestPopupService ) {} ngOnInit() { this.routeSub = this.route.params.subscribe((params) => { if ( params['id'] ) { this.diabetesSugarTestPopupService .open(DiabetesSugarTestDialogComponent as Component, params['id']); } else { this.diabetesSugarTestPopupService .open(DiabetesSugarTestDialogComponent as Component); } }); } ngOnDestroy() { this.routeSub.unsubscribe(); } } <file_sep>/src/main/webapp/app/entities/blood-test/blood-test-detail.component.ts import { Component, OnInit, OnDestroy } from '@angular/core'; import { ActivatedRoute } from '@angular/router'; import { HttpResponse } from '@angular/common/http'; import { Subscription } from 'rxjs/Subscription'; import { JhiEventManager } from 'ng-jhipster'; import { BloodTest } from './blood-test.model'; import { BloodTestService } from './blood-test.service'; @Component({ selector: 'jhi-blood-test-detail', templateUrl: './blood-test-detail.component.html' }) export class BloodTestDetailComponent implements OnInit, OnDestroy { bloodTest: BloodTest; private subscription: Subscription; private eventSubscriber: Subscription; constructor( private eventManager: JhiEventManager, private bloodTestService: BloodTestService, private route: ActivatedRoute ) { } ngOnInit() { this.subscription = this.route.params.subscribe((params) => { this.load(params['id']); }); this.registerChangeInBloodTests(); } load(id) { this.bloodTestService.find(id) .subscribe((bloodTestResponse: HttpResponse<BloodTest>) => { this.bloodTest = bloodTestResponse.body; }); } previousState() { window.history.back(); } ngOnDestroy() { this.subscription.unsubscribe(); this.eventManager.destroy(this.eventSubscriber); } registerChangeInBloodTests() { this.eventSubscriber = this.eventManager.subscribe( 'bloodTestListModification', (response) => this.load(this.bloodTest.id) ); } }
137c83da39bde95c5276903aa15ca0c7e7fc706a
[ "Java", "TypeScript", "HTML" ]
89
HTML
SIRTTS/hcPortal
ea6d0f4962619bdc7c06cbde47d8e693deb5ccbb
98a2f6a7c1834756493a47fa33f3849df21d4283
refs/heads/master
<file_sep>package com.lecode.chatranslator; /* * Developed by <NAME> * Rights reserved by lecode * Dedicated to my Maama - <NAME>. * She has been great in my live * I love you Mom * */ public class OneComment { public boolean left; public String comment; public OneComment(boolean left, String comment) { super(); this.left = left; this.comment = comment; } } <file_sep># Chat-Translator Real time language translator 1. Added version 2.4 of chat translator
7ddce13f22037ec711ae26ba65bcb2161ba9d323
[ "Markdown", "Java" ]
2
Java
sseguku/Chat-Translator
99ad1e20e82b80e81c4af535418ee27a7c914b95
05f99cb91c9e43894ccec4780819b9c7695f82fa
refs/heads/master
<repo_name>yamanayama/tutorial-svelte-style-cssinjs<file_sep>/src/apps/style/Color.js export default { BaseColor: '#FFF', /*メイン色(黒)*/ KeyColor: '#444', /*サブ色(グレー)*/ SubColor: '#ececec', /*サブ色(グレーストライプ)*/ SubColorBg: 'if(--common-device == pc, url(/images/common/stripebg.png) repeat left top #ececec,url(/images_sp/common/stripebg.png) repeat left top/4.5px #ececec)', /*注意色(赤)*/ AttentionColor: '#de3049', /*ポイント色(ハナユメグリーン)*/ PointColor: '#4cb7c3', /*価格色:ディスカウント(赤)*/ PriceColorD: '#de3049', /*価格色:通常(グレー)*/ PriceColorN: '#999', /*プレミアム色(黄色)*/ PremiumColor: '#c39d4d', /*ベース色 80%*/ BaseColorAlpha: 'rgba(255,255,255,0.8)', /*メイン色 90%*/ KeyColorAlpha: 'rgba(68, 68, 68, 0.9)', /*土曜日の色*/ WeekEndColor_sat: '#5AACE2', /*日曜日の色*/ WeekEndColor_sun: '#FF6486', /* 文字 v-fHogeColor*/ /* ------------------------------- /* メイン文字色(黒)*/ FontColor: '#444', /* サブ文字色(グレー)*/ FontSubColor: '#999', /* 注意文言文字色(赤)*/ FontAttentionColor: '#de3049', /* リンク文字色(青)*/ FontLinkColor: '#589aee', /* 価格文字色:ディスカウント(赤)*/ FontPriceColorD: '#de3049', /* 価格文字色:通常(グレー)*/ FontPriceColorN: '#999', } <file_sep>/src/apps/style/Base.js import { css } from "emotion"; // sp = 480 // tab = 768 // pc = 980 // lg = 1200 export const breakpoints = [480, 768, 980, 1200] export const mq = breakpoints.map( bp => `@media (min-width: ${bp}px)` ) //utility export function square(val , key) { return { width: val, height: key, }; } export const baseStyle = css ` display: flex; border-bottom: 1px solid red; `; export const utilityStyles = css ` .u-fz-10 { font-size: 1rem !important; } .u-fz-12 { font-size: 1.2rem !important; } .u-fz-14 { font-size: 1.4rem !important; } .u-fz-16 { font-size: 1.6rem !important; } .u-fz-18 { font-size: 1.8rem !important; } ` // export const box = css ` // position: relative; // display: inline-block; // border: 2px solid ${brand}; // line-height: 1; // padding: 4px; // border-radius: 4px; // position: relative; // &::before{ // content: ''; // background: red; // width: 20px; // height: 1px; // display: block; // position: absolute; // top: 200px; // } // ${mq[2]}{ // background: red; // } // ${mq[3]} { // background: blue; // } // `;
303b329db10efc6ebeb4a7a2d068754d200f6eca
[ "JavaScript" ]
2
JavaScript
yamanayama/tutorial-svelte-style-cssinjs
d166586f57525c12db7ceac71600afc27c306a57
65bb7e1b87595b7a43d2f9e6f487a062662a9fee
refs/heads/master
<repo_name>dilipchand/6<file_sep>/chase-atm-search-test-pack/src/test/java/com/chase/web/qa/utils/BrowserConfig.java package com.chase.web.qa.utils; import java.io.IOException; import java.io.InputStream; import java.util.Properties; public class BrowserConfig extends Properties { /** * */ private static final long serialVersionUID = 1L; public BrowserConfig() { try { InputStream is = this.getClass().getClassLoader().getResourceAsStream("browser.properties"); super.load(is); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); throw new RuntimeException(e); } } } <file_sep>/CodingTask/src/com/comcast/interview/solution/MaximumYield.java package com.comcast.interview.solution; import java.util.Arrays; public class MaximumYield { public static void main(String args[]) { int[] input = null, optimalSquares = null; input = new int[]{206, 140, 300, 52, 107}; optimalSquares = findOptimalSquares(input); printOutput(input, optimalSquares); System.out.println(); input = new int[]{147, 206, 52, 240, 300}; optimalSquares = findOptimalSquares(input); printOutput(input, optimalSquares); } public static int[] findOptimalSquares(int[] squares) { int optimalSquares[] = new int[squares.length]; Arrays.fill(optimalSquares, 0); optimalSquares[0] = 1; int lastIndex = 0; for(int i = 1; i < squares.length; i++) { if(lastIndex == i-1) { if(squares[i] > squares[i-1]) { lastIndex = i; optimalSquares[i] = 1; optimalSquares[i-1] = 0; if(i != 1) { int toptimalSquares[] = findOptimalSquares(Arrays.copyOf(squares, i-1)); for(int j = 1; j < toptimalSquares.length; j++) { optimalSquares[j] = toptimalSquares[j]; } } } } else { lastIndex = i; optimalSquares[i] = 1; } } return optimalSquares; } public static void printOutput(int inputArray[], int[] optimalSquares) { long totalUnits = 0; StringBuilder selectedSquaresInput = new StringBuilder(); StringBuilder selectedSquaresOutput = new StringBuilder(); selectedSquaresInput.append("["); selectedSquaresOutput.append("["); for(int i = 0; i < optimalSquares.length; i++) { if(optimalSquares[i] == 1) { selectedSquaresOutput.append(" " + inputArray[i] + ","); totalUnits = totalUnits + inputArray[i]; } else { selectedSquaresOutput.append(" X,"); } selectedSquaresInput.append(" " + inputArray[i] + ","); } selectedSquaresInput.deleteCharAt(selectedSquaresInput.length()-1); selectedSquaresOutput.deleteCharAt(selectedSquaresOutput.length()-1); selectedSquaresInput.append(" ]"); selectedSquaresOutput.append(" ]"); System.out.println("Input = " + selectedSquaresInput); System.out.println("Output = " + totalUnits + " units. " + selectedSquaresOutput); } } <file_sep>/chase-atm-search-test-pack/src/test/java/com/chase/web/qa/selenium/UIActionHelper.java package com.chase.web.qa.selenium; import java.io.File; import java.util.NoSuchElementException; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.firefox.FirefoxBinary; import org.openqa.selenium.firefox.FirefoxDriver; import org.openqa.selenium.firefox.FirefoxProfile; import org.openqa.selenium.support.ui.ExpectedConditions; import com.chase.web.qa.utils.BrowserConfig; public class UIActionHelper { private WebDriver webDriver; private BrowserConfig browserConfig; public UIActionHelper() { browserConfig = new BrowserConfig(); this.webDriver = new FirefoxDriver(new FirefoxBinary(new File(browserConfig.getProperty("firefox.location"))), new FirefoxProfile()); } public void get(String url) { this.webDriver.get(url); this.webDriver.manage().window().maximize(); } public void quitWebDriver() { this.webDriver.quit(); } public void selectCheckBoxById(String id) { WebElement checkbox = this.webDriver.findElement(By.id(id)); if(!checkbox.isSelected()) { checkbox.click(); } } public void clickOnButton(String button) { this.webDriver.findElement(By.xpath(button)).click(); } public void typeInputById(String input, String id) { this.webDriver.findElement(By.id(id)).sendKeys(input); } public void waitForElementByLinkTextAndClick(String linkText) { System.out.println(linkText); waitForElementByLinkTextToClick(linkText); this.webDriver.findElement(By.linkText(linkText)).click(); } public void waitForElementToBeVisible(By by) { WaitFactory.newFluentWait(this.webDriver).ignoring(NoSuchElementException.class).until(ExpectedConditions.visibilityOfElementLocated(by)); } private void waitForElementByLinkTextToClick(String linkText) { WaitFactory.newFluentWait(this.webDriver).ignoring(NoSuchElementException.class).until(ExpectedConditions.elementToBeClickable(By.linkText(linkText))); } } <file_sep>/chase-atm-search-test-pack/src/test/resources/browser.properties firefox.location=C:\\Program Files (x86)\\Mozilla Firefox\\firefox.exe<file_sep>/CodingTask/src/Test.java public class Test { public static void main(String[] args) { int[] A = {0,3,-4,5,1,-6,2,1}; Integer equilibirum = 0; int leftsum = 0; int rightsum = 0; for(int i = 1; i < A.length; i++) { for(int k = 0; k < i; k++) { leftsum = leftsum + A[k]; } for(int j = i+1; j < A.length; j++) { rightsum = rightsum + A[j]; } if(leftsum == rightsum) { equilibirum = i; break; } leftsum = 0; rightsum = 0; } System.out.println(equilibirum); } } <file_sep>/CodingTask/src/Task1.java import java.util.Arrays; public class Task1 { public static void main(String[] args) { Task1 one = new Task1(); System.out.println(Long.parseLong("12345")); System.out.println(one.solution(139)); } public int solution(int N) { /* char[] strInput = Integer.toString(N).toCharArray(); int[] inputArray = new int[strInput.length]; for(int i = 0; i < strInput.length; i++) { inputArray[i] = Integer.parseInt(new String(strInput[i]+"")); } Arrays.sort(inputArray); String maxVal = ""; for(int i = inputArray.length; i > 0; i--) { maxVal = maxVal + inputArray[i-1]; } System.out.println(maxVal); return Integer.parseInt(maxVal);*/ char[] strInput = Integer.toString(N).toCharArray(); Arrays.sort(strInput); String maxVal = ""; for(int i = strInput.length; i > 0; i--) { maxVal = maxVal + strInput[i-1]; } System.out.println(maxVal); return Integer.parseInt(maxVal); } } <file_sep>/chase-atm-search-test-pack/src/test/java/com/chase/web/qa/selenium/WaitFactory.java package com.chase.web.qa.selenium; import java.util.concurrent.TimeUnit; import org.openqa.selenium.WebDriver; import org.openqa.selenium.support.ui.FluentWait; import org.openqa.selenium.support.ui.WebDriverWait; public class WaitFactory { public static FluentWait<WebDriver> newFluentWait(WebDriver driver) { FluentWait<WebDriver> fluentWait = new WebDriverWait(driver, 20); fluentWait.pollingEvery(500, TimeUnit.NANOSECONDS); return fluentWait; } } <file_sep>/CodingTask/src/EquilibriumIndex.java public class EquilibriumIndex { public static void main(String args[]) { int[] A = {0,3,-4,5,1,-6,2,1}; EquilibriumIndex e = new EquilibriumIndex(); System.out.println(e.solution(A)); } public int solution(int[] A) { Integer equilibirum = 0; int leftsum = A[0]; int rightsum = 0; for(int i = 2; i < A.length; i++) { rightsum = rightsum + A[i]; } for(int i = 1; i < A.length; i++) { if(leftsum == rightsum) { equilibirum = i; } else { leftsum = leftsum + A[i]; rightsum = rightsum - A[i+1]; } } for(int i = 2; i < A.length; i++) { for(int j = i; j < A.length; j++) { rightsum = rightsum + A[j]; } if(leftsum == rightsum) { equilibirum = i; break; } else { } rightsum = 0; } return equilibirum; } } <file_sep>/CodingTask/src/Task2.java import java.util.Arrays; public class Task2 { public static void main(String[] args) { int[] A = {2, 4}; int[] B = {1, 2}; Task2 two = new Task2(); System.out.println(two.solution(A, B)); // System.out.println(Long.parseLong("12345")); // System.out.println(one.solution(139)); } //1 2 3 4 5 6 //4 5 9 //1 2 3 4 public int solution(int[] A, int[] B) { Arrays.sort(A); Arrays.sort(B); int minValue = -1; int bIndex = 0; for(int i = 0; i < A.length; i++) { if(bIndex >= B.length) { break; } if(A[i] == B[bIndex]) { minValue = A[i]; break; } if(A[i] > B[bIndex]) { i--; bIndex++; } } return minValue; } }
3fcbcbcb0ec08905f97d448a08e5f757e3da872e
[ "Java", "INI" ]
9
Java
dilipchand/6
426bc5e2ee69f80477a8dd4d4be2aefcea00de79
293b0f06d325b8bc7ec847a4d1d6ec5cac629a39
refs/heads/master
<repo_name>kvzakhar/resume<file_sep>/src/main/java/net/simplesoft/resume/component/ImageResizer.java package net.simplesoft.resume.component; import java.io.IOException; import java.nio.file.Path; import javax.validation.constraints.NotNull; public interface ImageResizer { void resize(@NotNull Path sourceImageFile, @NotNull Path destImageFile, int width, int height) throws IOException; }<file_sep>/src/main/java/net/simplesoft/resume/annotation/constraints/Phone.java package net.simplesoft.resume.annotation.constraints; import static java.lang.annotation.ElementType.*; import java.lang.annotation.Documented; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import javax.validation.Constraint; import javax.validation.Payload; import net.simplesoft.resume.validator.PhoneConstraintValidator; @Target({ METHOD, FIELD, ANNOTATION_TYPE, CONSTRUCTOR, PARAMETER }) @Retention(RetentionPolicy.RUNTIME) @Documented @Constraint(validatedBy = {PhoneConstraintValidator.class}) public @interface Phone { String message() default "Phone"; Class<? extends Payload>[] payload() default { }; Class<?>[] groups() default { }; } <file_sep>/src/main/java/net/simplesoft/resume/service/ImageProcessorService.java package net.simplesoft.resume.service; import org.springframework.web.multipart.MultipartFile; import net.simplesoft.resume.model.UploadCertificateResult; import net.simplesoft.resume.model.UploadResult; public interface ImageProcessorService { UploadResult processNewProfilePhoto(MultipartFile uploadPhoto); UploadCertificateResult processNewCertificateImage(MultipartFile uploadCertificateImage); }<file_sep>/src/main/java/net/simplesoft/resume/form/SignUpForm.java package net.simplesoft.resume.form; import java.io.Serializable; import javax.validation.constraints.NotNull; import javax.validation.constraints.Size; import net.simplesoft.resume.annotation.EnableFormErrorConversion; import net.simplesoft.resume.annotation.constraints.EnglishLanguage; import net.simplesoft.resume.annotation.constraints.FieldMatch; import net.simplesoft.resume.annotation.constraints.PasswordStrength; @FieldMatch(first = "password", second = "confirmPassword") @EnableFormErrorConversion(formName="passwordForm", fieldReference="confirmPassword", validationAnnotationClass=FieldMatch.class) public class SignUpForm implements Serializable{ private static final long serialVersionUID = -499113161404192508L; @NotNull @Size(max=50) @EnglishLanguage(withNumbers=false, withSpechSymbols=false) private String firstName; @NotNull @Size(max=50) @EnglishLanguage(withNumbers=false, withSpechSymbols=false) private String lastName; @PasswordStrength private String password; private String confirmPassword; public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getConfirmPassword() { return confirmPassword; } public void setConfirmPassword(String confirmPassword) { this.confirmPassword = confirmPassword; } }<file_sep>/src/main/java/net/simplesoft/resume/validator/PhoneConstraintValidator.java package net.simplesoft.resume.validator; import javax.validation.ConstraintValidator; import javax.validation.ConstraintValidatorContext; import net.simplesoft.resume.annotation.constraints.Phone; public class PhoneConstraintValidator implements ConstraintValidator<Phone, String>{ @Override public boolean isValid(String value, ConstraintValidatorContext context) { return value.matches("^\\+?[0-9]+"); } } <file_sep>/src/main/java/net/simplesoft/resume/controller/PublicDataController.java package net.simplesoft.resume.controller; import static net.simplesoft.resume.Constants.*; import java.io.UnsupportedEncodingException; import javax.servlet.http.HttpSession; import javax.validation.Valid; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageRequest; import org.springframework.data.domain.Pageable; import org.springframework.data.domain.Sort; import org.springframework.data.web.PageableDefault; import org.springframework.data.web.SortDefault; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.validation.BindingResult; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import net.simplesoft.resume.annotation.constraints.FieldMatch; import net.simplesoft.resume.component.FormErrorConverter; import net.simplesoft.resume.entity.Profile; import net.simplesoft.resume.form.SignUpForm; import net.simplesoft.resume.model.CurrentProfile; import net.simplesoft.resume.service.EditProfileService; import net.simplesoft.resume.service.FindProfileService; import net.simplesoft.resume.util.SecurityUtil; @Controller public class PublicDataController { private static final Logger LOGGER = LoggerFactory.getLogger(PublicDataController.class); private final FindProfileService findProfileService; private final FormErrorConverter formErrorConverter; private final EditProfileService editProfileService; @Autowired public PublicDataController(FindProfileService findService, FormErrorConverter formErrorConverter, EditProfileService editService) { this.findProfileService = findService; this.formErrorConverter = formErrorConverter; this.editProfileService = editService; } @GetMapping(value="/{uid}") public String getProfile(@PathVariable("uid") String uid, Model model){ Profile profile = findProfileService.findByUid(uid); if(profile == null) { return "profile-not-found"; } model.addAttribute("profile", profile); return "profile"; } @GetMapping(value="/error") public String getError(){ return "error"; } @GetMapping(value="/welcome") public String listAll(Model model) { Page<Profile> profiles = findProfileService.findAllProfilesByPage(new PageRequest(0, MAX_PROFILES_PER_PAGE, new Sort("id"))); model.addAttribute("profiles", profiles.getContent()); model.addAttribute("page", profiles); return "welcome"; } @GetMapping("/fragment/more") public String moreProfiles(Model model, @PageableDefault(size = MAX_PROFILES_PER_PAGE) @SortDefault(sort = "id") Pageable pageable) throws UnsupportedEncodingException { Page<Profile> profiles = findProfileService.findAllProfilesByPage(pageable); model.addAttribute("profiles", profiles.getContent()); return "fragment/profile-items"; } @GetMapping(value="/search") public String searchProfiles() { return "search-results"; } @GetMapping(value = "/sign-in") public String signIn() { CurrentProfile currentProfile = SecurityUtil.getCurrentProfile(); if(currentProfile != null) { return "redirect:/" + currentProfile.getUsername(); } return "sign-in"; } @GetMapping(value = "/sign-up") public String signUp(Model model) { model.addAttribute("profileForm", new SignUpForm()); return "sign-up"; } @PostMapping(value = "/sign-up") public String signUp(@Valid @ModelAttribute("profileForm") SignUpForm signUpForm, BindingResult bindingResult) { if (bindingResult.hasErrors()) { formErrorConverter.convertToFieldError(FieldMatch.class, signUpForm, bindingResult); return "sign-up"; } else { Profile profile = editProfileService.createNewProfile(signUpForm); SecurityUtil.authentificate(profile); return "redirect:/sign-up/success"; } } @GetMapping(value = "/sign-up/success") public String signUpSuccess() { return "sign-up-success"; } @RequestMapping(value = "/sign-in-failed") public String signInFailed(HttpSession session) { if (session.getAttribute("SPRING_SECURITY_LAST_EXCEPTION") == null) { return "redirect:/sign-in"; } else { return "sign-in"; } } @GetMapping(value = "/restore") public String getRestoreAccess() { return "restore"; } @GetMapping(value = "/restore/success") public String getRestoreSuccess() { return "restore-success"; } @PostMapping(value = "/restore") public String processRestoreAccess(@RequestParam("uid") String anyUnigueId) { return "redirect:/restore/success"; } @RequestMapping(value = "/restore/{token}", method = RequestMethod.GET) public String restoreAccess(@PathVariable("token") String token) { return "redirect:/edit/password"; } } <file_sep>/src/main/webapp/static/js/app.js var resume = { alert : function(message){ alert(message); }, post : function(path, params) { var form = document.createElement("form"); form.setAttribute("method", 'post'); form.setAttribute("action", path); for ( var key in params) { if (params.hasOwnProperty(key)) { var value = params[key]; if (value != undefined) { var hiddenField = document.createElement("input"); hiddenField.setAttribute("type", "hidden"); hiddenField.setAttribute("name", key); hiddenField.setAttribute("value", params[key]); form.appendChild(hiddenField); } } } document.body.appendChild(form); form.submit(); }, logout : function (csrfToken){ resume.post('/logout', { _csrf : csrfToken }); }, moreProfiles : function() { var page = parseInt($('#profileContainer').attr('data-profile-number')) + 1; var total= parseInt($('#profileContainer').attr('data-profile-total')); if (page >= total) { $('#loadMoreIndicator').remove(); $('#loadMoreContainer').remove(); return; } var url = '/fragment/more?page=' + page; $('#loadMoreContainer').css('display', 'none'); $('#loadMoreIndicator').css('display', 'block'); $.ajax({ url : url, success : function(data) { $('#loadMoreIndicator').css('display', 'none'); $('#profileContainer').append(data); $('#profileContainer').attr('data-profile-number', page); if (page >= total-1) { $('#loadMoreIndicator').remove(); $('#loadMoreContainer').remove(); } else { $('#loadMoreContainer').css('display', 'block'); } }, error : function(data) { $('#loadMoreIndicator').css('display', 'none'); resume.alert('Error! Try again later...'); } }); }, initCertificateViewer : function(){ $('a.certificate-link').click(function(e){ e.preventDefault(); var title = $(this).attr('data-title'); $('#certificateViewer .modal-title').html(title); $('#certificateViewer .modal-body img').attr('src', $(this).attr("data-url")); $('#certificateViewer').modal({ show : true }); }); }, createCertificateUploader : function(csrfToken){ //https://github.com/kartik-v/bootstrap-fileinput $("#certificateFile").fileinput({ uploadUrl: '/edit/certificates/upload?_csrf='+csrfToken, allowedFileExtensions : ['jpg', 'png'], maxFileCount: 1, showPreview:false }); $('#certificateFile').on('fileuploaded', function(event, data, previewId, index) { var response = data.response; if(response.certificateName != null) { if($('#certificateName').val().trim() == '') { $('#certificateName').val(response.certificateName); } } $('#certificateUploader').attr('data-small-url', response.smallUrl); $('#certificateUploader').attr('data-large-url', response.largeUrl); }); $('#certificateFile').on('fileuploaderror', function(event, data, msg) { resume.showErrorDialog(messages.errorUploadCertificate); }); }, certificates : { showUploadDialog : function() { $('#certificateUploader').modal({ show : true }); }, add : function (){ var certificateName = $('#certificateName').val(); //https://www.tjvantoll.com/2012/08/05/html5-form-validation-showing-all-error-messages/ if(certificateName.trim() == '') { alert('certificateName is null') return; } var template = resume.ui.getTemplate(); var container = $('#ui-block-container'); var blockIndex = container.find('.ui-item').length; var context = { blockIndex : blockIndex, name : $('#certificateName').val(), smallUrl : $('#certificateUploader').attr('data-small-url'), largeUrl : $('#certificateUploader').attr('data-large-url') }; container.append(template(context)); $('#certificateUploader').modal('hide'); $('#certificateName').val(''); $('#certificateFile').fileinput('clear'); } }, createDatePicker : function() { /* http://bootstrap-datepicker.readthedocs.org/en/latest/options.html */ $('.datepicker').datepicker({ autoclose : true, clearBtn : true }); } }<file_sep>/src/main/java/net/simplesoft/resume/service/impl/UserDetailsService.java package net.simplesoft.resume.service.impl; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.core.userdetails.UsernameNotFoundException; import org.springframework.stereotype.Service; import net.simplesoft.resume.entity.Profile; import net.simplesoft.resume.model.CurrentProfile; import net.simplesoft.resume.repository.storage.ProfileRepository; @Service("userDetailsService") public class UserDetailsService implements org.springframework.security.core.userdetails.UserDetailsService{ private static final Logger LOGGER = LoggerFactory.getLogger(UserDetailsService.class); @Autowired private ProfileRepository profileRepository; @Override public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { Profile profile = findProfile(username); if(profile != null) { return new CurrentProfile(profile); } else { LOGGER.error("Profile not found for: "+username); throw new UsernameNotFoundException("Profile not found for: "+username); } } private Profile findProfile(String anyUniqueId) { Profile profile = profileRepository.findByUid(anyUniqueId); if(profile == null) { profile = profileRepository.findByEmail(anyUniqueId); if(profile == null) { profile = profileRepository.findByPhone(anyUniqueId); } } return profile; } } <file_sep>/src/main/java/net/simplesoft/resume/configuration/ServiceConfig.java package net.simplesoft.resume.configuration; import java.io.IOException; import org.springframework.beans.factory.config.PropertiesFactoryBean; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.EnableAspectJAutoProxy; import org.springframework.context.support.PropertySourcesPlaceholderConfigurer; import org.springframework.core.io.ClassPathResource; import org.springframework.core.io.Resource; @Configuration @ComponentScan({"net.simplesoft.resume.service.impl", "net.simplesoft.resume.component.impl", "net.simplesoft.resume.listener", "net.simplesoft.resume.filter"}) @EnableAspectJAutoProxy public class ServiceConfig { @Bean public PropertiesFactoryBean properties(){ PropertiesFactoryBean properties = new PropertiesFactoryBean(); properties.setLocations(new ClassPathResource("logic.properties")); return properties; } @Bean public static PropertySourcesPlaceholderConfigurer placeHolderConfigurer() throws IOException{ PropertySourcesPlaceholderConfigurer bean = new PropertySourcesPlaceholderConfigurer(); bean.setLocations(getResources()); return bean; } private static Resource[] getResources(){ return new Resource[] { new ClassPathResource("logic.properties"), new ClassPathResource("properties/application.properties")}; } } <file_sep>/src/main/java/net/simplesoft/resume/annotation/constraints/PasswordStrength.java package net.simplesoft.resume.annotation.constraints; import static java.lang.annotation.ElementType.*; import java.lang.annotation.Documented; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import javax.validation.Constraint; import javax.validation.Payload; import javax.validation.constraints.NotNull; import javax.validation.constraints.Size; @Target({ METHOD, FIELD, ANNOTATION_TYPE, CONSTRUCTOR, PARAMETER }) @Retention(RetentionPolicy.RUNTIME) @Documented @Constraint(validatedBy = { }) @Size(min = 8, message="Пароль должен содержать минимум 8 символов") @MinDigitCount @MinUpperCharCount @MinLowerCharCount @MinSpecCharCount public @interface PasswordStrength { String message() default "PasswordStrength"; Class<? extends Payload>[] payload() default { }; Class<?>[] groups() default { }; } <file_sep>/src/main/java/net/simplesoft/resume/repository/storage/SkillCategoryRepository.java package net.simplesoft.resume.repository.storage; import java.util.List; import org.springframework.data.domain.Sort; import org.springframework.data.repository.RepositoryDefinition; import net.simplesoft.resume.entity.SkillCategory; @RepositoryDefinition(domainClass=SkillCategory.class, idClass = Long.class) public interface SkillCategoryRepository { List<SkillCategory> findAll(Sort sort); } <file_sep>/src/main/java/net/simplesoft/resume/entity/Skill.java package net.simplesoft.resume.entity; import java.io.Serializable; import java.util.Objects; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.SequenceGenerator; import javax.persistence.Table; import javax.validation.constraints.Size; import net.simplesoft.resume.annotation.constraints.EnglishLanguage; @Entity @Table(name="skill") public class Skill extends AbstractEntity<Long> implements Serializable, ProfileEntity { private static final long serialVersionUID = 1L; @Id @SequenceGenerator(name="SKILL_ID_GENERATOR", sequenceName="SKILL_SEQ", allocationSize=1) @GeneratedValue(strategy=GenerationType.SEQUENCE, generator="SKILL_ID_GENERATOR") @Column(unique=true, nullable=false) private Long id; @Column(nullable=false, length=50) @EnglishLanguage @Size(min = 1) private String category; @Column(nullable=false, length=2147483647) @EnglishLanguage @Size(min = 1) private String value; @ManyToOne(fetch=FetchType.LAZY) @JoinColumn(name="id_profile", nullable=false) private Profile profile; public Skill() { } public Long getId() { return this.id; } public void setId(Long id) { this.id = id; } public String getCategory() { return this.category; } public void setCategory(String category) { this.category = category; } public String getValue() { return this.value; } public void setValue(String value) { this.value = value; } public Profile getProfile() { return this.profile; } public void setProfile(Profile profile) { this.profile = profile; } @Override public int hashCode() { return Objects.hash(id, category, value); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (!super.equals(obj)) return false; if (!(obj instanceof Skill)) return false; Skill other = (Skill) obj; return Objects.equals(id, other.id) && Objects.equals(category, other.category) && Objects.equals(value, other.value); } }<file_sep>/pom.xml <?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>net.simplesoft</groupId> <artifactId>resume</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>war</packaging> <name>resume Maven Webapp</name> <!-- FIXME change it to the project's website --> <url>http://www.example.com</url> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> </properties> <dependencies> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>3.1.0</version> <scope>provided</scope> </dependency> <dependency> <groupId>ch.qos.logback</groupId> <artifactId>logback-classic</artifactId> <version>1.2.3</version> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>jstl</artifactId> <version>1.2</version> </dependency> <dependency> <groupId>javax.servlet.jsp</groupId> <artifactId>jsp-api</artifactId> <version>2.2</version> <scope>provided</scope> </dependency> <dependency> <groupId>org.postgresql</groupId> <artifactId>postgresql</artifactId> <version>42.2.5</version> </dependency> <dependency> <groupId>net.coobird</groupId> <artifactId>thumbnailator</artifactId> <version>0.4.8</version> </dependency> <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-lang3</artifactId> <version>3.8.1</version> </dependency> <dependency> <groupId>joda-time</groupId> <artifactId>joda-time</artifactId> <version>2.10.1</version> </dependency> <dependency> <groupId>org.sitemesh</groupId> <artifactId>sitemesh</artifactId> <version>3.0.1</version> </dependency> <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-text</artifactId> <version>1.6</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context-support</artifactId> <version>4.3.7.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>4.3.7.RELEASE</version> </dependency> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-entitymanager</artifactId> <version>5.1.0.Final</version> </dependency> <dependency> <groupId>org.springframework.data</groupId> <artifactId>spring-data-jpa</artifactId> <version>1.11.1.RELEASE</version> </dependency> <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-dbcp2</artifactId> <version>2.1.1</version> </dependency> <dependency> <groupId>commons-fileupload</groupId> <artifactId>commons-fileupload</artifactId> <version>1.3.3</version> </dependency> <!-- Validation --> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-validator</artifactId> <version>6.0.13.Final</version> </dependency> <dependency> <groupId>javax.el</groupId> <artifactId>javax.el-api</artifactId> <version>3.0.1-b04</version> </dependency> <dependency> <groupId>org.jsoup</groupId> <artifactId>jsoup</artifactId> <version>1.11.3</version> </dependency> <dependency> <groupId>commons-collections</groupId> <artifactId>commons-collections</artifactId> <version>3.2.2</version> </dependency> <dependency> <groupId>org.springframework.data</groupId> <artifactId>spring-data-elasticsearch</artifactId> <version>2.0.1.RELEASE</version> </dependency> <dependency> <groupId>net.java.dev.jna</groupId> <artifactId>jna</artifactId> <version>4.2.2</version> </dependency> <dependency> <groupId>org.springframework.security</groupId> <artifactId>spring-security-web</artifactId> <version>4.0.4.RELEASE</version> </dependency> <dependency> <groupId>org.springframework.security</groupId> <artifactId>spring-security-config</artifactId> <version>4.0.4.RELEASE</version> </dependency> <dependency> <groupId>org.springframework.security</groupId> <artifactId>spring-security-taglibs</artifactId> <version>4.0.4.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-aspects</artifactId> <version>4.3.4.RELEASE</version> </dependency> <!-- Testing --> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.12</version> <scope>test</scope> </dependency> <dependency> <groupId>org.mockito</groupId> <artifactId>mockito-core</artifactId> <version>1.10.19</version> <scope>test</scope> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-test</artifactId> <version>4.3.7.RELEASE</version> <scope>test</scope> </dependency> <dependency> <groupId>org.hamcrest</groupId> <artifactId>hamcrest-library</artifactId> <version>1.3</version> <scope>test</scope> </dependency> <dependency> <groupId>org.hsqldb</groupId> <artifactId>hsqldb</artifactId> <version>2.4.1</version> </dependency> <dependency> <groupId>org.springframework.security</groupId> <artifactId>spring-security-test</artifactId> <version>4.0.4.RELEASE</version> <scope>test</scope> </dependency> <dependency> <groupId>org.glassfish.web</groupId> <artifactId>javax.el</artifactId> <version>2.2.6</version> </dependency> <!-- <dependency> <groupId>javax.el</groupId> <artifactId>javax.el-api</artifactId> <version>2.2.4</version> <scope>test</scope> </dependency> --> <!-- <dependency> <groupId>org.apache.tomcat</groupId> <artifactId>tomcat-el-api</artifactId> <version>8.5.14</version> <scope>test</scope> </dependency> <dependency> <groupId>org.apache.tomcat</groupId> <artifactId>tomcat-jasper-el</artifactId> <version>8.5.14</version> <scope>test</scope> </dependency> --> </dependencies> <build> <finalName>resume</finalName> <pluginManagement> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <configuration> <source>1.8</source> <target>1.8</target> <showWarnings>true</showWarnings> <showDeprecation>true</showDeprecation> <debug>true</debug> </configuration> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-war-plugin</artifactId> <version>2.6</version> <configuration> <warSourceDirectory>src/main/webapp</warSourceDirectory> <failOnMissingWebXml>false</failOnMissingWebXml> </configuration> </plugin> </plugins> </pluginManagement> <plugins> <plugin> <artifactId>maven-antrun-plugin</artifactId> <version>1.8</version> <executions> <!-- clean --> <execution> <id>clean-lib</id> <phase>clean</phase> <configuration> <tasks> <delete dir="${basedir}/src/main/webapp/WEB-INF/lib" /> </tasks> </configuration> <goals> <goal>run</goal> </goals> </execution> <!-- build --> <execution> <id>copy-lib</id> <phase>package</phase> <configuration> <tasks> <delete dir="${basedir}/src/main/webapp/WEB-INF/lib" /> <copy todir="${basedir}/src/main/webapp/WEB-INF/lib"> <fileset dir="${basedir}/target/${project.build.finalName}/WEB-INF/lib" /> </copy> </tasks> </configuration> <goals> <goal>run</goal> </goals> </execution> </executions> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-dependency-plugin</artifactId> <version>2.3</version> <executions> <execution> <phase>package</phase> <goals> <goal>copy</goal> </goals> <configuration> <artifactItems> <artifactItem> <groupId>com.github.jsimone</groupId> <artifactId>webapp-runner</artifactId> <version>8.0.52.0</version> <destFileName>webapp-runner.jar</destFileName> </artifactItem> </artifactItems> </configuration> </execution> </executions> </plugin> </plugins> </build> </project> <file_sep>/src/main/resources/properties/application.properties application.production=false db.driver=org.postgresql.Driver db.url=jdbc:postgresql://localhost/resume db.username=resume db.password=<PASSWORD> db.pool.initSize=5 db.pool.maxSize=10 hibernate.dialect=org.hibernate.dialect.PostgreSQL94Dialect elasticsearch.home=E:/simplesoft/data/elastic-search-data index.all.during.startup=true application.host=http://localhost:8080 application.css.common.version=1.0 application.css.ex.version=1.0 application.js.common.version=1.0 application.js.ex.version=1.0 application.js.messages.version=1.0 executorService.threadCount=2 media.storage.root.path=E:/Zakhar/oxygen/workspace/resume/src/main/webapp media.optimization.jpegtran=C:/img-optimization/jpegtran notification.config.path=/WEB-INF/notifications/notifications.xml social.facebook.idClient=1738151536432084 social.facebook.secret=${facebookSecret}<file_sep>/src/test/resources/db/sql/create.sql CREATE SEQUENCE PROFILE_SEQ; CREATE SEQUENCE PRACTIC_SEQ; CREATE SEQUENCE LANGUAGE_SEQ; CREATE SEQUENCE HOBBY_SEQ; CREATE SEQUENCE EDUCATION_SEQ; CREATE SEQUENCE SKILL_SEQ; CREATE SEQUENCE CERTIFICATE_SEQ; CREATE SEQUENCE COURSE_SEQ;<file_sep>/src/main/java/net/simplesoft/resume/form/LanguageForm.java package net.simplesoft.resume.form; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; import javax.validation.Valid; import net.simplesoft.resume.entity.Language; public class LanguageForm { @Valid private Set<Language> items = new HashSet(); public LanguageForm() { super(); } public LanguageForm(Set<Language> items) { super(); this.items = items; } public Set<Language> getItems() { return items; } public void setItems(Set<Language> items) { this.items = items; } }<file_sep>/src/test/java/net/simplesoft/config/EmbeddedDatabaseConfig.java package net.simplesoft.config; import java.util.Properties; import javax.sql.DataSource; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.data.jpa.repository.config.EnableJpaRepositories; import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseBuilder; import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseType; import net.simplesoft.resume.configuration.JPAConfig; import net.simplesoft.resume.repository.storage.ProfileRepository; @Configuration @EnableJpaRepositories(basePackageClasses = ProfileRepository.class) public class EmbeddedDatabaseConfig extends JPAConfig{ @Override @Bean public DataSource dataSource() { return new EmbeddedDatabaseBuilder(). setType(EmbeddedDatabaseType.HSQL). addScript("db/sql/create.sql"). build(); } @Override protected Properties hibernateProperties() { Properties properties = new Properties(); properties.put("hibernate.dialect", "org.hibernate.dialect.PostgreSQL94Dialect"); properties.put("hibernate.hbm2ddl.auto","create-drop"); properties.put("hibernate.show_sql", true); properties.put("javax.persistence.validation.mode", "none"); return properties; } } <file_sep>/src/main/java/net/simplesoft/resume/component/DataBuilder.java package net.simplesoft.resume.component; public interface DataBuilder { String buildProfileUid(String firstName, String lastName); String buildRestoreAccessLink(String appHost, String token); String rebuildUidWithRandomSuffix(String baseUid, String alphabet, int letterCount); String buildCertificateName(String fileName); } <file_sep>/src/main/java/net/simplesoft/resume/configuration/ElasticSearchConfig.java package net.simplesoft.resume.configuration; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.node.Node; import org.elasticsearch.node.NodeBuilder; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.data.elasticsearch.core.ElasticsearchOperations; import org.springframework.data.elasticsearch.core.ElasticsearchTemplate; import org.springframework.data.elasticsearch.repository.config.EnableElasticsearchRepositories; //@Configuration //@EnableElasticsearchRepositories("net.devstudy.resume.repository.search") public class ElasticSearchConfig { @Value("${elasticsearch.home}") private String elasticSearchHome; @Bean public Node node(){ return new NodeBuilder() .local(true) .settings(Settings.builder().put("path.home", elasticSearchHome)) .node(); } @Bean public ElasticsearchOperations elasticsearchTemplate() { return new ElasticsearchTemplate(node().client()); } } <file_sep>/src/main/java/net/simplesoft/resume/form/CertificateForm.java package net.simplesoft.resume.form; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; import javax.validation.Valid; import net.simplesoft.resume.entity.Certificate; public class CertificateForm { @Valid private Set<Certificate> items = new HashSet(); public CertificateForm() { super(); } public CertificateForm(Set<Certificate> items) { super(); this.items = items; } public Set<Certificate> getItems() { return items; } public void setItems(Set<Certificate> items) { this.items = items; } }<file_sep>/src/main/java/net/simplesoft/resume/annotation/constraints/Adulthood.java package net.simplesoft.resume.annotation.constraints; import static java.lang.annotation.ElementType.*; import java.lang.annotation.Documented; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import javax.validation.Constraint; import javax.validation.Payload; import net.simplesoft.resume.validator.AdulthoodConstraintValidator; @Target({ METHOD, FIELD, ANNOTATION_TYPE, CONSTRUCTOR, PARAMETER }) @Retention(RetentionPolicy.RUNTIME) @Documented @Constraint(validatedBy = {AdulthoodConstraintValidator.class}) public @interface Adulthood { String message() default "Adulthood"; int adulthoodAge() default 18; Class<? extends Payload>[] payload() default { }; Class<?>[] groups() default { }; }<file_sep>/src/main/java/net/simplesoft/resume/validator/AdulthoodConstraintValidator.java package net.simplesoft.resume.validator; import java.time.LocalDate; import java.time.ZoneId; import java.util.Date; import javax.validation.ConstraintValidator; import javax.validation.ConstraintValidatorContext; import net.simplesoft.resume.annotation.constraints.Adulthood; public class AdulthoodConstraintValidator implements ConstraintValidator<Adulthood, Date>{ private int age; @Override public void initialize(Adulthood constraintAnnotation) { this.age = constraintAnnotation.adulthoodAge(); } @Override public boolean isValid(Date value, ConstraintValidatorContext context) { if(value == null) { return true; } else { LocalDate critical = LocalDate.now().minusYears(age); return value.before( Date.from(critical.atStartOfDay(ZoneId.systemDefault()).toInstant())); } } } <file_sep>/src/main/java/net/simplesoft/resume/annotation/constraints/MinLowerCharCount.java package net.simplesoft.resume.annotation.constraints; import static java.lang.annotation.ElementType.*; import java.lang.annotation.Documented; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import javax.validation.Constraint; import javax.validation.Payload; import net.simplesoft.resume.validator.MinLowerCharCountConstraintValidator; @Target({ METHOD, FIELD, ANNOTATION_TYPE, CONSTRUCTOR, PARAMETER }) @Retention(RetentionPolicy.RUNTIME) @Documented @Constraint(validatedBy={MinLowerCharCountConstraintValidator.class}) public @interface MinLowerCharCount { int value() default 1; String message() default "Пароль должен содержать прописные буквы"; Class<? extends Payload>[] payload() default { }; Class<?>[] groups() default { }; }<file_sep>/src/main/java/net/simplesoft/resume/form/SkillForm.java package net.simplesoft.resume.form; import java.io.Serializable; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; import javax.validation.Valid; import net.simplesoft.resume.entity.Skill; public class SkillForm implements Serializable { private static final long serialVersionUID = 4135568197764740034L; @Valid private Set<Skill> items = new HashSet<>(); public SkillForm() { super(); } public SkillForm(Set<Skill> items) { super(); this.items = items; } public Set<Skill> getItems() { return items; } public void setItems(Set<Skill> items) { this.items = items; } }<file_sep>/src/main/java/net/simplesoft/resume/service/FindProfileService.java package net.simplesoft.resume.service; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import net.simplesoft.resume.entity.Profile; public interface FindProfileService { Profile findByUid(String uid); Page<Profile> findAllProfilesByPage(Pageable page); Iterable<Profile> findAllForIndexing(); } <file_sep>/src/test/java/net/simplesoft/controller/PublicDataControllerTest.java package net.simplesoft.controller; import static org.hamcrest.Matchers.*; import static org.hamcrest.Matchers.is; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.*; import static org.springframework.security.test.web.servlet.setup.SecurityMockMvcConfigurers.*; import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestBuilders.*; import static org.springframework.security.test.web.servlet.response.SecurityMockMvcResultMatchers.*; import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.*; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.web.config.EnableSpringDataWebSupport; import org.springframework.http.MediaType; import org.springframework.test.context.ActiveProfiles; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.web.WebAppConfiguration; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.setup.MockMvcBuilders; import org.springframework.web.context.WebApplicationContext; import net.simplesoft.resume.configuration.JPAConfig; import net.simplesoft.resume.configuration.MVCConfig; import net.simplesoft.resume.configuration.SecurityConfig; import net.simplesoft.resume.configuration.ServiceConfig; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes= {ServiceConfig.class, MVCConfig.class, JPAConfig.class, SecurityConfig.class}) @WebAppConfiguration @ActiveProfiles("local") @EnableSpringDataWebSupport public class PublicDataControllerTest { private MockMvc mockMvc; /* @Autowired private FindProfileService findProfileService; @Autowired ProfileRepository profileRepository;*/ @Autowired private WebApplicationContext webApplicationContext; // private Pageable pageRequest; @Before public void setup() { //findProfileService = Mockito.spy(new FindProfileServiceImpl(profileRepository)); //Mockito.reset(findProfileService); mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).apply(springSecurity()).build(); //pageRequest = new PageRequest(0, 10, new Sort("id")); } @Test public void testWelcomePage() throws Exception{ mockMvc.perform(get("/welcome")). andExpect(status().isOk()). andExpect(view().name("welcome")). andExpect(model().attribute("profiles", hasSize(10))); } @Test public void testFindByUid() throws Exception{ mockMvc.perform(get("/aly-dutta")). andExpect(status().isOk()). andExpect(view().name("profile")). andExpect(model().attribute("profile", hasProperty("id", is(1L)))); } @Test public void shouldSumbitSingUpFormSuccess() throws Exception{ mockMvc.perform( post("/sign-up"). contentType(MediaType.APPLICATION_FORM_URLENCODED). param("firstName", "FirstName"). param("lastName", "LastName"). param("password", "<PASSWORD>!"). param("confirmPassword", "<PASSWORD>!") ) .andExpect(status().is3xxRedirection()). andExpect(view().name("redirect:/sign-up/success")); } @Test public void shouldFailSingUpFormWithWrongConfirmPassword() throws Exception{ mockMvc.perform( post("/sign-up"). contentType(MediaType.APPLICATION_FORM_URLENCODED). param("firstName", "FirstName"). param("lastName", "LastName"). param("password", "<PASSWORD>!"). param("confirmPassword", "<PASSWORD>!") ) .andExpect(status().isOk()). andExpect(model().attributeHasFieldErrors("profileForm", "confirmPassword")). andExpect(view().name("sign-up")); } @Test public void shouldSuccessSingIn() throws Exception{ mockMvc.perform( formLogin(). loginProcessingUrl("/sign-in-handler"). user("uid", "zakhar-kvasov"). password("<PASSWORD>!") ).andDo(print()) .andExpect(status().is3xxRedirection()) .andExpect(redirectedUrl("/my-profile")) .andExpect(authenticated().withUsername("zakhar-kvasov")); } @Test public void shouldFailSingInWrongPassword() throws Exception{ mockMvc.perform( formLogin(). loginProcessingUrl("/sign-in-handler"). user("uid", "zakhar-kvasov"). password("<PASSWORD>") ).andDo(print()) .andExpect(status().is3xxRedirection()) .andExpect(redirectedUrl("/sign-in-failed")) .andExpect(unauthenticated()); } }
09c35f39ef55bd86f0d56ba9aa81f950d0ce88ba
[ "SQL", "JavaScript", "Maven POM", "INI", "Java" ]
26
Java
kvzakhar/resume
f10e71ede194628f676ae2e53ab7f1b8401430d4
b5a058462811d0ac4374b8f3fe677b89abb814f6
refs/heads/master
<file_sep>require "active_support/concern" require "santas-little-helpers" module Mongoid module Slug extend ActiveSupport::Concern included do cattr_accessor :slugged_fields, :slug_name, :slug_builder end module ClassMethods def slug(*fields, &block) options = fields.extract_options! self.slug_name = options[:as] || :slug self.slugged_fields = fields.map(&:to_s) self.slug_builder = block_given? ? block : default_slug_builder # Setup slugged field and index field slug_name, type: String index({ slug_name => 1 }) if options[:index] # Generate slug on every save or keep the first one? if options[:permanent] before_create :generate_slug else before_save :generate_slug end instance_eval <<-CODE def self.find_by_#{slug_name}(slug) where(slug_name => slug).first end def self.find_by_#{slug_name}!(slug) find_by_slug(slug) or raise Mongoid::Errors::DocumentNotFound.new(self.class, slug) end CODE end private def default_slug_builder lambda do |doc| slugged_fields.map { |f| doc.read_attribute(f) }.join(" ").to_url end end end private def generate_slug write_attribute slug_name, find_unique_slug end def find_unique_slug slug = slug_builder.call(self) # We can't do a simple query if this document belongs # to an embedded collection. But that's no big deal, # because we don't care about duplicate/redundant data # in this case anyway. unless self.embedded? pattern = /^#{Regexp.escape(slug)}(-\d+)?$/ existing_slugs_count = self.class. only(slug_name). where(slug_name => pattern, :_id.ne => _id). count if existing_slugs_count > 0 slug << "-#{existing_slugs_count}" end end slug end end end <file_sep>require 'rubygems' require 'bundler' Bundler.setup require 'rspec' require 'mongoid' require 'mongoid-rspec' require 'database_cleaner' require 'pry-byebug' require 'mongoid/seo' require 'mongoid/slug' cwd = File.dirname(__FILE__) Dir["#{cwd}/support/**/*.rb"].each { |f| require f } Mongoid.load!("#{cwd}/../config/mongoid.yml", :test) RSpec.configure do |config| config.include RSpec::Matchers config.include Mongoid::Matchers, type: :model config.mock_with :rspec config.before(:suite) { DatabaseCleaner[:mongoid].strategy = :truncation } config.before(:each) { DatabaseCleaner[:mongoid].start } config.after(:each) { DatabaseCleaner[:mongoid].clean } end <file_sep>source "http://rubygems.org" gemspec gem 'santas-little-helpers', git: '<EMAIL>:jazen/santas-little-helpers' gem 'fivemat', group: :test <file_sep>require "active_support/concern" module Mongoid module Localization extend ActiveSupport::Concern extend Forwardable included do cattr_accessor \ :localized_fields, :localized_languages, :localization_class self.localization_class = Mongoid::Localization::Localization embeds_many :localizations, class_name: localization_class.name, as: :localizable accepts_nested_attributes_for :localizations after_initialize :setup_empty_localizations end def_delegators "self.class", :localized_fields, :localized_languages def setup_empty_localizations localized_languages.each do |lang| localizations.new(language: lang) end end module ClassMethods # ---------------------------------- def localize(*fields) options = fields.extract_options! fields = [fields].flatten self.localized_fields = fields self.localized_languages = [options[:for]].flatten self.localization_class.class_eval do fields.each do |name| field name end end end end class Localization # ----------------------------------- include Mongoid::Document embedded_in :localizable, polymorphic: true, inverse_of: :localizations field :language # TODO validate def localized_fields localizable.class.localized_fields end end end end <file_sep>require "active_support/concern" module Mongoid module SEO module Aliases extend ActiveSupport::Concern module ClassMethods def aliases(*fields) fields.each do |name| field "#{name}_aliases".to_sym, type: Array, default: [] before_save "update_#{name}_aliases".to_sym, :if => "#{name}_changed?".to_sym class_eval <<-CODE def update_#{name}_aliases #{name}_aliases.push(#{name}_was) end CODE end end end end end end <file_sep># -*- coding: utf-8 -*- require 'spec_helper' describe Mongoid::Slug do context "when the object uses a single field as slug" do before :all do class Book include Mongoid::Document include Mongoid::Slug field :title slug :title, :index => true end end let(:book) { Book.create(:title => "A thousand plateaus") } subject { book } # it { should have_index_for(slug: 1) } it "generates a slug" do expect(book.slug).to eq("a-thousand-plateaus") end it "updates the slug" do book.title = "Anti Ödipus" book.save expect(book.slug).to eq("anti-oedipus") end it "generates a unique slug by appending a counter to duplicate text" do 15.times { |x| dup = Book.create(:title => book.title) expect(dup.slug).to eql "a-thousand-plateaus-#{x+1}" } end it "does not update slug if slugged fields have not changed" do book.save expect(book.slug).to eq("a-thousand-plateaus") end it "does not change slug if slugged fields have changed but generated slug is identical" do book.title = "a thousand plateaus" book.save expect(book.slug).to eq("a-thousand-plateaus") end it "finds by slug" do expect(Book.find_by_slug(book.slug)).to eq(book) end end # -------------------------------------------------------- context "when the slug is composed of multiple fields" do before :all do class Author include Mongoid::Document include Mongoid::Slug field :first_name field :last_name slug :first_name, :last_name end end let(:author) do Author.create :first_name => "Gilles", :last_name => "Deleuze" end it "generates a slug" do expect(author.slug).to eq("gilles-deleuze") end it "updates the slug" do author.first_name = "Félix" author.last_name = "Guattari" author.save expect(author.slug).to eq("felix-guattari") end it "generates a unique slug by appending a counter to duplicate text" do dup = Author.create( :first_name => author.first_name, :last_name => author.last_name) expect(dup.slug).to eq('gilles-deleuze-1') dup2 = Author.create( :first_name => author.first_name, :last_name => author.last_name) dup.save expect(dup2.slug).to eq('gilles-deleuze-2') end it "does not update slug if slugged fields have changed but generated slug is identical" do author.last_name = "DELEUZE" author.save expect(author.slug).to eq('gilles-deleuze') end it "finds by slug" do author expect(Author.find_by_slug("gilles-deleuze")).to eq(author) end end context "when :as is passed as an argument" do before :all do class Person include Mongoid::Document include Mongoid::Slug field :name slug :name, :as => :permalink end end let(:person) do Person.create(:name => "<NAME>") end it "sets an alternative slug field name" do expect(person).to respond_to(:permalink) expect(person.permalink).to eql "john-doe" end it "finds by slug" do person expect(Person.find_by_permalink("john-doe")).to eq(person) end end context "when :permanent is passed as an argument" do before :all do class FakeCity include Mongoid::Document include Mongoid::Slug field :name slug :name, :permanent => true end end let(:city) do FakeCity.create(:name => "Leipzig") end it "does not update the slug when the slugged fields change" do city.name = "Berlin" city.save expect(city.slug).to eq("leipzig") end end context "when :slug is given a block" do before :all do class Caption include Mongoid::Document include Mongoid::Slug field :author field :title field :medium # A fairly complex scenario, where we want to create a slug out # of an author field, which comprises name of artist and some # more bibliographic info in parantheses, and the title of the work. # # We are only interested in the name of the artist so we remove the # paranthesized details. slug :author, :title do |doc| [ doc.author.gsub(/\s*\([^)]+\)/, '').to_url, doc.title.to_url ].join('/') end end end let(:caption) do Caption.create( :author => '<NAME> (American, 1882-1967)', :title => '<NAME>, 1914', :medium => 'Oil on Canvas' ) end it "generates a slug" do expect(caption.slug).to eq('edward-hopper/soir-bleu-1914') end it "updates the slug" do caption.title = 'Road in Maine, 1914' caption.save expect(caption.slug).to eq("edward-hopper/road-in-maine-1914") end it "does not change slug if slugged fields have changed but generated slug is identical" do caption.author = '<NAME>' caption.save expect(caption.slug).to eq('edward-hopper/soir-bleu-1914') end it "finds by slug" do expect(Caption.find_by_slug(caption.slug)).to eql(caption) end end context "when slugged field contains non-ASCII characters" do let(:book) { Book.create(:title => "A thousand plateaus") } # it "slugs Cyrillic characters" do # book.title = "Капитал" # book.save # book.slug.should eql "kapital" # end # it "slugs Greek characters" do # book.title = "Ελλάδα" # book.save # book.slug.should eql "ellada" # end # it "slugs Chinese characters" do # book.title = "中文" # book.save # book.slug.should eql 'zhong-wen' # end it "slugs non-ASCII Latin characters" do book.title = '<NAME>' book.save expect(book.slug).to eql 'paul-cezanne' end end describe ".find_by_slug" do let(:book) { Book.create(:title => "A Thousand Plateaus") } it "returns nil if no document is found" do expect(Book.find_by_slug(:title => "Anti Oedipus")).to be_nil end it "returns the document if it is found" do expect(Book.find_by_slug(book.slug)).to eq(book) end end describe ".find_by_slug!" do let(:book) { Book.create(:title => "A Thousand Plateaus") } it "raises a Mongoid::Errors::DocumentNotFound error if no document is found" do expect { Book.find_by_slug!(:title => "Anti Oedipus") }.to raise_error(Mongoid::Errors::DocumentNotFound) end it "returns the document when it is found" do expect(Book.find_by_slug!(book.slug)).to eq(book) end end # context "when #slug is called on an existing record with no slug" do # before do # Book.collection.insert(:title => "Proust and Signs") # end # it "generates the missing slug" do # book = Book.first # book.slug # book.reload.slug.should == "proust-and-signs" # end # end end <file_sep>require "spec_helper" describe Mongoid::SEO do let(:klass) { Class.new } subject { klass } before do klass.send :include, Mongoid::Document klass.send :include, Mongoid::SEO end # it { should have_field(:page_title) } # it { should have_field(:meta_description) } describe ".seo_fields" do it "should return all fields added by the plugin" do expect(klass.seo_fields).to eq([ :page_title, :meta_description ]) end end end <file_sep>require "mongoid/localization" require "mongoid/seo" require "mongoid/seo/aliases" require "mongoid/slug" require "mongoid/variants" <file_sep>require "active_support/concern" module Mongoid module Variants extend ActiveSupport::Concern included do # Save all variants as an array of hashes containing # the key/value pairs which differ from the document's attributes # field :variants, type: Array, default: [] embeds_many :variants, class_name: "Mongoid::Variants::Variant", as: :variant_owner # Find document with a variant matching the given +options+ # +options+ will get automatically scoped to "variants." # # So calling # Model.with_variant(bacon: true, amount: 5) # # will result in a query like this: # Model.where("variants.bacon": true, "variants.amount": 5) # scope :with_variant, ->(options) { scoped_options = options.inject({}) do |memo, (k,v)| memo["variants.#{k}"] = v memo end where(scoped_options) } end # These attributes shouldn't be compared because # they're internal ones and differ anyway. INTERNAL_ATTRIBUTES = %w( _id # Mongoid's document id created_at # Mongoid::Timestamps updated_at # Mongoid::Timestamps variants # That's us! ) # Returns all attributes which differ from the +other+ document ones. def variant_attributes(other, options = {}) blocked_attributes = INTERNAL_ATTRIBUTES + options[:block].to_a a = self.attributes.block(*blocked_attributes) b = other.attributes.block(*blocked_attributes) a.inject({}) do |memo, (k,v)| memo[k] = v unless b[k] == v memo end end # The embedded document class Variant include Mongoid::Document embedded_in :variant_owner, polymorphic: true # Applies the variant's attributes to the +document+ # (defaults to the variant's owner) # # You can exclude attributes using the +:block: option. # def apply(document = variant_owner, options = {}) document.tap do |doc| # Apply all non-blocked attributes to the document blocked_attributes = INTERNAL_ATTRIBUTES + options[:block].to_a attributes.block(*blocked_attributes).each do |k,v| doc.send("#{k}=", v) end # Pick up any changes to '*_id' attributes doc.reload_relations end end # Get all variants for a given field def self.of(field) field = field.to_sym where(field.exists => true).only(field).map(&field) end end end end <file_sep>Gem::Specification.new do |s| s.name = "mongoid-plugins" s.version = "0.0.1" s.platform = Gem::Platform::RUBY s.summary = "A collection of modules/plugins for Mongoid." s.description = "A collection of modules/plugins for Mongoid." s.files = `git ls-files`.split("\n") s.add_runtime_dependency 'activesupport' s.add_runtime_dependency 'mongoid' s.add_runtime_dependency 'bson_ext' s.add_runtime_dependency 'mongo_ext' s.add_runtime_dependency 'urlify' s.add_development_dependency 'rspec' s.add_development_dependency 'mongoid-rspec' s.add_development_dependency 'database_cleaner' s.add_development_dependency 'pry-byebug' end <file_sep>require "active_support/concern" module Mongoid module SEO extend ActiveSupport::Concern SEO_FIELDS = [ :page_title, :meta_description ] included do SEO_FIELDS.each do |name| field name end end module ClassMethods # -------------------------------- def seo_fields SEO_FIELDS end end end end
06d287bfc27eedb30a46134da8e5c0d0f155d266
[ "Ruby" ]
11
Ruby
jazen/mongoid-plugins
c42ddb4c7455ec3c6bbb7024e43e7b3312d735a8
6d4d6e0997769306e1018cb3e8ca183d4291f858
refs/heads/master
<repo_name>Bdegraaf1234/TicTacToe<file_sep>/coordinate.h class coordinate { public: int x; int y; int getX() {return x;}; int getY() {return y;}; };<file_sep>/grid.cpp #include <iostream> #include <vector> #include <string> #include "grid.h" using namespace std; grid::grid() { for (int i(0); i < 3; i++) { for (int j(0); j < 3; j++) { fields[i][j] = '_'; } } } grid::~grid() { for (int i(0); i < 3; i++) { for (int j(0); j < 3; j++) { fields[i][j] = '_'; } } } void grid::display() { for (int i(0); i < 3; i++) { for (int j(0); j < 3; j++) { if (fields[i][j] == '_' && i == 2) cout << " "; else cout << fields[i][j]; if (j != 2) cout << "|"; else cout << endl; } } cout << endl; } void grid::enterChoice(int y, int x, bool isUser) { if (x < 0 || x > 2 || y < 0 || y > 2) { cout << "invalid choice provided\n"; } else { char insertChar; if (isUser) { insertChar = 'x'; } else { insertChar = 'o'; } if (fields[x][y] != '_' && fields[x][y] != ' ') { cout << "field was already chosen.\n"; } fields[x][y] = insertChar; } } coordinate grid::computeChoice() { coordinate toReturn; cout << "computing choice...\n\n"; for (size_t i = 0; i < 3; i++) { for (size_t j = 0; j < 3; j++) { if (fields[j][i] == '_' || fields[j][i] == ' ') { toReturn.x = i; toReturn.y = j; return toReturn; } } } return toReturn; } int grid::gameOver() { char players [2] = {'x', 'o'}; char player; for (size_t playerIndex = 0; playerIndex < 2; playerIndex++) { player = players[playerIndex]; if (fields[0][0] == player && fields[0][1] == player && fields[0][2] == player) { break; } if (fields[1][0] == player && fields[1][1] == player && fields[1][2] == player) { break; } if (fields[2][0] == player && fields[2][1] == player && fields[2][2] == player) { break; } if (fields[0][0] == player && fields[1][0] == player && fields[2][0] == player) { break; } if (fields[0][1] == player && fields[1][1] == player && fields[2][1] == player) { break; } if (fields[0][2] == player && fields[1][2] == player && fields[2][2] == player) { break; } if (fields[0][0] == player && fields[1][1] == player && fields[2][2] == player) { break; } if (fields[0][2] == player && fields[1][1] == player && fields[2][0] == player) { break; } player = 'a'; } if (player == 'o') { return 1; } if (player == 'x') { return 2; } return 0; }<file_sep>/grid.h #include "coordinate.h" class grid { public: char fields[3][3]; grid(); ~grid(); void display(); void enterChoice(int, int, bool); coordinate computeChoice(); int gameOver(); };<file_sep>/ticTacToe.cpp #include <iostream> #include <vector> #include <string> #include "grid.cpp" using namespace std; int main() { grid currentGrid = grid(); int x; int y; while (currentGrid.gameOver() == 0) { currentGrid.display(); cout << "provide x coordinate(0-2):"; cin >> x; cout << "provide y coordinate(0-2):"; cin >> y; cout << "\n"; currentGrid.enterChoice(x,y,true); if (currentGrid.gameOver() == 2) { cout << "user won!\n"; cin; break; } currentGrid.display(); coordinate pcChoice = currentGrid.computeChoice(); currentGrid.enterChoice(pcChoice.getX(),pcChoice.getY(),false); } currentGrid.display(); if (currentGrid.gameOver() == 1) { cout << "pc won!\n"; cin; } if (currentGrid.gameOver() == 0) { cout << "draw!\n"; cin; } }<file_sep>/coordinate.cpp int coordinate::getX() { return x; } int coordinate::getY() { return y; }
bad988efe8a67e997d89eacec57a442696fae037
[ "C++" ]
5
C++
Bdegraaf1234/TicTacToe
d90d97a5aa39d2f45624ea217bdc93eba92aaf31
c9727913e0178ace1eda417a0b048c4d13af362d
refs/heads/master
<repo_name>romanpras/InvadersGame<file_sep>/states/option.py from states.Invaders_Game import * from utils.font import * class OptionState(GameState): def __init__(self, game): super(OptionState, self).__init__(game) self.mainMenuState = None self.backgroundState = None self.spaceShipState = None self.OptionItems = ['Background', 'Spaceship', 'Back'] self.font = FontType("Ariel", 50, (255, 255, 255)) self.index = 0 self.inputTick = 0 """ Initialize the instance of state to move. """ def setMainMenuState(self, state): self.mainMenuState = state """ Initialize the instance of state to move. """ def setBackgroundState(self, state): self.backgroundState = state """ Initialize the instance of state to move. """ def setSpaceShipState(self, state): self.spaceShipState = state def update(self, gameTime): keys = pygame.key.get_pressed() if (keys[K_UP] or keys[K_DOWN]) and self.inputTick == 0: self.inputTick = 250 if keys[K_UP]: self.index -= 1 if self.index < 0: self.index = len(self.OptionItems) - 1 elif keys[K_DOWN]: self.index += 1 if self.index == len(self.OptionItems): self.index = 0 elif self.inputTick > 0: self.inputTick -= gameTime if self.inputTick < 0: self.inputTick = 0 if keys[K_RETURN]: if self.index == 2: self.game.changeState(self.mainMenuState) # back to main menu elif self.index == 0: self.game.changeState(self.backgroundState) # go to background state elif self.index == 1: self.game.changeState(self.spaceShipState) # go to spaceship state def draw(self, surface): self.font.center(surface, "Options", 48) count = 0 y = surface.get_rect().height - len(self.OptionItems) * 110 for item in self.OptionItems: itemText = " " if count == self.index: itemText = "> " itemText += item self.font.draw(surface, itemText, 300, y) y += 50 count += 1<file_sep>/main/InvadersApp.py # imports from states.background import BackgroundState from states.exit import ExitState from states.interstitial import * from states.menu import MainMenuState from states.play_game import PlayGameState from states.option import OptionState from states.spaceship import SpaceShipState """ ---------------------------------------------------------------------------------------------------- Application Entry Point main entry point to the application. Sets up the objects and starts the main loop. ---------------------------------------------------------------------------------------------------- """ SCREEN_W = 800 SCREEN_H = 600 invadersGame = InvadersGame("Invaders", SCREEN_W, SCREEN_H) mainMenuState = MainMenuState(invadersGame) gameOverState = InterstitialState(invadersGame, 'G A M E O V E R !', 3000, mainMenuState) exitState = ExitState(invadersGame,mainMenuState) playGameState = PlayGameState(invadersGame, gameOverState , mainMenuState,exitState) exitState.setGameState(playGameState) getReadyState = InterstitialState(invadersGame, 'Get Ready!', 2000, playGameState) mainMenuState.setPlayState(getReadyState) optionState = OptionState(invadersGame) getOptionState = InterstitialState(invadersGame, 'Enter To Options!', 2000, optionState) mainMenuState.setOptionState(getOptionState) getMainMenuState = InterstitialState(invadersGame, 'Back To Main Menu!', 2000, mainMenuState) optionState.setMainMenuState(getMainMenuState) backgroundState = BackgroundState(invadersGame) getBackgroundState = InterstitialState(invadersGame, 'Go To Backgrounds!', 2000, backgroundState) optionState.setBackgroundState(getBackgroundState) backgroundState.setOptionState(getOptionState) spaceShipState = SpaceShipState(invadersGame) getSpaceShipState = InterstitialState(invadersGame, 'Go To Spaceships!', 2000, spaceShipState) optionState.setSpaceShipState(getSpaceShipState) spaceShipState.setOptionState(getOptionState) invadersGame.run(mainMenuState) <file_sep>/states/exit.py import pygame from states.Invaders_Game import GameState from states.interstitial import InterstitialState from utils.font import FontType class ExitState(GameState): def __init__(self, game , mainMenuState): super(ExitState, self).__init__(game) self.mainMenuState = mainMenuState self.gameState = None self.font = FontType("Ariel", 50, (255, 255, 255)) self.fontTitle = FontType("Ariel", 50, (255, 255, 255)) self.index = 0 self.inputTick = 0 self.menuItems = ['Yes', 'No'] def setGameState(self, state): self.gameState = state def update(self, gameTime): keys = pygame.key.get_pressed() if (keys[pygame.K_UP] or keys[pygame.K_DOWN]) and self.inputTick == 0: self.inputTick = 250 if keys[pygame.K_UP]: self.index -= 1 if self.index < 0: self.index = len(self.menuItems) - 1 elif keys[pygame.K_DOWN]: self.index += 1 if self.index == len(self.menuItems): self.index = 0 elif self.inputTick > 0: self.inputTick -= gameTime if self.inputTick < 0: self.inputTick = 0 if keys[pygame.K_RETURN]: if self.index == 0: exitFromGame = InterstitialState(self.game, 'Exit From GAME', 2000, self.mainMenuState) self.game.changeState(exitFromGame) self.gameState.initialise() elif self.index == 1: self.game.changeState(self.gameState) def draw(self, surface): self.fontTitle.center(surface, "Are you sure to exit from the game?", 100) count = 0 y = surface.get_rect().height - len(self.menuItems) * 150 for item in self.menuItems: itemText = " " if count == self.index: itemText = "> " itemText += item self.font.draw(surface, itemText, 350, y) y += 50 count += 1<file_sep>/states/interstitial.py from states.Invaders_Game import * from utils.font import * """ ---------------------------------------------------------------------------------------------------- InterstitialState Displays a message between screens. Can be used for ''Game over'' or ''Get ready'' style messages ---------------------------------------------------------------------------------------------------- """ class InterstitialState(GameState): def __init__(self, game, msg, waitTimeMs, nextState): super(InterstitialState, self).__init__(game) self.nextState = nextState self.font = FontType("Ariel", 50, (255, 255, 255)) self.message = msg self.previousTimer = waitTimeMs self.waitTimer = waitTimeMs def update(self, gameTime): self.waitTimer -= gameTime if self.waitTimer < 0: self.game.changeState(self.nextState) self.waitTimer = self.previousTimer def draw(self, surface): self.font.center(surface, self.message, surface.get_rect().height / 2) <file_sep>/objects/collision.py # imports from states.play_game import * from states.interstitial import * class ExplosionModel: def __init__(self, x, y, maxFrames, speed, nextState=None): self.x = x self.y = y self.maxFrames = maxFrames self.speed = speed self.initialSpeed = speed self.frame = 0 self.nextState = nextState class ExplosionModelList: def __init__(self, game): self.explosions = [] self.game = game def add(self, explosion, nextState=None): x, y, frames, speed = explosion exp = ExplosionModel(x, y, frames, speed, nextState) self.explosions.append(exp) def cleanUp(self): killList = [] for e in self.explosions: if e.frame == e.maxFrames: killList.append(e) nextState = None for e in killList: if nextState is None and e.nextState is not None: nextState = e.nextState self.explosions.remove(e) if nextState is not None: self.game.changeState(nextState) class ExplosionView: def __init__(self, explosions, explosionImg, width, height): self.image = pygame.image.load(explosionImg) self.image.set_colorkey((255, 0, 255)) self.explosions = explosions self.width = width self.height = height def render(self, surface): for e in self.explosions: surface.blit(self.image, (e.x, e.y, self.width, self.height), (e.frame * self.width, 0, self.width, self.height)) class ExplosionController: def __init__(self, game): self.list = ExplosionModelList(game) def update(self, gameTime): for e in self.list.explosions: e.speed -= gameTime if e.speed < 0: e.speed += e.initialSpeed e.frame += 1 self.list.cleanUp() class CollisionController: def __init__(self, game, swarm, player, explosionController, playState): self.swarm = swarm self.player = player self.game = game self.BulletController = player.bullets self.EnemyBullets = swarm.bullets self.expCtrl = explosionController self.playGameState = playState self.alienDeadSound = pygame.mixer.Sound('../media/aliendie.wav') self.playerDie = pygame.mixer.Sound('../media/playerdie.wav') def update(self, gameTime): aliens = [] bullets = [] for b in self.BulletController.bullets: if bullets.count(b) > 0: continue for inv in self.swarm.invaders: if inv.hit(b.x + 3, b.y + 3, 8, 12): aliens.append(inv) bullets.append(b) break for b in bullets: self.BulletController.removeBullet(b) for inv in aliens: self.swarm.invaders.remove(inv) self.player.model.score += (10 * (inv.alientype + 1)) self.expCtrl.list.add((inv.x, inv.y, 6, 50)) self.alienDeadSound.play() playerHit = False for b in self.EnemyBullets.bullets: if self.player.hit(b.x + 3, b.y + 3, 8, 12): self.player.model.lives -= 1 playerHit = True break if self.swarm.collision: self.playerDie.play() self.playGameState.initialise() tryAgainMessage = InterstitialState(self.game, 'Try Again!', 2000, self.playGameState) self.game.changeState(tryAgainMessage) if playerHit: self.EnemyBullets.clear() self.player.bullets.clear() if self.player.model.lives > 0: self.player.pause(True) getReadyState = InterstitialState(self.game, 'Get Ready!', 2000, self.playGameState) self.expCtrl.list.add((self.player.model.x, self.player.model.y, 6, 50), getReadyState) self.playerDie.play() <file_sep>/states/Invaders_Game.py import pygame, os, sys from pygame.locals import * """ ---------------------------------------------------------------------------------------------------- GameState The game state class defines an interface that is used by the InvadersGame class. Each state manages a particular function of the game. For example; main menu, the actual game play, and interstitial screens. ---------------------------------------------------------------------------------------------------- """ class GameState(object): """ Initialise the Game state class. Each sub-type must call this method. Takes one parameter, which is the game instance. """ def __init__(self, game): self.game = game """ Called by the game when entering the state for the first time. """ def onEnter(self, previousState): pass """ Called by the game when leaving the state. """ def onExit(self): pass """ Called by the game allowing the state to update itself. The game time (in milliseconds) since the last call is passed. """ def update(self, gameTime): pass """ Called by the game allowing the state to draw itself. The surface that is passed is the current drawing surface. """ def draw(self, surface): pass """ ---------------------------------------------------------------------------------------------------- Invaders Game Basic game object-oriented framework for the Invaders. Users create 'states' that alter what is being displayed on-screen / updated at any particular time. ---------------------------------------------------------------------------------------------------- """ class InvadersGame(object): """ Initialise the Invaders Game class. """ def __init__(self, gameName, width, height): pygame.init() pygame.display.set_caption(gameName) icon_game = pygame.image.load('../media/ship2.png') pygame.display.set_icon(icon_game) self.gameSound = pygame.mixer.Sound('../media/background_music.wav') self.gameSound.play(20) self.fpsClock = pygame.time.Clock() self.main_window = pygame.display.set_mode((width, height)) self.background = pygame.transform.scale(pygame.image.load("../media/background-black.png"), (width, height)) self.currentState = None self.spaceship = '../media/ship1.png' """ Change the current state. If the newState is 'None' then the game will terminate. """ def changeState(self, newState): if self.currentState is not None: self.currentState.onExit() if newState is None: pygame.quit() sys.exit() oldState = self.currentState self.currentState = newState newState.onEnter(oldState) """ Run the game. Initial state must be supplied. """ def run(self, initialState): self.changeState(initialState) while True: for event in pygame.event.get(): if event.type == QUIT: pygame.quit() sys.exit() gameTime = self.fpsClock.get_time() if self.currentState is not None: self.currentState.update(gameTime) self.main_window.blit(self.background, (0, 0)) if self.currentState is not None: self.currentState.draw(self.main_window) pygame.display.update() self.fpsClock.tick(60) <file_sep>/states/background.py from states.Invaders_Game import * from utils.font import * """ ---------------------------------------------------------------------------------------------------- Background class which controls the backgrounds of all game screens. ---------------------------------------------------------------------------------------------------- """ class BackgroundState(GameState): def __init__(self, game): super(BackgroundState, self).__init__(game) self.optionState = None self.font = FontType("Ariel", 50, (255, 255, 255)) self.font_text = FontType("Ariel", 25, (255, 255, 255)) self.index = 0 self.inputTick = 0 self.OptionItems = ['Press Enter to select your background'] self.backgrounds = ['../media/background_space.jpg', '../media/background_space_blue.png', '../media/background_space_purple.jpg', '../media/background-black.png'] self.myBackgrounds = self.loadBackgrounds(self.backgrounds) SCREEN_W = 800 SCREEN_H = 600 self.surface = pygame.display.set_mode((SCREEN_W, SCREEN_H)) """ Initialize the instance of state to move. """ def setOptionState(self, state): self.optionState = state """ Load array of background and resized them for the game. """ @staticmethod def loadBackgrounds(backgrounds): resized_backgrounds = [] for background in backgrounds: pic = pygame.image.load(background) pic = pygame.transform.scale(pic, (400, 300)) resized_backgrounds.append(pic) return resized_backgrounds def update(self, gameTime): keys = pygame.key.get_pressed() if (keys[K_LEFT] or keys[K_RIGHT]) and self.inputTick == 0: self.inputTick = 250 if keys[K_LEFT]: self.index -= 1 self.draw(self.surface) if self.index < 0: self.index = len(self.myBackgrounds) - 1 elif keys[K_RIGHT]: self.index += 1 if self.index == len(self.myBackgrounds): self.index = 0 self.draw(self.surface) elif self.inputTick > 0: self.inputTick -= gameTime if self.inputTick < 0: self.inputTick = 0 if keys[K_RETURN]: self.game.changeState(self.optionState) # Exit the game self.game.background = pygame.transform.scale(pygame.image.load(self.backgrounds[self.index]), (800, 600)) def draw(self, surface): self.font.center(surface, "Background", 48) surface.blit(self.myBackgrounds[self.index], (200, 150)) surface.blit(pygame.transform.scale(pygame.image.load('../media/right_arrow.png'), (70, 70)), (680, 250)) surface.blit(pygame.transform.scale(pygame.image.load('../media/left_arrow.png'), (70, 70)), (60, 250)) y = surface.get_rect().height - len(self.OptionItems) * 110 self.font_text.draw(surface, self.OptionItems[0], 250, y) <file_sep>/states/spaceship.py from states.Invaders_Game import * from utils.font import * """ ---------------------------------------------------------------------------------------------------- SpaceShip class which controls the ship that you want to choice in the game. ---------------------------------------------------------------------------------------------------- """ class SpaceShipState(GameState): def __init__(self, game): super(SpaceShipState, self).__init__(game) SCREEN_W = 800 SCREEN_H = 600 self.optionState = None self.font = FontType("Ariel", 50, (255, 255, 255)) self.font_text = FontType("Ariel", 25, (255, 255, 255)) self.index = 0 self.inputTick = 0 self.OptionItems = ['Press Enter to select your spaceship'] self.spaceships = ['../media/ship1.png', '../media/ship2.png', '../media/ship3.png', '../media/ship4.png', '../media/ship5.png', '../media/ship6.png'] self.mySpaceships = self.loadSpaceships(self.spaceships) self.surface = pygame.display.set_mode((SCREEN_W, SCREEN_H)) """ Initialize the instance of state to move. """ def setOptionState(self, state): self.optionState = state """ Load array of ships and resized them for the game. """ @staticmethod def loadSpaceships(spaceships): resized_backgrounds = [] for spaceship in spaceships: pic = pygame.image.load(spaceship) pic = pygame.transform.scale(pic, (100, 100)) resized_backgrounds.append(pic) return resized_backgrounds def update(self, gameTime): keys = pygame.key.get_pressed() if (keys[K_LEFT] or keys[K_RIGHT]) and self.inputTick == 0: self.inputTick = 250 if keys[K_LEFT]: self.index -= 1 self.draw(self.surface) if self.index < 0: self.index = len(self.mySpaceships) - 1 elif keys[K_RIGHT]: self.index += 1 if self.index == len(self.mySpaceships): self.index = 0 self.draw(self.surface) elif self.inputTick > 0: self.inputTick -= gameTime if self.inputTick < 0: self.inputTick = 0 if keys[K_RETURN]: self.game.changeState(self.optionState) # go to option state self.game.spaceship = self.spaceships[self.index] def draw(self, surface): self.font.center(surface, "Spaceship", 48) surface.blit(self.mySpaceships[self.index], (350, 250)) surface.blit(pygame.transform.scale(pygame.image.load('../media/right_arrow.png'), (70, 70)), (680, 250)) surface.blit(pygame.transform.scale(pygame.image.load('../media/left_arrow.png'), (70, 70)), (60, 250)) y = surface.get_rect().height - len(self.OptionItems) * 110 self.font_text.draw(surface, self.OptionItems[0], 250, y) <file_sep>/objects/swarm.py # imports from objects.bullet import * """ ---------------------------------------------------------------------------------------------------- InvaderModel Representation of an alien lifeform. Boiled down to its basic attributes; position on the playing field, its type and the current animation frame. ---------------------------------------------------------------------------------------------------- """ class InvaderModel: def __init__(self, x, y, alientype): self.x = x self.y = y self.alientype = alientype self.animframe = 0 def flipframe(self): if self.animframe == 0: self.animframe = 1 else: self.animframe = 0 def hit(self, x, y, width, height): return x >= self.x and y >= self.y and x + width <= self.x + 32 and y + height <= self.y + 32 """ ---------------------------------------------------------------------------------------------------- Swarm The swarm updates all the alien invaders. It handles movement and collision detection. ---------------------------------------------------------------------------------------------------- """ class SwarmController: def __init__(self, scrwidth, offsety, initialframeticks): self.currentframecount = initialframeticks self.framecount = initialframeticks self.invaders = [] self.sx = -8 self.move_down = False self.alienslanded = False self.bullets = BulletController(200) # pixels per sec self.alienShooter = 3 # each 3rd alien (to start with) fires self.bulletDropTime = 2500 self.shootTimer = self.bulletDropTime # each bullet is fired in this ms interval self.currentShooter = 0 # current shooting alien self.collision = False self.positionInvaders(offsety) # Position the invaders in the swarm def reset(self, offsety, ticks): self.currentframecount = ticks self.framecount = ticks self.positionInvaders(offsety) def positionInvaders(self, offsety): for y in range(7): for x in range(10): invader = InvaderModel(160 + (x * 48) + 8, (y * 32) + offsety, y % 2) self.invaders.append(invader) def update(self, gameTime): self.bullets.update(gameTime) self.framecount -= gameTime movesideways = True if self.framecount < 0: if self.move_down: self.move_down = False movesideways = False self.sx *= -1 self.bulletDropTime -= 250 if self.bulletDropTime < 1000: self.bulletDropTime = 1000 self.currentframecount -= 100 if self.currentframecount < 200: # clamp the speed of the aliens to 200ms self.currentframecount = 200 for i in self.invaders: i.y += 32 self.framecount = self.currentframecount + self.framecount for i in self.invaders: i.flipframe() if movesideways: for i in self.invaders: i.x += self.sx x, y, width, height = self.getarea() if x <= 0 and self.sx < 0 or x + width >= 800 and self.sx > 0: if y + height >= 500: self.collision = True self.move_down = True self.shootTimer -= gameTime if self.shootTimer <= 0: self.shootTimer += self.bulletDropTime # reset the timer self.currentShooter += self.alienShooter self.currentShooter = self.currentShooter % len(self.invaders) shooter = self.invaders[self.currentShooter] x = shooter.x + 9 # bullet is 8 pixels y = shooter.y + 16 self.bullets.addBullet(x, y) def getarea(self): leftmost = 2000 rightmost = -2000 topmost = -2000 bottommost = 2000 for i in self.invaders: if i.x < leftmost: leftmost = i.x if i.x > rightmost: rightmost = i.x if i.y < bottommost: bottommost = i.y if i.y > topmost: topmost = i.y width = (rightmost - leftmost) + 32 height = (topmost - bottommost) + 32 return leftmost, bottommost, width, height """ ---------------------------------------------------------------------------------------------------- InvaderView Draws each invader in their position on the playing field with the correct frame. ---------------------------------------------------------------------------------------------------- """ class InvaderView: def __init__(self, swarm, imgpath): self.image = pygame.image.load(imgpath) self.swarm = swarm def render(self, surface): for i in self.swarm.invaders: surface.blit(self.image, (i.x, i.y, 32, 32), (i.animframe * 32, 32 * i.alientype, 32, 32)) <file_sep>/objects/bullet.py # imports import pygame, os, sys from pygame.locals import * """ ---------------------------------------------------------------------------------------------------- BulletModel A single bullet for the player. ---------------------------------------------------------------------------------------------------- """ class BulletModel: def __init__(self, x, y): self.x = x self.y = y def update(self, delta): self.y = self.y + delta """ ---------------------------------------------------------------------------------------------------- Bullet Manager Manages the update for each bullet. ---------------------------------------------------------------------------------------------------- """ class BulletController: def __init__(self, speed): self.countdown = 0 self.bullets = [] self.speed = speed def clear(self): self.bullets[:] = [] def canFire(self): return self.countdown == 0 and len(self.bullets) < 3 def addBullet(self, x, y): self.bullets.append(BulletModel(x, y)) self.countdown = 1000 def removeBullet(self, bullet): self.bullets.remove(bullet) def update(self, gameTime): killList = [] if self.countdown > 0: self.countdown = self.countdown - gameTime else: self.countdown = 0 for b in self.bullets: b.update(self.speed * (gameTime / 1000.0)) if b.y < 0: killList.append(b) for b in killList: self.removeBullet(b) """ ---------------------------------------------------------------------------------------------------- BulletView Renders the bullets for the player's missiles. ---------------------------------------------------------------------------------------------------- """ class BulletView: def __init__(self, bulletController, imgpath): self.BulletController = bulletController self.image = pygame.image.load(imgpath) def render(self, surface): for b in self.BulletController.bullets: surface.blit(self.image, (b.x, b.y, 8, 8)) <file_sep>/objects/player.py # imports from objects.bullet import * from utils.font import * """ ---------------------------------------------------------------------------------------------------- PlayerModel The player model. ---------------------------------------------------------------------------------------------------- """ class PlayerModel: def __init__(self, x, y): self.x = x self.y = y self.lives = 3 self.score = 0 self.level = 1 self.speed = 100 # pixels per second """ ---------------------------------------------------------------------------------------------------- Player The tank at the bottom of the screen. ---------------------------------------------------------------------------------------------------- """ class PlayerController: def __init__(self, x, y): self.model = PlayerModel(x, y) self.isPaused = False self.bullets = BulletController(-200) # pixels per sec self.shootSound = pygame.mixer.Sound('../media/playershoot.wav') def pause(self, isPaused): self.isPaused = isPaused def update(self, gameTime): self.bullets.update(gameTime) if self.isPaused: return keys = pygame.key.get_pressed() if keys[K_RIGHT] and self.model.x < 800 - 32: self.model.x += (gameTime / 1000.0) * self.model.speed elif keys[K_LEFT] and self.model.x > 0: self.model.x -= (gameTime / 1000.0) * self.model.speed if keys[K_SPACE] and self.bullets.canFire(): x = self.model.x + 9 # bullet is 8 pixels y = self.model.y - 16 self.bullets.addBullet(x, y) self.shootSound.play() def hit(self, x, y, width, height): return x >= self.model.x and y >= self.model.y and x + width <= self.model.x + 32 and y + height <= self.model.y + 32 """ ---------------------------------------------------------------------------------------------------- PlayerView Renders the player tank. ---------------------------------------------------------------------------------------------------- """ class PlayerView: def __init__(self, player, imgpath): self.player = player self.image = pygame.image.load(imgpath) def render(self, surface): surface.blit(self.image, (self.player.model.x, self.player.model.y, 32, 32)) """ ---------------------------------------------------------------------------------------------------- PlayerLivesView Renders the number of lives left for the player. ---------------------------------------------------------------------------------------------------- """ class PlayerLivesView: def __init__(self, player, imgpath): self.player = player self.image = pygame.image.load(imgpath) self.font = FontType("david", 25, (255, 255, 255)) def render(self, surface): x = 8 for life in range(0, self.player.model.lives): surface.blit(self.image, (x, 8, 32, 32)) x += 40 self.font.center(surface, 'Score:' + ' ' + str(self.player.model.score), 10) self.font.draw(surface, 'Level:' + ' ' + str(self.player.model.level), 700, 10) if __name__ == '__main__': pygame.init() fpsClock = pygame.time.Clock() surface = pygame.display.set_mode((800, 600)) pygame.display.set_caption('Player Test') black = pygame.Color(0, 0, 0) player = PlayerController(0, 400) playerView = PlayerView(player, 'media/ship1.png') playerLivesView = PlayerLivesView(player, 'media/ship1.png') while True: for event in pygame.event.get(): if event.type == QUIT: pygame.quit() sys.exit() player.update(fpsClock.get_time()) surface.fill(black) playerView.render(surface) playerLivesView.render(surface) pygame.display.update() fpsClock.tick(60) <file_sep>/states/play_game.py from objects.collision import * from objects.player import * from objects.swarm import * from states.interstitial import InterstitialState class PlayGameState(GameState): def __init__(self, game, gameOverState , mainMenuState ,exitGameState): super(PlayGameState, self).__init__(game) self.controllers = None self.renderers = None self.player_controller = None self.swarm_controller = None self.swarmSpeed = 500 self.gameOverState = gameOverState self.mainMenuState = mainMenuState self.exitGameState = exitGameState self.exitMessage = FontType("Ariel", 50, (255, 255, 255)) self.initialise() def onEnter(self, previousState): self.player_controller.pause(False) def initialise(self): self.swarm_controller = SwarmController(800, 48, self.swarmSpeed) swarm_renderer = InvaderView(self.swarm_controller, '../media/monsters_anim.png') self.player_controller = PlayerController(0, 540) player_renderer = PlayerView(self.player_controller, self.game.spaceship) lives_renderer = PlayerLivesView(self.player_controller, self.game.spaceship) bullet_renderer = BulletView(self.player_controller.bullets, '../media/bullet.png') alienbullet_renderer = BulletView(self.swarm_controller.bullets, "../media/alienbullet.png") explosion_controller = ExplosionController(self.game) collision_controller = CollisionController(self.game, self.swarm_controller, self.player_controller , explosion_controller, self) explosion_view = ExplosionView(explosion_controller.list.explosions, '../media/explosion.png', 32, 32) self.renderers = [alienbullet_renderer, swarm_renderer, bullet_renderer, player_renderer, lives_renderer, explosion_view] self.controllers = [self.swarm_controller, self.player_controller, collision_controller, explosion_controller] def update(self, gameTime): self.renderers[3] = PlayerView(self.player_controller, self.game.spaceship) self.renderers[4] = PlayerLivesView(self.player_controller, self.game.spaceship) keys = pygame.key.get_pressed() if keys[K_ESCAPE]: self.game.changeState(self.exitGameState) # exitFromGame = InterstitialState(self.game, 'Exit From GAME', 2000, self.mainMenuState) # self.game.changeState(exitFromGame) for ctrl in self.controllers: ctrl.update(gameTime) if self.player_controller.model.lives == 0: self.game.changeState(self.gameOverState) self.initialise() if len(self.swarm_controller.invaders) == 0: self.swarmSpeed -= 50 if self.swarmSpeed < 100: self.swarmSpeed = 100 self.swarm_controller.reset(48, self.swarmSpeed) levelUpMessage = InterstitialState(self.game, 'Congratulations Level Up!', 2000, self) self.game.changeState(levelUpMessage) self.player_controller.model.level += 1 def draw(self, surface): for view in self.renderers: view.render(surface) <file_sep>/utils/font.py import pygame, os, sys class FontType: def __init__(self, fontName, fontSize, color): self.font = pygame.font.SysFont(fontName, fontSize) self.color = color def draw(self, surface, msg, x, y): title_text = self.font.render(msg, True, self.color) width = title_text.get_width() height = title_text.get_height() surface.blit(title_text, (x, y, width, height)) def center(self, surface, msg, distance_for_top): title_text = self.font.render(msg, True, self.color) half_width = surface.get_rect().width / 2 surface.blit(title_text, (half_width - title_text.get_width() // 2, distance_for_top)) <file_sep>/README.md # InvadersGame Space Invaders is a fixed shooter in which the player controls a spaceship by moving it horizontally across the bottom of the screen and firing at descending aliens. The aim is to defeat seven rows of ten aliens. The player uses the spaceship to explosion an alien he gets a score and the more aliens are defeated, the aliens' movement and the game's music both speed up. Defeating all the aliens on-screen brings level up difficult. The aliens try to destroy the players' spaceship by firing bullets as they approach the bottom of the screen. The game continues until all the aliens are defeated or if the alien reaches the bottom of the screen, then the game is over. The player can be disqualified up to 3 times and then there is an announcement of the end of the game. ### MVC Design Pattern The game incorporates a MVC design pattern for each object in the app. #### PlayerModel Includes attributes like coordinates ,lives, score, speed, and level. #### PlayerController * Have an instance of PlayerModel in order to update and change the model attributes. * Have an instance of Bullet Controller to update list of bullet model. #### PlayerView Have an instance of PlayerController to have an access to PlayerModel. ![image](https://user-images.githubusercontent.com/48810056/105578285-ada26000-5d87-11eb-95ce-97b07f372604.png) ## Main Menu ![menu_window](https://user-images.githubusercontent.com/48810056/105577978-aa0dd980-5d85-11eb-9786-c314b83c8df3.JPG) ## Background selection ![select_background](https://user-images.githubusercontent.com/48810056/105577941-64511100-5d85-11eb-864d-95487bb2bc4f.JPG) ## Spaceship selection ![select_spaceship](https://user-images.githubusercontent.com/48810056/105578007-e3dee000-5d85-11eb-9ceb-f1a5cad8abd4.JPG) ## Game Window ![game](https://user-images.githubusercontent.com/48810056/105578016-f22cfc00-5d85-11eb-9bcb-100840cdf981.JPG) ## Game window after selecting background and spaceship ![game2](https://user-images.githubusercontent.com/48810056/105578014-f1946580-5d85-11eb-97b3-20cb6935095e.JPG) <file_sep>/states/menu.py from states.Invaders_Game import * from utils.font import * class MainMenuState(GameState): def __init__(self, game): super(MainMenuState, self).__init__(game) self.playGameState = None self.optionGameState = None self.font = FontType("Ariel", 50, (255, 255, 255)) self.fontTitle = FontType("Ariel", 70, (255, 255, 255)) self.index = 0 self.inputTick = 0 self.menuItems = ['Start Game', 'Options', 'Quit'] def setPlayState(self, state): self.playGameState = state def setOptionState(self,state): self.optionGameState = state def update(self, gameTime): keys = pygame.key.get_pressed() if (keys[K_UP] or keys[K_DOWN]) and self.inputTick == 0: self.inputTick = 250 if keys[K_UP]: self.index -= 1 if self.index < 0: self.index = len(self.menuItems) -1 elif keys[K_DOWN]: self.index += 1 if self.index == len(self.menuItems): self.index = 0 elif self.inputTick > 0: self.inputTick -= gameTime if self.inputTick < 0: self.inputTick = 0 if keys[K_RETURN]: if self.index == 2: self.game.changeState(None) # Exit the game elif self.index == 1: self.game.changeState(self.optionGameState) elif self.index == 0: self.game.changeState(self.playGameState) def draw(self, surface): self.fontTitle.center(surface, "Welcome To Invaders!", 100) count = 0 y = surface.get_rect().height - len(self.menuItems)*110 for item in self.menuItems: itemText = " " if count == self.index: itemText = "> " itemText += item self.font.draw(surface, itemText, 300, y) y += 50 count += 1
bb5c6dfc10b0cac60d3fcc7796877753814605e2
[ "Markdown", "Python" ]
15
Python
romanpras/InvadersGame
b5b14c66f761df7b5951ae6e83462fdfe979000e
0c545be5e3eca7f2b01e0adfd7618136b3f5f02b
refs/heads/master
<file_sep>from django.db import models class VoteModel(models.Model): class Meta: abstract = True votes = models.PositiveIntegerField(default=0) sum_of_rates = models.PositiveIntegerField(default=0) def upvote(self, rate): self.votes += 1 self.sum_of_rates += rate self.save() @property def average(self): if self.votes: return round((self.sum_of_rates / self.votes), 2) else: return 'Not rated yet' class CarManager(models.Manager): def filter_by_popularity(self): return super().get_queryset().order_by('-votes') class Car(VoteModel): make = models.CharField(max_length=120) model = models.CharField(max_length=120) objects = CarManager() def __str__(self): return '%s %s' % (self.make, self.model) <file_sep>from django.test import TestCase from ..models import Car class VoteModelTestCase(TestCase): def setUp(self): self.car = Car.objects.create(make="TOYOTA", model="PREVIA") def test_upvote(self): self.car.upvote(5) self.car.upvote(3) self.assertEqual(self.car.votes, 2) self.assertEqual(self.car.sum_of_rates, 8) def test_average(self): self.car.upvote(5) self.car.upvote(2) self.assertEqual(self.car.average, 3.5) class CarManagerTestCase(TestCase): def setUp(self): c1 = Car.objects.create(make="TOYOTA", model="PREVIA") c2 = Car.objects.create(make="PORSCHE", model="CAYENNE") c3 = Car.objects.create(make="DODGE", model="CARAVAN") # votes c3.upvote(7) c3.upvote(4) c3.upvote(7) c1.upvote(4) c1.upvote(5) def test_filter_by_popularity(self): popular_cars = Car.objects.filter_by_popularity() rates = [] for car in popular_cars: rates.append(car.votes) self.assertEqual(rates, [3, 2, 0]) <file_sep>from django.test import TestCase from django.urls import reverse from rest_framework import status from ..models import Car GET_POST_CARS = reverse('cars') POST_RATE = reverse('rate') GET_POPULARS = reverse('populars') class CreateCarViewTest(TestCase): def setUp(self): self.c1 = Car.objects.create(make="TOYOTA", model="PREVIA") self.c2 = Car.objects.create(make="PORSCHE", model="CAYENNE") def test_get_object_list(self): response = self.client.get(GET_POST_CARS) self.assertEqual(response.status_code, status.HTTP_200_OK) def test_post_object_success(self): make = 'HONDA' model = 'Odyssey' body = { 'make': make, 'model': model, } response = self.client.post(GET_POST_CARS, body) self.assertEqual(response.status_code, status.HTTP_201_CREATED) created_car = Car.objects.get(make=make, model=model) self.assertIn(created_car, Car.objects.all()) def test_post_object_not_exists_in_external_API(self): body = { 'make': self.c2.make, 'model': self.c2.model, } response = self.client.post(GET_POST_CARS, body) self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND) self.assertEqual(Car.objects.count(), 2) def test_post_object_no_params(self): body = {} response = self.client.post(GET_POST_CARS, body) self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST) self.assertEqual(Car.objects.count(), 2) class RateCarViewTest(TestCase): def setUp(self): self.car = Car.objects.create(make="TOYOTA", model="PREVIA") def test_vote_success(self): body = { 'car_id': self.car.pk, 'rate': 3 } response = self.client.post(POST_RATE, body) self.assertEqual(response.status_code, status.HTTP_200_OK) updated_car = Car.objects.get(pk=self.car.pk) self.assertEqual(updated_car.votes, 1) self.assertEqual(updated_car.sum_of_rates, 3) def test_vote_no_params(self): body = {} response = self.client.post(POST_RATE, body) self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST) def test_vote_wrong_params(self): body = { 'car_id': 'STRING', 'rate': 'STRING', } response = self.client.post(POST_RATE, body) self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST) def test_wrong_vote_note(self): body = { 'car_id': self.car.pk, 'rate': 7, } response = self.client.post(POST_RATE, body) self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST) def test_object_not_exists(self): body = { 'car_id': 2, 'rate': 5, } response = self.client.post(POST_RATE, body) self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND) class PopularCarsView(TestCase): def test_get_popular_cars(self): self.c1 = Car.objects.create(make="TOYOTA", model="PREVIA") self.c2 = Car.objects.create(make="FORD", model="FOCUS") self.c3 = Car.objects.create(make="AUDI", model="A4") self.c2.upvote(3) self.c2.upvote(5) self.c3.upvote(1) response = self.client.get(GET_POPULARS) self.assertEqual(response.status_code, status.HTTP_200_OK) def test_no_cars_in_db(self): response = self.client.get(GET_POPULARS) self.assertEqual(response.status_code, status.HTTP_200_OK) result = [r for r in response.data] self.assertEqual(result, []) <file_sep>import requests def fetch_car_models(car_make): url = 'https://vpic.nhtsa.dot.gov/api/vehicles/getmodelsformake/' + car_make + '?format=json' r = requests.get(url) car_models = r.json() return car_models['Results']<file_sep>from django.contrib import admin from .models import Car class CarAdmin(admin.ModelAdmin): pass admin.site.register(Car, CarAdmin) <file_sep># Cars Django Django app which allows you to search in [external API]("https://vpic.nhtsa.dot.gov/api") for car make and model, updating database with cars, voting for them and viewing by popularity #### App demo (deployed on Heroku): [App demo](https://cars-api-karol.herokuapp.com/) #### Installation: 1. Build docker image sudo docker-compose build 2. Run migrations for first time sudo docker-compose run web python3 manage.py migrate 3. Run application sudo docker-compose up #### Running tests: sudo docker-compose run web python3 manage.py test <file_sep>import os from .base import * import dj_database_url db_from_env = dj_database_url.config() DATABASES['default'].update(db_from_env) DATABASES['default']['CONN_MAX_AGE'] = 500 DEBUG = os.environ.get('DEBUG', False) SECRET_KEY = os.environ.get('SECRET_KEY', '')<file_sep>from django.shortcuts import render from rest_framework.views import APIView from rest_framework.response import Response from .models import Car from .services import fetch_car_models from .serializers import CarSerializer from rest_framework import generics, status def index(request): return render(request, 'home.html') def render_list_cars(request, msg, status=status.HTTP_200_OK): cars = Car.objects.all() context = {'cars': cars, 'message': msg} return render(request, 'list.html', context=context, status=status) def render_add_template(request, msg='', status=status.HTTP_200_OK): context = {'message': msg} return render(request, 'add.html', context=context, status=status) class CreateCarView(APIView): def get(self, request): cars_serializer = CarSerializer(Car.objects.all(), many=True) return Response(cars_serializer.data) def post(self, request, *args, **kwargs): cars_serializer = CarSerializer(data=request.data) car_make = str.upper(request.POST.get('make', '')).rstrip() car_model = request.POST.get('model', '').rstrip() if car_make: car_models = fetch_car_models(car_make) for car in car_models: if car['Model_Name'].rstrip() == car_model and cars_serializer.is_valid(): cars_serializer.save() return Response(cars_serializer.data, status=status.HTTP_201_CREATED) else: return Response(status=status.HTTP_400_BAD_REQUEST) return Response(status=status.HTTP_404_NOT_FOUND) class RateCarView(APIView): def post(self, request, *args, **kwargs): car_id = request.POST.get('car_id', '') rate = request.POST.get('rate', '') if not car_id.isnumeric() or not rate.isnumeric(): return Response(status=status.HTTP_400_BAD_REQUEST) if int(rate) not in [1, 2, 3, 4, 5]: return Response(status=status.HTTP_400_BAD_REQUEST) try: car = Car.objects.get(pk=car_id) car.upvote(int(rate)) return Response('Voted for a car', status=status.HTTP_200_OK) except Car.DoesNotExist: return Response('Car not found', status=status.HTTP_404_NOT_FOUND) class PopularCarsView(generics.ListAPIView): serializer_class = CarSerializer def get_queryset(self): qs = Car.objects.filter_by_popularity() return qs
6261c8f98c7993f13be4a8cc5c0cd812f54e74ee
[ "Markdown", "Python" ]
8
Python
Emu-Emax/carsDjango
83d73c20f13225f2dc1959760f8fd92551c1ea19
3eb74f07f4f16d4759e97c8477df820268646e5e
refs/heads/main
<repo_name>Mark-Walen/VueProgramm<file_sep>/src/main.js import { createApp } from 'vue' import App from './App.vue' import router from './router' import installElementPlus from './plugins/element.js' import './assets/font/iconfont.css' import './assets/css/global.css' import axios from 'axios' // 配置请求根路径 axios.defaults.baseURL = 'http://localhost:3000' axios.interceptors.request.use(config => { config.headers.Authorization = window.sessionStorage.getItem('token') return config }) const app = createApp(App) app.config.globalProperties.$http = axios installElementPlus(app) app.use(router).mount('#app') <file_sep>/src/plugins/element.js import { ElButton, ElForm, ElFormItem, ElInput, ElMessage, ElContainer, ElHeader, ElAside, ElMain, ElMenu, ElSubmenu, ElMenuItemGroup, ElMenuItem, ElBreadcrumb, ElBreadcrumbItem, ElCard, ElRow, ElCol, ElTable, ElTableColumn, ElSwitch, ElTooltip, ElPagination, ElDialog, ElMessageBox } from 'element-plus' import lang from 'element-plus/lib/locale/lang/zh-cn' import locale from 'element-plus/lib/locale' export default (app) => { locale.use(lang) app.use(ElButton) .use(ElFormItem) .use(ElForm) .use(ElInput) .use(ElContainer) .use(ElHeader) .use(ElAside) .use(ElMain) .use(ElMenu) .use(ElSubmenu) .use(ElMenuItemGroup) .use(ElMenuItem) .use(ElBreadcrumb) .use(ElBreadcrumbItem) .use(ElCard) .use(ElRow) .use(ElCol) .use(ElTable) .use(ElTableColumn) .use(ElSwitch) .use(ElTooltip) .use(ElPagination) .use(ElDialog) .use(ElMessageBox) app.config.globalProperties.$message = ElMessage }
9e2b44ccd43516159917c1de9144e0d179c6f4f9
[ "JavaScript" ]
2
JavaScript
Mark-Walen/VueProgramm
34f91ea6d77543cc7c8a0464659ad66763f4865f
ea6212f469dc2576806438f9f608e147874e7d28
refs/heads/master
<file_sep> package com.capgemini.ec.gateway.model; import org.apache.commons.lang.builder.ToStringBuilder; public class AssignedTo { private String link; private String value; public String getLink() { return link; } public void setLink(String link) { this.link = link; } public String getValue() { return value; } public void setValue(String value) { this.value = value; } @Override public String toString() { return new ToStringBuilder(this).append("link", link).append("value", value).toString(); } } <file_sep>package com.capgemini.ec.gateway.model; import java.util.Map; public class Request { public Map<String, String> sysParmQuery; public Map<String, String> sysParmFields; public Map<String, String> sysParmLimit; public Map<String, String> getSysParmQuery() { return sysParmQuery; } public void setSysParmQuery(Map<String, String> sysParmQuery) { this.sysParmQuery = sysParmQuery; } public Map<String, String> getSysParmFields() { return sysParmFields; } public void setSysParmFields(Map<String, String> sysParmFields) { this.sysParmFields = sysParmFields; } public Map<String, String> getSysParmLimit() { return sysParmLimit; } public void setSysParmLimit(Map<String, String> sysParmLimit) { this.sysParmLimit = sysParmLimit; } @Override public String toString() { return "Request [sysParmQuery=" + sysParmQuery + ", sysParmFields=" + sysParmFields + ", sysParmLimit=" + sysParmLimit + "]"; } } <file_sep>server.port=8088 serviceNow.url=https://capgeminiukplcdemo10.service-now.com/api/now/table/incident accept=application/json contentType=application/json authorization=Basic d2ViLkFQSTp3ZWIuQVBJ CAMPARI_CLIENT_URL=https://capgeminiukplcdemo10.service-now.com INC_BASE_URL=/api/now/table/incident<file_sep>package com.capgemini.ec.gateway.model; public class IncidentInfo extends Request { private String client; private String system; public String getClient() { return client; } public void setClient(String client) { this.client = client; } public String getSystem() { return system; } public void setSystem(String system) { this.system = system; } @Override public String toString() { return "IncidentInfo [client=" + client + ", system=" + system + ", sysParmQuery=" + sysParmQuery + ", sysParmFields=" + sysParmFields + ", sysParmLimit=" + sysParmLimit + "]"; } } <file_sep>package com.capgemini.ec.gateway.model; public class UpdateDetails { } <file_sep>package com.capgemini.ec.gateway.model; import java.util.List; public class CreateResponse { public static Response createResponse(String message, List<String> errors) { Response response = new Response(); response.setMessage(message); ResponseErrors responseError; for (String error : errors) { responseError = new ResponseErrors(); responseError.setError(error); response.addErrorsItem(responseError); } return response; } } <file_sep> package com.capgemini.ec.gateway.model; import org.codehaus.jackson.annotate.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonInclude.Include; @JsonIgnoreProperties(ignoreUnknown = true) @JsonInclude(value=Include.NON_EMPTY) //@JsonInclude(value=Include.NON_EMPTY) public class Result { private String promoted_by; private String parent; private String caused_by; private String watch_list; private UTenantSubcategory u_tenant_subcategory; private String upon_reject; private String sys_updated_on; private String approval_history; private String number; private String proposed_by; private String u_contact_attempt; private String u_security_type; private String lessons_learned; private String state; private String sys_created_by; private String knowledge; private String order; private CmdbCI cmdb_ci; private String delivery_plan; private String impact; private String active; private String work_notes_list; private String u_vendor; private String priority; private String sys_domain_path; private String business_duration; private String group_list; private String u_copied_from; private String u_template; private String approval_set; private String u_security_related; private String major_incident_state; private String short_description; private String correlation_display; private String delivery_task; private String work_start; private String trigger_rule; private String additional_assignee_list; private String notify; private String service_offering; private String sys_class_name; private ClosedBy closed_by; private String follow_up; private String parent_incident; private String reopened_by; private String reassignment_count; private AssignedTo assigned_to; private String sla_due; private String comments_and_work_notes; private UTenantCategory u_tenant_category; private String u_tenant_resolution_code; private String escalation; private String upon_approval; private String correlation_id; private String timeline; private String u_vendor_ticket_number; private String made_sla; private String promoted_on; private String child_incidents; private String hold_reason; private ResolvedBy resolved_by; private String sys_updated_by; private OpenedBy opened_by; private String user_input; private String sys_created_on; private SysDomain sys_domain; private String proposed_on; private String actions_taken; private TaskFor task_for; private String calendar_stc; private String closed_at; private String u_sd2sd_interface_type; private BusinessService business_service; private String business_impact; private String rfc; private String time_worked; private String expected_start; private String opened_at; private String work_end; private CallerId caller_id; private String reopened_time; private String resolved_at; private String u_interface_type; private String work_notes; private AssignmentGroup assignment_group; private String business_stc; private String cause; private String description; private String calendar_duration; private String u_sd2sd_external_system; private String close_notes; private String sys_id; private String contact_type; private String incident_state; private String urgency; private String problem_id; private Company company; private String activity_due; private String severity; private String overview; private String comments; private String approval; private String u_environment; private String due_date; private String sys_mod_count; private String u_affected_user; private String reopen_count; private String sys_tags; private String u_external_system; private String u_knowledge_article; private String location; private String u_sd2sd_service_provider; public String getPromoted_by() { return promoted_by; } public void setPromoted_by(String promoted_by) { this.promoted_by = promoted_by; } public String getParent() { return parent; } public void setParent(String parent) { this.parent = parent; } public String getCaused_by() { return caused_by; } public void setCaused_by(String caused_by) { this.caused_by = caused_by; } public String getWatch_list() { return watch_list; } public void setWatch_list(String watch_list) { this.watch_list = watch_list; } public UTenantSubcategory getU_tenant_subcategory() { return u_tenant_subcategory; } public void setU_tenant_subcategory(UTenantSubcategory u_tenant_subcategory) { this.u_tenant_subcategory = u_tenant_subcategory; } public String getUpon_reject() { return upon_reject; } public void setUpon_reject(String upon_reject) { this.upon_reject = upon_reject; } public String getSys_updated_on() { return sys_updated_on; } public void setSys_updated_on(String sys_updated_on) { this.sys_updated_on = sys_updated_on; } public String getApproval_history() { return approval_history; } public void setApproval_history(String approval_history) { this.approval_history = approval_history; } public String getNumber() { return number; } public void setNumber(String number) { this.number = number; } public String getProposed_by() { return proposed_by; } public void setProposed_by(String proposed_by) { this.proposed_by = proposed_by; } public String getU_contact_attempt() { return u_contact_attempt; } public void setU_contact_attempt(String u_contact_attempt) { this.u_contact_attempt = u_contact_attempt; } public String getU_security_type() { return u_security_type; } public void setU_security_type(String u_security_type) { this.u_security_type = u_security_type; } public String getLessons_learned() { return lessons_learned; } public void setLessons_learned(String lessons_learned) { this.lessons_learned = lessons_learned; } public String getState() { return state; } public void setState(String state) { this.state = state; } public String getSys_created_by() { return sys_created_by; } public void setSys_created_by(String sys_created_by) { this.sys_created_by = sys_created_by; } public String getKnowledge() { return knowledge; } public void setKnowledge(String knowledge) { this.knowledge = knowledge; } public String getOrder() { return order; } public void setOrder(String order) { this.order = order; } public CmdbCI getCmdb_ci() { return cmdb_ci; } public void setCmdb_ci(CmdbCI cmdb_ci) { this.cmdb_ci = cmdb_ci; } public String getDelivery_plan() { return delivery_plan; } public void setDelivery_plan(String delivery_plan) { this.delivery_plan = delivery_plan; } public String getImpact() { return impact; } public void setImpact(String impact) { this.impact = impact; } public String getActive() { return active; } public void setActive(String active) { this.active = active; } public String getWork_notes_list() { return work_notes_list; } public void setWork_notes_list(String work_notes_list) { this.work_notes_list = work_notes_list; } public String getU_vendor() { return u_vendor; } public void setU_vendor(String u_vendor) { this.u_vendor = u_vendor; } public String getPriority() { return priority; } public void setPriority(String priority) { this.priority = priority; } public String getSys_domain_path() { return sys_domain_path; } public void setSys_domain_path(String sys_domain_path) { this.sys_domain_path = sys_domain_path; } public String getBusiness_duration() { return business_duration; } public void setBusiness_duration(String business_duration) { this.business_duration = business_duration; } public String getGroup_list() { return group_list; } public void setGroup_list(String group_list) { this.group_list = group_list; } public String getU_copied_from() { return u_copied_from; } public void setU_copied_from(String u_copied_from) { this.u_copied_from = u_copied_from; } public String getU_template() { return u_template; } public void setU_template(String u_template) { this.u_template = u_template; } public String getApproval_set() { return approval_set; } public void setApproval_set(String approval_set) { this.approval_set = approval_set; } public String getU_security_related() { return u_security_related; } public void setU_security_related(String u_security_related) { this.u_security_related = u_security_related; } public String getMajor_incident_state() { return major_incident_state; } public void setMajor_incident_state(String major_incident_state) { this.major_incident_state = major_incident_state; } public String getShort_description() { return short_description; } public void setShort_description(String short_description) { this.short_description = short_description; } public String getCorrelation_display() { return correlation_display; } public void setCorrelation_display(String correlation_display) { this.correlation_display = correlation_display; } public String getDelivery_task() { return delivery_task; } public void setDelivery_task(String delivery_task) { this.delivery_task = delivery_task; } public String getWork_start() { return work_start; } public void setWork_start(String work_start) { this.work_start = work_start; } public String getTrigger_rule() { return trigger_rule; } public void setTrigger_rule(String trigger_rule) { this.trigger_rule = trigger_rule; } public String getAdditional_assignee_list() { return additional_assignee_list; } public void setAdditional_assignee_list(String additional_assignee_list) { this.additional_assignee_list = additional_assignee_list; } public String getNotify() { return notify; } public void setNotify(String notify) { this.notify = notify; } public String getService_offering() { return service_offering; } public void setService_offering(String service_offering) { this.service_offering = service_offering; } public String getSys_class_name() { return sys_class_name; } public void setSys_class_name(String sys_class_name) { this.sys_class_name = sys_class_name; } public ClosedBy getClosed_by() { return closed_by; } public void setClosed_by(ClosedBy closed_by) { this.closed_by = closed_by; } public String getFollow_up() { return follow_up; } public void setFollow_up(String follow_up) { this.follow_up = follow_up; } public String getParent_incident() { return parent_incident; } public void setParent_incident(String parent_incident) { this.parent_incident = parent_incident; } public String getReopened_by() { return reopened_by; } public void setReopened_by(String reopened_by) { this.reopened_by = reopened_by; } public String getReassignment_count() { return reassignment_count; } public void setReassignment_count(String reassignment_count) { this.reassignment_count = reassignment_count; } public AssignedTo getAssigned_to() { return assigned_to; } public void setAssigned_to(AssignedTo assigned_to) { this.assigned_to = assigned_to; } public String getSla_due() { return sla_due; } public void setSla_due(String sla_due) { this.sla_due = sla_due; } public String getComments_and_work_notes() { return comments_and_work_notes; } public void setComments_and_work_notes(String comments_and_work_notes) { this.comments_and_work_notes = comments_and_work_notes; } public UTenantCategory getU_tenant_category() { return u_tenant_category; } public void setU_tenant_category(UTenantCategory u_tenant_category) { this.u_tenant_category = u_tenant_category; } public String getU_tenant_resolution_code() { return u_tenant_resolution_code; } public void setU_tenant_resolution_code(String u_tenant_resolution_code) { this.u_tenant_resolution_code = u_tenant_resolution_code; } public String getEscalation() { return escalation; } public void setEscalation(String escalation) { this.escalation = escalation; } public String getUpon_approval() { return upon_approval; } public void setUpon_approval(String upon_approval) { this.upon_approval = upon_approval; } public String getCorrelation_id() { return correlation_id; } public void setCorrelation_id(String correlation_id) { this.correlation_id = correlation_id; } public String getTimeline() { return timeline; } public void setTimeline(String timeline) { this.timeline = timeline; } public String getU_vendor_ticket_number() { return u_vendor_ticket_number; } public void setU_vendor_ticket_number(String u_vendor_ticket_number) { this.u_vendor_ticket_number = u_vendor_ticket_number; } public String getMade_sla() { return made_sla; } public void setMade_sla(String made_sla) { this.made_sla = made_sla; } public String getPromoted_on() { return promoted_on; } public void setPromoted_on(String promoted_on) { this.promoted_on = promoted_on; } public String getChild_incidents() { return child_incidents; } public void setChild_incidents(String child_incidents) { this.child_incidents = child_incidents; } public String getHold_reason() { return hold_reason; } public void setHold_reason(String hold_reason) { this.hold_reason = hold_reason; } public ResolvedBy getResolved_by() { return resolved_by; } public void setResolved_by(ResolvedBy resolved_by) { this.resolved_by = resolved_by; } public String getSys_updated_by() { return sys_updated_by; } public void setSys_updated_by(String sys_updated_by) { this.sys_updated_by = sys_updated_by; } public OpenedBy getOpened_by() { return opened_by; } public void setOpened_by(OpenedBy opened_by) { this.opened_by = opened_by; } public String getUser_input() { return user_input; } public void setUser_input(String user_input) { this.user_input = user_input; } public String getSys_created_on() { return sys_created_on; } public void setSys_created_on(String sys_created_on) { this.sys_created_on = sys_created_on; } public SysDomain getSys_domain() { return sys_domain; } public void setSys_domain(SysDomain sys_domain) { this.sys_domain = sys_domain; } public String getProposed_on() { return proposed_on; } public void setProposed_on(String proposed_on) { this.proposed_on = proposed_on; } public String getActions_taken() { return actions_taken; } public void setActions_taken(String actions_taken) { this.actions_taken = actions_taken; } public TaskFor getTask_for() { return task_for; } public void setTask_for(TaskFor task_for) { this.task_for = task_for; } public String getCalendar_stc() { return calendar_stc; } public void setCalendar_stc(String calendar_stc) { this.calendar_stc = calendar_stc; } public String getClosed_at() { return closed_at; } public void setClosed_at(String closed_at) { this.closed_at = closed_at; } public String getU_sd2sd_interface_type() { return u_sd2sd_interface_type; } public void setU_sd2sd_interface_type(String u_sd2sd_interface_type) { this.u_sd2sd_interface_type = u_sd2sd_interface_type; } public BusinessService getBusiness_service() { return business_service; } public void setBusiness_service(BusinessService business_service) { this.business_service = business_service; } public String getBusiness_impact() { return business_impact; } public void setBusiness_impact(String business_impact) { this.business_impact = business_impact; } public String getRfc() { return rfc; } public void setRfc(String rfc) { this.rfc = rfc; } public String getTime_worked() { return time_worked; } public void setTime_worked(String time_worked) { this.time_worked = time_worked; } public String getExpected_start() { return expected_start; } public void setExpected_start(String expected_start) { this.expected_start = expected_start; } public String getOpened_at() { return opened_at; } public void setOpened_at(String opened_at) { this.opened_at = opened_at; } public String getWork_end() { return work_end; } public void setWork_end(String work_end) { this.work_end = work_end; } public CallerId getCaller_id() { return caller_id; } public void setCaller_id(CallerId caller_id) { this.caller_id = caller_id; } public String getReopened_time() { return reopened_time; } public void setReopened_time(String reopened_time) { this.reopened_time = reopened_time; } public String getResolved_at() { return resolved_at; } public void setResolved_at(String resolved_at) { this.resolved_at = resolved_at; } public String getU_interface_type() { return u_interface_type; } public void setU_interface_type(String u_interface_type) { this.u_interface_type = u_interface_type; } public String getWork_notes() { return work_notes; } public void setWork_notes(String work_notes) { this.work_notes = work_notes; } public AssignmentGroup getAssignment_group() { return assignment_group; } public void setAssignment_group(AssignmentGroup assignment_group) { this.assignment_group = assignment_group; } public String getBusiness_stc() { return business_stc; } public void setBusiness_stc(String business_stc) { this.business_stc = business_stc; } public String getCause() { return cause; } public void setCause(String cause) { this.cause = cause; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public String getCalendar_duration() { return calendar_duration; } public void setCalendar_duration(String calendar_duration) { this.calendar_duration = calendar_duration; } public String getU_sd2sd_external_system() { return u_sd2sd_external_system; } public void setU_sd2sd_external_system(String u_sd2sd_external_system) { this.u_sd2sd_external_system = u_sd2sd_external_system; } public String getClose_notes() { return close_notes; } public void setClose_notes(String close_notes) { this.close_notes = close_notes; } public String getSys_id() { return sys_id; } public void setSys_id(String sys_id) { this.sys_id = sys_id; } public String getContact_type() { return contact_type; } public void setContact_type(String contact_type) { this.contact_type = contact_type; } public String getIncident_state() { return incident_state; } public void setIncident_state(String incident_state) { this.incident_state = incident_state; } public String getUrgency() { return urgency; } public void setUrgency(String urgency) { this.urgency = urgency; } public String getProblem_id() { return problem_id; } public void setProblem_id(String problem_id) { this.problem_id = problem_id; } public Company getCompany() { return company; } public void setCompany(Company company) { this.company = company; } public String getActivity_due() { return activity_due; } public void setActivity_due(String activity_due) { this.activity_due = activity_due; } public String getSeverity() { return severity; } public void setSeverity(String severity) { this.severity = severity; } public String getOverview() { return overview; } public void setOverview(String overview) { this.overview = overview; } public String getComments() { return comments; } public void setComments(String comments) { this.comments = comments; } public String getApproval() { return approval; } public void setApproval(String approval) { this.approval = approval; } public String getU_environment() { return u_environment; } public void setU_environment(String u_environment) { this.u_environment = u_environment; } public String getDue_date() { return due_date; } public void setDue_date(String due_date) { this.due_date = due_date; } public String getSys_mod_count() { return sys_mod_count; } public void setSys_mod_count(String sys_mod_count) { this.sys_mod_count = sys_mod_count; } public String getU_affected_user() { return u_affected_user; } public void setU_affected_user(String u_affected_user) { this.u_affected_user = u_affected_user; } public String getReopen_count() { return reopen_count; } public void setReopen_count(String reopen_count) { this.reopen_count = reopen_count; } public String getSys_tags() { return sys_tags; } public void setSys_tags(String sys_tags) { this.sys_tags = sys_tags; } public String getU_external_system() { return u_external_system; } public void setU_external_system(String u_external_system) { this.u_external_system = u_external_system; } public String getU_knowledge_article() { return u_knowledge_article; } public void setU_knowledge_article(String u_knowledge_article) { this.u_knowledge_article = u_knowledge_article; } public String getLocation() { return location; } public void setLocation(String location) { this.location = location; } public String getU_sd2sd_service_provider() { return u_sd2sd_service_provider; } public void setU_sd2sd_service_provider(String u_sd2sd_service_provider) { this.u_sd2sd_service_provider = u_sd2sd_service_provider; } @Override public String toString() { return "Result [promoted_by=" + promoted_by + ", parent=" + parent + ", caused_by=" + caused_by + ", watch_list=" + watch_list + ", u_tenant_subcategory=" + u_tenant_subcategory + ", upon_reject=" + upon_reject + ", sys_updated_on=" + sys_updated_on + ", approval_history=" + approval_history + ", number=" + number + ", proposed_by=" + proposed_by + ", u_contact_attempt=" + u_contact_attempt + ", u_security_type=" + u_security_type + ", lessons_learned=" + lessons_learned + ", state=" + state + ", sys_created_by=" + sys_created_by + ", knowledge=" + knowledge + ", order=" + order + ", cmdb_ci=" + cmdb_ci + ", delivery_plan=" + delivery_plan + ", impact=" + impact + ", active=" + active + ", work_notes_list=" + work_notes_list + ", u_vendor=" + u_vendor + ", priority=" + priority + ", sys_domain_path=" + sys_domain_path + ", business_duration=" + business_duration + ", group_list=" + group_list + ", u_copied_from=" + u_copied_from + ", u_template=" + u_template + ", approval_set=" + approval_set + ", u_security_related=" + u_security_related + ", major_incident_state=" + major_incident_state + ", short_description=" + short_description + ", correlation_display=" + correlation_display + ", delivery_task=" + delivery_task + ", work_start=" + work_start + ", trigger_rule=" + trigger_rule + ", additional_assignee_list=" + additional_assignee_list + ", notify=" + notify + ", service_offering=" + service_offering + ", sys_class_name=" + sys_class_name + ", closed_by=" + closed_by + ", follow_up=" + follow_up + ", parent_incident=" + parent_incident + ", reopened_by=" + reopened_by + ", reassignment_count=" + reassignment_count + ", assigned_to=" + assigned_to + ", sla_due=" + sla_due + ", comments_and_work_notes=" + comments_and_work_notes + ", u_tenant_category=" + u_tenant_category + ", u_tenant_resolution_code=" + u_tenant_resolution_code + ", escalation=" + escalation + ", upon_approval=" + upon_approval + ", correlation_id=" + correlation_id + ", timeline=" + timeline + ", u_vendor_ticket_number=" + u_vendor_ticket_number + ", made_sla=" + made_sla + ", promoted_on=" + promoted_on + ", child_incidents=" + child_incidents + ", hold_reason=" + hold_reason + ", resolved_by=" + resolved_by + ", sys_updated_by=" + sys_updated_by + ", opened_by=" + opened_by + ", user_input=" + user_input + ", sys_created_on=" + sys_created_on + ", sys_domain=" + sys_domain + ", proposed_on=" + proposed_on + ", actions_taken=" + actions_taken + ", task_for=" + task_for + ", calendar_stc=" + calendar_stc + ", closed_at=" + closed_at + ", u_sd2sd_interface_type=" + u_sd2sd_interface_type + ", business_service=" + business_service + ", business_impact=" + business_impact + ", rfc=" + rfc + ", time_worked=" + time_worked + ", expected_start=" + expected_start + ", opened_at=" + opened_at + ", work_end=" + work_end + ", caller_id=" + caller_id + ", reopened_time=" + reopened_time + ", resolved_at=" + resolved_at + ", u_interface_type=" + u_interface_type + ", work_notes=" + work_notes + ", assignment_group=" + assignment_group + ", business_stc=" + business_stc + ", cause=" + cause + ", description=" + description + ", calendar_duration=" + calendar_duration + ", u_sd2sd_external_system=" + u_sd2sd_external_system + ", close_notes=" + close_notes + ", sys_id=" + sys_id + ", contact_type=" + contact_type + ", incident_state=" + incident_state + ", urgency=" + urgency + ", problem_id=" + problem_id + ", company=" + company + ", activity_due=" + activity_due + ", severity=" + severity + ", overview=" + overview + ", comments=" + comments + ", approval=" + approval + ", u_environment=" + u_environment + ", due_date=" + due_date + ", sys_mod_count=" + sys_mod_count + ", u_affected_user=" + u_affected_user + ", reopen_count=" + reopen_count + ", sys_tags=" + sys_tags + ", u_external_system=" + u_external_system + ", u_knowledge_article=" + u_knowledge_article + ", location=" + location + ", u_sd2sd_service_provider=" + u_sd2sd_service_provider + "]"; } } <file_sep>package com.capgemini.ec.gateway.services; import java.util.HashMap; import java.util.Map; import org.apache.camel.Produce; import org.apache.camel.ProducerTemplate; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Service; import com.capgemini.ec.gateway.model.IncidentInfo; import com.capgemini.ec.gateway.processor.IncInfoProcessor; @Service public class GatewayRequestProcessService { @Produce private ProducerTemplate template; @Autowired private IncInfoProcessor incInfoProcessor; public ResponseEntity<String> processUpdateInc(Map<String, String> input, String sys_id) throws Exception { Map<String, Object> headers = new HashMap<String, Object>(); headers.put("sys_id", sys_id); headers.put("customer", input.get("customer").toUpperCase()); input.remove("customer"); byte[] result = template.requestBodyAndHeaders("direct:forwardToUpdate", input, headers, byte[].class); System.out.println("Out Put " + new String(result)); return new ResponseEntity<String>(new String(result), HttpStatus.OK); } public ResponseEntity<String> processCreateInc(Map<String, String> input) throws Exception { Map<String, Object> headers = new HashMap<String, Object>(); headers.put("customer", input.get("customer").toUpperCase()); input.remove("customer"); byte[] result = template.requestBodyAndHeaders("direct:forwardToCreate", input, headers, byte[].class); System.out.println("Out Put " + new String(result)); return new ResponseEntity<String>(new String(result), HttpStatus.OK); } public ResponseEntity<String> processGetInc(String customer,String sysParmQuery,String sysParmFields) throws Exception { Map<String, Object> headers = new HashMap<String, Object>(); headers.put("sysParmQuery", sysParmQuery); headers.put("sysParmFields", sysParmFields); headers.put("customer", customer.toUpperCase()); byte[] result = template.requestBodyAndHeaders("direct:forwardToGet", null, headers, byte[].class); System.out.println("Out Put " + new String(result)); return new ResponseEntity<String>(new String(result), HttpStatus.OK); } public ResponseEntity<String> processGetIncidentInfo(IncidentInfo input) throws Exception { return new ResponseEntity<String>(incInfoProcessor.processIncInfo(input), HttpStatus.OK); } }
1f85f9c75e4260a48fa4fccca3c241c29969fd0f
[ "Java", "INI" ]
8
Java
giriraj1995/VAPOC
5005c169639a7d7bb45c1cda356f431cbfc6131a
8ceec05f215b33c50fa7f48516771bef1ec4d93f
refs/heads/master
<repo_name>gusfrehse/ruby-battleships<file_sep>/board.rb class Board @@ships = { :A => [ ['A', '+', '+'] ], :B => [ ['~', 'B', '~'], ['+', '+', '+'] ], :C => [ ['+'], ['+'], ['C'] ] } def initialize( width, height ) raise ArgumentError, 'width and height must be bigger than five and less \ than eleven.' unless width > 5 && width < 11 && height > 5 && height < 11 @width = width @height = height @board = ( Array.new( height ) { Array.new( width ) } ) @board = @board.collect { |l| l.collect { '~' } } end def ship_head_position( code ) arr = Array.new @@ships[code].each_with_index do |line, dy| line.each_with_index do |value, dx| if ('A'..'Z') === value arr << dx << dy end end end arr[0, 2] end def put_ship( code, hx, hy ) hdx = self.ship_head_position( code )[0] hdy = self.ship_head_position( code )[1] @@ships[code].each_with_index do |line, dy| line.each_with_index do |value, dx| by = dy - hdy + hy bx = dx - hdx + hx unless value == '~' raise ArgumentError, 'desired position is not inside the board' \ if by > @height - 1 || by < 0 || bx > @width - 1 || bx < 0 raise ArgumentError, "there's a ship in the desired position" \ if @board[by][bx] != '~' @board[by][bx] = value end end end # raise ArgumentError, 'position (x and y) must be inside the board' \ # unless x < @width - 1 && x > -1 && y < @height - 1 && y > -1 end def to_s ret = "" ret << " " (0...@width).each { |n| ret << " " + n.to_s } ret << "\n" @board.each_with_index do |line, y| ret << " " + y.to_s + " " line.each_with_index do |value, x| ret << "|#{ value }|" end ret << "\n" end ret end end <file_sep>/main.rb # This is supposed to be a Battleships game. # only supposed because I almosted never # finish my projects. require_relative "board" class Application @@board01 = "board 01 test lul\n" def select_phase puts "Player 01 look to the pc, Player 02 look away" sleep 5 puts "Player 01, I just wanted to say you're so much more beatiful than \ Player 02.\nAnyway, here is your board" print @@board01 puts "and here is your ships. Now, you need to understand something \ rather difficult.\nFirst, each ship looks like this:\n\ A+++++\n\ Each ship has a letter. This letter we will call CODE. The ship's CODE \ is what you can think as the name of the ship. So when I ask for a ship \ you will NOT write the actual ship, but WILL write it's CODE. The CODE \ is also the 'head' of the ship (in this case it is the letter 'A'). Do \ you understand? If not, too bad because I am a pre-written message.\n\ Also, it is important for you to know what is position and what is the \ position of the ships. Position, at least in this game is a combination \ of two numbers, a X (horizontal) and an Y (vertical) number. The \ position of the ship is based on the position of the ship's CODE, which \ is the letter, which is the 'head' of the ship and which is the only \ character in the ship different from '+'." end def run( width, height ) puts "Starting game" b1 = Board.new( width, height ) b2 = Board.new( width, height ) puts "01 enter three positions" pos = gets pos.strip! posa = pos.split( " " ) b1.put_ship( :A, posa[0].to_i, posa[1].to_i ) puts b1.to_s pos = gets pos.strip! posa = pos.split( " " ) b1.put_ship( :B, posa[0].to_i, posa[1].to_i ) puts b1.to_s pos = gets pos.strip! posa = pos.split( " " ) b1.put_ship( :C, posa[0].to_i, posa[1].to_i ) puts b1.to_s puts "This is your board now" puts b1.to_s puts "02 enter three positions" pos = gets pos.strip! posa = pos.split( " " ) b2.put_ship( :A, posa[0].to_i, posa[1].to_i ) puts b2.to_s pos = gets pos.strip! posa = pos.split( " " ) b2.put_ship( :B, posa[0].to_i, posa[1].to_i ) puts b2.to_s pos = gets pos.strip! posa = pos.split( " " ) b2.put_ship( :C, posa[0].to_i, posa[1].to_i ) puts b2.to_s puts "This is your board now" puts b2.to_s end end app = Application.new app.run( 10, 10 )
94cd76f1acddcd27d08ddf999822b9c69bbd8b49
[ "Ruby" ]
2
Ruby
gusfrehse/ruby-battleships
e242cb5ed8cf2d95c703998d4ac9fd59e06edde3
e4737ab0d9cfdcf31309d5cf1b9e4291bfd88e5c
refs/heads/master
<file_sep>Random Quote Generator Single Page ---------------------------------- A [Pen](https://codepen.io/firstCodePen/pen/pVePwb) by [<NAME>](https://codepen.io/firstCodePen) on [CodePen](https://codepen.io). [License](https://codepen.io/firstCodePen/pen/pVePwb/license).<file_sep> $(document).ready(function(){ generateRandom(); $("#quoteBtn").on("click", function(e){ e.preventDefault(); //call function to do random generation of the page generateRandom(); }); $("#twitterBtn").on("click", function(e){ var author = $("#author").html(); var quote = $("#quote").html(); window.open("https://twitter.com/intent/tweet?text=\""+quote+"\""+author); }); }); function generateRandom(){ $.getJSON("https://quotesondesign.com/wp-json/posts?filter[orderby]=rand&filter[posts_per_page]=1&_jsonp=?", function(json) { var post = json.shift(); var html = post.content; // console.log(html); $("#text").html(html); $("#text p").html("<i class='fa fa-quote-left' aria-hidden='true'></i><span id = \"quote\">"+$("#text p").html()+"</span>"); $("#author").html("- "+post.title); }); var red = Math.floor(Math.random() * 255); var green = Math.floor(Math.random() * 255); var blue = Math.floor(Math.random() * 255); var rgb = "rgb("+red+", "+green +", "+ blue+")"; //$("#text").html(rgb); $("body").css("background-color",rgb); $(".box").css("color", rgb); $("#quoteBtn").css("background-color",rgb); $("#twitterBtn").css("background-color",rgb); $("#tumblrBtn").css("background-color",rgb); }<file_sep># Random-quote-generator A simple web page which generates random quotes whenever someone clicks on the generate quote button. The Randomly Generated Quotes are generated from this API: https://quotesondesign.com/api-v4-0/. The quote and the author of the quote can be tweeted out by clicking the button with the twitter icon in the bottom left of the quote box.
51f810dd04f8527b3a5d3ffedaae6cf89bf54442
[ "Markdown", "JavaScript" ]
3
Markdown
ntang58/Random-quote-generator
ba805bdf2820a344a3e4efe9e456d056473bd0f4
7f8c64878ebd3f0dd342d32c73438249ded9bf95
refs/heads/main
<repo_name>Felipe-Affonso047/ICS3U-Unit3-02-CPP<file_sep>/guessingGame.cpp // Copyright (c) 2021 <NAME> All rights reserved // // Created by: <NAME> // Created on: April 2021 // This program is a guessing number game #include <iostream> #include <cmath> #include <iomanip> int main() { float number; std::cout << "Try to guess a number from 0 to 9:" << std::endl; std::cin >> number; if (number == 5) { std::cout << "\nCongratulations, guessed right!" << std::endl; } if (number != 5) { std::cout << "\nSorry, guessed wrong!" << std::endl; } std::cout << std::endl; std::cout << "Done." << std::endl; }
4d2cdcc1c84cb4c637de8aa52fcf9a3c4ca3d112
[ "C++" ]
1
C++
Felipe-Affonso047/ICS3U-Unit3-02-CPP
c9d0eeb5b9d7473049d717bb8b1ff68d0163b7ad
92890b7844979124c831a6d60b31ebdb9611c3e5
refs/heads/master
<file_sep>import pygame import os import sys import copy from pygame.locals import * def get_file(file): main_dir = os.path.split(os.path.abspath(__file__))[0] data_dir = os.path.join(main_dir, "data") return os.path.join(data_dir, file) class Engine: def __init__(self, width, height, g, caption = "NOPE"): pygame.init() pygame.display.set_mode((width, height)) pygame.display.set_caption(caption) pygame.key.set_repeat() self.screen = pygame.display.get_surface() self.clock = pygame.time.Clock() self.g = g self.clear() def set_background(self, background): self.background = background def get_display_rect(self): return pygame.display.get_surface().get_rect() def delay(self, time): pygame.time.delay(time) def toogle_fullscreen(self): pygame.display.toggle_fullscreen() def load_sound(self, name): class NoneSound: def play(self): pass if not pygame.mixer: return NoneSound() fullname = get_file(name) try: sound = pygame.mixer.Sound(fullname) except pygame.error: sound = NoneSound return sound def play_music(self, name, repeats): fullname = get_file(name) try: pygame.mixer.music.load(fullname) pygame.mixer.music.play(repeats) except pygame.error: pass def add_entity(self, entity): self.entities.append(entity) self.sprites.add(entity) if entity.rect.right > self.maximumx: self.maximumx = entity.rect.right - 250 if entity.enttype == "player": self.player = self.entities[-1] elif entity.enttype == "exit": self.exit = self.entities[-1] def remove_entity(self, entity): self.entities.remove(entity) self.sprites.remove(entity) def gravity(self): entity = copy.deepcopy(self.player) entity.rect.y += self.g collision = self.check_collision(entity) if not len(collision): if self.player.jumpheight <= 0: self.player.rect.y += self.g else: if self.entities[collision[0]].enttype == "lift": if self.entities[collision[0]].dy != 0 and self.player.jumpheight > 0: self.player.rect.y -= 2 * self.entities[collision[0]].dy return if entity.rect.bottom - 5 < self.entities[collision[0]].rect.bottom and self.player.rect.top < self.entities[collision[0]].rect.top: self.player.rect.x += self.entities[collision[0]].dx self.player.rect.bottom = self.entities[collision[0]].rect.top self.player.jumping = False self.player.jumpheight = 0 return if self.player.rect.bottom <= self.entities[collision[0]].rect.top: self.player.rect.bottom = self.entities[collision[0]].rect.top self.player.jumping = False elif self.player.rect.bottom > self.entities[collision[0]].rect.top: self.player.rect.y += self.g self.player.jumpheight = 0 def clear(self): self.entities = [] self.sprites = pygame.sprite.RenderPlain() self.background = self.player = self.exit = None self.maximumx = self.totaldeltay = self.totaldeltax = 0 def check_collision(self, entity): # retval = [collide for collide in entity.rect.collidelistall([x.rect for x in self.entities]) if entity != self.entities[collide] and self.entities[collide].enttype != "player" and self.entities[collide].enttype != "text" and self.entities[collide].enttype != "exit"] return [collide for collide in entity.rect.collidelistall([x.rect for x in self.entities]) if entity != self.entities[collide] and not (self.entities[collide].enttype in ["player","exit","text"])] def check_completed_collision(self): return self.player.rect.colliderect(self.exit.rect) def check_jumpable(self): ent = copy.deepcopy(self.player) ent.rect.y += 1 if not len(self.check_collision(ent)): self.player.jumping = True def get_pressed(self): return pygame.key.get_pressed() def handle_input(self): for event in pygame.event.get(): if event.type == QUIT: self.quit() def update(self, enttype = None, reverse = False): self.sprites.empty() for entity in self.entities: if enttype is not None: if (reverse and entity.enttype != enttype) or (not reverse and entity.enttype == enttype): self.sprites.add(entity) else: self.sprites.add(entity) self.sprites.update() def update_camera(self): if self.player.rect.x > 250 and self.maximumx > 640 - 250: self.move_camera(dx = 250 - self.player.rect.x) elif self.player.rect.x < 150 and self.totaldeltax < 0: self.move_camera(dx = 150 - self.player.rect.x) if self.player.rect.y < 250: self.move_camera(dy = 250 - self.player.rect.y) elif self.player.rect.y > 420 and self.totaldeltay > 0: self.move_camera(dy = 420 - self.player.rect.y) def move_camera(self, dx = 0, dy = 0): self.maximumx += dx self.totaldeltax += dx self.totaldeltay += dy for i in range(len(self.entities)): self.entities[i].move(dx, dy) def render(self): if self.background is not None: self.screen.blit(self.background.image, (0, 0)) if self.player is not None: self.gravity() self.check_jumpable() self.update("text") self.sprites.draw(self.screen) self.update("text", True) self.sprites.draw(self.screen) pygame.display.flip() def quit(self): sys.exit(0) <file_sep>import engine import pyclbr import levels from levels import * def start(): eng = engine.Engine(640, 480, 6, "Glow") eng.play_music("music.ogg", -1) eng.set_background(entity.Entity("logo.png", 0, 0)) eng.render() eng.delay(1500) eng.clear() eng.set_background(entity.Entity("black.png", 0, 0)) eng.add_entity(entity.Text("G", 72, "m46.TTF", (230, 230), (255, 0, 0))) eng.add_entity(entity.Text("L", 72, "m46.TTF", (270, 230), (0, 255, 0))) eng.add_entity(entity.Text("O", 72, "m46.TTF", (290, 230), (0, 0, 255))) eng.add_entity(entity.Text("W", 72, "m46.TTF", (340, 230), (255, 255, 255))) eng.render() eng.delay(2000) eng.clear() lvls = [getattr(levels, level)(eng) for level in pyclbr.readmodule("package.levels").keys() if level.startswith("Level") and len(level) > 5] for level in lvls: while not level.completed: level.run() if not level.completed: eng.clear() eng.set_background(entity.Entity("death.png", 0, 0)) eng.render() eng.delay(300) <file_sep>#!/usr/bin/env python import package.game package.game.start() <file_sep>__author__ = 'testtest' <file_sep>from distutils.core import setup files = ["data/*"] setup(name = "Forever Glow", version = "1.0", description = "LudumDare entry", author = "StarLight", author_email = "<EMAIL>", url = "http://strlght.ru", packages = ['package'], package_data = {'package' : files }, scripts = ["glow"], long_description = """StarLight's LudumDare 22 Entry!""" ) <file_sep>import copy from pygame.locals import * from package import entity class Level: def __init__(self, engine): self.eng = engine self.going = True self.completed = False self.jumpsound = engine.load_sound("jump.wav") def initialize(self): self.eng.clear() self.going = True self.completed = False def handle_input(self): entity = copy.deepcopy(self.eng.player) pressed = self.eng.get_pressed() if pressed[K_LEFT] or pressed[ord("a")]: entity.rect.x -= 5 collision = self.eng.check_collision(entity) if not len(collision): self.eng.player.rect.x -= 5 else: if self.eng.entities[collision[0]].enttype != "lift" and self.eng.entities[collision[0]].rect.bottom < self.eng.entities[collision[0]].rect.top: self.eng.player.rect.left = self.eng.entities[collision[0]].rect.right if pressed[K_RIGHT] or pressed[ord("d")]: entity.rect.x += 5 collision = self.eng.check_collision(entity) if not len(collision): self.eng.player.rect.x += 5 else: if self.eng.entities[collision[0]].enttype != "lift" and self.eng.entities[collision[0]].rect.bottom < self.eng.entities[collision[0]].rect.top: self.eng.player.rect.right = self.eng.entities[collision[0]].rect.left if pressed[K_UP] or pressed[K_SPACE] or pressed[ord("w")]: if not self.eng.player.jumping: self.jumpsound.play() self.eng.player.jumpheight = self.eng.player.totalheight self.eng.player.jumping = True if pressed[K_ESCAPE]: self.eng.quit() if pressed[ord("f")]: self.eng.toogle_fullscreen() def jump(self): if self.eng.player.jumpheight > 0: self.eng.player.rect.y -= self.eng.g + 1 self.eng.player.jumpheight -= self.eng.g + 1 else: self.eng.player.jumpheight = 0 def needs_respawn(self): if not self.eng.player.rect.colliderect(self.eng.get_display_rect()): self.going = False def run(self): pass def start(self): while self.going and not self.completed: self.needs_respawn() self.eng.update_camera() self.eng.handle_input() self.handle_input() self.eng.clock.tick(30) self.jump() self.eng.render() self.completed = self.eng.check_completed_collision() class LevelA(Level): def run(self): self.initialize() self.eng.set_background(entity.Entity("sun.png", 0, 0)) self.eng.add_entity(entity.Text("Press arrows or WASD to move", 42, "m46.TTF", (60, 265), (255, 255, 255))) self.eng.add_entity(entity.Text("Exit ->", 34, "m46.TTF", (500, 400), (255,255,255))) self.eng.add_entity(entity.Entity("hero.png", 10, 396, "player", 45)) self.eng.add_entity(entity.Entity("pic2.png", -1, 300, scale = (1, 200))) self.eng.add_entity(entity.Entity("pic2.png",-20, 440, scale = (680, 80))) self.eng.add_entity(entity.Entity("exit.png", 605, 396, "exit")) self.start() class LevelB(Level): def run(self): self.initialize() self.eng.set_background(entity.Entity("sun.png", 0, 0)) self.eng.add_entity(entity.Text("Press up or space to jump", 42, "m46.TTF", (105, 265), (255, 255, 255))) self.eng.add_entity(entity.Entity("hero.png", 10, 396, "player", 45)) self.eng.add_entity(entity.Entity("pic2.png", -1, 300, scale = (1, 200))) self.eng.add_entity(entity.Entity("pic2.png", -20, 440, scale = (680, 80))) self.eng.add_entity(entity.Entity("pic2.png", 500, 420, scale = (50, 20))) self.eng.add_entity(entity.Entity("pic2.png", 550, 400, scale = (50, 40))) self.eng.add_entity(entity.Entity("pic2.png", 590, 380, scale = (50, 60))) self.eng.add_entity(entity.Entity("exit.png", 605, 336, "exit")) self.start() class LevelC(Level): def run(self): self.initialize() self.eng.set_background(entity.Entity("sun.png", 0, 0)) self.eng.add_entity(entity.Text("OMG IT'S MOVING!", 42, "m46.TTF", (160, 265), (255, 255, 255))) self.eng.add_entity(entity.Entity("hero.png", 10, 396, "player", 45)) self.eng.add_entity(entity.Entity("pic2.png", -1, 300, scale = (1, 200))) self.eng.add_entity(entity.Entity("pic2.png", 0, 440, scale = (100, 80))) self.eng.add_entity(entity.Lift("platform.png", 270, 440, 110, 455, 440, 440, -3)) self.eng.add_entity(entity.Entity("pic2.png", 551, 440, scale = (100, 80))) self.eng.add_entity(entity.Entity("exit.png", 605, 396, "exit")) self.start() class LevelD(Level): def run(self): self.initialize() self.completed = True for i in range(7): self.eng.clear() if i%2: self.eng.set_background(entity.Entity("black.png", 0, 0)) else: self.eng.set_background(entity.Entity("white.png", 0, 0)) self.eng.render() self.eng.delay(200) class LevelE(Level): def run(self): self.initialize() self.eng.set_background(entity.Entity("moon.png", 0, 0)) self.eng.add_entity(entity.Text("What happend?", 36,"m46.TTF", (0, 265), (255, 255, 255))) self.eng.add_entity(entity.Text("Where am I?", 36, "m46.TTF", (180, -36), (255, 255, 255))) self.eng.add_entity(entity.Text("Where is everyone?", 36, "m46.TTF", (500, 93), (255, 255, 255))) self.eng.add_entity(entity.Text("It was a day a minute ago...", 36, "m46.TTF", (480, -20), (255, 255, 255))) self.eng.add_entity(entity.Entity("hero.png", 10, 396, "player", 45)) self.eng.add_entity(entity.Entity("pic2.png", -1, 300, scale = (1, 200))) self.eng.add_entity(entity.Entity("pic2.png", 0, 440, scale = (100, 80))) self.eng.add_entity(entity.Lift("platform.png", 110, 400, 110, 110, 110, 445, dy = -3)) self.eng.add_entity(entity.Entity("pic2.png", 195, 115, scale = (200, 60))) self.eng.add_entity(entity.Entity("pic2.png", 325, 95, scale = (35, 20))) self.eng.add_entity(entity.Entity("pic2.png", 360, 75,scale = (35, 40))) self.eng.add_entity(entity.Lift("platform.png", 401, 75, 400, 740, 75, 75, 3)) self.eng.add_entity(entity.Entity("pic2.png", 845, 75, scale = (100, 30))) self.eng.add_entity(entity.Entity("exit.png", 910, 31, "exit")) self.start() class LevelF(Level): def run(self): self.initialize() self.eng.set_background(entity.Entity("moon.png", 0, 0)) self.eng.add_entity(entity.Text("Hello?", 36, "m46.TTF", (50, 320), (255, 255, 255))) self.eng.add_entity(entity.Text("Anybody?...", 36, "m46.TTF", (480, -40), (255, 255, 255))) self.eng.add_entity(entity.Entity("hero.png", 10, 396, "player", 45)) self.eng.add_entity(entity.Entity("pic2.png", -1, 300, scale = (1, 200))) self.eng.add_entity(entity.Entity("pic2.png", 0, 440, scale = (150, 80))) self.eng.add_entity(entity.Lift("platform.png", 480, 440, 155, 480, 0, 0, -3)) self.eng.add_entity(entity.Lift("platform.png", 570, 440, 0, 0, 115, 440, dy = -3)) self.eng.add_entity(entity.Lift("platform.png", 1000, 120, 675, 1000, 0, 0, -3)) self.eng.add_entity(entity.Lift("platform.png", 1105, 120, 1105, 1430, 0, 0, 3)) self.eng.add_entity(entity.Entity("pic2.png", 1530, 120, scale = (150, 40))) self.eng.add_entity(entity.Entity("exit.png", 1647, 76, "exit")) self.start() class LevelG(Level): def run(self): self.initialize() self.eng.set_background(entity.Entity("sun.png", 0, 0)) self.eng.add_entity(entity.Text("This world is strange", 36, "m46.TTF", (-20, 220), (255, 255, 255))) self.eng.add_entity(entity.Text("Don't hurry", 36, "m46.TTF", (650, 220), (255, 255, 255))) self.eng.add_entity(entity.Entity("hero.png", 50, 396, "player", 45)) self.eng.add_entity(entity.Entity("pic2.png", -1, 300, scale = (1, 200))) self.eng.add_entity(entity.Entity("pic2.png", 0, 440, scale = (130, 30))) self.eng.add_entity(entity.Entity("pic2.png", 100, 410, scale = (30, 30))) self.eng.add_entity(entity.Entity("pic2.png", 150, 380, scale = (30, 30))) self.eng.add_entity(entity.Entity("pic2.png", 230, 360, scale = (30, 30))) self.eng.add_entity(entity.Entity("pic2.png", 310, 340, scale = (30, 30))) self.eng.add_entity(entity.Entity("pic2.png", 410, 330, scale = (30, 30))) self.eng.add_entity(entity.Entity("pic2.png", 535, 350, scale = (30, 30))) self.eng.add_entity(entity.Entity("pic2.png", 650, 340, scale = (30, 30))) self.eng.add_entity(entity.Entity("pic2.png", 750, 330, scale = (30, 30))) self.eng.add_entity(entity.Entity("pic2.png", 850, 340, scale = (30, 30))) self.eng.add_entity(entity.Entity("pic2.png", 970, 350, scale = (30, 30))) self.eng.add_entity(entity.Entity("pic2.png", 1070, 335, scale = (30, 30))) self.eng.add_entity(entity.Entity("pic2.png", 1170, 315, scale = (30, 30))) self.eng.add_entity(entity.Entity("pic2.png", 1270, 300, scale = (30, 30))) self.eng.add_entity(entity.Entity("pic2.png", 1370, 285, scale = (130, 30))) self.eng.add_entity(entity.Entity("exit.png", 1460, 241, "exit")) self.start() class LevelH(Level): def run(self): self.initialize() self.eng.set_background(entity.Entity("far.png", 0, 0)) self.eng.add_entity(entity.Text("Wait", 36, "m46.TTF", (80, 320), (255, 255, 255))) self.eng.add_entity(entity.Text("Far far away", 36, "m46.TTF", (350, 290), (255, 255, 255))) self.eng.add_entity(entity.Text("Is it...?", 36, "m46.TTF", (670, 265), (255, 255, 255))) self.eng.add_entity(entity.Text("I need to get there as soon as I can!", 36, "m46.TTF", (900, 265), (255, 255, 255))) self.eng.add_entity(entity.Entity("hero.png", 50, 396, "player", 45)) self.eng.add_entity(entity.Entity("pic2.png", -1, 300, scale = (1, 200))) self.eng.add_entity(entity.Entity("pic2.png", 0, 440, scale = (300, 80))) self.eng.add_entity(entity.Entity("pic2.png", 300, 410, scale = (300, 110))) self.eng.add_entity(entity.Entity("pic2.png", 600, 380, scale = (300, 140))) self.eng.add_entity(entity.Entity("pic2.png", 900, 360, scale = (520, 160))) self.eng.add_entity(entity.Lift("platform.png", 1425, 360, 1420, 1570, 0, 0, -3)) self.eng.add_entity(entity.Entity("pic2.png", 1655, 360, scale = (150, 160))) self.eng.add_entity(entity.Entity("exit.png", 1770, 316, "exit")) self.start() class LevelI(Level): def run(self): self.initialize() self.eng.set_background(entity.Entity("sun.png", 0, 0)) self.eng.add_entity(entity.Entity("hero.png", 30, 195, "player", 45)) self.eng.add_entity(entity.Entity("pic2.png", -1, 300, scale = (1, 200))) self.eng.add_entity(entity.Entity("pic2.png", 0, 240, scale = (150, 80))) self.eng.add_entity(entity.Entity("pic2.png", 200, 260, scale = (40, 40))) self.eng.add_entity(entity.Entity("pic2.png", 290, 280, scale = (40, 40))) self.eng.add_entity(entity.Entity("pic2.png", 380, 300, scale = (40, 40))) self.eng.add_entity(entity.Lift("platform.png", 430, 300, 430, 600, 0, 0, 3)) self.eng.add_entity(entity.Entity("pic2.png", 690, 300, scale = (40, 40))) self.eng.add_entity(entity.Entity("pic2.png", 780, 280, scale = (40, 40))) self.eng.add_entity(entity.Entity("pic2.png", 870, 260, scale = (40, 40))) self.eng.add_entity(entity.Entity("pic2.png", 960, 240, scale = (150, 80))) self.eng.add_entity(entity.Entity("exit.png", 1079, 195, "exit")) self.start() class LevelJ(Level): def run(self): self.initialize() self.eng.set_background(entity.Entity("moon.png", 0, 0)) self.eng.add_entity(entity.Text("What the hell?", 36, "m46.TTF", (490, -120), (255, 255, 255))) self.eng.add_entity(entity.Text("phew", 36, "m46.TTF", (520,420), (255, 255, 255))) self.eng.add_entity(entity.Entity("hero.png", 30, 195, "player", 45)) self.eng.add_entity(entity.Entity("pic2.png", -1, 300, scale = (1, 200))) self.eng.add_entity(entity.Entity("pic2.png", 0, 240, scale = (150, 80))) self.eng.add_entity(entity.Entity("pic2.png", 200, 220, scale = (40, 40))) self.eng.add_entity(entity.Entity("pic2.png", 290, 200, scale = (40, 40))) self.eng.add_entity(entity.Entity("pic2.png", 380, 180, scale = (40, 40))) self.eng.add_entity(entity.Entity("pic2.png", 470, 160, scale = (40, 40))) self.eng.add_entity(entity.Entity("pic2.png", 560, 140, scale = (40, 40))) self.eng.add_entity(entity.Entity("pic2.png", 620, 440, scale = (200, 40))) self.eng.add_entity(entity.Lift("platform.png", 825, 440, 825, 1225, 0, 0, 3)) self.eng.add_entity(entity.Lift("platform.png", 1325, 35, 0, 0, 35, 435, dy = -3)) self.eng.add_entity(entity.Entity("pic2.png", 1425, 30, scale = (150, 40))) self.eng.add_entity(entity.Entity("exit.png", 1540, -14, "exit")) self.start() class LevelK(Level): def run(self): self.initialize() self.eng.set_background(entity.Entity("moon.png", 0, 0)) self.eng.add_entity(entity.Entity("pic2.png", -1, 300, scale = (1, 200))) self.eng.add_entity(entity.Text("I have found you!", 36, "m46.TTF", (150, 265), (255, 255, 255))) self.eng.add_entity(entity.Entity("hero.png", 10, 396, "player", 45)) self.eng.add_entity(entity.Entity("pic2.png", -20, 440, scale = (680, 80))) self.eng.add_entity(entity.Entity("black.png", 595, 360, "exit", scale = (10, 80))) self.eng.add_entity(entity.Entity("fhero.png", 605, 396)) self.start() class LevelL(Level): def run(self): self.initialize() self.eng.set_background(entity.Entity("sun.png", 0, 0)) self.eng.add_entity(entity.Text("Not again.", 36, "m46.TTF", (200, 200), (255, 255, 255))) self.eng.add_entity(entity.Text("Wait. It was night minute ago.", 36, "m46.TTF", (450, 200), (255, 255, 255))) self.eng.add_entity(entity.Text("Where's she?", 36, "m46.TTF", (1050, 200), (255, 255, 255))) self.eng.add_entity(entity.Text("Why this happens to me?", 36, "m46.TTF", (1500, 200), (255, 255, 255))) self.eng.add_entity(entity.Entity("hero.png", 10, 396, "player", 45)) self.eng.add_entity(entity.Entity("pic2.png", -1, 300, scale = (1, 200))) self.eng.add_entity(entity.Entity("pic2.png", 0, 440, scale = (100, 80))) self.eng.add_entity(entity.Lift("platform.png", 270, 440, 110, 1705, 0, 0, -3)) self.eng.add_entity(entity.Entity("pic2.png", 1800, 440, scale = (100, 80))) self.eng.add_entity(entity.Entity("exit.png", 1854, 396, "exit")) self.start() class LevelM(Level): def run(self): self.initialize() self.eng.set_background(entity.Entity("sun.png", 0, 0)) self.eng.add_entity(entity.Text("I will never find her again", 36, "m46.TTF", (10, 200), (255, 255, 255))) self.eng.add_entity(entity.Text("Why can't I be happy for a while? :(", 36, "m46.TTF", (275, -150), (255, 255, 255))) self.eng.add_entity(entity.Entity("hero.png", 10, 396, "player", 45)) self.eng.add_entity(entity.Entity("pic2.png", -1, 300, scale = (1, 200))) self.eng.add_entity(entity.Entity("pic2.png", 0, 440, scale = (150, 80))) self.eng.add_entity(entity.Lift("platform.png", 155, 360, 110, 110, 110, 445, dy = -3)) self.eng.add_entity(entity.Entity("pic2.png", 240, 115, scale = (50, 60))) self.eng.add_entity(entity.Lift("platform.png", 300, 110, 110, 110, -40, 110, dy = -3)) self.eng.add_entity(entity.Entity("pic2.png", 390, -35, scale = (150, 60))) self.eng.add_entity(entity.Entity("exit.png", 505, -79,"exit")) self.start() class LevelN(Level): def run(self): self.initialize() self.completed = True self.eng.set_background(entity.Entity("black.png", 0, 0)) self.eng.add_entity(entity.Text("Many years later", 42, "m46.TTF" , (175, 230), (255, 255, 255))) self.eng.render() self.eng.delay(2500) self.eng.clear() for i in range(7): if i%2: self.eng.set_background(entity.Entity("black.png", 0, 0)) else: self.eng.set_background(entity.Entity("white.png", 0, 0)) self.eng.render() self.eng.delay(200) self.eng.clear() self.eng.set_background(entity.Entity("black.png", 0, 0)) self.eng.add_entity(entity.Entity("oldhero.png", 10, 396)) self.eng.add_entity(entity.Entity("pic2.png", 0, 440, scale = (640, 80))) self.eng.add_entity(entity.Entity("fhero.png", 599, 396)) self.eng.add_entity(entity.Text("Is it you?", 42, "m46.TTF", (235, 130), (255, 255, 255))) self.eng.add_entity(entity.Text("After all this years", 42, "m46.TTF", (165, 230),(255, 255, 255))) self.eng.render() self.eng.delay(2000) for i in range(278): self.eng.entities[0].rect.x += 1 self.eng.entities[2].rect.x -= 1 self.eng.render() self.eng.render() self.eng.delay(2000) self.eng.clear() self.eng.set_background(entity.Entity("black.png", 0, 0)) self.eng.add_entity(entity.Text("The End", 42, "m46.TTF", (250, 230), (255, 255, 255))) self.eng.render() self.eng.delay(5000) self.eng.clear() <file_sep>import pygame import engine class Entity(pygame.sprite.Sprite): def __init__(self, path, x, y, enttype = "static", jumpheight = 0, scale = (0, 0)): pygame.sprite.Sprite.__init__(self) self.load_image(path, scale) self.rect.topleft = (x,y) self.enttype = enttype self.jumping = False self.jumpheight = 0 self.totalheight = jumpheight def __eq__(self, y): return self.rect == y.rect and self.image == y.image def __ne__(self, y): return not self.__eq__(y) def update(self): pass def move(self, dx, dy): self.rect.x += dx self.rect.y += dy def load_image(self, name, scale): fullname = engine.get_file(name) try: image = pygame.image.load(fullname) except pygame.error, message: raise SystemExit, message image = image.convert_alpha() if scale != (0,0): self.image = pygame.transform.scale(image, scale) else: self.image = image self.rect = self.image.get_rect() class Lift(Entity): def __init__(self, path, x, y, minx, maxx, miny, maxy, dx = 0, dy = 0, scale = (0, 0)): Entity.__init__(self, path, x, y, "lift", scale = scale) self.minx = minx self.maxx = maxx self.miny = miny self.maxy = maxy self.up = False self.right = True self.dx = dx self.dy = -dy self.vertical = self.maxy - self.miny > 0 self.horizontal = self.maxx - self.minx > 0 def move(self, dx, dy): Entity.move(self, dx, dy) self.maxx += dx self.minx += dx self.maxy += dy self.miny += dy def update(self): if self.vertical: if self.up: self.rect.y -= self.dy else: self.rect.y += self.dy if self.rect.y <= self.miny: self.up = False elif self.rect.y >= self.maxy: self.up = True if self.horizontal: self.rect.x += self.dx if self.rect.x >= self.maxx: self.dx = -self.dx elif self.rect.x <= self.minx: self.dx = -self.dx class Text(Entity): def __init__(self, text, size, fontname, (x, y), (r, g, b)): pygame.sprite.Sprite.__init__(self) self.enttype = "text" self.jumpheight = 0 self.jumping = False self.load_font(text, size, fontname, (r, g, b)) self.rect.topleft = (x, y) def load_font(self, text, size, fontname, (r, g, b)): fullname = engine.get_file(fontname) font = pygame.font.Font(fullname, size) self.image = font.render(text, 1, (r, g, b)) self.rect = self.image.get_rect()
0c8e2c78ff49f9c156150f72023ff37834ba5b89
[ "Python" ]
7
Python
strlght/glow
eb503be68bfe971b34b6e0ba858a67adc10d562f
77551a30faebc3805cbfb465b760aefed39735cb
refs/heads/main
<repo_name>Garald-48rus/SqlGuide<file_sep>/saleproduct.h #ifndef SALEPRODUCT_H #define SALEPRODUCT_H #include <QWidget> #include <QVector> #include <QString> #include <QMessageBox> namespace Ui { class SaleProduct; } class SaleProduct : public QWidget { Q_OBJECT public: explicit SaleProduct(QWidget *parent = nullptr); explicit SaleProduct(QVector<QString> &); ~SaleProduct(); private slots: void on_pushButton_2_clicked(); void on_pushButton_clicked(); private: Ui::SaleProduct *ui; private: QVector<QString> vec; double tmp{}; QString date{}; signals: void upd_data(QVector<QString> &); void sale_data(QVector<QString> &); }; #endif // SALEPRODUCT_H <file_sep>/izmproduct.h #ifndef IZMPRODUCT_H #define IZMPRODUCT_H #include <QWidget> #include <QVector> #include <QString> namespace Ui { class izmProduct; } class izmProduct : public QWidget { Q_OBJECT public: explicit izmProduct(QWidget *parent = nullptr); explicit izmProduct(QVector<QString> &); ~izmProduct(); private slots: void on_pushButton_clicked(); private: Ui::izmProduct *ui; private: QVector<QString> vec; signals: void izm_Prd(QVector<QString> &); }; #endif // IZMPRODUCT_H <file_sep>/db.h #ifndef DB_H #define DB_H #include <QSqlDatabase> #include <QSqlQueryModel> #include <QSqlTableModel> #include <QSqlQuery> #include <QDir> #include <QString> #include <QFile> #include <QVector> #include <QAxObject> class DB { public: DB(); ~DB(); public: bool GreateDb(); QSqlQueryModel* GetProduct(); QSqlTableModel* GetProductSales(); void addProduct(QVector<QString> const &); bool delProduct(int const &); QVector<QString>& getPoroductInfo(int const &); bool updateProduct(QVector<QString> const &); void addProductSales(QVector<QString> const &); void printData(const QString &, QObject *); private: QSqlDatabase db; QSqlQueryModel* model; QSqlTableModel* tmodel; QSqlQuery* querly; QFile* file; QAxObject* word; QAxObject* doc; QVector<QString> vec; QDir Path; }; extern double total; #endif // DB_H <file_sep>/mainwindow.cpp #include "mainwindow.h" #include "ui_mainwindow.h" MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent) , ui(new Ui::MainWindow) { ui->setupUi(this); } //================================================ MainWindow::~MainWindow() { delete ui; delete maddPrd; delete mizmPrd; delete msalePrd; delete mprdSales; } //================================================ void MainWindow::on_pushButton_clicked() { if(!mDB.GreateDb()){ QMessageBox::information(this, "Информация", "Соединение с базой данных не установлено"); } else { QMessageBox::information(this, "Информация", "Соединение с базой данных установлено"); ui->pushButton->setEnabled(false); ui->pushButton_2->setEnabled(true); ui->pushButton_3->setEnabled(true); ui->pushButton_7->setEnabled(true); } } //=================================================== void MainWindow::on_pushButton_2_clicked() { ui->tableView->setModel(mDB.GetProduct()); ui->tableView->resizeColumnsToContents(); ui->tableView->show(); } //================================================================== void MainWindow::on_pushButton_3_clicked() { maddPrd = new addProduct(); connect(maddPrd, &addProduct::refresh_table, this, &MainWindow::add_product); maddPrd->show(); } //============================================================= void MainWindow::add_product(QVector<QString> &vec) { mDB.addProduct(vec); on_pushButton_2_clicked(); } //============================================================ void MainWindow::on_tableView_clicked(const QModelIndex &index) { id = ui->tableView->model()->data(ui->tableView->model()->index(index.row(),0)).toInt(); ui->pushButton_4->setEnabled(true); ui->pushButton_5->setEnabled(true); ui->pushButton_6->setEnabled(true); } //==================================================== void MainWindow::on_pushButton_4_clicked() { if(mDB.delProduct(id)) { on_pushButton_2_clicked(); } ui->pushButton_4->setEnabled(false); ui->pushButton_5->setEnabled(false); ui->pushButton_6->setEnabled(false); } //===================================================== void MainWindow::on_pushButton_5_clicked() { mizmPrd = new izmProduct(mDB.getPoroductInfo(id)); connect(mizmPrd, &izmProduct::izm_Prd, this, &MainWindow::upd_product); mizmPrd->show(); } //=========================================================== void MainWindow::upd_product(QVector<QString> & v) { if(mDB.updateProduct(v)) { on_pushButton_2_clicked(); ui->pushButton_5->setEnabled(false); ui->pushButton_4->setEnabled(false); ui->pushButton_6->setEnabled(false); } } //========================================================= void MainWindow::on_pushButton_6_clicked() { msalePrd = new SaleProduct(mDB.getPoroductInfo(id)); connect(msalePrd, &SaleProduct::upd_data, this, &MainWindow::upd_product); connect(msalePrd, &SaleProduct::sale_data, this, &MainWindow::add_productsales); msalePrd->show(); ui->pushButton_5->setEnabled(false); ui->pushButton_4->setEnabled(false); ui->pushButton_6->setEnabled(false); } //=============================================================== void MainWindow::add_productsales(QVector<QString> &vec) { mDB.addProductSales(vec); } //========================================================= void MainWindow::on_pushButton_7_clicked() { mprdSales = new Productsales(mDB.GetProductSales()); connect(mprdSales, &Productsales::printfSales, this, &MainWindow::print_data); mprdSales->show(); } //====================================================== void MainWindow::on_pushButton_8_clicked() { exit(0); } //==================================================== void MainWindow::print_data(const QString & str) { mDB.printData(str, mprdSales); } <file_sep>/izmproduct.cpp #include "izmproduct.h" #include "ui_izmproduct.h" izmProduct::izmProduct(QWidget *parent) : QWidget(parent), ui(new Ui::izmProduct) { ui->setupUi(this); } //=============================================== izmProduct::izmProduct(QVector<QString> & vec): ui(new Ui::izmProduct) { ui->setupUi(this); auto it = vec.begin(); ui->lineEdit->setText(*it); std::advance(it,1); ui->lineEdit_2->setText(*it); std::advance(it,1); ui->lineEdit_3->setText(*it); std::advance(it,1); ui->lineEdit_4->setText(*it); std::advance(it,1); ui->lineEdit_5->setText(*it); } //=================================================== izmProduct::~izmProduct() { delete ui; } //============================================= void izmProduct::on_pushButton_clicked() { vec.clear(); vec.push_back(ui->lineEdit->text()); vec.push_back(ui->lineEdit_2->text()); vec.push_back(ui->lineEdit_3->text()); vec.push_back(ui->lineEdit_4->text()); vec.push_back(ui->lineEdit_5->text()); emit izm_Prd(vec); this->close(); } //================================================== <file_sep>/db.cpp #include "db.h" #include <QtDebug> DB::DB() { } //============================================ DB::~DB() { delete querly; delete model; delete tmodel; delete file; delete word; delete doc; } //============================================== bool DB::GreateDb() { bool fl{false}; QString path{Path.currentPath()+"/"+"test.db"}; db = QSqlDatabase::addDatabase("QSQLITE"); if(!QFile(path).exists()){ db.setDatabaseName(path); if (db.open()) { querly = new QSqlQuery(db); fl = true; querly->exec("CREATE TABLE product ""(id integer primary key, ""name varchar(30), ""col integer," """date varchar(10), ""price double)"); querly->exec("CREATE TABLE productsales ""(id integer, ""name varchar(30), ""col integer," """date varchar(10), ""price double, ""pricesales double )"); } } else { db.setDatabaseName(path); if (db.open()) {fl = true; querly = new QSqlQuery(db);} } return fl; } //========================================================================== QSqlQueryModel* DB::GetProduct() { model = new QSqlQueryModel(); model->setQuery("SELECT * FROM product"); model->setHeaderData(0,Qt::Horizontal,"Номер позиции"); model->setHeaderData(1,Qt::Horizontal,"Наименование товара"); model->setHeaderData(2,Qt::Horizontal,"В наличии"); model->setHeaderData(3,Qt::Horizontal,"Дата производства"); model->setHeaderData(4,Qt::Horizontal,"Цена на реализацию за ед. товара"); return model; } //========================================================================= void DB::addProduct(QVector<QString> const &v) { querly->prepare("INSERT INTO product(name, col, date, price) VALUES(:name, :col, :date, :price)"); auto it = v.begin(); querly->bindValue(":name",*it); std::advance(it,1); querly->bindValue(":col",it->toInt()); std::advance(it,1); querly->bindValue(":date",*it); std::advance(it,1); querly->bindValue(":price",it->toDouble()); querly->exec(); } //===================================================== bool DB::delProduct(int const & id) { querly->prepare("DELETE FROM product WHERE id=?"); querly->bindValue(0,id); return querly->exec(); } //=========================================================== QVector<QString>& DB::getPoroductInfo(int const & id) { querly->prepare("SELECT name, col, date, price FROM product WHERE id=?"); querly->bindValue(0,id); vec.clear(); if(querly->exec()){ querly->next(); vec.push_back(querly->value(0).toString()); vec.push_back(querly->value(1).toString()); vec.push_back(querly->value(2).toString()); vec.push_back(querly->value(3).toString()); vec.push_back(QString::number(id)); } return vec; } //======================================================================= bool DB::updateProduct(QVector<QString> const & vec) { querly->prepare("UPDATE product SET name = ?, col = ?, date = ?, price = ? WHERE id = ?"); auto it = vec.begin(); querly->bindValue(0,*it); std::advance(it,1); querly->bindValue(1,it->toInt()); std::advance(it,1); querly->bindValue(2,*it); std::advance(it,1); querly->bindValue(3,it->toDouble()); std::advance(it,1); querly->bindValue(4,it->toInt()); return querly->exec();; } //=========================================================================== void DB::addProductSales(QVector<QString> const & vec) { querly->prepare("INSERT INTO productsales(name, col, date, price, pricesales, id)" " VALUES(:name, :col, :date, :price, :pricesales, :id)"); auto it = vec.begin(); querly->bindValue(":name",*it); std::advance(it,1); querly->bindValue(":col",it->toInt()); std::advance(it,1); querly->bindValue(":date",*it); std::advance(it,1); querly->bindValue(":price",it->toDouble()); std::advance(it,1); querly->bindValue(":pricesales",it->toDouble()); std::advance(it,1); querly->bindValue(":id",it->toInt()); querly->exec(); } //========================================================================================== QSqlTableModel* DB::GetProductSales() { tmodel = new QSqlTableModel(); tmodel->setTable("productsales"); tmodel->select(); tmodel->setHeaderData(0,Qt::Horizontal,"Номер позиции"); tmodel->setHeaderData(1,Qt::Horizontal,"Наименование товара"); tmodel->setHeaderData(2,Qt::Horizontal,"Кол. реализованного товара"); tmodel->setHeaderData(3,Qt::Horizontal,"Дата реализации"); tmodel->setHeaderData(4,Qt::Horizontal,"Цена на реализацию за ед. товара"); tmodel->setHeaderData(5,Qt::Horizontal,"Сумма за реализацию"); if(querly->exec("SELECT * FROM productsales")){ while (querly->next()) { total += querly->value(5).toDouble(); } } return tmodel; } double total{}; //============================================================================ void DB::printData(const QString &str, QObject *obj) { if(str == "SALES") { file = new QFile(Path.currentPath()+"/"+"sales.html"); file->open(QIODevice::WriteOnly); QTextStream in(file); in << "<html><head><head><body><center>" + QString("Отчет о продажах"); in << "<table bolder-1><tr>"; in << "<td>" + QString("Номер позиции") + "<td>"; in << "<td>" + QString("Наименование товара") + "<td>"; in << "<td>" + QString("Кол. реализованного товара") + "<td>"; in << "<td>" + QString("Дата реализации") + "<td>"; in << "<td>" + QString("Цена на реализацию за ед. товара") + "<td>"; in << "<td>" + QString("Сумма за реализацию товара") + "<td><tr>"; querly->exec("SELECT * FROM productsales"); while (querly->next()) { in << "<td>"; in << querly->value(0).toString(); in << "<td><td>"; in << querly->value(1).toString(); in << "<td><td>"; in << querly->value(2).toString(); in << "<td><td>"; in << querly->value(3).toString(); in << "<td><td>"; in << querly->value(4).toString(); in << "<td><td>"; in << querly->value(5).toString(); in << "<td><tr>"; } in << QString("Итоговая сумма :"); in << "<td>"; in << QString::number(total); in <<"<table><center><body><html>"; file->close(); word= new QAxObject("Word.Application",obj); word->setProperty("DisplayAlerts", false); word->setProperty("Visible", true); doc = word->querySubObject("Documents"); doc->dynamicCall("Open(QVariant)",Path.currentPath()+"/"+"sales.html"); } } <file_sep>/addproduct.h #ifndef ADDPRODUCT_H #define ADDPRODUCT_H #include <QWidget> #include <QVector> #include <QString> #include <QMessageBox> namespace Ui { class addProduct; } class addProduct : public QWidget { Q_OBJECT public: explicit addProduct(QWidget *parent = nullptr); ~addProduct(); private slots: void on_pushButton_clicked(); private: Ui::addProduct *ui; private: QVector<QString> vec; bool fl{true}; signals: void refresh_table(QVector<QString>&); }; #endif // ADDPRODUCT_H <file_sep>/mainwindow.h #ifndef MAINWINDOW_H #define MAINWINDOW_H #include <QMainWindow> #include <QMessageBox> #include "db.h" #include "addproduct.h" #include "ui_addproduct.h" #include "izmproduct.h" #include "ui_izmproduct.h" #include "saleproduct.h" #include "ui_saleproduct.h" #include "productsales.h" #include "ui_productsales.h" QT_BEGIN_NAMESPACE namespace Ui { class MainWindow; } QT_END_NAMESPACE class MainWindow : public QMainWindow { Q_OBJECT public: MainWindow(QWidget *parent = nullptr); ~MainWindow(); private slots: void on_pushButton_clicked(); void on_pushButton_2_clicked(); void on_pushButton_3_clicked(); void add_product(QVector<QString> &); void upd_product(QVector<QString> &); void add_productsales(QVector<QString> &); void print_data(const QString &); void on_tableView_clicked(const QModelIndex &index); void on_pushButton_4_clicked(); void on_pushButton_5_clicked(); void on_pushButton_6_clicked(); void on_pushButton_7_clicked(); void on_pushButton_8_clicked(); private: Ui::MainWindow *ui; private: DB mDB; addProduct* maddPrd; izmProduct* mizmPrd; SaleProduct* msalePrd; Productsales* mprdSales; int id{}; }; #endif // MAINWINDOW_H <file_sep>/addproduct.cpp #include "addproduct.h" #include "ui_addproduct.h" addProduct::addProduct(QWidget *parent) : QWidget(parent), ui(new Ui::addProduct) { ui->setupUi(this); ui->dateEdit->setDate(QDate::currentDate()); } addProduct::~addProduct() { delete ui; } void addProduct::on_pushButton_clicked() { fl = true; if(ui->lineEdit->text().isEmpty() || ui->lineEdit_2->text().isEmpty() || ui->lineEdit_3->text().isEmpty()) { QMessageBox::information(this, "Информация", "Не все поля заполнены"); fl = false; } if(fl){ for(auto &it: ui->lineEdit_3->text()){ if(it.unicode() < 48 || it.unicode() > 57 ){ if(it.unicode() == 46) continue; fl = false; QMessageBox::information(this, "Информация", "Поле цены заполнено не корректно"); break; } } } if(fl){ for(auto &it: ui->lineEdit_2->text()){ if(it.unicode() < 48 || it.unicode() > 57 ){ fl = false; QMessageBox::information(this, "Информация", "Поле колличество заполнено не корректно"); break; } } } if(fl) { vec.clear(); vec.push_back(ui->lineEdit->text()); vec.push_back(ui->lineEdit_2->text()); vec.push_back(ui->dateEdit->text()); vec.push_back(ui->lineEdit_3->text()); emit refresh_table(vec); this->close(); } } //================================================== <file_sep>/productsales.cpp #include "productsales.h" #include "ui_productsales.h" #include "db.h" Productsales::Productsales(QWidget *parent) : QWidget(parent), ui(new Ui::Productsales) { ui->setupUi(this); } //=============================================== Productsales::Productsales(QSqlTableModel* model): ui(new Ui::Productsales) { ui->setupUi(this); ui->tableView->setModel(model); ui->tableView->resizeColumnsToContents(); ui->tableView->show(); ui->lineEdit->setText(QString::number(total)); } //=========================================== Productsales::~Productsales() { delete ui; } //============================================== void Productsales::on_pushButton_clicked() { this->close(); } void Productsales::on_pushButton_2_clicked() { emit printfSales("SALES"); } <file_sep>/saleproduct.cpp #include "saleproduct.h" #include "ui_saleproduct.h" SaleProduct::SaleProduct(QWidget *parent) : QWidget(parent), ui(new Ui::SaleProduct) { ui->setupUi(this); } //============================================= SaleProduct::SaleProduct(QVector<QString> & vec): ui(new Ui::SaleProduct) { ui->setupUi(this); auto it = vec.begin(); ui->lineEdit->setText(*it); std::advance(it,1); ui->lineEdit_2->setText(*it); std::advance(it,1); date = *it; std::advance(it,1); ui->dateEdit->setDate(QDate::currentDate()); ui->lineEdit_5->setText(*it); std::advance(it,1); ui->lineEdit_4->setText(*it); std::advance(it,1); } //============================================ SaleProduct::~SaleProduct() { delete ui; } //============================================== void SaleProduct::on_pushButton_2_clicked() { if(ui->lineEdit_3->text().toInt() > ui->lineEdit_2->text().toInt() || ui->lineEdit_3->text().toInt() <= 0){ QMessageBox::information(this, "Информация", "Поле Колличество на реализацию заполнено не корректно"); } tmp = ui->lineEdit_3->text().toDouble() * ui->lineEdit_5->text().toDouble(); ui->lineEdit_6->setText(QString::number(tmp)); ui->pushButton->setEnabled(true); } //================================================== void SaleProduct::on_pushButton_clicked() { vec.clear(); vec.push_back(ui->lineEdit->text()); vec.push_back(QString::number(ui->lineEdit_2->text().toInt() - ui->lineEdit_3->text().toInt())); vec.push_back(date); vec.push_back(ui->lineEdit_5->text()); vec.push_back(ui->lineEdit_4->text()); emit upd_data(vec); vec.clear(); vec.push_back(ui->lineEdit->text()); vec.push_back(ui->lineEdit_3->text()); vec.push_back(ui->dateEdit->text()); vec.push_back(ui->lineEdit_5->text()); vec.push_back(ui->lineEdit_6->text()); vec.push_back(ui->lineEdit_4->text()); emit sale_data(vec); this->close(); }
774d4026e08c230188a1257c4e2fae964ab38e9c
[ "C++" ]
11
C++
Garald-48rus/SqlGuide
9d1db8d28b9a844554dc281336eaaf2e19cb70a4
e73f07bdeb2988d9ddffa9f85d8e8e5f2dba43bf
refs/heads/master
<repo_name>suyridan/ConnectBD<file_sep>/README.md # ConnectBD Clase para conexión de base de datos en PDO con funciones de consulta y ejecución de SQL. <file_sep>/connectDB.php <?php class connectDB { /** * Clase para conexion a base de datos por medio del metodo PDO * * @param string $database base de datos (mysql,pgsql) * @param string $host direccion del host de la base de datos * @param string $dbname Nombre de la base de datos * @param string $user Nombre de usuario para la conexcion * @param string $password <PASSWORD> * */ protected $database = 'pgsql'; protected $host = '127.0.0.1'; protected $dbname = 'test'; protected $user = 'postgres'; protected $password = '<PASSWORD>'; public $conn; public function __construct(){ try { $this->conn = new PDO($this->database.":host=".$this->host." dbname=".$this->dbname." user=".$this->user." password=".$this-><PASSWORD>); $this->conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); return $this->conn; } catch (PDOException $exepcion) { return $exepcion; } } /** * Ejecuta y devuelve el número de filas afectadas de una consulta UPDATE / INSERT / DELETE. * * @param string $consulta Consulta en formato PDO * @param array $valores Valores vinculados a la consulta * @return int Número de filas afectadas después de ejecutar la consulta */ function getFilasAfectadas($consulta, $valores) { try{ $consultaSQL = $this->conn->prepare($consulta); $consultaSQL -> execute($valores); return $consultaSQL -> rowCount(); } catch (Exception $e){ return false; } } /** * Ejecuta y devuelve el resultado de una consulta SELECT en formato JSON. * * @param string $consulta Consulta en formato PDO * @param array $valores Valores vinculados a la consulta * @return string Resultado de la consulta (en JSON) */ function getFilasJSON($consulta, $valores) { return json_encode($this->getFilasArrayUTF8($consulta, $valores)); } /** * Devuelve un arreglo con todas sus llaves en letras minúscula. * @param array $array Arreglo del que se cambiarán las llaves * @return array NUevo arreglo con las llaves en minúscula */ function arregloMinusculas($array){ $rowsn = array(); for($i=0;$i<count($array);$i++){ $rowsn[$i]=array(); foreach ($array[$i] as $k => $v) { $rowsn[$i][mb_strtolower($k)] = $v; } } return $rowsn; } /** * Ejecuta y devuelve el resultado de una consulta SELECT en formato JSON. * Es igual a la función getFilasJSON($consulta, $vars, $conexion), pero * adicionalmente cambia la codificación de los valores a UTF8 * * @param string $consulta Consulta en formato PDO * @param array $valores Valores vinculados a la consulta * @return string Resultado de la consulta (en JSON) */ function getFilasArrayUTF8($consulta, $valores) { try{ $pdo = $this->conn->prepare($consulta); $pdo-> execute($valores); $res = $pdo->fetchAll(PDO::FETCH_ASSOC); return $this->arregloMinusculas($res); } catch (Exception $ex){ return NULL; } } /** * Ejecuta y devuelve el resultado de una consulta SELECT en formato JSON. * Es igual a la función getFilasJSON($consulta, $vars, $conexion), pero * adicionalmente cambia la codificación de los valores a UTF8 * * @param string $consulta Consulta en formato PDO * @param array $valores Valores vinculados a la consulta * @return string Resultado de la consulta (en JSON) */ function getFilasJSONutf8($consulta, $valores) { $consultaSQL = $this->conn->prepare($consulta); if ($consultaSQL->execute($valores)) { $resultado = $this->filasLATIN1aUTF8($consultaSQL); return json_encode( $this->arregloMinusculas($resultado)); } return NULL; } /** * Ejecuta y devuelve el resultado de una consulta SELECT en un array. * * @param string $consulta Consulta en formato PDO * @param array $valores Valores vinculados a la consulta * @return string Resultado de la consulta (en array) */ function getFilasUTF8($consulta, $valores) { $consultaSQL = $this->conn->prepare($consulta); if ($consultaSQL->execute($valores)) { $resultado = $this->arregloMinusculas($this->filasLATIN1aUTF8($consultaSQL)); return $resultado; } return NULL; } /** * Convierte de codificación latin1 a utf8, los valores de todas las columnas * de todos las filas de la consulta * * @param PDOStatement $consultaSQL Contiene los resultados de la consulta * @return array Arreglo con las filas de $consultaSQL codificadas en utf8 */ function filasLATIN1aUTF8($consultaSQL) { $resultado = array(); while ($fila = $consultaSQL->fetch(PDO::FETCH_ASSOC)) { foreach ($fila as $columna => $valor) { $str_tmp = utf8_encode($fila[$columna]); $fila[$columna] = $str_tmp; } $resultado[] = $fila; } return $resultado; } } ?>
ae4effae9f1d70f2b5ae3d107f720e212c5ffd35
[ "Markdown", "PHP" ]
2
Markdown
suyridan/ConnectBD
f3e02e6cdb7bee962e5e9b7245f062bb20241bec
42a2911fc4aa3782f002dea72b16dd85c7360e59
refs/heads/master
<file_sep>package eu.iescities.pilot.rovereto.roveretoexplorer; import java.util.ArrayList; import android.app.Activity; import android.content.Intent; import android.content.pm.PackageManager.NameNotFoundException; import android.content.res.Configuration; import android.content.res.Resources.NotFoundException; import android.content.res.TypedArray; import android.os.Bundle; import android.support.v4.app.ActionBarDrawerToggle; import android.support.v4.app.FragmentActivity; import android.support.v4.app.FragmentManager; import android.support.v4.widget.DrawerLayout; import android.support.v7.app.ActionBarActivity; import android.view.MenuItem; import android.widget.ListView; import android.widget.Toast; import eu.iescities.pilot.rovereto.roveretoexplorer.custom.AbstractAsyncTaskProcessor; import eu.iescities.pilot.rovereto.roveretoexplorer.custom.DrawerItemOld; import eu.iescities.pilot.rovereto.roveretoexplorer.custom.HackActionBarToggle; import eu.iescities.pilot.rovereto.roveretoexplorer.custom.data.DTHelper; import eu.iescities.pilot.rovereto.roveretoexplorer.custom.data.model.BaseDTObject; import eu.iescities.pilot.rovereto.roveretoexplorer.map.MapFragment; import eu.iescities.pilot.rovereto.roveretoexplorer.ui.navdrawer.NavDrawerAdapter; import eu.iescities.pilot.rovereto.roveretoexplorer.ui.navdrawer.NavDrawerItem; import eu.iescities.pilot.rovereto.roveretoexplorer.ui.navdrawer.NavMenuItem; import eu.trentorise.smartcampus.android.common.GlobalConfig; import eu.trentorise.smartcampus.android.common.SCAsyncTask; import eu.trentorise.smartcampus.protocolcarrier.exceptions.SecurityException; public class MainActivityOld extends ActionBarActivity{ public static final String TAG_FRAGMENT_MAP = "fragmap"; public static final String TAG_FRAGMENT_POI_LIST = "fragpopi"; public static final String TAG_FRAGMENT_EVENT_LIST = "fragewent"; public static final String TAG_FRAGMENT_TRACK_LIST = "fragtrack"; public static final String TAG_FRAGMENT_INFO_LIST = "fraginfo"; private FragmentManager mFragmentManager; private DrawerLayout mDrawerLayout; private ListView mListView; private ActionBarDrawerToggle mDrawerToggle; private String[] navMenuTitles; private boolean isLoading; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); getSupportActionBar().setDisplayHomeAsUpEnabled(true); getSupportActionBar().setHomeButtonEnabled(true); setupProperties(); initDataManagement(savedInstanceState); } //it is not referenced anywhere /*public void navDrawerOutItemClick(View v) { if (v.getId() == R.id.tv_header) { if (! (mFragmentManager.findFragmentById(R.id.frame_content) instanceof MapFragment)) onChildClick(null, null, -1, -1, -1); else mDrawerLayout.closeDrawers(); } } */ private void initDataManagement(Bundle savedInstanceState) { try { initGlobalConstants(); try { // if (!SCAccessProvider.getInstance(this).login(this, null)) { DTHelper.init(getApplicationContext()); initData(); // } } catch (Exception e) { e.printStackTrace(); Toast.makeText(this, getString(R.string.auth_failed), Toast.LENGTH_SHORT).show(); finish(); } } catch (Exception e) { Toast.makeText(this, R.string.app_failure_init, Toast.LENGTH_LONG).show(); e.printStackTrace(); return; } } private void initGlobalConstants() throws NameNotFoundException, NotFoundException { GlobalConfig.setAppUrl(this, getResources().getString(R.string.smartcampus_app_url)); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); } private boolean initData() { try { // to start with the map. mFragmentManager.beginTransaction().replace(R.id.content_frame, new MapFragment(), TAG_FRAGMENT_MAP).commit(); new SCAsyncTask<Void, Void, BaseDTObject>(this, new LoadDataProcessor(this)).execute(); } catch (Exception e1) { Toast.makeText(this, R.string.app_failure_init, Toast.LENGTH_LONG).show(); return false; } return true; } private void setupProperties() { mFragmentManager = getSupportFragmentManager(); mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout); // this is a class created to avoid an Android bug // see the class for further infos. mDrawerToggle = new HackActionBarToggle(this, mDrawerLayout, R.drawable.ic_drawer, R.string.app_name, R.string.app_name); mDrawerLayout.setDrawerListener(mDrawerToggle); mListView = (ListView) findViewById(R.id.left_drawer); navMenuTitles = getResources().getStringArray(R.array.fragments_label_array); //Add header title //LayoutInflater inflater = getLayoutInflater(); //ViewGroup header_news = (ViewGroup)inflater.inflate(R.layout.drawer_header_title, mListView, false); //mListView.addHeaderView(header_news, null, false); NavDrawerAdapter nda = buildAdapter(); mListView.setAdapter(nda); //mListView.setOnChildClickListener(this); } private NavDrawerAdapter buildAdapter() { //ArrayList<DrawerItem> items = new ArrayList<DrawerItem>(); // getting items from the xml // see the method for further infos // ArrayList<DrawerItemOld> items = populateFromXml(R.array.drawer_items_labels, // R.array.drawer_items_icons); ArrayList<NavDrawerItem> items = populateFromXml(R.array.drawer_items_labels, R.array.drawer_items_icons); return new NavDrawerAdapter(this, R.layout.navdrawer_item, items); } /** * @param items * where to put elements * @param ids * array of arrays made in xml */ private ArrayList<NavDrawerItem> populateFromXml(int... ids) { ArrayList<NavDrawerItem> items = new ArrayList<NavDrawerItem>(); String[] labels = getResources().getStringArray(ids[0]); TypedArray drawIds = getResources().obtainTypedArray((ids[1])); for (int j = 0; j < labels.length; j++) { int imgd = drawIds.getResourceId(j, -1); items.add(NavMenuItem.create(j, labels[j], ((imgd != -1) ? imgd : null), false, false, this)); } drawIds.recycle(); return items; } /** * @param items * where to put elements * @param ids * array of arrays made in xml */ private ArrayList<DrawerItemOld> populateFromXml2(int... ids) { ArrayList<DrawerItemOld> items = new ArrayList<DrawerItemOld>(); String[] labels = getResources().getStringArray(ids[0]); TypedArray drawIds = getResources().obtainTypedArray((ids[1])); for (int j = 0; j < labels.length; j++) { int imgd = drawIds.getResourceId(j, -1); items.add(new DrawerItemOld( labels[j], ((imgd != -1) ? getResources().getDrawable(imgd) : null))); } drawIds.recycle(); return items; } @Override protected void onDestroy() { DTHelper.destroy(); super.onDestroy(); } @Override public boolean onOptionsItemSelected(MenuItem item) { if (mDrawerToggle.onOptionsItemSelected(item)) { return true; } return false; } @Override protected void onPause() { if (DTHelper.getLocationHelper() != null) DTHelper.getLocationHelper().stop(); super.onPause(); } @Override protected void onPostCreate(Bundle savedInstanceState) { super.onPostCreate(savedInstanceState); // Sync the toggle state after onRestoreInstanceState has occurred. mDrawerToggle.syncState(); } @Override protected void onResume() { if (DTHelper.getLocationHelper() != null) DTHelper.getLocationHelper().start(); super.onResume(); } @Override public void onConfigurationChanged(Configuration newConfig) { super.onConfigurationChanged(newConfig); mDrawerToggle.onConfigurationChanged(newConfig); } private class LoadDataProcessor extends AbstractAsyncTaskProcessor<Void, BaseDTObject> { private int syncRequired = 0; private FragmentActivity currentRootActivity = null; public LoadDataProcessor(Activity activity) { super(activity); } @Override public BaseDTObject performAction(Void... params) throws SecurityException, Exception { Exception res = null; try { syncRequired = DTHelper.SYNC_REQUIRED;//DTHelper.syncRequired(); } catch (Exception e) { res = e; } if (res != null) { throw res; } return null; } @Override public void handleResult(BaseDTObject result) { if (syncRequired != DTHelper.SYNC_NOT_REQUIRED) { if (syncRequired == DTHelper.SYNC_REQUIRED_FIRST_TIME) { Toast.makeText(MainActivityOld.this, R.string.initial_data_load, Toast.LENGTH_LONG).show(); } setSupportProgressBarIndeterminateVisibility(true); isLoading = true; new Thread(new Runnable() { @Override public void run() { try { currentRootActivity = DTHelper.start(MainActivityOld.this); } catch (Exception e) { e.printStackTrace(); } finally { if (currentRootActivity != null) { currentRootActivity.runOnUiThread(new Runnable() { @Override public void run() { currentRootActivity.setProgressBarIndeterminateVisibility(false); if (MainActivityOld.this != null) { MainActivityOld.this.setSupportProgressBarIndeterminateVisibility(false); } isLoading = false; } }); } } } }).start(); } else { setSupportProgressBarIndeterminateVisibility(false); // DTHelper.activateAutoSync(); } } } } <file_sep>package eu.iescities.pilot.rovereto.roveretoexplorer.fragments.event; public interface ReloadAdapter { public void reload(); } <file_sep>package eu.iescities.pilot.rovereto.roveretoexplorer.fragments.search; import android.os.Parcel; import android.os.Parcelable; public class WhenForSearch implements Parcelable{ private String description; private long from; private long to; public WhenForSearch(String description, long from, long to) { this.description=description; this.from = from; this.to = to; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public long getFrom() { return from; } public void setFrom(long from) { this.from = from; } public long getTo() { return to; } public void setTo(long to) { this.to = to; } @Override public String toString() { return description; } @Override public int describeContents() { return 0; } @Override public void writeToParcel(Parcel dest, int flags) { } } <file_sep>/******************************************************************************* * Copyright 2012-2013 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package eu.iescities.pilot.rovereto.roveretoexplorer.custom; import android.app.Activity; import android.app.AlertDialog; import android.content.DialogInterface; import android.support.v4.app.FragmentActivity; import android.support.v4.app.FragmentTransaction; import android.view.MotionEvent; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.ImageView; import android.widget.RatingBar; import android.widget.TextView; import android.widget.Toast; import eu.iescities.pilot.rovereto.roveretoexplorer.R; import eu.iescities.pilot.rovereto.roveretoexplorer.custom.ReviewHelper.ReviewHandler; import eu.iescities.pilot.rovereto.roveretoexplorer.custom.data.DTHelper; import eu.iescities.pilot.rovereto.roveretoexplorer.custom.data.model.BaseDTObject; import eu.iescities.pilot.rovereto.roveretoexplorer.custom.data.model.CommunityData; import eu.iescities.pilot.rovereto.roveretoexplorer.custom.data.model.Review; import eu.iescities.pilot.rovereto.roveretoexplorer.fragments.ReviewListFragment; import eu.trentorise.smartcampus.ac.AACException; import eu.trentorise.smartcampus.ac.SCAccessProvider; import eu.trentorise.smartcampus.android.common.SCAsyncTask; import eu.trentorise.smartcampus.protocolcarrier.exceptions.SecurityException; /** * @author raman * */ public class CommentsHandler { private boolean commentsVisible = false; private FragmentActivity activity = null; private View main; private BaseDTObject object = null; /** * @param ctx * @param toggle * @param container */ public CommentsHandler(BaseDTObject object, FragmentActivity activity, View main) { super(); this.activity = activity; this.main = main; TextView toggle = (TextView)main.findViewById(R.id.comments_tv); ImageView toggleButton = (ImageView) main.findViewById(R.id.comments_button); Button rateButton = (Button) main.findViewById(R.id.rate_button); this.object = object; OnClickListener commentsListener = new OnClickListener() { @Override public void onClick(View v) { commentsVisible = !commentsVisible; if (commentsVisible) { loadComments(); } } }; toggle.setOnClickListener(commentsListener); toggleButton.setOnClickListener(commentsListener); RatingBar rating = (RatingBar) main.findViewById(R.id.rating); rating.setOnTouchListener(new View.OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { if (event.getAction() == MotionEvent.ACTION_UP) { ratingDialog(); } return true; } }); rateButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { ratingDialog(); } }); updateRating(); } private void ratingDialog() { if (!signedIn()) { return; } float rating = (object != null && object.getCommunityData() != null && object.getCommunityData() .getAverageRating() > 0) ? object.getCommunityData().getAverageRating() : 2.5f; ReviewHelper.reviewDialog(activity, rating, new ReviewProcessor(activity), R.string.rating_event_dialog_title); } private void updateRating() { if (main != null) { RatingBar rating = (RatingBar) main.findViewById(R.id.rating); if (object.getCommunityData() != null) { CommunityData cd = object.getCommunityData(); rating.setRating(cd.getAverageRating()); // total raters ((TextView) main.findViewById(R.id.rating_raters)).setText(activity.getString(R.string.ratingtext_raters,""+cd.getRatingsCount())); } } } protected boolean signedIn() { SCAccessProvider provider = SCAccessProvider.getInstance(activity); try { if (provider.isLoggedIn(activity)) { return true; } showLoginDialog(provider); } catch (AACException e) { e.printStackTrace(); return false; } return false; } private void showLoginDialog(final SCAccessProvider accessprovider) { // dialogbox for registration DialogInterface.OnClickListener updateDialogClickListener; updateDialogClickListener = new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { switch (which) { case DialogInterface.BUTTON_POSITIVE: try { accessprovider.login(activity, null); } catch (AACException e) { e.printStackTrace(); } break; case DialogInterface.BUTTON_NEGATIVE: break; } } }; AlertDialog.Builder builder = new AlertDialog.Builder(activity); builder.setCancelable(false); builder.setMessage(activity.getString(R.string.auth_required)) .setPositiveButton(android.R.string.yes, updateDialogClickListener) .setNegativeButton(android.R.string.no, updateDialogClickListener).show(); } private void loadComments() { FragmentTransaction fragmentTransaction = activity.getSupportFragmentManager().beginTransaction(); ReviewListFragment fragment = new ReviewListFragment(); fragment.setArguments(ReviewListFragment.prepareArgs(object)); fragmentTransaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE); fragmentTransaction.replace(R.id.content_frame, fragment); fragmentTransaction.addToBackStack(fragment.getTag()); fragmentTransaction.commit(); } private class ReviewProcessor extends AbstractAsyncTaskProcessor<Review, CommunityData> implements ReviewHandler { public ReviewProcessor(Activity activity) { super(activity); } @Override public CommunityData performAction(Review... params) throws SecurityException, Exception { return DTHelper.writeReview(object, params[0]); } @Override public void handleResult(CommunityData result) { object.setCommunityData(result); updateRating(); if (activity != null) Toast.makeText(activity, R.string.comment_success, Toast.LENGTH_SHORT).show(); } @Override public void onReviewChanged(Review review) { new SCAsyncTask<Review, Void, CommunityData>(activity, this).execute(review); } } } <file_sep>APP for familys living in trentino, to setup you'll need: Google play services: http://developer.android.com/google/play-services/index.html Support V7:http://developer.android.com/tools/support-library/setup.html <file_sep>/******************************************************************************* * Copyright 2012-2013 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package eu.iescities.pilot.rovereto.roveretoexplorer.custom.data; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import android.content.ContentValues; import android.database.Cursor; import eu.iescities.pilot.rovereto.roveretoexplorer.custom.data.model.BaseDTObject; import eu.iescities.pilot.rovereto.roveretoexplorer.custom.data.model.CommunityData; import eu.trentorise.smartcampus.android.common.Utils; public class BaseDTStorageHelper { public static void setCommonFields(Cursor cursor, BaseDTObject o) { if (cursor != null) { o.setId(cursor.getString(cursor.getColumnIndex("id"))); o.setDescription(cursor.getString(cursor.getColumnIndex("description"))); o.setTitle(cursor.getString(cursor.getColumnIndex("title"))); o.setSource(cursor.getString(cursor.getColumnIndex("source"))); //from BasicObject o.setVersion(cursor.getLong(cursor.getColumnIndex("version"))); // set community data o.setCommunityData(new CommunityData()); o.getCommunityData().setAverageRating(cursor.getInt(cursor.getColumnIndex("averageRating"))); o.getCommunityData().setRatings( Utils.convertJSONToObjects(cursor.getString(cursor.getColumnIndex("ratings")), Rating.class)); o.getCommunityData().setRatingsCount(cursor.getInt(cursor.getColumnIndex("ratingsCount"))); o.getCommunityData().setAttendees(cursor.getInt(cursor.getColumnIndex("attendees"))); o.getCommunityData().setAttending( Utils.convertJSONToObject(cursor.getString(cursor.getColumnIndex("attending")), Set.class)); o.getCommunityData().setTags( Utils.convertJSONToObjects(cursor.getString(cursor.getColumnIndex("tags")), String.class)); o.setType(cursor.getString(cursor.getColumnIndex("type"))); o.setLocation(new double[] { cursor.getDouble(cursor.getColumnIndex("latitude")), cursor.getDouble(cursor.getColumnIndex("longitude")) }); o.setFromTime(cursor.getLong(cursor.getColumnIndex("fromTime"))); o.setToTime(cursor.getLong(cursor.getColumnIndex("toTime"))); @SuppressWarnings("unchecked") Map<String, Object> map = Utils.convertJSONToObject(cursor.getString(cursor.getColumnIndex("customData")), Map.class); if (map != null && !map.isEmpty()) o.setCustomData(map); else o.setCustomData(new HashMap<String, Object>()); } } public static ContentValues toCommonContent(BaseDTObject bean) { ContentValues values = new ContentValues(); values.put("id", bean.getId()); values.put("description", bean.getDescription()); values.put("title", bean.getTitle()); values.put("source", bean.getSource()); //from BasicObject values.put("version", bean.getVersion()); if (bean.getCommunityData() != null) { if (bean.getCommunityData().getTags() != null) { values.put("tags", Utils.convertToJSON(bean.getCommunityData().getTags())); } values.put("notes", bean.getCommunityData().getNotes()); values.put("averageRating", bean.getCommunityData().getAverageRating()); values.put("ratings", Utils.convertToJSON(bean.getCommunityData().getRatings())); if (bean.getCommunityData().getAttending()!=null && bean.getCommunityData().getAttending().isEmpty()) values.put("attending",(String) null); else values.put("attending", Utils.convertToJSON(bean.getCommunityData().getAttending())); values.put("attendees", bean.getCommunityData().getAttendees()); values.put("ratingsCount", bean.getCommunityData().getRatingsCount()); } values.put("type", bean.getType()); if (bean.getLocation() != null) { values.put("latitude", bean.getLocation()[0]); values.put("longitude", bean.getLocation()[1]); } values.put("fromTime", bean.getFromTime()); values.put("toTime", bean.getToTime()); if (bean.getCustomData() != null && !bean.getCustomData().isEmpty()) { values.put("customData", Utils.convertToJSON(bean.getCustomData())); } return values; } public static Map<String, String> getCommonColumnDefinitions() { Map<String, String> defs = new HashMap<String, String>(); defs.put("description", "TEXT"); defs.put("title", "TEXT"); defs.put("source", "TEXT"); defs.put("version", "DOUBLE"); defs.put("creatorId", "TEXT"); defs.put("creatorName", "TEXT"); defs.put("tags", "TEXT"); defs.put("notes", "TEXT"); defs.put("averageRating", "TEXT"); defs.put("ratings", "TEXT"); defs.put("attending", "TEXT"); defs.put("attendees", "INTEGER"); defs.put("ratingsCount", "INTEGER"); defs.put("type", "TEXT"); defs.put("latitude", "DOUBLE"); defs.put("longitude", "DOUBLE"); defs.put("fromTime", "DOUBLE"); defs.put("toTime", "DOUBLE"); defs.put("customData", "TEXT"); return defs; } } <file_sep>package eu.iescities.pilot.rovereto.roveretoexplorer.custom.data.model; import java.util.List; import eu.iescities.pilot.rovereto.roveretoexplorer.R; import eu.iescities.pilot.rovereto.roveretoexplorer.custom.data.Constants; public class ToKnow { private String name; //it defines whether the field is an attribute (e.g., abbigliamento consigliato) or a value (e.g., sport clothes) private String type; //it defines whether the field of type "attribute" allows for multiple values. If the field is of "value" type then this attribute is null. private Boolean multiValue = null; private Boolean addedbyUser = null; private int leftIconId = -1; private int[] rightIconIds = null; private int divider_height=1; private int divider_color = R.color.jungle_green; private boolean textInBold = false; private int default_text_color = R.color.black_background; public ToKnow() { } public ToKnow(String name, String type) { setName(name); setType(type); } public ToKnow(String name, String type, Boolean multivalue) { setName(name); setType(type); setMultiValue(multivalue); } public Boolean getMultiValue() { return multiValue; } public void setMultiValue(Boolean multiValue) { this.multiValue = multiValue; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getType() { return type; } public void setType(String type) { this.type = type; } public int getLeftIconId() { return leftIconId; } public void setLeftIconId(int leftIconId) { this.leftIconId = leftIconId; } public int[] getRightIconIds() { return rightIconIds; } public void setRightIconIds(int[] rightIconIds) { this.rightIconIds = rightIconIds; } public int getDividerColor() { return divider_color; } public void setDividerColor(int divider_colorId) { this.divider_color = divider_colorId; } public int getDividerHeight() { return divider_height; } public void setDividerHeight(int divider_height) { this.divider_height = divider_height; } public boolean getTextInBold() { return textInBold; } public void setTextInBold(boolean text_in_bold) { this.textInBold = text_in_bold; } public Boolean getAddedbyUser() { return addedbyUser; } public void setAddedbyUser(Boolean addedbyUser) { this.addedbyUser = addedbyUser; } public int getDefault_text_color() { return default_text_color; } public void setDefault_text_color(int default_text_color) { this.default_text_color = default_text_color; } public static ToKnow newCustomDataAttributeField(String name, Boolean addedByUser, int divider_height){ ToKnow toKnow = new ToKnow(name, Constants.CUSTOM_TOKNOW_TYPE_ATTRIBUTE); if ((name.matches(Constants.CUSTOM_TOKNOW_LANGUAGE_MAIN)) || (name.matches(Constants.CUSTOM_TOKNOW_CLOTHING)) || (name.matches(Constants.CUSTOM_TOKNOW_TO_BRING))) toKnow.setMultiValue(true); else toKnow.setMultiValue(false); if (addedByUser){ toKnow.setAddedbyUser(true); toKnow.setMultiValue(true); }else toKnow.setAddedbyUser(false); toKnow.setDividerHeight(divider_height); toKnow.setTextInBold(true); int[] rightIconIds1 = new int[] {R.drawable.ic_action_edit}; toKnow.setRightIconIds(rightIconIds1); return toKnow; } public static ToKnow newCustomDataValueField(String name, int divider_height){ ToKnow toKnow = new ToKnow(name, Constants.CUSTOM_TOKNOW_TYPE_VALUE); toKnow.setDividerHeight(divider_height); toKnow.setTextInBold(false); return toKnow; } } <file_sep>/******************************************************************************* * Copyright 2012-2013 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package eu.iescities.pilot.rovereto.roveretoexplorer.custom; import android.app.Dialog; import android.content.Context; import android.view.View; import android.widget.Button; import android.widget.RatingBar; import eu.iescities.pilot.rovereto.roveretoexplorer.R; public class RatingHelper { public interface RatingHandler { public void onRatingChanged(float rating); } public static void ratingDialog(Context context, float initValue, final RatingHandler handler, int ResourceString) { final Dialog rankDialog = new Dialog(context); rankDialog.setContentView(R.layout.rating); rankDialog.setCancelable(true); rankDialog.setTitle(ResourceString); final RatingBar ratingBar = (RatingBar) rankDialog.findViewById(R.id.ratingBar); ratingBar.setRating(initValue); Button updateButton = (Button) rankDialog.findViewById(R.id.rating_ok); updateButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { handler.onRatingChanged(ratingBar.getRating()); rankDialog.dismiss(); } }); Button cancelButton = (Button) rankDialog.findViewById(R.id.rating_cancel); cancelButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { rankDialog.dismiss(); } }); rankDialog.show(); } } <file_sep>package eu.iescities.pilot.rovereto.roveretoexplorer.custom; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.Calendar; import java.util.Collection; import java.util.Date; import java.util.GregorianCalendar; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.LinkedList; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Map.Entry; import java.util.StringTokenizer; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.apache.http.impl.cookie.DateUtils; import android.content.Context; import android.util.Log; import android.util.Patterns; import com.google.android.gms.maps.model.LatLng; import eu.iescities.pilot.rovereto.roveretoexplorer.R; import eu.iescities.pilot.rovereto.roveretoexplorer.custom.data.Address; import eu.iescities.pilot.rovereto.roveretoexplorer.custom.data.Constants; import eu.iescities.pilot.rovereto.roveretoexplorer.custom.data.DTHelper; import eu.iescities.pilot.rovereto.roveretoexplorer.custom.data.model.CommunityData; import eu.iescities.pilot.rovereto.roveretoexplorer.custom.data.model.ExplorerObject; import eu.iescities.pilot.rovereto.roveretoexplorer.custom.data.model.ToKnow; import eu.trentorise.smartcampus.android.common.follow.model.Concept; import eu.trentorise.smartcampus.android.common.geo.OSMAddress; import eu.trentorise.smartcampus.android.common.tagging.SemanticSuggestion; import eu.trentorise.smartcampus.android.common.tagging.SemanticSuggestion.TYPE; import eu.trentorise.smartcampus.protocolcarrier.exceptions.ConnectionException; import eu.trentorise.smartcampus.protocolcarrier.exceptions.ProtocolException; import eu.trentorise.smartcampus.protocolcarrier.exceptions.SecurityException; import eu.trentorise.smartcampus.storage.DataException; import eu.trentorise.smartcampus.storage.StorageConfigurationException; public class Utils { public static final String userPoiObject = "eu.trentorise.smartcampus.dt.model.UserPOIObject"; public static final String servicePoiObject = "eu.trentorise.smartcampus.dt.model.ServicePOIObject"; public static final SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("dd/MM/yyyy"); public static final SimpleDateFormat DATETIME_FORMAT_WITH_SEC = new SimpleDateFormat("dd/MM/yyyy hh:mm:ss"); public static final SimpleDateFormat DATETIME_FORMAT = new SimpleDateFormat("dd/MM/yyyy HH:mm"); public static final SimpleDateFormat DATE_FORMAT_2 = new SimpleDateFormat("dd MMM. yyyy"); public static final DateFormat DATE_FORMAT_2_with_dayweek = new SimpleDateFormat("EEEEEE dd MMM. yyyy"); public static final SimpleDateFormat DATE_FORMAT_2_with_time = new SimpleDateFormat("dd MMM. yyyy HH:mm"); public static final DateFormat DATE_FORMAT_2_with_dayweek_time = new SimpleDateFormat("EEEEEE dd MMM. yyyy HH:mm"); public static final SimpleDateFormat FORMAT_DATE_UI = new SimpleDateFormat("dd/MM/yy", Locale.ENGLISH); public static final SimpleDateFormat FORMAT_DATE_UI_LONG = new SimpleDateFormat("dd/MM/yyyy", Locale.ENGLISH); public static final SimpleDateFormat FORMAT_TIME_UI = new SimpleDateFormat("HH:mm", Locale.ENGLISH); public static final int PAST_MINUTES_SPAN = -5; // has to be negative public static final String ARG_EVENT_ID = "event_id"; public static final String ARG_EVENT_FIELD_TYPE = "event_field_type"; public static final String ARG_EVENT_FIELD_TYPE_IS_MANDATORY = "event_field_type_is_mandatory"; public static final String ARG_EVENT_IMAGE_URL = "event_image"; public static final String ROVERETO_REGION = "it"; public static final String ROVERETO_COUNTRY = "IT"; public static final String ROVERETO_ADM_AREA = "TN"; public static final String ADDRESS = "address"; public static final String EDIT_FIELD_PHONE_TYPE = "phone"; public static final String EDIT_FIELD_EMAIL_TYPE = "email"; public static final String EDIT_FIELD_TEXT_TYPE = "text"; public static final String EMAIL_CONTACT_TYPE = "email"; public static final String PHONE_CONTACT_TYPE = "phone"; public static final String[] stopWordsForOrigin = new String[]{"a cura", "acura"}; // public static List<ExplorerObject> appEvents = getFakeEventObjects(); public static List<Concept> conceptConvertSS(Collection<SemanticSuggestion> tags) { List<Concept> result = new ArrayList<Concept>(); for (SemanticSuggestion ss : tags) { if (ss.getType() == TYPE.KEYWORD) { result.add(new Concept(null, ss.getName())); } else if (ss.getType() == TYPE.SEMANTIC) { Concept c = new Concept(); // c.setId(ss.getId()); c.setName(ss.getName()); c.setDescription(ss.getDescription()); c.setSummary(ss.getSummary()); result.add(c); } } return result; } public static ArrayList<SemanticSuggestion> conceptConvertToSS(List<Concept> tags) { if (tags == null) return new ArrayList<SemanticSuggestion>(); ArrayList<SemanticSuggestion> result = new ArrayList<SemanticSuggestion>(); for (Concept c : tags) { SemanticSuggestion ss = new SemanticSuggestion(); if (c.getId() == null) { ss.setType(TYPE.KEYWORD); } else { // ss.setId(c.getId()); ss.setDescription(c.getDescription()); ss.setSummary(c.getSummary()); ss.setType(TYPE.SEMANTIC); } ss.setName(c.getName()); result.add(ss); } return result; } public static String conceptToSimpleString(List<Concept> tags) { if (tags == null) return null; String content = ""; for (Concept s : tags) { if (content.length() > 0) content += ", "; content += s.getName(); } return content; } /** * @param mTrack * @return */ // public static boolean isCreatedByUser(BaseDTObject obj) { // if (obj.getDomainType() == null || // userPoiObject.equals(obj.getDomainType())) { // return true; // } else // return false; // } // public static Collection<LocalExplorerObject> // convertToLocalEventFromBean( // Collection<ExplorerObjectForBean> searchInGeneral) { // Collection<LocalExplorerObject> returnCollection = new // ArrayList<LocalExplorerObject>(); // for (ExplorerObjectForBean event : searchInGeneral) { // LocalExplorerObject localEvent = // DTHelper.findEventById(event.getObjectForBean().getId()); // if (localEvent != null) { // // returnCollection.add(localEvent); // } // } // return returnCollection; // } // public static Collection<LocalExplorerObject> // convertToLocalEvent(Collection<ExplorerObject> events) { // Collection<ExplorerObjectForBean> beanEvents = new // ArrayList<ExplorerObjectForBean>(); // Collection<LocalExplorerObject> returnEvents = new // ArrayList<LocalExplorerObject>(); // // for (ExplorerObject event : events) { // ExplorerObjectForBean newObject = new ExplorerObjectForBean(); // LocalExplorerObject localObject = new LocalExplorerObject(); // newObject.setObjectForBean(event); // localObject.setEventFromExplorerObjectForBean(newObject); // returnEvents.add(localObject); // } // // return returnEvents; // } public static List<LatLng> decodePolyline(String encoded) { List<LatLng> polyline = new ArrayList<LatLng>(); int index = 0, len = encoded.length(); int lat = 0, lng = 0; while (index < len) { int b, shift = 0, result = 0; do { b = encoded.charAt(index++) - 63; result |= (b & 0x1f) << shift; shift += 5; } while (b >= 0x20); int dlat = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1)); lat += dlat; shift = 0; result = 0; if (index >= len) { break; } do { b = encoded.charAt(index++) - 63; result |= (b & 0x1f) << shift; shift += 5; } while (b >= 0x20); int dlng = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1)); lng += dlng; LatLng p = new LatLng((double) lat / 1E5, (double) lng / 1E5); polyline.add(p); } return polyline; } /** * @param event * @return */ public static String getEventShortAddress(ExplorerObject event) { if (event.getCustomData() != null && event.getCustomData().get("place") != null) { return event.getCustomData().get("place").toString(); } else { return null; } } public static Long toDateTimeLong(SimpleDateFormat sdf, String date_string) { Date date; Long mills = null; try { date = (Date) sdf.parse(date_string); mills = date.getTime(); } catch (ParseException e) { // TODO Auto-generated catch block e.printStackTrace(); } return mills; } public static CharSequence eventDatesString(DateFormat sdf, Long fromTime, Long toTime) { String res = sdf.format(new Date(fromTime)); if (toTime != null && toTime != fromTime) { Calendar f = Calendar.getInstance(); f.setTimeInMillis(fromTime); Calendar t = Calendar.getInstance(); t.setTimeInMillis(toTime); if (t.get(Calendar.DATE) != f.get(Calendar.DATE)) { res += " - " + sdf.format(new Date(toTime)); } } return res; } // public static ArrayList<String> createFakeDateGroupList(){ // ArrayList<String> groupList = new ArrayList<String>(); // groupList.add("Oggi 29/10/2013"); // groupList.add("Domani 30/10/2013"); // groupList.add("Giovedi 31/10/2013"); // return groupList; // } // // // public static Map<String, List<ExplorerObject>> // createFakeEventCollection(List<String> dateGroupList ) { // // List<ExplorerObject> eventList = getFakeExplorerObjects(); // Map<String, List<ExplorerObject>> eventCollection = new // LinkedHashMap<String, List<ExplorerObject>>(); // List<ExplorerObject> childList; // try { // eventList = new // ArrayList<ExplorerObject>(DTHelper.getEventsByCategories(0, 10, // CategoryHelper.CAT_SOCIALE)); // // eventList = new ArrayList<ExplorerObject>(DTHelper.getEvents(0, 10, // CategoryHelper.CAT_SOCIALE)); // } catch (Exception e) { // // TODO Auto-generated catch block // e.printStackTrace(); // } // // // preparing laptops collection(child) // for (String event_date : dateGroupList) { // childList = new ArrayList<ExplorerObject>(); // if (event_date.equals("Oggi 29/10/2013")) { // childList.add(eventList.get(0)); // childList.add(eventList.get(1)); // } else if (event_date.equals("Domani 30/10/2013")) // childList.add(eventList.get(2)); // else if (event_date.equals("Giovedi 31/10/2013")){ // childList.add(eventList.get(3)); // childList.add(eventList.get(4)); // } // // eventCollection.put(event_date, childList); // } // // return eventCollection; // } private static List<ExplorerObject> loadChild(ExplorerObject[] eventsByDate) { List<ExplorerObject> childList = new ArrayList<ExplorerObject>(); for (ExplorerObject event : eventsByDate) childList.add(event); return childList; } // public static List<ExplorerObject> getFakeExplorerObjects(){ // // List<ExplorerObject> fake_events = new ArrayList<ExplorerObject>(); // ExplorerObject fake_event; new ExplorerObject(); // Map<String, Object> customData = new HashMap<String, Object>(); // Map<String,Object> contacts = new HashMap<String, Object>(); // CommunityData communityData = new CommunityData(); // // //create fake event object 1 // fake_event = new ExplorerObject(); // // // //set basic info // fake_event.setTitle("Roverunning training"); // fake_event.setWhenWhere("tutti i marted� con inizio il 14 - 21 - 28 gennaio, 4 - 11 - 18 - 25 febbraio, 4 - 11 - 18 - 25 marzo, ritrovo nella piazza del Mart ore 18.00"); // fake_event.setOrigin("Assessorato allo Sport, US Quercia, NW Arcobaleno"); // //the source // fake_event.setFromTime(Utils.toDateTimeLong(DATE_FORMAT, // "17/1/2014 08:30 PM")); // //fake_event.setToTime(Utils.toDateTimeLong(DATE_FORMAT, // "17/1/2014 10:30 PM")); // fake_event.setId("1"); // fake_event.setDescription("percorrerovereto. Vuoi imparare a correre? A camminare? Vuoi migliorare la tua attivit� di runner? Cerchi un'opportunit� per correre/camminare in compagnia? " // + // "La partecipazione � gratuita e aperta a tutti i principianti, amatori e agonisti"); // String site_url = new // String("http://www.comune.rovereto.tn.it/Vivi-la-citta/Sport/Calendario-eventi-sportivi/Roverunning-training6"); // String img_url = new // String("http://www.comune.rovereto.tn.it/var/rovereto/storage/images/vivi-la-citta/sport/calendario-eventi-sportivi/roverunning-training6/124779-4-ita-IT/Roverunning-training_medium.jpg"); // fake_event.setImage(img_url); // fake_event.setWebsiteUrl(site_url); // // //set location and address // double[] loc = {45.890960000000000000,11.040139899999986}; // fake_event.setLocation(loc); // Address address = new Address(); // address.setCitta("Rovereto"); // address.setLuogo("<NAME>"); // address.setVia("<NAME>, 52"); // fake_event.setAddress(address); // // //set contacts // String[] telefono = new String[]{"0461235678", "3345678910"}; // String[] email = new String[]{"<EMAIL>"}; // contacts.put("telefono", telefono); // contacts.put("email", email); // fake_event.setContacts(contacts); // // //set community data // List<String> tags = Arrays.asList(new String[]{"sport", "calcio"}); // communityData.setTags(tags); // communityData.setAttendees(5); // communityData.setAverageRating(3); // fake_event.setCommunityData(communityData); // // // //set custom data // customData.put("Tipo di luogo", "aperto"); // customData.put("Accesso", "libero"); // customData.put("Propabilita dell'evento", "confermato"); // customData.put("Lingua principale ", "Italiano"); // customData.put("Abbigliamento consigliato", "sportivo"); // customData.put("Abbigliamento consigliato", "sportivo"); // fake_event.setCustomData(customData); // // fake_events.add(fake_event); // // //create fake event object 2 // telefono = new String[]{"0464565880"}; // email = new String[]{"<EMAIL>"}; // tags = Arrays.asList(new String[]{"sport", "pallavolo"}); // site_url = new // String("http://www.comune.rovereto.tn.it/Vivi-la-citta/Sport/Calendario-eventi-sportivi/24-TORNEO-DI-NATALE-Pallavolo-Femminile"); // img_url = new // String("http://www.comune.rovereto.tn.it/var/rovereto/storage/images/vivi-la-citta/sport/calendario-eventi-sportivi/24-torneo-di-natale-pallavolo-femminile/123469-1-ita-IT/24-TORNEO-DI-NATALE-Pallavolo-Femminile_medium.jpg"); // // // address = new Address(); // address.setCitta("Rovereto"); // address.setLuogo("Palasport e palestre"); // address.setVia("<NAME>, 52"); // // customData.clear(); // customData.put("Tipo di luogo", "chiuso"); // customData.put("Accesso", "a pagamento"); // customData.put("Propabilita dell'evento", "confermato"); // customData.put("Lingua principale ", "Italiano"); // customData.put("Abbigliamento consigliato", "sportivo"); // // //set community data // tags = Arrays.asList(new String[]{"sport", "calcio"}); // communityData.setTags(tags); // communityData.setAttendees(5); // communityData.setAverageRating(3); // fake_event.setCommunityData(communityData); // // fake_event = new ExplorerObject(); // fake_event.setAddress(address); // fake_event.setAddress(address); // // fake_event.setWhenWhere("whenwhere a"); // fake_event.setFromTime(Utils.toDateTimeLong(DATE_FORMAT, "27/12/2013")); // fake_event.setToTime(Utils.toDateTimeLong(DATE_FORMAT, "28/12/2013")); // fake_event.setId("2"); // fake_event.setDescription("description 1"); // fake_event.setTitle("24esimo TORNEO DI NATALE Pallavolo Femminile"); // fake_event.setCustomData(customData); // fake_event.setImage(img_url); // fake_event.setWebsiteUrl(site_url); // contacts.put("telefono", telefono); // contacts.put("email", email); // contacts.put("tags", tags); // fake_event.setContacts(contacts); // fake_events.add(fake_event); // // //create fake event object 3 // telefono = new String[]{"0464565880"}; // email = new String[]{"<EMAIL>"}; // tags = Arrays.asList(new String[]{"sport", "pallavolo"}); // site_url = new // String("http://www.comune.rovereto.tn.it/Vivi-la-citta/Sport/Calendario-eventi-sportivi/24-TORNEO-DI-NATALE-Pallavolo-Femminile"); // img_url = new // String("http://www.comune.rovereto.tn.it/var/rovereto/storage/images/vivi-la-citta/sport/calendario-eventi-sportivi/24-torneo-di-natale-pallavolo-femminile/123469-1-ita-IT/24-TORNEO-DI-NATALE-Pallavolo-Femminile_medium.jpg"); // address = new Address(); // address.setCitta("Rovereto"); // address.setLuogo("Palasport e palestre"); // address.setVia("Corso Bettini, 52"); // // customData.put("Tipo di luogo", "chiuso"); // customData.put("Accesso", "a pagamento"); // customData.put("Propabilita dell'evento", "confermato"); // customData.put("Lingua principale ", "Italiano"); // customData.put("Abbigliamento consigliato", "sportivo"); // // <<<<<<< HEAD // fake_event = new EventObject(); // ======= // //set community data // tags = Arrays.asList(new String[]{"sport", "calcio"}); // communityData.setTags(tags); // communityData.setAttendees(5); // communityData.setAverageRating(3); // fake_event.setCommunityData(communityData); // // fake_event = new ExplorerObject(); // >>>>>>> branch 'master' of // https://github.com/smartcampuslab/smartcampus.vas.roveretoexplorer.android.git // fake_event.setAddress(address); // fake_event.setAddress(address); // // fake_event.setWhenWhere("whenwhere a"); // fake_event.setFromTime(Utils.toDateTimeLong(DATE_FORMAT, "27/12/2013")); // fake_event.setToTime(Utils.toDateTimeLong(DATE_FORMAT, "28/12/2013")); // fake_event.setId("3"); // fake_event.setDescription("description 1"); // fake_event.setTitle("titolo 3"); // fake_event.setCustomData(customData); // fake_event.setImage(img_url); // fake_event.setWebsiteUrl(site_url); // contacts.put("telefono", telefono); // contacts.put("email", email); // contacts.put("tags", tags); // fake_event.setContacts(contacts); // fake_events.add(fake_event); // // //create fake event object 4 // telefono = new String[]{"0464565880"}; // email = new String[]{"<EMAIL>"}; // tags = Arrays.asList(new String[]{"sport", "pallavolo"}); // site_url = new // String("http://www.comune.rovereto.tn.it/Vivi-la-citta/Sport/Calendario-eventi-sportivi/24-TORNEO-DI-NATALE-Pallavolo-Femminile"); // img_url = new // String("http://www.comune.rovereto.tn.it/var/rovereto/storage/images/vivi-la-citta/sport/calendario-eventi-sportivi/24-torneo-di-natale-pallavolo-femminile/123469-1-ita-IT/24-TORNEO-DI-NATALE-Pallavolo-Femminile_medium.jpg"); // address = new Address(); // address.setCitta("Rovereto"); // address.setLuogo("Palasport e palestre"); // address.setVia("<NAME>, 52"); // // customData.put("Tipo di luogo", "chiuso"); // customData.put("Accesso", "a pagamento"); // customData.put("Propabilita dell'evento", "confermato"); // customData.put("Lingua principale ", "Italiano"); // customData.put("Abbigliamento consigliato", "sportivo"); // // // //set community data // tags = Arrays.asList(new String[]{"sport", "calcio"}); // communityData.setTags(tags); // communityData.setAttendees(5); // communityData.setAverageRating(3); // fake_event.setCommunityData(communityData); // fake_event = new ExplorerObject(); // fake_event.setAddress(address); // fake_event.setAddress(address); // // fake_event.setWhenWhere("whenwhere a"); // fake_event.setFromTime(Utils.toDateTimeLong(DATE_FORMAT, "27/12/2013")); // fake_event.setToTime(Utils.toDateTimeLong(DATE_FORMAT, "28/12/2013")); // fake_event.setId("4"); // fake_event.setDescription("description 1"); // fake_event.setTitle("saggio di danza"); // fake_event.setCustomData(customData); // fake_event.setImage(img_url); // fake_event.setWebsiteUrl(site_url); // contacts.put("telefono", telefono); // contacts.put("email", email); // contacts.put("tags", tags); // fake_event.setContacts(contacts); // fake_events.add(fake_event); // // // //create fake event object 5 // telefono = new String[]{"0464565880"}; // email = new String[]{"<EMAIL>"}; // tags = Arrays.asList(new String[]{"sport", "pallavolo"}); // site_url = new // String("http://www.comune.rovereto.tn.it/Vivi-la-citta/Sport/Calendario-eventi-sportivi/24-TORNEO-DI-NATALE-Pallavolo-Femminile"); // img_url = new // String("http://www.comune.rovereto.tn.it/var/rovereto/storage/images/vivi-la-citta/sport/calendario-eventi-sportivi/24-torneo-di-natale-pallavolo-femminile/123469-1-ita-IT/24-TORNEO-DI-NATALE-Pallavolo-Femminile_medium.jpg"); // address = new Address(); // address.setCitta("Rovereto"); // address.setLuogo("Palasport e palestre"); // address.setVia("<NAME>, 52"); // // customData.put("Tipo di luogo", "chiuso"); // customData.put("Accesso", "a pagamento"); // customData.put("Propabilita dell'evento", "confermato"); // customData.put("Lingua principale ", "Italiano"); // customData.put("Abbigliamento consigliato", "sportivo"); // // //set community data // tags = Arrays.asList(new String[]{"sport", "calcio"}); // communityData.setTags(tags); // communityData.setAttendees(5); // communityData.setAverageRating(3); // fake_event.setCommunityData(communityData); // // <<<<<<< HEAD // fake_event = new EventObject(); // ======= // fake_event = new ExplorerObject(); // >>>>>>> branch 'master' of // https://github.com/smartcampuslab/smartcampus.vas.roveretoexplorer.android.git // fake_event.setAddress(address); // fake_event.setAddress(address); // // fake_event.setWhenWhere("whenwhere a"); // fake_event.setFromTime(Utils.toDateTimeLong(DATE_FORMAT, "27/12/2013")); // fake_event.setToTime(Utils.toDateTimeLong(DATE_FORMAT, "29/12/2013")); // fake_event.setId("5"); // fake_event.setDescription("description 1"); // fake_event.setTitle("Hockey su ghiaccio"); // fake_event.setCustomData(customData); // fake_event.setImage(img_url); // fake_event.setWebsiteUrl(site_url); // contacts.put("telefono", telefono); // contacts.put("email", email); // contacts.put("tags", tags); // fake_event.setContacts(contacts); // fake_events.add(fake_event); // // return fake_events; // // } // public static ExplorerObject // getFakeLocalExplorerObject(List<ExplorerObject> events, String id){ // // ExplorerObject fake_event = null; // for (ExplorerObject event: events){ // if (event.getId()==id) { // return event; // } // } // return fake_event; // } // public static String getDateString(Context context, Long fromTime, // SimpleDateFormat sdf, boolean uppercase, boolean dayweek) { // // String stringEvent = (sdf.format(new Date(fromTime))); // // if (dayweek){ // Date dateToday = new Date(); // String stringToday = (sdf.format(dateToday)); // Calendar cal = Calendar.getInstance(); // cal.setTime(dateToday); // cal.add(Calendar.DAY_OF_YEAR, 1); // <-- // Date tomorrow = cal.getTime(); // String stringTomorrow = (sdf.format(tomorrow)); // // check actual date // if (stringToday.equals(stringEvent)) { // // if equal put the Today string // return getDateFormatted(context.getString(R.string.list_event_today) + // " " + stringToday, uppercase); // } else if (stringTomorrow.equals(stringEvent)) { // // else if it's tomorrow, cat that string // return getDateFormatted(context.getString(R.string.list_event_tomorrow) + // " " + stringTomorrow, uppercase); // } // // else put the day's name // else // return getDateFormatted(DATE_FORMAT_2_with_dayweek.format(new // Date(fromTime)), uppercase); // } // else{ // Log.i("FORMAT", "Utils --> no dayweek date formatted: " + stringEvent + // "!!"); // return stringEvent; // } // } public static String[] getDateTimeString(Context context, Long fromTime, SimpleDateFormat sdf, boolean uppercase, boolean dayweek) { String[] date_time = { "", "" }; date_time[1] = ""; String dateAndTime = sdf.format(new Date(fromTime)); String date = dateAndTime; if (dateAndTime.contains(":")) { // there is a time date = dateAndTime.substring(0, dateAndTime.lastIndexOf(" ")); date_time[1] = dateAndTime.substring(dateAndTime.lastIndexOf(" ") + 1); } if (dayweek) { Date dateToday = new Date(); String stringToday = (sdf.format(dateToday)); Calendar cal = Calendar.getInstance(); cal.setTime(dateToday); cal.add(Calendar.DAY_OF_YEAR, 1); // <-- Date tomorrow = cal.getTime(); String stringTomorrow = (sdf.format(tomorrow)); // check actual date if (stringToday.equals(date)) { // if equal put the Today string date_time[0] = getDateFormatted(context.getString(R.string.list_event_today) + " " + stringToday, uppercase); } else if (stringTomorrow.equals(date)) { // else if it's tomorrow, cat that string date_time[0] = getDateFormatted(context.getString(R.string.list_event_tomorrow) + " " + stringTomorrow, uppercase); } // else put the day's name else { date_time[0] = getDateFormatted(DATE_FORMAT_2_with_dayweek.format(new Date(fromTime)), uppercase); } } else { date_time[0] = date; } //Log.i("FORMAT", "Utils --> date formatted: " + date_time[0] + "!!"); //Log.i("FORMAT", "Utils --> time formatted: " + date_time[1] + "!!"); return date_time; } private static String getDateFormatted(String date, boolean uppercase) { // Log.i("FORMAT", "Utils --> initial string : " + date + "!!"); String date_formatted = new String(""); String[] dateformatted_split = date.split(" "); for (int i = 0; i < dateformatted_split.length; i++) { String piece = dateformatted_split[i]; if (uppercase) { piece = (i == 0) ? piece.substring(0, 1).toUpperCase() + piece.substring(1) + "," : piece; piece = (i == 2) ? piece.substring(0, 1).toUpperCase() + piece.substring(1) : piece; } else piece = (i == 0) ? piece + "," : piece; // Log.i("FORMAT", "Utils --> string split: " + piece + "!!"); date_formatted = date_formatted + piece + " "; } return date_formatted; } public static boolean validFromDateTime(Date fromDate, Date fromTime) { Calendar now = Calendar.getInstance(); now.set(Calendar.SECOND, 0); now.set(Calendar.MILLISECOND, 0); // minutes in the past span now.add(Calendar.MINUTE, Utils.PAST_MINUTES_SPAN); Calendar time = Calendar.getInstance(); time.setTime(fromTime); Calendar from = Calendar.getInstance(); from.setTime(fromDate); from.set(Calendar.HOUR_OF_DAY, time.get(Calendar.HOUR_OF_DAY)); from.set(Calendar.MINUTE, time.get(Calendar.MINUTE)); from.set(Calendar.SECOND, 0); from.set(Calendar.MILLISECOND, 0); return from.compareTo(now) < 0 ? false : true; } // public static List<ToKnow> toKnowMapToList(Map<String, String> map) { // List<ToKnow> list = new ArrayList<ToKnow>(); // // for (Entry<String, String> entry : map.entrySet()) { // ToKnow toKnow = new ToKnow(entry.getKey(), entry.getValue()); // list.add(toKnow); // } // // return list; // } public static List<ToKnow> toKnowMapToList(Map<String, List<String>> map) { List<ToKnow> list = new ArrayList<ToKnow>(); for (Entry<String, List<String>> entry : map.entrySet()) { List<String> values = new LinkedList<String>((List<String>) entry.getValue()); values.remove(""); if (entry.getKey().startsWith("_toknow_")) list.add((values.size()!=0) ? ToKnow.newCustomDataAttributeField(entry.getKey(), false, 2) : ToKnow.newCustomDataAttributeField(entry.getKey(), false, 3)); else list.add((values.size()!=0) ? ToKnow.newCustomDataAttributeField(entry.getKey(), true, 2) : ToKnow.newCustomDataAttributeField(entry.getKey(), true, 3)); for (int i = 0; i < values.size(); i++) { String value = values.get(i); if (i == (values.size() - 1)) { // Last item... list.add(ToKnow.newCustomDataValueField(value,3)); }else{ list.add(ToKnow.newCustomDataValueField(value,2)); } } } return list; } public static Map<String, List<String>> toKnowListToMap(List<ToKnow> list) { Map<String, List<String>> map = new LinkedHashMap<String, List<String>>(); String previousAttrName = null; if (list != null) { previousAttrName = list.get(0).getName(); List<String> values = new ArrayList<String>(); for (ToKnow toKnow : list) { String currentAttrName = (toKnow.getType().matches(Constants.CUSTOM_TOKNOW_TYPE_ATTRIBUTE)) ? toKnow.getName() : previousAttrName; if ((currentAttrName.matches(previousAttrName)) && (toKnow.getType().matches(Constants.CUSTOM_TOKNOW_TYPE_VALUE))) values.add(toKnow.getName()); if (!currentAttrName.matches(previousAttrName)){ map.put(previousAttrName, values); values = new ArrayList<String>(); previousAttrName = currentAttrName; } } } return map; } public static Map<String, List<String>> convert(Map<String, String> oldMap) { Map<String, List<String>> ret = new HashMap<String, List<String>>(); for (String key : oldMap.keySet()) { ret.put(key, Arrays.asList(new String[]{oldMap.get(key)})); } return ret; } public static boolean isOldMapType(Map<String,Object> map){ boolean isOld = false; for (Entry<String, Object> entry : map.entrySet()) { if(!(entry.getValue() instanceof List<?>)) { isOld=true; break; } } return isOld; } public static Map<String,List<String>> getCustomToKnowDataFromEvent(ExplorerObject event){ Map<String,List<String>> toKnowMap = null; if (event.getCustomData().containsKey(Constants.CUSTOM_TOKNOW)){ //eventually convert the old map type with the new one if (Utils.isOldMapType((Map<String,Object>) event.getCustomData().get(Constants.CUSTOM_TOKNOW))){ toKnowMap = Utils.convert((Map<String,String>) event.getCustomData().get(Constants.CUSTOM_TOKNOW)); } else{ toKnowMap = (Map<String,List<String>>) event.getCustomData().get(Constants.CUSTOM_TOKNOW); } } return toKnowMap; } /** * This is used to check the given email is valid or not. * * @param url * @return */ public final static boolean isValidEmail(CharSequence target) { if (target == null) { return false; } else { return android.util.Patterns.EMAIL_ADDRESS.matcher(target).matches(); } } /** * This is used to check the given URL is valid or not. * * @param url * @return */ public final static boolean isValidUrl(String url) { Pattern p = Patterns.WEB_URL; Matcher m = p.matcher(url); if (m.matches()) return true; else return false; } public static boolean isSameDay(Date date1, Date date2) { if (date1 == null || date2 == null) { throw new IllegalArgumentException("The dates must not be null"); } Calendar cal1 = Calendar.getInstance(); cal1.setTime(date1); Calendar cal2 = Calendar.getInstance(); cal2.setTime(date2); return isSameDay(cal1, cal2); } public static boolean isSameDay(Calendar cal1, Calendar cal2) { if (cal1 == null || cal2 == null) { throw new IllegalArgumentException("The dates must not be null"); } return (cal1.get(Calendar.ERA) == cal2.get(Calendar.ERA) && cal1.get(Calendar.YEAR) == cal2.get(Calendar.YEAR) && cal1.get(Calendar.DAY_OF_YEAR) == cal2.get(Calendar.DAY_OF_YEAR)); } public static List<Date> getDatesBetweenInterval(Date dateInitial, Date dateFinal) { List<Date> dates = new ArrayList<Date>(); Calendar calendar = new GregorianCalendar(); calendar.setTime(dateInitial); while (!calendar.getTime().after(dateFinal)) { Date result = calendar.getTime(); dates.add(result); calendar.add(Calendar.DATE, 1); } return dates; } //delete an unwanted word from a sentence public static String removeWord(String unwanted, String sentence) { return (sentence.indexOf(unwanted) != -1) ? sentence.replace(unwanted,"").trim() : sentence; } //delete a list of unwanted words from a sentence public static String removeWords(List<String> unwanted, String sentence) { for (String word : unwanted) sentence = removeWord(word, sentence); return sentence; } public static OSMAddress getOsmAddressFromAddress(android.location.Address address) { OSMAddress returnAddress = new OSMAddress(); if (address!=null){ //city Map<String,String> cities = new HashMap<String, String>(); cities.put("", address.getLocality()); returnAddress.setCity(cities); //name returnAddress.setName(address.getLocality()); //street returnAddress.setStreet(address.getAddressLine(0)); //location double[] addressLocation = {address.getLatitude(),address.getLongitude()}; returnAddress.setLocation(addressLocation); return returnAddress; } return null; } } <file_sep>package eu.iescities.pilot.rovereto.roveretoexplorer.fragments.event.dasapere; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import android.app.Activity; import android.content.Context; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentTransaction; import android.support.v4.app.ListFragment; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.widget.Button; import eu.iescities.pilot.rovereto.roveretoexplorer.R; import eu.iescities.pilot.rovereto.roveretoexplorer.custom.AbstractAsyncTaskProcessor; import eu.iescities.pilot.rovereto.roveretoexplorer.custom.Utils; import eu.iescities.pilot.rovereto.roveretoexplorer.custom.data.Constants; import eu.iescities.pilot.rovereto.roveretoexplorer.custom.data.DTHelper; import eu.iescities.pilot.rovereto.roveretoexplorer.custom.data.model.ExplorerObject; import eu.iescities.pilot.rovereto.roveretoexplorer.custom.data.model.ToKnow; import eu.trentorise.smartcampus.android.common.SCAsyncTask; import eu.trentorise.smartcampus.protocolcarrier.exceptions.SecurityException; public class Fragment_EvDetail_DaSapere extends ListFragment { private static final List<String> CUSTOM_TOKNOW_FIELDS = Arrays.asList(Constants.CUSTOM_TOKNOW_PLACE_TYPE, Constants.CUSTOM_TOKNOW_ACCESS, Constants.CUSTOM_TOKNOW_CHANCE, Constants.CUSTOM_TOKNOW_LANGUAGE_MAIN, Constants.CUSTOM_TOKNOW_CLOTHING, Constants.CUSTOM_TOKNOW_TO_BRING); protected Context mContext; protected String mEventId; protected ExplorerObject mEvent = null; private EventDetailToKnowAdapter adapter; public static Fragment_EvDetail_DaSapere newInstance(String event_id) { Fragment_EvDetail_DaSapere f = new Fragment_EvDetail_DaSapere(); Bundle b = new Bundle(); b.putString(Utils.ARG_EVENT_ID, event_id); f.setArguments(b); return f; } @Override public void onAttach(Activity activity) { super.onAttach(activity); //Log.d("FRAGMENT LC", "Fragment_evDetail_DaSapere --> onAttach"); } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Log.d("FRAGMENT LC", "Fragment_evDetail_Info --> onCreate"); this.mContext = this.getActivity(); if (savedInstanceState == null) { Log.d("SCROLLTABS", "onCreate FIRST TIME"); if (getArguments() != null) { mEventId = getArguments().getString(Utils.ARG_EVENT_ID); mEvent = DTHelper.findEventById(mEventId); } else { Log.d("SCROLLTABS", "onCreate SUBSEQUENT TIME"); } } } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { super.onCreateView(inflater, container, savedInstanceState); //Log.d("FRAGMENT LC", "Fragment_evDetail_DaSapere --> onCreateView"); return inflater.inflate(R.layout.frag_ev_detail_dasapere, container, false); } @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); //Log.d("FRAGMENT LC", "Fragment_evDetail_DaSapere --> onActivityCreated"); mEvent = getEvent(); //adapter = new EventDetailToKnowAdapter(getActivity(), R.layout.event_toknow_row_item, getTag(), mEventId); adapter = new EventDetailToKnowAdapter(getActivity(), R.layout.event_info_child_item, getTag(), mEventId); getListView().setDivider(null); getListView().setDivider(getResources().getDrawable(R.color.transparent)); setListAdapter(adapter); //List<ToKnow> toKnowList = Utils.toKnowMapToList(getToKnowEventData()); List<ToKnow> toKnowList = Utils.toKnowMapToList(getToKnowEventData()); adapter.addAll(toKnowList); adapter.notifyDataSetChanged(); //handle the creation of new type of information by the user Button toKnowAddButton = (Button) getActivity().findViewById(R.id.toKnowAddButton); toKnowAddButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { FragmentTransaction fragmentTransaction = getActivity().getSupportFragmentManager().beginTransaction(); Bundle args = new Bundle(); String frag_description = null; Fragment editFragment = new Fragment_EvDetail_AddNew_FieldType(); Log.i("CONTACTS", "EventDetailInfoAdapter --> event selected ID: " + mEventId + "!!"); args.putString(Utils.ARG_EVENT_ID, mEventId); frag_description = "event_details_custom_addnew_fieldtype"; editFragment.setArguments(args); fragmentTransaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE); // fragmentTransaction.detach(this); fragmentTransaction.replace(R.id.content_frame, editFragment, frag_description); fragmentTransaction.addToBackStack(getTag()); fragmentTransaction.commit(); // reset event and event id // mEvent = null; // mEventId = null; } }); } private Map<String, List<String>> getToKnowEventData(){ if (mEvent.getCustomData() == null) { mEvent.setCustomData(new HashMap<String, Object>()); } Map<String, List<String>> toKnowMap = Utils.getCustomToKnowDataFromEvent(mEvent); if (toKnowMap == null) { Map<String, Object> customData = mEvent.getCustomData(); customData.put(Constants.CUSTOM_TOKNOW, new LinkedHashMap<String, List<String>>()); mEvent.setCustomData(customData); toKnowMap = (Map<String, List<String>>) mEvent.getCustomData().get(Constants.CUSTOM_TOKNOW); } if (toKnowMap.isEmpty()) { Log.i("DASAPERE", "DaSapere--> toKnowMap EMPTY"); try { List<ToKnow> toKnowList = new ArrayList<ToKnow>(); for (String field : CUSTOM_TOKNOW_FIELDS) { toKnowList.add(ToKnow.newCustomDataAttributeField(field, false, 3)); } Map<String, Object> customData = new HashMap<String, Object>(); toKnowMap = Utils.toKnowListToMap(toKnowList); customData.put(Constants.CUSTOM_TOKNOW, toKnowMap); mEvent.setCustomData(customData); // persistence new SCAsyncTask<ExplorerObject, Void, Boolean>(getActivity(), new UpdateEventProcessor(getActivity())) .execute(mEvent); } catch (Exception e) { Log.e(getClass().getName(), e.getMessage() != null ? e.getMessage() : ""); } } return toKnowMap; } @Override public void onStart() { super.onStart(); //Log.d("FRAGMENT LC", "Fragment_evDetail_DaSapere --> onStart"); } @Override public void onResume() { super.onResume(); //Log.d("FRAGMENT LC", "Fragment_evDetail_DaSapere --> onResume"); } @Override public void onPause() { super.onPause(); //Log.d("FRAGMENT LC", "Fragment_evDetail_DaSapere --> onPause"); } @Override public void onStop() { super.onStop(); //Log.d("FRAGMENT LC", "Fragment_evDetail_DaSapere --> onStop"); } @Override public void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); //Log.d("FRAGMENT LC", "Fragment_evDetail_DaSapere --> onSaveInstanceState"); } @Override public void onDestroyView() { super.onDestroyView(); //Log.d("FRAGMENT LC", "Fragment_evDetail_DaSapere --> onDestroyView"); } @Override public void onDestroy() { super.onDestroy(); //Log.d("FRAGMENT LC", "Fragment_evDetail_DaSapere --> onDestroy"); } @Override public void onDetach() { super.onDetach(); //Log.d("FRAGMENT LC", "Fragment_evDetail_DaSapere --> onDetach"); } private ExplorerObject getEvent() { if (mEventId == null) { mEventId = getArguments().getString(Utils.ARG_EVENT_ID); } mEvent = DTHelper.findEventById(mEventId); return mEvent; } private class UpdateEventProcessor extends AbstractAsyncTaskProcessor<ExplorerObject, Boolean> { public UpdateEventProcessor(Activity activity) { super(activity); } @Override public Boolean performAction(ExplorerObject... params) throws SecurityException, Exception { // to be enabled when the connection with the server is ok return DTHelper.saveEvent(params[0]); } @Override public void handleResult(Boolean result) { if (getActivity() != null) { // getActivity().getSupportFragmentManager().popBackStack(); // if (result) { // Toast.makeText(getActivity(), R.string.event_create_success, // Toast.LENGTH_SHORT).show(); // } else { // Toast.makeText(getActivity(), R.string.update_success, // Toast.LENGTH_SHORT).show(); // } } } } } <file_sep>package eu.iescities.pilot.rovereto.roveretoexplorer; import java.util.ArrayList; import org.apache.http.HttpStatus; import android.accounts.AccountManager; import android.app.Activity; import android.app.AlertDialog; import android.content.DialogInterface; import android.content.Intent; import android.content.pm.PackageManager.NameNotFoundException; import android.content.res.Configuration; import android.content.res.Resources.NotFoundException; import android.content.res.TypedArray; import android.os.AsyncTask; import android.os.Bundle; import android.support.v4.app.ActionBarDrawerToggle; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentActivity; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentTransaction; import android.support.v4.widget.DrawerLayout; import android.util.Log; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.widget.Toast; import eu.iescities.pilot.rovereto.roveretoexplorer.custom.AbstractAsyncTaskProcessor; import eu.iescities.pilot.rovereto.roveretoexplorer.custom.CategoryHelper; import eu.iescities.pilot.rovereto.roveretoexplorer.custom.data.DTHelper; import eu.iescities.pilot.rovereto.roveretoexplorer.custom.data.model.BaseDTObject; import eu.iescities.pilot.rovereto.roveretoexplorer.fragments.event.AnimateFirstDisplayListener; import eu.iescities.pilot.rovereto.roveretoexplorer.fragments.event.EventsListingFragment; import eu.iescities.pilot.rovereto.roveretoexplorer.fragments.search.SearchFragment; import eu.iescities.pilot.rovereto.roveretoexplorer.map.MapFragment; import eu.iescities.pilot.rovereto.roveretoexplorer.ui.navdrawer.AbstractNavDrawerActivity; import eu.iescities.pilot.rovereto.roveretoexplorer.ui.navdrawer.NavDrawerActivityConfiguration; import eu.iescities.pilot.rovereto.roveretoexplorer.ui.navdrawer.NavDrawerAdapter; import eu.iescities.pilot.rovereto.roveretoexplorer.ui.navdrawer.NavDrawerItem; import eu.iescities.pilot.rovereto.roveretoexplorer.ui.navdrawer.NavMenuItem; import eu.iescities.pilot.rovereto.roveretoexplorer.ui.navdrawer.NavMenuSection; import eu.trentorise.smartcampus.ac.AACException; import eu.trentorise.smartcampus.ac.SCAccessProvider; import eu.trentorise.smartcampus.android.common.GlobalConfig; import eu.trentorise.smartcampus.android.common.SCAsyncTask; import eu.trentorise.smartcampus.protocolcarrier.exceptions.SecurityException; public class MainActivity extends AbstractNavDrawerActivity { public static final String TAG_FRAGMENT_MAP = "fragmap"; public static final String TAG_FRAGMENT_EVENT_LIST = "fragevent"; private FragmentManager mFragmentManager; private boolean isLoading; private DrawerLayout mDrawerLayout; private ActionBarDrawerToggle mDrawerToggle; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // Log.i("AB TITLE", "MainActivity start on create!!!"); mFragmentManager = getSupportFragmentManager(); // signedIn(); signedIn(); mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout); // this is a class created to avoid an Android bug // see the class for further infos. mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout, R.drawable.ic_drawer, R.string.drawer_open, R.string.drawer_close) { @Override public void onDrawerSlide(View drawerView, float slideOffset) { super.onDrawerSlide(drawerView, slideOffset); mDrawerLayout.bringChildToFront(drawerView); mDrawerLayout.requestLayout(); } }; mDrawerLayout.setDrawerListener(mDrawerToggle); } protected void signedIn() { try { SCAccessProvider provider = SCAccessProvider.getInstance(this); // if (!provider.isLoggedIn(this)) { if (!provider.isLoggedIn(MainActivity.this)) { showLoginDialog(SCAccessProvider.getInstance(MainActivity.this)); // new TokenTask().execute(); } initDataManagement(); } catch (Exception e) { e.printStackTrace(); Toast.makeText(MainActivity.this, getString(R.string.auth_failed), Toast.LENGTH_SHORT).show(); finish(); } // SCAccessProvider provider = SCAccessProvider.getInstance(this); // try { // if (provider.isLoggedIn(this)) { // return true; // } // showLoginDialog(provider); // } catch (AACException e) { // e.printStackTrace(); // return false; // } // // return false; } private void showLoginDialog(final SCAccessProvider accessprovider) { // dialogbox for registration DialogInterface.OnClickListener updateDialogClickListener; updateDialogClickListener = new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { switch (which) { case DialogInterface.BUTTON_POSITIVE: try { if (!SCAccessProvider.getInstance(MainActivity.this).login(MainActivity.this, null)) { new TokenTask().execute(); } } catch (Exception e) { e.printStackTrace(); Toast.makeText(MainActivity.this, getString(R.string.auth_failed), Toast.LENGTH_SHORT).show(); finish(); } // try { // accessprovider.login(MainActivity.this, null); // break; // } catch (AACException e) { // // e.printStackTrace(); // } break; case DialogInterface.BUTTON_NEGATIVE: MainActivity.this.finish(); break; } } }; AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setCancelable(false); builder.setMessage(getString(R.string.auth_required)) .setPositiveButton(android.R.string.yes, updateDialogClickListener) .setNegativeButton(android.R.string.no, updateDialogClickListener).show(); } private void initDataManagement() { try { initGlobalConstants(); try { // if (!SCAccessProvider.getInstance(this).login(this, null)) { DTHelper.init(getApplicationContext()); initData(); // } } catch (Exception e) { e.printStackTrace(); Toast.makeText(this, getString(R.string.auth_failed), Toast.LENGTH_SHORT).show(); finish(); } } catch (Exception e) { Toast.makeText(this, R.string.app_failure_init, Toast.LENGTH_LONG).show(); e.printStackTrace(); return; } } private void initGlobalConstants() throws NameNotFoundException, NotFoundException { GlobalConfig.setAppUrl(this, getResources().getString(R.string.smartcampus_app_url)); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (requestCode == SCAccessProvider.SC_AUTH_ACTIVITY_REQUEST_CODE) { if (resultCode == RESULT_OK) { String token = data.getExtras().getString(AccountManager.KEY_AUTHTOKEN); if (token == null) { Toast.makeText(this, R.string.app_failure_security, Toast.LENGTH_LONG).show(); finish(); } else { initDataManagement(); } } else if (resultCode == RESULT_CANCELED && requestCode == SCAccessProvider.SC_AUTH_ACTIVITY_REQUEST_CODE) { DTHelper.endAppFailure(this, R.string.app_failure_security); } } } private boolean initData() { try { // to start with the map. mFragmentManager.beginTransaction().replace(R.id.content_frame, new MapFragment(), TAG_FRAGMENT_MAP) .commit(); new SCAsyncTask<Void, Void, BaseDTObject>(this, new LoadDataProcessor(this)).execute(); } catch (Exception e1) { Toast.makeText(this, R.string.app_failure_init, Toast.LENGTH_LONG).show(); return false; } return true; } private class LoadDataProcessor extends AbstractAsyncTaskProcessor<Void, BaseDTObject> { private int syncRequired = 0; private FragmentActivity currentRootActivity = null; public LoadDataProcessor(Activity activity) { super(activity); } @Override public BaseDTObject performAction(Void... params) throws SecurityException, Exception { Exception res = null; try { syncRequired = DTHelper.SYNC_REQUIRED;// DTHelper.syncRequired(); } catch (Exception e) { res = e; } if (res != null) { throw res; } return null; } @Override public void handleResult(BaseDTObject result) { if (syncRequired != DTHelper.SYNC_NOT_REQUIRED) { if (syncRequired == DTHelper.SYNC_REQUIRED_FIRST_TIME) { Toast.makeText(MainActivity.this, R.string.initial_data_load, Toast.LENGTH_LONG).show(); } setSupportProgressBarIndeterminateVisibility(true); isLoading = true; new Thread(new Runnable() { @Override public void run() { try { currentRootActivity = DTHelper.start(MainActivity.this); } catch (Exception e) { e.printStackTrace(); } finally { if (currentRootActivity != null) { currentRootActivity.runOnUiThread(new Runnable() { @Override public void run() { currentRootActivity.setProgressBarIndeterminateVisibility(false); if (MainActivity.this != null) { MainActivity.this.setSupportProgressBarIndeterminateVisibility(false); } isLoading = false; } }); } } } }).start(); } else { setSupportProgressBarIndeterminateVisibility(false); // DTHelper.activateAutoSync(); } } } /** * @param items * where to put elements * @param ids * array of arrays made in xml */ private ArrayList<NavDrawerItem> getMenuItems(int... ids) { ArrayList<NavDrawerItem> menu_items = new ArrayList<NavDrawerItem>(); menu_items.add(NavMenuSection.create(0, "Eventi")); String[] labels = getResources().getStringArray(ids[0]); String[] abTitles = getResources().getStringArray(ids[2]); TypedArray drawIds = getResources().obtainTypedArray((ids[1])); for (int j = 0; j < labels.length; j++) { int imgd = drawIds.getResourceId(j, -1); menu_items.add(NavMenuItem.create(j + 1, labels[j], abTitles[j], ((imgd != -1) ? imgd : null), true, false, this)); } drawIds.recycle(); return menu_items; } @Override protected NavDrawerActivityConfiguration getNavDrawerConfiguration() { NavDrawerActivityConfiguration navDrawerActivityConfiguration = new NavDrawerActivityConfiguration(); navDrawerActivityConfiguration.setMainLayout(R.layout.activity_main); navDrawerActivityConfiguration.setDrawerLayoutId(R.id.drawer_layout); navDrawerActivityConfiguration.setLeftDrawerId(R.id.left_drawer); navDrawerActivityConfiguration.setDrawerShadow(R.drawable.drawer_shadow); navDrawerActivityConfiguration.setDrawerOpenDesc(R.string.drawer_open); navDrawerActivityConfiguration.setDrawerCloseDesc(R.string.drawer_close); ArrayList<NavDrawerItem> menu_items = getMenuItems(R.array.drawer_items_labels, R.array.drawer_items_icons, R.array.drawer_items_actionbar_titles); navDrawerActivityConfiguration.setMenuItems(menu_items); navDrawerActivityConfiguration.setBaseAdapter(new NavDrawerAdapter(this, R.layout.navdrawer_item, menu_items)); navDrawerActivityConfiguration.setDrawerIcon(R.drawable.ic_drawer); return navDrawerActivityConfiguration; } @Override protected void onNavItemSelected(int id) { Object[] objects = getFragmentAndTag(id); // can't replace the current fragment with nothing or with one of the // same type if (objects != null) { FragmentTransaction ft = mFragmentManager.beginTransaction(); ft.setCustomAnimations(R.anim.enter, R.anim.exit); ft.replace(R.id.content_frame, (Fragment) objects[0], objects[1].toString()); // ft.addToBackStack(objects[1].toString()); mFragmentManager.popBackStack(null, FragmentManager.POP_BACK_STACK_INCLUSIVE); ft.commit(); } } private Object[] getFragmentAndTag(int pos_in_list) { Object[] out = new Object[2]; String cat = null; Bundle args = new Bundle(); EventsListingFragment elf = null; switch (pos_in_list) { case 1: // click on "I miei eventi" item args = new Bundle(); elf = new EventsListingFragment(); args.putBoolean(SearchFragment.ARG_MY, true); elf.setArguments(args); out[0] = elf; out[1] = TAG_FRAGMENT_EVENT_LIST; break; case 2: // click on "Oggi" item args = new Bundle(); elf = new EventsListingFragment(); args.putString(EventsListingFragment.ARG_QUERY_TODAY, ""); elf.setArguments(args); out[0] = elf; out[1] = TAG_FRAGMENT_EVENT_LIST; break; case 3: // click on "Cultura" item cat = CategoryHelper.CAT_CULTURA; args = new Bundle(); elf = new EventsListingFragment(); args.putString(SearchFragment.ARG_CATEGORY, cat); elf.setArguments(args); out[0] = elf; out[1] = TAG_FRAGMENT_EVENT_LIST; break; case 4: // click on "Sport" item cat = CategoryHelper.CAT_SPORT; args = new Bundle(); elf = new EventsListingFragment(); args.putString(SearchFragment.ARG_CATEGORY, cat); elf.setArguments(args); out[0] = elf; out[1] = TAG_FRAGMENT_EVENT_LIST; break; case 5: // click on "Svago" item cat = CategoryHelper.CAT_SOCIALE; args = new Bundle(); elf = new EventsListingFragment(); args.putString(SearchFragment.ARG_CATEGORY, cat); elf.setArguments(args); out[0] = elf; out[1] = TAG_FRAGMENT_EVENT_LIST; break; case 6: // click on "Altri eventi" item cat = CategoryHelper.EVENT_NONCATEGORIZED; args = new Bundle(); elf = new EventsListingFragment(); args.putString(SearchFragment.ARG_CATEGORY, cat); elf.setArguments(args); out[0] = elf; out[1] = TAG_FRAGMENT_EVENT_LIST; break; default: return null; } return out; } // to handle action bar menu @Override public boolean onCreateOptionsMenu(Menu menu) { Log.i("MENU", "start on Create Options Menu MAIN frag"); MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.global_menu, menu); // if (listmenu) { // Log.i("MENU", "ITEM 0" + menu.getItem(0).toString()); // menu.getItem(0).setVisible(false); // } // else { // Log.i("MENU", "ITEM 1" + menu.getItem(1).toString()); // menu.getItem(1).setVisible(false); // } // super.onCreateOptionsMenu(menu, inflater); return true; } @Override public void onBackPressed() { Log.i("BACKPRESSED", "MainActivity --> OnBackPressed "); // See bug: // http://stackoverflow.com/questions/13418436/android-4-2-back-stack-behaviour-with-nested-fragments/14030872#14030872 // If the fragment exists and has some back-stack entry FragmentManager fm = getSupportFragmentManager(); Fragment currentFragment = fm.findFragmentById(R.id.content_frame); if (currentFragment != null && currentFragment.getChildFragmentManager().getBackStackEntryCount() > 0) { // Get the fragment fragment manager - and pop the backstack currentFragment.getChildFragmentManager().popBackStack(); } // Else, nothing in the direct fragment back stack else { Log.i("BACKPRESSED", "MainActivity --> current fragment: " + currentFragment.getTag() + "!"); if (!this.TAG_FRAGMENT_MAP.equals(currentFragment.getTag())) this.setTitleWithDrawerTitle(); if (this.TAG_FRAGMENT_EVENT_LIST.equals(currentFragment.getTag())) AnimateFirstDisplayListener.displayedImages.clear(); super.onBackPressed(); } } /* * public void goHomeFragment( AbstractNavDrawerActivity activity) { * activity.getSupportFragmentManager().beginTransaction() * .replace(R.id.content_frame, new MainFragment(), * HOME_FRAGMENT_TAG).commit(); activity.setTitleWithDrawerTitle(); } */ @Override protected void onPostCreate(Bundle savedInstanceState) { super.onPostCreate(savedInstanceState); // Sync the toggle state after onRestoreInstanceState has occurred. mDrawerToggle.syncState(); } @Override public void onConfigurationChanged(Configuration newConfig) { super.onConfigurationChanged(newConfig); mDrawerToggle.onConfigurationChanged(newConfig); } @Override public boolean onOptionsItemSelected(MenuItem item) { if (mDrawerToggle.onOptionsItemSelected(item)) { return true; } return false; } private class TokenTask extends AsyncTask<Void, Void, String> { @Override protected String doInBackground(Void... params) { SCAccessProvider provider = SCAccessProvider.getInstance(MainActivity.this); try { return provider.readToken(MainActivity.this); } catch (AACException e) { Log.e(MainActivity.class.getName(), "" + e.getMessage()); switch (e.getStatus()) { case HttpStatus.SC_UNAUTHORIZED: try { provider.logout(MainActivity.this); } catch (AACException e1) { e1.printStackTrace(); } default: break; } return null; } } @Override protected void onPostExecute(String result) { if (result == null) { SCAccessProvider provider = SCAccessProvider.getInstance(MainActivity.this); try { provider.login(MainActivity.this, null); initDataManagement(); } catch (AACException e) { Log.e(MainActivity.class.getName(), "" + e.getMessage()); } } else initDataManagement(); } } } <file_sep>/******************************************************************************* * Copyright 2012-2013 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package eu.iescities.pilot.rovereto.roveretoexplorer.custom.data; import eu.iescities.pilot.rovereto.roveretoexplorer.custom.data.model.ExplorerObject; import eu.trentorise.smartcampus.storage.BasicObject; import eu.trentorise.smartcampus.storage.StorageConfigurationException; import eu.trentorise.smartcampus.storage.db.BeanStorageHelper; import eu.trentorise.smartcampus.storage.db.StorageConfiguration; public class DTStorageConfiguration implements StorageConfiguration { private static final long serialVersionUID = 906503482979452854L; @SuppressWarnings("unchecked") private static Class<? extends BasicObject>[] classes = (Class<? extends BasicObject>[])new Class<?>[]{ExplorerObject.class}; private static BeanStorageHelper<ExplorerObject> eventHelper = new EventStorageHelper(); @Override public Class<? extends BasicObject>[] getClasses() { return classes; } @Override public String getTableName(Class<? extends BasicObject> cls) throws StorageConfigurationException { if (cls.equals(ExplorerObject.class)) { return "events"; } return null; } @SuppressWarnings("unchecked") @Override public <T extends BasicObject> BeanStorageHelper<T> getStorageHelper(Class<T> cls) throws StorageConfigurationException { if (cls.equals(ExplorerObject.class)) { return (BeanStorageHelper<T>) eventHelper; } return null; } } <file_sep>package eu.iescities.pilot.rovereto.roveretoexplorer.fragments.event.community; import java.util.HashMap; import java.util.List; import android.app.Activity; import android.content.Context; import android.graphics.Typeface; import android.view.LayoutInflater; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.widget.BaseExpandableListAdapter; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; import eu.iescities.pilot.rovereto.roveretoexplorer.R; import eu.iescities.pilot.rovereto.roveretoexplorer.custom.AbstractAsyncTaskProcessor; import eu.iescities.pilot.rovereto.roveretoexplorer.custom.ReviewHelper; import eu.iescities.pilot.rovereto.roveretoexplorer.custom.ReviewHelper.ReviewHandler; import eu.iescities.pilot.rovereto.roveretoexplorer.custom.data.DTHelper; import eu.iescities.pilot.rovereto.roveretoexplorer.custom.data.model.CommunityData; import eu.iescities.pilot.rovereto.roveretoexplorer.custom.data.model.ExplorerObject; import eu.iescities.pilot.rovereto.roveretoexplorer.custom.data.model.Review; import eu.trentorise.smartcampus.android.common.SCAsyncTask; import eu.trentorise.smartcampus.protocolcarrier.exceptions.SecurityException; public class CommentAdapter extends BaseExpandableListAdapter { private Context _context; private Activity activity; private ExplorerObject mEvent; private List<String> _listDataHeader; // header titles // child data in format of header title, child title private HashMap<String, List<Review>> _listDataChild; private RefreshComments refreshcomment; public CommentAdapter(Context context, List<String> listDataHeader, HashMap<String, List<Review>> listChildData, Activity activity, ExplorerObject event, RefreshComments refreshComments) { this._context = context; this._listDataHeader = listDataHeader; this._listDataChild = listChildData; this.activity = activity; this.mEvent = event; this.refreshcomment = refreshComments; } @Override public void notifyDataSetChanged() { super.notifyDataSetChanged(); } @Override public Object getChild(int groupPosition, int childPosititon) { return this._listDataChild.get(this._listDataHeader.get(groupPosition)).get(childPosititon); } @Override public long getChildId(int groupPosition, int childPosition) { return childPosition; } @Override public View getChildView(int groupPosition, final int childPosition, boolean isLastChild, View convertView, ViewGroup parent) { final Review review = (Review) getChild(groupPosition, childPosition); if (convertView == null) { LayoutInflater infalInflater = (LayoutInflater) this._context .getSystemService(Context.LAYOUT_INFLATER_SERVICE); convertView = infalInflater.inflate(R.layout.event_comment_item, parent, false); // convertView = // inflater.inflate(R.layout.forum_list_child_item_row,parent, // false); } TextView txtListChild = (TextView) convertView.findViewById(R.id.lblListItem); txtListChild.setText(review.getComment()); return convertView; } @Override public int getChildrenCount(int groupPosition) { return this._listDataChild.get(this._listDataHeader.get(groupPosition)).size(); } @Override public Object getGroup(int groupPosition) { return this._listDataHeader.get(groupPosition); } @Override public int getGroupCount() { return this._listDataHeader.size(); } @Override public long getGroupId(int groupPosition) { return groupPosition; } public void getGroupClear(int groupPosition) { } @Override public View getGroupView(int groupPosition, boolean isExpanded, View convertView, ViewGroup parent) { String headerTitle = (String) getGroup(groupPosition); if (convertView == null) { LayoutInflater infalInflater = (LayoutInflater) this._context .getSystemService(Context.LAYOUT_INFLATER_SERVICE); convertView = infalInflater.inflate(R.layout.event_comments_group, null); } TextView lblListHeader = (TextView) convertView.findViewById(R.id.lblListHeader); lblListHeader.setTypeface(null, Typeface.BOLD); lblListHeader.setText(headerTitle); // setlistener setCommentAddInteraction(convertView); return convertView; } private void setCommentAddInteraction(View convertView) { // set listener on the button ImageView image = (ImageView) convertView.findViewById(R.id.event_comment_action); image.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { ReviewHelper.reviewDialog(_context, 0, new ReviewProcessor(activity), R.string.comment_event_dialog_title); } }); } private class ReviewProcessor extends AbstractAsyncTaskProcessor<Review, CommunityData> implements ReviewHandler { public ReviewProcessor(Activity activity) { super(activity); } @Override public CommunityData performAction(Review... params) throws SecurityException, Exception { return DTHelper.writeReview(mEvent, params[0]); } @Override public void handleResult(CommunityData result) { mEvent.setCommunityData(result); if (_context != null) Toast.makeText(_context, R.string.comment_success, Toast.LENGTH_SHORT).show(); // return community data instead a review // notifyDataSetChanged(); if (refreshcomment != null) refreshcomment.refresh(); } @Override public void onReviewChanged(Review review) { new SCAsyncTask<Review, Void, CommunityData>(activity, this).execute(review); // update list of comment } } @Override public boolean hasStableIds() { return false; } @Override public boolean isChildSelectable(int groupPosition, int childPosition) { return true; } } <file_sep>/******************************************************************************* * Copyright 2012-2013 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package eu.iescities.pilot.rovereto.roveretoexplorer.custom.data; import java.util.Map; import android.content.ContentValues; import android.database.Cursor; import eu.iescities.pilot.rovereto.roveretoexplorer.custom.data.model.ExplorerObject; import eu.trentorise.smartcampus.android.common.Utils; import eu.trentorise.smartcampus.storage.db.BeanStorageHelper; public class EventStorageHelper implements BeanStorageHelper<ExplorerObject> { @Override public ExplorerObject toBean(Cursor cursor) { ExplorerObject event = new ExplorerObject(); BaseDTStorageHelper.setCommonFields(cursor, event); event.setWhenWhere(cursor.getString(cursor.getColumnIndex("whenWhere"))); event.setAddress(new Address()); event.getAddress().setLuogo(cursor.getString(cursor.getColumnIndex("luogo"))); event.getAddress().setCitta(cursor.getString(cursor.getColumnIndex("citta"))); event.getAddress().setVia(cursor.getString(cursor.getColumnIndex("via"))); event.setImage(cursor.getString(cursor.getColumnIndex("image"))); event.setWebsiteUrl(cursor.getString(cursor.getColumnIndex("websiteurl"))); event.setFacebookUrl(cursor.getString(cursor.getColumnIndex("facebookurl"))); event.setTwitterUrl(cursor.getString(cursor.getColumnIndex("twitterurl"))); event.setOrigin(cursor.getString(cursor.getColumnIndex("origin"))); event.setImage(cursor.getString(cursor.getColumnIndex("image"))); event.setCategory(Utils.convertJSONToObjects(cursor.getString(cursor.getColumnIndex("category")), String.class)); @SuppressWarnings("unchecked") Map<String, Object> map = Utils.convertJSONToObject(cursor.getString(cursor.getColumnIndex("contacts")), Map.class); if (map != null && !map.isEmpty()) event.setContacts(map); return event; } @Override public ContentValues toContent(ExplorerObject bean) { ExplorerObject event = bean; ContentValues values = BaseDTStorageHelper.toCommonContent(event); values.put("whenWhere", event.getWhenWhere()); if (event.getAddress() != null) { values.put("luogo", event.getAddress().getLuogo()); values.put("via", event.getAddress().getVia()); values.put("citta", event.getAddress().getCitta()); } values.put("image", event.getImage()); values.put("websiteurl", event.getWebsiteUrl()); values.put("twitterurl", event.getTwitterUrl()); values.put("facebookurl", event.getFacebookUrl()); values.put("origin", event.getOrigin()); values.put("category", Utils.convertToJSON(event.getCategory())); if (event.getContacts()!= null) { values.put("contacts", Utils.convertToJSON(event.getContacts())); } return values; } @Override public Map<String, String> getColumnDefinitions() { Map<String, String> defs = BaseDTStorageHelper.getCommonColumnDefinitions(); defs.put("whenWhere", "TEXT"); defs.put("luogo", "TEXT"); defs.put("via", "TEXT"); defs.put("citta", "TEXT"); defs.put("image", "TEXT"); defs.put("websiteurl", "TEXT"); defs.put("twitterurl", "TEXT"); defs.put("facebookurl", "TEXT"); defs.put("origin", "TEXT"); defs.put("category", "TEXT"); defs.put("contacts", "TEXT"); return defs; } @Override public boolean isSearchable() { return true; } } <file_sep>/******************************************************************************* * Copyright 2012-2013 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package eu.iescities.pilot.rovereto.roveretoexplorer.custom.data; import java.util.ArrayList; import java.util.Calendar; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import android.content.Context; import android.database.sqlite.SQLiteDatabase; import eu.iescities.pilot.rovereto.roveretoexplorer.custom.DTParamsHelper; import eu.iescities.pilot.rovereto.roveretoexplorer.custom.data.model.BaseDTObject; import eu.iescities.pilot.rovereto.roveretoexplorer.custom.data.model.ExplorerObject; import eu.trentorise.smartcampus.android.common.Utils; import eu.trentorise.smartcampus.protocolcarrier.exceptions.ConnectionException; import eu.trentorise.smartcampus.protocolcarrier.exceptions.ProtocolException; import eu.trentorise.smartcampus.protocolcarrier.exceptions.SecurityException; import eu.trentorise.smartcampus.storage.DataException; import eu.trentorise.smartcampus.storage.StorageConfigurationException; import eu.trentorise.smartcampus.storage.db.StorageConfiguration; import eu.trentorise.smartcampus.storage.sync.ISynchronizer; import eu.trentorise.smartcampus.storage.sync.SyncData; import eu.trentorise.smartcampus.storage.sync.SyncStorageHelper; import eu.trentorise.smartcampus.storage.sync.SyncStorageHelperWithPaging; import eu.trentorise.smartcampus.storage.sync.SyncStorageWithPaging; /** * Specific storage that deletes the old data upon sync complete * * @author raman * */ public class DTSyncStorage extends SyncStorageWithPaging { private static final Map<String, Object> exclude = new HashMap<String, Object>(); private static final Map<String, Object> include = new HashMap<String, Object>(); public DTSyncStorage(Context context, String appToken, String dbName, int dbVersion, StorageConfiguration config) { super(context, appToken, dbName, dbVersion, config); Map<String, Object> map = null; map = DTParamsHelper.getExcludeArray(); if (map != null) exclude.putAll(map); map = DTParamsHelper.getIncludeArray(); if (map != null) include.putAll(map); } @Override protected SyncStorageHelper createHelper(Context context, String dbName, int dbVersion, StorageConfiguration config) { return new DTSyncStorageHelper(context, dbName, dbVersion, config); } public void synchronize(final String token) throws StorageConfigurationException, DataException, SecurityException, ConnectionException, ProtocolException { synchronize(new ISynchronizer() { @Override public SyncData fetchSyncData(Long version, SyncData in) throws SecurityException, ConnectionException, ProtocolException { SyncData dbData = remoteSynchronize(); ((DTSyncStorageHelper) helper).removeOld(); return dbData; } }); } protected SyncData remoteSynchronize() { return null; } protected Map<String, List<String>> convertToBasicObjectDeleted(Map<String, List<String>> deleted) { Map<String, List<String>> returnDTOObjects = new HashMap<String, List<String>>(); Iterator it = deleted.entrySet().iterator(); while (it.hasNext()) { // for every map element iterate the entire list { Map.Entry pairs = (Map.Entry) it.next(); String key = (String) pairs.getKey(); Class<? extends BaseDTObject> cls = null; if ("eu.trentorise.smartcampus.dt.model.EventObject".equals(key)) { cls = BaseDTObject.class; } List<String> dtoObjects = (List<String>) pairs.getValue(); // //convert the single element // basicobjects.add(newObject); // //add the element to the return list // } // add the list to the return map // key or the new one??? returnDTOObjects.put(cls.getCanonicalName(), dtoObjects); } // System.out.println(pairs.getKey() + " = " + pairs.getValue()); } return returnDTOObjects; } protected Map<String, List<Object>> convertToBasicObject(Map<String, List<Object>> map) { Map<String, List<Object>> returnDTOObjects = new HashMap<String, List<Object>>(); Iterator it = map.entrySet().iterator(); while (it.hasNext()) { // for every map element iterate the entire list { Map.Entry pairs = (Map.Entry) it.next(); String key = (String) pairs.getKey(); Class<? extends BaseDTObject> cls = null; if ("eu.trentorise.smartcampus.dt.model.EventObject".equals(key)) { cls = ExplorerObject.class; } List<Object> dtoObjects = (List<Object>) pairs.getValue(); List<Object> basicobjects = new ArrayList<Object>(); for (Object object : dtoObjects) { BaseDTObject newObject = null; if (ExplorerObject.class.equals(cls)) { newObject = new ExplorerObject(); newObject = Utils.convertObjectToData(ExplorerObject.class, object); } // convert the single element basicobjects.add(newObject); // add the element to the return list } // add the list to the return map // key or the new one??? returnDTOObjects.put(cls.getCanonicalName(), basicobjects); } // System.out.println(pairs.getKey() + " = " + pairs.getValue()); } return returnDTOObjects; } private static class DTSyncStorageHelper extends SyncStorageHelperWithPaging { // sync filtering: exclude transit stops // static { // exclude.put("source", "smartplanner-transitstops"); // } public DTSyncStorageHelper(Context context, String dbName, int version, StorageConfiguration config) { super(context, dbName, version, config); } @Override public SyncData getDataToSync(long version) throws StorageConfigurationException { SyncData data = super.getDataToSync(version); data.setExclude(exclude); data.setInclude(include); return data; } private void removeOld() { SQLiteDatabase db = helper.getWritableDatabase(); db.beginTransaction(); Calendar calendar = Calendar.getInstance(); calendar.add(Calendar.DATE, -1); calendar.set(Calendar.HOUR_OF_DAY, 23); calendar.set(Calendar.MINUTE, 59); calendar.set(Calendar.SECOND, 0); try { db.delete("events", "attending IS NULL AND toTime < " + calendar.getTimeInMillis(), null); // c.moveToNext(); // int total = c.getInt(0); // if (total > num) { // int toDelete = total - num; // c = // db.rawQuery("SELECT id FROM notifications WHERE starred = 0 ORDER BY timestamp ASC", // null); // c.moveToFirst(); // for (int i = 0; i < toDelete; i++) { // db.delete("notifications", "id = '" + c.getString(0) + "'", // null); // c.moveToNext(); // } // } db.setTransactionSuccessful(); } finally { db.endTransaction(); } } } } <file_sep>/******************************************************************************* * Copyright 2012-2013 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package eu.iescities.pilot.rovereto.roveretoexplorer.custom; import java.util.Arrays; import java.util.List; import android.content.Context; import eu.iescities.pilot.rovereto.roveretoexplorer.R; import eu.iescities.pilot.rovereto.roveretoexplorer.fragments.search.WhenForSearch; import eu.iescities.pilot.rovereto.roveretoexplorer.fragments.search.WhereForSearch; public class SearchHelper { private static long oneDay = 1 * 24 * 60 * 60 * 1000; private static WhenForSearch[] WHEN_CATEGORIES = null; private static WhereForSearch[] WHERE_CATEGORIES =null; public interface OnSearchListener { void onSearch(String query); } public static void initSpinners(Context context) { WHEN_CATEGORIES = new WhenForSearch[] { new WhenForSearch(context.getString(R.string.search_anytime),0,0), new WhenForSearch(context.getString(R.string.search_today),0,oneDay), new WhenForSearch(context.getString(R.string.search_tomorrow),oneDay,oneDay), new WhenForSearch(context.getString(R.string.search_thisweek),0,7*oneDay), new WhenForSearch(context.getString(R.string.search_intwoweeks),0,14 * oneDay), new WhenForSearch(context.getString(R.string.search_inonemonth),0,30 * oneDay)}; WHERE_CATEGORIES = new WhereForSearch[] { new WhereForSearch(context.getString(R.string.search_anywhere),0.00), new WhereForSearch(context.getString(R.string.search_within,"100m"),0.001), new WhereForSearch(context.getString(R.string.search_within,"200m"),0.002), new WhereForSearch(context.getString(R.string.search_within,"500m"),0.005), new WhereForSearch(context.getString(R.string.search_within,"1km"),0.01), new WhereForSearch(context.getString(R.string.search_within,"10km"),0.1), new WhereForSearch(context.getString(R.string.search_within,"50km"),0.5)}; } public static List<WhenForSearch> getWhenList() { return Arrays.asList(WHEN_CATEGORIES); } public static List<WhereForSearch> getWhereList() { return Arrays.asList(WHERE_CATEGORIES); } } <file_sep>package eu.iescities.pilot.rovereto.roveretoexplorer.fragments.event.info.edit; import java.text.ParseException; import java.util.Date; import java.util.List; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.support.v4.app.DialogFragment; import android.support.v4.app.Fragment; import android.support.v7.app.ActionBarActivity; import android.util.Log; import android.view.LayoutInflater; import android.view.Menu; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.widget.AutoCompleteTextView; import android.widget.AutoCompleteTextView.Validator; import android.widget.Button; import android.widget.EditText; import android.widget.ImageButton; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; import eu.iescities.pilot.rovereto.roveretoexplorer.R; import eu.iescities.pilot.rovereto.roveretoexplorer.custom.AbstractAsyncTaskProcessor; import eu.iescities.pilot.rovereto.roveretoexplorer.custom.DTParamsHelper; import eu.iescities.pilot.rovereto.roveretoexplorer.custom.Utils; import eu.iescities.pilot.rovereto.roveretoexplorer.custom.data.Address; import eu.iescities.pilot.rovereto.roveretoexplorer.custom.data.DTHelper; import eu.iescities.pilot.rovereto.roveretoexplorer.custom.data.model.ExplorerObject; import eu.trentorise.smartcampus.android.common.GeocodingAutocompletionHelper; import eu.trentorise.smartcampus.android.common.GeocodingAutocompletionHelper.OnAddressSelectedListener; import eu.trentorise.smartcampus.android.common.SCAsyncTask; import eu.trentorise.smartcampus.android.common.geo.OSMAddress; import eu.trentorise.smartcampus.protocolcarrier.exceptions.SecurityException; public class Fragment_EvDetail_Info_WhenWhere extends Fragment { private Context context; public final static int REQUEST_CODE= 10; private ExplorerObject mEvent = null; private String mEventId; protected TextView txtWhenWhere; protected TextView formLabel; protected EditText txtStartDay; protected EditText txtStartTime; protected EditText txtEndDay; protected EditText txtEndTime; //this edit field is currently disabled //protected EditText txtDuration; protected Date fromDate; protected Date fromTime; protected EditText txtPlaceName; protected EditText txtCity; protected AutoCompleteTextView txtStreet; protected Position where; OSMAddress selectedAddress = null; @Override public void onAttach(Activity activity) { super.onAttach(activity); Log.d("FRAGMENT LC", "Fragment_evDetail_Info_Where --> onAttach"); } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Log.d("FRAGMENT LC", "Fragment_evDetail_Info_Where --> onCreate"); this.context = this.getActivity(); if (savedInstanceState == null) { Log.d("FRAGMENT LC", "onCreate FIRST TIME"); setHasOptionsMenu(true); if (getArguments() != null) { mEventId = getArguments().getString(Utils.ARG_EVENT_ID); Log.i("FRAGMENT LC", "Fragment_evDetail_Info_Where --> EVENT ID: " + mEventId); mEvent = DTHelper.findEventById(mEventId); } } else { Log.d("FRAGMENT LC", "Fragment_evDetail_Info_Where --> onCreate SUBSEQUENT TIME"); } } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { super.onCreateView(inflater, container, savedInstanceState); Log.d("FRAGMENT LC", "Fragment_evDetail_Info_Where --> onCreateView"); return inflater.inflate(R.layout.frag_ev_detail_info_edit_when_where, container, false); } @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); List<Double> mapcenter = DTParamsHelper.getCenterMap(); double[] refLoc = mapcenter == null ? null : new double[] { mapcenter.get(0), mapcenter.get(1) }; Log.d("FRAGMENT LC", "Fragment_evDetail_Info_Where --> onActivityCreated"); ((ActionBarActivity) getActivity()).getSupportActionBar().setTitle(getResources().getString(R.string.modify) + " " + getResources().getString(R.string.date_place_name)); // getActivity().getActionBar().setTitle( // getResources().getString(R.string.modify) + " " + getResources().getString(R.string.date_place_name)); txtWhenWhere= (EditText) getActivity().findViewById(R.id.when_where_text); txtStartDay = (EditText) getActivity().findViewById(R.id.start_day_text); txtStartTime = (EditText) getActivity().findViewById(R.id.start_time_text); txtEndDay = (EditText) getActivity().findViewById(R.id.end_day_text); txtEndTime = (EditText) getActivity().findViewById(R.id.end_time_text); //txtDuration = (EditText) getActivity().findViewById(R.id.duration_text); formLabel = (TextView) getActivity().findViewById(R.id.title_when_where_label); txtPlaceName = (EditText) getActivity().findViewById(R.id.place_name_text); txtCity = (EditText) getActivity().findViewById(R.id.city_text); //txtStreet = (EditText) getActivity().findViewById(R.id.street_text); txtStreet = (AutoCompleteTextView) getView().findViewById(R.id.street_text); GeocodingAutocompletionHelper fromAutocompletionHelper = new GeocodingAutocompletionHelper(getActivity(), txtStreet, Utils.ROVERETO_REGION, Utils.ROVERETO_COUNTRY, Utils.ROVERETO_ADM_AREA, refLoc); fromAutocompletionHelper.setOnAddressSelectedListener(new OnAddressSelectedListener() { @Override public void onAddressSelected(android.location.Address address) { Log.i("ADDRESS", "Fragment_EvDetail_Info_WhenWhere --> onAddressSelected"); //convert from address to OsmAddress savePosition(Utils.getOsmAddressFromAddress(address)); } }); ImageView imgBtn = (ImageView) getView().findViewById(R.id.select_where_map); if (imgBtn != null) { imgBtn.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(getActivity(), AddressSelectActivity.class); //not useful but necessary because otherwise the app crashes //in that it is dependent on line 57 of the InfoDialog class of the //package eu.trentorise.smartcampus.android.map; intent.putExtra("field", Utils.ADDRESS); //launch the sub-activity to locate an address in the map startActivityForResult(intent, REQUEST_CODE); } }); } formLabel.setText("Evento: " + mEvent.getTitle()); if (mEvent.getWhenWhere() != null) { txtWhenWhere.setText(mEvent.getWhenWhere()); } else { txtWhenWhere.setText(""); } if (mEvent.getFromTime() != null) { String[] fromDateTime = Utils.getDateTimeString(this.context, mEvent.getFromTime(), Utils.DATETIME_FORMAT, false, false); Log.d("FRAGMENT LC", "Fragment_evDetail_Info_When --> from Time: " + fromTime); txtStartDay.setText(fromDateTime[0]); if (!fromDateTime[1].matches("")) txtStartTime.setText(fromDateTime[1]); } else { txtStartDay.setText(getResources().getString(R.string.day_hint)); txtStartTime.setText(getResources().getString(R.string.time_hint)); } txtStartDay.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // DialogFragment f = // DatePickerDialogFragment.newInstance((EditText) v); DialogFragment f = DatePickerDialogFragment.newInstance((EditText) v); f.setArguments(DatePickerDialogFragment.prepareData(txtStartDay.getText().toString())); f.show(getActivity().getSupportFragmentManager(), "datePicker"); } }); txtStartTime.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { DialogFragment f = TimePickerDialogFragment.newInstance((EditText) v); f.setArguments(TimePickerDialogFragment.prepareData(txtStartTime.getText().toString())); f.show(getActivity().getSupportFragmentManager(), "timePicker"); } }); if ((mEvent.getToTime() != null) && (mEvent.getToTime() != 0)) { String[] toDateTime = Utils.getDateTimeString(this.context, mEvent.getToTime(), Utils.DATETIME_FORMAT, false, false); Log.d("FRAGMENT LC", "Fragment_evDetail_Info_When --> to Time: " + toDateTime); txtEndDay.setText(toDateTime[0]); if (!toDateTime[1].matches("")) txtEndTime.setText(toDateTime[1]); // compute duration, currently duration edit field is disabled // String duration = "3 ore"; // txtDuration.setText(duration); } else { // txtEndDay.setText(getResources().getString(R.string.day_hint)); // txtEndTime.setText(getResources().getString(R.string.time_hint)); txtEndDay.setText(""); txtEndTime.setText(""); } txtEndDay.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { DialogFragment f = DatePickerDialogFragment.newInstance((EditText) v); f.setArguments(DatePickerDialogFragment.prepareData(txtEndDay.getText().toString())); f.show(getActivity().getSupportFragmentManager(), "datePicker"); } }); txtEndTime.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { DialogFragment f = TimePickerDialogFragment.newInstance((EditText) v); f.setArguments(TimePickerDialogFragment.prepareData(txtEndTime.getText().toString())); f.show(getActivity().getSupportFragmentManager(), "timePicker"); } }); Address address = mEvent.getAddress(); if (address != null) { String place = (address.getLuogo() != null) ? (String) address.getLuogo() : ""; String street = (address.getVia() != null) ? (String) address.getVia() : ""; String city = (address.getCitta() != null) ? (String) address.getCitta() : ""; txtPlaceName.setText(place); txtCity.setText(city); txtStreet.setText(street); } Button modifyBtn = (Button) getView().findViewById(R.id.edit_whenwhere_modify_button); modifyBtn.setOnClickListener(new OnClickListener() { @Override public void onClick(View view) { Address modifiedAddress = new Address(); modifiedAddress.setLuogo(txtPlaceName.getText().toString()); modifiedAddress.setVia(txtStreet.getText().toString()); modifiedAddress.setCitta(txtCity.getText().toString()); mEvent.setAddress(modifiedAddress); // persist the new contacts Log.i("FRAGMENT LC", "Edited Fields: " + txtStartDay.getText() + ", " + txtStartTime.getText() + ", " + txtEndDay.getText() + ", " + txtEndTime.getText()); // Toast.makeText( // context, // "Edited Fields: " + txtStartDay.getText() + ", " + // txtStartTime.getText() + ", " // + txtEndDay.getText() + ", " + txtEndTime.getText(), // Toast.LENGTH_SHORT).show(); if (!txtStartDay.getText().toString().matches("")) { String start_datetime; if (!txtStartTime.getText().toString().matches("")) { start_datetime = txtStartDay.getText().toString() + " " + txtStartTime.getText().toString(); Log.i("FRAGMENT LC", "datatime inizio string: " + start_datetime); Log.i("FRAGMENT LC", "datatime inizio long: " + Utils.toDateTimeLong(Utils.DATETIME_FORMAT, start_datetime)); String[] fromTime = Utils.getDateTimeString(context, Utils.toDateTimeLong(Utils.DATETIME_FORMAT, start_datetime), Utils.DATETIME_FORMAT, false, false); Log.i("FRAGMENT LC", "datatime inizio string converted: " + fromTime); mEvent.setFromTime(Utils.toDateTimeLong(Utils.DATETIME_FORMAT, start_datetime)); } else { start_datetime = txtStartDay.getText().toString(); Log.i("FRAGMENT LC", "data inizio string: " + start_datetime); Log.i("FRAGMENT LC", "data inizio long: " + Utils.toDateTimeLong(Utils.DATE_FORMAT, start_datetime)); String[] fromTime = Utils.getDateTimeString(context, Utils.toDateTimeLong(Utils.DATE_FORMAT, start_datetime), Utils.DATE_FORMAT, false, false); Log.i("FRAGMENT LC", "data inizio string converted: " + fromTime); mEvent.setFromTime(Utils.toDateTimeLong(Utils.DATE_FORMAT, start_datetime)); } } if (!txtEndDay.getText().toString().matches("")) { String end_datetime; if (!txtEndTime.getText().toString().matches("")) { end_datetime = txtEndDay.getText().toString() + " " + txtEndTime.getText().toString(); Log.i("FRAGMENT LC", "datatime fine string: " + end_datetime); Log.i("FRAGMENT LC", "datatime fine long: " + Utils.toDateTimeLong(Utils.DATETIME_FORMAT, end_datetime)); String[] toTime = Utils.getDateTimeString(context, Utils.toDateTimeLong(Utils.DATETIME_FORMAT, end_datetime), Utils.DATETIME_FORMAT, false, false); Log.i("FRAGMENT LC", "datatime fine string converted: " + toTime); mEvent.setToTime(Utils.toDateTimeLong(Utils.DATETIME_FORMAT, end_datetime)); } else { end_datetime = txtEndDay.getText().toString(); Log.i("FRAGMENT LC", "data fine string: " + end_datetime); Log.i("FRAGMENT LC", "data fine long: " + Utils.toDateTimeLong(Utils.DATE_FORMAT, end_datetime)); String[] toTime = Utils.getDateTimeString(context, Utils.toDateTimeLong(Utils.DATE_FORMAT, end_datetime), Utils.DATE_FORMAT, false, false); Log.i("FRAGMENT LC", "data fine string converted: " + toTime); mEvent.setToTime(Utils.toDateTimeLong(Utils.DATE_FORMAT, end_datetime)); } } if (!checkDateTime()) { Toast.makeText(getActivity(), getActivity().getString(R.string.toast_time_wrong), Toast.LENGTH_SHORT).show(); return; } new SCAsyncTask<ExplorerObject, Void, Boolean>(getActivity(), new UpdateEventProcessor(getActivity())) .execute(mEvent); // Utils.appEvents.set(index, mEvent); } }); Button cancelBtn = (Button) getView().findViewById(R.id.edit_contacts_cancel_button); cancelBtn.setOnClickListener(new OnClickListener() { @Override public void onClick(View arg0) { getActivity().getSupportFragmentManager().popBackStack(); } }); } protected boolean checkDateTime() { Date fromDate = null; Date toDate = null; Date fromTime = null; Date toTime = null; try { fromDate = Utils.FORMAT_DATE_UI_LONG.parse(txtStartDay.getText().toString()); toDate = Utils.FORMAT_DATE_UI_LONG.parse(txtEndDay.getText().toString()); fromTime = Utils.FORMAT_TIME_UI.parse(txtStartTime.getText().toString()); toTime = Utils.FORMAT_TIME_UI.parse(txtEndTime.getText().toString()); } catch (ParseException e) { } if (toDate!=null ){ if (fromDate.after(toDate)) return false; if (fromDate.equals(toDate)) if (fromTime.after(toTime)) return false; } return true; } // private void savePosition(android.location.Address address) { // // Log.i("ADDRESS", "Fragment_EvDetail_Info_WhenWhere --> saveAddress"); // // EditText street = null; // EditText city = null; // // String s = ""; // for (int i = 0; i <= address.getMaxAddressLineIndex(); i++) { // // Log.i("ADDRESS", "AddressLine: " + address.getAddressLine(i)); // s += address.getAddressLine(i) + " "; // } // s = s.trim(); // // Log.i("ADDRESS", "Fragment_EvDetail_Info_WhenWhere --> AddressLine0: " + address.getAddressLine(0)); // Log.i("ADDRESS", "Fragment_EvDetail_Info_WhenWhere --> Address Country: " + address.getCountryName()); // Log.i("ADDRESS", "Fragment_EvDetail_Info_WhenWhere --> Address Locality: " + address.getLocality()); // // // where = new Position(address.getAddressLine(0), address.getCountryName(), address.getLocality(), // address.getLongitude(), address.getLatitude()); // // if (getView() != null) { // street = (EditText) getView().findViewById(R.id.street_text); // city = (EditText) getView().findViewById(R.id.city_text); // } // // if (street != null) { // street.setFocusable(false); // street.setFocusableInTouchMode(false); // street.setText(s); // street.setFocusable(true); // street.setFocusableInTouchMode(true); // } // // if (city != null) { // city.setFocusable(false); // city.setFocusableInTouchMode(false); // city.setText(address.getLocality()); // city.setFocusable(true); // city.setFocusableInTouchMode(true); // } // // } private void savePosition(OSMAddress address) { if (address!=null){ if (address.getName()!=null && !address.getName().matches(address.getStreet())) txtPlaceName.setText(address.getName()); txtCity.setText(address.city()); txtStreet.setText(address.getStreet()); mEvent.setLocation(address.getLocation()); } } // to be deleted when there will be the call to the server public void setNewEventContacts(String eventID, String[] tel, String[] email, String website) { // //set the new fields // Map<String,Object> contacts = new HashMap<String, Object>(); // contacts.put("telefono", tel); // contacts.put("email", email); // mEvent.getContacts().clear(); // mEvent.setContacts(contacts); // mEvent.setWebsiteUrl(website); } // @Override // public void onActivityResult(int requestCode, int resultCode, Intent result) { // // if (resultCode == RESULT_SELECTED) { // android.location.Address address = result.getParcelableExtra("address"); // String field = result.getExtras().getString("field"); // savePosition(address); // } // } @Override public void onActivityResult(int requestCode, int resultCode, Intent result_data) { if (resultCode == android.app.Activity.RESULT_OK && requestCode == REQUEST_CODE) { selectedAddress = (OSMAddress) result_data.getSerializableExtra(Utils.ADDRESS); savePosition(selectedAddress); } } @Override public void onStart() { super.onStart(); Log.d("FRAGMENT LC", "Fragment_evDetail_Info_Where --> onStart"); } @Override public void onResume() { super.onResume(); Log.d("FRAGMENT LC", "Fragment_evDetail_Info_Where --> onResume"); } @Override public void onPause() { super.onPause(); Log.d("FRAGMENT LC", "Fragment_evDetail_Info_Where --> onPause"); } @Override public void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); Log.d("FRAGMENT LC", "Fragment_evDetail_Info_Where --> onSaveInstanceState"); } @Override public void onStop() { super.onStop(); Log.d("FRAGMENT LC", "Fragment_evDetail_Info_Where --> onStop"); } @Override public void onDestroyView() { super.onDestroyView(); Log.d("FRAGMENT LC", "Fragment_evDetail_Info_Where --> onDestroyView"); } @Override public void onDestroy() { super.onDestroy(); Log.d("FRAGMENT LC", "Fragment_evDetail_Info_Where --> onDestroy"); } @Override public void onDetach() { super.onDetach(); Log.d("FRAGMENT LC", "Fragment_evDetail_Info_Where --> onDetach"); } @Override public void onPrepareOptionsMenu(Menu menu) { Log.i("FRAGMENT LC", "start on Prepare Options Menu EVENT LISTING frag: " + menu.toString()); menu.clear(); // getActivity().getMenuInflater().inflate(R.menu.event_detail_menu, // menu); /* * if (category == null) { category = (getArguments() != null) ? * getArguments().getString(SearchFragment.ARG_CATEGORY) : null; } */ super.onPrepareOptionsMenu(menu); } private class UpdateEventProcessor extends AbstractAsyncTaskProcessor<ExplorerObject, Boolean> { public UpdateEventProcessor(Activity activity) { super(activity); } @Override public Boolean performAction(ExplorerObject... params) throws SecurityException, Exception { // to be enabled when the connection with the server is ok return DTHelper.saveEvent(params[0]); // store the modified event // int index = Utils.appEvents.indexOf(params[0]); // Utils.appEvents.set(index, params[0]); // ExplorerObject mNewEvent = Utils.appEvents.get(index); // return true; } @Override public void handleResult(Boolean result) { if (getActivity() != null) { getActivity().getSupportFragmentManager().popBackStack(); if (result) { Toast.makeText(getActivity(), R.string.event_create_success, Toast.LENGTH_SHORT).show(); } else { Toast.makeText(getActivity(), R.string.update_success, Toast.LENGTH_SHORT).show(); } } } } }<file_sep>/******************************************************************************* * Copyright 2012-2013 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package eu.iescities.pilot.rovereto.roveretoexplorer.custom; import java.util.ArrayList; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Set; import android.util.Log; import eu.iescities.pilot.rovereto.roveretoexplorer.R; public class CategoryHelper { public static final String CAT_CULTURA = "Cultura"; public static final String CAT_SOCIALE = "Sociale"; public static final String CAT_SPORT = "Sport"; private final static String TAG = "CategoryHelper"; public static final String EVENT_NONCATEGORIZED = "Other event"; public static final String CATEGORY_TYPE_EVENTS = "events"; public static final String CATEGORY_TODAY = "Today"; public static final String CATEGORY_MY = "My"; public static CategoryDescriptor EVENTS_TODAY = new CategoryDescriptor(R.drawable.ic_altri_eventi, R.drawable.ic_altri_eventi_map, CATEGORY_TODAY, R.string.categories_event_today); public static CategoryDescriptor EVENTS_MY = new CategoryDescriptor(R.drawable.ic_altri_eventi, R.drawable.ic_altri_eventi_map, CATEGORY_MY, R.string.categories_event_my); public static CategoryDescriptor[] EVENT_CATEGORIES = new CategoryDescriptor[] { /* 1 */new CategoryDescriptor(R.drawable.ic_cultura_map, R.drawable.ic_cultura, CAT_CULTURA, R.string.categories_event_cultura), /* 2 */new CategoryDescriptor(R.drawable.ic_sport_map, R.drawable.ic_sport, CAT_SPORT, R.string.categories_event_sport), /* 3 */new CategoryDescriptor(R.drawable.ic_svago_map, R.drawable.ic_person, CAT_SOCIALE, R.string.categories_event_social), /* 4 */new CategoryDescriptor(R.drawable.ic_altri_eventi_map, R.drawable.ic_altri_eventi, EVENT_NONCATEGORIZED, R.string.categories_event_altri_eventi), }; private static Map<String, String> categoryMapping = new HashMap<String, String>(); private static Map<String, CategoryDescriptor> descriptorMap = new LinkedHashMap<String, CategoryHelper.CategoryDescriptor>(); static { for (CategoryDescriptor event : EVENT_CATEGORIES) { descriptorMap.put(event.category, event); } descriptorMap.put("Ambiente", EVENT_CATEGORIES[3]); descriptorMap.put("NaturaMenteVino", EVENT_CATEGORIES[3]); descriptorMap.put("Biblioteca", EVENT_CATEGORIES[3]); descriptorMap.put("Urban Center", EVENT_CATEGORIES[3]); for (String s : descriptorMap.keySet()) { categoryMapping.put(s, s); } categoryMapping.put("Ambiente", EVENT_NONCATEGORIZED); categoryMapping.put("NaturaMenteVino", EVENT_NONCATEGORIZED); categoryMapping.put("Biblioteca", EVENT_NONCATEGORIZED); categoryMapping.put("Urban Center", EVENT_NONCATEGORIZED); } public static String[] getAllCategories(Set<String> set) { List<String> result = new ArrayList<String>(); for (String key : categoryMapping.keySet()) { if (set.contains(categoryMapping.get(key))) { if (key.equals(EVENT_NONCATEGORIZED)) { result.add(null); } result.add(key); // set.remove(categoryMapping.get(key)); } } return result.toArray(new String[result.size()]); } public static String getMainCategory(String category) { return categoryMapping.get(category); } public static int getMapIconByType(String type) { if (categoryMapping.containsKey(type)) return descriptorMap.get(categoryMapping.get(type)).map_icon; return R.drawable.ic_altri_eventi_map; } public static int getIconByType(String type) { if (categoryMapping.containsKey(type)) return descriptorMap.get(categoryMapping.get(type)).thumbnail; return R.drawable.ic_altri_eventi; } public static class CategoryDescriptor { public int map_icon; public int thumbnail; public String category; public int description; public CategoryDescriptor(int map_icon, int thumbnail, String category, int description) { super(); this.map_icon = map_icon; this.thumbnail = thumbnail; this.category = category; this.description = description; } } public static CategoryDescriptor[] getEventCategoryDescriptors() { return EVENT_CATEGORIES; } public static String[] getEventCategories() { String[] res = new String[EVENT_CATEGORIES.length]; for (int i = 0; i < EVENT_CATEGORIES.length; i++) { res[i] = EVENT_CATEGORIES[i].category; } Log.i("MENU", "EVENT CATEGORIES: " + res.toString() + "\n--- lenght: " + res.length); return res; } public static String[] getEventCategoriesForMapFilters() { String[] res = new String[EVENT_CATEGORIES.length + 2]; res[0] = EVENTS_MY.category; res[1] = EVENTS_TODAY.category; for (int i = 2; i < EVENT_CATEGORIES.length + 2; i++) { res[i] = EVENT_CATEGORIES[i - 2].category; } Log.i("MENU", "EVENT CATEGORIES: " + res.toString() + "\n--- lenght: " + res.length); return res; } public static CategoryDescriptor[] getEventCategoryDescriptorsFiltered() { return DTParamsHelper.getInstance().getFilteredArrayByParams(EVENT_CATEGORIES, CATEGORY_TYPE_EVENTS); } public static CategoryDescriptor getCategoryDescriptorByCategoryFiltered(String type, String cat) { if (descriptorMap.containsKey(cat)) return descriptorMap.get(cat); return descriptorMap.get(EVENT_NONCATEGORIZED); } } <file_sep>package eu.iescities.pilot.rovereto.roveretoexplorer.fragments.event.info; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import android.app.Activity; import android.content.Context; import android.graphics.drawable.Drawable; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentTransaction; import android.text.Spannable; import android.text.SpannableString; import android.text.Spanned; import android.text.method.LinkMovementMethod; import android.text.style.ClickableSpan; import android.text.style.ImageSpan; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ExpandableListView; import android.widget.ExpandableListView.OnChildClickListener; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; import eu.iescities.pilot.rovereto.roveretoexplorer.R; import eu.iescities.pilot.rovereto.roveretoexplorer.RoveretoExplorerApplication; import eu.iescities.pilot.rovereto.roveretoexplorer.custom.Utils; import eu.iescities.pilot.rovereto.roveretoexplorer.custom.data.Address; import eu.iescities.pilot.rovereto.roveretoexplorer.custom.data.DTHelper; import eu.iescities.pilot.rovereto.roveretoexplorer.custom.data.model.ExplorerObject; public class Fragment_EvDetail_Info extends Fragment { protected Context context; // For the expandable list view List<String> attributeGroupList; // private List<LocalExplorerObject> listEvents = new // ArrayList<LocalExplorerObject>(); Map<String, List<String>> eventAttributeCollection; ExpandableListView expListView; protected ExplorerObject mEvent = null; private EventDetailInfoAdapter eventDetailInfoAdapter; View header; public static final String ARG_INDEX = "index_adapter"; private Integer indexAdapter; protected String mEventId; private String mEventImageUrl; // Initialize variables protected int ParentClickStatus = -1; protected int childClickStatus = -1; protected ArrayList<EventInfoParent> parents; protected List<Integer> groupImages; // private HashMap<Integer, List<Integer>> childImages; protected HashMap<Integer, List<Integer>> childType2Images; protected HashMap<Integer, Integer> childType1Images; Activity infoActivity = null; public static Fragment_EvDetail_Info newInstance(String event_id) { Fragment_EvDetail_Info f = new Fragment_EvDetail_Info(); Bundle b = new Bundle(); b.putString(Utils.ARG_EVENT_ID, event_id); f.setArguments(b); return f; } public static Fragment_EvDetail_Info newInstance(String event_id, String event_img_url) { Fragment_EvDetail_Info f = new Fragment_EvDetail_Info(); Bundle b = new Bundle(); b.putString(Utils.ARG_EVENT_ID, event_id); b.putString(Utils.ARG_EVENT_IMAGE_URL, event_img_url); f.setArguments(b); return f; } @Override public void onAttach(Activity activity) { super.onAttach(activity); Log.d("FRAGMENT LC", "Fragment_evDetail_Info --> onAttach: " + activity.toString()); infoActivity = activity; } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Log.d("FRAGMENT LC", "Fragment_evDetail_Info --> onCreate"); this.context = this.getActivity(); if (savedInstanceState == null) { Log.d("SCROLLTABS", "onCreate FIRST TIME"); if (getArguments() != null) { mEventId = getArguments().getString(Utils.ARG_EVENT_ID); } } else { Log.d("SCROLLTABS", "onCreate SUBSEQUENT TIME"); mEventId = savedInstanceState.getString(Utils.ARG_EVENT_ID); } Log.d("IMAGES", "Fragment_evDetail_Info --> image url:" + mEventImageUrl + "!"); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { super.onCreateView(inflater, container, savedInstanceState); Log.d("FRAGMENT LC", "Fragment_evDetail_Info --> onCreateView"); return inflater.inflate(R.layout.frag_ev_detail_info_list, container, false); } @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); Log.d("FRAGMENT LC", "Fragment_evDetail_Info --> onActivityCreated"); } // private void editField(String field_type) { // // Log.d("FRAGMENT LC", "Fragment_evDetail_Info --> INFO ACTIVITY: " + infoActivity.toString()); // Log.i("CONTACTS", "Fragment_EvDetail_Info --> event selected ID: " + mEventId + "!!"); // // String frag_description = "event_details_info_edit_" + field_type; // Bundle args = new Bundle(); // args.putString(Utils.ARG_EVENT_ID, mEventId); // args.putString(Utils.ARG_EVENT_FIELD_TYPE, field_type); // // Fragment edit_fragment = new Fragment_EvDetail_Info_What(); // // // FragmentTransaction transaction = // // getChildFragmentManager().beginTransaction(); // // if (edit_fragment != null) { // // edit_fragment.setArguments(args); // // transaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE); // // // fragmentTransaction.detach(this); // // //transaction.replace(R.id.content_frame, edit_fragment, // // frag_description); // // transaction.add(edit_fragment, frag_description); // // //transaction.addToBackStack(edit_fragment.getTag()); // // transaction.commit(); // // // reset event and event id // // mEvent = null; // // mEventId = null; // // } // // FragmentTransaction fragmentTransaction = getActivity().getSupportFragmentManager().beginTransaction(); // if (edit_fragment != null) { // // reset event and event id // mEvent = null; // mEventId = null; // edit_fragment.setArguments(args); // fragmentTransaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE); // // fragmentTransaction.detach(this); // fragmentTransaction.replace(R.id.content_frame, edit_fragment, frag_description); // fragmentTransaction.addToBackStack(getTag()); // fragmentTransaction.commit(); // // } // // } @Override public void onStart() { super.onStart(); Log.d("FRAGMENT LC", "Fragment_evDetail_Info --> onStart"); mEvent = getEvent(); if (mEvent != null) mEventImageUrl = mEvent.getImage(); // set expandable list view setExpandableListView(); // display the event title TextView titleTextView = (TextView) getActivity().findViewById(R.id.event_info_placeholder_title); titleTextView.setText(mEvent.getTitle()); //add the edit icon besides the text // String text = mEvent.getTitle() + " "; // SpannableString ss = new SpannableString(text); // Drawable d = getResources().getDrawable(R.drawable.ic_action_edit); // d.setBounds(0, 0, 35, 35); // ImageSpan span = new ImageSpan(d, ImageSpan.ALIGN_BASELINE); // int start = text.length() - 1; // ss.setSpan(span, start, start + 1, Spannable.SPAN_INCLUSIVE_EXCLUSIVE); // ss.setSpan(new android.text.style.StyleSpan(android.graphics.Typeface.BOLD), start, start + 1, // Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); // ss.setSpan(new ClickableSpan() { // @Override // public void onClick(View v) { // Log.d("main", "link clicked"); // // Toast.makeText(context, "modify event title", // // Toast.LENGTH_SHORT).show(); // editField("title"); // } // }, start, start + 1, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); // titleTextView.setText(ss); // titleTextView.setMovementMethod(LinkMovementMethod.getInstance()); // display the event image ImageView imgView = (ImageView) getActivity().findViewById(R.id.event_placeholder_photo); if ((mEventImageUrl != null) && (!mEventImageUrl.matches(""))) { RoveretoExplorerApplication.imageLoader.displayImage(mEventImageUrl, imgView); } // display the event category plus the "promoted by" attribute TextView categoryTextView = (TextView) getActivity().findViewById(R.id.event_placeholder_category); String category = mEvent.categoryString(getActivity()); if (mEvent.getOrigin() != null && !mEvent.getOrigin().matches("")) { String origin = mEvent.getOrigin().substring(0, 1).toLowerCase() + mEvent.getOrigin().substring(1); String text = getResources().getString(R.string.event_category, category, Utils.removeWords(Arrays.asList(Utils.stopWordsForOrigin), origin)); categoryTextView.setText(text); //add the edit icon besides the text // text += " "; // ss = new SpannableString(text); // start = text.length() - 1; // ss.setSpan(span, start, start + 1, Spannable.SPAN_INCLUSIVE_EXCLUSIVE); // ss.setSpan(new ClickableSpan() { // @Override // public void onClick(View v) { // Log.d("main", "link clicked"); // // Toast.makeText(context, "modify promoted by", // // Toast.LENGTH_SHORT).show(); // editField("origin"); // } // }, start, start + 1, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); // categoryTextView.setText(ss); // categoryTextView.setMovementMethod(LinkMovementMethod.getInstance()); } else categoryTextView.setText("Evento " + category + "."); } @Override public void onResume() { super.onResume(); Log.d("FRAGMENT LC", "Fragment_evDetail_Info --> onResume"); } @Override public void onPause() { super.onPause(); Log.d("FRAGMENT LC", "Fragment_evDetail_Info --> onPause"); } @Override public void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); Log.d("FRAGMENT LC", "Fragment_evDetail_Info --> onSaveInstanceState"); outState.putString(Utils.ARG_EVENT_ID, mEventId); } @Override public void onStop() { super.onStop(); Log.d("FRAGMENT LC", "Fragment_evDetail_Info --> onStop"); } @Override public void onDestroyView() { super.onDestroyView(); Log.d("FRAGMENT LC", "Fragment_evDetail_Info --> onDestroyView"); } @Override public void onDestroy() { super.onDestroy(); Log.d("FRAGMENT LC", "Fragment_evDetail_Info --> onDestroy"); } @Override public void onDetach() { super.onDetach(); Log.d("FRAGMENT LC", "Fragment_evDetail_Info --> onDetach"); } private void setExpandableListView() { Log.d("FRAGMENT LC", "Fragment_evDetail_Info --> setExpandableListView"); // Creating static data in arraylist ArrayList<EventInfoParent> eventInfoList = getEventDetailData(mEvent); setGroupImages(); // attributeGroupList = createAttributeGroupList(); // //eventAttributeCollection = // createFakeEventDetailCollection(attributeGroupList); // eventAttributeCollection = // getEventDetailCollection(attributeGroupList, mEvent); expListView = (ExpandableListView) getActivity().findViewById(R.id.event_details_info); expListView.setChildDivider(null); expListView.setChildDivider(getResources().getDrawable(R.color.transparent)); // header part header = getActivity().getLayoutInflater().inflate(R.layout.frag_ev_detail_info_header, null); // adding header to the list if (expListView.getHeaderViewsCount() == 0) { expListView.addHeaderView(header); expListView.setHeaderDividersEnabled(true); } if (getArguments() != null) { // Restore last state for checked position. mEventId = getArguments().getString(Utils.ARG_EVENT_ID); indexAdapter = getArguments().getInt(ARG_INDEX); } /* create the adapter is it is the first time you load */ // Adding ArrayList data to ExpandableListView values parents = eventInfoList; if (eventDetailInfoAdapter == null) { eventDetailInfoAdapter = new EventDetailInfoAdapter(Fragment_EvDetail_Info.this); } expListView.invalidateViews(); expListView.setAdapter(eventDetailInfoAdapter); eventDetailInfoAdapter.notifyDataSetChanged(); expListView.expandGroup(0); expListView.expandGroup(1); //this is not useful now expListView.setOnChildClickListener(new OnChildClickListener() { @Override public boolean onChildClick(ExpandableListView parent, View v, int groupPosition, int childPosition, long id) { // if(_lastColored != null) // { // _lastColored.setBackgroundColor(Color.WHITE); // _lastColored.invalidate(); // } // _lastColored = v; // // v.setBackgroundColor(Color.BLUE); Log.i("GROUPVIEW", "parent == " + groupPosition + "= child : ==" + childPosition); if (childClickStatus != childPosition) { childClickStatus = childPosition; // Toast.makeText(context, "Parent :" + groupPosition + // " Child :" + childPosition, Toast.LENGTH_LONG).show(); } int iCount; int iIdx; EventInfoChild childItem; EventDetailInfoAdapter adapter = (EventDetailInfoAdapter) parent.getExpandableListAdapter(); iCount = adapter.getChildrenCount(groupPosition); for (iIdx = 0; iIdx < iCount; ++iIdx) { childItem = (EventInfoChild) adapter.getChild(groupPosition, iIdx); if (childItem != null) { Log.i("GROUPVIEW", "child item not null"); if (iIdx == childPosition) { // Here you would toggle checked state in the data // for this item } else { // Here you would clear checked state in the data // for this item } } } parent.invalidateViews(); // Update the list view return false; } }); } private void setGroupImages() { groupImages = new ArrayList<Integer>(); groupImages.add(R.drawable.ic_action_edit_white); groupImages.add(R.drawable.ic_action_edit_white); groupImages.add(R.drawable.ic_action_edit_white); groupImages.add(R.drawable.ic_action_edit_white); } protected void resetEvent() { mEvent = null; mEventId = null; } /** * here should come your data service implementation * * @return */ private ArrayList<EventInfoParent> getEventDetailData(ExplorerObject event) { // Creating ArrayList of type parent class to store parent class objects ArrayList<EventInfoParent> list = new ArrayList<EventInfoParent>(); for (int i = 1; i < 5; i++) { // Create parent class object EventInfoParent parent = new EventInfoParent(); if (event.getImage() != null) { Log.i("EVENT", "Fragment_EvDetail_Info --> image: " + event.getImage() + "!!"); } // // // if (event.getCategory() != null) { // Log.i("EVENT", "Fragment_EvDetail_Info --> Category: " + // event.getCategory() + "!!"); // } // // if (event.getOrigin() != null) { // Log.i("EVENT", "Fragment_EvDetail_Info --> Origin: " + // event.getOrigin() + "!!"); // } // // if (event.getLocation() != null) { // Log.i("EVENT", "Fragment_EvDetail_Info --> Location: " + // event.getLocation() + "!!"); // } if (event.getCommunityData().getTags() != null) { Log.i("EVENT", "Fragment_EvDetail_Info --> TAGS: " + event.getCommunityData().getTags() + "!!"); } else Log.i("EVENT", "Fragment_EvDetail_Info --> TAGS NULL!!"); // Set values in parent class object if (i == 1) { // field DOVE e QUANDO parent.setName("" + i); parent.setText1("Dove e quando"); parent.setChildren(new ArrayList<EventInfoChild>()); if (event.getWhenWhere() != null) { Log.i("EVENT", "Fragment_EvDetail_Info --> WhenWhere: " + event.getWhenWhere() + "!!"); EventInfoChild child = new EventInfoChild(); child.setName("whenwhere"); child.setText(event.getWhenWhere()); child.setType(0); parent.getChildren().add(child); } Address address = event.getAddress(); if (address != null) { String place = (address.getLuogo() != null) ? (String) address.getLuogo() : null; String street = (address.getVia() != null) ? (String) address.getVia() : null; String city = (address.getCitta() != null) ? (String) address.getCitta() : null; String addressStr = ""; if ((place != null) && (!place.matches(""))) addressStr = addressStr + place; if ((street != null) && (!street.matches(""))) addressStr = addressStr + ", " + street; if ((city != null) && (!city.matches(""))) addressStr = addressStr + ", " + city; //to be enabled again when on the server side there will be distinction between street and city // else // addressStr = addressStr + context.getString(R.string.city_hint); if (addressStr.startsWith(",")) addressStr = addressStr.substring(1); if (addressStr.length()==0) addressStr = context.getString(R.string.city_hint); // Create Child class object EventInfoChild child = new EventInfoChild(); child.setName("address"); //child.setText(getResources().getString(R.string.address) + ": " + addressStr); child.setText(addressStr); child.setType(0); child.setLeftIconId(R.drawable.ic_action_place); parent.getChildren().add(child); } if ((event.getFromTime() != null) && (event.getFromTime() != 0)) { String[] fromDateTime = Utils.getDateTimeString(this.context, event.getFromTime(), Utils.DATETIME_FORMAT, false, true); EventInfoChild child = new EventInfoChild(); child.setName(getResources().getString(R.string.start_date)); if (!fromDateTime[1].matches("")) { child.setText(getResources().getString(R.string.date_with_time,fromDateTime[0],fromDateTime[1])); } else child.setText(fromDateTime[0]); child.setType(0); child.setLeftIconId(R.drawable.ic_start); parent.getChildren().add(child); } if ((event.getToTime() != null) && (event.getToTime() != 0)) { String[] toDateTime = Utils.getDateTimeString(this.context, event.getToTime(), Utils.DATETIME_FORMAT, false, true); EventInfoChild child = new EventInfoChild(); child.setName(getResources().getString(R.string.end_date)); if (!toDateTime[1].matches("")) { child.setText(getResources().getString(R.string.date_with_time,toDateTime[0],toDateTime[1])); } else child.setText(toDateTime[0]); Log.i("EVENT", "Fragment_EvDetail_Info --> toTime: " + child.getText() + "!!"); child.setType(0); child.setLeftIconId(R.drawable.ic_end); parent.getChildren().add(child); // compute duration or get in from the Explorer Object when // there will be such info!!! // String duration = null; // if (duration != null) { // child = new EventInfoChild(); // child.setName(getResources().getString(R.string.duration)); // child.setText("Durata: " + duration); // child.setType(0); // parent.getChildren().add(child); // } } } else if (i == 2) { // field COSA parent.setName("" + i); parent.setText1("Cosa"); parent.setChildren(new ArrayList<EventInfoChild>()); if (event.getDescription() != null) { Log.i("EVENT", "Fragment_EvDetail_Info --> description: " + event.getDescription() + "!!"); String desc = event.getDescription(); EventInfoChild child = new EventInfoChild(); child.setName("Description"); child.setText(desc); child.setType(0); parent.getChildren().add(child); } } else if (i == 3) { // field CONTATTI parent.setName("" + i); parent.setText1("Contatti"); parent.setChildren(new ArrayList<EventInfoChild>()); // String[] telList = null; // set the Phone item of type 1 EventInfoChild telChildLabel = new EventInfoChild(); telChildLabel.setName("Phones"); telChildLabel.setText("Telefono"); telChildLabel.setType(1); telChildLabel.setTextInBold(true); telChildLabel.setLeftIconId(R.drawable.ic_action_phone); // to be added again when it will be possible to add more // numbers // int[] rightIconIds = new int[]{R.drawable.ic_action_new}; // telChildLabel.setRightIconIds(rightIconIds); parent.getChildren().add(telChildLabel); // set the list of phone numbers List<String> telephones = event.getPhoneEmailContacts(Utils.PHONE_CONTACT_TYPE); if (telephones!=null){ telChildLabel.setDividerHeight(0); for (String tel : telephones) { if (!tel.matches("")) { EventInfoChild child1 = new EventInfoChild(); child1.setName("tel"); child1.setText(tel); child1.setType(0); // to be added when it will be possible to // cancel/edit the single item // int[] rightIconIds1 = new // int[]{R.drawable.ic_action_edit, // R.drawable.ic_action_cancel, // R.drawable.ic_action_call}; int[] rightIconIds1 = new int[] { R.drawable.ic_action_call }; child1.setRightIconIds(rightIconIds1); child1.setDividerHeight(0); if (tel==telephones.get(telephones.size()-1)) child1.setDividerHeight(1); parent.getChildren().add(child1); } } } // set the Email item of type 1 EventInfoChild emailChildLabel = new EventInfoChild(); emailChildLabel.setName("Emails"); emailChildLabel.setText("Email"); emailChildLabel.setType(1); emailChildLabel.setTextInBold(true); emailChildLabel.setLeftIconId(R.drawable.ic_action_email); // to be added again when it will be possible to add more emails // int[] rightIconIdsEmail = new // int[]{R.drawable.ic_action_new_email}; // emailChildLabel.setRightIconIds(rightIconIdsEmail); parent.getChildren().add(emailChildLabel); List<String> emails = event.getPhoneEmailContacts(Utils.EMAIL_CONTACT_TYPE); if (emails != null) { emailChildLabel.setDividerHeight(0); for (String email : emails) { if (!email.matches("")) { EventInfoChild child = new EventInfoChild(); child.setName("email"); child.setText(email); child.setType(0); // to be added when it will be possible to // cancel/edit the single item // int[] rightIconIds2 = new // int[]{R.drawable.ic_action_edit, // R.drawable.ic_action_cancel, // R.drawable.ic_action_email}; int[] rightIconIds2 = new int[] { R.drawable.ic_compose_email }; child.setRightIconIds(rightIconIds2); child.setDividerHeight(0); if (email==emails.get(emails.size()-1)) child.setDividerHeight(1); parent.getChildren().add(child); } } } // set the Web Site item of type 0 EventInfoChild siteChildLabel = new EventInfoChild(); siteChildLabel.setName("Website "); if (event.getWebsiteUrl() != null) { siteChildLabel.setText(event.getWebsiteUrl()); } else siteChildLabel.setText("Web Site"); siteChildLabel.setType(0); siteChildLabel.setTextInBold(true); siteChildLabel.setLeftIconId(R.drawable.ic_action_web_site); Log.i("EVENT", "Fragment_EvDetail_Info --> website: " + siteChildLabel.getText() + "!!"); parent.getChildren().add(siteChildLabel); // set Facebook item of type 0 EventInfoChild fbChildLabel = new EventInfoChild(); fbChildLabel.setName("Facebook "); if (event.getFacebookUrl() != null) { // fbChildLabel.setText("<a href=\"" + // event.getFacebookUrl() + "\">Facebook</a>"); fbChildLabel.setText(event.getFacebookUrl()); } else fbChildLabel.setText("Facebook"); fbChildLabel.setType(0); fbChildLabel.setTextInBold(true); fbChildLabel.setLeftIconId(R.drawable.ic_facebook); Log.i("EVENT", "Fragment_EvDetail_Info --> facebook: " + fbChildLabel.getText() + "!!"); parent.getChildren().add(fbChildLabel); // set Twitter item of type 0 EventInfoChild twitterChildLabel = new EventInfoChild(); twitterChildLabel.setName("Twitter "); if (event.getTwitterUrl() != null) { // twitterChildLabel.setText("<a href=\"" + // event.getTwitterUrl() + "\">Twitter</a>"); twitterChildLabel.setText(event.getTwitterUrl()); } else twitterChildLabel.setText("Twitter "); twitterChildLabel.setType(0); twitterChildLabel.setTextInBold(true); twitterChildLabel.setLeftIconId(R.drawable.ic_twitter); Log.i("EVENT", "Fragment_EvDetail_Info --> twitter: " + twitterChildLabel.getText() + "!!"); parent.getChildren().add(twitterChildLabel); } else if (i == 4) { // field TAGS parent.setName("" + i); parent.setText1("Tags"); parent.setChildren(new ArrayList<EventInfoChild>()); List<String> tags = null; if (event.getCommunityData().getTags() != null) { tags = event.getCommunityData().getTags(); for (String tag : tags) { EventInfoChild child = new EventInfoChild(); child.setName("tag"); child.setText(tag); child.setType(0); child.setLeftIconId(R.drawable.ic_action_labels_dark); parent.getChildren().add(child); } } } //delete the divider line for the last item of a group if (parent.getChildren().size()!=0){ EventInfoChild lastChild = parent.getChildren().get(parent.getChildren().size()-1); lastChild.setDividerHeight(0); parent.getChildren().remove(parent.getChildren().size()-1); parent.getChildren().add(lastChild); } // Adding Parent class object to ArrayList list.add(parent); } return list; } /** * Get the ExpandableListAdapter associated with this activity's * ExpandableListView. */ public EventDetailInfoAdapter getExpandableListAdapter() { return eventDetailInfoAdapter; } public void setListAdapter(EventDetailInfoAdapter adapter) { eventDetailInfoAdapter = adapter; } private ExplorerObject getEvent() { if (mEventId == null) { mEventId = getArguments().getString(Utils.ARG_EVENT_ID); } // if (mEvent == null) { mEvent = DTHelper.findEventById(mEventId); // } return mEvent; } } <file_sep>package eu.iescities.pilot.rovereto.roveretoexplorer.fragments.event.multimedia; import android.app.Activity; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.ImageView; import android.widget.TextView; import eu.iescities.pilot.rovereto.roveretoexplorer.R; import eu.iescities.pilot.rovereto.roveretoexplorer.RoveretoExplorerApplication; import eu.iescities.pilot.rovereto.roveretoexplorer.custom.data.model.Multimedia; public class EventDetailMultimediaAdapter extends ArrayAdapter<Multimedia> { private Context mContext; private int layoutResourceId; private String mEventId; public EventDetailMultimediaAdapter(Context mContext, int layoutResourceId, String mEventId) { super(mContext, layoutResourceId); this.mContext = mContext; this.layoutResourceId = layoutResourceId; this.mEventId = mEventId; } @Override public View getView(int position, View convertView, ViewGroup parent) { View row = convertView; MultimediaHolder holder = null; final Multimedia multimedia = getItem(position); if (row == null) { LayoutInflater inflater = ((Activity) mContext).getLayoutInflater(); row = inflater.inflate(layoutResourceId, parent, false); holder = new MultimediaHolder(); holder.multimediaThumbnail = (ImageView) row.findViewById(R.id.multimediaThumbnail); holder.multimediaName = (TextView) row.findViewById(R.id.multimediaName); row.setTag(holder); } else { holder = (MultimediaHolder) row.getTag(); } RoveretoExplorerApplication.imageLoader.displayImage(multimedia.getThumbnailUrl(), holder.multimediaThumbnail); holder.multimediaName.setText(multimedia.getName()); return row; } public static class MultimediaHolder { ImageView multimediaThumbnail; TextView multimediaName; } // private class UpdateEventProcessor extends // AbstractAsyncTaskProcessor<ExplorerObject, Boolean> { // // private ToKnow toKnow; // // public UpdateEventProcessor(Activity activity, ToKnow toKnow) { // super(activity); // this.toKnow = toKnow; // } // // @Override // public Boolean performAction(ExplorerObject... params) throws // SecurityException, Exception { // // to be enabled when the connection with the server is ok // return DTHelper.saveEvent(params[0]); // } // // @Override // public void handleResult(Boolean result) { // if (getContext() != null) { // if (result) { // Toast.makeText(getContext(), R.string.event_create_success, // Toast.LENGTH_SHORT).show(); // } else { // Toast.makeText(getContext(), R.string.update_success, // Toast.LENGTH_SHORT).show(); // } // remove(toKnow); // // getActivity().getSupportFragmentManager().popBackStack(); // } // } // } } <file_sep>/******************************************************************************* * Copyright 2012-2013 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package eu.iescities.pilot.rovereto.roveretoexplorer.fragments.event.info.edit; import java.net.MalformedURLException; import java.net.URL; import java.util.List; import java.util.Locale; import android.app.Activity; import android.content.Intent; import android.location.Address; import android.os.Bundle; import android.os.Vibrator; import android.support.v4.app.FragmentActivity; import android.support.v7.app.ActionBar; import android.support.v7.app.ActionBarActivity; import android.util.Log; import android.view.MenuItem; import android.widget.Toast; import com.google.android.gms.maps.CameraUpdateFactory; import com.google.android.gms.maps.GoogleMap; import com.google.android.gms.maps.GoogleMap.OnMapLongClickListener; import com.google.android.gms.maps.SupportMapFragment; import com.google.android.gms.maps.model.LatLng; import com.google.android.gms.maps.model.TileOverlayOptions; import com.google.android.gms.maps.model.TileProvider; import com.google.android.gms.maps.model.UrlTileProvider; import com.google.android.maps.GeoPoint; import eu.iescities.pilot.rovereto.roveretoexplorer.R; import eu.iescities.pilot.rovereto.roveretoexplorer.custom.AbstractAsyncTaskProcessor; import eu.iescities.pilot.rovereto.roveretoexplorer.custom.DTParamsHelper; import eu.iescities.pilot.rovereto.roveretoexplorer.custom.Utils; import eu.iescities.pilot.rovereto.roveretoexplorer.custom.data.DTHelper; import eu.trentorise.smartcampus.android.common.SCAsyncTask; import eu.trentorise.smartcampus.android.common.geo.OSMAddress; import eu.trentorise.smartcampus.android.common.geo.OSMGeocoder; import eu.trentorise.smartcampus.android.map.InfoDialog; import eu.trentorise.smartcampus.protocolcarrier.exceptions.SecurityException; public class AddressSelectActivity extends ActionBarActivity implements OnMapLongClickListener { private GoogleMap mMap = null; private String url = "https://vas.smartcampuslab.it"; private OSMAddress osmAddress = null; private String osmUrl = "http://otile1.mqcdn.com/tiles/1.0.0/osm/%d/%d/%d.jpg"; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.mapcontainer); // getActionBar().setDisplayShowTitleEnabled(false); getSupportActionBar().setDisplayHomeAsUpEnabled(true); if (getSupportActionBar().getNavigationMode() != ActionBar.NAVIGATION_MODE_STANDARD) { getSupportActionBar().setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD); } if (((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map)).getMap() != null) { mMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map)).getMap(); mMap.setOnMapLongClickListener(this); mMap.setMyLocationEnabled(true); setUpMap(); LatLng centerLatLng = null; if (DTParamsHelper.getCenterMap() != null) { centerLatLng = new LatLng(DTParamsHelper.getCenterMap().get(0), DTParamsHelper.getCenterMap().get(1)); } else if (DTHelper.getLocationHelper().getLocation() != null) { centerLatLng = new LatLng(DTHelper.getLocationHelper().getLocation().getLatitudeE6() / 1e6, DTHelper .getLocationHelper().getLocation().getLongitudeE6() / 1e6); } if (centerLatLng != null) { mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(centerLatLng, DTParamsHelper.getZoomLevelMap())); } else { mMap.moveCamera(CameraUpdateFactory.zoomTo(DTParamsHelper.getZoomLevelMap())); } Toast.makeText(this, R.string.address_select_toast, Toast.LENGTH_LONG).show(); } } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case android.R.id.home: finish(); return true; default: return super.onOptionsItemSelected(item); } } protected boolean isRouteDisplayed() { return false; } @Override public void onMapLongClick(LatLng point) { Vibrator vibrator = (Vibrator) getSystemService(VIBRATOR_SERVICE); vibrator.vibrate(100); // GeoPoint p = new GeoPoint((int) (point.latitude * 1e6), (int) // (point.longitude * 1e6)); GeoPoint p = new GeoPoint((int) (point.latitude * 1e6), (int) (point.longitude * 1e6)); // List<OSMAddress> addresses = new // SCGeocoder(getApplicationContext(),url).findAddressesAsync(p); // addresses = new // OSMGeocoder(getApplicationContext(),url).getFromLocation(point.latitude // , point.longitude, null); new SCAsyncTask<Void, Void, List<OSMAddress>>(this, new GetAddressProcessor((Activity) this, p)).execute(); } @Override public void finish() { //Prepare data intent Intent data = new Intent(); data.putExtra(Utils.ADDRESS, osmAddress); // Activity finished ok, return the data setResult(RESULT_OK, data); super.finish(); } private class GetAddressProcessor extends AbstractAsyncTaskProcessor<Void, List<OSMAddress>> { List<OSMAddress> addresses = null; private GeoPoint point; public GetAddressProcessor(Activity activity, GeoPoint p) { super(activity); this.point = p; } @Override public List<OSMAddress> performAction(Void... params) throws SecurityException, Exception { return addresses = new OSMGeocoder(getApplicationContext(), url).getFromLocation( point.getLatitudeE6() / 1e6, point.getLongitudeE6() / 1e6, null); } @Override public void handleResult(List<OSMAddress> result) { Address address = new Address(Locale.getDefault()); OSMAddress myAddress = new OSMAddress(); // get first wit street for (OSMAddress osmAddress : result) { Log.i("ADDRESS", "AddressSelectActivity --> osmAddress: " + osmAddress.toString()); if (osmAddress.getStreet() != null) { myAddress = osmAddress; break; } } //store the osm address so that it is returned as intent result osmAddress = myAddress; address.setAddressLine(0, myAddress.formattedAddress()); address.setCountryName(myAddress.country()); address.setLocality(myAddress.getCity().get("")); address.setLatitude(myAddress.getLocation()[0]); address.setLongitude(myAddress.getLocation()[1]); if (addresses != null && !addresses.isEmpty()) { new InfoDialog(AddressSelectActivity.this, address).show(getSupportFragmentManager(), "me"); } else { address.setLatitude(point.getLatitudeE6()); address.setLongitude(point.getLongitudeE6()); String addressLine = "LON " + Double.toString(address.getLongitude()) + ", LAT " + Double.toString(address.getLatitude()); address.setAddressLine(0, addressLine); new InfoDialog(AddressSelectActivity.this, address).show(getSupportFragmentManager(), "me"); } } } private void setUpMap() { mMap.setMapType(GoogleMap.MAP_TYPE_NONE); TileProvider tileProvider = new UrlTileProvider(256, 256) { @Override public URL getTileUrl(int x, int y, int z) { try { if (z>17) z=17; return new URL(String.format(osmUrl, z, x, y)); } catch (MalformedURLException e) { return null; } } }; mMap.addTileOverlay(new TileOverlayOptions().tileProvider(tileProvider)); } }
fc482b0696c873a7cf0cbb3502e88e17a75a4dd5
[ "Markdown", "Java" ]
21
Java
smartcommunitylab/smartcampus.vas.roveretoexplorer.android
0b19d254f63a2a38a98c6ef6326f4e7d44177486
57b7b2167e059a2527f3a00ee8528f862c9f2e80
refs/heads/main
<repo_name>HaMa05/QuanLyBanDay<file_sep>/Code/QLBanDay/QLBanDay/FormProduct/fAddProduct.cs using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace QLBanDay { public partial class fAddProduct : Form { common commomMethodFn = new common(); public fAddProduct() { InitializeComponent(); } private void fAddProduct_Load(object sender, EventArgs e) { this.FormBorderStyle = FormBorderStyle.None; } private void iconMininum_Click(object sender, EventArgs e) { commomMethodFn.Mininum_Click(this); } private void ionMaxinum_Click(object sender, EventArgs e) { commomMethodFn.Maxinum_Click(this); } private void iconExit_Click(object sender, EventArgs e) { commomMethodFn.Exit_Click(this); } private void panelAddProduct_MouseDown(object sender, MouseEventArgs e) { commomMethodFn.MouseDown(this); } } } <file_sep>/Code/QLBanDay/QLBanDay/FormProduct/fListProduct.cs using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace QLBanDay { public partial class fListProduct : Form { common commomMethodFn = new common(); public fListProduct() { InitializeComponent(); } private void fListProduct_Load(object sender, EventArgs e) { commomMethodFn.changeColordgv(dgvProduct); } private void btnAdd_Click(object sender, EventArgs e) { fAddProduct f = new fAddProduct(); f.ShowDialog(); } } } <file_sep>/Code/QLBanDay/QLBanDay/FormProduct/fcompany.cs using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace QLBanDay { public partial class fcompany : Form { common commomMethodFn = new common(); public fcompany() { InitializeComponent(); } private void fcompany_Load(object sender, EventArgs e) { commomMethodFn.changeColordgv(dgvCompany); } private void btnAdd_Click(object sender, EventArgs e) { fAddCompany f = new fAddCompany(); f.ShowDialog(); } } } <file_sep>/Code/QLBanDay/QLBanDay/FormProduct/fAddCompany.cs using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace QLBanDay { public partial class fAddCompany : Form { common commomMethodFn = new common(); public fAddCompany() { InitializeComponent(); } private void fAddCompany_Load(object sender, EventArgs e) { this.FormBorderStyle = FormBorderStyle.None; } private void iconMininum_Click(object sender, EventArgs e) { commomMethodFn.Mininum_Click(this); } private void ionMaxinum_Click(object sender, EventArgs e) { //commomMethodFn.Maxinum_Click(this); } private void iconExit_Click(object sender, EventArgs e) { commomMethodFn.Exit_Click(this); } private void panelFirstCompany_MouseDown(object sender, MouseEventArgs e) { commomMethodFn.MouseDown(this); } } }
0786e1dded46799e4f36a364a72e28ae9600af8c
[ "C#" ]
4
C#
HaMa05/QuanLyBanDay
cb52278f3105aeea71b8245c229bb31f5a2976fe
82baad1aa3c6811b8980faf309d1e74c539d17a8
refs/heads/master
<file_sep><?php $currentPage = basename($_SERVER['PHP_SELF']); ?> <!DOCTYPE html> <html lang="en"> <head> <?php require_once('header.html'); ?> </head> <body> <?php require_once('navbar.php'); ?> <main role="main"> <div class="container"> <h1 class="heading">Something went wrong</h1> <p>You will be redirected back to the main page in 5 seconds</p> <?php header( "refresh:5; url=index.php" ); ?></div> </main> <footer> <?php require_once('footer.html'); ?> </footer> </body> </html><file_sep><?php session_start(); function random_str() { $keyspace = '0123456789'; $pieces = []; $max = mb_strlen($keyspace, '8bit') - 1; for ($i = 0; $i < 8; ++$i) { $pieces []= $keyspace[random_int(0, $max)]; } return implode('', $pieces); } if(isset($_SESSION['token'])){ if(isset($_POST['token'])){ if($_POST['token'] == $_SESSION['token']){ $connection = mysqli_connect("localhost", "root", "", "alohacak_bookings"); if(!$connection){ require_once("error.php"); exit; } $booking_id = random_str(); $booking_date = date('Y-m-d G:i A'); $approved = 0; $stmt = mysqli_prepare($connection, "INSERT INTO bookings values (?,?,?,?,?,?,?,?,?,?,?)"); if(!$stmt){ require_once("error.php"); exit; } $full_name = trim($_POST['full_name']); $email = trim($_POST['email']); $contact_number = trim($_POST['contact_number']); $date_event = trim($_POST['date_event']); $time_event = trim($_POST['time_event']); $guests = trim($_POST['guests']); $venue = trim($_POST['venue']); $theme = trim($_POST['theme']); if(empty($full_name) || empty($email) || empty($contact_number) || empty($date_event) || empty($time_event) || ($guests < 0 && $guests > 1000) || empty($venue) || empty($theme)){ require_once("error.php"); exit; } $full_name = mysqli_real_escape_string($connection, filter_var($full_name, FILTER_SANITIZE_STRING)); $email = mysqli_real_escape_string($connection, filter_var($email, FILTER_SANITIZE_EMAIL)); $contact_number = mysqli_real_escape_string($connection, filter_var($contact_number, FILTER_SANITIZE_STRING)); $date_event = mysqli_real_escape_string($connection, filter_var($date_event, FILTER_SANITIZE_STRING)); $time_event = mysqli_real_escape_string($connection, filter_var($time_event, FILTER_SANITIZE_STRING)); $guests = mysqli_real_escape_string($connection, filter_var($guests, FILTER_SANITIZE_NUMBER_INT)); $venue = mysqli_real_escape_string($connection, filter_var($venue, FILTER_SANITIZE_STRING)); $theme = mysqli_real_escape_string($connection, filter_var($theme, FILTER_SANITIZE_STRING)); if(mysqli_stmt_bind_param($stmt, 'sssssssissi', $booking_id, $booking_date, $full_name, $email, $contact_number, $date_event, $time_event, $guests, $venue, $theme, $approved)){ if(mysqli_stmt_execute($stmt)){ require_once("booking-success.php"); mysqli_close($connection); unset($_SESSION['token']); exit; }else{ require_once("error.php"); mysqli_close($connection); unset($_SESSION['token']); exit; } }else{ require_once("error.php"); exit; } }else{ require_once("error.php"); exit; } }else{ require_once("error.php"); exit; } }else{ require_once("error.php"); exit; } ?><file_sep><?php $currentPage = basename($_SERVER['PHP_SELF']); ?> <!DOCTYPE html> <html lang="en"> <head> <?php require_once('header.html'); ?> <link rel="stylesheet" href="https://unpkg.com/leaflet@1.3.3/dist/leaflet.css" integrity="<KEY> crossorigin=""/> </head> <body> <?php require_once('navbar.php'); ?> <main role="main"> <div class="container"> <h1 class="heading">Set an appointment with us</h1> <div class="row"> <div class="col-lg-7 col-md-7"> <p>Contact us at: 808-451-9540</p> <p>Or via email: <EMAIL></p> </div> <div id="map" class="col-lg-5 col-md-5"> </div> </div> </div> </main> <footer> <?php require_once('footer.html'); ?> </footer> <script src="https://unpkg.com/leaflet@1.3.3/dist/leaflet.js" integrity="<KEY> crossorigin=""></script> <script> var mymap = L.map('map').setView([21.3816862, -158.0171266], 16); var marker = L.marker([21.3816862, -158.0171266]).addTo(mymap); L.tileLayer('https://api.tiles.mapbox.com/v4/{id}/{z}/{x}/{y}.png?access_token=<KEY>', { maxZoom: 25, attribution: 'Map data &copy; <a href="https://www.openstreetmap.org/">OpenStreetMap</a> contributors, ' + '<a href="https://creativecommons.org/licenses/by-sa/2.0/">CC-BY-SA</a>, ' + 'Imagery © <a href="https://www.mapbox.com/">Mapbox</a>', id: 'mapbox.streets'}).addTo(mymap); marker.bindPopup("<h6>We are located at:</h6>94-366 Pupupani St. Westgate Center (2nd floor) Waipahu, Hawaii 96797").openPopup(); </script> </body> </html><file_sep><?php $currentPage = basename($_SERVER['PHP_SELF']); ?> <!DOCTYPE html> <html lang="en"> <head> <?php require_once('header.html'); ?> <link href="../css/lightbox.min.css" rel="stylesheet"> </head> <body> <?php require_once('navbar.php'); ?> <main role="main"> <div class="container about-container"> <div class="row"> <div class="col-lg-7 col-md-7 col-sm-7 col-7"> <h1>Aloha!</h1> <p class="lead">Aloha Cake Art & Supplies LLC prides itself as a one-stop shop for all things party-related. We offer services such as customized cakes, cupcakes and all kinds of desserts that cater to all kinds of occassions, and cake decorating supplies.</p> <p>All desserts are baked and designed by <NAME> pictured on the right.</p> <p><b>Employer Identification Number:</b> 83-1474267</p> <p><b>Hawaii Tax I.D. Number:</b> GE-108-253-2864-01</p> <p>Aloha Cake Art & Supplies LLC is certified by <a href="https://www.statefoodsafety.com/">State Food Safety</a> and Hawaii's Department of Health Food Safety Program.</p> <a class="img-thumbnail thumbnail" href="../images/FHCT.jpg" data-lightbox="certs"> <img src="../images/FHCT.jpg"> </a> <a class="img-thumbnail thumbnail" href="../images/FSP.jpg" data-lightbox="certs"> <img src="../images/FSP.jpg"> </a> </div> <div class="col-lg-5 col-md-5 col-sm-5 col-5"> <img class="img-fluid featurette-img" src="../images/Portrait.jpg"> </div> </div> </div> </main> <footer> <?php require_once('footer.html'); ?> <script src="../js/lightbox.min.js"></script> </footer> </body> </html><file_sep><?php $currentPage = basename($_SERVER['PHP_SELF']); ?> <!DOCTYPE html> <html lang="en"> <head> <?php require_once('header.html'); ?> <link href="css/lightbox.min.css" rel="stylesheet"> </head> <body> <?php require_once('navbar.php'); ?> <main role="main"> <div class="container gallery-container"> <h1 class="heading">Our creations</h1> <div class="row"> <div class="col-6"> <p class="text-center">Birthdays</p> <a class="img-thumbnail gallery-thumbnail" href="images/bday-1.jpg" data-lightbox="bday"> <img src="images/bday-1.jpg"> </a> <a class="img-thumbnail gallery-thumbnail" href="images/bday-2.jpg" data-lightbox="bday" hidden></a> <a class="img-thumbnail gallery-thumbnail" href="images/bday-3.jpg" data-lightbox="bday" hidden></a> <a class="img-thumbnail gallery-thumbnail" href="images/bday-4.jpg" data-lightbox="bday" hidden></a> <a class="img-thumbnail gallery-thumbnail" href="images/bday-5.jpg" data-lightbox="bday" hidden></a> </div> <div class="col-6"> <p class="text-center">Weddings</p> <a class="img-thumbnail gallery-thumbnail" href="images/wedding-1.jpg" data-lightbox="wedding"> <img src="images/wedding-1.jpg"> </a> <a class="img-thumbnail gallery-thumbnail" href="images/wedding-2.jpg" data-lightbox="wedding" hidden></a> <a class="img-thumbnail gallery-thumbnail" href="images/wedding-3.jpg" data-lightbox="wedding" hidden></a> <a class="img-thumbnail gallery-thumbnail" href="images/wedding-4.jpg" data-lightbox="wedding" hidden></a> <a class="img-thumbnail gallery-thumbnail" href="images/wedding-5.jpg" data-lightbox="wedding" hidden></a> </div> </div> <div class="row"> <div class="col-6"> <p class="text-center">Baby Shower/Christenings</p> <a class="img-thumbnail gallery-thumbnail" href="images/babyshower-1.jpg" data-lightbox="babyshower"> <img src="images/babyshower-1.jpg"> </a> <a class="img-thumbnail gallery-thumbnail" href="images/babyshower-2.jpg" data-lightbox="babyshower" hidden></a> <a class="img-thumbnail gallery-thumbnail" href="images/babyshower-3.jpg" data-lightbox="babyshower" hidden></a> <a class="img-thumbnail gallery-thumbnail" href="images/babyshower-4.jpg" data-lightbox="babyshower" hidden></a> <a class="img-thumbnail gallery-thumbnail" href="images/babyshower-5.jpg" data-lightbox="babyshower" hidden></a> </div> <div class="col-6"> <p class="text-center">Carved Cakes</p> <a class="img-thumbnail gallery-thumbnail" href="images/carved-2.jpg" data-lightbox="carved"> <img src="images/carved-2.jpg"> </a> <a class="img-thumbnail gallery-thumbnail" href="images/carved-1.jpg" data-lightbox="carved" hidden></a> <a class="img-thumbnail gallery-thumbnail" href="images/carved-3.jpg" data-lightbox="carved" hidden></a> <a class="img-thumbnail gallery-thumbnail" href="images/carved-4.jpg" data-lightbox="carved" hidden></a> <a class="img-thumbnail gallery-thumbnail" href="images/carved-5.jpg" data-lightbox="carved" hidden></a> </div> </div> <div class="row"> <div class="col-12"> <p class="text-center">Military Cakes</p> <a class="img-thumbnail gallery-thumbnail" href="images/military-3.jpg" data-lightbox="military"> <img src="images/military-3.jpg"> </a> <a class="img-thumbnail gallery-thumbnail" href="images/military-2.jpg" data-lightbox="military" hidden></a> <a class="img-thumbnail gallery-thumbnail" href="images/military-1.jpg" data-lightbox="military" hidden></a> <a class="img-thumbnail gallery-thumbnail" href="images/military-4.jpg" data-lightbox="military" hidden></a> <a class="img-thumbnail gallery-thumbnail" href="images/military-5.jpg" data-lightbox="military" hidden></a> </div> </div> <p>For more pictures of our work, please visit our <a href="https://www.facebook.com/alohacakeartsupplies/" target="=_blank">Facebook</a> and <a href="https://www.instagram.com/aloha.cakeart.supplies/" target="_blank">Instagram</a> pages</p> </div> </main> <footer> <?php require_once('footer.html'); ?> <script src="js/lightbox.min.js"></script> </footer> </body> </html><file_sep><?php $currentPage = basename($_SERVER['PHP_SELF']); ?> <!DOCTYPE html> <html lang="en"> <head> <?php require_once('header.html'); ?> <link href="css/lightbox.min.css" rel="stylesheet"> </head> <body> <?php require_once('navbar.php'); ?> <main role="main"> <div class="container about-container"> <div class="row"> <div class="col-lg-7 col-md-7 col-sm-7 col-7"> <h1 class="heading">Aloha!</h1> <p>Aloha Cake Art & Supplies LLC prides itself as a one-stop shop for all things party-related. We offer services such as customized cakes, cupcakes and all kinds of desserts that cater to all kinds of occassions, and cake decorating supplies.</p> <p><b>Employer Identification Number:</b> 83-1474267</p> <p><b>Hawaii Tax I.D. Number:</b> GE-108-253-2864-01</p> <p>Aloha Cake Art & Supplies LLC is certified by <a href="https://www.statefoodsafety.com/">State Food Safety</a> and Hawaii's Department of Health Food Safety Program.</p> <a class="img-thumbnail thumbnail" href="images/FHCT.jpg" data-lightbox="certs"> <img src="images/FHCT.jpg"> </a> <a class="img-thumbnail thumbnail" href="images/FSP.jpg" data-lightbox="certs"> <img src="images/FSP.jpg"> </a> </div> <div class="col-lg-5 col-md-5 col-sm-5 col-5"> <img class="img-fluid featurette-img" src="images/Portrait.jpg"> <p>All desserts are baked and designed by <NAME> pictured</p> </div> </div> </div> </main> <footer> <?php require_once('footer.html'); ?> <script src="js/lightbox.min.js"></script> </footer> </body> </html><file_sep><?php $currentPage = basename($_SERVER['PHP_SELF']); ?> <!DOCTYPE html> <html lang="en"> <head> <?php require_once('header.html'); ?> <link href="../css/lightbox.min.css" rel="stylesheet"> </head> <body> <?php require_once('navbar.php'); ?> <main role="main"> <div class="container"> <h1>Our creations</h1> <div class="row"> <div class="col-6"> <p class="text-center">Birthday Cakes</p> <a class="img-thumbnail gallery-thumbnail" href="../images/bday-1.jpg" data-lightbox="bday"> <img src="../images/bday-1.jpg"> </a> <a class="img-thumbnail gallery-thumbnail" href="../images/bday-2.jpg" data-lightbox="bday" hidden></a> <a class="img-thumbnail gallery-thumbnail" href="../images/bday-3.jpg" data-lightbox="bday" hidden></a> <a class="img-thumbnail gallery-thumbnail" href="../images/bday-4.jpg" data-lightbox="bday" hidden></a> <a class="img-thumbnail gallery-thumbnail" href="../images/bday-5.jpg" data-lightbox="bday" hidden></a> </div> <div class="col-6"> <p class="text-center">Wedding Cakes</p> <a class="img-thumbnail gallery-thumbnail" href="../images/wedding-1.jpg" data-lightbox="wedding"> <img src="../images/wedding-1.jpg"> </a> <a class="img-thumbnail gallery-thumbnail" href="../images/wedding-2.jpg" data-lightbox="wedding" hidden></a> <a class="img-thumbnail gallery-thumbnail" href="../images/wedding-3.jpg" data-lightbox="wedding" hidden></a> <a class="img-thumbnail gallery-thumbnail" href="../images/wedding-4.jpg" data-lightbox="wedding" hidden></a> <a class="img-thumbnail gallery-thumbnail" href="../images/wedding-5.jpg" data-lightbox="wedding" hidden></a> </div> </div> <div class="row"> <div class="col-6"> <p class="text-center">Baby Shower/Christening Cakes</p> <a class="img-thumbnail gallery-thumbnail" href="../images/babyshower-1.jpg" data-lightbox="babyshower"> <img src="../images/babyshower-1.jpg"> </a> <a class="img-thumbnail gallery-thumbnail" href="../images/babyshower-2.jpg" data-lightbox="babyshower" hidden></a> <a class="img-thumbnail gallery-thumbnail" href="../images/babyshower-3.jpg" data-lightbox="babyshower" hidden></a> <a class="img-thumbnail gallery-thumbnail" href="../images/babyshower-4.jpg" data-lightbox="babyshower" hidden></a> <a class="img-thumbnail gallery-thumbnail" href="../images/babyshower-5.jpg" data-lightbox="babyshower" hidden></a> </div> <div class="col-6"> <p class="text-center">Carved Cakes</p> <a class="img-thumbnail gallery-thumbnail" href="../images/carved-2.jpg" data-lightbox="carved"> <img src="../images/carved-2.jpg"> </a> <a class="img-thumbnail gallery-thumbnail" href="../images/carved-1.jpg" data-lightbox="carved" hidden></a> <a class="img-thumbnail gallery-thumbnail" href="../images/carved-3.jpg" data-lightbox="carved" hidden></a> <a class="img-thumbnail gallery-thumbnail" href="../images/carved-4.jpg" data-lightbox="carved" hidden></a> <a class="img-thumbnail gallery-thumbnail" href="../images/carved-5.jpg" data-lightbox="carved" hidden></a> </div> </div> <div class="row"> <div class="col-12"> <p class="text-center">Military Cakes</p> <a class="img-thumbnail gallery-thumbnail" href="../images/military-3.jpg" data-lightbox="military"> <img src="../images/military-3.jpg"> </a> <a class="img-thumbnail gallery-thumbnail" href="../images/military-2.jpg" data-lightbox="military" hidden></a> <a class="img-thumbnail gallery-thumbnail" href="../images/military-1.jpg" data-lightbox="military" hidden></a> <a class="img-thumbnail gallery-thumbnail" href="../images/military-4.jpg" data-lightbox="military" hidden></a> <a class="img-thumbnail gallery-thumbnail" href="../images/military-5.jpg" data-lightbox="military" hidden></a> </div> </div> <span>For more pictures of our work, please visit our <a href="https://www.facebook.com/alohacakeartsupplies/" target="=_blank">Facebook</a> and <a href="https://www.instagram.com/aloha.cakeart.supplies/" target="_blank">Instagram</a> pages</span> </div> </main> <footer> <?php require_once('footer.html'); ?> <script src="../js/lightbox.min.js"></script> </footer> </body> </html><file_sep><?php session_start(); $_SESSION['token'] = hash('<PASSWORD>', (session_id() . time())); $currentPage = basename($_SERVER['PHP_SELF']); $connection = mysqli_connect("localhost", "root", "", "alohacak_bookings"); $result = mysqli_query($connection, "SELECT event_date FROM bookings where approved = 1"); if(!$result){ require_once("error.php"); exit; } $dates = array(); if($result->num_rows > 0){ while($row = $result->fetch_array(MYSQLI_NUM)){ array_push($dates, $row[0]); } } $js_dates = json_encode($dates); mysqli_close($connection); ?> <!DOCTYPE html> <html lang="en"> <head> <?php require_once('header.html'); ?> <link href="css/jquery-ui.css" rel="stylesheet"> <script> var booked_dates = <?php echo $js_dates ?>; </script> </head> <body> <?php require_once('navbar.php'); ?> <main role="main"> <div class="container"> <noscript> <h1>Please enable Javascript to use the booking feature</h1> </noscript> </div> <div class="container booking-container" style="display:none"> <h1 class="heading">Book your next event with us</h1> <span><i>Please fill up the form below for bookings</i></span> <form id="bookingForm" action="booking-submit.php" method="post"> <input type="hidden" name="token" value="<?php echo $_SESSION['token']?>"/> <div class="form-group"> <label for="inputName">Full Name</label> <input type="text" name="full_name" class="form-control" id="inputName" maxlength="100" required> </div> <div class="form-row"> <div class="form-group col-6"> <label for="inputEmail">Email</label> <input type="email" name="email" class="form-control" id="inputEmail" maxlength="100" required> </div> <div class="form-group col-6"> <label for="inputNumber">Contact Number</label> <input type="text" name="contact_number" class="form-control" id="inputNumber" maxlength="50" required> </div> </div> <div class="form-row"> <div class="form-group col-6 col-sm-4"> <label for="inputDate">Date of the event</label> <input type="text" name="date_event" class="form-control" id="inputDate" required readonly> </div> <div class="form-group col-6 col-sm-4"> <label for="inputTime">Start Time</label> <input type="time" name="time_event" class="form-control" id="inputTime" required> </div> <div class="form-group col-12 col-sm-4"> <label for="inputGuests">Number of guests</label> <input type="number" name="guests" class="form-control" id="inputGuests" min="1" max="1000" required> </div> </div> <div class="form-group"> <label for="inputVenue">Venue</label> <input type="text" name="venue" class="form-control" id="inputVenue" maxlength="200" placeholder="Address of the venue" required> </div> <div class="form-group"> <label for="inputTheme">Theme</label> <textarea class="form-control" name="theme" id="inputTheme" rows="3" maxlength=400 placeholder="Describe your desired theme for the party" required></textarea> </div> <div class="form-check"> <input type="checkbox" class="form-check-input" id="policyCheck" required> <label class="form-check-label" for="policyCheck"><i>I have read the <a href="" data-toggle="modal" data-target="#policyModal">booking policy</a> and agree to its terms and conditions</i></label> <div class="modal fade" id="policyModal" tabindex="-1" role="dialog" aria-labelledby="policyModal" aria-hidden="true"> <div class="modal-dialog modal-dialog-centered modal-lg" role="document"> <div class="modal-content"> <div class="modal-header"> <h4 class="modal-title" id="policyModalTitle">Booking Policy</h4> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <div class="modal-body"> <h5>Please read carefully before submitting your booking.</h5> <p>1) In order to schedule your cake on your event date, a 50 percent non-refundable deposit is required. Without the deposit, we will not hold your date. Priority will be given to the paying customer.</p> <p>2) All final payments are due 2 weeks prior to your event date. If payments are not made by the due date the cake may be cancelled.</p> <p>3) Refunds are not provided for any reason. Due to our full schedule and our attention to detail, we spend many hours planning and preparing before even beginning on a cake.</p> <p>4) There is a minimum delivery fee of $30 and will change depending how far the venue from the bakery.</p> <p>5) Any cake placed outside during an event has the possibility of melting or deforming due to the heat. We are not liable for a cake once it has been delivered or picked up.</p> <p>6) If you choose to pick up your cake and transport it yourself, we are not liable or responsible for the cake once it has left the bakery. You should prepare your vehicle so it is clean and free of items that could roll or slide into the cake. We do everything in our power to provide a well-structured cake, but please note that cakes are very fragile and break easily. Drive carefully and slowly.</p> <p>7) Wedding and custom cakes are designed to serve the number of people you specify. Our cake serving size is 1″ x 2″ and 5" tall. If you are serving larger slices of cake and run out, we are not responsible to provide additional cake.</p> </div> <div class="modal-footer"> <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button> </div> </div> </div> </div> </div> </form> </div> </main> <footer> <?php require_once('footer.html'); ?> <script src="js/jquery-ui.js"></script> <script src="js/bookings.js"></script> </footer> </body> </html><file_sep> <nav class="navbar navbar-expand-lg navbar-light bg-light"> <a class="navbar-brand" href="/"> <img id="nav-logo" width="150" src="../images/aloha_cake_logo.png" class="d-inline-block align-top" alt=""> </a> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarSupportedContent"> <ul class="navbar-nav mr-auto"> <li class='nav-item <?php if($currentPage == "home.php" || $currentPage == "index.php") echo "active"; ?>'> <a class="nav-link" href="/">Home</a> </li> <li class='nav-item <?php if($currentPage == "about.php") echo "active"; ?>'> <a class="nav-link" href="about">About</a> </li> <li class='nav-item <?php if($currentPage == "gallery.php") echo "active"; ?>'> <a class="nav-link" href="gallery">Gallery</a> </li> <li class='nav-item <?php if($currentPage == "contact.php") echo "active"; ?>'> <a class="nav-link" href="contact">Contact</a> </li> <li class='nav-item <?php if($currentPage == "bookings.php") echo "active"; ?>'> <a class="nav-link" href="bookings">Bookings</a> </li> </ul> <a href="https://www.facebook.com/alohacakeartsupplies/" class ="link-icon" target="=_blank"> <img width="35" height="35" src="../images/fb_icon.png" class="d-inline-block align-top" alt=""> </a> <a href="https://www.instagram.com/aloha.cakeart.supplies/" class ="link-icon" target="_blank"> <img width="35" height="35" src="../images/ig_icon.png" class="d-inline-block align-top" alt=""> </a> </div> </nav><file_sep><?php $currentPage = basename($_SERVER['PHP_SELF']); ?> <!DOCTYPE html> <html lang="en"> <head> <?php require_once('header.html'); ?> </head> <body> <?php require_once('navbar.php'); ?> <main role="main"> <div class="jumbotron banner"> <div class="container"> <div class="row"> <div class="col-lg-5 d-none d-lg-block"> <img class="img-fluid banner-logo" src="../images/aloha_cake_logo.png"> </div> <div class="col-lg-7"> <h1 class="display-5 banner-tagline">Your one-stop-shop for customized cakes, decorating supplies, and party planning</h1> </div> </div> </div> </div> <div class="container"> <div class="row"> <div class="col-lg-7 col-md-7 col-sm-7 col-7"> <h2 class="featurette-heading">Customized cakes and desserts</h2> <p class="featurette-text">Customized cakes and desserts for all occasions, from birthdays to weddings to anniversaries. Aloha Cake Art will provide you anything you can imagine to satisfy your sweet tooth as well as a feast for the eyes with our intricate designs.</p> </div> <div class="col-lg-5 col-md-5 col-sm-5 col-5"> <img class="img-fluid mx-auto featurette-img" src="../images/cake-1.jpg"> </div> </div> <hr class="featurette-divider"> <div class="row"> <div class="col-lg-7 col-md-7 col-sm-7 col-7 order-lg-2 order-md-2 order-sm-2 order-2"> <h2 class="featurette-heading">Cake Decorating Supplies</h2> <p class="featurette-text">Aside from personalized cakes, Aloha Cake Art also has cake decorating supplies in store for all budding pastry artists.</p> </div> <div class="col-lg-5 col-md-5 col-sm-5 col-5 order-lg-1 order-md-1 order-sm-1 order-1"> <img class="img-fluid mx-auto featurette-img" src="../images/Supplies.jpg"> </div> </div> <hr class="featurette-divider"> <div class="row"> <div class="col-lg-7 col-md-7 col-sm-7 col-7"> <h2 class="featurette-heading">Party Planning</h2> <p class="featurette-text">Allow us to make your parties memorable with our great tasting desserts.</p> </div> <div class="col-lg-5 col-md-5 col-sm-5 col-5"> <img class="img-fluid mx-auto featurette-img" src="../images/Party.jpg"> </div> </div> </div> </main> <footer> <?php require_once('footer.html'); ?> </footer> </body> </html>
2d5eab33385c9b145d1f629b8de08f1e13a099eb
[ "PHP" ]
10
PHP
cjqvita/AlohaCake
f7988e73832001dd3d7caff0f65f0146f97ec9ec
80ff9a919e3337a430e9ffa1f45160e907bcec07
refs/heads/master
<repo_name>victorybringer/study<file_sep>/MiniProgram/pages/video/video.js const app = getApp() Page({ /** * 页面的初始数据 */ data: { name:'', url:'', image:'', click1: 'false', click2: 'false', text:'', comment:[], none:"false", count:0, share: 'false' }, /** * 生命周期函数--监听页面加载 */ onLoad: function (options) { var that = this if (options.share == 'true') { app.globalData.name = options.name app.globalData.image = options.image app.globalData.url = options.url app.globalData.openid = 'oFPA65BTgQ-MRSdCKjx5FUr4r4nU' this.setData({ share:'true' }) } wx.request({ url: 'https://mercifuldruid.cn/loadfunction?type=video' + '&name=' + app.globalData.name + '&openid=' + app.globalData.openid, success(res) { var data = res.data.trim().split(" "); that.setData({ text: '', name: app.globalData.name, url: app.globalData.url, image: app.globalData.image }) if (data[0] == 'true') { that.setData({ click1: 'true' }) } else { that.setData({ click1: 'false' }) } if (data[1] == 'true') { that.setData({ click2: 'true' }) } else { that.setData({ click2: 'false' }) } wx.request({ url: 'https://mercifuldruid.cn/loadcomment?type=video' + '&name=' + app.globalData.name, success(res) { var bind = [] var a = res.data.trim().split("\n") if (a == "") { that.setData({ none: "true" }) } else{ for(var i=0;i<a.length;++i){ var b=a[i].split(" ") bind.push([b[0], b[1], b[2],b[3], b[4]]) } that.setData({ none: "false", comment:bind }) } wx.request({ url: 'https://mercifuldruid.cn/loadcount?type=video' + '&name=' + app.globalData.name, success(res) { that.setData({ count: res.data }) } }) } }) } }) }, input:function(e){ this.data.text=e.detail.value console.log(this.data.text) }, image1:function(){ var that=this if(this.data.click1=='false'){ this.setData({ click1:'true' }) } else{ this.setData({ click1: 'false' }) } wx.showLoading({ title: 'Waiting', }) wx.request({ url: 'https://mercifuldruid.cn/function?type=video&mode=1&good=' + this.data.click1 + '&save=' + this.data.click2 + '&name=' + this.data.name + '&openid=' + app.globalData.openid, success(res) { wx.hideLoading() var options = '' getCurrentPages()[getCurrentPages().length - 1].onLoad(options) } }) } , image2: function () { var that=this if (this.data.click2 == 'true') { this.setData({ click2: 'false' }) } else { this.setData({ click2: 'true' }) } wx.showLoading({ title: 'Waiting', }) wx.request({ url: 'https://mercifuldruid.cn/function?type=video&mode=2&save=' + this.data.click2 + '&good=' + this.data.click1+ '&name=' + this.data.name + '&openid=' + app.globalData.openid, success(res) { wx.hideLoading() var options = '' getCurrentPages()[getCurrentPages().length - 1].onLoad(options) } }) }, /** * 生命周期函数--监听页面显示 */ onShow: function () { }, /** * 生命周期函数--监听页面隐藏 */ onHide: function () { }, /** * 生命周期函数--监听页面卸载 */ onUnload: function () { }, /** * 页面相关事件处理函数--监听用户下拉动作 */ onPullDownRefresh: function () { }, /** * 页面上拉触底事件的处理函数 */ onReachBottom: function () { }, back: function () { wx.redirectTo({ url: '../index/index', }) }, /** * 用户点击右上角分享 */ onShareAppMessage: function (res) { var that = this if (res.from === 'button') { console.log("来自页面内转发按钮"); console.log(res.target); } else { console.log("来自右上角转发菜单") } return { title: app.globalData.name, path: '/pages/video/video?share=true&name=' + app.globalData.name + '&url=' + app.globalData.url + '&image=' + app.globalData.image, success: (res) => { console.log("转发成功", res); }, fail: (res) => { console.log("转发失败", res); } } }, send:function(){ var that=this wx.showLoading({ title: 'Waiting', }) wx.request({ url: 'https://mercifuldruid.cn/comment?type=video&name=' + this.data.name + '&openid=' + app.globalData.openid+ '&text=' + this.data.text, success(res) { wx.hideLoading() var options='' getCurrentPages()[getCurrentPages().length - 1].onLoad(options) } }) } })<file_sep>/MiniProgram/pages/profile/profile.js //index.js //获取应用实例 const app = getApp() Page({ data: { userinfo:'', grade:'', major:'' }, //事件处理函数 onShow:function(){ }, onLoad: function () { this.setData({ userinfo:app.globalData.userInfo, grade: app.globalData.grade, major: app.globalData.major }) } }) <file_sep>/README.md # Info 基于微信小程序的在线学习软件,后端为Tomcat, JDK 1.8, 基于Mysql <br> # Frontend Install `1.安装微信web开发者工具 `<br> `2.导入MiniProgram,APPID为wx27b44fda89f37897 `<br> # Backend Install ## 1.使用预构建的Docker镜像<br> `docker run -it -p 8080:8080 ccr.ccs.tencentyun.com/victroybringer/study`<br> ## 2.或使用Dockerfile进行构建<br> `运行源码构建.bat`<br> ## 3.工程源码导入<br> `使用Eclipse导入工程 `<br> <file_sep>/MiniProgram/pages/me/me.js const app = getApp() Page({ /** * 页面的初始数据 */ data: { userinfo:'' }, /** * 生命周期函数--监听页面加载 */ onLoad: function (options) { this.setData({ userinfo: app.globalData.userInfo }) }, /** * 生命周期函数--监听页面初次渲染完成 */ onReady: function () { }, /** * 生命周期函数--监听页面显示 */ onShow: function () { }, /** * 生命周期函数--监听页面隐藏 */ onHide: function () { }, /** * 生命周期函数--监听页面卸载 */ onUnload: function () { }, /** * 页面相关事件处理函数--监听用户下拉动作 */ onPullDownRefresh: function () { }, exit:function(){ wx.redirectTo({ url: '../index/index', }) }, /** * 页面上拉触底事件的处理函数 */ onReachBottom: function () { }, /** * 用户点击右上角分享 */ onShareAppMessage: function () { }, profile:function() { wx.showLoading({ title: 'Please Waiting', }) wx.request({ url: 'https://mercifuldruid.cn/loadprofile?a=' + app.globalData.openid, success(res) { wx.hideLoading() var data = res.data app.globalData.grade = data.trim().split(" ")[0] app.globalData.major = data.trim().split(" ")[1] wx.navigateTo({ url: '../profile/profile', }) } }) }, save:function(){ wx.showLoading({ title: '请等待', }) wx.request({ url: 'https://mercifuldruid.cn/loadsave?type=video&openid=' + app.globalData.openid, success(res) { wx.hideLoading() var data = res.data.trim().split("\n") if (data == "") { app.globalData.none1 = 'true' } app.globalData.savevideo=[] app.globalData.savebook = [] for(var i=0;i<data.length;i++){ app.globalData.savevideo.push(data[i]) } wx.request({ url: 'https://mercifuldruid.cn/loadsave?type=book&openid=' + app.globalData.openid, success(res) { wx.hideLoading() var data = res.data.trim().split("\n") if(data==""){ app.globalData.none2 = 'true' } app.globalData.savebook = [] for (var i = 0; i < data.length; i++) { app.globalData.savebook.push(data[i]) } wx.navigateTo({ url: '../save/save', }) } }) } }) } })<file_sep>/Server/study/src/openid.java import java.io.BufferedReader; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.PrintWriter; import java.math.BigInteger; import java.net.HttpURLConnection; import java.net.URL; import java.net.URLConnection; import java.sql.DriverManager; import java.sql.ResultSet; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.List; import java.util.Map; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.mysql.jdbc.Connection; import com.mysql.jdbc.Statement; /** * Servlet implementation class watchB */ @WebServlet("/openid") public class openid extends HttpServlet { private static final long serialVersionUID = 1L; /** * @see HttpServlet#HttpServlet() */ public openid() { super(); // TODO Auto-generated constructor stub } /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String requestUrl = "https://api.weixin.qq.com/sns/jscode2session"; BufferedReader in = null; String result = ""; PrintWriter out = response.getWriter(); String urlNameString = requestUrl+"?appid=wx27b44fda89f37897&js_code="+request.getParameter("code")+"&secret=<KEY>&grant_type=authorization_code"; URL realUrl = new URL(urlNameString); URLConnection connection = realUrl.openConnection(); connection.connect(); in = new BufferedReader(new InputStreamReader(connection.getInputStream())); String line=null; while((line = in.readLine()) != null){ result += line; } out.print(result) ; } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub doGet(request, response); } } <file_sep>/MiniProgram/pages/menu2/menu2.js const app=getApp() Page({ /** * 页面的初始数据 */ data: { video: [], book: [], allvideo:[], allbook:[], currentbook:[], currentvideo: [], cur:0, none1: "false", none2: "false", array1:['Book','Video','Favorite'], color1: ['white', '#CD0000', '#CD0000'], array2: ['Computer Science', 'Economy', 'Philosophy'], array3: ['Freshman', 'Sophomore', 'Junior', 'Senior'], color2: ['white', '#CD0000', '#CD0000'], color3: ['white', '#CD0000', '#CD0000', '#CD0000'], farray: ['Video','Book' ], fcolor: ['white', '#CD0000'] }, bt:function(e){ var color=[] for (var i = 0; i < this.data.array1.length;++i){ color.push('#CD0000') } color[e.target.id]='white' this.setData({ color1:color, cur: 0 }) }, bt2: function (e) { var color = [] for (var i = 0; i < this.data.array2.length; ++i) { color.push('#CD0000') } color[e.target.id] = 'white' this.setData({ color2: color }) var currentbook=[]; var currentvideo = []; for (var i = 0; i < this.data.array2.length; ++i) { for (var j = 0; j < this.data.array3.length; ++j) { for (var k = 0; k < this.data.allbook.length; ++k) { if (this.data.allbook[k][3] == this.data.array2[i] && this.data.allbook[k][4] == this.data.array3[j] && this.data.color2[i] == 'white' && this.data.color3[j] == 'white'){ currentbook.push([this.data.allbook[k][0], this.data.allbook[k][1], this.data.allbook[k][2], this.data.allbook[k][3], this.data.allbook[k][4]]) } } } } for (var i = 0; i < this.data.array2.length; ++i) { for (var j = 0; j < this.data.array3.length; ++j) { for (var k = 0; k < this.data.allvideo.length; ++k) { if (this.data.allvideo[k][3] == this.data.array2[i] && this.data.allvideo[k][4] == this.data.array3[j] && this.data.color2[i] == 'white' && this.data.color3[j] == 'white') { currentvideo.push([this.data.allvideo[k][0], this.data.allvideo[k][1], this.data.allvideo[k][2], this.data.allvideo[k][3], this.data.allvideo[k][4]]) } } } } this.setData({ currentbook: currentbook, currentvideo: currentvideo, cur: 0 }) }, bt3: function (e) { var color = [] for (var i = 0; i < this.data.array3.length; ++i) { color.push('#CD0000') } color[e.target.id] = 'white' this.setData({ color3: color }) var currentbook = []; var currentvideo = []; for (var i = 0; i < this.data.array2.length; ++i) { for (var j = 0; j < this.data.array3.length; ++j) { for (var k = 0; k < this.data.allbook.length; ++k) { if (this.data.allbook[k][3] == this.data.array2[i] && this.data.allbook[k][4] == this.data.array3[j] && this.data.color2[i] == 'white' && this.data.color3[j] == 'white') { currentbook.push([this.data.allbook[k][0], this.data.allbook[k][1], this.data.allbook[k][2], this.data.allbook[k][3], this.data.allbook[k][4]]) } } } } for (var i = 0; i < this.data.array2.length; ++i) { for (var j = 0; j < this.data.array3.length; ++j) { for (var k = 0; k < this.data.allvideo.length; ++k) { if (this.data.allvideo[k][3] == this.data.array2[i] && this.data.allvideo[k][4] == this.data.array3[j] && this.data.color2[i] == 'white' && this.data.color3[j] == 'white') { currentvideo.push([this.data.allvideo[k][0], this.data.allvideo[k][1], this.data.allvideo[k][2], this.data.allvideo[k][3], this.data.allvideo[k][4]]) } } } } this.setData({ currentbook: currentbook, currentvideo: currentvideo, cur:0 }) }, fbt: function (e) { var color = [] for (var i = 0; i < this.data.farray.length; ++i) { color.push('#CD0000') } color[e.target.id] = 'white' this.setData({ fcolor: color }) }, allimage: function (e) { wx.navigateTo({ url: '../video/video' }) app.globalData.name = this.data.currentvideo[e.target.id][1] app.globalData.image = this.data.currentvideo[e.target.id][0] app.globalData.url = this.data.currentvideo[e.target.id][2] }, allimage2: function (e) { console.log(e.target.id) wx.navigateTo({ url: '../Book/Book' }) app.globalData.name = this.data.currentbook[e.target.id][1] app.globalData.image = this.data.currentbook[e.target.id][0] app.globalData.url = this.data.currentbook[e.target.id][2] }, image: function (e) { wx.navigateTo({ url: '../video/video' }) app.globalData.name = this.data.video[e.target.id][1] app.globalData.image = this.data.video[e.target.id][0] app.globalData.url = this.data.video[e.target.id][2] }, image2: function (e) { wx.navigateTo({ url: '../Book/Book' }) app.globalData.name = this.data.book[e.target.id][1] app.globalData.image = this.data.book[e.target.id][0] app.globalData.url = this.data.book[e.target.id][2] }, fbt1: function () { this.setData({ fcolor1: 'white', fcolor2: '#CD0000', }) }, fbt2: function () { this.setData({ fcolor1: '#CD0000', fcolor2: 'white', }) }, /** * 生命周期函数--监听页面加载 */ onShow: function (options) { var that = this wx.request({ url: 'https://mercifuldruid.cn/loadbook', success(res) { var data = res.data.trim().split("\n") var allbook2 = [] for (var i = 0; i < data.length; ++i) { allbook2.push([data[i].trim().split(" ")[0], data[i].trim().split(" ")[1], data[i].trim().split(" ")[2], data[i].trim().split(" ")[3], data[i].trim().split(" ")[4]]) } that.setData({ allbook: allbook2, }) console.log(that.data.currentbook) wx.request({ url: 'https://mercifuldruid.cn/loadvideo', success(res) { var data = res.data.trim().split("\n") var allvideo = [] for (var i = 0; i < data.length; ++i) { allvideo.push([data[i].trim().split(" ")[0], data[i].trim().split(" ")[1], data[i].trim().split(" ")[2], data[i].trim().split(" ")[3], data[i].trim().split(" ")[4]]) } that.setData({ allvideo: allvideo, }) var currentbook = []; var currentvideo = []; for (var i = 0; i < that.data.array2.length; ++i) { for (var j = 0; j < that.data.array3.length; ++j) { for (var k = 0; k < that.data.allbook.length; ++k) { if (that.data.allbook[k][3] == that.data.array2[i] && that.data.allbook[k][4] == that.data.array3[j] && that.data.color2[i] == 'white' && that.data.color3[j] == 'white') { currentbook.push([that.data.allbook[k][0], that.data.allbook[k][1], that.data.allbook[k][2], that.data.allbook[k][3], that.data.allbook[k][4]]) } } } } for (var i = 0; i < that.data.array2.length; ++i) { for (var j = 0; j < that.data.array3.length; ++j) { for (var k = 0; k < that.data.allvideo.length; ++k) { if (that.data.allvideo[k][3] == that.data.array2[i] && that.data.allvideo[k][4] == that.data.array3[j] && that.data.color2[i] == 'white' && that.data.color3[j] == 'white') { currentvideo.push([that.data.allvideo[k][0], that.data.allvideo[k][1], that.data.allvideo[k][2], that.data.allvideo[k][3], that.data.allvideo[k][4]]) } } } } that.setData({ currentbook: currentbook, currentvideo: currentvideo }) console.log(that.data.allvideo) wx.request({ url: 'https://mercifuldruid.cn/loadsave?type=video&openid=' + app.globalData.openid, success(res) { var data = res.data.trim().split("\n") if (data == "") { that.setData({ none1: 'true' }) } else { var video2 = [] for (var i = 0; i < data.length; i++) { video2.push([data[i].split(" ")[0], data[i].split(" ")[1], data[i].split(" ")[2]]) } that.setData({ none1: 'false', video: video2 }) } wx.request({ url: 'https://mercifuldruid.cn/loadsave?type=book&openid=' + app.globalData.openid, success(res) { var data = res.data.trim().split("\n") if (data == "") { that.setData({ none2: 'true' }) } else { var book2 = [] for (var i = 0; i < data.length; i++) { book2.push([data[i].split(" ")[0].trim(), data[i].split(" ")[1].trim(), data[i].split(" ")[2].trim()]) } that.setData({ none2: 'false', book: book2 }) } } }) } }) } }) } }) }, /** * 生命周期函数--监听页面初次渲染完成 */ onReady: function () { }, /** * 生命周期函数--监听页面显示 */ onLoad: function () { }, /** * 生命周期函数--监听页面隐藏 */ onHide: function () { }, /** * 生命周期函数--监听页面卸载 */ onUnload: function () { }, /** * 页面相关事件处理函数--监听用户下拉动作 */ onPullDownRefresh: function () { }, /** * 页面上拉触底事件的处理函数 */ onReachBottom: function () { }, /** * 用户点击右上角分享 */ })<file_sep>/MiniProgram/pages/first/first.js const app = getApp() Page({ /** * 页面的初始数据 */ data: { index1: 0, index2:0, array1: ['Freshman', 'Sophomore', 'Junior', 'Senior'], array2: ['Computer Science', 'Economy', 'Philosophy'], }, bindPickerChange1: function (e) { this.setData({ index1: e.detail.value, }) }, bindPickerChange2: function (e) { this.setData({ index2: e.detail.value, }) }, confirm:function(){ var that=this wx.request({ url: 'https://mercifuldruid.cn/profile?a=' + that.data.array1[that.data.index1] + '&b=' + that.data.array2[that.data.index2] + '&c=' + app.globalData.openid + '&d=' + app.globalData.userInfo.avatarUrl + '&e=' + app.globalData.userInfo.nickName , success(res) { console.log(that.data.array1[that.data.index1]), wx.showModal({ showCancel: false, title: 'Setting', content: 'Successed', success(res) { if (res.confirm) { wx.switchTab({ url: '../recommend/recommend', }) } } }) } }) }, /** * 生命周期函数--监听页面加载 */ onLoad: function (options) { }, /** * 生命周期函数--监听页面初次渲染完成 */ onReady: function () { }, /** * 生命周期函数--监听页面显示 */ onShow: function () { }, /** * 生命周期函数--监听页面隐藏 */ onHide: function () { }, /** * 生命周期函数--监听页面卸载 */ onUnload: function () { }, /** * 页面相关事件处理函数--监听用户下拉动作 */ onPullDownRefresh: function () { }, /** * 页面上拉触底事件的处理函数 */ onReachBottom: function () { }, /** * 用户点击右上角分享 */ onShareAppMessage: function () { } })<file_sep>/MiniProgram/pages/Book/Book.js const app=getApp() Page({ /** * 页面的初始数据 */ data: { url:'', name:'', image: '', name2:" ", click1: 'false', click2: 'false', text: '', comment: [], none: "false", count:0, share:'false' }, /** * 生命周期函数--监听页面加载 */ onLoad: function (options) { var that = this console.log(options) if(options.share=='true'){ app.globalData.name=options.name app.globalData.image = options.image app.globalData.url = options.url app.globalData.openid ='oFPA65BTgQ-MRSdCKjx5FUr4r4nU' this.setData({ share: 'true' }) } wx.request({ url: 'https://mercifuldruid.cn/loadfunction?type=book' + '&name=' + app.globalData.name + '&openid=' + app.globalData.openid, success(res) { var data = res.data.trim().split(" "); console.log(data) that.setData({ text:'', name: app.globalData.name, url: app.globalData.url, image: app.globalData.image }) if(data[0]=='true'){ that.setData({ click1:'true' }) } else{ that.setData({ click1: 'false' }) } if (data[1] == 'true') { that.setData({ click2: 'true' }) } else { that.setData({ click2: 'false' }) } wx.request({ url: 'https://mercifuldruid.cn/loadcomment?type=book' + '&name=' + app.globalData.name, success(res) { var bind = [] var a = res.data.trim().split("\n") if (a == "") { that.setData({ none: "true" }) } else { for (var i = 0; i < a.length; ++i) { var b = a[i].split(" ") bind.push([b[0], b[1], b[2], b[3], b[4]]) } that.setData({ none: "false", comment: bind }) } wx.request({ url: 'https://mercifuldruid.cn/loadcount?type=book' + '&name=' + app.globalData.name, success(res) { that.setData({ count: res.data }) } }) } }) } }) }, /** * 生命周期函数--监听页面初次渲染完成 */ onReady: function () { }, /** * 生命周期函数--监听页面显示 */ onShow: function () { }, click:function(){ var that = this wx.showLoading({ title: 'Opening', }), console.log(that.data.url) wx.downloadFile({ // 示例 url,并非真实存在 url:that.data.url , success: function (res) { console.log(res) const filePath = res.tempFilePath wx.hideLoading() wx.openDocument({ filePath: filePath, success: function (res) { console.log('打开文档成功') }, fail: function (res) { console.log(res) } }) }, fail: function (res) { console.log(res) } }) }, image1: function () { var that = this if (this.data.click1 == 'false') { this.setData({ click1: 'true' }) } else { this.setData({ click1: 'false' }) } wx.showLoading({ title: 'Waiting', }) wx.request({ url: 'https://mercifuldruid.cn/function?type=book&mode=1&good=' + this.data.click1 + '&save=' + this.data.click2 + '&name=' + this.data.name + '&openid=' + app.globalData.openid, success(res) { wx.hideLoading() var options = '' getCurrentPages()[getCurrentPages().length - 1].onLoad(options) } }) }, image2: function () { var that = this if (this.data.click2 == 'true') { this.setData({ click2: 'false' }) } else { this.setData({ click2: 'true' }) } wx.showLoading({ title: 'Waiting', }) wx.request({ url: 'https://mercifuldruid.cn/function?type=book&mode=2&good=' + this.data.click1 + '&save=' + this.data.click2 + '&name=' + this.data.name + '&openid=' + app.globalData.openid, success(res) { wx.hideLoading() var options = '' getCurrentPages()[getCurrentPages().length - 1].onLoad(options) } }) }, /** * 生命周期函数--监听页面隐藏 */ onHide: function () { }, /** * 生命周期函数--监听页面卸载 */ /** * 页面相关事件处理函数--监听用户下拉动作 */ onPullDownRefresh: function () { }, /** * 页面上拉触底事件的处理函数 */ onReachBottom: function () { }, /** * 用户点击右上角分享 */ onShareAppMessage: (res) => { var that=this if (res.from === 'button') { console.log("来自页面内转发按钮"); console.log(res.target); } else { console.log("来自右上角转发菜单") } return { title: app.globalData.name, path: '/pages/Book/Book?share=true&name='+app.globalData.name+'&url='+app.globalData.url+'&image='+app.globalData.image, success: (res) => { console.log("转发成功", res); }, fail: (res) => { console.log("转发失败", res); } } }, send: function () { var that = this wx.showLoading({ title: 'Waiting', }) wx.request({ url: 'https://mercifuldruid.cn/comment?type=book&name=' + this.data.name + '&openid=' + app.globalData.openid + '&text=' + this.data.text, success(res) { var options='' getCurrentPages()[getCurrentPages().length - 1].onLoad(options) wx.hideLoading() } }) }, input: function (e) { this.data.text = e.detail.value }, back:function(){ wx.redirectTo({ url: '../index/index', }) } })<file_sep>/MiniProgram/app.js const app=getApp() App({ onLaunch: function () { // 展示本地存储能力 var logs = wx.getStorageSync('logs') || [] logs.unshift(Date.now()) wx.setStorageSync('logs', logs) // 登录 wx.login({ }) // 获取用户信息 wx.getSetting({ success: res => { if (res.authSetting['scope.userInfo']) { // 已经授权,可以直接调用 getUserInfo 获取头像昵称,不会弹框 wx.getUserInfo({ success: res => { // 可以将 res 发送给后台解码出 unionId this.globalData.userInfo = res.userInfo // 由于 getUserInfo 是网络请求,可能会在 Page.onLoad 之后才返回 // 所以此处加入 callback 以防止这种情况 if (this.userInfoReadyCallback) { this.userInfoReadyCallback(res) } } }) } } }) }, getOpenid: function () { var that = this; return new Promise(function (resolve, reject) { wx.login({ success: function (res) { //code 获取用户信息的凭证 if (res.code) { //请求获取用户openid wx.request({ url: "https://mercifuldruid.cn/openid", data: { "code": res.code }, method: 'GET', header: { 'Content-type': 'application/json' }, success: function (res) { wx.setStorageSync('openid', res.data.openid);//存储openid var res = { status: 200, data: res.data.openid } resolve(res); } }); } else { console.log('获取用户登录态失败!' + res.errMsg) reject('error'); } } }) }); }, globalData: { userInfo: null, openid:'', grade:'', major:'', url:'', image:'', name:'', } })
df9f0d93b32d8865142c6b51964e2bfdb1a4a52b
[ "JavaScript", "Java", "Markdown" ]
9
JavaScript
victorybringer/study
a6df59e379491a9a86d975e145afb660e9877f86
25a43b35cd12f64aff7556deb74881db5367dce4
refs/heads/master
<repo_name>mattheath/ritly<file_sep>/app/models/url.rb class Url < ActiveRecord::Base validates_format_of :link, :with => /\A(http|https):\/\/[a-z0-9]+([\-\.]{1}[a-z0-9]+)*\.[a-z]{2,15}(:[0-9]{1,5})?(\/.*)?\z/ix end <file_sep>/app/controllers/urls_controller.rb class UrlsController < ApplicationController before_action :authenticate_user!, only: [:new, :create] before_action :load_link_by_hash, only: [:redirectors, :preview] def new @url = Url.new end def create @url = Url.new(safe_url_params) @url.hash_code = generate_hash_code # @todo catch errors if @url.save redirect_to :controller => 'urls', :action => 'preview', :code => @url.hash_code else render 'new' end end def redirectors if @url # @todo check that urls are valid redirect_to @url.link else flash[:alert] = "Link not valid" redirect_to new_url_path end end def preview end private def safe_url_params params.require('url').permit(:link) end def generate_hash_code rand(10000) end def load_link_by_hash @url = Url.find_by hash_code: params[:code] # @todo catch errors!!! end end
d1b9b4f8b34354fc4009e232981ed5f9fe52d33e
[ "Ruby" ]
2
Ruby
mattheath/ritly
0b5bc5ba08f7b5ebd6889d755461e4f5d6c32f38
904038731da4d63a4784f58cb68fa12dbb1a5109
refs/heads/master
<repo_name>gregheo/XPlatSwiftDemo<file_sep>/README.md # XPlatSwiftDemo Cross-platform Swift demo from Indie DevStock 2016 This is the raw "finished project" and related files from my talk "Cross-Platform Swift" at Indie DevStock 2016. <file_sep>/SessionsJSON.playground/Contents.swift //: Playground - noun: a place where people can play import Foundation #if os(Linux) typealias RegexType = RegularExpression let fileUrl = URL(fileURLWithPath: "sessions.json") #else typealias RegexType = NSRegularExpression let fileUrl = Bundle.main.url(forResource: "sessions", withExtension: "json")! #endif guard let jsonData = try? Data(contentsOf: fileUrl) else { fatalError() } guard let sessions = try JSONSerialization.jsonObject(with: jsonData, options: []) as? [[String:String]] else { fatalError() } guard let swiftRegex = try? RegexType(pattern: "swift", options: [.caseInsensitive]) else { fatalError() } if let jsonData = try? JSONSerialization.data(withJSONObject: sessions, options: [.prettyPrinted]), let jsonString = String(bytes: jsonData, encoding: String.Encoding.utf8) { } for session in sessions { if let speaker = session["speaker"], let title = session["title"] { if swiftRegex.numberOfMatches(in: title, options: [], range: NSMakeRange(0, title.utf8.count)) > 0 { print("\(speaker): \(title)") } } } <file_sep>/PlatformsMac/Platforms/LocalJSONLoader.swift // // LocalJSONLoader.swift // Platforms // // Created by <NAME> on 2016-09-16. // Copyright © 2016 <NAME>. All rights reserved. // import Foundation public class LocalJSONLoader: JSONLoader { public func getJSONData() -> Data { #if os(Linux) typealias RegexType = RegularExpression let fileUrl = URL(fileURLWithPath: "sessions.json") #else typealias RegexType = NSRegularExpression guard let fileUrl = Bundle.main.url(forResource: "sessions", withExtension: "json") else { fatalError("Could not get file URL from the bundle!") } #endif guard let jsonData = try? Data(contentsOf: fileUrl) else { fatalError() } return jsonData } } <file_sep>/JSONStarter.playground/Contents.swift //: JSON Parsing & You import Cocoa <file_sep>/PlatformsMac/Platforms/JSONDataSource.swift // // JSONDataSource.swift // Platforms // // Created by <NAME> on 2016-09-16. // Copyright © 2016 <NAME>. All rights reserved. // import Foundation public protocol JSONLoader { func getJSONData() -> Data } public class JSONDataSource { private(set) public var sessions: [[String: String]] = [] public init(jsonLoader: JSONLoader) { #if os(Linux) typealias RegexType = RegularExpression #else typealias RegexType = NSRegularExpression #endif guard let swiftRegex = try? RegexType(pattern: ".*", options: [.caseInsensitive]) else { fatalError() } let jsonData = jsonLoader.getJSONData() do { if let sessions = try JSONSerialization.jsonObject(with: jsonData, options: []) as? [[String:String]] { for session in sessions { guard let title = session["title"] else { continue } if swiftRegex.numberOfMatches(in: title, options: [], range: NSMakeRange(0, title.utf8.count)) > 0 { self.sessions.append(session) } } } } catch { fatalError() } } public var count: Int { return sessions.count } } <file_sep>/PlatformsMac/Platforms/ViewController.swift // // ViewController.swift // Platforms // // Created by <NAME> on 2016-09-15. // Copyright © 2016 <NAME>. All rights reserved. // import Cocoa class ViewController: NSViewController { @IBOutlet weak var tableView: NSTableView! var sessionDataSource = JSONDataSource(jsonLoader: RemoteJSONLoader()) override func viewDidLoad() { super.viewDidLoad() tableView.delegate = self tableView.dataSource = self tableView.reloadData() } } extension ViewController: NSTableViewDataSource { func numberOfRows(in tableView: NSTableView) -> Int { return sessionDataSource.count } } extension ViewController: NSTableViewDelegate { func tableView(_ tableView: NSTableView, viewFor tableColumn: NSTableColumn?, row: Int) -> NSView? { let session = sessionDataSource.sessions[row] guard let tableColumn = tableColumn, let cellView = tableView.make(withIdentifier: tableColumn.identifier , owner: nil) as? NSTableCellView, let sessionTitle = session["title"], let sessionSpeaker = session["speaker"], let sessionTime = session["time"] else { return nil } if tableColumn == tableView.tableColumns[0] { cellView.textField?.stringValue = sessionTime } else if tableColumn == tableView.tableColumns[1] { cellView.textField?.stringValue = sessionTitle } else if tableColumn == tableView.tableColumns[2] { cellView.textField?.stringValue = sessionSpeaker } return cellView } } <file_sep>/PlatformsMac/Platforms/RemoteJSONLoader.swift // // RemoteJSONLoader.swift // Platforms // // Created by <NAME> on 2016-09-16. // Copyright © 2016 <NAME>. All rights reserved. // import Foundation class RemoteJSONLoader: JSONLoader { public func getJSONData() -> Data { do { let data = try Data(contentsOf: URL(string: "http://localhost:8090/sessions")!) return data } catch { return Data() } } }
e47e62d519be66d9821d583395b01eb04a27080c
[ "Markdown", "Swift" ]
7
Markdown
gregheo/XPlatSwiftDemo
a28ad6177413355f3bec6daf23fd3c5f46034e5f
087ebe9749e6de85b2d07eaf67e90571ce6f71c8
refs/heads/master
<repo_name>007xiaochen/news<file_sep>/02 网易新闻/Podfile source ‘https://github.com/CocoaPods/Specs.git' pod 'SDWebImage' pod 'AFNetworking', '~> 3.0.4' pod 'MJExtension', '~> 3.0.9'
cd82df216176c4bf703d84812c0e22b5e68ce16b
[ "Ruby" ]
1
Ruby
007xiaochen/news
f11b40d62de0bd159aaee9b4c3a65a5af8772b50
bf5bc7ee7044de26bdec524a71aed913d5644c15
refs/heads/master
<file_sep>/** * functionsUtilService * @description - Service with util functions used accross the whole application * @constructor */ module app.core.util.functionsUtil { 'use strict'; /**********************************/ /* INTERFACES */ /**********************************/ export interface IFunctionsUtilService { dateMonthToString: (date: string, zone: string) => string; getPositionByUid: (array: Array<any>, uid: string) => number; groupByYear: (array: Array<any>) => any; arrayToObject: (array: Array<any>) => any; } /****************************************/ /* CLASS DEFINITION */ /****************************************/ export class FunctionsUtilService implements IFunctionsUtilService { static serviceId = 'finApp.core.util.FunctionsUtilService'; /**********************************/ /* PROPERTIES */ /**********************************/ // -------------------------------- /**********************************/ /* CONSTRUCTOR */ /**********************************/ constructor() { console.log('functionsUtil service called'); } /**********************************/ /* METHODS */ /**********************************/ /* * Split Date Format Method * @description Split Date in 3 parts: day, month and year */ public static splitDateFormat(date: string): app.interfaces.IDateFormatted { //Format date to MM/DD/YYYY /* TODO: Analizar month, ya que hasta el momento no me sirve de nada tenerlo: MAY, JUN Lo estoy usando completo: Junio o June. Analizar si transformarlo aqui de esa forma O aqui guardar solo el numero. */ let dateString = moment(date).format('YYYY/MMM/DD').split('/'); //Split date to day, month and year let dateFormatted = { complete: date, day: dateString[2], month: dateString[1], year: dateString[0] }; return dateFormatted; } /** * dateMonthToString * @description - format month to long string (example: 'November') * @use - this.FinanceService.dateMonthToString('Mon May 01 2016 01:23:34 GMT-0500 (COT)', 'es-ES'); * @function * @params {string} date - complete date * @params {string} zone - specific the language zone (example: 'en-US', 'es-ES') * @return {string} month - Returns month formatted to long string (example: 'November') */ dateMonthToString(date, zone): string { //VARIABLES var dateFormatted = new Date(date); var options = {month: "long"}; var month = dateFormatted.toLocaleDateString(zone, options); return month; } /** * formatCurrency * @description - format a number to currency string * @function * @params {number} num - number without format * @params {string} formatted - number formatted (if you don't have this value, please send '') * @return {object} currency - Returns an object with 2 properties: num - number without format * and formatted - number formatted. */ formatCurrency(num: number, formatted: string): app.models.finance.IMoney { let currency = { num: num, formatted: formatted }; if (currency.formatted) { currency.num = accounting.unformat(currency.formatted); } /* TODO: Remove '$' hardcode, change it with some variable */ currency.formatted = accounting.formatMoney(currency.num, '$', 0); return currency; } /** * generateGuid * @description - generate Guid id string * @function * @return {string} guid - Returns an Guid Id string. */ public static generateGuid(): string { var fmt = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'; var guid = fmt.replace(/[xy]/g, function (c) { var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8); return v.toString(16); }); return guid; } /** * getPositionByUid * @description - get Position on Array by Uid * @example - this.FunctionsUtilService.getPositionByUid(expenses, expenseId); * @function * @params {Array<any>} array - list of data @params {string} uid - data uid * @return {number} index - Returns an index position on Array */ getPositionByUid(array, uid): number { let index = array.map(function(element){ return element.Uid; }).indexOf(uid); return index; } /** * groupByYear * @description - take an array and grouping it by Year * @function * @return {Array<any>} newArrayGroupedByYear - Returns an array grouped by Year */ groupByYear(array): any { let newArrayGroupedByYear = _.groupBy(array, function(item:any) { return item.dateCreated.year; }); return newArrayGroupedByYear; } /** * arrayToObject * @description - change an Array to firebase object. * @example - array = [{title: 'text'}, {title: 'text'}] return firebaseObject = { 367990d1-258b-404a-aa32-b29125fcde3e: {title: 'text'}, e8f703e7-6970-462c-88ae-66d1e9bf4792: {title: 'text'} } * @function * @params {Array<any>} array - list of data * @return {Array<any>} newArrayGroupedByYear - Returns an array grouped by Year */ arrayToObject(array): any { let newObject = {}; for (let i = 0; i < array.length; ++i) { if (array[i] !== undefined) { newObject[array[i].uid] = array[i]; } } return newObject; } } /*-- MODULE DEFINITION --*/ angular .module('finApp.core.util') .service(FunctionsUtilService.serviceId, FunctionsUtilService); } <file_sep>/** * SessionService * @description - Session Service * @function * @param {app.core.firebase.FirebaseFactory} FirebaseFactory - Firebase connections. * @param {AngularFireAuthService} $firebaseAuth - AngularFire methods. */ module app.auth { 'use strict'; /**********************************/ /* INTERFACES */ /**********************************/ export interface ISessionService { getAuthData:() => string; } /****************************************/ /* CLASS DEFINITION */ /****************************************/ export class SessionService implements ISessionService { static serviceId = 'mainApp.auth.SessionService'; /**********************************/ /* PROPERTIES */ /**********************************/ private _authData: string = JSON.parse(this.localStorage.getItem('session.authData')); // -------------------------------- /*-- INJECT DEPENDENCIES --*/ static $inject = ['mainApp.localStorageService']; /**********************************/ /* CONSTRUCTOR */ /**********************************/ constructor(private localStorage) { console.log('session service called'); } /**********************************/ /* METHODS */ /**********************************/ /** * get AuthData * @description - Return data user session Authenticated * @get * @return {string} this._authData - user session authenticated */ getAuthData(): string { return this._authData; } } /*-- MODULE DEFINITION --*/ angular .module('mainApp.auth', []) .service(SessionService.serviceId, SessionService); } <file_sep>/** * customPopupService * @description - Service invoke custom Popup * @constructor */ module app.core.util.customPopup { 'use strict'; /**********************************/ /* INTERFACES */ /**********************************/ export interface ICustomPopupService { invokeCardRewardPopup: (scope: any, popupConfig: app.interfaces.IPopup) => void; invokeCardResultPopup: (scope: any, popupConfig: app.interfaces.IPopup) => void; } /****************************************/ /* CLASS DEFINITION */ /****************************************/ export class CustomPopupService implements ICustomPopupService { static serviceId = 'mainApp.core.util.CustomPopupService'; /**********************************/ /* PROPERTIES */ /**********************************/ // -------------------------------- /*-- INJECT DEPENDENCIES --*/ static $inject = ['$compile']; /**********************************/ /* CONSTRUCTOR */ /**********************************/ constructor(private $compile: angular.ICompileService) { console.log('customPopup service called'); } /**********************************/ /* METHODS */ /**********************************/ /** * invokeCardRewardPopup * @description - invoke Card Reward popUp * @use - this.customPopup.invokeCardRewardPopup(scope, popupConfig); * @function * @params {any} scope - parent scope * @params {app.interfaces.IPopup} popupConfig - popup config data */ invokeCardRewardPopup(scope, popupConfig): void { scope.cardRewardScope = scope.$new(); scope.cardRewardScope.popupConfig = popupConfig; var element = document.createElement("ma-card-reward-popup"); document.body.appendChild(element); this.$compile(element)(scope.cardRewardScope); } /** * invokeCardResultPopup * @description - invoke Card Result popUp * @use - this.customPopup.invokeCardResultPopup(scope, popupConfig); * @function * @params {any} scope - parent scope * @params {app.interfaces.IPopup} popupConfig - popup config data */ invokeCardResultPopup(scope, popupConfig): void { scope.cardResultScope = scope.$new(); scope.cardResultScope.popupConfig = popupConfig; var element = document.createElement("ma-card-result-popup"); document.body.appendChild(element); this.$compile(element)(scope.cardResultScope); } } /*-- MODULE DEFINITION --*/ angular .module('mainApp.core.util', []) .service(CustomPopupService.serviceId, CustomPopupService); } <file_sep>/** * AuthService * @description - Authorization Service * @function * @param {app.core.firebase.FirebaseFactory} FirebaseFactory - Firebase connections. * @param {AngularFireAuthService} $firebaseAuth - AngularFire methods. */ module app.auth { 'use strict'; /**********************************/ /* INTERFACES */ /**********************************/ export interface IAuthService { signUpPassword: (username: string, email: string, password: string) => void; } /****************************************/ /* CLASS DEFINITION */ /****************************************/ export class AuthService implements IAuthService { static serviceId = 'mainApp.auth.AuthService'; /**********************************/ /* PROPERTIES */ /**********************************/ // -------------------------------- /*-- INJECT DEPENDENCIES --*/ static $inject = ['$q', '$rootScope', '$http']; /**********************************/ /* CONSTRUCTOR */ /**********************************/ constructor(private session: ISessionService, private $q: any, $rootScope: app.core.interfaces.IFinAppRootScope, private $http: angular.IHttpService) { console.log('auth service called'); } /**********************************/ /* METHODS */ /**********************************/ /** * signUpPassword * @description - Create Account on Database * @function TODO: refactor this comment block * @params {app.interfaces.IUserDataAuth} currentDataUser - User Authenticated Data * @return {angular.IPromise<any>} promise - return user uid created promise */ signUpPassword (username, email, password): any { let self = this; let userData: app.core.interfaces.IUserDataAuth = { username: username, email: email, password: <PASSWORD> }; return this.$http.post('/api/v1/accounts/', { username: userData.username, password: <PASSWORD>, email: userData.email }); } } /*-- MODULE DEFINITION --*/ angular .module('mainApp.auth') .service(AuthService.serviceId, AuthService); } <file_sep>/** * SignUpPageController * @description - Sign up Page Controller */ module app.pages.signUpPage { /**********************************/ /* INTERFACES */ /**********************************/ export interface ISignUpPageController { form: ISignUpForm; error: ISignUpError; signUp: () => void; activate: () => void; } export interface ISignUpForm { username: string; email: string; password: string; } export interface ISignUpError { message: string; } /****************************************/ /* CLASS DEFINITION */ /****************************************/ export class SignUpPageController implements ISignUpPageController { static controllerId = 'mainApp.pages.signUpPage.SignUpPageController'; /**********************************/ /* PROPERTIES */ /**********************************/ form: ISignUpForm; error: ISignUpError; // -------------------------------- /*-- INJECT DEPENDENCIES --*/ public static $inject = [ '$state', '$filter', '$scope', 'mainApp.auth.AuthService']; /**********************************/ /* CONSTRUCTOR */ /**********************************/ constructor( private $state: ng.ui.IStateService, private $filter: angular.IFilterService, private $scope: angular.IScope, private AuthService: app.auth.IAuthService) { this._init(); } /*-- INITIALIZE METHOD --*/ private _init() { //Init form this.form = { username: '', email: '', password: '' }; this.error = { message: '' }; this.activate(); } /*-- ACTIVATE METHOD --*/ activate(): void { //LOG console.log('signUpPage controller actived'); } /**********************************/ /* METHODS */ /**********************************/ /* * Register Method * @description Create new user if current user doesn`t have an account */ signUp(): void { let self = this; this.AuthService.signUpPassword(this.form.username, this.form.email, this.form.password); } } /*-- MODULE DEFINITION --*/ angular .module('mainApp.pages.signUpPage') .controller(SignUpPageController.controllerId, SignUpPageController); } <file_sep>/** * module() Here inject dependencies of App modules and components, such as controllers, service, directive, etc * config() Here define the main state, routes, http interceptor * * @param {angular.ui.IUrlRouterProvider} $urlRouterProvider * @return {void} */ (function (): void { 'use strict'; angular .module('mainApp', [ 'mainApp.auth', 'mainApp.core', 'mainApp.core.util', 'mainApp.localStorage', 'mainApp.pages.signUpPage' ]) .config(config); function config($locationProvider: angular.ILocationProvider, $urlRouterProvider: angular.ui.IUrlRouterProvider, $translateProvider: angular.translate.ITranslateProvider) { $locationProvider.html5Mode(true); $locationProvider.hashPrefix('!'); $urlRouterProvider.otherwise('/page/tutorial'); /* Translate Provider */ let prefix = 'assets/i18n/'; let suffix = '.json'; $translateProvider.useStaticFilesLoader({ prefix: prefix, suffix: suffix }); $translateProvider.preferredLanguage('es'); } })(); <file_sep>var gulp = require('gulp'); var ts = require('gulp-typescript'); var sass = require('gulp-sass'); var sourcemaps = require('gulp-sourcemaps'); var autoprefixer = require('gulp-autoprefixer'); /*Path Files*/ var paths = { htmlTemplates: 'src/**/*.html', appTypescript: ['www/**/*.ts', '!typings/**/*.*'], appJs: ['www/**/*.js', 'www/**/*.js.map'], appSass: ['www/**/**/*.scss'], inputSass: 'www/app/app.scss', outputSass: 'www/app', sassdocOptions: {dest: './www/css/doc'} }; /** * SASS to CSS - based on http://www.sitepoint.com/simple-gulpy-workflow-sass/ * @desc This task take app.scss and transform this to .css, after that put each new .css into App_Web -> dist -> styles */ var sassOptions = { errLogToConsole: true }; gulp.task('sass', function() { gulp .src(paths.inputSass) .pipe(sourcemaps.init()) .pipe(sass(sassOptions).on('error', sass.logError)) .pipe(autoprefixer()) .pipe(sourcemaps.write()) .pipe(gulp.dest(paths.outputSass)) }); <file_sep>/** * {1:nameDirective} * @description - Some description * @constructor * @param {type} title - The title of the book. * @param {type} author - The author of the book. */ /* module {2:path.of.file} { 'use strict'; export interface {3:InterfaceDirective} extends ng.IDirective { } class {1:nameDirective} implements {3:InterfaceDirective} extends ng.IDirective { //directive config static directiveId = '{1: nameDirective}'; bindToController = true; controller = {9:NameClassController}.controllerId; controllerAs = 'vm'; restrict = 'EA'; scope = { //'example': '=' }; templateUrl = '{8:templateUrl}'; //inject dependencies static $inject = ['{4:dependency}']; //constructor receive the dependency as a parameter. //The parameter is marked as private (optional), so that it is available throughout the whole class constructor({4:dependency}: {6:dependencyType}) { } //instance method is a requirement from Angular, that needs a method that returns something as the registration function for factories and directives. static instance({4:dependency}: {6:dependencyType}): {3:InterfaceDirective} { return new {1:nameDirective}({4:dependency}); } } angular .module('{7:module}') .directive({1:nameDirective}.directiveId, {1:nameDirective}.instance); /*********************************************************/ /* CONTROLLER */ /*********************************************************/ /** * {9:NameClassController} * @description - Some description * @constructor * @param {type} title - The title of the book. * @param {type} author - The author of the book. */ /* interface {3:InterfaceController} { {10:property}: {5:type}; activate: () => void; } class {9:NameClassController} implements {3:InterfaceController} { static controllerId = '{7:module}.{9:NameClassController}'; {10:property}: {5:type}; //inject dependencies static $inject = ['{4:dependency}']; //constructor receive the dependency as a parameter. //The parameter is marked as private (optional), so that it is available throughout the whole class constructor(private {4:dependency}: {6:dependencyType}) { this.init(); } //init function to handle all initialization logic private init() { this.{10:property} = 'example'; this.activate(); } //active function to handle all controller logic activate(): void { } //methods {8:method} () { } } angular.module('{7:module}') .controller({9:NameClassController}.controllerId, {9:NameClassController}); } */<file_sep>/** * run() run low-level functionality * such as authorization, get user info, roles, etc. * * @param {scope} $rootScope * @param {ICurrentUser} currentUser * @return {void} */ (function (): void { 'use strict'; angular .module('mainApp') .run(run); run.$inject = ['$rootScope', 'dataConfig', '$http']; function run($rootScope: ng.IRootScopeService, dataConfig: IDataConfig, $http: any ): void { //TODO: Get these values from the logged user dataConfig.userId = 'id1234'; $http.defaults.xsrfHeaderName = 'X-CSRFToken'; $http.defaults.xsrfCookieName = 'csrftoken'; } })(); (function (angular) { function localStorageServiceFactory($window){ if($window.localStorage){ return $window.localStorage; } throw new Error('Local storage support is needed'); } // Inject dependencies localStorageServiceFactory.$inject = ['$window']; // Export angular .module('mainApp.localStorage', []) .factory('mainApp.localStorageService', localStorageServiceFactory); })(angular); <file_sep>/** * config() * @description - sign up page config file */ (function() { 'use strict'; angular .module('mainApp.pages.signUpPage', []) .config(config); function config($stateProvider: angular.ui.IStateProvider) { $stateProvider .state('page.signUp', { url: '/signUp', views: { 'container': { templateUrl: 'signUpPage.html', controller: 'mainApp.pages.signUpPage.SignUpPageController', controllerAs: 'vm' } }, params: { user: null }, parent: 'page' }); } })(); <file_sep>var app; (function (app) { var core; (function (core) { var util; (function (util) { var functionsUtil; (function (functionsUtil) { 'use strict'; var FunctionsUtilService = (function () { function FunctionsUtilService() { console.log('functionsUtil service called'); } FunctionsUtilService.splitDateFormat = function (date) { var dateString = moment(date).format('YYYY/MMM/DD').split('/'); var dateFormatted = { complete: date, day: dateString[2], month: dateString[1], year: dateString[0] }; return dateFormatted; }; FunctionsUtilService.prototype.dateMonthToString = function (date, zone) { var dateFormatted = new Date(date); var options = { month: "long" }; var month = dateFormatted.toLocaleDateString(zone, options); return month; }; FunctionsUtilService.prototype.formatCurrency = function (num, formatted) { var currency = { num: num, formatted: formatted }; if (currency.formatted) { currency.num = accounting.unformat(currency.formatted); } currency.formatted = accounting.formatMoney(currency.num, '$', 0); return currency; }; FunctionsUtilService.generateGuid = function () { var fmt = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'; var guid = fmt.replace(/[xy]/g, function (c) { var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8); return v.toString(16); }); return guid; }; FunctionsUtilService.prototype.getPositionByUid = function (array, uid) { var index = array.map(function (element) { return element.Uid; }).indexOf(uid); return index; }; FunctionsUtilService.prototype.groupByYear = function (array) { var newArrayGroupedByYear = _.groupBy(array, function (item) { return item.dateCreated.year; }); return newArrayGroupedByYear; }; FunctionsUtilService.serviceId = 'finApp.core.util.FunctionsUtilService'; return FunctionsUtilService; }()); functionsUtil.FunctionsUtilService = FunctionsUtilService; angular .module('finApp.core.util') .service(FunctionsUtilService.serviceId, FunctionsUtilService); })(functionsUtil = util.functionsUtil || (util.functionsUtil = {})); })(util = core.util || (core.util = {})); })(core = app.core || (app.core = {})); })(app || (app = {})); <file_sep>/** * {1:nameService} * @description - Some description * @constructor * @param {type} title - The title of the book. * @param {type} author - The author of the book. */ /* module {2:path.of.file} { 'use strict'; export interface {3:InterfaceService} { //properties {4:propety}: {5:type}; //methods {8:method}:({9:param}: {10:type}) => {11:typeReturn}; //third party {12:thirdMethod}: {13:type} //log: ng.ILogCall; } class {1:nameService} implements {3:InterfaceService} { static serviceId = '{7:module}.{1:nameService}'; {4:propety}: {5:type}; {12:thirdMethod}: {13:type}; //log: ng.ILogCall; //inject dependencies static $inject = ['{14:dependency}']; //constructor receive the dependency as a parameter. //The parameter is marked as private (optional), so that it is available throughout the whole class constructor(private {14:dependency}: {6:dependencyType}) { this.{4:property} = 'example'; } //methods {8:method}({9:param}: {10:type}): {11:typeReturn} { } //instance method is a requirement from Angular, that needs a method that returns something as the registration function for factories and directives. static instance({14:dependency}: {6:dependencyType}): {3:InterfaceService} { return new {1:nameService}({14:dependency}); } } angular .module('{7:module}') .factory({1:nameService}.serviceId, {1:nameService}.instance); } //More information: https://hstefanski.wordpress.com/2015/08/19/converting-an-angular-app-to-typescript-part-2/ */<file_sep>/** * values() Here we define each core variables * such as user logged Id, end points, etc * * @param {IDataConfig} dataConfig * @return {void} */ /*-- INTERFACE --*/ interface IDataConfig { baseUrl: string; salaryIncomeUrl: string; investmentIncomeUrl: string; businessIncomeUrl: string; neccesaryExpenseUrl: string; unneccesaryExpenseUrl: string; userId: string; } /*-- MAIN FUNCTION --*/ (function (): void { 'use strict'; var dataConfig: IDataConfig = { baseUrl: 'https://shining-fire-8072.firebaseio.com', salaryIncomeUrl: '/income/salary', investmentIncomeUrl: '/income/investment', businessIncomeUrl: '/income/business', neccesaryExpenseUrl: '/typeOfExpense/necessaries/', unneccesaryExpenseUrl: '/typeOfExpense/unnecessaries/', userId: '' }; angular .module('mainApp') .value('dataConfig', dataConfig); })(); <file_sep>/** * {1:NameClassController} * @description - Some description * @constructor * @param {type} title - The title of the book. * @param {type} author - The author of the book. */ /* module {2:path.of.file} { export interface {3:InterfaceController} { {9:property}: {5:type}; activate: () => void; } export class {1:NameClassController} implements {3:InterfaceController} { static controllerId = '{7:module}.{1:NameClassController}'; {9:property}: {5:type}; //inject dependencies static $inject = ['{4:dependency}']; //constructor receive the dependency as a parameter. //The parameter is marked as private (optional), so that it is available throughout the whole class constructor(private {4:dependency}: {6:dependencyType}) { this.init(); } //init function to handle all initialization logic private init() { this.{9:property} = 'example'; this.activate(); } //active function to handle all controller logic activate(): void { } //methods {8:method}(): {10:typeReturn} {} { } } angular .module('{7:module}') .controller({1:NameClassController}.controllerId, {1:NameClassController}); } //More information: https://hstefanski.wordpress.com/2015/07/22/converting-an-angular-app-to-typescript/ */<file_sep>/** * Specifies the Interfaces throughout App */ module app.core.interfaces { /*******************************/ /* ROOTSCOPE INTERFACE */ /*******************************/ export interface IFinAppRootScope extends angular.IRootScopeService { User: any; auth: any; session: any; } /*******************************/ /* USER DATA AUTH INTERFACE */ /*******************************/ export interface IUserDataAuth { username: string; email: string; password: string; } /*******************************/ /* DATE FORMATTED INTERFACE */ /*******************************/ export interface IDateFormatted { complete: string; day: string; month: string; year: string; } /********************************/ /* STATEPARAMS INTERFACES */ /********************************/ ///////////////////////////////// /********************************/ /* POPUPS INTERFACES */ /********************************/ export interface IPopup { subtitle?: string; textsList?: Array<string>; } } <file_sep>amqp==1.4.9 awscli==1.7.41 awsebcli==3.7.7 bcdoc==0.16.0 billiard==3.3.0.23 blessed==1.9.5 boto==2.41.0 botocore==1.4.37 cement==2.8.2 colorama==0.3.7 defusedxml==0.4.1 dj-database-url==0.4.1 dj-static==0.0.6 Django==1.10 django-appconf==1.0.1 django-argonauts==1.1.3 django-compressor==1.5 django-cors-headers==1.1.0 django-debug-toolbar==1.4 django-model-utils==2.5 djangorestframework==3.4.0 docopt==0.6.2 drf-nested-routers==0.9.0 ecdsa==0.13 jmespath==0.9.0 kombu==3.0.35 langdetect==1.0.5 paramiko==1.17.1 pathspec==0.3.4 prettytable==0.7.2 psycopg2==2.6.1 pyasn1==0.1.9 pycrypto==2.6.1 python-dateutil==2.5.3 requests==2.9.1 six==1.10.0 sqlparse==0.1.19 ssh==1.8.0 static3==0.6.1 texttable==0.8.4 wcwidth==0.1.7 websocket-client==0.37.0 wheel==0.24.0 <file_sep>/** * module() Here inject dependencies of Angular Modules and 3rd Party * * @param {none} * @return {void} */ (function (): void { 'use strict'; angular.module('mainApp.core', [ /*Angular Modules*/ 'ngCookies', 'ngResource', 'ngSanitize', 'ui.router', /*3rd Party*/ ]); })();
d7243d1aa069134389674fce22dff23caa7ebcdd
[ "JavaScript", "TypeScript", "Text" ]
17
TypeScript
sruda/angular-typescript-django-rest
470cd23f36528f9408a27b39a4e584c42a007ec2
5033bfb499ad3014058c83a62d62a03b9d8b840c
refs/heads/master
<file_sep>#ifndef TEXTURE_H #define TEXTURE_H struct texture { GLuint texture_id; } texture *texture_init( texture *txt, const char *fname); #endif <file_sep>CC = g++ CFLAGS = -pg -g -Wall -lGL -lGLEW -lSDL2 -lSDL2_image -lm all: cube.bin 3d_menge_grid_displacements.bin \ menge_sponge.cpp ../simple_obj_reader/bin_obj_reader.cpp \ ../simple_obj_reader/bin_obj_reader.hpp \ ../shader_compiler/shader_compiler.cpp \ ../shader_compiler/shader_compiler.hpp \ ../utils/utils.cpp ../utils/utils.hpp \ ../InputProcessor/InputProcessor.cpp \ ../InputProcessor/InputProcessor.hpp \ read_menge_grid.cpp read_menge_grid.hpp $(CC) menge_sponge.cpp ../simple_obj_reader/bin_obj_reader.cpp \ ../shader_compiler/shader_compiler.cpp \ ../utils/utils.cpp \ ../InputProcessor/InputProcessor.cpp \ read_menge_grid.cpp \ $(CFLAGS) -o menge_sponge cube.bin: ../simple_obj_reader/simple_obj_reader.cpp $(CC) ../simple_obj_reader/simple_obj_reader.cpp \ $(CFLAGS) -o ../simple_obj_reader/simple_obj_reader ../simple_obj_reader/simple_obj_reader cube.obj > cube.bin 3d_menge_grid_displacements.bin: gen_menge_grid.cpp $(CC) gen_menge_grid.cpp -o gen_menge_grid ./gen_menge_grid > 3d_menge_grid_displacements.bin clean: rm -f *.o menge_sponge gen_menge_grid <file_sep>#ifndef GEN_INPUT_PROCESSOR_H #define GEN_INPUT_PROCESSOR_H #include <SDL2/SDL.h> #include <set> #include <algorithm> enum binding_type { BINDING_ATOMIC, // press button to turn state on, // press again to switch off BINDING_CONTINUOUS, // press button and state turns on, // release and state turns off BINDING_ONE_TIME // press button and state turns on, // state must then be turned off // manually }; template <class states_enum> class binding { public: SDL_Keycode k; states_enum s; binding_type t; friend bool operator== (const binding &a, SDL_Keycode ck) { if (a.k == ck) { return true; } return false; } friend bool operator< (const binding &a, const binding &b) { if (a.k == b.k && a.s == b.s) { return false; } if (a.k <= b.k) { return true; } return false; } }; class BaseInputProcessor { }; template <class states_enum> class GenInputProcessor : public BaseInputProcessor { public: void test_meth(states_enum s); void add_key_binding(SDL_Keycode k, states_enum s, binding_type t); void rm_key_binding(SDL_Keycode k, states_enum s, binding_type t); void process_input(SDL_Event *event); bool is_state_active(states_enum s); void activate_state(states_enum s); void deactivate_state(states_enum s); private: std::set<binding<states_enum> > bindings; std::set<states_enum> active_states; }; template <class states_enum> void GenInputProcessor<states_enum>::test_meth( states_enum s) { binding<states_enum> b = { .s = s}; bindings.insert(b); } template <class states_enum> void GenInputProcessor<states_enum>::add_key_binding( SDL_Keycode k, states_enum s, binding_type t) { binding<states_enum> b = {.k = k, .s = s, .t = t}; bindings.insert(b); } template <class states_enum> void GenInputProcessor<states_enum>::rm_key_binding( SDL_Keycode k, states_enum s, binding_type t) { binding<states_enum> b = {.k = k, .s = s, .t = t}; bindings.erase(b); } #include <iostream> template <class states_enum> void GenInputProcessor<states_enum>::process_input(SDL_Event *event) { SDL_Keycode key = event->key.keysym.sym; typename std::set<binding<states_enum> >::iterator res = std::find(bindings.begin(), bindings.end(), key); while (res != bindings.end() && res->k == key) { if (event->key.type == SDL_KEYDOWN) { if (res->t == BINDING_ATOMIC && is_state_active(res->s)) { active_states.erase(res->s); res++; continue; } active_states.insert(res->s); } else if (event->key.type == SDL_KEYUP && res->t == BINDING_CONTINUOUS) { active_states.erase(res->s); } res++; } } template <class states_enum> bool GenInputProcessor<states_enum>::is_state_active(states_enum s) { if (active_states.find(s) != active_states.end()) { return true; } return false; } template <class states_enum> void GenInputProcessor<states_enum>::activate_state(states_enum s) { active_states.insert(s); } template <class states_enum> void GenInputProcessor<states_enum>::deactivate_state(states_enum s) { active_states.erase(s); } #endif <file_sep>#include "billboard.hpp" #define GLM_FORCE_RADIANS #include <glm/glm.hpp> #include <glm/gtc/matrix_inverse.hpp> #include <stdio.h> Billboard::Billboard( const BoalerVSLModelUnitLink &mother, BoalerVSLModelUnitLink &bb_vsl_model_link, GLfloat mother_radius ) : mother(&mother), bb_vsl_model_link(&bb_vsl_model_link), mother_radius(mother_radius), M_pre_translate(bb_vsl_model_link.model_unit->M) {} void Billboard::update_pos() { const glm::mat4 &mother_V = mother->vs_link->view_unit->V; const glm::mat4 &mother_P = mother->vs_link->view_unit->P; const glm::mat4 &mother_M = mother->model_unit->M; glm::vec4 bb_centre_point_screen_space = mother_P * mother_V * mother_M * glm::vec4(0.0f, mother_radius, 0.0f, 1.0f); bb_centre_point_screen_space /= bb_centre_point_screen_space.w; bb_centre_point_screen_space.z = 0; const glm::mat4 &bb_P = bb_vsl_model_link->vs_link->view_unit->P; bb_centre_point_screen_space = glm::inverseTranspose(bb_P) * bb_centre_point_screen_space; bb_vsl_model_link->model_unit->M = glm::translate( glm::mat4(1), glm::vec3(bb_centre_point_screen_space)) * M_pre_translate; } <file_sep>#include "mo_billboard.hpp" enum { WIN_W = 800, WIN_H = 600, FPS = 100 }; glm::mat4 MoBillboard::V = glm::mat4(1); glm::mat4 MoBillboard::P = glm::ortho( -WIN_W / 2.0f, // left WIN_W / 2.0f, // right -WIN_H / 2.0f, // bottom WIN_H / 2.0f, // top -0.1f, // near 100.0f // far ); BoalerViewUnit *MoBillboard::view_unit = NULL; BoalerModel *MoBillboard::model = NULL; BoalerVSLink *MoBillboard::vs_link = NULL; SDL_Surface *MoBillboard::bb_bg_img = NULL; SDL_Surface *MoBillboard::bb_bg_img_active = NULL; SDL_Surface *MoBillboard::bb_bg_img_rotate = NULL; int MoBillboard::bb_w = 40; int MoBillboard::bb_h = 50; SDL_Rect MoBillboard::txt_rect = { .x = 0, .y = 12, .w = bb_w, .h = bb_h }; void MoBillboard::prep( MoEng *eng, BoalerShaderUnit &shader_unit ) { view_unit = new BoalerViewUnit(V, P); eng->beng.reg_view_unit(view_unit); model = new BoalerModel("square.bin"); vs_link = new BoalerVSLink( *view_unit, shader_unit); bb_bg_img = IMG_Load("resources/id_bb_bg.png"); bb_bg_img_active = IMG_Load("resources/id_bb_bg_active.png"); bb_bg_img_rotate = IMG_Load("resources/id_bb_bg_rotate.png"); } MoBillboard::MoBillboard( const BoalerVSLModelUnitLink &mother_vslm_link, int shape_id, GLfloat r_bb) : shape_id(shape_id), text_texture(TextTexture(txt_rect, bb_bg_img)), model_unit(BoalerModelUnit( glm::scale(glm::mat4(1), glm::vec3(bb_w, bb_h, 1.0f)), 3, text_texture.texture_id, *model)), vslm_link(BoalerVSLModelUnitLink(*vs_link, model_unit)), bb(Billboard(mother_vslm_link, vslm_link, r_bb)) { char tmp_string[150]; sprintf(tmp_string, "<span color='white'>%d</span>", shape_id); text_texture.set_text(tmp_string); } void MoBillboard::set_to_active() { text_texture.bg_img = bb_bg_img_active; char tmp_string[150]; sprintf(tmp_string, "<span color='black'>%d</span>", shape_id); text_texture.set_text(tmp_string); } void MoBillboard::set_to_rotate() { text_texture.bg_img = bb_bg_img_rotate; char tmp_string[150]; sprintf(tmp_string, "<span color='black'>%d</span>", shape_id); text_texture.set_text(tmp_string); } void MoBillboard::set_to_normal() { text_texture.bg_img = bb_bg_img; char tmp_string[150]; sprintf(tmp_string, "<span color='white'>%d</span>", shape_id); text_texture.set_text(tmp_string); } <file_sep>#include <vector> #include <GL/glew.h> #include <GL/gl.h> #define GLM_FORCE_RADIANS #include <glm/glm.hpp> #include <glm/gtc/matrix_transform.hpp> #include <SDL2/SDL.h> #include <SDL2/SDL_opengl.h> #include <SDL2/SDL_image.h> #include <stdlib.h> #include <stdio.h> #include "../simple_obj_reader/bin_obj_reader.hpp" #include "../shader_compiler/shader_compiler.hpp" #include "../utils/utils.hpp" #include "../InputProcessor/InputProcessor.hpp" #include "read_menge_grid.hpp" #include <iostream> #define DEBUG_MODE int main() { SDL_Event event; init_sdl_gl_window(800, 600, "Menge Sponge"); bool carry_on = true; std::vector<GLuint> element_array; std::vector<glm::vec3> vertices; std::vector<glm::vec2> uvs; std::vector<glm::vec3> normals; std::vector<glm::vec3> ordered_vertices; std::vector<GLuint> element_array_vertices_ordered_vertices_map; GLuint vao; glGenVertexArrays(1, &vao); glBindVertexArray(vao); bin_obj_read( "cube.bin", element_array, vertices, uvs, normals, &ordered_vertices, &element_array_vertices_ordered_vertices_map); GLuint shader_program = compile_shader( "../shaders/basic_shading.vertexshader", "../shaders/basic_shading.fragmentshader"); glUseProgram(shader_program); GLuint element_bo; glGenBuffers(1, &element_bo); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, element_bo); glBufferData( GL_ELEMENT_ARRAY_BUFFER, element_array.size() * sizeof(element_array[0]), &element_array[0], GL_STATIC_DRAW); GLuint vertex_bo, uv_bo, normal_bo; glGenBuffers(1, &vertex_bo); glBindBuffer(GL_ARRAY_BUFFER, vertex_bo); glBufferData( GL_ARRAY_BUFFER, vertices.size() * sizeof(vertices[0]), &vertices[0][0], GL_STATIC_DRAW); GLint pos_attrib = glGetAttribLocation(shader_program, "position_modelspace"); glVertexAttribPointer(pos_attrib, 3, GL_FLOAT, GL_FALSE, 0, 0); glEnableVertexAttribArray(pos_attrib); glGenBuffers(1, &uv_bo); glBindBuffer(GL_ARRAY_BUFFER, uv_bo); glBufferData( GL_ARRAY_BUFFER, uvs.size() * sizeof(uvs[0]), &uvs[0][0], GL_STATIC_DRAW); GLint uv_attrib = glGetAttribLocation(shader_program, "uv"); glVertexAttribPointer(uv_attrib, 2, GL_FLOAT, GL_FALSE, 0, 0); glEnableVertexAttribArray(uv_attrib); glGenBuffers(1, &normal_bo); glBindBuffer(GL_ARRAY_BUFFER, normal_bo); glBufferData( GL_ARRAY_BUFFER, normals.size() * sizeof(normals[0]), &normals[0][0], GL_STATIC_DRAW); GLint normal_attrib = glGetAttribLocation(shader_program, "normal_modelspace"); glVertexAttribPointer(normal_attrib, 3, GL_FLOAT, GL_FALSE, 0, 0); glEnableVertexAttribArray(normal_attrib); GLuint instance_model_bo; glGenBuffers(1, &instance_model_bo); std::vector<glm::vec3> instance_displacements; bin_menge_grid_read( "3d_menge_grid_displacements.bin", instance_displacements); std::cout << instance_displacements.size(); glBindBuffer(GL_ARRAY_BUFFER, instance_model_bo); glBufferData( GL_ARRAY_BUFFER, instance_displacements.size() * sizeof(instance_displacements[0]), &instance_displacements[0][0], GL_STATIC_DRAW); GLint instance_displacement_attrib = glGetAttribLocation(shader_program, "instance_displacement"); glEnableVertexAttribArray(instance_displacement_attrib); glVertexAttribPointer( instance_displacement_attrib, 3, GL_FLOAT, GL_FALSE, 0,0); glVertexAttribDivisor(instance_displacement_attrib, 1); GLuint texture_id = load_texture("resources/cube_texture.png"); GLuint sampler_id = glGetUniformLocation( shader_program, "texture_sampler"); InputProcessor in_processor(0.001, 0.001, glm::vec3(0.0, 0.0, 4)); glm::mat4 model = glm::mat4(1.0f); glm::mat4 view = in_processor.get_view_mat(); glm::mat4 projector = in_processor.get_proj_mat(); glm::vec3 light_position_worldspace = glm::vec3(2.0, 2.0, 2.0); GLuint light_pos_id = glGetUniformLocation(shader_program, "light_position_cameraspace"); glm::vec3 light_position_cameraspace(view * glm::vec4(light_position_worldspace, 1.0)); GLuint V_id = glGetUniformLocation(shader_program, "V"); glm::mat4 V = view; GLuint P_id = glGetUniformLocation(shader_program, "P"); glm::mat4 P = projector; // Bind our texture in Texture Unit 0 glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, texture_id); // Set our sampler to use Texture Unit 0 glUniform1i(sampler_id, GL_TEXTURE0); Uint32 curr_time = SDL_GetTicks(); Uint32 last_time = SDL_GetTicks(); while(carry_on) { curr_time = SDL_GetTicks(); in_processor.compute_direction((double)(curr_time - last_time)); last_time = curr_time; glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); view = in_processor.get_view_mat(); projector = in_processor.get_proj_mat(); P = projector; glUniformMatrix4fv(P_id, 1, GL_FALSE, &P[0][0]); V = view; glUniformMatrix4fv(V_id, 1, GL_FALSE, &V[0][0]); glm::vec3 light_position_cameraspace(view * glm::vec4(light_position_worldspace, 1.0)); glUniform3f(light_pos_id, light_position_cameraspace.x, light_position_cameraspace.y, light_position_cameraspace.z); glDrawElementsInstanced(GL_TRIANGLES, element_array.size(), GL_UNSIGNED_INT, 0, instance_displacements.size()); #ifdef DEBUG_MODE glUseProgram(0); // Draw normals glMatrixMode(GL_PROJECTION); glLoadMatrixf((const GLfloat*)&projector[0]); glMatrixMode(GL_MODELVIEW); glm::mat4 MV = view * model; glLoadMatrixf((const GLfloat*)&MV[0]); glColor3f(0,0,1); glBegin(GL_LINES); for (unsigned int i=0; i<element_array.size(); i++){ glm::vec3 p = vertices[element_array[i]]; glVertex3fv(&p.x); glm::vec3 o = glm::normalize(normals[element_array[i]]); p+=o*0.1f; glVertex3fv(&p.x); } glEnd(); // Draw line pointing to light position glMatrixMode(GL_MODELVIEW); glLoadMatrixf((const GLfloat*)&view); glColor3f(1,0,0); glBegin(GL_LINES); glm::vec3 p = light_position_worldspace; glVertex3fv(&p.x); p = glm::vec3(0, 0, 0); glVertex3fv(&p.x); glEnd(); glUseProgram(shader_program); #endif swap_sdl_gl_window(); while (SDL_PollEvent(&event)) { if (event.type == SDL_QUIT) { carry_on = false; } in_processor.process_event(&event); } } destroy_sdl_gl_window(); } <file_sep>CC = g++ CFLAGS = -pg -g -Wall -lGL -lGLEW -lSDL2 -lSDL2_image -lm -ljson-c `pkg-config --cflags --libs pangocairo` all: shark.bin toblerone_fish.bin \ multi_object_draw.cpp ../boaler/boaler.cpp \ ../boaler/boaler.hpp \ ../simple_obj_reader/bin_obj_reader.cpp \ ../simple_obj_reader/bin_obj_reader.hpp \ ../shader_compiler/shader_compiler.cpp \ ../shader_compiler/shader_compiler.hpp \ ../utils/utils.cpp ../utils/utils.hpp \ ../InputProcessor/gen_input_processor.hpp \ ../cameras/fp_camera.cpp ../cameras/fp_camera.hpp \ ../billboard/billboard.cpp ../billboard/billboard.hpp \ ../text_texture/text_texture.cpp ../text_texture/text_texture.hpp \ mo_billboard.cpp mo_billboard.hpp \ ../utils/base_eng/base_eng.cpp \ ../utils/base_eng/base_eng.hpp \ mo_eng.hpp mo_eng.cpp $(CC) multi_object_draw.cpp ../boaler/boaler.cpp \ ../simple_obj_reader/bin_obj_reader.cpp \ ../shader_compiler/shader_compiler.cpp \ ../utils/utils.cpp \ ../cameras/fp_camera.cpp \ ../billboard/billboard.cpp \ ../text_texture/text_texture.cpp \ mo_billboard.cpp \ ../utils/base_eng/base_eng.cpp \ mo_eng.cpp \ $(CFLAGS) -o multi_object_draw simple_obj_reader: ../simple_obj_reader/simple_obj_reader.cpp $(CC) ../simple_obj_reader/simple_obj_reader.cpp \ $(CFLAGS) -o ../simple_obj_reader/simple_obj_reader shark.bin: simple_obj_reader ../simple_obj_reader/simple_obj_reader \ resources/fishbowl/shark/shark.obj > \ resources/fishbowl/shark/shark.bin toblerone_fish.bin: simple_obj_reader ../simple_obj_reader/simple_obj_reader \ resources/fishbowl/toblerone_fish/toblerone_fish.obj > \ resources/fishbowl/toblerone_fish/toblerone_fish.bin clean: rm -f *.o multi_object_draw <file_sep>#ifndef BOALER_H #define BOALER_H #include <vector> #include <GL/glew.h> #include <GL/gl.h> #define GLM_FORCE_RADIANS #include <glm/glm.hpp> #include <glm/gtc/matrix_transform.hpp> #include <glm/gtx/transform.hpp> typedef class BoalerVSLink BoalerVSLink; typedef class BoalerVSLModelUnitLink BoalerVSLModelUnitLink; // BoalerModel class BoalerModel { public: BoalerModel( const char *bin_model_fname); // std::vector and buffer object for storing the element // array data std::vector<GLuint> element_array; GLuint element_array_bo; // std::vector of positions ordered in the same way that they // are declared in the *.obj file that contains the model std::vector<glm::vec3> ordered_positions; // std::vector and buffer object // for storing the position vertex data std::vector<glm::vec3> positions; GLuint position_bo; // std::vector with size = positions.size() where each element // gives the index of the ordered_positions // vertex that is the same as the positions vertex corresponding // to that element std::vector<GLuint> element_array_positions_ordered_positions_map; // std::vector, buffer object and shader attribute variable // for storing the texture coordinate data std::vector<glm::vec2> uvs; GLuint uv_bo; // std::vector, buffer object and shader attribute variable // for storing the normals coordinate data std::vector<glm::vec3> normals; GLuint normal_bo; }; class BoalerModelUnit { public: BoalerModelUnit( glm::mat4 M, unsigned int texture_unit_index, GLuint texture_id, BoalerModel &model); // Model unit's model matrix glm::mat4 M; unsigned int texture_unit_index; GLuint texture_id; // Pointer to the linked model BoalerModel *model; }; class BoalerShaderUnit { public: BoalerShaderUnit(GLuint program_id); // Reference to shader unit's program GLuint program_id; // References to model unit's shader's position, uv and // normal attributes GLint position_attr; GLint uv_attr; GLint normal_attr; // References to shader program's M, V and P // uniforms GLuint M_unfm; GLuint V_unfm; GLuint P_unfm; GLuint texture_sampler_unfm; }; class BoalerViewUnit { public: BoalerViewUnit( glm::mat4 V, glm::mat4 P); // vector to list of view unit's shader units std::vector<BoalerVSLink *> shader_links; // view unit's view and projection matrices glm::mat4 V; glm::mat4 P; void render(); private: }; class BoalerVSLink { public: BoalerVSLink( BoalerViewUnit &view_unit, BoalerShaderUnit &shader_unit); virtual ~BoalerVSLink(); // References to the link's view and shader units BoalerViewUnit *view_unit; BoalerShaderUnit *shader_unit; // Handler method that is called and links the ViewUnit's // member variables with the shader's uniforms virtual void shader_unit_linker(); // list of VS link - model unit links that should be rendered with this shader and view unit std::vector<BoalerVSLModelUnitLink *> model_unit_links; }; class BoalerVSLModelUnitLink { public: BoalerVSLModelUnitLink( BoalerVSLink &vs_link, BoalerModelUnit &model_unit); virtual ~BoalerVSLModelUnitLink(); void update_model_unit(BoalerModelUnit &model_unit); // Pointers to the linked VS link and model unit BoalerVSLink *vs_link; BoalerModelUnit *model_unit; // Reference to this vertex array object that links this // model unit with the shader referenced through this link GLuint vao; virtual void model_unit_linker(); void render(); }; class BoalerEng { public: std::vector<BoalerModel *> models; std::vector<BoalerModelUnit *> model_units; std::vector<BoalerShaderUnit *> shader_units; std::vector<BoalerViewUnit *> view_units; void reg_view_unit(BoalerViewUnit *vu); void reg_shader_unit(BoalerShaderUnit *su); void reg_model(BoalerModel *m); void reg_model_unit(BoalerModelUnit *m); void render(); }; #endif <file_sep>#ifndef UTILS_H #define UTILS_H typedef struct GL_Rect { GLfloat x, y, w, h; } GL_Rect; #endif <file_sep>#include "InputProcessor.hpp" #include <iostream> InputProcessor::InputProcessor( double speed, double omega, const glm::vec3 &position) : actions(0), theta(M_PI), phi(0) { this->speed = speed; this->omega = omega; this->position = position; } enum { UP_PRESSED = 1, DOWN_PRESSED = 1<<1, LEFT_PRESSED = 1<<2, RIGHT_PRESSED = 1<<3, FORWARD_PRESSED = 1<<4 }; void InputProcessor::process_event(SDL_Event *event) { switch(event->key.keysym.sym) { case SDLK_UP: if (event->key.type == SDL_KEYDOWN) { this->actions |= UP_PRESSED; } else { this->actions ^= UP_PRESSED; } break; case SDLK_DOWN: if (event->key.type == SDL_KEYDOWN) { this->actions |= DOWN_PRESSED; } else { this->actions ^= DOWN_PRESSED; } break; case SDLK_LEFT: if (event->key.type == SDL_KEYDOWN) { this->actions |= LEFT_PRESSED; } else { this->actions ^= LEFT_PRESSED; } break; case SDLK_RIGHT: if (event->key.type == SDL_KEYDOWN) { this->actions |= RIGHT_PRESSED; } else { this->actions ^= RIGHT_PRESSED; } break; case SDLK_a: if (event->key.type == SDL_KEYDOWN) { this->actions |= FORWARD_PRESSED; } else { this->actions ^= FORWARD_PRESSED; } default: break; } } void InputProcessor::compute_direction(double dt) { double dtheta = 0, dphi = 0, dr = 0; if (this->actions == 0) { return; } if (this->actions & UP_PRESSED) { dphi += 1; } if (this->actions & DOWN_PRESSED) { dphi -= 1; } if (this->actions & LEFT_PRESSED) { dtheta += 1; } if (this->actions & RIGHT_PRESSED) { dtheta -= 1; } if (this->actions & FORWARD_PRESSED) { dr += 1; } this->position.x += dr * sin(this->theta) * cos(this->phi) * this->speed * dt; this->position.y += dr * sin(this->phi) * this->speed * dt; this->position.z += dr * cos(this->theta) * cos(this->phi) * this->speed * dt; // this->position.z += dr * this->speed * dt; if (dtheta == 0 && dphi == 0) { return; } double mag = sqrt(dtheta * dtheta + dphi * dphi); this->theta += dtheta/mag * this->omega * dt; this->phi += dphi/mag * this->omega * dt; } glm::mat4 InputProcessor::get_view_mat() { glm::vec3 looking_dn; glm::vec3 up_dn; looking_dn.x = sin(this->theta) * cos(this->phi); looking_dn.y = sin(this->phi); looking_dn.z = cos(this->theta) * cos(this->phi); up_dn.x = -sin(this->theta) * sin(this->phi); up_dn.y = cos(this->phi); up_dn.z = -cos(this->theta) * sin(this->phi); // std::cout << this->position.x << ',' << this->position.y << ',' << this->position.z << '\n'; return glm::lookAt( this->position, this->position + looking_dn, up_dn); } glm::mat4 InputProcessor::get_proj_mat() { return glm::perspective(44.9f, 4.0f / 3.0f, 0.1f, 100.0f); } <file_sep>#ifndef MO_BILLBOARD_H #define MO_BILLBOARD_H #include <GL/glew.h> #include <GL/gl.h> #include <SDL2/SDL.h> #include <SDL2/SDL_opengl.h> #include <SDL2/SDL_image.h> #include "../boaler/boaler.hpp" #include "../text_texture/text_texture.hpp" #include "../billboard/billboard.hpp" #include "mo_eng.hpp" typedef class MoEng MoEng; class MoBillboard { public: static void prep( MoEng *eng, BoalerShaderUnit &shader_unit); MoBillboard( const BoalerVSLModelUnitLink &mother_vslm_link, int shape_id, GLfloat r_bb); void set_to_active(); void set_to_rotate(); void set_to_normal(); static glm::mat4 V; static glm::mat4 P; static BoalerViewUnit *view_unit; static BoalerModel *model; static BoalerVSLink *vs_link; static SDL_Surface *bb_bg_img; static SDL_Surface *bb_bg_img_active; static SDL_Surface *bb_bg_img_rotate; static int bb_w; static int bb_h; static SDL_Rect txt_rect; int shape_id; TextTexture text_texture; BoalerModelUnit model_unit; BoalerVSLModelUnitLink vslm_link; Billboard bb; }; #endif <file_sep>#ifndef BIN_OBJ_READER_H #define BIN_OBJ_READER_h #include <vector> #include <GL/gl.h> #define GLM_FORCE_RADIANS #include <glm/glm.hpp> void bin_obj_read( const char *path, std::vector<GLuint> &element_array, std::vector<glm::vec3> &vertices, std::vector<glm::vec2> &uvs, std::vector<glm::vec3> &normals, std::vector<glm::vec3> *ordered_vertices = NULL, std::vector<GLuint> *element_array_vertices_ordered_vertices_map = NULL ); #endif <file_sep>#ifndef READ_MENGE_GRID_H #define READ_MENGE_GRID_H #include <vector> #define GLM_FORCE_RADIANS #include <glm/glm.hpp> void bin_menge_grid_read( const char *path, std::vector<glm::vec3> &displacements ); #endif <file_sep>Hooke Cloth =========== A cloth simulation based on particles connected by springs <file_sep>#ifndef HOOKE_CLOTH_ENG_H #define HOOKE_CLOTH_ENG_H #include "../utils/base_eng/base_eng.hpp" #include <vector> #include <GL/glew.h> #include <GL/gl.h> #define GLM_FORCE_RADIANS #include <glm/glm.hpp> class Cloth; class ClothPt; class ClothPt { public: ClothPt *right; ClothPt *above; Cloth *cloth; glm::vec3 *r; glm::vec3 v; glm::vec3 a; void calc_force(); void iterate(); ClothPt(); ClothPt(Cloth *cloth, glm::vec3 *r); }; class Cloth { public: BaseEng &eng; unsigned int pts_w; unsigned int pts_h; std::vector<glm::vec3> vertices; std::vector<ClothPt> cloth_pts; double g_frame_unit; double hooke_constant_frame_unit; double damping_constant_frame_unit; double equil_length; void calc_force(); void iterate(); void load_into_buffer(GLuint buffer); Cloth( BaseEng &eng, unsigned int pts_w, unsigned int pts_h, std::vector<glm::vec3> &points, double g, double hooke_constant, double damping_constant, double equil_length); void add_fixed_pt(unsigned int x, unsigned int y); private: void init_points(std::vector<glm::vec3> &points); std::vector<unsigned int> fixed_pts; }; #endif <file_sep>CC = g++ CFLAGS = -pg -g -Wall -lGL -lGLEW -lSDL2 -lSDL2_image -lm all: cloth.bin cursor.bin \ hooke_cloth.cpp hooke_cloth_eng.cpp \ hooke_cloth_eng.hpp \ ../simple_obj_reader/bin_obj_reader.cpp \ ../simple_obj_reader/bin_obj_reader.hpp \ ../shader_compiler/shader_compiler.cpp \ ../shader_compiler/shader_compiler.hpp \ ../utils/utils.cpp ../utils/utils.hpp \ ../InputProcessor/InputProcessor.cpp \ ../InputProcessor/InputProcessor.hpp \ ../utils/base_eng/base_eng.cpp \ ../utils/base_eng/base_eng.hpp \ drawable.hpp drawable.cpp $(CC) hooke_cloth.cpp hooke_cloth_eng.cpp \ ../simple_obj_reader/bin_obj_reader.cpp \ ../shader_compiler/shader_compiler.cpp \ ../utils/utils.cpp \ ../InputProcessor/InputProcessor.cpp \ ../utils/base_eng/base_eng.cpp \ drawable.cpp \ $(CFLAGS) -o hooke_cloth cloth.obj: gen_cloth.cpp $(CC) gen_cloth.cpp -o gen_cloth ./gen_cloth > cloth.obj cloth.bin: ../simple_obj_reader/simple_obj_reader.cpp cloth.obj $(CC) ../simple_obj_reader/simple_obj_reader.cpp \ $(CFLAGS) -o ../simple_obj_reader/simple_obj_reader ../simple_obj_reader/simple_obj_reader cloth.obj > cloth.bin cursor.bin: ../simple_obj_reader/simple_obj_reader.cpp $(CC) ../simple_obj_reader/simple_obj_reader.cpp \ $(CFLAGS) -o ../simple_obj_reader/simple_obj_reader ../simple_obj_reader/simple_obj_reader cursor.obj > cursor.bin clean: rm -f *.o menge_sponge gen_menge_grid <file_sep>#include "read_menge_grid.hpp" #include <stdio.h> void bin_menge_grid_read( const char *path, std::vector<glm::vec3> &displacements ) { FILE *fp = fopen(path, "r"); int displacements_array_size; fscanf(fp, "%d \n", &displacements_array_size); displacements.resize(displacements_array_size); fread( &displacements[0], sizeof(displacements[0]), displacements_array_size, fp); fclose(fp); } <file_sep>#ifndef BASE_ENG_H #define BASE_ENG_H #include <stdbool.h> #include <GL/glew.h> #include <GL/gl.h> #include <SDL2/SDL.h> #include <SDL2/SDL_opengl.h> #include "../../InputProcessor/gen_input_processor.hpp" class BaseEng { public: SDL_Window *window; SDL_GLContext main_context; unsigned int fps; unsigned int current_frame; unsigned int frames_last_render_loop; bool should_continue_logic_loops(); BaseInputProcessor *base_input_processor; BaseEng( int w, int h, const char *window_title, unsigned int fps, BaseInputProcessor *input_processor); ~BaseEng(); private: bool should_start_logic_loop; unsigned int whole_frames_to_do; Uint32 start_time; void init_for_global_loop(); }; #endif <file_sep>#define DEBUG #include "engine.h" #include <GL/glew.h> #include <GL/gl.h> #include <SDL2/SDL.h> #include <SDL2/SDL_opengl.h> #include <SDL2/SDL_image.h> void setup_sprite_vertex_data(); void setup_shader(); void setup_projection_matrix(); void setup_uniforms(); void setup_attributes(); void setup_texture_params(); void setup_textures(); void setup_decals(); void setup_actors(); void setup_bindings(); bool should_continue_logic_loops(); engine *engine_init( unsigned int w, unsigned int h, const char *window_title, unsigned int fps) { eng.fps = fps; eng.current_frame = 0; eng.start_time = 0; eng.should_start_logic_loop = true; eng.whole_frames_to_do = 0; if(SDL_Init(SDL_INIT_VIDEO) == -1){ fprintf( stderr, "Video initialisation failed: %s\n", SDL_GetError()); return NULL; } eng.window = SDL_CreateWindow( window_title, SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, w, h, SDL_WINDOW_OPENGL); eng.w = w; eng.h = h; if(eng.window == NULL) { fprintf( stderr, "Window could not be created: %s\n", SDL_GetError()); return NULL; } eng.main_context = SDL_GL_CreateContext(eng.window); glewExperimental = GL_TRUE; if (glewInit() != GLEW_OK) { fprintf(stderr, "Failed to initialize GLEW\n"); exit(1); } SDL_GL_SetSwapInterval(1); glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); setup_sprite_vertex_data(); setup_shader(); setup_projection_matrix(); setup_uniforms(); setup_attributes(); setup_textures(); setup_decals(); setup_bindings(); eng.render_list = NULL; eng.logic_list = NULL; setup_actors(); return &eng; } void engine_destroy() { SDL_GL_DeleteContext(eng.main_context); SDL_DestroyWindow(eng.window); SDL_Quit(); } void engine_start() { bool carry_on = true; eng.start_time = SDL_GetTicks(); while (carry_on) { process_input(); if (is_state_active(GS_QUIT)) { carry_on = false; } glClearColor(0.0f, 0.0f, 0.0f, 1.0f); glClear(GL_COLOR_BUFFER_BIT); actor_list *al; for (al = eng.render_list; al != NULL; al = al->next) { al->a->render_handler(al->a); } SDL_GL_SwapWindow(eng.window); while (should_continue_logic_loops()) { for (al = eng.logic_list; al != NULL; al = al->next) { al->a->logic_handler(al->a); } } } } void setup_sprite_vertex_data() { GLfloat vertices[] = { -1.0f, -1.0f, 1.0f, -1.0f, -1.0f, 1.0f, -1.0f, 1.0f, 1.0f, -1.0f, 1.0f, 1.0f } ; glGenBuffers(1, &(eng.sprite_vertex_bo)); glBindBuffer(GL_ARRAY_BUFFER, eng.sprite_vertex_bo); glBufferData( GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW); } void setup_shader() { char simple_vertexshader[] = { #include "simple_vertexshader.h" }; const char * p_simple_vertexshader = simple_vertexshader; char simple_fragmentshader[] = { #include "simple_fragmentshader.h" }; const char * p_simple_fragmentshader = simple_fragmentshader; GLuint vao; glGenVertexArrays(1, &vao); glBindVertexArray(vao); GLuint vertex_shader = glCreateShader(GL_VERTEX_SHADER); glShaderSource(vertex_shader, 1, &(p_simple_vertexshader), NULL); glCompileShader(vertex_shader); GLuint fragment_shader = glCreateShader(GL_FRAGMENT_SHADER); glShaderSource(fragment_shader, 1, &(p_simple_fragmentshader), NULL); glCompileShader(vertex_shader); eng.shader_program = glCreateProgram(); glAttachShader(eng.shader_program, vertex_shader); glAttachShader(eng.shader_program, fragment_shader); glLinkProgram(eng.shader_program); glUseProgram(eng.shader_program); #ifdef DEBUG GLint status; glGetShaderiv(vertex_shader, GL_COMPILE_STATUS, &status); char buffer[512]; glGetShaderInfoLog(vertex_shader, 512, NULL, buffer); fprintf(stderr, "%s\n", buffer); glGetProgramInfoLog(eng.shader_program, 512, NULL, buffer); fprintf(stderr, "%s\n", buffer); #endif glBindBuffer(GL_ARRAY_BUFFER, eng.sprite_vertex_bo); GLint pos_attrib = glGetAttribLocation(eng.shader_program, "pos"); glVertexAttribPointer(pos_attrib, 2, GL_FLOAT, GL_FALSE, 0, 0); glEnableVertexAttribArray(pos_attrib); } void setup_projection_matrix() { GLfloat P[] = { 2/(float)eng.w, 0, 0, -1, 0, 2/(float)eng.h, 0, -1, 0, 0, 0, 0, 0, 0, 0, 1 }; GLint P_unfm = glGetUniformLocation(eng.shader_program, "P"); glUniformMatrix4fv(P_unfm, 1, GL_TRUE, P); } void setup_uniforms() { eng.w_unfm = glGetUniformLocation(eng.shader_program, "w"); eng.h_unfm = glGetUniformLocation(eng.shader_program, "h"); eng.r_unfm = glGetUniformLocation(eng.shader_program, "r"); eng.texture_sampler_unfm = glGetUniformLocation( eng.shader_program, "texture_sampler"); } void setup_attributes() { eng.pos_attrib = glGetAttribLocation(eng.shader_program, "pos"); eng.uv_attrib = glGetAttribLocation(eng.shader_program, "uv"); } void setup_texture_params() { // Possible values: // GL_REPEAT // GL_MIRRORED_REPEAT // GL_CLAMP_TO_EDGE // GL_CLAMP_TO_BORDER glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glGenerateMipmap(GL_TEXTURE_2D); } void setup_textures() { char * filenames[] = { "img/sand.png", "img/sprites.png" }; int i; glGenTextures(NUM_TEXTURES, eng.textures); for (i = 0; i < sizeof(filenames) / sizeof(filenames[0]); i++) { char * fname = filenames[i]; SDL_Surface *img = IMG_Load(fname); if(!img){ fprintf(stderr, "Error! Could not load %s\n", fname); exit(1); } glActiveTexture(GL_TEXTURE0 + i); glBindTexture(GL_TEXTURE_2D, eng.textures[i]); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, img->w, img->h, 0, GL_RGBA, GL_UNSIGNED_BYTE, img->pixels); SDL_FreeSurface(img); setup_texture_params(); } } void setup_decals() { int i; for (i = 0; i < NUM_SPRITES_DECALS; i++) { GLfloat w = 1/8.; GLfloat h = 1/2.; GLfloat x = (float)(i % 8) * w; GLfloat y = (float)(i / 8) * h; decal_init( &eng.sprites_decals[i], SPRITES_TEXTURE, x, y, w, h); } decal_init( &(eng.sand_decal), SAND_TEXTURE, 0, 0, 1, 1); } void setup_actors() { snake_actor_init(&eng.snake_actor); eng.render_list = actor_list_add(eng.render_list, (actor *)(&eng.snake_actor)); eng.logic_list = actor_list_add(eng.logic_list, (actor *)(&eng.snake_actor)); apple_actor_init(&eng.apple_actor); eng.render_list = actor_list_add(eng.render_list, (actor *)(&eng.apple_actor)); background_actor_init(&eng.background_actor); eng.render_list = actor_list_add(eng.render_list, (actor *)(&eng.background_actor)); } bool should_continue_logic_loops() { if (eng.should_start_logic_loop) { unsigned int logic_loop_start_time = SDL_GetTicks(); double elapsed_frames = (double)(logic_loop_start_time \ - eng.start_time) / 1000.0f * eng.fps; eng.whole_frames_to_do = (unsigned int)elapsed_frames - eng.current_frame; } if (!eng.whole_frames_to_do) { eng.should_start_logic_loop = true; return false; } eng.whole_frames_to_do -= 1; eng.current_frame += 1; eng.should_start_logic_loop = false; return true; } void setup_bindings() { input_processor_init(); key_state_binding binding; binding.k = SDLK_UP; binding.s = GS_N; binding.t = BINDING_ONE_TIME; add_binding(&binding); binding.k = SDLK_RIGHT; binding.s = GS_E; add_binding(&binding); binding.k = SDLK_DOWN; binding.s = GS_S; add_binding(&binding); binding.k = SDLK_LEFT; binding.s = GS_W; add_binding(&binding); } <file_sep>#include <fstream> #include <stdio.h> #include <iterator> #include <GL/glew.h> #include <GL/gl.h> #include <stdlib.h> GLuint compile_shader( const char *vertex_shader_path, const char *fragment_shader_path ) { std::ifstream vertex_file_stream(vertex_shader_path); std::string vertex_shader_source( (std::istreambuf_iterator<char>(vertex_file_stream)), std::istreambuf_iterator<char>()); const char *vertex_shader_source_c_str = vertex_shader_source.c_str(); GLuint vertex_shader = glCreateShader(GL_VERTEX_SHADER); glShaderSource(vertex_shader, 1, &vertex_shader_source_c_str, NULL); glCompileShader(vertex_shader); GLint status; glGetShaderiv(vertex_shader, GL_COMPILE_STATUS, &status); if (status != GL_TRUE) { char buffer[512]; glGetShaderInfoLog(vertex_shader, 512, NULL, buffer); fprintf(stderr, "vertexshader compile error: %s\n", buffer); exit(1); } std::ifstream fragment_file_stream(fragment_shader_path); std::string fragment_shader_source( (std::istreambuf_iterator<char>(fragment_file_stream)), std::istreambuf_iterator<char>()); const char *fragment_shader_source_c_str = fragment_shader_source.c_str(); GLuint fragment_shader = glCreateShader(GL_FRAGMENT_SHADER); glShaderSource( fragment_shader, 1, &fragment_shader_source_c_str, NULL); glCompileShader(fragment_shader); glGetShaderiv(fragment_shader, GL_COMPILE_STATUS, &status); if (status != GL_TRUE) { char buffer[512]; glGetShaderInfoLog(fragment_shader, 512, NULL, buffer); fprintf(stderr, "fragmentshader compile error: %s\n", buffer); exit(1); } GLuint shader_program =glCreateProgram(); glAttachShader(shader_program, vertex_shader); glAttachShader(shader_program, fragment_shader); glLinkProgram(shader_program); return shader_program; } <file_sep>#include <vector> #include <stdio.h> #include <GL/gl.h> #define GLM_FORCE_RADIANS #include <glm/glm.hpp> #include "bin_obj_reader.hpp" void bin_obj_read( const char *path, std::vector<GLuint> &element_array, std::vector<glm::vec3> &vertices, std::vector<glm::vec2> &uvs, std::vector<glm::vec3> &normals, std::vector<glm::vec3> *ordered_vertices, std::vector<GLuint> *element_array_vertices_ordered_vertices_map ) { FILE *fp = fopen(path, "r"); int element_array_size, vertices_size, ordered_vertices_size; if (ordered_vertices) { fscanf( fp, "%d %d %d\n", &element_array_size, &vertices_size, &ordered_vertices_size); } else { fscanf(fp, "%d %d\n", &element_array_size, &vertices_size); } element_array.resize(element_array_size); fread( &element_array[0], sizeof(element_array[0]), element_array_size, fp); vertices.resize(vertices_size); fread( &vertices[0], sizeof(vertices[0]), vertices_size, fp); uvs.resize(vertices_size); fread( &uvs[0], sizeof(uvs[0]), vertices_size, fp); normals.resize(vertices_size); fread( &normals[0], sizeof(normals[0]), vertices_size, fp); if (ordered_vertices) { ordered_vertices->resize(ordered_vertices_size); fread( &((*ordered_vertices)[0]), sizeof((*ordered_vertices)[0]), ordered_vertices_size, fp); element_array_vertices_ordered_vertices_map->resize(vertices_size); fread( &((*element_array_vertices_ordered_vertices_map)[0]), sizeof((*element_array_vertices_ordered_vertices_map)[0]), element_array_size, fp); } fclose(fp); } <file_sep>#include <vector> #include <algorithm> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <stdbool.h> #include <GL/gl.h> #define GLM_FORCE_RADIANS #include <glm/glm.hpp> struct face { int v; int t; int n; bool operator==(struct face f2) { if (memcmp(this, &f2, sizeof(*this)) == 0) { return true; } return false; } }; void process_face( struct face new_face, std::vector<GLuint> &element_array, std::vector<struct face> &temp_faces ) { std::vector<struct face>::iterator it; it = find( temp_faces.begin(), temp_faces.end(), new_face); if (it != temp_faces.end()) { element_array.push_back(it - temp_faces.begin()); return; } element_array.push_back(temp_faces.size()); temp_faces.push_back(new_face); } void simple_obj_read( const char *path, std::vector<GLuint> &element_array, std::vector<glm::vec3> &vertices, std::vector<glm::vec2> &uvs, std::vector<glm::vec3> &normals, std::vector<glm::vec3> *ordered_vertices = NULL, std::vector<GLuint> *element_array_vertices_ordered_vertices_map = NULL ) { FILE *file = fopen(path, "r"); std::vector<glm::vec3> temp_vertices; std::vector<glm::vec2> temp_uvs; std::vector<glm::vec3> temp_normals; std::vector<struct face> temp_faces; if (file == NULL) { fprintf(stderr, "File couldn't be opened\n"); exit(1); } char line_buffer[128]; while ((fgets(line_buffer, sizeof(line_buffer) - 1, file) != NULL)) { char entry_type[128]; sscanf(line_buffer, "%s", entry_type); if (strcmp(entry_type, "v") == 0) { glm::vec3 vertex; sscanf( &(line_buffer[1]), "%f %f %f\n", &vertex.x, &vertex.y, &vertex.z); temp_vertices.push_back(vertex); if (ordered_vertices) { ordered_vertices->push_back(vertex); } continue; } if (strcmp(entry_type, "vt") == 0) { glm::vec2 uv; sscanf( &(line_buffer[2]), "%f %f\n", &uv.x, &uv.y); temp_uvs.push_back(uv); continue; } if (strcmp(entry_type, "vn") == 0) { glm::vec3 normal; sscanf( &(line_buffer[2]), "%f %f %f\n", &normal.x, &normal.y, &normal.z); temp_normals.push_back(normal); continue; } if (strcmp(entry_type, "f") == 0) { struct face triangle_points[3]; sscanf( &(line_buffer[1]), "%d/%d/%d %d/%d/%d %d/%d/%d\n", &triangle_points[0].v, &triangle_points[0].t, &triangle_points[0].n, &triangle_points[1].v, &triangle_points[1].t, &triangle_points[1].n, &triangle_points[2].v, &triangle_points[2].t, &triangle_points[2].n); for (int i = 0; i < 3; i++) { process_face(triangle_points[i], element_array, temp_faces); } } } std::vector<struct face>::iterator it; for (it = temp_faces.begin(); it != temp_faces.end(); it++) { // fprintf(stderr, "%d %d %d\n", it->v, it->t, it->n); vertices.push_back(temp_vertices[it->v - 1]); uvs.push_back(temp_uvs[it->t - 1]); normals.push_back(temp_normals[it->n - 1]); element_array_vertices_ordered_vertices_map->push_back(it->v - 1); } return; } void simple_obj_write( std::vector<GLuint> &element_array, std::vector<glm::vec3> &vertices, std::vector<glm::vec2> &uvs, std::vector<glm::vec3> &normals, std::vector<glm::vec3> *ordered_vertices = NULL, std::vector<GLuint> *element_array_vertices_ordered_vertices_map = NULL ) { if (ordered_vertices) { fprintf( stdout, "%lu %lu %lu\n", element_array.size(), vertices.size(), ordered_vertices->size()); } else { fprintf(stdout, "%lu %lu\n", element_array.size(), vertices.size()); } fwrite( &element_array[0], sizeof(element_array[0]), element_array.size(), stdout); fwrite( &vertices[0], sizeof(vertices[0]), vertices.size(), stdout); fwrite( &uvs[0], sizeof(uvs[0]), uvs.size(), stdout); fwrite( &normals[0], sizeof(normals[0]), normals.size(), stdout); if (ordered_vertices) { fwrite( &((*ordered_vertices)[0]), sizeof((*ordered_vertices)[0]), ordered_vertices->size(), stdout); fwrite( &((*element_array_vertices_ordered_vertices_map)[0]), sizeof((*element_array_vertices_ordered_vertices_map)[0]), element_array_vertices_ordered_vertices_map->size(), stdout); } } int main(int argc, char *argv[]) { std::vector<GLuint> element_array; std::vector<glm::vec3> vertices; std::vector<glm::vec2> uvs; std::vector<glm::vec3> normals; std::vector<glm::vec3> ordered_vertices; std::vector<GLuint> element_array_vertices_ordered_vertices_map; simple_obj_read( argv[1], element_array, vertices, uvs, normals, &ordered_vertices, &element_array_vertices_ordered_vertices_map); simple_obj_write( element_array, vertices, uvs, normals, &ordered_vertices, &element_array_vertices_ordered_vertices_map); } <file_sep>#include "texture.h" #include <GL/glew.h> #include <GL/gl.h> #include <SDL2/SDL.h> #include <SDL2/SDL_opengl.h> #include <SDL2/SDL_image.h> GLuint load_texture(const char *fname) { GLuint texture_id; SDL_Surface *img = IMG_Load(fname); if(!img){ fprintf(stderr, "Error! Could not load %s\n", fname); exit(1); } glGenTextures(1, &texture_id); glBindTexture(GL_TEXTURE_2D, texture_id); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, img->w, img->h, 0, GL_RGBA, GL_UNSIGNED_BYTE, img->pixels); SDL_FreeSurface(img); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR_MIPMAP_LINEAR); glGenerateMipmap(GL_TEXTURE_2D); return texture_id; } texture *texture_init( texture *txt, const char *fname) { txt->texture_id = load_texture(fname); } <file_sep>import sys fname = sys.argv[2] scale_factor = float(sys.argv[1]) lines = open(fname).readlines() for l in lines: ls = l.split() if ls[0] == "v": for i in range(1, 4): ls[i] = str(float(ls[i]) * scale_factor) print " ".join(ls) <file_sep>#include "text_texture.hpp" #if SDL_BYTEORDER == SDL_BIG_ENDIAN enum { RMASK = 0xff000000, GMASK = 0x00ff0000, BMASK = 0x0000ff00, AMASK = 0x000000ff}; #else enum { RMASK = 0x000000ff, GMASK = 0x0000ff00, BMASK = 0x00ff0000, AMASK = 0xff000000}; #endif TextTexture::TextTexture( SDL_Rect txt_rect, SDL_Surface *bg_img) : txt_rect(txt_rect), bg_img(bg_img) { int w, h; if (bg_img) { w = bg_img->w; h = bg_img->h; } else { w = txt_rect.w; h = txt_rect.h; } surface = SDL_CreateRGBSurface( SDL_SWSURFACE, w, h, 32, RMASK, GMASK, BMASK, AMASK); if(!surface){ fprintf(stderr, "Error creating a surface for the sprite\n"); } txt_surface = SDL_CreateRGBSurface( SDL_SWSURFACE, txt_rect.w, txt_rect.h, 32, RMASK, GMASK, BMASK, AMASK); if(SDL_MUSTLOCK(txt_surface)) SDL_LockSurface(txt_surface); cairo_surface = cairo_image_surface_create_for_data( static_cast<unsigned char *>(txt_surface->pixels), CAIRO_FORMAT_RGB24, txt_surface->w, txt_surface->h, txt_surface->pitch); cr = cairo_create(cairo_surface); font_description = pango_font_description_new(); pango_font_description_set_family(font_description, "serif"); pango_font_description_set_weight(font_description, PANGO_WEIGHT_BOLD); pango_font_description_set_absolute_size( font_description, 20 * PANGO_SCALE); layout = pango_cairo_create_layout(cr); pango_layout_set_font_description(layout, font_description); pango_layout_set_width(layout, w * PANGO_SCALE); pango_layout_set_height(layout, h * PANGO_SCALE); pango_layout_set_alignment(layout, PANGO_ALIGN_CENTER); if(SDL_MUSTLOCK(txt_surface)) SDL_UnlockSurface(txt_surface); text[0] = '\0'; glGenTextures(1, &texture_id); glBindTexture( GL_TEXTURE_2D, texture_id); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, w, h, 0, GL_RGBA, GL_UNSIGNED_BYTE, surface->pixels); return; } void TextTexture::set_text(const char *text_input) { strncpy(text, text_input, TEXTLENGTH - 1); SDL_BlitSurface(bg_img, NULL, surface, NULL); if(SDL_MUSTLOCK(txt_surface)) { SDL_LockSurface(txt_surface); } pango_layout_set_markup(layout, text, -1); pango_cairo_show_layout(cr, layout); if(SDL_MUSTLOCK(txt_surface)) SDL_UnlockSurface(txt_surface); SDL_BlitSurface(txt_surface, NULL, surface, &txt_rect); glBindTexture(GL_TEXTURE_2D, texture_id); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, surface->w, surface->h, 0, GL_RGBA, GL_UNSIGNED_BYTE, surface->pixels); } <file_sep>#ifndef DECAL_H #define DECAL_H typedef struct decal decal; struct decal { GLuint texture_index; GLuint uv_bo; GLfloat uvs[12]; }; decal *decal_init( decal *d, GLuint texture_index, GLfloat x, GLfloat y, GLfloat w, GLfloat h); void decal_set_xywh( decal *d, GLfloat x, GLfloat y, GLfloat w, GLfloat h); #endif <file_sep>#include "mo_eng.hpp" #include "../shader_compiler/shader_compiler.hpp" #include "../utils/utils.hpp" #include <string.h> #include <iostream> #include <libgen.h> MoEng *MoObject::eng = NULL; void MoObject::prep(MoEng *objects_eng) { eng = objects_eng; } MoObject::MoObject(unsigned int object_index) : object_index(object_index), model_index(0), texture_index(eng->model_templates[model_index].textures[0]), shader_index(0) { model_unit = new BoalerModelUnit( glm::mat4(1), 0, texture_index, *eng->model_templates[model_index].model); vslm_link = new BoalerVSLModelUnitLink( *eng->view_shader_links[shader_index], *model_unit); billboard = new MoBillboard( *vslm_link, object_index + 1, eng->model_templates[model_index].r_bb); } MoObject::~MoObject() { delete model_unit; delete vslm_link; delete billboard; } void MoObject::change_model(unsigned int new_model_index) { model_index = new_model_index; model_unit->model = eng->model_templates[new_model_index].model; texture_index = 0; model_unit->texture_id = eng->model_templates[new_model_index] .textures[texture_index]; billboard->bb.mother_radius = eng->model_templates[new_model_index].r_bb; vslm_link->update_model_unit(*model_unit); } void MoObject::change_texture() { unsigned int num_of_textures = eng->model_templates[model_index] .textures.size(); texture_index = (texture_index + 1) % num_of_textures; model_unit->texture_id = eng->model_templates[model_index] .textures[texture_index]; vslm_link->update_model_unit(*model_unit); } void MoObject::move(glm::vec3 direction_modelspace) { GLfloat model_move_speed = 10.0f / eng->fps; if (direction_modelspace != glm::vec3(0.0f, 0.0f, 0.0f)) { direction_modelspace = glm::normalize(direction_modelspace); } model_unit->M = model_unit->M * glm::translate(glm::mat4(1), model_move_speed * direction_modelspace); } void MoObject::rotate(glm::vec3 rotation_axis) { model_unit->M = model_unit->M * glm::rotate(glm::mat4(1), 0.1f, rotation_axis); } void MoObject::put_in_rotate_mode() { mode = OBJECT_MODE_ROTATE; billboard->set_to_rotate(); } void MoObject::put_in_active_mode() { mode = OBJECT_MODE_ACTIVE; billboard->set_to_active(); eng->input_processor->deactivate_state(DELETE_OBJECT); } void MoObject::put_in_normal_mode() { mode = OBJECT_MODE_INACTIVE; billboard->set_to_normal(); } MoObject *MoEng::add_object(unsigned int model_index) { unsigned int i; for (i = 0; i < NUMBER_OF_OBJECTS_ALLOWED; i++) { if (!indexed_objects[i]) { break; } } MoObject *mobj = new MoObject(i); mobj->change_model(model_index); objects.push_back(mobj); indexed_objects[i] = mobj; set_active_object(mobj->object_index); mobj->model_unit->M = glm::affineInverse(view_unit.V) * glm::translate(glm::mat4(1), -1.0f * initial_camera_pos); return mobj; } void MoEng::set_active_object(unsigned int new_active_object_index) { if ( new_active_object_index >= NUMBER_OF_OBJECTS_ALLOWED || !indexed_objects[new_active_object_index] ) { return; } active_object_index = new_active_object_index; active_object = indexed_objects[active_object_index]; active_object->put_in_active_mode(); input_processor->deactivate_state(ROTATE_MODE); input_processor->deactivate_state(DELETE_OBJECT); } void MoEng::move_active_object_on_request() { if (!active_object) { return; } glm::vec3 move_dn(0.0f, 0.0f, 0.0f); if (input_processor->is_state_active(MV_RIGHT)) { move_dn += glm::vec3(1.0f, 0.0f, 0.0f); } if (input_processor->is_state_active(MV_LEFT)) { move_dn += glm::vec3(-1.0f, 0.0f, 0.0f); } if (input_processor->is_state_active(MV_UP)) { move_dn += glm::vec3(0.0f, 1.0f, 0.0f); } if (input_processor->is_state_active(MV_DOWN)) { move_dn += glm::vec3(0.0f, -1.0f, 0.0f); } if (input_processor->is_state_active(MV_FORWARD)) { move_dn += glm::vec3(0.0f, 0.0f, 1.0f); } if (input_processor->is_state_active(MV_BACKWARD)) { move_dn += glm::vec3(0.0f, 0.0f, -1.0f); } active_object->move(move_dn); } void MoEng::rotate_active_object_on_request() { if (!active_object) { return; } if (input_processor->is_state_active(MV_RIGHT)) { active_object->rotate(glm::vec3(1.0f, 0.0f, 0.0f)); } if (input_processor->is_state_active(MV_LEFT)) { active_object->rotate(glm::vec3(-1.0f, 0.0f, 0.0f)); } if (input_processor->is_state_active(MV_UP)) { active_object->rotate(glm::vec3(0.0f, 1.0f, 0.0f)); } if (input_processor->is_state_active(MV_DOWN)) { active_object->rotate(glm::vec3(0.0f, -1.0f, 0.0f)); } if (input_processor->is_state_active(MV_FORWARD)) { active_object->rotate(glm::vec3(0.0f, 0.0f, 1.0f)); } if (input_processor->is_state_active(MV_BACKWARD)) { active_object->rotate(glm::vec3(0.0f, 0.0f, -1.0f)); } } void MoEng::delete_active_object() { MoObject *object_to_be_deleted = active_object; indexed_objects[active_object->object_index] = NULL; objects.erase( std::remove(objects.begin(), objects.end(), active_object), objects.end()); enter_global_mode(); active_object = NULL; delete object_to_be_deleted; } void MoEng::change_active_object_model() { unsigned int new_model_index = (active_object->model_index + 1) % model_templates.size(); active_object->change_model(new_model_index); } void MoEng::do_logic() { if (active_object) { if (input_processor->is_state_active(ROTATE_MODE_SWITCH)) { input_processor->deactivate_state(ROTATE_MODE_SWITCH); if (input_processor->is_state_active(ROTATE_MODE)) { std::cout << "switching rotate mode on\n"; active_object->put_in_rotate_mode(); } else { std::cout << "switching rotate mode off\n"; active_object->put_in_active_mode(); } } if (input_processor->is_state_active(DELETE_OBJECT)) { input_processor->deactivate_state(DELETE_OBJECT); delete_active_object(); } if (input_processor->is_state_active(GLOBAL_MODE_SWITCH)) { input_processor->deactivate_state(GLOBAL_MODE_SWITCH); enter_global_mode(); } if (input_processor->is_state_active(CHANGE_MODEL)) { input_processor->deactivate_state(CHANGE_MODEL); change_active_object_model(); } if (input_processor->is_state_active(CHANGE_TEXTURE)) { input_processor->deactivate_state(CHANGE_TEXTURE); active_object->change_texture(); } if (input_processor->is_state_active(ROTATE_MODE)) { rotate_active_object_on_request(); } else { // just in normal move mode move_active_object_on_request(); } } else { // in global mode if (input_processor->is_state_active(CHANGE_MODEL)) { input_processor->deactivate_state(CHANGE_MODEL); add_object(BASE_MODEL_TRIANGLE); } } read_for_requested_object(); } void MoEng::create_key_bindings() { input_processor->add_key_binding(SDLK_UP, MV_UP, BINDING_CONTINUOUS); input_processor->add_key_binding(SDLK_DOWN, MV_DOWN, BINDING_CONTINUOUS); input_processor->add_key_binding(SDLK_LEFT, MV_LEFT, BINDING_CONTINUOUS); input_processor->add_key_binding(SDLK_RIGHT, MV_RIGHT, BINDING_CONTINUOUS); input_processor->add_key_binding(SDLK_a, MV_FORWARD, BINDING_CONTINUOUS); input_processor->add_key_binding(SDLK_s, MV_BACKWARD, BINDING_CONTINUOUS); input_processor->add_key_binding(SDLK_1, PRESSED_1, BINDING_CONTINUOUS); input_processor->add_key_binding(SDLK_2, PRESSED_2, BINDING_CONTINUOUS); input_processor->add_key_binding(SDLK_3, PRESSED_3, BINDING_CONTINUOUS); input_processor->add_key_binding(SDLK_4, PRESSED_4, BINDING_CONTINUOUS); input_processor->add_key_binding(SDLK_5, PRESSED_5, BINDING_CONTINUOUS); input_processor->add_key_binding(SDLK_6, PRESSED_6, BINDING_CONTINUOUS); input_processor->add_key_binding(SDLK_7, PRESSED_7, BINDING_CONTINUOUS); input_processor->add_key_binding(SDLK_8, PRESSED_8, BINDING_CONTINUOUS); input_processor->add_key_binding(SDLK_9, PRESSED_9, BINDING_CONTINUOUS); input_processor->add_key_binding(SDLK_0, PRESSED_0, BINDING_CONTINUOUS); input_processor->add_key_binding(SDLK_r, ROTATE_MODE_SWITCH, BINDING_ONE_TIME); input_processor->add_key_binding(SDLK_r, ROTATE_MODE, BINDING_ATOMIC); input_processor->add_key_binding(SDLK_d, DELETE_OBJECT, BINDING_ONE_TIME); input_processor->add_key_binding(SDLK_ESCAPE, GLOBAL_MODE_SWITCH, BINDING_ONE_TIME); input_processor->add_key_binding(SDLK_m, CHANGE_MODEL, BINDING_ONE_TIME); input_processor->add_key_binding(SDLK_n, CHANGE_TEXTURE, BINDING_ONE_TIME); input_processor->add_key_binding(SDLK_RETURN, SUBMIT_REQUEST, BINDING_ONE_TIME); } int MoEng::load_textures_for_model_template( mo_model_template *mo_template, json_object *texture_lib, json_object *textures_j) { unsigned int num_textures = json_object_array_length(textures_j); for (unsigned int i = 0; i < num_textures; i++) { json_object *t_name_j = json_object_array_get_idx(textures_j, i); const char *t_name = json_object_get_string(t_name_j); json_object *t_id_j; if (!json_object_object_get_ex(texture_lib, t_name, &t_id_j)) { fprintf(stderr, "ERROR! No texture with name %s\n", t_name); return -1; } GLuint t_id = (GLuint)json_object_get_int64(t_id_j); mo_template->textures.push_back(t_id); } return 0; } int MoEng::setup_with_file(const char *setup_file_path) { FILE *fp = fopen(setup_file_path, "r"); fseek(fp, 0, SEEK_END); long fsize = ftell(fp); fseek(fp, 0, SEEK_SET); char *setup_contents = new char[fsize + 1]; fread(setup_contents, fsize, 1, fp); fclose(fp); setup_contents[fsize] = 0; json_object *jobj = json_tokener_parse(setup_contents); delete setup_contents; char *setup_file_path_cp = new char[strlen(setup_file_path) + 1]; strcpy(setup_file_path_cp, setup_file_path); char *setup_file_path_dirname = dirname(setup_file_path_cp); char path_buffer[512]; char dirname_buffer[512]; memset(dirname_buffer, '\0', sizeof(dirname_buffer)); strncpy(dirname_buffer, setup_file_path_dirname, sizeof(dirname_buffer)); dirname_buffer[strlen(setup_file_path_dirname)] = '/'; json_object *texture_lib; if (!json_object_object_get_ex(jobj, "texture_lib", &texture_lib)) { fprintf(stderr, "ERROR! No textures_lib attribute in set-up file\n"); return -1; } if (json_object_get_type(texture_lib) != json_type_object) { fprintf(stderr, "ERROR! textures_lib attribute should be " "a json object in set-up file\n"); return -1; } json_object_object_foreach(texture_lib, k, v){ const char *texture_fname = json_object_get_string(v); memcpy(path_buffer, dirname_buffer, sizeof(dirname_buffer)); const char *texture_path = strncat( path_buffer, texture_fname, sizeof(path_buffer)); json_object_object_add(texture_lib, k, json_object_new_int64( load_texture(texture_path))); } json_object *models; if (!json_object_object_get_ex(jobj, "models", &models)) { fprintf(stderr, "ERROR! No models attribute in set-up file\n"); return -1; } if (json_object_get_type(models) != json_type_array) { fprintf(stderr, "ERROR! models attribute should be " "a json array in set-up file\n"); return -1; } unsigned int models_length = (unsigned int)json_object_array_length(models); for (unsigned int i = 0; i < models_length; i++) { json_object *model_detail = json_object_array_get_idx( models, i); json_object *obj_file_fname_j; if (!json_object_object_get_ex( model_detail, "object_file", &obj_file_fname_j)) { fprintf(stderr, "ERROR! No object_file attribute in" " model declaration\n"); return -1; } const char *obj_file_fname = json_object_get_string(obj_file_fname_j); memcpy(path_buffer, dirname_buffer, sizeof(dirname_buffer)); char *obj_file_fname_path = strncat( path_buffer, obj_file_fname, sizeof(path_buffer)); mo_model_template mt; mt.model = new BoalerModel(obj_file_fname_path); model_templates.push_back(mt); json_object *r_bb_j; if (!json_object_object_get_ex( model_detail, "radius_bb", &r_bb_j)) { fprintf(stderr, "ERROR! No radius_bb attribute in" " model declaration\n"); return -1; } model_templates[i].r_bb = json_object_get_double(r_bb_j); json_object *textures_j; if (!json_object_object_get_ex( model_detail, "textures", &textures_j)) { fprintf(stderr, "ERROR! No textures attribute in" " model declaration\n"); return -1; } if (load_textures_for_model_template( &model_templates[i], texture_lib, textures_j) == -1) { return -1; } } free(jobj); return 0; } MoEng::MoEng( const char*setup_file_path, int w, int h, const char *window_title, unsigned int fps) : BaseEng(w, h, window_title, fps, NULL), initial_camera_pos(glm::vec3(0.0f, 0.0f, 10.0f)), beng(BoalerEng()), billboard_shader_unit(compile_shader( "resources/basic_shading.vertexshader", "resources/basic_shading.fragmentshader")), view_unit(BoalerViewUnit( glm::lookAt( glm::vec3(0.0, 0.0, -1.0), glm::vec3(0.0, 0.3, 0.0), glm::vec3(0.0, 1.0, 0.0)), glm::perspective(44.9f, (float)w / (float)h, 0.1f, 100.0f))), object_index_being_requested(0), frames_since_last_entry(0), last_digit_pressed(NO_DIGIT_PRESSED), active_object_index(0), active_object(NULL) { input_processor = new GenInputProcessor<game_states>; base_input_processor = static_cast<BaseInputProcessor *>(input_processor); create_key_bindings(); beng.reg_view_unit(&view_unit); if (setup_with_file(setup_file_path) == -1) { throw MoEngReturnException(); } // Set up shader unit library GLuint shader_program = compile_shader( "resources/basic_shading.vertexshader", "resources/basic_shading.fragmentshader"); shaders[0] = new BoalerShaderUnit(shader_program); view_shader_links[0] = new BoalerVSLink(view_unit, *shaders[0]); // Prepare the static variables of billboard // and MoObject MoBillboard::prep(this, billboard_shader_unit); MoObject::prep(this); memset( indexed_objects, 0, NUMBER_OF_OBJECTS_ALLOWED * sizeof(indexed_objects[0])); } void MoEng::enter_global_mode() { if (!active_object) { return; } active_object->put_in_normal_mode(); active_object = NULL; active_object_index = NUMBER_OF_OBJECTS_ALLOWED + 1; } void MoEng::check_digit(int value) { unsigned int update_limit = 0.5f * fps; game_states digits[10] = { PRESSED_0, PRESSED_1, PRESSED_2, PRESSED_3, PRESSED_4, PRESSED_5, PRESSED_6, PRESSED_7, PRESSED_8, PRESSED_9 }; game_states digit = digits[value]; if (input_processor->is_state_active(digit)) { if ( frames_since_last_entry < update_limit && last_digit_pressed == digit ) { return; } last_digit_pressed = digit; frames_since_last_entry = 0; // update requested number object_index_being_requested = object_index_being_requested * 10 + value; } return; } void MoEng::read_for_requested_object() { frames_since_last_entry += 1; for (int i = 0; i < 10; i++) { check_digit(i); } if (input_processor->is_state_active(SUBMIT_REQUEST)) { input_processor->deactivate_state(SUBMIT_REQUEST); object_index_being_requested -= 1; enter_global_mode(); set_active_object(object_index_being_requested); object_index_being_requested = 0; last_digit_pressed = NO_DIGIT_PRESSED; } } void MoEng::render() { for ( std::vector<MoObject *>::iterator it = objects.begin(); it != objects.end(); ++it ) { (*it)->billboard->bb.update_pos(); } beng.render(); } void MoEng::process_input(SDL_Event *event) { input_processor->process_input(event); } <file_sep>#include "fp_camera.hpp" FpCamera::FpCamera( BaseEng &engine, double speed, double omega, const glm::vec3 &position, get_direction_fn get_direction) : engine(engine), speed_frame_unit(speed/engine.fps), omega_frame_unit(omega/engine.fps), position(position), get_direction(get_direction), phi(0), theta(M_PI) {} glm::mat4 FpCamera::get_V() { glm::vec3 looking_dn; glm::vec3 up_dn; looking_dn.x = sin(theta) * cos(phi); looking_dn.y = sin(phi); looking_dn.z = cos(theta) * cos(phi); up_dn.x = -sin(theta) * sin(phi); up_dn.y = cos(phi); up_dn.z = -cos(theta) * sin(phi); return glm::lookAt( position, position + looking_dn, up_dn); } void FpCamera::compute_direction() { double dtheta = 0, dphi = 0, dr = 0; unsigned int direction = get_direction(engine); if (direction == CAM_MV_NONE) { return; } if (direction & CAM_MV_UP) { dphi += 1; } if (direction & CAM_MV_DOWN) { dphi -= 1; } if (direction & CAM_MV_LEFT) { dtheta += 1; } if (direction & CAM_MV_RIGHT) { dtheta -= 1; } if (direction & CAM_MV_FORWARD) { dr += 1; } position.x += dr * sin(theta) * cos(phi) * speed_frame_unit; position.y += dr * sin(phi) * speed_frame_unit; position.z += dr * cos(theta) * cos(phi) * speed_frame_unit; if (dtheta == 0 && dphi == 0) { return; } double mag = sqrt(dtheta * dtheta + dphi * dphi); this->theta += dtheta/mag * omega_frame_unit; this->phi += dphi/mag * omega_frame_unit; } <file_sep>#ifndef UTILS_H #define UTILS_H #include <GL/glew.h> #include <GL/gl.h> #include <SDL2/SDL.h> #include <SDL2/SDL_opengl.h> void init_sdl_gl_window(int w, int h, const char*title); GLuint load_texture(const char *fname); void swap_sdl_gl_window(); void destroy_sdl_gl_window(); #endif <file_sep>#ifndef SKY_BOX_H #define SKY_BOX_H #include "../multi_object_draw/boaler.hpp" class SkyBox { SkyBox( BoalerEng &beng, GLuint texture_ref, const BoalerViewUnit &view_unit_to_track, const BoalerShaderUnit &shader_unit); ~SkyBox(); void update(); const BoalerViewUnit *view_unit_to_track; BoalerVSLModelUnitLink *vslmu; }; SkyBox::SkyBox( GLuint texture_ref, BoalerViewUnit *view_unit_to_track, BoalerShaderUnit *shader_unit ) : view_unit_to_track(*view_unit_to_track) { BoalerModel *model = new BoalerModel("cube.bin"); BoalerModelUnit *model_unit = new BoalerModelUnit( glm::mat4(1), 0, texture_ref, *model); BoalerVSLink *vs_link = new BoalerVSLink( } #endif <file_sep>#include <GL/glew.h> #include <GL/gl.h> #include "../simple_obj_reader/bin_obj_reader.hpp" #include "../utils/utils.hpp" #include "drawable.hpp" void Drawable::draw() { glBindVertexArray(vao); glUseProgram(program_id); glActiveTexture(texture_unit); glBindTexture(GL_TEXTURE_2D, texture_id); GLuint sampler_id = glGetUniformLocation( program_id, "texture_sampler"); glUniform1i(sampler_id, texture_id - 1); glDrawElements( GL_TRIANGLES, element_array.size(), GL_UNSIGNED_INT, 0); } void Drawable::update_vertices( std::vector<glm::vec3> &new_ordered_positions ) { for ( unsigned int i = 0; i < element_array_positions_ordered_positions_map.size(); i++ ) { int j = element_array_positions_ordered_positions_map[i]; positions[i] = new_ordered_positions[j]; } load_position_bo(); } void Drawable::load_element_array_bo() { glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, element_array_bo); glBufferData( GL_ELEMENT_ARRAY_BUFFER, element_array.size() * sizeof(element_array[0]), &element_array[0], GL_STATIC_DRAW); } void Drawable::load_position_bo() { glBindBuffer(GL_ARRAY_BUFFER, position_bo); glBufferData( GL_ARRAY_BUFFER, positions.size() * sizeof(positions[0]), &positions[0][0], GL_STATIC_DRAW); } void Drawable::load_normal_bo() { glBindBuffer(GL_ARRAY_BUFFER, normal_bo); glBufferData( GL_ARRAY_BUFFER, normals.size() * sizeof(normals[0]), &normals[0][0], GL_STATIC_DRAW); } void Drawable::load_uv_bo() { glBindBuffer(GL_ARRAY_BUFFER, uv_bo); glBufferData( GL_ARRAY_BUFFER, uvs.size() * sizeof(uvs[0]), &uvs[0][0], GL_STATIC_DRAW); } Drawable::~Drawable() { glDeleteBuffers(1, &element_array_bo); glDeleteBuffers(1, &position_bo); glDeleteBuffers(1, &uv_bo); glDeleteBuffers(1, &normal_bo); } void Drawable::set_V(glm::mat4 new_V) { V = new_V; glUniformMatrix4fv(V_id, 1, GL_FALSE, &V[0][0]); } void Drawable::set_P(glm::mat4 new_P) { P = new_P; glUniformMatrix4fv(P_id, 1, GL_FALSE, &P[0][0]); } Drawable::Drawable( const char *bin_model_fname, GLuint program_id, GLuint vao, GLenum texture_unit, GLuint texture_id) : program_id(program_id), vao(vao), texture_unit(texture_unit), texture_id(texture_id) { bin_obj_read( bin_model_fname, element_array, positions, uvs, normals, &ordered_positions, &element_array_positions_ordered_positions_map); glBindVertexArray(vao); glUseProgram(program_id); glGenBuffers(1, &element_array_bo); load_element_array_bo(); glGenBuffers(1, &position_bo); load_position_bo(); position_attrib = glGetAttribLocation( program_id, "position_modelspace"); glVertexAttribPointer(position_attrib, 3, GL_FLOAT, GL_FALSE, 0, 0); glEnableVertexAttribArray(position_attrib); glGenBuffers(1, &normal_bo); load_normal_bo(); normal_attrib = glGetAttribLocation( program_id, "normal_modelspace"); glVertexAttribPointer(normal_attrib, 3, GL_FLOAT, GL_FALSE, 0, 0); glEnableVertexAttribArray(normal_attrib); glGenBuffers(1, &uv_bo); load_uv_bo(); uv_attrib = glGetAttribLocation( program_id, "uv"); glVertexAttribPointer(uv_attrib, 2, GL_FLOAT, GL_FALSE, 0, 0); glEnableVertexAttribArray(uv_attrib); GLuint sampler_id = glGetUniformLocation( program_id, "texture_sampler"); glActiveTexture(texture_unit); glBindTexture(GL_TEXTURE_2D, texture_id); // Set our sampler to use the texture unit glUniform1i(sampler_id, texture_id); M_id = glGetUniformLocation(program_id, "M"); V_id = glGetUniformLocation(program_id, "V"); P_id = glGetUniformLocation(program_id, "P"); M = glm::mat4(1.0f); V = glm::mat4(1.0f); P = glm::mat4(1.0f); } <file_sep>#include "engine.h" void background_render_handler(actor *a) { background_actor *bg = (background_actor *)a; sprite_render(&(bg->background_sprite)); } background_actor *background_actor_init(background_actor *bg) { actor_init(&bg->a, background_render_handler, NULL); sprite_init( &bg->background_sprite, 800, 600, &eng.sand_decal); bg->background_sprite.r[0] = 400; bg->background_sprite.r[1] = 300; return bg; } <file_sep>import subprocess import os points = [ [0, 0.866], [0, 0.2], [0.5, 0.2], [0, -0.2], [0.5, -0.2], [0, -0.866], [0.8464, -0.4], [0.3464, - 1.066] ] shapes = [ (0, 1, 2), (1, 2, 4, 3), (3, 4, 5), (4, 6, 7, 5) ] target_dims = (1024, 1024) def get_min_max(shapes): min_coord = [0, 0] max_coord = [0, 0] for shape in shapes: for p in shape: pt = points[p] if pt[0] < min_coord[0]: min_coord[0] = pt[0] if pt[1] < min_coord[1]: min_coord[1] = pt[1] if pt[0] > max_coord[0]: max_coord[0] = pt[0] if pt[1] > max_coord[1]: max_coord[1] = pt[1] return [min_coord, max_coord] def get_scale_factor(bounding_box): sf_x = target_dims[0] / bounding_box[0] sf_y = target_dims[1] / bounding_box[1] return min([sf_x, sf_y]) def translate_and_scale_and_flip(points, vector, sf): for pt in points: for i in range(2): pt[i] += vector[i] pt[i] *= sf pt[1] = target_dims[1] - pt[1] def draw_and_save_shapes(): preamble = """ convert -size %dx%d xc:white -draw \"%s\" net.svg""" % ( target_dims[0], target_dims[1], "%s") closed_path_string = "path 'M %s Z'" annotation = " text %d,%d '%d' " shape_strings = ["push graphic-context fill 'white' stroke 'black' "] for shape in shapes: path_contents = [] for p in shape: pt = points[p] path_contents.append(",".join([str(int(p)) for p in pt])) shape_strings.append(closed_path_string % " ".join(path_contents)) shape_strings.append("pop graphic-context %s") convert_command = preamble % " ".join(shape_strings) annotation_strings = ["push graphic-context font-size 40 fill 'black' "] for i, pt in enumerate(points): annotation_strings.append(annotation % (pt[0], pt[1], i + 1)) annotation_strings.append("pop graphic-context") convert_command = convert_command % " ".join(annotation_strings) # print convert_command os.system(convert_command) # subprocess.call(["convert", convert_command]) def print_vt_coords(): for pt in points: print "vt %f %f" % (pt[0] / target_dims[0], pt[1] / target_dims[1]) min_coord, max_coord = get_min_max(shapes) sf = get_scale_factor([max_coord[0] - min_coord[0], max_coord[1] - min_coord[1]]) translate_and_scale_and_flip(points, [-1 * m for m in min_coord], sf) draw_and_save_shapes() print_vt_coords() <file_sep>#ifndef BILLBOARD_H #define BILLBOARD_H #include "../multi_object_draw/boaler.hpp" class Billboard { public: Billboard( const BoalerVSLModelUnitLink &mother, BoalerVSLModelUnitLink &bb_vsl_model_link, GLfloat mother_radius ); const BoalerVSLModelUnitLink *mother; BoalerVSLModelUnitLink *bb_vsl_model_link; GLfloat mother_radius; glm::mat4 M_pre_translate; void update_pos(); }; #endif <file_sep>#include <vector> #include <math.h> #include <stdio.h> #include <stdbool.h> #define GLM_FORCE_RADIANS #include <glm/glm.hpp> enum { TOTAL_ITERATIONS = 3 }; bool is_in_sierpinski_carpet(unsigned int i, unsigned int j) { while (i != 0 && j != 0) { if (i % 3 == 1 && j % 3 == 1) { return false; } i /= 3; j /= 3; } return true; } bool is_in_menge_sponge(unsigned int i, unsigned int j, unsigned int k) { if (!is_in_sierpinski_carpet(i, j)) { return false; } if (!is_in_sierpinski_carpet(j, k)) { return false; } if (!is_in_sierpinski_carpet(k, i)) { return false; } return true; } int main() { const int grid_side_len = pow(3, TOTAL_ITERATIONS); const int grid_size = (int)pow(grid_side_len, 2); int grid[grid_side_len][grid_side_len]; std::vector<glm::vec3> instance_displacements; for (unsigned int i = 0; i < grid_side_len; i++){ for (unsigned int j = 0; j < grid_side_len; j++) { for (unsigned int k = 0; k < grid_side_len; k++) { if (is_in_menge_sponge(i, j, k)) { instance_displacements.push_back( glm::vec3(i * 2.0f,j * 2.0f,k * -2.0f)); } } } } fprintf(stdout, "%lu \n", instance_displacements.size()); fwrite( &instance_displacements[0], sizeof(instance_displacements[0]), instance_displacements.size(), stdout); } <file_sep>#include "engine.h" #include "decal.h" decal *decal_init( decal *d, GLuint texture_index, GLfloat x, GLfloat y, GLfloat w, GLfloat h ) { d->texture_index = texture_index; glGenBuffers(1, &d->uv_bo); decal_set_xywh(d, x, y, w, h); return d; } void decal_set_xywh( decal *d, GLfloat x, GLfloat y, GLfloat w, GLfloat h) { GLfloat uvs_tmp[] = { x, y + h, // bottom left x + w, y + h, // bottom right x, y, // top left x, y, // top left x + w, y + h, // bottom right x + w, y // top right }; memcpy(d->uvs, uvs_tmp, 12 * sizeof(uvs_tmp[0])); glBindBuffer(GL_ARRAY_BUFFER, d->uv_bo); glBufferData( GL_ARRAY_BUFFER, sizeof(d->uvs), d->uvs, GL_STATIC_DRAW); } <file_sep>#ifndef DRAWABLE_HPP_ #define DRAWABLE_HPP_ #include <vector> #include <GL/glew.h> #include <GL/gl.h> #include <stdlib.h> #include <stdio.h> #define GLM_FORCE_RADIANS #include <glm/glm.hpp> #include <glm/gtc/matrix_transform.hpp> class Drawable { private: // std::vector and buffer object for storing the element // array data std::vector<GLuint> element_array; GLuint element_array_bo; // std::vector, buffer object and shader attribute variable // for storing the position vertex data std::vector<glm::vec3> positions; GLuint position_bo; GLint position_attrib; // std::vector with size = positions.size() where each element // gives the index of the ordered_positions // vertex that is the same as the positions vertex corresponding // to that element std::vector<GLuint> element_array_positions_ordered_positions_map; // std::vector, buffer object and shader attribute variable // for storing the texture coordinate data std::vector<glm::vec2> uvs; GLuint uv_bo; GLint uv_attrib; // std::vector, buffer object and shader attribute variable // for storing the normals coordinate data std::vector<glm::vec3> normals; GLuint normal_bo; GLint normal_attrib; // Reference to this Drawable's shader program GLuint program_id; // Regerence to this Drawable's vertex array object GLuint vao; // Reference to this Drawable's texture unit and texture GLenum texture_unit; GLuint texture_id; // References to shader's M V and P matrices GLuint M_id; GLuint V_id; GLuint P_id; public: Drawable( const char *bin_model_fname, GLuint program_id, GLuint vao, GLenum texture_unit, GLuint texture_id); ~Drawable(); // Succession of methods that bind and load // the corresponding vector of attributes into // a buffer object void load_element_array_bo(); void load_position_bo(); void load_normal_bo(); void load_uv_bo(); // loads both the vertex and the normal buffer // objects void load_position_normal_bo(); // std::vector of positions ordered in the same way that they // are declared in the *.obj file that contains the model std::vector<glm::vec3> ordered_positions; glm::mat4 M; glm::mat4 V; glm::mat4 P; // set drawable's V and P matrices void set_V(glm::mat4 new_V); void set_P(glm::mat4 new_V); // updates the positions and normals based on the values // contained in new_ordered_positions void update_vertices( std::vector<glm::vec3> &new_ordered_positions); void draw(); }; #endif <file_sep>#include "boaler.hpp" #include "../simple_obj_reader/bin_obj_reader.hpp" #include <stdio.h> #include <algorithm> typedef class BoalerVSLink BoalerVSLink; BoalerModel::BoalerModel( const char *bin_model_fname) { bin_obj_read( bin_model_fname, element_array, positions, uvs, normals, &ordered_positions, &element_array_positions_ordered_positions_map); glGenBuffers(1, &element_array_bo); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, element_array_bo); glBufferData( GL_ELEMENT_ARRAY_BUFFER, element_array.size() * sizeof(element_array[0]), &element_array[0], GL_STATIC_DRAW); glGenBuffers(1, &position_bo); glBindBuffer(GL_ARRAY_BUFFER, position_bo); glBufferData( GL_ARRAY_BUFFER, positions.size() * sizeof(positions[0]), &positions[0][0], GL_STATIC_DRAW); glGenBuffers(1, &normal_bo); glBindBuffer(GL_ARRAY_BUFFER, normal_bo); glBufferData( GL_ARRAY_BUFFER, normals.size() * sizeof(normals[0]), &normals[0][0], GL_STATIC_DRAW); glGenBuffers(1, &uv_bo); glBindBuffer(GL_ARRAY_BUFFER, uv_bo); glBufferData( GL_ARRAY_BUFFER, uvs.size() * sizeof(uvs[0]), &uvs[0][0], GL_STATIC_DRAW); } BoalerModelUnit::BoalerModelUnit( glm::mat4 M, unsigned int texture_unit_index, GLuint texture_id, BoalerModel &model) : M(M), texture_unit_index(texture_unit_index), texture_id(texture_id), model(&model) {} BoalerVSLModelUnitLink::BoalerVSLModelUnitLink( BoalerVSLink &vs_link, BoalerModelUnit &model_unit) : vs_link(&vs_link), model_unit(&model_unit) { vs_link.model_unit_links.push_back(this); glGenVertexArrays(1, &vao); update_model_unit(model_unit); } BoalerVSLModelUnitLink::~BoalerVSLModelUnitLink() { std::vector<BoalerVSLModelUnitLink *> &vec = vs_link->model_unit_links; vec.erase(std::remove(vec.begin(), vec.end(), this), vec.end()); } void BoalerVSLModelUnitLink::update_model_unit( BoalerModelUnit &new_model_unit ) { model_unit = &new_model_unit; glBindVertexArray(vao); glBindBuffer( GL_ELEMENT_ARRAY_BUFFER, model_unit->model->element_array_bo); glBindBuffer(GL_ARRAY_BUFFER, model_unit->model->position_bo); glVertexAttribPointer( vs_link->shader_unit->position_attr, 3, GL_FLOAT, GL_FALSE, 0, 0); glEnableVertexAttribArray(vs_link->shader_unit->position_attr); glBindBuffer(GL_ARRAY_BUFFER, model_unit->model->uv_bo); glVertexAttribPointer( vs_link->shader_unit->uv_attr, 2, GL_FLOAT, GL_FALSE, 0, 0); glEnableVertexAttribArray(vs_link->shader_unit->uv_attr); glBindBuffer(GL_ARRAY_BUFFER, model_unit->model->normal_bo); glVertexAttribPointer( vs_link->shader_unit->normal_attr, 3, GL_FLOAT, GL_FALSE, 0, 0); glEnableVertexAttribArray(vs_link->shader_unit->normal_attr); glBindVertexArray(0); } void BoalerVSLModelUnitLink::model_unit_linker() { glBindVertexArray(vao); glUniformMatrix4fv( vs_link->shader_unit->M_unfm, 1, GL_FALSE, &(model_unit->M[0][0])); glActiveTexture(GL_TEXTURE0 + model_unit->texture_unit_index); glBindTexture(GL_TEXTURE_2D, model_unit->texture_id); glUniform1i( vs_link->shader_unit->texture_sampler_unfm, model_unit->texture_unit_index); } void BoalerVSLModelUnitLink::render() { glBindVertexArray(vao); glDrawElements( GL_TRIANGLES, model_unit->model->element_array.size(), GL_UNSIGNED_INT, 0); glBindVertexArray(0); } BoalerShaderUnit::BoalerShaderUnit( GLuint program_id) : program_id(program_id) { position_attr = glGetAttribLocation( program_id, "position_modelspace"); uv_attr = glGetAttribLocation( program_id, "uv"); normal_attr = glGetAttribLocation( program_id, "normal_modelspace"); M_unfm = glGetUniformLocation( program_id, "M"); V_unfm = glGetUniformLocation( program_id, "V"); P_unfm = glGetUniformLocation( program_id, "P"); texture_sampler_unfm = glGetUniformLocation( program_id, "texture_sampler"); } BoalerViewUnit::BoalerViewUnit( glm::mat4 V, glm::mat4 P) : V(V), P(P) {} void BoalerViewUnit::render() { for (unsigned int i = 0; i < shader_links.size(); i++) { shader_links[i]->shader_unit_linker(); for ( unsigned int j = 0; j < shader_links[i]->model_unit_links.size(); j++ ) { shader_links[i]->model_unit_links[j]->model_unit_linker(); shader_links[i]->model_unit_links[j]->render(); } } } BoalerVSLink::BoalerVSLink( BoalerViewUnit &view_unit, BoalerShaderUnit &shader_unit) : view_unit(&view_unit), shader_unit(&shader_unit) { view_unit.shader_links.push_back(this); } BoalerVSLink::~BoalerVSLink() {} void BoalerVSLink::shader_unit_linker() { glUseProgram(shader_unit->program_id); glUniformMatrix4fv( shader_unit->V_unfm, 1, GL_FALSE, &(view_unit->V[0][0])); glUniformMatrix4fv( shader_unit->P_unfm, 1, GL_FALSE, &(view_unit->P[0][0])); } void BoalerEng::reg_view_unit(BoalerViewUnit *vu) { view_units.push_back(vu); } void BoalerEng::reg_shader_unit(BoalerShaderUnit *su) { shader_units.push_back(su); } void BoalerEng::reg_model(BoalerModel *m) { models.push_back(m); } void BoalerEng::reg_model_unit(BoalerModelUnit *mu) { model_units.push_back(mu); } void BoalerEng::render() { for (unsigned int i = 0; i < view_units.size(); i++) { view_units[i]->render(); } } <file_sep>#ifndef ENGINE_H #define ENGINE_H #include <GL/glew.h> #include <GL/gl.h> #include <SDL2/SDL.h> #include <SDL2/SDL_opengl.h> #include <SDL2/SDL_image.h> #include <stdbool.h> #include "input_processor.h" #include "sprite.h" #include "actor.h" typedef struct engine engine; typedef enum DIRECTION { DIRECTION_N, DIRECTION_E, DIRECTION_S, DIRECTION_W } DIRECTION; enum { SAND_TEXTURE, SPRITES_TEXTURE, NUM_TEXTURES }; typedef enum SPRITES_DECALS { TAIL_S, TAIL_W, HEAD_N, HEAD_E, BODY_SE, BODY_SW, BODY_NW, BLANK, TAIL_E, TAIL_N, HEAD_W, HEAD_S, BODY_N, BODY_E, BODY_NE, APPLE, NUM_SPRITES_DECALS } SPRITES_DECALS; enum { MAX_SNAKE_SEGMENTS = 8 }; #include "apple_actor.h" #include "snake_actor.h" #include "background_actor.h" struct engine { unsigned int fps; unsigned int current_frame; SDL_Window *window; unsigned int w; unsigned int h; SDL_GLContext main_context; Uint32 start_time; bool should_start_logic_loop; unsigned int whole_frames_to_do; // vertex buffer object for the square that is // used for drawing sprites GLuint sprite_vertex_bo; // shader program for shading the sprites displayed // by the engine GLuint shader_program; GLint w_unfm; GLint h_unfm; GLint r_unfm; GLint texture_sampler_unfm; GLint pos_attrib; GLint uv_attrib; actor_list *render_list; actor_list *logic_list; GLuint textures[NUM_TEXTURES]; decal sprites_decals[NUM_SPRITES_DECALS]; decal sand_decal; apple_actor apple_actor; background_actor background_actor; snake_actor snake_actor; }; engine eng; engine *engine_init( unsigned int w, unsigned int h, const char *window_title, unsigned int fps); void engine_destroy(); void engine_start(); #endif <file_sep>#ifndef SHADER_COMPILER_H #define SHADER_COMPILER_H #include <GL/gl.h> GLuint compile_shader( const char *vertex_shader_path, const char *fragment_shader_path ); #endif <file_sep>#ifndef SPRITE_H #define SPRITE_H #include "decal.h" typedef struct sprite sprite; typedef struct sprite_list sprite_list; struct sprite { GLfloat w; GLfloat h; GLfloat r[2]; GLuint vao; decal *d; }; sprite *sprite_init( sprite *sp, double w, double h, decal *d); void sprite_destroy(sprite *sp); void sprite_render(sprite *sp); void sprite_set_decal(sprite *sp, decal *d); #endif <file_sep>#include "engine.h" #include <stdlib.h> void apple_render_handler(actor *a) { apple_actor *ap = (apple_actor *)a; sprite_render(&ap->sprite); } apple_actor *apple_actor_init(apple_actor *ap) { actor_init(&ap->a, apple_render_handler, NULL); sprite_init( &ap->sprite, 40, 40, &eng.sprites_decals[APPLE]); ap->sprite.r[0] = 100; ap->sprite.r[1] = 100; return ap; } void apple_replace(apple_actor *ap) { int i = rand() % (eng.w / 40); int j = rand() % (eng.h / 40); ap->sprite.r[0] = 20 + i * 40; ap->sprite.r[1] = 20 + j * 40; } <file_sep>#ifndef INPUT_PROCESSOR_H #define INPUT_PROCESSOR_H #define GLM_FORCE_RADIANS #include <glm/glm.hpp> #include <glm/gtc/matrix_transform.hpp> #include <glm/gtx/transform.hpp> #include <SDL2/SDL.h> class InputProcessor { private: int actions; double theta; double phi; glm::vec3 position; double speed; double omega; public: glm::mat4 get_proj_mat(); glm::mat4 get_view_mat(); void compute_direction(double dt); void process_event(SDL_Event *event); // class input_processor set_position(glm::vec3 position); InputProcessor( double speed, double omega, const glm::vec3 &position); }; #endif <file_sep>#include <vector> #include <GL/glew.h> #include <GL/gl.h> #define GLM_FORCE_RADIANS #include <glm/glm.hpp> #include <glm/gtc/matrix_transform.hpp> #include <SDL2/SDL.h> #include <SDL2/SDL_opengl.h> #include <SDL2/SDL_image.h> #include <stdlib.h> #include <stdio.h> #include "../shader_compiler/shader_compiler.hpp" #include "../utils/utils.hpp" #include "../InputProcessor/InputProcessor.hpp" #include "hooke_cloth_eng.hpp" #include "../utils/base_eng/base_eng.hpp" #include "drawable.hpp" enum { WIN_W = 800, WIN_H = 600, FPS = 100 }; int main() { SDL_Event event; BaseEng engine(WIN_W, WIN_H, "Hooke Cloth", FPS, NULL); bool carry_on = true; GLuint vao; glGenVertexArrays(1, &vao); glBindVertexArray(vao); GLuint shader_program = compile_shader( "../shaders/basic_shading.vertexshader", "../shaders/basic_shading.fragmentshader"); glUseProgram(shader_program); GLuint program_cursor = compile_shader( "../shaders/simple_shader.vertexshader", "../shaders/simple_shader.fragmentshader"); glUseProgram(program_cursor); glUseProgram(shader_program); GLuint texture_id = load_texture("resources/cloth_texture.png"); GLuint cursor_texture_id = load_texture("resources/cursor_texture.png"); Drawable cloth_drawable( "cloth.bin", shader_program, vao, GL_TEXTURE0, texture_id); GLuint vao_cursor; glGenVertexArrays(1, &vao_cursor); glBindVertexArray(vao_cursor); Drawable cursor_drawable( "cursor.bin", shader_program, vao_cursor, GL_TEXTURE1, cursor_texture_id); Cloth cloth( engine, 5, // pts_w 5, // pts_h cloth_drawable.ordered_positions, 5, // g 50, // hooke constant 12, // damping constant 1 // equilibrium length ); cloth.add_fixed_pt(0, 4); cloth.add_fixed_pt(4, 4); InputProcessor in_processor(0.001, 0.001, glm::vec3(0.0, 0.0, 4)); glm::vec3 light_position_worldspace = glm::vec3(2.0, 2.0, 2.0); GLuint light_pos_id = glGetUniformLocation(shader_program, "light_position_cameraspace"); Uint32 last_time = SDL_GetTicks(); Uint32 curr_time = SDL_GetTicks(); while (carry_on) { // Work through all elapsed logic frames while (engine.should_continue_logic_loops()) { cloth.calc_force(); cloth.iterate(); } curr_time = SDL_GetTicks(); in_processor.compute_direction((double)(curr_time - last_time)); last_time = curr_time; cloth_drawable.update_vertices(cloth.vertices); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glm::mat4 view = in_processor.get_view_mat(); cloth_drawable.set_V(view); cloth_drawable.set_P(in_processor.get_proj_mat()); glm::vec3 light_position_cameraspace(view * glm::vec4(light_position_worldspace, 1.0)); glUniform3f(light_pos_id, light_position_cameraspace.x, light_position_cameraspace.y, light_position_cameraspace.z); cloth_drawable.draw(); cursor_drawable.draw(); #ifdef DEBUG_MODE glUseProgram(0); // Draw normals glMatrixMode(GL_PROJECTION); glLoadMatrixf((const GLfloat*)&projector[0]); glMatrixMode(GL_MODELVIEW); glm::mat4 MV = view * model; glLoadMatrixf((const GLfloat*)&MV[0]); glColor3f(0,0,1); glBegin(GL_LINES); for (unsigned int i=0; i<element_array.size(); i++){ glm::vec3 p = vertices[element_array[i]]; glVertex3fv(&p.x); glm::vec3 o = glm::normalize(normals[element_array[i]]); p+=o*0.1f; glVertex3fv(&p.x); } glEnd(); // Draw line pointing to light position glMatrixMode(GL_MODELVIEW); glLoadMatrixf((const GLfloat*)&view); glColor3f(1,0,0); glBegin(GL_LINES); glm::vec3 p = light_position_worldspace; glVertex3fv(&p.x); p = glm::vec3(0, 0, 0); glVertex3fv(&p.x); glEnd(); glUseProgram(shader_program); #endif SDL_GL_SwapWindow(engine.window); while (SDL_PollEvent(&event)) { if (event.type == SDL_QUIT) { carry_on = false; } in_processor.process_event(&event); } GLenum err = glGetError(); if (err != 0) { switch (err) { case GL_INVALID_ENUM: fprintf(stderr, "invalid enum\n"); break; case GL_INVALID_VALUE: fprintf(stderr, "invalid value\n"); break; case GL_INVALID_FRAMEBUFFER_OPERATION: fprintf(stderr, "invalid fb op\n"); break; case GL_INVALID_OPERATION: fprintf(stderr, "invalid fb\n"); break; case GL_OUT_OF_MEMORY: fprintf(stderr, "no memory\n"); break; } } } // Cleanup glDeleteVertexArrays(1, &vao); glDeleteProgram(shader_program); } <file_sep>#include "base_eng.hpp" #include <GL/glew.h> #include <GL/gl.h> #include <SDL2/SDL.h> #include <SDL2/SDL_opengl.h> bool BaseEng::should_continue_logic_loops() { if (!this->start_time) { this->start_time = SDL_GetTicks(); } if (should_start_logic_loop) { Uint32 logic_loop_start_time = SDL_GetTicks(); double elapsed_frames = (double)(logic_loop_start_time \ - this->start_time) / 1000.0f * this->fps; this->frames_last_render_loop = 0; this->whole_frames_to_do = (unsigned int)elapsed_frames - this->current_frame; } if (!this->whole_frames_to_do) { this->should_start_logic_loop = true; return false; } this->whole_frames_to_do -= 1; this->current_frame += 1; this->frames_last_render_loop += 1; this->should_start_logic_loop = false; return true; } BaseEng::BaseEng( int w, int h, const char *window_title, unsigned int fps, BaseInputProcessor *input_processor) : fps(fps), current_frame(0), frames_last_render_loop(0), base_input_processor(input_processor), should_start_logic_loop(true), whole_frames_to_do(0), start_time(0) { if(SDL_Init(SDL_INIT_VIDEO) == -1){ fprintf(stderr, "Video initialisation failed: %s\n", SDL_GetError()); exit(1); } #ifndef DEBUG_MODE SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 3); SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 3); #endif this->window = SDL_CreateWindow( window_title, SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, w, h, SDL_WINDOW_OPENGL); if(window == NULL) { fprintf(stderr, "Window could not be created: %s\n", SDL_GetError()); exit(1); } this->main_context = SDL_GL_CreateContext(window); // Initialize GLEW glewExperimental = GL_TRUE; if (glewInit() != GLEW_OK) { fprintf(stderr, "Failed to initialize GLEW\n"); exit(1); } SDL_GL_SetSwapInterval(1); // Enable depth test glEnable(GL_DEPTH_TEST); // glEnable(GL_CULL_FACE); // Accept fragment if it closer to the camera than the former one glDepthFunc(GL_LESS); glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); } BaseEng::~BaseEng() { SDL_GL_DeleteContext(this->main_context); SDL_DestroyWindow(this->window); SDL_Quit(); } <file_sep>#include "engine.h" #include "sprite.h" sprite *sprite_init( sprite *sp, double w, double h, decal *d) { sp->w = w; sp->h = h; sp->d = d; sp->r[0] = 0.0f; sp->r[1] = 0.0f; glGenVertexArrays(1, &sp->vao); glBindVertexArray(sp->vao); glBindBuffer(GL_ARRAY_BUFFER, d->uv_bo); glVertexAttribPointer(eng.uv_attrib, 2, GL_FLOAT, GL_FALSE, 0, 0); glEnableVertexAttribArray(eng.uv_attrib); glBindBuffer(GL_ARRAY_BUFFER, eng.sprite_vertex_bo); glVertexAttribPointer(eng.pos_attrib, 2, GL_FLOAT, GL_FALSE, 0, 0); glEnableVertexAttribArray(eng.pos_attrib); return sp; } void sprite_render(sprite *sp) { glBindVertexArray(sp->vao); glUniform1i(eng.texture_sampler_unfm, sp->d->texture_index); glUniform1f(eng.w_unfm, sp->w); glUniform1f(eng.h_unfm, sp->h); glUniform2fv(eng.r_unfm, 1, sp->r); glDrawArrays(GL_TRIANGLES, 0, 6); GLenum errno; while ((errno = glGetError())) { fprintf(stderr, "%x\n", errno); } } void sprite_set_decal(sprite *sp, decal *d) { glBindVertexArray(sp->vao); sp->d = d; glBindBuffer(GL_ARRAY_BUFFER, d->uv_bo); glVertexAttribPointer(eng.uv_attrib, 2, GL_FLOAT, GL_FALSE, 0, 0); } <file_sep>#include <algorithm> #include <set> #include <SDL2/SDL.h> #include "gen_input_processor.hpp" template <class states_enum> void GenInputProcessor<states_enum>::test_meth( states_enum s) { binding<states_enum> b = { .s = s}; bindings.insert(b); } template <class states_enum> void GenInputProcessor<states_enum>::add_key_binding( SDL_Keycode k, states_enum s) { binding<states_enum> b = {.k = k, .s = s}; bindings.insert(b); } template <class states_enum> void GenInputProcessor<states_enum>::rm_key_binding( SDL_Keycode k, states_enum s) { binding<states_enum> b = {.k = k, .s = s}; bindings.erase(b); } template <class states_enum> void GenInputProcessor<states_enum>::process_input(SDL_Event *event) { SDL_Keycode key = event->key.keysym.sym; typename std::set<binding<states_enum> >::iterator res = \ std::find_if(bindings.begin(), bindings.end(), key); if (res != bindings.end()) { active_states.insert(res->s); } } template <class states_enum> bool GenInputProcessor<states_enum>::is_state_active(states_enum s) { if (active_states.find(s) != active_states.end()) { return true; } return false; } <file_sep>CC = g++ CFLAGS = -pg -g -Wall -lGL simple_obj_reader: simple_obj_reader.cpp $(CC) simple_obj_reader.cpp \ $(CFLAGS) -o simple_obj_reader bin_obj_reader: bin_obj_reader.cpp $(CC) bin_obj_reader.cpp \ -shared -fPIC -o libbinobjreader.so clean: rm -f *.o simple_obj_reader bin_obj_reader <file_sep>#include "utils.hpp" #include <GL/glew.h> #include <GL/gl.h> #include <SDL2/SDL.h> #include <SDL2/SDL_opengl.h> #include <SDL2/SDL_image.h> SDL_Window *window; SDL_GLContext main_context; void init_sdl_gl_window(int w, int h, const char*title) { if(SDL_Init(SDL_INIT_VIDEO) == -1){ fprintf(stderr, "Video initialisation failed: %s\n", SDL_GetError()); exit(1); } #ifndef DEBUG_MODE SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 3); SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 3); #endif window = SDL_CreateWindow( title, SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, w, h, SDL_WINDOW_OPENGL); if(window == NULL) { fprintf(stderr, "Window could not be created: %s\n", SDL_GetError()); exit(1); } main_context = SDL_GL_CreateContext(window); // Initialize GLEW glewExperimental = GL_TRUE; if (glewInit() != GLEW_OK) { fprintf(stderr, "Failed to initialize GLEW\n"); exit(1); } SDL_GL_SetSwapInterval(1); // Enable depth test glEnable(GL_DEPTH_TEST); glEnable(GL_CULL_FACE); // Accept fragment if it closer to the camera than the former one glDepthFunc(GL_LESS); } GLuint load_texture(const char *fname) { GLuint texture_id; SDL_Surface *img = IMG_Load(fname); if(!img){ fprintf(stderr, "Error! Could not load %s\n", fname); exit(1); } glGenTextures(1, &texture_id); glBindTexture(GL_TEXTURE_2D, texture_id); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, img->w, img->h, 0, GL_RGBA, GL_UNSIGNED_BYTE, img->pixels); SDL_FreeSurface(img); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR_MIPMAP_LINEAR); glGenerateMipmap(GL_TEXTURE_2D); return texture_id; } void swap_sdl_gl_window() { SDL_GL_SwapWindow(window); } void destroy_sdl_gl_window() { SDL_GL_DeleteContext(main_context); SDL_DestroyWindow(window); SDL_Quit(); } <file_sep>#ifndef MO_ENG_H #define MO_ENG_H #include "../utils/base_eng/base_eng.hpp" #include "../boaler/boaler.hpp" #include "mo_billboard.hpp" #include <vector> #define GLM_FORCE_RADIANS #include <glm/glm.hpp> #include <glm/gtc/matrix_inverse.hpp> #include <json-c/json.h> #include <exception> struct MoEngReturnException : public std::exception {}; enum { NUMBER_OF_SHADERS = 1, NUMBER_OF_OBJECTS_ALLOWED = 9 }; enum { BASE_MODEL_TRIANGLE = 0, BASE_MODEL_RECTANGLE = 1 }; enum game_states { MV_UP, MV_DOWN, MV_LEFT, MV_RIGHT, MV_FORWARD, MV_BACKWARD, CHANGE_TEXTURE, CHANGE_MODEL, GLOBAL_MODE, ROTATE_MODE_SWITCH, ROTATE_MODE, DELETE_OBJECT, GLOBAL_MODE_SWITCH, SUBMIT_REQUEST, NO_DIGIT_PRESSED, PRESSED_1, PRESSED_2, PRESSED_3, PRESSED_4, PRESSED_5, PRESSED_6, PRESSED_7, PRESSED_8, PRESSED_9, PRESSED_0 }; enum object_mode { OBJECT_MODE_INACTIVE, OBJECT_MODE_ACTIVE, OBJECT_MODE_ROTATE }; typedef class MoBillboard MoBillboard; typedef class MoEng MoEng; class MoObject { public: MoObject(unsigned int object_index); ~MoObject(); static void prep(MoEng *eng); void change_model(unsigned int new_model_index); void change_texture(); void move(glm::vec3 direction_modelspace); void rotate(glm::vec3 rotation_axis); void put_in_rotate_mode(); void put_in_active_mode(); void put_in_normal_mode(); object_mode mode; static MoEng *eng; unsigned int object_index; unsigned int model_index; unsigned int texture_index; unsigned int shader_index; BoalerModelUnit *model_unit; BoalerVSLModelUnitLink *vslm_link; MoBillboard *billboard; }; struct mo_model_template { BoalerModel *model; GLfloat r_bb; std::vector<GLuint> textures; }; class MoEng : public BaseEng { public: MoEng( const char *setup_file_path, int w, int h, const char *window_title, unsigned int fps); glm::vec3 initial_camera_pos; void create_key_bindings(); int load_textures_for_model_template( mo_model_template *mo_template, json_object *texture_lib, json_object *textures_j); int setup_with_file(const char*setup_file_path); void enter_global_mode(); void check_digit(int value); void read_for_requested_object(); void render(); void process_input(SDL_Event *event); MoObject *add_object(unsigned int model_index); void set_active_object( unsigned int new_active_object_index); void move_active_object_on_request(); void rotate_active_object_on_request(); void delete_active_object(); void change_active_object_model(); void do_logic(); GenInputProcessor<game_states> *input_processor; BoalerEng beng; BoalerShaderUnit billboard_shader_unit; std::vector<mo_model_template> model_templates; BoalerShaderUnit *shaders[NUMBER_OF_SHADERS]; BoalerViewUnit view_unit; BoalerVSLink *view_shader_links[NUMBER_OF_SHADERS]; unsigned int object_index_being_requested; unsigned int frames_since_last_entry; game_states last_digit_pressed; unsigned int active_object_index; MoObject *active_object; std::vector<MoObject *> objects; MoObject *indexed_objects[NUMBER_OF_OBJECTS_ALLOWED]; }; #endif <file_sep>Menge Sponge ============ Explore an approximation to a menge sponge fractal. Use arrow keys to look in directions and 'a' key to move in that direction. Uses instanced rendering <file_sep>#include "hooke_cloth_eng.hpp" #include <vector> #include <GL/glew.h> #include <GL/gl.h> #include <stdio.h> #define GLM_FORCE_RADIANS #include <glm/glm.hpp> Cloth::Cloth( BaseEng &eng, unsigned int pts_w, unsigned int pts_h, std::vector<glm::vec3> &pts, double g, double hooke_constant, double damping_constant, double equil_length) : eng(eng) { this->pts_w = pts_w; this->pts_h = pts_h; this->init_points(pts); this->g_frame_unit = g / (eng.fps * eng.fps); this->hooke_constant_frame_unit = hooke_constant / (eng.fps * eng.fps); this->damping_constant_frame_unit = damping_constant / eng.fps; this->equil_length = equil_length; for (unsigned int i = 0; i < this->cloth_pts.size(); i++) { fprintf(stderr, "cloth pt %d: (%f, %f, %f)\n",i, this->cloth_pts[i].r->x, this->cloth_pts[i].r->y, this->cloth_pts[i].r->z); if (this->cloth_pts[i].right != NULL) { fprintf(stderr, "cloth pt %d right: (%f, %f, %f)\n",i, this->cloth_pts[i].right->r->x, this->cloth_pts[i].right->r->y, this->cloth_pts[i].right->r->z); } if (this->cloth_pts[i].above != NULL) { fprintf(stderr, "cloth pt %d above: (%f, %f, %f)\n",i, this->cloth_pts[i].above->r->x, this->cloth_pts[i].above->r->y, this->cloth_pts[i].above->r->z); } } } void Cloth::init_points(std::vector<glm::vec3> &pts) { unsigned int w = this->pts_w; unsigned int h = this->pts_h; if (pts.size() != w * h) { fprintf(stderr, "Not enough points for specified width and height!\n"); exit(1); } this->vertices.resize(w * h); this->cloth_pts.resize(w * h); for (unsigned int j = 0; j < h; j++) { for (unsigned int i = 0; i < w; i++) { int index = w * j + i; this->vertices[index] = pts[index]; this->cloth_pts[index] = ClothPt(this, &this->vertices[index]); if (i != 0) { this->cloth_pts[index - 1].right = &this->cloth_pts[index]; } if (j != 0) { this->cloth_pts[index - w].above = &this->cloth_pts[index]; } } } } void Cloth::calc_force() { unsigned int w = this->pts_w; unsigned int h = this->pts_h; for (unsigned int j = 0; j < h; j++) { for (unsigned int i = 0; i < w; i++) { int index = w * j + i; this->cloth_pts[index].calc_force(); } } // Fix the points that need to be fixed for (unsigned int i = 0; i < this->fixed_pts.size(); i++) { this->cloth_pts[this->fixed_pts[i]].a = glm::vec3(0,0,0); } } void Cloth::iterate() { unsigned int w = this->pts_w; unsigned int h = this->pts_h; for (unsigned int j = 0; j < h; j++) { for (unsigned int i = 0; i < w; i++) { int index = w * j + i; this->cloth_pts[index].iterate(); } } } void Cloth::add_fixed_pt(unsigned int x, unsigned int y) { unsigned int pt_index = this->pts_h * y + x; if (pt_index + 1 > this->pts_w * this->pts_h) { return; } for (unsigned int i = 0; i < this->fixed_pts.size(); i++) { if (this->fixed_pts[i] == pt_index) { return; } } this->fixed_pts.push_back(pt_index); } ClothPt::ClothPt() { this->cloth = NULL; this->r = NULL; this->v = glm::vec3(0,0,0); this->a = glm::vec3(0,0,0); this->right = NULL; this->above = NULL; } ClothPt::ClothPt(Cloth *cloth, glm::vec3 *r) { this->cloth = cloth; this->r = r; this->v = glm::vec3(0,0,0); this->a = glm::vec3(0,0,0); this->right = NULL; this->above = NULL; } void ClothPt::calc_force() { double k = this->cloth->hooke_constant_frame_unit; float D = this->cloth->damping_constant_frame_unit; double g = this->cloth->g_frame_unit; double x_o = this->cloth->equil_length; glm::vec3 a_right = glm::vec3(0.0f, 0.0f, 0.0f); if (this->right) { double x_right = glm::length(*(this->right->r) - *(this->r)); glm::vec3 d_right = glm::normalize(*(this->right->r) - *(this->r)); a_right = (GLfloat)(k * (x_right - x_o)) * d_right; this->a += a_right + (D * (this->right->v - this->v)); this->right->a -= a_right + (D * (this->right->v - this->v)); } if (this->above) { double x_above = glm::length(*(this->above->r) - *(this->r)); glm::vec3 d_above = glm::normalize(*(this->above->r) - *(this->r)); glm::vec3 a_above = (GLfloat)(k * (x_above - x_o)) * d_above; this->a += a_above + (D * (this->above->v - this->v)); this->above->a -= a_above + (D * (this->above->v - this->v)); } // Addition of gravity this->a += glm::vec3(0,-g,0); } void ClothPt::iterate() { *(this->r) += v; this->v += a; this->a = glm::vec3(0,0,0); } <file_sep>#include <stdio.h> enum { width = 4, height = 4, texture_total_width = 512, texture_total_height = 512, texture_width = 300, texture_height = 300 }; int main() { for (unsigned int j = 0; j < height + 1; j++) { for (unsigned int i = 0; i < width + 1; i++) { fprintf(stdout, "v %d %d 0 \n", i, j); } } fprintf(stdout, "vt 0 0\n" "vt %f 0\n" "vt 0 %f\n" "vt %f %f\n", (float)texture_width / (float)texture_total_width, (float)texture_height / (float)texture_total_height, (float)texture_width / (float)texture_total_width, (float)texture_height / (float)texture_total_height); fprintf(stdout, "vn 0 0 1\n"); for (unsigned int j = 0; j < height; j++) { for (unsigned int i = 0; i < width; i++) { fprintf( stdout, "f %d/3/1 %d/4/1 %d/2/1\n" "f %d/3/1 %d/2/1 %d/1/1\n", 1 + i + (width + 1) * j, 1 + i + 1 + (width + 1) * j, 1 + i + 1 + (width + 1) * (j + 1), 1 + i + (width + 1) * j, 1 + i + 1 + (width + 1) * (j + 1), 1 + i + (width + 1) * (j + 1) ); } } } <file_sep>#include <vector> #include <GL/glew.h> #include <GL/gl.h> #define GLM_FORCE_RADIANS #include <glm/glm.hpp> #include <glm/gtc/matrix_transform.hpp> #include <glm/gtc/matrix_inverse.hpp> #include <SDL2/SDL.h> #include <SDL2/SDL_opengl.h> #include <SDL2/SDL_image.h> #include <stdlib.h> #include <stdio.h> #include "../utils/base_eng/base_eng.hpp" #include "../shader_compiler/shader_compiler.hpp" #include "../utils/utils.hpp" #include "../InputProcessor/gen_input_processor.hpp" #include "boaler.hpp" #include "../cameras/fp_camera.hpp" #include "../billboard/billboard.hpp" #include "../text_texture/text_texture.hpp" #include "mo_billboard.hpp" #include "mo_eng.hpp" enum { WIN_W = 800, WIN_H = 600, FPS = 100 }; unsigned int direction_fn(const BaseEng &eng) { unsigned int direction = CAM_MV_NONE; GenInputProcessor<game_states> *input_processor = static_cast<GenInputProcessor<game_states> *>(eng.base_input_processor); const MoEng &mo_eng = static_cast<const MoEng &>(eng); if (mo_eng.active_object) { return 0; } if (input_processor->is_state_active(MV_UP)) { direction |= CAM_MV_UP; } if (input_processor->is_state_active(MV_DOWN)) { direction |= CAM_MV_DOWN; } if (input_processor->is_state_active(MV_LEFT)) { direction |= CAM_MV_LEFT; } if (input_processor->is_state_active(MV_RIGHT)) { direction |= CAM_MV_RIGHT; } if (input_processor->is_state_active(MV_FORWARD)) { direction |= CAM_MV_FORWARD; } return direction; } struct texture_struct { unsigned int texture_unit_index; GLuint texture_id; }; void change_texture(const BaseEng &eng, BoalerModelUnit &mu, const texture_struct *ts) { GenInputProcessor<game_states> *input_processor = static_cast<GenInputProcessor<game_states> *>(eng.base_input_processor); static bool texture_should_change = true; static unsigned int i = 0; if (input_processor->is_state_active(CHANGE_TEXTURE) && texture_should_change) { i = (i + 1) % 2; mu.texture_unit_index = ts[i].texture_unit_index; mu.texture_id = ts[i].texture_id; texture_should_change = false; return; } if (!input_processor->is_state_active(CHANGE_TEXTURE)) { texture_should_change = true; } } int main() { try { SDL_Event event; MoEng engine( "resources/fishbowl/fishbowl.json", WIN_W, WIN_H, "Multi object draw", FPS); bool carry_on = true; FpCamera camera( engine, 0.8, 0.5, engine.initial_camera_pos, direction_fn); glClearColor(0.2f, 0.2f, 0.2f, 1.0f); while(carry_on) { // Work through all elapsed logic frames while (engine.should_continue_logic_loops()) { camera.compute_direction(); engine.do_logic(); } engine.view_unit.V = camera.get_V(); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); engine.render(); SDL_GL_SwapWindow(engine.window); while (SDL_PollEvent(&event)) { if (event.type == SDL_QUIT) { carry_on = false; } engine.process_input(&event); } } } catch (const MoEngReturnException& e) { return EXIT_FAILURE; } } <file_sep>CC = gcc CFLAGS = -pg -g -Wall -lGL -lGLEW -lSDL2 -lSDL2_image all: simple.vertexshader simple.fragmentshader main.c engine.c engine.h input_processor.c input_processor.h \ sprite.c sprite.h decal.c decal.h actor.c actor.h snake_actor.c snake_actor.h background_actor.c background_actor.h \ apple_actor.c apple_actor.h xxd -i < simple.vertexshader > simple_vertexshader.h echo ', 0' >> simple_vertexshader.h xxd -i < simple.fragmentshader > simple_fragmentshader.h echo ', 0' >> simple_fragmentshader.h $(CC) decal.c sprite.c engine.c input_processor.c actor.c snake_actor.c background_actor.c apple_actor.c main.c $(CFLAGS) -o snake clean: rm -f *.o <file_sep>#include "engine.h" void snake_render_handler(actor *a) { snake_actor *sn = (snake_actor *)a; int i; for (i = 0; i < sn->num_segments; i++) { sprite_render(&(sn->snake_sprites[i])); } } void snake_direction_to_vector(snake_actor *sn, GLfloat *r) { switch (sn->direction) { case DIRECTION_N: r[0] = 0; r[1] = sn->segment_h; break; case DIRECTION_E: r[0] = sn->segment_w; r[1] = 0; break; case DIRECTION_S: r[0] = 0; r[1] = -(int)sn->segment_h; break; case DIRECTION_W: r[0] = -(int)sn->segment_w; r[1] = 0; break; } } SPRITES_DECALS snake_get_neck_decal(snake_actor *sn, DIRECTION old_direction) { switch (sn->direction) { case DIRECTION_N: switch (old_direction) { case DIRECTION_W: return BODY_NE; case DIRECTION_E: return BODY_NW; default: return BODY_N; } case DIRECTION_E: switch (old_direction) { case DIRECTION_N: return BODY_SE; case DIRECTION_S: return BODY_NE; default: return BODY_E; } case DIRECTION_S: switch (old_direction) { case DIRECTION_W: return BODY_SE; case DIRECTION_E: return BODY_SW; default: return BODY_N; } return BODY_N; case DIRECTION_W: switch (old_direction) { case DIRECTION_N: return BODY_SW; case DIRECTION_S: return BODY_NW; default: return BODY_E; } } return BODY_N; } SPRITES_DECALS snake_get_head_decal(snake_actor *sn) { switch (sn->direction) { case DIRECTION_N: return HEAD_N; case DIRECTION_E: return HEAD_E; case DIRECTION_S: return HEAD_S; case DIRECTION_W: return HEAD_W; } return HEAD_N; } SPRITES_DECALS snake_get_tail_decal(snake_actor *sn) { unsigned int next_to_tail_index = (sn->tail_index + 1) % sn->num_segments; if (sn->snake_sprites[next_to_tail_index].r[0] > sn->snake_sprites[sn->tail_index].r[0]) { if (sn->snake_sprites[next_to_tail_index].r[0] - sn->snake_sprites[sn->tail_index].r[0] > sn->segment_w) { return TAIL_W; } return TAIL_E; } if (sn->snake_sprites[next_to_tail_index].r[0] < sn->snake_sprites[sn->tail_index].r[0]) { if (sn->snake_sprites[sn->tail_index].r[0] - sn->snake_sprites[next_to_tail_index].r[0] > sn->segment_w) { return TAIL_E; } return TAIL_W; } if (sn->snake_sprites[next_to_tail_index].r[1] > sn->snake_sprites[sn->tail_index].r[1]) { if (sn->snake_sprites[next_to_tail_index].r[1] - sn->snake_sprites[sn->tail_index].r[1] > sn->segment_h) { return TAIL_S; } return TAIL_N; } if (sn->snake_sprites[sn->tail_index].r[1] - sn->snake_sprites[next_to_tail_index].r[1] > sn->segment_h) { return TAIL_N; } return TAIL_S; } void snake_apply_boundary_conditions(snake_actor *sn, GLfloat *r) { if (r[0] + sn->segment_w / 2 > eng.w) { r[0] = sn->segment_w / 2; } if (r[0] - sn->segment_w / 2 < 0) { r[0] = eng.w - sn->segment_w / 2.; } if (r[1] + sn->segment_h / 2 > eng.h) { r[1] = sn->segment_h / 2; } if (r[1] - sn->segment_h / 2 < 0) { r[1] = eng.h - sn->segment_h / 2.; } } sprite *snake_get_head_sprite(snake_actor *sn) { int head_index = ((sn->tail_index - 1 + sn->num_segments) % sn->num_segments); return &sn->snake_sprites[head_index]; } void snake_apple_collision_detect(snake_actor *sn) { sprite *snake_head = snake_get_head_sprite(sn); if (snake_head->r[0] == eng.apple_actor.sprite.r[0] && snake_head->r[1] == eng.apple_actor.sprite.r[1]) { apple_replace(&eng.apple_actor); } } void snake_logic_handler(actor *a) { snake_actor * sn = (snake_actor *)a; if (eng.current_frame % sn->snake_frame_ratio == 0) { DIRECTION old_direction = sn->direction; if (is_state_active(GS_N)) { deactivate_state(GS_N); if (sn->direction != DIRECTION_S) { sn->direction = DIRECTION_N; } } else if (is_state_active(GS_E)) { deactivate_state(GS_E); if (sn->direction != DIRECTION_W) { sn->direction = DIRECTION_E; } } else if (is_state_active(GS_S)) { deactivate_state(GS_S); if (sn->direction != DIRECTION_N) { sn->direction = DIRECTION_S; } } else if (is_state_active(GS_W)) { deactivate_state(GS_W); if (sn->direction != DIRECTION_E) { sn->direction = DIRECTION_W; } } sprite *old_head = snake_get_head_sprite(sn); SPRITES_DECALS decal = snake_get_neck_decal(sn, old_direction); sprite_set_decal(old_head, &(eng.sprites_decals[decal])); sprite *new_head = &sn->snake_sprites[sn->tail_index]; snake_direction_to_vector(sn, new_head->r); new_head->r[0] += old_head->r[0]; new_head->r[1] += old_head->r[1]; snake_apply_boundary_conditions(sn, new_head->r); decal = snake_get_head_decal(sn); sprite_set_decal(new_head, &(eng.sprites_decals[decal])); sn->tail_index = (sn->tail_index + 1) % sn->num_segments; decal = snake_get_tail_decal(sn); sprite_set_decal(&sn->snake_sprites[sn->tail_index], &(eng.sprites_decals[decal])); snake_apple_collision_detect(sn); } } snake_actor *snake_actor_init(snake_actor *sn) { sn->num_segments = 3; sn->segment_w = 40; sn->segment_h = 40; actor_init(&(sn->a), snake_render_handler, snake_logic_handler); int i; SPRITES_DECALS snake_init_config[] = {TAIL_E, BODY_E, HEAD_E}; GLfloat tail_pos[] = {sn->segment_w / 2, sn->segment_w / 2}; for (i = 0; i < sn->num_segments; i++) { sprite_init( &(sn->snake_sprites[i]), sn->segment_w, sn->segment_h, &(eng.sprites_decals[snake_init_config[i]])); sn->snake_sprites[i].r[0] = tail_pos[0] + i * sn->segment_w; sn->snake_sprites[i].r[1] = tail_pos[1]; } sn->direction = DIRECTION_E; float seconds_per_update = 0.1; sn->snake_frame_ratio = eng.fps * seconds_per_update; sn->tail_index = 0; return sn; } <file_sep>Multi-object Draw ================= Program for experimenting with developing a graphics engine. Editing the scene is done in a modal way, with global, model and rotation modes The mode is indicated by the colour of the billboards above the models with: blue = global mode yellow = model mode (with yellow billboard above active model) green = rotation mode (with green billboard above active model) In global mode ------------- Press 'm' to draw a new model at the position you are currently looking at (puts you into model mode) Input a number and press 'enter' to enter model mode and make the object with that number on its billboard the active model Use the arrow keys to look around, and 'a' to move forward in direction you are currently looking in In model mode ------------- Press 'm' multiple times to cycle through various different models Use arrow keys to move model around along its local x and y axes. Use a/s to move along model's positive/negative z axes Press 'r' to enter rotation mode for the currently active model Press 'esc' to enter global mode In rotation mode ---------------- Use arrow keys and a/s to rotate around x,y,z axes Press 'r' to re-enter model mode Press 'esc' to enter global mode <file_sep>#ifndef BACKGROUND_ACTOR_H #define BACKGROUND_ACTOR_H #include "engine.h" typedef struct background_actor background_actor; struct background_actor { actor a; sprite background_sprite; }; background_actor *background_actor_init(background_actor *bg); #endif <file_sep>#include "engine.h" #include "snake_actor.h" #include "background_actor.h" int main() { engine_init( 800, 600, "Snake", 100); engine_start(); engine_destroy(); } <file_sep># gl_demos Collection of demos using modern openGL <file_sep>#ifndef TEXT_TEXTURE_H #define TEXT_TEXTURE_H #include <GL/glew.h> #include <GL/gl.h> #include <SDL2/SDL.h> #include <SDL2/SDL_opengl.h> #include <cairo.h> #include <pango/pangocairo.h> #include <string.h> enum {TEXTLENGTH = 80}; // Max amount of characters (including null // character) that can be written on texture class TextTexture { public: SDL_Rect txt_rect; // SDL Rect describing the position of // text relative to bg. If there is no // bg just describes the width and height // of the texture SDL_Surface *bg_img; // Background image of surface SDL_Surface *surface; // SDL Surface that bg img and text // is blitted onto prior to display SDL_Surface *txt_surface; // SDL Surface text is drawn onto char text[TEXTLENGTH]; cairo_surface_t *cairo_surface; cairo_t *cr; PangoLayout *layout; PangoFontDescription *font_description; GLuint texture_id; // Handle to openGL texture that will contain // this text TextTexture(SDL_Rect txt_rect, SDL_Surface *bg_img = NULL); void set_text(const char *text_input); }; #endif <file_sep>#ifndef FP_CAMERA_H #define FP_CAMERA_H #include "../utils/base_eng/base_eng.hpp" #include <GL/glew.h> #include <GL/gl.h> #define GLM_FORCE_RADIANS #include <glm/glm.hpp> #include <glm/gtc/matrix_transform.hpp> #include <glm/gtx/transform.hpp> enum cam_mv_dn { CAM_MV_NONE = 0, CAM_MV_UP = 1, CAM_MV_DOWN = 1<<1, CAM_MV_LEFT = 1<<2, CAM_MV_RIGHT = 1<<3, CAM_MV_FORWARD = 1<<4 }; typedef unsigned int (*get_direction_fn)(const BaseEng &); class FpCamera { public: FpCamera( BaseEng &engine, double speed, double omega, const glm::vec3 &position, get_direction_fn get_direction); BaseEng &engine; glm::mat4 get_V(); void compute_direction(); private: double speed_frame_unit; double omega_frame_unit; glm::vec3 position; get_direction_fn get_direction; double phi; double theta; }; #endif
2130126f1c5463faf18f19db801d3559f9cafda4
[ "Markdown", "Makefile", "Python", "C", "C++" ]
62
C
John-Sharp/gl_demos
8a17f1236d73b031feabc788b5a6cdc123af68ec
482ec62e2c16b886e959c1806fcaed0c8781891e
refs/heads/master
<file_sep>/** * Created by eloy on 29/11/16. */ package factorial_capsa_negra; /* * Aquest algorisme no té en compte els valors negatius que demana a l'exercici * Tampoc permet calcular valors superiors a factorial(12) ja que dóna error, cal * pensar que s'ha utilitzat un int en lloc de un long. */ public class Factorial_capsa_negra { public static int factorial(int n){ if(n == 0 || n== 1){ return 1; } return n * factorial(n - 1); } /* Aquesta funció millora l'anterior */ public static long factorial_bo(int n){ if(n < 0) { return -1; } if(n == 0 || n== 1){ return 1; } return n * factorial(n - 1); } public static void main(String[] args){ System.out.println(factorial(Integer.parseInt(args[0]))); } }
0958bae0ca556d88d02e82c4ec6d9dba2bddc760
[ "Java" ]
1
Java
EloyAlbiach/java-capsa-negra
d1069a64cf2d09c0312a0f90f7446384b647c3f1
adb979febc81803a7e8eccd9b8bf40e6243f16d4
refs/heads/master
<file_sep>package com.example.demo.user; import javax.persistence.GeneratedValue; import javax.persistence.Id; public class User { } <file_sep>package studentForm; import java.util.LinkedHashMap; import javax.validation.constraints.NotNull; import javax.validation.constraints.Size; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; @Getter@Setter public class Student { @NotNull @Size(min = 4,max = 18,message = "invalid name") private String fname,lname; private String country,favoriteLanguage; private String[] os; private LinkedHashMap<String, String> countries; public Student() { super(); countries = new LinkedHashMap<>(); countries.put("IN", "India"); countries.put("BR", "Brazil"); countries.put("FR", "France"); countries.put("GER", "Germany"); countries.put("ITY", "Italy"); countries.put("US", "United States of America"); } } <file_sep>package thread.group; public class ThreadGroupTest { public static void main(String[] args) { System.out.print("number of active threads: "); System.out.print(Thread.currentThread().getThreadGroup().activeCount() + " "+Thread.currentThread()+"\n\n"); Thread t1 = new SimpleThread1("Boston"); t1.start(); System.out.print("number of active threads: "); System.out.print(Thread.currentThread().getThreadGroup().activeCount() + "\n"); Thread t2 = new SimpleThread1("New York"); t2.start(); System.out.print("number of active threads: "); System.out.print(Thread.currentThread().getThreadGroup().activeCount() + "\n"); Thread t3 = new SimpleThread1("Telangana"); t3.start(); System.out.print("number of active threads: "); System.out.print(Thread.currentThread().getThreadGroup().activeCount() + "\n"); // System.out.println(Thread.currentThread().getThreadGroup()); /* * SimpleThread1 s1 = new SimpleThread1("Boston"); SimpleThread1 s2 = new * SimpleThread1("Boston"); SimpleThread1 s3 = new SimpleThread1("Boston"); * Thread t1= new Thread(s1); Thread t2= new Thread(s2); Thread t3= new * Thread(s3); t1.start(); t2.start(); t3.start(); */ } } <file_sep>package customerServlet; import java.io.IOException; import java.sql.SQLException; import java.util.List; public interface CustomerDao { public Customer createCustomer(Customer customer) throws SQLException, IOException; public List<Customer> getAllCustomers(); public void updateCustomer(Customer c); public Customer findById(int id); } <file_sep>package employeeAssignment; import java.util.List; public class EmployeeBO { public static void printEmployees(List<Employee> e1) { System.out.format("%-15s %-30s %-30s %-10s %-10s %-5s\n","id","name","dest","DoJ","Age","Salary"); for(Employee e:e1) System.out.println(e); } } <file_sep>package comm.customer.flightBooking; import java.io.IOException; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import java.util.logging.Logger; public class FlightBookingDAOImpl implements FlightBookingDAO { private MyConnectionFactory factory = null; private Connection connection = null; PreparedStatement pStatement = null; static Logger logger = Logger.getLogger("com.customer.jdbcMaven1.CustomerDAOImpl"); private FlightBooking fb = null; { factory = MyConnectionFactory.getFactoryObject(); try { logger.info("connection started"); connection = factory.getMyConnection(); logger.info("got connection"); } catch (IOException | SQLException e) { e.printStackTrace(); logger.info("connection unsucessfull"); } } @Override public List<FlightBooking> displayFlightBooking() throws Exception { pStatement = connection.prepareStatement("select flightno,noofseats from flightbooking"); ResultSet rSet = pStatement.executeQuery(); List<FlightBooking> list = new ArrayList<FlightBooking>(); while (rSet.next()) { FlightBooking fb = new FlightBooking(rSet.getString("flightno"), rSet.getInt("noofseats")); list.add(fb); } return list; } @Override public FlightBooking updateFlightBooking(FlightBooking fb1,int noofseats) throws Exception { pStatement = connection.prepareStatement("update customer set noofseats=noofseats-? where flightno=?"); pStatement.setInt(1, noofseats); pStatement.setString(2, fb1.getFlightno()); pStatement.executeUpdate(); return fb1; } } <file_sep>package enum1; public enum DAY { SUNDAY("Today is Holiday",1), MONDAY("Today is Monday",2), TUESDAY("Today is Tuesday",3), WEDNESDAY("Today is Wednesday",4), THURSDAY("Today is Thursday",5), FRIDAY("Today is Friday",6), SATDAY("Today is Holiday",7); private final String day1; private final int no; private DAY(String string, int i) { day1 = string; no = i; } public String getDay1() { return day1; } public int getNo() { return no; } } <file_sep>package myOnlineShop; public class Books extends Product { private String publisher; private int yearPublished; public Books(double regularPrice, String publisher, int yearPublished) { super(regularPrice); this.publisher = publisher; this.yearPublished = yearPublished; } public String getPublisher() { return publisher; } public void setPublisher(String publisher) { this.publisher = publisher; } public int getYearPublished() { return yearPublished; } public void setYearPublished(int yearPublished) { this.yearPublished = yearPublished; } @Override public double computeSalesPrice() { // TODO Auto-generated method stub return getRegularPrice(); } } <file_sep>insert into Student(first_name,last_name,email) values('sravan','kumar','<EMAIL>'); insert into Student(first_name,last_name,email) values('balaji','','<EMAIL>'); <file_sep>package com.hibernate.taskTodo; import java.time.LocalDateTime; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Table; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; @NoArgsConstructor@AllArgsConstructor @Entity@Data public class TodoTask { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private int todoId; private String id; private String name; private LocalDateTime crtDateTime; public TodoTask(String id, String name, LocalDateTime crtDateTime) { todoId++; this.id=id; this.name=name; this.crtDateTime=crtDateTime; } } <file_sep>package com.example.demo; import org.springframework.boot.CommandLineRunner; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class SpringBootDemo1Application { //implements CommandLineRunner{ /* * private ToDoDao toDoDao; * * // @Autowired public SpringBootDemo1Application(ToDoDao toDoDao) { super(); * this.toDoDao = toDoDao; } */ public static void main(String[] args) { SpringApplication.run(SpringBootDemo1Application.class, args); } /* * @Override public void run(String... args) throws Exception { * * toDoDao.save(new ToDo(1, "todo 1")); toDoDao.save(new ToDo(2, "todo 2")); * toDoDao.save(new ToDo(3, "todo 3")); toDoDao.save(new ToDo(4, "todo 4")); * toDoDao.save(new ToDo(5, "todo 5")); toDoDao.save(new ToDo(6, "todo 6")); * toDoDao.save(new ToDo(7, "todo 7")); toDoDao.save(new ToDo(8, "todo 8")); * toDoDao.save(new ToDo(9, "todo 9")); * * } */ } <file_sep>package comm.servlet; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class ProductServlet extends HttpServlet { private static final long serialVersionUID = 1L; protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws IOException { try { response.setContentType("text/html"); PrintWriter out = response.getWriter(); out.println(request.getParameter("name")); out.println("hello"); } catch(Exception e) { e.printStackTrace(); } } } <file_sep>package Assingment.one; public class SavingAc extends Account { Float rateOfIntrest; Double amount; public SavingAc() { super(); } public SavingAc(Float rateOfIntrest, Double amount) { super(); this.rateOfIntrest = rateOfIntrest; this.amount = amount; } @Override public String toString() { System.out.println("-----------------------------------------------------------------------"); return "\nSavingAc [rateOfIntrest=" + rateOfIntrest + ", amount=" + amount + "]"; } } <file_sep>package Assingment.one; public class Account { Integer acId; String name; String add; public Account() { super(); } public Account(Integer acId, String name, String add) { super(); this.acId = acId; this.name = name; this.add = add; } public Integer getAcId() { return acId; } public void setAcId(Integer acId) { this.acId = acId; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getAdd() { return add; } public void setAdd(String add) { this.add = add; } @Override public String toString() { System.out.println("-----------------------------------------------------------------------"); return "\nAccount [acId=" + acId + ", name=" + name + ", add=" + add + ", getAcId()=" + getAcId()+", hashCode()=" + hashCode()+ "]"; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((acId == null) ? 0 : acId.hashCode()); result = prime * result + ((add == null) ? 0 : add.hashCode()); result = prime * result + ((name == null) ? 0 : name.hashCode()); return result; } @Override public boolean equals(Object obj) { Account a=null; if(obj instanceof Account) { a=(Account)obj; } if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Account other = (Account) obj; if (acId == null) { if (other.acId != null) return false; } else if (!acId.equals(other.acId)) return false; if (add == null) { if (other.add != null) return false; } else if (!add.equals(other.add)) return false; if (name == null) { if (other.name != null) return false; } else if (!name.equals(other.name)) return false; return true; } } <file_sep>package assignment.one; import com.sun.java_cup.internal.runtime.Scanner; public class PasswordMain { public static void main(String[] args) { UserMainCode umc=new UserMainCode(); boolean c=umc.checkPassword("<PASSWORD>"); if(c) System.out.println("valid Password"); else System.out.println("invalid Password"); } } <file_sep>package thread.group; //public class SimpleThread1 implements Runnable{ public class SimpleThread1 extends Thread { /* * private String str; */ public SimpleThread1(String str) { super(str); } @Override public void run() { for (int i = 0; i <= 5; i++) { System.out.println(i+" "+getName()); try { //wait((long) (Math.random() * 1000)); sleep((long)(Math.random()*1000)); //System.out.print(" "+getName()); } catch (InterruptedException e) { e.printStackTrace(); } } System.out.println("\n\n"+getName()+"\n"); } } <file_sep>public class Count { private static Integer count = 0; private String temp; private final int MAX; public Count() { super(); MAX = 10; } public Count(String temp) { super(); MAX = 18; count++; this.temp = temp; } @Override public String toString() { return count + temp; } public int display() { System.out.println(MAX); return count; } public static void main(String[] args) { Count c = new Count(); System.out.println(c.toString()); System.out.println(c.display()); } }<file_sep>package enum1; public class EnumDay { private DAY day; public EnumDay(DAY day) { super(); this.day = day; } public DAY getDay() { return day; } public static void main(String[] args) { EnumDay ed=new EnumDay(DAY.FRIDAY); System.out.println(ed.getDay().getDay1()+"- "+ed.getDay().getNo()); } }<file_sep>todo.id=100 todo.name=Sachin<file_sep>package comm.customer.flightBooking; import java.io.Serializable; import lombok.Getter; import lombok.Setter; @Getter@Setter public class FCustomer implements Serializable { private static final long serialVersionUID = 8822142042502434567L; private String uId; private String password; public FCustomer(String uId, String password) { super(); this.uId = uId; this.password = <PASSWORD>; } @Override public String toString() { return "Customer [uid=" + uId + ", password=" + password + "]"; } } <file_sep>package com.springJdbc.customer; import java.sql.SQLException; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.stereotype.Component; import lombok.Setter; @Setter @Component("dao2") public class CustomerDaoImpl2 implements CustomerDao2 { private JdbcTemplate jdbcTemplate; @Autowired public void setJdbcTemplate(JdbcTemplate jdbcTemplate) { this.jdbcTemplate = jdbcTemplate; } @Override public Customer createCustomer(Customer customer) throws SQLException { String sql = "insert into customer(first_name,last_name,email,uid) values(?,?,?,?)"; jdbcTemplate.update(sql, new Object[] { customer.getFirst_name(), customer.getLast_name(), customer.getEmail(), customer.getId() }); return customer; } @Override public List<Customer> displayAllCustomers() throws SQLException { String query = "select uid,first_name,last_name,email from customer"; return jdbcTemplate.query(query, new CustomerRowMapper()); } @Override public List<Customer> findById(Customer customer, String id, CustomerRowMapper rm) throws SQLException { String query = "select uid,first_name,last_name,email from customer where uid=?"; // jdbcTemplate.update(query,new Object[] {id}); return jdbcTemplate.query(query, new Object[] { id }, new CustomerRowMapper()); } @Override public List<Customer> findByLname(Customer customer, String lname, CustomerRowMapper rm) throws SQLException { String query = "select uid,first_name,last_name,email from customer where last_name=?"; return jdbcTemplate.query(query, new Object[] { lname }, new CustomerRowMapper()); } @Override public Customer updateCustomer(Customer customer) throws SQLException { String query = "update customer set first_name=? ,last_name=?,email=? where uid=?"; jdbcTemplate.update(query, new Object[] { customer.getFirst_name(), customer.getLast_name(), customer.getEmail(), customer.getId() }); return customer; } @Override public Customer deleteCustomer(Customer customer) throws SQLException { String query = "delete from customer where uid=?"; jdbcTemplate.update(query, new Object[] { customer.getId() }); return customer; } } <file_sep>package todo; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.UUID; public class ToDoDaoImpl implements ToDoDao { List<ToDo> todoList=null; { todoList=new ArrayList<ToDo>(); } private ToDo td; @Override public ToDo crtToDo(String todoName) { String[] str=UUID.randomUUID().toString().split("-"); td=new ToDo(str[1], todoName); todoList.add(td); return td; } @Override public List<ToDo> getAllToDos() { // TODO Auto-generated method stub return todoList; } @Override public ToDo findId(String todoId) { // TODO Auto-generated method stub // Iterator<ToDo> iterator=todoList.iterator(); /* * while(iterator.hasNext()) { td=iterator.next(); if(td.getTodoId()==todoId) { * * System.out.println(td.getTodoId()); break; } } return td; */ for(ToDo t:todoList) { if(t.getTodoId().equals(todoId)) { td=t; System.out.println("found."); } } return td; } @Override public void deleteToDo(String todoId) { if(todoList.isEmpty()) { System.out.println("todo list is empty."); } td=findId(todoId); if(td==null) { System.out.println("no such todo to delete"); } else { todoList.remove(td); //System.out.println("remoded sucessfully with id: "+todoId); } } @Override public void removeAllToDo() { todoList.removeAll(todoList); } @Override public void updateToDo(String oid) { for(ToDo t:todoList) { if(t.getTodoId().equals(oid)) { System.out.println("found."); String n=t.getTodoName(); td=crtToDo(n); System.out.println(td); deleteToDo(oid); break; } else { System.out.println("not found"); } } } } <file_sep>package springHibernate.springHbnDemo; import javax.transaction.Transactional; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; @Service("service") public class UserServiceImpl implements UserSevice { private UserDao dao; @Autowired public UserServiceImpl(UserDao dao) { super(); this.dao = dao; } @Override @Transactional public UserDetails createUser(UserDetails user) { // TODO Auto-generated method stub return dao.createUser(user); } } <file_sep>package myOnlineShop; public interface IElectronics extends IProduct { public String getMangfr(); } <file_sep>package com.example.demo; import java.time.LocalDate; import java.time.LocalDateTime; import java.util.List; import java.util.Optional; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.PutMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import com.example.demo.execptionHandlers.ItemNotFoundException; import com.example.demo.execptionHandlers.ItemError; @RestController @RequestMapping("/item") public class ItemRestController { private ItemService itemService; @Autowired public ItemRestController(ItemService itemService) { super(); this.itemService = itemService; } @PostMapping("/create") public Item createItem(@RequestBody Item item) { item.setMnfgDt(LocalDateTime.now()); item.setUpdatedDt(LocalDateTime.now()); return itemService.createItem(item); } @PutMapping("/update") public Item updateItem(@RequestBody Item item) { item.setUpdatedDt(LocalDateTime.now()); return itemService.createItem(item); } @GetMapping("/all") public List<Item> findAll() { return itemService.findAll(); } @GetMapping("/id/{itemId}") public Optional<Item> findById(@PathVariable String itemId) { return itemService.findById(itemId); /* * if (item.isPresent()) return item; else { throw new * ItemNotFoundException("Item not found with id: " + itemId); } */ //return item; } @GetMapping("/name/{itemName}") List<Item> findName(@PathVariable String itemName) { //List<Item> item = itemService.findName(itemName); return itemService.findName(itemName); //if (!item.isEmpty()) // return item; //else { // throw new ItemNotFoundException("Item not found with name: " + itemName); //} } @GetMapping("/price/{itemPrice}") List<Item> findPrice(@PathVariable Double itemPrice) { List<Item> item = itemService.findPrice(itemPrice); if (!item.isEmpty()) return item; else { throw new ItemNotFoundException("Item not found with price: " + itemPrice); } } @DeleteMapping("/delete/{itemId}") void deleteItemById(@PathVariable String itemId) { itemService.deleteItemById(itemId); } @DeleteMapping("/deleteall") void deleteItems() { itemService.deleteItems(); } @ExceptionHandler public ResponseEntity<ItemError> error1(ItemNotFoundException ide) { ItemError error = new ItemError(); error.setMessage(ide.getMessage()); error.setStatus(HttpStatus.NOT_FOUND.value()); error.setErrorTime(LocalDateTime.now()); return new ResponseEntity<ItemError>(error, HttpStatus.NOT_FOUND); } @ExceptionHandler public ResponseEntity<ItemError> error2(Exception e) { ItemError error = new ItemError(); error.setMessage(e.getMessage()); error.setStatus(HttpStatus.BAD_REQUEST.value()); error.setErrorTime(LocalDateTime.now()); return new ResponseEntity<ItemError>(error, HttpStatus.BAD_REQUEST); } } <file_sep>package com.example.demo; import java.util.List; import java.util.Optional; public interface ToDoService { List<ToDo> getAllToDo(); Optional<ToDo> findId(Integer todoId); ToDo createToDo(ToDo todo); void deleteToDoById(Integer todoId); void deleteToDos(); List<ToDo> findName(String todoName); } <file_sep>package springHibernate.springHbnDemo; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.UUID; import org.hibernate.SessionFactory; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class App { public static void main( String[] args ) throws IOException { int choice = 0; UserDetails ur = null; BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); /*try { do { System.out.println("======================\n1. create User"); System.out.println("2. create Images"); System.out.println("3. find album by id"); System.out.println("4. update album"); System.out.println("5. delete album"); System.out.println("0. exit"); System.out.print("choice: "); choice = Integer.parseInt(br.readLine().toString()); int uId; switch (choice) { case 1:*/ try { ApplicationContext context=new ClassPathXmlApplicationContext("appContext.xml"); UserSevice service=context.getBean("service",UserSevice.class); System.out.print("Enter user name: "); String name = br.readLine().toString(); System.out.print("enter mail address: "); String mail = br.readLine().toString(); String userid[]=UUID.randomUUID().toString().split("-"); ur=new UserDetails(userid[1], name, mail); UserDetails ur1 = service.createUser(ur); System.out.println(ur); System.err.println("User created"); } catch (Exception e) { e.printStackTrace(); } /* * break; case 0: System.exit(0); break; default: * System.out.println("invalid choice"); break; } * * } while (choice != 0); * * } catch (Exception e) { e.printStackTrace(); } */ } } <file_sep>package com.example.demo; import java.util.List; import java.util.Optional; public interface ItemService { public Item createItem(Item item); public List<Item> findAll(); public Optional<Item> findById(String id); List<Item> findName(String itemName); void deleteItemById(String itemId); void deleteItems(); List<Item> findPrice(Double itemPrice); } <file_sep>package assignment.two; import java.util.Arrays; import java.util.Collections; import java.util.LinkedList; import java.util.List; public class Country { private String name; List<State> stateList=new LinkedList<State>(); State state=new State(); public String getName() { return name; } public void setName(String name) { this.name = name; } public void addState(String statename) { // Add the new state to this country object stateList.add(state.getStateName); } public void getStateList() {// - Sort the state collection and return the list List<State> l=Arrays.asList(state); Collections.sort(l); } } <file_sep>package springHibernate.springHbnDemo; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Repository; @Repository("dao") public class UserDaoImpl implements UserDao { private SessionFactory sessionFactory; private Session session; @Autowired public UserDaoImpl(SessionFactory sessionFactory) { super(); this.sessionFactory = sessionFactory; session = sessionFactory.openSession(); } @Override public UserDetails createUser(UserDetails user) { session.save(user); return user; } }<file_sep>package com.example.demo.execptionHandlers; import java.time.LocalDate; import java.time.LocalDateTime; public class ItemError { private String message; private int status; private LocalDateTime errorTime; public ItemError(String message, int status, LocalDateTime errorTime) { super(); this.message = message; this.status = status; this.errorTime = errorTime; } public ItemError() { super(); } public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } public int getStatus() { return status; } public void setStatus(int status) { this.status = status; } public LocalDateTime getErrorTime() { return errorTime; } public void setErrorTime(LocalDateTime errorTime) { this.errorTime = errorTime; } } <file_sep>package comm.customer.jdbcMaven1; import java.io.IOException; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import java.util.logging.Logger; import comm.customer.jdbcMaven1.*; public class CustomerDAOImpl implements CustomerDAO { private MyConnectionFactory factory = null; private Connection connection = null; PreparedStatement pStatement = null; static Logger logger = Logger.getLogger("com.customer.jdbcMaven1.CustomerDAOImpl"); private Customer customer = null; { factory = MyConnectionFactory.getFactoryObject(); try { logger.info("connection started"); connection = factory.getMyConnection(); logger.info("got connection"); } catch (IOException | SQLException e) { e.printStackTrace(); logger.info("connection unsucessfull"); } } @Override public Customer createCustomer(Customer customer) throws SQLException { pStatement = connection .prepareStatement("insert into customer(first_name,last_name,email,uid) values(?,?,?,?)"); pStatement.setString(1, customer.getFirstName()); pStatement.setString(2, customer.getLastName()); pStatement.setString(3, customer.getEmail()); pStatement.setString(4, customer.getUId()); pStatement.executeUpdate(); return customer; } @Override public List<Customer> findById(String uId) throws SQLException { pStatement = connection.prepareStatement("select first_name,last_name,email,uid from customer where uid=?"); pStatement.setString(1, uId); ResultSet rSet = pStatement.executeQuery(); List<Customer> list = new ArrayList<Customer>(); while (rSet.next()) { Customer customer = new Customer(rSet.getString("uid"), rSet.getString("first_name"), rSet.getString("last_name"), rSet.getString("email")); list.add(customer); } return list; } @Override public List<Customer> getAllCustomers() throws SQLException { pStatement = connection.prepareStatement("select uid,first_name,last_name,email from customer"); ResultSet rSet = pStatement.executeQuery(); List<Customer> list = new ArrayList<Customer>(); while (rSet.next()) { Customer customer = new Customer(rSet.getString("uid"), rSet.getString("first_name"), rSet.getString("last_name"), rSet.getString("email")); list.add(customer); } return list; } @Override public Customer updateCustomer(Customer customer, String uId) throws SQLException { // TODO Auto-generated method stub pStatement = connection.prepareStatement("update customer set first_name=? ,last_name=?,email=? where uid=?"); pStatement.setString(1, customer.getFirstName()); pStatement.setString(2, customer.getLastName()); pStatement.setString(3, customer.getEmail()); pStatement.setString(4, uId); pStatement.executeUpdate(); return customer; } @Override public Customer deleteCustomer(Customer customer, String uId) throws SQLException { // TODO Auto-generated method stub pStatement = connection.prepareStatement("delete from customer where uid=?"); pStatement.setString(1, uId); pStatement.executeUpdate(); return customer; } @Override public List<Customer> findByLname(String lname) throws SQLException { List<Customer> list = new ArrayList<Customer>(); pStatement = connection .prepareStatement("select uid,first_name,last_name,email from customer where last_name=?"); pStatement.setString(1, lname); ResultSet rSet = pStatement.executeQuery(); while (rSet.next()) { Customer customer = new Customer(rSet.getString("uid"), rSet.getString("first_name"), rSet.getString("last_name"), rSet.getString("email")); list.add(customer); } return list; } @Override public List<Customer> findByAttribute(String attribute, String et) throws SQLException { pStatement = connection.prepareStatement("select uid,first_name,last_name,email from customer where ? = ?"); pStatement.setString(1, attribute); pStatement.setString(2, et); ResultSet rSet = pStatement.executeQuery(); List<Customer> list = new ArrayList<Customer>(); while (rSet.next()) { Customer customer = new Customer(rSet.getString("uid"), rSet.getString("first_name"), rSet.getString("last_name"), rSet.getString("email")); list.add(customer); } return list; } }<file_sep>import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.InputMismatchException; public class DefaultStreamDemo { public static void main(String[] args) throws Exception { BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); try { System.out.print("Enter name: "); String name=br.readLine(); System.out.format("your name: %s\n", name); System.out.println("Enter age: "); int age=Integer.parseInt(br.readLine().toString()); System.out.format("your age: %d", age); } catch (NumberFormatException e) { //System.err.println(e.getStackTrace().toString()); e.printStackTrace(); } } }<file_sep>package employeeAssignment; import java.io.BufferedReader; import java.io.InputStreamReader; import java.sql.Date; import java.text.SimpleDateFormat; import java.time.LocalDate; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.InputMismatchException; import java.util.List; import java.util.Scanner; public class MEmployee { @SuppressWarnings("null") public static void main(String[] args) throws Exception{ BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); System.out.println("input the number of employees :"); int n=Integer.parseInt(br.readLine()); Employee[] e1=new Employee[n]; for(int i=0;i<n;i++) { System.out.println("enter the details for employee "+(i+1)); String name=br.readLine(); String department=br.readLine(); java.util.Date dateOfJoining=new SimpleDateFormat("MM/dd/yyyy").parse(br.readLine()); int age=Integer.parseInt(br.readLine()); int salary=Integer.parseInt(br.readLine()); e1[i]=new Employee(name,department,dateOfJoining,age,salary); } System.out.println("1.Sort employees by salary"); System.out.println("2.Sort employees by age and by date of joining"); System.out.println("Enter your choice"); int choice=Integer.parseInt(br.readLine()); switch(choice) { case 1: //for(int i=0;i<n;i++) { List<Employee> l=Arrays.asList(e1); Collections.sort(l); EmployeeBO.printEmployees(l); //} break; case 2:System.out.println("case 2"); break; case 0: System.out.println("bye"); System.exit(0); break; default: System.out.println("invalid choice"); break; } } } <file_sep> public class Finally { public static void main(String[] args) { int c=0; while(true) { try { if(c++==0) { throw new Exception();} }catch(Exception e){ e.printStackTrace();} finally { System.out.println("finally block "+c); if(c==3) break; } } }} <file_sep>package com.spring2.todotask; import org.springframework.stereotype.Component; import lombok.AllArgsConstructor; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; @NoArgsConstructor@AllArgsConstructor @Setter@Getter @Component public class Task { private String taskid; private String taskname; @Override public String toString() { return "Task [taskid=" + taskid + ", taskname=" + taskname + "]"; } } <file_sep>package com.hibernate.person; import java.time.LocalDate; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import lombok.AllArgsConstructor; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; import lombok.ToString; @NoArgsConstructor@AllArgsConstructor @Setter@Getter @ToString //@Table(name="person1") public class Person { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private String id; //@Column(name = "name") if DB name are different private String name; private LocalDate date; } <file_sep>package Password; public class Password { private String password; public Password(String password) { super(); this.password = <PASSWORD>; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public static void main(String[] args) throws PasswordException { Password p=new Password(args[0]); if(args[0].length()<=8 || args[0].length()>=15) { throw new PasswordException("length mismatch"); } char[] c=new char[15]; for(int i=0;i<args[0].length();i++) { c[i]=args[0].charAt(i); System.out.print(c[i]); } System.out.println("\n\n"); for(int k=0;k<c.length;k++) { for(int l=0;l<26;l++) { if(((c[k]==(char)('a'+l)) || (c[k]==(char)('A'+l))||(c[k]<=9&&c[k]>=0) )) { System.out.println(c[k]); } throw new PasswordException("invalid password\nthank you"); } } System.out.println(args[0]); } } <file_sep>package todo; import java.util.List; public interface ToDoService { Object tdservice = null; public ToDo crtToDo(String todoName); public List<ToDo> getAllToDos(); public ToDo findId(String todoId); public void deleteToDo(String toDoId); public void removeAllToDo(); public void updateToDo(String oid); } <file_sep>package com.example.demo; import java.util.List; import java.util.Optional; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; @Repository @org.springframework.transaction.annotation.Transactional public interface ToDoDao extends JpaRepository<ToDo, Integer> { List<ToDo> findByTodoName(String todoName); } <file_sep>package com.spring1.employee; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class App { public static void main(String[] args) { try { ApplicationContext context = new ClassPathXmlApplicationContext("applicatiionContext.xml"); Employee employee = context.getBean("employee", Employee.class); Address address = context.getBean("address", Address.class); // Employee employee1=context.getBean("employee",Employee.class); // System.out.println(employee==employee1); System.out.println(employee.getDetails() + " " + address.getDetails()); } catch (Exception e) { } } } <file_sep>package customerServlet; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import lombok.Data; import lombok.NoArgsConstructor; @Entity @Data @NoArgsConstructor public class Customer { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private int id; private String firstName,lastName,email; public Customer(String firstName, String lastName, String email) { super(); this.firstName = firstName; this.lastName = lastName; this.email = email; } } <file_sep>package jsonDemo1; import lombok.AllArgsConstructor; import lombok.EqualsAndHashCode; import lombok.NoArgsConstructor; import lombok.ToString; @NoArgsConstructor @AllArgsConstructor @EqualsAndHashCode @ToString public class Student { private int id; private String firstName, lastName; private boolean active; public boolean isActive() { return active; } public void setActive(boolean active) { this.active = active; } public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } public int getId() { return id; } public void setId(int id) { this.id = id; } @Override public String toString() { return "Student [id=" + id + ", Name=" + firstName + " " + lastName + ", active=" + active + "]"; } } <file_sep>package Password; public class PasswordException extends Throwable { public PasswordException(String msg) { super(msg); } } <file_sep>package customerServlet; import java.time.LocalDate; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; @Controller //@RequestMapping("/customer") public class CustomerController { @RequestMapping("/") public String home(Model model) { model.addAttribute("customer", new Customer()); return "list"; } /* * @RequestMapping(method = RequestMethod.POST, path = "/processLogin") public * String processLogin(@ModelAttribute("customer") Customer customer) { if * ((user.getEmail().equals("<EMAIL>")) && * (user.getPassword().equals("<PASSWORD>"))) { return "add_cd"; } else { return * "error"; } * * } * * * @RequestMapping(method = RequestMethod.GET, path = "/addCD") public String * addCd() { return "add_cd"; } */ @RequestMapping("/processCustomer") public String processForm(@RequestParam("firstName") String firstName, @RequestParam("lastName") String lastName, @RequestParam("email") String email, Model theModel) { Customer cd = new Customer(firstName, lastName, email); theModel.addAttribute("cd", cd); return "success_cd"; } }<file_sep>package comm.customer.flightBooking; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.sql.SQLException; import java.util.List; import java.util.UUID; import lombok.ToString; @ToString public class BookingApp { private static BookingService service; static { service = new BookingServiceImpl(); } public static void main(String args[]) throws NumberFormatException, IOException, SQLException { int choice = 0; String uid,password,fid; int noofseats; List<FCustomer> clist = null; List<FlightBooking> flist =null; FCustomer fc = null; FlightBooking fb=null; BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); try { do { System.out.println("======================\n1. Booking flight"); System.out.println("0. exit"); System.out.print("choice: "); choice = Integer.parseInt(br.readLine().toString()); switch (choice) { case 1: System.out.print("enter customer uid: "); uid = br.readLine().toString(); clist = service.findById(uid); if (clist.isEmpty()) { System.err.println("no such uid found\n\n"); String arr[] = UUID.randomUUID().toString().split("-"); System.out.print("your new uid: "+arr[1]); System.out.print("\ncreate password: "); password=br.readLine().toString(); FCustomer theCustomer = new FCustomer(arr[1], password); //System.out.println(theCustomer); fc = service.createCustomer(theCustomer); System.out.println("Create Customer Sucess " + fc); } else { System.out.println("found uid"); System.out.print("enter password: "); String password1=br.readLine().toString(); if(service.findByPassword(password1).isEmpty()) { System.out.println("worng password"); System.exit(0); } } System.err.println("-----------------------------"); flist=service.displayFlightBooking(); System.err.format("%-20s %s\n", "Flight No", "No. of Seats"); flist.forEach(c -> { System.out.format("%-20s %s\n", c.getFlightno(),c.getNoofseats()); }); System.out.println(); System.out.print("Enter flight no: "); fid=br.readLine().toString(); System.out.print("Enter no. of tickets: "); noofseats=Integer.parseInt(br.readLine().toString()); fb =service.updateFlightBooking(fb,noofseats); System.out.println("Flight table updated: "+fb); System.out.println("Tickets booked successfully\n"); break; case 0: System.exit(0); break; default: System.out.println("invalid choice"); break; } } while (choice != 0); }catch( Exception e) { e.printStackTrace(); System.exit(0); } }} <file_sep>package hibernateAnnotationDAO.personHbm; import java.io.IOException; import java.sql.SQLException; import java.util.List; public interface Person1Dao { Person1 createCustomer(Person1 person) throws SQLException, IOException; List<Person1> displayAllPersons() throws SQLException; Person1 findById(String id) throws SQLException; Person1 findByLname(String lname) throws SQLException; Person1 updateCustomer(String id) throws SQLException, IOException; Person1 deleteCustomer(String id) throws SQLException; } <file_sep>package Interface; public interface OperateCar { } <file_sep>package com.spring2.todotask; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class App { public static void main( String[] args ) { try { ApplicationContext context=new ClassPathXmlApplicationContext("applicationContext.xml"); Todo todo=context.getBean("todo",Todo.class); Task task=context.getBean("task",Task.class); task.setTaskid("123"); task.setTaskname("Coding"); todo.setTask(task); System.out.println(todo); } catch (Exception e) { e.printStackTrace(); } } } <file_sep># ctsfsd feb work is in feb branch
58816e5f82d1f186675491ce010ef0541dfb20db
[ "Markdown", "Java", "SQL", "INI" ]
50
Java
ChiluveruSra1/ctsfsd
833aa6de3cbd943dcd8f38353a41538738e0d637
8580abc6c86d417dbd75538d71709e7acb3ac50b
refs/heads/master
<file_sep>import React from 'react'; class Articles extends React.Component { truncate(str, num) { return str.length > num ? str.slice(0, num) + '...' : str; } render() { const { articles } = this.props; return ( <div> <h2 className="text-center mt-4">{this.props.title}</h2> <div className="row"> {articles.map((article, index) => { return ( <div className="col-md-6" key={index}> <div className="card"> <div className="card-img"> <img src={article.urlToImage} className="img-responsive card-img-top" /> </div> <div> <h4><a href={article.url} target="_blank">{article.title}</a></h4> <p>{this.truncate(article.description, 100)}</p> </div> </div> </div> ); })} </div> </div> ); } } export default Articles; <file_sep>import React from 'react'; class SelectNews extends React.Component { constructor(props) { super(props); this.changeSelect = this.changeSelect.bind(this); } changeSelect(e) { const name = e.target.value; this.props.onChange(name); } render() { let options = this.props.sources.map((source, index) => { return <option value={index} key={index}>{source.name}</option>; }); options.unshift(<option value="-1" key="-1">Select A Source</option>); return ( <div> <select id="choice" onChange={this.changeSelect} className="form-control"> {options} </select> </div> ); } } export default SelectNews; <file_sep>import React from 'react'; import SelectNews from './SelectNews'; import Articles from './Articles'; const SOURCES = [ { name: 'Bloomberg', sortedBy: 'top' }, { name: 'The New York Times', sortedBy: 'top' }, { name: 'BBC News', sortedBy: 'top' }, { name: 'The Wall Street Journal', sortedBy: 'top' }, { name: 'Google News', sortedBy: 'top' }, ]; const BASE_URL = 'https://newsapi.org/v1/articles'; // Here should be your https://newsapi.org/ API Key const API_KEY = '332d00016ea64d3d938c0c7a70590da6'; class App extends React.Component { constructor(props) { super(props); this.state = { newsName: '', articles: [] }; this.handleChange = this.handleChange.bind(this); } hyphenated(name) { return name.trim().toLowerCase().replace(/\s/g, '-'); } handleChange(num) { const URL = `${BASE_URL}?source=${this.hyphenated(SOURCES[num].name)}&sortedBy=${SOURCES[num].sortedBy}&apiKey=${API_KEY}`; fetch(URL, { method: 'GET' }) .then(response => response.json()) .then(json => { const { articles } = json; this.setState({ newsName: SOURCES[num].name, articles }); }); } render() { const articles = this.state.articles.length > 0 ? <Articles articles={this.state.articles} title={this.state.newsName} /> : <div></div>; return ( <div className="app container"> <h1>Top News Viewer</h1> <SelectNews sources={SOURCES} onChange={this.handleChange} /> {articles} </div> ); } } export default App; <file_sep># react-news-viewer Top News Viewer (React, News API) Внимание! Необходим установленный на вашем компьютере nodejs. Установка проекта: 1. Выполните команду git clone https://github.com/Serhii75/react-news-viewer.git 2. Войдите в папку проекта и выполните команду npm install Для запуска проекта: 1. Выполните команду npm run start 2. В адресной строке браузера введите http://localhost:8080/
8f2dec7ca0a6b335f088e3496275ef43ae390edf
[ "JavaScript", "Markdown" ]
4
JavaScript
Serhii75/react-news-viewer
65ad0ce64b1525a6c549f9cf9d6133e3f3b3c93f
9c5465231a15f0ee5dcb631101d8a7bb35b3b110
refs/heads/main
<repo_name>Aurelien-Be/Youtube-transcript-auto-generated-included-<file_sep>/Transcription youtube.py from youtube_transcript_api import YouTubeTranscriptApi from youtube_transcript_api.formatters import TextFormatter import os ytlink = input('YT id:') #yt id is what after https:// www.youtube.com/watch?v= lang = input('language:') Transcriptions = YouTubeTranscriptApi.get_transcript(ytlink, languages=[lang]) #formatter in order to read easily the file formatter = TextFormatter() text_formatted = formatter.format_transcript(Transcriptions) print(text_formatted) #use of os module in order to create and write a file with this transcription path = R'C:\Users\Asus\Documents\Transcriptions' file = input('name of the file:') with open(os.path.join(path, file), 'w', encoding='utf-8') as text_file: text_file.write(str(text_formatted))
012ac140a9800ead8905ceced947b6e315f621e4
[ "Python" ]
1
Python
Aurelien-Be/Youtube-transcript-auto-generated-included-
bec339d2fe69ebb37204346484f78cf4ab03b4c6
be2f1471c81bb7e36400d42c65a3589cba836584
refs/heads/master
<file_sep>-- // create tabela table -- Migration SQL that makes the change goes here. create table tabela ( id integer not null, nome varchar(30) ); -- //@UNDO -- SQL to undo the change goes here. drop table tabela;
6727767c4f6c827ecc4ef5f800a8df09fcb8490a
[ "SQL" ]
1
SQL
mbgarcia/migrations
82c43515c3026e39a218d138851400615f8fc088
ab9182b6365b4435f7376a5987171771bab9db92
refs/heads/master
<file_sep>#include "Game.h" #include <iostream> #include <string> #include <vector> #include <SFML/Graphics.hpp> #include <cmath> struct ball { sf::Sprite sprite; sf::Vector2f v; }; int main() { Game game(sf::Vector2u(800, 600)); game.start_game(); } <file_sep>#pragma once #include <vector> #include "Cell.h" #include <SFML/Graphics.hpp> #include <string> class Map{ private: std::vector<std::vector<Cell>> map; std::vector<sf::Vector2i> xs; sf::Vector2i dude; public: Map() {}; Map(std::string path); void print_map(); void draw_map(sf::RenderWindow& window); int step(char c);// 'l', 'r', 'u', 'd' bool is_complete(); };<file_sep>#pragma once class Cell { private: int type; public: Cell(); Cell(int type); void change_type(int type); int get_type(); }; <file_sep>#pragma once #include <SFML/Graphics.hpp> #include "Map.h" class Game { private: sf::RenderWindow window; sf::Event event; Map map; public: Game(sf::Vector2u w_size); int start_level(int level); void start_game(); }; <file_sep># Game Aliens for C++ course at MIPT This is my project for C++ course. Some screenshots: <img src="https://raw.githubusercontent.com/malmakova-na/alien_game_cpp/master/screenshots/screen1.png" width="45%"></img> <img src="https://raw.githubusercontent.com/malmakova-na/alien_game_cpp/master/screenshots/screen2.png" width="45%"/> ## How to play You need to blow up the planets by pushing them into black holes. Use arrows to move alien dude. Press "R" for restart level, press space to make the alien start to move randomly. ## How to install on Linux Firstly you need to install SFML library: ``` sudo apt-get install libsfml-dev ``` Then compile: ``` g++ run.cpp Game.cpp Map.cpp Cell.cpp -o run -lsfml-graphics -lsfml-window -lsfml-system ``` And run: ``` ./run ``` Enjoy!<file_sep>#include "Game.h" #include <iostream> #include <cstdlib> #include <unistd.h> std::string moves = "lrud"; Game::Game(sf::Vector2u w_size) { window.create(sf::VideoMode(600,600), "My game"); window.setSize(w_size); window.setTitle("My Game"); } int Game::start_level(int level) { bool self_flag = 0; int steps = 0; std::string path = "levels/" + std::to_string(level) + ".txt"; map = Map(path); window.clear(sf::Color::White); map.draw_map(window); window.display(); while (!map.is_complete()) { if (self_flag) { int prev_steps = steps; while (steps == prev_steps) { char move = moves[std::rand() % 4]; steps += map.step(move); } window.clear(sf::Color::White); map.draw_map(window); window.display(); usleep(300000); } while (window.pollEvent(event)) { if (event.type == sf::Event::Closed) window.close(); else if (event.type == sf::Event::KeyPressed) { if (event.key.code == sf::Keyboard::Space) { self_flag = !self_flag; } if (event.key.code == sf::Keyboard::R) { return 1; } if(!self_flag) { if (event.key.code == sf::Keyboard::Left) { steps += map.step('l'); window.clear(sf::Color::White); map.draw_map(window); window.display(); } else if (event.key.code == sf::Keyboard::Right) { steps += map.step('r'); window.clear(sf::Color::White); map.draw_map(window); window.display(); } else if (event.key.code == sf::Keyboard::Up) { steps += map.step('u'); window.clear(sf::Color::White); map.draw_map(window); window.display(); } else if (event.key.code == sf::Keyboard::Down) { steps += map.step('d'); window.clear(sf::Color::White); map.draw_map(window); window.display(); } } } } if (sf::Keyboard::isKeyPressed(sf::Keyboard::Left)) steps += map.step('l'); else if (sf::Keyboard::isKeyPressed(sf::Keyboard::Right)) steps += map.step('r'); else if (sf::Keyboard::isKeyPressed(sf::Keyboard::Up)) steps += map.step('u'); else if (sf::Keyboard::isKeyPressed(sf::Keyboard::Down)) steps += map.step('d'); window.clear(sf::Color::White); map.draw_map(window); window.display(); } return 0; } void Game::start_game() { int n = 2; int i = 0; while (window.isOpen()) { while (window.pollEvent(event)) { if (event.type == sf::Event::Closed) window.close(); } std::cout << "start level " << i + 1 << "\n"; int r = start_level(i + 1); if (r == 0){ i = (i + 1) % n; } } }<file_sep>#include "Cell.h" Cell::Cell() { type = 0; } Cell::Cell(int t) { type = t; } void Cell::change_type(int t) { type = t; } int Cell::get_type() { return type; }<file_sep>#include "Map.h" #include <fstream> #include <iostream> #include <algorithm> sf::Sprite get_sprite(std::string path, sf::Vector2f size) { sf::Texture texture; texture.loadFromFile(path); sf::Sprite sprite(texture); float scale_x = size.x / sprite.getGlobalBounds().height; float scale_y = size.y / sprite.getGlobalBounds().width; sprite.setScale(scale_x, scale_y); return sprite; } sf::Vector2f icon_size(64, 64); Map::Map(std::string path) { std::ifstream in(path); if (in.is_open()) { int n, m; in >> n; in >> m; for (int i = 0; i < n; i++) { std::vector<Cell> t_cells; for (int j = 0; j < n; j++) { int t; in >> t; Cell t_cell(t); t_cells.push_back(t_cell); } map.push_back(t_cells); } int k; in >> k; for (int i = 0; i < k; i++) { int x, y; in >> x; in >> y; xs.push_back(sf::Vector2i(x, y)); } int dude_x, dude_y; in >> dude_x; in >> dude_y; dude = sf::Vector2i(dude_x, dude_y); } in.close(); } void Map::print_map() { for (int i = 0; i < map.size(); i++) { for (int j = 0; j < map[i].size(); j++) std::cout << map[i][j].get_type() << ' '; std::cout << std::endl; } for (int i = 0; i < xs.size(); i++) std::cout << xs[i].x << " " << xs[i].y << std::endl; std::cout << dude.x << " " << dude.y; } void Map::draw_map(sf::RenderWindow& window) { sf::Vector2f pos_back = sf::Vector2f(0, 0); int n = map.size(); int m = map[0].size(); sf::Texture texture_back; texture_back.loadFromFile("icons/sky.png"); sf::Sprite sprite_back(texture_back); float scale_x =600 / sprite_back.getGlobalBounds().height; float scale_y = 600 / sprite_back.getGlobalBounds().width; sprite_back.setScale(scale_x, scale_y); sprite_back.setPosition(pos_back); window.draw(sprite_back); for (auto v : xs) { sf::Vector2f pos = sf::Vector2f(50 + icon_size.x*v.y, 50 + icon_size.y*v.x); sf::Texture texture_x; texture_x.loadFromFile("icons/hole.png"); sf::Sprite sprite_x(texture_x); float scale_x = icon_size.x / sprite_x.getGlobalBounds().height; float scale_y = icon_size.y / sprite_x.getGlobalBounds().width; sprite_x.setScale(scale_x, scale_y); sprite_x.setPosition(pos); window.draw(sprite_x); } for(int i = 0; i < map.size(); i++) for (int j = 0; j < map[i].size(); j++) { sf::Vector2f pos = sf::Vector2f(50 + j * icon_size.x, 50 + i * icon_size.y); int type = map[i][j].get_type(); if (type == 2) { if (std::find(xs.begin(), xs.end(), sf::Vector2i(i, j)) != xs.end()) { sf::Texture texture_map; texture_map.loadFromFile("icons/planet1.png"); sf::Sprite sprite_map(texture_map); float scale_x = icon_size.x / sprite_map.getGlobalBounds().height; float scale_y = icon_size.y / sprite_map.getGlobalBounds().width; sprite_map.setScale(scale_x, scale_y); sprite_map.setPosition(pos); window.draw(sprite_map); } else { sf::Texture texture_map; texture_map.loadFromFile("icons/planet2.png"); sf::Sprite sprite_map(texture_map); float scale_x = icon_size.x / sprite_map.getGlobalBounds().height; float scale_y = icon_size.y / sprite_map.getGlobalBounds().width; sprite_map.setScale(scale_x, scale_y); sprite_map.setPosition(pos); window.draw(sprite_map); } } else if (type == 0) { sf::Texture texture_map; texture_map.loadFromFile("icons/bl.png"); sf::Sprite sprite_map(texture_map); float scale_x = icon_size.x / sprite_map.getGlobalBounds().height; float scale_y = icon_size.y / sprite_map.getGlobalBounds().width; sprite_map.setScale(scale_x, scale_y); sprite_map.setPosition(pos); window.draw(sprite_map); } } sf::Vector2f pos = sf::Vector2f(50 + 64 * dude.y, 50 + 64 * dude.x); sf::Texture texture_dude; texture_dude.loadFromFile("icons/UFOdude.png"); sf::Sprite sprite_dude(texture_dude); scale_x = icon_size.x / sprite_dude.getGlobalBounds().height; scale_y = icon_size.y / sprite_dude.getGlobalBounds().width; sprite_dude.setScale(scale_x, scale_y); sprite_dude.setPosition(pos); window.draw(sprite_dude); } int Map::step(char c) { if (c == 'l') { if(map[dude.x][dude.y - 1].get_type() == 0) return 0; if (map[dude.x][dude.y - 1].get_type() == 1) { dude.y -= 1; return 1; } if (map[dude.x][dude.y - 1].get_type() == 2 && map[dude.x][dude.y - 2].get_type() == 1) { map[dude.x][dude.y - 1].change_type(1); map[dude.x][dude.y - 2].change_type(2); dude.y -= 1; } } if (c == 'r') { if (map[dude.x][dude.y + 1].get_type() == 0) return 0; if (map[dude.x][dude.y + 1].get_type() == 1) { dude.y += 1; return 1; } if (map[dude.x][dude.y + 1].get_type() == 2 && map[dude.x][dude.y + 2].get_type() == 1) { map[dude.x][dude.y + 1].change_type(1); map[dude.x][dude.y + 2].change_type(2); dude.y += 1; } } if (c == 'u') { if (map[dude.x - 1][dude.y].get_type() == 0) return 0; if (map[dude.x - 1][dude.y].get_type() == 1) { dude.x -= 1; return 1; } if (map[dude.x - 1][dude.y].get_type() == 2 && map[dude.x - 2][dude.y].get_type() == 1) { map[dude.x - 1][dude.y].change_type(1); map[dude.x - 2][dude.y].change_type(2); dude.x -= 1; } } if (c == 'd') { if (map[dude.x + 1][dude.y].get_type() == 0) return 0; if (map[dude.x + 1][dude.y].get_type() == 1) { dude.x += 1; return 1; } if (map[dude.x + 1][dude.y].get_type() == 2 && map[dude.x + 2][dude.y].get_type() == 1) { map[dude.x + 1][dude.y].change_type(1); map[dude.x + 2][dude.y].change_type(2); dude.x += 1; } } return 0; } bool Map::is_complete() { int count = 0; for (auto v : xs) if (map[v.x][v.y].get_type() == 2) count += 1; if (count == xs.size()) return 1; else return 0; }
52ae2219febd21e5d4830bf135d823570169a223
[ "Markdown", "C++" ]
8
C++
malmakova-na/alien_game_cpp
d0a3b5bcf323c8435348ab78965cce51a987cbe5
ce41f2e4f252b3c1390bae149e53536dc3d12c05
refs/heads/master
<file_sep>""" MKDocs-Autodoc This plugin implemented autodoc in MKDocs, just like autodoc in Sphinx. Doc strings should follow Google Python Style, otherwise will not well parsed. """ import io import os from mkdocs import utils from mkdocs.config import load_config from mkdocs.commands import build from mkdocs.commands.build import log, get_global_context, get_page_context from mkdocs.toc import TableOfContents, AnchorLink from mkdocs_autodoc.autodoc import parse_selected from magicpatch import patch AUTODOC_MARK = ".autodoc" TEMPLATE_PATH = os.path.join(os.path.dirname(__file__), "autodoc.jinja2") def create_toc(titles): """ Create table of contents """ toc = TableOfContents("") if not titles: return toc first = titles.pop(0) link = AnchorLink(title=first, url="#0") link.active = True link.children = [ AnchorLink(title=title, url="#%d" % (index + 1)) for index, title in enumerate(titles) ] toc.items = [link] return toc def get_complete_paths(config, page): """ Return the complete input/output paths for the supplied page. """ input_path = os.path.join(config['docs_dir'], page.input_path) output_path = os.path.join(config['site_dir'], page.output_path) return input_path, output_path def build_autodoc(page, config, site_navigation, env, dump_json, dirty=False): """ Build autodoc, just like mkdocs.commands.build._build_page """ input_path, output_path = get_complete_paths(config, page) try: input_content = io.open(input_path, 'r', encoding='utf-8').read() except IOError: log.error('file not found: %s', input_path) raise # render autodoc contents tmplstr = io.open(TEMPLATE_PATH).read() template = env.from_string(tmplstr) contents, titles = parse_selected(input_content) table_of_contents = create_toc(titles) html_content = template.render(contents=contents) # render page meta = None context = get_global_context(site_navigation, config) context.update(get_page_context( page, html_content, table_of_contents, meta, config )) template = env.get_template('base.html') output_content = template.render(context) utils.write_file(output_content.encode('utf-8'), output_path) return html_content, table_of_contents, None @patch(build._build_page) def build_page(f, page, *args, **kwargs): """ A patch of mkdocs.commands.build._build_page """ if page.input_path.endswith(AUTODOC_MARK): return build_autodoc(page, *args, **kwargs) return f(page, *args, **kwargs) @patch(build.build) def patched_build(f, config, *args, **kwargs): print("HACK".center(60, "-")) real_config = load_config(config_file=None) for k in ["theme", "theme_dir"]: config[k] = real_config[k] return f(config, *args, **kwargs) <file_sep>from setuptools import setup setup( name="mkdocs-autodoc", version="0.1.2", url="https://github.com/restaction/mkdocs-autodoc", license="MIT", description="Auto generate API document in MKDocs", author="guyskk", author_email="<EMAIL>", keywords=["mkdocs"], packages=["mkdocs_autodoc"], py_modules=["magicpatch"], package_data={ "mkdocs_autodoc": ["autodoc.jinja2"] }, include_package_data=True, entry_points={ "mkdocs.themes": [ "autodoc = mkdocs_autodoc", ] }, zip_safe=False ) <file_sep># MKDocs-Autodoc Auto generate API document in MKDocs, just like autodoc for Sphinx. ## Install pip install git+https://github.com/restaction/mkdocs-autodoc.git After install this plugin, it will auto patch mkdocs and disable --theme option of mkdocs cli in order to use custom theme in ReadTheDocs. See issues below if you wonder **Why should I patch**: https://github.com/rtfd/readthedocs.org/issues/978 https://github.com/mkdocs/mkdocs/issues/206 ## Usage Write a *.autodoc file, which contains which should be rendered in your page. The syntax is: module package.module module::ClassName package.module::ClassName Each line contains a module or class, use `::` to split module and class. This plugin will render functions which defined in the module you selected, or methods of the class you selected, built-in, private, speciall functions/methods will be ignored. This plugin works well for [Google](https://google.github.io/styleguide/pyguide.html#Comments) style docstrings, it not works well for [NumPy](https://github.com/numpy/numpy/blob/master/doc/HOWTO_DOCUMENT.rst.txt) and [Sphinx](http://www.sphinx-doc.org/en/stable/ext/autodoc.html) style docstrings currently. Then add the *.autodoc file(eg: api.autodoc) to mkdocs.yml: site_name: AutodocDemo pages: - Home: index.md - API: api.autodoc Save and restart `mkdocs serve`, it will works. ## Who use it [Flask-Restaction简体中文文档](https://github.com/restaction/docs-zh_CN) [Flask-Restaction English document](https://github.com/restaction/docs-en) <file_sep>""" Autodoc Some useful functions for parsing doc string of modules. """ import importlib import inspect import pydoc from markdown import markdown EXTENSIONS = ['nl2br', 'tables', 'fenced_code'] DOC_STRING_MARKS = ["Args", "Returns", "Yields", "Raises", "Attributes"] def load_selected(text): """ Load selected module or class in text text syntax: module package.module module::class Returns: A list of loaded objects """ result = [] for line in text.splitlines(): if not line: continue if "::" in line: module, classname = line.rsplit("::", maxsplit=1) module = importlib.import_module(module) result.append(getattr(module, classname)) else: result.append(importlib.import_module(line)) return result def parse_meta(meta): """ Parse returns meta of split_doc Returns: A dict of parsed meta """ parsed = {} for section in meta: mark, content = section.split("\n", maxsplit=1) mark = mark.strip("\n:") parsed[mark] = markdown( inspect.cleandoc(content), extensions=EXTENSIONS) return parsed def split_doc(doc): """ Split docstring into title, desc and meta Returns: A tuple of title, desc, meta. title: the summary line of doc desc: the description part meta: a list of sections of the meta part """ if not doc: return "", "", [] # split title/desc,meta lines = doc.strip().split("\n", maxsplit=1) if len(lines) == 1: return lines[0], "", [] title, doc = lines # split desc/meta indexs = [] for mark in DOC_STRING_MARKS: i = doc.find("%s:" % mark) if i >= 0: indexs.append(i) if not indexs: return title, doc, [] indexs = sorted(indexs) desc = doc[:indexs[0]] # split meta into sections sections = [] for i, j in zip(indexs[:-1], indexs[1:]): sections.append(doc[i:j]) sections.append(doc[indexs[-1]:]) return title, desc, sections def parse_doc(doc): """ Parse docstring Returns: A tuple of title, desc, meta. """ title, desc, meta = split_doc(doc) desc = markdown(desc, extensions=EXTENSIONS) meta = parse_meta(meta) return title, desc, meta def get_signature(obj): """ Get signature of module/class/routine Returns: A string signature """ name = obj.__name__ if inspect.isclass(obj): if hasattr(obj, "__init__"): signature = str(inspect.signature(obj.__init__)) return "class %s%s" % (name, signature) else: signature = "%s()" % name elif inspect.ismodule(obj): signature = name else: signature = str(inspect.signature(obj)) return name + signature return signature def parse_routine(obj): """ Parse routine object Returns: A dict, eg: { "signature": "func(*args, **kwargs)", "title": "title", "desc": "desc", "meta": meta } """ title, desc, meta = parse_doc(inspect.getdoc(obj)) return { "signature": get_signature(obj), "title": title, "desc": desc, "meta": meta } def parse_module_or_class(obj): """ Parse module or class and routines in it. Returns: A dics, eg: { "routines": routines, "signature": signature, "title": title, "desc": desc, "meta": meta } """ def predicate(x): # exclude not routines if not inspect.isroutine(x): return False # exclude private and special if x.__name__.startswith("_"): return False # exclude routines not defined in the module if inspect.ismodule(obj) and inspect.getmodule(x) != obj: return False return True routines = inspect.getmembers(obj, predicate) title, desc, meta = parse_doc(inspect.getdoc(obj)) parsed = [parse_routine(obj) for name, obj in routines] return { "routines": parsed, "signature": get_signature(obj), "title": title, "desc": desc, "meta": meta } def get_name(obj): """ Get the name of object """ if inspect.isclass(obj): name = pydoc.classname(obj, None) name = obj.__name__ return name.rsplit(".", maxsplit=1)[-1] def parse_selected(text): """ Parse selected module and class Returns: tuple(contents, titles) """ titles = [] contents = [] for obj in load_selected(text): titles.append(get_name(obj)) item = parse_module_or_class(obj) contents.append(item) return contents, titles <file_sep>""" Patch functions in magic way Usage: >>> from magicpatch import patch >>> def func(x): ... return x ... >>> @patch(func) ... def patch_func(be_patched, x): ... return 2*be_patched(x) ... >>> func(1) 2 >>> """ import uuid import types import functools def copy_func(f): """ Deep copy function of Python3. Based on: http://stackoverflow.com/a/6528148/190597 (<NAME>) http://stackoverflow.com/questions/13503079/how-to-create-a-copy-of-a-python-function (<NAME>) """ # noqa g = types.FunctionType( f.__code__, f.__globals__, f.__name__, f.__defaults__, f.__closure__ ) g = functools.update_wrapper(g, f) g.__kwdefaults__ = f.__kwdefaults__ return g PATCHED = {} def patch(f_be_patched): def decorater(f): key = str(uuid.uuid4()) PATCHED[key] = functools.partial(f, copy_func(f_be_patched)) code = """ def wrapper(*args, **kwargs): return __import__("magicpatch").PATCHED["{}"](*args, **kwargs) """.format(key) context = {} exec(code, context) f_be_patched.__code__ = context["wrapper"].__code__ return f return decorater
8a588180b044a357f84082c82ae59ab29406e731
[ "Markdown", "Python" ]
5
Python
watson8544/mkdocs-autodoc
8a5031f84fe7bf713f365c7c74b7c22e94f54968
1be6238d6a80412c355e72c3ef7a080a60c96a22