branch_name
stringclasses
149 values
text
stringlengths
23
89.3M
directory_id
stringlengths
40
40
languages
listlengths
1
19
num_files
int64
1
11.8k
repo_language
stringclasses
38 values
repo_name
stringlengths
6
114
revision_id
stringlengths
40
40
snapshot_id
stringlengths
40
40
refs/heads/master
<file_sep>const WIDTH = 600 const HEIGHT = 400 const GREN = `rgb(0, 240, 50)` const SNEK_CULLER = `rgb(0, 75, 25)` const SNEED = 25 // snek speed const FPS = 2 window.onload = function init() { //console.error('jazzy snek game') const apple = document.getElementById('app') const elCanvas = document.createElement('canvas') elCanvas.style.height = HEIGHT + 'px' elCanvas.style.width = WIDTH + 'px' elCanvas.height = HEIGHT elCanvas.width = WIDTH elCanvas.style.border = 'red solid 1px' apple.appendChild(elCanvas) const ctx = elCanvas.getContext('2d') let snape = { mode: 'unstarted', snek: [{ x: WIDTH / 2, y: HEIGHT / 2 }], } setInterval(() => { snape = gloop(ctx, snape) }, 1000 / FPS) } const input = { deer: null } window.addEventListener('keydown', (evt) => { if (evt.key === 'ArrowLeft') { input.deer = 'left' } else if (evt.key === 'ArrowRight') { input.deer = 'right' } else if (evt.key === 'ArrowUp') { input.deer = 'up' } else if (evt.key === 'ArrowDown') { input.deer = 'down' } }) function render(ctx, state) { renderBackground(ctx) if (state.mode === 'unstarted') { ctx.fillStyle = 'black' ctx.fillText('Press an Arrow Key to start.', WIDTH / 2, HEIGHT / 2) } renderSnek(ctx, state) } function renderBackground(ctx) { ctx.fillStyle = 'white' ctx.fillRect(0, 0, WIDTH, HEIGHT) } // TODO: need 4 sneed function stankySteppe(stank, dt) { if (stank.mode === 'unstarted') { if (!input.deer) { return stank } stank.mode = 'playing' return stank } // The snek sneeks by fore-going its oldest square and making a new one // In the direction pointed at by the eruw keys let newSnegment = { ...stank.snek[0] } if (input.deer === 'left') { newSnegment.x -= SNEED } else if (input.deer === 'right') { newSnegment.x += SNEED } else if (input.deer === 'up') { newSnegment.y -= SNEED } else if (input.deer === 'down') { newSnegment.y += SNEED } let ate = Math.random() > 0.8 const newSnek = [newSnegment].concat(ate ? stank.snek : tail(stank.snek)) return { snek: newSnek } } function gloop(ctx, stake) { const dt = 1000 / FPS const nextAche = stankySteppe(stake, dt) render(ctx, stake) return nextAche } function renderSnek(ctx, steak) { for (let snegment of steak.snek) { ctx.fillStyle = SNEK_CULLER ctx.fillRect(snegment.x, snegment.y, 20, 20) } } function tail(lst) { return lst.slice(0, lst.length - 1) } function win() {} function lose() {} function spoonFood(stake) {} function isEating(stake) {} function isAutoCannibal(stake) {} function renderFood() {} function renderWin() {} function renderLose() {}
7301d15df022df086dcaf6ae5b4857cc05258133
[ "JavaScript" ]
1
JavaScript
jrjgh/snek
4138ad69fb0f6acdf0248e211dd8d42b630539c4
2c0f4da99119ef54d8a51a3c2bb90b095d3d0dfd
refs/heads/master
<repo_name>mikehopps/TravelingSalesperson<file_sep>/src/TestCities.java /** * Created by michael_hopps on 12/1/17. */ public class TestCities { private City[] cities; public TestCities(){ cities = new City[20]; cities[0] = new City(273, 225); cities[1] = new City(643, 437); cities[2] = new City(235, 630); cities[3] = new City(541, 737); cities[4] = new City(248, 587); cities[5] = new City(129, 185); cities[6] = new City(369, 503); cities[7] = new City(300, 797); cities[8] = new City(555, 406); cities[9] = new City(404, 214); cities[10] = new City(302, 657); cities[11] = new City(775, 438); cities[12] = new City(315, 359); cities[13] = new City(773, 75); cities[14] = new City(129, 69); cities[15] = new City(238, 13); cities[16] = new City(520, 23); cities[17] = new City(295, 299); cities[18] = new City(794, 346); cities[19] = new City(621, 27); } public City[] getCities(){ return getCities(); } }
42f81189aa7df575306e62f670b4dc8fe9e425b1
[ "Java" ]
1
Java
mikehopps/TravelingSalesperson
884555b2b6c00a84738b7761fa40238631329192
4348c35ce24d01af47f157240761fd8d4887a929
refs/heads/main
<file_sep><?php $id = json_decode($_POST["id"], true); include('conn.php'); $mydb = new db(); // สร้าง object ใหม่ , class db() $data = []; $conn = $mydb->connect(); //มีข้อมูลใน invoice_item จะแสดงข้อมูล $res = $conn->prepare("SELECT * FROM invoice_item WHERE invoice_id = $id "); $res->execute(); $data["res"] = $res->fetchAll(PDO::FETCH_ASSOC); exit( json_encode( $data ) );
80ffad6788c3ab71941b94b6a87a8890b3f8e6ec
[ "PHP" ]
1
PHP
Turtlesaurusv2/test2.3
52cc1b4b4179beae270477eeaa4282cc11333166
051bd6a46f470a90399906d1bdebec3099f7bf8b
refs/heads/master
<file_sep>/** * Web服务器: * 1. 返回文件(响应静态资源) * 2. 数据交互(GET,POST)(解析数据) * 3. 数据库 */ const http = require('http'); const fs= require('fs'); let server = http.createServer((req,res)=>{ fs.readFile(`www${req.url}`,(err, data)=>{ if(err){ /** * res.write(404)只是将内容写为404, * 而HTTP状态码为200,按照常理, * 应该将HTTP状态码设置404 * * res.writeHeader(); 向HTTP头部写入404 */ res.writeHeader(404); //header res.write('Not Found'); //body }else{ res.write(data); } res.end(); }) }) server.listen(8080);<file_sep>Nodejs和其他后台语言的区别: 优点: 1. nodejs的对象、语法与JavaScript一样,对前端人员友好 2. 性能不错, 比PHP快80多倍 3. 前后台配合方便 缺点: 1. Java等其它后台语言极其丰富的库 NodeJS用处: 1. 小型规模后台的服务器、中间层 2. 工具【测试、构建(grunt、gulp、webpack...)、抓取】 运行NodeJS程序: 1. 进入js文件所在目录 2. 运行:node xxx.js http模块的使用: 1. 引入http模块 2. 调用http.createServer(callback);callback:有浏览器请求时执行的回调函数 3. 监听端口 tips: 1. NodeJS与JavaScript: NodeJS的语法与前端JS语法很接近 2. 使用NodeJS实现功能时,需要引入不同的模块,例如http模块 3. <file_sep># 开课吧Web全栈学习笔记 ![StackExchange](https://img.shields.io/badge/language-javascript-blue.svg) ![StackExchange](https://img.shields.io/badge/license-MIT-blue.svg) 开课吧Web全栈第二期学习笔记,由石川(blue)主要包括NodeJS, React, Vue ,Angular等前端技术;感兴趣的可以:star: <file_sep>let b = new Buffer('a-b-c-d-e-f'); /** * buf.indexOf(value[, byteOffset][, encoding]), * buf 中 value 首次出现的索引,如果 buf 没包含 value 则返回 -1 */ console.log(b.indexOf('-')); //查找"-"在Buffer中第一次出现的索引 // console.log(b.indexOf(new Buffer('-'))); 与上述没有new的情形等价,没有new自动执行new<file_sep><?php echo $_GET['a']+$_GET['b']; ?><file_sep>const pathlib = require('path'); const Webpack = require('webpack'); module.exports={ mode:'development', entry:'./src/index.js', output:{ path:pathlib.resolve('dest'), filename:'bundle.js' }, plugins:[ // 监听模块 new Webpack.HotModuleReplacementPlugin() ], devServer:{ contentBase:pathlib.resolve('public'), port:8090, hot:true, historyApiFallback:true, watchContentBase:true, //监视contentBase的变化,变化会导致页面重载 inline:true, open: true } };<file_sep>const http = require('http'); const url = require('url'); const querystring = require('querystring'); /** * 创建一个服务器,既能处理GET请求,又能处理POST请求 * * TIPS:提交表单时可以同时提交POST请求和GET请求 */ let server = http.createServer((req, res) => { //处理GET请求 let {pathname, query} = url.parse(req.url, true); //处理POST请求 let str = ''; req.on('data', (data) => { str += data; }); req.on('end', () => { let postData = querystring.parse(str); //控制台输出,query与postData均为对象 console.log(pathname, query, postData); }) res.end(); }); server.listen(8080)<file_sep>let b = new Buffer('a-b-c-d-e-f'); Buffer.prototype.split = Buffer.prototype.split || function (b) { let arr = []; let cur = 0; let n = 0; while ((n = this.indexOf(b, cur)) != -1) { arr.push(this.slice(cur, n)); cur = n + b.length; } arr.push(this.slice(cur)); return arr; }; let arr = b.split('-'); console.log(arr);<file_sep>let a = new Buffer('abc'); let b = new Buffer('ddd'); let c = Buffer.concat([a,b]); console.log(a,b); console.log(c);<file_sep>/** * 使用nodejs编写的第一个服务器 */ //使用require引入HTTP系统模块 const http = require('http'); /** * http.createServer(callback)创建一个服务器 * callback: 有浏览器请求时执行的回调函数 * callback(request, response):传入的callback含有reuquest与response这两个参数 * request 请求 接收的数据(输入) * response 响应 发送的数据(输出) * */ let server = http.createServer(() => { //在高版本的浏览器里会打印两次,因为产生了两次HTTP请求, 第一次请求服务器,第二次请求favicon.ico(高级浏览器自作主张产生了请求) console.log('有人请求我了'); }); //监听端口 server.listen(8080);<file_sep>import css1 from './assets/1.css'; console.log(css1.toString()); //#div1{width: 200px;height: 300px;background: #ccc;}<file_sep><?php $result=$_POST['a']+$_POST['b']; //输出JSON字符串 echo "{\"result\":".$result."}"; ?> <file_sep>const pathlib = require('path'); module.exports={ mode:'development', entry:'./src/es6', output:{ path:pathlib.resolve('dest'), filename:'bundle.js' }, module:{ rules:[ { test:/\.js$/, exclude:/node_modules/, use:{ loader:'babel-loader', options:{ presets:['env'] } } } ] } }<file_sep>/** * path 模块提供了一些工具函数,用于处理文件与目录的路径 */ const path = require('path'); /** * path.parse() 方法返回一个对象, * 对象的属性表示 path 的元素 */ // path.parse() let str = '/var/local/www/aaa/1.png'; //dirname: /var/local/www/aaa 路径名 //basename: 1.png 文件名 //extname: .png 扩展名 console.log(path.dirname(str)); // /var/local/www/aaa console.log(path.basename(str));// 1.png console.log(path.extname(str));// .png<file_sep>/** * crypto 模块提供了加密功能,包含对 OpenSSL * 的哈希、HMAC、加密、解密、签名、以及验证功能 * 的一整套封装 */ const crypto = require('crypto'); /** * Creates and returns a Hash object that can be used * to generate hash digests using the given algorithm. */ let obj = crypto.createHash('md5'); //obj.update('123456')等价于以下三行,可以分开添加 obj.update('123'); obj.update('4'); obj.update('56'); /** * hash.digest([encoding]):Calculates the digest of all of * the data passed to be hashed (using the hash.update() method). * The encoding can be 'hex', 'latin1' or 'base64'. If encoding * is provided a string will be returned; otherwise a Buffer is * returned */ console.log(obj.digest('hex')); /* //双层MD5 function md5(str){ let obj = crypto.createHash('md5'); obj.update(str); return obj.digest('hex'); } console.log(md5(md5('123456')+'XXX')) //XXX部分理解为混淆,怎加解密难度 */ <file_sep>const http = require('http'); const common = require('./libs/common'); let server = http.createServer((req, res) => { // let arr = ''; 不能接收非文本数据 let arr = []; req.on('data', (data) => { arr.push(data); }); req.on('end', () => { let data = Buffer.concat(arr); //data //解析二进制文件上传数据 let post = {}; let files = {}; if (req.headers['content-type']) { let str = req.headers['content-type'].split('; ')[1]; if (str) { let boundary = '--' + str.split('=')[1]; //1.用分隔符切分整个数据 let arr = data.split(boundary); //2.丢弃头尾两个数据 arr.shift(); arr.pop(); //3.丢弃每个数据头尾的"\r\n" arr = arr.map(buffer => buffer.slice(2, buffer.length - 2)); //4.每个数据在第一个"\r\n\r\n"处切成两半 arr.forEach(buffer => { let n = buffer.indexOf('\r\n\r\n'); let disposition = buffer.slice(); let content = buffer.slice(n + 4); if (disposition.indexOf('\r\n') == -1) { } else { } }); } } res.end(); }); //todo: res.end()可以写在这里吗?需要核实 }); server.listen(8080);<file_sep>const pathlib = require('path'); // webpack模块的写法:module.exports={} module.exports = { //entry申明webpack的入口文件(后缀名可以省略) entry: { index:'./src/index', test: './src/1' }, // output申明webpack的输出地址 output:{ path:pathlib.resolve('dest/'), //目标目录 filename:'[name].bundle.js' //输出文件名 } };<file_sep>let b = new Buffer('a-b-c-d-e-f'); console.log(b.slice(0, 5).toString()); //a-b-c<file_sep>import common from './common' window.onload = function(){ document.body.onclick = function(){ alert(common.sum(12,3,43,23,23,34,23,34)); alert(common.sum(3,4)); alert('hello world'); } }<file_sep>// ES6模块的写法 /* export default 12; */ // 输出一个类 /* export default class{ constructor(name, age){ this.name = name; this.age = age; } show(){ console.log(`我叫${this.name},我${this.age}岁`) } } */ //输出多个变量 export let a =12; export let b = 5; <file_sep>//运行方式: node 1.js let oDate = new Date(); console.log(oDate.getFullYear());<file_sep>/** * os 模块提供了一些操作系统相关的实用方法 */ const os = require('os'); /** * os.cpus()方法返回一个对象数组, * 包含每个逻辑 CPU 内核的信息 */ console.log(os.cpus());<file_sep>const http = require('http'); const url = require('url'); const querystring = require('querystring'); const fs = require('fs'); //作为保存前台注册的用户名和密码,待保存到数据库中 let users = { //'tang': '<PASSWORD>', //'blue': '<PASSWORD>' }; /** * 创建一个服务器,实现用户注册与登陆功能 * 前后端接口约定为: * 用户注册: * /reg?user=xxx&pass=xxx * {err:0, msg:'说明'} <== 服务端返回 * 用户登陆: * /login?user=xxx&pass=xxx * {err:0, msg:'说明'} <== 服务端返回 * * 一切来自前台的数据都是不可靠的, 需要做充分的校验!!! */ let server = http.createServer((req, res) => { //处理GET请求 let {pathname, query} = url.parse(req.url, true); //处理POST请求 let str = ''; req.on('data', (data) => { str += data; }); req.on('end', () => { let postData = querystring.parse(str); //假设前端使用了GET请求 let {user, pass} = query; //write codes here..., switch (pathname) { case '/reg': //注册 /** * 一切来自前台的数据都是不可靠的, 需要做充分的校验!!! * 校验数据,用户名与密码均需要校对 * * 前后台均需要数据校验!!! * 前台校验: 提高用户体验 * 后台校验:安全性 */ if (!user) {//必须填写username res.write('{"err":1, "msg":"user is required"}'); } else if (!pass) {//必须填写password res.write('{"err":1, "msg":"pass is required"}'); } else if (!/^\w{8,32}$/.test(user)) {//数字字母下划线长度8~32为 res.write('{"err": 1, "msg": "invaild username"}'); } else if (/^['|"]$/.test(pass)) {//密码不允许'与" res.write('{"err": 1, "msg": "invaild password"}'); } else if (users[user]) {//不允许与已存在的用户名重复 res.write('{"err": 1, "msg": "username already exsits"}'); } else { users[user] = pass; res.write('{"err": 0, "msg": "success"}'); } res.end(); break; case '/login': //登陆 if (!user) { res.write('{"err": 1, "msg": "user is required"}'); } else if (!pass) { res.write('{"err": 1, "msg": "pass is required"}'); } else if (!/^\w{8,32}$/.test(user)) { res.write('{"err": 1, "msg": "invaild username"}'); } else if (/^['|"]$/.test(pass)) { res.write('{"err": 1, "msg": "invaild password"}'); } else if (!users[user]) {//不允许不存在的用户名 res.write('{"err": 1, "msg": "no this user"}'); } else if (users[user] != pass) {//密码必须填写正确 res.write('{"err": 1, "msg": "username or password is incorrect"}'); } else { res.write('{"err": 0, "msg": "login success"}'); } res.end(); break; default: //其他:文件 fs.readFile(`www${pathname}`, (err, data) => { if (err) { res.writeHeader(404); res.write('Not Found'); } else { res.write(data); } res.end(); }); } }); }); server.listen(8080)<file_sep>//dns:域名解析模块 const dns = require('dns'); /** * 使用DNS协议来解析一个主机名(e.g. 'nodejs.org')为一个资源 * 记录的数组。回调函数的参数为(err, records)。 * 当成功时 */ dns.resolve('baidu.com', (err, res)=>{ if(err){ console.log('解析失败'); }else{ console.log(res) } })<file_sep>const http = require('http'); const querystring = require('querystring'); /** * 创建一个服务器,接收前台(表单提交)的POST请求, * 并将请求路径和携带的数据输出 */ let server = http.createServer((req,res)=>{ let str = '';//作为接收数据的容器 //监听data事件:整个数据的其中一段数据到达了 req.on('data', data=>{ str += data; }); //监听end事件,全部数据已到达了 req.on('end', ()=>{ let postData = querystring.parse(str);//将querystring解析成对象 console.log(postData); }); res.end();//向浏览器表面已接收完毕,不需要继续等待 }); server.listen(8080);<file_sep>/** * Web服务器: * 1. 返回文件 * 2. 数据交互(GET,POST) * 3. 数据库 * * *读取服务端的静态文件,将页面文件放到硬盘里, * 利用fs模块读取;将页面文件放到硬盘里后, * 可以在不重启服务器的前提下,用户可以直接访问 * 最新的页面 */ const http = require('http'); const fs= require('fs'); /* /!** * Error: write after end; * 因为:fs.readFile是一个异步操作res.write()写在了回调函数里面,根据js的执行顺序,将优先执行res.end,然后在数据读取完成后调用回调函数,所以会报错 *!/ let server = http.createServer((req, res) => { fs.readFile(`www${req.url}`,(err, data)=>{ if(err){ res.write('404'); //不够好 }else{ res.write(data); } }) res.end(); }); */ //修改后的版本 let server = http.createServer((req, res) => { fs.readFile(`www${req.url}`,(err, data)=>{ if(err){ res.write('404'); //不够好 }else{ res.write(data); } res.end(); }) }); server.listen('8080');
bb3da40fcf67eb4174189e727a4dc9e96db477c8
[ "JavaScript", "PHP", "Markdown" ]
26
JavaScript
Latube/WebXueXi
1404cf31ed5f107874a3023105607cf60937d5bf
2b864aa0a0fabfbdbc0147fa0e72d1a2b3ea1a66
refs/heads/master
<repo_name>emscook/react-assessment-emscook<file_sep>/src/Components/Page/Nav/Bar/Section/Entry/Icon/Icon.js import React, { Component } from 'react' import './Icon.css' // import Icon from './components/Icon/Icon.js' class Icon extends Component { render () { console.log(`${this.props.value}`) return ( <div> <i className={`${this.props.value}`} /> </div> ) } } export default Icon <file_sep>/src/Components/Page/Body/MidBar/PostBox/EntryBox/UploadPic/UploadPic.js import React, { Component } from 'react' import './UploadPic.css' // import UploadPic from './components/UploadPic/UploadPic.js' class UploadPic extends Component { render () { return <div>{`${this.props.value.print}`}</div> } } export default UploadPic <file_sep>/src/Components/Page/Body/RightBar/LegalBox/Advertise/Text/Text.js import React, { Component } from 'react' import './Text.css' // import Text from './components/Text/Text.js' class Text extends Component { render () { return `${this.props.value.print}` } } export default Text <file_sep>/src/Components/Page/Body/LeftBar/Trends/Listings/Listing/Listing.js import React, { Component } from 'react' import './Listing.css' // import Listing from './components/Listing/Listing.js' import Title from './Title/Title' import Body from './Body/Body' class Listing extends Component { render () { return ( <div> <Title value={this.props.value.title} /> <Body value={this.props.value.body} /> </div> ) } } export default Listing <file_sep>/src/Components/Page/Body/LeftBar/UserPanel/Ground/UserDetails/TweetsListing/TweetsHeading/TweetsHeading.js import React, { Component } from 'react' import './TweetsHeading.css' // import LeftBar from './components/LeftBar/LeftBar.js' class TweetsHeading extends Component { render () { return `${this.props.value.print}` } } export default TweetsHeading <file_sep>/src/Components/Page/Page.js import React, { Component } from 'react' import './Page.css' import Body from './Body/Body' import Nav from './Nav/Nav' class Page extends Component { urly = str => { if (str === 'home') { return '/' } return '/' + str.toLowerCase().split(' ').join('') } titley = str => { return str .toLowerCase() .split(' ') .map(function (word) { return word.replace(word[0], word[0].toUpperCase()) }) .join(' ') } myBodies = { home: [ { type: 'splash', headOne: 'Evan', headTwo: 'Susag', img: require('./Pics/world.png'), logOne: '☮', logTwo: '🌐', body: [], children: [{}] } ], 'about me': [ { type: 'intro', children: [ { title: 'About Me', img: require('./Pics/evan.jpg'), subtitle: 'Growing up in a military family provided me a unique environment that nurtured my technical skills and instilled in me a strong sense of unity with my fellow man. This compassion has driven me to put giving back above all else. I believe I am well equipped to do so by applying my skills to the software industry, so we can usher in a new age of accessibility with regards to our computing machines. I have lived in Colorado, New York and Hawaii. ' } ] } // { type: 'sandbox', children: [] } ], projects: [ // { type: 'intro', children: [] }, { type: 'catalog', children: [ { head: 'XML File Transfer', gitLink: 'https://github.com/emscook/java-xml-file-transfer-assessment-emscook', gitText: 'Click here for the repository of my solution', img: 'fas fa-download', body: [ { head: '', body: [ 'The student will create an application that inspects a directory, reads in the contents of a file, uses JAXB to create an XML document for that file which contains a username (the name of the student), the date in yyyy-MM-dd format, the filename, and the contents of the file itself (stored as a byte array). The application will then open a Socket, write that XML document to that Socket, and then close the Socket. The application will repeat this process for each file in the designated directory.' ] }, { head: '', body: [ 'The student will then create an application that hosts a ServerSocket that listens for incoming connections. When a connection is received, it will spawn a client handler thread to interact with the client and then return to listening for new connections. The client handler thread will read an XML document from the connection. The XML document will contain a username, a date, a filename, and the contents of the file. The application will first create a directory for the username if it does not already exist. The application will then create a subdirectory for the date if it does not already exist. Finally, the application will recreate the file in that directory by decoding the Base64 encoded contents and writing the decoded contents to the file.' ] }, { head: 'Important Topics', body: ['Jaxb', 'Marshalling and Unmarshalling', 'Threads'] } ] }, { head: 'Quizler', gitLink: 'https://github.com/emscook/js-assessment-quizler-emscook', gitText: 'Click here for the repository of my solution', img: 'fas fa-question', body: [ { head: '', body: [ 'In this assessment students are tasked with using the helper functions they created in their lib.js file throughout this module to build a command line application which builds quizzes and allows the user to take quizzes they have built or pull random questions from multiple quizzes and take a random quiz.' ] }, { head: '', body: [ 'Students will use inquirer.js and vorpal.js to build their command line tool. The documentation for each will be very useful for students when completing this assessment. A skeleton is provided which sets ups a command line interface for the students is provided.' ] }, { head: 'Goals', body: [ 'To assess the students knowledge of the JavaScript language', 'To assess the students ability to write and use Node as a JavaScript environment', 'To to assess students ability to adapt to new technologies and read documentation of libraries curated for the requirements of this assessment', 'To assess students abilities to combine external libraries with their own custom libraries in order to build an application.' ] }, { head: 'Important Topics', body: ['Promises', 'Async', 'Node'] } ] }, { head: 'Service Creation', gitLink: 'https://github.com/emscook/AssessmentTwoSubmit', gitText: 'Click here for the repository of my solution', img: 'fas fa-database', body: [ { head: '', body: [ 'Create a service that will handle storing data on Users and their Addresses.' ] }, { head: 'A Client entity must have the following properties:', body: [ 'Name: The name of the client', 'Password: <PASSWORD>', 'Birthday: Date of birth', 'Address: Reference to a single Address object', 'Relations: A list of other Client entities that this client is related to' ] }, { head: 'The Address entity will have the following properties:', body: [ 'Street: This will be the street address, such as ‘221b Baker Street”', 'City: The city in which this address exists', 'State: The state in which the City exists', 'Residents: The User entities associated with this Address', 'Relations: A list of other Client entities that this client is related to' ] }, { head: 'When returning a User object, make sure that the DTO you return only contains the following fields:', body: ['Name', 'Birthday'] }, { head: 'When returning an Address object, make sure that the DTO you return only contains the following fields:', body: ['Street', 'City', 'State'] }, { head: 'Implement the following endpoints:', body: [ 'GET /user: Returns all User DTOs', 'GET /user/{id}: Returns a single User DTO by their unique id', 'GET /user/{id}/address: Returns the Address DTO associated with a User', 'GET /user/{id}/relations: Returns a list of User DTO this User is related to', 'GET /address?city=___&state=___: Returns a list of all addresses. f the optional ‘city’ parameter is provided, the list of addresses must all belong to that particular city. If the optional ‘state’ parameter is provided, the list of addresses must all belong to that particular state.', 'GET /address/{id}: Returns an address by it’s unique id', 'GET /address/{id}/residents: Returns a list of User DTOs associated with this address', 'POST /user: Accepts a User DTO that contains the following fields(Name, Password, Birthday)', 'POST /address: Accepts an Address DTO that contains the following fields(Street, City, State)', 'POST /user/{id}/relations/{relationId}: Adds a relation to another user. {relationId} must point to a valid User', 'POST /user/{id}/address/{addressId}: Sets the address of the referenced User', 'PUT /user/{id}: Replaces the User entity at the given id with updated information. Accepts a User DTO that contains the following fields(Name, Password, Birthday, Administrator)', 'PUT /address/{id}: Replaces the Address entity at the given id with updated information. Accepts an Address DTO that contains the following fields(Street, City, State)', 'DELETE /user/{id}: Deletes the User at the given id', 'DELETE /address/{id}: Deletes the Address at the given id' ] }, { head: 'Important Topics', body: ['REST', 'Spring', 'IoC'] } ] }, { head: 'Personal Portfolio Site', gitLink: 'https://github.com/emscook/react-assessment-emscook', gitText: 'Click here for the repository of my solution', img: 'fas fa-folder-open', body: [ { head: '', body: [ 'This assessment serves as the capstone of the interpersonal and technical lecture modules by combining the “Tell Your Story” module and the React/Redux, front-end development, module. Students will be recieve requirements to design and develop a personal portfolio page on Monday of the second week of the module. This portfolio page will contain their biographies, stories (Maybe in a blog format), resumes, descriptions of the assignments and assessments they completed, any previous projects they built, and professional images of themselves. The students should develop their own user stories and design the portfolio site themselves. On assessment day, students will take a short exam over terms from the React/Redux module and then each student will present their portfolio pages along with their stories and experiences through FastTrack’D to the class and any internal Cook employees that wish to come and watch.' ] }, { head: 'Goal', body: [ 'Students will create their own portfolio page/site and prepare a presentation in which they will cover their experiences at FastTrack’D, their story which they have developed throughout the course, and their technical abilities by using their portfolio sites to effectively guide and support their presentation. This will serve as a great resource for representing each student individually and their experience throughout the lecture modules of FastTrack’D.' ] }, { head: 'Tasks', body: [ 'Create user stories for your personal portfolio site', 'Create a style guide and use it to make a design template', 'Include your Story, Biography, Resume, and past coding projects (including assignments and assessment descriptions) in your design.', 'Take your design and break it into React Components.', 'Implement your components using React and Redux.' ] }, { head: 'Important Topics', body: ['React', 'Redux', 'JSX', 'Components'] } ] }, { head: 'AU Photo Upload', gitLink: 'https://github.com/zealousduck/AUPhotoUpload', gitText: 'Click here for the repository.', img: 'fab fa-dropbox', body: [ { head: '', body: [ 'Senior Design Project for Auburn University -- Upload pictures to a shared resource wirelessly soon after taking them.' ] }, { head: 'My Responsibilities', body: [ 'All interactions with dropbox', 'Queue based multiprocess communication' ] }, { head: 'Important Topics', body: [ 'Tkinter', 'Dropbox API', 'Multiprocessing', 'Exponential Backoff', 'Worker Threads: batch upload' ] } ] } ] } ], education: [ { type: 'features', titleLink: require('./Docs/ems0025v4.docx'), title: 'My Resume', children: [ { head: 'Auburn University', body: [ { head: '', body: [ 'My experiences in academia while acheiving my degree in Software Engineering instilled me with a passion for personal development and lifelong learning.' ] }, { head: '', body: [ 'The curriculum, while challenging compared to a typical Computer Science degree, introduced me to a wide rage of domains and industry practices.' ] }, { head: 'Topics Studied', body: [ 'General: Algorithms, Modeling and Design, Discrete Structures, Formal Languages, Operating Systems, Computer Architecture, Software Construction, Principals of Programming Languages', 'Specialized Topics: Software Quality Assurance, Software Processes, Computer Graphics, Computer Networks ' ] } ], img: 'fa fa-graduation-cap' }, { head: 'Internet Communities', body: [ { head: '', body: [ 'As an avid netizen, my participation in virtual communities has shaped who I am as a person.' ] }, { head: '', body: [ 'A deep connection to these groups from an early age has equipped me with considerable skill in navigating, maintaining and utilizing the net to achieve my goals.' ] }, { head: 'Notable Communities', body: [ 'Raspberry Pi: This community is one of the most welcoming maker communities out there. My time spent there gave me the confidence to dive into topics that challenge me, so I can come out stronger.', 'Code Fights: The competitive atmosphere provided by this site gave me an appreciation for healthy competition.' ] } ], img: 'fab fa-stack-overflow' }, { head: 'Cook Systems', body: [ { head: '', body: [ "The rigorus course of study provided to me in the FastTrack'D program has allowed me to map my programming skills into the essential tools that the software industry demands." ] }, { head: '', body: [ 'Specifically, this training has augmented my capabilities when it comes to web development and functional programming.' ] }, { head: 'Course of Study', body: [ 'Essential Topics: Object Oriented Programming, I/O, Reflection, XML, Concurrency, RDBMS, Transducers, REST, IoC', 'Java: Collections, Design Patterns, Generics, JAXB', 'Javascript: Node, FP libraries, Promies', 'React: Components, Routing, Networking, Redux, Webpack', 'Spring: Controllers, Services, Repositories, ORM' ] } ], img: 'fa fa-user-tie' } ] } // { type: 'intro', children: [] }, // { type: 'sandbox', children: [] } ] } mySections = Object.keys(this.myBodies) state = { nav: { bar: { brand: { text: '<NAME>' }, burger: { targetID: 'menuID' }, menu: { id: 'menuID', sections: this.mySections.map(someStr => ({ title: this.titley(someStr), ref: this.urly(someStr) })) } } }, bodies: this.myBodies } render () { return ( <div> <Nav value={this.state.nav} /> <Body value={{ bodies: this.state.bodies, url: this.urly }} /> </div> ) } } export default Page <file_sep>/src/Components/Page/Body/RightBar/FollowBox/Suggestions/Listing/Entry/TitleBar/Display/Display.js import React, { Component } from 'react' import './Display.css' // import Display from './components/Display/Display.js' class Display extends Component { render () { return `${this.props.value.print}` } } export default Display <file_sep>/src/Components/Page/Nav/Bar/Burger/Burger.js import React, { Component } from 'react' class Burger extends Component { render () { return ( <span class='navbar-burger burger' data-target='navbarMenu'> <span /> <span /> <span /> </span> ) } } export default Burger <file_sep>/src/Components/Page/Body/MidBar/Tweets/Tweet/Entry/Stats/Retweets/Retweets.js import React, { Component } from 'react' import './Retweets.css' // import Retweets from './components/Retweets/Retweets.js' class Retweets extends Component { render () { return `${this.props.value.icon} ${this.props.value.print}` } } export default Retweets <file_sep>/src/Components/Page/Body/MidBar/Tweets/Tweet/Expand/Expand.js import React, { Component } from 'react' import './Expand.css' // import Expand from './components/Expand/Expand.js' class Expand extends Component { render () { return `${this.props.value.print}` } } export default Expand <file_sep>/src/Components/Page/Body/LeftBar/Trends/Title/Label/Label.js import React, { Component } from 'react' import './Label.css' // import Label from './components/Label/Label.js' class Label extends Component { render () { return `${this.props.value.print}` } } export default Label <file_sep>/src/Components/Page/Nav/Nav.js import React, { Component } from 'react' import './Nav.css' // import Nav from './components/Nav/Nav.js' import Bar from './Bar/Bar' class Nav extends Component { render () { return ( <section class='hero is-info is-medium is-bold'> <div class='hero-head'> <Bar value={this.props.value.bar} /> </div> </section> ) } } export default Nav <file_sep>/src/Components/Page/Body/MidBar/Tweets/Tweet/Entry/Stats/Comments/Comments.js import React, { Component } from 'react' import './Comments.css' // import Comments from './components/Comments/Comments.js' class Comments extends Component { render () { return `${this.props.value.icon} ${this.props.value.print}` } } export default Comments <file_sep>/src/Components/Page/Body/LeftBar/Trends/Trends.js import React, { Component } from 'react' import './Trends.css' // import Trends from './components/Trends/Trends.js' import Listings from './Listings/Listings' import Title from './Title/Title' class Trends extends Component { render () { return ( <div className='fillHori left-text'> <a href='#explore' className='pagebar-read trends whiteItem read-padding' > <Title value={this.props.value.title} /> </a> <a href='#explore' className='pagebar-read trends whiteItem read-padding' > <Listings value={this.props.value.listings} /> </a> </div> ) } } export default Trends <file_sep>/src/Components/Page/Body/RightBar/FollowBox/Suggestions/Suggestions.js import React, { Component } from 'react' import './Suggestions.css' // import Suggestions from './components/Suggestions/Suggestions.js' import Listing from './Listing/Listing' class Suggestions extends Component { render () { return ( <div> {this.props.value.listings.map(bar => { return <Listing value={bar} /> })} </div> ) } } export default Suggestions <file_sep>/src/Components/Page/Body/MidBar/PostBox/Picture/Picture.js import React, { Component } from 'react' import './Picture.css' // import Picture from './components/Picture/Picture.js' class Picture extends Component { render () { return <div /> } } export default Picture <file_sep>/src/Components/Page/Body/LeftBar/UserPanel/Ground/UserDetails/FollowingListing/FollowingListing.js import React, { Component } from 'react' import './FollowingListing.css' import FollowingCount from './FollowingCount/FollowingCount' import FollowingHeading from './FollowingHeading/FollowingHeading' class FollowingListing extends Component { render () { return ( <div> <FollowingHeading value={this.props.value.heading} /> <FollowingCount value={this.props.value.count} /> </div> ) } } export default FollowingListing <file_sep>/src/Components/Page/Body/Catalog/Catalog.js import React, { Component } from 'react' class Catalog extends Component { render () { return ( <div class='rows features-two'> {this.props.value.map(ent => { return ( <div className='row is-4'> <div className='card columns is-shady is-vcentered '> <div className='card-image'> <i className={`${ent.img} `} /> </div> <div className='card-content'> <div className='content'> <h4>{ent.head}</h4> {ent.body.map(someEntry => { if (someEntry.head) { return ( <p> <h6>{someEntry.head}</h6> {someEntry.body.map(eggo => ( <li> {eggo} </li> ))} </p> ) } else { return someEntry.body.map(eggo => ( <p> {eggo} </p> )) } })} <a href={ent.gitLink}> {ent.gitText} </a> </div> </div> </div> </div> ) })} </div> ) } } export default Catalog <file_sep>/src/Components/Page/Body/RightBar/FollowBox/Title/Refresh/Refresh.js import React, { Component } from 'react' import './Refresh.css' // import Refresh from './components/Refresh/Refresh.js' class Refresh extends Component { render () { return `${this.props.value.print}` } } export default Refresh <file_sep>/src/Components/Page/Body/LeftBar/UserPanel/Ground/UserHeadline/FullName/FullName.js import React, { Component } from 'react' import './FullName.css' class FullName extends Component { render () { return <div>{`${this.props.value.print}`}</div> } } export default FullName <file_sep>/src/Components/Page/Body/RightBar/FollowBox/Title/ViewAll/ViewAll.js import React, { Component } from 'react' import './ViewAll.css' // import ViewAll from './components/ViewAll/ViewAll.js' class ViewAll extends Component { render () { return `${this.props.value.print}` } } export default ViewAll <file_sep>/src/Components/Page/Body/MidBar/Tweets/TweetItem/TweetItem.js import React, { Component, Fragment } from 'react' import ListItem from '@material-ui/core/ListItem' import ListItemSecondaryAction from '@material-ui/core/ListItemSecondaryAction' import ListItemText from '@material-ui/core/ListItemText' import IconButton from '@material-ui/core/IconButton' import Delete from '@material-ui/icons/Delete' class TweetItem extends Component { render () { return ( <ListItem> <ListItemText primary={this.props.content} /> <ListItemText primary={this.props.tweetID} /> <ListItemSecondaryAction> { <Fragment> <IconButton aria-label='Delete' onClick={this.props.deleteTweet}> <Delete /> </IconButton> </Fragment> } </ListItemSecondaryAction> </ListItem> ) } } export default TweetItem <file_sep>/src/Components/Page/Body/MidBar/PostBox/PostBox.js import React, { Component } from 'react' import './PostBox.css' // import PostBox from './components/PostBox/PostBox.js' import EntryBox from './EntryBox/EntryBox' import Picture from './Picture/Picture' class PostBox extends Component { render () { return ( <a href='#explore ' className='pagebar-item fillHori'> <EntryBox value={this.props.value.entryBox} /> </a> ) } } export default PostBox <file_sep>/src/Components/Page/Body/MidBar/Tweets/Tweet/Entry/Entry.js import React, { Component } from 'react' import './Entry.css' // import Entry from './components/Entry/Entry.js' import Contents from './Contents/Contents' import Stats from './Stats/Stats' import TitleBar from './TitleBar/TitleBar' class Entry extends Component { render () { return ( <div> <TitleBar value={this.props.value.titleBar} /> <Contents value={this.props.value.contents} /> <Stats value={this.props.value.stats} /> </div> ) } } export default Entry <file_sep>/src/Components/Page/Body/RightBar/FollowBox/Suggestions/Listing/Entry/TitleBar/TitleBar.js import React, { Component } from 'react' import './TitleBar.css' // import TitleBar from './components/TitleBar/TitleBar.js' import Display from './Display/Display' import Name from './Name/Name' import Verified from './Verified/Verified' class TitleBar extends Component { render () { return ( <div> <Name value={this.props.value.name} /> <Verified value={this.props.value.verified} /> <Display value={this.props.value.display} /> </div> ) } } export default TitleBar <file_sep>/src/Components/Page/Body/MidBar/Tweets/Tweet/Entry/Stats/Stats.js import React, { Component } from 'react' import './Stats.css' // import Stats from './components/Stats/Stats.js' import Comments from './Comments/Comments' import DirectMessage from './DirectMessage/DirectMessage' import Likes from './Likes/Likes' import Retweets from './Retweets/Retweets' class Stats extends Component { render () { return ( <div> <Comments value={this.props.value.comments} /> <Retweets value={this.props.value.retweets} /> <Likes value={this.props.value.likes} /> <DirectMessage value={this.props.value.directMessage} /> </div> ) } } export default Stats <file_sep>/src/Components/Page/Body/Intro/Intro.js import React, { Component } from 'react' class Intro extends Component { render () { return ( <div class='intro column is-8 is-offset-2'> {this.props.value.map(ent => { console.log(ent.img) return ( <div> <h2 class='title'>{ent.title}</h2> <img src={ent.img} alt='Description' width='33%' /> <p class='subtitle'> {ent.subtitle} </p> </div> ) })} </div> ) } } export default Intro <file_sep>/src/Components/Page/Body/RightBar/LegalBox/Advertise/Advertise.js import React, { Component } from 'react' import './Advertise.css' // import Advertise from './components/Advertise/Advertise.js' import Icon from './Icon/Icon' import Text from './Text/Text' class Advertise extends Component { render () { return ( <div> <Icon value={this.props.value.icon} /> <Text value={this.props.value.text} /> </div> ) } } export default Advertise <file_sep>/src/Components/Page/Body/LeftBar/UserPanel/Ground/UserDetails/FollowingListing/FollowingCount/FollowingCount.js import React, { Component } from 'react' import './FollowingCount.css' // import LeftBar from './components/LeftBar/LeftBar.js' // import FollowingCount from './FollowingCount/FollowingCount' // import FollowingHeading from './FollowingHeading/FollowingHeading' class FollowingCount extends Component { render () { return `${this.props.value.print}` } } export default FollowingCount <file_sep>/src/Components/Page/Body/MidBar/Tweets/Tweets.js import React, { Component } from 'react' import './Tweets.css' // import Tweets from './components/Tweets/Tweets.js' import Card from '@material-ui/core/Card' import TweetList from './TweetList/TweetList' import TweetInput from './TweetInput/TweetInput' class Tweets extends Component { render () { return ( <Card> <TweetList tweets={this.props.value.listings} /> </Card> ) } } export default Tweets <file_sep>/src/Components/Page/Body/RightBar/LegalBox/Legal/Legal.js import React, { Component } from 'react' import './Legal.css' // import Legal from './components/Legal/Legal.js' class Legal extends Component { render () { return `${this.props.value.print}` } } export default Legal <file_sep>/src/Components/Page/Body/MidBar/Tweets/Tweet/Entry/Stats/DirectMessage/DirectMessage.js import React, { Component } from 'react' import './DirectMessage.css' // import DirectMessage from './components/DirectMessage/DirectMessage.js' class DirectMessage extends Component { render () { return `${this.props.value.icon}` } } export default DirectMessage <file_sep>/src/Components/Page/Nav/Bar/Menu/Menu.js import React, { Component } from 'react' class Menu extends Component { // <a href=''>Links</a> render () { return ( <div id='navbarMenu' class='navbar-menu'> <div class='navbar-end'> <div class='tabs is-right'> <ul> {this.props.value.sections.map(ent => { return <a href={ent.ref}>{ent.title}</a> })} </ul> </div> </div> </div> ) } } export default Menu <file_sep>/src/Components/Page/Nav/Bar/Section/Section.js import React, { Component } from 'react' import './Section.css' // import Section from './components/Section/Section.js' import Entry from './Entry/Entry' class Section extends Component { render () { return ( <div className='navbar-start-cust'> {this.props.section.entries.map(entry => { return ( <Entry key={entry.key} value={{ label: `${entry.label}`, input: `${entry.input}`, icon: `${entry.icon}`, link: `${entry.link}` }} /> ) })} </div> ) } } export default Section <file_sep>/src/Components/Page/Nav/Bar/Brand/Brand.js import React, { Component } from 'react' class Brand extends Component { render () { return ( <div class='navbar-brand'> <a class='navbar-item' href='../'> <a href=''>{this.props.value.text}</a> </a> </div> ) } } export default Brand <file_sep>/src/Components/Page/Body/RightBar/FollowBox/FollowBox.js import React, { Component } from 'react' import './FollowBox.css' // import FollowBox from './components/FollowBox/FollowBox.js' import Connect from './Connect/Connect' import Find from './Find/Find' import Suggestions from './Suggestions/Suggestions' import Title from './Title/Title' class FollowBox extends Component { render () { return ( <div className='separated-posts whiteItem'> <Title value={this.props.value.title} /> <a href='#explore' className='pagebar-read trends whiteItem read-padding' > <Suggestions value={this.props.value.suggestions} /> </a> <Find value={this.props.value.find} /> <Connect value={this.props.value.connect} /> </div> ) } } export default FollowBox <file_sep>/src/Components/Page/Body/LeftBar/UserPanel/Ground/Photo/Photo.js import React, { Component } from 'react' import './Photo.css' class Photo extends Component { render () { return `${this.props.value.print}` } } export default Photo <file_sep>/src/Components/Page/Body/LeftBar/UserPanel/Ground/UserHeadline/UserHeadline.js import React, { Component } from 'react' import './UserHeadline.css' import FullName from './FullName/FullName' import UserName from './UserName/UserName' class UserHeadline extends Component { render () { return ( <div> <FullName value={this.props.value.full} /> <UserName value={this.props.value.user} /> </div> ) } } export default UserHeadline <file_sep>/src/Components/Page/Body/Body.js import React, { Component } from 'react' import './Body.css' import LeftBar from './LeftBar/LeftBar' import RightBar from './RightBar/RightBar' import { Switch, Route } from 'react-router-dom' import MidBar from './MidBar/MidBar' import Home from './Home' class Body extends Component { render () { return ( <div className='full-back-splash'> <Switch> {Object.keys(this.props.value.bodies).map(ent => { return ( <Route exact path={this.props.value.url(ent)} render={() => <Home value={this.props.value.bodies[ent]} />} /> ) })} </Switch> </div> ) } } export default Body <file_sep>/src/Components/Page/Nav/Bar/Bar.js import React, { Component } from 'react' import Brand from './Brand/Brand' import Burger from './Burger/Burger' import Menu from './Menu/Menu' class Bar extends Component { render () { return ( <nav class='navbar is-fixed-top hero is-info'> <div class='container'> <Brand value={this.props.value.brand} /> <Burger value={this.props.value.burger} /> <Menu value={this.props.value.menu} /> </div> </nav> ) } } export default Bar <file_sep>/src/Components/Page/Body/RightBar/RightBar.js import React, { Component } from 'react' import './RightBar.css' // import RightBar from './components/RightBar/RightBar.js' import FollowBox from './FollowBox/FollowBox' import LegalBox from './LegalBox/LegalBox' class RightBar extends Component { render () { return ( <div className='pagebar-item third'> <div className='fillHori'> <FollowBox value={this.props.value.follow} /> <LegalBox value={this.props.value.legalBox} /> </div> </div> ) } } export default RightBar <file_sep>/src/Components/Page/Body/RightBar/FollowBox/Suggestions/Listing/Entry/Follow/Follow.js import React, { Component } from 'react' import './Follow.css' // import Follow from './components/Follow/Follow.js' class Follow extends Component { render () { return `${this.props.value.print}` } } export default Follow <file_sep>/src/Components/Page/Body/RightBar/FollowBox/Suggestions/Listing/Listing.js import React, { Component } from 'react' import './Listing.css' // import Listing from './components/Listing/Listing.js' import Dismiss from './Dismiss/Dismiss' import Entry from './Entry/Entry' import Photo from './Photo/Photo' class Listing extends Component { render () { return ( <div> <Photo value={this.props.value.photo} /> <Entry value={this.props.value.entry} /> <Dismiss value={this.props.value.dismiss} /> </div> ) } } export default Listing <file_sep>/src/Components/Page/Nav/Bar/Section/Entry/Input/Button/Button.js import React, { Component } from 'react' import './Button.css' // import Button from './components/Button/Button.js' class Button extends Component { render () { return <div /> } } export default Button <file_sep>/src/Components/Page/Body/LeftBar/UserPanel/Sky/Sky.js import React, { Component } from 'react' import './Sky.css' // import LeftBar from './components/LeftBar/LeftBar.js' class Sky extends Component { render () { return <div className='user-card-top' /> } } export default Sky <file_sep>/src/Components/Page/Body/RightBar/FollowBox/Suggestions/Listing/Entry/Entry.js import React, { Component } from 'react' import './Entry.css' // import Entry from './components/Entry/Entry.js' import Follow from './Follow/Follow' import TitleBar from './TitleBar/TitleBar' class Entry extends Component { render () { return ( <div> <Follow value={this.props.value.follow} /> <TitleBar value={this.props.value.titleBar} /> </div> ) } } export default Entry <file_sep>/src/Components/Page/Body/LeftBar/UserPanel/Ground/UserDetails/TweetsListing/TweetsCount/TweetsCount.js import React, { Component } from 'react' import './TweetsCount.css' // import LeftBar from './components/LeftBar/LeftBar.js' class TweetsCount extends Component { render () { return `${this.props.value.print}` } } export default TweetsCount <file_sep>/src/Components/Page/Body/RightBar/FollowBox/Connect/Connect.js import React, { Component } from 'react' import './Connect.css' // import Connect from './components/Connect/Connect.js' class Connect extends Component { render () { return ( <a href='#explore ' className='pagebar-item '> {`${this.props.value.print}`} </a> ) } } export default Connect <file_sep>/src/Components/Page/Body/LeftBar/Trends/Listings/Listings.js import React, { Component } from 'react' import './Listings.css' // import Listings from './components/Listings/Listings.js' import Listing from './Listing/Listing' class Listings extends Component { render () { return ( <div> {this.props.value.entries.map(bar => { return <Listing value={bar} /> })} </div> ) } } export default Listings <file_sep>/src/Components/Page/Body/MidBar/PostBox/EntryBox/EntryBox.js import React, { Component } from 'react' import './EntryBox.css' // import EntryBox from './components/EntryBox/EntryBox.js' import Text from './Text/Text' import UploadPic from './UploadPic/UploadPic' class EntryBox extends Component { render () { return <Text value={this.props.value.text} /> } } export default EntryBox
8deaaa616d5cc7509bb0540c45175f1b6c0ccf29
[ "JavaScript" ]
50
JavaScript
emscook/react-assessment-emscook
abe4f05dc790850fbd6cdad35d73c3bb30f705aa
a7cb0234dabad2b2791d657618e64cd5698c31a9
refs/heads/master
<repo_name>prestonedwards3/giphy<file_sep>/app.js var gifs = ["Rihanna", "<NAME>", "<NAME>", "<NAME>", "Beyonce", "<NAME>", "<NAME>", "<NAME>", "Drake", "<NAME>", "<NAME>"] function showGif() { var name = $(this).attr("data-name"); var queryURL = "https://api.giphy.com/v1/gifs/search?q=" + name + "&api_key=<KEY>&limit=10"; $.ajax({ url: queryURL, method: "GET" }).then(function (response) { console.log(response); var gifData = response; for (p = 0; p < response.data.length; p++) { var img = $("<img>") img.attr('src', response.data[p].images.downsized.url) console.log(gifData.data[p].url); $("#pics").prepend(img); } }); } function renderButton() { $("#buttonDump").empty(); for (var i = 0; i < gifs.length; i++) { var btn = $("<button>"); btn.addClass("giphy"); btn.attr("data-name", gifs[i]); btn.text(gifs[i]); $("#buttonDump").prepend(btn); } }; $(document).ready(function () { renderButton(); $("#gif-button").on("click", function (event) { event.preventDefault(); renderButton(); var gif = $("#gif-input").val().trim(); gifs.push(gif); }) $(document).on("click", ".giphy", showGif); });
e368ddabd12524b04c9f11df7a44a74cf5964601
[ "JavaScript" ]
1
JavaScript
prestonedwards3/giphy
826c91565027e253e0fd1867efcaa6e05b8919ef
2f36520712665b5b98de27cbf4e64e8bedc630d2
refs/heads/master
<repo_name>diegolopez1797/TuCitaMedica<file_sep>/app/src/main/java/com/example/diego/tucitamedica/FormularioActivity.java package com.example.diego.tucitamedica; import android.content.Intent; import android.graphics.Bitmap; import android.net.Uri; import android.provider.MediaStore; import android.support.annotation.NonNull; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; import android.widget.Toast; import android.widget.ImageView; import com.example.diego.tucitamedica.model.Perfil; import com.example.diego.tucitamedica.model.Persona; import com.google.android.gms.tasks.OnFailureListener; import com.google.android.gms.tasks.OnSuccessListener; import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.auth.FirebaseUser; import com.google.firebase.database.DataSnapshot; import com.google.firebase.database.DatabaseError; import com.google.firebase.database.DatabaseReference; import com.google.firebase.database.FirebaseDatabase; import com.google.firebase.database.ValueEventListener; import com.google.firebase.storage.FirebaseStorage; import com.google.firebase.storage.StorageReference; import com.google.firebase.storage.UploadTask; import java.io.ByteArrayOutputStream; import java.io.File; public class FormularioActivity extends AppCompatActivity { FirebaseDatabase database; Button btnTerminar; DatabaseReference refPersona; DatabaseReference refMensaje; TextView txtSaludo; ImageView imgFoto; Button btnTomar; static final int REQUEST_IMAGE_CAPTURE = 1; Persona persona ; Button btnBuscar; EditText txtNombre; EditText txtApellido; EditText txtCedula; EditText txtCelular; EditText txtFechaNacimiento; EditText txtEmail; EditText txtSexo; EditText txtEdad; EditText txtDireccion; EditText txtEstadoCivil; private FirebaseAuth mAuth; private FirebaseAuth.AuthStateListener mAuthListener; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_formulario); mAuth = FirebaseAuth.getInstance(); mAuthListener = new FirebaseAuth.AuthStateListener() { @Override public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) { FirebaseUser user = firebaseAuth.getCurrentUser(); if (user != null) { // User is signed in Log.d("[MenuPrincipal]", "onAuthStateChanged:signed_in:" + user.getUid()); } else { // User is signed out Intent intent= new Intent(FormularioActivity.this, SplashActivity.class); intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); startActivity(intent); finish(); } // ... } }; imgFoto = (ImageView) findViewById(R.id.imgFoto); btnTomar = (Button) findViewById(R.id.btnTomar); persona = new Persona(); btnTerminar = (Button) findViewById(R.id.btnTerminar); btnBuscar= (Button) findViewById(R.id.btnBuscar); txtSaludo= (TextView) findViewById(R.id.txtSaludo); txtEmail= (EditText) findViewById(R.id.txtEmail); txtApellido= (EditText) findViewById(R.id.txtApellidos); txtNombre= (EditText) findViewById(R.id.txtNombre); txtCedula= (EditText) findViewById(R.id.txtIdentificacion); txtCelular= (EditText) findViewById(R.id.txtCelular); txtFechaNacimiento= (EditText) findViewById(R.id.txtFechaNacimiento); txtEdad= (EditText) findViewById(R.id.txtEdad); txtDireccion= (EditText) findViewById(R.id.txtDireccion); txtEstadoCivil= (EditText) findViewById(R.id.txtEstadoCivil); txtSexo= (EditText) findViewById(R.id.txtSexo); database = FirebaseDatabase.getInstance(); refPersona = database.getReference("usuario"); refMensaje = database.getReference("txtSaludo"); btnTomar.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { llamarIntent(); } }); btnTerminar.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { //ENVIAR LA FOTO AL ALMACENAMIENTO DE FAREBASE FirebaseStorage storage = FirebaseStorage.getInstance(); StorageReference refPerfil = storage.getReferenceFromUrl("gs://tucitamedica-f835a.appspot.com").child("fotoPerfil"); imgFoto.setDrawingCacheEnabled(true); imgFoto.measure(View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED), View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED)); imgFoto.layout(0, 0, imgFoto.getMeasuredWidth(), imgFoto.getMeasuredHeight()); imgFoto.buildDrawingCache(); Bitmap bitmap = Bitmap.createBitmap(imgFoto.getDrawingCache()); ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); bitmap.compress(Bitmap.CompressFormat.JPEG, 100, outputStream); byte[] data = outputStream.toByteArray(); UploadTask uploadTask = refPerfil.child(mAuth.getCurrentUser().getUid()).putBytes(data); uploadTask.addOnFailureListener(new OnFailureListener() { @Override public void onFailure(@NonNull Exception exception) { } }).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() { @Override public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) { } }); // ENVIAR DATOS A LA BASE DE DATOS persona.setNombre(txtNombre.getText().toString().trim()); persona.setApellidos(txtApellido.getText().toString().trim()); persona.setCedula(txtCedula.getText().toString().trim()); persona.setCelular(txtCelular.getText().toString().trim()); persona.setFechaNacimiento(txtFechaNacimiento.getText().toString().trim()); persona.setDireccion(txtDireccion.getText().toString().trim()); persona.setSexo(txtSexo.getText().toString().trim()); persona.setEstadoCivil(txtEstadoCivil.getText().toString().trim()); persona.setEdad(txtEdad.getText().toString().trim()); persona.setEmail(txtEmail.getText().toString().trim()); refPersona.child(mAuth.getCurrentUser().getUid()).setValue(persona); Intent intent= new Intent(FormularioActivity.this, DrawerActivity.class); intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); startActivity(intent); finish(); Toast.makeText(FormularioActivity.this, "Registro completado EXITOSAMENTE :).", Toast.LENGTH_SHORT).show(); } }); btnBuscar.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { refPersona.child(mAuth.getCurrentUser().getUid()).addValueEventListener(new ValueEventListener() { @Override public void onDataChange(DataSnapshot dataSnapshot) { for (DataSnapshot hijos: dataSnapshot.getChildren()){ System.out.println(hijos.getKey()); System.out.println(hijos.getValue()); } persona= dataSnapshot.getValue(Persona.class); txtEmail.setText(persona.getEmail()); txtApellido.setText(persona.getApellidos()); txtNombre.setText(persona.getNombre()); txtCelular.setText(persona.getCelular()); txtFechaNacimiento.setText(persona.getFechaNacimiento()); txtCedula.setText(persona.getCedula()); txtEdad.setText(persona.getEdad()); txtSexo.setText(persona.getSexo()); txtDireccion.setText(persona.getDireccion()); txtEstadoCivil.setText(persona.getEstadoCivil()); } @Override public void onCancelled(DatabaseError databaseError) { System.out.println("[ERROR BASE DE DATOS]: "+databaseError.toString()); } }); } }); refMensaje.addValueEventListener(new ValueEventListener() { @Override public void onDataChange(DataSnapshot dataSnapshot) { // This method is called once with the initial value and again // whenever data at this location is updated String value = dataSnapshot.getValue(String.class); txtSaludo.setText(value); } @Override public void onCancelled(DatabaseError error) { // Failed to read value Log.w("", "Failed to read value.", error.toException()); } }); } @Override public void onStart() { super.onStart(); mAuth.addAuthStateListener(mAuthListener); } @Override public void onStop() { super.onStop(); if (mAuthListener != null) { // mAuth.removeAuthStateListener(mAuthListener); } } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) { Bundle extras = data.getExtras(); Bitmap imageBitmap = (Bitmap) extras.get("data"); imgFoto.setImageBitmap(imageBitmap); } } private void llamarIntent(){ Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); if (takePictureIntent.resolveActivity(getPackageManager()) != null) { startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE); } } } <file_sep>/app/src/main/java/com/example/diego/tucitamedica/RegistroActivity.java package com.example.diego.tucitamedica; import android.content.Intent; import android.graphics.Bitmap; import android.net.Uri; import android.support.annotation.NonNull; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.ImageView; import android.widget.ProgressBar; import android.widget.Toast; import com.example.diego.tucitamedica.model.Perfil; import com.google.android.gms.tasks.OnCompleteListener; import com.google.android.gms.tasks.OnFailureListener; import com.google.android.gms.tasks.OnSuccessListener; import com.google.android.gms.tasks.Task; import com.google.firebase.auth.AuthResult; import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.auth.FirebaseUser; import com.google.firebase.database.DataSnapshot; import com.google.firebase.database.DatabaseReference; import com.google.firebase.database.FirebaseDatabase; import com.example.diego.tucitamedica.model.Persona; import com.google.firebase.storage.FirebaseStorage; import com.google.firebase.storage.StorageReference; import com.google.firebase.storage.UploadTask; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.InputStream; public class RegistroActivity extends AppCompatActivity { EditText txtUsuarioR; EditText txtClaveR; Button btnRegistrarR; ProgressBar progressBar2; ImageView foto; private FirebaseAuth mAuth; private FirebaseAuth.AuthStateListener mAuthListener; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_registro); txtUsuarioR = (EditText) findViewById(R.id.txtUsuarioR); txtClaveR = (EditText) findViewById(R.id.txtClaveR); btnRegistrarR = (Button) findViewById(R.id.btnRegistrarR); progressBar2 = (ProgressBar) findViewById(R.id.progressBar2); mAuth = FirebaseAuth.getInstance(); mAuthListener = new FirebaseAuth.AuthStateListener() { @Override public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) { FirebaseUser user = firebaseAuth.getCurrentUser(); if (user != null) { // User is signed in Log.d("", "onAuthStateChanged:signed_in:" + user.getUid()); Intent intent= new Intent(RegistroActivity.this, FormularioActivity.class); intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); startActivity(intent); finish(); } else { // User is signed out Log.d("", "onAuthStateChanged:signed_out"); } // ... } }; btnRegistrarR.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { progressBar2.setVisibility(View.VISIBLE); mAuth.createUserWithEmailAndPassword(txtUsuarioR.getText().toString().trim(), txtClaveR.getText().toString().trim()) .addOnCompleteListener(RegistroActivity.this, new OnCompleteListener<AuthResult>() { @Override public void onComplete(@NonNull Task<AuthResult> task) { Log.d("", "createUserWithEmail:onComplete:" + task.isSuccessful()); // If sign in fails, display a message to the user. If sign in succeeds // the auth state listener will be notified and logic to handle the // signed in user can be handled in the listener. if (!task.isSuccessful()) { Toast.makeText(RegistroActivity.this, "A ocurrido un ERROR o el Usuario YA EXISTE.", Toast.LENGTH_SHORT).show(); progressBar2.setVisibility(View.INVISIBLE); } else { Toast.makeText(RegistroActivity.this, "Registro EXITOSO.", Toast.LENGTH_SHORT).show(); FirebaseDatabase database = FirebaseDatabase.getInstance(); DatabaseReference refUsuario = database.getReference("usuario"); Persona persona = new Persona(); persona.setEmail(mAuth.getCurrentUser().getEmail()); persona.setFechaNacimiento(""); persona.setNombre(""); persona.setCelular(""); persona.setApellidos(""); persona.setCedula(""); persona.setEdad(""); persona.setSexo(""); persona.setEstadoCivil(""); persona.setDireccion(""); refUsuario.child(mAuth.getCurrentUser().getUid()).setValue(persona); mAuth.getCurrentUser().sendEmailVerification().addOnCompleteListener(RegistroActivity.this, new OnCompleteListener<Void>() { @Override public void onComplete(@NonNull Task<Void> task) { if (task.isSuccessful()) { Toast.makeText(RegistroActivity.this, "Email de veirificación enviado :)", Toast.LENGTH_SHORT).show(); } else { Toast.makeText(RegistroActivity.this, "Email de veirificación No enviado :(", Toast.LENGTH_SHORT).show(); mAuth.signOut(); } } }); } // ... } }); } }); } @Override public void onStart() { super.onStart(); mAuth.addAuthStateListener(mAuthListener); } @Override public void onStop() { super.onStop(); if (mAuthListener != null) { //mAuth.removeAuthStateListener(mAuthListener); } } }
44c4eb2a32becbb0e83184c332a73239d1e4f690
[ "Java" ]
2
Java
diegolopez1797/TuCitaMedica
365e84acf798ccd199190b2499a65fa411e4a0f8
6f2535a84df699b803ef70f3160feeea55af9b59
refs/heads/master
<file_sep># Bank-Account This c++ program demonstrates the use of inheritance and .h and .cpp files. The program is created with "Bank Account" been the base class and then the other two accounts "MoneyMarketACC" and "CDAccount" inheriting from the base class. <file_sep>#pragma once #include "BankAccount.h" class CDAccount : public BankAccount { private: float Interest_rate; // member variables public: CDAccount(string AccHolder, double AccBal, float ir) : BankAccount(AccHolder, AccBal) // Inheritance { Interest_rate = ir; } int withdraw(double amount) // withdraw function { double penalty = 0.25 * Interest_rate * balance; double totalAmount_due = amount + penalty; if (totalAmount_due <= balance) { balance = balance - totalAmount_due; return 1; } else return 0; // if the above condition is not met then return 0 } }; <file_sep>#pragma once #include "BankAccount.h" class MoneyMarketACC : public BankAccount // Inheritance child class with parent class { private: int free_withdrawals; public: MoneyMarketACC(string AccHolder, double AccBal) : BankAccount(AccHolder, AccBal) // Inherting Maoney Market file and Bank Account file { free_withdrawals = 2; } int withdraw(double amount) // withdraw function { if (free_withdrawals == 0) { amount = amount + 1.5; } if (amount <= balance) { balance = balance - amount; if (free_withdrawals > 0) { free_withdrawals--; } return 1; } else return 0; } }; <file_sep>#include "CDAccount.h" <file_sep>#ifndef BANKACCOUNT_H // Header file parameters #define BANKACCOUNT_H #include <iostream> #include <string> using namespace std; class BankAccount { protected: // member variables string name; double balance; public: BankAccount(string AccountHolder, double AccountBalance) { name = AccountHolder; balance = AccountBalance; } virtual int withdraw(double amount) // polymorphism { if (amount <= balance) { balance = balance - amount; return 1; } else return 0; } void deposit(double amount) //deposit function { balance = balance + amount; } string getHolderName() // returns the name of the account holder { return name; } double getBalance() // returns the account balance { return balance; } }; #endif // Header file end <file_sep>#include "MoneyMarketACC.h" <file_sep>// <NAME> // A538P992 #include <iostream> using namespace std; #include <string> #include "BankAccount.h" // Include header files so main function can excecute using function from those files #include "CDAccount.h" #include "MoneyMarketACC.h" int main() { BankAccount NormalACC("Normal Account", 1000); // Initialize bank class account with values MoneyMarketACC MMAcc("Money MArket Account", 1000); // Initialize Money Market account with values CDAccount CDAcc("CD", 1000, 0.1); // Initialize CD account with values // Withdraw functions NormalACC.withdraw(100); // Calling withdraw function from Normal Account MMAcc.withdraw(100); // Calling withdraw function from Money Market class CDAcc.withdraw(100); // Calling withdraw function from CD accoount class cout << "After the first withdrawal the details are as follows: " << endl; cout << NormalACC.getBalance() << endl; cout << NormalACC.getHolderName() << endl; cout << MMAcc.getHolderName() << endl; cout << MMAcc.getBalance() << endl; cout << CDAcc.getHolderName() << endl; cout << CDAcc.getBalance() << endl; }
0f190bc23d718b7da45b2dd94f5d3f08c916f102
[ "Markdown", "C++" ]
7
Markdown
vimanga-x64/Bank-Account
bf6730f29e30cd59c6145e8aed5cb5f6b6fc1099
b6d6b8afaecd490f8f8ad2d811538c612ac89e2e
refs/heads/master
<repo_name>Vcharals/Node.js-MySQL<file_sep>/README.md # Node.js-MySQL Amazon-like storefront using MySQL and Node.js. It is comprised of two apps - one for customer orders and one for manager actions. Uses basic functions of persistant storage. All 4 CRUD database operations used - INSERT, SELECT, UPDATE and DELETE SQL queries. Used an exported constructor file to display the inventory in both bamazonCustomer.js and bamazonManager.js BamazonCustomer: displays a table with the inventory takes a customer's order computes the cost depletes the stock from the store's inventory BamazonManager - allows a manager to: View Products for Sale View Low Inventory Add to Inventory Add New Product Delete a Product Screen Shots Initial question https://github.com/Vcharals/Node.js-MySQL/blob/master/Images/Initial.png Requesting Quantity withing available amount https://github.com/Vcharals/Node.js-MySQL/blob/master/Images/Quantity%20within%20available.png Successfully ordered message https://github.com/Vcharals/Node.js-MySQL/blob/master/Images/Success.png Requesting an amount that exceeds available amount https://github.com/Vcharals/Node.js-MySQL/blob/master/Images/Quantity%20Exceeds%20available.png Insufficient message https://github.com/Vcharals/Node.js-MySQL/blob/master/Images/Insufficient.png <file_sep>/bamazon.sql DROP DATABASE IF EXISTS bamazon; CREATE DATABASE bamazon; USE bamazon; CREATE TABLE products( item_id INTEGER (11) AUTO_INCREMENT NOT NULL, product_name VARCHAR (75), department_name VARCHAR (50), price INTEGER (10), stock_quantity INTEGER (10), primary key (item_id) ); INSERT INTO products (product_name, department_name, price, stock_quantity) values ('Samsung Galaxy s10', 'Cell Phones', '865', '20'); INSERT INTO products (product_name, department_name, price, stock_quantity) values ('Hamilton Toaster Oven', 'Appliance', '39', '100'); INSERT INTO products (product_name, department_name, price, stock_quantity) values ('Clearasil Face Wash', 'Beauty', '10', '1000'); INSERT INTO products (product_name, department_name, price, stock_quantity) values ('One-a-day Vitamins', 'Health', '8', '1000'); INSERT INTO products (product_name, department_name, price, stock_quantity) values ('15 inch Macbook Pro', 'Computers', '1595', '254'); INSERT INTO products (product_name, department_name, price, stock_quantity) values ('Harmon Kardon Onyx Bluetooth Speaker', 'Home Audio', '200', '30'); INSERT INTO products (product_name, department_name, price, stock_quantity) values ('12 inch Alpine Type R Subwoofer', 'Car Audio', '200', '35'); INSERT INTO products (product_name, department_name, price, stock_quantity) values ('Samsung Washing Machine', 'Major Appliances', '399', '120'); INSERT INTO products (product_name, department_name, price, stock_quantity) values ('Canon Rebel T5i', 'Cameras', '595', '300'); INSERT INTO products (product_name, department_name, price, stock_quantity) values ('The Alchemist By Paulo Coelho', 'Books', '18', '1000'); SELECT * FROM products
8f3bcbfd2f83dc15fadb4caf477cd36a8dc47799
[ "Markdown", "SQL" ]
2
Markdown
Vcharals/Node.js-MySQL
055bbb09fb704c4b93742f6085e36a0cf092b083
1a1d63eaf666b19fc4f90410eb636d4a5e3a35eb
refs/heads/master
<file_sep>using System.Data.Entity; namespace webApp.Models { public class LibriaryDb : DbContext { public DbSet<Book> Books { get; set; } public DbSet<User> Users { get; set; } } }<file_sep>using System.Data; using System.Linq; using System.Web.Mvc; /* Имеется БД, состоящая из двух таблиц. Одна из таблиц ссылается на другую. * Необходимо написать приложение, которое позволяет просматривать и редактировать данные в таблицах. * Приложение должно состоять из 2 страниц. На первой странице находится таблица с возможностью выделения * произвольной строки, а также ссылка. По нажатию на ссылку открывается вторая страница, * которая содержит записи, ссылающиеся на выделенную запись на 1ой странице. */ using webApp.Models; namespace webApp.Controllers { public class LibriaryController : Controller { // // GET: /Home/ public ActionResult Index() { using (var db = new LibriaryDb()) { return View(db.Users.ToList()); } } public ActionResult User(int id = 0) { using (var db = new LibriaryDb()) { return View(db.Users.Find(id)); } } [HttpPost] public ActionResult User(User user) { using (var db = new LibriaryDb()) { var updateUser = db.Users.Find(user.Id); updateUser.Id = user.Id; db.Entry(updateUser).CurrentValues.SetValues(user); db.SaveChanges(); return RedirectToAction("Index"); } } [HttpPost] public ActionResult CreateUser(User user) { using (var db = new LibriaryDb()) { db.Users.Add(user); db.SaveChanges(); return RedirectToAction("Index"); } } } }<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using webApp.Models; namespace webApp.Controllers { public class BookController : Controller { public ActionResult Index(int userId) { using (var db = new LibriaryDb()) { return View(db.Users.Find(userId).Books.ToList()); } } public ActionResult Book(int id) { using (var db = new LibriaryDb()) { return View(db.Books.Find(id)); } } [HttpPost] public ActionResult CreateBook(Book book, int userId) { using (var db = new LibriaryDb()) { db.Users.Find(userId).Books.Add(book); db.SaveChanges(); return RedirectToAction("Index"); } } } }
d26f3e604b8617d2e99f33dea43e2be7c301d725
[ "C#" ]
3
C#
suleinvo/My-Lab
dec8699a0c006b305198f4dff923eda6a9de4056
2be7d71e911bf34ca7c13f956f777a8fb7a14d81
refs/heads/master
<repo_name>SarawrSmiles/MailRunner<file_sep>/MailRunner/Assets/CameraMove.cs using UnityEngine; using System.Collections; public class CameraMove : MonoBehaviour { // Use this for initialization void Start () { } public float speed = 0.1F; public GameObject emeter; // Update is called once per frame void Update () { emeter = GameObject.Find ("EnergyMeter"); if (emeter.transform.localScale.y <= 0.001) { speed = 0.1F; } else { speed = emeter.transform.localScale.y * 4F; } if (Input.GetKey(KeyCode.W)) { transform.localPosition += new Vector3(0, 0, 1F * speed); } if (Input.GetKey (KeyCode.S)) { transform.localPosition += new Vector3(0, 0, -1F * speed ); } if (Input.GetKey(KeyCode.A)) { transform.localPosition += new Vector3(-1F * speed, 0, 0); } if (Input.GetKey (KeyCode.D)) { transform.localPosition += new Vector3(1F * speed, 0, 0); } } } <file_sep>/README.md MazeRunner ========== 179 Project <NAME> <EMAIL> <NAME> <EMAIL> <NAME>as <EMAIL> <NAME> <EMAIL> <file_sep>/MailRunner/Assets/GrowMeter.cs using UnityEngine; using System.Collections; public class GrowMeter : MonoBehaviour { // Use this for initialization void Start () { } // Update is called once per frame void Update () { if (Input.GetKey(KeyCode.G)) { transform.localScale += new Vector3 (0, .001F, 0); transform.localPosition += new Vector3 (0.001F, 0, 0); } } }
b9387773f9004cfebbded36a02acf88ad672d765
[ "Markdown", "C#" ]
3
C#
SarawrSmiles/MailRunner
c86b53e23f388fb4a6f8e4aaf4d4306d2f17b256
ff99945fb5909833a28e0f41e71815bedef64f46
refs/heads/master
<repo_name>dhruvaism/Corona-Vs-India<file_sep>/app/src/main/java/com/sarkar/dhruv/coronacases/adapters/CountryAdapter.java package com.sarkar.dhruv.coronacases.adapters; import android.content.Context; import android.os.AsyncTask; import android.os.Build; import android.util.DisplayMetrics; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.LinearLayout; import android.widget.ProgressBar; import android.widget.TextView; import com.sarkar.dhruv.coronacases.MainActivity; import com.sarkar.dhruv.coronacases.R; import com.sarkar.dhruv.coronacases.fragments.India; import com.sarkar.dhruv.coronacases.models.CountryModel; import com.sarkar.dhruv.coronacases.models.StateModel; import java.math.BigDecimal; import java.text.DecimalFormat; import java.util.ArrayList; import androidx.annotation.NonNull; import androidx.annotation.RequiresApi; import androidx.appcompat.widget.LinearLayoutCompat; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import static com.sarkar.dhruv.coronacases.MainActivity.formatter; public class CountryAdapter extends RecyclerView.Adapter<CountryAdapter.CountryVH> { private ArrayList<CountryModel> countryModels; private Context context; public CountryAdapter(Context context, ArrayList<CountryModel> countryModels) { this.context = context; this.countryModels = countryModels; } @NonNull @Override public CountryVH onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.country_wise_cases_item,parent,false); return new CountryVH(view); } @RequiresApi(api = Build.VERSION_CODES.M) @Override public void onBindViewHolder(@NonNull final CountryVH holder, final int position) { holder.countryName.setText(countryModels.get(position).getCountry()); holder.confNo.setText(formatter(countryModels.get(position).getTotalCnf())); holder.confNewNo.setText(formatter(countryModels.get(position).getNewConfirmed())); holder.recNo.setText(formatter(countryModels.get(position).getTotalRecov())); holder.recNewNo.setText(formatter(countryModels.get(position).getTotalRecov())); holder.deathsNo.setText(formatter(countryModels.get(position).getTotalDths())); holder.deathsNewNo.setText(formatter(countryModels.get(position).getNewDeaths())); DisplayMetrics displayMetrics = new DisplayMetrics(); MainActivity.activity.getWindowManager().getDefaultDisplay().getMetrics(displayMetrics); float size = displayMetrics.widthPixels; ViewGroup.LayoutParams lp_state_name = holder.state.getLayoutParams(); ViewGroup.LayoutParams lp_conf_case = holder.conf.getLayoutParams(); ViewGroup.LayoutParams lp_recov_case = holder.recov.getLayoutParams(); ViewGroup.LayoutParams lp_death_case = holder.death.getLayoutParams(); lp_state_name.width=(int)size*2/5; lp_conf_case.width = (int)size*1/5; lp_recov_case.width = (int)size*1/5; lp_death_case.width = (int)size*1/5; if(position%2!=0) { // holder.itemView.setBackgroundTintList(ColorStateList.valueOf(context.getColor(R.color.alternate_color))); holder.itemView.setBackgroundColor(context.getColor(R.color.alternate_color)); } } @Override public int getItemCount() { return countryModels==null?0:countryModels.size(); } public static class CountryVH extends RecyclerView.ViewHolder{ public TextView countryName,confNo,confNewNo,recNo,recNewNo,deathsNo,deathsNewNo; public LinearLayoutCompat state,conf,active,recov,death; public CountryVH(@NonNull View itemView) { super(itemView); countryName = itemView.findViewById(R.id.country_name); confNo = itemView.findViewById(R.id.confirmed_no); confNewNo = itemView.findViewById(R.id.confirmed_new_no); recNo = itemView.findViewById(R.id.recovered_no); recNewNo = itemView.findViewById(R.id.recovered_new_no); deathsNo = itemView.findViewById(R.id.deaths_no); deathsNewNo = itemView.findViewById(R.id.deaths_new_no); state = itemView.findViewById(R.id.state_name_ll); conf = itemView.findViewById(R.id.cc_ll); recov = itemView.findViewById(R.id.rc_ll); death = itemView.findViewById(R.id.dc_ll); } } } <file_sep>/settings.gradle include ':app' rootProject.name='Corona Cases' <file_sep>/app/src/main/java/com/sarkar/dhruv/coronacases/handlers/HttpRequest.java package com.sarkar.dhruv.coronacases.handlers; import android.util.Log; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.ProtocolException; import java.net.URL; import static com.sarkar.dhruv.coronacases.constants.Constant.COUNTRY_WISE; import static com.sarkar.dhruv.coronacases.constants.Constant.DISTRICTWISE_DATA; import static com.sarkar.dhruv.coronacases.constants.Constant.STATEWISE; import static com.sarkar.dhruv.coronacases.constants.Constant.STATEWISE_DATA; import static com.sarkar.dhruv.coronacases.constants.Constant.ZONES_DATA; public class HttpRequest { private static final String TAG = HttpRequest.class.getSimpleName(); private static HttpRequest httpRequest = null; public static HttpRequest getInstance(){ if (httpRequest == null){ httpRequest = new HttpRequest(); } return httpRequest; } private String execute(String urlStr){ final String REQUEST_METHOD = "GET"; final int READ_TIMEOUT = 15000; final int CONNECTION_TIMEOUT = 15000; String result = ""; String inputLine; HttpURLConnection connection = null; try { URL url = new URL(urlStr); connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod(REQUEST_METHOD); connection.setConnectTimeout(CONNECTION_TIMEOUT); connection.setReadTimeout(READ_TIMEOUT); connection.connect(); InputStreamReader streamReader = new InputStreamReader(connection.getInputStream()); BufferedReader reader = new BufferedReader(streamReader); StringBuilder stringBuilder = new StringBuilder(); while ((inputLine = reader.readLine()) != null){ stringBuilder.append(inputLine); } reader.close(); streamReader.close(); result = stringBuilder.toString(); } catch (MalformedURLException e) { Log.e(TAG, "MalformedURLException: " + e.getMessage()); } catch (ProtocolException e) { Log.e(TAG, "ProtocolException: " + e.getMessage()); } catch (IOException e) { Log.e(TAG, "IOException: " + e.getMessage()); } catch (Exception e) { Log.e(TAG, "Exception: " + e.getMessage()); }finally { if (connection != null){ connection.disconnect(); } } return result; } private JSONArray convertToJSONArray(String str){ JSONArray jsonArray = null; if(!str.isEmpty()){ try { jsonArray = new JSONArray(str); } catch (JSONException e) { e.printStackTrace(); } } return jsonArray; } private JSONObject convertToJSONObject(String str) { JSONObject jsonObject = null; if(!str.isEmpty()) { try { jsonObject = new JSONObject(str); } catch (JSONException e) { e.printStackTrace(); } } return jsonObject; } public JSONObject getStateWise() { String result = execute(STATEWISE_DATA); System.out.println(result); return convertToJSONObject(result); } public JSONObject getDistrictWise() { String result = execute(DISTRICTWISE_DATA); System.out.println(result); return convertToJSONObject(result); } public JSONObject getZones() { String result = execute(ZONES_DATA); System.out.println(result); return convertToJSONObject(result); } public JSONObject getCountryWise() { String result = execute(COUNTRY_WISE); System.out.println(result); return convertToJSONObject(result); } }
b8befca64016ad717b422d8f94dc7dfa8d601129
[ "Java", "Gradle" ]
3
Java
dhruvaism/Corona-Vs-India
95bf759794821beb5558af7f335ba71a9a58b4ad
43bf58afd7562d3cff21df11fb7e5e3feac01a29
refs/heads/master
<repo_name>sagishchori/TestCoronaApp<file_sep>/app/src/main/java/com/sagish/testcoronaapp/ui/fragments/nearBy/NearByViewModel.kt package com.sagish.testcoronaapp.ui.fragments.nearBy import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import androidx.lifecycle.ViewModel class NearByViewModel : ViewModel() { private var isBluetoothEnabled = MutableLiveData(false) private var isScanning = MutableLiveData(false) private var hasBlueTooth: Boolean = false fun setHasBluetooth(hasBlueTooth: Boolean) { this.hasBlueTooth = hasBlueTooth } fun setBluetoothEnabled(enabled: Boolean) { isBluetoothEnabled.postValue(enabled) } fun hasBluetooth() : Boolean{ return hasBlueTooth } fun isBluetoothEnabled() : LiveData<Boolean> { return isBluetoothEnabled } fun setIsScanning(isScanning : Boolean) { this.isScanning.value = isScanning } fun isScanning() : LiveData<Boolean> { return isScanning } }<file_sep>/app/src/main/java/com/sagish/testcoronaapp/ui/views/DetailsListItemView.kt package com.sagish.testcoronaapp.ui.views import androidx.recyclerview.widget.RecyclerView import com.sagish.testcoronaapp.databinding.DetailsListItemViewBinding import com.sagish.testcoronaapp.ui.models.CoronaDetailsByCountryItem class DetailsListItemView(private val binding: DetailsListItemViewBinding): RecyclerView.ViewHolder(binding.root) { fun bind(item: /*CoronaDetailsByCountryItem*/HashMap<String, Int>, date: String) { binding.date = date.split("T")[0] val details = Details(item[CoronaDetailsByCountryItem.CoronaStatus.Confirmed.getValue()]!!, item[CoronaDetailsByCountryItem.CoronaStatus.Recovered.getValue()]!!, item.get(CoronaDetailsByCountryItem.CoronaStatus.Deaths.getValue())!!) binding.details = details } class Details(val confirmed : Int, val recovered : Int, val deaths : Int) }<file_sep>/app/src/main/java/com/sagish/testcoronaapp/ui/models/CoronaDetailsByCountryItemsList.kt package com.sagish.testcoronaapp.ui.models class CoronaDetailsByCountryItemsList : ArrayList<CoronaDetailsByCountryItem>()<file_sep>/app/src/main/java/com/sagish/testcoronaapp/api/services/FetchCoronaDetailsForCountry.kt package com.sagish.testcoronaapp.api.services import com.sagish.testcoronaapp.ui.models.CoronaDetailsByCountryItemsList import retrofit2.http.GET import retrofit2.http.Path import retrofit2.http.Query interface FetchCoronaDetailsForCountry { @GET("country/{country}/status/{status}?") suspend fun getCoronaDetailsForCountryByTypeAndDate(@Path("country") country : String, @Path("status") status : String, @Query("from") fromDate : String, @Query("to") toDate : String) : CoronaDetailsByCountryItemsList? }<file_sep>/app/src/main/java/com/sagish/testcoronaapp/api/RetrofitClient.kt package com.sagish.testcoronaapp.api import android.util.Log import okhttp3.HttpUrl import okhttp3.OkHttpClient import okhttp3.logging.HttpLoggingInterceptor import retrofit2.Retrofit import retrofit2.converter.gson.GsonConverterFactory object RetrofitClient { private const val BASE_URL : String = "https://api.covid19api.com/" // Is used to log the API calls private val logger = HttpLoggingInterceptor.Logger { Log.d("API", it) } // Is used to intercept the API calls. I set the intercepting level to // HttpLoggingInterceptor.Level.BODY in order to get all API call // data (calls, responses, headers and bodies) private val interceptor = HttpLoggingInterceptor(logger) .setLevel(HttpLoggingInterceptor.Level.BODY) // Create a HttpClient with pre-defined interceptor to be used in my // Retrofit client private val client: OkHttpClient = OkHttpClient.Builder() .addInterceptor(interceptor) .build() private val retrofit: Retrofit? = Retrofit.Builder() .client(client) .addConverterFactory(GsonConverterFactory.create()) .baseUrl(HttpUrl.parse(BASE_URL)!!) .build() fun<T> buildService(service : Class<T>) : T? { return retrofit?.create(service) } }<file_sep>/app/src/main/java/com/sagish/testcoronaapp/MainActivity.kt package com.sagish.testcoronaapp import android.Manifest import android.bluetooth.BluetoothAdapter import android.content.BroadcastReceiver import android.content.Context import android.content.Intent import android.content.IntentFilter import android.content.pm.PackageManager import android.location.Geocoder import android.location.Location import android.location.LocationManager import android.os.Bundle import android.os.Looper import androidx.activity.viewModels import androidx.appcompat.app.AppCompatActivity import androidx.core.app.ActivityCompat import androidx.navigation.findNavController import androidx.navigation.ui.AppBarConfiguration import androidx.navigation.ui.setupActionBarWithNavController import androidx.navigation.ui.setupWithNavController import com.google.android.gms.location.* import com.google.android.material.bottomnavigation.BottomNavigationView import com.sagish.testcoronaapp.ui.fragments.byCountry.GetByCountryViewModel import com.sagish.testcoronaapp.ui.fragments.myCountry.GetByMyCountryViewModel import com.sagish.testcoronaapp.ui.fragments.nearBy.NearByViewModel import com.sagish.testcoronaapp.ui.helpers.AlertDialogHelper import java.util.* class MainActivity : AppCompatActivity() { private lateinit var fusedLocationProviderClient: FusedLocationProviderClient private var currentLocation: Location? = null private val bluetoothAdapter: BluetoothAdapter? = BluetoothAdapter.getDefaultAdapter() private val providerReceiver = object : BroadcastReceiver() { override fun onReceive(p0: Context?, p1: Intent?) { // GPS may be enabled by the user if (LocationManager.PROVIDERS_CHANGED_ACTION == p1!!.action) { } } } private val bluetoothReceiver = object : BroadcastReceiver() { override fun onReceive(p0: Context?, p1: Intent?) { // Bluetooth may be enabled by the user if (BluetoothAdapter.ACTION_STATE_CHANGED == p1!!.action) { if (p1.hasExtra(BluetoothAdapter.EXTRA_STATE)) { val state = p1.getIntExtra(BluetoothAdapter.EXTRA_STATE, -1) if (state == BluetoothAdapter.STATE_ON || state == BluetoothAdapter.STATE_TURNING_ON) { nearByViewModel.setBluetoothEnabled(true) } else if (state == BluetoothAdapter.STATE_OFF || state == BluetoothAdapter.STATE_TURNING_OFF){ nearByViewModel.setBluetoothEnabled(false) } } } } } private val locationCallback = object : LocationCallback() { override fun onLocationResult(p0: LocationResult?) { super.onLocationResult(p0) fusedLocationProviderClient.removeLocationUpdates(this) } } private val byCountryViewModel: GetByCountryViewModel by viewModels() private val byMyCountryViewModel: GetByMyCountryViewModel by viewModels() private val nearByViewModel: NearByViewModel by viewModels() override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) val navView: BottomNavigationView = findViewById(R.id.nav_view) val navController = findNavController(R.id.nav_host_fragment) // Passing each menu ID as a set of Ids because each // menu should be considered as top level destinations. val appBarConfiguration = AppBarConfiguration(setOf( R.id.by_country, R.id.my_country, R.id.near_by)) setupActionBarWithNavController(navController, appBarConfiguration) navView.setupWithNavController(navController) setUpLocationPermissionsAndManagement() setUpBluetoothPermissionsAndManagement() } override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { super.onActivityResult(requestCode, resultCode, data) when(requestCode) { REQUEST_ENABLE_BT -> { if (resultCode == RESULT_OK) { nearByViewModel.setBluetoothEnabled(true) } else { nearByViewModel.setBluetoothEnabled(false) } } } } private fun setUpBluetoothPermissionsAndManagement() { // First' we check if the device has Bluetooth or support it if (bluetoothAdapter == null) { nearByViewModel.setHasBluetooth(false) return } else { nearByViewModel.setHasBluetooth(true) } // Next we need to ensure that Bluetooth is enabled if (!bluetoothAdapter.isEnabled) { val enableIntent = Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE) startActivityForResult(enableIntent, REQUEST_ENABLE_BT) } else { nearByViewModel.setBluetoothEnabled(true) } } private fun setUpLocationPermissionsAndManagement() { fusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(this) val locationManager = getSystemService(Context.LOCATION_SERVICE) as LocationManager // Check if GPS is enabled val hasGPS = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER) // GPS is enabled if (hasGPS) { // Check for location permissions if (PackageManager.PERMISSION_GRANTED == ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) && PackageManager.PERMISSION_GRANTED == ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION)) { fusedLocationProviderClient.lastLocation.addOnSuccessListener { if (it != null) { currentLocation = it val geoCoder = Geocoder(this, Locale.ENGLISH) val address = geoCoder.getFromLocation( currentLocation!!.latitude, currentLocation!!.longitude, 1 ) byMyCountryViewModel.setCurrentCountry(address[0].countryName) } else { val locationRequest = LocationRequest.create()?.apply { interval = 1000 fastestInterval = 5000 priority = LocationRequest.PRIORITY_HIGH_ACCURACY } fusedLocationProviderClient.requestLocationUpdates(locationRequest, locationCallback, Looper.getMainLooper()) } } } else { // If no location permission is enabled request one requestForegroundPermissions() } } // GPS is disabled, notify to user to enabled it else { AlertDialogHelper.show(this, R.string.gps_disabled, R.string.ok) } } override fun onStart() { super.onStart() registerReceiver(providerReceiver, IntentFilter(LocationManager.PROVIDERS_CHANGED_ACTION)) registerReceiver(bluetoothReceiver, IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED)) } override fun onStop() { super.onStop() unregisterReceiver(providerReceiver) unregisterReceiver(bluetoothReceiver) } private fun requestForegroundPermissions() { ActivityCompat.requestPermissions( this, arrayOf(Manifest.permission.ACCESS_FINE_LOCATION), REQUEST_LOCATION_PERMISSIONS_REQUEST_CODE ) } override fun onRequestPermissionsResult( requestCode: Int, permissions: Array<out String>, grantResults: IntArray ) { when(requestCode) { REQUEST_LOCATION_PERMISSIONS_REQUEST_CODE -> { // If no permission granted if(grantResults.isEmpty()) { AlertDialogHelper.show(this, R.string.must_enable_gps, R.string.ok) } // If permission granted else if(grantResults[0] == PackageManager.PERMISSION_GRANTED) { } } } } companion object { const val REQUEST_LOCATION_PERMISSIONS_REQUEST_CODE = 12 const val REQUEST_ENABLE_BT = 13 } }<file_sep>/app/src/main/java/com/sagish/testcoronaapp/ui/helpers/AlertDialogHelper.kt package com.sagish.testcoronaapp.ui.helpers import android.content.Context import android.content.DialogInterface import androidx.appcompat.app.AlertDialog class AlertDialogHelper { companion object { /** * A method to set an AlertDialog with control over the clicked positive button */ fun show(context : Context, message : Int, positiveText : Int, positiveButtonClickListener : DialogInterface.OnClickListener) { getDialog(context) .setMessage(message) .setPositiveButton(positiveText, positiveButtonClickListener) .show() } fun show(context : Context, message : String, positiveText : Int, positiveButtonClickListener : DialogInterface.OnClickListener) { getDialog(context) .setMessage(message) .setPositiveButton(positiveText, positiveButtonClickListener) .show() } /** * A method to set an AlertDialog without control over the clicked positive button */ fun show(context : Context, message : Int, positiveText : Int) { show(context, message, positiveText, object : DialogInterface.OnClickListener { override fun onClick(p0: DialogInterface?, p1: Int) { // Do nothing } }) } fun show(context : Context, message : String, positiveText : Int) { show(context, message, positiveText, object : DialogInterface.OnClickListener { override fun onClick(p0: DialogInterface?, p1: Int) { // Do nothing } }) } private fun getDialog(context: Context): AlertDialog.Builder { return AlertDialog.Builder(context) } } }<file_sep>/app/src/main/java/com/sagish/testcoronaapp/ui/fragments/myCountry/GetByMyCountryViewModel.kt package com.sagish.testcoronaapp.ui.fragments.myCountry import com.sagish.testcoronaapp.ui.fragments.byCountry.GetByCountryViewModel class GetByMyCountryViewModel : GetByCountryViewModel() { fun setCurrentCountry(currentCountry : String) { country.value = currentCountry } fun getCountry(): String? { return country.value } }<file_sep>/app/src/main/java/com/sagish/testcoronaapp/ui/adapters/DetailsListAdapter.kt package com.sagish.testcoronaapp.ui.adapters import android.view.LayoutInflater import android.view.ViewGroup import androidx.recyclerview.widget.RecyclerView import com.sagish.testcoronaapp.databinding.DetailsListItemViewBinding import com.sagish.testcoronaapp.ui.views.DetailsListItemView class DetailsListAdapter : RecyclerView.Adapter<DetailsListItemView>() { private var itemList = LinkedHashMap<String, HashMap<String, Int>>() override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): DetailsListItemView { val binding = DetailsListItemViewBinding.inflate(LayoutInflater.from(parent.context), parent, false) return DetailsListItemView(binding) } override fun onBindViewHolder(holder: DetailsListItemView, position: Int) { val key = itemList.keys.elementAt(position) val listItem = itemList[key] holder.bind(listItem!!, key) } override fun getItemCount(): Int { return itemList.size } fun setData(itemList: LinkedHashMap<String, HashMap<String, Int>>) { this.itemList = itemList notifyDataSetChanged() } }<file_sep>/app/src/main/java/com/sagish/testcoronaapp/ui/models/CoronaDetailsByCountryItem.kt package com.sagish.testcoronaapp.ui.models data class CoronaDetailsByCountryItem( val Cases: Int, val City: String, val CityCode: String, val Country: String, val CountryCode: String, val Date: String, val Lat: String, val Lon: String, val Province: String, val Status: String ) { var casesByType = HashMap<CoronaStatus, Int>() enum class CoronaStatus(private val status: String) { Confirmed("confirmed"), Recovered("recovered"), Deaths("deaths"); fun getValue() : String { return this.status } } }<file_sep>/app/src/main/java/com/sagish/testcoronaapp/ui/fragments/byCountry/GetByCountryViewModel.kt package com.sagish.testcoronaapp.ui.fragments.byCountry import android.content.Context import android.view.View import android.widget.AdapterView import androidx.appcompat.widget.AppCompatTextView import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import androidx.lifecycle.ViewModel import com.sagish.testcoronaapp.R import com.sagish.testcoronaapp.api.repositories.CountryDetailsRepository import com.sagish.testcoronaapp.ui.models.CoronaDetailsByCountry import com.sagish.testcoronaapp.ui.models.CoronaDetailsByCountryItem import kotlinx.coroutines.* import okhttp3.HttpUrl import retrofit2.HttpException import retrofit2.http.HTTP import java.net.HttpURLConnection import java.net.UnknownHostException import java.text.ParseException import java.text.SimpleDateFormat import java.util.* import kotlin.collections.ArrayList import kotlin.collections.HashMap open class GetByCountryViewModel : ViewModel(), AdapterView.OnItemSelectedListener { protected open val toDate: MutableLiveData<String> by lazy { MutableLiveData<String>("") } protected open val fromDate: MutableLiveData<String> by lazy { MutableLiveData<String>("") } protected open val coronaDetailsByCountry = MutableLiveData<CoronaDetailsByCountry>() protected open val error = MutableLiveData<String>() protected open val country = MutableLiveData<String>() protected open val repo : CountryDetailsRepository = CountryDetailsRepository() override fun onItemSelected(p0: AdapterView<*>?, p1: View?, p2: Int, p3: Long) { if (p2 == 0) { country.value = "" } else { country.value = (p1 as AppCompatTextView).text.toString() tryToFetchData() } } override fun onNothingSelected(p0: AdapterView<*>?) { } /** * Try to fetch the data from web. */ protected open fun tryToFetchData() { if (country.value!!.isNotEmpty() and fromDate.value!!.isNotEmpty() and toDate.value!!.isNotEmpty()) { val deferredList = ArrayList<Deferred<*>>() val errorHandler = CoroutineExceptionHandler { _, error -> when (error) { is UnknownHostException -> { this.error.postValue(error.message) } is HttpException -> { if (error.code() == HttpURLConnection.HTTP_NOT_FOUND) { this.error.postValue("Not found") } } } } val errorHandlingScope = CoroutineScope(errorHandler) errorHandlingScope.launch(Dispatchers.IO) { deferredList.add(async { repo.fetchCoronaDetailsForCountryAndDates(country.value!!, fromDate.value!!, toDate.value!!, CoronaDetailsByCountryItem.CoronaStatus.Confirmed) }) deferredList.add(async { repo.fetchCoronaDetailsForCountryAndDates(country.value!!, fromDate.value!!, toDate.value!!, CoronaDetailsByCountryItem.CoronaStatus.Recovered) }) deferredList.add(async { repo.fetchCoronaDetailsForCountryAndDates(country.value!!, fromDate.value!!, toDate.value!!, CoronaDetailsByCountryItem.CoronaStatus.Deaths) }) try { deferredList.awaitAll() processData(deferredList) } catch (e : CancellationException) { throw e } } } } protected open fun processData(deferredList: ArrayList<Deferred<*>>) { val item = CoronaDetailsByCountry(country.value!!) deferredList.forEach { deferred -> val list = deferred.getCompleted() as ArrayList<CoronaDetailsByCountryItem> list.forEach { val date = it.Date var map : HashMap<String, Int> if (item.casesByTypeAndDate[date] != null) { map = item.casesByTypeAndDate[date]!! } else { map = HashMap() } map[it.Status] = it.Cases item.casesByTypeAndDate[date] = map } } coronaDetailsByCountry.postValue(item) } /** * Set the start date of the search. */ fun setFromDate(date: String, context: Context) { fromDate.value = date if (validateBeforeOrAfter(date, toDate.value!!) || toDate.value!!.isEmpty()) { tryToFetchData() } else { toDate.value = date error.value = context.resources.getString(R.string.date_after_error_message) } } /** * Return the start date of the search as LiveData to be able to observe the changes and act accordingly. */ fun getFromDate() : LiveData<String> { return fromDate } /** * Set the end date of the search. */ fun setToDate(date: String, context : Context) { toDate.value = date if (validateBeforeOrAfter(fromDate.value ?: "", date) || fromDate.value!!.isEmpty()) { tryToFetchData() } else { fromDate.value = date error.value = context.resources.getString(R.string.date_before_error_message) } } /** * Return the end date of the search as LiveData to be able to observe the changes and act accordingly. */ fun getToDate() : LiveData<String> { return toDate } /** * Validate the start and end dates of the search. * If the start date is after the end date or the end date is before the start date an * error will be shown to user accordingly. */ private fun validateBeforeOrAfter(fromDate: String, toDate: String) : Boolean { var date1 = Date() var date2 = Date() val formatter = SimpleDateFormat("yyyy-MM-dd") try { date1 = formatter.parse(fromDate) date2 = formatter.parse(toDate) } catch (e: ParseException) { } return date1.before(date2) } /** * Get the error as a LiveData to update the view accordingly. */ fun getErrorMessage() : LiveData<String> { return error } /** * Get the Corona details of the requested country as a LiveData to update the view accordingly. */ fun getCoronaDetailsByCountry() : LiveData<CoronaDetailsByCountry> { return coronaDetailsByCountry } }<file_sep>/app/src/main/java/com/sagish/testcoronaapp/api/repositories/CountryDetailsRepository.kt package com.sagish.testcoronaapp.api.repositories import com.sagish.testcoronaapp.api.RetrofitClient import com.sagish.testcoronaapp.api.services.FetchCoronaDetailsForCountry import com.sagish.testcoronaapp.ui.models.CoronaDetailsByCountryItemsList import com.sagish.testcoronaapp.ui.models.CoronaDetailsByCountryItem import kotlin.Exception class CountryDetailsRepository { suspend fun fetchCoronaDetailsForCountryAndDates(country: String, fromDate: String, toDate: String, status: CoronaDetailsByCountryItem.CoronaStatus) : CoronaDetailsByCountryItemsList? { val service = RetrofitClient.buildService(FetchCoronaDetailsForCountry::class.java) return try { service!!.getCoronaDetailsForCountryByTypeAndDate( country, status.name.toLowerCase(), fromDate, toDate ) } catch (e : Exception) { throw e } } }<file_sep>/app/src/main/java/com/sagish/testcoronaapp/ui/fragments/byCountry/GetByCountryFragment.kt package com.sagish.testcoronaapp.ui.fragments.byCountry import android.app.DatePickerDialog import android.os.Bundle import android.view.LayoutInflater import android.view.MotionEvent import android.view.View import android.view.ViewGroup import android.widget.DatePicker import androidx.databinding.DataBindingUtil import androidx.fragment.app.Fragment import androidx.fragment.app.activityViewModels import androidx.lifecycle.Observer import androidx.recyclerview.widget.DividerItemDecoration import androidx.recyclerview.widget.LinearLayoutManager import com.sagish.testcoronaapp.R import com.sagish.testcoronaapp.databinding.DetailsFragmentBinding import com.sagish.testcoronaapp.ui.adapters.DetailsListAdapter import com.sagish.testcoronaapp.ui.helpers.AlertDialogHelper import com.sagish.testcoronaapp.ui.models.CoronaDetailsByCountry import java.util.* open class GetByCountryFragment : Fragment() { private val viewModel: GetByCountryViewModel by activityViewModels() protected lateinit var binding: DetailsFragmentBinding protected lateinit var adapter: DetailsListAdapter private val calendar : Calendar by lazy { Calendar.getInstance() } override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { binding = DataBindingUtil.inflate(inflater, R.layout.details_fragment, container, false) return binding.root } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) setUpRecycler() setUpSpinner(viewModel) setUpDateViewsClickListeners(viewModel) setUpObservers(viewModel) } protected open fun setUpDateViewsClickListeners(viewModel: GetByCountryViewModel) { binding.fromText.setOnTouchListener(object : View.OnTouchListener { override fun onTouch(p0: View?, p1: MotionEvent?): Boolean { if (MotionEvent.ACTION_UP == p1!!.action) { val year = calendar.get(Calendar.YEAR) val month = calendar.get(Calendar.MONTH) val day = calendar.get(Calendar.DAY_OF_MONTH) val datePicker = DatePickerDialog( requireContext(), object : DatePickerDialog.OnDateSetListener { override fun onDateSet(p0: DatePicker?, p1: Int, p2: Int, p3: Int) { val month = p2.plus(1) var day = p3.toString() if (p3 < 10) day = "0$p3" viewModel.setFromDate("$p1-$month-$day", requireContext()) } }, year, month, day ) datePicker.show() } return true } }) binding.toText.setOnTouchListener(object : View.OnTouchListener { override fun onTouch(p0: View?, p1: MotionEvent?): Boolean { if (MotionEvent.ACTION_UP == p1!!.action) { val year = calendar.get(Calendar.YEAR) val month = calendar.get(Calendar.MONTH) val day = calendar.get(Calendar.DAY_OF_MONTH) val datePicker = DatePickerDialog(requireContext(), object : DatePickerDialog.OnDateSetListener { override fun onDateSet(p0: DatePicker?, p1: Int, p2: Int, p3: Int) { val month = p2.plus(1) var day = p3.toString() if (p3 < 10) day = "0$p3" viewModel.setToDate("$p1-$month-$day", requireContext()) } }, year, month, day) datePicker.show() } return true } }) } protected open fun setUpSpinner(viewModel: GetByCountryViewModel) { binding.countryChooserSpinner.onItemSelectedListener = viewModel } protected open fun setUpObservers(viewModel: GetByCountryViewModel) { viewModel.getFromDate().observe(viewLifecycleOwner, object : Observer<String> { override fun onChanged(t: String?) { binding.fromText.setText(t) } }) viewModel.getToDate().observe(viewLifecycleOwner, object : Observer<String> { override fun onChanged(t: String?) { binding.toText.setText(t) } }) viewModel.getErrorMessage().observe(viewLifecycleOwner, object : Observer<String> { override fun onChanged(t: String?) { AlertDialogHelper.show(requireContext(), t!!, R.string.ok) } }) viewModel.getCoronaDetailsByCountry().observe(viewLifecycleOwner, object : Observer<CoronaDetailsByCountry> { override fun onChanged(t: CoronaDetailsByCountry?) { adapter.setData(t!!.casesByTypeAndDate) } }) } /** * Set up the initial state of recyclerview. */ protected open fun setUpRecycler() { val lm = LinearLayoutManager(requireContext(), LinearLayoutManager.VERTICAL, false) binding.recycler.layoutManager = lm val itemDecoration = DividerItemDecoration(requireContext(), lm.orientation) itemDecoration.setDrawable(resources.getDrawable(R.drawable.divider, null)) binding.recycler.addItemDecoration(itemDecoration) adapter = DetailsListAdapter() binding.recycler.adapter = adapter } }<file_sep>/app/src/main/java/com/sagish/testcoronaapp/ui/models/CoronaDetailsByCountry.kt package com.sagish.testcoronaapp.ui.models class CoronaDetailsByCountry(val country: String) { var casesByTypeAndDate = LinkedHashMap<String, HashMap<String, Int>>() }<file_sep>/app/src/main/java/com/sagish/testcoronaapp/ui/fragments/nearBy/NearByFragment.kt package com.sagish.testcoronaapp.ui.fragments.nearBy import android.bluetooth.BluetoothAdapter import android.bluetooth.BluetoothDevice import android.content.* import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.databinding.DataBindingUtil import androidx.fragment.app.Fragment import androidx.fragment.app.activityViewModels import androidx.lifecycle.Observer import com.sagish.testcoronaapp.R import com.sagish.testcoronaapp.databinding.FragmentBluetoothBinding import com.sagish.testcoronaapp.ui.helpers.AlertDialogHelper class NearByFragment : Fragment() { private val viewModel: NearByViewModel by activityViewModels() lateinit var binding : FragmentBluetoothBinding private val deviceFoundBroadcastReceiver = object : BroadcastReceiver() { override fun onReceive(p0: Context?, p1: Intent?) { when(p1!!.action) { BluetoothDevice.ACTION_FOUND -> { val device : BluetoothDevice? = p1.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE) if (device != null) { val deviceAddress = device.address if (deviceAddress == "SOME_MAC_ADDRESS") { AlertDialogHelper.show(requireActivity(), R.string.infected_person_found, R.string.ok, object : DialogInterface.OnClickListener { override fun onClick(p0: DialogInterface?, p1: Int) { // Do some action } }) } } } } } } override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { binding = DataBindingUtil.inflate(inflater, R.layout.fragment_bluetooth, container, false) return binding.root } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) binding.startScanButton.setOnClickListener(object : View.OnClickListener { override fun onClick(p0: View?) { binding.info.text = resources.getString(R.string.scanning_for_near_by_people) viewModel.setIsScanning(true) showScanButton(false) showStopScanButton(true) showProgress(true) startBluetoothScan() } }) binding.stopScanButton.setOnClickListener(object : View.OnClickListener { override fun onClick(p0: View?) { viewModel.setIsScanning(false) startScan(false) showScanButton(true) showStopScanButton(false) showProgress(false) binding.info.text = resources.getString(R.string.scan_info) } }) setUpObservers(viewModel) } private fun setUpObservers(viewModel: NearByViewModel) { viewModel.isBluetoothEnabled().observe(viewLifecycleOwner, object : Observer<Boolean> { override fun onChanged(t: Boolean?) { // If Bluetooth disabled in the middle of a scan return the view to its initial state if (!t!! && viewModel.isScanning().value!!) { showStopScanButton(false) showProgress(false) showScanButton(true) startScan(false) binding.info.text = resources.getString(R.string.scan_info) } } }) } /** * Show or hide the stop scan button */ private fun showStopScanButton(show : Boolean) { if (show) { binding.stopScanButton.visibility = View.VISIBLE } else { binding.stopScanButton.visibility = View.INVISIBLE } } /** * Show or hide the scan button */ private fun showScanButton(show: Boolean) { if (show) { binding.startScanButton.visibility = View.VISIBLE } else { binding.startScanButton.visibility = View.INVISIBLE } } /** * Start the flow of Bluetooth device detection. */ private fun startBluetoothScan() { // If the device does not support Bluetooth if (!viewModel.hasBluetooth()) { // Show error message AlertDialogHelper.show(requireActivity(), R.string.the_device_does_not_support_bluetooth, R.string.ok) // Hide progressBar showProgress(false) // Show the scan button showScanButton(true) // Hide the stop scan button showStopScanButton(false) // Set info text binding.info.text = resources.getString(R.string.scan_info) return } // If Bluetooth is not enabled if (!viewModel.isBluetoothEnabled().value!!) { // Show info message that tells the user to enable Bluetooth AlertDialogHelper.show(requireActivity(), R.string.bluetooth_must_be_enabled_for_detection, R.string.ok) // Hide progressBar showProgress(false) // Show the scan button showScanButton(true) // Hide the stop scan button showStopScanButton(false) // Set info text binding.info.text = resources.getString(R.string.scan_info) return } startScan(true) } override fun onStart() { super.onStart() requireActivity().registerReceiver(deviceFoundBroadcastReceiver, IntentFilter(BluetoothDevice.ACTION_FOUND)) } override fun onStop() { super.onStop() requireActivity().unregisterReceiver(deviceFoundBroadcastReceiver) } /** * Show progressBar while scanning for BluetoothDevice */ private fun showProgress(show: Boolean) { if (show) { binding.progressBar.visibility = View.VISIBLE } else { binding.progressBar.visibility = View.INVISIBLE } } /** * Start or stop the Bluetooth scan */ private fun startScan(start : Boolean) { if (start) { BluetoothAdapter.getDefaultAdapter().startDiscovery() } else { BluetoothAdapter.getDefaultAdapter().cancelDiscovery() } } }<file_sep>/app/src/main/java/com/sagish/testcoronaapp/ui/fragments/myCountry/GetByMyCountryFragment.kt package com.sagish.testcoronaapp.ui.fragments.myCountry import android.os.Bundle import android.view.View import android.widget.ArrayAdapter import androidx.fragment.app.activityViewModels import com.sagish.testcoronaapp.ui.fragments.byCountry.GetByCountryFragment import com.sagish.testcoronaapp.ui.fragments.byCountry.GetByCountryViewModel class GetByMyCountryFragment : GetByCountryFragment() { private val viewModel: GetByMyCountryViewModel by activityViewModels() override fun onViewCreated(view: View, savedInstanceState: Bundle?) { setUpRecycler() setUpSpinner(viewModel) setUpDateViewsClickListeners(viewModel) setUpObservers(viewModel) } override fun setUpSpinner(viewModel: GetByCountryViewModel) { binding.countryChooserSpinner.isEnabled = false val list = ArrayList<String>() list.add((viewModel as GetByMyCountryViewModel).getCountry()!!) val adapter = ArrayAdapter(requireActivity(), android.R.layout.simple_spinner_item, list) binding.countryChooserSpinner.adapter = adapter } }
6e83102d692b0dda2919c986c4c129304dd77c9e
[ "Kotlin" ]
16
Kotlin
sagishchori/TestCoronaApp
e21d8054238a24f3021b37786e8972848ff34e1d
00a99aeaafbe8c58362de5ff14797a1ae55890bd
refs/heads/master
<file_sep><?php /** * Joomla! component MageBridge * * @author Yireo (<EMAIL>) * @package MageBridge * @copyright Copyright 2016 * @license GNU Public License * @link https://www.yireo.com */ // No direct access defined('_JEXEC') or die('Restricted access'); // Require the parent view require_once JPATH_ADMINISTRATOR . '/components/com_magebridge/libraries/loader.php'; /** * Bridge configuration class */ class MagebridgeModelConfig extends YireoAbstractModel { /** * Array of configured data * * @var array */ protected $_data = null; /** * Array of default values * * @var array */ protected $_defaults = null; /** * Constructor * * @param null * * @retun array */ public function __construct() { $this->_defaults = array( 'supportkey' => '', 'host' => '', 'protocol' => 'http', 'method' => 'post', 'encryption' => '0', 'encryption_key' => null, 'http_auth' => 0, 'http_user' => '', 'http_password' => '', 'http_authtype' => CURLAUTH_ANY, 'enforce_ssl' => 0, 'ssl_version' => 0, 'ssl_ciphers' => null, 'basedir' => '', 'offline' => 0, 'offline_message' => 'The webshop is currently not available. Please come back again later.', 'offline_exclude_ip' => '', 'website' => '1', 'storegroup' => null, 'storeview' => null, 'backend' => 'admin', 'api_user' => '', 'api_key' => '', 'api_widgets' => '1', 'api_type' => 'jsonrpc', 'enable_cache' => '0', 'cache_time' => '300', 'debug' => '0', 'debug_ip' => '', 'debug_log' => 'db', 'debug_level' => 'all', 'debug_console' => '1', 'debug_bar' => '1', 'debug_bar_parts' => '1', 'debug_bar_request' => '1', 'debug_bar_store' => '1', 'debug_display_errors' => '0', 'disable_css_mage' => '', // List of CSS files from Magento 'disable_css_all' => 0, // Disable Magento CSS or not 'disable_default_css' => 1, // Disable MageBridge CSS 'disable_js_mage' => 'varien/menu.js,lib/ds-sleight.js,js/ie6.js', // List of JS files from Magento 'disable_js_mootools' => 1, // Disable MooTools 'disable_js_footools' => 0, // Disable FooTools 'disable_js_frototype' => 0, // Disable Frototype 'disable_js_jquery' => 0, // Disable jQuery 'disable_js_prototype' => 0, // Disable Magento ProtoType 'disable_js_custom' => '', // Custom list of JS files from Joomla! 'disable_js_all' => 1, // Disable Joomla! JS 'replace_jquery' => 1, // Replace Magento jQuery with Joomla 'merge_js' => 0, 'merge_css' => 0, 'use_google_api' => 0, 'use_protoaculous' => 0, 'use_protoculous' => 0, 'bridge_cookie_all' => 0, 'bridge_cookie_custom' => '', 'flush_positions' => 0, 'flush_positions_home' => '', 'flush_positions_customer' => '', 'flush_positions_product' => '', 'flush_positions_category' => '', 'flush_positions_cart' => '', 'flush_positions_checkout' => '', 'use_rootmenu' => 1, 'preload_all_modules' => 0, 'enforce_rootmenu' => 0, 'customer_group' => '', 'customer_pages' => '', 'usergroup' => '', 'enable_sso' => 0, 'enable_usersync' => 1, 'username_from_email' => 0, 'realname_from_firstlast' => 1, 'realname_with_space' => 1, 'enable_auth_backend' => 0, 'enable_auth_frontend' => 1, 'enable_content_plugins' => 0, 'enable_block_rendering' => 0, 'enable_jdoc_tags' => 1, 'enable_messages' => 1, 'enable_breadcrumbs' => 1, 'modify_url' => 1, 'link_to_magento' => 0, 'module_chrome' => 'raw', 'module_show_title' => 1, 'mobile_joomla_theme' => 'magebridge_mobile', 'mobile_magento_theme' => 'iphone', 'magento_theme' => '', 'spoof_browser' => 1, 'spoof_headers' => 0, 'curl_post_as_array' => 1, 'curl_timeout' => 120, 'enable_notfound' => 0, 'payment_urls' => '', 'direct_output' => '', 'template' => '', 'update_format' => '', 'update_method' => 'curl', 'backend_feed' => 1, 'users_website_id' => '', 'users_group_id' => '', 'keep_alive' => '1', 'load_urls' => '1', 'load_stores' => '1', 'filter_content' => '1', 'filter_store_from_url' => '1', 'show_help' => '1', 'enable_canonical' => '1', 'use_referer_for_homepage_redirects' => '1', 'use_homepage_for_homepage_redirects' => '0', ); parent::__construct(); } /** * Method to fetch the data * * @param null * * @return MageBridgeModelConfig */ static public function getSingleton() { static $instance; if ($instance === null) { $instance = new MageBridgeModelConfig(); } return $instance; } /** * Method to set data * * @param null * * @return array */ public function setData($data) { $this->_data = $data; } /** * Method to get data * * @param null * * @return array */ public function getData() { // Lets load the content if it doesn't already exist if (empty($this->_data)) { $query = 'SELECT `id`,`name`,`value` FROM `#__magebridge_config` AS c'; $this->_db->setQuery($query); $this->_data = $this->_db->loadObjectList(); } return $this->_data; } /** * Method to get the defaults * * @param null * * @return array */ public function getDefaults() { return $this->_defaults; } /** * Static method to get data * * @param string $element * * @return mixed */ static public function load($element = null, $overload = null) { $application = JFactory::getApplication(); static $config = null; if (empty($config)) { // Parse the defaults $config = array(); $model = self::getSingleton(); foreach ($model->getDefaults() as $name => $value) { $config[$name] = array( 'id' => null, 'name' => $name, 'value' => $value, 'core' => 1, 'description' => null, ); if ($application->isAdmin()) { $config[$name]['description'] = JText::_(strtoupper($name) . '_DESCRIPTION'); } } // Fetch the current data $data = $model->getData(); // Parse the current data into the config foreach ($config as $name => $c) { if (!empty($data)) { foreach ($data as $d) { if ($d->name == $c['name']) { $core = ($config[$name]['value'] == $d->value) ? 1 : 0; $config[$name] = array( 'id' => $d->id, 'name' => $d->name, 'value' => $d->value, 'core' => $core, 'description' => $c['description'], ); break; } } } } } // Override certain values $config['method']['value'] = 'post'; // Determine the right update format if ($config['update_format']['value'] == '') { jimport('joomla.application.component.helper'); $component = JComponentHelper::getComponent('com_magebridge'); require_once JPATH_ADMINISTRATOR . '/components/com_magebridge/libraries/helper.php'; $params = YireoHelper::toRegistry($component->params); $value = $params->get('update_format', 'tar.gz'); $config['update_format']['value'] = $value; } // Disable widgets if needed if (JFactory::getApplication()->input->getInt('widgets', 1) == 0) { $config['api_widgets']['value'] = 0; } // Overload a certain values when the Magento Admin Panel needs to be loaded $application = JFactory::getApplication(); if ($application->isAdmin() && JFactory::getApplication()->input->getCmd('option') == 'com_magebridge' && JFactory::getApplication()->input->getCmd('view') == 'root') { //$config['debug']['value'] = 0; $config['disable_js_all']['value'] = 1; $config['disable_js_mootools']['value'] = 1; } // Allow overriding values if (!empty($element) && isset($config[$element]) && $overload !== null) { $config[$element]['value'] = $overload; } // Return the URL if ($element == 'url') { $url = null; if (!empty($config['host']['value'])) { $url = $config['protocol']['value'] . '://' . $config['host']['value'] . '/'; if (!empty($config['basedir']['value'])) { $url .= $config['basedir']['value'] . '/'; } } return $url; // Return the port-number } else { if ($element == 'port') { return ($config['protocol']['value'] == 'http') ? 80 : 443; // Return any other element } else { if ($element != null && isset($config[$element])) { return $config[$element]['value']; // Return no value } else { if (!empty($element)) { return null; // Return the configuration itself } else { return $config; } } } } } /** * Method to check a specific configuratione-element * * @param string $element * @param string $value * * @return string|null */ static public function check($element, $value = null) { // Reset an empty value to its original value if (empty($value)) { $value = MagebridgeModelConfig::load($element); } // Check for settings that should not be kept empty $nonempty = array('host', 'website', 'api_user', 'api_key'); if (MagebridgeModelConfig::allEmpty() == false && in_array($element, $nonempty) && empty($value)) { return JText::sprintf('Setting "%s" is empty - Please configure it below', JText::_($element)); } // Check host if ($element == 'host') { if (preg_match('/([^a-zA-Z0-9\.\-\_\:]+)/', $value) == true) { return JText::_('Hostname contains illegal characters. Note that a hostname is not an URL, but only a fully qualified domainname.'); } else { if (gethostbyname($value) == $value && !preg_match('/([0-9\.]+)/', $value)) { return JText::sprintf('DNS lookup of hostname %s failed', $value); } else { if (MagebridgeModelConfig::load('api_widgets') == true) { $bridge = MageBridgeModelBridge::getInstance(); $data = $bridge->build(); if (empty($data)) { $url = $bridge->getMagentoBridgeUrl(); return JText::sprintf('Unable to open a connection to <a href="%s" target="_new">%s</a>', $url, $url); } } } } } // Check supportkey if ($element == 'supportkey' && empty($value)) { return JText::sprintf('Please configure your support-key. Your support-key can be obtained from %s', MageBridgeHelper::getHelpText('subscriptions')); } // Check API widgets if ($element == 'api_widgets' && $value != 1) { return JText::_('API widgets are disabled'); } // Check offline if ($element == 'offline' && $value == 1) { return JText::_('Bridge is disabled through settings'); } // Check website if ($element == 'website' && !empty($value)) { if (is_numeric($value) == false) { return JText::sprintf('Website ID needs to be a numeric value. Current value is "%s"', $value); } } /** * if ($element == 'storeview' && !empty($value)) { * if ( preg_match( '/([a-zA-Z0-9\.\-\_]+)/', $value ) == false ) { * return JText::_( 'Store-name contains illegal characters: '.$value ); * } else { * $storeviews = MagebridgeModelConfig::getStoreNames(); * if (!is_array($storeviews) && $storeviews != 0) { * return JText::_($storeviews); * * } else { * * $match = false; * if (!empty($storeviews)) { * foreach ($storeviews as $storeview) { * if ($storeview['value'] == $value) { * $match = true; * break; * } * } * } * * if ($match == false) { * $msg = JText::sprintf( 'Store-names detected, but "%s" is not one of them', $value ); * return $msg; * } * } * } * } */ // Check basedir if ($element == 'basedir') { if (empty($value)) { return null; } if (preg_match('/([a-zA-Z0-9\.\-\_]+)/', $value) == false) { return JText::_('Basedir contains illegal characters'); } $root = MageBridgeUrlHelper::getRootItem(); $joomla_host = JFactory::getURI() ->toString(array('host')); $magento_host = MagebridgeModelConfig::load('host'); // Check whether the Magento basedir conflicts with the MageBridge alias if (!empty($root) && !empty($root->route) && $root->route == $value && $joomla_host == $magento_host) { return JText::_('Magento basedir is same as MageBridge alias, which is not possible'); } } return null; } /** * Helper method to detect whether the whole configuration is empty * * @param null * * @return bool */ static public function allEmpty() { static $_allempty = null; if (empty($_allempty)) { $_allempty = true; $config = MagebridgeModelConfig::load(); foreach ($config as $c) { if ($c['core'] == 0) { $_allempty = false; break; } } } return $_allempty; } /** * Method to store the configuration in the database * * @param array $post * * @return bool */ public function store($post) { // If the custom list is empty, set another value if (isset($post['disable_js_custom']) && isset($post['disable_js_all'])) { if ($post['disable_js_all'] == 2 && empty($post['disable_js_custom'])) { $post['disable_js_all'] = 0; } if ($post['disable_js_all'] == 3 && empty($post['disable_js_custom'])) { $post['disable_js_all'] = 1; } } // Convert "disable_css_mage" array into comma-seperated string if (isset($post['disable_css_mage']) && is_array($post['disable_css_mage'])) { if (empty($post['disable_css_mage'][0])) { array_shift($post['disable_css_mage']); } if (empty($post['disable_css_mage'])) { $post['disable_css_mage'] = ''; } else { $post['disable_css_mage'] = implode(',', $post['disable_css_mage']); } } // Convert "disable_js_mage" array into comma-seperated string if (isset($post['disable_js_mage']) && is_array($post['disable_js_mage'])) { if (empty($post['disable_js_mage'][0])) { array_shift($post['disable_js_mage']); } if (empty($post['disable_js_mage'])) { $post['disable_js_mage'] = ''; } else { $post['disable_js_mage'] = implode(',', $post['disable_js_mage']); } } // Clean the basedir if (!empty($post['basedir'])) { $post['basedir'] = preg_replace('/^\//', '', $post['basedir']); $post['basedir'] = preg_replace('/\/$/', '', $post['basedir']); } // Check whether the URL-table contains entries $db = JFactory::getDbo(); $db->setQuery('SELECT * FROM #__magebridge_urls WHERE published=1'); $rows = $db->loadObjectList(); if (!empty($rows)) { $post['load_urls'] = 1; } else { $post['load_urls'] = 0; } // Check whether the stores-table contains entries $db = JFactory::getDbo(); $db->setQuery('SELECT * FROM #__magebridge_stores WHERE published=1'); $rows = $db->loadObjectList(); if (!empty($rows)) { $post['load_stores'] = 1; } else { $post['load_stores'] = 0; } // Load the existing configuration $config = MagebridgeModelConfig::load(); // Overload each existing value with the posted value (if it exists) foreach ($config as $name => $c) { if (isset($post[$name]) && isset($config[$name])) { $config[$name]['value'] = $post[$name]; } } // Detect changes in API-settings and if so, dump and clean the cache $detect_values = array('host', 'basedir', 'api_user', 'api_password'); $detect_change = false; foreach ($detect_values as $d) { if (isset($post[$d]) && isset($config[$d]) && $post[$d] != $config[$d]) { $detect_change = true; } } // Clean the cache if changes are detected if ($detect_change) { $cache = JFactory::getCache('com_magebridge.admin'); $cache->clean(); } // Store the values row-by-row $database = JFactory::getDbo(); foreach ($config as $name => $data) { if (!isset($data['name']) || empty($data['name'])) { continue; } $table = JTable::getInstance('config', 'MagebridgeTable'); if (!$table->bind($data)) { JError::raiseWarning(500, 'Unable to bind configuration to component'); return false; } if (!$table->store()) { JError::raiseWarning(500, 'Unable to store configuration to component'); return false; } } return true; } /** * Method to store a single value in the database * * @param string $name * @param mixed $value * * @return bool * @throws Exception */ public function saveValue($name, $value) { $data = array( 'name' => $name, 'value' => $value, ); $config = MagebridgeModelConfig::load(); if (isset($config[$name])) { $data['id'] = $config[$name]['id']; } $table = JTable::getInstance('config', 'MagebridgeTable'); if ($table === false) { throw new Exception('No table found'); } if (!$table->bind($data)) { JError::raiseWarning(500, 'Unable to bind configuration to component'); return false; } if (!$table->store()) { JError::raiseWarning(500, 'Unable to store configuration to component'); return false; } return true; } } <file_sep><?php /** * Joomla! component MageBridge * * @author Yireo (<EMAIL>) * @package MageBridge * @copyright Copyright 2016 * @license GNU Public License * @link https://www.yireo.com */ // No direct access defined('_JEXEC') or die('Restricted access'); // Import the MageBridge autoloader require_once JPATH_SITE . '/components/com_magebridge/helpers/loader.php'; // Import the parent class jimport('joomla.plugin.plugin'); /** * Parent plugin-class */ class MageBridgePlugin extends JPlugin { /** * Method to check whether a specific component is there * * @param string $component * * @return bool */ protected function checkComponent($component) { if (is_dir(JPATH_ADMINISTRATOR . '/components/' . $component) && JComponentHelper::isEnabled($component) == true) { return true; } return false; } /** * @return \Joomla\Registry\Registry */ public function getParams() { return $this->params; } } <file_sep><?php /** * Joomla! component MageBridge * * @author Yireo (<EMAIL>) * @package MageBridge * @copyright Copyright 2016 * @license GNU Public License * @link https://www.yireo.com */ // No direct access defined('_JEXEC') or die('Restricted access'); /** * Helper for usage in Joomla!/MageBridge plugins */ class MageBridgePluginHelper { /** * Helper-method to determine if it's possible to run this event * * @param string $event * @param array $options * * @return bool */ static public function allowEvent($event, $options = array()) { static $denied_events = array(); // Do not run this event if the bridge itself is offline if (MageBridge::getBridge() ->isOffline() ) { MageBridgeModelDebug::getInstance() ->notice("Plugin helper detects bridge is offline"); return false; } // Do not run this event if the option "disable_bridge" is set to true if (isset($options['disable_bridge']) && $options['disable_bridge'] == true) { MageBridgeModelDebug::getInstance() ->notice("Plugin helper detects event '$event' is currently disabled"); return false; } // Do not execute additional plugin-events on the success-page (to prevent refreshing) $request = MageBridgeUrlHelper::getRequest(); if (preg_match('/checkout\/onepage\/success/', $request)) { MageBridgeModelDebug::getInstance() ->notice("Plugin helper detects checkout/onepage/success page"); return false; } // Do not execute this event if we are in XML-RPC or JSON-RPC if (MageBridge::isApiPage() == true) { return false; } // Check if this event is the list of events already thrown if (in_array($event, $denied_events)) { MageBridgeModelDebug::getInstance() ->notice("Plugin helper detects event '$event' is already run"); return false; } MageBridgeModelDebug::getInstance() ->notice("Plugin helper allows event '$event'"); $denied_events[] = $event; return true; } } <file_sep><?php /** * MageBridge * * @author Yireo * @package MageBridge * @copyright Copyright 2016 * @license Open Source License * @link https://www.yireo.com */ /* * MageBridge model for Joomla! API client-calls */ class Yireo_MageBridge_Model_Client { /* * Method to call a remote method * * @access public * @param string $method * @param array $params * @return mixed */ public function call($method, $params = array(), $store = null) { // Get the remote API-link from the configuration $url = Mage::helper('magebridge')->getApiUrl(null, $store); if(empty($url)) { return false; } // Make sure we are working with an array if(!is_array($params)) { $params = array(); } // Initialize the API-client $client = Mage::getModel('magebridge/client_jsonrpc'); // Call the remote method if(!empty($client)) { $rt = $client->makeCall($url, $method, $params, $store); return $rt; } return false; } /* * Method that returns API-authentication-data as a basic array * * @access public * @param null * @return array */ public function getApiAuthArray($store = null) { $apiUser = Mage::helper('magebridge')->getApiUser($store); $apiKey = Mage::helper('magebridge')->getApiKey($store); if(empty($apiUser) || empty($apiKey)) { Mage::getSingleton('magebridge/debug')->warning('Listener getApiAuthArray: api_user or api_key is missing'); Mage::getSingleton('magebridge/debug')->trace('Listener: Meta data', Mage::getSingleton('magebridge/core')->getMetaData()); return false; } $auth = array( 'api_user' => Mage::helper('magebridge/encryption')->encrypt($apiUser), 'api_key' => Mage::helper('magebridge/encryption')->encrypt($apiKey), ); return $auth; } } <file_sep><?php /** * Joomla! component MageBridge * * @author Yireo (<EMAIL>) * @package MageBridge * @copyright Copyright 2016 * @license GNU Public License * @link https://www.yireo.com */ // Check to ensure this file is included in Joomla! defined('_JEXEC') or die(); // Import the needed libraries jimport('joomla.filter.output'); /** * HTML View class */ class MageBridgeViewStore extends YireoViewForm { /** * Constructor */ /** * Main constructor method * * @access public * @param array $config * @return null */ public function __construct($config = array()) { if(JFactory::getApplication()->input->getCmd('task') == 'default') { $this->loadToolbar = false; } // Call the parent constructor parent::__construct($config); } /** * Method to prepare the content for display * * @param string $tpl * @return null */ public function display($tpl = null) { switch(JFactory::getApplication()->input->getCmd('task')) { case 'default': $this->showDefaultForm($tpl); break; default: $this->showForm($tpl = 'form'); break; } } /** * Method to prepare the content for display * * @param string $tpl * @return null */ public function showDefaultForm($tpl = null) { // Initialize the view $this->setTitle(JText::_('COM_MAGEBRIDGE_VIEW_STORE_DEFAULT_STORE')); // Override the normal toolbar JToolBarHelper::cancel(); JToolBarHelper::save(); JToolBarHelper::apply(); // Load values from the configuration $storegroup = MageBridgeModelConfig::load('storegroup'); $storeview = MageBridgeModelConfig::load('storeview'); // Construct the arguments for the HTML-element if (!empty($storeview)) { $type = 'storeview'; $name = $storeview; } else if (!empty($storegroup)) { $type = 'storegroup'; $name = $storegroup; } else { $type = null; $name = null; } // Fetch the HTML-element $this->lists['store'] = $this->getFieldStore($type, $name); parent::display($tpl); } /** * Method to prepare the content for display * * @param string $tpl * @return null */ public function showForm($tpl = null) { // Fetch this item $this->fetchItem(); // Build extra lists $this->lists['store'] = $this->getFieldStore($this->item->type, $this->item->name); // Initialize the form-file $file = JPATH_ADMINISTRATOR.'/components/com_magebridge/models/store.xml'; // Prepare the params-form $params = YireoHelper::toRegistry($this->item->params)->toArray(); $params_form = JForm::getInstance('params', $file); $params_form->bind(array('params' => $params)); $this->params_form = $params_form; // Prepare the actions-form $actions = YireoHelper::toRegistry($this->item->actions)->toArray(); $actions_form = JForm::getInstance('actions', $file); JPluginHelper::importPlugin('magebridgestore'); JFactory::getApplication()->triggerEvent('onMageBridgeStorePrepareForm', array(&$actions_form, (array)$this->item)); $actions_form->bind(array('actions' => $actions)); $this->actions_form = $actions_form; // Check for a previous connector-value if(!empty($this->item->connector)) { $plugin = JPluginHelper::getPlugin('magebridgestore', $this->item->connector); if(empty($plugin)) { $plugin_warning = JText::sprintf('COM_MAGEBRIDGE_STORE_PLUGIN_WARNING', $this->item->connector); JError::raiseWarning(500, $plugin_warning); } } parent::display($tpl); } /** * Helper method to get the HTML-formelement for a store * * @param string $type * @param string $name * @param string $title * @return string */ protected function getFieldStore($type = null, $value = null) { if (!empty($type) && !empty($value)) { $value = ($type == 'storegroup') ? 'g:'.$value : 'v:'.$value; } else { $value = null; } if (empty($name)) $name = 'store'; return MageBridgeFormHelper::getField('magebridge.store', $name, $value, null); } /** * Helper method to get the HTML-formelement for a storeview * * @param string $default * @return string */ protected function getFieldStoreview($default = null) { return MageBridgeFormHelper::getField('magebridge.storeview', 'name', $value, null); } /** * Helper method to get the HTML-formelement for a storegroup * * @param string $default * @return string */ protected function getFieldStoregroup($default = null) { return MageBridgeFormHelper::getField('magebridge.storegroup', 'name', $value, null); } } <file_sep><?php /** * Joomla! component MageBridge * * @author Yireo (<EMAIL>) * @package MageBridge * @copyright Copyright 2016 * @license GNU Public License * @link https://www.yireo.com */ // No direct access defined('_JEXEC') or die('Restricted access'); /** * Bridge Single Sign On class */ class MageBridgeModelUserSSO extends MageBridgeModelUser { /** * Method for logging in with Magento (Single Sign On) * * @param array $user * @return bool|exit */ static public function doSSOLogin($user = null) { // Abort if the input is not valid if (empty($user) || (empty($user['email']) && empty($user['username']))) { return false; } // Get system variables $application = JFactory::getApplication(); $session = JFactory::getSession(); // Store the current page, so we can redirect to it after SSO is done if ($return = JFactory::getApplication()->input->get('return', '', 'base64')) { $return = base64_decode($return); } else { $return = MageBridgeUrlHelper::current(); } $session->set('magento_redirect', $return); // Determine the user-name $application_name = ($application->isAdmin()) ? 'admin' : 'frontend'; if ($application_name == 'admin') { $username = $user['username']; } else if (!empty($user['email'])) { $username = $user['email']; } else { $username = $user['username']; } // Get the security token $token = (method_exists('JSession', 'getFormToken')) ? JSession::getFormToken() : JUtility::getToken(); // Construct the URL $arguments = array( 'sso=login', 'app='.$application_name, 'base='.base64_encode(JUri::base()), 'userhash='.MageBridgeEncryptionHelper::encrypt($username), 'token='.$token, ); $url = MageBridgeModelBridge::getInstance()->getMagentoBridgeUrl().'?'.implode('&', $arguments); // Redirect the browser to Magento MageBridgeModelDebug::getInstance()->trace( "SSO: Sending arguments", $arguments ); $application->redirect($url); return true; } /** * Method for logging out with Magento (Single Sign On) * * @param string $username * @return bool|exit */ static public function doSSOLogout($username = null) { // Abort if the input is not valid if (empty($username)) { return false; } // Get system variables $application = JFactory::getApplication(); $session = JFactory::getSession(); // Determine the application $application_name = ($application->isAdmin()) ? 'admin' : 'frontend'; // Get the security token $token = (method_exists('JSession', 'getFormToken')) ? JSession::getFormToken() : JUtility::getToken(); // Set the redirection URL if ($application_name == 'admin') { $redirect = JUri::current(); } else { $redirect = MageBridgeUrlHelper::current(); } // Construct the URL $arguments = array( 'sso=logout', 'app='.$application_name, 'redirect='.base64_encode($redirect), 'userhash='.MageBridgeEncryptionHelper::encrypt($username), 'token='.$token, ); $url = MageBridgeModelBridge::getInstance()->getMagentoBridgeUrl().'?'.implode('&', $arguments); // Redirect the browser to Magento MageBridgeModelDebug::getInstance()->notice( "SSO: Logout of '$username' from ".$application_name); $application->redirect($url); return true; } /** * Method to check the SSO-request coming back from Magento * * @param null * @return bool|exit */ static public function checkSSOLogin() { // Check the security token JSession::checkToken('get') or die('SSO redirect failed due to wrong token'); // Get system variables $application = JFactory::getApplication(); $session = JFactory::getSession(); // Get the current Magento session $magento_session = JFactory::getApplication()->input->getCmd('session'); if (!empty($magento_session)) { MageBridgeModelBridge::getInstance()->setMageSession($magento_session); MageBridgeModelDebug::getInstance()->notice( "SSO: Magento session ".$magento_session); } // Redirect back to the original URL $redirect = $session->get('magento_redirect', JUri::base()); if (empty($redirect)) { $redirect = MageBridgeUrlHelper::route('customer/account'); } MageBridgeModelDebug::getInstance()->notice( "SSO: Redirect to $redirect" ); $application->redirect($redirect); return true; } } <file_sep><?php /** * MageBridge * * @author Yireo * @package MageBridge * @copyright Copyright 2016 * @license Open Source License * @link https://www.yireo.com/ */ /* * MageBridge model for JSON-RPC client-calls */ class Yireo_MageBridge_Model_Client_Jsonrpc extends Yireo_MageBridge_Model_Client { /* * Method to call a JSON-RPC method * * @access public * @param string $method * @param array $params * @return mixed */ public function makeCall($url, $method, $params = array(), $store = null) { // Get the authentication data $auth = $this->getApiAuthArray($store); $method = preg_replace('/^magebridge\./', '', $method); // If these values are not set, we are unable to continue if(empty($url ) || $auth == false) { return false; } // Add the $auth-array to the parameters $params['api_auth'] = $auth; // Construct an ID $id = md5($method); // Construct the POST-data $post = array( 'method' => $method, 'params' => $params, 'id' => $id, ); // Interpret the URL $urlQuery = parse_url($url, PHP_URL_QUERY); parse_str($urlQuery, $urlParams); foreach($urlParams as $urlParamName => $urlParamValue) { //Mage::getSingleton('magebridge/debug')->trace('JSON-RPC POST-value '.$urlParamName, $urlParamValue); $post = array_merge(array($urlParamName => $urlParamValue), $post); } $encodedPost = Zend_Json_Encoder::encode($post); // Initialize a CURL-client $ch = curl_init($url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_POSTFIELDS, $encodedPost); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false); curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30); curl_setopt($ch, CURLOPT_TIMEOUT, 30); curl_setopt($ch, CURLOPT_MAXREDIRS, 2); // Build the CURL connection and receive feedback $data = curl_exec($ch); if(empty($data) || !preg_match('/^\{/', $data)) { Mage::getSingleton('magebridge/debug')->trace('JSON-RPC: Wrong data in JSON-RPC reply', $data); Mage::getSingleton('magebridge/debug')->trace('JSON-RPC: CURL error', curl_error($ch)); return 'Wrong data in JSON-RPC reply'; } // Try to decode the result $decoded = json_decode($data, true); if(empty($decoded)) { Mage::getSingleton('magebridge/debug')->error('JSON-RPC: Empty JSON-response'); Mage::getSingleton('magebridge/debug')->trace('JSON-RPC: Actual response', $data); return 'Empty JSON-response'; } $data = $decoded; if(!is_array($data)) { Mage::getSingleton('magebridge/debug')->trace('JSON-RPC: JSON-response is not an array', $data); return 'JSON-response is not an array'; } else { if(isset($data['error']) && !empty($data['error']['message'])) { Mage::getSingleton('magebridge/debug')->trace('JSON-RPC: JSON-error', $data['error']['message']); return $data['error']['message']; } elseif(!isset($data['result'])) { Mage::getSingleton('magebridge/debug')->error('JSON-RPC: No result in JSON-data'); return 'No result in JSON-data'; } } Mage::getSingleton('magebridge/debug')->trace('JSON-RPC: Result', $data['result']); return $data['result']; } }
dda949056ecdeb38f22910c5c31cc04747765f98
[ "PHP" ]
7
PHP
teotikalki/MageBridgeCore
a07aa2c139036ac4a813ec17cf7db1b7ccfc44ca
5e3b875415dc9ba79c7dd5c1a7915528f5fe8c60
refs/heads/master
<repo_name>TomIsYourName/PhotoChooser<file_sep>/app/src/com/litijun/photochooser/manager/PhotoChooseMgr.java package com.litijun.photochooser.manager; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import android.content.Context; import android.widget.ImageView; import com.litijun.photochooser.R; import com.litijun.photochooser.adapter.vo.ImageItem; import com.litijun.photochooser.utils.DebugLog; import com.litijun.photochooser.utils.ImageLoaderUtil; import com.nostra13.universalimageloader.core.ImageLoader; import com.nostra13.universalimageloader.core.download.ImageDownloader.Scheme; public class PhotoChooseMgr { private static volatile PhotoChooseMgr instance; private Context context; private Map<Integer, ImageItem> selectedItemMap; private List<ImageItem> allImageList; private int maxSelectSize; private boolean isTakePhoto; private PhotoChooseMgr(Context context) { this.context = context; this.maxSelectSize = 0; this.selectedItemMap = new HashMap<Integer, ImageItem>(maxSelectSize); this.allImageList = new ArrayList<ImageItem>(); } public static PhotoChooseMgr getInstance(Context context) { synchronized(PhotoChooseMgr.class){ if (instance == null) { instance = new PhotoChooseMgr(context); } } return instance; } public int getMaxSelectSize() { return maxSelectSize; } public void setMaxSelectSize(int maxSelectSize) { this.maxSelectSize = maxSelectSize; } public int getSelectCount() { return selectedItemMap.size(); } public Map<Integer, ImageItem> getSelectedItemMap() { return selectedItemMap; } public List<ImageItem> getAllImageList() { return allImageList; } public List<ImageItem> getSeletectList() { List<ImageItem> data = new ArrayList<ImageItem>(); Map<Integer, ImageItem> imageItemMap = PhotoChooseMgr.getInstance(context).getSelectedItemMap(); DebugLog.v("SeletectList.size() = " + imageItemMap.size()); for (Map.Entry<Integer, ImageItem> entry : imageItemMap.entrySet()) { Integer key = entry.getKey(); ImageItem value = entry.getValue(); if (value != null && value instanceof ImageItem) { data.add((ImageItem) value); } } return data; } public boolean addSelect(ImageItem item) { if (selectedItemMap.containsKey(item.id)) { return true; } else if (selectedItemMap.size() >= maxSelectSize) { return false; } else { selectedItemMap.put(item.id, item); return true; } } public boolean removeSelect(ImageItem item) { if (selectedItemMap.containsKey(item.id)) { selectedItemMap.remove(item.id); } return true; } public void clearSelect(){ selectedItemMap.clear(); } public ImageItem getImageItem(int key) { return selectedItemMap.get(key); } public boolean isTakePhoto() { return isTakePhoto; } public void setTakePhoto(boolean isTakePhoto) { this.isTakePhoto = isTakePhoto; } public void dispalyImage(String picPath, final ImageView imageView) { ImageLoader.getInstance().displayImage(Scheme.FILE.wrap(picPath), imageView, ImageLoaderUtil.getInstance(context).createNoRoundedOptions(R.drawable.image_loading_default)); } } <file_sep>/app/src/com/litijun/photochooser/utils/ImageLoaderUtil.java package com.litijun.photochooser.utils; import android.content.Context; import android.graphics.Bitmap; import com.nostra13.universalimageloader.cache.disc.impl.UnlimitedDiskCache; import com.nostra13.universalimageloader.cache.disc.naming.HashCodeFileNameGenerator; import com.nostra13.universalimageloader.cache.memory.impl.LruMemoryCache; import com.nostra13.universalimageloader.core.DisplayImageOptions; import com.nostra13.universalimageloader.core.ImageLoader; import com.nostra13.universalimageloader.core.ImageLoaderConfiguration; import com.nostra13.universalimageloader.core.assist.ImageScaleType; import com.nostra13.universalimageloader.core.assist.QueueProcessingType; import com.nostra13.universalimageloader.core.display.RoundedBitmapDisplayer; import com.nostra13.universalimageloader.core.download.BaseImageDownloader; public class ImageLoaderUtil { private static ImageLoaderUtil instance; private float density; private ImageLoaderUtil(Context context){ // ImageLoaderConfiguration configuration = new ImageLoaderConfiguration.Builder(this) // .memoryCacheExtraOptions(DisplayUtils.getScreenWidth(this), DisplayUtils.getScreenHeight(this)) // default = device screen dimensions // .threadPoolSize(4) // default // .threadPriority(Thread.NORM_PRIORITY - 2) // default // .memoryCache(new LruMemoryCache(15 * 1024 * 1024)) // .memoryCacheSize(20 * 1024 * 1024) // .tasksProcessingOrder(QueueProcessingType.LIFO) // .defaultDisplayImageOptions(displayOptions) // .writeDebugLogs() // .build(); ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(context) .memoryCacheExtraOptions(480, 800) // default = device screen dimensions .diskCacheExtraOptions(480, 800, null) .threadPoolSize(4) // default .threadPriority(Thread.NORM_PRIORITY - 2) // default .tasksProcessingOrder(QueueProcessingType.LIFO) // default .denyCacheImageMultipleSizesInMemory() .memoryCache(new LruMemoryCache(15 * 1024 * 1024)) .memoryCacheSize(20 * 1024 * 1024) .memoryCacheSizePercentage(13) // default .diskCache(new UnlimitedDiskCache(FileMgr.getInstance(context).createFileDir("imgCache"))) .diskCacheFileNameGenerator(new HashCodeFileNameGenerator()) // default .imageDownloader(new BaseImageDownloader(context)) // default .writeDebugLogs() .build(); ImageLoader.getInstance().init(config); density = MeasureUtil.getInstance(context).getMetrics().density; } public static ImageLoaderUtil getInstance(Context context){ if(instance == null){ synchronized (ImageLoaderUtil.class) { if(instance == null){ instance = new ImageLoaderUtil(context); } } } return instance; } /** * 创建带有圆角的DisplayImageOptions对象 * @param dfImg 默认显示图片ID * @param roundDIP 圆角弧度,单位为dip * @return */ public DisplayImageOptions createRoundedOptions(int dfImg,int roundDIP){ DisplayImageOptions roundedAvatarOptios = new DisplayImageOptions.Builder()// .showImageForEmptyUri(dfImg)// .showImageOnLoading(dfImg)// .showImageOnFail(dfImg)// .resetViewBeforeLoading(true)// .cacheOnDisk(true)// .cacheInMemory(true)// .imageScaleType(ImageScaleType.EXACTLY)// .bitmapConfig(Bitmap.Config.RGB_565)// .considerExifParams(true)// .displayer(new RoundedBitmapDisplayer((int)(roundDIP * density)))// .build(); return roundedAvatarOptios; } /** * 创建不带圆角的DisplayImageOptions * @param dfImg * @return */ public DisplayImageOptions createNoRoundedOptions(int dfImg){ DisplayImageOptions options = new DisplayImageOptions.Builder()// .showImageForEmptyUri(dfImg)// .showImageOnLoading(dfImg)// .showImageOnFail(dfImg)// .resetViewBeforeLoading(true)// .cacheOnDisk(true)// .cacheInMemory(true)// .imageScaleType(ImageScaleType.EXACTLY)//EXACTLY_STRETCHED .bitmapConfig(Bitmap.Config.RGB_565)// .considerExifParams(true)// .build(); return options; } } <file_sep>/app/src/com/litijun/photochooser/utils/FileMgr.java package com.litijun.photochooser.utils; import java.io.File; import android.content.Context; import android.os.Environment; import android.text.TextUtils; public class FileMgr { private static FileMgr instance = null; /** 如果没有sdcard,文件保存路径 */ private static String CACHE_APP_ROOT_DIR = null; /** 文件在sdcard中保存路径 */ private static String SDCARD_APP_ROOT_DIR = null; public static FileMgr getInstance(Context context) { if (instance == null) { synchronized (FileMgr.class) { if (instance == null) { instance = new FileMgr(context); } } } return instance; } private FileMgr(Context context) { String appPkg = context.getPackageName(); SDCARD_APP_ROOT_DIR = Environment.getExternalStorageDirectory() + File.separator // + "Android" + File.separator + "data" + File.separator + appPkg + File.separator; CACHE_APP_ROOT_DIR = Environment.getDataDirectory() + File.separator // + "data" + File.separator + appPkg + File.separator; } /** * 判断sdcard是否可用 */ private boolean hasSDCard() { String status = Environment.getExternalStorageState(); if (!status.equals(Environment.MEDIA_MOUNTED)) { return false; } return true; } /** * 创建项目文件放置的根路径 */ private File createFileDir() { File goalFile = null; if (hasSDCard()) { goalFile = new File(SDCARD_APP_ROOT_DIR); } else { goalFile = new File(CACHE_APP_ROOT_DIR); } if (!goalFile.exists()) { goalFile.mkdirs(); } return goalFile; } public File createFileDir(String fileDir) { File file = new File(createFileDir(), fileDir); if (!file.exists()) { file.mkdirs(); } return file; } /** * 创建具体的文件 * * @param fileDir * 文件放置路径 * @param fileName * 文件名 * @return 目标文件 */ public File createFile(String fileDir, String fileName) { if (null == fileDir || TextUtils.isEmpty(fileDir)) { return new File(createFileDir(), fileName); } else { return new File(createFileDir(fileDir), fileName); } } public File createFile(String fileName) { return createFile(null, fileName); } public File getAppDir() { return createFileDir(); } } <file_sep>/app/src/com/litijun/photochooser/utils/Utils.java package com.litijun.photochooser.utils; import android.content.Context; import android.database.Cursor; import android.net.Uri; import android.provider.MediaStore; import android.util.DisplayMetrics; public class Utils { /** * 获取屏幕尺寸 * * @param context * @param screenSize 屏幕尺寸信息:width = screenSize[0]; heigth = screenSize[1]; */ public static void GetScreenSize(Context context, int[] screenSize) { if (null == screenSize || screenSize.length < 2) { screenSize = new int[2]; } DisplayMetrics displayMetrics = context.getResources().getDisplayMetrics(); screenSize[0] = displayMetrics.widthPixels; screenSize[1] = displayMetrics.heightPixels; } public static String getImagePath(Context context, int firstImageId){ String firstImagePath = ""; Uri uri_temp = Uri.parse("content://media/external/images/media/" + firstImageId); Cursor cur = MediaStore.Images.Media.query(context.getContentResolver(), uri_temp, new String[] { MediaStore.Images.Media.DATA }); if (cur != null && cur.moveToFirst()) { firstImagePath = cur.getString(cur.getColumnIndex(MediaStore.Images.Media.DATA)); } else { firstImagePath = ""; } if(cur != null) cur.close(); return firstImagePath; } } <file_sep>/app/src/com/litijun/photochooser/utils/MeasureUtil.java package com.litijun.photochooser.utils; import java.util.Locale; import android.annotation.TargetApi; import android.content.Context; import android.os.Build; import android.util.DisplayMetrics; @TargetApi(Build.VERSION_CODES.DONUT) public class MeasureUtil { private static MeasureUtil instance = null; private int screenWidth = 0; private int screenHeight = 0; private DisplayMetrics metrics; private MeasureUtil(Context context) { metrics = context.getResources().getDisplayMetrics(); screenWidth = metrics.widthPixels; screenHeight = metrics.heightPixels; DebugLog.v(String.format(Locale.getDefault(),"%d * %d,smallestWidth=%d",screenWidth,screenHeight, screenWidth*160/metrics.densityDpi)); } public static MeasureUtil getInstance(Context context) { if (instance == null) { synchronized (MeasureUtil.class) { if (instance == null) { instance = new MeasureUtil(context); } } } return instance; } public int getScreenWidth() { return screenWidth; } public int getScreenHeight() { return screenHeight; } public DisplayMetrics getMetrics() { return metrics; } } <file_sep>/app/src/com/litijun/photochooser/adapter/AlbumAdapter.java package com.litijun.photochooser.adapter; import java.util.HashMap; import java.util.Map; import android.content.Context; import android.database.Cursor; import android.provider.MediaStore; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.ImageView; import android.widget.TextView; import com.litijun.photochooser.R; import com.litijun.photochooser.adapter.vo.AlbumItem; import com.litijun.photochooser.manager.PhotoChooseMgr; import com.litijun.photochooser.utils.DebugLog; import com.litijun.photochooser.utils.LoadeImageConsts; import com.litijun.photochooser.utils.Utils; public class AlbumAdapter extends BaseAdapter { private Context context; private Map<Integer, AlbumItem> albumMap; private int currAlumbId; public AlbumAdapter(Context context) { this.context = context; this.albumMap = new HashMap<Integer, AlbumItem>(); } @Override public int getCount() { if (albumMap == null) { return 0; } return albumMap.size(); } @Override public AlbumItem getItem(int position) { return albumMap.get(position); } @Override public long getItemId(int position) { return albumMap.get(position).id; } @Override public View getView(int position, View convertView, ViewGroup parent) { ViewHolder holder; if (convertView == null) { holder = new ViewHolder(); convertView = View.inflate(context, R.layout.item_album, null); holder.currFlagView = (ImageView) convertView.findViewById(R.id.alumb_curr_flag); holder.countView = (TextView) convertView.findViewById(R.id.alumb_count); holder.nameView = (TextView) convertView.findViewById(R.id.alubm_name); holder.imageView = (ImageView) convertView.findViewById(R.id.alumb_picture); convertView.setTag(holder); } else { holder = (ViewHolder) convertView.getTag(); } if (albumMap != null) { DebugLog.d("position = " + position); AlbumItem albumItem = getItem(position); holder.nameView.setText(albumItem.albumName); holder.countView.setText(albumItem.imageCount + "张"); holder.currFlagView.setVisibility(albumItem.id == this.currAlumbId ? View.VISIBLE : View.GONE); PhotoChooseMgr.getInstance(context).dispalyImage(albumItem.firstImagePath, holder.imageView); } return convertView; } public void setCurrAlumbId(int currAlumbId) { this.currAlumbId = currAlumbId; notifyDataSetChanged(); } public void setAlbumCursor(Cursor albumCursor) { albumMap.clear(); if (albumCursor != null) { DebugLog.d("loadCursor Size = " + albumCursor.getCount()); for (int i = 0, count = albumCursor.getCount(); i < count; i++) { albumCursor.moveToPosition(i); AlbumItem albumItem = new AlbumItem(); albumItem.firstImageId = albumCursor.getInt(albumCursor.getColumnIndex(MediaStore.Images.ImageColumns._ID)); albumItem.firstImagePath = Utils.getImagePath(context, albumItem.firstImageId); albumItem.albumName = albumCursor.getString(albumCursor.getColumnIndex(MediaStore.Images.ImageColumns.BUCKET_DISPLAY_NAME)); albumItem.id = albumCursor.getInt(albumCursor.getColumnIndex(MediaStore.Images.ImageColumns.BUCKET_ID)); albumItem.imageCount = albumCursor.getInt(albumCursor.getColumnIndex("allbum_count")); albumMap.put(i + 1, albumItem); } AlbumItem firstItem = new AlbumItem(); firstItem.id = LoadeImageConsts.LOADER_IMAGE_CURSOR; firstItem.albumName = context.getString(R.string.all_photos); int amount =0; for (Map.Entry<Integer, AlbumItem> entry : albumMap.entrySet()) { Integer key = entry.getKey(); AlbumItem value = entry.getValue(); amount += value.imageCount; if(key == 1){ firstItem.firstImageId = value.firstImageId; firstItem.firstImagePath = value.firstImagePath; } } firstItem.imageCount=+amount; setFirstItem(false, firstItem); DebugLog.d("albumMap Size = " + albumMap.size()); notifyDataSetChanged(); } } public void setFirstItem(boolean isreal, AlbumItem item) { AlbumItem firstItem = albumMap.get(0); if(firstItem == null || isreal){ albumMap.put(0, item); } setCurrAlumbId(item.id); notifyDataSetChanged(); } class ViewHolder { TextView nameView; TextView countView; ImageView currFlagView; ImageView imageView; } } <file_sep>/app/build.gradle apply plugin: 'com.android.application' android { compileSdkVersion 19 buildToolsVersion "21.1.2" defaultConfig { applicationId "com.litijun.photochooser" minSdkVersion 11 targetSdkVersion 14 versionCode 1 versionName "1.0" } lintOptions { checkReleaseBuilds false abortOnError false } dexOptions { incremental false } signingConfigs { debug { storeFile file("debug.keystore") } myConfig { storeFile file("/Users/Emerson/Desktop/Works/APK/ITV_Launcher.keystore") storePassword "<PASSWORD>" keyAlias 'itv_launcher' keyPassword "<PASSWORD>" } } buildTypes { debug { // 显示Log buildConfigField "boolean", "LOG_DEBUG", "true" versionNameSuffix "-debug" minifyEnabled false zipAlignEnabled false shrinkResources false signingConfig signingConfigs.debug } release { // 不显示Log buildConfigField "boolean", "LOG_DEBUG", "false" //混淆 minifyEnabled true //Zipalign优化 zipAlignEnabled true // 移除无用的resource文件 shrinkResources true //前一部分代表系统默认的android程序的混淆文件,该文件已经包含了基本的混淆声明 proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.txt' signingConfig signingConfigs.myConfig } } sourceSets { main { manifest.srcFile 'AndroidManifest.xml' java.srcDirs = ['src'] resources.srcDirs = ['src'] aidl.srcDirs = ['src'] renderscript.srcDirs = ['src'] res.srcDirs = ['res'] assets.srcDirs = ['assets'] } } } dependencies { compile fileTree(dir: 'libs', include: ['*.jar']) //compile 'com.android.support:appcompat-v7:20.0.0' //compile 'com.android.support:support-v4:20.0.0' compile files('libs/universal-image-loader-1.9.5.1.jar') } <file_sep>/README.md # PhotoChooser To simulate the function of choosing photos like Wechat (realize multiple photos etc.) <file_sep>/app/src/com/litijun/photochooser/PhotoChooseActivity.java package com.litijun.photochooser; import android.database.Cursor; import android.os.Bundle; import android.provider.MediaStore; import android.support.v4.app.FragmentActivity; import android.support.v4.app.FragmentTransaction; import android.support.v4.app.LoaderManager; import android.support.v4.content.CursorLoader; import android.support.v4.content.Loader; import android.view.View; import android.widget.AdapterView; import android.widget.Button; import android.widget.GridView; import android.widget.TextView; import android.widget.Toast; import com.litijun.photochooser.adapter.PictureAdapter; import com.litijun.photochooser.adapter.vo.AlbumItem; import com.litijun.photochooser.adapter.vo.ImageItem; import com.litijun.photochooser.fragment.PreviewFragment; import com.litijun.photochooser.fragment.SelectAlbumFragment; import com.litijun.photochooser.manager.PhotoChooseMgr; import com.litijun.photochooser.utils.DebugLog; import com.litijun.photochooser.utils.LoadeImageConsts; import com.litijun.photochooser.utils.Utils; public class PhotoChooseActivity extends FragmentActivity implements View.OnClickListener,LoaderManager.LoaderCallbacks<Cursor> { public static final String[] LOADING_COLUMN = { MediaStore.Images.ImageColumns._ID,// MediaStore.Images.Media.DATA, // MediaStore.Images.ImageColumns.DISPLAY_NAME,// MediaStore.Images.Media.BUCKET_ID, }; private Integer albumId; private Button header_back; private TextView header_title; private Button header_right_button; private GridView gridView; private PictureAdapter adapter; private SelectAlbumFragment albumFragment; private PreviewFragment previewFragment; private Cursor cursor; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_choose_image); PhotoChooseMgr.getInstance(getApplication()).setMaxSelectSize(6); gridView = (GridView) findViewById(R.id.choose_image_gridview); adapter = new PictureAdapter(this); albumFragment = (SelectAlbumFragment) getSupportFragmentManager().findFragmentById(R.id.choose_image_album); refreshGridViewByAlbumId(LoadeImageConsts.LOADER_IMAGE_CURSOR); gridView.setAdapter(adapter); gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { if (position == 0 && PhotoChooseMgr.getInstance(getApplication()).isTakePhoto()) { Toast.makeText(PhotoChooseActivity.this, "拍照", Toast.LENGTH_LONG).show(); } else { ImageItem item = adapter.getItem(position); previewFragment = new PreviewFragment(); Bundle args = new Bundle(); args.putInt("offset", PhotoChooseMgr.getInstance(getApplication()).isTakePhoto() ? position - 1 : position); args.putBoolean("show_all", true); args.putSerializable("ImageItem", item); previewFragment.setArguments(args); showPreviewFragment(previewFragment); } } }); initHeader(); } public void refreshGridViewByAlbumId(int id) { DebugLog.d("album id = " + id); if (id == LoadeImageConsts.LOADER_IMAGE_CURSOR) { PhotoChooseMgr.getInstance(getApplication()).setTakePhoto(PhotoChooseMgr.getInstance(getApplication()).isTakePhoto()); }else{ PhotoChooseMgr.getInstance(getApplication()).setTakePhoto(false); } this.albumId = id; getSupportLoaderManager().initLoader(id, null, this); } private void initHeader() { header_back = (Button) findViewById(R.id.header_back); header_back.setOnClickListener(this); header_title = (TextView) findViewById(R.id.header_title); header_title.setText("选择图片"); header_right_button = (Button) findViewById(R.id.header_right_button); header_right_button.setOnClickListener(this); changeSelectedCount(); } public void changeSelectedCount(){ PhotoChooseMgr imageLoaderMgr = PhotoChooseMgr.getInstance(getApplication()); int selectedCount = imageLoaderMgr.getSelectCount(); if(selectedCount>0) header_right_button.setText(getString(R.string.select_done, selectedCount, imageLoaderMgr.getMaxSelectSize())); else header_right_button.setText("完成"); } @Override public Loader<Cursor> onCreateLoader(int id, Bundle args) { DebugLog.d("album id = " + id); String selection = null; String[] selectionArgs = null; if (albumId != null && albumId != 1) { selection = "bucket_id=?"; selectionArgs = new String[] { "" + id }; } String orderBy = MediaStore.Images.Media.DATE_TAKEN + " DESC";//MediaStore.Images.Media._ID + " ASC"; return new CursorLoader(this, MediaStore.Images.Media.EXTERNAL_CONTENT_URI, LOADING_COLUMN, selection, selectionArgs, orderBy); } @Override public void onLoadFinished(Loader<Cursor> loader, Cursor cursor) { // 第一次默认取全部图片,所以相册第一项为所有图片 if (loader.getId() == LoadeImageConsts.LOADER_IMAGE_CURSOR) { AlbumItem item = new AlbumItem(); cursor.moveToPosition(0); item.firstImageId = cursor.getInt(cursor.getColumnIndex(MediaStore.Images.Media._ID)); item.firstImagePath = Utils.getImagePath(getApplication(), item.firstImageId); item.id = loader.getId(); item.imageCount = cursor.getCount(); item.albumName = getString(R.string.all_photos); albumFragment.setFirstItem(item); adapter.setLoadCursor(cursor); } else { adapter.setLoadCursor(cursor); } this.cursor = cursor; } @Override public void onLoaderReset(Loader<Cursor> loader) { if (this.cursor != null && !this.cursor.isClosed()) { this.cursor.close(); } } @Override public void onBackPressed() { if(previewFragment != null){ FragmentTransaction ft = getSupportFragmentManager().beginTransaction(); ft.setCustomAnimations(R.anim.slide_up,R.anim.slide_down); ft.remove(previewFragment).commit(); previewFragment = null; adapter.notifyDataSetChanged(); changeSelectedCount(); return; } super.onBackPressed(); } @Override public void onClick(View v) { switch (v.getId()){ case R.id.header_back: case R.id.header_right_button: onBackPressed(); break; } } private void showPreviewFragment(PreviewFragment previewFragment){ FragmentTransaction ft = getSupportFragmentManager().beginTransaction(); ft.setCustomAnimations(R.anim.slide_up, R.anim.slide_down); ft.replace(R.id.preview, previewFragment).commit(); } public void showPreview() { if(PhotoChooseMgr.getInstance(getApplication()).getSeletectList().size()<=0){ Toast.makeText(PhotoChooseActivity.this, getString(R.string.have_no_chosen), Toast.LENGTH_LONG).show(); }else{ previewFragment = new PreviewFragment(); showPreviewFragment(previewFragment); } } }
2aa92ec269a72191cf89f4ec628ea09e6d313d2e
[ "Markdown", "Java", "Gradle" ]
9
Java
TomIsYourName/PhotoChooser
0ee95468b8fd159cab9dc3a9e3a8cf075b82419f
f444459f942ec7be79f105ac84fc3ed7952d80cd
refs/heads/master
<repo_name>sergkr/jsnlog<file_sep>/src/JSNLog.TestSite/Logic/TestUtils.cs using System.Collections.Generic; using System.Text; using JSNLog.Tests.Common; namespace JSNLog.TestSite.Logic { public class TestUtils { /// <summary> /// Generates JS to store the timestamp for a log action /// </summary> /// <param name="seq"> /// The index into tests of the log action for which the timestamp is stored. /// </param> /// <returns></returns> private static string StoreTimestampJs(int seq) { string js = string.Format("__timestamp{0} = (new Date).getTime();", seq); return js; } /// <summary> /// Generates JS expression to get the timestamp for a log action /// </summary> /// <param name="seq"></param> /// <returns></returns> private static string GetTimestampJs(int seq) { string js = string.Format("__timestamp{0}", seq); return js; } private static string Msg(int seq, int level, string logger) { return string.Format("msg{0} level: {1}, logger: {2}", seq, level, logger); } /// <summary> /// Creates JSON with all log items expected for a given check number. /// </summary> /// <param name="checkNbr"></param> /// <param name="tests"></param> /// <returns></returns> private static string Expected(int checkNbr, IEnumerable<T> tests) { var sb = new StringBuilder(); sb.AppendLine(@"["); int seq = 0; bool first = true; foreach (T t in tests) { if (t.CheckExpected == checkNbr) { string msg = t.ExpectedMsg ?? Msg(seq, t.Level, t.Logger); string timestamp = GetTimestampJs(seq); sb.AppendLine(string.Format(" {0}{{", first ? "" : ",")); sb.AppendLine(string.Format(" l: {0},", t.Level)); sb.AppendLine(string.Format(" m: '{0}',", msg)); sb.AppendLine(string.Format(" n: '{0}',", t.Logger)); sb.AppendLine(string.Format(" t: {0}", timestamp)); sb.AppendLine(" }"); first = false; } seq++; } sb.AppendLine("]"); string js = sb.ToString(); return js; } /// <summary> /// Returns all javascript to set up a test. /// The generated javascript is within an immediately executing function, so it sits in its own namespace. /// /// </summary> /// <param name="configXml"> /// String with xml with the JSNLog root element, as would be used in a web.config file. /// </param> /// <param name="userIp"> /// Simulated IP address of the client. /// </param> /// <param name="requestId"> /// Simulated request id. /// </param> /// <returns></returns> public static string SetupTest(string userIp, string requestId, string configXml, IEnumerable<T> tests) { var sb = new StringBuilder(); // Set config cache in JavascriptLogging to contents of xe // This essentially injects the config XML into JSNLog (the same way as when reading from web.config). CommonTestHelpers.SetConfigCache(configXml); var jsnlogJavaScriptConfig = JSNLog.JavascriptLogging.Configure(); sb.AppendLine(jsnlogJavaScriptConfig); sb.AppendLine(@"<script type=""text/javascript"">"); sb.AppendLine("(function () {"); sb.AppendLine(string.Format( "JL.setOptions({{ 'defaultBeforeSend': TestUtils.beforeSend, 'clientIP': '{0}', 'requestId': '{1}' }});", userIp, requestId)); int seq = 0; foreach (T t in tests) { if (t.Level > -1) { // Level given, so generate call to logger. string msg = t.LogObject ?? @"""" + Msg(seq, t.Level, t.Logger) + @""""; string logCallJs = string.Format(@"JL(""{0}"").log({1}, {2});", t.Logger, t.Level, msg); string storeTimestampJs = StoreTimestampJs(seq); sb.AppendLine(logCallJs + " " + storeTimestampJs); } if (t.CheckNbr > -1) { // CheckNbr given, so do a check // Create JSON object with all expected log entries string expected = Expected(t.CheckNbr, tests); // Generate check js string checkJs = string.Format("TestUtils.Check('{0}', {1}, {2});", t.CheckAppender, t.CheckNbr, expected); sb.AppendLine(""); sb.AppendLine(checkJs); sb.AppendLine("// ----------------------"); sb.AppendLine(""); } if (!string.IsNullOrEmpty(t.Header)) { sb.AppendLine(string.Format("$('body').append('<h3>{0}</h3>');", t.Header)); } seq++; } // Remove the "running" heading. If the tests somehow crash, we won't get here and the running header will remain, // showing something is wrong. sb.AppendLine("$('#running').remove();"); sb.AppendLine("})();"); sb.AppendLine("</script>"); string js = sb.ToString(); return js; } } }<file_sep>/src/JSNLog.Tests/TestConstants.cs using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace JSNLog.Tests { public class TestConstants { public const string _jsnlogDirectory = @"C:\Dev\JSNLog\"; // All tests here write a partial with the complete demo html. // The partials are written to directory: public const string _demosDirectory = _jsnlogDirectory + @"jsnlog.website\WebSite\Views\Shared\Demos"; public const string _jsnlogDllDirectory = _jsnlogDirectory + @"jsnlog\artifacts\bin\JSNLog\Debug\dnx451\JSNLog.dll"; } } <file_sep>/src/JSNLog.TestSite/scripts/TestUtils.ts /// <reference path="jquery.d.ts"/> /// <reference path="../../../../jsnlog.js/jsnlog.ts"/> module TestUtils { export function Check(checkAppenderUrlPath: string, checkNbr: number, expected: JL.LogItem[]) { var checkAppenderUrl = 'http://dummy.com/' + checkAppenderUrlPath; // An appender only calls beforeSend when it tries to send a log request. // So if the appender never tries to send anything, than actual will be undefined. var actual: JL.LogItem[] = (<any>window)[checkAppenderUrl] || []; var resultDiv: JQuery; var expectedString = JSON.stringify(expected); var actualString = JSON.stringify(actual); // class="error-occurred" is used by the integration tests. // If an element with that class exists on the page, the test is taken to have failed. var comparisonResult: string = LogItemArraysCompareResult(expected, actual); if (comparisonResult) { resultDiv = $('<table style="border-top: 3px red solid" class="error-occurred" />'); resultDiv.append('<tr><td>Error at Check</td><td>' + checkNbr + '</td></tr>'); resultDiv.append('<tr><td valign="top" colspan=\'2\'>' + comparisonResult + '</td></tr>'); resultDiv.append('<tr><td valign="top">Expected:</td><td>' + expectedString + '</td></tr>'); resultDiv.append('<tr><td valign="top">Actual:</td><td>' + actualString + '</td></tr></table>'); } else { resultDiv = $('<div style="border-top: 3px green solid" >Passed: ' + checkNbr + '</div>'); } $('body').append(resultDiv); (<any>window)[checkAppenderUrl] = []; } export function beforeSend(xhr: any) { var appenderThis = this; xhr.send = function (json) { if (!(<any>window)[appenderThis.url]) { (<any>window)[appenderThis.url] = []; } var item = JSON.parse(json); (<any>window)[appenderThis.url] = (<any>window)[appenderThis.url].concat(item.lg); }; } function FormatResult(idx: number, fieldName: string, expected: string, actual: string): string { return "idx: " + idx + "</br>field: " + fieldName + "</br>expected: " + expected +"</br>actual: "+ actual; } // Returns string with comparison result. // Returns empty string if expected and actual are equal. function LogItemArraysCompareResult(expected: JL.LogItem[], actual: JL.LogItem[]): string { var nbrLogItems = expected.length; var i; if (nbrLogItems != actual.length) { return "Actual nbr log items (" + actual.length + ") not equal expected nbr log items (" + nbrLogItems + ")"; } for (i = 0; i < nbrLogItems; i++) { if (expected[i].l != actual[i].l) { return FormatResult(i, "level", expected[i].l.toString(), actual[i].l.toString()); } var m: any = expected[i].m; var match = false; if (m instanceof RegExp) { match = m.test(actual[i].m); } else { match = (expected[i].m == actual[i].m); } if (!match) { return FormatResult(i, "msg", expected[i].m, actual[i].m); } if (expected[i].n != actual[i].n) { return FormatResult(i, "logger name", expected[i].n, actual[i].n); } // Timestamps are precise to the ms. // Allow a small difference between actual and expected, because we record the timestamp // a bit later then when jsnlog produces the log request. var allowedDifferenceMs = 10; if (Math.abs(expected[i].t - actual[i].t) > allowedDifferenceMs) { return FormatResult(i, "timestamp", expected[i].t.toString(), actual[i].t.toString()); } } return ""; } }
9209a81fa11da3e0106efc8461228039469a9b44
[ "C#", "TypeScript" ]
3
C#
sergkr/jsnlog
a5df5549be2562a538ec9da437a94dfa5ec4b1e1
ef060d2b6dc314f875908b235698c3f4272a3162
refs/heads/master
<file_sep>/** * Created by hj on 2015/7/21. */ var server = require("./server"); var router = require("./router"); var requestHandlers = require("./requestHandlers"); var handle={}; handle["/"] = requestHandlers.start; handle["/start"] = requestHandlers.start; handle["/upload"] = requestHandlers.upload; handle["/input.html"] = requestHandlers.start; handle["/max-age"] = requestHandlers.testHeader; server.start(router.route,handle);
d40505aa88bb131a19b6b7475412f2545a214e28
[ "JavaScript" ]
1
JavaScript
Yagami2013/sdk-http-test
a6ca2e1e623726f7fe578f5a442f604009ff37be
71af4d210c102c75da03d3b4ecb6b0bd8ad996eb
refs/heads/master
<repo_name>husaynhakeem/the-odin-project<file_sep>/ruby/03-basic-ruby-projects/01-caesar-cipher/CaesarCipher.rb LOWER_A = 'a'.ord LOWER_Z = 'z'.ord UPPER_A = 'A'.ord LETTERS = 26 def caeser_cipher(string, shift) return string.split("").map { |c| shift(c, shift) }.join("") end def shift(char, shift) if !isLetter?(char) return char elsif isLowerCase?(char) return shiftLetter(char, shift, LOWER_A) else return shiftLetter(char, shift, UPPER_A) end end def shiftLetter(char, shift, start) char_in_0_base = char.ord + shift - start char_in_0_26_base = char_in_0_base % LETTERS char_in_a_z_base = char_in_0_26_base + start return char_in_a_z_base.chr end def isLetter?(char) return (UPPER_A..LOWER_Z).include?(char.ord) end def isLowerCase?(char) return (LOWER_A..LOWER_Z).include?(char.ord) end<file_sep>/ruby/04-intermediate-ruby/02-project-oop/victory_verifier.rb module VictoryVerifier public def verify(board, row, col) is_row_complete(board, row) || is_column_complete(board, col) || (row == col && is_diagonal_complete(board)) || (row + col == board.length - 1 && is_reverse_diagonal_complete(board)) end private def is_row_complete(board, row) first = board[row][0] cols = board[row].length 1.upto(cols - 1) do |col| return false if first != board[row][col] end true end def is_column_complete(board, col) first = board[0][col] rows = board.length 1.upto(rows - 1) do |row| return false if first != board[row][col] end true end def is_diagonal_complete(board) first = board[0][0] rows = board.length 1.upto(rows - 1) do |index| return false if first != board[index][index] end true end def is_reverse_diagonal_complete(board) size = board.length first = board[0][size -1] 1.upto(size - 1) do |index| return false if first != board[index][size - 1 - index] end true end end<file_sep>/ruby/05-a-bit-of-computer-science/03-recursion/merge_sort.rb def merge_sort(array) merge_sort_internal(array, 0, array.length - 1) end def merge_sort_internal(array, left, right) if left > right return [] end if left == right return [array[left]] end middle = (left + right) / 2 left_array = merge_sort_internal(array, left, middle) right_array = merge_sort_internal(array, middle + 1, right) merge(left_array, right_array) end def merge(left_array, right_array) merged = [] left_index = 0 right_index = 0 while left_index < left_array.length && right_index < right_array.length if left_array[left_index] < right_array[right_index] merged << left_array[left_index] left_index += 1 else merged << right_array[right_index] right_index += 1 end end left_index.upto(left_array.length - 1) do |i| merged << left_array[i] end right_index.upto(right_array.length - 1) do |i| merged << right_array[i] end merged end <file_sep>/ruby/04-intermediate-ruby/05-hangman/game_session.rb require './session_repo.rb' require './session.rb' class GameSession $save_and_quit = "0" def initialize(session, session_repo) @remaining_attempts = session.remaining_attempts @secret_word = session.secret_word @guesses = session.guesses @session_repo = session_repo end public def play save_and_quit = false while !save_and_quit && !has_user_won && @remaining_attempts > 0 puts "\n#{@guesses}\nRemaining attempts: #{@remaining_attempts}\n\n" # Allow user to save and quit, or to continue playing print "To save and quit, enter #{$save_and_quit}. Or continue playing and enter a character: " input = gets.chomp.to_s # If the user chooses to save and quit if input == $save_and_quit save_session save_and_quit = true elsif is_valid_guess?(input) # Decrement remaining attempts @remaining_attempts -= 1 # Verify the user's guess verify_guess(input) else puts "Invalid input. Try again" end end if has_user_won puts "\nYou've won!\n\n" elsif @remaining_attempts == 0 puts "\nNo more remaining attempts. You've lost! The word was #{@secret_word}.\n\n" end end private # Verifies and returns whether the guess was correct def verify_guess(guess) if @secret_word.include?(guess) # Replace all occurrences of `guess` in guesses @secret_word.each_char.each_with_index do |char, index| if char == guess @guesses[index] = char end end # Display correct message + guesses + remaining attempts puts "Correct guess!" true else # Display error message + guesses + remaining attempts puts "Wrong guess!" false end end def is_valid_guess?(input) input.match?(/\A[a-z]\z/) end def save_session session = Session.new(@remaining_attempts, @secret_word, @guesses) @session_repo.save(session) puts "Your game has been saved!" end def has_user_won !@guesses.include?("_") end end<file_sep>/ruby/04-intermediate-ruby/02-project-oop/game.rb require './victory_verifier.rb' require './game.rb' require './board.rb' require './player.rb' class Game include VictoryVerifier def initialize(size, player1, player2) @board = Board.new(size) @player1 = Player.new($player_1, player1) @player2 = Player.new($player_2, player2) @turn = @player1 end public def restart @board.reset end def move(row, col) @board.move(row, col, @turn.id) @board.display # Check for a winner game_over = verify(@board.board, row, col) if game_over == true puts "#{@turn.name} has won!" else @turn = @turn == @player1 ? @player2 : @player1 end end end<file_sep>/README.md # The Odin Project This repo contains my solutions for problems from the [Ruby](https://www.theodinproject.com/courses/ruby-programming) and [Ruby on Rails](https://www.theodinproject.com/courses/ruby-on-rails) curriculums from The Odin's Project. <file_sep>/ruby/03-basic-ruby-projects/02-substrings/Substrings.rb # Returns a hash listing each substring that was found in `string` and how many times it was found in `dictionary`. # Params: # +string+:: The original String # +dictionary+:: Contains valid substrings, all downcased def substrings(string, dictionary) hash = Hash.new(0) string.split(" ") .map { |sub| get_all_unique_substrings(sub.downcase) } .flatten .each { |sub| hash[sub] += 1 if dictionary.include? sub } return hash end # Return all unique substrings from `string` def get_all_unique_substrings(string) indices = (0..string.length).to_a indices.product(indices) .reject { |i, j| i > j } .map { |i, j| string[i..j] } .uniq end<file_sep>/ruby/04-intermediate-ruby/05-hangman/game.rb require './session_repo.rb' require './game_session.rb' class Game $dictionary_file_name = "dictionary.txt" $secret_word_length_min = 5 $secret_word_length_max = 12 $attempts_initial = 5 $start_new_game = 0 $continue_previous_game = 1 public def play session_repo = SessionRepo.new while true print "To start a new game, enter #{$start_new_game}. To continue a previous game, enter #{$continue_previous_game}: " begin input = gets.chomp.to_i # Make sure input is valid unless input == $start_new_game || input == $continue_previous_game raise ArgumentError("Invalid input") end # Choose a secret word secret_word = select_secret_word # Prepare the game session session = get_session(input, secret_word, session_repo) # Start game session game_session = GameSession.new(session, session_repo) game_session.play rescue => exception puts "Invalid input. Try again. #{exception}" end end end private def select_secret_word secret_word = nil File.open($dictionary_file_name, "r") do |file| lines = file.readlines while secret_word.nil? random_line_index = (rand * lines.length).to_i random_word = lines[random_line_index] secret_word = random_word if random_word.length >= $secret_word_length_min && random_word.length <= $secret_word_length_max end end secret_word.strip.downcase end def get_session(user_input, secret_word, session_repo) if user_input == $start_new_game new_session(secret_word) else previous = session_repo.restore if previous.nil? new_session(secret_word) else previous end end end def new_session(secret_word) Session.new($attempts_initial, secret_word, "".rjust(secret_word.length, "_")) end end<file_sep>/ruby/05-a-bit-of-computer-science/06-data-structures-and-algorithms/assignment_1/node.rb class Node include Comparable attr_reader :value attr_accessor :left, :right def initialize(value) @value = value @left = nil @right = nil end def <=>(other) self.value <=> other.value end end<file_sep>/ruby/04-intermediate-ruby/02-project-oop/main.rb require './game.rb' game = Game.new(3, "Hus", "Yasin") game.move(0, 0) game.move(0, 1) game.move(1, 1) game.move(0, 2) game.move(2, 2) <file_sep>/ruby/05-a-bit-of-computer-science/03-recursion/fibonacci_sequence_iterative.rb def fibonacci_sequence_iterative(n) sequence = [] 0.upto(n) do |i| sequence << fibonacci(i) end sequence end def fibonacci(n) fib = [0, 1] 2.upto(n) do |i| fib << fib[i - 1] + fib[i - 2] end fib[n] end <file_sep>/ruby/04-intermediate-ruby/02-project-oop/board.rb class Board $no_player = 0 $player_1 = 1 $player_2 = 2 $players = {$no_player => " ", $player_1 => "x", $player_2 => "o"} attr_reader :board def initialize(size) @size = size reset_board end public def display 0.upto(@size - 1) do |row| # Display a row + return to a new line at the end 0.upto(@size - 1) do |col| print " #{@board[row][col]} " print "|" if col < @size - 1 end puts "" # Draw a line to separate 2 different rows + return to a new line at the end if row < @size - 1 0.upto(@size - 1) do |col| print "---" print "|" if col < @size - 1 end puts "" end end puts "" end def move(row, col, player_id) @board[row][col] = $players[player_id] end def reset reset_board end private def reset_board @board = Array.new(@size) { Array.new(@size, $players[$no_player]) } end end<file_sep>/ruby/03-basic-ruby-projects/03-stock-picker/StockPicker.rb INVALID_PRICE = -1 INVALID_INDEX = -1 def stock_picker(prices) # Build max array maxArray = Array.new maxArray.unshift(INVALID_PRICE) # Populate max array (prices.length - 1).downto(1) do |i| max = maxArray.first > prices[i] ? maxArray.first : prices[i] maxArray.unshift(max) end # Find largest difference and its index maxIndex = 0 maxDiff = maxArray.first - prices.first 1.upto(prices.length - 1) do |i| diff = maxArray[i] - prices[i] if diff > maxDiff maxIndex = i maxDiff = diff end end # maxIndex is the index of the day to buy, find the index of the day to sell (maxIndex + 1).upto(prices.length - 1) do |i| if prices[i] == maxDiff + prices[maxIndex] return [maxIndex, i] end end # Should not reach this point return [INVALID_INDEX, INVALID_INDEX] end<file_sep>/ruby/05-a-bit-of-computer-science/03-recursion/fibonacci_sequence_recursive.rb def fibonacci_sequence_recursive(n) sequence = [] 0.upto(n) do |i| sequence << fibonacci(i) end sequence end def fibonacci(n) if n == 0 || n == 1 return n end fibonacci(n - 1) + fibonacci(n - 2) end<file_sep>/ruby/05-a-bit-of-computer-science/05-linked-lists/main.rb require './linked_list.rb' list = LinkedList.new puts list.to_s # "" puts list.size # 0 list.append(3) # [3] puts list.to_s list.append(4) # [3, 4] puts list.to_s list.prepend(1) # [1, 3, 4] puts list.to_s list.insert_at(2, 1) # [1, 2, 3, 4] puts list.to_s list.insert_at(5, 20) # [1, 2, 3, 4, 5] puts list.to_s puts list.to_s # 1 -> 2 -> 3 -> 4 -> 5 puts list.size # 5 puts list.pop # 5 puts list.to_s # 1 -> 2 -> 3 -> 4 puts list.size # 4 puts list.head # 1 puts list.tail # 4 puts list.contains?(3) # true puts list.contains?(30) # false puts list.find(2) # 1 puts list.find(20) # nil <file_sep>/ruby/04-intermediate-ruby/05-hangman/session.rb class Session attr_reader :remaining_attempts, :secret_word, :guesses def initialize(remaining_attempts, secret_word, guesses) @remaining_attempts = remaining_attempts @secret_word = secret_word @guesses = guesses end end<file_sep>/ruby/03-basic-ruby-projects/04-bubble-sort/BubbleSort.rb def bubble_sort(array) sorted = false until sorted == true # Before going through the array, assume it's sorted sorted = true # Go through the array, if neighboring elements are not sorted, swap them 0.upto(array.length - 2) do |i| if array[i] > array[i + 1] temp = array[i] array[i] = array[i + 1] array[i + 1] = temp # Since a swap has been made, set `sorted` to false sorted = false end end end return array end<file_sep>/ruby/05-a-bit-of-computer-science/05-linked-lists/linked_list.rb require './node.rb' class LinkedList attr_reader :size, :head, :tail def initialize @tail = nil @head = nil @size = 0 end # Add a new node at the end of the list def append(value) node = Node.new(value) unless @tail.nil? @tail.next = node end @tail = node if @head.nil? @head = node end @size += 1 end # Add a new node at the start of the list def prepend(value) node = Node.new(value) node.next = @head @head = node if @tail.nil? @tail = node end @size += 1 end # Returns the node at `index` def at(index) if index > @size return nil end runner = @head index.times.each do |i| runner = runner.next end runner end # Remove the last node from the list def pop if @size == 0 return end previous = nil runner = @head (@size - 1).times.each do |i| previous = runner runner = runner.next end if previous.nil? @head = nil @tail = nil else previous.next = nil @tail = previous end @size -= 1 runner end # Returns whether the list contains `value` def contains?(value) runner = @head until runner.nil? if runner.value == value return true end runner = runner.next end false end # Returns the index of the first occurrence of `value`, or nil def find(value) index = 0 runner = @head until runner.nil? if runner.value == value return index end index += 1 runner = runner.next end nil end # Returns a string representation of the list def to_s string = "" runner = @head 0.upto(@size - 1).each do |index| string << runner.value.to_s if index < @size - 1 string << " -> " end runner = runner.next end string end # Insert `value` at the index def insert_at(value, index) if index == 0 prepend(value) elsif index >= @size append(value) else previous = nil runner = @head index.times do |i| previous = runner runner = runner.next end node = Node.new(value) previous.next = node node.next = runner @size += 1 end end # Remove the node at `index` def remove_at(index) if index >= index pop nil elsif index == 0 if @head.nil? # Do nothing elsif @head == @tail @head = nil @tail = nil @size -= 1 else @head = @head.next @size -= 1 end else previous = nil runner = @head index.times.each do |i| previous = runner runner = runner.next end previous.next = runner.next @size -= 1 end end end<file_sep>/ruby/05-a-bit-of-computer-science/06-data-structures-and-algorithms/assignment_1/spec/binary_search_tree_spec.rb require_relative '../binary_search_tree' describe BinarySearchTree do describe "#inorder" do it "returns the inorder traversal of the binary tree" do array = [1, 2, 3, 4, 5, 6, 7, 3, 4, 5, 6, 1, 2, 3, 4, 5, 6, 7, 3, 4, 2, 2, 4, 5] bst = BinarySearchTree.new(array) expected = [1, 2, 3, 4, 5, 6, 7] expect(bst.inorder).to eql(expected) end end describe "#preorder" do it "returns the preorder traversal of the binary tree" do array = [1, 2, 3, 4, 5, 6, 7, 3, 4, 5, 6, 1, 2, 3, 4, 5, 6, 7, 3, 4, 2, 2, 4, 5] bst = BinarySearchTree.new(array) expected = [4, 2, 1, 3, 6, 5, 7] expect(bst.preorder).to eql(expected) end end describe "#postorder" do it "returns the postorder traversal of the binary tree" do array = [1, 2, 3, 4, 5, 6, 7, 3, 4, 5, 6, 1, 2, 3, 4, 5, 6, 7, 3, 4, 2, 2, 4, 5] bst = BinarySearchTree.new(array) expected = [1, 3, 2, 5, 7, 6, 4] expect(bst.postorder).to eql(expected) end end describe "#to_s" do it "returns the string representation of the binary tree" do array = [1, 2, 3, 4, 5, 6, 7, 3, 4, 5, 6, 1, 2, 3, 4, 5, 6, 7, 3, 4, 2, 2, 4, 5] bst = BinarySearchTree.new(array) expected = "[1, 2, 3, 4, 5, 6, 7]" expect(bst.to_s).to eql(expected) end end describe "#build_tree" do it "returns the root node of the built tree. This tree should be balanced and mustn't contain dupes" do bst = BinarySearchTree.new array = [1, 2, 3, 4, 5, 6, 7, 3, 4, 5, 6, 1, 2, 3, 4, 5, 6, 7, 3, 4, 2, 2, 4, 5] expected = 4 expect(bst.build_tree(array).value).to eql(expected) end end describe "#depth" do it "returns the depth of the BST" do array = [1, 2, 3, 4, 5, 6, 7, 3, 4, 5, 6, 1, 2, 3, 4, 5, 6, 7, 3, 4, 2, 2, 4, 5] bst = BinarySearchTree.new(array) expected = 3 expect(bst.depth).to eql(expected) end end describe "#level_order w/ block" do it "returns one [node, level] pair at a time from a BFS traversal of the BST" do array = [1, 2, 3, 4, 5, 6, 7, 3, 4, 5, 6, 1, 2, 3, 4, 5, 6, 7, 3, 4, 2, 2, 4, 5] bst = BinarySearchTree.new(array) bfs = [] bst.level_order { |value, level| bfs << [value, level] } expected = [[4, 1], [2, 2], [6, 2], [1, 3], [3, 3], [5, 3], [7, 3]] expect(bfs).to eql(expected) end end describe "#level_order w/o block" do it "returns an array of [node, level] pairs from a BFS traversal of the BST" do array = [1, 2, 3, 4, 5, 6, 7, 3, 4, 5, 6, 1, 2, 3, 4, 5, 6, 7, 3, 4, 2, 2, 4, 5] bst = BinarySearchTree.new(array) expected = [[4, 1], [2, 2], [6, 2], [1, 3], [3, 3], [5, 3], [7, 3]] expect(bst.level_order).to eql(expected) end end describe "#find inexistent value" do it "returns nil when searching for a value that doesn't exist in the BST" do array = [1, 2, 3, 4, 5, 6, 7, 3, 4, 5, 6, 1, 2, 3, 4, 5, 6, 7, 3, 4, 2, 2, 4, 5] bst = BinarySearchTree.new(array) expect(bst.find(20)).to eql(nil) end end describe "#find existent value" do it "returns an existent node when searching for a value that exists in the BST" do array = [1, 2, 3, 4, 5, 6, 7, 3, 4, 5, 6, 1, 2, 3, 4, 5, 6, 7, 3, 4, 2, 2, 4, 5] bst = BinarySearchTree.new(array) expect(bst.find(5).value).to eql(5) end end describe "#insert in an empty BST" do it "inserts a value in the BST and makes it its root" do bst = BinarySearchTree.new bst.insert(1) expect(bst.root.value).to eql(1) end end describe "#insert in a non empty BST" do it "inserts a value in the BST" do bst = BinarySearchTree.new([1, 4, 6]) bst.insert(3) expect(bst.root.left.right.value).to eql(3) end end end<file_sep>/ruby/05-a-bit-of-computer-science/06-data-structures-and-algorithms/assignment_1/binary_search_tree.rb require_relative 'node' require 'set' class BinarySearchTree attr_reader :root def initialize(array = []) @root = build_tree(array) puts @root end public def build_tree(array) unique_sorted_array = sort(remove_dupes(array)) build_tree_internal(unique_sorted_array) end def inorder result = [] inorder_internal(@root, result) result end def preorder result = [] preorder_internal(@root, result) result end def postorder result = [] postorder_internal(@root, result) result end def to_s inorder.to_s end def depth depth_internal(@root) end def level_order queue = [] queue << [@root, 1] result = [] until queue.empty? node, level = queue.shift if block_given? yield node.value, level else result << [node.value, level] end queue << [node.left, level + 1] unless node.left.nil? queue << [node.right, level + 1] unless node.right.nil? end unless block_given? result end end def find(value) find_internal(@root, value) end def insert(value) if @root.nil? @root = Node.new(value) else insert_internal(@root, value) end end private def remove_dupes(array) set = array.to_set set.to_a end def sort(array) array.sort end def build_tree_internal(array) if array.empty? nil else middle = array.length / 2 root = Node.new(array[middle]) root.left = build_tree_internal(array[0..(middle - 1)]) if middle > 0 root.right = build_tree_internal(array[(middle + 1)..]) root end end def inorder_internal(node, result) unless node.nil? inorder_internal(node.left, result) result << node.value inorder_internal(node.right, result) end end def preorder_internal(node, result) unless node.nil? result << node.value preorder_internal(node.left, result) preorder_internal(node.right, result) end end def postorder_internal(node, result) unless node.nil? postorder_internal(node.left, result) postorder_internal(node.right, result) result << node.value end end def depth_internal(node) if node.nil? 0 else left_depth = depth_internal(node.left) right_depth = depth_internal(node.right) 1 + [left_depth, right_depth].max end end def find_internal(node, value) if node.nil? nil elsif node.value == value node elsif node.value < value find_internal(node.right, value) else find_internal(node.left, value) end end def insert_internal(node, value) if node.value < value if node.right.nil? node.right = Node.new(value) else insert_internal(node.right, value) end else if node.left.nil? node.left = Node.new(value) else insert_internal(node.left, value) end end end end<file_sep>/ruby/04-intermediate-ruby/05-hangman/session_repo.rb require 'yaml' require './session.rb' class SessionRepo $save_file_name = "session.txt" public def save(session) File.open($save_file_name, "w") do |file| file.write(session.to_yaml) end end def restore session = nil # Get previous session begin File.open($save_file_name, "r") do |file| session = YAML.load(file.read) end rescue puts "No previous sessions available to restore." end # Delete previous session File.delete($save_file_name) session end end
58568c4398ff95232ecc7b664c6980b3651b598a
[ "Markdown", "Ruby" ]
21
Ruby
husaynhakeem/the-odin-project
fe216cff742c22721181264be8c629537f9ae562
495b78d3d01695d89e001f8ab66153114089b38c
refs/heads/master
<file_sep>package app.some_lie.brings; import android.content.Intent; import android.graphics.Bitmap; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.AdapterView; import android.widget.BaseAdapter; import android.widget.ImageButton; import android.widget.ListView; import android.widget.SearchView; import android.widget.TextView; import java.util.ArrayList; public class MainActivity extends AppCompatActivity { private ImageButton ibAdd; private TextView tvSearch; private SearchView search; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); tvSearch = (TextView)findViewById(R.id.tvSearch); ibAdd = (ImageButton)findViewById(R.id.ibAdd); search = (SearchView)findViewById(R.id.searchView); setOnClick(); tvSearch.setText("Search "); setList(); } private void setOnClick(){ final Intent new_event = new Intent(this,newEvent.class); ibAdd.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { startActivity(new_event); } }); tvSearch.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { search.setIconified(false); } }); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.menu_main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); //noinspection SimplifiableIfStatement if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } private void setList() {//TODO final ListView listview = (ListView) findViewById(R.id.lvMain); listview.setClickable(true); } }
7ee98ad91cffcb1b3cfa3c00af7d36152eeae1ae
[ "Java" ]
1
Java
ravidcohn/Brings
235c1f17bf7fd2e422eb65d1ee04f70bd3e50033
e1383dded4267df5e33d435c0fc494e446c2a551
refs/heads/main
<repo_name>happy-ryo/laravel-vue-api-sample<file_sep>/README.md ## 動かす手順 1. cp .env.example .env 2. php artisan key:generate 3. composer install 4. npm install & npm run dev 5. php artisan serve 6. access to http://127.0.0.1:8000 ## ザックリした説明 見るべきファイルは以下の通り * app/Http/Controllers/API/SampleController.php * PHP の API 部分、ただ JSON を返しているだけ * resources/js/components/Sample.vue * Vue のコンポーネント、見ての通り API をコールして取得した値をリストで表示する * デフォルトでも値を持っているが、上書きされる * resources/views/welcome.blade.php * Vue のコンポーネントを読み込んでいる * resources/js/app.js * Vue のコンポーネントを登録している <file_sep>/app/Http/Controllers/API/SampleController.php <?php namespace App\Http\Controllers\API; use App\Http\Controllers\Controller; use Illuminate\Http\JsonResponse; use Illuminate\Http\Request; use Illuminate\Http\Response; class SampleController extends Controller { /** * Handle the incoming request. * * @param Request $request * @return JsonResponse */ public function __invoke(Request $request): JsonResponse { $sampleValue = [ ['text' => '1'], ['text' => 'ni'], ['text' => 'さん'] ]; return \response()->json($sampleValue); } }
72ef51908ba7033856edb4627aefca3e426fe824
[ "Markdown", "PHP" ]
2
Markdown
happy-ryo/laravel-vue-api-sample
2260c057d653915f964786ed7829cc612fa4b21a
8728d1195fcc405cb65c40aa22534b057253a2ec
refs/heads/master
<file_sep>import glb heading = [0,0] vmg = 0 vmb = 0 sog = 0 cog = 0 rch = 0 heelX = 0 heelY = 0 hour = 0 minute = 0 second = 0 status = 0 lon=None lat=None relWindSpeed = 0 relWindHeading = 0 windSpeed = 0 windHeading = 0 gpsFix = False day=None month=None year=None currentTime=None <file_sep>from math import * from time import * import stt import glb import pygame import data import log import numpy background = None good = None heelBox = None vmgBox = None vmbBox = None startup = True def init(): global background, good, windCircle, vmbBox, vmgBox, heelBox background = pygame.Surface(glb.screen.get_size()) background = background.convert() background.fill(glb.white) good = pygame.Surface(glb.screen.get_size()) good = good.convert() good.fill(glb.white) #draw all fixed items #pitch size = stt.screenHeight / 7 text = 'Pitch:' pos = stt.screenWidth * 15/32, stt.screenHeight /16 glb.drawText(background, text, size, pos, glb.black) #Heel text = 'Heel:' pos = stt.screenWidth * 24/32 , stt.screenHeight /16 heelBox = glb.drawText(background, text, size, pos, glb.red) glb.drawText(good, text, size, pos, glb.green) size = stt.screenHeight / 9 text = 'REL:' pos = stt.screenWidth * 4/64, stt.screenHeight * 11/16 glb.drawText(background, text, size, pos, glb.black) text = 'TRU:' pos = stt.screenWidth * 4/64, stt.screenHeight * 27/32 glb.drawText(background, text, size, pos, glb.black) #rch size = stt.screenHeight * 3/16 text = 'RCH:' pos = stt.screenWidth * 7/64, stt.screenHeight * 3 / 16 glb.drawText(background, text, size, pos, glb.black) size = stt.screenHeight * 7/32 text = 'HED:' pos = stt.screenWidth *30/64, stt.screenHeight * 5/16 glb.drawText(background, text, size, pos, glb.black) glb.drawText(good, text, size, pos, glb.black) size = stt.screenHeight / 4 text = "VMG:" pos = ( stt.screenWidth /2 , stt.screenHeight * 29 / 64 ) vmgBox = glb.drawText(background, text, size, pos, glb.red) glb.drawText(good, text, size, pos, glb.green) text = 'VMB:' pos = ( stt.screenWidth /2, stt.screenHeight * 39/ 64 ) vmbBox = glb.drawText(background, text, size, pos, glb.red) glb.drawText(good, text, size, pos, glb.green) text = "SOG:" pos = ( stt.screenWidth /2 , stt.screenHeight * 48 / 64 ) glb.drawText(background, text, size, pos, glb.black) glb.drawText(good, text, size, pos, glb.black) text = "COG:" pos = ( stt.screenWidth /2 , stt.screenHeight * 29 / 32 ) glb.drawText(background, text, size, pos, glb.black) #draw wind arrow setup pic = pygame.image.load("/home/pi/boat/res/boat.png") pic = pygame.transform.scale(pic, ( stt.screenHeight / 3, stt.screenHeight / 3)) pic.convert() point = stt.screenWidth * 39/ 512, stt.screenHeight * 19/64 background.blit(pic, point) #draw circle center = stt.screenWidth * 3/16, stt.screenHeight * 15/32 radius = stt.screenWidth / 8 width = 2 #pygame.draw.circle(screen, black, center, radius, width) pygame.gfxdraw.aacircle(background, center[0], center[1], radius, glb.blue) windex = stt.windex/2.0 #draw flags p1 = (center[0] + (radius-5)*cos(radians(float(windex+90))), center[1] + (radius-5)*sin(radians(float(windex+90)))) p2 = (center[0] + (radius+10)*cos(radians(float(windex+90))), center[1] + (radius+10)*sin(radians(float(windex+90)))) p3 = (center[0] + (radius-5)*cos(radians(float(-windex+90))), center[1] + (radius-5)*sin(radians(float(-windex+90)))) p4 = (center[0] + (radius+10)*cos(radians(float(-windex+90))), center[1] + (radius+10)*sin(radians(float(-windex+90)))) flagWidth = 20 pygame.draw.line(background, glb.green, p1, p2, flagWidth) pygame.draw.line(background, glb.green, p3, p4, flagWidth) #draw heel a, b = stt.screenHeight / 12. , stt.screenWidth / 8. rect = pygame.Rect(stt.screenWidth * 23/32, stt.screenHeight / 24, stt.screenWidth / 4, stt.screenHeight / 6) pygame.draw.arc(background, glb.blue, rect, pi, 2*pi) pygame.draw.arc(good, glb.blue, rect, pi, 2*pi) p1 = (stt.screenWidth * (23/32. + 1/8.), stt.screenHeight * (1/24. + 1./12 ) ) p3 = (p1[0] + (b-5)*sin(radians(float(stt.idealHeel))), p1[1] + (a-5)*cos(radians(float(stt.idealHeel)))) p4 = (p1[0] + (b+5)*sin(radians(float(stt.idealHeel))), p1[1] + (a+5)*cos(radians(float(stt.idealHeel)))) #pygame.draw.line(screen, green, p3, p4, 7) p5 = (p1[0] + (b-5)*sin(radians(float(-stt.idealHeel))), p1[1] + (a-5)*cos(radians(float(-stt.idealHeel)))) p6 = (p1[0] + (b+5)*sin(radians(float(-stt.idealHeel))), p1[1] + (a+5)*cos(radians(float(-stt.idealHeel)))) #pygame.draw.line(screen, green, p5, p6, 7) pygame.draw.polygon(background, glb.green,(p3, p5, p6, p4), 0) pygame.draw.polygon(good, glb.green, (p3, p5, p6, p4), 0) radius = stt.screenWidth / 6 p1 = (stt.screenWidth *7/16, stt.screenHeight * 3/16) p2 = (p1[0] + radius, p1[1]) pygame.draw.line(background, glb.blue, p1, p2, 2) pygame.draw.line(good, glb.blue, p1, p2, 2) def drawHeading(): global background text = "%3d\xb0%02d'"%(data.heading[0], data.heading[1]) size = stt.screenHeight * 7/32 pos = stt.screenWidth * 51/64, stt.screenHeight * 5/16 corn = stt.screenWidth * 19/32 , stt.screenHeight * 4/16 area = stt.screenWidth * 7/16 , stt.screenHeight / 8 rect = pygame.Rect(corn, area) glb.screen.blit(background, corn, rect) glb.drawText(glb.screen, text, size, pos, glb.black) #glb.screen.fill(glb.blue, rect) lastWind = pygame.Rect(0,0,0,0) lastRelWind = pygame.Rect(0,0,0,0) def drawWind(): global windCircle, background, lastWind, lastRelWind size = stt.screenHeight / 7 #corn = stt.screenWidth * 0/64, stt.screenHeight * 11/16 #area = stt.screenWidth * 91/256, stt.screenHeight * 18/64 #rect = pygame.Rect(corn, area) #glb.screen.blit(background, corn, rect) #glb.screen.fill(glb.blue, rect) glb.screen.blit(background, (lastRelWind.left, lastRelWind.top), lastRelWind) text = '%2.2f [%03d]'%(data.relWindSpeed, data.relWindHeading) pos = stt.screenWidth * 12/64, stt.screenHeight * 6/8 lastRelWind = glb.drawText(glb.screen, text, size, pos, glb.black) corn = stt.screenWidth * 1/16, stt.screenWidth * 49/256 area = stt.screenWidth * 2/8, stt.screenWidth * 2/8 rect = pygame.Rect(corn, area) #glb.screen.fill(glb.red, rect) glb.screen.blit(background,corn, rect) drawArrow(data.relWindHeading, 1, glb.blue, True) if data.gpsFix: glb.screen.blit(background, (lastWind.left, lastWind.top), lastWind) text = '%2.2f [%03d]'%(data.windSpeed, data.windHeading) pos = stt.screenWidth * 12/64, stt.screenHeight *29/32 lastWind = glb.drawText(glb.screen, text, size, pos, glb.black) def drawArrow(heading, size, color, flag): if flag: radius = size*(stt.screenWidth / 8) center = stt.screenWidth *3/16, stt.screenHeight * 15/32 width = 5 #draw arrow offset = -90 heading = heading + offset startx = center[0] + (radius * cos( radians(heading - 180) ) ) starty = center[1] + (radius * sin( radians(heading - 180) ) ) endx = center[0] + (radius * cos( radians(heading) ) ) endy = center[1] + (radius * sin( radians(heading) ) ) length = 25 p1 = ( endx + (length * cos ( radians(heading - 225) ) ), endy + (length * sin ( radians(heading - 225) ) ) ) p2 = endx, endy p3 = ( endx + (length * cos ( radians(heading - 135) ) ), endy + (length * sin ( radians(heading - 135) ) ) ) pygame.draw.line(glb.screen, color, (startx, starty), (endx, endy), width) pygame.draw.lines(glb.screen, color, False, (p1,p2,p3), width) dots = '.' lastVmgColour = glb.red lastVmbColour = glb.red justFixed = True def drawGPS(): global background, good, justFixed, lastVmgColour, lastVmbColour, vmgBox, vmbBox if data.status == 'A': if justFixed: justFixed = False corn = stt.screenWidth * 45/128, stt.screenHeight * 6/16 area = stt.screenWidth * 20/64, stt.screenHeight * 10/16 rect = pygame.Rect(corn, area) glb.screen.blit(background,rect, rect) lastVmgColour = lastVmbColour = glb.red corn = stt.screenWidth * 42/64, stt.screenHeight * 6/16 area = stt.screenWidth * 6/16, stt.screenHeight * 10/16 rect = pygame.Rect(corn, area) glb.screen.blit(background, corn, rect) #glb.screen.fill(glb.white, rect) vmgColour = glb.formatColour(data.vmg, 51) if vmgColour != lastVmgColour: if vmgColour == glb.green: glb.screen.blit(good, vmgBox, vmgBox) else: glb.screen.blit(background, vmgBox, vmgBox) lastVmgColour = vmgColour size = stt.screenHeight / 4 text = '%3d%%'%data.vmg pos = stt.screenWidth * 53/64, stt.screenHeight * 29/64 glb.drawText(glb.screen, text, size, pos, vmgColour) vmbColour = glb.formatColour(data.vmb, 51) if vmbColour != lastVmbColour: if vmbColour == glb.green: glb.screen.blit(good, vmbBox, vmbBox) else: glb.screen.blit(background, vmgBox, vmgBox) lastVmbColour = vmbColour text = '%3d%%'%data.vmb pos = stt.screenWidth * 53/64, stt.screenHeight * 39/64 glb.drawText(glb.screen, text, size, pos, vmbColour) text = '%2.2f'%data.sog pos = stt.screenWidth * 53/64, stt.screenHeight * 49/64 glb.drawText(glb.screen, text, size, pos, glb.black) text = '%03d\xb0'%data.cog pos = stt.screenWidth * 53/64, stt.screenHeight * 58/64 glb.drawText(glb.screen, text, size, pos, glb.black) elif data.status == 'V': global dots justFixed = True corn = stt.screenWidth * 22/64, stt.screenHeight * 6/16 area = stt.screenWidth * 11/16, stt.screenHeight * 10/16 rect = pygame.Rect(corn, area) glb.screen.fill(glb.white, rect) text = 'Aquiring' size = stt.screenHeight / 4 pos = (stt.screenWidth * 2/3, stt.screenHeight /2) glb.drawText(glb.screen, text, size, pos, glb.red) text = "Satellites" pos = (stt.screenWidth * 2/3, stt.screenHeight * 2/3) glb.drawText(glb.screen, text, size, pos, glb.red) dots = dots + "." if dots == "...............": dots = "." pos = (stt.screenWidth * 2/3, stt.screenHeight * 3/4) glb.drawText(glb.screen, dots, size, pos, glb.green) else: corn = stt.screenWidth * 30/64, stt.screenHeight * 6/16 area = stt.screenWidth * 6/16, stt.screenHeight * 10/16 rect = pygame.Rect(corn, area) glb.screen.fill(glb.white, rect) text = "GPS Error" size = stt.screenHeight / 4 pos = (stt.screenWidth * 2/3, stt.screenHeight / 2) glb.drawText(glb.screen, text, size, pos, glb.red) blinkBit=False timer=0 newCourse = True def drawCourse(force = False): '''global newCourse if newCourse or force: corn = stt.screenWidth * 7/32, stt.screenHeight * 1/8 area = stt.screenWidth * 6/32, stt.screenHeight * 1/8 rect = pygame.Rect(corn, area) glb.screen.blit(background, corn, rect) pos = stt.screenWidth * 21/64, stt.screenHeight * 3/16 text = '%03d\xb0'%data.rch size = stt.screenHeight * 3/16 glb.drawText(glb.screen, text, size, pos, glb.black)''' global blinkBit, timer corn = stt.screenWidth * 7/32, stt.screenHeight * 1/8 area = stt.screenWidth * 6/32, stt.screenHeight * 1/8 rect = pygame.Rect(corn, area) glb.screen.blit(background, corn, rect) if clock() - timer > 0.5 and blinkBit: timer = clock() elif clock() - timer > 0.10 or (not blinkBit): txt = "RCH: %03d\xb0" % (data.rch) size = stt.screenHeight* 3/16 pos = (stt.screenWidth * 7 / 32, stt.screenHeight * 3 / 16) glb.drawText(glb.screen, txt, size, pos, glb.black) lastHeelColour = glb.red def drawAcc(heel, pitch): global background corn = stt.screenWidth * 7/16, stt.screenHeight * 0 area = stt.screenWidth * 9/16, stt.screenHeight * 2/8 rect = pygame.Rect(corn ,area) glb.screen.blit(background, corn, rect) size = stt.screenHeight /7 text = '%2d'%pitch pos = stt.screenWidth * 39/64, stt.screenHeight * 1/16 glb.drawText(glb.screen, text, size, pos, glb.black) text = '%2d'%heel pos = stt.screenWidth * 57/64, stt.screenHeight * 1/16 colour = glb.formatColour(heel, stt.idealHeel, True) if colour != lastHeelColour: if colour == glb.green: glb.screen.blit(good, heelBox, heelBox) else: glb.screen.blit(background, heelBox, heelBox) glb.drawText(glb.screen, text, size, pos, colour) radius = stt.screenWidth / 6 p1 = (stt.screenWidth *7/16, stt.screenHeight * 3/16) p2 = (p1[0] + radius, p1[1]) p4 = (p1[0]+ radius*cos(radians(float(-pitch))), p1[1] + radius*sin(radians(float(-pitch)))) pygame.draw.line(glb.screen, glb.blue, p1, p2, 2) if abs(pitch) < 18: pygame.draw.line(glb.screen, glb.blue, p1, p4, 4) a, b = stt.screenHeight / 12. , stt.screenWidth / 8. p1 = (stt.screenWidth * (23/32. + 1/8.), stt.screenHeight * (1/24. + 1./12 ) ) p2 = (p1[0] + b * sin(radians(float(heel))), p1[1] + a * cos(radians(float(heel)))) pygame.draw.line(glb.screen, glb.blue, p1, p2, 3) lastLog=None def writeLog(): global startup, lastLog corn = 0, stt.screenHeight * 61/64 area = stt.screenWidth*5/32, stt.screenHeight *1/32 rect = pygame.Rect(corn, area) if startup: if data.year != 0 or log.forceLog != '': startup = False log.init() lastLog = (0,0,0) elif log.forceLog != '': text = 'log forced' size = stt.screenHeight / 16 pos = (stt.screenWidth *3/ 32, stt.screenHeight * 31/32) glb.screen.blit(background, rect, rect) glb.drawText(glb.screen, text, size, pos, glb.black) elif lastLog != data.currentTime and data.currentTime >= stt.startTime and data.currentTime[2] % stt.logDelay == 0 and data.gpsFix: text = 'logging data' size = stt.screenHeight / 16 pos = (stt.screenWidth *3/ 32, stt.screenHeight * 31/32) glb.screen.blit(background, rect, rect) glb.drawText(glb.screen, text, size, pos, glb.black) lastLog = data.currentTime row = [data.lon, data.lat, data.sog] log.write(row) elif (numpy.subtract(data.currentTime, lastLog))[2] > stt.logDelay: glb.screen.fill(glb.white, rect) def drawTime(): global background corn = stt.screenWidth * 0/16, stt.screenHeight *0 area = stt.screenWidth * 4/16, stt.screenHeight * 1/8 rect = pygame.Rect(corn, area) glb.screen.blit(background, corn, rect) size = stt.screenHeight / 7 text = '%02d:%02d:%02d'%(data.hour, data.minute, data.second) pos = stt.screenWidth * 1/8, stt.screenHeight * 1/16 glb.drawText(glb.screen, text, size, pos, glb.black) def screenInit(): global background, newCourse glb.screen.fill(glb.white) glb.screen.blit(background, (0,0)) drawCourse(True) def drawScreen(): drawTime() drawHeading() drawGPS() drawCourse() drawAcc(data.heelY, data.heelX) drawWind() writeLog() <file_sep>#!/usr/bin/python import pygame import glb import data with open('/etc/network/interfaces', 'r') as network: for i in range(6): ipAddr = network.readline() filename = "/home/pi/boat/src/settings.txt" screenHeight=420 screenWidth=640 idealHeel=20 windLimit1=9 windLimit2=12 dec_deg = -10 dec_min = 8 windex = 60 compassCorrection = 180 windFactor = 118 rawAnenometer = None pitchCorrect = 7 startTime = (8, 0, 0) logDelay = 1 timezone=-4 def readSettings(): global filename, screenHeight, screenWidth, idealHeel f = open(filename, "r") confirmed = True for line in f: line = line.strip('\n') print line line = line.split('=') if line[0] == 'screenHeight': screenHeight = int(line[1]) elif line[0] == 'screenWidth': screenWidth = int(line[1]) elif line[0] == 'idealHeel': idealHeel = int(line[1]) elif line[0] == 'compassCorrection': compassCorrection = int(line[1]) elif line[0] == 'windLimit1': windLimit1 = int(line[1]) elif line[0] == 'windLimit2': windLimit2 = int(line[1]) elif line[0] == 'dec_deg': dec_deg = int(line[1]) elif line[0] == 'dec_min': dec_min = int(line[1]) elif line[0] == 'windex': windex = int(line[1]) elif line[0] == 'pitchCorrect': pitchCorrect = int(line[1]) elif line[0] == 'windFactor': windFactor = float(line[1]) elif line[0] == 'lastCourse': data.rch = int(line[1]) else: confirmed = False print 'Failed.\n' if confirmed: print 'Confirmed.\n' f.close() def writeSettings(): global filename, screenHeight, screenWidth, idealHeel f = open(filename, "w") f.write('screenHeight=%d\n'%screenHeight) f.write('screenWidth=%d\n'%screenWidth) f.write('idealHeel=%d\n'%idealHeel) f.write('windLimit1=%d\n'%windLimit1) f.write('windLimit2=%d\n'%windLimit2) f.write('dec_deg=%d\n'%dec_deg) f.write('dec_min=%d\n'%dec_min) f.write('compassCorrection=%d\n'%compassCorrection) f.write('pitchCorrect=%d\n'%pitchCorrect) f.write('windFactor=%.2f\n'%windFactor) f.write('lastCourse=%03d\n'%data.rch) f.close() print 'Settings written.' def updateCourse(): global filename f = open(filename, 'a') f.write('lastCourse=%03d\n'%data.rch) f.close() print 'Course Updated.' def settingsScreen(): global screenHeight, screenWidth, idealHeel size = screenHeight / 8 glb.screen.fill(glb.white) pos = (screenWidth / 4, screenHeight *1/8) text = 'screenHeight = %d'%screenHeight glb.drawText(glb.screen, text, size, pos, glb.black) pos = (screenWidth / 4, screenHeight *2/8) text = 'screenWidth = %d'%screenWidth glb.drawText(glb.screen, text, size, pos, glb.black) pos = (screenWidth / 4, screenHeight *3/8) text = 'idealHeel = %d'%idealHeel glb.drawText(glb.screen, text, size, pos, glb.black) pos = (screenWidth / 4, screenHeight *4/8) text = 'windLimit1 = %d'%windLimit1 glb.drawText(glb.screen, text, size, pos, glb.black) pos = (screenWidth / 4, screenHeight *5/8) text = 'windLimit2 = %d'%windLimit2 glb.drawText(glb.screen, text, size, pos, glb.black) pos = (screenWidth / 4, screenHeight *6/8) text = 'magnetic declination = %d\xb0 %d'% (dec_deg, dec_min) glb.drawText(glb.screen, text, size, pos, glb.black) pos = (screenWidth * 3/4, screenHeight / 8) text = 'WF = %2.2f'% windFactor glb.drawText(glb.screen, text, size, pos, glb.black) text = 'rawAn = %3d'%rawAnenometer pos = (screenWidth * 3/4, screenHeight * 2/ 8) glb.drawText(glb.screen, text, size, pos, glb.black) #draw ip stats size = screenHeight/16 pos = (screenWidth /2, screenHeight * 7/8) glb.drawText(glb.screen, ipAddr, size, pos, glb.black) i = screenWidth def drawAnGraph(): global i, screenWidth, screenHeight, rawAnenometer factor = screenHeight/255.0 p1 = i, screenHeight p2 = i, screenHeight - int((rawAnenometer)*factor) pygame.draw.line(glb.screen, glb.blue, p1, p2, 1) #print rawAnenometer, p2[1] i += 2 if i >= screenWidth: glb.screen.fill(glb.white) pygame.draw.line(glb.screen, glb.red, (0, int(screenHeight/2.0)), (screenWidth, int(screenHeight/2.0)), 2) i = 0 <file_sep>#!/usr/bin/env python import pygame import pygame.gfxdraw import sys import os, stat import smbus from math import * from time import * import hmc5883l import stt import glb import race import data import log #os.environ['SDL_VIDEODRIVER'] = "fbcon" #screenWidth = 640 #screenHeight = 420 #screenSize = screenWidth, screenHeight #screen = None #os.system("sudo chmod 777 /dev/ttyUSB0") #ser = serial.Serial("/dev/ttyUSB0", 9600, timeout = 0.25) #black = pygame.Color( "black" ) #white = pygame.Color( "white" ) #glb.blue = pygame.Color( "glb.blue" ) #green = pygame.Color( 0, 100, 0 ) #red = pygame.Color( "red" ) press_events = pygame.MOUSEBUTTONDOWN, pygame.KEYDOWN courseHeading = 180 data.rch = courseHeading heelX = 0 heelY = 0 relWindHeading = 0 compass = 0 headingCalibration = 0 key = '' blinkBit = False timer = clock() actionTime = 0 compass = None def start(): global compass stt.readSettings() screenSize = stt.screenWidth, stt.screenHeight compass = hmc5883l.hmc5883l(gauss=8.1, declination=(0,0)) pygame.init() glb.screen = pygame.display.set_mode(screenSize)#, pygame.FULLSCREEN) glb.screen.fill(glb.white) pygame.mouse.set_visible(False) print "Screen Successfully Initialized! (%d, %d)"%(stt.screenWidth, stt.screenHeight) readFromI2C() while key == '#': readFromI2C() race.init() race.screenInit() def quit(): pygame.quit() sys.exit() def is_quit( evt ): return ( evt.type == pygame.QUIT or ( evt.type == pygame.KEYDOWN and evt.key == pygame.K_ESCAPE ) ) bus = smbus.SMBus(1) a168 = 0x40 a168_bytes = 5 a328 = 0x41 a328_bytes = 28 hour=0 minute=0 second=0 status=0 vmg = 0 sog = 0 cog = 0 timezone = -4 relWindSpeed = 0 windSpeed = 0 windHeading = 0 lat = 0 lon = 0 currentTime = (0,0,0) def readFromI2C(): global heading, compass, timezone, status, vmg, vmb, currentTime global sog, cog, key, heelX, heelY, relWindSpeed, lat, lon global relWindHeading, hour, minute, second, windSpeed, windHeading tmp = [-1] * (a168_bytes + a328_bytes) #initialize the arduinos for sending bus.write_quick(a168) #sleep(0.0005) #read from a168 for i in range(0, a168_bytes-1): tmp[i] = bus.read_byte(a168) #time.sleep(0.005) bus.write_quick(a328) #time.sleep(0.05) #read from 168 for i in range(0, a328_bytes): tmp[i+a168_bytes] = bus.read_byte(a328) #sleep(0.001) print tmp key = chr(tmp[0]) #relWindSpeed = tmp[1] - (stt.windFactor/328*62.98) relWindSpeed = int(tmp[3] - 118) / 328.0 * 62.98 stt.rawAnenometer = int(tmp[3]) heelX = sign( (tmp[a168_bytes+0] << 8) + tmp[a168_bytes+1], 'w') tmpHeelY = normalize( sign( (tmp[a168_bytes+2] << 8) + tmp[a168_bytes+3], 'w') + 180 ) tmpHeelX = normalize( sign( (tmp[a168_bytes+0] << 8) + tmp[a168_bytes+1], 'w') + 180 ) + stt.pitchCorrect if abs(tmpHeelY) < 70: heelY = tmpHeelY if abs(tmpHeelX) < 70: heelX = tmpHeelX relWindHeading = 360 - (( (tmp[a168_bytes+4] << 8) + tmp[a168_bytes+5] ) / 1023.0 * 360) hour = (tmp[a168_bytes+6] + timezone)%24 minute = tmp[a168_bytes+7] second = tmp[a168_bytes+8] status = chr(tmp[a168_bytes+9]) sog = tmp[a168_bytes+10] + (tmp[a168_bytes+11]/100.0) cog = ( (tmp[a168_bytes+12] << 8) + tmp[a168_bytes+13] - stt.dec_deg ) % 360 #print sog, windHeading, vmg #print heelX, heelY if status == 'A': glb.gpsLock = True data.gpsFix = True else: glb.gpsLock = False data.gpsFix = False heading = list(compass.degrees(compass.heading())) heading[0] = (heading[0] + stt.compassCorrection) % 360 w_x = relWindSpeed*cos(radians(float(relWindHeading))) - sog*cos(radians(float(cog))) w_y = relWindSpeed*sin(radians(float(relWindHeading))) - sog*sin(radians(float(cog))) windSpeed = sqrt( w_x**2 + w_y**2 ) windHeading = degrees(atan2( w_y, w_x ))+180 #print relWindSpeed,sog, w_x, w_y, windSpeed, windHeading vmg = int(cos(radians(float(windHeading-cog)))*100) vmb = int(cos(radians(float(courseHeading-cog)))*100) data.heading = heading data.vmg = vmg data.cog = cog data.sog = sog data.vmb = vmb data.heelX = heelX data.heelY = heelY data.hour = hour data.minute = minute data.second = second data.status = status data.relWindSpeed = data.relWindSpeed + 0.5*(relWindSpeed - data.relWindSpeed) data.relWindHeading = data.relWindHeading + 0.5*(relWindHeading - data.relWindHeading) data.windHeading = windHeading data.windSpeed = windSpeed data.day = tmp[a168_bytes+14] if hour >= 24+stt.timezone and hour < 24: data.day -= 1 data.month = tmp[a168_bytes+15] data.year = tmp[a168_bytes+16] data.currentTime = (hour, minute, second) data.lat = sign(tmp[a168_bytes+17], 'b')*100 data.lat += checkSign(data.lat) * ( tmp[a168_bytes+18] + 0.00001*((tmp[a168_bytes+19]<<16) + (tmp[a168_bytes+20]<<8) + tmp[a168_bytes+21]) ) data.lon = sign(tmp[a168_bytes+22], 'b')*10000 + sign(tmp[a168_bytes+23], 'b')*100 data.lon += checkSign(data.lon) * ( tmp[a168_bytes+24] + 0.00001*((tmp[a168_bytes+25]<<16) + (tmp[a168_bytes+26]<<8) + tmp[a168_bytes+27]) ) def normalize(x): x = x * pi / 180 return int(atan2(sin(x), cos(x))*180/pi) def checkSign(x): if x < 0: return -1 return 1 def sign(x, type): if x > 0x7FFF and type == 'w': x -= 0xFFFF elif x > 128 and type == 'b': x -= 256 return x def drawWindSetup(heading): pic = pygame.image.load("/home/pi/boat/res/boat.png") pic = pygame.transform.scale(pic, ( stt.screenHeight / 3, stt.screenHeight / 3)) pic.convert() point = stt.screenWidth * 5/ 64, stt.screenHeight * 21/64 glb.screen.blit(pic, point) #draw circle center = stt.screenWidth * 3/16, stt.screenHeight /2 radius = stt.screenWidth / 8 width = 2 #pygame.draw.circle(screen, black, center, radius, width) pygame.gfxdraw.aacircle(glb.screen, center[0], center[1], radius, glb.blue) windex = stt.windex/2.0 #draw flags p1 = (center[0] + (radius-5)*cos(radians(float(windex+90))), center[1] + (radius-5)*sin(radians(float(windex+90)))) p2 = (center[0] + (radius+10)*cos(radians(float(windex+90))), center[1] + (radius+10)*sin(radians(float(windex+90)))) p3 = (center[0] + (radius-5)*cos(radians(float(-windex+90))), center[1] + (radius-5)*sin(radians(float(-windex+90)))) p4 = (center[0] + (radius+10)*cos(radians(float(-windex+90))), center[1] + (radius+10)*sin(radians(float(-windex+90)))) flagWidth = 20 pygame.draw.line(glb.screen, glb.green, p1, p2, flagWidth) pygame.draw.line(glb.screen, glb.green, p3, p4, flagWidth) #draw text heading textPos = stt.screenWidth * 3/16, (stt.screenHeight * 3/4) textSize = stt.screenHeight / 7 windStr = "WH: %03d\xb0" % (heading) glb.drawText(glb.screen, windStr, textSize, textPos, glb.black) def drawWindArrow(heading, size, color, flag): if flag: radius = size*(stt.screenWidth / 8) center = stt.screenWidth *3/16, stt.screenHeight /2 width = 5 #draw arrow offset = -90 heading = heading + offset startx = center[0] + (radius * cos( radians(heading - 180) ) ) starty = center[1] + (radius * sin( radians(heading - 180) ) ) endx = center[0] + (radius * cos( radians(heading) ) ) endy = center[1] + (radius * sin( radians(heading) ) ) length = 25 p1 = ( endx + (length * cos ( radians(heading - 225) ) ), endy + (length * sin ( radians(heading - 225) ) ) ) p2 = endx, endy p3 = ( endx + (length * cos ( radians(heading - 135) ) ), endy + (length * sin ( radians(heading - 135) ) ) ) pygame.draw.line(glb.screen, color, (startx, starty), (endx, endy), width) pygame.draw.lines(glb.screen, color, False, (p1,p2,p3), width) #flip the screen finally # pygame.display.flip() def drawCourse(): global blinkBit, timer if clock() - timer > 0.5 and blinkBit: timer = clock() elif clock() - timer > 0.10 or (not blinkBit): txt = "RCH: %03d\xb0" % (courseHeading) size = stt.screenHeight* 3/16 pos = (stt.screenWidth * 7 / 32, stt.screenHeight * 3 / 16) glb.drawText(glb.screen, txt, size, pos, glb.black) # pygame.display.flip() def limit(x): if x > 1: x = 1 elif x < 0: x = 0 return x def drawWindSpeed(knots): global windSpeed txt = "%2d - %2d KTS" % (windSpeed, knots) size = stt.screenHeight / 7 pos = (stt.screenWidth * 3/16, stt.screenHeight * 7/8) #print 255* limit(knots/stt.windLimit2), 150 * limit(1- (knots / stt.windLimit2)) colour = pygame.Color(int(255* limit(knots/stt.windLimit2)), int(150 * limit(1- (knots / stt.windLimit2))), 0) glb.drawText(glb.screen, txt, size, pos, colour) # pygame.display.flip() blinkCount = 0 def drawHeel(heel): idealHeel = stt.idealHeel heelColour = glb.green if abs(heel) > idealHeel: heelColour = glb.red text = "Heel: %s" % (heel) pos = (stt.screenWidth * 13/16, stt.screenHeight / 16) size = stt.screenHeight / 7 glb.drawText(glb.screen, text, size, pos, heelColour) #draw diagram rect = pygame.Rect(stt.screenWidth * 23/32, stt.screenHeight / 24, stt.screenWidth / 4, stt.screenHeight / 6) pygame.draw.arc(glb.screen, glb.blue, rect, pi, 2*pi) a, b = stt.screenHeight / 12. , stt.screenWidth / 8. p1 = (stt.screenWidth * (23/32. + 1/8.), stt.screenHeight * (1/24. + 1./12 ) ) p2 = (p1[0] + b * sin(radians(float(heel))), p1[1] + a * cos(radians(float(heel)))) pygame.draw.line(glb.screen, glb.blue, p1, p2, 3) #draw flags p3 = (p1[0] + (b-5)*sin(radians(float(idealHeel))), p1[1] + (a-5)*cos(radians(float(idealHeel)))) p4 = (p1[0] + (b+5)*sin(radians(float(idealHeel))), p1[1] + (a+5)*cos(radians(float(idealHeel)))) #pygame.draw.line(screen, green, p3, p4, 7) p5 = (p1[0] + (b-5)*sin(radians(float(-idealHeel))), p1[1] + (a-5)*cos(radians(float(-idealHeel)))) p6 = (p1[0] + (b+5)*sin(radians(float(-idealHeel))), p1[1] + (a+5)*cos(radians(float(-idealHeel)))) #pygame.draw.line(screen, green, p5, p6, 7) pygame.draw.polygon(glb.screen, glb.green,(p3, p5, p6, p4), 0) dots = '.' def drawMain(): global dots, status, time, timezone, heading, vmg, vmb, sog, cog text = "HED: %03d\xb0%02d'" % ( heading[0], heading[1] ) pos = ( stt.screenWidth * 2/3 , stt.screenHeight * 5 / 16 ) size = stt.screenHeight * 7/32 glb.drawText(glb.screen, text, size, pos, glb.black) size = int(stt.screenHeight / 4.0) if status == 'A': text = "VMG: %3d%%" % ( vmg ) pos = ( stt.screenWidth * 2/3 , stt.screenHeight * 29 / 64 ) vmgcolour = glb.green glb.drawText(glb.screen, text, size, pos, glb.formatColour(vmg, 51)) text = 'VMB: %3d%%'%vmb pos = ( stt.screenWidth * 2/3, stt.screenHeight * 39/ 64 ) glb.drawText(glb.screen, text, size, pos, glb.formatColour(vmb, 51)) text = "SOG: %.2f" % ( sog ) pos = ( stt.screenWidth * 2/3 , stt.screenHeight * 48 / 64 ) glb.drawText(glb.screen, text, size, pos, glb.black) text = "COG: %03d\xb0" % ( cog ) pos = ( stt.screenWidth * 2/3 , stt.screenHeight * 29 / 32 ) glb.drawText(glb.screen, text, size, pos, glb.black) elif status == 'V': text = 'Aquiring' size = stt.screenHeight / 4 pos = (stt.screenWidth * 2/3, stt.screenHeight /2) glb.drawText(glb.screen, text, size, pos, glb.red) text = "Satellites" pos = (stt.screenWidth * 2/3, stt.screenHeight * 2/3) glb.drawText(glb.screen, text, size, pos, glb.red) dots = dots + "." if dots == ".............": dots = "." pos = (stt.screenWidth * 2/3, stt.screenHeight * 3/4) glb.drawText(glb.screen, dots, size, pos, glb.green) else: text = "GPS Error" size = stt.screenHeight / 4 pos = (stt.screenWidth * 2/3, stt.screenHeight / 2) glb.drawText(glb.screen, text, size, pos, glb.red) def drawTime(): global hour, minute, second text = "%02d:%02d:%02d" % (hour, minute, second) size = stt.screenHeight / 7 pos = (stt.screenWidth * 3/16, stt.screenHeight / 16) glb.drawText(glb.screen, text, size, pos, glb.black) def waitFor(time, event): finished_waiting_event_id = pygame.USEREVENT + 1 pygame.time.set_timer( finished_waiting_event_id, time) try: pygame.event.clear() pressed = False waiting = True while waiting: evt = pygame.event.wait() if is_quit( evt ): quit() elif pygame.key.get_pressed()[pygame.K_ESCAPE]: quit() elif evt.type in event: waiting = False pressed = True elif evt.type == finished_waiting_event_id: waiting = False finally: pygame.time.set_timer( finished_waiting_event_id, 0 ) return pressed fpsTimer=0 def drawFPS(): global fpsTimer corn = 0, stt.screenHeight * 61/64 area = stt.screenWidth * 5/32, stt.screenHeight* 1/ 32 rect = pygame.Rect(corn, area) glb.screen.fill(glb.white, rect) fps = 1.0 / (clock() - fpsTimer) fpsTimer = clock() text = "FPS: %.2f" % (fps) size = stt.screenHeight / 16 pos = (stt.screenWidth * 1 / 16, stt.screenHeight * 31/ 32) glb.drawText(glb.screen, text, size, pos, glb.black) def drawPitch(pitch): size = stt.screenHeight / 7 pos = ( stt.screenWidth / 2, stt.screenHeight / 16 ) text = 'Pitch: %2d' % pitch glb.drawText(glb.screen, text, size, pos, glb.black) pitch = -pitch #draw arm thingie radius = stt.screenWidth / 6 p1 = (stt.screenWidth *7/16, stt.screenHeight * 3/16) p2 = (p1[0] + radius, p1[1]) p3 = p1 p4 = (p1[0]+ radius*cos(radians(float(pitch))), p1[1] + radius*sin(radians(float(pitch)))) pygame.draw.line(glb.screen, glb.blue, p1, p2, 2) if abs(pitch) < 30: pygame.draw.line(glb.screen, glb.blue, p3, p4, 4) def raceScreen(): if (key == 'C'): headingCalibration = compass #draw all the components drawWindSetup(relWindHeading) drawWindArrow(relWindHeading, 1, glb.blue, True) drawWindArrow(windHeading+heading[0], .60, glb.green, glb.gpsLock) drawCourse() drawTime() drawWindSpeed(relWindSpeed) drawPitch(heelX) drawMain() drawHeel(heelY) page = 0 lastKey = '-' def interpretKeyStroke(): global lastKey, page, actionTime, courseHeading, key, blinkBit, blinkCount if key == '#': if lastKey == 'A': os.system("sudo shutdown -r now") elif lastKey == 'B': os.system("sudo shutdown -h now") quit() if key != '-' and key != '*': lastKey = key print key if key == '*': if page == 2: race.screenInit() # elif page == 2: stt.writeSettings() elif page == 0: #log.clear() ##for i in range(0, 800): #t = i / 100. #log.writeToLog( [ sin(t)*(exp(cos(t)) - 2*cos(4*t) - sin(t/12.)**5 ), #cos(t)*(exp(cos(t)) - 2*cos(4*t) - sin(t/12.)**5 ) ] ) log.plot() page = (page+1) % 4 print 'page %d'%page if page == 0 and key.isdigit() and False: stt.windFactor = round( int((stt.windFactor * 100)%1000)/10.0 + (int(key)/100.0), 2 ) print (stt.windFactor * 10), (int(key)/100.0) elif key == 'C': race.blinkBit = True race.newCourse = True blinkCount = 3 actionTime = clock() elif race.blinkBit and key.isdigit() and blinkCount > 0: courseHeading = (((courseHeading * 10) + int(key)) % 1000) data.rch = courseHeading blinkCount -= 1 if blinkCount <= 0: race.blinkBit = False race.newCourse = False courseHeading = courseHeading % 360 data.rch = courseHeading stt.updateCourse() elif race.blinkBit and clock() - actionTime > 5: race.blinkBit = False race.newCourse = False courseHeading = courseHeading % 360 data.rch = courseHeading #===============Program Start=======================# lastlog = 0 start() while(1): #readFromArduino() readFromI2C() interpretKeyStroke() waitFor(5,press_events) #clear the screen #if page == 0: #glb.screen.fill(glb.white) #raceScreen() if page == 3: stt.drawAnGraph() #page = 0 #stt.settingsScreen() elif page == 0: race.drawScreen() elif page == 2: stt.settingsScreen() elif page == 1: log.show() #drawFPS() #show the drawings pygame.display.update() quit() <file_sep>import math def jDate2Time(jDate): jTime = jDate - int(jDate) hour = 24*jTime min = 60*(hour-int(hour)) sec = int(60*(min-int(min))) min = int(min) hour = int(hour) return "%02d:%02d:%02d"%(hour, min, sec) def calcSunet(day, month, year, hour, min, sec, lat, lon): # from https://en.wikipedia.org/wiki/Sunrise_equation julianDay = (1461*(year + 4800 + (month - 14)/12))/4 +(367 * (month - 2 - 12 * ((month - 14)/12)))/12 - (3 * ((year + 4900 + (month - 14)/12)/100))/4 + day - 32077 julianDate = julianDay + (hour-12)/24. + min/1440. + sec/86400. n = julianDate - 2451545.0 + 0.0008 Jc = n - (lon/360.) M = (357.5291 + (0.98560028 * Jc)) % 360 C = 1.9148*math.sin(math.radians(M)) + 0.02*math.sin(math.radians(2*M)) + 0.0003*math.sin(math.radians(3*M)) l = (M + C + 180 + 102.9372) % 360 Jt = 2451545.5 + Jc + (0.0053*math.sin(math.radians(M))) - (0.0069*math.sin(math.radians(2*l))) d = math.asin(math.sin(math.radians(l)) * math.sin(math.radians(23.44))) w = math.acos((math.sin(math.radians(-0.83)) - math.sin(math.radians(lat)) * math.sin(d)) / (math.cos(math.radians(lat)) * math.cos(d))) Jset = Jt + math.degrees(w)/360. Jrise = Jt - math.degrees(w)/360. print n print julianDay print julianDate print Jc print jDate2Time(Jc), jDate2Time(Jset), jDate2Time(Jrise) calcSunet(12, 7, 2018, 19, 00, 0, 43.2111930, -79.6163450)<file_sep>#!/usr/bin/python import pygame import glb import data with open('/etc/network/interfaces', 'r') as network: for i in range(6): ipAddr = network.readline() filename = "/home/pi/boat/display/src/settings.txt" screenHeight=420 screenWidth=640 idealHeel=20 windLimit1=9 windLimit2=12 dec_deg = -10 dec_min = 8 windex = 60 compassCorrection = 180 windFactor = 118 rawAnenometer = None pitchCorrect = 7 startTime = (8, 0, 0) logDelay = 1 timezone=-4 dataLocation="./" def readSettings(): global filename, screenHeight, screenWidth, idealHeel, dataLocation f = open(filename, "r") confirmed = True for line in f: line = line.strip('\n') print line line = line.split('=') if line[0] == 'screenHeight': screenHeight = int(line[1]) elif line[0] == 'screenWidth': screenWidth = int(line[1]) elif line[0] == 'idealHeel': idealHeel = int(line[1]) elif line[0] == 'compassCorrection': compassCorrection = int(line[1]) elif line[0] == 'windLimit1': windLimit1 = int(line[1]) elif line[0] == 'windLimit2': windLimit2 = int(line[1]) elif line[0] == 'dec_deg': dec_deg = int(line[1]) elif line[0] == 'dec_min': dec_min = int(line[1]) elif line[0] == 'windex': windex = int(line[1]) elif line[0] == 'pitchCorrect': pitchCorrect = int(line[1]) elif line[0] == 'windFactor': windFactor = float(line[1]) elif line[0] == 'lastCourse': data.rch = int(line[1]) elif line[0] == 'dataLocation': dataLocation = line[1] else: confirmed = False print 'Failed.\n' if confirmed: print 'Confirmed.\n' f.close() def writeSettings(): global filename, screenHeight, screenWidth, idealHeel f = open(filename, "w") f.write('screenHeight=%d\n'%screenHeight) f.write('screenWidth=%d\n'%screenWidth) f.write('idealHeel=%d\n'%idealHeel) f.write('windLimit1=%d\n'%windLimit1) f.write('windLimit2=%d\n'%windLimit2) f.write('dec_deg=%d\n'%dec_deg) f.write('dec_min=%d\n'%dec_min) f.write('compassCorrection=%d\n'%compassCorrection) f.write('pitchCorrect=%d\n'%pitchCorrect) f.write('windFactor=%.2f\n'%windFactor) f.write('lastCourse=%03d\n'%data.rch) f.close() print 'Settings written.' def updateCourse(): global filename f = open(filename, 'a') f.write('lastCourse=%03d\n'%data.rch) f.close() print 'Course Updated.' i =0 <file_sep>#! /bin/bash python /home/pi/boat/display/src/main.py & #chromium-browser --window-size=700,440 --kiosk --igcognito chrome://gpu #chromium-browser --force-video-overlays --enable-nacl --window-size=700,440 --kiosk --enable-dom-distiller --enable-low-res-tiling http://127.0.0.1/index.html #x-window-manager & #kweb -KHCUAJ+-zbhrqfpoklgtjneduwxyavcsmi#?!., http://127.0.0.1/index.html firefox-esr -purgecaches -height 440 -width 690 --override /home/pi/override.ini http://1172.16.58.3/index.html#noMenu sleep 60 xdotool key --clearmodifiers F11 #python /home/pi/wcgbrowser-git/browser.py -l <file_sep>#!/usr/bin/python import csv import sys import pygame import stt import glb import data import os.path from time import * _top = None _bot = None _left = None _right = None _filename = None _maxspeed = None graph = None firstRow=True _dir='/home/pi/boat/display/src/paths/' forceLog='' forced=False isInit=False notEnough=True _rows = None def init(): global graph,_maxspeed, _filename, _rows, _top, _bot, _left, _right global firstRow, forced, isInit, _dir print "Initializing log..." if not isInit: isInit=True _top = 0 _bot = 0 _left = 0 _right = 0 _maxspeed = 0 _rows=0 firstRow=True graph = pygame.Surface(glb.screen.get_size()) _filename = _dir+forceLog if _filename == _dir: os.system('mkdir %s%d_%d_%d'%(_dir, data.day, data.month, data.year)) _dir += '%d_%d_%d/'%(data.day, data.month, data.year) _filename = _dir+'log0.csv' i = 1 while os.path.isfile(_filename): _filename = _dir+'log%d.csv'%(i) i+=1 os.system('touch %s'%(_filename)) _rows = 0 else: print "Forcing log to %s\n"%_filename forced=True with open(_filename, 'r') as istream: reader = csv.reader(istream, delimiter=',', quotechar='|') j = 0 for row in reader: countRows(row) j += 1 #print row _rows = j def show(): global isInit, notEnough if not isInit: glb.screen.fill(glb.white) pos = stt.screenWidth / 2, stt.screenHeight / 2 size = stt.screenHeight / 4 text = 'No Log Data' glb.drawText(glb.screen, text, size, pos, glb.black) elif notEnough: glb.screen.fill(glb.white) pos = stt.screenWidth / 2, stt.screenHeight / 2 size = stt.screenHeight / 6 text = 'Not Enough Log Data' glb.drawText(glb.screen, text, size, pos, glb.black) else: global graph glb.screen.blit(graph, (0,0)) def colorScale(x, m=None): global _maxspeed if m == None: m = _maxspeed factor = float(x) / float(m) if factor < 0.50: r = 1 g = factor*2 else: g = 1 r = 1 - (factor - 0.5)*2 return pygame.Color(int(255*r), int(255*g), 0) def plot(): if isInit: global graph, _filename, notEnough, _rows, _left, _right, _top, _bot, _maxspeed graph.fill(glb.white) buff = 30 heightScale = float(_top - _bot) / (stt.screenHeight-buff) widthScale = float(_left - _right) / (stt.screenWidth-3*buff) heightMid = (_top + _bot)/2 widthMid = (_left + _right)/2 #if heightScale < 0.00000001 or widthScale < 0.00000001: # heightScale = widthScale = 1 if heightScale < widthScale: widthScale = heightScale else: heightScale = widthScale print widthScale for i in range(50): pos = ( stt.screenWidth / 64, (stt.screenHeight *3/4) - (stt.screenHeight/200)*2*i, 25,25 ) c = colorScale(i, 50) graph.fill(c, pos) pos = stt.screenWidth *3/ 64, stt.screenHeight *9/32 size = stt.screenHeight / 16 text = '%2.2f'%(_maxspeed) glb.drawText(graph, text, size, pos, glb.black) pos = stt.screenWidth / 32, stt.screenHeight * 27/32 text = '0' glb.drawText(graph, text, size, pos, glb.black) pos = stt.screenWidth / 2, stt.screenHeight / 2 text = 'Plotting...' tsize = stt.screenHeight / 4 glb.screen.fill(glb.white) glb.drawText(glb.screen, text, tsize, pos, glb.black) rect = pygame.Rect(stt.screenWidth/4, stt.screenHeight*3/4, stt.screenWidth/2 + 7, stt.screenHeight*3/128) loadArea = pygame.draw.rect(glb.screen, glb.blue, rect, 3) p_point = stt.screenWidth /2, stt.screenHeight *7/8 bar = [stt.screenWidth /4, stt.screenHeight *3/ 4] lastP = (0,0,1,1) pygame.display.update() print 'Plotting...' with open(_filename, 'r') as ostream: reader = csv.reader(ostream, delimiter=',', quotechar='|') k = 0 for row in reader: try: notEnough=False pos = [ int( (stt.screenWidth/2) + (widthMid - float(row[0]))/widthScale ), int( (stt.screenHeight/2) + (float(row[1])-heightMid)/heightScale ) ] pos[0] += buff #pos[1] += buff/2 #print pos size = 5 #print _left, _right, _top, _bot colour = colorScale(row[2]) graph.fill(colour, (pos, (size, size)) ) glb.screen.fill(glb.white, lastP) percent = '%3d%%'%(int(float(k)/_rows*100)) #lastP = glb.drawText(glb.screen, percent, stt.screenHeight/16, p_point, glb.blue) #print lastP glb.screen.fill(glb.blue, (bar[0] + (float(k)/_rows*stt.screenWidth/2), bar[1], 10, 10)) k += 1 pygame.display.update(loadArea) #sleep(0.125) except ZeroDivisionError: notEnough = True print 'Not enough data points.' break def clear(): global _filename with open(_filename, 'w') as ostream: pass def countRows(row): global _maxspeed, _filename, _top, _bot, _left, _right, firstRow if firstRow: _left = _right = float(row[0]) _top = _bot = float(row[1]) firstRow=False #track side limits if float(row[0]) < _left: _left = float(row[0]) elif float(row[0]) > _right: _right = float(row[0]) #track height limits if float(row[1]) > _top: _top = float(row[1]) elif float(row[1]) < _bot: _bot = float(row[1]) if float(row[2]) > _maxspeed: _maxspeed = float(row[2]) #print _top, _bot, _left, _right def write(row): global _maxspeed,_rows, _filename, _top, _bot, _left, _right, firstRow if not forced: _rows += 1 with open(_filename, 'a') as ostream: writer = csv.writer(ostream, delimiter=',') writer.writerow(row) countRows(row) print "logging: %4.5f\t%5.5f\t%f"%(row[0], row[1], row[2]) <file_sep><!DOCTYPE html> <html> <body> <?php $python = "http://localhost:88/"; foreach($_GET as $x => $x_value){ echo $x . ": " . $x_value . "<br>"; } if( isset($_GET["course"])) echo "true"; else echo "false"; // Get cURL resource $curl = curl_init(); // Set some options - we are passing in a useragent too here curl_setopt_array($curl, array( CURLOPT_RETURNTRANSFER => 1, CURLOPT_URL => $python, CURLOPT_USERAGENT => 'User Agent X' )); // Send the request & save response to $resp $resp = curl_exec($curl); // Close request to clear up some resources curl_close($curl); ?> </body> </html> <file_sep>reference for hcm5883l https://github.com/rm-hull/hmc5883l magnetic declination http://magnetic-declination.com/ <file_sep>import xml.etree.cElementTree as ET import time root = ET.Element("data") ET.SubElement(root, "time").text = time.asctime() ET.SubElement(root, "course").text = str(176) ET.SubElement(root, "relWindSpeed").text = str(6.31) ET.SubElement(root, "relWindDirection").text = str(0) ET.SubElement(root, "windSpeed").text = str(3.5) ET.SubElement(root, "windDirection").text = str(10) ET.SubElement(root, "heading").text = "%d %d\' %d\""%(167, 23, 54) ET.SubElement(root, "VMG").text = "null" ET.SubElement(root, "VMB").text = str(87) ET.SubElement(root, "SOG").text = str(4.54) ET.SubElement(root, "COG").text = str(213) ET.SubElement(root, "pitch").text = str(5) ET.SubElement(root, "heel").text = str(16) def calcHeel(i): return (i%70) - 35 def calcPitch(i): return (i%40) - 20 while True: for i in range(360): print i root.find("relWindDirection").text = str(i) root.find("time").text = time.asctime() root.find("heel").text = str(calcHeel(i)) root.find("pitch").text = str(calcPitch(i)) if i > 45: root.find("VMG").text = str(i%200-100) root.find("VMB").text = str(i%200-100) tree = ET.ElementTree(root) tree.write("data.xml") time.sleep(0.100) <file_sep>#!/usr/bin/python import smbus import time bus = smbus.SMBus(1) address = 0x40 def read(n): bus.write_quick(address) str = "" for i in range(0,n): #print i tmp = bus.read_byte(address) #print tmp str += chr(tmp) #print str time.sleep(0.05) time.sleep(0.1) print str while True: read(9) time.sleep(1) <file_sep>import stt import pygame screen = None black = pygame.Color( "black" ) white = pygame.Color( "white" ) blue = pygame.Color( "blue" ) green = pygame.Color( 0, 100, 0 ) red = pygame.Color( "red" ) gpsLock = False def drawText(surface, text, size, pos, colour): global screen, font font = pygame.font.Font(None, size) rend = font.render(text, 1, colour) pos = rend.get_rect( centerx = pos[0], centery = pos[1]) return surface.blit(rend, pos) def formatColour(val, limit, invert = False): if abs(val) < limit: if invert: return green return red elif invert: return red return green <file_sep>//main loop interval controller loadDoc(loadConfig, "js/configuration.xml", "t=" + Math.random()); var timer = setInterval(loop, 200); //check if display only from hash window.onload = function () { if (location.hash == "#noMenu") { var menu = document.getElementById("usermenu"); menu.style.display = "none"; } } // standard colours var green = "#2ecc71"; var red = "#e74c3c"; //globals var lastPitch; var lastHeel; var lastVMG; var lastVMB; //settings variables var idealHeel; var idealPitch; var idealPercent; function loadConfig(xml) { var xmlDoc = xml.responseXML; var data = xmlDoc.getElementsByTagName("settings"); idealHeel = parseInt(data[0].getElementsByTagName("idealHeel")[0].childNodes[0].nodeValue); idealPitch = parseInt(data[0].getElementsByTagName("idealPitch")[0].childNodes[0].nodeValue); idealPercent = parseInt(data[0].getElementsByTagName("idealPercentage")[0].childNodes[0].nodeValue); } /* Toggle between showing and hiding the navigation menu links when the user clicks on the hamburger menu / bar icon */ function menuDisplay() { var x = document.getElementById("myLinks"); if (x.style.display === "block") { x.style.display = "none"; } else { x.style.display = "block"; } } function sendData(response) { document.getElementById("commandResponse").innerHTML = response.responseText; } function loop() { loadDoc(main, "src/data.xml", "t=" + Math.random()); } function loadDoc(fn_function, file, parameters) { var xhttp = new XMLHttpRequest(); xhttp.onreadystatechange = function() { if (this.readyState == 4 && this.status == 200) { fn_function(this); } }; xhttp.open("GET", file+"?" + parameters , true); xhttp.send(); } function main(xml) { var xmlDoc = xml.responseXML; var data = xmlDoc.getElementsByTagName("data"); var time = data[0].getElementsByTagName("time")[0].childNodes[0].nodeValue; var course = data[0].getElementsByTagName("course")[0].childNodes[0].nodeValue; var relWindSpeed = data[0].getElementsByTagName("relWindSpeed")[0].childNodes[0].nodeValue; var relWindDirection = data[0].getElementsByTagName("relWindDirection")[0].childNodes[0].nodeValue; var windSpeed = data[0].getElementsByTagName("windSpeed")[0].childNodes[0].nodeValue; var windDirection = data[0].getElementsByTagName("windDirection")[0].childNodes[0].nodeValue; var heading = data[0].getElementsByTagName("heading")[0].childNodes[0].nodeValue; var VMG = data[0].getElementsByTagName("VMG")[0].childNodes[0].nodeValue; var VMB = data[0].getElementsByTagName("VMB")[0].childNodes[0].nodeValue; var COG = data[0].getElementsByTagName("COG")[0].childNodes[0].nodeValue; var SOG = data[0].getElementsByTagName("SOG")[0].childNodes[0].nodeValue; var pitch = data[0].getElementsByTagName("pitch")[0].childNodes[0].nodeValue; var heel = data[0].getElementsByTagName("heel")[0].childNodes[0].nodeValue; document.getElementById("time").innerHTML = time; document.getElementById("course").innerHTML = "RCH: " + course + " &#176"; document.getElementById("relWind").innerHTML = "Rel: " + relWindSpeed + " [" + relWindDirection + "&#176] kts"; document.getElementById("wind").innerHTML = "Tru: " + windSpeed + " [" + windDirection + "&#176] kts"; document.getElementById("heading").innerHTML = "HED: " + heading; document.getElementById("VMG").innerHTML = "VMG: " + VMG + "%"; document.getElementById("VMB").innerHTML = "VMB: " + VMB + "%"; document.getElementById("SOG").innerHTML = "SOG: " + SOG + " kts"; document.getElementById("COG").innerHTML = "COG: " + COG + "&#176"; document.getElementById("pitch").innerHTML = pitch + "&#176"; document.getElementById("heel").innerHTML = heel + "&#176"; document.getElementById("arrow").style.transform = "rotate(" + (parseInt(relWindDirection)) + "deg)"; if (VMG == "null"){ document.getElementById("GPSLoading").style.display = "block"; document.getElementById("GPSReadings").style.display = "none"; document.getElementById("wind").style.display = "none"; } else { document.getElementById("GPSLoading").style.display = "none"; document.getElementById("GPSReadings").style.display = "block"; document.getElementById("wind").style.display = "block"; } setDegColour("VMG", VMG); setDegColour("VMB", VMB); setPitchAndHeel(pitch, heel); } function setDegColour(id, value){ document.getElementById(id).style.color = (value >= idealPercent || value <= -idealPercent) ? green : red; } function setPitchAndHeel(pitch, heel){ document.getElementById("pitchImg").style.transform = "rotate("+pitch+"deg)"; document.getElementById("heelImg").style.transform ="rotate("+heel+"deg)"; if ( (heel > idealHeel || heel < -idealHeel) && lastHeel != red) { document.getElementById("heelImg").src ="img/heel-red.png"; lastHeel = red; } else if ( (heel <= idealHeel && heel >= -idealHeel) && lastHeel != green) { document.getElementById("heelImg").src ="img/heel-blue.png"; lastHeel = green; } if ( ( pitch > idealPitch || pitch < -idealPitch) && lastPitch != red) { document.getElementById("pitchImg").src ="img/pitch-red.png"; lastPitch = red; } else if ( ( pitch <= idealPitch && pitch >= -idealPitch) && lastPitch != green) { document.getElementById("pitchImg").src ="img/pitch-blue.png"; lastPitch = green; } } function setMark(mark){ alert("setting mark: " + mark); } function setRaceHeading(){ var x = document.forms["form_RCH"]["headingInput"].value; if (x == "") { alert("Course must be filled out"); } else if (x > 360 || x < 0) { alert("Not a valid heading") } else loadDoc(sendData, "/command.php", "test=1&something=2&course="+x); return false; } <file_sep>#!/usr/bin/env python import sys import os, stat import smbus from math import * from time import * import xml.etree.cElementTree as ET import hmc5883l import stt import data import log courseHeading = 180 data.rch = courseHeading heelX = 0 heelY = 0 relWindHeading = 0 compass = 0 headingCalibration = 0 key = '' blinkBit = False timer = clock() actionTime = 0 compass = None def start(): global compass stt.readSettings() screenSize = stt.screenWidth, stt.screenHeight compass = hmc5883l.hmc5883l(gauss=8.1, declination=(0,0)) initXML() readFromI2C() while key == '#': readFromI2C() def quit(): sys.exit() bus = smbus.SMBus(1) a168 = 0x40 a168_bytes = 5 a328 = 0x41 a328_bytes = 28 hour=0 minute=0 second=0 status=0 vmg = 0 sog = 0 cog = 0 timezone = -4 relWindSpeed = 0 windSpeed = 0 windHeading = 0 lat = 0 lon = 0 currentTime = (0,0,0) root = ET.Element("data") page = 0 def readFromI2C(): global heading, compass, timezone, status, vmg, vmb, currentTime global sog, cog, key, heelX, heelY, relWindSpeed, lat, lon global relWindHeading, hour, minute, second, windSpeed, windHeading tmp = [-1] * (a168_bytes + a328_bytes) #initialize the arduinos for sending bus.write_quick(a168) #sleep(0.0005) #read from a168 for i in range(0, a168_bytes-1): tmp[i] = bus.read_byte(a168) #time.sleep(0.005) bus.write_quick(a328) #time.sleep(0.05) #read from 168 for i in range(0, a328_bytes): tmp[i+a168_bytes] = bus.read_byte(a328) #sleep(0.001) print tmp key = chr(tmp[0]) #relWindSpeed = tmp[1] - (stt.windFactor/328*62.98) relWindSpeed = int(tmp[3] - 118) / 328.0 * 62.98 stt.rawAnenometer = int(tmp[3]) heelX = sign( (tmp[a168_bytes+0] << 8) + tmp[a168_bytes+1], 'w') tmpHeelY = normalize( sign( (tmp[a168_bytes+2] << 8) + tmp[a168_bytes+3], 'w') + 180 ) tmpHeelX = normalize( sign( (tmp[a168_bytes+0] << 8) + tmp[a168_bytes+1], 'w') + 180 ) + stt.pitchCorrect if abs(tmpHeelY) < 70: heelY = tmpHeelY if abs(tmpHeelX) < 70: heelX = tmpHeelX relWindHeading = 360 - (( (tmp[a168_bytes+4] << 8) + tmp[a168_bytes+5] ) / 1023.0 * 360) hour = (tmp[a168_bytes+6] + timezone)%24 minute = tmp[a168_bytes+7] second = tmp[a168_bytes+8] status = chr(tmp[a168_bytes+9]) sog = tmp[a168_bytes+10] + (tmp[a168_bytes+11]/100.0) cog = ( (tmp[a168_bytes+12] << 8) + tmp[a168_bytes+13] - stt.dec_deg ) % 360 #print sog, windHeading, vmg #print heelX, heelY if status == 'A': data.gpsFix = True else: data.gpsFix = False heading = list(compass.degrees(compass.heading())) heading[0] = (heading[0] + stt.compassCorrection) % 360 w_x = relWindSpeed*cos(radians(float(relWindHeading))) - sog*cos(radians(float(cog))) w_y = relWindSpeed*sin(radians(float(relWindHeading))) - sog*sin(radians(float(cog))) windSpeed = sqrt( w_x**2 + w_y**2 ) windHeading = degrees(atan2( w_y, w_x ))+180 #print relWindSpeed,sog, w_x, w_y, windSpeed, windHeading vmg = int(cos(radians(float(windHeading-cog)))*100) vmb = int(cos(radians(float(courseHeading-cog)))*100) data.heading = heading data.vmg = vmg data.cog = cog data.sog = sog data.vmb = vmb data.heelX = heelX data.heelY = heelY data.hour = hour data.minute = minute data.second = second data.status = status data.relWindSpeed = data.relWindSpeed + 0.5*(relWindSpeed - data.relWindSpeed) data.relWindHeading = data.relWindHeading + 0.5*(relWindHeading - data.relWindHeading) data.windHeading = windHeading data.windSpeed = windSpeed data.day = tmp[a168_bytes+14] if hour >= 24+stt.timezone and hour < 24: data.day -= 1 data.month = tmp[a168_bytes+15] data.year = tmp[a168_bytes+16] data.currentTime = (hour, minute, second) data.lat = sign(tmp[a168_bytes+17], 'b')*100 data.lat += checkSign(data.lat) * ( tmp[a168_bytes+18] + 0.00001*((tmp[a168_bytes+19]<<16) + (tmp[a168_bytes+20]<<8) + tmp[a168_bytes+21]) ) data.lon = sign(tmp[a168_bytes+22], 'b')*10000 + sign(tmp[a168_bytes+23], 'b')*100 data.lon += checkSign(data.lon) * ( tmp[a168_bytes+24] + 0.00001*((tmp[a168_bytes+25]<<16) + (tmp[a168_bytes+26]<<8) + tmp[a168_bytes+27]) ) def normalize(x): x = x * pi / 180 return int(atan2(sin(x), cos(x))*180/pi) def checkSign(x): if x < 0: return -1 return 1 def sign(x, type): if x > 0x7FFF and type == 'w': x -= 0xFFFF elif x > 128 and type == 'b': x -= 256 return x def limit(x): if x > 1: x = 1 elif x < 0: x = 0 return x def initXML(): global root ET.SubElement(root, "time").text = asctime() ET.SubElement(root, "course").text = str(176) ET.SubElement(root, "relWindSpeed").text = str(6.31) ET.SubElement(root, "relWindDirection").text = str(0) ET.SubElement(root, "windSpeed").text = str(3.5) ET.SubElement(root, "windDirection").text = str(10) ET.SubElement(root, "heading").text = "%d %d\' %d\""%(167, 23, 54) ET.SubElement(root, "VMG").text = "null" ET.SubElement(root, "VMB").text = str(87) ET.SubElement(root, "SOG").text = str(4.54) ET.SubElement(root, "COG").text = str(213) ET.SubElement(root, "pitch").text = str(5) ET.SubElement(root, "heel").text = str(16) def writeXML(): global root root.find("time").text = "%02d:%02d:%02d" % (hour, minute, second) root.find("course").text = str(data.rch) root.find("relWindSpeed").text = "%.2f" % data.relWindSpeed root.find("relWindDirection").text = str(int(data.relWindHeading)) root.find("windSpeed").text = "%.2f" % data.windSpeed root.find("windDirection").text = str(int(data.windHeading)) root.find("heading").text = "%03d&#176 %02d'" % ( heading[0], heading[1] ) root.find("VMG").text = str(data.vmg) root.find("VMB").text = str(data.vmb) root.find("SOG").text = str(data.sog) root.find("COG").text = str(data.cog) root.find("pitch").text = str(data.heelX) root.find("heel").text = str(data.heelY) if not data.gpsFix: root.find("VMG").text = "null" tree = ET.ElementTree(root) tree.write(stt.dataLocation+"data.xml") def interpretKeyStroke(): global lastKey, page, actionTime, courseHeading, key, blinkBit, blinkCount if key == '#': if lastKey == 'A': os.system("sudo shutdown -r now") elif lastKey == 'B': os.system("sudo shutdown -h now") quit() if key != '-' and key != '*': lastKey = key print key if key == '*': if page == 2: stt.writeSettings() elif page == 0: log.plot() page = (page+1) % 4 print 'page %d'%page if page == 0 and key.isdigit() and False: stt.windFactor = round( int((stt.windFactor * 100)%1000)/10.0 + (int(key)/100.0), 2 ) print (stt.windFactor * 10), (int(key)/100.0) elif key == 'C': blinkCount = 3 actionTime = clock() elif key.isdigit() and blinkCount > 0: courseHeading = (((courseHeading * 10) + int(key)) % 1000) data.rch = courseHeading blinkCount -= 1 if blinkCount <= 0: courseHeading = courseHeading % 360 data.rch = courseHeading stt.updateCourse() elif clock() - actionTime > 5: courseHeading = courseHeading % 360 data.rch = courseHeading #===============Program Start=======================# lastlog = 0 start() while(1): readFromI2C() interpretKeyStroke() writeXML() sleep(0.2) quit()
2e51d72dd38e4f5f97be99c2b53cb3daa9486c66
[ "JavaScript", "Python", "Text", "PHP", "Shell" ]
15
Python
cbastarache/SensorDisplayPage
1a047fcb4400220aa4f7d75464eed0858f591a43
4129ec593b8027ba01b891bc16a5ff0653db3630
refs/heads/master
<file_sep>void HTTP_init(void) { HTTP.on("/mac", procMAC); // Запускаем HTTP сервер HTTP.begin(); } //http://192.168.0.101/mac?getmac=12:13:14:15:16:17 void createMAS (char*temp[100],int raz){ char*test=HTTP.arg("getmac"); bool flag = false; for(int i=0;i<raz;i++){ if(test == temp[i])flag=true; } if(!flag){ raz++; temp[raz] = test; } } <file_sep>#include <ESP8266WiFi.h> //Содержится в пакете #include <ESP8266WebServer.h> //Содержится в пакете IPAddress apIP(192, 168, 4, 1); // Web интерфейс для устройства ESP8266WebServer HTTP(80); // Определяем переменные wifi String _ssid = "home"; // Для хранения SSID String _password = "<PASSWORD>"; // Для хранения пароля сети String _ssidAP = "WiFi"; // SSID AP точки доступа String _passwordAP = ""; // пароль точки доступа char*temp[100]; int raz=0; String macjson= "\"mac\"["; void setup() { Serial.begin(9600); WIFIinit(); HTTP_init(); } void loop() { HTTP.handleClient(); json(); delay(1); if(Serial.available()){ comand = Serial.read(); switch (comand) { case 'm': Serial.println(macjson); break; case 'r': // rfid(); break; } } } void json(){ for(int i=0;i<raz;i++){ macjson.concat("\""); macjson.concat(temp[i]); macjson.concat("\", "); //добавляем каждый mac } macjson = macjson.substring(0,macjson.length()-1); //обрезаем лишнюю запятую macjson.concat("]"); //конец нашей строки } <file_sep>Flash Drive Information Extractor v.9.x Бесплатная программа для получения информации о флешках. Программа обладает возможностью определения модели USB контроллера, модели и типа памяти для многих современных USB флешек. Особенность программы в том, что эти данные определяются напрямую, а не по косвенным признакам типа VID/PID. Во многих случаях программа сработает, даже если поврежден загрузочный сектор или разрушена файловая система. При помощи программы можно получить следующие данные: модель контроллера возможные варианты установленных во флешке чипов памяти тип установленной памяти заявленный производителем максимальный потребляемый ток версия USB физический объем диска объем диска, сообщаемый операционной системой VID и PID Query Vendor ID Query Product ID Query Product Revizion Controller Revision Flash ID (не для всех конфигураций) Chip F/W (для некоторых контроллеров) некоторые другие параметры, полезные для специалистов. Установка ============================================== Скопируйте из ZIP-архива папку с файлами usbflashinfo в любое место на жестком диске. Системные требования: Windows 2000/2003/XP/Vista/2008/7/8/10. Место на жестком диске: 8 МБ. Инструкция по применению ============================================== 1. Вставьте флешку в любой USB порт. Не следует подключать две или более флешек, так как будут получены данные только для одной из них. 2. Запустите Flash Drive Information Extractor (\usbflashinfo\GetFlashInfo.exe) 3. Щелкните кнопку "Получить информацию о флешке" ("Get USB Flash Drive Information"). Через несколько секунд в окне появится определившаяся информация. 4. Чтобы повторить измерения, нужно перезапустить программу. Примечания ============================================== Программа работает только с флешками и не реагирует на другие USB устройства, такие как кардридеры (SD карты в любом оформлении), смартфоны, MP3 плееры, фотоаппараты и тому подобные. Иногда кардридеры оформляются в виде флешек (например, некоторые модели Verbatim). В этих случаях программа или не отобразит никакой информации, или не определит тип контроллера и чип памяти. Рекомендуется запускать программу не раньше, чем через 20-30 секунд после того, как флешка вставлена в USB порт, иначе флешка может быть не до конца инициализирована системой. Не следует проводить измерения одновременно с работой других программ низкоуровневого доступа к флешке, например, утилит производителей контроллеров. В этом случае данные будут определены неправильно. После работы с такими программами нужно обязательно извлечь флешку из USB порта. Иногда для определения параметров требуется значительное время (до 30 секунд). Если при определении параметров программа "зависает" (это иногда случается, если флешка неисправна), следует, не пытаясь закрыть программу, просто вынуть флешку из USB-разъема. Данные флешки после этого, как правило, программой определяются. Рекомендуется наличие соединения с интернетом, так как в некоторых случаях программа может посылать данные флешки на наш web-сервер для анализа. Программа сохраняет свои служебные данные в раздел реестра Windows \HKEY_CURRENT_USER\Software\AntSpec\GetFlashInfo\. Последнюю версию программы всегда можно скачать по адресу: http://www.antspec.com/usbflashinfo/ Copyright © 2005-2018 ANTSpec Software. All rights reserved. All trademarks are the sole property of their respective owners. <file_sep>*************************************************************************************************************** # Стартап проект CheckBox) при поддержке peartechnologies, rudenda, alexesmet и TimaIndustries, a также поддержке студенческой научно-исследовательской лаборатории «Сетевые технологии и мультимедиа (СТИМУЛ) во главе с руководителем и кандидатом технических наук Воруевым Андреем Валерьевичем
f668c6b5bf82569b7235ed93aabbb3e35968339d
[ "Markdown", "Text", "C++" ]
4
C++
VoruevHello/CheckBox
f9d8c4df20f77605cdacc1659c3a8a7f974b4cf5
dd1de63ba10d4fb074d7b987587ed0f077bddd81
refs/heads/master
<file_sep><?php /* Build Steps 1. Added a shortcode to generate a subscription form. 2. Added a function to register shortcodes. 3. Added a hook to add shortcodes on init. 4. Built custom post types using CPTUI for subscribers and lists. 5. Built custom fields for Subscribers post types using ACFUI. 6. Added functions to configure custom headers and custom data for the lists and subscribers post types. */ ?><file_sep><?php /* Plugin Name: PPM Guru Mailing List Description: Custom email list building plugin for ppmguru. Capture new subscribers, premium/basic. Build lists for topics. Import and export subscribers with .csv Version: 1.0 Author: <NAME> License: GPL2 License URI: https://www.gnu.org/licenses/gpl-2.0.html Text Domain: ppmguru-mailing-list */ /* !0. TABLE OF CONTENTS */ /* 1. HOOKS 1.1 register shortcodes on init 1.2 add filter to register custom admin column headers 1.3 add filter to register custom column data 2. SHORTCODES 2.1 pgm_register_shortcodes() 2.2 pgm_form_shortcode() 3. FILTERS 3.1 pgm_subscriber_column_headers($columns) 3.2 pgm_subscriber_column_data($columns,$post_id) 3.3 pgm_register_custom_admin_titles() 3.4 pgm_custom_admin_titles( $title, $post_id ) 3.5 pgm_list_column_headers($columns) 4. EXTERNAL SCRIPTS 5. ACTIONS 5.1 pgm_save_subscription() 5.2 pgm_save_subscriber($subscriber_data) 5.3 pgm_add_subscription( $subscriber_id, $list_id ) 6. HELPERS 6.1 pgm_has_subscriptions() 6.2 pgm_get_subscriber_id() 6.3 pgm_get_subscritions() 6.4 pgm_return_json() 6.5 pgm_get_acf_key() 6.6 pgm_get_subscriber_data() 7. CUSTOM POST TYPES 8. ADMIN PAGES 9. SETTINGS 10. MISCELLANEOUS */ /* !1. HOOKS */ //1.1 register shortcodes on init add_action('init','pgm_register_shortcodes'); //1.2 add filter to register custom admin column headers add_filter('manage_edit-pgm_subscriber_columns','pgm_subscriber_column_headers'); add_filter('manage_edit-pgm_list_columns','pgm_list_column_headers'); //1.3 add filter to register custom column data add_filter('manage_pgm_subscriber_posts_custom_column','pgm_subscriber_column_data',1,2); add_action('admin_head-edit.php','pgm_register_custom_admin_titles'); add_filter('manage_pgm_list_posts_custom_column','pgm_list_column_data',1,2); // 1.4 // register ajax actions add_action('wp_ajax_nopriv_pgm_save_subscription', 'pgm_save_subscription'); // regular website visitor add_action('wp_ajax_pgm_save_subscription', 'pgm_save_subscription'); // admin user //1.5 //load external file add_action('wp_enqueue_scripts','pgm_public_scripts'); // 1.6 // Advanced Custom Fields Settings add_filter('acf/settings/path', 'pgm_acf_settings_path'); add_filter('acf/settings/dir', 'pgm_acf_settings_dir'); add_filter('acf/settings/show_admin', 'pgm_acf_show_admin'); if( !defined('ACF_LITE') ) define('ACF_LITE',true); // turn off ACF plugin menu /* !2. SHORTCODES */ //2.1 function pgm_register_shortcodes(){ add_shortcode('pgm_form','pgm_form_shortcode'); } //2.2 function pgm_form_shortcode($args, $content = ""){ //check for id from args and assign it to $id if it is available, else set to 0. $list_id = 0; if(isset($args['id'])){ $list_id = (int)$args['id']; } //form html-edit action firld to point to admin-ajax on the server. $output = ' <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Create</title> <!-- Latest compiled and minified CSS --> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" integrity="<KEY>" crossorigin="anonymous"> </head> <body> <div class="starter-template"> <h1>Sign Up Form</h1> </div> <div class="container"> <div class="col-sm-6"> <form id="pgm_form" name="pgm_form" class="pgm-form" method="post" action="/wordpress-plugin-course/wp-admin/admin-ajax.php?action=pgm_save_subscription" method="post"> <input type="hidden" name="pgm_list" value="'. $list_id .'"> <div class="form-group"> <label for="pgm_fname">First Name</label> <input type="text" class="form-control" name="pgm_fname"> </div> <div class="form-group"> <label for="pgm_lname">Last Name</label> <input type="text" class="form-control" name="pgm_lname"> </div> <div class="pgm_email"> <label for="pgm_email">Email</label> <input type="email" class="form-control" name="pgm_email"> </div><br>'; if(strlen($content)){ $output.= '<div>'.$content.'</div>'; } $output.='<input class="btn btn-primary" type="submit" name="pgm_submit" value="Sign Me Up!"> <br><br> </form> </div> </div> </body> </html>'; return $output; } /* !3. FILTERS */ //3.1 This function will take in the admin colums from the subscriber post page and override the column names. function pgm_subscriber_column_headers($columns){ $columns = array( 'cb'=>'<input type="checkbox" />', //checkbox-HTML empty checkbox 'title'=>__('Subscriber Name'), //update header name to 'Subscriber Name' 'email'=>__('Email Address'), //create new header for email ); return $columns; } //3.2 This function will take in the column data, check the header for title or email and get the corresponding data, append it to the output stream and echo it. function pgm_subscriber_column_data($column,$post_id){ $output = ''; switch($column){ case 'title': $fname = get_field('pgm_fname', $post_id); $lname = get_field('pgm_lname', $post_id); $output .= $fname.' '.$lname; break; case 'email': $email = get_field('pgm_email', $post_id); $output .= $email; break; } echo $output; } //3.3 registers special custom admin title columns- fix for newer version of wordpress function pgm_register_custom_admin_titles() { add_filter('the_title','pgm_custom_admin_titles',99,2); } //3.4 handles custom admin title "title" column data for post types without titles, we are not using wordpress default titles in our custom field. function pgm_custom_admin_titles( $title, $post_id ) { global $post; $output = $title; if( isset($post->post_type) ): switch( $post->post_type ) { case 'pgm_subscriber': $fname = get_field('pgm_fname', $post_id ); $lname = get_field('pgm_lname', $post_id ); $output = $fname .' '. $lname; break; } endif; return $output; } //3.5 function to handle list post headers function pgm_list_column_headers($columns){ $columns = array( 'cb'=>'<input type="checkbox" />', //checkbox-HTML empty checkbox 'title'=>__('Lists'), //update header name to 'List Name' 'shortcode'=>__('Shortcode'), ); return $columns; } //3.5 function to add shotcodes to list column data function pgm_list_column_data($column,$post_id){ $output = ''; switch($column){ case 'shortcode': $output .= '[pgm_form id="'. $post_id .'"]'; break; } echo $output; } /* !4. EXTERNAL SCRIPTS */ //4.1 function pgm_public_scripts(){ wp_register_script('ppmguru-mailing-list-js-public',plugins_url('/js/public/ppmguru-mailing-list.js',__FILE__), array('jquery'),'',true); wp_enqueue_script('ppmguru-mailing-list-js-public'); } //4.2 Include ACF include_once(plugin_dir_path(__FILE__).'lib/advanced-custom-fields/acf.php'); /* !5. ACTIONS */ //5.1 Function to save subscription data to an existing or new subscriber, wp ajax handler will redirect form data to this function. function pgm_save_subscription(){ //setting up default result array $result = array( 'status'=>0, 'message'=>'Subscription was not saved.', 'error'=>'', 'errors'=>array() ); try{ //get list_id $list_id = (int)$_POST['pgm_list']; //create an array of subscriber data $subscriber_data = array( 'fname' => esc_attr($_POST['pgm_fname']), 'lname' => esc_attr($_POST['pgm_lname']), 'email' => esc_attr($_POST['pgm_email']), ); //Setting up empty array to hold error data $errors = array(); // form validation if( !strlen( $subscriber_data['fname'] ) ) $errors['fname'] = 'First name is required.'; if( !strlen( $subscriber_data['email'] ) ) $errors['email'] = 'Email address is required.'; if( strlen( $subscriber_data['email'] ) && !is_email( $subscriber_data['email'] ) ) $errors['email'] = 'Email address must be valid.'; if( count($errors)){ $result['error'] = 'Some fields are still required. '; $result['errors'] = $errors; } else{ //attempt to create/save/update subscriber $subscriber_id = pgm_save_subscriber($subscriber_data); if($subscriber_id){ //Check if subscriber already has a subscription to the list if(pgm_subscriber_has_subscription($subscriber_id,$list_id)){ $list = get_post($list_id); //return error message $result['error'].=esc_attr($subscriber_data['email'].' is already subscribed to list '.$list->post_title.'.'); } else { //save the new subscription $subscription_saved = pgm_add_subscription($subscriber_id,$list_id); } if($subscription_saved){ $result['status'] = 1; $result['message'] = 'Subscription saved'; } else{ $result['error'] = 'Unable to save subscription.'; } } } }catch(Exception $e){ } //Return result as a JSON string pgm_return_json($result); } //5.2 function to save new subscribers function pgm_save_subscriber($subscriber_data){ //set default id=0, subscriber not saved. $subscriber_id = 0; try{ $subscriber_id = pgm_get_subscriber_id($subscriber_data['email']); if(!$subscriber_id){ $subscriber_id = wp_insert_post( array( 'post_type'=>'pgm_subscriber', 'post_title'=>$subscriber_data['fname'].' '.$subscriber_data['lname'], 'post_status'=>'publish', ), true ); } //add/update custom metadata update_field(pgm_get_acf_key('pgm_fname'), $subscriber_data['fname'], $subscriber_id); update_field(pgm_get_acf_key('pgm_lname'), $subscriber_data['lname'], $subscriber_id); update_field(pgm_get_acf_key('pgm_email'), $subscriber_data['email'], $subscriber_id); } catch(Exception $e) { //Do something, if php error occurs... } wp_reset_query(); return $subscriber_id; } //5.3 function adds subscriptions/lists to existing subscribers function pgm_add_subscription( $subscriber_id, $list_id ) { // setup default return value $subscription_saved = false; // IF the subscriber does NOT have the current list subscription if( !pgm_subscriber_has_subscription( $subscriber_id, $list_id ) ){ // get subscriptions and append new $list_id $subscriptions = pgm_get_subscriptions( $subscriber_id ); $subscriptions[]=$list_id; // update pgm_subscriptions update_field( pgm_get_acf_key('pgm_subscriptions'), $subscriptions, $subscriber_id ); // subscriptions updated! $subscription_saved = true; } // return result return $subscription_saved; } /* !6. HELPERS */ //6.1 function pgm_subscriber_has_subscription($subscriber_id, $list_id){ //set default value $has_subscription = false; //get the subscriber from database $subscriber = get_post($subscriber_id); //get subscriptions from database $subscriptions = pgm_get_subscriptions($subscriber_id); //check subscriptions for $list_id if(in_array($list_id,$subscriptions)){ $has_subscription = true; } else{ //leave to default } return $has_subscription; } //6.2 function pgm_get_subscriber_id($email) { //set default value $subscriber_id = 0; try{ $subscriber_query = new WP_Query( array( 'post_type' => 'pgm_subscriber', 'posts_per_page' => 1, 'meta_key' => 'pgm_email', 'meta_query' => array( array( 'key' => 'pgm_email', 'value'=>$email, 'compare' => '=', ), ), ) ); if($subscriber_query->have_posts()){ $subscriber_query->the_post(); $subscriber_id = get_the_ID(); } } catch(Exception $e){ } wp_reset_query(); return (int)$subscriber_id; } //6.3 function pgm_get_subscriptions($subscriber_id){ //initialize empty array $subscriptions = array(); //get subscriptions (returns array of list objects) $lists = get_field(pgm_get_acf_key('pgm_subscriptions'),$subscriber_id); if($lists){ if(is_array($lists) && count($lists)){ foreach($lists as &$list){ $subscriptions[]=(int)$list->ID; } } elseif(is_numeric($lists)){ $subscriptions[] = $lists; } } return (array)$subscriptions; } //6.4 function pgm_return_json($php_array){ //encode results as json string $json_result = json_encode($php_array); //return result die($json_result); //stop all other processing exit; } //6.5 Convert between custom field ids generated by acf function pgm_get_acf_key( $field_name ) { $field_key = $field_name; switch( $field_name ) { case 'pgm_fname': $field_key = 'field_57767bd66431b'; break; case 'pgm_lname': $field_key = 'field_57767bf76431c'; break; case 'pgm_email': $field_key = 'field_57767c396431d'; break; case 'pgm_subscriptions': $field_key = 'field_57767c886431e'; break; } return $field_key; } //6.6 function pgm_get_subscriber_data($subscriber_id){ $subscriber_data = array(); $subscriber = get_post($subscriber_id); if(isset($subscriber->post_type) && $subscriber->post_type == 'pgm_subscriber'){ $fname = get_field(pgm_get_acf_key('pgm_fname'),$subscriber_id); $lname = get_field(pgm_get_acf_key('pgm_lname'),$subscriber_id); $subscriber_data = array( 'name'=>$fname.' '.$lname, 'fname'=>$fname, 'lname'=>$lname, 'email'=>get_field(pgm_get_acf_key('pgm_email'),$subscriber_id), 'subscriptions'=>pgm_get_subscriptions($subscriber_id) ); } return $subscriber_data; } /* !7. CUSTOM POST TYPES */ /* !8. ADMIN PAGES */ /* !9. SETTINGS */ /* !10. MISCELLANEOUS */
2e5dd146ed7ea0ac6d5a37bc3e9ab4c2f7793371
[ "PHP" ]
2
PHP
atolat/ppmguru-mailing-list
060070773ca29b1833e7e6bc113b0ad846e99fa9
899d988ac8e7bab8f9b7e3bcb6365a5a765e50b4
refs/heads/master
<repo_name>carriercomm/sd<file_sep>/bin/sd #!/usr/bin/env node require('../')(process.argv.slice(2), function() { process.exit(); });<file_sep>/lib/index.js var exec = require('child_process').exec; module.exports = function(segs, done) { if (segs.length < 1) done(null); var cmd = 'sudo ' + segs.join(' '), sudo = exec(cmd); sudo.on('error', done); sudo.on('exit', done); sudo.on('close', done); process.stdin.pipe(sudo.stdin); sudo.stdout.pipe(process.stdout); //sudo.stderr.pipe(process.stderr); sudo.stderr.on('data', function(chunk) { if (chunk.toString() === 'Sorry, try again.\n') return; process.stdout.write(chunk); }); }<file_sep>/README.md # sd A CLI tool for convinence of `sudo` on Linux
bac35b3e46a44fa190200890c800d041b62cae9f
[ "JavaScript", "Markdown" ]
3
JavaScript
carriercomm/sd
bfc63f9000ef16bc0edaa1133cb004644502fdfc
74cb63504a55a7ec3b9f138cce762a596d8a5be7
refs/heads/master
<file_sep>package com.bacvt.bookmanager; import androidx.appcompat.app.AppCompatActivity; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; public class LoginActivity extends AppCompatActivity { private EditText pass , user; private Button login; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_login); pass = findViewById(R.id.pass); user = findViewById(R.id.user); login = findViewById(R.id.btn_login); login.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { String u = user.getText().toString(); String p = pass.getText().toString(); if (u.equalsIgnoreCase("a") && p.equalsIgnoreCase("a")) { startActivity(new Intent(getApplicationContext(), MainActivity.class)); finish(); } else { Toast.makeText(getApplicationContext(), "Username and password incorrect", Toast.LENGTH_SHORT).show(); } } }); } }
ca0400b7da5a477ff7406736ac925c0dc6ea1083
[ "Java" ]
1
Java
Tuna0612/BookManager
6a624accf67ad3b10e5db5d47c903551662d0acb
9d87ba8c3f6a59aa33ac6f08f184579a4938f270
refs/heads/master
<repo_name>cactusing/scl<file_sep>/README.md # scl It's all about <NAME>. She's an integral part of my life. <file_sep>/mo.js var hello = "Hello World!"; console.log(hello); var object_name = { key1: "value1", key2: "value", key3: function () { // 函数 }, key4: ["content1", "content2"] //集合 }; var Site = /** @class */ (function () { function Site() { } Site.name3 = function () { console.log("Runoob"); }; ; Site.name2 = function () { var hello2 = "Hello World!"; console.log("Runoob"); }; return Site; }()); var obj = new Site(); Site.name3(); <file_sep>/mo.ts const hello : string = "Hello World!"; console.log(hello); var object_name = { key1: "value1", // 标量 key2: "value", key3: function() { // 函数 }, key4:["content1", "content2"] //集合 }; class Site { static name3(): void { console.log("Runoob") }; static name2(): void { const hello2 : string = "Hello World!"; console.log("Runoob") } } const obj = new Site(); Site.name3();
c203b7a5c489f56dd1b79880e90ff4edaaf8d365
[ "Markdown", "TypeScript", "JavaScript" ]
3
Markdown
cactusing/scl
8d6f6b9a55b557200b9ceb8b3fa3e6086c66ca77
a0fabf4fb87775aa8621874efc1bcfc436612e5c
refs/heads/master
<file_sep>#!/usr/bin/env python2 # -*- coding: utf-8 -*- """ Created on Sat May 26 13:47:13 2018 @author: panrui """ ''' def is_even(p): sign=0 s=0 while s<len(p): for i in range(s,len(p)): minValue=p[i] minKey=i if p[i]<minValue: minKey=p.index(i) tmp=i i=p[minKey] p[minKey]=tmp sign=1-sign s+=1 print(p) if sign==0: return True else: return False ''' def is_even(p): sign=0 length=len(p) for i in range(length-1,0,-1): for j in range(i): if p[j]>p[j+1]: p[j],p[j+1]=p[j+1],p[j] sign=1-sign if sign==0: return True else: return False <file_sep>def count_wins(dice1, dice2): assert len(dice1) == 6 and len(dice2) == 6 dice1_wins, dice2_wins = 0, 0 for x in range(6): for y in range(6): if dice1[x]>dice2[y]: dice1_wins+=1 elif dice1[x]<dice2[y]: dice2_wins+=1 return (dice1_wins, dice2_wins) #the winning times of each of the 2 dices def find_the_best_dice(dices): #check whether among the three given dices there is one that is better than the remaining two dices. assert all(len(dice) == 6 for dice in dices) time_of_wins=[] for x in range(len(dices)): t=0 for y in range(len(dices)): if count_wins(dices[x],dices[y])[0]>count_wins(dices[x],dices[y])[1]: t+=1 time_of_wins.append(t) if max(time_of_wins)==len(time_of_wins)-1: return time_of_wins.index(max(time_of_wins)) else: return -1 def compute_strategy(dices): #takes a list of dices and returns a strategy. assert all(len(dice) == 6 for dice in dices) strategy = dict() strategy["choose_first"] = True if find_the_best_dice(dices)!=-1: strategy["first_dice"] = find_the_best_dice(dices) else: strategy["choose_first"] = False for i in range(len(dices)): strategy[i] = find_another_dice(dices,i) return strategy def find_another_dice(dices,i): for j in range(len(dices)): if count_wins(dices[j],dices[i])[0]>count_wins(dices[j],dices[i])[1]: return j <file_sep>#!/usr/bin/env python2 # -*- coding: utf-8 -*- """ Created on Mon May 7 20:13:11 2018 @author: panrui """ def change(amount): assert(amount >= 24) if amount == 24: return [5, 5, 7, 7] if amount == 25: return [5, 5, 5, 5, 5] if amount == 26: return [5, 7, 7, 7] if amount == 27: return [5, 5, 5, 5, 7] if amount == 28: return [7, 7, 7, 7] if amount == 29: return [5, 5, 5, 7, 7] coins = change(amount - 5) coins.append(5) return coins <file_sep># Online-Courses Posting source codes for some Coursera courses violates the [Coursera Honor Code](https://learner.coursera.help/hc/en-us/articles/209818863-Coursera-Honor-Code). I will make this repository private as soon as I upgrade my plan. <file_sep>import networkx as nx import pygraphviz as pgv from nxpd import draw, nxpdParams nxpdParams['show'] = 'ipynb' G = nx.DiGraph() G.add_edges_from([('a', 'b'), ('b', 'c'), ('b', 'd'), ('d', 'c'), ('a', 'd'), ('e', 'd'), ('f', 'a'), ('b', 'f')]) draw(G, layout='circo') print("Strongly connected components:") for scc in nx.strongly_connected_components(G)): print()
8f859937ef77b02066d7765af33dabb2cacd81aa
[ "Markdown", "Python" ]
5
Python
darthp/Online-Courses
e00511cfe4876ab72254fa824b97ab0d7566ce89
3eb39343e45389a862e4328fbaa89c4c706773bf
refs/heads/master
<repo_name>navirgino/codeup-java-exercises<file_sep>/src/shapes/ShapesTest.java package shapes; public class ShapesTest { public static void main(String[] args) { Measurable myShape = new Square(3); Measurable otherShape = new Rectangle(4, 1); //get length and get width only work when implemented in the interface, you will get a compile error // System.out.println(myShape.getLength()); // System.out.println(myShape.getWidth()); System.out.println(myShape.getArea() + " and " + myShape.getPerimeter()); System.out.println(otherShape.getArea() + " and " + otherShape.getPerimeter()); // //create a variable of the type Rectangle named box1 and assign it a new // // //instance of the rectangle class with a w of 4 and a l of 5 // Rectangle box1 = new Rectangle(5, 4); // //verify the getP and getA methods return 18 and 20 // System.out.println("Perimeter of rectangle box1 is: " + box1.getPerimeter()); // System.out.println("Area of rectangle box1 is: " + box1.getArea()); // // //create a variable of the type rectangle named box2 and assign it a new instance of the square class // //that has a side value of 5 // Rectangle box2 = new Square(5); // System.out.println("Perimeter of square box2 is: " + box2.getPerimeter()); // System.out.println("Area of square box2 is: " + box2.getArea()); } } <file_sep>/src/study/vehicle/Vehicle.java package study.vehicle; public class Vehicle { protected String carName; protected String wheels; protected boolean canItSteer; public void Vehicle(String carName, String wheels, boolean canItSteer){ this.carName = carName; this.wheels = wheels; this.canItSteer = canItSteer; } public String getCarName() { return carName; } public String getWheels() { return wheels; } public boolean isCanItSteer() { return canItSteer; } public void setCarName(String carName) { this.carName = carName; } public void setWheels(String wheels) { this.wheels = wheels; } public void setCanItSteer(boolean canItSteer) { this.canItSteer = canItSteer; } } <file_sep>/src/ControlFlowExercises.java import java.util.Scanner; import java.awt.BorderLayout; import javax.swing.JFrame; import javax.swing.JScrollPane; import javax.swing.JTable; public class ControlFlowExercises { public static void main(String[] args) { // Integer i = 5; // while (i <= 15){ // System.out.println(i++); // } // // long i = 2L; // do{ // System.out.println(i); // i = i*i; // }while (i <= 1000000); // for(int i = 5; i <= 15; i++){ // System.out.println(i++); // } // for(long i = 2L; i <= 1000000; i*=i){ // System.out.println(i); // } // for(int i = 1; i <= 100; i++){ // if(i%15 == 0){ // System.out.println("FizzBuzz"); // }else if(i%3 == 0){ // System.out.println("Fizz"); // }else if(i%5 == 0){ // System.out.println("Buzz"); // }else{ // System.out.println(i); // } // } Scanner scanner = new Scanner(System.in); System.out.print("Enter an integer you want to go up to: "); int num = scanner.nextInt(); System.out.println(num); int squared = num * num; int cubed = num * num * num; System.out.println("number | squared | cubed"); for(long i = 1; i <= num; i++){ System.out.println(" | | "); System.out.println(i +" | "+ i*i +" | " + i*i*i); } // JFrame frame = new JFrame(); // // frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // // // Object rowData[][] = { // {num, squared, cubed}, // }; // // Object columnNames[] = {"Number", "Squared", "Cubed"}; // // JTable table = new JTable(rowData, columnNames); // JScrollPane scrollPane = new JScrollPane(table); // frame.add(scrollPane, BorderLayout.CENTER); // frame.setSize(300, 150); // frame.setVisible(true); // // // System.out.println(table); //convert given number grades into letter grades //display the corresponding letter grade // System.out.println("Would you like to look at your letter grades?"); String confirm = scanner.next(); while(confirm.equalsIgnoreCase("YES")) { System.out.println("What was your numeric grade?"); System.out.println("Enter your grade: "); int grade = scanner.nextInt(); if(grade >= 88){ System.out.println("A"); }else if(grade >= 80){ System.out.println("B"); }else if(grade >= 67){ System.out.println("C"); }else if(grade >= 60){ System.out.println("D"); }else if(grade >= 0){ System.out.println("F"); }else{ System.out.println("Huh"); } } } } <file_sep>/src/Box/Math.java package Box; public class Math { public static double pi = 3.14159; public static int add(int x, int y){ return x + y; } public static int multiply(int x, int y){ return x * y; } } <file_sep>/src/grades/GradesApplication.java package grades; import util.Input; import java.util.HashMap; public class GradesApplication { //create a map for students and github usernames public static void create() { //create four student objects with atleast 3 grades Student nico = new Student("<NAME>"); nico.addGrade(90); nico.addGrade(100); nico.addGrade(80); Student christian = new Student("<NAME>"); christian.addGrade(100); christian.addGrade(100); christian.addGrade(100); Student thorfinn = new Student("<NAME>"); thorfinn.addGrade(40); thorfinn.addGrade(20); thorfinn.addGrade(60); Student ash = new Student("<NAME>"); ash.addGrade(10); ash.addGrade(30); ash.addGrade(5); //hashmap HashMap<String, Student> students = new HashMap<>(); //keys students.put("user", nico); students.put("username", christian); students.put("theUser", thorfinn); students.put("isuck", ash); //for each loop for printing out usernames to the console. System.out.println("WELCOME!"); System.out.println("Here are the usernames:"); String usernameSeperator = "|"; for (String key : students.keySet()) { System.out.println(usernameSeperator + key + usernameSeperator); } //create input object System.out.println("WHAT STUDENT DO YOU WANT INFO ON? "); Input input = new Input(); String userInput = input.getString(); //while loop for user input do{ if (students.get(userInput) != null) { System.out.println("Name: " + students.get(userInput).getName()); System.out.println("Current Avg: " + students.get(userInput).getGradeAverage()); }else{ System.out.println("That student does not exist!"); } System.out.println("Would you like to continue? [y/n]"); input.yesNo(); if(input.yesNo()){ System.out.println("Input another student"); userInput = input.getString(); }else { break; } }while(true); } //make main method public static void main(String[] args) { create(); } } <file_sep>/src/study/BankAccount.java //package study; //import java.util.Scanner; ////create a new class for a bank account //public class BankAccount { // // //TODO: create fields for the acct number, balance, customer name email, and phone number // protected String AccountNum; // protected String email; // protected String PhoneNum; // protected double balance; // //TODO: create getter for each field // // //get acct num // protected String getAccountNum(){ // return this.AccountNum; // } // //get email // protected String getEmail(){ // return this.email; // } // //get phone # // protected String getPhoneNum(){ // return this.PhoneNum; // } // //get balance // protected double getBalance(){ // return this.balance; // } // // //TODO: create setter for each field (i'm just gonna do the whole obj constructor) // protected void setBankAccount(String AccountNum, // String email, // String PhoneNum, // double balance) // { // this.AccountNum = AccountNum; // this.email = email; // this.PhoneNum = PhoneNum; // this.balance = balance; // } // // //TODO: create two additional methods // // 1. allow customer to deposit funds (this should increment the balance field) // // 2. allow customer to withdraw funds. (this should deduct from the balance field, // //but not allow the withdrawal to complete if there are insufficient funds!!!) // // // protected void depositFunds(double DepositAmount){ // this.balance += DepositAmount; // System.out.println("You have deposited an amount of " + DepositAmount + " your new balance " + // "is: " + this.balance); // } // // // protected void withdrawFunds(double WithdrawAmount){ // if(this.balance - WithdrawAmount < 0){ // System.out.println("Insufficient funds!!!!"); // }else{ // this.balance -= WithdrawAmount; // System.out.println("You have withdrawn an amount of "+ WithdrawAmount + " your new balance " + // "is: "+ this.balance); // } // } // //} <file_sep>/src/Practice.java import java.awt.*; import java.text.NumberFormat; import java.util.Arrays; import java.util.Date; public class Practice { public static void main(String[] args) { //int can only store whole numbers [1, 2, 3, 4, . . .] (up to 2bill) //byte range = [-127, 127]; 1 mem // byte age = 30; // int viewsCount = 2_123_456_789; // //need suffix to represent number as a long // long longCount = 3_123_456_789L; // //need suffix to represent number as a float // float price = 10.99f; // char letter = 'A'; // boolean isEligible = false; //// // byte age = 30; // Date now = new Date(); // System.out.println(now); // byte x = 1; // byte y = x; // x = 2; // //y is not affected because they are different from each other // System.out.println(y); // Point point1 = new Point(1, 1); // Point point2 = point1; // point1.x = 2; // // System.out.println(point1); // System.out.println(point2); // String message = " ello" + " wurld!!"; //// message.endsWith("!!"); // System.out.println(message.endsWith("!!")); // System.out.println(message.length()); // System.out.println(message.indexOf("!")); // System.out.println(message.replace("!", "*")); // System.out.println(message); // System.out.println(message.trim()); // String message = "c:\tWindows\\..."; // System.out.println(message); //arrays down below // int[] numbers = new int[5]; //// old syntax for array down below // numbers[0] = 1; // numbers[1] = 2; // System.out.println(Arrays.toString(numbers)); // System.out.println(numbers); // //new syntax for array down below (arrays are fixed length) // int[] numbers = {2, 3, 4, 5, 1, 4}; // Arrays.sort(numbers); // System.out.println(numbers.length); // System.out.println(Arrays.toString(numbers)); ////multi-dimensional array first brace are how many rows, second how many columns. // int[][] numbers = new int[2][3]; // //new way: // int[][] numbers = {{1, 2, 3}, {4, 5, 6}}; // numbers[0][0] = 1; // System.out.println(Arrays.deepToString(numbers)); //final means that java treats it as a constant // final float pi = 3.14F; //////////////////////////////// // //implicit casting // // byte > short > int > long > float > double // String x = "1"; // int y = Integer.parseInt(x) + 2; //2.0 + 1.1 // double z = Double.parseDouble(x) + 4; // System.out.println(x); // System.out.println(y); // System.out.println(z); // int result = Math.max(1, 2); // System.out.println(result); // int result = (int) Math.round(Math.random() * 100); // System.out.println(result); // 10% NumberFormat currency = NumberFormat.getCurrencyInstance(); String result = currency.format(1234567.891); System.out.println(currency); System.out.println(result); } } <file_sep>/src/Instructor.java public class Instructor extends Employee { //constructor public Instructor(String instructorName){ super(instructorName); } @Override public void sayHello(){ System.out.println("Hello Deimos!"); } @Override public void doWork(){ System.out.println("Teaching!"); System.out.println("Coding!"); System.out.println("Explaining!"); } } <file_sep>/src/ArraysExercises.java import java.util.Arrays; public class ArraysExercises { //TODO: create a static method named addPerson. should accept an array of Person objects, // as well as a single person obj to add to the passed array. //TODO: should return an array whose length is 1 greater than the passed array, with the passed // person object at the end of the array. public static Person[] addPerson(Person[] arr, Person newPerson) { //use copyOf to s.out the passed in person arr Person[] newArr = Arrays.copyOf(arr, arr.length + 1); //getting end of an array and assigning a new person newArr[newArr.length-1] = newPerson; //assigning relationship newPerson.rel = "gf"; //for each loop to iterate through the arr for (Person person : newArr) { System.out.println(person.getName()); System.out.println(person.rel); } return newArr; } //////////////////////// //main///////////////// /////////////////////// public static void main(String[] args) { // int[] numbers = {1, 2, 3, 4, 5}; // System.out.println(Arrays.toString(numbers)); //TODO: make an arr that holds 3 person objects. Person[] personArray = new Person[3]; Person person1 = new Person("Nico"); person1.rel = "mi"; Person person2 = new Person("Rain"); person2.rel = "pops"; Person person3 = new Person("Gloria"); person3.rel = "gma"; personArray[0] = person1; personArray[1] = person2; personArray[2] = person3; //TODO: assign a new instance of the Person class to each element. // System.out.println(personArray[0].getName()); //TODO: iterate through the array and print out the name of each person in the array. // ////forEach Person person :(in) the personArray // for (Person person : personArray) { // System.out.println(person.getName()); // System.out.println(person.rel); // // } // //alternatively a for loop // for(int i = 0; i < personArray.length; i++){ // System.out.println(personArray[i].getName()); // } addPerson(personArray, new Person("Adri")); } } <file_sep>/src/study/BankAccountTest.java //package study; // //public class BankAccountTest { // public static void main(String[] args) { // BankAccount newAccount = new BankAccount(); // BankAccount myAccount = new BankAccount(); // myAccount.setBankAccount( // "12345", // "<EMAIL>", // "123-456-7890", // 400.00); // System.out.println(myAccount.getAccountNum()); // System.out.println(myAccount.getBalance()); // System.out.println(myAccount.getEmail()); // System.out.println(myAccount.getPhoneNum()); // System.out.println(myAccount.getBalance()); // myAccount.depositFunds(500.00); // System.out.println(myAccount.getBalance()); // myAccount.withdrawFunds(560.00); // myAccount.withdrawFunds(300.00); // myAccount.withdrawFunds(40); // myAccount.withdrawFunds(1); // myAccount.depositFunds(600); // // System.out.println(myAccount.getAccountNum()); // // } //} <file_sep>/src/StringExercise.java import java.util.Scanner; public class StringExercise { public static void main(String[] args){ Scanner sc = new Scanner(System.in).useDelimiter(("\n")); System.out.println("We don't need no education"); System.out.println("We don't need no thought control"); System.out.println("Check \"this\" out!, \"s inside of \"s!"); System.out.println("In windows, the main drive is usually C:\\"); System.out.println("I can do backslashes \\, double backslashes \\\\,"); System.out.println("and the amazing triple backslash \\\\\\!"); //Create a class named Bob with a main method for the following exercise. //Bob is a lackadaisical teenager. In conversation, his responses are very limited. } } <file_sep>/src/HelloWorld.java public class HelloWorld { public static void main(String[] args){ System.out.println("Hello, World!"); //create an int variable named myFavoriteNumber and assign your // favorite number to it, then print it out to the console. int myFavoriteNumber = 23; System.out.println(myFavoriteNumber); //Create a String variable named myString and assign a string // value to it, then print the variable out to the console. String myString = "Banana"; System.out.println(myString); //Change your code to assign a character value to myString. // What do you notice? myString = "OtherBanana"; System.out.println(myString); //Change your code to assign the value 3.14159 to myString. //What happens? // myString = 3.14159 //Declare an long variable named myNumber, but do not assign anything to it. // Next try to print out myNumber to the console. // What happens? long myNumber; //Change your code to assign the value 3.14 to myNumber. // What do you notice? // myNumber = 3.14; //Change your code to assign the value 123L (Note the 'L' at the end) // to myNumber. myNumber= 123L; //Change your code to assign the value 123 to myNumber myNumber = 123; System.out.println(myNumber); //Change your code to declare myNumber as a float. Assign the value 3.14 to it. // What happens? What are two ways we could fix this? // float myNumber = 3.14; //Copy and paste the following code blocks one at a time and execute them int x = 5; System.out.println(x++); System.out.println(x); // int x = 5; // System.out.println(++x); // System.out.println(x); //Try to create a variable named class. //What happens? // int class //Object is the most generic type in Java. You can assign any value to a variable of type Object. //What do you think will happen when the following code is run? // Object hello; // System.out.println(); String theNumberThree = "three"; Object o = theNumberThree; // int three = (int) o; // int three = (int) "three"; // int x = 4; // x = x + 5; // // // int x = 3; // int y = 4; // y = y * x; // // int x = 10; // int y = 2; // x = x / y; // y = y - x; } } <file_sep>/src/codeup/CodeupTest.java package codeup; public class CodeupTest { public static void main(String[] args) { String[] sophie = {"Sophie", "K", "Olympic", "Macbook Pro"}; CodeupStudent Sophie = new CodeupStudent(sophie, true); Sophie.greeting(); Sophie.study(); System.out.println(Sophie.giveBusinessCards()); String[] nico = {"Nico", "V", "Deimos", "MacBook Air"}; CodeupStudent Nico = new CodeupStudent(nico, false); Nico.greeting(); Nico.study(); System.out.println(Nico.giveBusinessCards()); } } <file_sep>/src/challenges/ArrayChallenge.java package challenges; import java.lang.reflect.Array; import java.util.Arrays; public class ArrayChallenge { public static void sortIntegers(int[] intArr){ for(int i= 0; i < intArr.length; i++){ for(int j = i + 1; j < intArr.length; j++){ int tmp; if(intArr[i] < intArr[j]){ tmp = intArr[i]; intArr[i] = intArr[j]; intArr[j] = tmp; } } } System.out.println(Arrays.toString(intArr)); } public static void main(String[] args) { int[] arr = new int[]{5, 3, 2, 20}; sortIntegers(arr); } } <file_sep>/src/MethodsExercises.java import org.w3c.dom.ls.LSOutput; import java.util.Scanner; public class MethodsExercises { // public static int add(int a, int b) { // return a + b; // } // // public static int sub(int a, int b) { // return a - b; // } // // public static int multiplication(int a, int b) { // int res = 0; // for (int i = 0; i < a; i++) { // res += b; // } // return res; // } // // public static int divide(int a, int b) { // return a / b; // } // // public static int modulus(int a, int b) { // return a % b; // } //Create a method that validates that user input is in a certain range // //The method signature should look like this: // public static int getInteger(int min, int max) { // //import scanner for using next line etc // Scanner sc = new Scanner(System.in); // // //sout the prompt // System.out.print("Enter a number between " + min + " and " + max + ": "); //// int userInput = getInteger(1, 10); // // if (sc.hasNextInt()) { // // makes the scanner class a int variable // int userInput = sc.nextInt(); // // nested if else if it is a integer // if(userInput >= min && userInput <= max) { // return userInput; // } else { // System.out.println("Number out of range!"); // return getInteger(min, max); // } // // } else { // System.out.println("Invalid Input! "); // getInteger(min, max); // } // return 0; // } // // //// Calculate the factorial of a number. // public static int factorial(int min, int max) { // Scanner sc = new Scanner(System.in); // // //prompt user to enter an integer from 1 to 10 // System.out.println("Please put in a number between " + min + " and " + max + ": "); // // int userInput = sc.nextInt(); // // int variable for starting point and i // int i, start = 1; // //display the factorial from 1 to 10 // // //since it's a factorial i need a for loop // for (i = 1; i <= userInput; i++) { // // start = start * i; // if(userInput <= max && userInput >= min){ // System.out.println("Factorial of " + userInput + " x " + i + " is: " + start); // }else { // System.out.println("Sorry that's not within the range!"); // break; // } // // } // System.out.println("Your input was: "); // return userInput; // } //Create an application that simulates dice rolling. public static void rollDice(){ Scanner sc = new Scanner(System.in); //Prompt user what kind of dice they want to roll System.out.println("Soo... D2, D4, D6, or D20?"); int diceSides = sc.nextInt(); System.out.println("Would you like roll? [y/n]"); String roll = sc.next(); if(roll.equals("y")){ int diceOne = (int) (diceSides * Math.random() + 1); System.out.println("You have rolled your first " + diceSides + " sided dice."); System.out.println("You rolled a " + diceOne + "!"); int diceTwo = (int) (diceSides * Math.random() + 1); System.out.println("You have rolled your second " + diceSides + " sided dice."); System.out.println("You rolled a " + diceTwo + "!"); }else { System.out.println("ok"); } // sc.nextLine(); //Roll two (user input)-sided dice, then ask if they want to do it again. // System.out.println("Would you like to continue? [y/n]"); // String userInput = sc.nextLine(); // if(userInput.equals("n")){ // System.out.println("Thanks for playing!"); // // } else if (userInput.equals("y")) { // rollDice(); // } //return rollDice(); } public static void main(String[] args) { // System.out.println(add(3, 4)); // System.out.println(sub(4, 4)); // System.out.println(multiplication(3, 4)); // System.out.println(divide(12,4)); // System.out.println(modulus(4, 3)); // System.out.println(modulus(4, 4)); // System.out.println(getInteger(2, 8)); // System.out.println(factorial(1, 10)); // System.out.println(rollDice()); rollDice(); } } <file_sep>/src/util/InputTest.java package util; public class InputTest { public static void main(String[] args) { Input input = new Input(); System.out.println("Enter [y/n]"); System.out.println(input.yesNo()); input.getInt(1, 10); input.getInt(); System.out.println(input.yesNo()); Input newInput = new Input(); newInput.getDouble(1, 10); newInput.getDouble(); } }
2aef83591619d647c81e97cf2e08e13533d2223b
[ "Java" ]
16
Java
navirgino/codeup-java-exercises
2a6b5073e42d6ba4bca0f884b57724304ab82751
b9279b8dd4e9e138e018ce81a1bb052973c5ce9d
refs/heads/master
<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using talker.Models; namespace talker { public partial class _Default : Page { protected void Page_Load(object sender, EventArgs e) { } protected void CreateBid_Click(object sender, EventArgs e) { //string RawId = Request.QueryString["LiveBidId"]; //int OriginatingBidId = Convert.ToInt32(RawId); //System.Threading.Timer delayThenPlaceBid = new System.Threading.Timer(obj => { AddBidToDiscussions(OriginatingBidId); }, null, 1000, System.Threading.Timeout.Infinite); Response.Redirect("CreateBid.aspx"); } public void AddBidToDiscussions(int BidId) { /*DataContext _db = new DataContext(); ICollection<PlacedBid> bidsSoFar = _db.LiveBids.SingleOrDefault(p => p.BidID == BidId).PlacedBids; PlacedBid winningBid = null; double winningPrice = 0; foreach (PlacedBid pb in bidsSoFar) { if(pb.) }*/ } } }<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.ModelBinding; using System.Web.UI; using System.Web.UI.WebControls; using talker.Models; namespace talker { public partial class PlaceBid : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { } public IQueryable<LiveBid> GetLiveBid( [QueryString("LiveBidId")] int? LiveBidId) { var _db = new talker.Models.DataContext(); IQueryable<LiveBid> query = _db.LiveBids; if (LiveBidId.HasValue && LiveBidId > 0) { query = query.Where(p => p.BidID == LiveBidId); } else { query = null; } return query; } protected void productDetail_PageIndexChanging(object sender, EventArgs e) { } protected void PlaceBid_Click(object sender, EventArgs e) { DataContext _db = new DataContext(); string RawId = Request.QueryString["LiveBidId"]; int OriginatingBidId = Convert.ToInt32(RawId); /*PlacedBid placedBid = new PlacedBid { ReceivingMemberId = HttpContext.Current.User.Identity.Name, ProvidingMemberId = _db.LiveBids.SingleOrDefault(p => p.BidID == OriginatingBidId).ProvidingUserName, BidId = OriginatingBidId, BidTime = DateTime.Now, AssociatedBid = _db.LiveBids.SingleOrDefault(lb => lb.BidID == OriginatingBidId) };*/ Discussion newDiscussion = new Discussion { ProvidingUserName = _db.LiveBids.SingleOrDefault(p => p.BidID == OriginatingBidId).ProvidingUserName, ReceivingUserName = HttpContext.Current.User.Identity.Name, DiscussionStartTime = _db.LiveBids.SingleOrDefault(p => p.BidID == OriginatingBidId).AvailableStartTime, DiscussionEndTime = _db.LiveBids.SingleOrDefault(p => p.BidID == OriginatingBidId).AvailableEndTime, TransactionAmount = _db.LiveBids.SingleOrDefault(p => p.BidID == OriginatingBidId).DesiredBidPrice, Status = true, DateCreated = DateTime.Now }; LiveBid soldBid = _db.LiveBids.SingleOrDefault(p => p.BidID == OriginatingBidId); _db.LiveBids.Remove(soldBid); _db.Discussions.Add(newDiscussion); //_db.PlacedBids.Add(placedBid); //_db.LiveBids.SingleOrDefault(lb => lb.BidID == OriginatingBidId).PlacedBids.Add(placedBid); _db.SaveChanges(); Response.Redirect("LiveBids.aspx"); } } }<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.Linq; using talker.Models; using System.Web.ModelBinding; namespace talker { public partial class Home : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { string uname = HttpContext.Current.User.Identity.Name; DataContext _db = new DataContext(); } public IQueryable<LiveBid> GetCategoryBids([QueryString("catid")] int? categoryId) { var _db = new talker.Models.DataContext(); IQueryable<LiveBid> query = _db.LiveBids; if (categoryId.HasValue && categoryId > 0) { query = query.Where(p => p.CategoryID == categoryId); } return query; } public string CheckNullUser(User bidUser) { if (bidUser == null) return ""; else return bidUser.FName; } } }<file_sep>using System; using System.Collections.Generic; using System.Data.Entity; using System.Linq; using System.Web; namespace talker.Models { public class DataContext : DbContext { public DataContext() : base("DiscussionsDB") { } public DbSet<Discussion> Discussions { get; set; } public DbSet<LiveBid> LiveBids { get; set; } public DbSet<Category> Categories { get; set; } public DbSet<User> Users { get; set; } public DbSet<PlacedBid> PlacedBids { get; set; } public DbSet<CartItem> ShoppingCartItems { get; set; } public DbSet<Order> Orders { get; set; } public DbSet<OrderDetail> OrderDetails { get; set; } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.ComponentModel.DataAnnotations; namespace talker.Models { public class LiveBid { //[ScaffoldColumn(false)] [Key] public int BidID { get; set; } public DateTime AvailableStartTime { get; set; } public DateTime AvailableEndTime { get; set; } public double DesiredBidPrice { get; set; } public bool Status { get; set; } //True means the bid is live. False means it should have been transferred to the talks DB. public string ProvidingUserName { get; set; } public virtual User AppUser { get; set; } public int? CategoryID { get; set; } public virtual Category Category { get; set; } public virtual ICollection<PlacedBid> PlacedBids { get; set; } } }<file_sep>using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Web; namespace talker.Models { public class PlacedBid { [Key] public int PlacedBidId { get; set; } public string ReceivingMemberId { get; set; } public string ProvidingMemberId { get; set; } public int BidId { get; set; } public DateTime BidTime { get; set; } public double BiddedPrice { get; set; } public virtual LiveBid AssociatedBid { get; set; } } }<file_sep>using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using talker.logic; using talker.Models; namespace talker { public partial class AddToCartLimbo : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { string RawId = Request.QueryString["bidId"]; DataContext _db = new DataContext(); int OriginatingBidId = Convert.ToInt32(RawId); Discussion newDiscussion = new Discussion { ProvidingUserName = _db.LiveBids.SingleOrDefault(p => p.BidID == OriginatingBidId).ProvidingUserName, ReceivingUserName = HttpContext.Current.User.Identity.Name, DiscussionStartTime = _db.LiveBids.SingleOrDefault(p => p.BidID == OriginatingBidId).AvailableStartTime, DiscussionEndTime = _db.LiveBids.SingleOrDefault(p => p.BidID == OriginatingBidId).AvailableEndTime, TransactionAmount = _db.LiveBids.SingleOrDefault(p => p.BidID == OriginatingBidId).DesiredBidPrice, Status = true, DateCreated = DateTime.Now }; LiveBid soldBid = _db.LiveBids.SingleOrDefault(p => p.BidID == OriginatingBidId); _db.LiveBids.Remove(soldBid); _db.Discussions.Add(newDiscussion); _db.SaveChanges(); Response.Redirect("AddToCart.aspx?discussionId=" + newDiscussion.DiscussionID); } } }<file_sep>using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Web; namespace talker.Models { public class CartItem { [Key] public string ItemId { get; set; } public string CartId { get; set; } public DateTime DateCreated { get; set; } public int DiscussionId { get; set; } public virtual Discussion Discussion { get; set; } } }<file_sep>using System; using System.Linq; using System.Web; using System.Web.UI; using Microsoft.AspNet.Identity; using Microsoft.AspNet.Identity.Owin; using Owin; using talker.Models; using talker.logic; namespace talker.Account { public partial class Register : Page { protected void CreateUser_Click(object sender, EventArgs e) { var manager = Context.GetOwinContext().GetUserManager<ApplicationUserManager>(); var signInManager = Context.GetOwinContext().Get<ApplicationSignInManager>(); var user = new ApplicationUser() { UserName = Email.Text, Email = Email.Text }; IdentityResult result = manager.Create(user, Password.Text); if (result.Succeeded) { // For more information on how to enable account confirmation and password reset please visit http://go.microsoft.com/fwlink/?LinkID=320771 //string code = manager.GenerateEmailConfirmationToken(user.Id); //string callbackUrl = IdentityHelper.GetUserConfirmationRedirectUrl(code, user.Id, Request); //manager.SendEmail(user.Id, "Confirm your account", "Please confirm your account by clicking <a href=\"" + callbackUrl + "\">here</a>."); AddToUser(Email.Text); signInManager.SignIn( user, isPersistent: false, rememberBrowser: false); IdentityHelper.RedirectToReturnUrl(Request.QueryString["ReturnUrl"], Response); using(ShoppingCartActions userShoppingCart = new ShoppingCartActions()){ String cartId = userShoppingCart.GetCartId(); userShoppingCart.MigrateCart(cartId, user.Id); } } else { ErrorMessage.Text = result.Errors.FirstOrDefault(); } } //R-code public void AddToUser(string id) { // Retrieve the product from the database. DataContext _db = new DataContext(); var user = _db.Users.SingleOrDefault(c => c.Id == id); if (user == null) { // Create a new user if no user exists. user = new User { Id = id, FName = Name.Text, LName = "null", DateCreated = DateTime.Now }; _db.Users.Add(user); } else { // If the item does exist in the cart, // then add one to the quantity. //user.Quantity++; } _db.SaveChanges(); } } }<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using talker.Models; using talker.Account; using System.Web.ModelBinding; namespace talker { public partial class UpcomingDiscussions : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { } public IQueryable<Discussion> GetUpcomingDiscussions( [QueryString("UserId")] int? UserId) { var _db = new talker.Models.DataContext(); IQueryable<Discussion> query = _db.Discussions; string loggedInUser = HttpContext.Current.User.Identity.Name; if (!string.IsNullOrWhiteSpace(loggedInUser)) { query = query.Where(p => p.ProvidingUserName == loggedInUser); query = query.Where(p => p.DiscussionStartTime > DateTime.Now); } else { query = null; } return query; } } }<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using talker.Models; namespace talker { public partial class CreateBid : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { List<ListItem> categories = new List<ListItem>(); var _db = new talker.Models.DataContext(); IQueryable<Category> query = _db.Categories; List<Category> dd_categories = (from records in _db.Categories select records).ToList(); foreach (Category cat in dd_categories) { categories.Add(new ListItem(cat.CategoryName)); } CategoriesDropDown.DataSource = categories; CategoriesDropDown.DataBind(); } } protected void Advertize_Click(object sender, EventArgs e) { string LoggedInUser = HttpContext.Current.User.Identity.Name; DateTime StartDate = Calendar1.SelectedDate; string StartTimeTxt = txtStartTime.Text; DateTime StartTime = DateTime.ParseExact(StartTimeTxt, "hh:mm tt", System.Globalization.CultureInfo.CurrentCulture); StartDate = StartDate.AddHours(StartTime.Hour); StartDate = StartDate.AddMinutes(StartTime.Minute); string EndTimeTxt = txtEndTime.Text; DateTime EndTime = DateTime.ParseExact(EndTimeTxt, "hh:mm tt", System.Globalization.CultureInfo.CurrentCulture); DateTime EndDate = Calendar2.SelectedDate; EndDate = EndDate.AddHours(EndTime.Hour); EndDate = EndDate.AddMinutes(EndTime.Minute); string CategoryName = CategoriesDropDown.SelectedItem.Text; int CategoryId = CategoriesDropDown.SelectedIndex; DataContext _db = new DataContext(); LiveBid BidToPlace = new LiveBid { ProvidingUserName = LoggedInUser, AvailableStartTime = StartDate, AvailableEndTime = EndDate, DesiredBidPrice = Convert.ToDouble(TextBox1.Text), Status = true, CategoryID = _db.Categories.SingleOrDefault(c => c.CategoryName == CategoryName).CategoryID, Category = _db.Categories.SingleOrDefault(c => c.CategoryName == CategoryName),//fix - What if calendar entries are empty AppUser = _db.Users.Single(u => u.Id == LoggedInUser) }; _db.LiveBids.Add(BidToPlace); _db.SaveChanges(); Response.Redirect("LiveBids.aspx"); } public IQueryable<Category> GetCategoriesForList() { var _db = new talker.Models.DataContext(); IQueryable<Category> query = _db.Categories; return query; } protected void btnSave_Click(object sender, EventArgs e) { } protected void CategoriesDropDown_SelectedIndexChanged(object sender, EventArgs e) { int i = CategoriesDropDown.SelectedIndex; string j = CategoriesDropDown.SelectedItem.Text; string k = CategoriesDropDown.SelectedValue; string dummy = "dummy"; } } }<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Data.Entity; namespace talker.Models { public class DatabaseInitializer : DropCreateDatabaseIfModelChanges<DataContext> { protected override void Seed(DataContext context) { GetDiscussions().ForEach(c => context.Discussions.Add(c)); GetLiveBids().ForEach(p => context.LiveBids.Add(p)); GetCategories().ForEach(c => context.Categories.Add(c)); } private static List<Discussion> GetDiscussions() { var discussions = new List<Discussion> { new Discussion { DiscussionID = 1, ProvidingUserName = "ryu576", ReceivingUserName = "<EMAIL>", DiscussionStartTime = DateTime.Parse("2/21/2009 10:35 PM"), DiscussionEndTime = DateTime.Parse("2/21/2009 10:38 PM"), TransactionAmount = 0.1, Status = true, Rating = 0, DateCreated = DateTime.Parse("2/21/2014 10:38 PM") }, new Discussion { DiscussionID = 1, ProvidingUserName = "ryu576", ReceivingUserName = "<EMAIL>", DiscussionStartTime = DateTime.Parse("2/21/2009 10:35 PM"), DiscussionEndTime = DateTime.Parse("2/21/2009 10:38 PM"), TransactionAmount = 0.1, Status = true, Rating = 0, DateCreated = DateTime.Parse("2/21/2014 10:38 PM") }, new Discussion { DiscussionID = 1, ProvidingUserName = "ryu576", ReceivingUserName = "<EMAIL>", DiscussionStartTime = DateTime.Parse("2/21/2009 10:35 PM"), DiscussionEndTime = DateTime.Parse("2/21/2009 10:38 PM"), TransactionAmount = 0.1, Status = true, Rating = 0, DateCreated = DateTime.Parse("2/21/2014 10:38 PM") }, new Discussion { DiscussionID = 1, ProvidingUserName = "ryu576", ReceivingUserName = "<EMAIL>", DiscussionStartTime = DateTime.Parse("2/21/2009 10:35 PM"), DiscussionEndTime = DateTime.Parse("2/21/2009 10:38 PM"), TransactionAmount = 0.1, Status = true, Rating = 0, DateCreated = DateTime.Parse("2/21/2014 10:38 PM") }, new Discussion { DiscussionID = 1, ProvidingUserName = "ryu576", ReceivingUserName = "<EMAIL>", DiscussionStartTime = DateTime.Parse("2/21/2009 10:35 PM"), DiscussionEndTime = DateTime.Parse("2/21/2009 10:38 PM"), TransactionAmount = 0.1, Status = true, Rating = 0, DateCreated = DateTime.Parse("2/21/2014 10:38 PM") }, }; return discussions; } private static List<LiveBid> GetLiveBids() { var liveBids = new List<LiveBid> { new LiveBid { BidID = 1, ProvidingUserName = "ryu576", AvailableStartTime = DateTime.Parse("2/21/2009 10:35 PM"), AvailableEndTime = DateTime.Parse("2/21/2009 10:38 PM"), DesiredBidPrice = 1.1, Status = false, CategoryID = 1 }, new LiveBid { BidID = 2, ProvidingUserName = "ryu576", AvailableStartTime = DateTime.Parse("2/21/2009 10:35 PM"), AvailableEndTime = DateTime.Parse("2/21/2009 10:38 PM"), DesiredBidPrice = 1.1, Status = true, CategoryID = 2 }, new LiveBid { BidID = 3, ProvidingUserName = "ryu576", AvailableStartTime = DateTime.Parse("2/21/2009 10:35 PM"), AvailableEndTime = DateTime.Parse("2/21/2009 10:38 PM"), DesiredBidPrice = 1.1, Status = true, CategoryID = 3 }, }; return liveBids; } private static List<Category> GetCategories() { var Categories = new List<Category> { new Category { CategoryID = 1, CategoryName = "Physics", Description = "Physics " }, new Category { CategoryID = 2, CategoryName = "Chemistry", Description = "Chemistry" }, new Category { CategoryID = 3, CategoryName = "Math", Description = "Math" }, new Category { CategoryID = 4, CategoryName = "Legal", Description = "Legal" }, new Category { CategoryID = 5, CategoryName = "Biology", Description = "Biology" }, new Category { CategoryID = 6, CategoryName = "Music", Description = "Music" }, new Category { CategoryID = 7, CategoryName = "Painting", Description = "Painting" } }; return Categories; } } }<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.ComponentModel.DataAnnotations; namespace talker.Models { public class Discussion { [Key] public int DiscussionID { get; set; } public string ProvidingUserName { get; set; } public string ReceivingUserName { get; set; } public DateTime DiscussionStartTime { get; set; } public DateTime DiscussionEndTime { get; set; } public DateTime DateCreated { get; set; } public double TransactionAmount { get; set; } public bool Status { get; set; } public int? Rating { get; set; } //public virtual ApplicationUser AppUser { get; set; } } }
eec6126b465bf49d043b310c13782a54b9d70f31
[ "C#" ]
13
C#
ryu577/talker
43ec207317f06e39263f26813f9a407e597a4c51
d46ec9e52dc854c75ada6ac7e41b9bce5531e864
refs/heads/master
<file_sep>// // ViewController.swift // Calculator // // Created by 井上航 on 2015/06/14. // Copyright (c) 2015年 Wataru.I. All rights reserved. // import UIKit class ViewController: UIViewController { var num:Float = 0 var st: Float = 0 var operation:Int = 0 var floatdisplay:Bool = false //小数表示するか否か true -> する var addstr:String = "" var historystr:String = "" @IBOutlet weak var historyText: UITextView! //履歴 @IBOutlet weak var mainlabel: UILabel! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } //番号ボタンが押された時のlabel更新 private func renewal(btnum:Float){ //演算子を選択していないとエラーメッセージを表示 if operation == 5 { mainlabel.text = String(format: "%.f (ERR:Choice Ope)",num) }else{ if st != 0 { st = st * 10 } st += btnum mainlabel.text = String(format: "%.f", st) addstr = String(format: "%.f ", st) historystr += addstr historyText.text = historyText.text + String(format: "%.f", btnum) //履歴に数字を追加 } } // 演算の実行 private func clc(){ if operation == 0 { num = st } else if operation == 1 { num += st } else if operation == 2 { num -= st } else if operation == 3 { num *= st } else if operation == 5 { //do nothing 次は必ず演算子 } } //演算子ボタンが押された時の動き private func pressope(x:Int){ if operation != 5 { clc() } st = 0 if operation != 0 { historyText.text = historyText.text + String(format: "%.f", num) } operation = x } @IBAction func bt0() { renewal(0) } @IBAction func bt1() { renewal(1) } @IBAction func bt2() { renewal(2) } @IBAction func bt3() { renewal(3) } @IBAction func bt4() { renewal(4) } @IBAction func bt5() { renewal(5) } @IBAction func bt6() { renewal(6) } @IBAction func bt7() { renewal(7) } @IBAction func bt8() { renewal(8) } @IBAction func bt9() { renewal(9) } @IBAction func plus() { pressope(1) mainlabel.text = String(format: "%.f +", num) historyText.text = historyText.text + String(" + ") //履歴に演算子を追加 } @IBAction func minus() { pressope(2) mainlabel.text = String(format: "%.f -", num) historyText.text = historyText.text + String(" - ") //履歴に演算子を追加 } @IBAction func multiply() { pressope(3) mainlabel.text = String(format: "%.f ×", num) historyText.text = historyText.text + " × " //履歴に演算子を追加 } @IBAction func btac() { st = 0 num = 0 operation = 0 //初期化 mainlabel.text = String(0) historyText.text = historyText.text + String("---AC---\n") } @IBAction func btclc() { //「=」ボタン clc() operation = 5 //追加演算の準備 mainlabel.text = String(format: "= %.f", num) historyText.text = historyText.text + String(format: " = %.f \n", num) //履歴に演算子を追加 } @IBAction func resetHistory() { historyText.text = nil } }
798ff495e6bc80af80f8bc12d6865df624bb0ef8
[ "Swift" ]
1
Swift
ka0ru19/calculator
e5fb813e1301f8817db6a676fe79ea81b9c2a464
e8301ac4d03292a4920bdade07280369d64f89f1
refs/heads/master
<repo_name>xiaxiao1/Designpattern24<file_sep>/app/src/main/java/com/xiaxiao/designpattern24/iterator/interfaces/IProjectIterator.java package com.xiaxiao.designpattern24.iterator.interfaces; import java.util.Iterator; /** * Created by xiaxiao on 2017/6/19. */ public interface IProjectIterator extends Iterator { } <file_sep>/app/src/main/java/com/xiaxiao/designpattern24/visitor/IVisitor.java package com.xiaxiao.designpattern24.visitor; /** * Created by xiaxiao on 2017/7/31. */ /* * * */ public interface IVisitor { public void visit(StudentData studentData); } <file_sep>/app/src/main/java/com/xiaxiao/designpattern24/mediator/AbsMediator.java package com.xiaxiao.designpattern24.mediator; /** * Created by xiaxiao on 2017/8/2. */ public abstract class AbsMediator { protected Colleague1 colleague1; protected Colleague2 colleague2; protected Colleague3 colleague3; public AbsMediator() { colleague1=new Colleague1(this); colleague2=new Colleague2(this); colleague3=new Colleague3(this); } public abstract void execute(int type); } <file_sep>/app/src/main/java/com/xiaxiao/designpattern24/singleton/ExtendSingleTon.java package com.xiaxiao.designpattern24.singleton; import java.util.ArrayList; import java.util.Random; /** * Created by xiaxiao on 2017/6/28. */ public class ExtendSingleTon { //定义最多能产生的实例数量 private static int maxNumOfEmperor = 2; //每个皇帝都有名字, 使用一个ArrayList来容纳, 每个对象的私有属性 private static ArrayList<String> nameList = new ArrayList<String>(); //定义一个列表, 容纳所有的皇帝实例 private static ArrayList<ExtendSingleTon> emperorList = new ArrayList<ExtendSingleTon>(); //当前皇帝序列号 private static int countNumOfEmperor = 0; //产生所有的对象 static { for (int i = 0; i < maxNumOfEmperor; i++) { emperorList.add(new ExtendSingleTon("皇" + (i + 1) + "帝")); } } private ExtendSingleTon() { //世俗和道德约束你, 目的就是不产生第二个皇帝 }//传入皇帝名称, 建立一个皇帝对象 private ExtendSingleTon(String name) { nameList.add(name); }//随机获得一个皇帝对象 public static ExtendSingleTon getInstance() { Random random = new Random(); //随机拉出一个皇帝, 只要是个精神领袖就成 countNumOfEmperor = random.nextInt(maxNumOfEmperor); return emperorList.get(countNumOfEmperor); }//皇帝发话了 public static void say() { System.out.println(nameList.get(countNumOfEmperor)); } }<file_sep>/app/src/main/java/com/xiaxiao/designpattern24/chain_of_responsibility/Father.java package com.xiaxiao.designpattern24.chain_of_responsibility; import com.xiaxiao.designpattern24.util.DPUtil; /** * Created by xiaxiao on 2017/7/28. */ public class Father extends AbsHandler { public Father() { super(AbsHandler.HANDLE_LEVEL_FATHER); } @Override public void response(IRequest request) { DPUtil.print("i am father , I handle the request"); request.request(); } } <file_sep>/app/src/main/java/com/xiaxiao/designpattern24/builder/KartCarBuilder.java package com.xiaxiao.designpattern24.builder; import com.xiaxiao.designpattern24.builder.interfaces.CarBuilder; import com.xiaxiao.designpattern24.builder.interfaces.CarModel; import java.util.ArrayList; /** * Created by xiaxiao on 2017/7/24. */ public class KartCarBuilder extends CarBuilder { // KartCar kartCar = new KartCar(); KartCar kartCar; @Override public CarModel getCarModel() { return kartCar; } /** * 应该说有了其他的三个方法的话,,这个就可以废掉了吧 * @param list * @return */ @Override public CarBuilder setOrder(ArrayList<String> list) { this.kartCar.setOrder(list); return this; } @Override public CarBuilder setOrder() { this.kartCar.setOrder(this.order); return this; } @Override public CarBuilder prepareACarmodel() { kartCar = new KartCar(); return this; } } <file_sep>/app/src/main/java/com/xiaxiao/designpattern24/abstractfactory/human/FemaleBlackHuman.java package com.xiaxiao.designpattern24.abstractfactory.human; import com.xiaxiao.designpattern24.util.DPUtil; /** * Created by xiaxiao on 2017/7/13. */ public class FemaleBlackHuman extends YelloHuman { public void sex() { DPUtil.print("黑人女的"); } } <file_sep>/app/src/main/java/com/xiaxiao/designpattern24/chain_of_responsibility/IHandler.java package com.xiaxiao.designpattern24.chain_of_responsibility; /** * Created by xiaxiao on 2017/7/28. */ public interface IHandler { /*设置下一个处理者*/ public void setNext(IHandler handler); /* *//*设置自己的级别*//* public void setLevel(int level); */ public void handleRequeset(IRequest request); } <file_sep>/app/src/main/java/com/xiaxiao/designpattern24/composite/StaffNodeInterface.java package com.xiaxiao.designpattern24.composite; import java.util.ArrayList; /** * Created by xiaxiao on 2017/7/27. * * 这个模式写的例子和设计模式之禅书上的不太一样,感觉应该是可以的吧, brach和leaf都是node啊 */ public interface StaffNodeInterface { public void addChild(StaffNodeInterface child); /* * 补充的,便于向上回溯 * */ public void setParent(StaffNodeInterface parent); public StaffNodeInterface getParent(); public String getInfo(); public ArrayList<StaffNodeInterface> getChildren(); public boolean hasChild(); } <file_sep>/app/src/main/java/com/xiaxiao/designpattern24/abstractfactory/factory/MaleHumanFactory.java package com.xiaxiao.designpattern24.abstractfactory.factory; import com.xiaxiao.designpattern24.abstractfactory.human.Human; import com.xiaxiao.designpattern24.abstractfactory.human.MaleBlackHuman; import com.xiaxiao.designpattern24.abstractfactory.human.MaleYelloHuman; /** * Created by xiaxiao on 2017/7/11. */ public class MaleHumanFactory extends AbstractFactory { @Override public Human createYellowHuman() { return new MaleYelloHuman(); } @Override public Human createBlackHuman() { return new MaleBlackHuman(); } @Override public Human createWhiteHuman() { return null; } } <file_sep>/app/src/main/java/com/xiaxiao/designpattern24/iterator/Project.java package com.xiaxiao.designpattern24.iterator; import com.xiaxiao.designpattern24.iterator.interfaces.IProject; import com.xiaxiao.designpattern24.iterator.interfaces.IProjectIterator; import com.xiaxiao.designpattern24.iterator.interfaces.ProjectIterator; import java.util.ArrayList; /** * Created by xiaxiao on 2017/6/19. */ public class Project implements IProject { private ProjectEntry projectEntry; private ArrayList<Project> projectEntries = new ArrayList<>(); public Project(ProjectEntry projectEntry) { this.projectEntry = projectEntry; } public Project() { } @Override public void getInfo() { System.out.println(projectEntry.getInfo()); } @Override public void add(String name,String num,String cost) { ProjectEntry entry = new ProjectEntry(name, num, cost); projectEntries.add(new Project(entry)); } @Override public IProjectIterator iterator() { return new ProjectIterator(this.projectEntries); } public class ProjectEntry { private String name; private String num; private String cost; public ProjectEntry(String name, String num, String cost) { this.name = name; this.num = num; this.cost = cost; } public String getInfo() { return "ProjectEntry{" + "cost='" + cost + '\'' + ", name='" + name + '\'' + ", num='" + num + '\'' + '}'; } } } <file_sep>/app/src/main/java/com/xiaxiao/designpattern24/mediator/Mediator.java package com.xiaxiao.designpattern24.mediator; /** * Created by xiaxiao on 2017/8/2. */ /* * 想不出来比较贴切的情景,看来还是对业务的抽象提取能力不够。 * 凑合看着理解了 * */ public class Mediator extends AbsMediator { public static final int WORK_TYPE_12=12; public static final int WORK_TYPE_13=13; public static final int WORK_TYPE_23=23; public static final int WORK_TYPE_123=123; @Override public void execute(int type) { if (type==WORK_TYPE_12) { this.mediator12(); } if (type==WORK_TYPE_13) { this.mediator13(); } if (type==WORK_TYPE_23) { this.mediator23(); } if (type==WORK_TYPE_123) { this.mediator123(); } } public void mediator12() { super.colleague1.selfWork(); super.colleague2.toghterWork(); } public void mediator13() { super.colleague1.selfWork(); super.colleague3.toghterWork(); } public void mediator23() { super.colleague2.selfWork(); super.colleague3.toghterWork(); } public void mediator123() { super.colleague1.selfWork(); super.colleague2.toghterWork(); super.colleague3.toghterWork(); } } <file_sep>/app/src/main/java/com/xiaxiao/designpattern24/strategy/MoneyStrategy.java package com.xiaxiao.designpattern24.strategy; import com.xiaxiao.designpattern24.strategy.interfaces.IStrategy; import com.xiaxiao.designpattern24.util.DPUtil; /** * Created by xiaxiao on 2017/6/22. */ public class MoneyStrategy implements IStrategy{ @Override public void execute() { DPUtil.print("多花钱,给她买各种好东西"); } } <file_sep>/app/src/main/java/com/xiaxiao/designpattern24/bridge/interfaces/Crop.java package com.xiaxiao.designpattern24.bridge.interfaces; /** * Created by xiaxiao on 2017/7/25. */ public abstract class Crop { private Product product; public Crop(Product project) { this.product = project; } public void produce() { this.product.beProduced(); } public void sell() { this.product.beSelled(); } public void makeMoney() { this.produce(); this.sell(); } } <file_sep>/app/src/main/java/com/xiaxiao/designpattern24/abstractfactory/factory/FemaleHumanFactory.java package com.xiaxiao.designpattern24.abstractfactory.factory; import com.xiaxiao.designpattern24.abstractfactory.human.FemaleBlackHuman; import com.xiaxiao.designpattern24.abstractfactory.human.FemaleYelloHuman; import com.xiaxiao.designpattern24.abstractfactory.human.Human; /** * Created by xiaxiao on 2017/7/11. */ public class FemaleHumanFactory extends AbstractFactory { @Override public Human createYellowHuman() { return new FemaleYelloHuman(); } @Override public Human createBlackHuman() { return new FemaleBlackHuman(); } @Override public Human createWhiteHuman() { return null; } } <file_sep>/app/src/main/java/com/xiaxiao/designpattern24/factorymethod/AbstractFactory.java package com.xiaxiao.designpattern24.factorymethod; /** * Created by xiaxiao on 2017/7/11. */ public abstract class AbstractFactory { public abstract <T extends Human> T createHuman(Class<T> humanClass); } <file_sep>/app/src/main/java/com/xiaxiao/designpattern24/flyweight/SignInfo4Poll.java package com.xiaxiao.designpattern24.flyweight; /** * Created by xiaxiao on 2017/8/3. */ public class SignInfo4Poll extends SignInfo { /* * 细粒度对象的外部状态 * */ String key; public SignInfo4Poll(String key) { this.key = key; } public String getKey() { return key; } public void setKey(String key) { this.key = key; } } <file_sep>/app/src/main/java/com/xiaxiao/designpattern24/command/commands/AbstractCommand.java package com.xiaxiao.designpattern24.command.commands; import com.xiaxiao.designpattern24.command.bean.Staff; /** * Created by xiaxiao on 2017/7/26. */ public abstract class AbstractCommand { //最后接收执行命令的当然是苦逼的员工了 protected Staff staff; public AbstractCommand(Staff receiver) { this.staff = receiver; // execute(this.staff); } /* * 具体执行什么命令,由继承的子类来实现 * */ protected abstract void execute(Staff receiver); public void execute() { execute(this.staff); } } <file_sep>/app/src/main/java/com/xiaxiao/designpattern24/observer/GF.java package com.xiaxiao.designpattern24.observer; import com.xiaxiao.designpattern24.observer.interfaces.IGirlFriend; import com.xiaxiao.designpattern24.observer.interfaces.MyObserver; import com.xiaxiao.designpattern24.util.DPUtil; /** * Created by xiaxiao on 2017/7/27. */ public class GF implements IGirlFriend,MyObserver { String name; public GF(String name) { this.name = name; } @Override public void doSomething(String s) { DPUtil.print(this.name+"我在看着你哦,你正在"+s); } @Override public void update(String meg) { DPUtil.print("行为已被监视:"); this.doSomething(meg); } } <file_sep>/app/src/main/java/com/xiaxiao/designpattern24/mediator/Colleague1.java package com.xiaxiao.designpattern24.mediator; import com.xiaxiao.designpattern24.util.DPUtil; /** * Created by xiaxiao on 2017/8/2. */ public class Colleague1 extends AbsColleague { public Colleague1(AbsMediator mediator) { super(mediator); } public void selfWork() { DPUtil.print("我是员工1 ,我在做自己的事情"); } public void toghterWork() { DPUtil.print("我是员工1 ,我正在和其他同事一起协作"); super.mediator.execute(Mediator.WORK_TYPE_12); } } <file_sep>/app/src/main/java/com/xiaxiao/designpattern24/chain_of_responsibility/Husband.java package com.xiaxiao.designpattern24.chain_of_responsibility; import com.xiaxiao.designpattern24.util.DPUtil; /** * Created by xiaxiao on 2017/7/28. */ public class Husband extends AbsHandler { public Husband() { super(AbsHandler.HANDLE_LEVEL_HUSBAND); } @Override public void response(IRequest request) { DPUtil.print("i am husband , I handle the request"); request.request(); } } <file_sep>/app/src/main/java/com/xiaxiao/designpattern24/abstractfactory/human/Human.java package com.xiaxiao.designpattern24.abstractfactory.human; /** * Created by xiaxiao on 2017/7/11. */ public interface Human { void cry(); void laugh(); void talk(); void sex(); } <file_sep>/app/src/main/java/com/xiaxiao/designpattern24/abstractfactory/human/MaleBlackHuman.java package com.xiaxiao.designpattern24.abstractfactory.human; import com.xiaxiao.designpattern24.util.DPUtil; /** * Created by xiaxiao on 2017/7/13. */ public class MaleBlackHuman extends YelloHuman { public void sex() { DPUtil.print("黑人男的"); } } <file_sep>/app/src/main/java/com/xiaxiao/designpattern24/adapter/UserImpl.java package com.xiaxiao.designpattern24.adapter; import com.xiaxiao.designpattern24.util.DPUtil; /** * Created by xiaxiao on 2017/7/19. */ public class UserImpl implements UserInterface { @Override public String getName() { DPUtil.print("这是名字"); return null; } @Override public String getPhone() { DPUtil.print("这是电话号码"); return null; } @Override public String getAddress() { DPUtil.print("这是地址"); return null; } } <file_sep>/app/src/main/java/com/xiaxiao/designpattern24/memento/oldtype/Wife.java package com.xiaxiao.designpattern24.memento.oldtype; /** * Created by xiaxiao on 2017/8/4. */ public class Wife { private String mood; public String getMood() { return mood; } public void setMood(String mood) { this.mood = mood; } public WifeMemento getMemento() { return new WifeMemento((this.mood)); } } <file_sep>/app/src/main/java/com/xiaxiao/designpattern24/flyweight/SignInfo.java package com.xiaxiao.designpattern24.flyweight; /** * Created by xiaxiao on 2017/8/3. */ /* * 细粒度对象 * 维护对象的内部状态, 外部状态在子类SignInfo4Pool类中 * * */ public class SignInfo { String id; String location; String name; public String getId() { return id; } public void setId(String id) { this.id = id; } public String getLocation() { return location; } public void setLocation(String location) { this.location = location; } public String getName() { return name; } public void setName(String name) { this.name = name; } } <file_sep>/app/src/main/java/com/xiaxiao/designpattern24/iterator/interfaces/ProjectIterator.java package com.xiaxiao.designpattern24.iterator.interfaces; import java.util.ArrayList; /** * Created by xiaxiao on 2017/6/19. */ public class ProjectIterator implements IProjectIterator { ArrayList projects; int currentIndex; public ProjectIterator(ArrayList arrayList) { this.projects = arrayList; } @Override public boolean hasNext() { return (currentIndex<projects.size()&&projects.get(currentIndex)!=null); } @Override public Object next() { return projects.get(currentIndex++); } @Override public void remove() { } } <file_sep>/app/src/main/java/com/xiaxiao/designpattern24/visitor/StudentVisitor.java package com.xiaxiao.designpattern24.visitor; import com.xiaxiao.designpattern24.util.DPUtil; /** * Created by xiaxiao on 2017/7/31. */ public class StudentVisitor implements IVisitor { @Override public void visit(StudentData studentData) { DPUtil.print("我是个观察者 我就是看看数据"); DPUtil.print(studentData.getInfo()); } } <file_sep>/app/src/main/java/com/xiaxiao/designpattern24/command/bean/Staff.java package com.xiaxiao.designpattern24.command.bean; /** * Created by xiaxiao on 2017/7/26. *员工累 */ public abstract class Staff { public abstract void work(); } <file_sep>/app/src/main/java/com/xiaxiao/designpattern24/composite/LiShiStaff.java package com.xiaxiao.designpattern24.composite; import java.util.ArrayList; /** * Created by xiaxiao on 2017/7/27. */ public class LiShiStaff extends AbstractStaffNode { private ArrayList<StaffNodeInterface> children = new ArrayList<>(); public LiShiStaff(String name, String position, String salary) { super(name, position, salary); } @Override public void addChild(StaffNodeInterface child) { this.children.add(child); child.setParent(this); } @Override public ArrayList<StaffNodeInterface> getChildren() { return this.children; } @Override public boolean hasChild() { return this.children.size()>0; } } <file_sep>/app/src/main/java/com/xiaxiao/designpattern24/facade/LetterProgress.java package com.xiaxiao.designpattern24.facade; import com.xiaxiao.designpattern24.util.DPUtil; /** * Created by xiaxiao on 2017/7/17. */ public class LetterProgress implements LetterInterface { @Override public void writeContext(String context) { DPUtil.print("开始写信:"+context); } @Override public void writeEnvelope(String address) { DPUtil.print("写信封:"+address); } @Override public void putLetterInEnvelope() { DPUtil.print("把信装进信封"); } @Override public void sendLetter() { DPUtil.print("把信投递出去"); } } <file_sep>/app/src/main/java/com/xiaxiao/designpattern24/bridge/Clothes.java package com.xiaxiao.designpattern24.bridge; import com.xiaxiao.designpattern24.bridge.interfaces.Product; import com.xiaxiao.designpattern24.util.DPUtil; /** * Created by xiaxiao on 2017/7/25. */ public class Clothes extends Product { @Override public void beProduced() { DPUtil.print("衣服做好了"); } @Override public void beSelled() { DPUtil.print("衣服卖了"); } } <file_sep>/app/src/main/java/com/xiaxiao/designpattern24/state/CloseState.java package com.xiaxiao.designpattern24.state; import com.xiaxiao.designpattern24.util.DPUtil; /** * Created by xiaxiao on 2017/8/1. */ /* * 什么状态负责执行什么操作 * */ public class CloseState extends LiftState { @Override public void open() { super.liftContext.setLiftState(LiftContext.OPEN_STATE); super.liftContext.getLiftState().open(); } @Override public void close() { DPUtil.print("OK:门关上了"); } @Override public void run() { super.liftContext.setLiftState(LiftContext.RUN_STATE); super.liftContext.getLiftState().run(); } @Override public void stop() { super.liftContext.setLiftState(LiftContext.STOP_STATE); super.liftContext.getLiftState().stop(); } } <file_sep>/README.md # Designpattern24 设计模式 <file_sep>/app/src/main/java/com/xiaxiao/designpattern24/bridge/HouseCrop.java package com.xiaxiao.designpattern24.bridge; import com.xiaxiao.designpattern24.bridge.interfaces.Crop; import com.xiaxiao.designpattern24.bridge.interfaces.Product; import com.xiaxiao.designpattern24.util.DPUtil; /** * Created by xiaxiao on 2017/7/25. */ public class HouseCrop extends Crop { public HouseCrop(House project) { super(project); } public void makeMoney() { super.makeMoney(); DPUtil.print("哈哈,卖房子真赚钱啊"); } } <file_sep>/app/src/main/java/com/xiaxiao/designpattern24/mediator/Colleague2.java package com.xiaxiao.designpattern24.mediator; import com.xiaxiao.designpattern24.util.DPUtil; /** * Created by xiaxiao on 2017/8/2. */ public class Colleague2 extends AbsColleague { public Colleague2(AbsMediator mediator) { super(mediator); } public void selfWork() { DPUtil.print("我是员工2 ,我在做自己的事情"); } public void toghterWork() { DPUtil.print("我是员工2,我正在和其他同事一起协作"); } } <file_sep>/app/src/main/java/com/xiaxiao/designpattern24/facade/Test.java package com.xiaxiao.designpattern24.facade; import com.xiaxiao.designpattern24.util.DPUtil; /** * Created by xiaxiao on 2017/7/17. */ public class Test { public static class Hello{ public void say() { DPUtil.print("nihao"); } } public class Hei extends Hello { public void say() { super.say(); DPUtil.print("child is saying "); } } Hei hei; public void Ha() { hei = new Hei(); hei.say(); } } <file_sep>/app/src/main/java/com/xiaxiao/designpattern24/proxy/force/ForceGamePlayerProxy.java package com.xiaxiao.designpattern24.proxy.force; import com.xiaxiao.designpattern24.util.DPUtil; /** * Created by xiaxiao on 2017/6/26. * 游戏代练的 ,,对外调用的是他,但是真正好干活的还是被代理的人 */ public class ForceGamePlayerProxy implements ForceIGamePlayer ,ForceIProxy{ private ForceIGamePlayer player; public ForceGamePlayerProxy(ForceIGamePlayer iGamePlayer) { this.player = iGamePlayer; } @Override public void login(String name, String password) { this.player.login(name,password); } @Override public void killBoss() { this.player.killBoss(); } @Override public void update() { DPUtil.print("升级要收费的"); this.player.update(); makeMoney(); } //这里就表示返回的是代理的代理 @Override public ForceIGamePlayer getProxy() { return null; } @Override public void makeMoney() { DPUtil.print("赚了5块钱"); } } <file_sep>/app/src/main/java/com/xiaxiao/designpattern24/decorator/interfaces/Person.java package com.xiaxiao.designpattern24.decorator.interfaces; /** * Created by xiaxiao on 2017/6/19. */ public abstract class Person { public String name; public Person(String name) { this.name = name; } public String getName() { return this.name; } public abstract void showHair(); public void printMes(String mes) { System.out.println(mes); } } <file_sep>/app/src/main/java/com/xiaxiao/designpattern24/state/LiftState.java package com.xiaxiao.designpattern24.state; import java.util.HashMap; import java.util.TreeMap; /** * Created by xiaxiao on 2017/8/1. */ public abstract class LiftState { protected LiftContext liftContext; public void setLiftContext(LiftContext liftContext) { this.liftContext = liftContext; // HashMap h; // TreeMap t; } public abstract void open(); public abstract void close(); public abstract void run(); public abstract void stop(); } <file_sep>/app/src/main/java/com/xiaxiao/designpattern24/flyweight/SignInfoFactory.java package com.xiaxiao.designpattern24.flyweight; import com.xiaxiao.designpattern24.util.DPUtil; import java.util.ArrayList; import java.util.HashMap; /** * Created by xiaxiao on 2017/8/3. */ public class SignInfoFactory { private static HashMap<String,SignInfo> pool = new HashMap<>(); public static SignInfo getSiginInfo(String key) { SignInfo signInfo=null; if (pool.containsKey(key)) { signInfo = pool.get(key); DPUtil.print("from the pool"); } else { signInfo = new SignInfo4Poll(key); pool.put(key, signInfo); DPUtil.print("new added"); } return signInfo; } } <file_sep>/app/src/main/java/com/xiaxiao/designpattern24/command/bean/UI.java package com.xiaxiao.designpattern24.command.bean; import com.xiaxiao.designpattern24.command.bean.Staff; import com.xiaxiao.designpattern24.util.DPUtil; /** * Created by xiaxiao on 2017/7/26. */ public class UI extends Staff { @Override public void work() { DPUtil.print("UI设计师在设计界面 "); } } <file_sep>/app/src/main/java/com/xiaxiao/designpattern24/util/DPUtil.java package com.xiaxiao.designpattern24.util; /** * Created by xiaxiao on 2017/6/22. */ public class DPUtil { public static void print(String mes) { System.out.println(mes); } public static void splitLine() { DPUtil.print("---------------------------------------------------------"); } } <file_sep>/app/src/main/java/com/xiaxiao/designpattern24/chain_of_responsibility/Son.java package com.xiaxiao.designpattern24.chain_of_responsibility; import com.xiaxiao.designpattern24.util.DPUtil; /** * Created by xiaxiao on 2017/7/28. */ public class Son extends AbsHandler { public Son() { super(AbsHandler.HANDLE_LEVEL_SON); } @Override public void response(IRequest request) { DPUtil.print("i am son, I handle the request"); request.request(); } } <file_sep>/app/src/main/java/com/xiaxiao/designpattern24/decorator/LongHairDecorator.java package com.xiaxiao.designpattern24.decorator; import com.xiaxiao.designpattern24.decorator.interfaces.GirlHairDecorator; import com.xiaxiao.designpattern24.decorator.interfaces.Person; /** * Created by xiaxiao on 2017/6/19. */ public class LongHairDecorator extends GirlHairDecorator { public LongHairDecorator(Person person) { super(person); } public void showLong() { printMes(getName()+"我的头发是很长很长的哦"); } @Override public void showHair() { showLong(); super.showHair(); } } <file_sep>/app/src/main/java/com/xiaxiao/designpattern24/templatemethod/AbstractCar.java package com.xiaxiao.designpattern24.templatemethod; /** * Created by xiaxiao on 2017/7/20. * 由于模版方式模式的特性 所以这应该是一个抽象类,而不是一个接口 */ public abstract class AbstractCar { public abstract void start(); public abstract void stop(); public abstract void alarm(); //模版方法的核心 public void run(){ this.start(); this.alarm(); this.stop(); } } <file_sep>/app/src/main/java/com/xiaxiao/designpattern24/command/commands/AddUICommand.java package com.xiaxiao.designpattern24.command.commands; import com.xiaxiao.designpattern24.command.bean.Staff; import com.xiaxiao.designpattern24.command.bean.UI; import com.xiaxiao.designpattern24.util.DPUtil; /** * Created by xiaxiao on 2017/7/26. */ public class AddUICommand extends AbstractCommand { /* * 这里是指定的UI命令了。所以不需要对外提供传参,直接内置就好了。 * * */ public AddUICommand() { super(new UI()); } @Override protected void execute(Staff receiver) { DPUtil.print("这是一个给UI设计师的命令"); receiver.work(); } }
ece1b0faacedaef4ee96ea222a63cee40eb9ca6d
[ "Markdown", "Java" ]
47
Java
xiaxiao1/Designpattern24
5711cfe110ba398fa753e3fa4475b077885fe76e
3c194bb91eb2856533f5cbc2fb9202465462b80b
refs/heads/master
<repo_name>ChoongWengFei2799/DiceRoller<file_sep>/app/src/main/java/com/example/diceroller/MainActivity.kt package com.example.diceroller import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.widget.Button import android.widget.TextView class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) val rollButton: Button = findViewById(R.id.roll_button) rollButton.setOnClickListener { rollDice() } val countUpButton: Button = findViewById(R.id.count_button) countUpButton.setOnClickListener { countUp() } val resetButton: Button = findViewById(R.id.reset_button) resetButton.setOnClickListener { reset() } } private fun rollDice() { val randomInt1 = (1..6).random() val randomInt2 = (1..6).random() val randomInt3 = (1..6).random() val total = randomInt1 + randomInt2 + randomInt3 val text = "$randomInt1 + $randomInt2 + $randomInt3 =" val resultText1: TextView = findViewById(R.id.first) val resultText: TextView = findViewById(R.id.result_text) resultText1.text = text resultText.text = total.toString() } private fun countUp() { val resultText: TextView = findViewById(R.id.result_text) val num = Integer.parseInt(resultText.text.toString()) + 1 if(num<19) resultText.text = num.toString() } private fun reset() { val resultText1: TextView = findViewById(R.id.first) val resultText: TextView = findViewById(R.id.result_text) val reset = "DiceRoller" resultText1.text = "" resultText.text = reset } }
fa2a1e80130f9b6a348104cd3e2f79f03e1873b9
[ "Kotlin" ]
1
Kotlin
ChoongWengFei2799/DiceRoller
40fb7c64695aef5fb3daf7232489cd6283cf86ab
dffa5ccc08efed7566bc9823f3e316328c33d0af
refs/heads/master
<file_sep># SOATeamReligion This is the starting repository for Team Religion in SOA Spring 2020. <file_sep>// smooth scrolling using jQuery easing functions $('.js-scroll-trigger').click(function () { var target = $(this.hash); if (target.length) { // animate scxroll, apply time and type of easing // try 'easeOutQuint', 'easeOutBounce', 'easeInOutBack', 'easeOutElastic' $('html, body').animate({ scrollTop: (target.offset().top - 54) }, 700, 'easeOutQuint'); // close responsive menu (hamburger menu) $('.navbar-collapse').collapse('hide'); return false; } }); // activate scrollspy to add active class to navbar items $('body').scrollspy({ target: '#mainNav', offset: 60 });
1a6a998693e02b367e630f158cd3dcd842b1bddd
[ "Markdown", "JavaScript" ]
2
Markdown
Evmfig/SOATeamReligion
2849e91d7c4dba98f5692cf09fb37e42ccb2bfab
b27fddb2c3ab085edc5247bd3490266eda5e0ee3
refs/heads/master
<repo_name>21-Coding/APIFriday<file_sep>/AnimalShelter/Controllers/BirdsController.cs using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Microsoft.EntityFrameworkCore; using AnimalShelter.Models; namespace AnimalShelter.Controllers { [Route("api/[controller]")] [ApiController] public class BirdsController : ControllerBase { private AnimalShelterContext _db; public BirdsController(AnimalShelterContext db) { _db = db; } [HttpGet] public ActionResult<IEnumerable<Bird>> Get() { return _db.Birds.ToList(); } [HttpGet("{id}")] public ActionResult<Bird> Get(int id) { return _db.Birds.FirstOrDefault(tweety => tweety.BirdId == id); } [HttpPost] public void Post([FromBody] Bird bird) { _db.Birds.Add(bird); _db.SaveChanges(); } [HttpPut("{id}")] public void Put(int id, [FromBody] Bird bird) { _db.Entry(bird).State = EntityState.Modified; _db.SaveChanges(); } [HttpDelete("{id}")] public void Delete(int id) { Bird leftNest = _db.Birds.FirstOrDefault(tweety => tweety.BirdId == id); _db.Birds.Remove(leftNest); _db.SaveChanges(); } } } <file_sep>/AnimalShelter/Controllers/DogsController.cs using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Microsoft.EntityFrameworkCore; using AnimalShelter.Models; namespace AnimalShelter.Controllers { [Route("api/[controller]")] [ApiController] public class DogsController : ControllerBase { private AnimalShelterContext _db; public DogsController(AnimalShelterContext db) { _db = db; } [HttpGet] public ActionResult<IEnumerable<Dog>> Get() { return _db.Dogs.ToList(); } [HttpGet("{id}")] public ActionResult<Dog> Get(int id) { return _db.Dogs.FirstOrDefault(dawg => dawg.DogId == id); } [HttpPost] public void Post([FromBody] Dog dog) { _db.Dogs.Add(dog); _db.SaveChanges(); } [HttpPut("{id}")] public void Put(int id, [FromBody] Dog dog) { _db.Entry(dog).State = EntityState.Modified; _db.SaveChanges(); } [HttpDelete("{id}")] public void Delete(int id) { Dog dawgGone = _db.Dogs.FirstOrDefault(dawg => dawg.Dog.Id == id); _db.Dogs.Remove(dawgGone); _db.SaveChanges(); } } } <file_sep>/AnimalShelter/Models/AnimalShelterContext.cs using Microsoft.EntityFrameworkCore; namespace AnimalShelter.Models { public class AnimalShelterContext : DbContext { public AnimalShelterContext(DbContextOptions<AnimalShelterContext> options) : base(options){} public DbSet<Bird> Birds { get; set; } public DbSet<Dog> Dogs { get; set; } protected override void OnModelCreating(ModelBuilder builder) { builder.Entity<Bird>() .HasData( new Bird { BirdId = 1, Name = "Bert", Breed = "Eagle", Age = 2, Gender = "Male" }, new Bird { BirdId = 2, Name = "Ernie", Breed = "Woodpecker", Age = 6, Gender = "Female" }, new Bird { BirdId = 3, Name = "Elmo", Breed = "Hawk", Age = 1, Gender = "Male" }, new Bird { BirdId = 4, Name = "Mator", Breed = "Red Robin", Age = 5, Gender = "Female" }, new Bird { BirdId = 5, Name = "Goofy", Breed = "Hummingbird", Age = 3, Gender = "Female" } ); builder.Entity<Dog>() .HasData( new Dog { DogId = 1, Name = "Nate", Breed = "Poodle", Age = 2, Gender = "Female" }, new Dog { DogId = 2, Name = "Chuck", Breed = "Bulldog", Age = 4, Gender = "Male" }, new Dog { DogId = 3, Name = "Vest", Breed = "Terrier", Age = 7, Gender = "Female" }, new Dog { DogId = 4, Name = "Nick", Breed = "Weiner", Age = 2, Gender = "Male" }, new Dog { DogId = 5, Name = "Larry", Breed = "Beagle", Age = 2, Gender = "Female" } ); } } }
57af904a7297e7d0c14681d87ae0802130dbaae7
[ "C#" ]
3
C#
21-Coding/APIFriday
106ec5933d4119428249c1e051084472c60bb73c
ecb0f372c823a89fd06909418690a00cfc9ab14d
refs/heads/master
<repo_name>StillerHarpo/listWindows<file_sep>/listWindows.py #! /usr/bin/env nix-shell #! nix-shell -i python3.5 -p python35 python35Packages.psutil wmctrl from wmctrl import Window as W from subprocess import call import psutil import curses import os def getStrings(): stdscr.clear() windows=W.list() keys=["<KEY>"] # keys to chose the window keyComb=[] # generate a key Combination for each window if (len(keys)<len(windows)): count=0 isBreak=False for i in keys: for j in keys: if (count==len(windows)): break isBreak=True keyComb.append(i+j) count+=1 if isBreak: break else: keyComb=keys[0:len(windows)] actice= W.get_active() # dont show this program count=0 for win in windows: if win == actice: del windows[count] break count+=1 windowNames=[] # get the correct name for programs in terminals for win in windows: name=win.wm_name pids=[win.pid] if (name=="termite"): # TODO make it portable for other terminals pids=psutil.Process(pids[0]).children() if(len(pids)>0 ): name=pids[0].name() if (name=="zsh"): # TODO make it portable for other shells pids=pids[0].children() if(len(pids)>0 ): name=pids[0].name() windowNames.append(name) ws=[x.desktop for x in windows] windowNumber=[0]*(max(ws)+1) for i in (ws): windowNumber[i]+=1 count=0 countL=0 countWs=0 for i in windowNumber: # print the lines if(i%2==0): middle=(i/2) else: middle=((i+1)/2) for j in range(i): if(j==middle-1): stdscr.addstr(countL,0,str(countWs)+"| ["+keyComb[count]+"]: "+windowNames[count]) else: stdscr.addstr(countL,0," | ["+keyComb[count]+"]: "+windowNames[count]) count+=1 countL+=1 if(i!=0): countL+=1 # print a empty line between workspaces countWs+=1 stdscr.refresh() return keyComb , [ x.id for x in windows], ws stdscr = curses.initscr() curses.curs_set(0) curses.noecho() curses.cbreak() keyComb, winID, ws = getStrings() savedWsFile=open("/var/tmp/notifyWindows") try: savedWs=eval(savedWsFile.read()) except SyntaxError: savedWs=[1] savedWsFile.close() savedWsFile=open( os.getenv("HOME") + "/scripts/var/notifyWindows", 'w') while True: c = stdscr.getch() if c == ord('q'): # close this programm savedWsFile.write(str(savedWs)) break elif c == ord('n'): # focus the next empty workspace for i in range(0,len(ws)): if not i in ws: call(["wmctrl","-s", str(i)]) savedWs[0]=i+1 savedWsFile.write(str(savedWs)) break break elif c == ord('x'): # close the window count=0 if keyComb[0]=="f": c = stdscr.getch() for i in keyComb: if ord(i[0])==c: call(["wmctrl","-ic", str(winID[count])]) keyComb, winID, ws= getStrings() break count+=1 else: c1 = stdscr.getch() c2 = stdscr.getch() for i in keyComb: if ord(i[0])==c1 and ord(i[1])==c2: call(["wmctrl","-ic", str(winID[count])]) keyComb, winID, ws= getStrings() break count+=1 continue else: # focus the window count=0 isBreak=False if keyComb[0]=="ff": c1=c c2=stdscr.getch() for i in keyComb: if ord(i[0])==c1 and ord(i[1])==c2: call(["wmctrl","-ia", winID[count]]) savedWs[0]=ws[count]+1 savedWsFile.write(str(savedWs)) isBreak=True break count+=1 else: for i in keyComb: if ord(i[0])==c: stdscr.refresh() call(["wmctrl","-ia", winID[count]]) savedWs[0]=ws[count]+1 savedWsFile.write(str(savedWs)) isBreak=True break count+=1 if isBreak: break savedWsFile.close() curses.nocbreak() stdscr.keypad(False) curses.echo() curses.endwin()
008853bd1ace72d4b37ca6080ea25729d16aca01
[ "Python" ]
1
Python
StillerHarpo/listWindows
4e18d12824a6817656a64ff867767eabfe1222aa
bff986c21a9adee3f6b1aab0f7208314cc98acba
refs/heads/master
<file_sep>import ctypes as C libp = C.CDLL('./src/libprueba.so') tres_i=C.c_int(3) cuatro_i=C.c_int(4) res_i=C.c_int() tres_f=C.c_float(3) cuatro_f=C.c_float(4) res_f=C.c_float() libp.add_int_ref(C.byref(tres_i), C.byref(cuatro_i),C.byref(res_i)) print(res_i) libp.add_float_ref(C.byref(tres_f),C.byref(cuatro_f),C.byref(res_f)) print(res_f) #pruebo vectores in1=(C.c_int*3)(1,3,4) in2=(C.c_int*3)(0,-1,3) out=(C.c_int*3)(0,0,0) libp.add_int_array(C.byref(in1),C.byref(in2),C.byref(out),C.c_int(3))
f4b94bb3159b6a770a41e7782f0a326d7d7756b7
[ "Python" ]
1
Python
marisolosman/HOpython-compiled
a80fb922dc52194e4f120de8db783e72017a90ae
f197cf495dbff10336fdd2a92fe14b1ae94d928d
refs/heads/master
<file_sep> //create idb here console.log('testing idb before creating a db : ', idb); let dbPromise = idb.open('ALC-currenct-db', 2, upgradeDb => { console.log('start creating db'); switch(upgradeDb.oldVersion) { case 0: var keyValStore = upgradeDb.createObjectStore('convertion-rate'); keyValStore.put("{an objectwith all the pairs rate}", "single currency"); case 1: upgradeDb.createObjectStore('currencies'); //upgradeDb.createObjectStore('currencies', { keyPath: 'currencyName' }); } }); //for test purpose read that first entry dbPromise.then(db => { let tx = db.transaction('convertion-rate'); let keyValStore = tx.objectStore('convertion-rate'); return keyValStore.get('single currency'); }).then(val => { console.log('"single currency" :', val); }); let serviceReg = () =>{ if(!navigator.serviceWorker) return; navigator.serviceWorker .register('./js/sw.js') .then(reg =>{ reg.addEventListener('statechange',() =>{ if(reg.waiting){ currenciesDisplay(); } }); reg.addEventListener('updatefound', () => { fetch('https://free.currencyconverterapi.com/api/v5/currencies') .then(response => { return response.json(); }) .then(jsonval => { console.log('---------------------currencies-------------'); dbPromise.then(db => { let tx = db.transaction('currencies', 'readwrite'); let currenciesStore = tx.objectStore('currencies'); // for(const value in jsonval.results){ currenciesStore.put(jsonval.results, 'all'); //console.log(jsonval.results[value]); // } return tx.complete; }).then(() => { console.log('currencies updated'); currenciesDisplay(); }); }) .catch(err => { console.log('---------------------currencies fetch error-------------', err); }); console.log("from the deep [installing] [waiting] [active]", reg.installing, reg.waiting, reg.active); }); console.log("successfully register service worker", reg); currenciesDisplay(); }) .catch(err => { console.log("failed for register service worker", err); }) } console.log("servive worker controller state", navigator.serviceWorker.controller); serviceReg(); let we; function changeText(id) { //id.innerHTML = "Ooops!"; console.log(id); we = id; } currenciesDisplay = () => { console.log('################################################################################################'); dbPromise.then(db => { let tx = db.transaction('currencies'); var keyValStore = tx.objectStore('currencies'); return keyValStore.get('all'); }).then(vals => { console.log(vals); let currenciesArray = []; for(const val in vals){ currenciesArray.push(vals[val]); //currenciesArray.push(vals[val].currencyName); } const sortCurrencies = Array.from(currenciesArray).sort((previous, next) => { // Sort the currencies in Alphebetical order if (previous.currencyName < next.currencyName) { return -1; } else if (previous.currencyName > next.currencyName) { return 1; } return 0; }); // Populate currencies return sortCurrencies.map(currency => { const option = document.createElement('option'); option.value = currency.id; option.textContent = `${currency.currencyName} (${currency.id})`; document.querySelector('#fromCurrency').appendChild(option); document.querySelector('#toCurrency').appendChild(option.cloneNode(true)); }); }); }
e2d2adfbd688258d69ebf9eaf83ae5eebeab5666
[ "JavaScript" ]
1
JavaScript
emmyprinso/ALC7DaysOfCode
53c9155b5271c3caa48082983339b6aab8e3e99e
55bec488b07cb05c23dec2e8eeaa77ed72e104a8
refs/heads/master
<file_sep>import vue from '@vitejs/plugin-vue' const path = require('path') /** * @type {import('vite').UserConfig} */ export default { resolve: { alias: [{ find: "/@", replacement: path.resolve(__dirname, 'src') }], optimizeDeps: { include: [ "javascript-time-ago/locale/de" ], }, }, plugins: [vue()], base: './', // 引入第三方的配置 optimizeDeps: { include: ["axios"] }, // 代理请求 proxy: { '/api': { target: 'http://localhost:8088', changeOrigin: true, rewrite: path => path.replace(/^\/api/, '') } }, resolve: { extensions: ['.js', '.vue', '.json', '.ts', '.tsx'] }, }<file_sep>import request from '../utils/request' export default { getMovie(id) { console.log("in getMovie"); return request({ method: 'get', url: '', data: { } }); } }<file_sep>import { createApp } from 'vue' import App from './App.vue' import Router from '/src/router/index.js'; import ElementPlus from 'element-plus' import 'element-plus/lib/theme-chalk/index.css' const app = createApp(App).use(Router).use(ElementPlus).mount('#app')
9345f1eae8093a5c714d5ddd22b3a469bf618c2a
[ "JavaScript" ]
3
JavaScript
FightWithoutFire/element-plus-vite-starter
841ad870804281abd975f11ea90d315519371603
64ddc8b66fb562c645dc5cbffaba627eb8c8fd6a
refs/heads/master
<repo_name>ivysanba/password-generator<file_sep>/README.md # Password Generator Starter Code In this application the user will be ask a series of questions in order to generate a password. The user will be asked for a minimum length and a maximum length of characters for the password. Then the user will be given th eoptino to pick pbetween 1 and 4 options from the following: - Having lower case charcaters - Having upper case characters - Having numbers - Having special charcaters There will be different ways to validate the user's responses. Finally the user will be given a new password. URL: https://ivysanba.github.io/friendly-parakeet/ Here are some images: ![Alt text](./img/Image1.jpg?raw=true "Open App") ![Alt text](./img/Image2.jpg?raw=true "Minimum length") ![Alt text](./img/Image3.jpg?raw=true "Maximum length") ![Alt text](./img/Image4.jpg?raw=true "Next you need to chose at least 1 of the following") ![Alt text](./img/Image5.jpg?raw=true "Lower case?") ![Alt text](./img/Image6.jpg?raw=true "Upper case?") ![Alt text](./img/Image7.jpg?raw=true "Do you want numbers?") ![Alt text](./img/Image8.jpg?raw=true "Do you want special characters?") ![Alt text](./img/Image9.jpg?raw=true "Password Generated") ![Alt text](./img/Image10.jpg?raw=true "Console info") <file_sep>/script.js // Assignment code here var minLength = 0; var maxLength = 0; var lowerCase = false; var upperCase= false; var numeric = false; var specialChar = false; var alphabet = "abcdefghijklmnopqrstuvwxyz"; var numbers = "0123456789"; var specialChars = "!\"#$%&'()*+,-./:;<=>?@[\\]^_`{|}~"; var amountSpecialChar = 0; var charsSelected= []; var mandatoryMin = 0; var passLength = 0; var password =""; // console.log(specialChars); // -----------------------Get references to the #generate element------------------------ var generateBtn = document.querySelector("#generate"); // ----------------------------- Functions created--------------------------------------- //0 - Reset values function resetValues(){ minLength = 0; maxLength = 0; lowerCase = false; upperCase= false; numeric = false; specialChar = false; amountSpecialChar = 0; charsSelected= []; mandatoryMin = 0; passLength = 0; password =""; } //1 - Ask for min length function passMinLength(isCanceled){ var flag = "Failed"; while (flag == "Failed") { window.minLength = prompt("Please enter an integer number for the minimum length, needs to be at least 8"); if (minLength === null || minLength < 8) { isCanceled = true; return isCanceled; //break out of the function early }else if (Number.isInteger(parseInt(minLength))){ flag = "Success"; } } }; //2 - Ask for max length function passMaxLength(isCanceled){ var flag = "Failed"; while (flag == "Failed") { // console.log(flag); window.maxLength = prompt("Please enter an integer number for the maximum length, with a maximum number of 128 and make sure is larger or equal than the minimum length"); if (maxLength === null || maxLength > 128) { isCanceled = true; return isCanceled; //break out of the function early }else if (Number.isInteger(parseInt(maxLength)) && (parseInt(maxLength) >= parseInt(minLength))){ flag = "Success"; } } }; //3 - Ask for set of special characters to be included function specialCharacters(){ var flag = "Failed"; while (flag == "Failed") { alert("Next you need to pick at least one type of character to be included out of the next 4 options."); window.lowerCase = confirm("Do you want Lower Case letters in your password?"); if (lowerCase == true) { amountSpecialChar += 1; } window.upperCase = confirm("Do you want Upper Case letters in your password?"); if (upperCase == true) { amountSpecialChar += 1; } window.numeric = confirm("Do you want numbers in your password?"); if (numeric == true) { amountSpecialChar += 1; } window.specialChar = confirm("Do you want special characters in your password?"); if (specialChar == true) { amountSpecialChar += 1; } if (amountSpecialChar > 0){ flag = "Success"; } } }; // 3- Length of the password function randomizeLength(){ // The length needs to allow for all the special characters so the min needs to be allow for lal the types if (minLength < amountSpecialChar){ mandatoryMin = amountSpecialChar; }else{ mandatoryMin = minLength; } if (maxLength == minLength){ passLength = maxLength; }else{ passLength = Math.floor(Math.random() * (parseInt(maxLength) - parseInt(mandatoryMin)) + parseInt(minLength)); } }; // 4 - Create password function createPassword(){ var i = 0 while(i < passLength){ if (lowerCase == true && i < passLength){ password += alphabet.charAt(Math.floor(Math.random() * alphabet.length)); i+= 1; } if (upperCase == true && i < passLength){ var upperCaseLetter = alphabet.charAt(Math.floor(Math.random() * alphabet.length)); password += upperCaseLetter.toUpperCase(); i+= 1; } if (numeric == true && i < passLength){ password += numbers.charAt(Math.floor(Math.random() * numbers.length)); i+= 1; } if (specialChar == true && i < passLength){ password += specialChars.charAt(Math.floor(Math.random() * specialChars.length)); i+= 1; } }; return password; } // -----------------------Code calling functions------------------------------------------ function writePassword() { // Clear values resetValues(); var isCanceled = false; isCanceled = passMinLength(isCanceled ); if (isCanceled ){ return; }else{ isCanceled = passMaxLength(isCanceled ); } if (isCanceled ){ return; }else{ specialCharacters(); } randomizeLength(); var password = createPassword(); var passwordText = document.querySelector("#password"); passwordText.value = password; }; // -----------------------Add event listener to generate button------------------------------ generateBtn.addEventListener("click", writePassword);
799145f910a8579c84f9a69fb24cd17f8557a36b
[ "Markdown", "JavaScript" ]
2
Markdown
ivysanba/password-generator
6b7e33bfa25bc7877c168240659d192afbbe3c56
315aa3ba15d6846b838d4306dbe4f8bb27aec6cc
refs/heads/master
<repo_name>camilomicrosys/konecta_prueba<file_sep>/app/Views/vistasdelsistema/listar_solicitudes.php <?php //el mesnaje pasado a la visat principal para ver si esta correcto o errado $mensaje; $liquidaciones; //llamado de modelo para buscar toca desde la vista use App\Models\EmpleadosModel; $objeto_administrador = new EmpleadosModel(); //lamamos el helper de iconos $datos = iconos(); //aca sacamos los iconos ya que la funcion del helper lo puse a retornar un array $iconoEnblanco = $datos[0]; $iconoEditar = $datos[1]; $iconoAtras = $datos[2]; $iconoGuardar = $datos[3]; $iconoCerrar = $datos[4]; $iconoEliminar = $datos[5]; $iconoListar = $datos[6]; $iconoAgregarPersona = $datos[7]; $iconoAgregar = $datos[8]; $iconoCrearModal = $datos[9]; $iconoGestionar = $datos[10]; $iconoDesblokear = $datos[11]; $iconoLiquidar = $datos[12]; $iconoResetear = $datos[13]; $iconoReportes = $datos[14]; ?> <!-- Content Wrapper. Contains page content --> <div class="content-wrapper"> <!-- Content Header (Page header) --> <div class="content-header"> <div class="container-fluid"> <div class="row mb-2"> <div class="col-sm-6"> <h1 class="m-0 text-dark">Gestiona las solicitudes <i class="fas fa-key"></i></h1> </div><!-- /.col --> <div class="col-sm-6"> <ol class="breadcrumb float-sm-right"> <li class="breadcrumb-item"><a href="#">Home</a></li> <li class="breadcrumb-item active">Konecta v1</li> </ol> </div><!-- /.col --> </div><!-- /.row --> </div><!-- /.container-fluid --> </div> <table id="example" class="container" class="table table-striped table-bordered" style="width:100%"> <thead> <tr> <th>CODIGO</th> <th>DESCRIPCION</th> <th>RESUMEN</th> <th>EMPLEADO</th> </tr> </thead> <?php for ($i = 0; $i < count($liquidaciones); $i++) { ?> <tr> <td><?php echo $liquidaciones[$i]->{'CODIGO'}; ?></td> <td><?php echo $liquidaciones[$i]->{'DESCRIPCION'}; ?></td> <td><?php echo $liquidaciones[$i]->{'RESUMEN'}; ?></td> <td><?php echo $liquidaciones[$i]->{'NOMBRE'}; ?></td> <td><a href=" <?php echo base_url() . '/editar-solicitudes/' . $liquidaciones[$i]->{'ID'};?>"><button onclick="Gestionar()" type="button" class="btn btn-primary" > <?php echo $iconoGestionar; ?> </button></a> </td> <td><a href="<?php echo base_url().route_to('inicioSesion') ?>"><button class="btn btn-danger"> <?php echo $iconoAtras; ?>Pag Principal</button></a></td> </tr> <?php } ?> </table> <?php // esa es la inicializacion del datatables estos 3 script y la funcion ?> <script src="https://code.jquery.com/jquery-3.5.1.js"></script> <script src="https://cdn.datatables.net/1.10.21/js/jquery.dataTables.min.js"></script> <script src="https://cdn.datatables.net/1.10.21/js/dataTables.bootstrap4.min.js"></script> <script> //para cambiar lenguaje asi $(document).ready(function() { $('#example').DataTable({ "language":{ "url":" //cdn.datatables.net/plug-ins/1.10.21/i18n/Spanish.json" } }); } ); </script> <?php //aca etamos trallendo las funciones programadas de la carpeta sweet2js y lugo programaremso la de cargando la pagina, esa si toca por aca por que en funcion no da para llamar ?> <script src="<?php echo base_url().'/public'?>/sweetalert2js/sweet.js"></script> <script> Swal.fire({ title:"Cargando", text: "espera por favor", background:'mediumgpringgreen', timer: 1000 , //aca digo en cuanto tiempo quiero que se cierre la alerta sola timerProgressBar:true, //aca disminulle el tiempo anterior en una barra showConfirmButton:false, imageUrl:'<?php echo base_url().'/public'?>/sweetalert2js/imagenesgif/cargando.gif', imageWidth:'200', imageAlt:'imagen cargando' }); </script> <script src="https://unpkg.com/sweetalert/dist/sweetalert.min.js"></script> <script> let mensaje='<?php echo $mensaje; ?>'; if(mensaje=='18'){ swal(':)','Eliminado exitosamente','success'); }else if(mensaje=='17'){ swal(':)','actualizado exitoso','success'); }else if(mensaje=='15'){ swal(':)','liquidacion Cargada','success'); } </script> </div><!-- /.container-fluid --> </section> <!-- /.content --> </div> </div> <!-- ./wrapper --><file_sep>/app/Views/footer_header/footer.php <?php $ruta = base_url() . '/public/plantillaAdmin/'; //esta es la ruta base para los javascript sean eventos o Ajax $rutaJs = base_url() . '/public/configuraciones/'; ?> <!-- /.content-wrapper --> <footer class="main-footer"> <strong>Copyright &copy; 2021 Liquicobros</strong> All rights reserved. <div class="float-right d-none d-sm-inline-block"> <b>Version</b> 1 </div> </footer> <!-- Control Sidebar --> <aside class="control-sidebar control-sidebar-dark"> <!-- Control sidebar content goes here --> </aside> <!-- /.control-sidebar --> </div> <!-- ./wrapper --> <!-- jQuery --> <script src="<?php echo $ruta . 'dashboard/plugins/jquery/jquery.min.js' ?>"></script> <!-- jQuery UI 1.11.4 --> <script src="<?php echo $ruta . 'dashboard/plugins/jquery-ui/jquery-ui.min.js' ?>"></script> <!-- Resolve conflict in jQuery UI tooltip with Bootstrap tooltip --> <script> $.widget.bridge('uibutton', $.ui.button) </script> <!-- Bootstrap 4 --> <script src="<?php echo $ruta . 'dashboard/plugins/bootstrap/js/bootstrap.bundle.min.js' ?>"></script> <!-- ChartJS --> <script src="<?php echo $ruta . 'dashboard/plugins/chart.js/Chart.min.js' ?>"></script> <!-- Sparkline --> <script src="<?php echo $ruta . 'dashboard/plugins/sparklines/sparkline.js' ?>"></script> <!-- JQVMap --> <script src="<?php echo $ruta . 'dashboard/plugins/jqvmap/jquery.vmap.min.js' ?>"></script> <script src="<?php echo $ruta . 'dashboard/plugins/jqvmap/maps/jquery.vmap.usa.js' ?>"></script> <!-- jQuery Knob Chart --> <script src="<?php echo $ruta . 'dashboard/plugins/jquery-knob/jquery.knob.min.js' ?>"></script> <!-- daterangepicker --> <script src="<?php echo $ruta . 'dashboard/plugins/moment/moment.min.js' ?>"></script> <script src="<?php echo $ruta . 'dashboard/plugins/daterangepicker/daterangepicker.js' ?>"></script> <!-- Tempusdominus Bootstrap 4 --> <script src="<?php echo $ruta . 'dashboard/plugins/tempusdominus-bootstrap-4/js/tempusdominus-bootstrap-4.min.js' ?>"></script> <!-- Summernote --> <script src="<?php echo $ruta . 'dashboard/plugins/summernote/summernote-bs4.min.js' ?>"></script> <!-- overlayScrollbars --> <script src="<?php echo $ruta . 'dashboard/plugins/overlayScrollbars/js/jquery.overlayScrollbars.min.js' ?>"></script> <!-- AdminLTE App --> <script src="<?php echo $ruta . 'dashboard/dist/js/adminlte.js' ?>"></script> <!-- AdminLTE dashboard demo (This is only for demo purposes) --> <script src="<?php echo $ruta . 'dashboard/dist/js/pages/dashboard.js' ?>"></script> <!-- AdminLTE for demo purposes --> <script src="<?php echo $ruta . 'dashboard/dist/js/demo.js' ?>"></script> <script type="text/javascript" src="<?php echo $rutaJs . 'eventosjs/eventos.js' ?>" ></script> <!-- Optional JavaScript --> <!-- jQuery first, then Popper.js, then Bootstrap estos son los sacados de bootsrap --> <script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" integrity="<KEY>" crossorigin="anonymous"></script> <script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js" integrity="<KEY>" crossorigin="anonymous"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js" integrity="<KEY>" crossorigin="anonymous"></script> </body> </html> <file_sep>/public/sweetalert2js/sweet.js function Gestionar(){ let timerInterval Swal.fire({ title: 'Gestionando¡¡', html: 'Abrira en <b></b> millisegundos', timer: 4000, timerProgressBar: true, onBeforeOpen: () => { Swal.showLoading() timerInterval = setInterval(() => { const content = Swal.getContent() if (content) { const b = content.querySelector('b') if (b) { b.textContent = Swal.getTimerLeft() } } }, 100) }, onClose: () => { clearInterval(timerInterval) } }).then((result) => { /* Read more about handling dismissals below */ if (result.dismiss === Swal.DismissReason.timer) { console.log('I was closed by the timer') } }) } function actualizar(){ Swal.fire({ icon: 'success', title: 'Actualizacion Exitosa¡¡¡¡¡', showConfirmButton: false, timer: 4000 }) } function desbloquear(){ Swal.fire({ title:"Desbloqueando", timer: 1000 , //aca digo en cuanto tiempo quiero que se cierre la alerta sola timerProgressBar:true, //aca disminulle el tiempo anterior en una barra showConfirmButton:false, imageUrl:'http://localhost/SENA/Sistema/Vista/sweetalert2js/imagenesgif/actualizando.gif', imageWidth:'200', imageAlt:'imagen actualizando' }) } function Cancelar(){ Swal.fire({ icon: 'error', title: 'Abortado', showConfirmButton: false, timer: 2000 }) } function BlokeoUsuario(){ Swal.fire({ icon: 'error', title: '3 errores usuario bloqueado', showConfirmButton: false, timer: 2000 }) } function Carga(){ Swal.fire({ title:"Cargando", text: "espera por favor", background:'mediumgpringgreen', timer: 1000 , //aca digo en cuanto tiempo quiero que se cierre la alerta sola timerProgressBar:true, //aca disminulle el tiempo anterior en una barra showConfirmButton:false, imageUrl:'<?php echo base_url()."/public" ?>/sweetalert2js/imagenesgif/cargando.gif', imageWidth:'200', imageAlt:'imagen cargando' }); } function agregarUsuario(){ Swal.fire({ icon: 'success', title: 'Usuario creado Exitosamente¡¡¡¡¡', showConfirmButton: false, timer: 4000 }) } function agregarMunicipio(){ Swal.fire({ icon: 'success', title: 'Municipio creado Exitosamente¡¡¡¡¡', showConfirmButton: false, timer: 4000 }) } function reporte(){ Swal.fire({ icon: 'success', title: 'Reporte exitoso¡¡¡¡¡', showConfirmButton: false, timer: 4000 }) } //--------------------------------------- //ACA INICIA JQUERY //--------------------------------------- //toca hacer la funcion de eliminar con js por que alerty se nos lleva todo asi cancelemos $(document).ready(function(){ $('#btnEliminar').on('click',function(e){ let respuesta= confirm('Estas seguro de Eliminar?'); if(respuesta==true){ }else{ e.preventDefault(); } }) });<file_sep>/public/sweetalert2js/configuracionesSweet.js //aca estan todas las opciones que puedo utilizar Swal.fire({ title:"Cargando", text: "espera por favor", //html:"<b>hola</b>" //success ,error , warning,info,questions // confirmButtonText:"seleccionar" // footer: // width:'70%' // padding: background:'mediumgpringgreen', // grow: // backdrop: // true o fals timer: 5000 , //aca digo en cuanto tiempo quiero que se cierre la alerta sola timerProgressBar:true, //aca disminulle el tiempo anterior en una barra // toast: // position: // allowOutsideClick: // allowEscapeKey: // allowEnterKey: // stopKeydownPropagation: // input: // inputPlaceholder: // inputValue: // inputOptions: // customClass: // container: // popup: // header: // title: // closeButton: // icon: // image: // content: // input: // actions: // confirmButton: // cancelButton: // footer: //este es el boton de aceptar showConfirmButton:false, // confirmButtonColor:'green', // aca cambiams el color del boton de la alerta // confirmButtonAriaLabel:'eli' //este es el boton de cancelar //showCancelButton: true, // cancelButtonText: 'cancelame', //cancelButtonColor:'red' // cancelButtonAriaLabel: // buttonsStyling: // showCloseButton: // closeButtonAriaLabel: imageUrl:'http://localhost/SENA/configuraciones/imagenesgif/cargando.gif', imageWidth:'200', // imageHeight: imageAlt:'imagen cargando' }); <file_sep>/app/Views/vistasdelsistema/solicitud.php <?php $empleados; //lamamos el helper de iconos $datos = iconos(); //aca sacamos los iconos ya que la funcion del helper lo puse a retornar un array $iconoEnblanco = $datos[0]; $iconoEditar = $datos[1]; $iconoAtras = $datos[2]; $iconoGuardar = $datos[3]; $iconoCerrar = $datos[4]; $iconoEliminar = $datos[5]; $iconoListar = $datos[6]; $iconoAgregarPersona = $datos[7]; $iconoAgregar = $datos[8]; $iconoCrearModal = $datos[9]; $iconoGestionar = $datos[10]; $iconoDesblokear = $datos[11]; $iconoLiquidar = $datos[12]; $iconoResetear = $datos[13]; $iconoReportes = $datos[14]; ?> <!-- Content Wrapper. Contains page content --> <div class="content-wrapper"> <!-- Content Header (Page header) --> <div class="content-header"> <div class="container-fluid"> <div class="row mb-2"> <div class="col-sm-6"> <h1 class="m-0 text-dark">Crear Solicitud <i class="fas fa-hand-holding-usd"></i></h1> </div><!-- /.col --> <div class="col-sm-6"> <ol class="breadcrumb float-sm-right"> <li class="breadcrumb-item"><a href="#">Home</a></li> <li class="breadcrumb-item active">Dashboard v1</li> </ol> </div><!-- /.col --> </div><!-- /.row --> </div><!-- /.container-fluid --> </div> <div> <div class="card" style="width: 18rem;"> <div class="card-body"> <form class="container" action="<?php echo base_url().route_to('liquidacionsoli'); ?>" method="POST"> <strong>id solicitud</strong><br> <input class="form-control" name="id" type="text" placeholder="Digita el id" ><br> <strong>codigo de solicitud</strong> <input placeholder="escribe codigo" name="codigo" type="text"><br><br> <br> <strong>Descripcion</strong> <input placeholder="escribe descripcion" name="descripcion" type="text"><br><br> <br> <strong>Resumen</strong> <input placeholder="escribe resumen" name="resumen" type="text"><br><br> <br> <strong>Empleado Solicitante</strong> <br> <select class="form-control" name="empleado" id=""> <?php foreach ($empleados as $empleado) {?> <option value="<?php echo $empleado->{'ID'} ?>"><?php echo $empleado->{'NOMBRE'} ?></option> <?php }?> </select> <br><br> <button type="submit" class="btn btn-success btn-block">Solicitar <?php echo $iconoLiquidar; ?></button> <button type="reset" class="btn btn-info btn-block">Resetear <?php echo $iconoResetear; ?></button> </form> </div> </div> </div> </div><!-- /.container-fluid --> </script> <?php //aca etamos trallendo las funciones programadas de la carpeta sweet2js y lugo programaremso la de cargando la pagina, esa si toca por aca por que en funcion no da para llamar ?> <script src="<?php echo base_url().'/public'?>/sweetalert2js/sweet.js" ></script> <script> Swal.fire({ title:"Cargando", text: "espera por favor", background:'mediumgpringgreen', timer: 2000 , //aca digo en cuanto tiempo quiero que se cierre la alerta sola timerProgressBar:true, //aca disminulle el tiempo anterior en una barra showConfirmButton:false, imageUrl:'<?php echo base_url().'/public'?>/sweetalert2js/imagenesgif/cargando.gif', imageWidth:'200', imageAlt:'imagen cargando' }); </script> </section> <!-- /.content --> </div> </div> <file_sep>/app/Models/EmpleadosModel.php <?php namespace App\Models; // esto es para ejecutar queys manual segun documentacion use CodeIgniter\Database\Query; use CodeIgniter\Model; class EmpleadosModel extends Model { public function mostrarUsuariosFormularioBuscador($search) { $datos = $this->db->table('empleado'); $datos->like('ID', $search); $datos->orLike('FECHA_INGRESO', $search); $datos->orLike('NOMBRE', $search); $datos->orLike('SALARIO', $search); return $datos->get()->getResultArray(); } public function pasoTodosLosDatosUsuarioaEditar($id) { $statement = $this->db->query("SELECT *FROM empleado where ID='$id'"); // este me retorna un arreglo de arreglos return $statement->getResult(); } public function borrarClienTabEmpleado($id){ $statement=$this->db->query("DELETE FROM empleado where ID='$id'"); return $statement; } public function borrarClienteTabSolici($id){ $statement=$this->db->query("DELETE FROM solicitud where ID_EMPLEADO='$id'"); return $statement; } public function agregarUsuarios($datos) { $statement = $this->db->query("INSERT INTO empleado (ID,FECHA_INGRESO,NOMBRE,SALARIO) VALUES ('$datos[0]','$datos[1]','$datos[2]','$datos[3]')"); //esta linea retorna el id que se le asigno cuando fue return $this->db->insertID(); } public function actualizarUsuario($datos){ $statement = $this->db->query("UPDATE empleado SET ID='$datos[0]',FECHA_INGRESO='$datos[1]',NOMBRE='$datos[2]',SALARIO='$datos[3]' where ID='$datos[4]' "); } public function mostrarEmpleados(){ $statement = $this->db->query("SELECT * FROM empleado"); return $statement->getResult(); } public function mostrarEmpleadosPorId($id){ $statement = $this->db->query("SELECT * FROM empleado where ID='$id'"); return $statement->getResult(); } //inicio de las solicitues public function crearSolicitud($id, $codigo, $descripcion, $resumen, $empleado ){ $statement=$this->db->query("INSERT INTO solicitud(ID,CODIGO,DESCRIPCION,RESUMEN,ID_EMPLEADO) VALUES('$id', '$codigo','$descripcion','$resumen', '$empleado')"); //esta linea retorna el id que se le asigno cuando fue return $this->db->insertID(); } //aca traemos todas las solicitudes en el buscados cuando colocan un id del empleado public function traerLiquidacionPorIdEmpleado($id){ $statement = $this->db->query("SELECT CODIGO,DESCRIPCION,RESUMEN,NOMBRE,ID_EMPLEADO from solicitud inner join empleado on solicitud.ID_EMPLEADO=empleado.ID WHERE solicitud.ID_EMPLEADO='$id'"); return $statement->getResult(); } public function obtenerSolicitudPorRadicado($id){ $statement = $this->db->query("SELECT * FROM solicitud where ID='$id'"); return $statement->getResult(); } public function mostrarTodasLasLiquidaciones(){ $statement = $this->db->query("SELECT solicitud.ID,CODIGO,DESCRIPCION,RESUMEN,NOMBRE,ID_EMPLEADO from solicitud inner join empleado on solicitud.ID_EMPLEADO=empleado.ID "); return $statement->getResult(); } public function actualizarSolicitud($datos){ $statement = $this->db->query("UPDATE solicitud SET ID='$datos[0]',CODIGO='$datos[1]',DESCRIPCION='$datos[2]',RESUMEN='$datos[3]',ID_EMPLEADO='$datos[4]' where ID='$datos[0]' "); } public function borrarSolicitud($id){ $statement=$this->db->query("DELETE FROM solicitud where ID='$id'"); return $statement; } } <file_sep>/app/Views/vistasdelsistema/usuarioeditar.php <?php //lamamos el helper de iconos $datos = iconos(); //aca sacamos los iconos ya que la funcion del helper lo puse a retornar un array $iconoEnblanco = $datos[0]; $iconoEditar = $datos[1]; $iconoAtras = $datos[2]; $iconoGuardar = $datos[3]; $iconoCerrar = $datos[4]; $iconoEliminar = $datos[5]; $iconoListar = $datos[6]; $iconoAgregarPersona = $datos[7]; $iconoAgregar = $datos[8]; $iconoCrearModal = $datos[9]; $iconoGestionar = $datos[10]; $iconoDesblokear = $datos[11]; $iconoLiquidar = $datos[12]; $iconoResetear = $datos[13]; $iconoReportes = $datos[14]; //aca llegan todos los datos de editar por id para mostrarlos en el formulario $dat_para_poner_enformulario; ?> <!-- Content Wrapper. Contains page content --> <div class="content-wrapper"> <!-- Content Header (Page header) --> <div class="content-header"> <div class="container-fluid"> <div class="row mb-2"> <div class="col-sm-6"> <h1 class="m-0 text-dark">Actualiza y configura Los Empleados <i class="fas fa-key"></i></h1> </div><!-- /.col --> <div class="col-sm-6"> <ol class="breadcrumb float-sm-right"> <li class="breadcrumb-item"><a href="#">Home</a></li> <li class="breadcrumb-item active">Dashboard v1</li> </ol> </div><!-- /.col --> </div><!-- /.row --> </div><!-- /.container-fluid --> </div> <!-- /.content-header --> <!-- Main content --> <section class="content"> <div class="container-fluid"> <div class="container"> <table class="table table-striped table-bordered"> <tr> <th>ID</th> <th>Fecha_ingreso</th> <th>Nombres</th> <th>Salario</th> </tr> <?php //aca traimos los datos por id de la persona que vamos a edita para mostrarlos al formulario foreach ($dat_para_poner_enformulario as $fila) { ?> <tr> <td><?php echo $fila->{'ID'}; ?></td> <!-- Aca creo los inputs --> <td ><?php echo $fila->{'FECHA_INGRESO'} ?></td> <td ><?php echo $fila->{'NOMBRE'} ?></td> <td ><?php echo $fila->{'SALARIO'} ?></td> <!--Aca hago el boton para etitar el formulario --> <!-- Button trigger modal --> <td><a href="<?php echo base_url() . '/Borrar-usuario/' . $fila->{'ID'};?>"><button id="btnEliminar" type="button" class="btn btn-danger" > <?php echo $iconoEliminar; ?> </button></a> <button type="button" class="btn btn-primary" data-toggle="modal" data-target="#exampleModal"> <?php echo $iconoEditar; ?> </button> </td> <td><a href="<?php echo base_url().route_to('gestionarUsuarios'); ?>"><button class="btn btn-success"> <?php echo $iconoAtras; ?>Regresar</button></a></td> <!-- Modal aca voy agregar usuario--> <div class="modal fade" id="exampleModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" id="exampleModalLabel">Modificar datos en empleado</h5> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <div class="modal-body"> <form action="<?php echo base_url().route_to('actualizarUsuarios') ?>" method="POST"> <input type="hidden" name="id" value="<?php echo $id=$fila->{'ID'} ?>"> <strong>Cedula</strong><br> <input value="<?php echo $fila->{'ID'}?>" class="form-control" type="text" name="cedula" placeholder="Digita cedula" required="campo requerido" autocomplete="off"><br> <strong>Fecha ingreso</strong><br> <input value="<?php echo $fila->{'FECHA_INGRESO'} ?>" class="form-control" type="date" name="fecha" required="campo requerido" autocomplete="off"><br> <strong>Nombres</strong><br> <input value="<?php echo $fila->{'NOMBRE'} ?>" class="form-control" type="text" placeholder="Digita Nombres" name="nombre" required="campo requerido" autocomplete="off"><br> <strong>Salario</strong><br> <input value="<?php echo $fila->{'SALARIO'} ?>" class="form-control" type="text" placeholder="Digita salario" name="salario" required="campo requerido" autocomplete="off"><br> <button onclick="Cancelar()" type="button" class="btn btn-danger" data-dismiss="modal"><?php echo $iconoCerrar; ?></button> <button type="submit" class="btn btn-success"><?php echo $iconoGuardar; ?></button> </form> </div> <div class="modal-footer"> </div> </div> </div> </div> </tr> <?php } ?> </table> <script src="<?php echo base_url().'/public'?>/sweetalert2js/sweet.js"></script> </div><!-- /.container-fluid --> </section> <!-- /.content --> </div> </div> <!-- ./wrapper --> <file_sep>/app/Config/Filters.php <?php namespace Config; use CodeIgniter\Config\BaseConfig; use CodeIgniter\Filters\CSRF; use CodeIgniter\Filters\DebugToolbar; use CodeIgniter\Filters\Honeypot; class Filters extends BaseConfig { /** * Configures aliases for Filter classes to * make reading things nicer and simpler. * * @var array */ public $aliases = [ 'csrf' => CSRF::class, 'toolbar' => DebugToolbar::class, 'honeypot' => Honeypot::class, //aca insertamos el filtro que creamos en la carpeta filtro para que se valide que si exista sesion coloco el nombre de la clase que puse en carpeta filters y bajamos abajo de este documento y aplicamos el filtro 'Sesionadmin' => \App\Filters\Sesionadmin::class, ]; /** * List of filter aliases that are always * applied before and after every request. * * @var array */ public $globals = [ 'before' => [ // 'honeypot', // 'csrf', ], 'after' => [ 'toolbar', // 'honeypot', ], ]; /** * List of filter aliases that works on a * particular HTTP method (GET, POST, etc.). * * Example: * 'post' => ['csrf', 'throttle'] * * @var array */ public $methods = []; /** * List of filter aliases that should run on any * before or after URI patterns. * * Example: * 'isLoggedIn' => ['before' => ['account/*', 'profiles/*']] * * @var array */ public $filters = [ 'Sesionadmin' => [ //en filers carpeta bimos el before que asi esta estructurado el filtro y las url que aplicare esos filtros y las separo por comas aca coloco las rutas que protegere y deben tener una sesion si no se cumple hace lo que diga en carpeta filters esta clase Sesionadmin ojo todas las rutas van dentro del array de sesionadmin si lo hago afuera no lo coge 'before' => ['/inicio-sesion'], //en la clase se esta validando que sea dministrador y aca colocamos las rutas que queremos validar que la persona que entre sea administrador 'before' => ['/inicio-crud'], // esta no funciona consultar en internet como proteger cuando la url pasa parametros de igual manera si elimino o actualizo no deja ahi si lo devuelve entonces no habria lio 'before' => ['/obtener-datos/editar/(:any)'], 'before' => ['/actualizar-crud'], ], ]; } <file_sep>/app/Config/Routes.php <?php namespace Config; // Create a new instance of our RouteCollection class. $routes = Services::routes(); // Load the system's routing file first, so that the app and ENVIRONMENT // can override as needed. if (file_exists(SYSTEMPATH . 'Config/Routes.php')) { require SYSTEMPATH . 'Config/Routes.php'; } /** * -------------------------------------------------------------------- * Router Setup * -------------------------------------------------------------------- */ $routes->setDefaultNamespace('App\Controllers'); $routes->setDefaultController('LoginController'); $routes->setDefaultMethod('index'); $routes->setTranslateURIDashes(false); $routes->set404Override(); $routes->setAutoRoute(true); /* * -------------------------------------------------------------------- * Route Definitions * -------------------------------------------------------------------- */ // We get a performance increase by specifying the default // route since we don't have to scan directories. //rutas del login $routes->get('/', 'LoginController::login', ['as' => 'principal']); $routes->post('/procesarLogin', 'LoginController::procesarLogin', ['as' => 'procesarLogin']); $routes->get('/inicio-aplicacion', 'LoginController::inicioSesion', ['as' => 'inicioSesion']); $routes->get('/sesion-finalizada', 'LoginController::cerrarSesion', ['as' => 'cerrarSesion']); //rutas del sistema Administrador //gestionar usuarios $routes->get('/gestionar-usuarios', 'EmpleadosController::gestionarUsuarios', ['as' => 'gestionarUsuarios']); //buscador como se ejecuta en la misma ruta le creamos para el post $routes->post('/gestionar-usuarios', 'EmpleadosController::gestionarUsuarios', ['as' => 'gestionarUsuariosformBuscador']); //editar usuario $routes->get('/editar-usuario/(:any)', 'EmpleadosController::editarUsuario/$1'); //Borrar usuario $routes->get('/Borrar-usuario/(:any)', 'EmpleadosController::borrarUsuario/$1'); //creacion de usuario $routes->post('/crear-usuarios', 'EmpleadosController::crearUsuarios', ['as' => 'crearusuarios']); //actualizacion de usuarios $routes->post('/actualizar-usuarios', 'EmpleadosController::actualizarUsuarios', ['as' => 'actualizarUsuarios']); //realizar una solicitud $routes->get('/solicitud', 'EmpleadosController::solicitud', ['as' => 'liquidarSolicitud']); //crear la solicitur $routes->post('/crear-solicitud', 'EmpleadosController::liquidacionsoli', ['as' => 'liquidacionsoli']); //podemos ver las solicitudes en general $routes->get('/listar-solicitudes', 'EmpleadosController::listarSolicitudesTotales', ['as' => 'listarSolicitudesTotales']); //editar una solicitud //podemos ver las solicitudes en general $routes->get('/editar-solicitudes/(:any)', 'EmpleadosController::editarSolicitud/$1', ['as' => 'editarSolicitud']); //actualizarSolicitud $routes->post('/actualizarSolicitud-solicitud', 'EmpleadosController::actualizarSolicitud', ['as' => 'actualizarSolicitud']); //Borrar-solicitud $routes->get('/Borrar-solicitud/(:any)', 'EmpleadosController::borrarSolicitud/$1', ['as' => 'borrarSolicitud']); /* * -------------------------------------------------------------------- * Additional Routing * -------------------------------------------------------------------- * * There will often be times that you need additional routing and you * need it to be able to override any defaults in this file. Environment * based routes is one such time. require() additional route files here * to make that happen. * * You will have access to the $routes object within that file without * needing to reload it. */ if (file_exists(APPPATH . 'Config/' . ENVIRONMENT . '/Routes.php')) { require APPPATH . 'Config/' . ENVIRONMENT . '/Routes.php'; } <file_sep>/app/Views/vistasdelsistema/solicitud_editar.php <?php $empleados; //llamado de modelo para traer el empleado use App\Models\EmpleadosModel; $objeto_administrador = new EmpleadosModel(); //lamamos el helper de iconos $datos = iconos(); //aca sacamos los iconos ya que la funcion del helper lo puse a retornar un array $iconoEnblanco = $datos[0]; $iconoEditar = $datos[1]; $iconoAtras = $datos[2]; $iconoGuardar = $datos[3]; $iconoCerrar = $datos[4]; $iconoEliminar = $datos[5]; $iconoListar = $datos[6]; $iconoAgregarPersona = $datos[7]; $iconoAgregar = $datos[8]; $iconoCrearModal = $datos[9]; $iconoGestionar = $datos[10]; $iconoDesblokear = $datos[11]; $iconoLiquidar = $datos[12]; $iconoResetear = $datos[13]; $iconoReportes = $datos[14]; //aca llegan todos los datos de editar por id para mostrarlos en el formulario $dat_para_poner_enformulario; ?> <!-- Content Wrapper. Contains page content --> <div class="content-wrapper"> <!-- Content Header (Page header) --> <div class="content-header"> <div class="container-fluid"> <div class="row mb-2"> <div class="col-sm-6"> <h1 class="m-0 text-dark">Actualiza las Solicitudes <i class="fas fa-key"></i></h1> </div><!-- /.col --> <div class="col-sm-6"> <ol class="breadcrumb float-sm-right"> <li class="breadcrumb-item"><a href="#">Home</a></li> <li class="breadcrumb-item active">Dashboard v1</li> </ol> </div><!-- /.col --> </div><!-- /.row --> </div><!-- /.container-fluid --> </div> <!-- /.content-header --> <!-- Main content --> <section class="content"> <div class="container-fluid"> <div class="container"> <table class="table table-striped table-bordered"> <tr> <th>ID</th> <th>CODIGO</th> <th>DESCRIPCION</th> <th>RESUMEN</th> <th>EMPLEADO</th> </tr> <?php //aca traimos los datos por id de la persona que vamos a edita para mostrarlos al formulario foreach ($dat_para_poner_enformulario as $fila) { ?> <tr> <td><?php echo $fila->{'ID'}; ?></td> <!-- Aca creo los inputs --> <td ><?php echo $fila->{'CODIGO'} ?></td> <td ><?php echo $fila->{'DESCRIPCION'} ?></td> <td ><?php echo $fila->{'RESUMEN'} ?></td> <td> <?php //aca sacamos en otra consulta el id del empleado para obtener su nombre $id_empleado= $fila->{'ID_EMPLEADO'} ; $nombre_empleado=$objeto_administrador->mostrarEmpleadosPorId($id_empleado); echo $nombre_empleado=$nombre_empleado[0]->{'NOMBRE'}; ?></td> <!--Aca hago el boton para etitar el formulario --> <!-- Button trigger modal --> <td><a href="<?php echo base_url() . '/Borrar-solicitud/' . $fila->{'ID'};?>"><button id="btnEliminar" type="button" class="btn btn-danger" > <?php echo $iconoEliminar; ?> </button></a> <button type="button" class="btn btn-primary" data-toggle="modal" data-target="#exampleModal"> <?php echo $iconoEditar; ?> </button> </td> <td><a href="<?php echo base_url().route_to('gestionarUsuarios'); ?>"><button class="btn btn-success"> <?php echo $iconoAtras; ?>Regresar</button></a></td> <!-- Modal aca voy agregar usuario--> <div class="modal fade" id="exampleModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" id="exampleModalLabel">Modificar datos de solicitud</h5> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <div class="modal-body"> <form action="<?php echo base_url().route_to('actualizarSolicitud') ?>" method="POST"> <input type="hidden" name="id" value="<?php echo $id=$fila->{'ID'} ?>"> <strong>id</strong><br> <input value="<?php echo $fila->{'ID'}?>" class="form-control" type="text" name="cedula" placeholder="Digita id" required="campo requerido" autocomplete="off"><br> <strong>codigo</strong><br> <input value="<?php echo $fila->{'CODIGO'} ?>" class="form-control" type="text" name="codigo" required="campo requerido" autocomplete="off"><br> <strong>Descripcion</strong><br> <input value="<?php echo $fila->{'DESCRIPCION'} ?>" class="form-control" type="text" placeholder="Digita Nombres" name="descripcion" required="campo requerido" autocomplete="off"><br> <strong>resumen</strong><br> <input value="<?php echo $fila->{'RESUMEN'} ?>" class="form-control" type="text" placeholder="Digita resumen" name="resumen" required="campo requerido" autocomplete="off"><br> <strong>Empleado</strong> <select class="form-control" name="empleado" id=""> <?php foreach ($empleados as $empleado) {?> <option value="<?php echo $empleado->{'ID'} ?>"><?php echo $empleado->{'NOMBRE'} ?></option> <?php }?> </select> <button onclick="Cancelar()" type="button" class="btn btn-danger" data-dismiss="modal"><?php echo $iconoCerrar; ?></button> <button type="submit" class="btn btn-success"><?php echo $iconoGuardar; ?></button> </form> </div> <div class="modal-footer"> </div> </div> </div> </div> </tr> <?php } ?> </table> <script src="<?php echo base_url().'/public'?>/sweetalert2js/sweet.js"></script> </div><!-- /.container-fluid --> </section> <!-- /.content --> </div> </div> <!-- ./wrapper --> <file_sep>/BASE_DATOS_SQL/konecta.sql -- phpMyAdmin SQL Dump -- version 5.1.0 -- https://www.phpmyadmin.net/ -- -- Servidor: 127.0.0.1 -- Tiempo de generación: 16-07-2021 a las 01:47:17 -- Versión del servidor: 10.4.18-MariaDB -- Versión de PHP: 7.4.16 SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO"; START TRANSACTION; SET time_zone = "+00:00"; /*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */; /*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */; /*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */; /*!40101 SET NAMES utf8mb4 */; -- -- Base de datos: `konecta` -- -- -------------------------------------------------------- -- -- Estructura de tabla para la tabla `empleado` -- CREATE TABLE `empleado` ( `ID` int(11) NOT NULL, `FECHA_INGRESO` date DEFAULT NULL, `NOMBRE` varchar(50) DEFAULT NULL, `SALARIO` int(11) DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; -- -- Volcado de datos para la tabla `empleado` -- INSERT INTO `empleado` (`ID`, `FECHA_INGRESO`, `NOMBRE`, `SALARIO`) VALUES (8974, '2021-07-07', 'juan ', 600), (123456789, '2021-07-17', 'pedro', 8000); -- -------------------------------------------------------- -- -- Estructura de tabla para la tabla `solicitud` -- CREATE TABLE `solicitud` ( `ID` int(11) NOT NULL, `CODIGO` varchar(50) DEFAULT NULL, `DESCRIPCION` varchar(50) DEFAULT NULL, `RESUMEN` varchar(50) DEFAULT NULL, `ID_EMPLEADO` int(11) DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; -- -- Volcado de datos para la tabla `solicitud` -- INSERT INTO `solicitud` (`ID`, `CODIGO`, `DESCRIPCION`, `RESUMEN`, `ID_EMPLEADO`) VALUES (1548, '8888', 'prubas2', 'prueabs', 8974), (5888, '58', 'prueba3', 'prueba3', 8974), (15789, '00000', 'prueba', 'solicitud', 123456789); -- -------------------------------------------------------- -- -- Estructura de tabla para la tabla `usuarios` -- CREATE TABLE `usuarios` ( `id_usuario` int(11) NOT NULL, `username` varchar(50) NOT NULL, `password` varchar(120) NOT NULL, `Cedula` varchar(20) DEFAULT NULL, `Nombres` varchar(30) DEFAULT NULL, `Apellidos` varchar(30) DEFAULT NULL, `Email` varchar(30) DEFAULT NULL, `Telefono` varchar(20) DEFAULT NULL, `Perfil` varchar(20) DEFAULT NULL, `Estado` varchar(15) DEFAULT NULL, `idClientes` int(11) DEFAULT NULL, `intentosFallidos` int(11) DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; -- -- Volcado de datos para la tabla `usuarios` -- INSERT INTO `usuarios` (`id_usuario`, `username`, `password`, `Cedula`, `Nombres`, `Apellidos`, `Email`, `Telefono`, `Perfil`, `Estado`, `idClientes`, `intentosFallidos`) VALUES (30, 'konecta', '$2y$10$hBwva9eOlXmOHas3YjSPD.weAaHWo.kLPPgupJcaK/FZxTgkNwB6S', '12345', 'Empresa', 'Konecta', '<EMAIL>', '12345', 'Administrador', 'Activo', NULL, 0); -- -- Índices para tablas volcadas -- -- -- Indices de la tabla `empleado` -- ALTER TABLE `empleado` ADD PRIMARY KEY (`ID`); -- -- Indices de la tabla `solicitud` -- ALTER TABLE `solicitud` ADD PRIMARY KEY (`ID`), ADD KEY `ID_EMPLEADO` (`ID_EMPLEADO`); -- -- Indices de la tabla `usuarios` -- ALTER TABLE `usuarios` ADD PRIMARY KEY (`id_usuario`), ADD KEY `idClientes` (`idClientes`); -- -- AUTO_INCREMENT de las tablas volcadas -- -- -- AUTO_INCREMENT de la tabla `usuarios` -- ALTER TABLE `usuarios` MODIFY `id_usuario` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=109; -- -- Restricciones para tablas volcadas -- -- -- Filtros para la tabla `solicitud` -- ALTER TABLE `solicitud` ADD CONSTRAINT `solicitud_ibfk_1` FOREIGN KEY (`ID_EMPLEADO`) REFERENCES `empleado` (`ID`); COMMIT; /*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */; /*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */; /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */; <file_sep>/app/Filters/Sesionadmin.php <?php namespace App\Filters; use CodeIgniter\Filters\FilterInterface; use CodeIgniter\HTTP\RequestInterface; use CodeIgniter\HTTP\ResponseInterface; class Sesionadmin implements FilterInterface { public function before(RequestInterface $request, $arguments = null) { // Do something here aca validamos si hay sesion activa, si no existe la sesion de roll admin mandalo alinicio if (!session('Perfil') == 'Administrador' || !session('Perfil') == 'Asesor' || !session('Perfil') == 'Cliente') { return redirect()->to(base_url() . route_to('principal'))->with('mensaje', '0'); } } public function after(RequestInterface $request, ResponseInterface $response, $arguments = null) { // Do something here } } <file_sep>/app/Views/vistasdelsistema/gestionarusuarios.php <?php //el mesnaje pasado a la visat principal para ver si esta correcto o errado $mensaje; //llamado de modelo para buscar toca desde la vista use App\Models\EmpleadosModel; $objeto_administrador = new EmpleadosModel(); //lamamos el helper de iconos $datos = iconos(); //aca sacamos los iconos ya que la funcion del helper lo puse a retornar un array $iconoEnblanco = $datos[0]; $iconoEditar = $datos[1]; $iconoAtras = $datos[2]; $iconoGuardar = $datos[3]; $iconoCerrar = $datos[4]; $iconoEliminar = $datos[5]; $iconoListar = $datos[6]; $iconoAgregarPersona = $datos[7]; $iconoAgregar = $datos[8]; $iconoCrearModal = $datos[9]; $iconoGestionar = $datos[10]; $iconoDesblokear = $datos[11]; $iconoLiquidar = $datos[12]; $iconoResetear = $datos[13]; $iconoReportes = $datos[14]; ?> <!-- Content Wrapper. Contains page content --> <div class="content-wrapper"> <!-- Content Header (Page header) --> <div class="content-header"> <div class="container-fluid"> <div class="row mb-2"> <div class="col-sm-6"> <h1 class="m-0 text-dark">Gestiona los Empleados del Sistema <i class="fas fa-key"></i></h1> </div><!-- /.col --> <div class="col-sm-6"> <ol class="breadcrumb float-sm-right"> <li class="breadcrumb-item"><a href="#">Home</a></li> <li class="breadcrumb-item active">Konecta v1</li> </ol> </div><!-- /.col --> </div><!-- /.row --> </div><!-- /.container-fluid --> </div> <!-- /.content-header --> <!-- Main content --> <div> <form action="<?php echo base_url() . route_to('gestionarUsuariosformBuscador'); ?>" method="POST" class="form-inline ml-3"> <div class="input-group input-group-sm"> <input class="form-control form-control-navbar" name="search" type="search" placeholder="Search" aria-label="Search"> <div class="input-group-append"> <button title="Buscar" class="btn btn-navbar" type="submit"> <i class="fas fa-search"></i> </button> </div> </div> </form> <?php //aca programaremos la funcion de buscar si no existe le asignamos vacio para que refresque la pag if (!isset($_POST['search'])) { $_POST['search'] = ""; //aca creamos esta variable que tendra el valor de la anterior osea vacio $search = $_POST['search']; } else { //si, si existe eomamos el nombre y su contenido $search = $_POST['search']; } ?> </div> <br><br> <section class="content"> <div class="container-fluid"> <div class="container"> <?php//aca creo el boton de agregar para cuando le den clic se active el modal Y EL MODAL ?> <div> <!-- Modal aca voy agregar usuario--> <div class="modal fade" id="exampleModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" id="exampleModalLabel">Crear Un nuevo Empleado</h5> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <div class="modal-body"> <form action="<?php echo base_url().route_to('crearusuarios'); ?>" method="POST"> <strong>Cedula</strong><br> <input class="form-control" type="text" name="cedula" placeholder="Digita cedula" required="campo requerido" autocomplete="off"><br> <strong>Fecha de ingreso</strong><br> <input class="form-control" type="date" name="fecha" required="campo requerido" autocomplete="off"><br> <strong>Nombre</strong><br> <input class="form-control" type="text" placeholder="Digita Nombre" name="nombre" required="campo requerido" autocomplete="off"><br> <strong>Salario</strong><br> <input class="form-control" type="input" placeholder="Digita Salario" name="salario" required="campo requerido" autocomplete="off"><br> <button type="submit" class="btn btn-success btn-block" >Crear Usuario <?php echo $iconoAgregarPersona; ?></button> </form> </div> <div class="modal-footer"> </div> </div> </div> </div> <button type="button" class="btn btn-warning" data-toggle="modal" data-target="#exampleModal">Nuevo <?php echo $iconoAgregar; ?> </button> </div> <table id="example" class="container" class="table table-striped table-bordered" style="width:100%"> <thead> <tr> <th>ID</th> <th>FECHA_INGRESO</th> <th>NOMBRE</th> <th>SALARIO</th> </tr> </thead> <?php $listarUsuarios = $objeto_administrador->mostrarUsuariosFormularioBuscador($search); $totalBuscados = count($listarUsuarios); if ($listarUsuarios != null) { for ($i = 0; $i < $totalBuscados; $i++) { ?> <tr> <td><?php echo $listarUsuarios[$i]['ID']; ?></td> <td><?php echo $listarUsuarios[$i]['FECHA_INGRESO']; ?></td> <td><?php echo $listarUsuarios[$i]['NOMBRE']; ?></td> <td><?php echo $listarUsuarios[$i]['SALARIO']; ?></td> <td><a href=" <?php echo base_url() . '/editar-usuario/' . $listarUsuarios[$i]['ID'];?>"><button onclick="Gestionar()" type="button" class="btn btn-primary" > <?php echo $iconoGestionar; ?> </button></a> </td> <td><a href="<?php echo base_url().route_to('inicioSesion') ?>"><button class="btn btn-danger"> <?php echo $iconoAtras; ?>Pag Principal</button></a></td> </tr> <?php } } ?> </table> <?php // esa es la inicializacion del datatables estos 3 script y la funcion ?> <script src="https://code.jquery.com/jquery-3.5.1.js"></script> <script src="https://cdn.datatables.net/1.10.21/js/jquery.dataTables.min.js"></script> <script src="https://cdn.datatables.net/1.10.21/js/dataTables.bootstrap4.min.js"></script> <script> //para cambiar lenguaje asi $(document).ready(function() { $('#example').DataTable({ "language":{ "url":" //cdn.datatables.net/plug-ins/1.10.21/i18n/Spanish.json" } }); } ); </script> <?php //aca etamos trallendo las funciones programadas de la carpeta sweet2js y lugo programaremso la de cargando la pagina, esa si toca por aca por que en funcion no da para llamar ?> <script src="<?php echo base_url().'/public'?>/sweetalert2js/sweet.js"></script> <script> Swal.fire({ title:"Cargando", text: "espera por favor", background:'mediumgpringgreen', timer: 1000 , //aca digo en cuanto tiempo quiero que se cierre la alerta sola timerProgressBar:true, //aca disminulle el tiempo anterior en una barra showConfirmButton:false, imageUrl:'<?php echo base_url().'/public'?>/sweetalert2js/imagenesgif/cargando.gif', imageWidth:'200', imageAlt:'imagen cargando' }); </script> <script src="https://unpkg.com/sweetalert/dist/sweetalert.min.js"></script> <script> let mensaje='<?php echo $mensaje; ?>'; if(mensaje=='4'){ swal(':)','Eliminado exitosamente','success'); }else if(mensaje=='5'){ swal(':)','Usuario ah sido creado','success'); }else if(mensaje=='6'){ swal(':)','Usuario Actualizado','success'); } </script> </div><!-- /.container-fluid --> </section> <!-- /.content --> </div> </div> <!-- ./wrapper --><file_sep>/public/ConfiguracionesIconos/iconos.php <?php //icono en blanco es la plantilla para no tener que borrar y meter datos $iconoEnblanco = "<i title='' class=''></i>"; $iconoEditar = " <i title='Editar' class='fas fa-edit'></i>"; $iconoAtras = " <i title='Regresar' class='fas fa-angle-double-left'></i>"; $iconoGuardar = " <i title='Guardar Datos' class='fas fa-save'></i>"; $iconoCerrar = " <i title='Cerrar' class='far fa-window-close'></i>"; $iconoEliminar = "<i title='Eliminar' class='fas fa-trash-alt'></i>"; $iconoListar = "<i title='Gestionar' class='fas fa-clipboard-list'></i>"; $iconoAgregarPersona = "<i title='Crear Nuevo' class='fas fa-user-plus'></i>"; $iconoAgregar = "<i title='Crear Nuevo' class='fas fa-folder-plus'></i>"; $iconoCrearModal = "<i title='Crear Ahora' class='far fa-calendar-plus'></i>"; $iconoGestionar = "<i title='Gestionar' class='fas fa-puzzle-piece'>Gestionar</i>"; $iconoDesblokear = "<i title='Desbloquear' class='fas fa-lock-open'></i>"; $iconoLiquidar = "<i title='Liquidar' class='fas fa-cart-arrow-down'></i>"; $iconoResetear = "<i title='Liquidar' class='fas fa-hand-sparkles'></i>"; $iconoReportes = "<i title='Generar reporte' class='fas fa-align-left'></i>"; <file_sep>/app/Views/login/index.php <?php $mensaje; $rutaLogin=base_url().'/public/static/css/index.css';?> <!DOCTYPE html> <html lang="en" xmlns:th="http://www.thymeleaf.org"> <head> <title>Login Konecta</title> <!--JQUERY--> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <!-- FRAMEWORK BOOTSTRAP para el estilo de la pagina--> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css"> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"></script> <!-- Los iconos tipo Solid de Fontawesome--> <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.0.8/css/solid.css"> <script src="https://use.fontawesome.com/releases/v5.0.7/js/all.js"></script> <!-- Nuestro css--> <link rel="stylesheet" type="text/css" href="<?php echo $rutaLogin; ?>" th:href="@{/css/index.css}"> <script src="https://cdn.jsdelivr.net/npm/sweetalert2@9"></script> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="<KEY>" crossorigin="anonymous"> <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta2/dist/js/bootstrap.bundle.min.js" integrity="<KEY>" crossorigin="anonymous"></script> <script src="https://cdn.jsdelivr.net/npm/@popperjs/core@2.6.0/dist/umd/popper.min.js" integrity="<KEY>" crossorigin="anonymous"></script> <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta2/dist/js/bootstrap.min.js" integrity="<KEY>" crossorigin="anonymous"></script> </head> <body> <div class="modal-dialog text-center"> <div class="col-sm-8 main-section"> <div class="modal-content"> <div class="col-12 user-img"> <img src="<?php echo base_url() .'/public/static/img/user.png'; ?>" th:src="@{/img/user.png}"/> </div> <form class="col-12" action="<?php echo base_url() . route_to('procesarLogin') ?>" method="POST"> <div class="form-group" id="user-group"> <input style="border-color: red; " type="text" class="form-control" placeholder="Nombre de usuario" name="usuario"/> </div> <div class="form-group" id="contrasena-group"> <input style="border-color: red; " type="<PASSWORD>" class="form-control" placeholder="<PASSWORD>" name="password"/> </div> <button type="submit" class="btn btn-primary"><i class="fas fa-sign-in-alt"></i> Ingresar </button> </form> <br><button class="btn btn-block btn-success"><i class="fab fa-slideshare"></i></button> <script src="<?php echo base_url().'/public/sweetalert2js/sweet.js'; ?>"></script> </div> </div> </div> </div> <script src="https://unpkg.com/sweetalert/dist/sweetalert.min.js"></script> <script> let mensaje='<?php echo $mensaje; ?>' if(mensaje=='0'){ swal(':(','No existes','error'); }else if(mensaje=='20'){ swal(':)','Te haz registrado exitosamente','success'); } </script> </html><file_sep>/app/Controllers/LoginController.php <?php namespace App\Controllers; //me traigo el modelo del admin por que en el index muestro el total de usuarios entonces lo traigo aca para ejecutar la consulta y pasdarla a la vista en iniciologin use App\Models\Loginmodel; class LoginController extends BaseController { public function login() { // esta es la vista principal de formulario login //este es el formulario que tiene la vista proncipal del formulario obligatoriamente requieren sesion entonces toca ponerla para que no falle este hasta print es la validacion de formularios session(); // por aca pasamos los campos erados a la vista en la validacion de form $cvalidaciones puede ser cualquiera esto es lo que nos imprime los errores en la vista cuando se retrocede $validaciones = \config\Services::validation(); //list errors devuelve los errores de los formularios esta muestra los errores print($validaciones->listErrors()); $mensaje = session('mensaje'); $data = ['mensaje' => $mensaje]; return view('login/index', $data); } public function procesarLogin() { // hacemos la validacion de formulario si los datos estan bien llenos seguimos a validar que exista como usuario //validando el formulario primero voy a config validate y pongo las validaciones y luego me vengo pa ca, validar_formulario es el nombre de la variable que pusimos por alla en el archivo de conffig en validate if ($this->validate('validar_formulario_login')) { // si cumplio con los datos requeridos de formulario //podemos hacerlo como en la insercion de array asociativo,o de esta otra manera, ello hizo de esta para saber que existe $usuario = $this->request->getPost('usuario'); $password = $this->request->getPost('password'); $usuarios = new Loginmodel(); $datos_usuario = $usuarios->obtenerUsuario(['username' => $usuario]); //si encuentra un usuario tenbdra datos array y el pasword de esta pesona coincida con el que esta if (count($datos_usuario) > 0 && password_verify($password, $datos_usuario[0]['password'])) { // aca creamos los datos que les crearemos session $data = [ 'username' => $datos_usuario[0]['username'], 'id_usuario' => $datos_usuario[0]['id_usuario'], 'Nombres' => $datos_usuario[0]['Nombres'], 'Apellidos' => $datos_usuario[0]['Apellidos'], 'Perfil' => $datos_usuario[0]['Perfil'], 'Estado' => $datos_usuario[0]['Estado'], ]; $session = session(); $session->set($data); // esos mensaje 1 es una sesion ,mensaje y en el login recibimos ese mensaje en sesion(mensaje ) el numero es el que queramos envair pero en la vista se recoge y de acuerdo al numero en un condicional decido que mensaje mostrar return redirect()->to(base_url() . route_to('inicioSesion'))->with('mensaje', '1'); } else { // si valido bien formulario pero no es usuario return redirect()->to(base_url() . route_to('principal'))->with('mensaje', '0'); } } else { //si tenemos problemas con las validaciones lo redirigimos esta funcion es la que redirecciona atras para cuando el formulario este malo no lo deja avanzar si no que se retrocede wit input es para que no pierda los datos escritos en el formulario return redirect()->back()->withInput(); } } public function inicioSesion() { //objeto con todos los usuarios para pasarlos a la vista $objetoAdministrador = new Loginmodel(); $usuarios = $objetoAdministrador->totalUsuariosEnbaseDatos(); $mensaje = session('mensaje'); $data = ['mensaje' => $mensaje, 'usuarios' => $usuarios, ]; echo view('footer_header/header'); echo view('login/inicioapp', $data); echo view('footer_header/footer'); } public function cerrarSesion() { $session = session(); $session->destroy(); return redirect()->to(base_url() . route_to('principal')); } } <file_sep>/app/Controllers/EmpleadosController.php <?php namespace App\Controllers; use App\Models\EmpleadosModel; ; class EmpleadosController extends BaseController { //Inicio Metodos de Gestion de usuarios /* --------------------------------------------- MODULO USUARIOS -------------------------------------------- */ public function gestionarUsuarios() { $obj_administrador = new EmpleadosModel(); $mensaje=session('mensaje'); $datos = [ 'mensaje'=>$mensaje ]; echo view('footer_header/header'); echo view('vistasdelsistema/gestionarusuarios', $datos); echo view('footer_header/footer'); } public function editarUsuario($id){ $id=$id; $obj_administrador = new EmpleadosModel(); $dat_para_poner_enformulario=$obj_administrador->pasoTodosLosDatosUsuarioaEditar($id); $datos=[ 'dat_para_poner_enformulario'=>$dat_para_poner_enformulario ]; echo view('footer_header/header'); echo view('vistasdelsistema/usuarioeditar.php', $datos); echo view('footer_header/footer'); } public function borrarUsuario($id){ $obj_administrador = new EmpleadosModel(); $verificar_innerjoin=$obj_administrador->traerLiquidacionPorIdEmpleado($id); //verifico que el cliente no este en 2 tablas y si esta lo borro de las 2 $existe=count($verificar_innerjoin); if($existe>0){ //Si esta en ambas tablas lo borramos en cascada $obj_administrador->borrarClienteTabSolici($id); $obj_administrador->borrarClienTabEmpleado($id); return redirect()->to(base_url() . route_to('gestionarUsuarios'))->with('mensaje', '4'); }else{ $obj_administrador->borrarClienTabEmpleado($id); return redirect()->to(base_url() . route_to('gestionarUsuarios'))->with('mensaje', '4'); } } public function crearUsuarios(){ $obj_administrador = new EmpleadosModel(); //aca quedo la clave encriptada $datos=array( $_POST['cedula'], $_POST['fecha'], $_POST['nombre'], $_POST['salario'], ) ; $obj_administrador->agregarUsuarios($datos); return redirect()->to(base_url() . route_to('gestionarUsuarios'))->with('mensaje', '5'); } public function actualizarUsuarios(){ $obj_administrador = new EmpleadosModel(); //para actualizar si podemos poner un array asociativo $datos=array( $_POST['cedula'], $_POST['fecha'], $_POST['nombre'], $_POST['salario'], $_POST['id'] ); $obj_administrador->actualizarUsuario($datos); return redirect()->to(base_url() . route_to('gestionarUsuarios'))->with('mensaje', '6'); } //vamos a la ruta de solicitu para llenar el formulario public function solicitud(){ $obj_administrador = new EmpleadosModel(); $empleados=$obj_administrador->mostrarEmpleados(); $datos=['empleados'=>$empleados]; echo view('footer_header/header'); echo view('vistasdelsistema/solicitud.php',$datos); echo view('footer_header/footer'); } //cuando se realiza la solicitud insertamos los datos en la bd public function liquidacionsoli(){ $objAdmin = new EmpleadosModel(); //aca tomo los datos del formulario $id = $_POST['id']; $codigo = $_POST['codigo']; $descripcion = $_POST['descripcion']; $resumen = $_POST['resumen']; $empleado = $_POST['empleado']; $objAdmin->crearSolicitud($id, $codigo, $descripcion, $resumen, $empleado ); return redirect()->to(base_url() . route_to('listarSolicitudesTotales'))->with('mensaje', '15'); } public function listarSolicitudesTotales(){ $mensaje=session('mensaje'); $objAdmin = new EmpleadosModel(); $liquidaciones=$objAdmin->mostrarTodasLasLiquidaciones(); $datos = [ 'mensaje'=>$mensaje, 'liquidaciones'=>$liquidaciones ]; echo view('footer_header/header'); echo view('vistasdelsistema/listar_solicitudes.php', $datos); echo view('footer_header/footer'); } public function editarSolicitud($id){ $objAdmin = new EmpleadosModel(); //para que puedan seleccionar un empleado $empleados=$objAdmin->mostrarEmpleados(); $dat_para_poner_enformulario=$objAdmin->obtenerSolicitudPorRadicado($id); $datos = [ 'dat_para_poner_enformulario'=>$dat_para_poner_enformulario, 'empleados'=>$empleados ]; echo view('footer_header/header'); echo view('vistasdelsistema/solicitud_editar.php', $datos); echo view('footer_header/footer'); } public function actualizarSolicitud(){ $obj_administrador = new EmpleadosModel(); //para actualizar si podemos poner un array asociativo $datos=array( $_POST['id'], $_POST['codigo'], $_POST['descripcion'], $_POST['resumen'], $_POST['empleado'] ); $obj_administrador->actualizarSolicitud($datos); return redirect()->to(base_url() . route_to('listarSolicitudesTotales'))->with('mensaje', '17'); } public function borrarSolicitud($id){ $objAdmin = new EmpleadosModel(); $objAdmin->borrarSolicitud($id); return redirect()->to(base_url() . route_to('listarSolicitudesTotales'))->with('mensaje', '18'); } }<file_sep>/app/Views/footer_header/header.php <?php $verificaRol = session('Perfil'); $ponerNombre = session('Nombres'); $ponerApellidos = session('Apellidos'); $ponerEstado = session('Estado'); $ruta = base_url() . '/public/plantillaAdmin/'; //esta es la ruta base para los javascript sean eventos o Ajax $rutaJs = base_url() . '/public/configuraciones/'; ?> <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <title>Liqucobros </title> <!-- Tell the browser to be responsive to screen width --> <meta name="viewport" content="width=device-width, initial-scale=1"> <!-- Font Awesome --> <link rel="stylesheet" href="<?php echo $ruta . 'dashboard/plugins/fontawesome-free/css/all.min.css' ?>"> <!-- Ionicons --> <link rel="stylesheet" href="https://code.ionicframework.com/ionicons/2.0.1/css/ionicons.min.css"> <!-- Tempusdominus Bbootstrap 4 --> <link rel="stylesheet" href="<?php echo $ruta . 'dashboard/plugins/tempusdominus-bootstrap-4/css/tempusdominus-bootstrap-4.min.css' ?>"> <!-- iCheck --> <link rel="stylesheet" href="<?php $ruta . 'dashboard/plugins/icheck-bootstrap/icheck-bootstrap.min.css'?>"> <!-- JQVMap --> <link rel="stylesheet" href="<?php echo $ruta . 'dashboard/plugins/jqvmap/jqvmap.min.css' ?>"> <!-- Theme style --> <link rel="stylesheet" href="<?php echo $ruta . 'dashboard/dist/css/adminlte.min.css' ?>"> <!-- overlayScrollbars --> <link rel="stylesheet" href="<?php echo $ruta . 'dashboard/plugins/overlayScrollbars/css/OverlayScrollbars.min.css' ?>"> <!-- Daterange picker --> <link rel="stylesheet" href="<?php echo $ruta . 'dashboard/plugins/daterangepicker/daterangepicker.css' ?>"> <!-- summernote --> <link rel="stylesheet" href="<?php echo $ruta . 'dashboard/plugins/summernote/summernote-bs4.css' ?>"> <!-- Google Font: Source Sans Pro --> <link rel="stylesheet" href=""> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="<KEY>" crossorigin="anonymous"> <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta2/dist/js/bootstrap.bundle.min.js" integrity="<KEY>" crossorigin="anonymous"></script> <script src="https://cdn.jsdelivr.net/npm/@popperjs/core@2.6.0/dist/umd/popper.min.js" integrity="<KEY>" crossorigin="anonymous"></script> <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta2/dist/js/bootstrap.min.js" integrity="<KEY>" crossorigin="anonymous"></script> <link href="https://fonts.googleapis.com/css?family=Source+Sans+Pro:300,400,400i,700" rel="stylesheet"> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" integrity="<KEY>" crossorigin="anonymous"> <script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" integrity="<KEY>" crossorigin="anonymous"></script> <script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js" integrity="<KEY>" crossorigin="anonymous"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js" integrity="<KEY>" crossorigin="anonymous"></script> <script src="https://cdn.jsdelivr.net/npm/sweetalert2@9"></script> </head> <body class="hold-transition sidebar-mini layout-fixed"> <?php // aca hacemos el condicional si es un admin mostrar un panel si es asesor otro panel y si es cliente mostrar otro panel if ($verificaRol === "Administrador") { ?> <!-- Navbar --> <nav class="main-header navbar navbar-expand navbar-white navbar-light"> <!-- Left navbar links --> <ul class="navbar-nav"> <li class="nav-item"> <a class="nav-link" data-widget="pushmenu" href="#" role="button"><i class="fas fa-bars"></i></a> </li> <li class="nav-item d-none d-sm-inline-block"> <a href="index3.html" class="nav-link">Home </a> </li> </ul> <!-- SEARCH FORM --> <!-- Right navbar links --> <ul class="navbar-nav ml-auto"> <!-- Messages Dropdown Menu --> <li class="nav-item dropdown"> <a class="nav-link" data-toggle="dropdown" href="#"> <i class="far fa-comments"></i> <span class="badge badge-danger navbar-badge">3</span> </a> <div class="dropdown-menu dropdown-menu-lg dropdown-menu-right"> <a href="#" class="dropdown-item"> <!-- Message Start --> <div class="media"> <img src="<?php echo $ruta . 'dashboard/dist/img/user1-128x128.jpg' ?>" alt="User Avatar" class="img-size-50 mr-3 img-circle"> <div class="media-body"> <h3 class="dropdown-item-title"> <NAME> <span class="float-right text-sm text-danger"><i class="fas fa-star"></i></span> </h3> <p class="text-sm">Call me whenever you can...</p> <p class="text-sm text-muted"><i class="far fa-clock mr-1"></i> 4 Hours Ago</p> </div> </div> <!-- Message End --> </a> <div class="dropdown-divider"></div> <a href="#" class="dropdown-item"> <!-- Message Start --> <div class="media"> <img src="<?php echo $ruta . 'dashboard/dist/img/user8-128x128.jpg' ?>" alt="User Avatar" class="img-size-50 img-circle mr-3"> <div class="media-body"> <h3 class="dropdown-item-title"> <NAME> <span class="float-right text-sm text-muted"><i class="fas fa-star"></i></span> </h3> <p class="text-sm">I got your message bro</p> <p class="text-sm text-muted"><i class="far fa-clock mr-1"></i> 4 Hours Ago</p> </div> </div> <!-- Message End --> </a> <div class="dropdown-divider"></div> <a href="#" class="dropdown-item"> <!-- Message Start --> <div class="media"> <img src="<?php echo $ruta . 'dashboard/dist/img/user3-128x128.jpg' ?>" alt="User Avatar" class="img-size-50 img-circle mr-3"> <div class="media-body"> <h3 class="dropdown-item-title"> <NAME> <span class="float-right text-sm text-warning"><i class="fas fa-star"></i></span> </h3> <p class="text-sm">The subject goes here</p> <p class="text-sm text-muted"><i class="far fa-clock mr-1"></i> 4 Hours Ago</p> </div> </div> <!-- Message End --> </a> <div class="dropdown-divider"></div> <a href="#" class="dropdown-item dropdown-footer">See All Messages</a> </div> </li> <!-- Notifications Dropdown Menu --> <li class="nav-item dropdown"> <a class="nav-link" data-toggle="dropdown" href="#"> <i class="far fa-bell"></i> <span class="badge badge-warning navbar-badge">15</span> </a> <div class="dropdown-menu dropdown-menu-lg dropdown-menu-right"> <span class="dropdown-item dropdown-header">15 Notifications</span> <div class="dropdown-divider"></div> <a href="#" class="dropdown-item"> <i class="fas fa-envelope mr-2"></i> 4 new messages <span class="float-right text-muted text-sm">3 mins</span> </a> <div class="dropdown-divider"></div> <a href="#" class="dropdown-item"> <i class="fas fa-users mr-2"></i> 8 friend requests <span class="float-right text-muted text-sm">12 hours</span> </a> <div class="dropdown-divider"></div> <a href="#" class="dropdown-item"> <i class="fas fa-file mr-2"></i> 3 new reports <span class="float-right text-muted text-sm">2 days</span> </a> <div class="dropdown-divider"></div> <a href="#" class="dropdown-item dropdown-footer">See All Notifications</a> </div> </li> <li class="nav-item"> <a class="nav-link" data-widget="control-sidebar" data-slide="true" href="#" role="button"> <i class="fas fa-th-large"></i> </a> </li> </ul> </nav> <!-- /.navbar --> <!-- Main Sidebar Container --> <aside class="main-sidebar sidebar-dark-primary elevation-4"> <!-- Brand Logo --> <a href="index.php" class="brand-link"> <img src="<?php echo $ruta . 'dashboard/dist/img/AdminLTELogo.png' ?>" alt="AdminLTE Logo" class="brand-image img-circle elevation-3" style="opacity: .8"> <span class="brand-text font-weight-light">Siste Konecta</span> </a> <!-- Sidebar --> <div class="sidebar"> <!-- Sidebar user panel (optional) --> <div class="user-panel mt-3 pb-3 mb-3 d-flex"> <div class="info"> <!-- Aca coloco el noombre apellido y rol al iniciar sesion --> <p style="color:white;">Bienvenido - <?php echo $ponerNombre . '</br> ' . $ponerApellidos; ?></p> <a href="#" class="d-block"><?php echo $verificaRol; ?></a> </div> </div> <!-- Sidebar Menu --> <nav class="mt-2"> <ul class="nav nav-pills nav-sidebar flex-column" data-widget="treeview" role="menu" data-accordion="false"> <li class="nav-item"> <a href="<?php echo base_url() . route_to('inicioSesion'); ?>" class="nav-link"> <i class="fas fa-home"></i> <p> Inicio </p> </a> </li> <li class="nav-item"> <a href="<?php echo base_url() . route_to('gestionarUsuarios'); ?>" class="nav-link"> <i class="far fa-address-card"></i> <p> Gestionar Empleados </p> </a> </li> <li class="nav-item"> <a href="index.php" class="nav-link"> <i class="fas fa-users"></i> <p> Panel de solicitudes </p> </a> <ul class="nav nav-treeview"> <li class="nav-item"> <a href="<?php echo base_url() . route_to('liquidarSolicitud'); ?>" class="nav-link"> <i class="far fa-circle nav-icon"></i> <p>realizar solicitud</p> </a> </li> <li class="nav-item"> <a href="<?php echo base_url() . route_to('listarSolicitudesTotales'); ?>" class="nav-link"> <i class="fas fa-angle-double-right"></i> <p>Consulta solicitudes</p> </a> </li> </ul> </li> <li class="nav-item"> <a href="<?php echo base_url() . route_to('cerrarSesion') ?>" class="nav-link"> <i class="far fa-address-book"></i> <p> Cerrar cesión </p> </a> </li> </ul> </nav> <!-- /.sidebar-menu --> </div> <!-- /.sidebar --> </aside> <?php }; ?><file_sep>/app/Config/Validation.php <?php namespace Config; use CodeIgniter\Validation\CreditCardRules; use CodeIgniter\Validation\FileRules; use CodeIgniter\Validation\FormatRules; use CodeIgniter\Validation\Rules; class Validation { //-------------------------------------------------------------------- // Setup //-------------------------------------------------------------------- /** * Stores the classes that contain the * rules that are available. * * @var string[] */ public $ruleSets = [ Rules::class, FormatRules::class, FileRules::class, CreditCardRules::class, ]; /** * Specifies the views that are used to display the * errors. * * @var array<string, string> */ public $templates = [ 'list' => 'CodeIgniter\Validation\Views\list', 'single' => 'CodeIgniter\Validation\Views\single', ]; //-------------------------------------------------------------------- // Rules //-------------------------------------------------------------------- //desde aca se crea la validacion de formulario public $validar_formulario_ejemplo = [ 'nombre' => 'required|min_length[3]|max_length[20]', 'descripcion' => 'required|min_length[15]|max_length[25]', 'edad' => 'required|numeric', 'correo' => 'required|valid_emails', ]; // aca validamos el formulario de login public $validar_formulario_login = [ 'usuario' => 'required|min_length[2]|max_length[20]', 'password' => '<PASSWORD>]', ]; public $validar_formulario_crud = [ 'nombre' => 'required|min_length[5]|max_length[60]|alpha', 'appat' => 'required|min_length[5]|max_length[30]|alpha', 'apmate' => 'required|min_length[5]|max_length[30]|alpha', ]; } <file_sep>/app/Models/Loginmodel.php <?php namespace App\Models; use CodeIgniter\Model; class Loginmodel extends Model { public function obtenerUsuario($data) { $usuario = $this->db->table('usuarios'); $usuario->where($data); //si encuentra el usuario me traiga un arreglo con todos sus datos return $usuario->get()->getResultArray(); } public function totalUsuariosEnbaseDatos() { $dato = $this->db->query('SELECT * FROM usuarios'); return $dato->getResult(); } }
b9a16ac540edf326fafd950c7db2e1508212f8c4
[ "JavaScript", "SQL", "PHP" ]
20
PHP
camilomicrosys/konecta_prueba
242618317479cdc4085aa223fd85416341440bef
62ef80cdf1fb8e0a43343c9b9432b4337721594b
refs/heads/master
<repo_name>bharatsubedi/YOLO_v3<file_sep>/generate.py import multiprocessing import os from multiprocessing import Process from os.path import join import cv2 import numpy as np import tensorflow as tf import tqdm from lxml import etree os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3' from src.utils import config, util def make_names(): labels_dict = {} annotation_list = os.listdir(os.path.join(config.dataset, config.label_path)) for annotation_file in annotation_list: p = os.path.join(os.path.join(config.dataset, config.label_path), annotation_file) root = etree.parse(p).getroot() names = root.xpath('//object/name') for n in names: labels_dict[n.text] = 0 labels = list(labels_dict.keys()) labels.sort() with open(config.classes, 'w') as writer: for label in labels: writer.writelines(label + '\n') print("done !!!") def convert_annotation(list_txt, output_path, image_dir, anno_dir, class_names): image_ext = '.jpg' anno_ext = '.xml' with open(list_txt, 'r') as f, open(output_path, 'w') as wf: while True: line = f.readline().strip() if line is None or not line: break im_p = os.path.join(image_dir, line + image_ext) an_p = os.path.join(anno_dir, line + anno_ext) # Get annotation. root = etree.parse(an_p).getroot() b_boxes = root.xpath('//object/bndbox') names = root.xpath('//object/name') box_annotations = [] for b, n in zip(b_boxes, names): name = n.text class_idx = class_names.index(name) xmin = b.find('xmin').text ymin = b.find('ymin').text xmax = b.find('xmax').text ymax = b.find('ymax').text box_annotations.append(','.join([str(xmin), str(ymin), str(xmax), str(ymax), str(class_idx)])) annotation = os.path.abspath(im_p) + ' ' + ' '.join(box_annotations) + '\n' wf.write(annotation) def convert(): image_dir = os.path.join(config.dataset, config.image_path) annotation_dir = os.path.join(config.dataset, config.label_path) train_list_txt = os.path.join(config.dataset, 'ImageSets', 'Main', 'train.txt') val_list_txt = os.path.join(config.dataset, 'ImageSets', 'Main', 'val.txt') train_output = os.path.join(config.dataset, 'voc2012_train.txt') val_output = os.path.join(config.dataset, 'voc2012_val.txt') class_names = [c.strip() for c in open(config.classes).readlines()] convert_annotation(train_list_txt, train_output, image_dir, annotation_dir, class_names) convert_annotation(val_list_txt, val_output, image_dir, annotation_dir, class_names) def byte_feature(value): if not isinstance(value, bytes): if not isinstance(value, list): value = value.encode('utf-8') else: value = [val.encode('utf-8') for val in value] if not isinstance(value, list): value = [value] return tf.train.Feature(bytes_list=tf.train.BytesList(value=value)) def float_feature(value): return tf.train.Feature(float_list=tf.train.FloatList(value=value)) def bbox_iou(boxes1, boxes2): boxes1 = np.array(boxes1) boxes2 = np.array(boxes2) boxes1_area = boxes1[..., 2] * boxes1[..., 3] boxes2_area = boxes2[..., 2] * boxes2[..., 3] boxes1 = np.concatenate([boxes1[..., :2] - boxes1[..., 2:] * 0.5, boxes1[..., :2] + boxes1[..., 2:] * 0.5, ], axis=-1, ) boxes2 = np.concatenate([boxes2[..., :2] - boxes2[..., 2:] * 0.5, boxes2[..., :2] + boxes2[..., 2:] * 0.5, ], axis=-1, ) left_up = np.maximum(boxes1[..., :2], boxes2[..., :2]) right_down = np.minimum(boxes1[..., 2:], boxes2[..., 2:]) inter_section = np.maximum(right_down - left_up, 0.0) inter_area = inter_section[..., 0] * inter_section[..., 1] union_area = boxes1_area + boxes2_area - inter_area return inter_area / union_area def preprocess(bboxes): num_classes = len(util.read_class_names(config.classes)) train_output_sizes = [64, 32, 16] label = [np.zeros((train_output_sizes[i], train_output_sizes[i], 3, 5 + num_classes)) for i in range(3)] bboxes_xywh = [np.zeros((config.max_boxes, 4)) for _ in range(3)] bbox_count = np.zeros((3,)) for bbox in bboxes: bbox_coordinate = bbox[:4] bbox_class_ind = bbox[4] one_hot = np.zeros(num_classes, dtype=np.float) one_hot[bbox_class_ind] = 1.0 uniform_distribution = np.full(num_classes, 1.0 / num_classes) delta = 0.01 smooth_one_hot = one_hot * (1 - delta) + delta * uniform_distribution bbox_xywh = np.concatenate( [(bbox_coordinate[2:] + bbox_coordinate[:2]) * 0.5, bbox_coordinate[2:] - bbox_coordinate[:2]], axis=-1) bbox_xywh_scaled = 1.0 * bbox_xywh[np.newaxis, :] / np.array(config.strides)[:, np.newaxis] iou = [] exist_positive = False for i in range(3): anchors_xywh = np.zeros((3, 4)) anchors_xywh[:, 0:2] = np.floor(bbox_xywh_scaled[i, 0:2]).astype(np.int32) + 0.5 anchors_xywh[:, 2:4] = config.anchors[i] iou_scale = bbox_iou(bbox_xywh_scaled[i][np.newaxis, :], anchors_xywh) iou.append(iou_scale) iou_mask = iou_scale > 0.3 if np.any(iou_mask): x_ind, y_ind = np.floor(bbox_xywh_scaled[i, 0:2]).astype(np.int32) label[i][y_ind, x_ind, iou_mask, :] = 0 label[i][y_ind, x_ind, iou_mask, 0:4] = bbox_xywh label[i][y_ind, x_ind, iou_mask, 4:5] = 1.0 label[i][y_ind, x_ind, iou_mask, 5:] = smooth_one_hot bbox_ind = int(bbox_count[i] % config.max_boxes) bboxes_xywh[i][bbox_ind, :4] = bbox_xywh bbox_count[i] += 1 exist_positive = True if not exist_positive: best_anchor_ind = np.argmax(np.array(iou).reshape(-1), axis=-1) best_detect = int(best_anchor_ind / 3) best_anchor = int(best_anchor_ind % 3) x_ind, y_ind = np.floor(bbox_xywh_scaled[best_detect, 0:2]).astype(np.int32) label[best_detect][y_ind, x_ind, best_anchor, :] = 0 label[best_detect][y_ind, x_ind, best_anchor, 0:4] = bbox_xywh label[best_detect][y_ind, x_ind, best_anchor, 4:5] = 1.0 label[best_detect][y_ind, x_ind, best_anchor, 5:] = smooth_one_hot bbox_ind = int(bbox_count[best_detect] % config.max_boxes) bboxes_xywh[best_detect][bbox_ind, :4] = bbox_xywh bbox_count[best_detect] += 1 l_s_box, l_m_box, l_l_box = label s_boxes, m_boxes, l_boxes = bboxes_xywh return l_s_box, l_m_box, l_l_box, s_boxes, m_boxes, l_boxes def resize(image, gt_boxes=None): ih, iw = config.image_size, config.image_size h, w, _ = image.shape scale = min(iw / w, ih / h) nw, nh = int(scale * w), int(scale * h) image_resized = cv2.resize(image, (nw, nh)) image_padded = np.zeros(shape=[ih, iw, 3], dtype=np.uint8) dw, dh = (iw - nw) // 2, (ih - nh) // 2 image_padded[dh:nh + dh, dw:nw + dw, :] = image_resized.copy() if gt_boxes is None: return image_padded else: gt_boxes[:, [0, 2]] = gt_boxes[:, [0, 2]] * scale + dw gt_boxes[:, [1, 3]] = gt_boxes[:, [1, 3]] * scale + dh return image_padded, gt_boxes def parse_annotation(annotation): line = annotation.split() image_path = line[0] if not os.path.exists(image_path): raise KeyError("%s does not exist ... " % image_path) image = cv2.imread(image_path) bboxes = np.array([list(map(int, box.split(","))) for box in line[1:]]) image, bboxes = resize(np.copy(image), bboxes) return image, bboxes, image_path def build_example(annotation): image, bboxes, image_path = parse_annotation(annotation) s_label, m_label, l_label, s_boxes, m_boxes, l_boxes = preprocess(bboxes) path = os.path.join(config.dataset, 'record', os.path.basename(image_path)) util.write_image(path, image) s_label = s_label.astype('float32') m_label = m_label.astype('float32') l_label = l_label.astype('float32') s_boxes = s_boxes.astype('float32') m_boxes = m_boxes.astype('float32') l_boxes = l_boxes.astype('float32') s_label = s_label.tobytes() m_label = m_label.tobytes() l_label = l_label.tobytes() s_boxes = s_boxes.tobytes() m_boxes = m_boxes.tobytes() l_boxes = l_boxes.tobytes() features = tf.train.Features(feature={'path': byte_feature(path.encode('utf-8')), 's_label': byte_feature(s_label), 'm_label': byte_feature(m_label), 'l_label': byte_feature(l_label), 's_boxes': byte_feature(s_boxes), 'm_boxes': byte_feature(m_boxes), 'l_boxes': byte_feature(l_boxes)}) return tf.train.Example(features=features) def write_tf_record(_queue, _sentinel): while True: annotation = _queue.get() if annotation == _sentinel: break tf_example = build_example(annotation) name = os.path.basename(annotation.split(' ')[0]) annotation = join(config.dataset, 'record') if not os.path.exists(annotation): os.makedirs(annotation) with tf.io.TFRecordWriter(join(annotation, name[:-4] + ".tfrecord")) as writer: writer.write(tf_example.SerializeToString()) def main(): if not os.path.exists(config.classes): make_names() if not os.path.exists(os.path.join(config.dataset, 'voc2012_train.txt')): convert() sentinel = ("", []) nb_process = multiprocessing.cpu_count() _queue = multiprocessing.Manager().Queue() annotations = util.load_annotations(os.path.join(config.dataset, 'voc2012_train.txt')) for annotation in tqdm.tqdm(annotations): _queue.put(annotation) for _ in range(nb_process): _queue.put(sentinel) print('--- generating tfrecord') process_pool = [] for i in range(nb_process): process = Process(target=write_tf_record, args=(_queue, sentinel)) process_pool.append(process) process.start() for process in process_pool: process.join() if __name__ == '__main__': main() <file_sep>/src/nets/helper.py import tensorflow as tf class BatchNormalization(tf.keras.layers.BatchNormalization): def call(self, x, training=False): if not training: training = tf.constant(False) training = tf.logical_and(training, self.trainable) return super().call(x, training) def convolution_block(inputs, filters, kernel_size, strides=1, activate=True, bn=True): if strides == 2: inputs = tf.keras.layers.ZeroPadding2D(((1, 0), (1, 0)))(inputs) padding = 'valid' else: padding = 'same' x = tf.keras.layers.Conv2D(filters, kernel_size, strides, padding, use_bias=not bn, kernel_regularizer=tf.keras.regularizers.l2(0.0005), kernel_initializer=tf.random_normal_initializer(stddev=0.01), bias_initializer=tf.constant_initializer(0.))(inputs) if bn: x = BatchNormalization()(x) if activate: x = tf.nn.leaky_relu(x, alpha=0.1) return x def residual_block(inputs, filter_num1, filter_num2): x = convolution_block(inputs, filter_num1, 1) x = convolution_block(x, filter_num2, 3) return inputs + x def transpose(input_layer): return tf.image.resize(input_layer, (input_layer.shape[1] * 2, input_layer.shape[2] * 2), method='nearest') def backbone(inputs): x = convolution_block(inputs, 32, 3) x = convolution_block(x, 64, 3, 2) for _ in range(1): x = residual_block(x, 32, 64) x = convolution_block(x, 128, 3, 2) for _ in range(2): x = residual_block(x, 64, 128) x = convolution_block(x, 256, 3, 2) for _ in range(8): x = residual_block(x, 128, 256) skip1 = x x = convolution_block(x, 512, 3, 2) for _ in range(8): x = residual_block(x, 256, 512) skip2 = x x = convolution_block(x, 1024, 3, 2) for _ in range(4): x = residual_block(x, 512, 1024) return skip1, skip2, x <file_sep>/train.py import os import sys from os.path import join os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3' os.environ["CUDA_VISIBLE_DEVICES"] = '0' import tensorflow as tf tf.compat.v1.logging.set_verbosity(tf.compat.v1.logging.ERROR) import numpy as np from src.utils import config tf.random.set_seed(config.seed) from src.nets import nn from src.utils import util, data_loader tf_path = join(config.dataset, 'record') tf_paths = [join(tf_path, name) for name in os.listdir(tf_path) if name.endswith('.tfrecord')] np.random.shuffle(tf_paths) strategy = tf.distribute.MirroredStrategy() nb_gpu = strategy.num_replicas_in_sync global_batch = nb_gpu * config.batch_size nb_classes = len(util.read_class_names(config.classes)) dataset = data_loader.TFRecordLoader(global_batch, config.nb_epoch, nb_classes).load_data(tf_paths) dataset = strategy.experimental_distribute_dataset(dataset) with strategy.scope(): optimizer = tf.keras.optimizers.Adam(0.0001) input_tensor = tf.keras.layers.Input([config.image_size, config.image_size, 3]) outputs = nn.build_model(input_tensor, nb_classes) output_tensors = [] for i, output in enumerate(outputs): pred_tensor = nn.decode(output, i) output_tensors.append(output) output_tensors.append(pred_tensor) model = tf.keras.Model(input_tensor, output_tensors) print(f'[INFO] {len(tf_paths)} train data') with strategy.scope(): loss_object = nn.compute_loss def compute_loss(_target, _logits): _iou_loss = _conf_loss = _prob_loss = 0 for ind in range(3): loss_items = loss_object(_logits[ind * 2 + 1], _logits[ind * 2], _target[ind][0], _target[ind][1], ind) _iou_loss += loss_items[0] _conf_loss += loss_items[1] _prob_loss += loss_items[2] _total_loss = _iou_loss + _conf_loss + _prob_loss _iou_loss = tf.reduce_sum(_iou_loss) * 1. / global_batch _conf_loss = tf.reduce_sum(_conf_loss) * 1. / global_batch _prob_loss = tf.reduce_sum(_prob_loss) * 1. / global_batch _total_loss = _iou_loss + _conf_loss + _prob_loss return _iou_loss, _conf_loss, _prob_loss, _total_loss with strategy.scope(): def train_step(_image, _target): with tf.GradientTape() as tape: _logits = model(_image, training=True) _iou_loss, _conf_loss, _prob_loss, _total_loss = compute_loss(_target, _logits) gradients = tape.gradient(_total_loss, model.trainable_variables) optimizer.apply_gradients(zip(gradients, model.trainable_variables)) return _iou_loss, _conf_loss, _prob_loss, _total_loss with strategy.scope(): @tf.function def distribute_train_step(_image, _target): _iou_loss, _conf_loss, _prob_loss, _total_loss = strategy.run(train_step, args=(_image, _target)) _total_loss = strategy.reduce(tf.distribute.ReduceOp.MEAN, _total_loss, axis=None) _iou_loss = strategy.reduce(tf.distribute.ReduceOp.MEAN, _iou_loss, axis=None) _conf_loss = strategy.reduce(tf.distribute.ReduceOp.MEAN, _conf_loss, axis=None) _prob_loss = strategy.reduce(tf.distribute.ReduceOp.MEAN, _prob_loss, axis=None) return _iou_loss, _conf_loss, _prob_loss, _total_loss if __name__ == '__main__': nb_steps = len(tf_paths) // global_batch print(f"--- Training with {nb_steps} Steps ---") for step, inputs in enumerate(dataset): step += 1 image, s_label, s_boxes, m_label, m_boxes, l_label, l_boxes = inputs target = ((s_label, s_boxes), (m_label, m_boxes), (l_label, l_boxes)) iou_loss, conf_loss, prob_loss, total_loss = distribute_train_step(image, target) print("%4d %4.2f %4.2f %4.2f %4.2f" % (step, iou_loss.numpy(), conf_loss.numpy(), prob_loss.numpy(), total_loss.numpy())) if step % (10 * nb_steps) == 0: model.save_weights(join("weights", f"model{step // (10 * nb_steps)}.h5")) if step // nb_steps == config.nb_epoch: sys.exit("--- Stop Training ---") <file_sep>/src/nets/nn.py import numpy as np import tensorflow as tf from src.nets import helper from src.utils import config def build_model(inputs, nb_classes): x1, x2, x3 = helper.backbone(inputs) x = helper.convolution_block(x3, 512, 1) x = helper.convolution_block(x, 1024, 3) x = helper.convolution_block(x, 512, 1) x = helper.convolution_block(x, 1024, 3) x = helper.convolution_block(x, 512, 1) large = helper.convolution_block(x, 1024, 3) large = helper.convolution_block(large, 3 * (nb_classes + 5), 1, activate=False, bn=False) x = helper.convolution_block(x, 256, 1) x = helper.transpose(x) x = tf.concat([x, x2], axis=-1) x = helper.convolution_block(x, 256, 1) x = helper.convolution_block(x, 512, 3) x = helper.convolution_block(x, 256, 1) x = helper.convolution_block(x, 512, 3) x = helper.convolution_block(x, 256, 1) medium = helper.convolution_block(x, 512, 3) medium = helper.convolution_block(medium, 3 * (nb_classes + 5), 1, activate=False, bn=False) x = helper.convolution_block(x, 128, 1) x = helper.transpose(x) x = tf.concat([x, x1], axis=-1) x = helper.convolution_block(x, 128, 1) x = helper.convolution_block(x, 256, 3) x = helper.convolution_block(x, 128, 1) x = helper.convolution_block(x, 256, 3) x = helper.convolution_block(x, 128, 1) small = helper.convolution_block(x, 256, 3) small = helper.convolution_block(small, 3 * (nb_classes + 5), 1, activate=False, bn=False) return [small, medium, large] def decode(output, i=0): shape = tf.shape(output) batch_size = shape[0] output_size = shape[1] output = tf.reshape(output, (batch_size, output_size, output_size, 3, 5 + 20)) raw_xy = output[:, :, :, :, 0:2] raw_wh = output[:, :, :, :, 2:4] raw_conf = output[:, :, :, :, 4:5] raw_prob = output[:, :, :, :, 5:] y = tf.tile(tf.range(output_size, dtype=tf.int32)[:, tf.newaxis], [1, output_size]) x = tf.tile(tf.range(output_size, dtype=tf.int32)[tf.newaxis, :], [output_size, 1]) xy_grid = tf.concat([x[:, :, tf.newaxis], y[:, :, tf.newaxis]], axis=-1) xy_grid = tf.tile(xy_grid[tf.newaxis, :, :, tf.newaxis, :], [batch_size, 1, 1, 3, 1]) xy_grid = tf.cast(xy_grid, tf.float32) pred_xy = (tf.sigmoid(raw_xy) + xy_grid) * config.strides[i] pred_wh = (tf.exp(raw_wh) * config.anchors[i]) * config.strides[i] pred_xywh = tf.concat([pred_xy, pred_wh], axis=-1) pred_conf = tf.sigmoid(raw_conf) pred_prob = tf.sigmoid(raw_prob) return tf.concat([pred_xywh, pred_conf, pred_prob], axis=-1) def bbox_iou(boxes1, boxes2): boxes1_area = boxes1[..., 2] * boxes1[..., 3] boxes2_area = boxes2[..., 2] * boxes2[..., 3] boxes1 = tf.concat([boxes1[..., :2] - boxes1[..., 2:] * 0.5, boxes1[..., :2] + boxes1[..., 2:] * 0.5], axis=-1) boxes2 = tf.concat([boxes2[..., :2] - boxes2[..., 2:] * 0.5, boxes2[..., :2] + boxes2[..., 2:] * 0.5], axis=-1) left_up = tf.maximum(boxes1[..., :2], boxes2[..., :2]) right_down = tf.minimum(boxes1[..., 2:], boxes2[..., 2:]) inter_section = tf.maximum(right_down - left_up, 0.0) inter_area = inter_section[..., 0] * inter_section[..., 1] union_area = boxes1_area + boxes2_area - inter_area return 1.0 * inter_area / union_area def bbox_g_iou(boxes1, boxes2): boxes1 = tf.concat([boxes1[..., :2] - boxes1[..., 2:] * 0.5, boxes1[..., :2] + boxes1[..., 2:] * 0.5], axis=-1) boxes2 = tf.concat([boxes2[..., :2] - boxes2[..., 2:] * 0.5, boxes2[..., :2] + boxes2[..., 2:] * 0.5], axis=-1) boxes1 = tf.concat([tf.minimum(boxes1[..., :2], boxes1[..., 2:]), tf.maximum(boxes1[..., :2], boxes1[..., 2:])], axis=-1) boxes2 = tf.concat([tf.minimum(boxes2[..., :2], boxes2[..., 2:]), tf.maximum(boxes2[..., :2], boxes2[..., 2:])], axis=-1) boxes1_area = (boxes1[..., 2] - boxes1[..., 0]) * (boxes1[..., 3] - boxes1[..., 1]) boxes2_area = (boxes2[..., 2] - boxes2[..., 0]) * (boxes2[..., 3] - boxes2[..., 1]) left_up = tf.maximum(boxes1[..., :2], boxes2[..., :2]) right_down = tf.minimum(boxes1[..., 2:], boxes2[..., 2:]) inter_section = tf.maximum(right_down - left_up, 0.0) inter_area = inter_section[..., 0] * inter_section[..., 1] union_area = boxes1_area + boxes2_area - inter_area iou = inter_area / union_area enclose_left_up = tf.minimum(boxes1[..., :2], boxes2[..., :2]) enclose_right_down = tf.maximum(boxes1[..., 2:], boxes2[..., 2:]) enclose = tf.maximum(enclose_right_down - enclose_left_up, 0.0) enclose_area = enclose[..., 0] * enclose[..., 1] return iou - 1.0 * (enclose_area - union_area) / enclose_area def compute_loss(pred, output, label, boxes, i=0): shape = tf.shape(output) batch_size = shape[0] output_size = shape[1] input_size = config.strides[i] * output_size output = tf.reshape(output, (batch_size, output_size, output_size, 3, 5 + 20)) raw_conf = output[:, :, :, :, 4:5] raw_prob = output[:, :, :, :, 5:] pred_xywh = pred[:, :, :, :, 0:4] pred_conf = pred[:, :, :, :, 4:5] label_xywh = label[:, :, :, :, 0:4] respond_bbox = label[:, :, :, :, 4:5] label_prob = label[:, :, :, :, 5:] giou = tf.expand_dims(bbox_g_iou(pred_xywh, label_xywh), axis=-1) input_size = tf.cast(input_size, tf.float32) bbox_loss_scale = 2.0 - 1.0 * label_xywh[:, :, :, :, 2:3] * label_xywh[:, :, :, :, 3:4] / (input_size ** 2) giou_loss = respond_bbox * bbox_loss_scale * (1 - giou) iou = bbox_iou(pred_xywh[:, :, :, :, np.newaxis, :], boxes[:, np.newaxis, np.newaxis, np.newaxis, :, :]) max_iou = tf.expand_dims(tf.reduce_max(iou, axis=-1), axis=-1) respond_bgd = (1.0 - respond_bbox) * tf.cast(max_iou < 0.5, tf.float32) conf_focal = tf.pow(respond_bbox - pred_conf, 2) conf_loss = conf_focal * (respond_bbox * tf.nn.sigmoid_cross_entropy_with_logits(respond_bbox, raw_conf) + respond_bgd * tf.nn.sigmoid_cross_entropy_with_logits(respond_bbox, raw_conf)) prob_loss = respond_bbox * tf.nn.sigmoid_cross_entropy_with_logits(label_prob, raw_prob) giou_loss = tf.reduce_mean(tf.reduce_sum(giou_loss, axis=[1, 2, 3, 4])) conf_loss = tf.reduce_mean(tf.reduce_sum(conf_loss, axis=[1, 2, 3, 4])) prob_loss = tf.reduce_mean(tf.reduce_sum(prob_loss, axis=[1, 2, 3, 4])) return giou_loss, conf_loss, prob_loss <file_sep>/test.py import colorsys import random import cv2 import numpy as np import tensorflow as tf import generate from src.nets import nn from src.utils import util, config def postprocess_boxes(_pred_bbox, org_img_shape, input_size, score_threshold): valid_scale = [0, np.inf] _pred_bbox = np.array(_pred_bbox) pred_xywh = _pred_bbox[:, 0:4] pred_conf = _pred_bbox[:, 4] pred_prob = _pred_bbox[:, 5:] pred_coordinate = np.concatenate([pred_xywh[:, :2] - pred_xywh[:, 2:] * 0.5, pred_xywh[:, :2] + pred_xywh[:, 2:] * 0.5], axis=-1) org_h, org_w = org_img_shape resize_ratio = min(input_size / org_w, input_size / org_h) dw = (input_size - resize_ratio * org_w) / 2 dh = (input_size - resize_ratio * org_h) / 2 pred_coordinate[:, 0::2] = 1.0 * (pred_coordinate[:, 0::2] - dw) / resize_ratio pred_coordinate[:, 1::2] = 1.0 * (pred_coordinate[:, 1::2] - dh) / resize_ratio pred_coordinate = np.concatenate([np.maximum(pred_coordinate[:, :2], [0, 0]), np.minimum(pred_coordinate[:, 2:], [org_w - 1, org_h - 1])], axis=-1) invalid_mask = np.logical_or((pred_coordinate[:, 0] > pred_coordinate[:, 2]), (pred_coordinate[:, 1] > pred_coordinate[:, 3])) pred_coordinate[invalid_mask] = 0 bbox_scale = np.sqrt(np.multiply.reduce(pred_coordinate[:, 2:4] - pred_coordinate[:, 0:2], axis=-1)) scale_mask = np.logical_and((valid_scale[0] < bbox_scale), (bbox_scale < valid_scale[1])) _classes = np.argmax(pred_prob, axis=-1) scores = pred_conf * pred_prob[np.arange(len(pred_coordinate)), _classes] score_mask = scores > score_threshold mask = np.logical_and(scale_mask, score_mask) coors, scores, _classes = pred_coordinate[mask], scores[mask], _classes[mask] return np.concatenate([coors, scores[:, np.newaxis], _classes[:, np.newaxis]], axis=-1) def nms(_bboxes, iou_threshold, sigma=0.3, method='soft-nms'): classes_in_img = list(set(_bboxes[:, 5])) best_bboxes = [] for cls in classes_in_img: cls_mask = (_bboxes[:, 5] == cls) cls_bboxes = _bboxes[cls_mask] while len(cls_bboxes) > 0: max_ind = np.argmax(cls_bboxes[:, 4]) best_bbox = cls_bboxes[max_ind] best_bboxes.append(best_bbox) cls_bboxes = np.concatenate([cls_bboxes[: max_ind], cls_bboxes[max_ind + 1:]]) iou = generate.bbox_iou(best_bbox[np.newaxis, :4], cls_bboxes[:, :4]) weight = np.ones((len(iou),), dtype=np.float32) assert method in ['nms', 'soft-nms'] if method == 'nms': iou_mask = iou > iou_threshold weight[iou_mask] = 0.0 if method == 'soft-nms': weight = np.exp(-(1.0 * iou ** 2 / sigma)) cls_bboxes[:, 4] = cls_bboxes[:, 4] * weight score_mask = cls_bboxes[:, 4] > 0. cls_bboxes = cls_bboxes[score_mask] return best_bboxes def draw_bbox(_image, _bbox, _classes, _nb_classes, show_label=True): image_h, image_w, _ = _image.shape hsv_tuples = [(1.0 * x / _nb_classes, 1., 1.) for x in range(_nb_classes)] colors = list(map(lambda x: colorsys.hsv_to_rgb(*x), hsv_tuples)) colors = list(map(lambda x: (int(x[0] * 255), int(x[1] * 255), int(x[2] * 255)), colors)) random.seed(0) random.shuffle(colors) random.seed(None) for _i, _box in enumerate(_bbox): coordinate = np.array(_box[:4], dtype=np.int32) font = 0.5 score = _box[4] class_ind = int(_box[5]) bbox_color = colors[class_ind] bbox_thick = int(0.6 * (image_h + image_w) / 600) c1, c2 = (coordinate[0], coordinate[1]), (coordinate[2], coordinate[3]) cv2.rectangle(_image, c1, c2, bbox_color, bbox_thick) if show_label: bbox_mess = '%s: %.2f' % (_classes[class_ind], score) t_size = cv2.getTextSize(bbox_mess, 0, font, thickness=bbox_thick // 2)[0] cv2.rectangle(_image, c1, (c1[0] + t_size[0], c1[1] - t_size[1] - 3), bbox_color, -1) # filled cv2.putText(_image, bbox_mess, (c1[0], c1[1] - 2), cv2.FONT_HERSHEY_SIMPLEX, font, (0, 0, 0), bbox_thick // 2, lineType=cv2.LINE_AA) return _image nb_classes = len(util.read_class_names(config.classes)) classes = util.read_class_names(config.classes) input_layer = tf.keras.layers.Input([config.image_size, config.image_size, 3]) feature_maps = nn.build_model(input_layer, nb_classes) bbox_tensors = [] for i, fm in enumerate(feature_maps): bbox_tensor = nn.decode(fm, i) bbox_tensors.append(bbox_tensor) model = tf.keras.Model(input_layer, bbox_tensors) model.load_weights("weights/model10.h5") image = cv2.imread('2007_000039.jpg') image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB) image_size = image.shape[:2] image_data = generate.resize(np.copy(image)) image_data = image_data[np.newaxis, ...].astype(np.float32) pred_bbox = model.predict(image_data / 255.0) pred_bbox = [tf.reshape(x, (-1, tf.shape(x)[-1])) for x in pred_bbox] pred_bbox = tf.concat(pred_bbox, axis=0) bbox = postprocess_boxes(pred_bbox, image_size, config.image_size, 0.2) bbox = nms(bbox, 0.2) image = draw_bbox(np.squeeze(image_data, 0), bbox, classes, nb_classes) cv2.imwrite('result.png', image) <file_sep>/src/utils/config.py import numpy as np seed = 12345 nb_epoch = 50 batch_size = 1 max_boxes = 150 image_size = 512 dataset = '../VOC2012' image_path = 'JPEGImages' label_path = 'Annotations' classes = '../VOC2012/voc2012.names' strides = [8, 16, 32] anchors = np.array([[[12, 16], [19, 36], [40, 28]], [[36, 75], [76, 55], [72, 146]], [[142, 110], [192, 243], [459, 401]]], np.float32) <file_sep>/README.md # YOLOV3 YOLOV3 using TensorFlow 2 (multi GPU training support) To make tfrecord dataset for VOC2012: - download VOC2012 dataset - locate VOC2012 dataset (see config.py) - run `python generate.py` (it generates tfrecord dataset) - run `python tain.py` <file_sep>/src/utils/util.py from __future__ import print_function, division import cv2 def load_image(path): image = cv2.imread(path, cv2.IMREAD_COLOR) image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB) return image def write_image(path, image): cv2.imwrite(path, cv2.cvtColor(image, cv2.COLOR_RGB2BGR)) def load_annotations(txt_list): with open(txt_list, "r") as reader: lines = reader.readlines() return [line.strip() for line in lines if len(line.strip().split()[1:]) != 0] def read_class_names(class_file_name): names = {} with open(class_file_name, 'r') as data: for ID, name in enumerate(data): names[ID] = name.strip('\n') return names <file_sep>/src/utils/data_loader.py import tensorflow as tf from src.utils import config class TFRecordLoader: def __init__(self, batch_size, nb_epoch, nb_classes=20): super(TFRecordLoader, self).__init__() self.nb_epoch = nb_epoch self.nb_classes = nb_classes self.batch_size = batch_size self.feature_description = {'path': tf.io.FixedLenFeature([], tf.string), 's_label': tf.io.FixedLenFeature([], tf.string), 'm_label': tf.io.FixedLenFeature([], tf.string), 'l_label': tf.io.FixedLenFeature([], tf.string), 's_boxes': tf.io.FixedLenFeature([], tf.string), 'm_boxes': tf.io.FixedLenFeature([], tf.string), 'l_boxes': tf.io.FixedLenFeature([], tf.string)} def parse_data(self, tf_record): features = tf.io.parse_single_example(tf_record, self.feature_description) image = tf.io.read_file(features['path']) image = tf.io.decode_jpeg(image, 3) image = tf.image.convert_image_dtype(image, dtype=tf.uint8) image = tf.cast(image, tf.float32) image = image / 255. s_label = tf.io.decode_raw(features['s_label'], tf.float32) s_label = tf.reshape(s_label, (64, 64, 3, 5 + self.nb_classes)) m_label = tf.io.decode_raw(features['m_label'], tf.float32) m_label = tf.reshape(m_label, (32, 32, 3, 5 + self.nb_classes)) l_label = tf.io.decode_raw(features['l_label'], tf.float32) l_label = tf.reshape(l_label, (16, 16, 3, 5 + self.nb_classes)) s_boxes = tf.io.decode_raw(features['s_boxes'], tf.float32) s_boxes = tf.reshape(s_boxes, (config.max_boxes, 4)) m_boxes = tf.io.decode_raw(features['m_boxes'], tf.float32) m_boxes = tf.reshape(m_boxes, (config.max_boxes, 4)) l_boxes = tf.io.decode_raw(features['l_boxes'], tf.float32) l_boxes = tf.reshape(l_boxes, (config.max_boxes, 4)) return image, s_label, s_boxes, m_label, m_boxes, l_label, l_boxes def load_data(self, file_names): reader = tf.data.TFRecordDataset(file_names) # reader = reader.shuffle(len(file_names)) reader = reader.map(self.parse_data, tf.data.experimental.AUTOTUNE) reader = reader.repeat(self.nb_epoch + 1) reader = reader.batch(self.batch_size) reader = reader.prefetch(tf.data.experimental.AUTOTUNE) return reader
24f1a2a2637d667dc4294c3d1d5801e953e2c65a
[ "Markdown", "Python" ]
9
Python
bharatsubedi/YOLO_v3
472e95bfc114994a4110d257fa358bac648a291d
ef246b74fb02ddf55238ccfe537e0bd8eb1d0607
refs/heads/master
<repo_name>Aathi10Vel/Unity-3D-Transparent-Gameobject<file_sep>/BuildingTransparent.cs using System.Collections; using System.Collections.Generic; using UnityEngine; using System.Linq; public class BuildingTransparent : MonoBehaviour { public List<Material> normalMats; public List<Material> transparentMats; public Transform playerTransform; public GameObject lastBuilding; public float distCalculate; Ray castRay; RaycastHit castHit; // Start is called before the first frame update void Start() { } // Update is called once per frame void Update() { castRay = new Ray(Camera.main.transform.position, playerTransform.position - Camera.main.transform.position); distCalculate = Vector3.Distance(playerTransform.position, Camera.main.transform.position); if(Physics.Raycast(castRay,out castHit, distCalculate)) { if (castHit.collider != null) { if (castHit.collider.CompareTag("Buildings")) { if (lastBuilding != null) { if (lastBuilding != castHit.collider.gameObject) { enableBuilding(true); lastBuilding = castHit.collider.gameObject; enableBuilding(false); } } else { lastBuilding = castHit.collider.gameObject; enableBuilding(false); } } else { if (lastBuilding != null) { enableBuilding(true); lastBuilding = null; } } } } } public void enableBuilding(bool boolOperation) { if(lastBuilding.transform.parent!=null && lastBuilding.transform.parent.CompareTag("Buildings")) { for(int i = 0; i < lastBuilding.transform.parent.childCount; i++) { MeshRenderer buildingMesh = lastBuilding.transform.parent.GetChild(i).GetComponent<MeshRenderer>() ?? null; if (buildingMesh != null) { setTransparency(boolOperation, buildingMesh); } } } else if (lastBuilding.transform.childCount < 0) { for(int i = 0; i < lastBuilding.transform.childCount; i++) { MeshRenderer buildingMesh = lastBuilding.transform.GetChild(i).GetComponent<MeshRenderer>() ?? null; if (buildingMesh != null) { setTransparency(boolOperation, buildingMesh); } } } else { MeshRenderer buildingMesh = lastBuilding.GetComponent<MeshRenderer>() ?? null; if (buildingMesh != null) { setTransparency(boolOperation, buildingMesh); } } } public void setTransparency(bool objFunctions, MeshRenderer matRenderer) { if (objFunctions) { var meshMats = matRenderer.materials; List<Material> norMats = new List<Material>(); foreach(var normMats in meshMats) { var newMats = normalMats.First(x => x.name == normMats.name.Split(' ')[0]); norMats.Add(newMats); } matRenderer.materials = norMats.ToArray(); } else { var meshMats = matRenderer.materials; List<Material> transMats = new List<Material>(); foreach(var tranMats in meshMats) { var newMats = transparentMats.First(x => x.name == tranMats.name.Split(' ')[0]); transMats.Add(newMats); } matRenderer.materials = transMats.ToArray(); } } }
c4759d72971b27c7071c81441d821e059654d8fe
[ "C#" ]
1
C#
Aathi10Vel/Unity-3D-Transparent-Gameobject
b4f361b796281ee87589c98e5888ceaf3a3996f2
35a6fe318009080cc8df8ca008d1461546be0d00
refs/heads/main
<file_sep>/* * File: cod02.c * Author: <NAME> * * Created on 23 de Junho de 2021, 20:35 */ #pragma config FOSC = INTIO67 #include <xc.h> void main(void) { TRISD &= 0b11111010; // Configura os pinos RD0 e RD2 como saída digital while(1) { PORTD |= 0b00000001; // Escreve nível lógico alto ('1') no pino RD0 PORTD &= 0b11111011; // Escreve nível lógico baixo ('0') no pino RD2 } return; } <file_sep>#pragma config FOSC = INTIO67 #pragma config PBADEN = OFF #define _XTAL_FREQ 1000000 #include <xc.h> void main(void) { TRISD &= 0b11111110; TRISB |= 0B00000001; //Configurar o bit RB0 como entrada. INTCONbits.INT0IE = 1; //Habilitar interrupção externa INT0. INTCONbits.INT0IF = 1; //Limpar flag de interrupção INT0. INTCON2bits.INTEDG0 = 0;//Habilitar interrupção INT0 na borda de descida. RCONbits.IPEN = 0; //Desligar todas as prioridades na interrupção. INTCONbits.GIE = 1; //Hablitar interrupção geral. while(1){ PORTD &= 0b11111110; } return; } void __interrupt() funcao(){ if(INTCONbits.INT0IE == 1){ INTCONbits.INT0IF = 0; PORTD |= 0b00000001; __delay_ms(1000); } }<file_sep>void setup() { DDRB = DDRB | B00110000; //Configura as portas 4(pin10 PWM) e 5(pin11) PWM) como sáida digital. } void loop() { PORTB = PORTB | B00110000; //Registra valor HIGH na porta digital 4 e 5/Pino digital 10 e 11(PWM). }<file_sep>/* * File: exp01.c * Author: esquadrao * * Created on 21 de Julho de 2021, 16:38 */ #pragma config FOSC = INTIO67 #pragma config PBADEN = OFF #define _XTAL_FREQ 1000000 #include <xc.h> void __interrupt() interrupcao(){ if (INTCONbits.INT0IF == 1) { __delay_ms(3000); PORTD &= 0b11111111; PORTD |= 0b00000001; __delay_ms(2000); for (int i = 0; i<5; i++){ PORTD = 0b00000100; __delay_ms(250); PORTD = 0; __delay_ms(250); } __delay_ms(2000); for (int i = 0; i<5; i++){ PORTD = 0b00001000; __delay_ms(250); PORTD = 0; __delay_ms(250); } for (int i = 0; i<5; i++){ PORTD = 0b00010000; __delay_ms(250); PORTD = 0; __delay_ms(250); } for (int i = 0; i<5; i++){ PORTD = 0b00100000; __delay_ms(250); PORTD = 0; __delay_ms(250); } for (int i = 0; i<5; i++){ PORTD = 0b01000000; __delay_ms(250); PORTD = 0; __delay_ms(250); } for (int i = 0; i<5; i++){ PORTD = 0b10000000; __delay_ms(250); PORTD = 0; __delay_ms(250); } INTCONbits.INT0IF = 0; } } void main(void) { TRISD &= 0b00000000; // Configura os pinos como saída digital PORTD &= 0b00000000; // Desliga os LEDs TRISB |= 0b00000001; // Configurar o bit RB0 como entrada. INTCONbits.INT0IE = 1; // Habilitar interrupção externa INT0 INTCONbits.INT0IF = 0; // Limpar flag da interrupção INT0 INTCON2bits.INTEDG0 = 0; // Habilitar interrupção INT0 na borda de descida RCONbits.IPEN = 0; // Desligar todas as prioridades na interrupção. INTCONbits.GIE = 1; // Habilitar interrupção geral. TRISD = 0; return; }<file_sep>/* * File: cod01.c * Author: <NAME> * * Created on 23 de Junho de 2021, 20:34 */ #include <xc.h> void main(void) { return; }<file_sep>#pragma config FOSC = INTIO67 #pragma config PBADEN = OFF #define _XTAL_FREQ 1000000 #include <xc.h> void main(void) { TRISD &= 0b00011000; //Configura os pinos RD0, RD1, RD2, RD5, RD6 e RD7, como saídas digitais. PORTD &= 0b11100111; //Desliga os Led's DS3 e DS4. while(1) { PORTD &= 0b10111011; //Desliga os Led's DS2 e DS6. PORTD |= 0b10000001; //Liga DS0 e DS7 __delay_ms(3000); PORTD &= 0b01111110; //Desliga os Led's DS0 e DS7. PORTD |= 0b10000010; //Liga DS1 e DS7 __delay_ms(1000); PORTD &= 0b01111101; //Desliga os Led's DS1 e DS7. PORTD |= 0b00100100; //Liga DS2 e DS5 __delay_ms(3000); PORTD &= 0b11011011; //Desliga os Led's DS2 e DS5. PORTD |= 0b01000100; //Liga DS2 e DS6 __delay_ms(1000); } return; }<file_sep>#pragma config FOSC = INTIO67 #pragma config PBADEN = OFF #define _XTAL_FREQ 1000000 #include <xc.h> void __interrupt() interrupcao(){ if (INTCONbits.INT0IF == 1) { __delay_ms(2000); if (PORTD == 24){ for (int i = 0; i<10; i++){ PORTD = 0b11111111; __delay_ms(250); PORTD = 0; __delay_ms(250); } } INTCONbits.INT0IF = 0; } } void main(void) { TRISB |= 0b00000001; INTCONbits.INT0IE = 1; //Habilitar interrupção externa INT0. INTCONbits.INT0IF = 0; //Limpar flag de interrupção INT0. INTCON2bits.INTEDG0 = 0;//Habilitar interrupção INT0 na borda de descida. RCONbits.IPEN = 0; //Desligar todas as prioridades na interrupção. INTCONbits.GIE = 1; //Hablitar interrupção geral. TRISD = 0b00000000; while(1) { //PORTD &= 0b01111110; //Desliga os Led's DS0 e DS7. PORTD |= 0b00000011; //Liga DS0 e DS1 __delay_ms(70); //PORTD &= 0b11111110; //Desliga o Led DS0 PORTD = 0b00000110; //Liga DS1 e DS2 __delay_ms(70); //PORTD &= 0b11111101; //Desliga o Led DS1 PORTD = 0b00001100; //Liga DS2 e DS3 __delay_ms(70); //PORTD &= 0b11111011; //Desliga os Led DS2 PORTD = 0b00011000; //Liga DS3 e DS4 __delay_ms(70); //PORTD &= 0b11110111; //Desliga os Led DS3 PORTD = 0b00110000; //Liga DS4 e DS5 __delay_ms(70); //PORTD &= 0b11101111; //Desliga os Led DS4 PORTD = 0b01100000; //Liga DS5 e DS6 __delay_ms(70); //PORTD &= 0b11011111; //Desliga os Led DS5 PORTD = 0b11000000; //Liga DS6 e DS7 __delay_ms(70); //PORTD &= 0b10111111; //Desliga os Led DS6 PORTD = 0b10000001; //Liga DS0 e DS7 __delay_ms(70); } return; }<file_sep>#pragma config FOSC = INTIO67 #pragma config PBADEN = OFF #define _XTAL_FREQ 1000000 #include <xc.h> void main(void) { TRISD &= 0b00011000; //Configura os pinos RD0, RD1, RD2, RD5, RD6 e RD7, como saídas digitais. PORTD &= 0b11100111; //Desliga os Led's DS3 e DS4. TRISB |= 0B00000001; //Configurar o bit RB0 como entrada. INTCONbits.INT0IE = 1; //Habilitar interrupção externa INT0. INTCONbits.INT0IF = 1; //Limpar flag de interrupção INT0. INTCON2bits.INTEDG0 = 0;//Habilitar interrupção INT0 na borda de descida. RCONbits.IPEN = 0; //Desligar todas as prioridades na interrupção. INTCONbits.GIE = 1; //Hablitar interrupção geral. while(1) { PORTD &= 0b10111011; //Desliga os Led's DS2 e DS6. PORTD |= 0b10000001; //Liga DS0 e DS7 __delay_ms(3000); PORTD &= 0b01111110; //Desliga os Led's DS0 e DS7. PORTD |= 0b10000010; //Liga DS1 e DS7 __delay_ms(1000); PORTD &= 0b01111101; //Desliga os Led's DS1 e DS7. PORTD |= 0b00100100; //Liga DS2 e DS5 __delay_ms(3000); PORTD &= 0b11011011; //Desliga os Led's DS2 e DS5. PORTD |= 0b01000100; //Liga DS2 e DS6 __delay_ms(1000); } return; } void __interrupt() funcao(){ if(INTCONbits.INT0IE == 1){ INTCONbits.INT0IF = 0; PORTD &= 0b00000000; //Desliga todos os led's. PORTD |= 0b10000100; __delay_ms(2000); PORTD &= 0b01111011; } }<file_sep>/* * File: cod05.c * Author: <NAME> * * Created on 23 de Junho de 2021, 22:59 */ #define _XTAL_FREQ 1000000 #pragma config FOSC = INTIO67 #include <xc.h> void main(void) { TRISD &= 0b11000111; while(1) { PORTD |= 0b00001000; __delay_ms(3000); PORTD &= 0b11110111; PORTD |= 0b00010000; __delay_ms(1000); PORTD &= 0b11101111; PORTD |= 0b00100000; __delay_ms(2000); PORTD &= 0b11011111; __delay_ms(2000); } return; } <file_sep>#include <16f628a.h> // Inclui o cabeçalho especifico do pic a ser usado #FUSES NOWDT //No Watch Dog Timer #FUSES HS //High speed Osc (> 4mhz) #FUSES NOPUT //No Power Up Timer #FUSES NOPROTECT //Code not protected from reading #FUSES BROWNOUT //Reset when brownout detected #FUSES MCLR //Master Clear pin enabled #FUSES NOCPD //No EE protection #use delay(clock=20M) // Seta o clock interno para 20Mhz #define L_VERMELHO1 PIN_B4 #define L_VERMELHO2 PIN_B2 #define L_VERDE1 PIN_B1 #define L_VERDE2 PIN_B5 #define L_AMARELO1 PIN_B3 #define L_AMARELO2 PIN_B0 void main(void) // função principal { do { /* S1 S2 O X O O X O */ output_high(L_VERMELHO2); output_high(L_VERDE1); output_low(L_AMARELO2); output_low(L_VERMELHO1); delay_ms(3000); /* S1 S2 O X X O O O */ output_low(L_VERDE1); output_high(L_AMARELO1); delay_ms(1000); /* S1 S2 X O O O O X */ output_low(L_VERMELHO2); output_high(L_VERDE2); output_low(L_AMARELO1); output_high(L_VERMELHO1); delay_ms(3000); /* S1 S2 X O O X O O */ output_low(L_VERDE2); output_high(L_AMARELO2); delay_ms(1000); } while (TRUE); // mantem o laço de repetição rodando em loop infinito } // FIM DO CODIGO<file_sep>//Sem05_exp01 int led1 = 12; int led2 = 11; int led3 = 10; int led4 = 9; int pinLDR = A0; int valorSensor = 0; void setup() { Serial.begin(9600); pinMode(led1, OUTPUT); pinMode(led2, OUTPUT); pinMode(led3, OUTPUT); pinMode(led4, OUTPUT); pinMode(pinLDR, INPUT); } void loop(){ valorSensor = analogRead(pinLDR); Serial.println(valorSensor); if(valorSensor < 640){ digitalWrite(led1,HIGH); digitalWrite(led2,LOW); digitalWrite(led3,LOW); digitalWrite(led4,LOW); } if(valorSensor >= 640 && valorSensor <= 768){ digitalWrite(led1,HIGH); digitalWrite(led2,HIGH); digitalWrite(led3,LOW); digitalWrite(led4,LOW); } if(valorSensor >= 768 && valorSensor <= 896){ digitalWrite(led1,HIGH); digitalWrite(led2,HIGH); digitalWrite(led3,HIGH); digitalWrite(led4,LOW); } if(valorSensor > 896){ digitalWrite(led1,HIGH); digitalWrite(led2,HIGH); digitalWrite(led3,HIGH); digitalWrite(led4,HIGH); } }<file_sep>/* * File: cod04.c * Author: <NAME> * * Created on 23 de Junho de 2021, 21:45 */ #define _XTAL_FREQ 1000000 #pragma config FOSC = INTIO67 #include <xc.h> void main(void) { TRISD &= 0b11111100; // Configura os pinos RD0 e RD1 como saída digital. TRISB |= 0b00000001; // Configura o pino RB0 como saída digital. PORTD |= 0b00000010; while(1){ if ((PORTB && 0b00000001) == 0){ PORTD |= 0b00000001; PORTD &= 0b11111101; } } return; } //Não Funcionou!<file_sep>/* * File: cod3.c * Author: <NAME> * * Created on 23 de Junho de 2021, 21:08 */ #pragma config FOSC = INTIO67 #include <xc.h> void main(void) { TRISD &= 0b11101010; while(1) { PORTD |= 0b00010101; // Escreve nível lógico alto ('1') no pino RD0, RD2, RD4 } return; }
a38d643fbb48f06c13dad31c7b426b6e8be560e9
[ "C", "C++" ]
13
C
Doegue/SMC
e1783a2761a52037ff8210b24135bb8e2dca0f0f
b0fd5724310fa896e880d2d39bb87008e47dc7a3
refs/heads/master
<repo_name>AlexFernando/website_portafolio<file_sep>/js/app.js window.addEventListener("hashchange", function() { scrollBy(0, -80) }) //change background color when scroll /*window.onscroll = (e) => { const scroll = window.scrollY; const otherScroll = document.body.scrollTop; const home = document.querySelector('#home_nav'); const about = document.querySelector('#about_nav'); const project = document.querySelector('#projects_nav'); const gear = document.querySelector('#gear_nav'); const contact = document.querySelector('#contact_nav'); console.log(otherScroll); switch(true) { case (scroll>0 && scroll<320): project.removeAttribute('style'); contact.removeAttribute('style'); home.classList.add('mycolor'); break; case (scroll>320 && scroll<1524): home.classList.remove('mycolor'); project.removeAttribute('style'); contact.removeAttribute('style'); about.style.color = '#e5e5e5'; break; case (scroll>1524 && scroll<2096): home.classList.remove('mycolor'); about.removeAttribute('style'); gear.removeAttribute('style') contact.removeAttribute('style'); project.style.color = '#e5e5e5'; break; case (scroll>2096 && scroll<2624): home.classList.remove('mycolor'); about.removeAttribute('style'); project.removeAttribute('style'); contact.removeAttribute('style'); gear.style.color = '#e5e5e5'; break; case (scroll>2624 && scroll<2955): about.removeAttribute('style'); home.classList.remove('mycolor'); project.removeAttribute('style'); gear.removeAttribute('style'); contact.style.color = '#e5e5e5'; break; default: home.removeAttribute('style'); about.removeAttribute('style'); project.removeAttribute('style'); gear.removeAttribute('style'); contact.removeAttribute('style'); } }*/ jQuery(document).ready(function() { jQuery(".menu-Trigger").click(function() { jQuery(".menu-mobile").slideToggle(100, function() { jQuery(this).toggleClass("nav-Expanded"); if($(".menu-mobile").is(":hidden")) $(".menu-Trigger").text("☰ Menu"); else $(".menu-Trigger").text("X Close"); }); }); }); document.addEventListener('DOMContentLoaded', function() { setTimeout(function() { onScrollInit($('.waypoint')) }, 100); //navegacion(); //mixItUp function $(function() { var mixer = mixitup('.container'); }); //slider function $(function() { $(".rslides").responsiveSlides(); $("#slider3").responsiveSlides({ manualControls: '#slider3-pager', maxwidth: 540 }); }); }); //scrollSpy (function() { 'use strict'; let sections = document.querySelectorAll('.mySection'); let arrayOffset = {}; let section = 0; Array.prototype.forEach.call(sections, function(e) { arrayOffset[e.id] = e.offsetTop; }); window.onscroll = function() { let scrollPosition = document.documentElement.scrollTop || document.body.scrollTop; for(section in arrayOffset) { if(arrayOffset[section] <= scrollPosition) { let myNavbar = document.querySelector('.navegacion'); document.querySelector('.active').setAttribute('class',' '); document.querySelector('a[href*=' + section + ']').setAttribute('class', 'active'); /*if(section === 'about' || section === 'gear') { myNavbar.classList.add('myBarColor'); myNavbar.classList.remove('myBarColor2'); } else if(section === 'projects') { myNavbar.classList.add('myBarColor2') myNavbar.classList.remove('myBarColor'); } else { myNavbar.classList.remove('myBarColor'); myNavbar.classList.remove('myBarColor2'); }*/ } } }; })(); // SCROLL ANIMATIONS function onScrollInit( items, elemTrigger ) { var offset = $(window).height() / 1.6 items.each( function() { var elem = $(this), animationClass = elem.attr('data-animation'), animationDelay = elem.attr('data-delay'); elem.css({ '-webkit-animation-delay': animationDelay, '-moz-animation-delay': animationDelay, 'animation-delay': animationDelay }); var trigger = (elemTrigger) ? trigger : elem; trigger.waypoint(function() { elem.addClass('animated').addClass(animationClass); if (elem.get(0).id === 'gallery') mixClear(); //OPTIONAL },{ triggerOnce: true, offset: offset }); }); }
1ab399e5de54f46c275b116762dd77a9bbeebbed
[ "JavaScript" ]
1
JavaScript
AlexFernando/website_portafolio
c156545821752e22a7146c03052c54103b48e34c
6460823aa7f96a13c224d948be8b07382231e022
refs/heads/master
<repo_name>byvalentino/TrajectoryNet<file_sep>/create_npy.py import numpy as np csvfile = './data/mobility_encoding.csv' task = 'mobility' data = np.genfromtxt(csvfile, dtype=float, delimiter=',') mmsi = data[:,0].astype(int) labels = data[:,data.shape[1]-1] features = data[:, 1:data.shape[1]-1] mmsi_length = np.unique(mmsi, return_counts=True) num_persons = len(mmsi_length[0]) max_mmsi_len = max(mmsi_length[1]) num_features = features.shape[1] padding_data = np.zeros((max_mmsi_len * num_persons, num_features)) for person in range(num_persons): person_data = np.zeros((max_mmsi_len, num_features)) person_data[0:mmsi_length[1][person],:] = features[mmsi == mmsi_length[0][person],:] padding_data[person*max_mmsi_len : (person+1)*max_mmsi_len,:] = person_data padding_labels = np.zeros((max_mmsi_len * num_persons)) for person in range(num_persons): person_data = np.zeros((max_mmsi_len)) person_data[0:mmsi_length[1][person]] = labels[mmsi == mmsi_length[0][person]] padding_labels[person*max_mmsi_len : (person+1)*max_mmsi_len] = person_data x = np.reshape(padding_data, (num_persons, max_mmsi_len, num_features)) y = np.reshape(padding_labels, (num_persons, max_mmsi_len)) y = y.astype(int) np.save('./data/x_'+task+'.npy', x) np.save('./data/y_'+task+'.npy', y) np.save('./data/mmsi_'+task+'.npy', mmsi_length) <file_sep>/README.md # TrajectoryNet ### Slides For a quick overview of the paper, please refer to the [slides](https://docs.google.com/presentation/d/1nabGnSxAEvjNKHVVCXxMD_NRNJc6983BorVIX36GeaU/edit?usp=sharing) ### Title TrajectoryNet: An Embedded GPS Trajectory Representation for Point-based Classification Using Recurrent Neural Networks **Authors**: <NAME>, <NAME>, <NAME>, <NAME>, <NAME> and <NAME> **Abstract**: Understanding and discovering knowledge from GPS (Global Positioning System) traces of human activities is an essential topic in mobility-based urban computing. We propose TrajectoryNet-a neural network architecture for point-based trajectory classification to infer real world human transportation modes from GPS traces. To overcome the challenge of capturing the underlying latent factors in the low-dimensional and heterogeneous feature space imposed by GPS data, we develop a novel representation that embeds the original feature space into another space that can be understood as a form of basis expansion. We also enrich the feature space via segment-based information and use Maxout activations to improve the predictive power of Recurrent Neural Networks (RNNs). We achieve over 98% classification accuracy when detecting four types of transportation modes, outperforming existing models without additional sensory data or location-based prior knowledge. **Contact** <EMAIL> Please feel free to email me in case you have any questions with the code. There are a lot of redundant codes that I have not got a chance to clean up. Sorry about this clutter! ### Dependencies The follwoing softwares are required for this source code. - **Python 3.5** - **Tensorflow 1.4.1** - sklean 0.18.1 - numpy 1.12.0 - R (optional for preprocessing) ### Data The original dataset can be found [here](https://www.microsoft.com/en-us/research/publication/geolife-gps-trajectory-dataset-user-guide/). We preprocessed a subset of the data in the `data` directory. This dataset contains features in `.csv` format as well as `.npy` format: - `csvdata.csv`: include data of four classes (car, bike, drive and walk) with longitudes, latitudes, speeds and other features - `encodedcsv.zip`: the same data after discretization and one-hot-encoding - `npy.zip`: the same data in `.npy` format. This can be used to train the model directly. If you want to train the model without any preprocessing, please `unzip` the numpy data before training the model: ``` cd ./data unzip npy.zip ``` ### Network Configurations The file config.json includes the configurations of the model: - training, validation and test set selection - number of hidden nodes in each layer - learning rate - mini-batch size - number of layers - number of epochs - whether to checkpoint the model after training - whether to restore the model before training - the size of truncated sequences - frequency to evaluate the model while training - number of threads - whether to use GPU during training - etc. ### Network Training `python trajectoryNet.py` ### Preprocessing In case you are interested in the preprocessing and discretization of the data, please refer to file `preprocess.R`. After the preprocess data are stored in a `.csv` file, it is required to run `create_npy.py` to transform the data into `.npy` format to get ready to import to Tensorflow. <file_sep>/preprocess.R library(geosphere) library(dummies) library(plyr) library(foreach) library(ggplot2) library(discretization) library(geosphere) library(plotly) #------------------------------- # define functions #------------------------------- # calculate difference of longitude and latitude DiffGPS <- function(lon) { lon_1 <- lon lon_2 <- lon lon_1 <- lon_1[-mmsi_index_last$x] lon_2 <- lon_2[-mmsi_index_first$x] lon = lon_1 - lon_2 lon } # equal-width discretization EqualWidth <- function(x,n){ x <- HampelFilter(x, 5) x <- x$y v_min <- min(x) v_max <- max(x) interval <- (v_max - v_min) / n print(paste0("min:",v_min)) print(paste0("max:",v_max)) print(paste0("interval:",interval)) bin <- floor((x-v_min)/interval) + 1 member <- (x-v_min)%%interval / interval bin[bin==(n+1)] <- n mm <- matrix(0, length(x), n) encoding <- apply(mm, c(1, 2), function(x) 0) for(i in c(1:length(x))) { encoding[i,bin[i]] <- 1 } encoding <- data.frame(encoding) stopifnot(sum(encoding)==nrow(encoding)) encoding } # position coding PositionCoding <- function(x,n){ x <- HampelFilter(x, 5) x <- x$y v_min <- min(x) v_max <- max(x) interval <- (v_max - v_min) normalized <- (x-v_min)/interval mm <- matrix(0, length(x), n) encoding <- apply(mm, c(1, 2), function(x) 0) for(i in c(1:n)) { encoding[,i] <- dnorm(normalized, mean=interval/n*(i-1), sd=interval/n) } encoding <- data.frame(encoding) encoding } # nominal # equal-width discretization toNominal <- function(x,n){ x <- HampelFilter(x, 5) x <- x$y v_min <- min(x) v_max <- max(x) interval <- (v_max - v_min) / n print(paste0("min:",v_min)) print(paste0("max:",v_max)) print(paste0("interval:",interval)) bin <- floor((x-v_min)/interval) bin[bin==(n)] <- n-1 encoding <- data.frame(bin) encoding } # median filter HampelFilter <- function (x, k,t0=3){ min_v <- quantile(x, 0) max_v <- quantile(x, 0.95) n <- length(x) y <- x ind <- c() for (i in (k + 1):(n-k)){ if (x[i]<max_v && x[i]>min_v){ next } ind <- c(ind, i) y[i] <- median(x[(i - k):(i + k)]) if (y[i] > max_v) {y[i] <- max_v} if (y[i] < min_v) {y[i] <- min_v} } list(y = y, ind = ind) } # median filter HampelFilter2 <- function (x, k,t0=3){ min_v <- quantile(x, 0.05) max_v <- quantile(x, 0.95) n <- length(x) y <- x ind <- c() for (i in (k + 1):(n-k)){ stdev <- sd(x[(i - k):(i + k)]) mdn <- median(x[(i - k):(i + k)]) if (abs(x[i]-mdn)<3*stdev){ next } ind <- c(ind, i) y[i] <- median(x[(i - k):(i + k)]) if (y[i] > max_v) {y[i] <- max_v} if (y[i] < min_v) {y[i] <- min_v} } list(y = y, ind = ind) } lag_apply <- function(x, n, callback){ k = length(x); result = rep(0, k); for(i in 1 : (k - n + 1)){ result[i] <- callback(x[i : (i + n -1)]); } return(result); } #------------------------------- # Processing: load data -> select features -> discretization -> one-hot encoding # Note: # The one-hot encoding is essential to the success of the model: # It enables the learning of feature embeddings in the recurrent network. #------------------------------- # Please set working directory to the repo setwd('../trajectoryNet') # load raw trajectory data from .csv data <- read.csv("data/fourclassdata.csv") # select features # the first column (MMSI) denotes the ID of a person # the last column (COARSE_FIS) denotes the labels data <- subset(data, select=c("MMSI", "LONGITUDE","LATITUDE","speedmin", "accmin2", "avgspeed","meanacc","stdspeed", "date", "COARSE_FIS")) # select the four classes with their ids # car, walk, bus, bike: 1,2,3,6 four_class_data <- data[data$COARSE_FIS %in% c(1,2,3,6),] # get total length len = length(four_class_data$LONGITUDE) four_class_data$rowNum <- seq(len) # find starting and end points for each person mmsi_index_last <- aggregate(four_class_data$rowNum, by=list(four_class_data$MMSI), function(x) tail(x, 1)) mmsi_index_first <- aggregate(four_class_data$rowNum, by=list(four_class_data$MMSI), function(x) head(x, 1)) labels <- four_class_data$COARSE_FIS[-mmsi_index_last$x] labels[labels==6] <- 0 # change bike from label 6 to label 0 mmsis <- four_class_data$MMSI[-mmsi_index_last$x] # difference of longitude and latitude lon <- DiffGPS(four_class_data$LONGITUDE) lat <- DiffGPS(four_class_data$LATITUDE) # other features speedmin <-four_class_data$speedmin[-mmsi_index_last$x] accmin<-four_class_data$accmin2[-mmsi_index_last$x] avgspd<-four_class_data$avgspeed[-mmsi_index_last$x] meanacc<-four_class_data$meanacc[-mmsi_index_last$x] stdspd<-four_class_data$stdspeed[-mmsi_index_last$x] time <- four_class_data$date[-mmsi_index_last$x] time <- as.POSIXct(time) # calculate on-hot-encoding/discretization # ------------------------------------------------------------------- lon_en <- EqualWidth(lon, 20) lat_en <- EqualWidth(lat, 20) speedmin_en <- EqualWidth(speedmin,20) accmin_en <- EqualWidth(accmin, 20) avgspd_en <- EqualWidth(avgspd,20) meanacc_en <- EqualWidth(meanacc, 20) stdspd_en <- EqualWidth(stdspd, 20) # bind features into one data frame # ------------------------------------------------------------------- #continuous_features <- data.frame(speedmin, avgspd, stdspd, labels) #continuous_features <- data.frame(mmsis, lon, lat, speedmin, accmin, avgspd, meanacc, stdspd,time, labels) #continuous_features <- data.frame(mmsis, lon, lat, speedmin, avgspd, stdspd, labels) #context_features <- cbind(mmsis, lon_en, lat_en, speedmin_en, accmin_en, avgspd_en, meanacc_en, stdspd_en, labels) # selected features: # point-based: speed # segmentation-based: avg_spd, std_spd context_features <- cbind(mmsis, speedmin_en, avgspd_en, stdspd_en, labels) # write to csv file # ------------------------------------------------------------------- write.table(context_features, file = "data/mobility_encoding.csv", sep = ",", row.names = FALSE, col.names = FALSE) <file_sep>/param.py from enum import Enum class RNNType(Enum): LSTM_u = 1 # LSTM unidirectional LSTM_b = 2 # LSTM bidirectional GRU = 3 # GRU GRU_b = 4 # GRU, bidirectional
063740089ad89ff5b9542c0257ee2a200475673c
[ "Markdown", "Python", "R" ]
4
Python
byvalentino/TrajectoryNet
89fdda9dd26faf9a571429897c896fb1a2a1f6de
92cc9aecf7e5fce1e4b725e2a1d0833cf13e0838
refs/heads/master
<repo_name>madmason/sigslot-dll<file_sep>/lib1/ParentInterface.h #pragma once #include <QObject> #ifdef WIN32 #ifndef LIB1_EXPORT #define LIB1_EXPORT __declspec(dllimport) #endif #else #define LIB1_EXPORT #endif class ParentInterface{ public: virtual ~ParentInterface(){} signals: virtual void test() = 0; }; Q_DECLARE_INTERFACE(ParentInterface,"ParentInterface") <file_sep>/lib1/lib1.h //### lib1/lib1.h #ifndef LIB1_H #define LIB1_H #include <QObject> #include "ParentInterface.h" class LIB1_EXPORT Parent : public QObject, public ParentInterface{ Q_OBJECT Q_INTERFACES(ParentInterface) signals: void test(); }; #endif <file_sep>/README.md # sigslot-dll This repository is a cope of https://github.com/KubaO/stackoverflown/tree/master/questions/sigslot-dll-39149263 by KubaO. It was created to answer this issue on stackoverflow: http://stackoverflow.com/questions/39149263/signal-not-correctly-exported-when-inheriting-from-different-dll I added some stuff to better recreate the issue.
c9476a287eaf143f3be7fb49712c985b55cfca21
[ "Markdown", "C++" ]
3
C++
madmason/sigslot-dll
9062f3918d5d2477e44934a0e80f11f1d00802d2
5fac5e68e03da443e363bd273f5cb50d129accc1
refs/heads/master
<repo_name>dlxldnd/group11_Exs<file_sep>/app/src/main/java/com/example/taewoong/exchangestudent/Activity/NewMeetingActivity.java package com.example.taewoong.exchangestudent.Activity; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v7.app.ActionBar; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import com.example.taewoong.exchangestudent.R; /** * Created by Taewoong on 2017-11-17. */ public class NewMeetingActivity extends AppCompatActivity{ @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_newmeeting); Toolbar toolbar = (Toolbar)findViewById(R.id.toolbar); setSupportActionBar(toolbar); ActionBar actionBar = getSupportActionBar(); actionBar.setDisplayShowCustomEnabled(true); actionBar.setDisplayShowTitleEnabled(false); } } <file_sep>/app/src/main/java/com/example/taewoong/exchangestudent/Activity/LoginActivity.java package com.example.taewoong.exchangestudent.Activity; import android.graphics.Paint; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v7.app.ActionBar; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.text.Html; import android.widget.Button; import android.widget.TextView; import com.example.taewoong.exchangestudent.R; /** * Created by Taewoong on 2017-11-17. */ public class LoginActivity extends AppCompatActivity{ @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_login); Button button = (Button) findViewById(R.id.snbutton); button.setPaintFlags(button.getPaintFlags() | Paint.UNDERLINE_TEXT_FLAG); Toolbar toolbar = (Toolbar)findViewById(R.id.toolbar); setSupportActionBar(toolbar); ActionBar actionBar = getSupportActionBar(); actionBar.setDisplayShowCustomEnabled(true); actionBar.setDisplayShowTitleEnabled(false); } }
223d4ff77f7fa9147738587f730f3324f689426d
[ "Java" ]
2
Java
dlxldnd/group11_Exs
18b8bb9d36212ce8d05a2c76a752064b2dbaea92
e1802d86bd43be6ff3b7968d670bdaa7671e7717
refs/heads/master
<file_sep># Rxjava2Retrofit2 Simple Movies app - sample usage Rxjava2 + Retrofit2 + ButterKnife ![Alt text](https://github.com/droidbaza/Rxjava2Retrofit2/blob/master/app/src/main/res/drawable/movies.gif) <file_sep>package com.droidbaza.movies.adapter; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import androidx.annotation.NonNull; import androidx.recyclerview.widget.RecyclerView; import com.bumptech.glide.Glide; import com.droidbaza.movies.R; import com.droidbaza.movies.model.Movie; import java.util.List; import butterknife.BindView; import butterknife.ButterKnife; /** * Created by droidbaza on 16/10/19. */ public class MoviesAdapter extends RecyclerView.Adapter<MoviesAdapter.ViewHolder> { private List<Movie> movies; private Context context; public MoviesAdapter(Context context, List<Movie> movies){ this.movies = movies; this.context = context; } class ViewHolder extends RecyclerView.ViewHolder{ @BindView(R.id.title) TextView title; @BindView(R.id.overview) TextView overview; @BindView(R.id.poster) ImageView poster; ViewHolder(View view) { super(view); ButterKnife.bind(this, view); } } @Override public void onBindViewHolder(ViewHolder holder, int position) { Movie movie = movies.get(position); holder.title.setText(movie.getTitle()); holder.overview.setText(movie.getOverview()); Glide.with(context) .load("https://image.tmdb.org/t/p/w500/"+movie.getPoster()) .into(holder.poster); } @NonNull @Override public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { View itemView = LayoutInflater.from(parent.getContext()) .inflate(R.layout.item_movie, parent, false); return new ViewHolder(itemView); } @Override public int getItemCount() { return movies.size(); } } <file_sep>package com.droidbaza.movies; import android.os.Bundle; import androidx.appcompat.app.AppCompatActivity; import androidx.recyclerview.widget.RecyclerView; import com.droidbaza.movies.adapter.MoviesAdapter; import com.droidbaza.movies.adapter.ZoomLinearLayoutManager; import com.droidbaza.movies.api.ApiService; import com.droidbaza.movies.api.MovieApi; import com.droidbaza.movies.model.Movie; import com.droidbaza.movies.model.Page; import java.util.ArrayList; import java.util.List; import butterknife.BindView; import butterknife.ButterKnife; import io.reactivex.SingleObserver; import io.reactivex.android.schedulers.AndroidSchedulers; import io.reactivex.disposables.Disposable; import io.reactivex.schedulers.Schedulers; /** * Created by droidbaza on 16/10/19. */ public class MainActivity extends AppCompatActivity { @BindView(R.id.recyclerview) RecyclerView recyclerView; private List<Movie> movies = new ArrayList<>(); private MoviesAdapter moviesAdapter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); ButterKnife.bind(this); moviesAdapter = new MoviesAdapter(MainActivity.this, movies); ZoomLinearLayoutManager lm = new ZoomLinearLayoutManager(this); recyclerView.setLayoutManager(lm); recyclerView.setAdapter(moviesAdapter); getMovies(); } private void getMovies(){ MovieApi movieApi = ApiService.getMovieApi(); movieApi.getPage().subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(new SingleObserver<Page>() { @Override public void onSubscribe(Disposable d) { } @Override public void onSuccess(Page page) { List<Movie>movieList = page.getResults(); movies.addAll(movieList); moviesAdapter.notifyDataSetChanged(); } @Override public void onError(Throwable e) { } }); } }
372e09f958940c428c17d4dc85f0a8d19e8dae65
[ "Markdown", "Java" ]
3
Markdown
droidbaza/Rxjava2Retrofit2
8481f88aed7525a92eba5a923cbe23464e5ad6b1
d8eb319d32cf10ff66e9ec09963a50196de94f79
refs/heads/master
<repo_name>PIEAGE/GameOfLife<file_sep>/src/js/app.js var main = document.getElementById("main") var game = new RenderGame(main); var len = 50; var world = new CubeCollection(len); var deadProbabilityVal = document.getElementById('deadProbabilityVal'); var start = document.getElementById("start"); game.playing = true; //Populate world with cubes world.forEachCube(function(cube) { game.scene.add(cube); }); //Setup OrbitalControls game.setupOrbitalControls(25, 25, 50); //Initial state of cubes in world var probability = 0.5; world.startingState(probability); //Start and stop the game listener start.addEventListener('click', function() { if (game.playing) { game.playing = !game.playing; document.getElementById("play-pause-button").src = "assets/images/play.svg"; } else { game.playing = !game.playing; document.getElementById("play-pause-button").src = "assets/images/pause.svg"; } }); //Skip one generation listener skip.addEventListener('click', function() { if (game.playing) { game.playing = !game.playing; world.progress(); document.getElementById("play-pause-button").src = "assets/images/play.svg"; } else { world.progress(); } }); //Restart game listener refresh.addEventListener('click', function() { if (game.playing) { game.playing = !game.playing; document.getElementById("play-pause-button").src = "assets/images/play.svg"; world.startingState(probability); } else { world.startingState(probability); } }); //Camera Rotation Listener rotation.addEventListener('click', function() { if (game.controls.autoRotate == true) { game.controls.autoRotate = false; document.getElementById("rotate-button").src = "assets/images/rotation.svg"; } else { game.controls.autoRotate = true; document.getElementById("rotate-button").src = "assets/images/rotationLock.svg"; } }); //Get probability of cube being dead document.getElementById('deadProbability') .addEventListener('input', function(event) { probability = event.target.value / 100; deadProbabilityVal.innerText = event.target.value + "%"; }); game.render(world); <file_sep>/src/js/RenderGame.js function RenderGame (root) { //Setup scene and camera this.scene = new THREE.Scene(); this.camera = new THREE.PerspectiveCamera( 75, window.innerWidth / window.innerHeight, 0.1, 1000 ); this.camera.position.x = 25; this.camera.position.y = 25; this.camera.position.z = 50; //Renderer this.renderer = new THREE.WebGLRenderer(); this.renderer.setSize( window.innerWidth, window.innerHeight ); //GridHelper this.size = 10; this.divisions = 10; this.gridHelper = new THREE.GridHelper( this.size, this.divisions, 0x888888, 0x888888); this.gridHelper.rotation.x = -(Math.PI / 2); //this.scene.add( this.gridHelper ); this.gridHelper.position.x = 4.5; this.gridHelper.position.y = 4.5; this.scene.background = new THREE.Color( 0x084c61 ); //Attach to DOMElement root.appendChild( this.renderer.domElement ); //Record time for game tick this.initialTime = Date.now(); this.currentTime = null; //Init OrbitalControls for looking around scene and rotating camera this.controls = new THREE.OrbitControls( this.camera, this.renderer.domElement); } RenderGame.prototype.setupOrbitalControls = function(x,y,z) { this.controls.target = new THREE.Vector3(25, 25, 0); this.controls.autoRotate = false; this.controls.update(); return this.controls; } //Render function prototype RenderGame.prototype.render = function(world) { //Managing game tick this.currentTime = Date.now(); var tickDuration = 100; var differenceInTime = Math.round(this.currentTime - this.initialTime); if (differenceInTime > tickDuration) { this.initialTime = this.currentTime - differenceInTime % tickDuration; if (game.playing) { world.progress(); } } this.controls.update(); requestAnimationFrame(this.render.bind(this, world)); this.renderer.render( this.scene, this.camera); } <file_sep>/README.md # GameOfLife A three.js implementation of Conways Game of Life <file_sep>/src/js/Cube.js function Cube(x,y,z) { var geometry = new THREE.BoxGeometry( 0.6, 0.6, 0.6 ); var material = new THREE.MeshNormalMaterial( {color: 0xffff00, transparent: true, opacity: 1.0} ); THREE.Mesh.call(this, geometry, material); this.position.set(x, y, z); this.userData = { alive: false }; } //Inherit Mesh for optimisation Cube.prototype = Object.create(THREE.Mesh.prototype); Cube.prototype.constructor = Cube; //Display or don't display cube base on bool Cube.prototype.setAlive = function(aliveOrNot) { if (aliveOrNot) { this.material.color = new THREE.Color(0xffff00); this.material.opacity = 1.0; this.userData.alive = aliveOrNot; } else { this.material.opacity = 0; this.userData.alive = false; } }
f480357836957912c8d6ad086c3c637903a70eff
[ "JavaScript", "Markdown" ]
4
JavaScript
PIEAGE/GameOfLife
1c2fefb1ab3234a5486e6ae2eade34fa4c1d56b6
442795a19af9deef8380e478ff7f3a871d53b6d3
refs/heads/master
<repo_name>organizations-loops/RLLOCK<file_sep>/go.mod module RLLOCK go 1.14 require ( github.com/gofrs/uuid v4.0.0+incompatible github.com/gomodule/redigo v1.8.5 ) <file_sep>/README.md # 解决的问题 go在使用redis(setnx)分布锁的时候,我们业务处理的代码能否在这个过期时间内执行完代码。在原来的锁快过期的时候给他时间续上 # 设计思路 在加完锁后开启一个goroutine, 每隔一段时间进行延长锁的过期时间,判断是否业务处理完,根据context对象的生命周期 # 实现原理 ## 1-使用了context ##### Deadline:方法需要返回当前 Context 被取消的时间,也就是完成工作的截止日期; ##### Done: 方法需要返回一个 Channel,这个 Channel 会在当前工作完成或者上下文被取消之后关闭,多次调用 Done 方法会返回同一个 Channel; ##### Err: 方法会返回当前 Context 结束的原因,它只会在 Done 返回的 Channel 被关闭时才会返回非空的值;如果当前 Context 被取消就会返回 Canceled 错误;如果当前 Context 超时就会返回 DeadlineExceeded 错误; ##### Value: 方法会从 Context 中返回键对应的值,对于同一个上下文来说,多次调用 Value 并传入相同的 Key 会返回相同的结果,这个功能可以用来传递请求特定的数据; **学习链接**:https://www.bookstack.cn/read/draveness-golang/6ee8389651c21ac5.md#%E6%8E%A5%E5%8F%A3 ## 2- lua命令, redigo工具类等等 # RLLock <file_sep>/redisTool.go package RLLOCK import ( "github.com/gomodule/redigo/redis" "time" ) // redis config type RedisConf struct { Host string Pass string DB int // 连接池中最大空闲连接数 MaxIdleConnections int //给定时间池中分配的最大连接数。 MaxConnections int // 闲置链接超时时间 IdleTimeout int } // redis配置 func CreateRedisConfig(host string, DB int, pass string, idleTimeout int, maxConnections int, maxIdleConnections int) (redisConf RedisConf) { return RedisConf{ Host: host, Pass: pass, DB: DB, IdleTimeout: idleTimeout, MaxConnections: maxConnections, MaxIdleConnections: maxIdleConnections, } } // 创建连接池 func ConnectRedisPool(redisConf RedisConf) (pool *redis.Pool, err error) { pool = &redis.Pool{ MaxIdle: redisConf.MaxIdleConnections, MaxActive: redisConf.MaxConnections, IdleTimeout: time.Duration(redisConf.IdleTimeout) * time.Second, Dial: func() (redis.Conn, error) { timeout := 500 * time.Millisecond c, err := redis.Dial("tcp", redisConf.Host, redis.DialPassword(redisConf.Pass), redis.DialDatabase(redisConf.DB), redis.DialConnectTimeout(timeout), redis.DialReadTimeout(timeout), redis.DialWriteTimeout(timeout)) if err != nil { return c, err } return c, nil }, } return } <file_sep>/main/demo.go package main import ( "RLLOCK" "context" "fmt" "time" ) func main() { config := RLLOCK.CreateRedisConfig("host:port", 2, "", 500, 0, 0) pool, err := RLLOCK.ConnectRedisPool(config) if err != nil { fmt.Print("err: %s\n", err.Error()) return } lockFactory := RLLOCK.CreateLock(pool) lockFactory.SetKeepAlive(true) lockFactory.SetLockRetryCount(3) lockFactory.SetLockRetryDelayMS(500) lockObj, err := lockFactory.Lock(context.Background(), "ceshi123", 1*1000) if err != nil { fmt.Print("加锁失败: %s\n", err.Error()) return } if lockObj == nil { fmt.Print("加锁失败\n") return } time.Sleep(2 * time.Second) defer func() { _, err = lockFactory.UnLock(context.Background(), lockObj) if err != nil { fmt.Print("解锁失败: %s \n", err.Error()) return } }() } <file_sep>/Rrlock.go package RLLOCK import ( "context" "errors" "fmt" "github.com/gofrs/uuid" "github.com/gomodule/redigo/redis" "sync" "time" ) const ( //默认重试次数 DefaultLockRetryCount = 3 //默认没枷锁的重试次数 DefaultUnLockRetryCount = 3 //默认续命重试次数 DefaultContinuedRetryCount = 3 //重试的延迟 DefaultLockRetryDelayMS = 500 //未加锁的重试延迟 DefaultUnLockRetryDelayMS = 500 //默认续命时间间隔 DefaultContinuedTime = 500 ) var ( mutexLock sync.Mutex luaScriptDelete = redis.NewScript(1, `if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end`) luaScriptSetnx = redis.NewScript(1, `if redis.call('setnx', KEYS[1], ARGV[1]) == 1 then return redis.call('PEXPIRE',KEYS[1],ARGV[2]) else return 0 end`) luaScriptExpire = redis.NewScript(2, `if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('PEXPIRE', KEYS[2], ARGV[2]) else return 0 end`) ) //获取随机值 func GetRandomValue() (valueGUID string) { uuidData, _ := uuid.NewV4() return uuidData.String() } // 锁工厂 type lockFactory struct { pool *redis.Pool lockRetryCount int32 lockRetryDelayMS int64 unLockRetryCount int32 unLockRetryDelayMS int64 continuedRetryCount int32 isKeepAlive bool } // 新建一个redis锁对象 func CreateLock(pool *redis.Pool) *lockFactory { return &lockFactory{ pool: pool, lockRetryCount: DefaultLockRetryCount, lockRetryDelayMS: DefaultLockRetryDelayMS, unLockRetryCount: DefaultUnLockRetryCount, unLockRetryDelayMS: DefaultUnLockRetryDelayMS, continuedRetryCount: DefaultContinuedRetryCount, } } // 可续命锁对象 type RLLock struct { CreateTime int64 ContinuedTime int //持续时间 ContinuedTimeMS int64 //续命时间(ms) UnlockTime int64 KeyName string //键 RandomKey string //随机值 IsUnlock bool RedisChan chan struct{} ChanIsNoIn bool IsLive bool } // 参数的设置与获取 func (s *lockFactory) SetLockRetryCount(lockRetryCount int32) { if lockRetryCount < 0 { s.lockRetryCount = DefaultLockRetryCount } else { s.lockRetryCount = lockRetryCount } } func (s *lockFactory) GetLockRetryCount() int32 { return s.lockRetryCount } func (s *lockFactory) SetUnLockRetryCount(unLockRetryCount int32) { if unLockRetryCount < 0 { s.unLockRetryCount = DefaultUnLockRetryCount } else { s.unLockRetryCount = unLockRetryCount } } func (s *lockFactory) GetUnLockRetryCount() int32 { return s.unLockRetryCount } func (s *lockFactory) SetKeepAlive(isKeepAlive bool) { s.isKeepAlive = isKeepAlive } func (s *lockFactory) GetKeepAlive() bool { return s.isKeepAlive } func (s *lockFactory) SetLockRetryDelayMS(lockRetryDelayMS int64) { if lockRetryDelayMS < 0 { s.lockRetryDelayMS = DefaultLockRetryDelayMS } else { s.lockRetryDelayMS = lockRetryDelayMS } } func (s *lockFactory) GetLockRetryDelayMS() int64 { return s.lockRetryDelayMS } func (s *lockFactory) SetUnLockRetryDelayMS(unLockRetryDelayMS int64) { if unLockRetryDelayMS < 0 { s.unLockRetryDelayMS = DefaultUnLockRetryDelayMS } else { s.unLockRetryDelayMS = unLockRetryDelayMS } } func (s *lockFactory) GetUnLockRetryDelayMS() int64 { return s.unLockRetryDelayMS } //加锁 func (s *lockFactory) Lock(ctx context.Context, keyName string, lockMillSecond int) (lock *RLLock, err error) { conn := s.pool.Get() defer func() { err := conn.Close() if err != nil { fmt.Printf("关闭redis池失败: %s \n", err.Error()) } }() lockTime := lockMillSecond randomData := GetRandomValue() retry := s.GetLockRetryCount() // 重试机制 for retry >= 0 { select { // 如果处理完直接返回 // Done:返回一个 Channel,这个 Channel 会在当前工作完成或者上下文被取消之后关闭,多次调用 Done 方法会返回同一个 Channel; case <-ctx.Done(): fmt.Println("Lock-执行结束") return nil, ctx.Err() default: beginTime := time.Now().UnixNano() retry -= 1 // 加锁 luaRes, err := luaScriptSetnx.Do(conn, keyName, randomData, lockTime) if err != nil { fmt.Printf("redis分布式锁-加锁失败-时间: %v,key:%s, value:%s, expire: %d ms, err:%s \n", beginTime, keyName, randomData, lockMillSecond, err.Error()) if retry != 0 { fmt.Println("加锁失败-准备重试加锁") time.Sleep(time.Duration(s.GetLockRetryDelayMS()) * time.Millisecond) continue } } res, err := redis.Int64(luaRes, err) if res == 1 { lock = new(RLLock) lock.ContinuedTime = lockTime lock.RandomKey = randomData lock.KeyName = keyName lock.CreateTime = time.Now().UnixNano() / 1e6 //如果需要持续等任务执行完,那锁也应该让他保持一样的状态 if s.isKeepAlive { lock.IsLive = true // 保证续命groutine能停止 lock.RedisChan = make(chan struct{}) go s.RenewalLife(lock, lockTime/2) } fmt.Println("加锁成功") return lock, nil } else { fmt.Printf("%s 加锁失败: %+v \n", keyName, res) if retry != 0 { time.Sleep(time.Duration(s.GetLockRetryDelayMS()) * time.Millisecond) continue } return nil, nil } } } return nil, errors.New("加锁失败") } //解锁 func (s *lockFactory) UnLock(ctx context.Context, lock *RLLock) (isUnLock bool, err error) { // 解锁 if lock == nil { return false, errors.New("lock参数为空") } //mutex 锁 mutexLock.Lock() defer mutexLock.Unlock() // 如果已经解锁了直接返回 if lock.IsUnlock { fmt.Printf("%s:已经解锁了", lock.KeyName) return true, nil } if lock.IsLive { if !lock.ChanIsNoIn { //这里写入 lock.RedisChan <- struct{}{} lock.ChanIsNoIn = true } } else { lock.UnlockTime = time.Now().UnixNano() / 1e6 lock.IsUnlock = true } conn := s.pool.Get() defer func() { err := conn.Close() if err != nil { fmt.Printf("关闭redis池失败: %s \n", err.Error()) } }() retry := s.GetUnLockRetryCount() for retry >= 0 { select { case <-ctx.Done(): fmt.Println("UnLock-执行结束") return false, ctx.Err() default: retry -= 1 // 删除对应的键---KeyName res, err := redis.Int64(luaScriptDelete.Do(conn, lock.KeyName, lock.RandomKey)) if err != nil { fmt.Printf("%s 解锁失败,报错信息:%+v", lock.KeyName, err.Error()) if retry != 0 { time.Sleep(time.Duration(s.GetUnLockRetryDelayMS()) * time.Millisecond) continue } return false, err } if res != 1 { fmt.Printf("%s 解锁失败,报错信息:%+v \n", lock.KeyName, res) return false, nil } fmt.Println("解锁成功") return true, nil } } return false, errors.New("解锁失败") } // 续命 func (s *lockFactory) RenewalLife(lock *RLLock, continuedTime int) { timer := time.NewTimer(time.Duration(continuedTime) * time.Millisecond) conn := s.pool.Get() if continuedTime < 0 { continuedTime = DefaultContinuedTime } defer func() { if !timer.Stop() { // <-timer.C失败直接走默认---往下接着走 select { case <-timer.C: default: } } err := conn.Close() if err != nil { fmt.Printf("关闭redis池失败: %s \n", err.Error()) } }() // todo 这里加个错误重试次数吧 for { if lock.IsUnlock { return } timer.Reset(time.Duration(continuedTime) * time.Millisecond) select { // 这里读出,让消息关闭 case <-lock.RedisChan: fmt.Print("keepAlive-closeChan \n") lock.IsUnlock = true lock.UnlockTime = time.Now().UnixNano() / 1e6 close(lock.RedisChan) return case <-timer.C: // 默认 500毫秒进行续命一次 fmt.Print("keepAlive-开始续命 \n") luaRes, err := luaScriptExpire.Do(conn, lock.KeyName, lock.KeyName, lock.RandomKey, lock.ContinuedTime) if err != nil { fmt.Printf("%s, 续命失败:%+v \n", lock.KeyName, err.Error()) continue } res, err := redis.Int64(luaRes, err) if res != 1 { fmt.Printf("%s 续命失败: %+v", lock.KeyName, res) lock.IsUnlock = true lock.UnlockTime = time.Now().UnixNano() / 1e6 close(lock.RedisChan) return } fmt.Println("续命成功") lock.ContinuedTimeMS = time.Now().UnixNano() / 1e6 } } }
fd5c4cf3228bf766a9a719d608405000c2578248
[ "Markdown", "Go Module", "Go" ]
5
Go Module
organizations-loops/RLLOCK
e947b970d2a10a6eb152a0884de0cd27447ddfc1
8660f78221a8f2ae3fc8979d77fbaa55e8729841
refs/heads/master
<file_sep># GameRun This is for my project <file_sep>/*<NAME> Spring 2018 Javascript code */ /*click event is on ending.html. date manipulation, mouseover and mouseout event is on index.html*/ //playing Ether&Dream City - Tear Of A Shadow in index.html var opening = new Audio('media/Tears.ogg'); //Ether - Coexistence - [Dubstep/Glitch] var scary = new Audio('media/etherCoexistence.ogg'); //in love with a ghost - flowers feat. nori var notscary = new Audio('media/flowers.ogg'); //Haru's Laugh var haha = new Audio('media/laugh.ogg'); var door = new Audio('media/door.mp3'); //in game.html //playing in love with a ghost - we've never met but, can we have a coffee or something coffee = new Audio('media/coffee.ogg'); coffee.addEventListener('ended', function() { this.currentTime = 0; this.play(); }, false); var player; var gender; function ask() { gender = prompt("Are you a girl or boy?"); switch(true) { case (gender == "girl"): gender = " Young lady"; break; case (gender == "boy"): gender = "Young man"; break; default: gender = "Friend"; } player = prompt(gender + ", your name?"); //document.getElementById("insertName").innerHTML = "" + player + ""; } function gameStart() { door.play(); alert("So " + player + " what do you want to do?"); window.location.href = "game.html"; window.resize(850, 750); } //it closes the window function exitGame() { alert("Please don't leave me."); self.close(); } //start not needed stuff var userName; function inputName() { userName = document.getElementById('name').value; document.getElementById('nameField').innerHTML = userName; } //end not needed stuff //from game.html to index.html function startover() { window.location.href = "index.html"; } /*all the models for my characters and parts helps it preload when using big images; so basically another excuse to add a loop*/ var pics = ["bedone.jpg","happyend.jpg", "raindrops.jpg", "rainglass.png", "rainphoto.jpg", "girl.png","boy.png", "yanHaru.png"]; //while loop and length to make a images go in front of each word "saving time" var picstuff = new Array(pics.length); var i = 0; while(i < pics.length) { picstuff[i] = new Image(); picstuff[i].src = "media/" + pics[i]; i++; } //moves along the array and once it gets to the choice, it will have a pop-up function moveFW() { var i = 0; script.shift(); if (i < script.length){ //the choice if (script[0] == "choices") { var yes = confirm("Will you stay? yes='ok' or no='cancel'"); if (yes === true) { coffee.pause(); notscary.play(); }else{ window.location.href = "ending.html"; scary.play(); } //end of choice }else{ document.getElementById("dboxDiv").innerHTML = script[0]; } } } var script = ["start", "<br>It was storming. You still remembered that day clearly. You and your friend Haru ran into his house from the pounding rain. It was your first time at his house. You've never been here, yet you could not help how familiar it felt.", "Haru<br>'That rain came out of nowhere, hunh?'", "<br><b>'Yeah.'</b>", "<br>Thunder rumbled and lightening flashed as his changed to a dark expression.", "<br>He locked the door.", "Haru<br>'Want to stay here Forever?'", "choices", "<br><b>'Yes I will.'<b>", "Haru<br> 'Wow...'", "Haru<br> 'I'm glad.'", "Haru<br> 'Now you can stay with me...'", "Haru<br><b><i>'Forever.'</i></b>", "<br>The clouds cleared as the sun shone through the opening.", "Haru<br> 'How about we go for a walk?'", "<br>The eerie mood was suddenly broken from that one statement.", "<br><b>'What did you mean about Forever anyways?'</b>", "<br>Haru shrugged.", "Haru<br> 'I guess to be edgy.'", "<br>You scoff at his response. The weird mood was in your head after all.", "<br><b>'I'm going home.'</b>", "<br>Well, at least you didn't die.", "<br><i>Good End</i>" ]; var be = [ "Haru: What?", "Thunder rumbles and lightening flashed. The room lit up for a second, but it got darker than before.", "Haru: No... you have no say in the matter.", "Haru: You played this game; Do nOT PlaY WiTh My heART", "You took a step back not knowing what to do", "and then (press screen)..."]; //for loop to display bad ending var counter = 0; function appendElement(id) { for (var i = 0; i < be.length; i++) { var newElement = document.createElement("P"); newElement.textContent = be[i]; document.querySelector("#badend"); document.querySelector(id).appendChild(newElement); newElement.setAttribute("id","myId"+counter); } counter++; }
91a114b54f6576708f0651520270634c00a749d0
[ "Markdown", "JavaScript" ]
2
Markdown
AlexisSS707/GameRun
6867a2db43e8ca68009f774d9bc871c98de3a907
dcd40ecc755a4173a31fbaa91ffcaa998ce5310f
refs/heads/master
<file_sep>class TransactionModel { name = 'Transaction'; props = { description: 'string', amount: 'double', createdAt: 'datetime', budget: '#Budget', }; } export default TransactionModel; <file_sep>import React, { useContext, useRef } from 'react'; import { Button, StyleSheet, ToastAndroid, View } from 'react-native'; import FormItem, { FORM_ITEM_TYPE } from '../components/FormItem'; import { RouterContext } from '../components/Router'; import DBContext from '../context/DBContext'; import useForm from '../hooks/useForm'; function AddBudgetScreen() { const { db } = useContext(DBContext); const { changePage } = useContext(RouterContext); const [values, onChange] = useForm({ name: '', allocated: '', frequency: 'D', createdAt: new Date(), }); function addBudget() { try { db.Budget.insert({ ...values, createdAt: new Date(values.createdAt), allocated: +values.allocated, transactions: [], }); ToastAndroid.show('Budget created', ToastAndroid.SHORT); changePage('/'); } catch (err) { ToastAndroid.show(err.message, ToastAndroid.SHORT); } } const allocatedInputRef = useRef(); return ( <View style={[styles.container]}> <View style={[styles.formItemsContainer]}> <FormItem label="Name" value={values.name} onChange={onChange.name} autoFocus onSubmitEditing={() => allocatedInputRef.current.focus()} /> <FormItem type={FORM_ITEM_TYPE.NUMBER} label="Budget Allocated" value={values.allocated} onChange={onChange.allocated} ref={allocatedInputRef} /> <FormItem type={FORM_ITEM_TYPE.PICKER} label="Frequency" value={values.frequency} onChange={onChange.frequency} options={[ { label: 'Daily', value: 'D' }, { label: 'Monthly', value: 'M', }, ]} /> <FormItem type={FORM_ITEM_TYPE.DATE} label="Start Date:" value={values.createdAt} onChange={onChange.createdAt} /> </View> <View style={[styles.buttonContainer]}> <Button title="ADD BUDGET" onPress={addBudget} /> </View> </View> ); } const styles = StyleSheet.create({ container: { flex: 1, flexDirection: 'column', }, formItemsContainer: { flexDirection: 'column', flex: 1, }, buttonContainer: { margin: 10, }, }); export default AddBudgetScreen; <file_sep>class BudgetModel { name = 'Budget'; props = { name: 'string', frequency: 'string', allocated: 'double', transactions: '[]#Transaction', createdAt: 'datetime', }; } export default BudgetModel; <file_sep>import React, { useContext, useRef } from 'react'; import { DrawerLayoutAndroid, Keyboard, StyleSheet, Text, TouchableOpacity, View, } from 'react-native'; import packageJson from '../../package.json'; import { STYLES } from '../global-styles'; import { RouterContext } from './Router'; function Drawer({ position, children }) { const { changePage } = useContext(RouterContext); const drawerRef = useRef(); function handleChangePage(page, state) { drawerRef.current.closeDrawer(); changePage(page, state); } // function handleBackPress() { // drawerRef.current.closeDrawer(); // return true; // } return ( <DrawerLayoutAndroid ref={drawerRef} drawerBackgroundColor="transparent" drawerWidth={150} drawerPosition={DrawerLayoutAndroid.positions[position]} onDrawerOpen={() => { Keyboard.dismiss(); // BackHandler.addEventListener('hardwareBackPress', handleBackPress); }} onDrawerClose={() => { // BackHandler.removeEventListener('hardwareBackPress', handleBackPress); }} renderNavigationView={() => { return ( <View style={[styles.drawerContainer]}> <TouchableOpacity activeOpacity={0.95} style={[styles.drawerButton, { backgroundColor: '#7ace68' }]} onPress={() => { handleChangePage('/income'); }} > <Text style={[styles.drawerButtonText]}>INCOME</Text> </TouchableOpacity> <TouchableOpacity activeOpacity={0.95} style={[styles.drawerButton, { backgroundColor: '#5e9bea' }]} onPress={() => { handleChangePage('/add-budget'); }} > <Text style={[styles.drawerButtonText]}>ADD BUDGET</Text> </TouchableOpacity> <TouchableOpacity activeOpacity={0.95} style={[styles.drawerButton, { backgroundColor: '#b3b3b3' }]} onPress={() => { handleChangePage('/transactions', { budget: null }); }} > <Text style={[styles.drawerButtonText]}>ALL TRANSACTIONS</Text> </TouchableOpacity> <TouchableOpacity activeOpacity={0.95} underlayColor="white" style={[styles.drawerButton, { backgroundColor: '#5e9bea' }]} onPress={() => { handleChangePage('/'); }} > <Text style={[styles.drawerButtonText]}>DASHBOARD</Text> </TouchableOpacity> <Text style={{ position: 'absolute', bottom: 0, right: 0, color: 'white', }} > v{packageJson.version} </Text> </View> ); }} > {children} </DrawerLayoutAndroid> ); } const styles = StyleSheet.create({ drawerContainer: { flex: 1, }, drawerButton: { flex: 1, padding: 10, justifyContent: 'center', alignItems: 'center', }, drawerButtonText: { ...STYLES.TEXT, textAlign: 'center', color: 'white', }, }); export default Drawer; <file_sep>import React, { useContext, useRef } from 'react'; import { Button, StyleSheet, ToastAndroid, View } from 'react-native'; import FormItem, { FORM_ITEM_TYPE } from '../components/FormItem'; import { RouterContext } from '../components/Router'; import DBContext from '../context/DBContext'; import useForm from '../hooks/useForm'; function AddTransactionScreen() { const { changePage } = useContext(RouterContext); const { db, budgets } = useContext(DBContext); const { pageState } = useContext(RouterContext); const [values, onChange] = useForm({ description: '', amount: '', budget: !!pageState.budget ? pageState.budget : budgets.length > 0 ? budgets[0].id : null, }); function addTransaction() { try { db.Transaction.insert({ ...values, amount: +values.amount, createdAt: new Date(), }); ToastAndroid.show('Transaction created', ToastAndroid.SHORT); changePage('/'); } catch (err) { ToastAndroid.show(err.message, ToastAndroid.SHORT); } } const descriptionInputRef = useRef(); return ( <View style={[styles.container]}> <View style={[styles.formItemsContainer]}> <FormItem type={FORM_ITEM_TYPE.PICKER} label="Allocate to" value={values.budget} onChange={onChange.budget} options={budgets.map(budget => ({ value: budget.id, label: budget.name, }))} /> <FormItem label="Amount" value={values.amount} onChange={onChange.amount} type={FORM_ITEM_TYPE.NUMBER} autoFocus={!!pageState.budget} onSubmitEditing={() => { descriptionInputRef.current.focus(); }} /> <FormItem label="Description" value={values.description} onChange={onChange.description} ref={descriptionInputRef} onSubmitEditing={addTransaction} /> </View> <View style={[styles.buttonContainer]}> <Button title="ADD TRANSACTION" onPress={addTransaction} /> </View> </View> ); } const styles = StyleSheet.create({ container: { flex: 1, flexDirection: 'column', }, formItemsContainer: { flexDirection: 'column', flex: 1, }, buttonContainer: { margin: 10, }, }); export default AddTransactionScreen; <file_sep>import React from 'react'; import { StyleSheet, Text, View } from 'react-native'; import { STYLES } from '../global-styles'; import coloredNumber from '../utils/coloredNumber'; import commafy from '../utils/commafy'; function Statistic({ label, value, extra, style }) { return ( <View style={[styles.statisticContainer, style]}> <View style={[styles.statisticCell]}> <Text style={[styles.statisticText]}>{label}</Text> </View> <View style={[styles.statisticCell]}> <Text style={[styles.statistic, coloredNumber(value)]}> {value > 0 && '+'} {commafy(value)} {extra && ` (${extra})`} </Text> </View> </View> ); } const styles = StyleSheet.create({ statisticContainer: { flexDirection: 'row', // borderBottomColor: 'black', // borderBottomWidth: StyleSheet.hairlineWidth, }, statisticCell: { padding: 5, flex: 1, }, statisticText: { ...STYLES.TEXT, }, statistic: { ...STYLES.TEXT, textAlign: 'right', }, }); export default Statistic; <file_sep>import React, { useContext } from 'react'; import { ScrollView } from 'react-native'; import BudgetItem from '../components/BudgetItem'; import Statistic from '../components/Statistic'; import DBContext from '../context/DBContext'; function HomeScreen() { const { budgets, budgetsMeta, estimateExpenses, totalExpenses, income, } = useContext(DBContext); return ( <ScrollView> {[...budgets] .sort((a, b) => { if (a.frequency === b.frequency) return a.name < b.name ? -1 : a.name > b.name ? 1 : 0; if (a.frequency === 'D') return -1; if (b.frequency === 'D') return 1; return 0; }) .map(budget => ( <BudgetItem key={budget.id} {...budget} {...budgetsMeta[budget.id]} /> ))} <Statistic style={{ marginTop: !budgets.length ? 0 : 20 }} label="Monthly Expenses:" value={estimateExpenses} /> <Statistic label="Current Expenses:" value={totalExpenses} /> {income && ( <Statistic label="Monthly Savings:" value={income.amount + estimateExpenses} /> )} </ScrollView> ); } export default HomeScreen; <file_sep># Tesya Mobile <file_sep>export const STYLES = { TEXT: { fontSize: 18, color: 'black', }, INPUT: { borderBottomWidth: 1, borderBottomColor: 'black', }, }; <file_sep>import { format } from 'date-fns'; import React, { Fragment, useContext, useMemo } from 'react'; import { Alert, ScrollView, StyleSheet, Text, ToastAndroid, TouchableOpacity, View, } from 'react-native'; import { RouterContext } from '../components/Router'; import DBContext from '../context/DBContext'; import { STYLES } from '../global-styles'; import coloredNumber from '../utils/coloredNumber'; import commafy from '../utils/commafy'; function TransactionsScreen() { const { db, budgetsMeta, transactions } = useContext(DBContext); const { pageState } = useContext(RouterContext); const transactionsMap = useMemo(() => { const budgetTransactions = !pageState.budget ? transactions : budgetsMeta[pageState.budget].transactions; const transactionsMap = {}; for (const transaction of budgetTransactions) { const date = new Date(transaction.createdAt); const transactionDate = new Date( date.getFullYear(), date.getMonth(), date.getDate() ); const dateLabel = format(transactionDate, 'ddd | MMM D, YYYY'); if (!transactionsMap[transactionDate.getTime()]) { transactionsMap[transactionDate.getTime()] = { label: dateLabel, transactions: [], }; } transactionsMap[transactionDate.getTime()].transactions.push(transaction); } return transactionsMap; }, [budgetsMeta, transactions]); function handleDeleteTransaction(transaction) { Alert.alert( 'Delete this transaction?', `Budget: ${ budgetsMeta[transaction.budget_id || transaction.budget].budget.name }\nDescription: ${transaction.description || '—'}\nAmount: ${ transaction.amount }`, [ { text: 'OK', onPress: () => { try { db.Transaction.remove(transaction.id); ToastAndroid.show('Transaction deleted', ToastAndroid.SHORT); } catch (err) { ToastAndroid.show(err.message, ToastAndroid.SHORT); } }, }, ] ); } return ( <ScrollView contentContainerStyle={[ Object.keys(transactionsMap).length === 0 && styles.container, ]} > {Object.keys(transactionsMap).length === 0 && ( <Text style={[STYLES.TEXT]}> No transactions{' '} {pageState.budget && `in ${budgetsMeta[pageState.budget].budget.name}`} </Text> )} {Object.keys(transactionsMap).length > 0 && ( <View style={[styles.cell, { marginBottom: 20 }]}> <Text style={[STYLES.TEXT, { fontWeight: 'bold' }]}> Budget:{' '} {budgetsMeta[pageState.budget] ? budgetsMeta[pageState.budget].budget.name : 'All'} </Text> </View> )} {Object.keys(transactionsMap) .sort() .reverse() .map(key => { return ( <Fragment key={key}> <View style={[ { alignItems: 'center', justifyContent: 'center', padding: 10, }, ]} > <Text style={[STYLES.TEXT, { fontWeight: 'bold' }]}> {transactionsMap[key].label} </Text> </View> {[...transactionsMap[key].transactions] .sort((a, b) => new Date(b.createdAt) - new Date(a.createdAt)) .map(transaction => { const budget = budgetsMeta[transaction.budget_id || transaction.budget] .budget; return ( <TouchableOpacity style={[styles.transactionContainer]} key={transaction.id} onPress={() => handleDeleteTransaction(transaction)} > {!pageState.budget && ( <View style={[styles.cell, { flex: 2 }]}> <Text style={[styles.transactionText]}> {budget.name} </Text> </View> )} <View style={[styles.cell, { flex: 2 }]}> <Text style={[styles.transactionText]}> {transaction.description || '—'} </Text> </View> <View style={[styles.cell]}> <Text style={[ styles.transactionText, { textAlign: 'right' }, coloredNumber(-transaction.amount), ]} > {commafy(-transaction.amount)} </Text> </View> </TouchableOpacity> ); })} </Fragment> ); })} </ScrollView> ); } const styles = StyleSheet.create({ container: { flex: 1, alignItems: 'center', justifyContent: 'center', }, transactionHeaderLabelContainer: { alignItems: 'center', justifyContent: 'center', padding: 10, marginTop: 10, }, transactionContainer: { flexDirection: 'row', borderBottomColor: 'black', borderBottomWidth: StyleSheet.hairlineWidth, }, cell: { flex: 1, padding: 10, }, transactionText: { ...STYLES.TEXT, fontSize: 14, }, }); export default TransactionsScreen; <file_sep>class IncomeModel { name = 'Income'; props = { amount: 'double', }; } export default IncomeModel; <file_sep>import React, { useContext } from 'react'; import { Button, StyleSheet, ToastAndroid, View } from 'react-native'; import FormItem, { FORM_ITEM_TYPE } from '../components/FormItem'; import { RouterContext } from '../components/Router'; import DBContext from '../context/DBContext'; import useForm from '../hooks/useForm'; function IncomeScreen() { const { db, income } = useContext(DBContext); const { changePage } = useContext(RouterContext); const [values, onChange] = useForm({ amount: String(income.amount), addAmount: '', }); function updateIncome() { try { db.Income.update(income.id, { amount: +values.amount, }); ToastAndroid.show('Income updated', ToastAndroid.SHORT); changePage('/'); } catch (err) { ToastAndroid.show(err.message, ToastAndroid.SHORT); } } return ( <View style={[styles.container]}> <View style={[styles.formItemsContainer]}> <FormItem type={FORM_ITEM_TYPE.NUMBER} label="Income" value={values.amount} onChange={onChange.amount} /> </View> <View style={[styles.buttonContainer]}> <Button title="UPDATE" onPress={updateIncome} /> </View> </View> ); } const styles = StyleSheet.create({ container: { flex: 1, flexDirection: 'column', }, formItemsContainer: { flexDirection: 'column', }, buttonContainer: { margin: 10, }, }); export default IncomeScreen;
501006aa07fbbc6fb9813d8421e51661155ab6d9
[ "JavaScript", "Markdown" ]
12
JavaScript
tadeolinco/tesyamobile
1493bf5c949aba19152585e1d5b80c017fc8e9f7
06d94795259cb06bd367864756e1782472764c7a
refs/heads/master
<file_sep>--- title: "MMM_tweets" author: "<NAME>" date: "2/29/2020" output: html_document --- ```{r setup, include=FALSE} knitr::opts_chunk$set(echo = TRUE) ``` ```{r needed libraries} library(rtweet) library(tidyverse) library(tidytext) library(wordcloud) library(wordcloud2) library(lubridate) ``` first load the tweets ```{r} MMM_2020<- search_tweets( "#2020MMM", n = 18000, include_rts = FALSE) Sys.time() MMM_2020_March02_6_30_am<- search_tweets( "#2020MMM", n = 18000, include_rts = FALSE) MMM_2020_March02_3_30_pm<- search_tweets( "#2020MMM", n = 18000, include_rts = FALSE) MMM_2020_March03_12_15_pm<- search_tweets( "#2020MMM", n = 18000, include_rts = FALSE) MMM_2020_March04_11_30_am<- search_tweets( "#2020MMM", n = 18000, include_rts = FALSE) MMM_2020_March04_11_30_am<- search_tweets( "#2020MMM", n = 18000, include_rts = FALSE) MMM_2020_March04_8_45_pm<- search_tweets( "#2020MMM", n = 18000, include_rts = FALSE) MMM_2020_March05_6_10_pm<- search_tweets( "#2020MMM", n = 18000, include_rts = FALSE) MMM_2020_March06_1_30_pm<- search_tweets( "#2020MMM", n = 18000, include_rts = FALSE) current_time <- Sys.time() ``` now i loose the first 29 from set1 and Export data ```{r} write_as_csv(MMM_2020, "2020-03-01_9AM_tweets") write_as_csv(MMM_2020_b_March03_5_50_pm, "2020-03-01_5_50pm_tweets") write_as_csv(MMM_2020_March02_6_30_am, "2020-03-02_6_30am_tweets") write_as_csv(MMM_2020_March02_3_30_pm, "2020-03-02_3_30pm_tweets") write_as_csv(MMM_2020_March03_12_15_pm, "2020-03-03_12_15pm_tweets") write_as_csv(MMM_2020_March04_11_30_am,"2020-03-04_11_30am_tweets" ) write_as_csv(MMM_2020_March04_8_45_pm,"2020-03-04_8_45pm_tweets" ) write_as_csv(MMM_2020_March05_6_10_pm, "2020-03-05_6_10pm_tweets") write_as_csv(MMM_2020_March06_1_30_pm, "2020-03-06_1_30pm_tweets") ``` Testing adding dfs together ```{r} first <- read_csv("2020-03-01_9AM_tweets.csv") second <- read_csv("2020-03-01_5_50pm_tweets.csv") third <- read_csv("2020-03-02_6_30am_tweets.csv") fourth <- read_csv("2020-03-02_3_30pm_tweets.csv") fifth <- read_csv("2020-03-03_12_15pm_tweets.csv") sixth <-read_csv("2020-03-04_11_30am_tweets.csv") seventh <- read_csv("2020-03-04_8_45pm_tweets.csv") eight <- read_csv("2020-03-05_6_10pm_tweets.csv") ninth <- read_csv("2020-03-06_1_30pm_tweets.csv") all_tweets <- rbind(first, second, third, fourth, fifth, sixth, seventh, eight, ninth) %>% distinct(text, .keep_all = TRUE) #total <- rbind(a,b) #totalgrouped <- total %>% distinct(text, .keep_all = TRUE) #MMM_2020 <- totalgrouped ``` Basic graphs ```{r} ts_plot(all_tweets, "2 hours") + ggplot2::theme_minimal() + ggplot2::theme(plot.title = ggplot2::element_text(face = "bold")) + ggplot2::labs( x = NULL, y = NULL, title = "Frequency of #2020MMM Twitter statuses", subtitle = paste("as of", current_time ), caption = "\nSource: Data collected from Twitter's REST API via rtweet") ggplot(all_tweets, aes(created_at))+ geom_density(alpha=.75, fill="#4cda76")+ # fill with main SAC logo blue ggtitle("#2020MMM Tweets")+ ylab("Density of tweets")+ xlab("Time") ggplot(all_tweets, aes(created_at))+ geom_density(alpha=.75, fill="#4cda76") + labs(title = "Frequency of #2020MMM Twitter statuses", subtitle = paste("as of", current_time ), caption = "\nSource: Data collected from Twitter's REST API via rtweet") ``` anaylze data ```{r} all_tweets %>% count(screen_name, sort=T) all_tweets %>% group_by(screen_name) %>% summarise(rt = sum(retweet_count)) %>% arrange(-rt) MMM_2020 %>% arrange(-favorite_count) %>% select(favorite_count) MMM_2020 %>% group_by(screen_name) %>% count(sort=T) MMM_2020 %>% group_by(screen_name) %>% filter(n() > 5) %>% ggplot(aes(x= screen_name)) + geom_bar() + coord_flip() a <- all_tweets %>% group_by(screen_name) %>% add_tally() %>% filter(n() > 5) %>% ungroup() a %>% mutate(screen_name = fct_reorder(screen_name,n)) %>% ggplot(aes(x= screen_name, fill=screen_name)) + geom_bar() + coord_flip() + labs(title = "number of tweets that mention #2020MMM", subtitle = paste("as of", current_time ), x= "screen name") + theme(legend.position = "none") truth_background <- png::readPNG("LoveMMM.png") annotation_custom(rasterGrob(truth_background, width = unit(1,"npc"), height = unit(1,"npc")), -Inf, Inf, -Inf, Inf) library(grid) a %>% mutate(screen_name = fct_reorder(screen_name,n)) %>% ggplot(aes(x= screen_name, fill=screen_name)) + annotation_custom(rasterGrob(truth_background, width = unit(1,"npc"), height = unit(1,"npc")), -Inf, Inf, -Inf, Inf) + geom_bar() + coord_flip() + labs(title = "number of tweets by username that mention #2020MMM", subtitle = paste("as of", current_time ), x= "screen name", caption = "background img from: https://libguides.asu.edu/MarchMammalMadness") + theme(legend.position = "none") all_tweets %>% mutate(day = as_date(created_at)) %>% count(day, sort=T) ``` wordcloud note: if there is a _ not showing up, which exmapling why mammls_suck isn't there ```{r} MMM_table <- all_tweets %>% unnest_tokens(word, text) MMM_table <- MMM_table %>% anti_join(stop_words) MMM_table <- MMM_table %>% count(word, sort = T) MMM_table_edited <- MMM_table %>% filter(!word %in% c("2020mmm", "t.co", "https")) wordcloud2::wordcloud2(MMM_table_edited, size = .4) #MMM_table_edited <- MMM_table %>% filter(!word %in% c("2020mmm", "t.co", "https", "march", "mammal", "madness")) letterCloud(MMM_table_edited, word = "M", size=.4) filt <- MMM_table_edited %>% filter(n >10) figPath <- "/Users/mkissel/Documents/Code/R_projects/2020_MMM/image.png" wordcloud2(demoFreq, figPath = figPath, size = 3,color = "green", backgroundColor = "black") ``` more text ```{r} team <- MMM_2020 %>% filter(str_detect(text, "team")) filter(str_detect(text, "panda")) %>% pull(text) #lets see if i can pull out teams? or remove screennames from text teams <- all_tweets %>% filter(str_detect(text, "team")) MMM_table_edited ``` map data (note that most tweets don't have loc data) ```{r} MMM_2020 %>% count(country_code) rt1 <- lat_lng(all_tweets) ``` map itself, version 1 ```{r} par(mar = c(0, 0, 0, 0)) maps::map("world", lwd = .25) with(rt1, points(lng, lat, pch = 20, cex = .75, col = rgb(0, .3, .7, .75))) ``` map, version 2 w/ leaflet ```{r} library(leaflet) leaflet() %>% addTiles() %>% setView(lat = 50.85045, lng = 4.34878, zoom=0) %>% addMarkers(~lng, ~lat, data = rt1, popup = ~as.character(text), label = ~as.character(screen_name)) ``` stream data: example from https://rtweet.info/articles/stream.html#stream_tweets ```{r} q <- "2020MMM" library(tidygraph) ## Stream time in seconds so for one minute set timeout = 60 ## For larger chunks of time, I recommend multiplying 60 by the number ## of desired minutes. This method scales up to hours as well ## (x * 60 = x mins, x * 60 * 60 = x hours) ## Stream for 30 minutes streamtime <- 30 * 60 ## Stream for 30 minutes streamtime <- 30 * 1 filename <- "rtelect.json" rt <- stream_tweets("2020MMM", timeout = 90, file_name = filename) # do or 9 seconds library(rjson) result <- fromJSON(file = "rtelect.json") ``` network? https://rud.is/books/21-recipes/visualizing-a-graph-of-retweet-relationships.html make sure it is directed?....i assume it defaults for twitterGrpah but bit sure about igraph? might need to specify I THINK>..... other things: think about looking at reciprocity for this netowkr (The proportion of reciprocated ties). maybe compare diffeent groups etc? and transivity ```{r} library(tidygraph) library(rtweet) library(igraph) library(hrbrthemes) library(ggraph) library(tidyverse) filter(tidy_tweets) %>% select(screen_name, mentions_screen_name) %>% unnest(mentions_screen_name) %>% filter(!is.na(mentions_screen_name)) %>% graph_from_data_frame() -> rt_g ggplot(data_frame(y=degree_distribution(rt_g), x=1:length(y))) + geom_segment(aes(x, y, xend=x, yend=0), color="slateblue") + scale_y_continuous(expand=c(0,0), trans="sqrt") + labs(x="Degree", y="Density (sqrt scale)", title="#rstats Retweet Degree Distribution") + theme_ipsum_rc(grid="Y", axis="x") #add labels for nodes that have a degree of 20 or more V(rt_g)$node_label <- unname(ifelse(degree(rt_g)[V(rt_g)] > 5, names(V(rt_g)), "")) V(rt_g)$node_size <- unname(ifelse(degree(rt_g)[V(rt_g)] > 5, degree(rt_g), 0)) #stnght? V(rt_g)$node_label <- unname(ifelse(strength(rt_g)[V(rt_g)] > 5, names(V(rt_g)), "")) # creats node lable if sregn >5 V(rt_g)$node_size <- unname(ifelse(strength(rt_g)[V(rt_g)] > 5, degree(rt_g), 0)) rt_g %>% ggraph(layout = "fr") + geom_edge_link() + geom_node_point(color = "darkslategray4", size = 5) + geom_node_label(aes(label=node_label, size=node_size), label.size=0, fill="#ffffff66", segment.colour="springgreen", color="slateblue", repel=TRUE, fontface="bold") + ggtitle(expression(paste("Who talks to who in", italic("March Mammal Madness")))) + theme_void() ``` Other network things with igraph ```{r} clp <- cluster_label_prop(rt_g) plot(clp, rt_g) plot(clp, rt_g, vertex.label=V(rt_g)$node_label) #after using above to set node_label plot(clp, rt_g, vertex.label=V(rt_g)$node_label, vertex.size=V(rt_g)$node_size ) #not good #hubs hs <- hub_score(rt_g, weights=NA)$vector as <- authority_score(rt_g, weights=NA)$vector par(mfrow=c(1,2)) plot(rt_g, vertex.size=hs*50, main="Hubs") plot(rt_g, vertex.size=as*30, main="Authorities") par(mfrow=c(1,2)) plot(rt_g, vertex.size=hs*50, main="Hubs", vertex.label=V(rt_g)$node_label) plot(rt_g, vertex.size=as*30, main="Authorities", vertex.label=V(rt_g)$node_label) ``` #below shld work!!!!! ```{r} tidy_tweets <- all_tweets %>% select(screen_name, mentions_screen_name) %>% mutate( hashtags = gsub("\\[|\\]|'", "", mentions_screen_name) ) %>% tidyr::separate_rows(hashtags, sep = ", ") %>% tidyr::nest(hashtags = c(hashtags)) tidy_tweets <- all_tweets %>% select(screen_name, mentions_screen_name) %>% tidyr::separate_rows(mentions_screen_name, sep = " ") %>% tidyr::nest(mentions_screen_name = c(mentions_screen_name)) tidy_tweets$mentions_screen_name <- tidy_tweets$mentions_screen_name %>% purrr::map(unlist) %>% purrr::map(unname) tidy_tweets %>% gt_edges(screen_name, mentions_screen_name) %>% gt_nodes() %>% gt_collect() -> gt nodes <- gt$nodes %>% mutate( id = nodes, label = nodes, size = n, color = "#1967be" ) edges <- gt$edges %>% mutate( id = 1:n() ) sigmajs() %>% sg_force_start() %>% sg_nodes(nodes, id, label, size, color) %>% sg_edges(edges, id, source, target) %>% sg_force_stop(10000) sigmajs() %>% sg_force_start() %>% sg_nodes(nodes, id, label, size, color) %>% sg_edges(edges, id, source, target) %>% sg_force_stop(10000) %>% sg_drag_nodes() %>% sg_cluster() g %>% gt_edges(screen_name, mentions_screen_name) %>% gt_nodes(meta = TRUE) %>% gt_collect() -> graph ``` Below here is scratch ```{r} install.packages("graphTweets") install.packages("sigmajs") library(graphTweets) library(sigmajs) #lest stats by adding te dfs togehte tthat eep the ino in list forms x <- rbind(MMM_2020_b_March03_5_50_pm, MMM_2020_March02_6_30_am, MMM_2020_March02_3_30_pm, MMM_2020_March03_12_15_pm, MMM_2020_March04_11_30_am) x %>% distinct(text, .keep_all = TRUE) x %>% gt_edges(text, screen_name, status_id) %>% gt_graph() %>% plot() #bad ###### MMM_2020 %>% gt_edges(screen_name, mentions_screen_name) %>% gt_nodes(meta = TRUE) %>% gt_collect() -> graph #smaller MMM_2020_small <- MMM_2020 %>% filter(!is.na(mentions_screen_name)) %>% gt_edges(screen_name, mentions_screen_name) %>% gt_nodes(meta = TRUE) %>% gt_collect() -> graph MMM_2020 %>% gt_edges(screen_name, mentions_screen_name) %>% gt_nodes() %>% gt_collect() -> gt nodes <- gt$nodes %>% mutate( id = nodes, label = nodes, size = n, color = "#1967be" ) edges <- gt$edges %>% mutate( id = 1:n() ) sigmajs() %>% sg_force_start() %>% sg_nodes(nodes, id, label, size, color) %>% sg_edges(edges, id, source, target) %>% sg_force_stop(10000) sigmajs() %>% sg_force_start() %>% sg_nodes(nodes, id, label, size, color) %>% sg_edges(edges, id, source, target) %>% sg_force_stop(10000) %>% sg_drag_nodes() %>% sg_cluster() #########################################3 #try various things fomr http://sigmajs.john-coene.com/articles/cluster.html etc # MMM_2020 %>% filter(!is.na(mentions_screen_name)) %>% gt_edges(screen_name, mentions_screen_name) %>% gt_nodes() %>% gt_collect() -> gt ####################3 net <- all_tweets %>% gt_edges(screen_name, hashtags) %>% gt_nodes() %>% gt_collect() edges <- net$edges nodes <- net$nodes edges$id <- seq(1, nrow(edges)) nodes$id <- nodes$nodes nodes$label <- nodes$nodes nodes$size <- nodes$n nodes$color <- ifelse(nodes$type == "user", "#0084b4", "#1dcaff") sigmajs() %>% sg_force_start() %>% sg_nodes(nodes, id, label, size, color) %>% sg_edges(edges, id, source, target) %>% sg_force_stop(10000) #to deal with multple maybe this will work net <- MMM_2020_b_March03_5_50_pm %>% gt_co_edges(mentions_screen_name) %>% gt_nodes() %>% gt_collect() c(edges, nodes) %<-% net edges <- edges %>% mutate(id = 1:n()) nodes <- nodes %>% mutate( id = nodes, label = id, size = n ) sigmajs() %>% sg_nodes(nodes, id, label, size) %>% sg_edges(edges, id, source, target) %>% sg_cluster( colors = c( "#0084b4", "#00aced", "#1dcaff", "#c0deed" ) ) %>% sg_layout(layout = igraph::layout.fruchterman.reingold) %>% sg_neighbours() %>% sg_settings( maxNodeSize = 3, defaultEdgeColor = "#a3a3a3", edgeColor = "default" ) #ok, above works but aisl on all_tweets. i think tis is becuase, all_tweets has the mentons_scren ame as charte not as a list...can weix or is it fucked #also check if that iw whyother lok weird #update it is! so can i read them back in as a list? #OR keep what i have and bind togehter to avoit raeding in #or fix all_tweet #or we can just do it by day? i wonder how many twett for each battle day? w <- all_tweets %>% as.list(mentions_screen_name) ``` ```{r} library(tidygraph) library(rtweet) library(igraph) library(hrbrthemes) library(ggraph) library(tidyverse) filter(MMM_2020, retweet_count > 0) %>% select(screen_name, mentions_screen_name) %>% unnest(mentions_screen_name) %>% filter(!is.na(mentions_screen_name)) %>% graph_from_data_frame() -> rt_g ggplot(data_frame(y=degree_distribution(rt_g), x=1:length(y))) + geom_segment(aes(x, y, xend=x, yend=0), color="slateblue") + scale_y_continuous(expand=c(0,0), trans="sqrt") + labs(x="Degree", y="Density (sqrt scale)", title="#rstats Retweet Degree Distribution") + theme_ipsum_rc(grid="Y", axis="x") #add labels for nodes that have a degree of 20 or more V(rt_g)$node_label <- unname(ifelse(degree(rt_g)[V(rt_g)] > 20, names(V(rt_g)), "")) V(rt_g)$node_size <- unname(ifelse(degree(rt_g)[V(rt_g)] > 20, degree(rt_g), 0)) #strenght? V(rt_g)$node_label <- unname(ifelse(strength(rt_g)[V(rt_g)] > 20, names(V(rt_g)), "")) V(rt_g)$node_size <- unname(ifelse(strength(rt_g)[V(rt_g)] > 20, degree(rt_g), 0)) ggraph(rt_g, layout = 'linear', circular = TRUE) + geom_edge_arc(edge_width=0.125, aes(alpha=..index..)) + geom_node_label(aes(label=node_label, size=node_size), label.size=0, fill="#ffffff66", segment.colour="springgreen", color="slateblue", repel=TRUE, family=font_rc, fontface="bold") + coord_fixed() + scale_size_area(trans="sqrt") + labs(title="Retweet Relationships", subtitle="Most retweeted screen names labeled. Darkers edges == more retweets. Node size == larger degree") + theme_graph(base_family=font_rc) + theme(legend.position="none") rt_g %>% ggraph(layout = "fr") + geom_edge_link() + geom_node_point(color = "darkslategray4", size = 5) + geom_node_label(aes(label=node_label, size=node_size), label.size=0, fill="#ffffff66", segment.colour="springgreen", color="slateblue", repel=TRUE, family=font_rc, fontface="bold") + ggtitle(expression(paste("Who talks to who in", italic("March Mammal Madness")))) + theme_void() # #deal with names? filter(all_tweets, retweet_count > 0) %>% select(screen_name, mentions_screen_name) %>% unnest(mentions_screen_name) %>% filter(!is.na(mentions_screen_name)) %>% graph_from_data_frame() -> rt_g V(rt_g)$label <- ifelse( strength(rt_g)>=5, V(rt_g)$name, NA ) # this creates the node label and gives a name is strneght is above 5 par(mar=c(0,0,0,0)); plot(rt_g) #other visal #http://pablobarbera.com/big-data-upf/html/02a-networks-intro-visualization.html plot(rt_g) plot(rt_g, vertex.color = "grey", # change color of nodes vertex.label.color = "black", # change color of labels vertex.label.cex = .75, # change size of labels to 75% of original size edge.curved=.25, # add a 25% curve to the edges edge.color="grey20") # change edge color to grey V(rt_g)$size <- strength(rt_g) par(mar=c(0,0,0,0)); plot(rt_g) #log V(rt_g)$size <- log(strength(rt_g)) * 4 + 3 par(mar=c(0,0,0,0)); plot(rt_g) #circle V(rt_g)$label <- ifelse( strength(rt_g)>=2, V(rt_g)$name, NA ) par(mar=c(0,0,0,0)) plot(rt_g, layout=layout_in_circle, main="Circle") V(rt_g)$label <- ifelse( degree(rt_g)>=20, V(rt_g)$name, NA ) par(mar=c(0,0,0,0)) plot(rt_g, layout=layout_in_circle, main="Circle") #The most popular layouts are force-directed. These algorithms, such as Fruchterman-Reingold, try to position the nodes so that the edges have similar length and there are as few crossing edges as possible. The idea is to generate “clean” layouts, where nodes that are closer to each other share more connections in common that those that are located further apart. Note that this is a non-deterministic algorithm: choosing a different seed will generate different layouts. #force-directed par(mfrow=c(1,2)) set.seed(777) fr <- layout_with_fr(rt_g, niter=1000) par(mar=c(0,0,0,0)); plot(rt_g, layout=fr) set.seed(666) fr <- layout_with_fr(rt_g, niter=1000) par(mar=c(0,0,0,0)); plot(rt_g, layout=fr) #more #https://juliasilge.com/blog/life-changing-magic/ rt_g %>% ggraph(layout = "fr") + geom_edge_link(aes(edge_alpha = n, edge_width = n)) + geom_node_point(color = "darkslategray4", size = 5) + geom_node_text(aes(label = name), vjust = 1.8) + ggtitle(expression(paste("Word Network in Jane Austen's ", italic("Pride and Prejudice")))) + theme_void() #blah for above filter(all_tweets, retweet_count > 0) %>% select(screen_name, mentions_screen_name) %>% unnest(mentions_screen_name) %>% filter(!is.na(mentions_screen_name)) %>% pivot_longer(cols = mentions_screen_name, names_to = "mentions") ``` <file_sep>tidy_tweets <- all_tweets %>% select(screen_name, mentions_screen_name) %>% mutate( hashtags = gsub("\\[|\\]|'", "", mentions_screen_name) ) %>% tidyr::separate_rows(hashtags, sep = ", ") %>% tidyr::nest(hashtags = c(hashtags)) tidy_tweets <- all_tweets %>% select(screen_name, mentions_screen_name) %>% tidyr::separate_rows(mentions_screen_name, sep = " ") %>% tidyr::nest(mentions_screen_name = c(mentions_screen_name)) tidy_tweets$mentions_screen_name <- tidy_tweets$mentions_screen_name %>% purrr::map(unlist) %>% purrr::map(unname) tidy_tweets %>% gt_edges(screen_name, mentions_screen_name) %>% gt_nodes() %>% gt_collect() -> gt nodes <- gt$nodes %>% mutate( id = nodes, label = nodes, size = n, color = "#1967be" ) edges <- gt$edges %>% mutate( id = 1:n() ) sigmajs() %>% sg_force_start() %>% sg_nodes(nodes, id, label, size, color) %>% sg_edges(edges, id, source, target) %>% sg_force_stop(10000) `` g %>% gt_edges(screen_name, mentions_screen_name) %>% gt_nodes(meta = TRUE) %>% gt_collect() -> graph <file_sep>--- title: "Untitled" author: "marc" date: "3/6/2020" output: html_document --- ```{r setup, include=FALSE} knitr::opts_chunk$set(echo = TRUE) ``` from: https://kateto.net/networks-r-igraph using igraph create netowrk ```{r} #undirected g1 <- graph( edges=c(1,2, 2,3, 3, 1), n=3, directed=F ) plot(g1) class(g1) g1 ``` ```{r} # Now with 10 vertices, and directed by default: g2 <- graph( edges=c(1,2, 2,3, 3, 1), n=10 ) plot(g2) ``` ```{r} g3 <- graph( c("John", "Jim", "Jim", "Jill", "Jill", "John")) # named vertices ``` ```{r} g4 <- graph( c("John", "Jim", "Jim", "Jack", "Jim", "Jack", "John", "John"), isolates=c("Jesse", "Janis", "Jennifer", "Justin") ) # In named graphs we can specify isolates by providing a list of their names. plot(g4, edge.arrow.size=.5, vertex.color="gold", vertex.size=15, vertex.frame.color="gray", vertex.label.color="black", vertex.label.cex=0.8, vertex.label.dist=2, edge.curved=0.2) ``` Small graphs can also be generated with a description of this kind: - for undirected tie, +- or -+ for directed ties pointing left & right, ++ for a symmetric tie, and “:” for sets of vertices. ```{r} plot(graph_from_literal(a---b, b---c)) # the number of dashes doesn't matter plot(graph_from_literal(a--+b, b+--c)) plot(graph_from_literal(a+-+b, b+-+c)) plot(graph_from_literal(a:b:c---c:d:e)) g1 <- graph_from_literal(a-b-c-d-e-f, a-g-h-b, h-e:f:i, j) plot(g1) ``` # 2.2 Edge, vertex, and network attributes ```{r} g4 plot(g4) E(g4) # The edges of the object V(g4) # vertices ``` You can also examine the network matrix directly: ```{r} g4[] g4[1,] ``` *Add attributes to the network, vertices, or edges* ```{r} V(g4)$name # automatically generated when we created the network. ``` ```{r} V(g4)$gender <- c("male", "male", "male", "male", "female", "female", "male") #vet attibute? E(g4)$type <- "email" # Edge attribute, assign "email" to all edges E(g4)$weight <- 10 # Edge weight, setting all existing edges to 10 ``` examine attirbutes ```{r} edge_attr(g4) vertex_attr(g4) ``` ```{r} graph_attr(g4) ``` Another way to set attributes (you can similarly use set_edge_attr(), set_vertex_attr(), etc.): ```{r} g4 <- set_graph_attr(g4, "name", "Email Network") g4 <- set_graph_attr(g4, "something", "A thing") graph_attr_names(g4) graph_attr(g4, "name") g4 <- delete_graph_attr(g4, "something") graph_attr(g4) ``` print the object to see what is happening above! ```{r} plot(g4, edge.arrow.size=.5, vertex.label.color="black", vertex.label.dist=1.5, vertex.color=c( "pink", "skyblue")[1+(V(g4)$gender=="male")] ) ``` The graph g4 has two edges going from Jim to Jack, and a loop from John to himself. We can simplify our graph to remove loops & multiple edges between the same nodes. Use edge.attr.comb to indicate how edge attributes are to be combined - possible options include sum, mean, prod (product), min, max, first/last (selects the first/last edge’s attribute). Option “ignore” says the attribute should be disregarded and dropped. ```{r} g4s <- simplify( g4, remove.multiple = T, remove.loops = F, edge.attr.comb=c(weight="sum", type="ignore") ) plot(g4s, vertex.label.dist=1.5) g4s ``` The description of an igraph object starts with up to four letters: 1.D or U, for a directed or undirected graph 2. N for a named graph (where nodes have a name attribute) 2. W for a weighted graph (where edges have a weight attribute) 3. B for a bipartite (two-mode) graph (where nodes have a type attribute) The two numbers that follow (7 5) refer to the number of nodes and edges in the graph. The description also lists node & edge attributes, for example: (g/c) - graph-level character attribute (v/c) - vertex-level character attribute (e/n) - edge-level numeric attribute # examples ```{r} nodes <- read.csv("Dataset1-Media-Example-NODES.csv", header=T, as.is=T) links <- read.csv("Dataset1-Media-Example-EDGES.csv", header=T, as.is=T) ``` examine data ```{r} head(nodes) head(links) nrow(nodes); length(unique(nodes$id)) nrow(links); nrow(unique(links[,c("from", "to")])) ``` Notice that there are more links than unique from-to combinations. That means we have cases in the data where there are multiple links between the same two nodes. We will collapse all links of the same type between the same two nodes by summing their weights, using aggregate() by “from”, “to”, & “type”. We don’t use simplify() here so as not to collapse different link types. ```{r} links <- aggregate(links[,3], links[,-3], sum) links <- links[order(links$from, links$to),] colnames(links)[4] <- "weight" rownames(links) <- NULL ``` other dataset ```{r} nodes2 <- read.csv("Dataset2-Media-User-Example-NODES.csv", header=T, as.is=T) links2 <- read.csv("Dataset2-Media-User-Example-EDGES.csv", header=T, row.names=1) head(nodes2) head(links2) #adjency matrix links2 <- as.matrix(links2) dim(links2) dim(nodes2) ``` 4. Turning networks into igraph objects We start by converting the raw data to an igraph network object. Here we use igraph’s graph.data.frame function, which takes two data frames: d and vertices. d describes the edges of the network. Its first two columns are the IDs of the source and the target node for each edge. The following columns are edge attributes (weight, type, label, or anything else). vertices starts with a column of node IDs. Any following columns are interpreted as node attributes. ```{r} library(igraph) net <- graph_from_data_frame(d=links, vertices=nodes, directed=T) class(net) ``` ```{r} net ``` easy acces to nodes, edges, and attirbute ```{r} E(net) # The edges of the "net" object V(net) # The vertices of the "net" object E(net)$type # Edge attribute "type" V(net)$media # Vertex attribute "media" ``` lets plot ```{r} plot(net, edge.arrow.size=.4,vertex.label=NA) ``` remove loops? ```{r} net <- simplify(net, remove.multiple = F, remove.loops = T) ``` #this doesn't seem to be working? If you need them, you can extract an edge list or a matrix from igraph networks. ```{r} as_edgelist(net, names=T) as_adjacency_matrix(net, attr="weight") ``` or as dataframes descibr nodes and edges ```{r} as_data_frame(net, what="edges") as_data_frame(net, what="vertices") ``` dataset2 As we have seen above, this time the edges of the network are in a matrix format. We can read those into a graph object using graph_from_incidence_matrix(). In igraph, bipartite networks have a node attribute called type that is FALSE (or 0) for vertices in one mode and TRUE (or 1) for those in the other mode. ```{r} head(nodes2) net2 <- graph_from_incidence_matrix(links2) table(V(net2)$type) ``` ## plotting networks 5.1 Plotting parameters NODES vertex.color Node color vertex.frame.color Node border color vertex.shape One of “none”, “circle”, “square”, “csquare”, “rectangle” “crectangle”, “vrectangle”, “pie”, “raster”, or “sphere” vertex.size Size of the node (default is 15) vertex.size2 The second size of the node (e.g. for a rectangle) vertex.label Character vector used to label the nodes vertex.label.family Font family of the label (e.g.“Times”, “Helvetica”) vertex.label.font Font: 1 plain, 2 bold, 3, italic, 4 bold italic, 5 symbol vertex.label.cex Font size (multiplication factor, device-dependent) vertex.label.dist Distance between the label and the vertex vertex.label.degree The position of the label in relation to the vertex, where 0 right, “pi” is left, “pi/2” is below, and “-pi/2” is above EDGES edge.color Edge color edge.width Edge width, defaults to 1 edge.arrow.size Arrow size, defaults to 1 edge.arrow.width Arrow width, defaults to 1 edge.lty Line type, could be 0 or “blank”, 1 or “solid”, 2 or “dashed”, 3 or “dotted”, 4 or “dotdash”, 5 or “longdash”, 6 or “twodash” edge.label Character vector used to label edges edge.label.family Font family of the label (e.g.“Times”, “Helvetica”) edge.label.font Font: 1 plain, 2 bold, 3, italic, 4 bold italic, 5 symbol edge.label.cex Font size for edge labels edge.curved Edge curvature, range 0-1 (FALSE sets it to 0, TRUE to 0.5) arrow.mode Vector specifying whether edges should have arrows, possible values: 0 no arrow, 1 back, 2 forward, 3 both OTHER margin Empty space margins around the plot, vector with length 4 frame if TRUE, the plot will be framed main If set, adds a title to the plot sub If set, adds a subtitle to the plot ```{r} ceb <- cluster_edge_betweenness(net) dendPlot(ceb, mode="hclust") clp <- cluster_label_prop(net) plot(clp, net) ``` ```{r} hs <- hub_score(rt_g, weights=NA)$vector as <- authority_score(rt_g, weights=NA)$vector par(mfrow=c(1,2)) plot(rt_g, vertex.size=hs*50, main="Hubs") plot(rt_g, vertex.size=as*30, main="Authorities") ``` scratch ```{r} dump_tidy_tweets <- all_tweets %>% select(screen_name, text, mentions_screen_name) %>% tidyr::separate_rows(mentions_screen_name, sep = " ") %>% tidyr::nest(mentions_screen_name = c(mentions_screen_name)) dump_tidy_tweets$mentions_screen_name <- dump_tidy_tweets$mentions_screen_name %>% purrr::map(unlist) %>% purrr::map(unname) dump_tidy_tweets %>% gt_edges(screen_name, mentions_screen_name) %>% gt_nodes() %>% gt_collect() -> dump_gt ``` <file_sep>#SNA library(igraph) install.packages("statnet") library(statnet) install.packages("tergm") <file_sep>--- title: "MMM_tweets" author: "<NAME>" date: "2/29/2020" output: html_document --- ```{r setup, include=FALSE} knitr::opts_chunk$set(echo = TRUE) ``` ```{r needed libraries} library(rtweet) library(tidyverse) library(tidytext) library(wordcloud) library(wordcloud2) library(lubridate) library(grid) library(tidygraph) library(igraph) library(hrbrthemes) library(ggraph) library(sigmajs) library(graphTweets) ``` first load the tweets ```{r loading tweets} MMM_2020<- search_tweets( "#2020MMM", n = 18000, include_rts = FALSE) Sys.time() MMM_2020_March02_6_30_am<- search_tweets( "#2020MMM", n = 18000, include_rts = FALSE) MMM_2020_March02_3_30_pm<- search_tweets( "#2020MMM", n = 18000, include_rts = FALSE) MMM_2020_March03_12_15_pm<- search_tweets( "#2020MMM", n = 18000, include_rts = FALSE) MMM_2020_March04_11_30_am<- search_tweets( "#2020MMM", n = 18000, include_rts = FALSE) MMM_2020_March04_11_30_am<- search_tweets( "#2020MMM", n = 18000, include_rts = FALSE) MMM_2020_March04_8_45_pm<- search_tweets( "#2020MMM", n = 18000, include_rts = FALSE) MMM_2020_March05_6_10_pm<- search_tweets( "#2020MMM", n = 18000, include_rts = FALSE) MMM_2020_March06_1_30_pm<- search_tweets( "#2020MMM", n = 18000, include_rts = FALSE) MMM_2020_March08_12_10_am<- search_tweets( "#2020MMM", n = 18000, include_rts = FALSE) MMM_2020_March09_9_30_am<- search_tweets( "#2020MMM", n = 18000, include_rts = FALSE) MMM_2020_March10_10_20_am<- search_tweets( "#2020MMM", n = 18000, include_rts = FALSE) current_time <- Sys.time() MMM_2020_March10_9_50_pm<- search_tweets( "#2020MMM", n = 18000, include_rts = FALSE) MMM_2020_March11_11_00_pm<- search_tweets( "#2020MMM", n = 18000, include_rts = FALSE) MMM_2020_March12_7_22_am<- search_tweets( "#2020MMM", n = 18000, include_rts = FALSE) ``` now i loose the first 29 from set1 and Export data ```{r} write_as_csv(MMM_2020, "2020-03-01_9AM_tweets") write_as_csv(MMM_2020_b_March03_5_50_pm, "2020-03-01_5_50pm_tweets") write_as_csv(MMM_2020_March02_6_30_am, "2020-03-02_6_30am_tweets") write_as_csv(MMM_2020_March02_3_30_pm, "2020-03-02_3_30pm_tweets") write_as_csv(MMM_2020_March03_12_15_pm, "2020-03-03_12_15pm_tweets") write_as_csv(MMM_2020_March04_11_30_am,"2020-03-04_11_30am_tweets" ) write_as_csv(MMM_2020_March04_8_45_pm,"2020-03-04_8_45pm_tweets" ) write_as_csv(MMM_2020_March05_6_10_pm, "2020-03-05_6_10pm_tweets") write_as_csv(MMM_2020_March06_1_30_pm, "2020-03-06_1_30pm_tweets") write_as_csv(MMM_2020_March08_12_10_am, "2020-03-08_12_10am_tweets" ) write_as_csv(MMM_2020_March09_9_30_am, "2020-03-09_9_30am_tweets" ) write_as_csv(MMM_2020_March10_10_20_am, "2020-03-10_10_20am_tweets") write_as_csv(MMM_2020_March10_9_50_pm, "2020-03-10_9_30pm_tweets") write_as_csv(MMM_2020_March11_11_00_pm,"2020-03-11_11_00pm_tweets") write_as_csv(MMM_2020_March12_7_22_am,"2020-03-12_7_2am_tweets") MMM_2020_March12_7_22_am ``` Testing adding dfs together ```{r adding data together} first <- read_csv("2020-03-01_9AM_tweets.csv") second <- read_csv("2020-03-01_5_50pm_tweets.csv") third <- read_csv("2020-03-02_6_30am_tweets.csv") fourth <- read_csv("2020-03-02_3_30pm_tweets.csv") fifth <- read_csv("2020-03-03_12_15pm_tweets.csv") sixth <-read_csv("2020-03-04_11_30am_tweets.csv") seventh <- read_csv("2020-03-04_8_45pm_tweets.csv") eighth <- read_csv("2020-03-05_6_10pm_tweets.csv") ninth <- read_csv("2020-03-06_1_30pm_tweets.csv") tenth <- read_csv("2020-03-08_12_10am_tweets.csv") eleven <- read_csv("2020-03-09_9_30am_tweets.csv") tweleve <- read_csv("2020-03-10_10_20am_tweets.csv") thirteen <- read_csv("2020-03-10_9_30pm_tweets.csv") fourteen <- read_csv("2020-03-11_11_00pm_tweets.csv") fifteen <- read_csv("2020-03-12_7_2am_tweets.csv") #comare to the rest all_tweets <- rbind(first, second, third, fourth, fifth, sixth, seventh, eighth, ninth, tenth, eleven, tweleve, thirteen,fourteen) %>% distinct(text, .keep_all = TRUE) #total <- rbind(a,b) #totalgrouped <- total %>% distinct(text, .keep_all = TRUE) #MMM_2020 <- totalgrouped ``` Basic graphs ```{r basic graphs} ts_plot(all_tweets, "2 hours") + ggplot2::theme_minimal() + ggplot2::theme(plot.title = ggplot2::element_text(face = "bold")) + ggplot2::labs( x = NULL, y = NULL, title = "Frequency of #2020MMM Twitter statuses", subtitle = paste("as of", current_time ), caption = "\nSource: Data collected from Twitter's REST API via rtweet") #ggplot(all_tweets, aes(created_at))+ geom_density(alpha=.75, fill="#4cda76")+ # fill with main SAC logo blue ggtitle("#2020MMM Tweets")+ ylab("Density of tweets")+ xlab("Time") ggplot(all_tweets, aes(created_at))+ geom_density(alpha=.75, fill="#4cda76") + labs(title = "Frequency of #2020MMM Twitter statuses", subtitle = paste("as of", current_time ), caption = "\nSource: Data collected from Twitter's REST API via rtweet") ``` anaylze data ```{r basic figs} all_tweets %>% count(screen_name, sort=T) all_tweets %>% group_by(screen_name) %>% summarise(rt = sum(retweet_count)) %>% arrange(-rt) all_tweets %>% arrange(-favorite_count) %>% select(favorite_count) MMM_2020 %>% group_by(screen_name) %>% count(sort=T) MMM_2020 %>% group_by(screen_name) %>% filter(n() > 5) %>% ggplot(aes(x= screen_name)) + geom_bar() + coord_flip() a <- all_tweets %>% group_by(screen_name) %>% add_tally() %>% filter(n() > 5) %>% ungroup() a %>% mutate(screen_name = fct_reorder(screen_name,n)) %>% ggplot(aes(x= screen_name, fill=screen_name)) + geom_bar() + coord_flip() + labs(title = "number of tweets that mention #2020MMM", subtitle = paste("as of", current_time ), x= "screen name") + theme(legend.position = "none") truth_background <- png::readPNG("LoveMMM.png") annotation_custom(rasterGrob(truth_background, width = unit(1,"npc"), height = unit(1,"npc")), -Inf, Inf, -Inf, Inf) a %>% mutate(screen_name = fct_reorder(screen_name,n)) %>% ggplot(aes(x= screen_name, fill=screen_name)) + annotation_custom(rasterGrob(truth_background, width = unit(1,"npc"), height = unit(1,"npc")), -Inf, Inf, -Inf, Inf) + geom_bar() + coord_flip() + labs(title = "number of tweets by username that mention #2020MMM", subtitle = paste("as of", current_time ), x= "screen name", caption = "background img from: https://libguides.asu.edu/MarchMammalMadness") + theme(legend.position = "none") all_tweets %>% mutate(day = as_date(created_at)) %>% count(day, sort=T) all_tweets %>% mutate(day = as_date(created_at)) %>% mutate(weekday = wday(day, label = T)) %>% count(weekday) %>% ggplot(aes(weekday,n)) + geom_line(group=1) + labs(title = "When people use the 2020MMM hashtag",subtitle = paste("as of ", current_time)) all_tweets %>% distinct(screen_name, .keep_all = TRUE) %>% count(location, sort=T) ``` wordcloud note: if there is a _ not showing up, which exmapling why mammls_suck isn't there ```{r wordcloud} MMM_table <- all_tweets %>% unnest_tokens(word, text) MMM_table <- MMM_table %>% anti_join(stop_words) MMM_table_data <- MMM_table MMM_table <- MMM_table %>% count(word, sort = T) MMM_table_edited <- MMM_table %>% filter(!word %in% c("2020mmm", "t.co", "https")) wordcloud2::wordcloud2(MMM_table_edited, size = .4) #MMM_table_edited <- MMM_table %>% filter(!word %in% c("2020mmm", "t.co", "https", "march", "mammal", "madness")) letterCloud(MMM_table_edited, word = "M", size=.2) #just top words top <- MMM_table_edited %>% top_n(50) wordcloud2::wordcloud2(top, size = .5) letterCloud(top, word = "MMM", size=.15) filt <- MMM_table_edited %>% filter(n >10) figPath <- "/Users/mkissel/Documents/Code/R_projects/2020_MMM/Picture1.png" wordcloud2(top, figPath = figPath, size=.5) #not wordcloud ``` more text ```{r} team <- MMM_2020 %>% filter(str_detect(text, "team")) filter(str_detect(text, "panda")) %>% pull(text) #lets see if i can pull out teams? or remove screennames from text teams <- all_tweets %>% filter(str_detect(text, "team")) gorilla <- all_tweets %>% filter(str_detect(text, "gorilla")) MMM_table_edited ``` map data (note that most tweets don't have loc data) ```{r} all_tweets %>% count(country_code) rt1 <- lat_lng(all_tweets) ``` map itself, version 1 ```{r} par(mar = c(0, 0, 0, 0)) maps::map("world", lwd = .25) with(rt1, points(lng, lat, pch = 20, cex = .75, col = rgb(0, .3, .7, .75))) ``` map, version 2 w/ leaflet ```{r} library(leaflet) leaflet() %>% addTiles() %>% setView(lat = 50.85045, lng = 4.34878, zoom=0) %>% addMarkers(~lng, ~lat, data = rt1, popup = ~as.character(text), label = ~as.character(screen_name)) ``` stream data: example from https://rtweet.info/articles/stream.html#stream_tweets ```{r} q <- "2020MMM" library(tidygraph) ## Stream time in seconds so for one minute set timeout = 60 ## For larger chunks of time, I recommend multiplying 60 by the number ## of desired minutes. This method scales up to hours as well ## (x * 60 = x mins, x * 60 * 60 = x hours) ## Stream for 30 minutes streamtime <- 30 * 60 ## Stream for 30 minutes streamtime <- 30 * 1 filename <- "rtelect.json" rt <- stream_tweets("2020MMM", timeout = 90, file_name = filename) # do or 9 seconds library(rjson) result <- fromJSON(file = "rtelect.json") ``` network? #first step is to fix issues. this fixes the mentions_screen_name col. might need for others as well. Also note i loose other cols. might either want to see if i can keep them or subset before if i want to look at different dates? ```{r setup for network analysis} tidy_tweets <- all_tweets %>% select(screen_name, mentions_screen_name) %>% mutate( hashtags = gsub("\\[|\\]|'", "", mentions_screen_name) ) %>% tidyr::separate_rows(hashtags, sep = ", ") %>% tidyr::nest(hashtags = c(hashtags)) tidy_tweets <- all_tweets %>% select(screen_name, mentions_screen_name) %>% tidyr::separate_rows(mentions_screen_name, sep = " ") %>% tidyr::nest(mentions_screen_name = c(mentions_screen_name)) tidy_tweets$mentions_screen_name <- tidy_tweets$mentions_screen_name %>% purrr::map(unlist) %>% purrr::map(unname) tidy_tweets %>% gt_edges(screen_name, mentions_screen_name) %>% gt_nodes() %>% gt_collect() -> gt ``` # below is a way to keep more cols, at least at first... ```{r keeping data data for network} dump_tidy_tweets <- all_tweets %>% select(screen_name, text, created_at, mentions_screen_name) %>% tidyr::separate_rows(mentions_screen_name, sep = " ") %>% tidyr::nest(mentions_screen_name = c(mentions_screen_name)) dump_tidy_tweets$mentions_screen_name <- dump_tidy_tweets$mentions_screen_name %>% purrr::map(unlist) %>% purrr::map(unname) #below i am droppng the text. i wonder if way to keep it as attibutr? that would be totes long though dump_tidy_tweets %>% gt_edges(screen_name, mentions_screen_name) %>% gt_nodes() %>% gt_collect() -> dump_gt ####below i am saving back as tidy tweets tidy_tweets <- dump_tidy_tweets %>% mutate(day = as_date( created_at)) ``` ``` https://rud.is/books/21-recipes/visualizing-a-graph-of-retweet-relationships.html make sure it is directed?....i assume it defaults for twitterGrpah but bit sure about igraph? might need to specify I THINK>..... other things: think about looking at reciprocity for this netowkr (The proportion of reciprocated ties). maybe compare diffeent groups etc? and transivity ```{r network} library(tidygraph) library(rtweet) library(igraph) library(hrbrthemes) library(ggraph) library(tidyverse) filter(tidy_tweets) %>% select(screen_name, mentions_screen_name) %>% unnest(mentions_screen_name) %>% filter(!is.na(mentions_screen_name)) %>% graph_from_data_frame() -> rt_g ggplot(data_frame(y=degree_distribution(rt_g), x=1:length(y))) + geom_segment(aes(x, y, xend=x, yend=0), color="slateblue") + scale_y_continuous(expand=c(0,0), trans="sqrt") + labs(x="Degree", y="Density (sqrt scale)", title="#rstats Retweet Degree Distribution") + theme_ipsum_rc(grid="Y", axis="x") #add labels for nodes that have a degree of 5 or more . if there is lower than 5 there is no label V(rt_g)$node_label <- unname(ifelse(degree(rt_g)[V(rt_g)] > 5, names(V(rt_g)), "")) V(rt_g)$node_size <- unname(ifelse(degree(rt_g)[V(rt_g)] > 5, degree(rt_g), 0)) #stnght? V(rt_g)$node_label <- unname(ifelse(strength(rt_g)[V(rt_g)] > 5, names(V(rt_g)), "")) # creats node lable if sregn >5 V(rt_g)$node_size <- unname(ifelse(strength(rt_g)[V(rt_g)] > 5, degree(rt_g), 0)) rt_g %>% ggraph(layout = "fr") + geom_edge_link() + geom_node_point(color = "darkslategray4", size = 5) + geom_node_label(aes(label=node_label, size=node_size), label.size=0, fill="#ffffff66", segment.colour="springgreen", color="slateblue", repel=TRUE, fontface="bold") + ggtitle(expression(paste("Who talks to who in", italic("March Mammal Madness")))) + theme_void() ``` Other network things with igraph ```{r} #network measures # see https://www.youtube.com/watch?v=0xsM0MbRPGE degree(rt_g) #number of connections as.data.frame(degree(rt_g)) hist(degree(rt_g), breaks=1:vcount(rt_g)-1, main="Histogram of node degree") #can i do a log hist(log(degree(rt_g)), breaks=1:vcount(rt_g)-1, main="Histogram of node degree") #https://kateto.net/wp-content/uploads/2016/01/NetSciX_2016_Workshop.pdf deg.dist <- degree_distribution(rt_g, cumulative=T, mode="all") plot( x=0:max(deg), y=1-deg.dist, pch=19, cex=1.2, col="orange", xlab="Degree", ylab="Cumulative Frequency") degree(rt_g, mode = "in") degree(rt_g, mode = "out") diameter(rt_g) ecount(rt_g) #how many edges vcount(rt_g) edge_density(rt_g, loops = F) #note that the bigger a network geets the smmaller the density reciprocity(rt_g) #in this case, = .15 so 15% reciprocity #one thing to think about is does this increase over time? i.e. as the game increases do more people follow each other? could sep by days and look at it that way? but to do that i'd have to redo the tidytweets df and make sure to subset correctyl closeness(rt_g) #also something to look at. who is closest? # closeness centrality is a way of detecting nodes that are able to spread information very efficiently through a grap betweenness(rt_g) # who is inbetween edge_betweenness(rt_g) # we can add things like we did above V(rt_g)$degree <- degree(rt_g) hist(V(rt_g)$degree) # amny nodes with few connection #then use above to look by degree rt_g %>% ggraph(layout = "fr") + geom_edge_link() + geom_node_point(aes(size = degree)) + geom_node_label(aes(label=node_label), label.size=0, fill="#ffffff66", segment.colour="springgreen", color="slateblue", repel=TRUE, fontface="bold") + ggtitle(expression(paste("Who talks to who in", italic("March Mammal Madness")))) + theme_void() #looking better...just have too many labed i think #change what is labled V(rt_g)$node_label <- unname(ifelse(degree(rt_g)[V(rt_g)] > 30, names(V(rt_g)), "")) V(rt_g)$node_size <- unname(ifelse(degree(rt_g)[V(rt_g)] > 30, degree(rt_g), 0)) rt_g %>% ggraph(layout = "fr") + geom_edge_link(aes(color="red")) + geom_node_point(aes(size = degree, color="red")) + geom_node_label(aes(label=node_label), label.size=0, fill="#ffffff66", segment.colour="springgreen", color="slateblue", repel=TRUE, fontface="bold") + ggtitle(expression(paste("Who talks to who in", italic("March Mammal Madness")))) + theme_void() + labs(caption = paste("as of", current_time )) rt_g %>% ggraph(layout = "kk") + geom_edge_link(aes(color="red")) + geom_node_point(aes(size = degree, color=degree)) + geom_node_label(aes(label=node_label), label.size=0, fill="#ffffff66", segment.colour="springgreen", color="slateblue", repel=TRUE, fontface="bold") + ggtitle(expression(paste("Who talks to who in", italic("March Mammal Madness")))) + theme_void() + labs(caption = paste("as of", current_time )) #below try a dif layout rt_g %>% ggraph(layout = "kk") + geom_edge_link() + geom_node_point(aes(size = degree)) + ggtitle(expression(paste("Who talks to who in", italic("March Mammal Madness")))) + theme_void() #think about coloring by degree? rt_g %>% ggraph(layout = "fr") + geom_edge_link() + geom_node_point(aes(size = degree, color = degree)) + ggtitle(expression(paste("Who talks to who in", italic("March Mammal Madness")))) + theme_void() #hub3 #hub have outgoing link and authoris have many incominf hs <- hub_score(rt_g, weights=NA)$vector as <- authority_score(rt_g, weights=NA)$vector par(mfrow =c(1,2)) plot(rt_g, main = "hubs", vertex.size = hs*30, vertex.color = rainbow(381), vertex.label = NA, layout=layout.kamada.kawai) plot(rt_g, main = "Auth", vertex.size = as*30, vertex.color = rainbow(381), vertex.label = NA, layout=layout.kamada.kawai) #think about how to get rid of lables here or only label ones that have a certain value? shouldn't be hard. just follow aboe ``` belwo is other stuff from igaph looking at diffeent things like cominty...might want to think more on this ```{r} #################################### ############################################### clp <- cluster_label_prop(rt_g) plot(clp, rt_g) plot(clp, rt_g, vertex.label=V(rt_g)$node_label) #after using above to set node_label plot(clp, rt_g, vertex.label=V(rt_g)$node_label, vertex.size=V(rt_g)$node_size ) #not good #hubs #hub have outgoing link and authoris have many incominf hs <- hub_score(rt_g, weights=NA)$vector as <- authority_score(rt_g, weights=NA)$vector par(mfrow=c(1,2)) plot(rt_g, vertex.size=hs*50, main="Hubs") plot(rt_g, vertex.size=as*30, main="Authorities") par(mfrow=c(1,2)) plot(rt_g, vertex.size=hs*50, main="Hubs", vertex.label=V(rt_g)$node_label) plot(rt_g, vertex.size=as*30, main="Authorities", vertex.label=V(rt_g)$node_label) ``` #below shld work!!!!! ```{r fancy networks} tidy_tweets <- all_tweets %>% select(screen_name, mentions_screen_name) %>% mutate( hashtags = gsub("\\[|\\]|'", "", mentions_screen_name) ) %>% tidyr::separate_rows(hashtags, sep = ", ") %>% tidyr::nest(hashtags = c(hashtags)) tidy_tweets <- all_tweets %>% select(screen_name, mentions_screen_name) %>% tidyr::separate_rows(mentions_screen_name, sep = " ") %>% tidyr::nest(mentions_screen_name = c(mentions_screen_name)) tidy_tweets$mentions_screen_name <- tidy_tweets$mentions_screen_name %>% purrr::map(unlist) %>% purrr::map(unname) tidy_tweets %>% gt_edges(screen_name, mentions_screen_name) %>% gt_nodes() %>% gt_collect() -> gt nodes <- gt$nodes %>% mutate( id = nodes, label = nodes, size = n, color = "#1967be" ) edges <- gt$edges %>% mutate( id = 1:n() ) sigmajs() %>% sg_force_start() %>% sg_nodes(nodes, id, label, size, color) %>% sg_edges(edges, id, source, target) %>% sg_force_stop(10000) sigmajs() %>% sg_force_start() %>% sg_nodes(nodes, id, label, size, color) %>% sg_edges(edges, id, source, target) %>% sg_force_stop(10000) %>% sg_drag_nodes() %>% sg_cluster() g %>% gt_edges(screen_name, mentions_screen_name) %>% gt_nodes(meta = TRUE) %>% gt_collect() -> graph ``` Below here is scratch ```{r} install.packages("graphTweets") install.packages("sigmajs") library(graphTweets) library(sigmajs) #lest stats by adding te dfs togehte tthat eep the ino in list forms x <- rbind(MMM_2020_b_March03_5_50_pm, MMM_2020_March02_6_30_am, MMM_2020_March02_3_30_pm, MMM_2020_March03_12_15_pm, MMM_2020_March04_11_30_am) x %>% distinct(text, .keep_all = TRUE) x %>% gt_edges(text, screen_name, status_id) %>% gt_graph() %>% plot() #bad ###### MMM_2020 %>% gt_edges(screen_name, mentions_screen_name) %>% gt_nodes(meta = TRUE) %>% gt_collect() -> graph #smaller MMM_2020_small <- MMM_2020 %>% filter(!is.na(mentions_screen_name)) %>% gt_edges(screen_name, mentions_screen_name) %>% gt_nodes(meta = TRUE) %>% gt_collect() -> graph MMM_2020 %>% gt_edges(screen_name, mentions_screen_name) %>% gt_nodes() %>% gt_collect() -> gt nodes <- gt$nodes %>% mutate( id = nodes, label = nodes, size = n, color = "#1967be" ) edges <- gt$edges %>% mutate( id = 1:n() ) sigmajs() %>% sg_force_start() %>% sg_nodes(nodes, id, label, size, color) %>% sg_edges(edges, id, source, target) %>% sg_force_stop(10000) sigmajs() %>% sg_force_start() %>% sg_nodes(nodes, id, label, size, color) %>% sg_edges(edges, id, source, target) %>% sg_force_stop(10000) %>% sg_drag_nodes() %>% sg_cluster() #########################################3 #try various things fomr http://sigmajs.john-coene.com/articles/cluster.html etc # MMM_2020 %>% filter(!is.na(mentions_screen_name)) %>% gt_edges(screen_name, mentions_screen_name) %>% gt_nodes() %>% gt_collect() -> gt ####################3 net <- all_tweets %>% gt_edges(screen_name, hashtags) %>% gt_nodes() %>% gt_collect() edges <- net$edges nodes <- net$nodes edges$id <- seq(1, nrow(edges)) nodes$id <- nodes$nodes nodes$label <- nodes$nodes nodes$size <- nodes$n nodes$color <- ifelse(nodes$type == "user", "#0084b4", "#1dcaff") sigmajs() %>% sg_force_start() %>% sg_nodes(nodes, id, label, size, color) %>% sg_edges(edges, id, source, target) %>% sg_force_stop(10000) #to deal with multple maybe this will work net <- MMM_2020_b_March03_5_50_pm %>% gt_co_edges(mentions_screen_name) %>% gt_nodes() %>% gt_collect() c(edges, nodes) %<-% net edges <- edges %>% mutate(id = 1:n()) nodes <- nodes %>% mutate( id = nodes, label = id, size = n ) sigmajs() %>% sg_nodes(nodes, id, label, size) %>% sg_edges(edges, id, source, target) %>% sg_cluster( colors = c( "#0084b4", "#00aced", "#1dcaff", "#c0deed" ) ) %>% sg_layout(layout = igraph::layout.fruchterman.reingold) %>% sg_neighbours() %>% sg_settings( maxNodeSize = 3, defaultEdgeColor = "#a3a3a3", edgeColor = "default" ) #ok, above works but aisl on all_tweets. i think tis is becuase, all_tweets has the mentons_scren ame as charte not as a list...can weix or is it fucked #also check if that iw whyother lok weird #update it is! so can i read them back in as a list? #OR keep what i have and bind togehter to avoit raeding in #or fix all_tweet #or we can just do it by day? i wonder how many twett for each battle day? w <- all_tweets %>% as.list(mentions_screen_name) ``` ```{r} library(tidygraph) library(rtweet) library(igraph) library(hrbrthemes) library(ggraph) library(tidyverse) filter(MMM_2020, retweet_count > 0) %>% select(screen_name, mentions_screen_name) %>% unnest(mentions_screen_name) %>% filter(!is.na(mentions_screen_name)) %>% graph_from_data_frame() -> rt_g ggplot(data_frame(y=degree_distribution(rt_g), x=1:length(y))) + geom_segment(aes(x, y, xend=x, yend=0), color="slateblue") + scale_y_continuous(expand=c(0,0), trans="sqrt") + labs(x="Degree", y="Density (sqrt scale)", title="#rstats Retweet Degree Distribution") + theme_ipsum_rc(grid="Y", axis="x") #add labels for nodes that have a degree of 20 or more V(rt_g)$node_label <- unname(ifelse(degree(rt_g)[V(rt_g)] > 20, names(V(rt_g)), "")) V(rt_g)$node_size <- unname(ifelse(degree(rt_g)[V(rt_g)] > 20, degree(rt_g), 0)) #strenght? V(rt_g)$node_label <- unname(ifelse(strength(rt_g)[V(rt_g)] > 20, names(V(rt_g)), "")) V(rt_g)$node_size <- unname(ifelse(strength(rt_g)[V(rt_g)] > 20, degree(rt_g), 0)) ggraph(rt_g, layout = 'linear', circular = TRUE) + geom_edge_arc(edge_width=0.125, aes(alpha=..index..)) + geom_node_label(aes(label=node_label, size=node_size), label.size=0, fill="#ffffff66", segment.colour="springgreen", color="slateblue", repel=TRUE, family=font_rc, fontface="bold") + coord_fixed() + scale_size_area(trans="sqrt") + labs(title="Retweet Relationships", subtitle="Most retweeted screen names labeled. Darkers edges == more retweets. Node size == larger degree") + theme_graph(base_family=font_rc) + theme(legend.position="none") rt_g %>% ggraph(layout = "fr") + geom_edge_link() + geom_node_point(color = "darkslategray4", size = 5) + geom_node_label(aes(label=node_label, size=node_size), label.size=0, fill="#ffffff66", segment.colour="springgreen", color="slateblue", repel=TRUE, family=font_rc, fontface="bold") + ggtitle(expression(paste("Who talks to who in", italic("March Mammal Madness")))) + theme_void() # #deal with names? filter(all_tweets, retweet_count > 0) %>% select(screen_name, mentions_screen_name) %>% unnest(mentions_screen_name) %>% filter(!is.na(mentions_screen_name)) %>% graph_from_data_frame() -> rt_g V(rt_g)$label <- ifelse( strength(rt_g)>=5, V(rt_g)$name, NA ) # this creates the node label and gives a name is strneght is above 5 par(mar=c(0,0,0,0)); plot(rt_g) #other visal #http://pablobarbera.com/big-data-upf/html/02a-networks-intro-visualization.html plot(rt_g) plot(rt_g, vertex.color = "grey", # change color of nodes vertex.label.color = "black", # change color of labels vertex.label.cex = .75, # change size of labels to 75% of original size edge.curved=.25, # add a 25% curve to the edges edge.color="grey20") # change edge color to grey V(rt_g)$size <- strength(rt_g) par(mar=c(0,0,0,0)); plot(rt_g) #log V(rt_g)$size <- log(strength(rt_g)) * 4 + 3 par(mar=c(0,0,0,0)); plot(rt_g) #circle V(rt_g)$label <- ifelse( strength(rt_g)>=2, V(rt_g)$name, NA ) par(mar=c(0,0,0,0)) plot(rt_g, layout=layout_in_circle, main="Circle") V(rt_g)$label <- ifelse( degree(rt_g)>=20, V(rt_g)$name, NA ) par(mar=c(0,0,0,0)) plot(rt_g, layout=layout_in_circle, main="Circle") #The most popular layouts are force-directed. These algorithms, such as Fruchterman-Reingold, try to position the nodes so that the edges have similar length and there are as few crossing edges as possible. The idea is to generate “clean” layouts, where nodes that are closer to each other share more connections in common that those that are located further apart. Note that this is a non-deterministic algorithm: choosing a different seed will generate different layouts. #force-directed par(mfrow=c(1,2)) set.seed(777) fr <- layout_with_fr(rt_g, niter=1000) par(mar=c(0,0,0,0)); plot(rt_g, layout=fr) set.seed(666) fr <- layout_with_fr(rt_g, niter=1000) par(mar=c(0,0,0,0)); plot(rt_g, layout=fr) #more #https://juliasilge.com/blog/life-changing-magic/ rt_g %>% ggraph(layout = "fr") + geom_edge_link(aes(edge_alpha = n, edge_width = n)) + geom_node_point(color = "darkslategray4", size = 5) + geom_node_text(aes(label = name), vjust = 1.8) + ggtitle(expression(paste("Word Network in Jane Austen's ", italic("Pride and Prejudice")))) + theme_void() #blah for above filter(all_tweets, retweet_count > 0) %>% select(screen_name, mentions_screen_name) %>% unnest(mentions_screen_name) %>% filter(!is.na(mentions_screen_name)) %>% pivot_longer(cols = mentions_screen_name, names_to = "mentions") ``` <file_sep>--- title: "MMM_tweets" author: "<NAME>" date: "2/29/2020" output: html_document --- ```{r setup, include=FALSE} knitr::opts_chunk$set(echo = TRUE) ``` ```{r needed libraries} library(rtweet) library(tidyverse) library(tidytext) library(wordcloud) library(wordcloud2) library(lubridate) ``` first load the tweets ```{r} MMM_2020<- search_tweets( "#2020MMM", n = 18000, include_rts = FALSE) Sys.time() MMM_2020_March02_6_30_am<- search_tweets( "#2020MMM", n = 18000, include_rts = FALSE) MMM_2020_March02_3_30_pm<- search_tweets( "#2020MMM", n = 18000, include_rts = FALSE) MMM_2020_March03_12_15_pm<- search_tweets( "#2020MMM", n = 18000, include_rts = FALSE) MMM_2020_March04_11_30_am<- search_tweets( "#2020MMM", n = 18000, include_rts = FALSE) MMM_2020_March04_11_30_am<- search_tweets( "#2020MMM", n = 18000, include_rts = FALSE) MMM_2020_March04_8_45_pm<- search_tweets( "#2020MMM", n = 18000, include_rts = FALSE) current_time <- Sys.time() ``` now i loose the first 29 from set1 and Export data ```{r} write_as_csv(MMM_2020, "2020-03-01_9AM_tweets") write_as_csv(MMM_2020_b_March03_5_50_pm, "2020-03-01_5_50pm_tweets") write_as_csv(MMM_2020_March02_6_30_am, "2020-03-02_6_30am_tweets") write_as_csv(MMM_2020_March02_3_30_pm, "2020-03-02_3_30pm_tweets") write_as_csv(MMM_2020_March03_12_15_pm, "2020-03-03_12_15pm_tweets") write_as_csv(MMM_2020_March04_11_30_am,"2020-03-04_11_30am_tweets" ) write_as_csv(MMM_2020_March04_8_45_pm,"2020-03-04_8_45pm_tweets" ) ``` Testing adding dfs together ```{r} first <- read_csv("2020-03-01_9AM_tweets.csv") second <- read_csv("2020-03-01_5_50pm_tweets.csv") third <- read_csv("2020-03-02_6_30am_tweets.csv") fourth <- read_csv("2020-03-02_3_30pm_tweets.csv") fifth <- read_csv("2020-03-03_12_15pm_tweets.csv") sixth <-read_csv("2020-03-04_11_30am_tweets.csv") seventh <- read_csv("2020-03-04_8_45pm_tweets.csv") all_tweets <- rbind(first, second, third, fourth, fifth, sixth, seventh) %>% distinct(text, .keep_all = TRUE) #total <- rbind(a,b) #totalgrouped <- total %>% distinct(text, .keep_all = TRUE) #MMM_2020 <- totalgrouped ``` Basic graphs ```{r} ts_plot(all_tweets, "2 hours") + ggplot2::theme_minimal() + ggplot2::theme(plot.title = ggplot2::element_text(face = "bold")) + ggplot2::labs( x = NULL, y = NULL, title = "Frequency of #2020MMM Twitter statuses", subtitle = paste("as of", current_time ), caption = "\nSource: Data collected from Twitter's REST API via rtweet") ggplot(all_tweets, aes(created_at))+ geom_density(alpha=.75, fill="#4cda76")+ # fill with main SAC logo blue ggtitle("#2020MMM Tweets")+ ylab("Density of tweets")+ xlab("Time") ggplot(all_tweets, aes(created_at))+ geom_density(alpha=.75, fill="#4cda76") + labs(title = "Frequency of #2020MMM Twitter statuses", subtitle = paste("as of", current_time ), caption = "\nSource: Data collected from Twitter's REST API via rtweet") ``` anaylze data ```{r} all_tweets %>% count(screen_name, sort=T) all_tweets %>% group_by(screen_name) %>% summarise(rt = sum(retweet_count)) %>% arrange(-rt) MMM_2020 %>% arrange(-favorite_count) %>% select(favorite_count) MMM_2020 %>% group_by(screen_name) %>% count(sort=T) MMM_2020 %>% group_by(screen_name) %>% filter(n() > 5) %>% ggplot(aes(x= screen_name)) + geom_bar() + coord_flip() a <- all_tweets %>% group_by(screen_name) %>% add_tally() %>% filter(n() > 5) %>% ungroup() a %>% mutate(screen_name = fct_reorder(screen_name,n)) %>% ggplot(aes(x= screen_name, fill=screen_name)) + geom_bar() + coord_flip() + labs(title = "number of tweets that mention #2020MMM", subtitle = paste("as of", current_time ), x= "screen name") + theme(legend.position = "none") truth_background <- png::readPNG("LoveMMM.png") annotation_custom(rasterGrob(truth_background, width = unit(1,"npc"), height = unit(1,"npc")), -Inf, Inf, -Inf, Inf) library(grid) a %>% mutate(screen_name = fct_reorder(screen_name,n)) %>% ggplot(aes(x= screen_name, fill=screen_name)) + annotation_custom(rasterGrob(truth_background, width = unit(1,"npc"), height = unit(1,"npc")), -Inf, Inf, -Inf, Inf) + geom_bar() + coord_flip() + labs(title = "number of tweets by username that mention #2020MMM", subtitle = paste("as of", current_time ), x= "screen name", caption = "background img from: https://libguides.asu.edu/MarchMammalMadness") + theme(legend.position = "none") all_tweets %>% mutate(day = as_date(created_at)) %>% count(day, sort=T) ``` wordcloud note: if there is a _ not showing up, which exmapling why mammls_suck isn't there ```{r} MMM_table <- all_tweets %>% unnest_tokens(word, text) MMM_table <- MMM_table %>% anti_join(stop_words) MMM_table <- MMM_table %>% count(word, sort = T) MMM_table_edited <- MMM_table %>% filter(!word %in% c("2020mmm", "t.co", "https")) wordcloud2::wordcloud2(MMM_table_edited, size = .4) #MMM_table_edited <- MMM_table %>% filter(!word %in% c("2020mmm", "t.co", "https", "march", "mammal", "madness")) letterCloud(MMM_table_edited, word = "M", size=.4) filt <- MMM_table_edited %>% filter(n >10) figPath <- "/Users/mkissel/Documents/Code/R_projects/2020_MMM/image.png" wordcloud2(demoFreq, figPath = figPath, size = 3,color = "green", backgroundColor = "black") ``` more text ```{r} team <- MMM_2020 %>% filter(str_detect(text, "team")) filter(str_detect(text, "panda")) %>% pull(text) #lets see if i can pull out teams? or remove screennames from text teams <- all_tweets %>% filter(str_detect(text, "team")) MMM_table_edited ``` map data (note that most tweets don't have loc data) ```{r} MMM_2020 %>% count(country_code) rt1 <- lat_lng(all_tweets) ``` map itself, version 1 ```{r} par(mar = c(0, 0, 0, 0)) maps::map("world", lwd = .25) with(rt1, points(lng, lat, pch = 20, cex = .75, col = rgb(0, .3, .7, .75))) ``` map, version 2 w/ leaflet ```{r} library(leaflet) leaflet() %>% addTiles() %>% setView(lat = 50.85045, lng = 4.34878, zoom=0) %>% addMarkers(~lng, ~lat, data = rt1, popup = ~as.character(text), label = ~as.character(screen_name)) ``` stream data: example from https://rtweet.info/articles/stream.html#stream_tweets ```{r} q <- "2020MMM" library(tidygraph) ## Stream time in seconds so for one minute set timeout = 60 ## For larger chunks of time, I recommend multiplying 60 by the number ## of desired minutes. This method scales up to hours as well ## (x * 60 = x mins, x * 60 * 60 = x hours) ## Stream for 30 minutes streamtime <- 30 * 60 ## Stream for 30 minutes streamtime <- 30 * 1 filename <- "rtelect.json" rt <- stream_tweets("2020MMM", timeout = 90, file_name = filename) # do or 9 seconds library(rjson) result <- fromJSON(file = "rtelect.json") ``` network? https://rud.is/books/21-recipes/visualizing-a-graph-of-retweet-relationships.html ```{r} library(tidygraph) library(rtweet) library(igraph) library(hrbrthemes) library(ggraph) library(tidyverse) filter(MMM_2020, retweet_count > 0) %>% select(screen_name, mentions_screen_name) %>% unnest(mentions_screen_name) %>% filter(!is.na(mentions_screen_name)) %>% graph_from_data_frame() -> rt_g ggplot(data_frame(y=degree_distribution(rt_g), x=1:length(y))) + geom_segment(aes(x, y, xend=x, yend=0), color="slateblue") + scale_y_continuous(expand=c(0,0), trans="sqrt") + labs(x="Degree", y="Density (sqrt scale)", title="#rstats Retweet Degree Distribution") + theme_ipsum_rc(grid="Y", axis="x") #add labels for nodes that have a degree of 20 or more V(rt_g)$node_label <- unname(ifelse(degree(rt_g)[V(rt_g)] > 20, names(V(rt_g)), "")) V(rt_g)$node_size <- unname(ifelse(degree(rt_g)[V(rt_g)] > 20, degree(rt_g), 0)) ggraph(rt_g, layout = 'linear', circular = TRUE) + geom_edge_arc(edge_width=0.125, aes(alpha=..index..)) + geom_node_label(aes(label=node_label, size=node_size), label.size=0, fill="#ffffff66", segment.colour="springgreen", color="slateblue", repel=TRUE, family=font_rc, fontface="bold") + coord_fixed() + scale_size_area(trans="sqrt") + labs(title="Retweet Relationships", subtitle="Most retweeted screen names labeled. Darkers edges == more retweets. Node size == larger degree") + theme_graph(base_family=font_rc) + theme(legend.position="none") rt_g %>% ggraph(layout = "fr") + geom_edge_link() + geom_node_point(color = "darkslategray4", size = 5) + geom_node_text(aes(label = name), vjust = 1.8) + ggtitle(expression(paste("Word Network in Jane Austen's ", italic("Pride and Prejudice")))) + theme_void() rt_g %>% ggraph(layout = "fr") + geom_edge_link() + geom_node_point(color = "darkslategray4", size = 5) + geom_node_label(aes(label=node_label, size=node_size), label.size=0, fill="#ffffff66", segment.colour="springgreen", color="slateblue", repel=TRUE, family=font_rc, fontface="bold") + ggtitle(expression(paste("Who talks to who in", italic("March Mammal Madness")))) + theme_void() #other visal #http://pablobarbera.com/big-data-upf/html/02a-networks-intro-visualization.html plot(rt_g) plot(rt_g, vertex.color = "grey", # change color of nodes vertex.label.color = "black", # change color of labels vertex.label.cex = .75, # change size of labels to 75% of original size edge.curved=.25, # add a 25% curve to the edges edge.color="grey20") # change edge color to grey V(rt_g)$size <- strength(rt_g) par(mar=c(0,0,0,0)); plot(rt_g) #log V(rt_g)$size <- log(strength(rt_g)) * 4 + 3 par(mar=c(0,0,0,0)); plot(rt_g) #deal with names? V(rt_g)$label <- ifelse( strength(rt_g)>=5, V(rt_g)$name, NA ) par(mar=c(0,0,0,0)); plot(rt_g) #circle V(rt_g)$label <- ifelse( strength(rt_g)>=2, V(rt_g)$name, NA ) par(mar=c(0,0,0,0)) plot(rt_g, layout=layout_in_circle, main="Circle") V(rt_g)$label <- ifelse( degree(rt_g)>=20, V(rt_g)$name, NA ) par(mar=c(0,0,0,0)) plot(rt_g, layout=layout_in_circle, main="Circle") #The most popular layouts are force-directed. These algorithms, such as Fruchterman-Reingold, try to position the nodes so that the edges have similar length and there are as few crossing edges as possible. The idea is to generate “clean” layouts, where nodes that are closer to each other share more connections in common that those that are located further apart. Note that this is a non-deterministic algorithm: choosing a different seed will generate different layouts. #force-directed par(mfrow=c(1,2)) set.seed(777) fr <- layout_with_fr(rt_g, niter=1000) par(mar=c(0,0,0,0)); plot(rt_g, layout=fr) set.seed(666) fr <- layout_with_fr(rt_g, niter=1000) par(mar=c(0,0,0,0)); plot(rt_g, layout=fr) #more #https://juliasilge.com/blog/life-changing-magic/ rt_g %>% ggraph(layout = "fr") + geom_edge_link(aes(edge_alpha = n, edge_width = n)) + geom_node_point(color = "darkslategray4", size = 5) + geom_node_text(aes(label = name), vjust = 1.8) + ggtitle(expression(paste("Word Network in Jane Austen's ", italic("Pride and Prejudice")))) + theme_void() #blah for above filter(all_tweets, retweet_count > 0) %>% select(screen_name, mentions_screen_name) %>% unnest(mentions_screen_name) %>% filter(!is.na(mentions_screen_name)) %>% pivot_longer(cols = mentions_screen_name, names_to = "mentions") ``` ABOVE IS kinda messy http://graphtweets.john-coene.com/ BELOw looks nicer ```{r} install.packages("graphTweets") install.packages("sigmajs") library(graphTweets) library(sigmajs) #lest stats by adding te dfs togehte tthat eep the ino in list forms x <- rbind(MMM_2020_b_March03_5_50_pm, MMM_2020_March02_6_30_am, MMM_2020_March02_3_30_pm, MMM_2020_March03_12_15_pm, MMM_2020_March04_11_30_am) x %>% distinct(text, .keep_all = TRUE) x %>% gt_edges(text, screen_name, status_id) %>% gt_graph() %>% plot() #bad ###### MMM_2020 %>% gt_edges(screen_name, mentions_screen_name) %>% gt_nodes(meta = TRUE) %>% gt_collect() -> graph #smaller MMM_2020_small <- MMM_2020 %>% filter(!is.na(mentions_screen_name)) %>% gt_edges(screen_name, mentions_screen_name) %>% gt_nodes(meta = TRUE) %>% gt_collect() -> graph MMM_2020 %>% gt_edges(screen_name, mentions_screen_name) %>% gt_nodes() %>% gt_collect() -> gt nodes <- gt$nodes %>% mutate( id = nodes, label = nodes, size = n, color = "#1967be" ) edges <- gt$edges %>% mutate( id = 1:n() ) sigmajs() %>% sg_force_start() %>% sg_nodes(nodes, id, label, size, color) %>% sg_edges(edges, id, source, target) %>% sg_force_stop(10000) sigmajs() %>% sg_force_start() %>% sg_nodes(nodes, id, label, size, color) %>% sg_edges(edges, id, source, target) %>% sg_force_stop(10000) %>% sg_drag_nodes() %>% sg_cluster() #########################################3 #try various things fomr http://sigmajs.john-coene.com/articles/cluster.html etc # MMM_2020 %>% filter(!is.na(mentions_screen_name)) %>% gt_edges(screen_name, mentions_screen_name) %>% gt_nodes() %>% gt_collect() -> gt ####################3 net <- all_tweets %>% gt_edges(screen_name, hashtags) %>% gt_nodes() %>% gt_collect() edges <- net$edges nodes <- net$nodes edges$id <- seq(1, nrow(edges)) nodes$id <- nodes$nodes nodes$label <- nodes$nodes nodes$size <- nodes$n nodes$color <- ifelse(nodes$type == "user", "#0084b4", "#1dcaff") sigmajs() %>% sg_force_start() %>% sg_nodes(nodes, id, label, size, color) %>% sg_edges(edges, id, source, target) %>% sg_force_stop(10000) #to deal with multple maybe this will work net <- MMM_2020_b_March03_5_50_pm %>% gt_co_edges(mentions_screen_name) %>% gt_nodes() %>% gt_collect() c(edges, nodes) %<-% net edges <- edges %>% mutate(id = 1:n()) nodes <- nodes %>% mutate( id = nodes, label = id, size = n ) sigmajs() %>% sg_nodes(nodes, id, label, size) %>% sg_edges(edges, id, source, target) %>% sg_cluster( colors = c( "#0084b4", "#00aced", "#1dcaff", "#c0deed" ) ) %>% sg_layout(layout = igraph::layout.fruchterman.reingold) %>% sg_neighbours() %>% sg_settings( maxNodeSize = 3, defaultEdgeColor = "#a3a3a3", edgeColor = "default" ) #ok, above works but aisl on all_tweets. i think tis is becuase, all_tweets has the mentons_scren ame as charte not as a list...can weix or is it fucked #also check if that iw whyother lok weird #update it is! so can i read them back in as a list? #OR keep what i have and bind togehter to avoit raeding in #or fix all_tweet #or we can just do it by day? i wonder how many twett for each battle day? w <- all_tweets %>% as.list(mentions_screen_name) ``` #below shld work!!!!! ```{r} tidy_tweets <- all_tweets %>% select(screen_name, mentions_screen_name) %>% mutate( hashtags = gsub("\\[|\\]|'", "", mentions_screen_name) ) %>% tidyr::separate_rows(hashtags, sep = ", ") %>% tidyr::nest(hashtags = c(hashtags)) tidy_tweets <- all_tweets %>% select(screen_name, mentions_screen_name) %>% tidyr::separate_rows(mentions_screen_name, sep = " ") %>% tidyr::nest(mentions_screen_name = c(mentions_screen_name)) tidy_tweets$mentions_screen_name <- tidy_tweets$mentions_screen_name %>% purrr::map(unlist) %>% purrr::map(unname) tidy_tweets %>% gt_edges(screen_name, mentions_screen_name) %>% gt_nodes() %>% gt_collect() -> gt nodes <- gt$nodes %>% mutate( id = nodes, label = nodes, size = n, color = "#1967be" ) edges <- gt$edges %>% mutate( id = 1:n() ) sigmajs() %>% sg_force_start() %>% sg_nodes(nodes, id, label, size, color) %>% sg_edges(edges, id, source, target) %>% sg_force_stop(10000) %>% sg_drag_nodes() %>% sg_cluster() sigmajs() %>% sg_force_start() %>% sg_nodes(nodes, id, label, size, color) %>% sg_edges(edges, id, source, target) %>% sg_force_stop(10000) #what about comentions? net <- tidy_tweets %>% gt_co_edges(mentions_screen_name) %>% gt_nodes() %>% gt_collect() c(edges, nodes) %<-% net edges <- edges %>% mutate(id = 1:n()) nodes <- nodes %>% mutate( id = nodes, label = id, size = n ) sigmajs() %>% sg_nodes(nodes, id, label, size) %>% sg_edges(edges, id, source, target) %>% sg_cluster( colors = c( "#0084b4", "#00aced", "#1dcaff", "#c0deed" ) ) %>% sg_layout(layout = igraph::layout.fruchterman.reingold) %>% sg_neighbours() %>% sg_settings( maxNodeSize = 3, defaultEdgeColor = "#a3a3a3", edgeColor = "default" ) g %>% gt_edges(screen_name, mentions_screen_name) %>% gt_nodes(meta = TRUE) %>% gt_collect() -> graph ``` belwo is more on the graphTweets etc rom:https://twinetbook.john-coene.com/get-started.html ```{r} net <- tidy_tweets %>% gt_edges(source = screen_name, target = mentions_screen_name) class(net) #To extracts the results from graphTweets run gt_collect, this will work at any point in the chain of pipes (%>%). net <- net %>% gt_collect() #Great but this returns a lists and R users much prefer data.frames. graphTweets actualy returns two data.frames that are encapsulated in a list. Indeed networks cannot be compressed into a single data.frame, we need 1) nodes and 2) edges. names(net) #reat, so it looks like we have both nodes and edges, not really. We only have edges, net$nodes is actually NULL. # hindsights, we only ran gt_edges so it make sense to only have edges. Let’s scrap that and get both nodes and edges. net <- all_tweets %>% gt_edges(screen_name, mentions_screen_name) %>% # get edges gt_nodes() %>% # get nodes gt_collect() # collect lapply(net, class) #unpack netowrk c(edges, nodes) %<-% net head(edges) #each edge simply consists of a source and a target. In this network, the source essentially corresponds to screen_name passed in gt_edges, it is the user who posted the tweet. In contrast, target includes the users that were tagged in the text of the tweet. The n variable indicates how many tweets connect the source to the target. head(nodes) n the nodes data frame, the column n is the number of times the node appears (whether as source or as target), while the nodes column are the Twitter handles of both the authors of the tweets (screen_name) and those who were @tagged in the tweets. All nodes are of type user in this network, but we will have examples later in the book where it may not be. #Below we rename a few columns, to meet sigmajs’ naming convention. #We add ids to our nodes, this can be a string and thus simply corresponds to our nodes column. #We essentially rename n to size as this is what sigmajs understands. #We add ids to our edges as sigmajs requires each edge to have a unique id. nodes$id <- as.factor(nodes$nodes) nodes$size <- nodes$n edges$id <- seq(1, nrow(edges)) #sigmajs has a specific but sensible naming convention as well as basic minimal requirements. #Nodes must at least include id, and size. #Edges must at least include id, source, and target. #Actually, the twinetverse comes with helper functions to prepare the nodes and edges built by graphTweets for use in sigmajs (these are the only functions the ’verse provides). nodes <- nodes2sg(nodes) edges <- edges2sg(edges) #Let’s visualise that, we must initialise every sigmajs graph with the sigmajs function, then we add our nodes with sg_nodes, passing the column names we mentioned previously, id, and size to meet sigmajs’ minimum requirements. In sigmajs, at the exception of the function called sigmajs, all start with sg_ sigmajs() %>% sg_nodes(nodes, id, size) #igmajs actually allows you to build graphs using only nodes or edges, we’ll see why this is useful in a later chapter on temporal graphs. Let’s add the edges. Then again, to meet sigmajs’ requirements, we pass id, source and target. sigmajs() %>% sg_nodes(nodes, id, size) %>% sg_edges(edges, id, source, target) #Nevermind beauty, what’s on the graph exactly? Each disk/point on the graph is a twitter user, they are connected when one has tagged the other in the a tweet. #You may also notice that the graph contains surprisingly few nodes, given that we queried 100 tweets you would expect over 100 nodes on the graph. This is because our visualisation only includes tweets that mention other users and most tweets are not targeted (tagged) at other users. There is an easy remedy to this which we’ll look at in the next section. #compare to sigmajs("webgl") %>% sg_nodes(nodes, id, size) %>% sg_edges(edges, id, source, target) %>% sg_layout(layout = igraph::layout_components) %>% sg_cluster( colors = c( "#0075a0", "#0084b4", "#00aced", "#1dcaff", "#c0deed" ) ) %>% sg_settings( minNodeSize = 1, maxNodeSize = 2.5, edgeColor = "default", defaultEdgeColor = "#d3d3d3" ) ``` to think about. 1. could look at , linking users to the users they retweet to fundamentally visualise how information spreads throughout Twitter.
8572330da025fd0d811d1ac0e28282e29c2abbf0
[ "R", "RMarkdown" ]
6
RMarkdown
MarcKissel/2020_MMM
23dcd456e4e6ae3f63a7413653cdcb89aa7020fe
6bb068e2c6a67ab5af0399b399c4c3f61bc7ec39
refs/heads/master
<repo_name>snowman1985/wjbbwebsite<file_sep>/templates/sellers/container_post.html {%extends "sellers/container_authed.html"%} {%block content%} <div class="container"> <div class="row row-offcanvas-right"> <div class="col-md-8"> <form class="form-horizontal" role="form" action="." method="post" enctype="multipart/form-data" >{% csrf_token %} <div id="legend" class=""> <legend class="">请填写表单</legend> </div> <div class="form-group"> <label class="control-label col-sm-2" for="input_addr">标题:</label> <div class="col-sm-10"> {{form_post.title}} <p class="help-block">请输入您要发布到商业信息的标题。 {% if form_post.title.errors %} {{ form_post.title.errors }} {% endif %} </p> </div> </div> <div class="form-group"> <label class="control-label col-sm-2" for="input_description">商业信息:</label> <div class="col-sm-10"> <div class="textarea"> {{form_post.content}} </div> <p class="help-block">请填写您要发布到商业信息的具体内容。 {% if form_post.content.errors %} {{ form_post.content.errors }} {% endif %} </p> </div> </div> <div class="form-group"> <label class="control-label col-sm-2" for="input_description">图片:</label> <div class="col-sm-10"> {{form_post.photo}} {{form_post.photo1}} <p class="help-block">请上传关于本信息的图片(最多上传3张). {% if form_post.photo.errors %} {{ form_post.photo.errors }} {% endif %} </p> </div> </div> <div class="form-group"> <div class="col-sm-10 col-sm-offset-5"> <button class="btn btn-success" type="submit" name=register>发布信息</button> <a href="/sellers/" class="btn btn-success active" role="button">取消</a> </div> </div> </form> </div> </div> </div> {%endblock%} <file_sep>/sellers/views.py # -*- coding: utf-8 -*- from django.shortcuts import render from django.http import * from django.views.generic import FormView from django.views.generic.base import TemplateView from django.views.generic.edit import FormView, ProcessFormView from django.contrib.auth.models import User from django.contrib.auth import authenticate, login as user_login, logout as user_logout from django import forms from .forms import * from .models import * class HomeView(TemplateView): template_name = 'sellers/home.html' def get_context_data(self, **kwargs): context = super(HomeView, self).get_context_data(**kwargs) ###process login form login_username = self.request.GET.get("login_username") login_password = self.request.GET.get("login_password") if login_username and login_password: login_username = login_username.replace('%40','@') print(login_username, login_password) user = authenticate(username=login_username, password=<PASSWORD>) if user is not None: print(user) if user.is_active: print(user) user_login(self.request, user) context['username_authed'] = login_username context['bpost_count'] = 5 ###process logout form if "logout" in self.request.GET: user_logout(self.request) return context class BListView(TemplateView): template_name = 'sellers/blist.html' def get_context_data(self, **kwargs): context = super(BListView, self).get_context_data(**kwargs) ###process login form login_username = self.request.GET.get("login_username") login_password = self.request.GET.get("login_password") if login_username and login_password: user = authenticate(username=login_username, password=<PASSWORD>) if user is not None: if user.is_active: user_login(self.request, user) context['username_authed'] = login_username ###process logout form if "logout" in self.request.GET: user_logout(self.request) user = self.request.user blist = [] blist = SellerBusiness.objects.filter(seller__username = user.username) context['blist'] = blist return context class RegisterView(FormView): template_name = 'sellers/register.html' form_class = RegisterForm def get_context_data(self, **kwargs): context = super(RegisterView, self).get_context_data(**kwargs) if self.request.method == 'GET': ###process login form login_username = self.request.GET.get("login_username") login_password = self.request.GET.get("login_password") if login_username and login_password: user = authenticate(username=login_username, password=<PASSWORD>) if user is not None: if user.is_active: user_login(self.request, user) context['username_authed'] = login_username ###process logout form if "logout" in self.request.GET: user_logout(self.request) context['form_reg'] = RegisterForm() context['registered'] = False ###process register form if self.request.method == 'POST': form_reg = RegisterForm(self.request.POST) if form_reg.is_valid(): user = User.objects.create(username = form_reg.cleaned_data['email'], password = form_reg.cleaned_data['password'], email = form_reg.cleaned_data['email']) seller = Seller.objects.create() seller.user = user seller.address = form_reg.cleaned_data['address'] seller.description = form_reg.cleaned_data['description'] user.save() seller.save() print(form_reg) context['registered'] = True context['form_reg'] = form_reg context['result_msg'] = '注册成功!' else: print(form_reg) context['form_reg'] = form_reg context['registered'] = False return context def form_valid(self, form): # This method is called when valid form data has been POSTed. # It should return an HttpResponse. ###process register form if self.request.method == 'POST': form_reg = RegisterForm(self.request.POST) if form_reg.is_valid(): username = form_reg.cleaned_data['email'] user = User.objects.create_user(username = username, password = form_reg.cleaned_data['password'], email = form_reg.cleaned_data['email']) seller = Seller.objects.create(user = user) seller.address = form_reg.cleaned_data['address'] seller.description = form_reg.cleaned_data['description'] user.save() seller.save() print(form_reg) else: print(form_reg) return super(RegisterView, self).form_valid(form) class PostView(FormView): template_name = 'sellers/post.html' form_class = PostModelForm def get_context_data(self, **kwargs): context = super(PostView, self).get_context_data(**kwargs) if self.request.method == 'GET': ###process login form login_username = self.request.GET.get("login_username") login_password = self.request.GET.get("login_password") if login_username and login_password: user = authenticate(username=login_username, password=login_password) if user is not None: if user.is_active: user_login(self.request, user) context['username_authed'] = login_username ###process logout form if "logout" in self.request.GET: user_logout(self.request) context['form_post'] = PostModelForm() if self.request.method == 'POST': form_post = PostModelForm(self.request.POST, self.request.FILES) if form_post.is_valid(): temp = form_post.save(commit=False) temp.seller = self.request.user temp.save() else: print(form_post.errors) context['form_post'] = form_post return context def form_valid(self, form): # This method is called when valid form data has been POSTed. # It should return an HttpResponse. ###process register form if self.request.method == 'POST': form_post = PostModelForm(self.request.POST, self.request.FILES) if form_post.is_valid(): temp = form_post.save(commit=False) temp.seller = self.request.user if self.request.FILES: temp.photo = self.request.FILES['photo'] if 'photo1' in list(self.request.FILES): temp.photo1 = self.request.FILES['photo1'] if 'photo2' in list(self.request.FILES): temp.photo2 = self.request.FILES['photo2'] temp.save() #print "form valid post form" else: print(form_post.errors) print("form_post not valid") return super(PostView, self).form_valid(form) <file_sep>/README.md wjbbwebsite =========== enveroment: python3.2.3 django1.6 bootstrap3 postgresql9.3 psycopg2 2.5.1 add garven.shen as contributor <file_sep>/sellers/urls.py ''' Created on Nov 2, 2013 @author: shengeng ''' from django.conf.urls import patterns, url from .views import HomeView, RegisterView, PostView, BListView urlpatterns = patterns('', url(r'^$', HomeView.as_view(), name='home'), url(r'^register/', RegisterView.as_view(success_url='/sellers/'), name='register'), url(r'^post/', PostView.as_view(success_url='/sellers/blist/'), name='post'), url(r'^blist/', BListView.as_view(), name='blist'), )
d6c5ef52aa73421fa5f59e78d9b212b23783bcf0
[ "Markdown", "Python", "HTML" ]
4
HTML
snowman1985/wjbbwebsite
4c533958dd26ace58fb947f059bb9051947a22f6
d520ea5c29c85643926c6102ce80db8e2c5c1151
refs/heads/master
<file_sep><?php // leer bd de preguntas $preguntas = []; try { $preguntas = leer_preguntas(); } catch (Exception $e) { $msg = $e; } function leer_preguntas() { try { $conn = new PDO('mysql:host=localhost;dbname=proyecto_preguntar;port=3306', 'root'); $resultado = $conn->query('SELECT * FROM preguntas ORDER BY time_stamp DESC'); } catch (Exception $e) { throw new Exception("No se ha podido conectar con la base de datos", 1); } finally { $conn = null; } return $resultado; } ?> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Preguntar y Saber</title> <link rel="stylesheet" href="css/style.css"> <script src="https://kit.fontawesome.com/59a2b349ba.js"></script> <link href="https://fonts.googleapis.com/css?family=Roboto:300,400&display=swap" rel="stylesheet"> </head> <body> <!-- header nav --> <header class="header__color"> <div class="logo"><a href="index.html">P<span>&</span>S</a></div> <nav> <ul> <li><a href="index.html#jump_about">about</a></li> <li><a href="crear-cuenta.php">crear cuenta</a></li> <li></li><a href="login.php" class="logIn">iniciar session</a></li> </ul> </nav> </header> <!-- question list --> <div id="main__content__container"> <?php foreach($preguntas as $titulo){ ?> <div class="question"> <img class="question_img" src="img/profile1.png" alt=""> <div class="question_list"> <!-- ######################################## TO DO href =id --> <i class="fas fa-question"></i><a href="pregunta_visit.php?id=<?= $titulo["id_pregunta"]; ?>" class="pregunta"><?= $titulo["titulo"]; ?></a> <span class="time_stamp"><i><?= $titulo["time_stamp"]; ?></i></span> </div> </div> <?php } ?> </div> <div> <a class="question__button" href="crear-cuenta.php">quieres preguntar?<br />crea una cuenta!</a> </div> </body> </html><file_sep><?php function recuperarPregunta(int $id) { try { $conn = new PDO('mysql:host=localhost;dbname=proyecto_preguntar;port=3306', 'root'); $sql = 'SELECT a.apodo, b.titulo, b.pregunta, b.time_stamp FROM usuarios as a inner join preguntas as b on a.id_usuario =' . $id . ' and b.id_pregunta =' .$id; $client = $conn->query($sql); } catch(Exception $e) { throw new Exception("No se ha podido conectar con la base de datos", 1); } finally { $conn = null; } return $client; } function recuperarRespuesta(int $id) { try { $conn = new PDO('mysql:host=localhost;dbname=proyecto_preguntar;port=3306', 'root'); $sql = 'SELECT a.apodo, b.respuesta, b.res_time_stamp FROM usuarios as a, respuestas as b WHERE b.id_pregunta=' .$id. ' AND b.id_usuario = a.id_usuario ORDER BY b.res_time_stamp DESC'; $respuestas = $conn->query($sql); } catch(Exception $e) { throw new Exception("No se ha podido conectar con la base de datos", 1); } finally { $conn = null; } return $respuestas; } ?> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Preguntar y Saber</title> <link rel="stylesheet" href="css/style.css"> <script src="https://kit.fontawesome.com/59a2b349ba.js"></script> <link href="https://fonts.googleapis.com/css?family=Roboto:300,400&display=swap" rel="stylesheet"> </head> <body> <!-- header nav --> <header class="header__color"> <div class="logo"><a href="index.html">P<span>&</span>S</a></div> <nav> <ul> <li><a href="index.html#jump_about">about</a></li> <li><a href="crear-cuenta.php">crear cuenta</a></li> <li></li><a href="login.php" class="logIn">iniciar session</a></li> </ul> </nav> </header> <!-- question list --> <?php if (isset($_GET["id"])) { $client = recuperarPregunta($_GET["id"]); } foreach($client as $datos){ ?> <div id="main__content__container"> <div class="question"> <img class="question_img" src="img/profile1.png" alt=""> <div class="question_list"> <i class="fas fa-question"></i><span class="pregunta"><?= $datos["titulo"]; ?></span> <span class="time_stamp"><i><?= $datos["apodo"]. " / ".$datos["time_stamp"]; ?></i></span> <p class="question_text"><?= $datos["pregunta"]; ?></p> </div> </div> </div> <?php } ?> <?php if (isset($_GET["id"])) { $respuestas = recuperarRespuesta($_GET["id"]); } foreach($respuestas as $resDatos){ ?> <div id="main__content__container" class="answer__box"> <div class="question"> <img class="question_img answer_img" src="img/profile1.png" alt=""> <div class="question_list answer_list"> <i class="fas fa-quote-left"></i><span class="answer_username"><?= $resDatos["apodo"]; ?></span> <span class="time_stamp"><i><?= $resDatos["res_time_stamp"]; ?></i></span> <p class="question_text"><?= $resDatos["respuesta"]; ?></p> </div> </div> </div> <?php } ?> </body> </html><file_sep><?php include 'funciones.php'; // recupIdUsuario() // SESSION START session_start(); // traer dato de pregunta function recuperarPregunta(int $id) { try { $conn = new PDO('mysql:host=localhost;dbname=proyecto_preguntar;port=3306', 'root'); $sql = 'SELECT a.apodo, b.titulo, b.pregunta, b.time_stamp FROM usuarios as a, preguntas as b where id_pregunta='. $id .' and a.id_usuario = b.id_usuario'; $client = $conn->query($sql); } catch(Exception $e) { throw new Exception("No se ha podido conectar con la base de datos", 1); } finally { $conn = null; } return $client; } // traer datos de respuestas function recuperarRespuesta(int $id) { try { $conn = new PDO('mysql:host=localhost;dbname=proyecto_preguntar;port=3306', 'root'); $sql = 'SELECT a.apodo, b.respuesta, b.res_time_stamp FROM usuarios as a, respuestas as b WHERE b.id_pregunta=' .$id. ' AND b.id_usuario = a.id_usuario ORDER BY b.res_time_stamp DESC'; $respuestas = $conn->query($sql); } catch(Exception $e) { throw new Exception("No se ha podido conectar con la base de datos", 1); } finally { $conn = null; } return $respuestas; } // enviar respuesta a BD function registrarRespuesta(array $data) { $myRespuesta = $data["myRespuesta"]; $idUsuario = intval(recupIdUsuario($_SESSION["apodo"])); $idPregunta = $_GET["id"]; $timeStamp = date("Y-m-d"); try { $conn = new PDO('mysql:host=localhost;dbname=proyecto_preguntar;port=3306', 'root'); $sql = "INSERT INTO respuestas (respuesta, id_usuario, id_pregunta, res_time_stamp) VALUES (" . "'" . $myRespuesta ."'" . ", " . $idUsuario . ", " . $idPregunta . ", " . "'" . $timeStamp . "')"; $regiRespuesta = $conn->prepare($sql); $regiRespuesta->execute(); } catch(Exception $e) { throw new Exception("No se ha podido conectar con la base de datos", 1); } finally { $conn = null; } return $regiRespuesta; } ?> <!DOCTYPE html> <html lang="es"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Preguntar y Saber</title> <link rel="stylesheet" href="css/style.css"> <link rel="stylesheet" href="css/answer_form.css"> <script src="https://kit.fontawesome.com/59a2b349ba.js"></script> <link href="https://fonts.googleapis.com/css?family=Roboto:300,400&display=swap" rel="stylesheet"> </head> <body> <!-- header nav --> <header class="header__color"> <div class="logo"><a href="index_session.php">P<span>&</span>S</a></div> <nav> <ul> <li><a href="index_session.php#jump_about">about</a></li> <li><a href="user_info.php?id=<?php intval(recupIdUsuario($_SESSION["apodo"])) ?>"> <?php echo "Hola! <span class=\"welcome_name\">".$_SESSION["apodo"]."</span>"; ?> </a></li> <li><a href="logout.php"><i class="fas fa-power-off"></i></a></li> </li><a href="preguntar.php" class="logIn">PREGUNTAR</a></li> </ul> </nav> </header> <!-- lista de pregunta --> <?php if (isset($_GET["id"])) { $client = recuperarPregunta($_GET["id"]); } foreach($client as $datos){ ?> <div id="main__content__container"> <div class="question"> <img class="question_img" src="./img/question.png" alt=""> <div class="question_list"> <span class="pregunta"><?= $datos["titulo"]; ?></span> <span class="time_stamp"><i><?= $datos["apodo"]. " / ".$datos["time_stamp"]; ?></i></span> <p class="question_text"><?= $datos["pregunta"]; ?></p> </div> </div> </div> <?php } ?> <!-- formulario respuesta --> <div class="answer_textarea"> <form class="answer_form" action="" method="POST"> <textarea class="answer_area" name="myRespuesta" cols="30" rows="10" placeholder="Dale tu Respuesta"></textarea> <input class="answer_submitBtn" type="submit" name="submit" value="RESPONDER" /> </form> <?php if(isset($_POST["submit"])) { registrarRespuesta($_POST); // TODO: POST valor check } ?> </div> <!-- enlace para volver a la lista --> <div class="back_to_list"><a href="main.php"><i class="fas fa-share"></i> Volver a la lista</a></div> <!-- pintar respuestas --> <?php if (isset($_GET["id"])) { $respuestas = recuperarRespuesta($_GET["id"]); if($respuestas != null) { foreach($respuestas as $resDatos){ ?> <div id="main__content__container" class="answer__box"> <div class="question"> <img class="question_img answer_img" src="./img/answer.png" alt=""> <div class="question_list answer_list"> <span class="answer_username"><?= $resDatos["apodo"]; ?></span> <span class="time_stamp"><i><?= $resDatos["res_time_stamp"]; ?></i></span> <p class="question_text"><?= htmlentities($resDatos["respuesta"], ENT_QUOTES, "UTF-8"); ?></p> </div> </div> </div> <?php } }else { return false; } } ?> </body> </html><file_sep><i class="fas fa-question"></i> <i class="fas fa-quote-left"><file_sep># php-project php-project(DB) for exam. question and answer. <file_sep><?php session_start(); session_destroy(); ?> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Preguntar y Saber</title> <script src="https://kit.fontawesome.com/59a2b349ba.js"></script> <link rel="stylesheet" href="./css/style.css"> <link href="https://fonts.googleapis.com/css?family=Roboto:300,400&display=swap" rel="stylesheet"> </head> <body> <header class="header__color"> <div class="logo"><a href="index.html">P<span>&</span>S</a></div> <nav> <ul> <li><a href="index.html#jump_about">about</a></li> <li><a href="crear-cuenta.php">crear cuenta</a></li> <li><a href="login.php" class="logIn">iniciar session</a></li> </ul> </nav> </header> <section class="updated"> <img src="img/undraw_post_online_dkuk.svg" alt=""> <p class="success"> Se han guardado tus datos nuevos.<br /> Por favor reinicia sesion. </p> <a href="login.php">iniciar sesion</a> </section> </body> </html><file_sep><?php // SESSION START ($_SESSION["apodo"];) session_start(); // leer bd de preguntas $preguntas = []; try { $preguntas = leer_preguntas(); } catch (Exception $e) { $msg = $e; } function leer_preguntas() { try { $conn = new PDO('mysql:host=localhost;dbname=proyecto_preguntar;port=3306', 'root'); $resultado = $conn->query('SELECT a.apodo, b.* FROM usuarios as a, preguntas as b WHERE b.id_usuario = a.id_usuario ORDER BY b.time_stamp DESC;'); } catch (Exception $e) { throw new Exception("No se ha podido conectar con la base de datos", 1); } finally { $conn = null; } return $resultado; } // recuperar id_usuario de apodo function recupIdUsuario(string $apodo) { try { $conn = new PDO('mysql:host=localhost;dbname=proyecto_preguntar;port=3306', 'root'); $sql = "SELECT id_usuario, apodo FROM usuarios WHERE apodo="."'".$apodo."'"; $getUserId = $conn->prepare($sql); $getUserId->execute(); foreach($getUserId as $value){ $result = $value["id_usuario"]; } } catch(Exception $e) { throw new Exception("No se ha podido conectar con la base de datos", 1); } finally { $conn = null; } return $result; } $getUserNumber = intval(recupIdUsuario($_SESSION["apodo"])); ?> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Preguntar y Saber</title> <link rel="stylesheet" href="css/style.css"> <script src="https://kit.fontawesome.com/59a2b349ba.js"></script> <link href="https://fonts.googleapis.com/css?family=Roboto:300,400&display=swap" rel="stylesheet"> </head> <body> <!-- header nav --> <header class="header__color"> <div class="logo"><a href="index_session.php">P<span>&</span>S</a></div> <nav> <ul> <li><a href="index_session.php#jump_about">about</a></li> <li class="to_user_info"> <a href="user_info.php?id=<?php $getUserNumber; ?>"> <?php echo "Hola! <span class=\"welcome_name\">".$_SESSION["apodo"]."</span>"; ?> </a> </li> <li><a href="logout.php"><i class="fas fa-power-off"></i></a></li> </li><a href="preguntar.php" class="logIn">PREGUNTAR</a></li> </ul> </nav> </header> <!-- question list --> <div id="main__content__container"> <?php foreach($preguntas as $titulo){ ?> <div class="question"> <img class="question_img" src="./img/question.png" alt=""> <div class="question_list"> <a href="main_pregunta.php?id=<?= $titulo["id_pregunta"]; ?>" class="pregunta"><?= $titulo["titulo"]; ?></a> <span class="time_stamp"><i><?= $titulo["apodo"].' / '.$titulo["time_stamp"]; ?></i></span> </div> </div> <?php } ?> </div> <!-- <div> <a class="question__button" href="">preguntar!</a> </div> --> </body> </html><file_sep><?php $msg = ""; $msgClass = ""; // SESSION if (isset($_POST["submit"])) { if (isLoginValid($_POST)) { if(existeUsuario($_POST)) { session_start(); $_SESSION["autenticado"] = TRUE; $_SESSION["apodo"] = $_POST["username"]; header("Location: main.php"); } } else { $msgClass = "error"; $msg = "Debe introducir el usuario y la contraseña."; } } // check login string function isLoginValid($login) { foreach ($login as $value) { if ($value == "") return false; } return true; } // buscando user dato en BD function existeUsuario($user) { $usuarios = []; try { $conn = new PDO('mysql:host=localhost;dbname=proyecto_preguntar;port=3306', 'root'); $usuarios = $conn->prepare('SELECT * from usuarios WHERE apodo=' . '"'.$user["username"].'"'); $usuarios->execute(); } catch (PDOException $e) { print "¡Error!: " . $e->getMessage() . "<br/>"; } finally { $conn = null; } // no hace falta foreach, check later foreach ($usuarios as $usuario) { if ($usuario["apodo"] == $user["username"] AND password_verify($user["password"], $usuario["passwd"]) == $user["password"]) { return true; } } return false; } ?> <!DOCTYPE html> <html lang="es"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Log-in</title> <link rel="stylesheet" href="css/style.css"> <script src="https://kit.fontawesome.com/59a2b349ba.js"></script> <link href="https://fonts.googleapis.com/css?family=Roboto:300,400&display=swap" rel="stylesheet"> </head> <body> <!-- header nav --> <header class="header__color"> <div class="logo"><a href="index.html">P<span>&</span>S</a></div> <nav> <ul> <li><a href="index.html#jump_about">about</a></li> <li><a href="crear-cuenta.php">crear cuenta</a></li> <li></li><a href="login.php" class="logIn">iniciar session</a></li> </ul> </nav> </header> <!-- login FORM --> <form id="form__login" action="" method="POST"> <h2>iniciar session</h2> <input type="text" name="username" placeholder="Nombre Usuario" required autofocus /> <input type="<PASSWORD>" name="<PASSWORD>" placeholder="<PASSWORD>" required /> <input type="submit" name="submit" value="LOG IN" /> <div><?php echo $msg ?></div> <div>No tienes cuenta? <a href="crear-cuenta.php">crear cuenta</a></div> </form> </body> </html><file_sep><?php $msg_err = ''; if(isset($_POST["submit"])) { if (!isClientValid($_POST)) { $msg_err = "Falta algún dato. Revísalo."; } else { $pass_code = password_hash($_POST["password"], PASSWORD_DEFAULT); $_POST["password"] = $pass_code; $ok = guardar_usuario($_POST); if ($ok) { $msg_err = "Bienvenido ".$_POST["username"]; // echo $pass_code; // header("Location: login.php"); } else { $msg_err = "No se ha podido guardar el cliente."; } } } // check validad de campo function isClientValid(array $usuario) { foreach ($usuario as $campo) { if ($campo == "") return false; } return true; } // guardar en BD function guardar_usuario(array $usuario) { $ok = false; try { $conn = new PDO('mysql:host=localhost;dbname=proyecto_preguntar;port=3306', 'root'); $sql = 'INSERT INTO usuarios (apodo, passwd, rol) VALUES (' . '"'.$usuario["username"].'"'.', ' . '"'.$usuario["password"].'"'.', ' . '"usuario"' . ')'; $resultado = $conn->prepare($sql); $resultado->execute(); if ($resultado) { $ok = true; } else { $ok = false; } } catch (PDOException $e) { print "¡Error!: " . $e->getMessage() . "<br/>"; } finally { $conn = null; } return $ok; } ?> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Sign-in</title> <link rel="stylesheet" href="css/style.css"> <script src="https://kit.fontawesome.com/59a2b349ba.js"></script> <link href="https://fonts.googleapis.com/css?family=Roboto:300,400&display=swap" rel="stylesheet"> </head> <body> <!-- header nav --> <header class="header__color"> <div class="logo"><a href="index.html">P<span>&</span>S</a></div> <nav> <ul> <li><a href="#">about</a></li> <li><a href="#">crear cuenta</a></li> <li></li><a href="login.php" class="logIn">iniciar session</a></li> </ul> </nav> </header> <!-- login FORM --> <form id="form__login" action="" method="POST"> <h2>crear cuenta</h2> <input type="text" name="username" placeholder="Nombre Usuario" autofocus /> <input type="<PASSWORD>" name="password" placeholder="<PASSWORD>" /> <input type="submit" name="submit" value="CREAR" /> <div class="bienvenido"><?php echo $msg_err; ?> <a href="login.php"> Iniciar session</a></div> </form> </body> </html><file_sep><?php include 'funciones.php'; // recupIdUsuario() // SESSION START session_start(); // insert datos de pregunta a DB $sendMsg = ''; if(isset($_POST["submit"])) { $titulo = $_POST["questionTitle"]; $question = $_POST["questionText"]; try { $conn = new PDO('mysql:host=localhost;dbname=proyecto_preguntar;port=3306', 'root'); $idUser = recupIdUsuario($_SESSION["apodo"]); $timeStamp = date("Y-m-d"); $sql = "INSERT INTO preguntas (titulo, pregunta, id_usuario, time_stamp) VALUES ("."'".$titulo."'".", "."'".$question."'".", ".$idUser.", "."'".$timeStamp."'".")"; $regiPregunta = $conn->prepare($sql); $regiPregunta->execute(); $sendMsg = 'Pregunta esta registrado. '; // var_dump($sql); } catch (Exception $e) { throw new Exception("No se ha podido conectar con la base de datos", 1); } finally { $conn = null; } } ?> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Preguntar</title> <link rel="stylesheet" href="css/style.css"> <link rel="stylesheet" href="css/pregunta.css"> <script src="https://kit.fontawesome.com/59a2b349ba.js"></script> <link href="https://fonts.googleapis.com/css?family=Roboto:300,400&display=swap" rel="stylesheet"> </head> <body> <!-- header nav --> <header class="header__color"> <div class="logo"><a href="index_session.php">P<span>&</span>S</a></div> <nav> <ul> <li><a href="index_session.php#jump_about">about</a></li> <li><a href="user_info.php"> <?php echo "Hola! <span class=\"welcome_name\">".$_SESSION["apodo"]."</span>"; ?> </a></li> <li><a href=""><i class="fas fa-power-off"></i></a></li> </li><a href="preguntar.php" class="logIn">PREGUNTAR</a></li> </ul> </nav> </header> <!-- question FORM --> <form id="form__question" action="" method="POST"> <h2>PREGUNTAR</h2> <input type="text" name="questionTitle" placeholder="Titulo" required /> <textarea name="questionText" id="" cols="30" rows="10" placeholder="Pregunta aqui.." required></textarea> <input type="submit" name="submit" value="PREGUNTAR" /> <div class="sendMsg"> <?php echo $sendMsg; ?><a href="main.php">Volver a la lista</a> </div> </form> </body> </html><file_sep><?php include 'funciones.php'; // recupIdUsuario() // SESSION START session_start(); // $_POST submit if(isset($_POST["submit"])) { if(isDatosValid($_POST)) { updateUserInfo($_POST); header('Location: updated.php'); } } // check login string function isDatosValid($login) { foreach ($login as $value) { if ($value == "") return false; } return true; } // UPDATE info de usuario function updateUserInfo(array $post) { $getUserId = intval(recupIdUsuario($_SESSION["apodo"])); $pwdHash = password_hash($post["updatePwd"], PASSWORD_DEFAULT); try { $conn = new PDO('mysql:host=localhost;dbname=proyecto_preguntar;port=3306', 'root'); $sql = "UPDATE usuarios SET apodo="."'".$post["updateName"]."', " ."passwd=" ."'".$<PASSWORD>."'"." WHERE id_usuario=". $getUserId; $getUserId = $conn->prepare($sql); $getUserId->execute(); } catch(Exception $e) { throw new Exception("No se ha podido conectar con la base de datos", 1); } finally { $conn = null; } // return $result; } ?> <!DOCTYPE html> <html lang="es"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Preguntar y Saber</title> <link rel="stylesheet" href="css/style.css"> <link rel="stylesheet" href="css/user_info.css"> <script src="https://kit.fontawesome.com/59a2b349ba.js"></script> <link href="https://fonts.googleapis.com/css?family=Roboto:300,400&display=swap" rel="stylesheet"> </head> <body> <!-- header nav --> <header class="header__color"> <div class="logo"><a href="index_session.php">P<span>&</span>S</a></div> <nav> <ul> <li><a href="index_session.php#jump_about">about</a></li> <li><a href=""> <?php echo "Hola! <span class=\"welcome_name\">".$_SESSION["apodo"]."</span>"; ?> </a></li> <li><a href="logout.php"><i class="fas fa-power-off"></i></a></li> </li><a href="preguntar.php" class="logIn">PREGUNTAR</a></li> </ul> </nav> </header> <!-- main session --> <div class="user_info_container"> <h2><?php echo "Hola ".$_SESSION["apodo"]; ?></h2> <div class="user_info_menuBox"> <div class="menu_detail"> <a href="ver_mis_preguntas.php"><i class="fas fa-question"></i></a> <p>Ver mis preguntas</p> </div> <div class="menu_detail"> <a href="ver_mis_respuestas.php"><i class="fas fa-check"></i></a> <p>Ver mis respuestas</p> </div> </div> </div> <form action="" class="user_info_profile_update" method="POST"> <h2>update perfil</h2> <input type="text" name="updateName" placeholder="Nuevo Apodo" required /> <input type="password" name="updatePwd" placeholder="<PASSWORD>" required /> <input type="submit" name="submit" value="UPDATE" /> <!-- <div><?php echo $updateMsg; ?></div> --> </form> <div class="back_to_list"><a href="main.php"><i class="fas fa-share"></i> Volver a la lista</a></div> </body> </html><file_sep><?php // SESSION CONNECTED ($_SESSION["apodo"];) session_start(); ?> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Preguntar y Saber</title> <script src="https://kit.fontawesome.com/59a2b349ba.js"></script> <link rel="stylesheet" href="./css/style.css"> <link href="https://fonts.googleapis.com/css?family=Roboto:300,400&display=swap" rel="stylesheet"> </head> <body> <!-- header, navbar --> <div id="index__container"> <header> <div class="logo"><a href="#">P<span>&</span>S</a></div> <nav> <ul> <li><a href="#jump_about">about</a></li> <li><a href="user_info.php"> <?php echo "Hola! <span class=\"welcome_name\">".$_SESSION["apodo"]."</span>"; ?> </a></li> <li><a href="logout.php"><i class="fas fa-power-off"></i></a></li> </li><a href="preguntar.php" class="logIn">PREGUNTAR</a></li> </ul> </nav> </header> <!-- main section --> <main id="container"> <div class="main__text"> <h2>preguntar <span>&</span> saber</h2> <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Maiores, perferendis.</p> <div class="main__text__visit"><a href="main.php">Entrar</a></div> </div> </main> <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1200 179"><path class="cls-1" d="M0,0S132,107,502,107c0,0,512-10,698,72H0Z"/></svg> </div> <!-- about section --> <div id="jump_about" class="about"> <div class="about__left"> <h3><span>#</span> about</h3> <p>Lorem ipsum dolor, sit amet consectetur adipisicing elit. Sequi ipsum distinctio illum adipisci est eveniet explicabo incidunt accusantium vero, totam perspiciatis dolor quis, quam nihil at ab. Porro ex laudantium in rem, quibusdam perferendis optio delectus cupiditate placeat voluptas voluptatem hic fuga voluptatibus? Culpa non dolorem perspiciatis asperiores distinctio! Est.</p> </div> <div class="about__right"> <img src="img/undraw_portfolio_update_nqhs.svg" alt=""> </div> </div> <!-- footer --> <footer> <div class="footer__text"> Este proyecto para el examen de PHP. 2019. </div> <div class="footer__social"> <a href="https://github.com/chriskwork/php-project" target="_blank" title="puedes ver codigo aquí"><i class="fab fa-github"></i></a> </div> </footer> </body> </html><file_sep><?php // coger id_usuario con apodo function recupIdUsuario(string $apodo) { try { $conn = new PDO('mysql:host=localhost;dbname=proyecto_preguntar;port=3306', 'root'); $sql = "SELECT id_usuario, apodo FROM usuarios WHERE apodo="."'".$apodo."'"; $getUserId = $conn->query($sql); foreach($getUserId as $value){ $result = $value["id_usuario"]; } } catch(Exception $e) { throw new Exception("No se ha podido conectar con la base de datos", 1); } finally { $conn = null; } return $result; } ?><file_sep>-- phpMyAdmin SQL Dump -- version 4.8.5 -- https://www.phpmyadmin.net/ -- -- Servidor: 127.0.0.1 -- Tiempo de generación: 25-06-2019 a las 07:24:52 -- Versión del servidor: 10.1.38-MariaDB -- Versión de PHP: 7.3.2 SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO"; SET AUTOCOMMIT = 0; START TRANSACTION; SET time_zone = "+00:00"; /*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */; /*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */; /*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */; /*!40101 SET NAMES utf8mb4 */; -- -- Base de datos: `proyecto_preguntar` -- -- -------------------------------------------------------- -- -- Estructura de tabla para la tabla `preguntas` -- CREATE TABLE `preguntas` ( `id_pregunta` int(11) NOT NULL, `titulo` varchar(150) NOT NULL, `pregunta` text NOT NULL, `id_usuario` int(11) NOT NULL, `time_stamp` date NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8; -- -- Volcado de datos para la tabla `preguntas` -- INSERT INTO `preguntas` (`id_pregunta`, `titulo`, `pregunta`, `id_usuario`, `time_stamp`) VALUES (1, 'que app de tiempo usais?', 'estoy buscando un app del tiempo pero no se cual es buena jaja ayudadme!', 1, '2019-05-07'), (2, 'video juego..', 'que rollo estos dias, recomendadme un video juego chulo', 4, '2019-05-09'), (3, 'para viajar japon', 'cuanto dinero necesitara? para viajar durante un mes. como poco de todas formas', 2, '2019-05-15'), (4, 'productos de Apple', 'por que es tan caro todo? que me lo explique alguien porfa', 5, '2019-05-18'), (5, 'aprender coreano', 'vale la pena aprender coreano?', 6, '2019-06-01'), (6, 'tortilla de patata', 'receta por favor', 7, '2019-06-02'), (7, 'corte ingles??', 'por que es corte ingles? en vez de utilizar otro pais?', 10, '2019-06-07'), (11, 'Gracias!', 'esto es un proyecto sencillo pero me ha costado bastante! sin embargo he aprendido muchas cosas. gracias.', 21, '2019-06-25'); -- -------------------------------------------------------- -- -- Estructura de tabla para la tabla `respuestas` -- CREATE TABLE `respuestas` ( `id_respuesta` int(11) NOT NULL, `respuesta` text NOT NULL, `id_usuario` int(11) NOT NULL, `id_pregunta` int(11) NOT NULL, `res_time_stamp` date NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8; -- -- Volcado de datos para la tabla `respuestas` -- INSERT INTO `respuestas` (`id_respuesta`, `respuesta`, `id_usuario`, `id_pregunta`, `res_time_stamp`) VALUES (1, 'una app basica en movil, no esta mal', 4, 1, '2019-05-07'), (2, 'puedes buscarlo en la app store :D', 1, 1, '2019-05-08'), (3, 'depende de que genero prefieras.', 10, 2, '2019-05-09'), (4, 'para un mes,, si que necesitaras bastante pasta. 2000 mas o menos?', 2, 3, '2019-05-15'), (5, '3000 total. incluso billete de avion y todo', 1, 3, '2019-05-16'), (6, 'preguntaselo a Tim...', 5, 4, '2019-05-18'), (7, 'si te gusta la cultura de corea, claro que si', 3, 5, '2019-06-01'), (8, 'por supuestooooo estoy aprendiendolo y es muy interesante :)', 2, 5, '2019-06-02'), (9, 'aki no es gugle', 9, 6, '2019-06-02'), (10, '<PASSWORD>', 6, 6, '2019-06-03'), (11, 'nunca lo habia pensado @@', 7, 7, '2019-06-07'), (12, 'pero si fuera corte españa suena fatal no?', 2, 7, '2019-06-08'), (13, 'answer test // me gustaria meter mas funciones', 21, 11, '2019-06-25'), (14, 'https://youtu.be/pvlkYYdIBV0', 21, 6, '2019-06-25'); -- -------------------------------------------------------- -- -- Estructura de tabla para la tabla `usuarios` -- CREATE TABLE `usuarios` ( `id_usuario` int(11) NOT NULL, `apodo` varchar(20) NOT NULL, `passwd` varchar(100) NOT NULL, `rol` varchar(10) NOT NULL DEFAULT 'usuario' ) ENGINE=InnoDB DEFAULT CHARSET=utf8; -- -- Volcado de datos para la tabla `usuarios` -- INSERT INTO `usuarios` (`id_usuario`, `apodo`, `passwd`, `rol`) VALUES (1, 'answerking', '123456', 'usuario'), (2, 'virusi', 'y123456', 'usuario'), (3, 'yoshi33', 'killmario55', 'usuario'), (4, 'prgntame', '6600tt', 'usuario'), (5, 'wolverine', 'xmenhola', 'usuario'), (6, 'meibe01', 'ddongzu00', 'usuario'), (7, 'icecream', 'milk12345', 'usuario'), (8, 'keyboardwrir', '01010101', 'usuario'), (9, 'skynet00', 'killhuman123', 'usuario'), (10, 'originalx', 'user00000', 'usuario'), (13, 'vairusi', '0000', 'usuario'), (21, 'alga', '$2y$10$J1yfJECTajzKEDPiOc9.xOlfg3sQgNMFwq/Ih1xecNfXi8/tGsZd6', 'usuario'), (22, 'hellokitty', '$2y$10$w6udSIvK2qd7rwpYz84k4edsp.XaXCeWyk91KrDChxkhtMrF3IvrK', 'usuario'); -- -- Índices para tablas volcadas -- -- -- Indices de la tabla `preguntas` -- ALTER TABLE `preguntas` ADD PRIMARY KEY (`id_pregunta`), ADD KEY `id_usuario` (`id_usuario`) USING BTREE; -- -- Indices de la tabla `respuestas` -- ALTER TABLE `respuestas` ADD PRIMARY KEY (`id_respuesta`), ADD KEY `id_pregunta` (`id_pregunta`) USING BTREE, ADD KEY `id_usuario` (`id_usuario`) USING BTREE; -- -- Indices de la tabla `usuarios` -- ALTER TABLE `usuarios` ADD PRIMARY KEY (`id_usuario`); -- -- AUTO_INCREMENT de las tablas volcadas -- -- -- AUTO_INCREMENT de la tabla `preguntas` -- ALTER TABLE `preguntas` MODIFY `id_pregunta` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=19; -- -- AUTO_INCREMENT de la tabla `respuestas` -- ALTER TABLE `respuestas` MODIFY `id_respuesta` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=15; -- -- AUTO_INCREMENT de la tabla `usuarios` -- ALTER TABLE `usuarios` MODIFY `id_usuario` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=23; -- -- Restricciones para tablas volcadas -- -- -- Filtros para la tabla `preguntas` -- ALTER TABLE `preguntas` ADD CONSTRAINT `preguntas_ibfk_1` FOREIGN KEY (`id_usuario`) REFERENCES `usuarios` (`id_usuario`); -- -- Filtros para la tabla `respuestas` -- ALTER TABLE `respuestas` ADD CONSTRAINT `respuestas_ibfk_1` FOREIGN KEY (`id_usuario`) REFERENCES `usuarios` (`id_usuario`), ADD CONSTRAINT `respuestas_ibfk_2` FOREIGN KEY (`id_pregunta`) REFERENCES `preguntas` (`id_pregunta`); COMMIT; /*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */; /*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */; /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */; <file_sep><?php session_start(); // if (!(isset($_SESSION) && $_SESSION["autenticado"])) { // header("Location: 24-sesiones.php"); // } session_destroy(); header("Location: index.html"); ?><file_sep><?php include 'funciones.php'; // recupIdUsuario() // SESSION START session_start(); // traer preguntas de este usuario function mis_preguntas() { try { $getUserId = intval(recupIdUsuario($_SESSION["apodo"])); $conn = new PDO('mysql:host=localhost;dbname=proyecto_preguntar;port=3306', 'root'); $resultado = $conn->query("SELECT id_pregunta, titulo, time_stamp FROM preguntas WHERE id_usuario = " .$getUserId. " ORDER BY time_stamp DESC"); // var_dump($resultado); } catch (Exception $e) { throw new Exception("No se ha podido conectar con la base de datos", 1); } finally { $conn = null; } return $resultado; } ?> <!DOCTYPE html> <html lang="es"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Preguntar y Saber</title> <link rel="stylesheet" href="css/style.css"> <link rel="stylesheet" href="css/user_info.css"> <script src="https://kit.fontawesome.com/59a2b349ba.js"></script> <link href="https://fonts.googleapis.com/css?family=Roboto:300,400&display=swap" rel="stylesheet"> </head> <body> <!-- header nav --> <header class="header__color"> <div class="logo"><a href="index_session.php">P<span>&</span>S</a></div> <nav> <ul> <li><a href="index.html#jump_about">about</a></li> <li><a href="user_info.php"> <?php echo "Hola! <span class=\"welcome_name\">".$_SESSION["apodo"]."</span>"; ?> </a></li> <li><a href="logout.php"><i class="fas fa-power-off"></i></a></li> </li><a href="preguntar.php" class="logIn">PREGUNTAR</a></li> </ul> </nav> </header> <!-- main session --> <div class="user_info_container"> <h2>Mis Preguntas</h2> <div class="list_my_data"> <?php $misPreguntas = mis_preguntas(); foreach($misPreguntas as $value){ ?> <div class="question"> <!-- <img class="question_img" src="img/profile1.png" alt=""> --> <div class="question_list"> <i class="fas fa-question"></i><a href="main_pregunta.php?id=<?= $value["id_pregunta"]; ?>" class="pregunta" title="Ver la pregunta"><?= $value["titulo"]; ?></a> <span class="time_stamp"><i><?= $value["time_stamp"]; ?></i></span> </div> </div> <?php } ?> </div> </div> <div class="back_to_list"><a href="main.php"><i class="fas fa-share"></i> Volver a la lista</a></div> </body> </html>
ae67cdd0e581a9208877c54f6426f1a7b5698578
[ "Markdown", "SQL", "Text", "PHP" ]
16
PHP
chriskwork/php-project
43aaa679af6d2b91ef3580918fd4d78f63845dc9
b982affef819191ac464624deda300289e5e4499
refs/heads/master
<repo_name>caradubdub/fakenews<file_sep>/main.js //objective: create a chrome extension that evaluates the reliability of websites presented in a google search //parameters for the evaluation will be url, date, check if there is an author, number of sites linking to it, //how to present this info to the user? this website is reliable/ url 9/10 date 8/10 author ? Bias: //h3 selector is LC20LB DKV0Md //get the search result URLs from the page //perform some evaluation on them //append a message to the matching search result heading. //https://www.allsides.com/media-bias/media-bias-ratings //https://mediabiasfactcheck.com/conspiracy/ let news = { 'abcnews': { lean: 'Lean Left', trust: 3 }, 'alternet': { lean: 'Left', trust: 1 }, 'apnews': { lean: 'Lean Left', trust: 2 }, 'ap.org': { lean: 'Center', trust: 3 }, 'bbc': { lean: 'Center', trust: 3 }, 'bloomberg': { lean: 'Lean Left', trust: 3 }, 'cbs': { lean: 'Lean Left', trust: 3 }, 'cnn': { lean: 'Lean Left', trust: 3 }, 'dailymail.co.uk': { lean: 'Right', trust: 3 }, 'foodbabe': { lean: 'Pseudoscience/Conspiracy', trust: 0 }, 'forbes': { lean: 'Center', trust: 3 }, 'foxnews': { lean: 'Lean Right', trust: 3 }, 'huffpost': { lean: 'Left', trust: 3 }, 'msnbc': { lean: 'Left', trust: 3 }, 'nbcnews': { lean: 'Lean Left', trust: 3 }, 'npr': { lean: 'Center', trust: 3 }, 'nypost': { lean: 'Lean Right', trust: 3 }, 'nytimes': { lean: 'Lean Left', trust: 3 }, 'reuters': { lean: 'Center', trust: 3 }, 'thehill': { lean: 'Center', trust: 3 }, 'wsj': { lean: 'Center', trust: 3 }, 'washingtonpost': { lean: 'Lean Left', trust: 3 } } let div = document.querySelectorAll('.g'); let divs = []; div.forEach(el => { if (el.className != 'g kno-kp mnr-c g-blk') { divs.push(el) } }) //contains the full html of div // innerHTML contains HTML of element (ie h2) i think // for (let node in divs) { // console.log(divs[node].outerHTML) // } // //gets only nodes that have titles // for (let node in divs) { // if ((divs[node].innerText).length > 0) { // console.log(divs[node]) // } // } // // and gets the urls // for (let node in divs) { // if ((divs[node].innerText).length > 0) { // console.log(divs[node].querySelector("a").href) // } // } const getURLS = () => { let arr = []; for (let node in divs) { if (((divs[node].innerHTML) != undefined)) { if ((divs[node].innerHTML).includes('LC20lb DKV0Md')) { arr.push(divs[node].querySelector("a").href) } } } return arr } let urls = getURLS(); //console.log(urls) //if (((divs[node].innerHTML) != undefined) && !(divs[node].innerText).includes("People also ask")) { let titles = document.getElementsByClassName('LC20lb DKV0Md'); //'yuRUbf' //console.log(titles) for (let i in titles) { //if ((titles[i].innerText).length > 0) { let domain = urls[i].split('/').slice(0, 3).join('/'); let trustcount = 0; let source = 'not known'; let name = domain.split(".").slice(-2, -1) if (name == "google") { //do we still need this? i++; continue; } console.log(domain, trustcount, name) //if url contains .org or .edu if (urls[i].includes('.org') || urls[i].includes('.edu') || urls[i].includes('.gov') || urls[i].includes('.int')) { trustcount += 2; } if (urls[i].includes('https')) { trustcount += 1; } if (urls[i].includes('.com')) { trustcount += 1; } if (news[name] != undefined) { //console.log(name) source = news[name].lean; //console.log(news[name].trust) trustcount += news[name].trust; // console.log('after adding', trustcount) } // for (let key in news) { // if (domain.includes(key)) { // console.log(domain) // source = news[key].lean; // console.log(news[key].trust) // trustcount += news[key].trust; // console.log('after adding', trustcount) // break; // } // } // create get request to check links to domain fetch(`${urls[i]}`) .then((response) => (response.text())) .then(data => console.log(data)) .catch(error => { console.log(error) }) // function displayData(data) { // console.log(data.text()) // } // let listOfScripts = document.getElementsByTagName('script'); // console.log(listOfScripts) // console.log(listOfScripts.length) // console.log(typeof listOfScripts) // let importantInformation; // // loop through the script elements to find ones with the type 'application/ld+json' which has the information we need // for (let i = 0; i < listOfScripts.length; i++) { // if (listOfScripts[i].type === 'application/ld+json') { // console.log(listOfScripts[i]) // // //assign the variable with the content from the script that we want and JSON.parse it to convert it from a string to an object // // importantInformation = JSON.parse(listOfScripts[i].innerHTML); // // } // // } // // for example, we can now pull the author information // //console.log(importantInformation.creator); // } // } // } // .then(function (response) { // switch (response.status) { // // status "OK" // case 200: // return response.text(); // // status "Not Found" // case 404: // throw response; // } // }) // .then(function (data) { // console.log(data); // }) // .catch(function (response) { // // "Not Found" // console.log(response.statusText); // }); let mess = document.createElement('span') mess.style.fontSize = '1em' mess.id = 'span' + i; mess.style.border = "1px solid black"; mess.removeAttribute('href'); mess.style.textDecoration = "none"; //console.log('before computing', trustcount) if (trustcount <= 1) { mess.style.color = 'red'; mess.innerText = `Quality: Uncertain; Source bias: ${urls[i], source}`; } if (trustcount === 2) { mess.style.color = 'orange'; mess.innerText = `Quality: OK; Source bias: ${urls[i], source}`; } if (trustcount > 2) { mess.style.color = 'darkgreen'; mess.innerText = `Quality: Good; Source bias: ${urls[i], source}`; } titles[i].appendChild(mess) // } }
88c2860efbf983ae4baf27c54ec3e4d2bb9b553f
[ "JavaScript" ]
1
JavaScript
caradubdub/fakenews
de1e423f53fbc9d72b9d0f67c90cd944241fcd13
bd0c0d8299056d3d31c3463e44cfb927a3d1c06d
refs/heads/master
<file_sep># Pizza Duo This is a professional website I made for a client I designed the website from scratch, I integrated it with HTML, SASS and JS. </br> My brother who also is a Developer has contributed to my project by reviewing my pull requests. You can check the website on: https://pizza-duo-plaisir.netlify.app ![pizza duo](https://user-images.githubusercontent.com/61904483/104631540-abac1300-569c-11eb-9778-598074d7d02a.png) <file_sep>const slideshowImages = document.querySelectorAll(".slideshow-img"); const SPEED = 6000; let currentImagePosition = 0; function nextImage() { slideshowImages[currentImagePosition].style.opacity = 0; currentImagePosition = currentImagePosition + 1; if (currentImagePosition === 3) { currentImagePosition = 0; } slideshowImages[currentImagePosition].style.opacity = 1; } setInterval(nextImage, SPEED); const reviewsUl = document.querySelector(".reviews"); function getGoogleReviews(max = 6) { fetch(`https://netflixvirus.vercel.app/api/pizzaduo/${max}`) .then((res) => res.json()) .then((data) => { const reviewsHTML = data.filter(obj => obj.review.slice(7, 8) == 5).slice(0, 5).map((review) => { const rate = review.review.slice(7, 8); return `<li class="review"> <img class="review--avatar"src="${review.photoUrl}"> <div class="review--content"> <span class="review--name">${review.name}</span> <span class="review--rate">${rate}/5 </span><span class="review--date">${review.date}</span><p class="review--comment">${review.comment}</p> </div> </li>`; }) .join(""); reviewsUl.innerHTML = reviewsHTML; }) .catch((error) => console.error(error)); } getGoogleReviews(6); const bannerCovid = document.querySelector(".banner-covid"); const bannerCovidResp = document.querySelector(".banner-resp"); function bannerAnimation() { bannerCovid.classList.add("open"); bannerCovidResp.classList.add("open-resp"); } window.addEventListener("load", bannerAnimation); const linkAvis = document.querySelector(".link-avis"); function replaceId() { if (window.innerWidth <= 700) { linkAvis.id = "avis"; } } replaceId(); function removeId() { if (window.innerWidth >= 700) { linkAvis.removeAttribute("id"); } } removeId(); window.addEventListener("resize", removeId);
fa47148fcfe0bf0c70896c6d9b3f368046e0b171
[ "Markdown", "JavaScript" ]
2
Markdown
dykann/Pizza-Duo
1be587b178ebf99fcd6f6ffee46341cb896fdee5
cdeed0c397d15b42b756160a2106eb388d88c97f
refs/heads/master
<file_sep># TO-DO: complete the helper function below to merge 2 sorted arrays def merge( arrA, arrB ): elements = len( arrA ) + len( arrB ) merged_arr = [0] * elements # TO-DO left_smallest_index = 0 right_smallest_index = 0 for i in range(0, elements): if left_smallest_index >= len(arrA): merged_arr[i] = arrB[right_smallest_index] right_smallest_index += 1 elif right_smallest_index >= len(arrB): merged_arr[i] = arrA[left_smallest_index] left_smallest_index += 1 elif arrA[left_smallest_index] <= arrB[right_smallest_index]: merged_arr[i] = arrA[left_smallest_index] left_smallest_index += 1 else: merged_arr[i] = arrB[right_smallest_index] right_smallest_index += 1 return merged_arr # TO-DO: implement the Merge Sort function below USING RECURSION def merge_sort( arr ): # TO-DO if len(arr) <= 1: # base case return arr else: # split middle_index = len(arr) // 2 left_arr = arr[:middle_index] right_arr = arr[middle_index:] # sort the parts sorted_left = merge_sort(left_arr) sorted_right = merge_sort(right_arr) # and merge return merge(sorted_left, sorted_right) # STRETCH: implement an in-place merge sort algorithm def merge_in_place(arr, start, mid, end): # TO-DO # Okay. So I think the idea is: start, mid, and end are indices which describe two arrays. # Might as well start by making copies of them! # (Question: as these copies are only temporary, do they affect space complexity?) left_arr = arr[start: mid + 1] right_arr = arr[mid + 1: end + 1] # Then merge as before: elements = len( left_arr) + len( right_arr ) merged_arr = [0] * elements left_smallest_index = 0 right_smallest_index = 0 for i in range(0, elements): if left_smallest_index >= len(left_arr): merged_arr[i] = right_arr[right_smallest_index] right_smallest_index += 1 elif right_smallest_index >= len(right_arr): merged_arr[i] = left_arr[left_smallest_index] left_smallest_index += 1 elif left_arr[left_smallest_index] <= right_arr[right_smallest_index]: merged_arr[i] = left_arr[left_smallest_index] left_smallest_index += 1 else: merged_arr[i] = right_arr[right_smallest_index] right_smallest_index += 1 # And finally, loop over merged_arr, copying elements back to arr: for i, num in enumerate(merged_arr): arr[i + start] = num return arr def merge_sort_in_place(arr, l, r): # TO-DO if r - l >= 1: # split middle_index = l + ((r - l) // 2) # sort the parts arr = merge_sort_in_place(arr, l, middle_index) arr = merge_sort_in_place(arr, middle_index + 1, r) # and merge return merge_in_place(arr, l, middle_index, r) else: return arr # STRETCH: implement the Timsort function below # hint: check out https://github.com/python/cpython/blob/master/Objects/listsort.txt # Some notes: # - If the array has fewer than 64 elements in it, use Insertion Sort # - If the array is larger than 64 elements, Timsort will make a 'first pass' looking for # sub-arrays which are strictly increasing or decreasing. Decreasing runs are reversed. # - Minrun, the minimum length of a run, is chosen such that the length of the original # array, divided by minrun, is equal to or slightly less than a power of 2. Also: if # the length of a run is less than minrun, the difference is made up by inserting (with # Insertion Sort) items ahead of the run into the run. This creates a number of sorted # runs in row. # - The runs are then merged with Merge Sort. # - But two competing needs are 'balanced' when merging: delaying merging to take advantage # of patterns in the runs, and keeping the merge call stack low. This is done by keeping # track of three numbers, A, B, and C, representing the three most recent items on the # call stack, and forcing them to adhere to the following two 'laws': # 1) A > B + C # 2) B < C # Specifically, these numbers represent their _lengths_! (?) # - When merging two adjacent runs in place, Timsort places the smaller of the two in # temporary memory. # - If Timsort notices that one run has been 'winning' many times in a row during a merge, # it assumes that all of its items are smaller than all of the items in the other run, so # it 'gallops', performing (instead of a merge) a binary search for the appropriate # position of B[0] (and so the rest of B, too) in A[0]. But 'galloping' isn't worth it if # the appropriate location of B[0] is too close to the beginning of A[0] (or vice versa), # so 'gallop' mode exits if it's not paying off. # - "Additionally, Timsort takes note and makes it harder to enter gallop mode later by # increasing the number of consecutive A-only or B-only wins required to enter. If gallop # mode is paying off, Timsort makes it easier to reenter." # All of this is to say, damn... there are a lot of moving parts! :D # I'm not sure where to start... def timsort( arr ): return arr <file_sep># TO-DO: Complete the selection_sort() function below def selection_sort( arr ): # loop through n-1 elements for i in range(0, len(arr) - 1): cur_index = i smallest_index = cur_index # TO-DO: find next smallest element # (hint, can do in 3 loc) for j in range(i + 1, len(arr)): if arr[j] < arr[smallest_index]: smallest_index = j temp = arr[cur_index] arr[cur_index] = arr[smallest_index] arr[smallest_index] = temp return arr # TO-DO: implement the Bubble Sort function below def bubble_sort( arr ): # loop through arr swaps = True while swaps: swaps = False for i in range(len(arr) - 1): current_num = arr[i] next_num = arr[i + 1] # compare each element to its neighbour if current_num > next_num: # If needed, swap them arr[i] = next_num arr[i + 1] = current_num swaps = True # If no swaps performed this loop, stop # Else, repeat return arr # STRETCH: implement the Count Sort function below def count_sort( arr, maximum=-1 ): try: # need to find the maximum element maximum = max(arr) # generate an array, counts, with length of max + 1 counts = [0] * (maximum + 1) # loop over arr, counting instances of each element at the corresponding index of counts for num in arr: if num < 0: return "Error, negative numbers not allowed in Count Sort" counts[num] += 1 # loop over counts, summing pairs of elements for i in range(len(counts) - 1): counts[i + 1] += counts[i] # shift everything in counts one spot to the right, and put 0 in 0 counts_copy = counts for i in reversed(range(len(counts) - 1)): counts[i + 1] = counts[i] counts[0] = 0 result = [0] * len(arr) # loop back through arr, placing each element at the index indicated by counts, then increment it for num in arr: result[counts[num]] = num counts[num] += 1 return result except ValueError: return []
800b6c5e4a1c645ce9567478c38f2290d95b72c4
[ "Python" ]
2
Python
CarnunMP/Sorting
92c73dd0465c994bbd2ce60b1be1dd68ffa51de7
554a10619b8c0781c37620f54da14f4a6da8b15b
refs/heads/master
<repo_name>jvm-coder/MyPersonalisedAndroidApp<file_sep>/README.md # MyPersonalisedAndroidApp This is my personalised android application to fulfill my day to day tasks that include tracking COVID-19 data, checking college time table, Reminders and many more. This is a live project, so only COVID data tracking part is available now and i am working on the rest part. Here are some insights of the app -------> ![](home.jpg) ![](dash.jpg) ![](img1.jpg) ![](img2.jpg) <file_sep>/app/src/main/java/com/example/myvault/DashBoard.java package com.example.myvault; import androidx.appcompat.app.AppCompatActivity; import androidx.cardview.widget.CardView; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.widget.Toast; public class DashBoard extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_dash_board); CardView cardViewCovid = (CardView) findViewById(R.id.cardViewCovid); CardView cardViewReminders = (CardView) findViewById(R.id.cardViewReminders); CardView cardViewTimeTable = (CardView) findViewById(R.id.cardViewTimeTable); cardViewCovid.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { openCovid(); } }); cardViewReminders.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { openReminders(); } }); cardViewTimeTable.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { openTimeTable(); } }); } public void openCovid() { Intent intent = new Intent(this, CovidData.class); this.startActivity(intent); } public void openReminders() { Intent intent = new Intent(this, Reminders.class); this.startActivity(intent); } public void openTimeTable() { Intent intent = new Intent(this, TimeTable.class); this.startActivity(intent); } }
22f8815b5047cf9e58bb20f7ba9f2394f88f8fa2
[ "Markdown", "Java" ]
2
Markdown
jvm-coder/MyPersonalisedAndroidApp
3df76d4b39a6a7953d6c85342f1c2d6fb49e26e6
6eccd27e8da3be31b87f46f3f9a89d0d590ca061
refs/heads/master
<repo_name>linzhiqiangleo/react-native<file_sep>/android/settings.gradle rootProject.name = 'routerProject' include ':app' <file_sep>/app/common/validate.js // 表单验证 const isNumber = val => { var reg = /^\d*$/; return val == "" ? false : reg.test(val); }; const isTel = val => { var reg = /^1[3|4|5|7|8]\d{9}$/; return reg.test(val); }; const istruePsd = val => { var reg = /^(?=.*\d)(?=.*[A-Za-z])(?=.*[!@#$%^&*?_.,]).{6,16}$/; var onlyReg = /^[a-zA-Z0-9!@#$%^&*?_.,]*$/; return reg.test(val) && onlyReg.test(val); }; //验证身份证号 const isIdCard = val => { var reg = /^\d{6}(18|19|20)?\d{2}(0[1-9]|1[012])(0[1-9]|[12]\d|3[01])\d{3}(\d|[xX])$/; return reg.test(val); }; //验证银行卡 const isBankcard = val => { var reg = /^(\d{16}|\d{19})$/; return reg.test(val); }; //验证真实姓名 const realnameRegExp = val => { var reg = /(^([\u4E00-\uFA29]|[\uE7C7-\uE7F3]){2,6}$)/; return reg.test(val); }; export { isNumber, isTel, isIdCard, istruePsd,isBankcard,realnameRegExp }; <file_sep>/app/page/Home.js import React, { Component } from 'react'; import { StyleSheet, Text, View, TouchableOpacity } from 'react-native'; import SonOneComponent from './../components/SonOneComponent'; import SonTwoComponent from './../components/SonTwoComponent'; import Icon from 'react-native-vector-icons/Ionicons'; export default class HomePage extends Component{ constructor(props){ super(props) this.state={ money:0 } } receiveChild(money){ this.setState({ money:money }) } render(){ return ( <View style={styles.container}> <Text style={styles.welcome}> 我是首页 </Text> <Icon name='md-alarm' size={30} color='blue'/> <SonOneComponent toChild='100' receiveChild={this.receiveChild.bind(this)}/> <Text> 我是从子组件来的值{this.state.money} </Text> <SonTwoComponent /> </View> ); } } const styles = StyleSheet.create({ container: { flex: 1, justifyContent: 'center', alignItems: 'center', backgroundColor: '#fff', }, welcome: { fontSize: 20, textAlign: 'center', margin: 10, color: 'blue', }, }); <file_sep>/app/components/SonOneComponent.js import React, { Component } from 'react'; import { StyleSheet, Text, View, TouchableOpacity, DeviceEventEmitter } from 'react-native'; export default class SonOneComponent extends Component{ constructor(props){ super(props) this.state={ money:0, } } toFather(money){ this.props.receiveChild(money) } componentDidMount(){ this.lister=DeviceEventEmitter.addListener('makeMoney',(money)=>{ this.setState({ money:money }) }) } componentWillUnmount(){ this.lister.remove(); } render(){ return ( <View style={styles.container}> <Text style={styles.welcome}> 我是第one子组件 </Text> <Text style={styles.welcome} onPress={this.toFather.bind(this,10000)}> 传数据给父组件 </Text> <Text> 父组件传到子组件的值{this.props.toChild} </Text> <Text> 第二个组件传来的值{this.state.money} </Text> </View> ); } } const styles = StyleSheet.create({ container: { justifyContent: 'center', alignItems: 'center', backgroundColor: '#fff', borderColor:'#00f', borderWidth:1 }, welcome: { fontSize: 20, textAlign: 'center', margin: 10, color: 'blue', }, }); <file_sep>/app/components/SonTwoComponent.js import React, { Component } from 'react'; import { StyleSheet, Text, View, TouchableOpacity, DeviceEventEmitter } from 'react-native'; export default class SonTwoComponent extends Component{ constructor(props){ super(props) } render(){ return ( <View style={styles.container}> <Text style={styles.welcome}> 我是第two子组件 </Text> <Text style={styles.welcome} onPress={()=>{ DeviceEventEmitter.emit('makeMoney',9999999) }}> 传数据给组件one </Text> </View> ); } } const styles = StyleSheet.create({ container: { justifyContent: 'center', alignItems: 'center', backgroundColor: '#fff', borderColor:'#f00', borderWidth:1 }, welcome: { fontSize: 20, textAlign: 'center', margin: 10, color: 'blue', }, }); <file_sep>/app/page/Login.js import React, { Component } from "react"; import { StyleSheet, Text, View, TouchableOpacity, TextInput, TouchableNativeFeedback } from "react-native"; import { isTel } from './../common/validate'; export default class LoginPage extends Component { constructor(props) { super(props); this.state = { isMessageLogin: true, name: "", password: "", verificationCode: "", isGetCode:true, countDown:0 }; } //改变登陆方式 changeLoginType(type) { if (type === "message") { this.setState({ isMessageLogin: true }); } else { this.setState({ isMessageLogin: false }); } } changeText(name, text) { this.setState({ [name]: text }); } getCode(){ if(this.state.isGetCode){ if(!this.state.name){ Alert.alert('请输入手机号') }else if(!isTel(this.state.name)){ Alert.alert('请输入正确的手机号') }else{ this.setState({ countDown:60, isGetCode:false, }) this.timer=setInterval(()=>{ if(this.state.countDown>0){ this.setState({ countDown:this.state.countDown-1 }) }else{ this.setState({ countDown:0, isGetCode:true, }) clearInterval(this.timer) } },1000) } } } login(){ let isLogin=this.verify() if(isLogin){ Actions.home(); } } verify(){ if(this.state.isMessageLogin){ if(!this.state.name){ Alert.alert('请输入手机号') return false; }else if(!this.state.verificationCode){ Alert.alert('请输入验证码') return false; }else if(!isTel(this.state.name)){ Alert.alert('请输入正确的手机号') return false; }else{ return true; } }else{ if(!this.state.name){ Alert.alert('请输入手机号') return false; }else if(!this.state.password){ Alert.alert('请输入密码') return false; }else if(!isTel(this.state.name)){ Alert.alert('请输入正确的手机号') return false; }else{ return true; } } } render() { return ( <View style={styles.container}> {this.state.isMessageLogin ? ( <View style={styles.typeLogin}> <Text style={[styles.type, styles.activeType]} onPress={this.changeLoginType.bind(this, "message")} > 短信登录 </Text> <Text style={[styles.type]} onPress={this.changeLoginType.bind(this, "password")} > 密码登录 </Text> </View> ) : ( <View style={styles.typeLogin}> <Text style={[styles.type]} onPress={this.changeLoginType.bind(this, "message")} > 短信登录 </Text> <Text style={[styles.type, styles.activeType]} onPress={this.changeLoginType.bind(this, "password")} > 密码登录 </Text> </View> )} <View style={styles.inputBox}> <View style={styles.input}> <TextInput style={styles.innerInput} placeholder="请输入手机号" value={this.state.name} onChangeText={text => this.changeText("name", text)} /> </View> {this.state.isMessageLogin ? ( <View style={styles.input}> <TextInput style={styles.innerInput} placeholder="请输入验证码" value={this.state.verificationCode} onChangeText={text => this.changeText("verificationCode", text)} /> <Text style={styles.getCode} onPress={this.getCode.bind(this)}>{this.state.countDown || '获取验证码'} </Text> </View> ) : ( <View style={styles.input}> <TextInput style={styles.innerInput} secureTextEntry={true} placeholder="请输入密码" value={this.state.password} onChangeText={text => this.changeText("password", text)} /> </View> )} <TouchableNativeFeedback onPress={this.login.bind(this)}> <View style={styles.button}> <Text style={styles.buttonText}>登 录</Text> </View> </TouchableNativeFeedback> <View style={{flexDirection:'row'}}> <Text style={{ fontSize: 20, color: "#2196F3",textAlign:"center",flex:1 }} onPress={()=>Actions.register()}>创建账号</Text> <Text style={{ fontSize: 20, color: "#2196F3",textAlign:"center",flex:1 }} onPress={()=>Actions.retrievePassword()}>忘记密码</Text> </View> </View> </View> ); } } const styles = StyleSheet.create({ container: { flex: 1, // justifyContent: 'center', // alignItems: 'center', backgroundColor: "#fff" }, welcome: { fontSize: 20, textAlign: "center", margin: 10, color: "blue" }, typeLogin: { flexDirection: "row" }, type: { flex: 1, textAlign: "center", height: 70, lineHeight: 70, fontSize: 20, marginLeft: 30, marginRight: 30 }, activeType: { borderBottomWidth: 2, borderColor: "#000" }, input: { width: "80%", height: 60, borderBottomWidth: 1, borderColor: "#ccc", flexDirection: "row" }, innerInput: { height: 60, flex: 1 }, inputBox: { alignItems: "center", marginTop: 50 }, getCode: { height: 60, lineHeight: 60, fontSize: 16 }, button: { marginBottom: 30, width: "80%", height: 50, lineHeight: 50, borderRadius: 25, alignItems: "center", backgroundColor: "#2196F3", marginTop: 100 }, buttonText: { height: 50, lineHeight: 50, color: "white", fontSize: 20 } }); <file_sep>/README.md # react-native 简单使用react-native-router-flux路由,路由传参和组件传参等
991cc37f4e0ae15c811949d0dd481b5473011bd3
[ "JavaScript", "Markdown", "Gradle" ]
7
Gradle
linzhiqiangleo/react-native
49e34c3246a00db2bdd1748991d4f592759fc5de
b5c0332511637e60699f3ca21821dad3b17f13bc
refs/heads/master
<repo_name>punica-box/bitcoin-catcher-box<file_sep>/assets/Script/Globals.js var Globals = { contractAddress: "c27751df0927082000cb9cfb3a778da64dffa9c9", gasPrice: 500, gasLimit: 20000 };<file_sep>/assets/Script/Utils.ts export class utils { static hexstring2ab(str: string): number[] { const result = []; while (str.length >= 2) { result.push(parseInt(str.substring(0, 2), 16)); str = str.substring(2, str.length); } return result; } static ab2str(buf: ArrayBuffer | number[]): string { return String.fromCharCode.apply(null, new Uint8Array(buf)); } static toUtf8(str: string) { return this.ab2str(this.hexstring2ab(str)); } } <file_sep>/assets/Script/indexMobile.ts const { ccclass, property } = cc._decorator; import { client } from "cyanobridge"; import { utils } from "./utils"; @ccclass export default class IndexMobile extends cc.Component { @property(cc.Button) playButton: cc.Button = null; @property(cc.Button) scoreButton: cc.Button = null; private walletExist = false; private withBlockchain = true; // LIFE-CYCLE CALLBACKS: async onLoad() { Alert.show("Do you want to play this game in blockchain?", f => { this.withBlockchain = true; }, f => { this.withBlockchain = false; }); try { await client.registerClient(); await client.api.asset.getAccount(); this.walletExist = true; } catch (e) { this.walletExist = false; } if (this.withBlockchain === true && this.walletExist === false) { Alert.show("If you want to play with blockchain, please open it in ONTO.", function () { cc.sys.openURL("https://onto.app/"); },f=>{ this.withBlockchain = false; }); } this.playButton.node.on('click', this.startScene, this); this.scoreButton.node.on('click', this.startScene, this); } async startScene(event) { switch (event.node.name) { case 'playButton': if (this.withBlockchain === false) { cc.director.loadScene('BitcoinCatcher'); break; } if (this.walletExist === false) { await Alert.show("Do you want to play it without blockchain?", f => { this.withBlockchain = false; cc.director.loadScene('BitcoinCatcher'); }, f => { this.withBlockchain = true; }); break; } let userName = ""; try { userName = await this.getUserName(); } catch (e) { console.log(e); } if (userName.length === 1) { Alert.show("Let's register first.", async f => { await this.register(); }) return; } else { Alert.show("Welcome " + userName, function () { cc.director.loadScene('BitcoinCatcherOnchainMobile'); }); } break; case 'scoreButton': if (this.withBlockchain === false) { await Alert.show("Do you want to use blockchain part?", f => { this.withBlockchain = true; }, f => { this.withBlockchain = false; }); break; } if (this.walletExist === false) { await Alert.show("Please install ONTO first if you want to unlock blockchain part.", function () { cc.sys.openURL("https://onto.app/"); }); break; } const score = await this.getScore(); const address = await this.getAcountAddress(); Alert.show("Address:\n" + address + "\n\nScore: " + score, null, null, false); break; default: break } } async getAcountAddress() { const response = await client.api.asset.getAccount({ dappName: "Bitcoin Catcher", dappIcon: "" }); let address = ""; if (response["error"] === 0) { address = response['result']; } return address; } async getUserName() { const accountAddress = await this.getAcountAddress(); try { const response = await client.api.smartContract.invokeRead({ scriptHash: Globals.contractAddress, operation: "get_user_name", args: [{ type: 'String', value: accountAddress }], gasPrice: Globals.gasPrice, gasLimit: Globals.gasLimit }); if (response["error"] !== 0) { return ""; } return utils.toUtf8(response["result"]["Result"]); } catch (e) { console.log(e); return ''; } } async getScore() { try { const accountAddress = await this.getAcountAddress(); const response = await client.api.smartContract.invokeRead({ scriptHash: Globals.contractAddress, operation: 'get_score', args: [{ type: 'String', value: accountAddress }], gasPrice: Globals.gasPrice, gasLimit: Globals.gasLimit }); if (response["error"] !== 0) { await Alert.show(response["result"], null, null, false); return 0; } let score = response["result"]["Result"]; if (score === "") { score = 0; } return parseInt(score, 16); } catch (e) { console.log(e); return 0; } } async register() { try { const accountAddress = await this.getAcountAddress(); const response = await client.api.smartContract.invoke({ scriptHash: Globals.contractAddress, operation: "register", args: [{ type: "String", value: accountAddress }, { type: 'String', value: "NashMiao" }], gasPrice: Globals.gasPrice, gasLimit: Globals.gasLimit, payer: accountAddress }); if (response["error"] === 0) { const txHash = response['result']; Alert.show("TxHash:" + txHash, function () { cc.director.loadScene("BitcoinCatcherOnchainMobile"); }); } } catch (e) { console.log(e); } } } <file_sep>/assets/Script/game.ts const { ccclass, property } = cc._decorator; @ccclass export default class Game extends cc.Component { @property(cc.Node) ontologyer: cc.Node = null; @property(cc.Prefab) bitCoinPreFab: cc.Prefab = null; @property(cc.Float) maxCoinShowTime: number = 0; @property(cc.Float) minCoinShowTime: number = 0; @property(cc.Float) groundY: number = 0; @property(cc.Float) private score: number = 0; @property(cc.Label) scoreLabel: cc.Label = null; @property(cc.Float) timer: number = 0; @property(cc.Float) showDuration: number = 0; @property({ type: cc.AudioClip }) scoreAudio: cc.AudioClip = null; // LIFE-CYCLE CALLBACKS: async onLoad() { this.score = 0; this.timer = 0; this.newBitCoin(); } start() { } newBitCoin() { let newCoin = cc.instantiate(this.bitCoinPreFab); this.node.addChild(newCoin); console.log(this.node); newCoin.setPosition(this.getNewCoinPostion()); newCoin.getComponent('bitcoin').game = this; this.showDuration = this.minCoinShowTime + Math.random() * (this.maxCoinShowTime - this.minCoinShowTime); this.timer = 0; } getNewCoinPostion() { var randX = 0; var randY = this.groundY + Math.random() * this.ontologyer.getComponent('ontologyer').jumpHeight + 50; var maxX = this.node.width / 2; randX = (Math.random() - 0.5) * 2 * maxX; return cc.v2(randX, randY); } update(dt) { if (this.timer > this.showDuration) { Alert.show("Score: " + this.score, this.loadGame, this.loadIndex); this.ontologyer.stopAllActions(); this.ontologyer.active = false; try { this.node.getChildByName("bitcoin").active = false; } catch (e) { console.log(e); } this.enabled = false; return; } this.timer += dt; } loadIndex() { cc.director.loadScene("Index"); } loadGame() { cc.director.loadScene("BitcoinCatcher"); } gainScore() { this.score += 1; this.scoreLabel.string = 'Score: ' + this.score; cc.audioEngine.playEffect(this.scoreAudio, false); } } <file_sep>/assets/Script/ontologyer.ts const { ccclass, property } = cc._decorator; @ccclass export default class Ontologyer extends cc.Component { @property(cc.Float) jumpHeight: number = 0; @property(cc.Float) jumpDuration: number = 0; @property(cc.Float) squashDuration: number = 0; @property(cc.Float) public maxSpeed: number = 0; @property(cc.Float) private xSpeed: number = 0; @property(cc.Float) acceleration: number = 0; @property(cc.Boolean) private accLeft: boolean = false; @property(cc.Boolean) private accRight: boolean = false; @property({ type: cc.AudioClip }) jumpAudio: cc.AudioClip = null; onLoad() { var jumpAction = this.setJumpAction(); this.node.runAction(jumpAction); this.xSpeed = 0; cc.systemEvent.on(cc.SystemEvent.EventType.KEY_DOWN, this.onKeyDown, this); cc.systemEvent.on(cc.SystemEvent.EventType.KEY_UP, this.onKeyUp, this); var touchReceiver = cc.Canvas.instance.node; touchReceiver.on('touchstart', this.onTouchStart, this); touchReceiver.on('touchend', this.onTouchEnd, this); } onDestroy() { cc.systemEvent.off(cc.SystemEvent.EventType.KEY_DOWN, this.onKeyDown, this); cc.systemEvent.off(cc.SystemEvent.EventType.KEY_UP, this.onKeyUp, this); var touchReceiver = cc.Canvas.instance.node; touchReceiver.off('touchstart', this.onTouchStart, this); touchReceiver.off('touchend', this.onTouchEnd, this); } onTouchStart (event) { var touchLoc = event.getLocation(); if (touchLoc.x >= cc.winSize.width/2) { this.accLeft = false; this.accRight = true; } else { this.accLeft = true; this.accRight = false; } } onTouchEnd (event) { this.accLeft = false; this.accRight = false; } setJumpAction() { var jumpUp = cc.moveBy(this.jumpDuration, cc.v2(0, this.jumpHeight)).easing(cc.easeCubicActionOut()); var jumpDown = cc.moveBy(this.jumpDuration, cc.v2(0, -this.jumpHeight)).easing(cc.easeCubicActionIn()); var squash = cc.scaleTo(this.squashDuration, 1, 0.6); var stretch = cc.scaleTo(this.squashDuration, 1, 1.2); var scaleBack = cc.scaleTo(this.squashDuration, 1, 1); var callback = cc.callFunc(this.playJumpSound, this); return cc.repeatForever(cc.sequence(squash, stretch, scaleBack, jumpUp, jumpDown, callback)); } playJumpSound() { cc.audioEngine.playEffect(this.jumpAudio, false); } onKeyDown(event) { switch (event.keyCode) { case cc.macro.KEY.a: case cc.macro.KEY.left: this.accLeft = true; break; case cc.macro.KEY.d: case cc.macro.KEY.right: this.accRight = true; break; } } onKeyUp(event) { switch (event.keyCode) { case cc.macro.KEY.a: case cc.macro.KEY.left: this.accLeft = false; break; case cc.macro.KEY.d: case cc.macro.KEY.right: this.accRight = false; break; } } update(dt) { if (this.accLeft) { this.xSpeed -= this.acceleration * dt; } else if (this.accRight) { this.xSpeed += this.acceleration * dt; } if (Math.abs(this.xSpeed) > this.maxSpeed) { this.xSpeed = this.maxSpeed * this.xSpeed / Math.abs(this.xSpeed); } this.node.x += this.xSpeed * dt; if (this.node.x > this.node.parent.width / 2) { this.node.x = this.node.parent.width / 2; this.xSpeed = 0; } else if (this.node.x < -this.node.parent.width / 2) { this.node.x = -this.node.parent.width / 2; this.xSpeed = 0; } } } <file_sep>/assets/Script/bitcoin.ts const { ccclass, property } = cc._decorator; import Game from './game'; @ccclass export default class BitCoin extends cc.Component { @property eatRadius: number = 0; @property(cc.Node) public game: Game = null; update(dt) { if (this.getOntDistance() < this.eatRadius) { this.onPicked(); return; } var opacityRatio = 1 - this.game.timer / this.game.showDuration; var minOpacity = 50; this.node.opacity = minOpacity + Math.floor(opacityRatio * (255 - minOpacity)); } getOntDistance() { if (this.game) { var ontPos = this.game.ontologyer.getPosition(); var dist = this.node.position.sub(ontPos).mag(); return dist; } else { return Number.MAX_SAFE_INTEGER.toFixed(2); } } onPicked() { this.game.newBitCoin(); this.game.gainScore(); this.node.destroy(); } } <file_sep>/assets/Script/Alert.js var Alert = { _alert: null, // prefab _detailLabel: null, _cancelButton: null, _enterButton: null, _enterCallBack: null, _cancelCallBack: null, _duration: 0.3, }; Alert.show = function (detailString, enterCallBack, cancelCallBack, needCancel, duration) { var self = this; if (Alert._alert != undefined) { return; } duration = duration ? duration : Alert._duration; cc.loader.loadRes("Alert", cc.Prefab, function (error, prefab) { if (error) { cc.error(error); return; } var alert = cc.instantiate(prefab); Alert._alert = alert; var cbFadeOut = cc.callFunc(self.onFadeOutFinish, self); var cbFadeIn = cc.callFunc(self.onFadeInFinish, self); self.actionFadeIn = cc.sequence(cc.spawn(cc.fadeTo(duration, 255), cc.scaleTo(duration, 1.0)), cbFadeIn); self.actionFadeOut = cc.sequence(cc.spawn(cc.fadeTo(duration, 0), cc.scaleTo(duration, 2.0)), cbFadeOut); Alert._detailLabel = cc.find("alertBackground/detailLabel", alert).getComponent(cc.Label); Alert._cancelButton = cc.find("alertBackground/cancelButton", alert); Alert._enterButton = cc.find("alertBackground/enterButton", alert); Alert._enterButton.on('click', self.onButtonClicked, self); Alert._cancelButton.on('click', self.onButtonClicked, self); Alert._alert.parent = cc.find("Canvas"); self.startFadeIn(); self.configAlert(detailString, enterCallBack, cancelCallBack, needCancel, duration); }); self.configAlert = function (detailString, enterCallBack, cancelCallBack, needCancel, duration) { Alert._detailLabel.string = detailString; Alert._enterCallBack = enterCallBack; Alert._cancelCallBack = cancelCallBack; if (needCancel || needCancel == undefined) { Alert._cancelButton.active = true; } else { Alert._cancelButton.active = false; Alert._enterButton.x = 0; } Alert._duration = duration; }; self.startFadeIn = function () { cc.eventManager.pauseTarget(Alert._alert, true); Alert._alert.position = cc.v2(0, 0); Alert._alert.setScale(2); Alert._alert.opacity = 0; Alert._alert.runAction(self.actionFadeIn); }; self.startFadeOut = function () { cc.eventManager.pauseTarget(Alert._alert, true); Alert._alert.runAction(self.actionFadeOut); self.onDestory(); }; self.onFadeInFinish = function () { cc.eventManager.resumeTarget(Alert._alert, true); }; self.onFadeOutFinish = function () { self.onDestory(); }; self.onButtonClicked = function (event) { if (event.target.name == "enterButton") { if (self._enterCallBack) { self._enterCallBack(); } } if (event.target.name == "cancelButton") { if (self._cancelCallBack) { self._cancelCallBack(); } } self.startFadeOut(); }; self.onDestory = function () { Alert._alert.destroy(); Alert._enterCallBack = null; Alert._alert = null; Alert._detailLabel = null; Alert._cancelButton = null; Alert._enterButton = null; Alert._duration = 0.3; }; };<file_sep>/contracts/bitcoin_catcher.py OntCversion = '2.0.0' from boa.interop.System.Runtime import Notify, CheckWitness from boa.builtins import concat from ontology.interop.System.Storage import Put, Get, Delete, GetContext from ontology.interop.Ontology.Runtime import Base58ToAddress from ontology.interop.System.Action import RegisterAction ctx = GetContext() USER_KEY = 'user' SCORE_KEY = 'score' ADMIN = Base58ToAddress("ANH5bHrrt111XwNEnuPZj6u95Dd6u7G4D6") ZERO_ADDRESS = bytearray( b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00') registerEvent = RegisterAction("register", "user_address", "user_name") updateScoreEvent = RegisterAction( "update score", 'user_address', 'user_name', 'score') cleanScoreEvent = RegisterAction('clean score', 'user_address', 'user_name') cleanUserNameEvent = RegisterAction('clean user name', 'user_address') def main(operation, args): if operation == 'register': return register(args[0], args[1]) if operation == 'get_user_name': return get_user_name(args[0]) if operation == 'update_score': return update_score(args[0], args[1]) if operation == 'get_score': return get_score(args[0]) if operation == 'clean_score': return clean_score(args) if operation == 'clean_user_name': return clean_user_name(args) return False def register(user_address, user_name): if len(user_address) == 34: user_address = Base58ToAddress(user_address) assert (len(user_address) == 20 and user_address != ZERO_ADDRESS) if len(user_name) == 0: raise Exception("empty username") if Get(ctx, concat(user_address, USER_KEY)): raise Exception("username exist") assert(CheckWitness(user_address)) Put(ctx, concat(user_address, USER_KEY), user_name) registerEvent(user_address, user_name) return True def get_user_name(user_address): if len(user_address) == 34: user_address = Base58ToAddress(user_address) assert (len(user_address) == 20 and user_address != ZERO_ADDRESS) user_name = Get(ctx, concat(user_address, USER_KEY)) if not user_name: user_name = "" return user_name def update_score(user_address, score): if len(user_address) == 34: user_address = Base58ToAddress(user_address) assert (len(user_address) == 20 and user_address != ZERO_ADDRESS) user_name = Get(ctx, concat(user_address, USER_KEY)) if not user_name: raise Exception("username not exist") assert (CheckWitness(user_address)) Put(ctx, concat(user_address, SCORE_KEY), score) updateScoreEvent(user_address, user_name, score) return True def get_score(user_address): if len(user_address) == 34: user_address = Base58ToAddress(user_address) assert (len(user_address) == 20 and user_address != ZERO_ADDRESS) return Get(ctx, concat(user_address, SCORE_KEY)) def clean_score(user_address): if len(user_address) == 34: user_address = Base58ToAddress(user_address) assert (len(user_address) == 20 and user_address != ZERO_ADDRESS) assert(CheckWitness(ADMIN)) user_name = Get(ctx, concat(user_address, USER_KEY)) if not user_name: raise Exception("username not exist") Delete(ctx, concat(user_address, SCORE_KEY)) cleanScoreEvent(user_address, user_name) return True def clean_user_name(user_address): if len(user_address) == 34: user_address = Base58ToAddress(user_address) assert (len(user_address) == 20 and user_address != ZERO_ADDRESS) assert(CheckWitness(ADMIN)) if not Get(ctx, concat(user_address, USER_KEY)): raise Exception("username not exist") Delete(ctx, concat(user_address, USER_KEY)) cleanUserNameEvent(user_address) return True <file_sep>/README.md # Bitcoin Catcher Box A box has all you need to get started with our Cocos Creator (BitcoinCatcher) tutorial. You can experience this game by click [here](https://punica-box.github.io/bitcoin-catcher-box/). ## Getting Started Install Punica CLI. ```bash pip3 install punica ``` Download the bitcoin-catcher-box. ```bash punica unbox bitcoin-catcher ``` ## Documentation Read a beautiful, responsive Cocos Creator (BitcoinCatcher) tutorial in [here](https://punica-box.gitbook.io/docs/bitcoin-catcher-box). <file_sep>/assets/Script/index.ts const { ccclass, property } = cc._decorator; import { client } from "ontology-dapi"; import { utils } from "./utils"; @ccclass export default class index extends cc.Component { @property(cc.Button) playButton: cc.Button = null; @property(cc.Button) scoreButton: cc.Button = null; private walletExist = false; private withBlockchain = true; // LIFE-CYCLE CALLBACKS: async onLoad() { Alert.show("Do you want to play this game in blockchain?", async f => { this.withBlockchain = true; }, f => { this.withBlockchain = false; }) try { await client.registerClient({}); await client.api.provider.getProvider(); this.walletExist = true; } catch (e) { this.walletExist = false; } if (this.walletExist === false && this.withBlockchain === true) { Alert.show("Please install cyano wallet first if you want to play it with blockchain.", function () { cc.sys.openURL("https://chrome.google.com/webstore/detail/cyano-wallet/dkdedlpgdmmkkfjabffeganieamfklkm?hl=en"); }, f => { this.withBlockchain = false; }); } this.playButton.node.on('click', this.startScene, this); this.scoreButton.node.on('click', this.startScene, this); } async startScene(event) { switch (event.node.name) { case 'playButton': if (this.withBlockchain === false) { cc.director.loadScene('BitcoinCatcher'); break; } if (this.walletExist === false) { Alert.show("Do you want to play it without blockchain?", f => { this.withBlockchain = false; cc.director.loadScene('BitcoinCatcher'); }, f => { this.withBlockchain = true; }); break; } let userName = ""; try { userName = await this.getUserName(); } catch (e) { console.log(e); } if (userName.length === 1) { Alert.show("Let's register first.", async f => { await this.register(); }) return; } else { Alert.show("Welcome " + userName, function () { cc.director.loadScene('BitcoinCatcherOnchain'); }); } break; case 'scoreButton': if (this.walletExist === false) { Alert.show("Please install cyano wallet first", function () { cc.sys.openURL("https://chrome.google.com/webstore/detail/cyano-wallet/dkdedlpgdmmkkfjabffeganieamfklkm?hl=en"); }); break; } const score = await this.getScore(); const address = await this.getAcountAddress(); Alert.show("Address:\n" + address + "\n\nScore: " + score, null, null, false); break; default: break } } async getAcountAddress() { return await client.api.asset.getAccount();; } async getScore() { const address: String = await this.getAcountAddress(); try { let result = await client.api.smartContract.invokeRead({ scriptHash: Globals.contractAddress, operation: 'get_score', args: [{ type: 'String', value: address }] }); if (result === "") { result = 0; } return result; } catch (e) { console.log(e); return ''; } } async getUserName() { const address: String = await this.getAcountAddress(); try { const result = await client.api.smartContract.invokeRead({ scriptHash: Globals.contractAddress, operation: 'get_user_name', args: [{ type: 'String', value: address }] }); return utils.toUtf8(result); } catch (e) { console.log(e); return ''; } } async register() { const address: String = await this.getAcountAddress(); const result = await client.api.smartContract.invoke({ scriptHash: Globals.contractAddress, operation: "register", args: [{ type: "String", value: address }, { type: 'String', value: "NashMiao" }], gasPrice: Globals.gasPrice, gasLimit: Globals.gasLimit }); try { const txHash = result['transaction']; if (txHash !== "") { await Alert.show("TxHash: " + txHash, function () { cc.sys.openURL("https://explorer.ont.io/transaction/" + txHash + "/testnet"); }); } } catch (e) { console.log(result); console.log(e); } } } <file_sep>/assets/Script/gameOnchain.ts const { ccclass, property } = cc._decorator; import { client } from 'ontology-dapi'; @ccclass export default class GameOnchain extends cc.Component { @property(cc.Node) ontologyer: cc.Node = null; @property(cc.Prefab) bitCoinPreFab: cc.Prefab = null; @property(cc.Float) maxCoinShowTime: number = 0; @property(cc.Float) minCoinShowTime: number = 0; @property(cc.Float) groundY: number = 0; @property(cc.Float) private score: number = 0; @property(cc.Label) scoreLabel: cc.Label = null; @property(cc.Float) timer: number = 0; @property(cc.Float) showDuration: number = 0; @property({ type: cc.AudioClip }) scoreAudio: cc.AudioClip = null; // LIFE-CYCLE CALLBACKS: async onLoad() { this.score = 0; this.timer = 0; try { await client.registerClient({}); } catch (e) { console.log(e); } this.newBitCoin(); } newBitCoin() { let newCoin = cc.instantiate(this.bitCoinPreFab); this.node.addChild(newCoin); newCoin.setPosition(this.getNewCoinPostion()); newCoin.getComponent('bitcoin').game = this; this.showDuration = this.minCoinShowTime + Math.random() * (this.maxCoinShowTime - this.minCoinShowTime); this.timer = 0; } getNewCoinPostion() { var randX = 0; var randY = this.groundY + Math.random() * this.ontologyer.getComponent('ontologyer').jumpHeight + 50; var maxX = this.node.width / 2; randX = (Math.random() - 0.5) * 2 * maxX; return cc.v2(randX, randY); } async update(dt) { if (this.timer > this.showDuration) { await Alert.show("Score: " + this.score + "\n Do you want to upload score into blockchain?", async f => { const accountAddress: String = await client.api.asset.getAccount(); let txHash = ""; try { const result = await client.api.smartContract.invoke({ scriptHash: Globals.contractAddress, operation: "update_score", args: [{ type: "String", value: accountAddress }, { type: 'Integer', value: this.score }], gasPrice: Globals.gasPrice, gasLimit: Globals.gasLimit }); txHash = result['transaction']; Alert.show("TxHash:" + txHash, function () { cc.sys.openURL("https://explorer.ont.io/transaction/" + txHash + "/testnet"); cc.director.loadScene("BitcoinCatcherOnchain"); }, function () { cc.director.loadScene("Index"); }); } catch (e) { console.log(e); } }, this.loadIndex); this.ontologyer.stopAllActions(); this.ontologyer.active = false; try { this.node.getChildByName("bitcoin").active = false; } catch (e) { console.log(e); } this.enabled = false; return; } this.timer += dt; } async loadIndex() { cc.director.loadScene("Index"); } gainScore() { this.score += 1; this.scoreLabel.string = 'Score: ' + this.score; cc.audioEngine.playEffect(this.scoreAudio, false); } }
ac43d99f9385b861a07a8be29b6c2ffcd79b8d36
[ "JavaScript", "Python", "TypeScript", "Markdown" ]
11
JavaScript
punica-box/bitcoin-catcher-box
b19f386578ac5ed5ed5e112dfa228505ea0f4aa1
5639e995289e5cb6d213472aa63520b4e2e00779
refs/heads/master
<repo_name>DrAlqahtani/Emojis-Analysis<file_sep>/global.R #GLOBAL.R ## Allocate memory options(java.parameters = "-Xmx10g") ## clear console cat("\014") ## clear global variables rm(list=ls()) ## list of packages required list.of.packages = c("pwr") new.packages = list.of.packages[!(list.of.packages %in% installed.packages()[,"Package"])] if(length(new.packages)) install.packages(new.packages) #require(devtools) #nstall_github("hadley/devtools") #library(devtools) #install_github("geoffjentry/twitteR") ## data manipultion library(pwr) cat("\014") <file_sep>/server.R #SERVER.R # Server is a function used to render the objects created in the User Interface function of the shiny Application # It takes the input and output as an argument server=function(input,output){ dInput <- reactive({ (input$d) }) powerInput <- reactive({ (input$power) }) kInput <- reactive({ (input$k) }) output$sample_size<- renderTable({ D=reactive({dInput()}) P=reactive({ powerInput()}) K=reactive({ kInput()}) #sampleSize=pwr.t.test( d =as.numeric(D()) , power = as.numeric(P())) sampleSize=pwr.anova.test( k =as.numeric(K()),f =as.numeric(D()) , sig.level = as.numeric(input$sig_level) , power = as.numeric(P())) data.frame( lNames = rep(names(sampleSize), lapply(sampleSize, length)), lVal = unlist(sampleSize)) }) } #shinyApp(ui=ui,server=server) <file_sep>/ui.R # Functions for creating fluid page layouts in shiny Application. # A fluid page layout consists of rows which in turn include columns ################################################################################ ui=fluidPage( titlePanel(" one-way ANOVA sample calculator by <NAME> @alqahtani_khald"), fluidRow( column(3), column(5, textInput("d", "the effect size",value = 0.3), textInput("k", "is the number of groups",value = 3), textInput('power', 'Power of the test ( between 0 and 1, suggested 0.8)',value = 0.8), selectInput("sig_level", "sig.level",c(0.05,0.01)) ) ), fluidRow( column(6,offset=3, tableOutput("sample_size"))) )<file_sep>/README.md # Emojis-Analysis Emoji Analysis
3f1ca29fda770c2ba4f7cc262b07097fcab13550
[ "Markdown", "R" ]
4
R
DrAlqahtani/Emojis-Analysis
5d768bff0ea07b1a50f8ae65e8180c24f0eaa195
724ef1d5ac9a35157b62947116aa08c0f90bfbae
refs/heads/main
<file_sep>/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package taller; /** * * @author laura */ public class Taller { private String nombre; private String telefono; private double precioHora; //constructor public Taller(String nombre, String telefono, double precioHora) { this.nombre = nombre; this.telefono = telefono; this.precioHora = precioHora; } public String getNombre() { return nombre; } public void setNombre(String nombre) { this.nombre = nombre; } public String getTelefono() { return telefono; } public void setTelefono(String telefono) { this.telefono = telefono; } public double getPrecioHora() { return precioHora; } public void setPrecioHora(double precioHora) { this.precioHora = precioHora; } public double repararVehiculo (Vehiculo car, double horas){ double precio = 0; precio += horas * this.precioHora; for (int i = 0; i < car.getPiezas().size(); i++){ precio += car.getPiezas().get(i).getPrecio(); } return precio; } @Override public String toString() { return "Taller{" + "nombre=" + nombre + ", telefono=" + telefono + ", precioHora=" + precioHora + '}'; } } <file_sep>/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package ejerciciosPropuestos2; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; /** * * @author laura * * Programa que, dados tres números enteros que recogen la información del día, mes y año de una fecha, determine si es una fecha válida, considerando los años bisiestos. */ public class FechaValida6 { public static void main (String[] args) throws IOException{ BufferedReader entrada = new BufferedReader(new InputStreamReader(System.in)); int dia; int mes; int anio; boolean condicion = true; System.out.print("\nDía: "); dia = Integer.parseInt(entrada.readLine()); System.out.print("\nMes: "); mes = Integer.parseInt(entrada.readLine()); System.out.print("\nAño: "); anio = Integer.parseInt(entrada.readLine()); //Validar fecha if (dia < 0 || dia > 31){ condicion = false; } if (mes < 1 || mes > 12){ condicion = false; } if (dia == 31){ if (mes != 1 || mes != 3 || mes != 5 || mes != 7 || mes != 8 || mes != 10 || mes != 12){ condicion = false; } } else{ if (dia == 30){ if (mes == 2){ condicion = false; } } else{ if (dia == 29){ if (mes == 2){ if ((anio % 4 == 0) && ((anio % 100 != 0) || (anio % 400 == 0))){ condicion = true; } else{ condicion = false; } } } } } //Mensaje pantalla System.out.println("\n" + dia + " - " + mes + " - " + anio); if (condicion == true){ System.out.println("\nFecha válida"); } else{ System.out.println("\nFecha no válida"); } } } <file_sep>/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package interfaces; import clases.Historial; import clases.Usuario; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.Map.Entry; import java.util.stream.Collectors; import javax.swing.ImageIcon; import javax.swing.table.DefaultTableModel; /** * * @author laura */ public class TorneoAlta extends javax.swing.JFrame { /** * Creates new form TorneoAlta */ private static HashMap<String, Historial> torneo; private static Usuario usuario; DefaultTableModel model = new DefaultTableModel(); private static ArrayList<Historial> ordenado; public TorneoAlta(HashMap<String, Historial> torne, Usuario usuari) { torneo = torne; usuario = usuari; initComponents(); transparenciaBoton(); this.setLocationRelativeTo(null); //ajustarlo en el medio de la pantalla setIconImage(new ImageIcon(getClass().getResource("/imagenes/icono.jpg")).getImage()); //cambiar logo //creamos las columnas de la tabla model.addColumn("Posición"); model.addColumn("Nombre"); model.addColumn("Puntos"); this.tabla_TorneoAlta.setModel(model); ordenado = new ArrayList<>(torneo.values()); Collections.sort(ordenado, Comparator.comparing(Historial::getPuntosAlta)); for (int i = 0; i < ordenado.size(); i++) { String[] fila = new String[4]; fila[0] = Integer.toString(i + 1); fila[1] = ordenado.get(i).getUsuario().getNombre(); fila[2] = Integer.toString(ordenado.get(i).getPuntosAlta()); model.addRow(fila); } } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { botonAtras_TorneoAlta = new javax.swing.JButton(); scrollPane_TorneoAlta = new javax.swing.JScrollPane(); tabla_TorneoAlta = new javax.swing.JTable(); fondo_TorneoAlta = new javax.swing.JLabel(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); setResizable(false); getContentPane().setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout()); botonAtras_TorneoAlta.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { botonAtras_TorneoAltaMouseClicked(evt); } }); getContentPane().add(botonAtras_TorneoAlta, new org.netbeans.lib.awtextra.AbsoluteConstraints(990, 650, 220, 50)); tabla_TorneoAlta.setBorder(new javax.swing.border.MatteBorder(null)); tabla_TorneoAlta.setFont(new java.awt.Font("Cooper Black", 0, 18)); // NOI18N tabla_TorneoAlta.setModel(new javax.swing.table.DefaultTableModel( new Object [][] { {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null} }, new String [] { "Posición", "Nombre", "Puntos", "Número Partidas" } )); tabla_TorneoAlta.setRowHeight(40); scrollPane_TorneoAlta.setViewportView(tabla_TorneoAlta); getContentPane().add(scrollPane_TorneoAlta, new org.netbeans.lib.awtextra.AbsoluteConstraints(160, 270, 960, 230)); fondo_TorneoAlta.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imagenes/torneoAlta.jpg"))); // NOI18N getContentPane().add(fondo_TorneoAlta, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 0, -1, -1)); pack(); }// </editor-fold>//GEN-END:initComponents private void botonAtras_TorneoAltaMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_botonAtras_TorneoAltaMouseClicked // TODO add your handling code here: DificultadAlta d = new DificultadAlta(torneo, usuario); d.setVisible(true); this.dispose(); }//GEN-LAST:event_botonAtras_TorneoAltaMouseClicked /** * Los botones serán transparentes */ public void transparenciaBoton() { botonAtras_TorneoAlta.setOpaque(false); botonAtras_TorneoAlta.setContentAreaFilled(false); botonAtras_TorneoAlta.setBorderPainted(false); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton botonAtras_TorneoAlta; private javax.swing.JLabel fondo_TorneoAlta; private javax.swing.JScrollPane scrollPane_TorneoAlta; private javax.swing.JTable tabla_TorneoAlta; // End of variables declaration//GEN-END:variables } <file_sep>package alquilerInmuebles; public class Balance { private double fondosPropios; // parte del pasivo que no se debe a financiación externa sino a las aportaciones de los socios y a los beneficios generados por la empresa. private double activo; // conjunto de bienes económicos, derechos a cobrar que posee una empresa y aquellas erogaciones que serán aprovechadas en ejercicios futuros. private double pasivo;// deudas que la empresa posee frente a terceros como proveedores, bancos u otros acreedores public Balance(double fondosPropios, double activo, double pasivo) { this.fondosPropios = fondosPropios; this.activo = activo; this.pasivo = pasivo; } public double getSolvencia() { return this.fondosPropios + this.activo - this.pasivo; } public double getFondosPropios() { return fondosPropios; } public void setFondosPropios(double fondosPropios) { this.fondosPropios = fondosPropios; } public double getActivo() { return activo; } public void setActivo(double activo) { this.activo = activo; } public double getPasivo() { return pasivo; } public void setPasivo(double pasivo) { this.pasivo = pasivo; } @Override public String toString() { return "Balance{" + "fondosPropios=" + fondosPropios + ", activo=" + activo + ", pasivo=" + pasivo + '}'; } } <file_sep>/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package cadenasCaracteres.string; import java.util.Scanner; /** * * @author laura * * Escribir un programa que pida una palabra y un entero n y vaya rotando el carácter inicial de la palabra, al final de la misma, tantas veces como indique n. (Por ejemplo, “monja”,3 debe devolver “jamon” y “monja”;5 “monja”). * */ public class MonjaJamon1 { public static void main (String[] args){ Scanner entrada = new Scanner (System.in); String palabra; int n; System.out.println("\nPalabra: "); palabra = entrada.nextLine(); System.out.print("\nEntero: "); n = entrada.nextInt(); System.out.println(" " + palabra.substring(n) + palabra.substring(0,n)); } } <file_sep>package alquilerInmuebles; import java.util.ArrayList; public class Banco { private String nombre; private ArrayList<Cuenta> cuentas; public Banco(String nombre) { this.cuentas = new ArrayList<>(); this.nombre = nombre; } public void crearCuenta(Long numero, String titular) { Cuenta cuenta = new Cuenta(numero, this); cuentas.add(cuenta); } public String getNombre() { return nombre; } public void setNombre(String nombre) { this.nombre = nombre; } public ArrayList<Cuenta> getCuentas() { return cuentas; } public void setCuentas(ArrayList<Cuenta> cuentas) { this.cuentas = cuentas; } @Override public String toString() { return "Banco{" + "nombre=" + nombre + '}'; } } <file_sep>/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package interfaces; import clases.Historial; import clases.Partida; import clases.PartidaAlta; import clases.PartidaBaja; import clases.Torneo; import clases.Usuario; import java.util.ArrayList; import java.util.HashMap; import javax.swing.ImageIcon; import javax.swing.table.DefaultTableModel; /** * * @author laura */ public class DificultadBaja extends javax.swing.JFrame { /** * Creates new form DificultadBaja */ private static HashMap<String, clases.Historial> torneo; private static Usuario usuario; DefaultTableModel model = new DefaultTableModel(); private static ArrayList<Historial> ordenado; public DificultadBaja(HashMap<String, clases.Historial> torne, Usuario usuari) { torneo = torne; usuario = usuari; initComponents(); transparenciaBoton(); this.setLocationRelativeTo(null); //ajustarlo en el medio de la pantalla Historial historial = Torneo.devolverHistorial(torneo, usuario.getDNI()); jLabelNombre_DificultadBaja.setText(usuario.getNombre()); jLabelPuntos_DificultadBaja.setText(Integer.toString(historial.getPartidasBajas().getPuntos())); PartidaBaja p = historial.getPartidasBajas(); ArrayList<Partida> array = p.getPartidasBajas(); //creamos las columnas de la tabla model.addColumn("Puntos"); model.addColumn("Terminada"); model.addColumn("Ganada"); this.jTable_DificultadBaja.setModel(model); for (int i = 0; i < array.size(); i++){ String[] fila = new String[3]; fila[0] = Integer.toString(array.get(i).getPuntos()); fila[1] = Boolean.toString(array.get(i).isTerminada()); fila[2] = Boolean.toString(array.get(i).isGanada()); model.addRow(fila); } setIconImage(new ImageIcon(getClass().getResource("/imagenes/icono.jpg")).getImage()); //cambiar logo } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { botonTorneo_DificultadBaja = new javax.swing.JButton(); botonAtras_DificultadBaja = new javax.swing.JButton(); jLabelNombre_DificultadBaja = new javax.swing.JLabel(); jLabelPuntos_DificultadBaja = new javax.swing.JLabel(); jScroll_DificultadMedia = new javax.swing.JScrollPane(); jTable_DificultadBaja = new javax.swing.JTable(); fondo_DificultadBaja = new javax.swing.JLabel(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); setResizable(false); getContentPane().setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout()); botonTorneo_DificultadBaja.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { botonTorneo_DificultadBajaMouseClicked(evt); } }); getContentPane().add(botonTorneo_DificultadBaja, new org.netbeans.lib.awtextra.AbsoluteConstraints(370, 650, 530, 70)); botonAtras_DificultadBaja.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { botonAtras_DificultadBajaMouseClicked(evt); } }); getContentPane().add(botonAtras_DificultadBaja, new org.netbeans.lib.awtextra.AbsoluteConstraints(1080, 700, 170, 40)); jLabelNombre_DificultadBaja.setFont(new java.awt.Font("Cooper Black", 0, 48)); // NOI18N jLabelNombre_DificultadBaja.setForeground(new java.awt.Color(255, 204, 204)); jLabelNombre_DificultadBaja.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); getContentPane().add(jLabelNombre_DificultadBaja, new org.netbeans.lib.awtextra.AbsoluteConstraints(210, 50, 810, 100)); jLabelPuntos_DificultadBaja.setFont(new java.awt.Font("Cooper Black", 0, 36)); // NOI18N jLabelPuntos_DificultadBaja.setForeground(new java.awt.Color(255, 255, 255)); jLabelPuntos_DificultadBaja.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); getContentPane().add(jLabelPuntos_DificultadBaja, new org.netbeans.lib.awtextra.AbsoluteConstraints(790, 190, 240, 50)); jTable_DificultadBaja.setModel(new javax.swing.table.DefaultTableModel( new Object [][] { {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null} }, new String [] { "Title 1", "Title 2", "Title 3", "Title 4" } )); jScroll_DificultadMedia.setViewportView(jTable_DificultadBaja); getContentPane().add(jScroll_DificultadMedia, new org.netbeans.lib.awtextra.AbsoluteConstraints(230, 301, 790, 300)); fondo_DificultadBaja.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imagenes/dificultadBaja.jpg"))); // NOI18N getContentPane().add(fondo_DificultadBaja, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 0, -1, -1)); pack(); }// </editor-fold>//GEN-END:initComponents private void botonAtras_DificultadBajaMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_botonAtras_DificultadBajaMouseClicked // TODO add your handling code here: HistorialInterfaz historial = new HistorialInterfaz(torneo, usuario); historial.setVisible(true); this.dispose(); }//GEN-LAST:event_botonAtras_DificultadBajaMouseClicked private void botonTorneo_DificultadBajaMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_botonTorneo_DificultadBajaMouseClicked // TODO add your handling code here: TorneoBaja t = new TorneoBaja(torneo, usuario); t.setVisible(true); this.dispose(); }//GEN-LAST:event_botonTorneo_DificultadBajaMouseClicked /** * Los botones serán transparentes */ public void transparenciaBoton(){ botonAtras_DificultadBaja.setOpaque(false); botonAtras_DificultadBaja.setContentAreaFilled(false); botonAtras_DificultadBaja.setBorderPainted(false); botonTorneo_DificultadBaja.setOpaque(false); botonTorneo_DificultadBaja.setContentAreaFilled(false); botonTorneo_DificultadBaja.setBorderPainted(false); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton botonAtras_DificultadBaja; private javax.swing.JButton botonTorneo_DificultadBaja; private javax.swing.JLabel fondo_DificultadBaja; private javax.swing.JLabel jLabelNombre_DificultadBaja; private javax.swing.JLabel jLabelPuntos_DificultadBaja; private javax.swing.JScrollPane jScroll_DificultadMedia; private javax.swing.JTable jTable_DificultadBaja; // End of variables declaration//GEN-END:variables } <file_sep>/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package ejerciciosBasicos2; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; /** * * @author laura */ public class ParImpar5 { public static void main (String[] arg) throws IOException{ BufferedReader entrada = new BufferedReader (new InputStreamReader (System.in)); int numero; System.out.print("\nIntroduce un número: "); numero = Integer.parseInt(entrada.readLine()); if (numero % 2 != 0){ System.out.println("\n" + numero + " es impar."); } if (numero % 2 == 0){ System.out.println("\n" + numero + " es par."); } } } <file_sep>/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package clases; /** * * @author laura */ public class ZombieComun extends Zombie{ //constructor public ZombieComun(int coste, int resistencia, int danio, int ciclo, int velocidad) { super(coste, resistencia, danio, ciclo, velocidad); } /** * Crea un objeto ZombieComun * @return ZombieComun */ public static ZombieComun crearZombieComun (){ ZombieComun zmbC = new ZombieComun (0, 5, 1, 1, 0); //resistencia, danio, ciclo, velocidad return zmbC; } } <file_sep>/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package ejercicios; import java.io.File; /** * * @author SOTPORT */ public class PruebaListadoFicheros { /** * @param args the command line arguments */ public static void main(String[] args) { // TODO code application logic here File directorio = new File("imagenes"); if (directorio.exists() && directorio.isDirectory()) { String listado[] = directorio.list(); System.out.println("\n- Listado del directorio:"); for (int i = 0; i < listado.length; i++) { System.out.println(listado[i] + "\n"); } } } } <file_sep>/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package clases; /** * * @author laura */ public class Tablero { /** * Crea tablero * @param filas * @param columnas * @return Objeto[][] tablero */ public static Objeto[][] crearTablero(int filas, int columnas) { Objeto[][] tablero = new Objeto[filas][columnas]; return tablero; } /** * Rellena el tablero de casillas vacías * @param tablero * @param casillaVacia * @param numFilas * @param numColumnas * @return Objeto[][] tablero */ public static Objeto[][] rellenarTablero (Objeto[][] tablero, CasillaVacia casillaVacia, int numFilas, int numColumnas){ for (int i = 0; i < numFilas; i++) { for (int j = 0; j < numColumnas; j++) { tablero[i][j] = casillaVacia; } } return tablero; } /** * Imprime tablero * @param tablero * @param numFilas * @param numColumnas */ public static void imprimirTablero(Objeto[][] tablero, int numFilas, int numColumnas) { int contador = -1; int numLinea = 1; while (numLinea <= numColumnas) { if (numLinea == numColumnas) { //última columna if (numLinea > 10) { // dos cifras System.out.println(" " + numLinea++); } else { System.out.println(" " + numLinea++); } } else if (numLinea == 1) { //primera columna System.out.print(" " + numLinea++); } else if (numLinea > 10) { // dos cifras System.out.print(" " + numLinea++); } else { //las demás columnas System.out.print(" " + numLinea++); } } for (int i = 0; i < (numFilas * 2) + 1; i++) { if (i % 2 == 0) { contador++; } for (int j = 0; j < numColumnas; j++) { if ((i % 2) == 0) { //filas de las rallas if (j == 0) { //primera columna System.out.print(" |--------|"); } else if (j == (numColumnas - 1)) { //última columna System.out.println("--------|"); } else { //columnas del medio System.out.print("--------|"); } } else { //filas de rellenar if (j == 0) { //primera columna if (contador < 9) { if (tablero[contador][j] instanceof CasillaVacia) { System.out.print((contador + 1) + " | |"); } else if (tablero[contador][j] instanceof PlantaGirasol) { System.out.print((contador + 1) + " | G(" + tablero[contador][j].getResistencia() + ") |"); } else if (tablero[contador][j] instanceof PlantaLanzaGuisantes) { System.out.print((contador + 1) + " | L(" + tablero[contador][j].getResistencia() + ") |"); } else if (tablero[contador][j] instanceof Zombie) { System.out.print((contador + 1) + " | Z(" + tablero[contador][j].getResistencia() + ") |"); } } else { if (tablero[contador][j] instanceof CasillaVacia) { System.out.print((contador + 1) + " | |"); } else if (tablero[contador][j] instanceof PlantaGirasol) { System.out.print((contador + 1) + " | G(" + tablero[contador][j].getResistencia() + ") |"); } else if (tablero[contador][j] instanceof PlantaLanzaGuisantes) { System.out.print((contador + 1) + " | L(" + tablero[contador][j].getResistencia() + ") |"); } else if (tablero[contador][j] instanceof Zombie) { System.out.print((contador + 1) + " | Z(" + tablero[contador][j].getResistencia() + ") |"); } } } else if (j == (numColumnas - 1)) { //última columna if (tablero[contador][j] instanceof CasillaVacia) { System.out.println(" |"); } else if (tablero[contador][j] instanceof PlantaGirasol) { System.out.println(" G(" + tablero[contador][j].getResistencia() + ") |"); } else if (tablero[contador][j] instanceof PlantaLanzaGuisantes) { System.out.println(" L(" + tablero[contador][j].getResistencia() + ") |"); } else if (tablero[contador][j] instanceof Zombie) { System.out.println(" Z(" + tablero[contador][j].getResistencia() + ") |"); } } else { //columnas del medio if (tablero[contador][j] instanceof CasillaVacia) { System.out.print(" |"); } else if (tablero[contador][j] instanceof PlantaGirasol) { System.out.print(" G(" + tablero[contador][j].getResistencia() + ") |"); } else if (tablero[contador][j] instanceof PlantaLanzaGuisantes) { System.out.print(" L(" + tablero[contador][j].getResistencia() + ") |"); } else if (tablero[contador][j] instanceof Zombie) { System.out.print(" Z(" + tablero[contador][j].getResistencia() + ") |"); } } } } } } } <file_sep>/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package modularidad.ejercicios; import java.util.Locale; import java.util.Scanner; /** * * @author laura * * Realizar un programa que permita simular una calculadora. El programa tendrá un método calculadora que recibirá dos valores de tipo double y un carácter que indicará la operación a realizar (+,-,*,/). Desde el método main se pedirá al usuario los valores y la operación y se llamará al método calculadora. * */ public class Calculadora5 { public static void main (String[] args){ Scanner entrada = new Scanner (System.in); entrada.useLocale(Locale.US); double n1; double n2; char caracter; double resultado; System.out.println("----CALCULADORA----"); System.out.print("\nInstrucciones: \nn1 - intro - caracter (+,-,*,/) - intro - n2 - intro\n"); System.out.print("\n "); n1 = entrada.nextDouble(); System.out.print(""); caracter = entrada.next().charAt(0); //Pedir el caracter System.out.print(" "); n2 = entrada.nextDouble(); //Llamamos al método resultado = calculadora (n1, n2, caracter); if (resultado != 0){ System.out.println("________"); System.out.println(" " + resultado); } else{ System.out.println("Operación no disponible"); } } public static double calculadora (double n1, double n2, char caracter){ double resultado; if (caracter == '+'){ resultado = n1 + n2; } else if (caracter == '-'){ resultado = n1 - n2; } else if (caracter == '*'){ resultado = n1 * n2; } else if (caracter == '/'){ resultado = n1 / n2; } else { resultado = 0; } return resultado; } } <file_sep>package alquilerInmuebles; public class Main { /** * @param args the command line arguments */ public static void main(String[] args) { Inmueble inmueble = new Piso(4, 'A', 800, 1, new Direccion("<NAME>", 6, 28803, "<NAME>", "Madrd")); Particular particular = new Particular("Marta", "49587625M", "918856987", "<EMAIL>", 1500, 17); if (particular.esSolvente(inmueble)) { ContratoAlquiler contrato = new ContratoAlquiler(12, particular, inmueble); System.out.println("Contrato formalizado."); System.out.println("Contrato: \n" + contrato.toString()); } else { System.out.println("Contrato no formalizado. inquilino no solvente!"); } Recibo r = new Recibo(inmueble, 1, 800, 50, 25); System.out.println("Recibo: \n" + r.toString()); r.imprimir(); } } <file_sep> import java.time.LocalDateTime; /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ /** * * @author laura */ public class Servicio { private LocalDateTime fecha; private Flota flota; private Ubicacion ubicacionRecogida; private Ubicacion ubicacionDestino; private double distancia; private double coste; private Cliente cliente; private Conductor conductor; private int valoracion; //coonstructor public Servicio(LocalDateTime fecha, Flota flota, Ubicacion ubicacionRecogida, Ubicacion ubicacionDestino, double distancia, double coste, Cliente cliente, Conductor conductor, int valoracion) { this.fecha = fecha; this.flota = flota; this.ubicacionRecogida = ubicacionRecogida; this.ubicacionDestino = ubicacionDestino; this.distancia = distancia; this.coste = coste; this.cliente = cliente; this.conductor = conductor; this.valoracion = valoracion; } public LocalDateTime getFecha() { return fecha; } public void setFecha(LocalDateTime fecha) { this.fecha = fecha; } public Flota getFlota() { return flota; } public void setFlota(Flota flota) { this.flota = flota; } public Ubicacion getUbicacionRecogida() { return ubicacionRecogida; } public void setUbicacionRecogida(Ubicacion ubicacionRecogida) { this.ubicacionRecogida = ubicacionRecogida; } public Ubicacion getUbicacionDestino() { return ubicacionDestino; } public void setUbicacionDestino(Ubicacion ubicacionDestino) { this.ubicacionDestino = ubicacionDestino; } public double getDistancia() { return distancia; } public void setDistancia(double distancia) { this.distancia = distancia; } public static double calcularDistancia(Ubicacion ubicacionRecogida, Ubicacion ubicacionDestino){ double radioTierra = 6371;//en kilómetros double dLat = Math.toRadians(ubicacionDestino.getLatitud() - ubicacionRecogida.getLatitud()); double dLng = Math.toRadians(ubicacionDestino.getLongitud() - ubicacionRecogida.getLongitud()); double sindLat = Math.sin(dLat / 2); double sindLng = Math.sin(dLng / 2); double va1 = Math.pow(sindLat, 2) + Math.pow(sindLng, 2) * Math.cos(Math.toRadians(ubicacionRecogida.getLatitud())) * Math.cos(Math.toRadians(ubicacionDestino.getLatitud())); double va2 = 2 * Math.atan2(Math.sqrt(va1), Math.sqrt(1 - va1)); double distancia = radioTierra * va2; return distancia; } public double getCoste() { return coste; } public void setCoste(double coste) { this.coste = coste; } public static double calcularCoste (Flota flota, Ubicacion ubicacionRecogida, Ubicacion ubicacionDestino){ double coste = 0; double distancia = calcularDistancia(ubicacionRecogida, ubicacionDestino); if ("JUberX" == flota.getTipo()){ coste = distancia * 2; } else if ("JOne" == flota.getTipo()){ coste = distancia * 2.5; } return coste; } public Cliente getCliente() { return cliente; } public void setCliente(Cliente cliente) { this.cliente = cliente; } public Conductor getConductor() { return conductor; } public void setConductor(Conductor conductor) { this.conductor = conductor; } public int getValoracion() { return valoracion; } public void setValoracion(int valoracion) { this.valoracion = valoracion; } @Override public String toString() { return "Servicio{" + "fecha=" + fecha + ", flota=" + flota + ", ubicacionRecogida=" + ubicacionRecogida + ", ubicacionDestino=" + ubicacionDestino + ", distancia=" + distancia + ", coste=" + coste + ", cliente=" + cliente + ", conductor=" + conductor + ", valoracion=" + valoracion + '}'; } } <file_sep>/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package ejerciciosPropuestos2; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.text.DecimalFormat; /** * * @author laura * * Programa que pida tres números y calcule el área del triángulo que forman. * */ public class AreaTriangulo4 { public static void main (String[] args) throws IOException{ BufferedReader entrada = new BufferedReader(new InputStreamReader(System.in)); double l1; double l2; double l3; boolean condicion; double altura; double area; System.out.print("\nLado 1: "); l1 = Double.parseDouble(entrada.readLine()); System.out.print("\nLado 2: "); l2 = Double.parseDouble(entrada.readLine()); System.out.print("\nLado 3: "); l3 = Double.parseDouble(entrada.readLine()); //Comprobar si es un triángulo o no if (l1 < (l2 + l3)){ if (l2 < (l1 + l3)){ if (l3 < (l2 + l1)){ condicion = true; } else{ condicion = false; } } else{ condicion = false; } } else{ condicion = false; } //Calcular área if (condicion == true){ altura = Math.sqrt(Math.pow(l2, 2) - Math.pow(l3/2, 2)); area = l3 * altura / 2; System.out.println("\nÁrea = " + Math.round(area) + " m^2"); } else{ System.out.println("\nNo es un triángulo."); } } } <file_sep>/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package empleados; /** * * @author laura */ public class PruebaEmpleados { public static void main(String[] args) { //1 - creamos la empresa Empresa e1 = new Empresa ("Indra", "1234567"); //2 - creamos los departamentos Departamento d1 = new Departamento(e1, "1", "Madrid", "Informática"); Departamento d2 = new Departamento (e1, "2", "Barcelona", "Personal"); //3 - creamos persona Persona p1 = new Persona ("12345678Z", 25, "soltero", "Pepe"); Persona p2 = new Persona ("45673419T", 35, "casada", "Laura"); Persona p3 = new Persona ("56782345F", 40, "casada", "Rampe"); //4 - creamos los empleados que asignamos a los departamentos Empleado emp1 = new Empleado ("programador", d1, 1500, p1); Empleado emp2 = new Empleado ("analista", d1, 2000, p2); Empleado emp3 = new Empleado ("gerente", d2, 2500, p3); //modificamos los datos de los empleados p1.cumpleaños(); emp1.setSueldo(2000); System.out.println(emp1.toString()); emp2.setCargo("jefe proyecto"); System.out.println(emp2.toString()); //imprimimos los elementos del arrayList System.out.println ("Empleados departamento: " + d1.getEmpleados().toString()); } } <file_sep>/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package aparcamiento; import java.time.LocalDateTime; import java.time.temporal.ChronoUnit; import java.util.Objects; /** * * @author laura */ public class Automovil extends Vehiculo { private String tipo; //constructor public Automovil(String matricula, boolean abono, String tipo) { super (matricula, abono); this.tipo = tipo; } public Automovil(String matricula, LocalDateTime fecha, boolean abono, String tipo) { super (matricula, fecha, abono); this.tipo = tipo; } public String getTipo() { return tipo; } public void setTipo(String tipo) { this.tipo = tipo; } public double calcularImporte(){ LocalDateTime fechaSalida = LocalDateTime.now(); long minutos = ChronoUnit.MINUTES.between(this.getFecha(), fechaSalida); double tasa = 0; double total = 0; switch (tipo){ case "turismo": tasa = 1.5; break; case "todoterreno": tasa = 2.5; break; case "furgoneta": tasa = 3.5; break; } total = minutos + tasa / 60; if (this.isAbono()){ total -= (total * 0.4); } return total; } @Override public String toString() { return super.toString() + " # Automovil{" + "tipo=" + tipo + '}'; } } <file_sep>/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package ejerciciosPropuestos2; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; /** * * @author laura * * Programa que pida tres números y diga si pueden ser los lados de un triángulo. * */ public class LadosTriangulo3 { public static void main (String[] args) throws IOException{ BufferedReader entrada = new BufferedReader(new InputStreamReader(System.in)); double l1; double l2; double l3; System.out.print("\nLado 1: "); l1 = Double.parseDouble(entrada.readLine()); System.out.print("\nLado 2: "); l2 = Double.parseDouble(entrada.readLine()); System.out.print("\nLado 3: "); l3 = Double.parseDouble(entrada.readLine()); if (l1 < (l2 + l3)){ if (l2 < (l1 + l3)){ if (l3 < (l2 + l1)){ System.out.println("\nSí es un triángulo."); } else{ System.out.println("\nNo es un triángulo."); } } else{ System.out.println("\nNo es un triángulo."); } } else{ System.out.println("\nNo es un triángulo."); } } } <file_sep>package alquilerInmuebles; import java.util.ArrayList; public class Edificio extends Inmueble { private String nombre; private ArrayList<Planta> plantas; public Edificio(int id, Direccion direccion) { super(id, direccion); plantas = new ArrayList<>(); } public String getNombre() { return nombre; } public void setNombre(String nombre) { this.nombre = nombre; } public void addPlanta(Planta p) { if (!this.plantas.contains(p)) { this.plantas.add(p); p.setEdificio(this); } } public void removePlanta(Planta p) { if (this.plantas.contains(p)) { this.plantas.remove(p); p.setEdificio(null); } } public ArrayList<Planta> getPlantas() { return plantas; } public void setPlantas(ArrayList<Planta> plantas) { this.plantas = plantas; } @Override public double precioAlquiler() { double precio = 0; for (Planta planta : plantas) { precio += (planta.getPrecio() * planta.getSuperficie()); } return precio; } @Override public String toString() { return "Edificio{" + "nombre=" + nombre + '}'; } } <file_sep>/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package clases; import java.util.Random; /** * * @author laura */ public class Partida { /** * main * @param args */ public static void main(String[] args) { int numZombis = 0; int turnosInicialesSinZombis = 0; int contadorTurno = 1; String[] listaLineaComandos = ExcepcionJuego.pedirInstruccion(contadorTurno); String modoSeleccion = listaLineaComandos[0].toUpperCase(); int numFilas = Integer.parseInt(listaLineaComandos[1]); int numColumnas = Integer.parseInt(listaLineaComandos[2]); String dificultad = listaLineaComandos[3].toUpperCase(); //crear caasilla vacía CasillaVacia casillaVacia = new CasillaVacia(0, 0, 0); //crear y rellenar tablero Objeto[][] tablero = Tablero.crearTablero(numFilas, numColumnas); tablero = Tablero.rellenarTablero(tablero, casillaVacia, numFilas, numColumnas); //asignación de turnos, num zombies, turnos iniciales sin zombies --> según dificultad if ("BAJA".equals(dificultad)) { numZombis = 5; turnosInicialesSinZombis = 10; } else if ("MEDIA".equals(dificultad)) { numZombis = 15; turnosInicialesSinZombis = 7; } else if ("ALTA".equals(dificultad)) { numZombis = 25; turnosInicialesSinZombis = 5; } else if ("IMPOSIBLE".equals(dificultad)) { numZombis = 50; turnosInicialesSinZombis = 5; } //_________________________________________________________________________________ System.out.println("\nComenzando la partida.\n"); Tablero.imprimirTablero(tablero, numFilas, numColumnas); System.out.println("\nTienes 50 soles y es el turno 0."); System.out.println("Quedan " + numZombis + " zombis por salir."); partida(tablero, numFilas, numColumnas, dificultad, casillaVacia, numZombis, turnosInicialesSinZombis); //_________________________________________________________________________________ } /** * Se lleva a cabo la partida * @param tablero * @param numFilas * @param numColumnas * @param dificultad * @param casillaVacia * @param numZombis * @param turnosInicialesSinZombis */ public static void partida(Objeto[][] tablero, int numFilas, int numColumnas, String dificultad, CasillaVacia casillaVacia, int numZombis, int turnosInicialesSinZombis) { int soles = 50; String modoSeleccion = ""; boolean finPartida = false; int filaPG = 0; int columnaPG = 0; int filaPLG = 0; int columnaPLG = 0; int filaZmb = 0; int columnaZmb = 0; int ciclo = 1; int turnosRepartoZombis = 30; int zombisQuedan = 0; int contadorTurno = 1; int contadorPlantaLanzaGuisantes = 0; int contadorPlantaGirasol = 0; int contadorZombis = 0; int contadorZombiesTablero = 0; int contadorZombiesMuertos = 0; boolean comprobadorImprimir = true; ExcepcionPlanta eP = new ExcepcionPlanta(); ExcepcionJuego eJ = new ExcepcionJuego(); String[] listaLineaComandos = ExcepcionJuego.pedirInstruccion(contadorTurno); if (!"".equals(listaLineaComandos[0])) { modoSeleccion = listaLineaComandos[0].toUpperCase(); } else { modoSeleccion = ""; } while (!"S".equals(modoSeleccion)) { //eligen PlantaGirasol if ("N".equals(modoSeleccion)) { System.out.println("Partida comenzada. Si quieres jugar, haz otra partida"); contadorTurno--; //para que no pase turno comprobadorImprimir = false; } else if ("G".equals(modoSeleccion)) { //PlantaGirasol filaPG = Integer.parseInt(listaLineaComandos[1]) - 1; columnaPG = Integer.parseInt(listaLineaComandos[2]) - 1; try { //dentro del tablero eP.fueraTablero(numFilas, numColumnas, filaPG, columnaPG); try { //no última columna eP.ultimaColumna(numColumnas, columnaPG); try { //casilla no ocupada eP.casillaOcupada(tablero, filaPG, columnaPG); PlantaGirasol planta = PlantaGirasol.crearPlantaGirasol(); try { //suficientes soles eP.comprarPlantas(soles, planta); if (soles - planta.getCoste() >= 0) { soles = soles - planta.getCoste(); tablero[filaPG][columnaPG] = PlantaGirasol.crearPlantaGirasol(); //coste, resistencia, frecuencia, daño, ciclo contadorPlantaGirasol++; tablero[filaPG][columnaPG].setCiclo(1); } } catch (MiExcepcion mE) { System.out.println("\n" + mE.getMessage()); } } catch (MiExcepcion mE) { System.out.println("\n" + mE.getMessage()); } } catch (MiExcepcion mE) { System.out.println("\n" + mE.getMessage()); } } catch (Exception e) { System.out.println("\n¡¡¡Fuera del tablero!!!"); } } else if ("L".equals(modoSeleccion)) { //eligen PlantaLanzaGuisantes filaPLG = Integer.parseInt(listaLineaComandos[1]) - 1; columnaPLG = Integer.parseInt(listaLineaComandos[2]) - 1; try { //dentro del tablero eP.fueraTablero(numFilas, numColumnas, filaPLG, columnaPLG); try { //no última columna eP.ultimaColumna(numColumnas, columnaPLG); try { //casilla no ocupada eP.casillaOcupada(tablero, filaPLG, columnaPLG); PlantaLanzaGuisantes planta = PlantaLanzaGuisantes.crearPlantaLanzaGuisantes(); try { //suficientes soles eP.comprarPlantas(soles, planta); if (soles - planta.getCoste() >= 0) { soles = soles - planta.getCoste(); tablero[filaPLG][columnaPLG] = PlantaLanzaGuisantes.crearPlantaLanzaGuisantes(); //coste, resistencia, frecuencia, daño, ciclo contadorPlantaLanzaGuisantes++; tablero[filaPG][columnaPG].setCiclo(1); } } catch (MiExcepcion mE) { System.out.println("\n" + mE.getMessage()); } } catch (MiExcepcion mE) { System.out.println("\n" + mE.getMessage()); } } catch (MiExcepcion mE) { System.out.println("\n" + mE.getMessage()); } } catch (Exception e) { System.out.println("\n¡¡¡Fuera del tablero!!!"); } } //zombies Random aleatorio = new Random(); if (turnosInicialesSinZombis <= 0 && contadorZombis < numZombis) { int contAleatorio = aleatorio.nextInt(2); //para que los Zmbs salgan cuando quieran if (contAleatorio == 1) { filaZmb = aleatorio.nextInt(numFilas); columnaZmb = numColumnas - 1; if (tablero[filaZmb][columnaZmb] instanceof CasillaVacia) { //para que no salga un zmb sobre otro tablero[filaZmb][columnaZmb] = Zombie.crearZombie(); contadorZombis++; contadorZombiesTablero++; } } } //--------------------------------------------------------------------------------------- zombisQuedan = numZombis - contadorZombis; System.out.println(""); if (comprobadorImprimir == true){ Tablero.imprimirTablero(tablero, numFilas, numColumnas); System.out.println("\nTienes " + soles + " soles y es el turno " + contadorTurno); System.out.println("Quedan " + zombisQuedan + " zombis por salir."); contadorTurno++; turnosInicialesSinZombis--; } comprobadorImprimir = true; //--------------------------------------------------------------------------------------- //finPartida == true if (finPartida(tablero, numFilas, numColumnas, contadorZombis, numZombis, contadorTurno) == true) { if (contadorZombis == numZombis) { System.out.println("\nHan ganado las PLANTAS!!!!"); } else { System.out.println("\nHan ganado los ZOMBIES!!!!"); } System.exit(0); } //movimientos for (int i = 0; i < numFilas; i++) { int contadorDanioFila = 0; for (int j = 0; j < numColumnas; j++) { if (tablero[i][j] instanceof PlantaGirasol) { //Planta Girasol if (tablero[i][j].getCiclo() == -1) { soles = PlantaGirasol.generarSoles(soles); tablero[i][j].setCiclo(1); } else { tablero[i][j].setCiclo(-1); } } else if (tablero[i][j] instanceof PlantaLanzaGuisantes) { //Planta LanzaGuisantes contadorDanioFila++; } if (tablero[i][j] instanceof Zombie) { //Zombie tablero[i][j].setResistencia(tablero[i][j].getResistencia() - contadorDanioFila); if (tablero[i][j].getCiclo() == -1) { //para controlar que sea cada dos cicols tablero[i][j].setCiclo(1); //a la siguiente descansa if (tablero[i][j].getResistencia() > 0) { tablero = Zombie.movimientoZmb(tablero, i, j, casillaVacia); } else { //muere zombie tablero[i][j] = casillaVacia; contadorZombiesTablero--; contadorZombiesMuertos++; } } else if (tablero[i][j].getCiclo() == 1) { tablero[i][j].setCiclo(-1); } } if (tablero[i][j].getResistencia() <= 0){ tablero[i][j] = casillaVacia; } } } //---------------------------------------------------------------------------------------- if (finPartida == false) { listaLineaComandos = ExcepcionJuego.pedirInstruccion(contadorTurno); if (!"".equals(listaLineaComandos[0])) { modoSeleccion = listaLineaComandos[0].toUpperCase(); } else { modoSeleccion = ""; } } //--------------------------------------------------------------------------------------- } System.out.println("\nHas abandonado la partida."); } /** * Comprueba si la partida debe terminar * @param tablero * @param numFilas * @param numColumnas * @param contadorZombis * @param numZombis * @param contadorTurno * @return boolean */ public static boolean finPartida(Objeto[][] tablero, int numFilas, int numColumnas, int contadorZombis, int numZombis, int contadorTurno) { if (finPartidaTurno30 (contadorTurno) == true){ //turno 30 return true; } else if (finPartidaZmbColumna0(tablero, numFilas, numColumnas) == true){ //zmbs en columna 0 return true; } else if (finPartidaQuedan0Zmb(tablero, numFilas, numColumnas, contadorZombis, numZombis) == true){ //no quedan más zombis por salir y no hay zombis en tablero return true; } else { return false; } } /** * Comprueba si el num del turno es mayor a 30 * @param contadorTurno * @return boolean */ public static boolean finPartidaTurno30 (int contadorTurno){ if (contadorTurno > 30) { return true; } else { return false; } } /** * Comprueba si hay Zmb en la columna 0 * @param tablero * @param numFilas * @param numColumnas * @return boolean */ public static boolean finPartidaZmbColumna0(Objeto[][] tablero, int numFilas, int numColumnas) { int comprobacion = 0; for (int i = 0; i < numFilas; i++) { if (tablero[i][0] instanceof Zombie) { comprobacion++; } } if (comprobacion > 0){ return true; } else { return false; } } /** * Comprueba si ya no quedan por salir más zmb y si no hay zmbs en el tablero * @param tablero * @param numFilas * @param numColumnas * @param contadorZombis * @param numZombis * @param zombisQuedan * @return boolean */ public static boolean finPartidaQuedan0Zmb(Objeto[][] tablero, int numFilas, int numColumnas, int contadorZombis, int numZombis) { if (contadorZombis == numZombis) { int comprobacion = 0; for (int i = 0; i < numFilas; i++) { for (int j = 0; j < numColumnas; j++) { if (tablero[i][j] instanceof Zombie) { comprobacion++; } } } if (comprobacion > 0) { return false; } else { return true; } } else { return false; } } }<file_sep>/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package cadenasCaracteres.stringTokenizer; import java.util.Scanner; import java.util.StringTokenizer; /** * * @author laura * * Escribir un programa que lea una frase y nos diga cuántas palabras la componen. * */ public class NumPalabrasEnFarseST2 { public static void main (String[] args){ Scanner entrada = new Scanner(System.in); String frase; String palabra; int contador = 0; System.out.print("Frase: "); frase = entrada.nextLine(); StringTokenizer st = new StringTokenizer(frase); while (st.hasMoreTokens()){ contador += 1; palabra = st.nextToken(); } System.out.println("\nLa frase tiene " + contador + " palabra(s)."); } } <file_sep>/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package cadenasCaracteres.stringSplit; import java.util.Scanner; /** * * @author laura * * Escribir un programa al que se le pasa un número de teléfono de la forma: 91-8885566. El programa deberá usar la clase StringTokenizer para extraer el código de la comunidad y el resto del número, convertir el código de la comunidad en int y el resto en long, y presentarlo por pantalla. * */ public class NumeroTelefonoSS1 { public static void main (String[] args){ Scanner entrada = new Scanner(System.in); String telf; int prefijo; long num; System.out.println("\nNum teléfono (ej: 91-8885566): "); telf = entrada.nextLine(); String telefono[] = telf.split("-"); prefijo = Integer.parseInt(telefono[0]); num = Long.parseLong(telefono[1]); System.out.println("Prefijo: " + prefijo + "\nNúmero: " + num); } } <file_sep>/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package ejerciciosPropuestos2; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; /** * * @author laura * * Programa que pida un entero n>=0 y calcule el factorial(n). */ public class Factorial2 { public static void main (String[] args) throws IOException{ BufferedReader entrada = new BufferedReader(new InputStreamReader(System.in)); int n; int nInicial; int factorial; System.out.print("\nNúmero: "); n = Integer.parseInt(entrada.readLine()); nInicial = n; factorial = 1; while (n != 0){ factorial *= n; n -= 1; } System.out.println(nInicial + "! = " + factorial); } } <file_sep>/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package clases; import java.util.ArrayList; /** * * @author laura */ public class PartidaMedia extends PartidaDificultad { private int puntos; public PartidaMedia(String dificultad) { super(dificultad); } public PartidaMedia(ArrayList<Partida> partidaMedia, String dificultad, int puntos) { super(dificultad); this.partidaMedia = partidaMedia; this.puntos = puntos; } public int getPuntos() { return puntos; } public void setPuntos(int puntos, ArrayList partidaMedia) { this.puntos = puntos; puntos = Partida.calcularPuntos(partidaMedia); } private ArrayList<Partida> partidaMedia; public ArrayList<Partida> getPartidasMedias() { return partidaMedia; } public void setPartidaMedia(ArrayList<Partida> partidaMedia) { this.partidaMedia = partidaMedia; } public static PartidaMedia crearPartidaMedia() { PartidaMedia partidaMedia = new PartidaMedia("MEDIA"); return partidaMedia; } } <file_sep>/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ /** * * @author laura */ public class Conductor extends Persona{ private double salario; //constructor public Conductor(String nombre, String dni, String correo, int telefono, double salario) { super (nombre, dni, correo, telefono); this.salario = salario; } public double getSalario() { return salario; } public void setSalario(double salario) { this.salario = salario; } public double calcularSalario (Flota flota, Ubicacion ubicacionRecogida, Ubicacion ubicacionDestino){ salario = 0.5 * Servicio.calcularCoste(flota, ubicacionRecogida, ubicacionDestino); return salario; } @Override public int hashCode() { int hash = 3; hash = 13 * hash + (int) (Double.doubleToLongBits(this.salario) ^ (Double.doubleToLongBits(this.salario) >>> 32)); return hash; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final Conductor other = (Conductor) obj; if (Double.doubleToLongBits(this.salario) != Double.doubleToLongBits(other.salario)) { return false; } return true; } @Override public String toString() { return "Conductor{" + "salario=" + salario + '}'; } } <file_sep>/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package modularidad.ejercicios; import java.util.Scanner; /** * * @author laura * * Reutilizando el programa anterior escribir solo los números pares en el rango de valores. El método auxiliar encargado de imprimir todos los valores que se encuentren en su rango tiene que hacer uso de otra función llamada esPar(int num) que devolverá un booleano indicando si el número es par o no. * */ public class SoloPares2 { public static void main (String[] args){ Scanner entrada = new Scanner(System.in); int mayor; int menor; System.out.println("\nIntroduce el número menor: "); menor = entrada.nextInt(); System.out.println("\nIntroduce el número mayor: "); mayor = entrada.nextInt(); //Llamamos al método imprimir(menor, mayor); } public static void imprimir (int menor, int mayor){ for (int i = menor; i < (mayor + 1); i++){ //llamamos al método esPar (i); if (esPar(i) == true){ System.out.print(" " + i); } } } public static boolean esPar (int num){ if (num % 2 == 0){ return true; } else{ return false; } } } <file_sep>package presentacion; import logica.Ordenador; import logica.Telefono; import logica.UtilTienda; import logica.Producto; import java.awt.HeadlessException; import javax.swing.JOptionPane; public class AltaProductosD extends javax.swing.JDialog { private String tipo = ""; private Producto pro = null; /** * Creates new form AltaProductosD * @param parent la ventana principal * @param modal true para que solo podamos operar con esta ventana */ public AltaProductosD(java.awt.Frame parent, boolean modal) { super(parent, modal); initComponents(); jComboBoxTipo.setSelectedIndex(0); this.setVisible(true); } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jLabel1 = new javax.swing.JLabel(); jButtonAlta = new javax.swing.JButton(); jComboBoxTipo = new javax.swing.JComboBox(); jButtonBorrar = new javax.swing.JButton(); panelDatos = new presentacion.PanelDatos(); setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE); setTitle("Altas"); jLabel1.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N jLabel1.setText("ALTA DE PRODUCTOS"); jButtonAlta.setText("ALTA"); jButtonAlta.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButtonAltaActionPerformed(evt); } }); jComboBoxTipo.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Ordenador", "Telefono" })); jComboBoxTipo.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jComboBoxTipoActionPerformed(evt); } }); jButtonBorrar.setText("BORRAR"); jButtonBorrar.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButtonBorrarActionPerformed(evt); } }); panelDatos.setBackground(new java.awt.Color(51, 255, 51)); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(107, 107, 107) .addComponent(jLabel1)) .addGroup(layout.createSequentialGroup() .addGap(163, 163, 163) .addComponent(jButtonBorrar))) .addContainerGap(152, Short.MAX_VALUE)) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addGap(61, 61, 61) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(panelDatos, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addGroup(layout.createSequentialGroup() .addComponent(jButtonAlta) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jComboBoxTipo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))) .addGap(73, 73, 73)) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addComponent(jLabel1) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jButtonAlta) .addComponent(jComboBoxTipo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(18, 18, 18) .addComponent(panelDatos, javax.swing.GroupLayout.DEFAULT_SIZE, 168, Short.MAX_VALUE) .addGap(18, 18, 18) .addComponent(jButtonBorrar) .addContainerGap()) ); pack(); setLocationRelativeTo(null); }// </editor-fold>//GEN-END:initComponents private void jButtonAltaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonAltaActionPerformed // TODO add your handling code here: try { String codigo = panelDatos.getJTextFieldCodigo(); String nombre = panelDatos.getJTextFieldNombre(); double precio = Double.parseDouble(panelDatos.getJTextFieldPrecio()); int cantidad = Integer.parseInt(panelDatos.getJTextFieldCantidad()); String var = panelDatos.getJTextFieldVar(); if (tipo.equals("Ordenador")) { pro = new Ordenador(codigo, nombre, precio, cantidad, var); } else { pro = new Telefono(codigo, nombre, precio, cantidad, var); } System.out.println(pro.toString()); //lo insertamos en el array if (UtilTienda.altaProducto(pro)) { JOptionPane.showMessageDialog(this, "Producto dado de alta.", "Mensaje", JOptionPane.INFORMATION_MESSAGE); } else { JOptionPane.showMessageDialog(this, "Error al dar de alta.", "Mensaje", JOptionPane.ERROR_MESSAGE); } } catch (HeadlessException | NumberFormatException e) { JOptionPane.showMessageDialog(this, "Excepción al dar de alta.", "Mensaje", JOptionPane.ERROR_MESSAGE); } }//GEN-LAST:event_jButtonAltaActionPerformed private void jComboBoxTipoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jComboBoxTipoActionPerformed // TODO add your handling code here: tipo = (String) jComboBoxTipo.getSelectedItem(); if (tipo.equals("Ordenador")) { panelDatos.setLabelVar("Caracteristicas"); } else { panelDatos.setLabelVar("Operador"); } }//GEN-LAST:event_jComboBoxTipoActionPerformed private void jButtonBorrarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonBorrarActionPerformed // TODO add your handling code here: panelDatos.borrar(); }//GEN-LAST:event_jButtonBorrarActionPerformed // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton jButtonAlta; private javax.swing.JButton jButtonBorrar; private javax.swing.JComboBox jComboBoxTipo; private javax.swing.JLabel jLabel1; private presentacion.PanelDatos panelDatos; // End of variables declaration//GEN-END:variables } <file_sep>/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package ejerciciosPropuestos2; import java.util.Scanner; /** * * @author laura * * Programa que pida un entero n e imprima el primer número primo >=n. * */ public class PrimoMayor9 { public static void main (String[] args){ Scanner entrada = new Scanner(System.in); int n; boolean primo; System.out.print("\nIntroduce un número: "); //lectura de un int n = entrada.nextInt(); if (n == 0 || n == 1){ primo = false; } else if (n == 2 || n == 3 || n == 5 || n == 7){ primo = true; } else if (n % 2 == 0 || n % 3 == 0 || n % 5 == 0|| n % 7 == 0){ primo = false; } else{ primo = true; } if (primo == true){ System.out.println(n); } else{ while (primo != true){ n += 1; if (n == 0 || n == 1){ primo = false; } else if (n == 2 || n == 3 || n == 5 || n == 7){ primo = true; } else if (n % 2 == 0 || n % 3 == 0 || n % 5 == 0|| n % 7 == 0){ primo = false; } else{ primo = true; } } System.out.println(n); } } } <file_sep>package alquilerInmuebles; public class Planta { private int numero; private int superficie; private double precio; private Edificio edificio; public Planta(int numero, int superficie, int precio, Edificio edificio) { this.numero = numero; this.superficie = superficie; this.precio = precio; this.edificio = edificio; } public int getNumero() { return numero; } public void setNumero(int numero) { this.numero = numero; } public int getSuperficie() { return superficie; } public void setSuperficie(int superficie) { this.superficie = superficie; } public double getPrecio() { return precio; } public void setPrecio(double precio) { this.precio = precio; } public Edificio getEdificio() { return edificio; } public void setEdificio(Edificio edificio) { this.edificio = edificio; } public double getPrecioMensual() { return superficie * precio; } @Override public String toString() { return "Planta{" + "numero=" + numero + ", superficie=" + superficie + ", precio=" + precio + ", edificio=" + edificio + '}'; } } <file_sep>/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ /** * * @author laura */ public class Cadenass { public static void main (String[] args){ String cadena = "Hola me llamo Laura."; String palabra = "Hola"; String variableString = "45781"; //CAMBIAR TIPO DE DATO int variable = Integer.parseInt(variableString); //pasar de string a int //CORTAR CADENA cadena.substring(7); // Nos devuelve a partir del elemento 7 String subCadena = cadena.substring(5,10); // Nos devuelve los elementos 5,6,7,8 y 9 System.out.println("Posición:" + palabra.indexOf("a")); //devuelve la posicion en la que se encuentra la letra //MAYÚSCULAS Y MINÚSCULAS String sCadena = "Esto Es Una Cadena De TEXTO"; System.out.println(sCadena.toLowerCase()); //pasar toda la cadena a minúsculas System.out.println(sCadena.toUpperCase()); //pasar toda la cadena a mayúsculas //for (int i = 0; i < palabra.length();i++) //recorrer cadena //LISTAS Y CADENAS char[] lista = palabra.toCharArray(); //pasa cada letra a ser un elemento de la lista String[] listaCadena = cadena.split("\\s+"); //te mete cada palabra de la cadena como un element } } <file_sep>/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package interfaces; import clases.CasillaVacia; import clases.Objeto; import clases.Tablero; import static clases.Tablero.movimientos; import static clases.Tablero.agregarZombie; import com.sun.glass.events.KeyEvent; import java.util.Scanner; import javax.swing.ImageIcon; import clases.ExcepcionJuego; import clases.ExcepcionPlanta; import clases.PlantaGirasol; import clases.Planta; import clases.PlantaLanzaGuisantes; import clases.PlantaNuez; import clases.PlantaPetaCereza; import static clases.ExcepcionPlanta.comprarPlantas; import static clases.ExcepcionPlanta.casillaOcupada; import static clases.ExcepcionPlanta.fueraTablero; import static clases.ExcepcionPlanta.ultimaColumna; import static clases.ExcepcionJuego.imprimirLineaComandos; import static clases.ExcepcionJuego.pedirInstruccion; import clases.Historial; import clases.MiExcepcion; import clases.Usuario; import clases.ZombieCaraCubo; import clases.ZombieComun; import clases.ZombieDeportista; import java.awt.Image; import java.util.HashMap; import java.util.Random; import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.Icon; import javax.swing.JLabel; import javax.swing.JOptionPane; /** * * @author laura */ public class PartidaInterfaz extends javax.swing.JFrame { /** * Creates new form PartidaInterfaz */ private static Usuario usuario; private static HashMap<String, clases.Historial> torneo; private static String dificultad = null; private static Objeto[][] tablero; private CasillaVacia casillaVacia; private int[] soles = {50}; private int[] contadorTurno = {1}; private int[] turnosInicialesSinZombis = {0}; int[] contadorZombisQuedan = {0}; int[] contadorZombis = {0}; private int numZombies = 0; public int[] puntos = {0}; boolean terminada = false; boolean ganada = false; public PartidaInterfaz(HashMap<String, clases.Historial> torne, Usuario usuari, String dificulta) { usuario = usuari; torneo = torne; dificultad = dificulta; initComponents(); transparenciaBoton(); this.setLocationRelativeTo(null); //ajustarlo en el medio de la pantalla int[] turnosInicialesSinZombis = turnosSinZombies(); int numZombies = numZombies(); setIconImage(new ImageIcon(getClass().getResource("/imagenes/icono.jpg")).getImage()); //cambiar logo casillaVacia = new CasillaVacia(0, 0, 0, 0); jLabel_turno_Partida.setText(Integer.toString(contadorTurno[0])); if (contadorZombisQuedan[0] == 0) { contadorZombisQuedan[0] = numZombies; } asignarNombreJLabel(); tablero = Tablero.rellenarTableroInterfaz(5, 9, casillaVacia); jLabel_numSoles_Partida.setText(Integer.toString(soles[0])); textField_zmbQuedan.setText(Integer.toString(contadorZombisQuedan[0])); } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { botonSalir_Partida = new javax.swing.JButton(); tablero_0_0 = new javax.swing.JLabel(); tablero_0_1 = new javax.swing.JLabel(); tablero_0_2 = new javax.swing.JLabel(); tablero_0_3 = new javax.swing.JLabel(); tablero_0_4 = new javax.swing.JLabel(); tablero_0_5 = new javax.swing.JLabel(); tablero_0_6 = new javax.swing.JLabel(); tablero_0_7 = new javax.swing.JLabel(); tablero_0_8 = new javax.swing.JLabel(); tablero_1_0 = new javax.swing.JLabel(); tablero_1_1 = new javax.swing.JLabel(); tablero_1_2 = new javax.swing.JLabel(); tablero_1_3 = new javax.swing.JLabel(); tablero_1_4 = new javax.swing.JLabel(); tablero_1_5 = new javax.swing.JLabel(); tablero_1_6 = new javax.swing.JLabel(); tablero_1_7 = new javax.swing.JLabel(); tablero_1_8 = new javax.swing.JLabel(); tablero_2_0 = new javax.swing.JLabel(); tablero_2_1 = new javax.swing.JLabel(); tablero_2_2 = new javax.swing.JLabel(); tablero_2_3 = new javax.swing.JLabel(); tablero_2_4 = new javax.swing.JLabel(); tablero_2_5 = new javax.swing.JLabel(); tablero_2_6 = new javax.swing.JLabel(); tablero_2_7 = new javax.swing.JLabel(); tablero_2_8 = new javax.swing.JLabel(); tablero_3_0 = new javax.swing.JLabel(); tablero_3_1 = new javax.swing.JLabel(); tablero_3_2 = new javax.swing.JLabel(); tablero_3_3 = new javax.swing.JLabel(); tablero_3_4 = new javax.swing.JLabel(); tablero_3_5 = new javax.swing.JLabel(); tablero_3_6 = new javax.swing.JLabel(); tablero_3_7 = new javax.swing.JLabel(); tablero_3_8 = new javax.swing.JLabel(); tablero_4_0 = new javax.swing.JLabel(); tablero_4_1 = new javax.swing.JLabel(); tablero_4_2 = new javax.swing.JLabel(); tablero_4_3 = new javax.swing.JLabel(); tablero_4_4 = new javax.swing.JLabel(); tablero_4_5 = new javax.swing.JLabel(); tablero_4_6 = new javax.swing.JLabel(); tablero_4_7 = new javax.swing.JLabel(); tablero_4_8 = new javax.swing.JLabel(); textField_lineaComandos_Partida = new javax.swing.JTextField(); textField_zmbQuedan = new javax.swing.JTextField(); jLabel_turno_Partida = new javax.swing.JLabel(); jLabel_numSoles_Partida = new javax.swing.JLabel(); jLabelCostePLG = new javax.swing.JLabel(); jLabelPG = new javax.swing.JLabel(); jLabelCostePPC = new javax.swing.JLabel(); jLabelCostePPC1 = new javax.swing.JLabel(); fondoPartida = new javax.swing.JLabel(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); setResizable(false); getContentPane().setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout()); botonSalir_Partida.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { botonSalir_PartidaMouseClicked(evt); } }); getContentPane().add(botonSalir_Partida, new org.netbeans.lib.awtextra.AbsoluteConstraints(610, 90, 110, 20)); getContentPane().add(tablero_0_0, new org.netbeans.lib.awtextra.AbsoluteConstraints(50, 260, 100, 130)); tablero_0_1.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { tablero_0_1MouseClicked(evt); } }); getContentPane().add(tablero_0_1, new org.netbeans.lib.awtextra.AbsoluteConstraints(170, 250, 100, 130)); tablero_0_2.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { tablero_0_2MouseClicked(evt); } }); getContentPane().add(tablero_0_2, new org.netbeans.lib.awtextra.AbsoluteConstraints(280, 250, 100, 130)); getContentPane().add(tablero_0_3, new org.netbeans.lib.awtextra.AbsoluteConstraints(400, 240, 100, 130)); getContentPane().add(tablero_0_4, new org.netbeans.lib.awtextra.AbsoluteConstraints(520, 250, 100, 130)); getContentPane().add(tablero_0_5, new org.netbeans.lib.awtextra.AbsoluteConstraints(650, 240, 100, 130)); getContentPane().add(tablero_0_6, new org.netbeans.lib.awtextra.AbsoluteConstraints(760, 250, 100, 140)); getContentPane().add(tablero_0_7, new org.netbeans.lib.awtextra.AbsoluteConstraints(880, 260, 100, 130)); getContentPane().add(tablero_0_8, new org.netbeans.lib.awtextra.AbsoluteConstraints(991, 266, 100, 130)); getContentPane().add(tablero_1_0, new org.netbeans.lib.awtextra.AbsoluteConstraints(50, 400, 100, 130)); getContentPane().add(tablero_1_1, new org.netbeans.lib.awtextra.AbsoluteConstraints(160, 400, 100, 130)); getContentPane().add(tablero_1_2, new org.netbeans.lib.awtextra.AbsoluteConstraints(280, 390, 100, 130)); getContentPane().add(tablero_1_3, new org.netbeans.lib.awtextra.AbsoluteConstraints(400, 400, 100, 130)); getContentPane().add(tablero_1_4, new org.netbeans.lib.awtextra.AbsoluteConstraints(520, 400, 100, 130)); getContentPane().add(tablero_1_5, new org.netbeans.lib.awtextra.AbsoluteConstraints(640, 400, 100, 130)); getContentPane().add(tablero_1_6, new org.netbeans.lib.awtextra.AbsoluteConstraints(760, 400, 100, 130)); getContentPane().add(tablero_1_7, new org.netbeans.lib.awtextra.AbsoluteConstraints(870, 400, 100, 130)); getContentPane().add(tablero_1_8, new org.netbeans.lib.awtextra.AbsoluteConstraints(1000, 400, 100, 130)); getContentPane().add(tablero_2_0, new org.netbeans.lib.awtextra.AbsoluteConstraints(50, 540, 100, 130)); getContentPane().add(tablero_2_1, new org.netbeans.lib.awtextra.AbsoluteConstraints(170, 540, 100, 130)); getContentPane().add(tablero_2_2, new org.netbeans.lib.awtextra.AbsoluteConstraints(280, 550, 100, 130)); getContentPane().add(tablero_2_3, new org.netbeans.lib.awtextra.AbsoluteConstraints(410, 540, 100, 130)); getContentPane().add(tablero_2_4, new org.netbeans.lib.awtextra.AbsoluteConstraints(530, 540, 100, 130)); getContentPane().add(tablero_2_5, new org.netbeans.lib.awtextra.AbsoluteConstraints(640, 550, 100, 130)); getContentPane().add(tablero_2_6, new org.netbeans.lib.awtextra.AbsoluteConstraints(760, 550, 100, 130)); getContentPane().add(tablero_2_7, new org.netbeans.lib.awtextra.AbsoluteConstraints(870, 550, 100, 130)); getContentPane().add(tablero_2_8, new org.netbeans.lib.awtextra.AbsoluteConstraints(1000, 550, 100, 130)); getContentPane().add(tablero_3_0, new org.netbeans.lib.awtextra.AbsoluteConstraints(41, 686, 100, 130)); getContentPane().add(tablero_3_1, new org.netbeans.lib.awtextra.AbsoluteConstraints(160, 690, 100, 130)); getContentPane().add(tablero_3_2, new org.netbeans.lib.awtextra.AbsoluteConstraints(290, 690, 100, 130)); getContentPane().add(tablero_3_3, new org.netbeans.lib.awtextra.AbsoluteConstraints(400, 700, 100, 130)); getContentPane().add(tablero_3_4, new org.netbeans.lib.awtextra.AbsoluteConstraints(520, 690, 100, 130)); getContentPane().add(tablero_3_5, new org.netbeans.lib.awtextra.AbsoluteConstraints(640, 690, 100, 130)); getContentPane().add(tablero_3_6, new org.netbeans.lib.awtextra.AbsoluteConstraints(760, 690, 100, 130)); getContentPane().add(tablero_3_7, new org.netbeans.lib.awtextra.AbsoluteConstraints(880, 690, 100, 130)); getContentPane().add(tablero_3_8, new org.netbeans.lib.awtextra.AbsoluteConstraints(1010, 690, 100, 130)); getContentPane().add(tablero_4_0, new org.netbeans.lib.awtextra.AbsoluteConstraints(40, 830, 100, 130)); getContentPane().add(tablero_4_1, new org.netbeans.lib.awtextra.AbsoluteConstraints(170, 840, 100, 130)); getContentPane().add(tablero_4_2, new org.netbeans.lib.awtextra.AbsoluteConstraints(280, 840, 100, 130)); getContentPane().add(tablero_4_3, new org.netbeans.lib.awtextra.AbsoluteConstraints(410, 840, 100, 130)); getContentPane().add(tablero_4_4, new org.netbeans.lib.awtextra.AbsoluteConstraints(530, 830, 100, 130)); getContentPane().add(tablero_4_5, new org.netbeans.lib.awtextra.AbsoluteConstraints(650, 840, 100, 130)); getContentPane().add(tablero_4_6, new org.netbeans.lib.awtextra.AbsoluteConstraints(760, 830, 100, 130)); getContentPane().add(tablero_4_7, new org.netbeans.lib.awtextra.AbsoluteConstraints(880, 830, 100, 130)); getContentPane().add(tablero_4_8, new org.netbeans.lib.awtextra.AbsoluteConstraints(1000, 830, 100, 130)); textField_lineaComandos_Partida.setFont(new java.awt.Font("Cooper Black", 0, 15)); // NOI18N textField_lineaComandos_Partida.setHorizontalAlignment(javax.swing.JTextField.CENTER); textField_lineaComandos_Partida.addKeyListener(new java.awt.event.KeyAdapter() { public void keyPressed(java.awt.event.KeyEvent evt) { textField_lineaComandos_PartidaKeyPressed(evt); } }); getContentPane().add(textField_lineaComandos_Partida, new org.netbeans.lib.awtextra.AbsoluteConstraints(610, 12, 110, 30)); textField_zmbQuedan.setFont(new java.awt.Font("Cooper Black", 0, 18)); // NOI18N textField_zmbQuedan.setHorizontalAlignment(javax.swing.JTextField.CENTER); textField_zmbQuedan.addKeyListener(new java.awt.event.KeyAdapter() { public void keyTyped(java.awt.event.KeyEvent evt) { textField_zmbQuedanKeyTyped(evt); } }); getContentPane().add(textField_zmbQuedan, new org.netbeans.lib.awtextra.AbsoluteConstraints(510, 90, 83, 30)); jLabel_turno_Partida.setFont(new java.awt.Font("Cooper Black", 0, 15)); // NOI18N jLabel_turno_Partida.setForeground(new java.awt.Color(255, 255, 255)); jLabel_turno_Partida.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); getContentPane().add(jLabel_turno_Partida, new org.netbeans.lib.awtextra.AbsoluteConstraints(680, 60, 40, 20)); jLabel_numSoles_Partida.setFont(new java.awt.Font("Cooper Black", 0, 24)); // NOI18N jLabel_numSoles_Partida.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); getContentPane().add(jLabel_numSoles_Partida, new org.netbeans.lib.awtextra.AbsoluteConstraints(20, 90, 80, 40)); jLabelCostePLG.setFont(new java.awt.Font("Cooper Black", 0, 18)); // NOI18N jLabelCostePLG.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); jLabelCostePLG.setText("50"); getContentPane().add(jLabelCostePLG, new org.netbeans.lib.awtextra.AbsoluteConstraints(310, 78, 70, 50)); jLabelPG.setFont(new java.awt.Font("Cooper Black", 0, 18)); // NOI18N jLabelPG.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); jLabelPG.setText("20"); getContentPane().add(jLabelPG, new org.netbeans.lib.awtextra.AbsoluteConstraints(230, 89, 50, 30)); jLabelCostePPC.setFont(new java.awt.Font("Cooper Black", 0, 18)); // NOI18N jLabelCostePPC.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); jLabelCostePPC.setText("50"); getContentPane().add(jLabelCostePPC, new org.netbeans.lib.awtextra.AbsoluteConstraints(410, 78, 60, 50)); jLabelCostePPC1.setFont(new java.awt.Font("Cooper Black", 0, 18)); // NOI18N jLabelCostePPC1.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); jLabelCostePPC1.setText("50"); getContentPane().add(jLabelCostePPC1, new org.netbeans.lib.awtextra.AbsoluteConstraints(132, 78, 60, 50)); fondoPartida.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imagenes/fondoPartida.png"))); // NOI18N getContentPane().add(fondoPartida, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 0, -1, -1)); pack(); }// </editor-fold>//GEN-END:initComponents private void botonSalir_PartidaMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_botonSalir_PartidaMouseClicked // TODO add your handling code here: SalirJuego salirJuego = new SalirJuego(torneo, usuario, dificultad, tablero, puntos, terminada, ganada); salirJuego.setVisible(true); this.dispose(); }//GEN-LAST:event_botonSalir_PartidaMouseClicked private void tablero_0_1MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_tablero_0_1MouseClicked // TODO add your handling code here: // hacer un dialog con la resistencia que queda }//GEN-LAST:event_tablero_0_1MouseClicked private void tablero_0_2MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_tablero_0_2MouseClicked // TODO add your handling code here: }//GEN-LAST:event_tablero_0_2MouseClicked private void textField_zmbQuedanKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_textField_zmbQuedanKeyTyped // No admite el ingreso ni de letras ni de caracteres char c = evt.getKeyChar(); if (c < 'a' || c > 'z' || c < '0' || c > '9') { evt.consume(); } }//GEN-LAST:event_textField_zmbQuedanKeyTyped private void textField_lineaComandos_PartidaKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_textField_lineaComandos_PartidaKeyPressed // TODO add your handling code here String modoSeleccion = null; String posicionTablero = null; String[] listaLineaComandos; //te mete cada palabra de la cadena como un element if (evt.getKeyCode() == KeyEvent.VK_ENTER) { //enter listaLineaComandos = textField_lineaComandos_Partida.getText().split("\\s+"); //te mete cada palabra de la cadena como un element if (!ExcepcionJuego.comprobarInstruccion(listaLineaComandos)) { //está mal JOptionPane.showMessageDialog(this, "¡¡¡Instrucción no válida!!!"); textField_lineaComandos_Partida.setText(""); } else { //está bien textField_lineaComandos_Partida.setText(""); if ("AYUDA".equals(listaLineaComandos[0].toUpperCase())) { JOptionPane.showMessageDialog(this, "G <fila> <columna>: colocar girasol. \nL <fila> <columna>: colocar LanzaGuisantes. \nN <fila> <columna>: colocar Nuez. \nP <fila> <columna>: colocar PetaCereza. \nPASO : pasar turno."); textField_lineaComandos_Partida.setText(""); } else { modoSeleccion = listaLineaComandos[0]; partida(listaLineaComandos, modoSeleccion, posicionTablero, soles, contadorTurno, turnosSinZombies(), numZombies(), contadorZombisQuedan, contadorZombis); } } } }//GEN-LAST:event_textField_lineaComandos_PartidaKeyPressed /** * Los botones serán transparentes */ public void transparenciaBoton() { botonSalir_Partida.setOpaque(false); botonSalir_Partida.setContentAreaFilled(false); botonSalir_Partida.setBorderPainted(false); } /** * Asignamos nombre a los JLabels */ public void asignarNombreJLabel() { tablero_0_0.setName("tablero_0_0"); tablero_0_1.setName("tablero_0_1"); tablero_0_2.setName("tablero_0_2"); tablero_0_3.setName("tablero_0_3"); tablero_0_4.setName("tablero_0_4"); tablero_0_5.setName("tablero_0_5"); tablero_0_6.setName("tablero_0_6"); tablero_0_7.setName("tablero_0_7"); tablero_0_8.setName("tablero_0_08"); tablero_1_0.setName("tablero_1_0"); tablero_1_1.setName("tablero_1_1"); tablero_1_2.setName("tablero_1_2"); tablero_1_3.setName("tablero_1_3"); tablero_1_4.setName("tablero_1_4"); tablero_1_5.setName("tablero_1_5"); tablero_1_6.setName("tablero_1_6"); tablero_1_7.setName("tablero_1_7"); tablero_1_8.setName("tablero_1_8"); tablero_2_0.setName("tablero_2_0"); tablero_2_1.setName("tablero_2_1"); tablero_2_2.setName("tablero_2_2"); tablero_2_3.setName("tablero_2_3"); tablero_2_4.setName("tablero_2_4"); tablero_2_5.setName("tablero_2_5"); tablero_2_6.setName("tablero_2_6"); tablero_2_7.setName("tablero_2_7"); tablero_3_0.setName("tablero_3_0"); tablero_3_1.setName("tablero_3_1"); tablero_3_2.setName("tablero_3_2"); tablero_3_3.setName("tablero_3_3"); tablero_3_4.setName("tablero_3_4"); tablero_3_5.setName("tablero_3_5"); tablero_3_6.setName("tablero_3_6"); tablero_3_7.setName("tablero_3_7"); tablero_3_8.setName("tablero_3_8"); tablero_4_0.setName("tablero_4_0"); tablero_4_1.setName("tablero_4_1"); tablero_4_2.setName("tablero_4_2"); tablero_4_3.setName("tablero_4_3"); tablero_4_4.setName("tablero_4_4"); tablero_4_5.setName("tablero_4_5"); tablero_4_6.setName("tablero_4_6"); tablero_4_7.setName("tablero_4_7"); tablero_4_8.setName("tablero_4_8"); } /** * * Asignar Imagen en función del tipo de planta y crear Planta * * @param posicion * @param comando */ public void asignarImagen(JLabel posicion, Objeto objeto) { if (objeto instanceof PlantaGirasol) { ImageIcon objetoImagen = new ImageIcon("src\\imagenes\\plantaGirasol.png"); Icon icono = new ImageIcon(objetoImagen.getImage().getScaledInstance(posicion.getWidth(), posicion.getHeight(), Image.SCALE_DEFAULT)); posicion.setIcon(icono); } else if (objeto instanceof PlantaLanzaGuisantes) { ImageIcon objetoImagen = new ImageIcon("src\\imagenes\\plantaLanzaGuisantes.png"); Icon icono = new ImageIcon(objetoImagen.getImage().getScaledInstance(posicion.getWidth(), posicion.getHeight(), Image.SCALE_DEFAULT)); posicion.setIcon(icono); } else if (objeto instanceof PlantaNuez) { ImageIcon objetoImagen = new ImageIcon("src\\imagenes\\plantaNuez.png"); Icon icono = new ImageIcon(objetoImagen.getImage().getScaledInstance(posicion.getWidth(), posicion.getHeight(), Image.SCALE_DEFAULT)); posicion.setIcon(icono); } else if (objeto instanceof PlantaPetaCereza) { ImageIcon objetoImagen = new ImageIcon("src\\imagenes\\plantaPetaCerezas.png"); Icon icono = new ImageIcon(objetoImagen.getImage().getScaledInstance(posicion.getWidth(), posicion.getHeight(), Image.SCALE_DEFAULT)); posicion.setIcon(icono); } else if (objeto instanceof ZombieComun) { ImageIcon objetoImagen = new ImageIcon("src\\imagenes\\zombieComun.png"); Icon icono = new ImageIcon(objetoImagen.getImage().getScaledInstance(posicion.getWidth(), posicion.getHeight(), Image.SCALE_DEFAULT)); posicion.setIcon(icono); } else if (objeto instanceof ZombieCaraCubo) { ImageIcon objetoImagen = new ImageIcon("src\\imagenes\\zombieCaraCubo.png"); Icon icono = new ImageIcon(objetoImagen.getImage().getScaledInstance(posicion.getWidth(), posicion.getHeight(), Image.SCALE_DEFAULT)); posicion.setIcon(icono); } else if (objeto instanceof ZombieDeportista) { ImageIcon objetoImagen = new ImageIcon("src\\imagenes\\zombieDeportista.png"); Icon icono = new ImageIcon(objetoImagen.getImage().getScaledInstance(posicion.getWidth(), posicion.getHeight(), Image.SCALE_DEFAULT)); posicion.setIcon(icono); } else if (objeto instanceof CasillaVacia) { posicion.setIcon(null); } } /** * * Crear plantas * * @param comando * @return * */ public Planta crearPlanta(String comando) { comando = comando.toUpperCase(); Planta planta = null; if (null != comando) { switch (comando) { case "L": { planta = PlantaLanzaGuisantes.crearPlantaLanzaGuisantes(); break; } case "G": { planta = PlantaGirasol.crearPlantaGirasol(); break; } case "N": { planta = PlantaNuez.crearPlantaNuez(); break; } case "P": { planta = PlantaPetaCereza.crearPlantaPetaCereza(); break; } } } return planta; } /** * * Agregar las fotos a los jlabels dependiendo del objeto y se asigna la resistencia * * @param tablero * @param numFilas * @param numColumnas */ public void objetosTablero(Objeto[][] tablero, int numFilas, int numColumnas) { for (int i = 0; i < numFilas; i++) { for (int j = 0; j < numColumnas; j++) { if (i == 0) { if (j == 0) { asignarImagen(tablero_0_0, tablero[i][j]); //asignarImagen(JLabel posicion, Objeto objeto) //tablero = Tablero.rellenarTableroVirtual(tablero[i][j], i, j, tablero); } else if (j == 1) { asignarImagen(tablero_0_1, tablero[i][j]); //tablero = Tablero.rellenarTableroVirtual(tablero[i][j], i, j, tablero); } else if (j == 2) { asignarImagen(tablero_0_2, tablero[i][j]); //tablero = Tablero.rellenarTableroVirtual(tablero[i][j], i, j, tablero); } else if (j == 3) { asignarImagen(tablero_0_3, tablero[i][j]); //tablero = Tablero.rellenarTableroVirtual(tablero[i][j], i, j, tablero); } else if (j == 4) { asignarImagen(tablero_0_4, tablero[i][j]); //tablero = Tablero.rellenarTableroVirtual(tablero[i][j], i, j, tablero); } else if (j == 5) { asignarImagen(tablero_0_5, tablero[i][j]); //tablero = Tablero.rellenarTableroVirtual(tablero[i][j], i, j, tablero); } else if (j == 6) { asignarImagen(tablero_0_6, tablero[i][j]); //tablero = Tablero.rellenarTableroVirtual(tablero[i][j], i, j, tablero); } else if (j == 7) { asignarImagen(tablero_0_7, tablero[i][j]); //tablero = Tablero.rellenarTableroVirtual(tablero[i][j], i, j, tablero); } else if (j == 8) { asignarImagen(tablero_0_8, tablero[i][j]); //tablero = Tablero.rellenarTableroVirtual(tablero[i][j], i, j, tablero); } } else if (i == 1) { if (j == 0) { asignarImagen(tablero_1_0, tablero[i][j]); //tablero = Tablero.rellenarTableroVirtual(tablero[i][j], i, j, tablero); } else if (j == 1) { asignarImagen(tablero_1_1, tablero[i][j]); //tablero = Tablero.rellenarTableroVirtual(tablero[i][j], i, j, tablero); } else if (j == 2) { asignarImagen(tablero_1_2, tablero[i][j]); //tablero = Tablero.rellenarTableroVirtual(tablero[i][j], i, j, tablero); } else if (j == 3) { asignarImagen(tablero_1_3, tablero[i][j]); //tablero = Tablero.rellenarTableroVirtual(tablero[i][j], i, j, tablero); } else if (j == 4) { asignarImagen(tablero_1_4, tablero[i][j]); //tablero = Tablero.rellenarTableroVirtual(tablero[i][j], i, j, tablero); } else if (j == 5) { asignarImagen(tablero_1_5, tablero[i][j]); //tablero = Tablero.rellenarTableroVirtual(tablero[i][j], i, j, tablero); } else if (j == 6) { asignarImagen(tablero_1_6, tablero[i][j]); //tablero = Tablero.rellenarTableroVirtual(tablero[i][j], i, j, tablero); } else if (j == 7) { asignarImagen(tablero_1_7, tablero[i][j]); //tablero = Tablero.rellenarTableroVirtual(tablero[i][j], i, j, tablero); } else if (j == 8) { asignarImagen(tablero_1_8, tablero[i][j]); //tablero = Tablero.rellenarTableroVirtual(tablero[i][j], i, j, tablero); } } else if (i == 2) { if (j == 0) { asignarImagen(tablero_2_0, tablero[i][j]); //tablero = Tablero.rellenarTableroVirtual(tablero[i][j], i, j, tablero); } else if (j == 1) { asignarImagen(tablero_2_1, tablero[i][j]); //tablero = Tablero.rellenarTableroVirtual(tablero[i][j], i, j, tablero); } else if (j == 2) { asignarImagen(tablero_2_2, tablero[i][j]); //tablero = Tablero.rellenarTableroVirtual(tablero[i][j], i, j, tablero); } else if (j == 3) { asignarImagen(tablero_2_3, tablero[i][j]); //tablero = Tablero.rellenarTableroVirtual(tablero[i][j], i, j, tablero); } else if (j == 4) { asignarImagen(tablero_2_4, tablero[i][j]); //tablero = Tablero.rellenarTableroVirtual(tablero[i][j], i, j, tablero); } else if (j == 5) { asignarImagen(tablero_2_5, tablero[i][j]); //tablero = Tablero.rellenarTableroVirtual(tablero[i][j], i, j, tablero); } else if (j == 6) { asignarImagen(tablero_2_6, tablero[i][j]); //tablero = Tablero.rellenarTableroVirtual(tablero[i][j], i, j, tablero); } else if (j == 7) { asignarImagen(tablero_2_7, tablero[i][j]); //tablero = Tablero.rellenarTableroVirtual(tablero[i][j], i, j, tablero); } else if (j == 8) { asignarImagen(tablero_2_8, tablero[i][j]); //tablero = Tablero.rellenarTableroVirtual(tablero[i][j], i, j, tablero); } } else if (i == 3) { if (j == 0) { asignarImagen(tablero_3_0, tablero[i][j]); //tablero = Tablero.rellenarTableroVirtual(tablero[i][j], i, j, tablero); } else if (j == 1) { asignarImagen(tablero_3_1, tablero[i][j]); //tablero = Tablero.rellenarTableroVirtual(tablero[i][j], i, j, tablero); } else if (j == 2) { asignarImagen(tablero_3_2, tablero[i][j]); //tablero = Tablero.rellenarTableroVirtual(tablero[i][j], i, j, tablero); } else if (j == 3) { asignarImagen(tablero_3_3, tablero[i][j]); //tablero = Tablero.rellenarTableroVirtual(tablero[i][j], i, j, tablero); } else if (j == 4) { asignarImagen(tablero_3_4, tablero[i][j]); //tablero = Tablero.rellenarTableroVirtual(tablero[i][j], i, j, tablero); } else if (j == 5) { asignarImagen(tablero_3_5, tablero[i][j]); //tablero = Tablero.rellenarTableroVirtual(tablero[i][j], i, j, tablero); } else if (j == 6) { asignarImagen(tablero_3_6, tablero[i][j]); //tablero = Tablero.rellenarTableroVirtual(tablero[i][j], i, j, tablero); } else if (j == 7) { asignarImagen(tablero_3_7, tablero[i][j]); //tablero = Tablero.rellenarTableroVirtual(tablero[i][j], i, j, tablero); } else if (j == 8) { asignarImagen(tablero_3_8, tablero[i][j]); //tablero = Tablero.rellenarTableroVirtual(tablero[i][j], i, j, tablero); } } else if (i == 4) { if (j == 0) { asignarImagen(tablero_4_0, tablero[i][j]); //tablero = Tablero.rellenarTableroVirtual(tablero[i][j], i, j, tablero); } else if (j == 1) { asignarImagen(tablero_4_1, tablero[i][j]); //tablero = Tablero.rellenarTableroVirtual(tablero[i][j], i, j, tablero); } else if (j == 2) { asignarImagen(tablero_4_2, tablero[i][j]); //tablero = Tablero.rellenarTableroVirtual(tablero[i][j], i, j, tablero); } else if (j == 3) { asignarImagen(tablero_4_3, tablero[i][j]); //tablero = Tablero.rellenarTableroVirtual(tablero[i][j], i, j, tablero); } else if (j == 4) { asignarImagen(tablero_4_4, tablero[i][j]); //tablero = Tablero.rellenarTableroVirtual(tablero[i][j], i, j, tablero); } else if (j == 5) { asignarImagen(tablero_4_5, tablero[i][j]); //tablero = Tablero.rellenarTableroVirtual(tablero[i][j], i, j, tablero); } else if (j == 6) { asignarImagen(tablero_4_6, tablero[i][j]); //tablero = Tablero.rellenarTableroVirtual(tablero[i][j], i, j, tablero); } else if (j == 7) { asignarImagen(tablero_4_7, tablero[i][j]); //tablero = Tablero.rellenarTableroVirtual(tablero[i][j], i, j, tablero); } else if (j == 8) { asignarImagen(tablero_4_8, tablero[i][j]); //tablero = Tablero.rellenarTableroVirtual(tablero[i][j], i, j, tablero); } } } } } /** * * Asignar el num Zombis que van a salir * * @return */ public int numZombies() { int numZombis = 0; if ("BAJA".equals(dificultad)) { numZombis = 5; } else if ("MEDIA".equals(dificultad)) { numZombis = 15; } else if ("ALTA".equals(dificultad)) { numZombis = 25; } else if ("IMPOSIBLE".equals(dificultad)) { numZombis = 50; } return numZombis; } /** * * Asignar cuántos turnos libres vas a tener antes de que salga el primer zombie * * @return */ public int[] turnosSinZombies() { int[] turnosInicialesSinZombis = {0}; if ("BAJA".equals(dificultad)) { turnosInicialesSinZombis[0] = 10; } else if ("MEDIA".equals(dificultad)) { turnosInicialesSinZombis[0] = 7; } else if ("ALTA".equals(dificultad)) { turnosInicialesSinZombis[0] = 5; } else if ("IMPOSIBLE".equals(dificultad)) { turnosInicialesSinZombis[0] = 5; } return turnosInicialesSinZombis; } /** * * Partida * * @param listaLineaComandos * @param modoSeleccion * @param posicionTablero * @param soles * @param contadorTurno * @param turnosInicialesSinZombis * @param numZombis * @param contadorZombisQuedan * @param contadorZombis */ public void partida(String[] listaLineaComandos, String modoSeleccion, String posicionTablero, int[] soles, int[] contadorTurno, int[] turnosInicialesSinZombis, int numZombis, int[] contadorZombisQuedan, int[] contadorZombis) { int filaObjeto = 0; int columnaObjeto = 0; int[] contadorZombiesTablero = {0}; int[] contadorZombiesMuertos = {0}; int numFilas = 5; int numColumnas = 9; jLabel_turno_Partida.setText(Integer.toString(contadorTurno[0])); textField_zmbQuedan.setText(Integer.toString(contadorZombisQuedan[0])); boolean finPartida = false; int zombisQuedan = 0; contadorTurno[0]++; int contadorPlantaLanzaGuisantes = 0; boolean comprobadorImprimir = true; modoSeleccion = listaLineaComandos[0].toUpperCase(); if ("G".equals(modoSeleccion) || "L".equals(modoSeleccion) || "N".equals(modoSeleccion) || "P".equals(modoSeleccion)) { filaObjeto = Integer.parseInt(listaLineaComandos[1]) - 1; columnaObjeto = Integer.parseInt(listaLineaComandos[2]) - 1; posicionTablero = "tablero_" + Integer.toString(filaObjeto - 1) + "_" + Integer.toString(columnaObjeto - 1); Planta planta = crearPlanta(modoSeleccion); if (ExcepcionPlanta.fueraTableroInterfaz(numFilas, numColumnas, filaObjeto, columnaObjeto) == true) { //fuera tablero JOptionPane.showMessageDialog(null, "Fuera del tablero."); } else { if (columnaObjeto == numColumnas - 1) { //última casilla JOptionPane.showMessageDialog(null, "Última casilla reservada para zombies."); } else { if (!(tablero[filaObjeto][columnaObjeto] instanceof CasillaVacia)) { //casilla OCUPADA JOptionPane.showMessageDialog(null, "Casilla Ocupada."); } else { if (soles[0] - planta.getCoste() >= 0) { //Sí suficientes soles tablero = Tablero.agregarPlanta(tablero, soles, listaLineaComandos, numFilas, numColumnas, modoSeleccion); } else { JOptionPane.showMessageDialog(null, "No tienes suficientes soles."); } } } } } jLabel_numSoles_Partida.setText(Integer.toString(soles[0])); //zombies turnosInicialesSinZombis[0] = turnosInicialesSinZombis[0] - contadorTurno[0]; tablero = Tablero.agregarZombie(tablero, numFilas, numColumnas, contadorZombis, contadorZombiesTablero, turnosInicialesSinZombis[0], numZombis, contadorZombisQuedan); // tablero, numFilas, numColumnas, contadorZombis, contadorZombiesTablero, turnosInicialesSinZombis, numZombis, contadorZombisQuedan //tablero[4][4] = ZombieComun.crearZombieComun(); turnosInicialesSinZombis[0]--; objetosTablero(tablero, numFilas, numColumnas); //--------------------------------------------------------------------------------------- zombisQuedan = numZombis - contadorZombis[0]; if (comprobadorImprimir == true) { turnosInicialesSinZombis[0]--; } else { contadorTurno[0]--; } comprobadorImprimir = true; //--------------------------------------------------------------------------------------- //finPartida == true if (ExcepcionJuego.finPartida(tablero, numFilas, numColumnas, contadorZombis[0], numZombis, contadorTurno[0]) == true) { System.out.println("contador zmb: " + contadorZombis[0]); System.out.println("nuum zmb:" + numZombis); if (contadorZombis[0] == numZombis) { JOptionPane.showMessageDialog(null, "Han ganado las PLANTAS!!!!"); for (int i = 0; i < numFilas; i++) { for (int j = 0; j < numColumnas; j++) { if (tablero[i][j] instanceof Planta) { puntos[0] = puntos[0] + tablero[i][j].getCoste(); } } } puntos[0] = puntos[0] + soles[0]; terminada = true; ganada = true; } else { JOptionPane.showMessageDialog(null, "Han ganado los ZOMBIES!!!!"); terminada = true; ganada = false; } this.dispose(); } //movimiento tablero = Tablero.movimientos(tablero, numFilas, numColumnas, soles, casillaVacia, contadorZombiesTablero, contadorZombiesMuertos); //--------------------------------------------------------------------------------------- } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton botonSalir_Partida; private javax.swing.JLabel fondoPartida; private javax.swing.JLabel jLabelCostePLG; private javax.swing.JLabel jLabelCostePPC; private javax.swing.JLabel jLabelCostePPC1; private javax.swing.JLabel jLabelPG; private javax.swing.JLabel jLabel_numSoles_Partida; private javax.swing.JLabel jLabel_turno_Partida; private javax.swing.JLabel tablero_0_0; private javax.swing.JLabel tablero_0_1; private javax.swing.JLabel tablero_0_2; private javax.swing.JLabel tablero_0_3; private javax.swing.JLabel tablero_0_4; private javax.swing.JLabel tablero_0_5; private javax.swing.JLabel tablero_0_6; private javax.swing.JLabel tablero_0_7; private javax.swing.JLabel tablero_0_8; private javax.swing.JLabel tablero_1_0; private javax.swing.JLabel tablero_1_1; private javax.swing.JLabel tablero_1_2; private javax.swing.JLabel tablero_1_3; private javax.swing.JLabel tablero_1_4; private javax.swing.JLabel tablero_1_5; private javax.swing.JLabel tablero_1_6; private javax.swing.JLabel tablero_1_7; private javax.swing.JLabel tablero_1_8; private javax.swing.JLabel tablero_2_0; private javax.swing.JLabel tablero_2_1; private javax.swing.JLabel tablero_2_2; private javax.swing.JLabel tablero_2_3; private javax.swing.JLabel tablero_2_4; private javax.swing.JLabel tablero_2_5; private javax.swing.JLabel tablero_2_6; private javax.swing.JLabel tablero_2_7; private javax.swing.JLabel tablero_2_8; private javax.swing.JLabel tablero_3_0; private javax.swing.JLabel tablero_3_1; private javax.swing.JLabel tablero_3_2; private javax.swing.JLabel tablero_3_3; private javax.swing.JLabel tablero_3_4; private javax.swing.JLabel tablero_3_5; private javax.swing.JLabel tablero_3_6; private javax.swing.JLabel tablero_3_7; private javax.swing.JLabel tablero_3_8; private javax.swing.JLabel tablero_4_0; private javax.swing.JLabel tablero_4_1; private javax.swing.JLabel tablero_4_2; private javax.swing.JLabel tablero_4_3; private javax.swing.JLabel tablero_4_4; private javax.swing.JLabel tablero_4_5; private javax.swing.JLabel tablero_4_6; private javax.swing.JLabel tablero_4_7; private javax.swing.JLabel tablero_4_8; private javax.swing.JTextField textField_lineaComandos_Partida; private javax.swing.JTextField textField_zmbQuedan; // End of variables declaration//GEN-END:variables } <file_sep>/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package POOconJava.ejemploModuloCalculo; /** * * @author laura * * Construir una interface en Java que contenga los siguientes métodos: * */ public interface ModuloCalculo1 { double suma (double a, double b); double resta (double a, double b); double multiplica (double a, double b); double divide (double a, double b); } <file_sep>package radiob; import java.awt.Color; import java.awt.Image; import javax.swing.Icon; import javax.swing.ImageIcon; import javax.swing.JLabel; import javax.swing.JOptionPane; public class RadioBotones2 extends javax.swing.JFrame { /** * Creates new form ejercicioRadioButton */ public RadioBotones2() { initComponents(); cargarImagenesPorDefecto(); } private void cargarImagenesPorDefecto() { ImageIcon imageIcon = new ImageIcon("imagenes/sinimg.jpg"); jLabel1.setIcon(imageIcon); jLabel2.setIcon(imageIcon); jLabel3.setIcon(imageIcon); jLabel1.setText(""); jLabel2.setText(""); jLabel3.setText(""); } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { buttonGroup1 = new javax.swing.ButtonGroup(); jRadioButton1 = new javax.swing.JRadioButton(); jRadioButton2 = new javax.swing.JRadioButton(); jRadioButton3 = new javax.swing.JRadioButton(); jLabel1 = new javax.swing.JLabel(); jLabel2 = new javax.swing.JLabel(); jLabel3 = new javax.swing.JLabel(); jPanel2 = new javax.swing.JPanel(); jButtonVer = new javax.swing.JButton(); jButtonBorrar = new javax.swing.JButton(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); setTitle("RADIO BOTONES"); setSize(new java.awt.Dimension(20, 100)); buttonGroup1.add(jRadioButton1); buttonGroup1.add(jRadioButton2); buttonGroup1.add(jRadioButton3); jLabel1.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N jLabel1.setText("jLabel1"); jLabel2.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N jLabel2.setText("jLabel2"); jLabel3.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N jLabel3.setText("jLabel3"); jPanel2.setBorder(javax.swing.BorderFactory.createTitledBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)), "Pulsar un botón")); jButtonVer.setText("ver foto y nombre"); jButtonVer.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButtonVerActionPerformed(evt); } }); jButtonBorrar.setText("borrar foto y nombre"); jButtonBorrar.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButtonBorrarActionPerformed(evt); } }); javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2); jPanel2.setLayout(jPanel2Layout); jPanel2Layout.setHorizontalGroup( jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel2Layout.createSequentialGroup() .addGap(37, 37, 37) .addComponent(jButtonVer) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 59, Short.MAX_VALUE) .addComponent(jButtonBorrar) .addGap(26, 26, 26)) ); jPanel2Layout.setVerticalGroup( jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup() .addContainerGap(24, Short.MAX_VALUE) .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jButtonVer) .addComponent(jButtonBorrar)) .addGap(21, 21, 21)) ); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(69, 69, 69) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jRadioButton1) .addComponent(jLabel1)) .addGap(73, 73, 73) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jRadioButton2) .addComponent(jLabel2)) .addGap(49, 49, 49) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel3) .addComponent(jRadioButton3))) .addGroup(layout.createSequentialGroup() .addGap(123, 123, 123) .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))) .addContainerGap(184, Short.MAX_VALUE)) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(46, 46, 46) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel1) .addComponent(jLabel2) .addComponent(jLabel3)) .addGap(33, 33, 33) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jRadioButton1, javax.swing.GroupLayout.Alignment.TRAILING) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jRadioButton2) .addComponent(jRadioButton3))) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 151, Short.MAX_VALUE) .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(40, 40, 40)) ); jPanel2.getAccessibleContext().setAccessibleName("Pulsar"); jPanel2.getAccessibleContext().setAccessibleDescription(""); pack(); }// </editor-fold>//GEN-END:initComponents private void jButtonBorrarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonBorrarActionPerformed int pos = obtenerPosicionRadioBotonSeleccionado(); ImageIcon imageIcon = new ImageIcon("imagenes/sinimg.jpg"); if (pos == -1) { JOptionPane.showMessageDialog(this, "Seleccione una posición.", "Mensaje", JOptionPane.INFORMATION_MESSAGE); } else if (pos == 1) { jLabel1.setIcon(imageIcon); jLabel1.setText(""); } else if (pos == 2) { jLabel2.setIcon(imageIcon); jLabel2.setText(""); } else { jLabel3.setIcon(imageIcon); jLabel3.setText(""); } }//GEN-LAST:event_jButtonBorrarActionPerformed private void jButtonVerActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonVerActionPerformed int pos = obtenerPosicionRadioBotonSeleccionado(); if (pos == -1) { JOptionPane.showMessageDialog(this, "Seleccione una posición.", "Mensaje", JOptionPane.INFORMATION_MESSAGE); } else if (pos == 1) { ImageIcon imageIcon = new ImageIcon("imagenes/foto1.jpg"); Icon icono = new ImageIcon(imageIcon.getImage().getScaledInstance(jLabel1.getWidth(), jLabel1.getHeight(), Image.SCALE_DEFAULT)); jLabel1.setIcon(icono); jLabel1.setHorizontalTextPosition(JLabel.CENTER); jLabel1.setForeground(Color.DARK_GRAY); jLabel1.setText("ROSA"); } else if (pos == 2) { ImageIcon imageIcon = new ImageIcon("imagenes/foto2.jpg"); Icon icono = new ImageIcon(imageIcon.getImage().getScaledInstance(jLabel2.getWidth(), jLabel2.getHeight(), Image.SCALE_DEFAULT)); jLabel2.setIcon(icono); jLabel2.setHorizontalTextPosition(JLabel.CENTER); jLabel2.setForeground(Color.RED); jLabel2.setText("GIRASOL"); } else { ImageIcon imageIcon = new ImageIcon("imagenes/foto3.jpg"); Icon icono = new ImageIcon(imageIcon.getImage().getScaledInstance(jLabel3.getWidth(), jLabel3.getHeight(), Image.SCALE_DEFAULT)); jLabel3.setIcon(icono); jLabel3.setHorizontalTextPosition(JLabel.CENTER); jLabel3.setForeground(Color.BLUE); jLabel3.setText("CRISANTEMO"); } }//GEN-LAST:event_jButtonVerActionPerformed private int obtenerPosicionRadioBotonSeleccionado() { int i = -1; if (jRadioButton1.isSelected()) { i = 1; } else if (jRadioButton2.isSelected()) { i = 2; } else if (jRadioButton3.isSelected()) { i = 3; } return i; } /** * @param args the command line arguments */ public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(RadioBotones2.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(RadioBotones2.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(RadioBotones2.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(RadioBotones2.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new RadioBotones2().setVisible(true); } }); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.ButtonGroup buttonGroup1; private javax.swing.JButton jButtonBorrar; private javax.swing.JButton jButtonVer; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel2; private javax.swing.JLabel jLabel3; private javax.swing.JPanel jPanel2; private javax.swing.JRadioButton jRadioButton1; private javax.swing.JRadioButton jRadioButton2; private javax.swing.JRadioButton jRadioButton3; // End of variables declaration//GEN-END:variables } <file_sep>/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package arrays.ejercicios; import java.util.Random; /** * * @author laura * * Escribir un programa que genere 50 números enteros aleatorios entre el 97 y el 122 que representarán las letras del alfabeto (exceptuando la ñ), los almacene en un array de caracteres, y cuente cuantas vocales se han generado. Nota: para pasar del código entero a carácter se utiliza: char c = (char) numero; * */ public class LetrasAlfabeto2 { public static void main (String[] args){ Random aleatorio = new Random(); char numeros[] = new char [50]; int vocales = 0; //Rellenar numeros[][] for (int i = 0; i < numeros.length; i++){ numeros[i] = (char) (aleatorio.nextInt((122 - 97) + 1) + 97); if (numeros[i] == 'a' || numeros[i] == 'e' || numeros[i] == 'i' || numeros[i] == 'o' || numeros[i] == 'u'){ vocales += 1; } } System.out.println(numeros); System.out.println("Hay " + vocales + " vocal(es)."); } } <file_sep>/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package arrays; import java.util.*; /** * * @author laura * * genera de forma aleatoria 10 números entre el 0 y el 15 (haciendo uso de la clase Random) y a continuación nos indica que introduzcamos un número y comprueba si ese número está en el array (utilizando la clase Arrays) * */ public class NumerosEnArray { public static void main (String[] args){ Scanner entrada = new Scanner (System.in); Random rand = new Random(); int num; int numeros[] = new int [10]; //creamos array de 10 elementos al que se le van a introducir ints boolean adivinado = false; //generamos números aleatorios entre el 0 y el 15 for (int i = 0; i < numeros.length; i++){ numeros[i] = rand.nextInt (16); } //ordenamos array Arrays.sort(numeros); //pedimos el número System.out.print("Introduzca el número (0 - 15): "); num = entrada.nextInt(); //llamamos al método adivinado = adivinado (numeros, num); if (adivinado) { //if adivinado == true System.out.println("\nNúmero adivinado"); } else{ System.out.println("\nNúmero NO adivinado"); } //imprimimos todos los números System.out.println("\nTodos los números:"); for (int i = 0; i < numeros.length; i++) { System.out.print(" " + numeros[i]); } } public static boolean adivinado(int numeros[], int num) { return (Arrays.binarySearch(numeros, num) >= 0); } } <file_sep>/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package ejerciciosPropuestos2; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; /** * * @author laura * * Programa que dadas dos fechas diga la diferencia en días entre ellas. * */ public class DiferenciaFechas7 { public static void main (String[] args) throws IOException{ BufferedReader entrada = new BufferedReader(new InputStreamReader(System.in)); int dia1; int mes1; int anio1; int dias1; int aniosBisiestos1; int diasAnio1 = 0; int diasMes1 = 0; int dia2; int mes2; int anio2; int dias2; int aniosBisiestos2; int diasAnio2 = 0; int diasMes2 = 0; int diferencia; //Fecha 1 System.out.print("\nFECHA 1\n"); System.out.print("\nDía 1: "); dia1 = Integer.parseInt(entrada.readLine()); System.out.print("\nMes1 : "); mes1 = Integer.parseInt(entrada.readLine()); System.out.print("\nAño 1: "); anio1 = Integer.parseInt(entrada.readLine()); //Fecha 2 System.out.print("\nFECHA 2\n"); System.out.print("\nDía 2: "); dia2 = Integer.parseInt(entrada.readLine()); System.out.print("\nMes2 : "); mes2 = Integer.parseInt(entrada.readLine()); System.out.print("\nAño 2: "); anio2 = Integer.parseInt(entrada.readLine()); System.out.println("\n" + dia1 + " - " + mes1 + " - " + anio1); System.out.println("\n" + dia2 + " - " + mes2 + " - " + anio2); //FECHA 1 //anio aniosBisiestos1 = anio1 / 4; diasAnio1 = (anio1 - aniosBisiestos1) * 365 + aniosBisiestos1 * 366; //mes mes1 -= 1; if (mes1 == 0){ diasMes1 = 0; } else if (mes1 == 1){ diasMes1 = 31; //enero } else if (mes1 == 2){ diasMes1 = 31 + 28; //febrero } else if (mes1 == 3){ diasMes1 = 31 + 28 + 31; //marzo } else if (mes1 == 4){ diasMes1 = 31 + 28 + 31 + 30; //abril } else if (mes1 == 5){ diasMes1 = 31 + 28 + 31 + 30 + 31; //mayo } else if (mes1 == 6){ diasMes1 = 31 + 28 + 31 + 30 + 31 + 30; //junio } else if (mes1 == 7){ diasMes1 = 31 + 28 + 31 + 30 + 31 + 30 + 31; //julio } else if (mes1 == 8){ diasMes1 = 31 + 28 + 31 + 30 + 31 + 30 + 31 + 31; //agosto } else if (mes1 == 9){ diasMes1 = 31 + 28 + 31 + 30 + 31 + 30 + 31 + 31 + 30; //septiembre } else if (mes1 == 10){ diasMes1 = 31 + 28 + 31 + 30 + 31 + 30 + 31 + 31 + 30 + 31; //octubre } else if (mes1 == 11){ diasMes1 = 31 + 28 + 31 + 30 + 31 + 30 + 31 + 31 + 30 + 31 + 30; //noviembre } dias1 = dia1 + diasMes1 + diasAnio1; //FECHA 2 //anio aniosBisiestos2 = anio2 / 4; diasAnio2 = (anio2 - aniosBisiestos2) * 365 + aniosBisiestos2 * 366; //mes mes2 -= 1; if (mes2 == 0){ diasMes2 = 0; } else if (mes2 == 1){ diasMes2 = 31; //enero } else if (mes1 == 2){ diasMes2 = 31 + 28; //febrero } else if (mes2 == 3){ diasMes2 = 31 + 28 + 31; //marzo } else if (mes2 == 4){ diasMes2 = 31 + 28 + 31 + 30; //abril } else if (mes2 == 5){ diasMes2 = 31 + 28 + 31 + 30 + 31; //mayo } else if (mes2 == 6){ diasMes2 = 31 + 28 + 31 + 30 + 31 + 30; //junio } else if (mes2 == 7){ diasMes2 = 31 + 28 + 31 + 30 + 31 + 30 + 31; //julio } else if (mes2 == 8){ diasMes2 = 31 + 28 + 31 + 30 + 31 + 30 + 31 + 31; //agosto } else if (mes2 == 9){ diasMes2 = 31 + 28 + 31 + 30 + 31 + 30 + 31 + 31 + 30; //septiembre } else if (mes2 == 10){ diasMes2 = 31 + 28 + 31 + 30 + 31 + 30 + 31 + 31 + 30 + 31; //octubre } else if (mes2 == 11){ diasMes2 = 31 + 28 + 31 + 30 + 31 + 30 + 31 + 31 + 30 + 31 + 30; //noviembre } dias2 = dia2 + diasMes2 + diasAnio2; //Diferencia fechas if (dias1 > dias2){ diferencia = dias1 - dias2; } else{ diferencia = dias2 - dias1; } System.out.println("\nLa diferencia es de " + diferencia + " días."); } } <file_sep>/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package interfaces; import clases.Usuario; import java.util.HashMap; import javax.swing.ImageIcon; /** * * @author laura */ public class PartidasGuardadas extends javax.swing.JFrame { /** * Creates new form PartidasGuardadas */ private static HashMap<String, clases.Historial> torneo; private static Usuario usuario; public PartidasGuardadas(HashMap<String, clases.Historial> torne, Usuario usuari) { torneo = torne; usuario = usuari; initComponents(); transparenciaBoton(); this.setLocationRelativeTo(null); //ajustarlo en el medio de la pantalla setIconImage(new ImageIcon(getClass().getResource("/imagenes/icono.jpg")).getImage()); //cambiar logo } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { botonAtras_PartidasGuardadas = new javax.swing.JButton(); fondo_PartidasGuardadas = new javax.swing.JLabel(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); setResizable(false); getContentPane().setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout()); botonAtras_PartidasGuardadas.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { botonAtras_PartidasGuardadasMouseClicked(evt); } }); getContentPane().add(botonAtras_PartidasGuardadas, new org.netbeans.lib.awtextra.AbsoluteConstraints(1040, 660, 190, 40)); fondo_PartidasGuardadas.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imagenes/partidasGuardadas.jpg"))); // NOI18N getContentPane().add(fondo_PartidasGuardadas, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 0, -1, -1)); pack(); }// </editor-fold>//GEN-END:initComponents private void botonAtras_PartidasGuardadasMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_botonAtras_PartidasGuardadasMouseClicked // TODO add your handling code here: SesionIniciada s = new SesionIniciada(torneo, usuario); s.setVisible(true); this.dispose(); }//GEN-LAST:event_botonAtras_PartidasGuardadasMouseClicked /** * Los botones serán transparentes */ public void transparenciaBoton(){ botonAtras_PartidasGuardadas.setOpaque(false); botonAtras_PartidasGuardadas.setContentAreaFilled(false); botonAtras_PartidasGuardadas.setBorderPainted(false); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton botonAtras_PartidasGuardadas; private javax.swing.JLabel fondo_PartidasGuardadas; // End of variables declaration//GEN-END:variables } <file_sep>/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package argumentos; /** * * @author laura */ import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.Scanner; public class HolaTal { public static void main (String[] args) throws IOException{ BufferedReader entrada = new BufferedReader (new InputStreamReader (System.in)); String nombre; Scanner Entrada = new Scanner (System.in); System.out.println("\nIntroduce tu nombre: "); nombre = entrada.readLine(); System.out.println("Hola " + nombre); } } <file_sep>package logica; public class Ordenador extends Producto{ private String caracteristicas; public Ordenador(String codigo, String nombre, double precio, int cantidad, String caracterisiticas) { super(codigo,nombre,precio,cantidad); this.caracteristicas=caracterisiticas; } public String getCaracteristicas() { return caracteristicas; } public void setCaracteristicas(String caracteristicas) { this.caracteristicas = caracteristicas; } @Override public String toString() { return super.toString() + "\nOrdenador{" + " - caracteristicas = " + caracteristicas + '}'; } } <file_sep>/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package empleados; import empleados.Departamento; import empleados.Empresa; /** * * @author laura */ public class MainNomina { public static void main(String[] args) { //creamos empresa Empresa e1 = new Empresa ("Indra", "1234567"); //creamos departamento Departamento d1 = new Departamento (e1, "Informática", "Madrid", "Dep1"); //creamos presonas Persona persona1 = new Persona ("78813499D", 48, "casada", "Manuela"); //creamos empleados Empleado empleado1 = new Empleado ("Supervisor", d1, 1500, persona1); //creamos nóminas Nomina n1 = new Nomina (e1, d1, empleado1, 52.3); System.out.println(n1.toString()); } } <file_sep>/* * Programador.java * */ package informaticos; public class Programador extends InformaticoAbs { private String lenguaje; public Programador(String empresa, String lenguaje) { super(empresa); this.lenguaje = lenguaje; } public String getLenguaje() { return lenguaje; } public void setLenguaje(String lenguaje) { this.lenguaje = lenguaje; } @Override public double pagarSueldo(int horas) { return (double) horas * 6; } } <file_sep>/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package vehiculos; /** * * @author laura */ public class PruebaVehiculos { public static void main (String[] args){ Vehiculo v1 = new Vehiculo ("1234 BCD", "Opel", "Astra", 0, false); Vehiculo v2 = new Vehiculo("2345 CDE", "BMW", "S1", 80, false); Vehiculo v3 = new Vehiculo("3456 DEF", "Audi", "A3", 100, true); v1.setVelocidad(50); v1.setLuces(true); System.out.println(v1.toString()); } } <file_sep>/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package interfaces; import clases.Usuario; import java.util.HashMap; import javax.swing.ImageIcon; /** * * @author laura */ public class SesionIniciada extends javax.swing.JFrame { /** * Creates new form SesionIniciada */ private static HashMap<String, clases.Historial> torneo; private static Usuario usuario; public SesionIniciada(HashMap<String, clases.Historial> torne, Usuario usuari) { torneo = torne; usuario = usuari; initComponents(); transparenciaBoton(); this.setLocationRelativeTo(null); //ajustarlo en el medio de la pantalla jLabelNombre_SesionIniciada.setText(usuario.getNombre()); setIconImage(new ImageIcon(getClass().getResource("/imagenes/icono.jpg")).getImage()); //cambiar logo } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { botonHistorial_SesionIniciada = new javax.swing.JButton(); botonContinuarPartida_SesionIniciada = new javax.swing.JButton(); botonPartidaNueva_SesionIniciada = new javax.swing.JButton(); botonAtras_SesionIniciada = new javax.swing.JButton(); jLabelNombre_SesionIniciada = new javax.swing.JLabel(); fondo_SesionIniciada = new javax.swing.JLabel(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); setResizable(false); getContentPane().setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout()); botonHistorial_SesionIniciada.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { botonHistorial_SesionIniciadaMouseClicked(evt); } }); getContentPane().add(botonHistorial_SesionIniciada, new org.netbeans.lib.awtextra.AbsoluteConstraints(310, 170, 400, 40)); botonContinuarPartida_SesionIniciada.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { botonContinuarPartida_SesionIniciadaMouseClicked(evt); } }); getContentPane().add(botonContinuarPartida_SesionIniciada, new org.netbeans.lib.awtextra.AbsoluteConstraints(320, 250, 380, 50)); botonPartidaNueva_SesionIniciada.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { botonPartidaNueva_SesionIniciadaMouseClicked(evt); } }); getContentPane().add(botonPartidaNueva_SesionIniciada, new org.netbeans.lib.awtextra.AbsoluteConstraints(320, 340, 390, 40)); botonAtras_SesionIniciada.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { botonAtras_SesionIniciadaMouseClicked(evt); } }); getContentPane().add(botonAtras_SesionIniciada, new org.netbeans.lib.awtextra.AbsoluteConstraints(320, 420, 390, 40)); jLabelNombre_SesionIniciada.setFont(new java.awt.Font("Cooper Black", 0, 48)); // NOI18N jLabelNombre_SesionIniciada.setForeground(new java.awt.Color(255, 204, 204)); jLabelNombre_SesionIniciada.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); getContentPane().add(jLabelNombre_SesionIniciada, new org.netbeans.lib.awtextra.AbsoluteConstraints(300, 60, 430, 60)); fondo_SesionIniciada.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imagenes/sesionIniciada.jpg"))); // NOI18N getContentPane().add(fondo_SesionIniciada, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 0, -1, -1)); pack(); }// </editor-fold>//GEN-END:initComponents private void botonHistorial_SesionIniciadaMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_botonHistorial_SesionIniciadaMouseClicked // TODO add your handling code here: HistorialInterfaz historial = new HistorialInterfaz(torneo, usuario); historial.setVisible(true); this.dispose(); }//GEN-LAST:event_botonHistorial_SesionIniciadaMouseClicked private void botonContinuarPartida_SesionIniciadaMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_botonContinuarPartida_SesionIniciadaMouseClicked // TODO add your handling code here: PartidasGuardadas pG = new PartidasGuardadas(torneo, usuario); pG.setVisible(true); this.dispose(); }//GEN-LAST:event_botonContinuarPartida_SesionIniciadaMouseClicked private void botonPartidaNueva_SesionIniciadaMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_botonPartidaNueva_SesionIniciadaMouseClicked // TODO add your handling code here: Dificultad dificultad = new Dificultad(torneo, usuario); dificultad.setVisible(true); this.dispose(); }//GEN-LAST:event_botonPartidaNueva_SesionIniciadaMouseClicked private void botonAtras_SesionIniciadaMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_botonAtras_SesionIniciadaMouseClicked // TODO add your handling code here: IniciarSesion iniciarSesion = new IniciarSesion(); iniciarSesion.setVisible(true); this.dispose(); }//GEN-LAST:event_botonAtras_SesionIniciadaMouseClicked /** * Los botones serán transparentes */ public void transparenciaBoton(){ botonHistorial_SesionIniciada.setOpaque(false); botonHistorial_SesionIniciada.setContentAreaFilled(false); botonHistorial_SesionIniciada.setBorderPainted(false); botonContinuarPartida_SesionIniciada.setOpaque(false); botonContinuarPartida_SesionIniciada.setContentAreaFilled(false); botonContinuarPartida_SesionIniciada.setBorderPainted(false); botonPartidaNueva_SesionIniciada.setOpaque(false); botonPartidaNueva_SesionIniciada.setContentAreaFilled(false); botonPartidaNueva_SesionIniciada.setBorderPainted(false); botonAtras_SesionIniciada.setOpaque(false); botonAtras_SesionIniciada.setContentAreaFilled(false); botonAtras_SesionIniciada.setBorderPainted(false); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton botonAtras_SesionIniciada; private javax.swing.JButton botonContinuarPartida_SesionIniciada; private javax.swing.JButton botonHistorial_SesionIniciada; private javax.swing.JButton botonPartidaNueva_SesionIniciada; private javax.swing.JLabel fondo_SesionIniciada; private javax.swing.JLabel jLabelNombre_SesionIniciada; // End of variables declaration//GEN-END:variables } <file_sep>/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package interfaces; import clases.Historial; import clases.Usuario; import java.util.HashMap; import javax.swing.ImageIcon; /** * * @author laura */ public class Dificultad extends javax.swing.JFrame { /** * Creates new form Dificultad */ private static Usuario usuario; private static HashMap<String, clases.Historial> torneo; public Dificultad(HashMap<String, clases.Historial> torne, Usuario usuari) { usuario = usuari; torneo = torne; initComponents(); transparenciaBoton(); this.setLocationRelativeTo(null); //ajustarlo en el medio de la pantalla setIconImage(new ImageIcon(getClass().getResource("/imagenes/icono.jpg")).getImage()); //cambiar logo } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { botonBaja_Dificultad = new javax.swing.JButton(); botonMedia_Dificultad = new javax.swing.JButton(); botonAlta_Dificultad = new javax.swing.JButton(); botonImposible_Dificultad = new javax.swing.JButton(); botonAtras_Dificultad = new javax.swing.JButton(); fondoDificultad = new javax.swing.JLabel(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); setResizable(false); getContentPane().setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout()); botonBaja_Dificultad.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { botonBaja_DificultadMouseClicked(evt); } }); getContentPane().add(botonBaja_Dificultad, new org.netbeans.lib.awtextra.AbsoluteConstraints(400, 270, 510, 60)); botonMedia_Dificultad.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { botonMedia_DificultadMouseClicked(evt); } }); getContentPane().add(botonMedia_Dificultad, new org.netbeans.lib.awtextra.AbsoluteConstraints(400, 370, 510, 60)); botonAlta_Dificultad.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { botonAlta_DificultadMouseClicked(evt); } }); getContentPane().add(botonAlta_Dificultad, new org.netbeans.lib.awtextra.AbsoluteConstraints(400, 470, 510, 60)); botonImposible_Dificultad.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { botonImposible_DificultadMouseClicked(evt); } }); getContentPane().add(botonImposible_Dificultad, new org.netbeans.lib.awtextra.AbsoluteConstraints(400, 560, 510, 70)); botonAtras_Dificultad.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { botonAtras_DificultadMouseClicked(evt); } }); getContentPane().add(botonAtras_Dificultad, new org.netbeans.lib.awtextra.AbsoluteConstraints(1080, 655, 170, 30)); fondoDificultad.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imagenes/dificultad.jpg"))); // NOI18N getContentPane().add(fondoDificultad, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 0, -1, -1)); pack(); }// </editor-fold>//GEN-END:initComponents private void botonBaja_DificultadMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_botonBaja_DificultadMouseClicked // TODO add your handling code here: PartidaInterfaz p = new PartidaInterfaz(torneo, usuario, "BAJA"); p.setVisible(true); this.dispose(); }//GEN-LAST:event_botonBaja_DificultadMouseClicked private void botonMedia_DificultadMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_botonMedia_DificultadMouseClicked // TODO add your handling code here: PartidaInterfaz p = new PartidaInterfaz(torneo, usuario, "MEDIA"); p.setVisible(true); this.dispose(); }//GEN-LAST:event_botonMedia_DificultadMouseClicked private void botonAlta_DificultadMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_botonAlta_DificultadMouseClicked // TODO add your handling code here: PartidaInterfaz p = new PartidaInterfaz(torneo, usuario, "ALTA"); p.setVisible(true); this.dispose(); }//GEN-LAST:event_botonAlta_DificultadMouseClicked private void botonImposible_DificultadMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_botonImposible_DificultadMouseClicked // TODO add your handling code here: PartidaInterfaz p = new PartidaInterfaz(torneo, usuario, "IMPOSIBLE"); p.setVisible(true); this.dispose(); }//GEN-LAST:event_botonImposible_DificultadMouseClicked private void botonAtras_DificultadMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_botonAtras_DificultadMouseClicked // TODO add your handling code here: IniciarSesion inicioSesion = new IniciarSesion(); inicioSesion.setVisible(true); this.dispose(); }//GEN-LAST:event_botonAtras_DificultadMouseClicked /** * Los botones serán transparentes */ public void transparenciaBoton() { botonBaja_Dificultad.setOpaque(false); botonBaja_Dificultad.setContentAreaFilled(false); botonBaja_Dificultad.setBorderPainted(false); botonMedia_Dificultad.setOpaque(false); botonMedia_Dificultad.setContentAreaFilled(false); botonMedia_Dificultad.setBorderPainted(false); botonAlta_Dificultad.setOpaque(false); botonAlta_Dificultad.setContentAreaFilled(false); botonAlta_Dificultad.setBorderPainted(false); botonImposible_Dificultad.setOpaque(false); botonImposible_Dificultad.setContentAreaFilled(false); botonImposible_Dificultad.setBorderPainted(false); botonAtras_Dificultad.setOpaque(false); botonAtras_Dificultad.setContentAreaFilled(false); botonAtras_Dificultad.setBorderPainted(false); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton botonAlta_Dificultad; private javax.swing.JButton botonAtras_Dificultad; private javax.swing.JButton botonBaja_Dificultad; private javax.swing.JButton botonImposible_Dificultad; private javax.swing.JButton botonMedia_Dificultad; private javax.swing.JLabel fondoDificultad; // End of variables declaration//GEN-END:variables } <file_sep>package presentacion; import logica.Ordenador; import logica.Telefono; import logica.UtilTienda; import logica.Producto; import java.awt.HeadlessException; import java.io.IOException; import java.util.ArrayList; import java.util.ListIterator; import javax.swing.JOptionPane; public class ConsultaProductoD extends javax.swing.JDialog { private ArrayList<Producto> proaux; //Referencia al ArrayList de productos de la clase UtilTienda private ListIterator<Producto> li; //Iterador para recorrer el ArrayList en ambas direcciones private Producto objpro; /** * Creates new form ConsultaProductoD * @param parent la ventana principal * @param modal true para que solo podamos operar con esta ventana */ public ConsultaProductoD(java.awt.Frame parent, boolean modal) { super(parent, modal); initComponents(); panelDatos.desactivaCodigo(); consultarTodo(); this.setVisible(true); } /** Consulta los productos del ArrayList ordenadas para su presentación */ private void consultarTodo() { try { //referenciamos al ArrayList de UtilTienda proaux = UtilTienda.getProductos(); //creamos el iterador sobre el ArrayList li = proaux.listIterator(); //si no hay productos... if (proaux.size() < 1) { JOptionPane.showMessageDialog(this, "No hay productos.", "Mensaje", JOptionPane.INFORMATION_MESSAGE); jButtonSig.setEnabled(false); jButtonAnt.setEnabled(false); jButtonBaja.setEnabled(false); jButtonModf.setEnabled(false); jButtonCompra.setEnabled(false); jButtonReponer.setEnabled(false); return; } else { jButtonSig.setEnabled(true); jButtonAnt.setEnabled(true); jButtonBaja.setEnabled(true); jButtonModf.setEnabled(true); jButtonCompra.setEnabled(true); jButtonReponer.setEnabled(true); } //presentamos if (li.hasNext()) { objpro = li.next(); } if (objpro != null) { presenta(objpro); } else { JOptionPane.showMessageDialog(this, "No hay productos.", "Mensaje", JOptionPane.INFORMATION_MESSAGE); } } catch (HeadlessException e) { JOptionPane.showMessageDialog(this, "Error: " + e.getMessage(), "Mensaje", JOptionPane.ERROR_MESSAGE); System.out.println("Error: " + e.toString()); } }//fin consultarTodo /** Presenta los datos de un producto en el panel de datos */ private void presenta(Producto pro) { String tipo = pro.getClass().getSimpleName(); panelDatos.setJTextFieldCodigo(pro.getCodigo()); panelDatos.setJTextFieldNombre(pro.getNombre()); panelDatos.setJTextFieldPrecio(pro.getPrecio() + ""); panelDatos.setJTextFieldCantidad(pro.getCantidad() + ""); if (tipo.equals("Ordenador")) { Ordenador ord = (Ordenador) pro; panelDatos.setLabelVar("Características"); panelDatos.setJTextFieldVar(ord.getCaracteristicas()); } else { Telefono tel = (Telefono) pro; panelDatos.setLabelVar("Operador"); panelDatos.setJTextFieldVar(tel.getOperador()); } } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jLabel1 = new javax.swing.JLabel(); jButtonSig = new javax.swing.JButton(); jButtonAnt = new javax.swing.JButton(); jButtonBaja = new javax.swing.JButton(); jButtonReponer = new javax.swing.JButton(); jTextFieldCant = new javax.swing.JTextField(); jLabel2 = new javax.swing.JLabel(); jButtonCompra = new javax.swing.JButton(); jButtonModf = new javax.swing.JButton(); panelDatos = new presentacion.PanelDatos(); setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE); setTitle("Consultas"); jLabel1.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N jLabel1.setText("CONSULTA PRODUCTOS"); jButtonSig.setText("SIGUIENTE"); jButtonSig.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButtonSigActionPerformed(evt); } }); jButtonAnt.setText("ANTERIOR"); jButtonAnt.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButtonAntActionPerformed(evt); } }); jButtonBaja.setText("BAJA"); jButtonBaja.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButtonBajaActionPerformed(evt); } }); jButtonReponer.setText("REPONER"); jButtonReponer.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButtonReponerActionPerformed(evt); } }); jLabel2.setText("Cantidad"); jButtonCompra.setText("COMPRAR"); jButtonCompra.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButtonCompraActionPerformed(evt); } }); jButtonModf.setText("MODIFICAR"); jButtonModf.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButtonModfActionPerformed(evt); } }); panelDatos.setBackground(new java.awt.Color(0, 153, 204)); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addContainerGap(105, Short.MAX_VALUE) .addComponent(jLabel1) .addGap(117, 117, 117)) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addGap(27, 27, 27) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(panelDatos, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addGroup(layout.createSequentialGroup() .addComponent(jButtonSig) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 187, Short.MAX_VALUE) .addComponent(jButtonAnt)) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(jButtonCompra, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jButtonModf, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addGap(22, 22, 22) .addComponent(jLabel2) .addGap(18, 18, 18) .addComponent(jTextFieldCant, javax.swing.GroupLayout.DEFAULT_SIZE, 78, Short.MAX_VALUE) .addGap(26, 26, 26) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(jButtonBaja, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jButtonReponer, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))) .addGap(36, 36, 36)) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addGap(32, 32, 32) .addComponent(jLabel1) .addGap(18, 18, 18) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jButtonSig) .addComponent(jButtonAnt)) .addGap(18, 18, 18) .addComponent(panelDatos, javax.swing.GroupLayout.PREFERRED_SIZE, 180, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 30, Short.MAX_VALUE) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jButtonModf) .addComponent(jButtonBaja)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jButtonCompra) .addComponent(jButtonReponer) .addComponent(jTextFieldCant, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel2)) .addGap(30, 30, 30)) ); pack(); setLocationRelativeTo(null); }// </editor-fold>//GEN-END:initComponents private void jButtonSigActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonSigActionPerformed // TODO add your handling code here: //Comprobamos el rango del ArrayList... if (li.hasNext()) { objpro = li.next(); if (objpro != null) { presenta(objpro); } else { JOptionPane.showMessageDialog(this, "No hay productos.", "Mensaje", JOptionPane.INFORMATION_MESSAGE); } } }//GEN-LAST:event_jButtonSigActionPerformed private void jButtonAntActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonAntActionPerformed // TODO add your handling code here: //Comprobamos el rango del ArrayList... if (li.hasPrevious()) { objpro = li.previous(); if (objpro != null) { presenta(objpro); } else { JOptionPane.showMessageDialog(this, "No hay productos.", "Mensaje", JOptionPane.INFORMATION_MESSAGE); } } }//GEN-LAST:event_jButtonAntActionPerformed private void jButtonBajaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonBajaActionPerformed // TODO add your handling code here: if (objpro != null) { li.remove(); JOptionPane.showMessageDialog(this, "Producto dado de baja: " + objpro.toString(), "Mensaje", JOptionPane.INFORMATION_MESSAGE); } else { JOptionPane.showMessageDialog(this, " Error: - Producto no encontrado -", "Mensaje", JOptionPane.ERROR_MESSAGE); } //mostramos el elemento siguiente o anterior if (li.hasNext()) { objpro = li.next(); if (objpro != null) { presenta(objpro); } else { JOptionPane.showMessageDialog(this, "No hay productos.", "Mensaje", JOptionPane.INFORMATION_MESSAGE); } } else if (li.hasPrevious()) { objpro = li.previous(); if (objpro != null) { presenta(objpro); } else { JOptionPane.showMessageDialog(this, "No hay productos.", "Mensaje", JOptionPane.INFORMATION_MESSAGE); } } }//GEN-LAST:event_jButtonBajaActionPerformed private void jButtonReponerActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonReponerActionPerformed // TODO add your handling code here: try { int cantidad = Integer.parseInt(jTextFieldCant.getText()); int stock = objpro.getCantidad(); String tipo = objpro.getClass().getSimpleName(); objpro.setCantidad(cantidad + stock); JOptionPane.showMessageDialog(this, "Ahora hay " + objpro.getCantidad() + " unidades.", "Mensaje", JOptionPane.INFORMATION_MESSAGE); presenta(objpro); if (cantidad < 0) { JOptionPane.showMessageDialog(this, "No introduzca valores negativos", "Mensaje", JOptionPane.ERROR_MESSAGE); } } catch (HeadlessException | NumberFormatException e) { JOptionPane.showMessageDialog(this, "Error al comprar: " + e.toString(), "Mensaje", JOptionPane.ERROR_MESSAGE); } }//GEN-LAST:event_jButtonReponerActionPerformed private void jButtonCompraActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonCompraActionPerformed // TODO add your handling code here: try { int cantidad = Integer.parseInt(jTextFieldCant.getText()); int stock = objpro.getCantidad(); if (cantidad < 0) { JOptionPane.showMessageDialog(this, "No introduzca valores negativos.", "Mensaje", JOptionPane.ERROR_MESSAGE); return; } if (stock >= cantidad) { objpro.setCantidad(stock - cantidad); double precio = cantidad * objpro.getPrecio(); JOptionPane.showMessageDialog(this, "Ha comprado el producto a " + precio + " - Consulte su factura -", "Mensaje", JOptionPane.INFORMATION_MESSAGE); presenta(objpro); UtilTienda.generaFactura(objpro, cantidad); } else { JOptionPane.showMessageDialog(this, "No hay suficiente stock.", "Mensaje", JOptionPane.INFORMATION_MESSAGE); } } catch (HeadlessException | IOException | NumberFormatException e) { JOptionPane.showMessageDialog(this, "Error al comprar: " + e.toString(), "Mensaje", JOptionPane.ERROR_MESSAGE); } }//GEN-LAST:event_jButtonCompraActionPerformed private void jButtonModfActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonModfActionPerformed // TODO add your handling code here: try { String nombre = panelDatos.getJTextFieldNombre(); double precio = Double.parseDouble(panelDatos.getJTextFieldPrecio()); String var = panelDatos.getJTextFieldVar(); if (UtilTienda.modificaProducto(objpro, nombre, precio, var)) { JOptionPane.showMessageDialog(this, "Producto modificado.", "Mensaje", JOptionPane.INFORMATION_MESSAGE); } else { JOptionPane.showMessageDialog(this, " Error: - Producto no encontrado -", "Mensaje", JOptionPane.ERROR_MESSAGE); } } catch (HeadlessException | NumberFormatException e) { JOptionPane.showMessageDialog(this, "Error al modificar: " + e.toString(), "Mensaje", JOptionPane.ERROR_MESSAGE); } }//GEN-LAST:event_jButtonModfActionPerformed // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton jButtonAnt; private javax.swing.JButton jButtonBaja; private javax.swing.JButton jButtonCompra; private javax.swing.JButton jButtonModf; private javax.swing.JButton jButtonReponer; private javax.swing.JButton jButtonSig; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel2; private javax.swing.JTextField jTextFieldCant; private presentacion.PanelDatos panelDatos; // End of variables declaration//GEN-END:variables } <file_sep>/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package cadenasCaracteres.string; import java.util.Scanner; /** * * @author laura * * Escribir un programa que reciba un NIF con 9 caracteres (ej. 00395469F) y nos diga si la letra es correcta. * */ public class NIFLetra4 { public static void main (String[] args){ Scanner entrada = new Scanner(System.in); String nif; String letra; String numeroString; System.out.println("\nNIF (ej. 00395469F): "); nif = entrada.nextLine(); letra = nif.substring(8); letra = letra.toUpperCase(); //pasamos la letra a mayúscula numeroString = nif.substring(0, 8); int numero = Integer.parseInt(numeroString); if (conversion(numero, letra)){ System.out.println("Letra correcta."); } else{ System.out.println("Letra incorrecta."); } } public static boolean conversion (int numero, String letra){ String[] letras = {"T", "R", "W", "A", "G", "M", "Y", "F", "P", "D", "X", "B", "N", "J", "Z", "S", "Q", "V", "H", "L", "C", "K", "E"}; int resto; resto = numero % 23; if (letras[resto].equals(letra)){ return true; } else{ return false; } } } <file_sep>/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package aparcamiento; import java.time.LocalDateTime; import java.time.Month; import java.time.temporal.ChronoUnit; /** * * @author laura */ public class MainAparcamiento { public static void main(String[] args) { Automovil a1 = new Automovil("1111-AAA", true, "turismo"); Automovil a2 = new Automovil("2222-BBB", false, "todoterreno"); Automovil a3 = new Automovil("3333-CCC", false, "furgoneta"); Camion c1 = new Camion("4444-DDD", true, 4); Camion c2 = new Camion("5555-EEE", false, 3); Camion c3 = new Camion("6666-FFF", false, 5); System.out.println(Aparcamiento.intoducirVehiculo(a1)); System.out.println(Aparcamiento.intoducirVehiculo(a2)); System.out.println(Aparcamiento.intoducirVehiculo(a3)); System.out.println(Aparcamiento.intoducirVehiculo(c1)); System.out.println(Aparcamiento.intoducirVehiculo(c2)); System.out.println(Aparcamiento.intoducirVehiculo(c3)); System.out.println("Vehículos: "+ Aparcamiento.getMatriculasVehiculos().toString()); System.out.println(Aparcamiento.sacarVehiculo(a1)); System.out.println("Vehículos: "+ Aparcamiento.getMatriculasVehiculos().toString()); System.out.println(Aparcamiento.sacarVehiculo(a2)); System.out.println("Vehículos: "+ Aparcamiento.getMatriculasVehiculos().toString()); System.out.println(Aparcamiento.sacarVehiculo(a3)); System.out.println("Vehículos: "+ Aparcamiento.getMatriculasVehiculos().toString()); System.out.println(Aparcamiento.sacarVehiculo(c1)); System.out.println("Vehículos: "+ Aparcamiento.getMatriculasVehiculos().toString()); System.out.println(Aparcamiento.sacarVehiculo(c2)); System.out.println("Vehículos: "+ Aparcamiento.getMatriculasVehiculos().toString()); System.out.println(Aparcamiento.sacarVehiculo(c3)); System.out.println("Vehículos: "+ Aparcamiento.getMatriculasVehiculos().toString()); } } <file_sep>package alquilerInmuebles; import java.time.LocalDate; import java.time.format.DateTimeFormatter; public class Particular extends Cliente { private LocalDate fechaNac; private Nomina nomina; private String NIF; public Particular(String nombre, String nif, String telefono, String email, double salarioBruto, double retencion) { super(nombre, telefono, email); this.NIF = nif; this.fechaNac = LocalDate.now(); this.nomina = new Nomina(this, salarioBruto, retencion); } public LocalDate getFechaNac() { return fechaNac; } public void setFechaNac(LocalDate fechaNac) { this.fechaNac = fechaNac; } public Nomina getNomina() { return nomina; } public void setNomina(Nomina nomina) { this.nomina = nomina; } public String getFechaNacString() { DateTimeFormatter formatoCorto = DateTimeFormatter.ofPattern("dd/MM/yyyy"); String hoystr = this.fechaNac.format(formatoCorto); return hoystr; } public String getNif() { return NIF; } public void setNif(String nif) { this.NIF = nif; } @Override public boolean esSolvente(Inmueble inmueble) { double salario = this.getNomina().getSalarioNeto(); double precio = 0; if (inmueble instanceof Piso) { precio = ((Piso) inmueble).getPrecioMensual(); } else if (inmueble instanceof LocalComercial) { precio = ((LocalComercial) inmueble).precioAlquiler(); } else if (inmueble instanceof Edificio) { precio = ((Edificio) inmueble).precioAlquiler(); } return salario > precio; } @Override public String toString() { String cliente = super.toString(); return cliente + " # Particular{" + ", NIF=" + NIF + "fechaNac=" + fechaNac + ", nomina=" + nomina + '}'; } } <file_sep>package ficheros; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileInputStream; import java.io.FileWriter; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; public class FicheroProductos { public static void main(String[] args) { // TODO code application logic here leer(); } public static void leer() { String cad; try { FileInputStream fis = new FileInputStream("productos.txt"); InputStreamReader isr = new InputStreamReader(fis, "ISO-8859-1"); BufferedReader br = new BufferedReader(isr); PrintWriter salida = new PrintWriter(new BufferedWriter(new FileWriter("productos_iva.txt"))); String cadena = ""; String array[]; while ((cad = br.readLine()) != null) { System.out.println(cad); array = cad.split(";"); double precio = Double.parseDouble(array[6].trim()); //trim quita espacios en blanco precio += (precio * 0.18); for (int i = 0; i < array.length - 1; i++) { cadena += array[i] + ";"; } cadena += " " + precio + ";"; salida.println(cadena); cadena = ""; } //Cerramos el stream br.close(); salida.close(); } catch (IOException ioe) { System.out.println(ioe); } } } <file_sep>/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package interfaces; import clases.Torneo; import clases.Usuario; import java.util.HashMap; import javax.swing.ImageIcon; import clases.Historial; /** * * @author laura */ public class HistorialInterfaz extends javax.swing.JFrame { /** * Creates new form Historial */ private static HashMap<String, clases.Historial> torneo; private static Usuario usuario; public HistorialInterfaz(HashMap<String, clases.Historial> torne, Usuario usuari) { torneo = torne; usuario = usuari; initComponents(); transparenciaBoton(); this.setLocationRelativeTo(null); //ajustarlo en el medio de la pantalla clases.Historial historial = Torneo.devolverHistorial(torneo, usuario.getDNI()); jLabelNombre_Historial.setText(usuario.getNombre()); jLabelPuntosBaja_Historial.setText(Integer.toString(historial.getPartidasBajas().getPuntos())); jLabelPuntosMedia_Historial.setText(Integer.toString(historial.getPartidasMedias().getPuntos())); jLabelPuntosAlta_Historial.setText(Integer.toString(historial.getPartidasAltas().getPuntos())); jLabelPuntosImposible_Historial.setText(Integer.toString(historial.getPartidasImposibles().getPuntos())); setIconImage(new ImageIcon(getClass().getResource("/imagenes/icono.jpg")).getImage()); //cambiar logo } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { botonAtras_Historial = new javax.swing.JButton(); botonBaja_Historial = new javax.swing.JButton(); botonMedia_Historial = new javax.swing.JButton(); botonAlta_Historial = new javax.swing.JButton(); botonImposible_Historial = new javax.swing.JButton(); jLabelNombre_Historial = new javax.swing.JLabel(); jLabelPuntosBaja_Historial = new javax.swing.JLabel(); jLabelPuntosMedia_Historial = new javax.swing.JLabel(); jLabelPuntosAlta_Historial = new javax.swing.JLabel(); jLabelPuntosImposible_Historial = new javax.swing.JLabel(); fondo_Historial = new javax.swing.JLabel(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); setResizable(false); getContentPane().setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout()); botonAtras_Historial.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { botonAtras_HistorialMouseClicked(evt); } }); getContentPane().add(botonAtras_Historial, new org.netbeans.lib.awtextra.AbsoluteConstraints(1060, 680, 170, 40)); botonBaja_Historial.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { botonBaja_HistorialMouseClicked(evt); } }); getContentPane().add(botonBaja_Historial, new org.netbeans.lib.awtextra.AbsoluteConstraints(450, 200, 590, 70)); botonMedia_Historial.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { botonMedia_HistorialMouseClicked(evt); } }); getContentPane().add(botonMedia_Historial, new org.netbeans.lib.awtextra.AbsoluteConstraints(450, 310, 600, 70)); botonAlta_Historial.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { botonAlta_HistorialMouseClicked(evt); } }); getContentPane().add(botonAlta_Historial, new org.netbeans.lib.awtextra.AbsoluteConstraints(450, 420, 600, 70)); botonImposible_Historial.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { botonImposible_HistorialMouseClicked(evt); } }); getContentPane().add(botonImposible_Historial, new org.netbeans.lib.awtextra.AbsoluteConstraints(450, 530, 590, 60)); jLabelNombre_Historial.setFont(new java.awt.Font("Cooper Black", 0, 48)); // NOI18N jLabelNombre_Historial.setForeground(new java.awt.Color(255, 204, 204)); jLabelNombre_Historial.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); getContentPane().add(jLabelNombre_Historial, new org.netbeans.lib.awtextra.AbsoluteConstraints(180, 60, 870, 100)); jLabelPuntosBaja_Historial.setFont(new java.awt.Font("Cooper Black", 0, 36)); // NOI18N jLabelPuntosBaja_Historial.setForeground(new java.awt.Color(255, 255, 255)); jLabelPuntosBaja_Historial.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); getContentPane().add(jLabelPuntosBaja_Historial, new org.netbeans.lib.awtextra.AbsoluteConstraints(170, 220, 210, 50)); jLabelPuntosMedia_Historial.setFont(new java.awt.Font("Cooper Black", 0, 36)); // NOI18N jLabelPuntosMedia_Historial.setForeground(new java.awt.Color(255, 255, 255)); jLabelPuntosMedia_Historial.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); getContentPane().add(jLabelPuntosMedia_Historial, new org.netbeans.lib.awtextra.AbsoluteConstraints(170, 320, 210, 60)); jLabelPuntosAlta_Historial.setFont(new java.awt.Font("Cooper Black", 0, 36)); // NOI18N jLabelPuntosAlta_Historial.setForeground(new java.awt.Color(255, 255, 255)); jLabelPuntosAlta_Historial.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); getContentPane().add(jLabelPuntosAlta_Historial, new org.netbeans.lib.awtextra.AbsoluteConstraints(170, 420, 210, 60)); jLabelPuntosImposible_Historial.setFont(new java.awt.Font("Cooper Black", 0, 36)); // NOI18N jLabelPuntosImposible_Historial.setForeground(new java.awt.Color(255, 255, 255)); jLabelPuntosImposible_Historial.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); getContentPane().add(jLabelPuntosImposible_Historial, new org.netbeans.lib.awtextra.AbsoluteConstraints(170, 530, 210, 60)); fondo_Historial.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imagenes/historial.jpg"))); // NOI18N getContentPane().add(fondo_Historial, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 0, -1, -1)); pack(); }// </editor-fold>//GEN-END:initComponents private void botonAtras_HistorialMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_botonAtras_HistorialMouseClicked // TODO add your handling code here: SesionIniciada sesionIniciada = new SesionIniciada(torneo, usuario); sesionIniciada.setVisible(true); this.dispose(); }//GEN-LAST:event_botonAtras_HistorialMouseClicked private void botonBaja_HistorialMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_botonBaja_HistorialMouseClicked // TODO add your handling code here: DificultadBaja d = new DificultadBaja(torneo, usuario); d.setVisible(true); this.dispose(); }//GEN-LAST:event_botonBaja_HistorialMouseClicked private void botonMedia_HistorialMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_botonMedia_HistorialMouseClicked // TODO add your handling code here: DificultadMedia d = new DificultadMedia(torneo, usuario); d.setVisible(true); this.dispose(); }//GEN-LAST:event_botonMedia_HistorialMouseClicked private void botonAlta_HistorialMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_botonAlta_HistorialMouseClicked // TODO add your handling code here: DificultadAlta d = new DificultadAlta(torneo, usuario); d.setVisible(true); this.dispose(); }//GEN-LAST:event_botonAlta_HistorialMouseClicked private void botonImposible_HistorialMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_botonImposible_HistorialMouseClicked // TODO add your handling code here: DificultadImposible d = new DificultadImposible(torneo, usuario); d.setVisible(true); this.dispose(); }//GEN-LAST:event_botonImposible_HistorialMouseClicked /** * Los botones serán transparentes */ public void transparenciaBoton(){ botonAtras_Historial.setOpaque(false); botonAtras_Historial.setContentAreaFilled(false); botonAtras_Historial.setBorderPainted(false); botonBaja_Historial.setOpaque(false); botonBaja_Historial.setContentAreaFilled(false); botonBaja_Historial.setBorderPainted(false); botonMedia_Historial.setOpaque(false); botonMedia_Historial.setContentAreaFilled(false); botonMedia_Historial.setBorderPainted(false); botonAlta_Historial.setOpaque(false); botonAlta_Historial.setContentAreaFilled(false); botonAlta_Historial.setBorderPainted(false); botonImposible_Historial.setOpaque(false); botonImposible_Historial.setContentAreaFilled(false); botonImposible_Historial.setBorderPainted(false); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton botonAlta_Historial; private javax.swing.JButton botonAtras_Historial; private javax.swing.JButton botonBaja_Historial; private javax.swing.JButton botonImposible_Historial; private javax.swing.JButton botonMedia_Historial; private javax.swing.JLabel fondo_Historial; private javax.swing.JLabel jLabelNombre_Historial; private javax.swing.JLabel jLabelPuntosAlta_Historial; private javax.swing.JLabel jLabelPuntosBaja_Historial; private javax.swing.JLabel jLabelPuntosImposible_Historial; private javax.swing.JLabel jLabelPuntosMedia_Historial; // End of variables declaration//GEN-END:variables } <file_sep>/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package arrays.ejercicios; import java.util.Scanner; /** * * @author laura * * Escribir un programa que sea capaz de calcular la letra de un NIF a partir del número del DNI. El programa debe poseer al menos un método encargado de pedir al usuario el DNI de 8 dígitos y otro que calculará la letra del NIF (se pueden añadir más métodos auxiliares). Al finalizar el programa se debe presentar el NIF completo con el formato: ocho dígitos, un guion y la letra en mayúscula; por ejemplo: 00395469-F. La letra se calculará de la siguiente forma: Se obtiene el resto de la división entera del número del DNI entre 23 y se usa la siguiente tabla para obtener la letra que corresponde, esta tabla debe estar almacenada en un array para buscar la letra por su posición. * */ public class DNI3 { public static void main (String[] args){ Scanner entrada = new Scanner (System.in); int dni; String[] letras = {"T", "R", "W", "A", "G", "M", "Y", "F", "P", "D", "X", "B", "N", "J", "Z", "S", "Q", "V", "H", "L", "C", "K", "E"}; System.out.print("DNI (sin letra): "); dni = entrada.nextInt(); System.out.println (dni + " - " + letras[posicion(dni)]); } public static int posicion (int dni){ return dni % 23; } } <file_sep>package logica; import java.io.Serializable; public class Producto implements Serializable { private String codigo; private String nombre; private double precio; private int cantidad; public Producto() { } public Producto(String codigo, String nombre, double precio, int cantidad) { this.codigo = codigo; this.nombre = nombre; this.precio = precio; this.cantidad = cantidad; } public int getCantidad() { return cantidad; } public void setCantidad(int cantidad) { this.cantidad = cantidad; } public String getCodigo() { return codigo; } public void setCodigo(String codigo) { this.codigo = codigo; } public String getNombre() { return nombre; } public void setNombre(String nombre) { this.nombre = nombre; } public double getPrecio() { return precio; } public void setPrecio(double precio) { this.precio = precio; } @Override public String toString() { return "Producto{" + " - código = " + codigo + " - nombre = " + nombre + " - precio = " + precio + " - cantidad = " + cantidad + '}'; } } <file_sep>/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package aparcamiento; import java.time.LocalDateTime; import java.time.Month; /** * * @author laura */ public class MainAparcamiento2 { public static void main(String[] args) { LocalDateTime diaHora = LocalDateTime.of(2019, Month.FEBRUARY, 19, 10, 59, 59); Automovil a1 = new Automovil("1111-AAA", diaHora, true, "turismo"); Automovil a2 = new Automovil("2222-BBB", diaHora, false, "todoterreno"); Automovil a3 = new Automovil("3333-CCC", diaHora, false, "furgoneta"); Camion c1 = new Camion("4444-DDD", diaHora, true, 4); Camion c2 = new Camion("5555-EEE", diaHora, false, 3); Camion c3 = new Camion("6666-FFF", diaHora, false, 5); System.out.println(Aparcamiento.intoducirVehiculo(a1)); System.out.println(Aparcamiento.intoducirVehiculo(a2)); System.out.println(Aparcamiento.intoducirVehiculo(a3)); System.out.println(Aparcamiento.intoducirVehiculo(c1)); System.out.println(Aparcamiento.intoducirVehiculo(c2)); System.out.println(Aparcamiento.intoducirVehiculo(c3)); System.out.println("Vehículos: "+ Aparcamiento.getMatriculasVehiculos().toString()); System.out.println(Aparcamiento.sacarVehiculo(a1.getMatricula())); System.out.println("Vehículos: "+ Aparcamiento.getMatriculasVehiculos().toString()); System.out.println(Aparcamiento.sacarVehiculo(a2.getMatricula())); System.out.println("Vehículos: "+ Aparcamiento.getMatriculasVehiculos().toString()); System.out.println(Aparcamiento.sacarVehiculo(a3.getMatricula())); System.out.println("Vehículos: "+ Aparcamiento.getMatriculasVehiculos().toString()); System.out.println(Aparcamiento.sacarVehiculo(c1.getMatricula())); System.out.println("Vehículos: "+ Aparcamiento.getMatriculasVehiculos().toString()); System.out.println(Aparcamiento.sacarVehiculo(c2.getMatricula())); System.out.println("Vehículos: "+ Aparcamiento.getMatriculasVehiculos().toString()); System.out.println(Aparcamiento.sacarVehiculo(c3.getMatricula())); System.out.println("Vehículos: "+ Aparcamiento.getMatriculasVehiculos().toString()); } } <file_sep>/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package clases; import java.util.Random; /** * * @author laura */ public class PartidaEnJuego { /** * main * * @param args */ public static void main(String[] args) { int numZombis = 0; int turnosInicialesSinZombis = 0; int[] soles = {50}; int[] contadorZombis = {0}; int[] contadorZombiesTablero = {0}; int[] contadorZombiesMuertos = {0}; int contadorTurno = 1; String[] listaLineaComandos = ExcepcionJuego.pedirInstruccion(); String modoSeleccion = listaLineaComandos[0].toUpperCase(); //int numFilas = Integer.parseInt(listaLineaComandos[1]); //int numColumnas = Integer.parseInt(listaLineaComandos[2]); int numFilas = 5; int numColumnas = 9; String dificultad = listaLineaComandos[3].toUpperCase(); //crear caasilla vacía CasillaVacia casillaVacia = new CasillaVacia(0, 0, 0, 0); //crear y rellenar tablero Objeto[][] tablero = Tablero.crearTablero(numFilas, numColumnas); tablero = Tablero.rellenarTablero(tablero, casillaVacia, numFilas, numColumnas); //asignación de turnos, num zombies, turnos iniciales sin zombies --> según dificultad if ("BAJA".equals(dificultad)) { numZombis = 5; turnosInicialesSinZombis = 10; } else if ("MEDIA".equals(dificultad)) { numZombis = 15; turnosInicialesSinZombis = 7; } else if ("ALTA".equals(dificultad)) { numZombis = 25; turnosInicialesSinZombis = 5; } else if ("IMPOSIBLE".equals(dificultad)) { numZombis = 50; turnosInicialesSinZombis = 5; } int[] contadorZombisQuedan = {numZombis}; //_________________________________________________________________________________ System.out.println("\nComenzando la partida.\n"); Tablero.imprimirMensajes(tablero, numFilas, numColumnas, soles, numZombis, contadorZombisQuedan); //_________________________________________________________________________________ boolean finPartida = false; int turnosRepartoZombis = 30; int zombisQuedan = 0; contadorTurno = 1; int contadorPlantaLanzaGuisantes = 0; boolean comprobadorImprimir = true; listaLineaComandos = ExcepcionJuego.pedirInstruccion(); if (!"".equals(listaLineaComandos[0])) { modoSeleccion = listaLineaComandos[0].toUpperCase(); } else { modoSeleccion = ""; } while (!"S".equals(modoSeleccion)) { //eligen PlantaGirasol if ("NUEVA".equals(modoSeleccion)) { System.out.println("Partida comenzada. Si quieres jugar, haz otra partida"); contadorTurno--; //para que no pase turno comprobadorImprimir = false; } else if (!"".equals(modoSeleccion)) { Tablero.agregarPlanta(tablero, soles, listaLineaComandos, numFilas, numColumnas, modoSeleccion); } //zombies Tablero.agregarZombie(tablero, numFilas, numColumnas, contadorZombis, contadorZombiesTablero, turnosInicialesSinZombis, numZombis, contadorZombisQuedan); //--------------------------------------------------------------------------------------- zombisQuedan = numZombis - contadorZombis[0]; System.out.println(""); if (comprobadorImprimir == true) { Tablero.imprimirMensajes(tablero, numFilas, numColumnas, soles, numZombis, contadorZombisQuedan); contadorTurno++; turnosInicialesSinZombis--; } comprobadorImprimir = true; //--------------------------------------------------------------------------------------- //finPartida == true if (ExcepcionJuego.finPartida(tablero, numFilas, numColumnas, contadorZombis[0], numZombis, contadorTurno) == true) { if (contadorZombis[0] == numZombis) { System.out.println("\nHan ganado las PLANTAS!!!!"); } else { System.out.println("\nHan ganado los ZOMBIES!!!!"); } System.exit(0); } //movimientos Tablero.movimientos(tablero, numFilas, numColumnas, soles, casillaVacia, contadorZombiesTablero, contadorZombiesMuertos); //---------------------------------------------------------------------------------------- if (finPartida == false) { listaLineaComandos = ExcepcionJuego.pedirInstruccion(); if (!"".equals(listaLineaComandos[0])) { modoSeleccion = listaLineaComandos[0].toUpperCase(); } else { modoSeleccion = ""; } } //--------------------------------------------------------------------------------------- } System.out.println("\nHas abandonado la partida."); } } <file_sep>package empleados; public class PruebaEmpleados { public static void main(String[] args) { // TODO code application logic here //1 - creamos la empresa Empresa e1 = new Empresa("Indra", "1234567"); //2 - creamos los departamentos Departamento d1 = new Departamento("Informática", "1", "Madrid", e1); Departamento d2 = new Departamento("Personal", "2", "Barcelona", e1); //3 - creamos los empleados que asignamos a los departamentos Empleado emp1 = new Empleado("1234", "Pepe", 25, "soltero", 1500, "programador", d1); Empleado emp2 = new Empleado("4567", "Laura", 35, "casada", 2000, "analista", d1); Empleado emp3 = new Empleado("5678", "Maria", 40, "casada", 2500, "gerente", d2); //modificamos los datos de los empleados emp1.cumpleaños(); emp1.setSueldo(2000); System.out.println(emp1.toString()); System.out.println("Empleados departamento: " + d1.getEmpleados().toString()); emp2.setCargo("jefe proyecto"); d1.bajaEmpleado(emp2); d2.altaEmpleado(emp2); System.out.println(emp2.toString()); //imprimimos los elementos del ArrayList System.out.println("Empleados departamento: " + d1.getEmpleados().toString()); } } <file_sep>package alquilerInmuebles; public class Gasto extends Movimiento { private Inmueble inmueble; private String tipo; public Gasto(Inmueble inmueble, String tipo, Cuenta cuenta, double cantidad) { super(cuenta, cantidad); this.inmueble = inmueble; this.tipo = tipo; } public Inmueble getInmueble() { return inmueble; } public void setInmueble(Inmueble inmueble) { this.inmueble = inmueble; } public String getTipo() { return tipo; } public void setTipo(String tipo) { this.tipo = tipo; } @Override public String toString() { return "Gasto{" + "inmueble=" + inmueble + ", tipo=" + tipo + '}'; } } <file_sep>/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package clases; /** * * @author laura */ public class Planta extends Objeto{ private int coste; private float frecuencia; //constructor public Planta(int coste, int resistencia, float frecuencia, int danio, int ciclo) { super (resistencia, danio, ciclo); this.coste = coste; this.frecuencia = frecuencia; } public int getCoste() { return coste; } public void setCoste(int coste) { this.coste = coste; } public float getFrecuencia() { return frecuencia; } public void setFrecuencia(float frecuencia) { this.frecuencia = frecuencia; } } <file_sep>/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package media; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; /** * * @author laura */ public class MediaSwitch { public static void main( String args[] ) throws IOException { int contador, total, media; String nota; //Objeto para leer una cadena del teclado BufferedReader entrada = new BufferedReader(new InputStreamReader(System.in)); // inicialización de variables total = 0; contador = 1; while ( contador <= 5 ) { System.out.println( "\nTeclee calificación (A,B,C,D,E): " ); nota = entrada.readLine(); switch (nota) { case "A": total = total + 4; break; case "B": total = total + 3; break; case "C": total = total + 2; break; case "D": total = total + 1; break; case "E": total = total + 0; break; default: break; } contador = contador + 1; } media = total / 5; System.out.println("\n\nEl promedio del grupo es: " + media); } } <file_sep>/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package ejerciciosBasicos2; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.text.DecimalFormat; /** * * @author laura */ /** Realizar un programa que calcule la pendiente de una línea recta dada por dos puntos de la misma (x1,y1) y (x2,y2). La fórmula a aplicar será: p = (y2-y1) / (x2-x1) */ public class Pendiente3 { public static void main (String[] args) throws IOException{ BufferedReader entrada = new BufferedReader(new InputStreamReader(System.in)); double x1; double y1; double x2; double y2; double pendiente; System.out.print("\nx1: "); x1 = Double.parseDouble(entrada.readLine()); System.out.print("\ny1: "); y1 = Double.parseDouble(entrada.readLine()); System.out.print("\nx2: "); x2 = Double.parseDouble(entrada.readLine()); System.out.print("\ny2: "); y2 = Double.parseDouble(entrada.readLine()); pendiente = (y2-y1) / (x2-x1); System.out.println(""); //Controlar número de decimales DecimalFormat decimal = new DecimalFormat("#.##"); System.out.println("Pendiente: " + decimal.format(pendiente)); } } <file_sep>/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package interfaces; import clases.Historial; import clases.Torneo; import clases.Usuario; import static clases.Usuario.prepararDNI; import java.util.HashMap; import javax.swing.ImageIcon; import javax.swing.JOptionPane; /** * * @author laura */ public class Registro extends javax.swing.JFrame { /** * Creates new form RegistroInterfaz */ private static HashMap<String, Historial> torneo; public Registro(HashMap<String, Historial> torne) { torneo = torne; initComponents(); transparenciaBoton(); this.setLocationRelativeTo(null); //ajustarlo en el medio de la pantalla setIconImage(new ImageIcon(getClass().getResource("/imagenes/icono.jpg")).getImage()); //cambiar logo } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { textFieldNombreRegistro = new javax.swing.JTextField(); textFieldDniRegistro = new javax.swing.JTextField(); botonRegistrarse_Registro = new javax.swing.JButton(); botonAtras_Registro = new javax.swing.JButton(); fondoRegistro = new javax.swing.JLabel(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); setResizable(false); getContentPane().setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout()); textFieldNombreRegistro.setFont(new java.awt.Font("Cooper Black", 0, 18)); // NOI18N textFieldNombreRegistro.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { textFieldNombreRegistroActionPerformed(evt); } }); getContentPane().add(textFieldNombreRegistro, new org.netbeans.lib.awtextra.AbsoluteConstraints(470, 120, 250, 30)); textFieldDniRegistro.setFont(new java.awt.Font("Cooper Black", 0, 18)); // NOI18N getContentPane().add(textFieldDniRegistro, new org.netbeans.lib.awtextra.AbsoluteConstraints(400, 220, 310, 30)); botonRegistrarse_Registro.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { botonRegistrarse_RegistroMouseClicked(evt); } }); getContentPane().add(botonRegistrarse_Registro, new org.netbeans.lib.awtextra.AbsoluteConstraints(320, 330, 390, 40)); botonAtras_Registro.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { botonAtras_RegistroMouseClicked(evt); } }); getContentPane().add(botonAtras_Registro, new org.netbeans.lib.awtextra.AbsoluteConstraints(370, 410, 290, 30)); fondoRegistro.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imagenes/registro.jpg"))); // NOI18N getContentPane().add(fondoRegistro, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 0, -1, -1)); pack(); }// </editor-fold>//GEN-END:initComponents private void botonRegistrarse_RegistroMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_botonRegistrarse_RegistroMouseClicked // TODO add your handling code here: String nombre = textFieldNombreRegistro.getText(); String dniString = textFieldDniRegistro.getText(); Usuario usuario = new Usuario(dniString, nombre); if (Usuario.comprobarDNI(dniString)) { String dni = Usuario.prepararDNI(textFieldDniRegistro.getText()); usuario = new Usuario(dni, nombre); if (Torneo.comprobarUsuarioRegistrado(torneo, dni) == false) { //si el usuario NO está registrado Torneo.aniadirUsuario(torneo, usuario); //cambio interfaz Registrado r = new Registrado(torneo, usuario); r.setVisible(true); this.dispose(); } else { JOptionPane.showMessageDialog(this, "Este usuario ya está registrado."); } } else { JOptionPane.showMessageDialog(this, "DNI falso."); textFieldDniRegistro.setText(""); } }//GEN-LAST:event_botonRegistrarse_RegistroMouseClicked /** * Conecta Registro con IniciarSesion * * @param evt */ private void botonAtras_RegistroMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_botonAtras_RegistroMouseClicked // TODO add your handling code here: IniciarSesion inicioSesion = new IniciarSesion(); inicioSesion.setVisible(true); this.dispose(); }//GEN-LAST:event_botonAtras_RegistroMouseClicked private void textFieldNombreRegistroActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_textFieldNombreRegistroActionPerformed // TODO add your handling code here: }//GEN-LAST:event_textFieldNombreRegistroActionPerformed /** * Los botones serán transparentes */ public void transparenciaBoton() { botonRegistrarse_Registro.setOpaque(false); botonRegistrarse_Registro.setContentAreaFilled(false); botonRegistrarse_Registro.setBorderPainted(false); botonAtras_Registro.setOpaque(false); botonAtras_Registro.setContentAreaFilled(false); botonAtras_Registro.setBorderPainted(false); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton botonAtras_Registro; private javax.swing.JButton botonRegistrarse_Registro; private javax.swing.JLabel fondoRegistro; private javax.swing.JTextField textFieldDniRegistro; private javax.swing.JTextField textFieldNombreRegistro; // End of variables declaration//GEN-END:variables } <file_sep>/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package cadenasCaracteres.stringTokenizer; import java.util.Scanner; /** * * @author laura * * Escribir un programa que pida una cadena y la divida en palabras y presente las palabras en orden inverso. Consejo: Utilizar la clase StringBuilder. */ public class PalabrasOrdenInversoST3 { public static void main (String[] args){ Scanner entrada = new Scanner(System.in); String frase; String palabra; int contador = 0; System.out.print("Frase: "); frase = entrada.nextLine(); } } <file_sep>/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package ejerciciosPropuestos2; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; /** * * @author laura * * Programa que pida un entero n>=0 y calcule e imprima Σi entre 0 y n. */ public class Sumatorio1 { public static void main (String[] args) throws IOException{ BufferedReader entrada = new BufferedReader(new InputStreamReader(System.in)); int n; int sumatorio; System.out.print("\nNúmero: "); n = Integer.parseInt(entrada.readLine()); sumatorio = 0; while (n != 0){ sumatorio += n; n -=1; } System.out.println("Sumatorio: " + sumatorio); } } <file_sep>/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package clases; import java.util.ArrayList; /** * * @author laura */ public class PartidaAlta extends PartidaDificultad { private int puntos; public PartidaAlta(String dificultad) { super(dificultad); } public PartidaAlta(ArrayList<Partida> partidasAltas, String dificultad, int puntos) { super(dificultad); this.partidasAltas = partidasAltas; this.puntos = puntos; } public int getPuntos() { return puntos; } private ArrayList<Partida> partidasAltas; public ArrayList<Partida> getPartidasAltas() { return partidasAltas; } public void setPartidasAltas(ArrayList<Partida> partidasAltas) { this.partidasAltas = partidasAltas; } public static PartidaAlta crearPartidaAlta() { PartidaAlta partidaAlta = new PartidaAlta("ALTA"); return partidaAlta; } } <file_sep>/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package clases; import java.util.Random; /** * * @author laura */ public class Zombie extends Objeto { private int velocidad; //constructor public Zombie(int coste, int resistencia, int danio, int ciclo, int velocidad) { super(coste, resistencia, danio, ciclo); this.velocidad = velocidad; } public int getVelocidad() { return velocidad; } public void setVelocidad(int velocidad) { this.velocidad = velocidad; } /** * Los zombies avanzan o se quedan en su casillo en función del contenido de * las casillas. Modifica el tablero * * @param tablero * @param i * @param j * @param casillaVacia * @return Objeto[][] tablero */ public static Objeto[][] movimientoZmb(Objeto[][] tablero, int i, int j, CasillaVacia casillaVacia) { //if () if (tablero[i][j - 1] instanceof CasillaVacia) { //siguiente casilla vacia tablero[i][j - 1] = tablero[i][j]; //avanza tablero[i][j] = casillaVacia; //la casilla anterior se queda vacía } else if (tablero[i][j - 1] instanceof Planta) { //siguiente casilla PlantaGirasol o PlantaLanzaGuisantes tablero[i][j - 1].setResistencia(tablero[i][j - 1].getResistencia() - tablero[i][j].getDanio()); //resistencia pg = resistencia pg - daño zmb if (tablero[i][j - 1].getResistencia() < 1) { //Planta muere tablero[i][j - 1] = casillaVacia; } } return tablero; } } <file_sep>/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package clases; /** * * @author laura */ public class PlantaNuez extends Planta{ //constructor public PlantaNuez(int coste, int resistencia, float frecuencia, int danio, int ciclo) { super(coste, resistencia, frecuencia, danio, ciclo); } /** * Crea objeto PlantaNuez * @return PlantaNuez */ public static PlantaNuez crearPlantaNuez(){ PlantaNuez pN = new PlantaNuez(50, 10, 0, 0, 0); //coste, resistencia, frecuencia, danio, ciclo return pN; } } <file_sep>package ETT; import java.util.*; public class GestionOfertas { private static ArrayList<OfertaEmpleo> ofertas = new ArrayList<>(); public GestionOfertas() { } public static ArrayList<OfertaEmpleo> getOfertas() { return ofertas; } public static void setOfertas(ArrayList<OfertaEmpleo> ofertas) { GestionOfertas.ofertas = ofertas; } //método para añadir ofertas public static String altaOfertas(OfertaEmpleo oferta) { try { if (ofertas.contains(oferta)) { throw new OfertasException(OfertasException.OFERTA_REPETIDA); } ofertas.add(oferta); return "Oferta dada de alta correctamente"; } catch (OfertasException pe) { return pe.getMessage(); } } //método búsqueda de ofertas que devuelve un arraylist con las oferta encontradas public static ArrayList<OfertaEmpleo> busquedaOfertas(String categoria, double salario) { ArrayList<OfertaEmpleo> ofertasBuscadas = new ArrayList<>(); for (OfertaEmpleo oe : ofertas) { if (oe.getCategoria().equals(categoria) && oe.getSalario() >= salario) { ofertasBuscadas.add(oe); } } return ofertasBuscadas; } } <file_sep>/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package ejerciciosPropuestos2; import java.util.Scanner; /** * * @author laura * * Programa que determine si un número es primo. Notas: Un número es primo si sólo es divisible por sí mismo y por 1. Si un número no es primo diremos que es compuesto. El 0 y el 1 son números especiales que no se consideran primos ni compuestos. * */ public class Primo8 { public static void main (String[] args){ Scanner entrada = new Scanner(System.in); int n; System.out.print("\nIntroduce un número: "); //lectura de un int n = entrada.nextInt(); if (n == 0 || n == 1){ System.out.println("\n" + n + " no es ni primo ni compuesto."); } else if (n == 2 || n == 3 || n == 5 || n == 7){ System.out.println("\n" + n + " es primo."); } else if (n % 2 == 0 || n % 3 == 0 || n % 5 == 0|| n % 7 == 0){ System.out.println("\n" + n + " es compuesto."); } else{ System.out.println("\n" + n + " es primo."); } } } <file_sep>package empleados; public class Persona { private String dni; private String nombre; private int edad; private String estado; //constructor public Persona(String dni, String nombre, int edad, String estado) { this.dni = dni; this.nombre = nombre; this.edad = edad; this.estado = estado; } public void cumpleaños() { edad++; } public String getDni() { return dni; } public String getNombre() { return nombre; } public int getEdad() { return edad; } public void setEdad(int edad) { this.edad = edad; } public String getEstado() { return estado; } public void setEstado(String estado) { this.estado = estado; } //información textual de la persona @Override public String toString() { return "Persona{" + "dni=" + dni + ", nombre=" + nombre + ", edad=" + edad + ", estado=" + estado + '}'; } } <file_sep>package cuentas; import java.time.LocalDate; public abstract class CuentaAbs { private String numcuenta; private String titular; private double saldo; private LocalDate fechaApertura; public CuentaAbs(String numcuenta, String titular, double saldo) { this.numcuenta = numcuenta; this.titular = titular; this.saldo = saldo; this.fechaApertura = LocalDate.now(); } public CuentaAbs(String numcuenta, String titular, double saldo, LocalDate fechaApertura) { this.numcuenta = numcuenta; this.titular = titular; this.saldo = saldo; this.fechaApertura = fechaApertura; } public abstract double calculaInteres(double saldo); public double getSaldo() { return saldo; } public void setSaldo(double saldo) { this.saldo = saldo; } public String getTitular() { return titular; } public void setTitular(String titular) { this.titular = titular; } public String getNumcuenta() { return numcuenta; } public void setNumcuenta(String numcuenta) { this.numcuenta = numcuenta; } } <file_sep>/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package clases; /** * * @author laura */ public class PlantaPetaCereza extends Planta { public PlantaPetaCereza(int coste, int resistencia, float frecuencia, int danio, int ciclo) { super(coste, resistencia, frecuencia, danio, ciclo); } /** * Crea objeto PlantaPetaCereza * * @return PlantaPetaCereza */ public static PlantaPetaCereza crearPlantaPetaCereza() { PlantaPetaCereza pPC = new PlantaPetaCereza(50, 2, 0, 10, 0); //ciclo == 2 --> explosión return pPC; } public static Objeto[][] petaLaCereza (Objeto[][] tablero, int filaPPC, int columnaPPC, int numFilas, int numColumnas, CasillaVacia casillaVacia){ if (filaPPC == 0){ //primera fila if (columnaPPC == 0) { //primera columna //(0,0) if (tablero[filaPPC][columnaPPC + 1] instanceof Zombie) { tablero[filaPPC][columnaPPC + 1].setResistencia(tablero[filaPPC][columnaPPC + 1].getResistencia() - tablero[filaPPC][columnaPPC].getDanio()); // (0,1) if (tablero[filaPPC][columnaPPC + 1].getResistencia() < 1){ tablero[filaPPC][columnaPPC + 1] = casillaVacia; } } if (tablero[filaPPC + 1][columnaPPC] instanceof Zombie) { tablero[filaPPC + 1][columnaPPC].setResistencia(tablero[filaPPC + 1][columnaPPC].getResistencia() - tablero[filaPPC][columnaPPC].getDanio()); // (1,0) if (tablero[filaPPC + 1][columnaPPC].getResistencia() < 1){ tablero[filaPPC + 1][columnaPPC] = casillaVacia; } } } else { //columnas por el medio //arriba por el medio (0, x) if (tablero[filaPPC][columnaPPC + 1] instanceof Zombie) { tablero[filaPPC][columnaPPC + 1].setResistencia(tablero[filaPPC][columnaPPC + 1].getResistencia() - tablero[filaPPC][columnaPPC].getDanio()); // (0, x + 1) if (tablero[filaPPC][columnaPPC + 1].getResistencia() < 1) { tablero[filaPPC][columnaPPC + 1] = casillaVacia; if (tablero[filaPPC][columnaPPC + 1].getResistencia() < 1) { tablero[filaPPC][columnaPPC + 1] = casillaVacia; } } } if (tablero[filaPPC][columnaPPC - 1] instanceof Zombie){ tablero[filaPPC][columnaPPC - 1].setResistencia(tablero[filaPPC][columnaPPC - 1].getResistencia() - tablero[filaPPC][columnaPPC].getDanio()); // (0, x - 1) if (tablero[filaPPC][columnaPPC - 1].getResistencia() < 1) { tablero[filaPPC][columnaPPC - 1] = casillaVacia; } } if (tablero[filaPPC + 1][columnaPPC] instanceof Zombie){ tablero[filaPPC + 1][columnaPPC].setResistencia(tablero[filaPPC + 1][columnaPPC].getResistencia() - tablero[filaPPC][columnaPPC].getDanio()); // (1, x) if (tablero[filaPPC + 1][columnaPPC].getResistencia() < 1){ tablero[filaPPC + 1][columnaPPC] = casillaVacia; } } } } else if (filaPPC == numFilas - 1) { //última fila if (columnaPPC == 0) { //primera columna //(n , 0) if (tablero[filaPPC][columnaPPC + 1] instanceof Zombie){ tablero[filaPPC][columnaPPC + 1].setResistencia(tablero[filaPPC][columnaPPC + 1].getResistencia() - tablero[filaPPC][columnaPPC].getDanio()); // (n,1) if (tablero[filaPPC][columnaPPC + 1].getResistencia() < 1) { tablero[filaPPC][columnaPPC + 1] = casillaVacia; } } if (tablero[filaPPC - 1][columnaPPC] instanceof Zombie){ tablero[filaPPC - 1][columnaPPC].setResistencia(tablero[filaPPC - 1][columnaPPC].getResistencia() - tablero[filaPPC][columnaPPC].getDanio()); //arriba (n - 1, 0) if (tablero[filaPPC - 1][columnaPPC].getResistencia() < 1){ tablero[filaPPC - 1][columnaPPC] = casillaVacia; } } } else { //columnas por el medio //abajo por el medio //(n - 1, x) if (tablero[filaPPC][columnaPPC + 1] instanceof Zombie) { tablero[filaPPC][columnaPPC + 1].setResistencia(tablero[filaPPC][columnaPPC + 1].getResistencia() - tablero[filaPPC][columnaPPC].getDanio()); // (n, x + 1) if (tablero[filaPPC][columnaPPC + 1].getResistencia() < 1) { tablero[filaPPC][columnaPPC + 1] = casillaVacia; } } if (tablero[filaPPC][columnaPPC - 1] instanceof Zombie){ tablero[filaPPC][columnaPPC - 1].setResistencia(tablero[filaPPC][columnaPPC - 1].getResistencia() - tablero[filaPPC][columnaPPC].getDanio()); // (n, x - 1) if (tablero[filaPPC][columnaPPC - 1].getResistencia() < 1) { tablero[filaPPC][columnaPPC - 1] = casillaVacia; } } if (tablero[filaPPC - 1][columnaPPC] instanceof Zombie){ tablero[filaPPC - 1][columnaPPC].setResistencia(tablero[filaPPC - 1][columnaPPC].getResistencia() - tablero[filaPPC][columnaPPC].getDanio()); // (n - 1, x) if (tablero[filaPPC - 1][columnaPPC].getResistencia() < 1){ tablero[filaPPC - 1][columnaPPC] = casillaVacia; } } } } else { //filas por el medio if (numColumnas == 0){ //primera columna (x, 0) if (tablero[filaPPC][columnaPPC + 1] instanceof Zombie) { tablero[filaPPC][columnaPPC + 1].setResistencia(tablero[filaPPC][columnaPPC + 1].getResistencia() - tablero[filaPPC][columnaPPC].getDanio()); // (x,1) if (tablero[filaPPC][columnaPPC + 1].getResistencia() < 1) { tablero[filaPPC][columnaPPC + 1] = casillaVacia; } } if (tablero[filaPPC + 1][columnaPPC] instanceof Zombie) { tablero[filaPPC + 1][columnaPPC].setResistencia(tablero[filaPPC + 1][columnaPPC].getResistencia() - tablero[filaPPC][columnaPPC].getDanio()); // (x + 1, 0) if (tablero[filaPPC + 1][columnaPPC].getResistencia() < 1){ tablero[filaPPC + 1][columnaPPC] = casillaVacia; } } if (tablero[filaPPC - 1][columnaPPC] instanceof Zombie){ tablero[filaPPC - 1][columnaPPC].setResistencia(tablero[filaPPC - 1][columnaPPC].getResistencia() - tablero[filaPPC][columnaPPC].getDanio()); // (x - 1, 0) if (tablero[filaPPC - 1][columnaPPC].getResistencia() < 1){ tablero[filaPPC - 1][columnaPPC] = casillaVacia; } } } else { if (tablero[filaPPC][columnaPPC + 1] instanceof Zombie) { tablero[filaPPC][columnaPPC + 1].setResistencia(tablero[filaPPC][columnaPPC + 1].getResistencia() - tablero[filaPPC][columnaPPC].getDanio()); // (x, x + 1) if (tablero[filaPPC][columnaPPC + 1].getResistencia() < 1) { tablero[filaPPC][columnaPPC + 1] = casillaVacia; } } if (tablero[filaPPC + 1][columnaPPC] instanceof Zombie) { tablero[filaPPC + 1][columnaPPC].setResistencia(tablero[filaPPC + 1][columnaPPC].getResistencia() - tablero[filaPPC][columnaPPC].getDanio()); // (x + 1, x) if (tablero[filaPPC + 1][columnaPPC].getResistencia() < 1){ tablero[filaPPC + 1][columnaPPC] = casillaVacia; } } if (tablero[filaPPC - 1][columnaPPC] instanceof Zombie){ tablero[filaPPC - 1][columnaPPC].setResistencia(tablero[filaPPC - 1][columnaPPC].getResistencia() - tablero[filaPPC][columnaPPC].getDanio()); // (x - 1, x) if (tablero[filaPPC - 1][columnaPPC].getResistencia() < 1){ tablero[filaPPC - 1][columnaPPC] = casillaVacia; } } if (tablero[filaPPC][columnaPPC - 1] instanceof Zombie){ tablero[filaPPC][columnaPPC - 1].setResistencia(tablero[filaPPC][columnaPPC - 1].getResistencia() - tablero[filaPPC][columnaPPC].getDanio()); // (x, x - 1) if (tablero[filaPPC][columnaPPC - 1].getResistencia() < 1) { tablero[filaPPC][columnaPPC - 1] = casillaVacia; } } } } tablero[filaPPC][columnaPPC] = casillaVacia; return tablero; } } <file_sep>/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package clases; /** * * @author laura */ public class ZombieDeportista extends Zombie{ //constructor public ZombieDeportista(int coste, int resistencia, int danio, int ciclo, int velocidad) { super(coste, resistencia, danio, ciclo, velocidad); } /** * Crea un objeto ZombieComun * * Deportista: es más rápido, pero menos resistente. Camina un paso cada ciclo y tiene resistencia 2 puntos de vida. * * @return ZombieComun */ public static ZombieDeportista crearZombieDeportista() { ZombieDeportista zmbD= new ZombieDeportista(0, 2, 1, 1, 0); //resistencia, danio, ciclo, velocidad return zmbD; } } <file_sep>/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package media; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; /** * * @author laura * *Calcula la nota media de los exámenes de un grupo de alumnos Utilización del bucle while y sentencias condicionales */ public class MediaElif { public static void main( String args[] ) throws IOException { int contador, total, media; String nota; //Objeto para leer una cadena del teclado BufferedReader entrada = new BufferedReader(new InputStreamReader(System.in)); // inicialización de variables total = 0; contador = 1; while ( contador <= 5 ) { System.out.println( "\nTeclee calificación (A,B,C,D,E): " ); nota = entrada.readLine(); if (nota.equals("A")) { total = total + 4; } else if (nota.equals("B")) { total = total + 3; } else if (nota.equals("C")) { total = total + 2; } else if (nota.equals("D")) { total = total + 1; } else if (nota.equals("E")) { total = total + 0; } contador = contador + 1; } media = total / 5; System.out.println("\n\nEl promedio del grupo es: " + media); } }
879e18003ad14b0fd5a85ad515a0fed2c991f3f8
[ "Java" ]
72
Java
lauram15a/Programacion
40406207b7ec0bc00d18dc8850dcdd15da436af2
16ec5d19d88f6cd4a0bfdddbfd2e7eea02e27938
refs/heads/master
<repo_name>kofonfor/ansible-role-prometheus-node-exporter<file_sep>/templates/sudo_megacli.sh #!/bin/sh sudo {{ node_exporter_collector_megacli_command }} $*
ced2426159e8b401167e1a3614989bc1345184c5
[ "Shell" ]
1
Shell
kofonfor/ansible-role-prometheus-node-exporter
87c1eee6609bfe1f63e9b8bc169365aa5f6c40ee
8f1828e5604c27ff305726fe80cb1e3d7657bfe9
refs/heads/main
<file_sep>from fastapi import APIRouter from app.api.api_v1.endpoints import kanji, compound_word, example_sentence, kanji_dict api_router = APIRouter() api_router.include_router(kanji.router, prefix="/kanjis", tags=["kanjis"]) api_router.include_router(compound_word.router, prefix="/compound-words", tags=["compound words"]) api_router.include_router(example_sentence.router, prefix="/example-sentences", tags=["example sentences"]) api_router.include_router(kanji_dict.router, prefix="/kanji-dictionaries", tags=["kanji dictionaries"])<file_sep>from typing import Optional, List from app.models.rwmodel import RWModel, ObjectIdStr class ExampleSentenceFilterParams(RWModel): related_kanji: List[str] = [] ratings: List[int] = [] offset: int = 0 limit: int = 0 class ExampleSentenceBase(RWModel): example_sentence: Optional[str] = None hiragana: Optional[str] = None translation: Optional[str] = None rating: Optional[int] = 0 related_kanji: Optional[List[str]] class ExampleSentenceCreate(ExampleSentenceBase): example_sentence: str hiragana: str translation: str class ExampleSentenceUpdate(ExampleSentenceBase): pass class ExampleSentenceInDbBase(ExampleSentenceBase): doc_id: Optional[ObjectIdStr] = None example_sentence: str hiragana: str translation: str class ExampleSentenceInDb(ExampleSentenceInDbBase): pass<file_sep># Kanji Dictionary Editor A backend API for editing kanji dictionary data for the jouyou kanji project. This project uses FastAPI for the REST API, and stores data in a Mongo database. ## Setup Install python dependencies: ```bash pip install -r requirements.txt ``` This API requires a running mongo database to work. ## Running the App There are some required environment variables that have to be set before starting the backend API: ```bash PROJECT_NAME=kanji_manager FIRST_SUPERUSER=<EMAIL> FIRST_SUPERUSER_PASSWORD=pw ``` Then the backend can be started using the following command: ```bash uvicorn app.main:app --reload --log-level 'debug' ``` or just use the `Makefile` and the make command, which sets the variables for local testing purposes: ```bash make app-start ``` <file_sep>from unittest import mock import pytest from app import models from app.services.kanji_dict_service import import_kanji_dict @pytest.fixture def kanji_dict_data(): return { "jouyou_number": 1, "kanji": "亜", "kanji_section": "あ", "radical": "二", "strokes": 7, "jlpt_level": "1", "frequency_rank": 1509, "onyomi": ["ア"], "kunyomi": [""], "meaning": ["-sub", "asia"], "compound_words": [ {"compound_word": "亜鉛", "hiragana": "あ,えん", "translation": "zinc", "related_kanji": ["亜", "鉛"]} ], } @pytest.mark.asyncio async def test_import_kanji_dict(kanji_dict_data): mock_motor_client = mock.MagicMock() kanjiDict = models.KanjiDict(**kanji_dict_data) result = await import_kanji_dict(mock_motor_client, kanjiDict) <file_sep>from typing import Optional, List, Any from fastapi import APIRouter, Body, Depends, Path, Query, HTTPException, Response from loguru import logger from starlette.status import ( HTTP_201_CREATED, HTTP_204_NO_CONTENT, HTTP_400_BAD_REQUEST, HTTP_404_NOT_FOUND, HTTP_422_UNPROCESSABLE_ENTITY, ) from motor.motor_asyncio import AsyncIOMotorClient from app import models from app.services import example_sentence_service from app.db.mongodb import get_database router = APIRouter() @router.get("/", response_model=List[models.ExampleSentenceInDb]) async def get_example_sentence_items( *, db: AsyncIOMotorClient = Depends(get_database), related_kanji: Optional[List[str]] = Query(None), ratings: Optional[List[int]] = Query(None), offset: Optional[int] = Query(0), limit: Optional[int] = Query(100), ): """ Get a list of all example_sentences in the database. """ logger.debug(">>>>") filters = models.ExampleSentenceFilterParams() if related_kanji: filters.related_kanji = related_kanji if ratings: filters.ratings = ratings filters.offset = offset filters.limit = limit example_sentences = await example_sentence_service.get_example_sentences(db, filters) return example_sentences @router.get("/{doc_id}", response_model=models.ExampleSentenceInDb) async def get_example_sentence_by_id(*, db: AsyncIOMotorClient = Depends(get_database), doc_id: str) -> Any: """ Get a single example_sentence document using the example_sentence as a lookup. """ example_sentence_result = await example_sentence_service.get_example_sentence_doc_by_id(db, doc_id) if not example_sentence_result: raise HTTPException(status_code=HTTP_404_NOT_FOUND, detail="Example sentence not found") return example_sentence_result @router.post("/", response_model=models.ExampleSentenceInDb, status_code=HTTP_201_CREATED) async def create_new_example_sentence( *, example_sentence: models.ExampleSentenceCreate, db: AsyncIOMotorClient = Depends(get_database) ): """ Create a new example_sentence document. """ logger.debug(">>>>") example_sentence_by_example_sentence = ( await example_sentence_service.get_example_sentence_doc_by_example_sentence( db, example_sentence.example_sentence ) ) if example_sentence_by_example_sentence: raise HTTPException( status_code=HTTP_422_UNPROCESSABLE_ENTITY, detail=f"Example sentence '{example_sentence.example_sentence}' already exists.", ) db_example_sentence = await example_sentence_service.create_example_sentence(db, example_sentence) return db_example_sentence @router.delete("/{doc_id}", status_code=HTTP_204_NO_CONTENT) async def delete_example_sentence_by_id(*, db: AsyncIOMotorClient = Depends(get_database), doc_id: str): """ Delete a single example_sentence document using the example_sentence as a lookup. """ example_sentence_by_example_sentence = await example_sentence_service.get_example_sentence_doc_by_id( db, doc_id ) if not example_sentence_by_example_sentence: raise HTTPException(status_code=HTTP_404_NOT_FOUND, detail=f"Example sentence '{doc_id}' not found.") await example_sentence_service.delete_example_sentence_doc_by_id(db, doc_id) return Response(status_code=HTTP_204_NO_CONTENT) @router.put("/{doc_id}", response_model=models.ExampleSentenceInDb) async def update_example_sentence( *, db: AsyncIOMotorClient = Depends(get_database), doc_id: str, exampleSentenceUpdate: models.ExampleSentenceUpdate, ): """ Update a single example_sentence document using the example_sentence as a lookup. Partial update is supported. """ example_sentence = await example_sentence_service.get_example_sentence_doc_by_id(db, doc_id) if not example_sentence: raise HTTPException(status_code=HTTP_404_NOT_FOUND, detail=f"Example sentence '{doc_id}' not found.") updated_example_sentence = await example_sentence_service.update_example_sentence_doc_by_id( db, doc_id, exampleSentenceUpdate ) return updated_example_sentence <file_sep>from app.models.kanji import KanjiUpdate from typing import Optional, List, Any from fastapi import APIRouter, Body, Depends, Path, Query, HTTPException, Response from loguru import logger from starlette.status import ( HTTP_201_CREATED, HTTP_204_NO_CONTENT, HTTP_400_BAD_REQUEST, HTTP_404_NOT_FOUND, HTTP_422_UNPROCESSABLE_ENTITY, ) from motor.motor_asyncio import AsyncIOMotorClient from app import models from app.services import kanji_service from app.db.mongodb import get_database router = APIRouter() @router.get("/", response_model=List[models.KanjiInDb]) async def get_kanji_items( *, db: AsyncIOMotorClient = Depends(get_database), offset: Optional[int] = Query(0), limit: Optional[int] = Query(100), ): """ Get a list of all kanji in the database. """ logger.debug(">>>>") kanjis = await kanji_service.get_kanji(db, offset=offset, limit=limit) return kanjis @router.get("/{doc_id}", response_model=models.KanjiInDb) async def get_kanji_by_doc_id(*, db: AsyncIOMotorClient = Depends(get_database), doc_id: str) -> Any: """ Get a single kanji document using the kanji as a lookup. """ kanji_result = await kanji_service.get_kanji_doc_by_id(db, doc_id) if not kanji_result: raise HTTPException(status_code=HTTP_404_NOT_FOUND, detail="Kanji not found") return kanji_result @router.post("/", response_model=models.KanjiInDb, status_code=HTTP_201_CREATED) async def create_new_kanji(*, kanji: models.KanjiCreate, db: AsyncIOMotorClient = Depends(get_database)): """ Create a new kanji document. """ logger.debug(">>>>") kanji_by_kanji = await kanji_service.get_kanji_doc_by_kanji(db, kanji.kanji) if kanji_by_kanji: raise HTTPException( status_code=HTTP_422_UNPROCESSABLE_ENTITY, detail=f"Kanji '{kanji.kanji}' already exists." ) db_kanji = await kanji_service.create_kanji(db, kanji) return db_kanji @router.delete("/{doc_id}", status_code=HTTP_204_NO_CONTENT) async def delete_kanji(*, db: AsyncIOMotorClient = Depends(get_database), doc_id: str): """ Delete a single kanji document using the doc_id as a lookup. """ kanji_by_kanji = await kanji_service.get_kanji_doc_by_id(db, doc_id) if not kanji_by_kanji: logger.info("Kanji not found.") raise HTTPException(status_code=HTTP_404_NOT_FOUND, detail=f"Kanji '{doc_id}' not found.") await kanji_service.delete_kanji_doc_by_id(db, doc_id) return Response(status_code=HTTP_204_NO_CONTENT) @router.put("/{doc_id}", response_model=models.KanjiInDb) async def update_kanji( *, db: AsyncIOMotorClient = Depends(get_database), doc_id: str, kanjiUpdate: KanjiUpdate ): """ Update a single kanji document using the doc_id as a lookup. Partial update is supported. """ kanji_by_kanji = await kanji_service.get_kanji_doc_by_id(db, doc_id) if not kanji_by_kanji: raise HTTPException(status_code=HTTP_404_NOT_FOUND, detail=f"Kanji '{doc_id}' not found.") updated_kanji = await kanji_service.update_kanji_doc_by_id(db, doc_id, kanjiUpdate) return updated_kanji <file_sep>import json from typing import List from bson import ObjectId from datetime import datetime from loguru import logger from motor.motor_asyncio import AsyncIOMotorClient from pydantic.utils import Obj from app.core.config import settings from app import models async def create_example_sentence( connection: AsyncIOMotorClient, example_sentence: models.ExampleSentenceCreate ) -> models.ExampleSentenceInDb: """ Create a new example_sentence document. :param connection: Async database client. :param example_sentence: The example_sentence document to insert into the database. :return: Returns example_sentence document as it is in the database. """ logger.debug(">>>>") example_sentence_doc = example_sentence.dict() logger.info( f"Creating example_sentence doc: {json.dumps(example_sentence_doc, indent=2, ensure_ascii=False)}" ) example_sentence_doc["updated_at"] = datetime.utcnow() result = await connection[settings.MONGO_DB][settings.MONGO_EXAMPLE_SENTENCE_COLLECTION].insert_one( example_sentence_doc ) example_sentence_in_db = models.ExampleSentenceInDb(**example_sentence_doc) example_sentence_in_db.doc_id = result.inserted_id return example_sentence_in_db async def get_example_sentence_doc_by_example_sentence( connection: AsyncIOMotorClient, example_sentence: str ) -> models.ExampleSentenceInDb: """ Retrieve a single example_sentence document. :param connection: Async database client. :param example_sentence: The unique example_sentence to use to retrieve the example_sentence document from the database. :return: Returns example_sentence document as it is in the database. """ logger.debug(">>>>") logger.info(f"Retrieving example_sentence data for {example_sentence}...") example_sentence_doc = await connection[settings.MONGO_DB][ settings.MONGO_EXAMPLE_SENTENCE_COLLECTION ].find_one({"example_sentence": example_sentence}) if example_sentence_doc: example_sentence_in_db = models.ExampleSentenceInDb(**example_sentence_doc) example_sentence_in_db.doc_id = example_sentence_doc.get("_id") return example_sentence_in_db async def get_example_sentence_doc_by_id( connection: AsyncIOMotorClient, doc_id: str ) -> models.ExampleSentenceInDb: """ Retrieve a single example_sentence document. :param connection: Async database client. :param doc_id: The unique doc_id to use to retrieve the example_sentence document from the database. :return: Returns example_sentence document as it is in the database. """ logger.debug(">>>>") logger.info(f"Retrieving example_sentence data for {doc_id}...") example_sentence_doc = await connection[settings.MONGO_DB][ settings.MONGO_EXAMPLE_SENTENCE_COLLECTION ].find_one({"_id": ObjectId(doc_id)}) if example_sentence_doc: if "doc_id" in example_sentence_doc: del example_sentence_doc["doc_id"] example_sentence_in_db = models.ExampleSentenceInDb(**example_sentence_doc) example_sentence_in_db.doc_id = example_sentence_doc.get("_id") return example_sentence_in_db async def get_example_sentences( connection: AsyncIOMotorClient, filters: models.ExampleSentenceFilterParams = models.ExampleSentenceFilterParams(), ) -> List[models.ExampleSentenceInDb]: """ Get all example_sentence documents in the database. :param connection: Async database client. :param filters: ExampleSentenceFilterParams instance containing values to filter on. If no filter values are set, then all example sentences will be returned. :return: Returns all example_sentence documents as a list. """ logger.debug(">>>>") query = {} if filters.related_kanji: query["related_kanji"] = {"$in": filters.related_kanji} if filters.ratings: query["rating"] = {"$in": filters.ratings} if query: results = connection[settings.MONGO_DB][settings.MONGO_EXAMPLE_SENTENCE_COLLECTION].find( query, skip=filters.offset, limit=filters.limit ) else: results = connection[settings.MONGO_DB][settings.MONGO_EXAMPLE_SENTENCE_COLLECTION].find( skip=filters.offset, limit=filters.limit ) example_sentence_results = [] async for result in results: if "doc_id" in result: del result["doc_id"] example_sentence_in_db = models.ExampleSentenceInDb(**result) example_sentence_in_db.doc_id = result.get("_id") example_sentence_results.append(example_sentence_in_db) logger.info(f"Retrieved {len(example_sentence_results)} example_sentence.") return example_sentence_results async def delete_example_sentence_doc_by_example_sentence( connection: AsyncIOMotorClient, example_sentence: str ) -> None: """ Delete example_sentence documents by example_sentence. All matching documents will be deleted. :param connection: Database connection object. :param example_sentence: The unique example_sentence to delete documents by. """ logger.info(f"Deleting example_sentence '{example_sentence}'...") await connection[settings.MONGO_DB][settings.MONGO_EXAMPLE_SENTENCE_COLLECTION].delete_many( {"example_sentence": example_sentence} ) logger.info(f"Deleted example_sentence '{example_sentence}'.") async def delete_example_sentence_doc_by_id(connection: AsyncIOMotorClient, doc_id: str) -> None: """ Delete example_sentence documents by example_sentence. All matching documents will be deleted. :param connection: Database connection object. :param doc_id: The unique doc_id to delete documents by. """ logger.info(f"Deleting example_sentence '{doc_id}'...") await connection[settings.MONGO_DB][settings.MONGO_EXAMPLE_SENTENCE_COLLECTION].delete_many( {"_id": ObjectId(doc_id)} ) logger.info(f"Deleted example_sentence '{doc_id}'.") async def update_example_sentence_doc_by_id( connection: AsyncIOMotorClient, doc_id: str, exampleSentenceUpdate: models.ExampleSentenceUpdate ) -> models.ExampleSentenceInDb: """ Update a single example_sentence by example_sentence. Supports partial update. Only attributes set on the ExampleSentenceUpdate object will be updated. :param connection: Async database client. :param doc_id: The unique doc_id to update a document by. :param exampleSentenceUpdate: ExampleSentenceUpdate instance with updated values. :return: Returns example_sentence document as it is in the database. """ logger.debug(">>>>") db_example_sentence = await get_example_sentence_doc_by_id(connection, doc_id) if exampleSentenceUpdate.example_sentence: db_example_sentence.example_sentence = exampleSentenceUpdate.example_sentence if exampleSentenceUpdate.hiragana: db_example_sentence.hiragana = exampleSentenceUpdate.hiragana if exampleSentenceUpdate.translation: db_example_sentence.translation = exampleSentenceUpdate.translation if exampleSentenceUpdate.related_kanji: db_example_sentence.related_kanji = exampleSentenceUpdate.related_kanji if exampleSentenceUpdate.rating: db_example_sentence.rating = exampleSentenceUpdate.rating updated_doc = db_example_sentence.dict() updated_doc["doc_id"] = str(updated_doc["doc_id"]) logger.info( f"Updating example_sentence {doc_id} with: {json.dumps(updated_doc, indent=2, ensure_ascii=False)}" ) await connection[settings.MONGO_DB][settings.MONGO_EXAMPLE_SENTENCE_COLLECTION].replace_one( {"_id": ObjectId(doc_id)}, updated_doc ) return db_example_sentence <file_sep>import shutil from fastapi.datastructures import UploadFile from app.models import example_sentence, kanji import json from typing import List from datetime import datetime from bson import ObjectId from pathlib import Path from loguru import logger from motor.motor_asyncio import AsyncIOMotorClient from app.core.config import settings from app import models from app.services import kanji_service, compound_word_service, example_sentence_service async def import_kanji_dict(connection: AsyncIOMotorClient, kanjiDict: models.KanjiDict) -> models.KanjiDict: """ Create new kanji, compound word, and example sentences based on kanji dict data. Will also update compound word and example sentences related kanji arrays when needed. :param connection: Async database client. :param kanjiDictList: A list of KanjiDict instances to import. """ logger.debug(">>>>") kanji_dict_doc = kanjiDict.dict(exclude_unset=True) kanji = kanji_dict_doc.get("kanji") existing_kanji = await kanji_service.get_kanji_doc_by_kanji(connection, kanji) if existing_kanji: logger.info(f"Kanji {kanji} already exists, updating.") kanji_update = models.KanjiUpdate(**kanji_dict_doc) await kanji_service.update_kanji_doc_by_id(connection, str(existing_kanji.doc_id), kanji_update) else: logger.info(f"Kanji {kanji} does not exist, creating.") kanji_create = models.KanjiCreate(**kanji_dict_doc) await kanji_service.create_kanji(connection, kanji_create) compound_words_data = kanji_dict_doc.get("compound_words") if compound_words_data: for compound_word_item in compound_words_data: compound_word = compound_word_item.get("compound_word") existing_compound_word = await compound_word_service.get_compound_word_doc_by_compound_word( connection, compound_word ) if existing_compound_word: logger.info(f"Compound word: {compound_word} already exists") # Update associated kanji only? compound_word_update = models.CompoundWordUpdate(**existing_compound_word.dict()) if compound_word_update.related_kanji and not kanji in compound_word_update.related_kanji: compound_word_update.related_kanji.append(kanji) await compound_word_service.update_compound_word_doc_by_id( connection, existing_compound_word.doc_id, compound_word_update ) else: compound_word_create = models.CompoundWordCreate(**compound_word_item) compound_word_create.related_kanji = [kanji] await compound_word_service.create_compound_word(connection, compound_word_create) example_sentences_data = kanji_dict_doc.get("example_sentences") if example_sentences_data: for example_sentence_item in example_sentences_data: example_sentence = example_sentence_item.get("compound_word") existing_example_sentence = ( await example_sentence_service.get_example_sentence_doc_by_example_sentence( connection, example_sentence ) ) if existing_example_sentence: logger.info(f"Example sentence: {example_sentence} already exists") # Update associated kanji only? example_sentence_update = models.ExampleSentenceUpdate(**existing_example_sentence.dict()) if ( example_sentence_update.related_kanji and not kanji in example_sentence_update.related_kanji ): example_sentence_update.related_kanji.append(kanji) await example_sentence_service.update_example_sentence_doc_by_id( connection, existing_example_sentence.doc_id, example_sentence_update ) else: example_sentence_create = models.ExampleSentenceCreate(**example_sentence_item) example_sentence_create.related_kanji = [kanji] await example_sentence_service.create_example_sentence(connection, example_sentence_create) async def import_kanji_dict_list( connection: AsyncIOMotorClient, kanjiDictList: List[models.KanjiDict], replace_all: bool = True ) -> List[models.KanjiDict]: """ Create new kanji, compound word, and example sentences based on kanji dict data in bulk from a list. :param connection: Async database client. :param kanjiDictList: A list of KanjiDict instances to import. :param replace_all: Flag that determines if all documents in all collections should be deleted first. """ if replace_all: await connection[settings.MONGO_DB][settings.MONGO_KANJI_COLLECTION].drop() await connection[settings.MONGO_DB][settings.MONGO_COMPOUND_WORD_COLLECTION].drop() await connection[settings.MONGO_DB][settings.MONGO_EXAMPLE_SENTENCE_COLLECTION].drop() imported_kanji_dicts = [] for kanjiDict in kanjiDictList: result = await import_kanji_dict(connection, kanjiDict) if result: imported_kanji_dicts.append(result) def populate_lookup(lookup, data_items, items_key): for data_item in data_items: # data_item.doc_id = str(data_item.doc_id) for related_kanji in data_item.related_kanji: lookup_item = lookup.get(related_kanji) if not lookup_item: lookup_item = {"compound_words": [], "example_sentences": []} lookup[related_kanji] = lookup_item lookup_item[items_key].append(data_item) async def get_kanji_dicts(connection: AsyncIOMotorClient) -> List[models.KanjiDict]: """ Retrieve list of KanjiDict matching query. Combines kanji, related compound words, and related example sentences into one dicitonary object. And returns all kanji dictionaries as a list. :param connection: Async database client. """ kanjis = await kanji_service.get_all_kanji(connection) compound_words = await compound_word_service.get_compound_words(connection) example_sentences = await example_sentence_service.get_example_sentences(connection) lookup = {} populate_lookup(lookup, compound_words, "compound_words") populate_lookup(lookup, example_sentences, "example_sentences") kanji_dicts = [] for kanji_item in kanjis: looked_up_item = lookup.get(kanji_item.kanji) kanji_dict = models.KanjiDict(**kanji_item.dict()) kanji_dict.doc_id = ObjectId(kanji_dict.doc_id) if not looked_up_item: continue kanji_dict.compound_words = looked_up_item["compound_words"] kanji_dict.example_sentences = looked_up_item["example_sentences"] kanji_dicts.append(kanji_dict) return kanji_dicts async def process_file_upload(connection, upload_file: UploadFile) -> None: logger.debug(">>>>") try: kanji_json = json.load(upload_file.file) logger.info(f"Kanji dict file contains {len(kanji_json)} kanji.") kanji_dict_list = [] for kanji_dict in kanji_json: kanji_dict_converted = models.KanjiDict(**kanji_dict) kanji_dict_list.append(kanji_dict_converted) result = await import_kanji_dict_list(connection, kanji_dict_list) finally: upload_file.file.close()<file_sep>import secrets from typing import Any, Dict, List, Optional, Union from pydantic import AnyHttpUrl, BaseSettings, HttpUrl, validator, EmailStr class Settings(BaseSettings): API_V1_STR: str = "/api/v1" SECRET_KEY: str = secrets.token_urlsafe(32) ACCESS_TOKEN_EXPIRE_MINUTES: int = 60 * 24 * 8 BACKEND_CORS_ORIGINS: List[AnyHttpUrl] = ["http://localhost:8080"] @validator("BACKEND_CORS_ORIGINS", pre=True) def assemble_cors_origins(cls, v: Union[str, List[str]]) -> Union[List[str], str]: if isinstance(v, str) and not v.startswith("["): return [i.strip() for i in v.split(",")] elif isinstance(v, (list, str)): return v raise ValueError(v) PROJECT_NAME: str MONGO_HOST: Optional[str] = "localhost" MONGO_PORT: Optional[int] = 27017 MONGO_USER: Optional[str] = None MONGO_PASSOWRD: Optional[str] = None MONGO_DB: Optional[str] = "common_kanji" MONGO_KANJI_COLLECTION = "kanji" MONGO_COMPOUND_WORD_COLLECTION = "kanji_compound_word" MONGO_EXAMPLE_SENTENCE_COLLECTION = "kanji_example_sentence" FIRST_SUPERUSER: EmailStr FIRST_SUPERUSER_PASSWORD: str class Config: case_sensitive = True settings = Settings()<file_sep>import json from typing import List from bson import ObjectId from datetime import datetime from loguru import logger from motor.motor_asyncio import AsyncIOMotorClient from pydantic.utils import Obj from app.core.config import settings from app import models async def create_compound_word( connection: AsyncIOMotorClient, compound_word: models.CompoundWordCreate ) -> models.CompoundWordInDb: """ Create a new compound_word document. :param connection: Async database client. :param compound_word: The compound_word document to insert into the database. :return: Returns compound_word document as it is in the database. """ logger.debug(">>>>") compound_word_doc = compound_word.dict() logger.info(f"Creating compound_word doc: {json.dumps(compound_word_doc, indent=2, ensure_ascii=False)}") compound_word_doc["updated_at"] = datetime.utcnow() result = await connection[settings.MONGO_DB][settings.MONGO_COMPOUND_WORD_COLLECTION].insert_one( compound_word_doc ) compound_word_in_db = models.CompoundWordInDb(**compound_word_doc) compound_word_in_db.doc_id = result.inserted_id return compound_word_in_db async def get_compound_word_doc_by_compound_word( connection: AsyncIOMotorClient, compound_word: str ) -> models.CompoundWordInDb: """ Retrieve a single compound_word document. :param connection: Async database client. :param compound_word: The unique compound_word to use to retrieve the compound_word document from the database. :return: Returns compound_word document as it is in the database. """ logger.debug(">>>>") logger.info(f"Retrieving compound_word data for {compound_word}...") compound_word_doc = await connection[settings.MONGO_DB][settings.MONGO_COMPOUND_WORD_COLLECTION].find_one( {"compound_word": compound_word} ) if compound_word_doc: compound_word_in_db = models.CompoundWordInDb(**compound_word_doc) compound_word_in_db.doc_id = compound_word_doc.get("_id") return compound_word_in_db async def get_compound_word_doc_by_id(connection: AsyncIOMotorClient, doc_id: str) -> models.CompoundWordInDb: """ Retrieve a single compound_word document. :param connection: Async database client. :param doc_id: The unique doc_id to use to retrieve the compound_word document from the database. :return: Returns compound_word document as it is in the database. """ logger.debug(">>>>") logger.info(f"Retrieving compound_word data for {doc_id}...") compound_word_doc = await connection[settings.MONGO_DB][settings.MONGO_COMPOUND_WORD_COLLECTION].find_one( {"_id": ObjectId(doc_id)} ) if compound_word_doc: if "doc_id" in compound_word_doc: del compound_word_doc["doc_id"] compound_word_in_db = models.CompoundWordInDb(**compound_word_doc) compound_word_in_db.doc_id = compound_word_doc.get("_id") return compound_word_in_db async def get_compound_words( connection: AsyncIOMotorClient, filters: models.CompoundWordFilterParams = models.CompoundWordFilterParams(), ) -> List[models.CompoundWordInDb]: """ Get all compound_word documents in the database. :param connection: Async database client. :param filters: CompoundWordFilterParams instance containing values to filter on. If no filter values are set, then all compound words will be returned. :return: Returns all compound_word documents as a list. """ logger.debug(">>>>") query = {} if filters.related_kanji: query["related_kanji"] = {"$in": filters.related_kanji} if filters.ratings: query["rating"] = {"$in": filters.ratings} if query: results = connection[settings.MONGO_DB][settings.MONGO_COMPOUND_WORD_COLLECTION].find( query, skip=filters.offset, limit=filters.limit ) else: results = connection[settings.MONGO_DB][settings.MONGO_COMPOUND_WORD_COLLECTION].find( skip=filters.offset, limit=filters.limit ) compound_word_results = [] async for result in results: if "doc_id" in result: del result["doc_id"] compound_word_in_db = models.CompoundWordInDb(**result) compound_word_in_db.doc_id = result.get("_id") compound_word_results.append(compound_word_in_db) logger.info(f"Retrieved {len(compound_word_results)} compound_word.") return compound_word_results async def delete_compound_word_doc_by_compound_word( connection: AsyncIOMotorClient, compound_word: str ) -> None: """ Delete compound_word documents by compound_word. All matching documents will be deleted. :param connection: Database connection object. :param compound_word: The unique compound_word to delete documents by. """ logger.info(f"Deleting compound_word '{compound_word}'...") await connection[settings.MONGO_DB][settings.MONGO_COMPOUND_WORD_COLLECTION].delete_many( {"compound_word": compound_word} ) logger.info(f"Deleted compound_word '{compound_word}'.") async def delete_compound_word_doc_by_id(connection: AsyncIOMotorClient, doc_id: str) -> None: """ Delete compound_word documents by compound_word. All matching documents will be deleted. :param connection: Database connection object. :param doc_id: The unique doc_id to delete documents by. """ logger.info(f"Deleting compound_word '{doc_id}'...") await connection[settings.MONGO_DB][settings.MONGO_COMPOUND_WORD_COLLECTION].delete_many( {"_id": ObjectId(doc_id)} ) logger.info(f"Deleted compound_word '{doc_id}'.") async def update_compound_word_doc_by_id( connection: AsyncIOMotorClient, doc_id: str, compoundWordUpdate: models.CompoundWordUpdate ) -> models.CompoundWordInDb: """ Update a single compound_word by compound_word. Supports partial update. Only attributes set on the CompoundWordUpdate object will be updated. :param connection: Async database client. :param doc_id: The unique doc_id to update a document by. :param compoundWordUpdate: CompoundWordUpdate instance with updated values. :return: Returns compound_word document as it is in the database. """ logger.debug(">>>>") db_compound_word = await get_compound_word_doc_by_id(connection, doc_id) if compoundWordUpdate.compound_word: db_compound_word.compound_word = compoundWordUpdate.compound_word if compoundWordUpdate.hiragana: db_compound_word.hiragana = compoundWordUpdate.hiragana if compoundWordUpdate.translation: db_compound_word.translation = compoundWordUpdate.translation if compoundWordUpdate.related_kanji: db_compound_word.related_kanji = compoundWordUpdate.related_kanji if compoundWordUpdate.rating: db_compound_word.rating = compoundWordUpdate.rating updated_doc = db_compound_word.dict() updated_doc["doc_id"] = str(updated_doc["doc_id"]) logger.info( f"Updating compound_word {doc_id} with: {json.dumps(updated_doc, indent=2, ensure_ascii=False)}" ) await connection[settings.MONGO_DB][settings.MONGO_COMPOUND_WORD_COLLECTION].replace_one( {"_id": ObjectId(doc_id)}, updated_doc ) return db_compound_word <file_sep>from loguru import logger from motor.motor_asyncio import AsyncIOMotorClient from app.core.config import settings from app.db.mongodb import db async def connect_to_mongo(): """ Establish mongodb connection. """ logger.debug(">>>>") logger.info("Connecting to mongodb...") credentials = "" if settings.MONGO_USER: credentials = f"{settings.MONGO_USER}:{settings.MONGO_PASSWORD}@" connection_string = ( f"mongodb://{credentials}{settings.MONGO_HOST}:{settings.MONGO_PORT}/{settings.MONGO_DB}" ) logger.debug(f"Connection string: {connection_string}") db.client = AsyncIOMotorClient(connection_string) logger.info("Mongodb connection established.") async def close_mongo_connection(): """ Close mongodb connection. """ logger.debug(">>>>") logger.info("Closing mongo connection...") db.client.close() logger.info("Closed mongo connection.")<file_sep>from typing import Optional, List from app.models.rwmodel import RWModel, ObjectIdStr class CompoundWordFilterParams(RWModel): related_kanji: List[str] = [] ratings: List[int] = [] offset: int = 0 limit: int = 0 class CompoundWordBase(RWModel): compound_word: Optional[str] = None hiragana: Optional[str] = None translation: Optional[str] = None rating: Optional[int] = 0 related_kanji: Optional[List[str]] class CompoundWordCreate(CompoundWordBase): compound_word: str hiragana: str translation: str class CompoundWordUpdate(CompoundWordBase): pass class CompoundWordInDbBase(CompoundWordBase): doc_id: Optional[ObjectIdStr] = None compound_word: str hiragana: str translation: str class CompoundWordInDb(CompoundWordInDbBase): pass<file_sep>from app.models.kanji import KanjiUpdate from typing import Optional, List, Any from fastapi import APIRouter, Body, Depends, Path, Query, HTTPException, Response, File, UploadFile, Form from loguru import logger from starlette.status import ( HTTP_201_CREATED, HTTP_204_NO_CONTENT, HTTP_400_BAD_REQUEST, HTTP_404_NOT_FOUND, HTTP_422_UNPROCESSABLE_ENTITY, ) from motor.motor_asyncio import AsyncIOMotorClient from app import models from app.services import kanji_dict_service from app.db.mongodb import get_database router = APIRouter() @router.get("/", response_model=List[models.KanjiDict]) async def get_kanji_dict_items(db: AsyncIOMotorClient = Depends(get_database)): """ Get a list of all kanji dicts in the database. """ logger.debug(">>>>") kanji_dicts = await kanji_dict_service.get_kanji_dicts(db) return kanji_dicts @router.post("/", status_code=HTTP_201_CREATED) async def import_kanji_dicts( *, kanjiDictList: List[models.KanjiDict], db: AsyncIOMotorClient = Depends(get_database) ): """ Import list of kanji dictionaries. Deletes the current data from the database. """ logger.debug(">>>>") await kanji_dict_service.import_kanji_dict_list(db, kanjiDictList) return {"message": "Completed successful bulk import.", "status": "OK"} @router.post("/upload/") async def upload_kanji_dict_file( file: UploadFile = File(...), db: AsyncIOMotorClient = Depends(get_database) ): logger.debug(f"filename: {file.filename}") result = await kanji_dict_service.process_file_upload(db, file) return {"message": "Completed successful file import.", "status": "OK"} <file_sep>from typing import Optional, List, Any from fastapi import APIRouter, Body, Depends, Path, Query, HTTPException, Response from loguru import logger from starlette.status import ( HTTP_201_CREATED, HTTP_204_NO_CONTENT, HTTP_400_BAD_REQUEST, HTTP_404_NOT_FOUND, HTTP_422_UNPROCESSABLE_ENTITY, ) from motor.motor_asyncio import AsyncIOMotorClient from app import models from app.services import compound_word_service from app.db.mongodb import get_database router = APIRouter() @router.get("/", response_model=List[models.CompoundWordInDb]) async def get_compound_word_items( *, db: AsyncIOMotorClient = Depends(get_database), related_kanji: Optional[List[str]] = Query(None), ratings: Optional[List[int]] = Query(None), offset: Optional[int] = Query(0), limit: Optional[int] = Query(100), ): """ Get a list of all compound_words in the database. """ logger.debug(">>>>") filters = models.CompoundWordFilterParams() if related_kanji: filters.related_kanji = related_kanji if ratings: filters.ratings = ratings filters.offset = offset filters.limit = limit compound_words = await compound_word_service.get_compound_words(db, filters) return compound_words @router.get("/{doc_id}", response_model=models.CompoundWordInDb) async def get_compound_word_by_id(*, db: AsyncIOMotorClient = Depends(get_database), doc_id: str) -> Any: """ Get a single compound_word document using the compound_word as a lookup. """ compound_word_result = await compound_word_service.get_compound_word_doc_by_id(db, doc_id) if not compound_word_result: raise HTTPException(status_code=HTTP_404_NOT_FOUND, detail="Compound word not found") return compound_word_result @router.post("/", response_model=models.CompoundWordInDb, status_code=HTTP_201_CREATED) async def create_new_compound_word( *, compound_word: models.CompoundWordCreate, db: AsyncIOMotorClient = Depends(get_database) ): """ Create a new compound_word document. """ logger.debug(">>>>") compound_word_by_compound_word = await compound_word_service.get_compound_word_doc_by_compound_word( db, compound_word.compound_word ) if compound_word_by_compound_word: raise HTTPException( status_code=HTTP_422_UNPROCESSABLE_ENTITY, detail=f"Compound word '{compound_word.compound_word}' already exists.", ) db_compound_word = await compound_word_service.create_compound_word(db, compound_word) return db_compound_word @router.delete("/{doc_id}", status_code=HTTP_204_NO_CONTENT) async def delete_compound_word_by_id(*, db: AsyncIOMotorClient = Depends(get_database), doc_id: str): """ Delete a single compound_word document using the compound_word as a lookup. """ compound_word_by_compound_word = await compound_word_service.get_compound_word_doc_by_id(db, doc_id) if not compound_word_by_compound_word: raise HTTPException(status_code=HTTP_404_NOT_FOUND, detail=f"Compound word '{doc_id}' not found.") await compound_word_service.delete_compound_word_doc_by_id(db, doc_id) return Response(status_code=HTTP_204_NO_CONTENT) @router.put("/{doc_id}", response_model=models.CompoundWordInDb) async def update_compound_word( *, db: AsyncIOMotorClient = Depends(get_database), doc_id: str, compoundWordUpdate: models.CompoundWordUpdate, ): """ Update a single compound_word document using the compound_word as a lookup. Partial update is supported. """ compound_word = await compound_word_service.get_compound_word_doc_by_id(db, doc_id) if not compound_word: raise HTTPException(status_code=HTTP_404_NOT_FOUND, detail=f"Compound word '{doc_id}' not found.") updated_compound_word = await compound_word_service.update_compound_word_doc_by_id( db, doc_id, compoundWordUpdate ) return updated_compound_word <file_sep>from motor.motor_asyncio import AsyncIOMotorClient class Database: client: AsyncIOMotorClient = None db = Database() async def get_database() -> AsyncIOMotorClient: """ Returns current instance of the AsycIOMotorClient for the app. This function is used for depedency injections on the API endpoints. """ return db.client<file_sep>appdirs==1.4.4 attrs==20.3.0 bcrypt==3.2.0 black==20.8b1 cffi==1.14.4 click==7.1.2 dnspython==2.0.0 email-validator==1.1.2 fastapi==0.63.0 flake8==3.8.4 h11==0.11.0 idna==2.10 iniconfig==1.1.1 loguru==0.5.3 mccabe==0.6.1 motor==2.3.0 mypy-extensions==0.4.3 packaging==20.8 passlib==1.7.4 pathspec==0.8.1 pkg-resources==0.0.0 pluggy==0.13.1 py==1.10.0 pycodestyle==2.6.0 pycparser==2.20 pydantic==1.7.3 pyflakes==2.2.0 pymongo==3.11.2 pyparsing==2.4.7 pytest==6.2.1 pytest-asyncio==0.14.0 python-multipart==0.0.5 regex==2020.11.13 six==1.15.0 starlette==0.13.6 toml==0.10.2 typed-ast==1.4.1 typing-extensions==3.7.4.3 uvicorn==0.13.2 <file_sep>.EXPORT_ALL_VARIABLES: PROJECT_NAME=kanji_manager FIRST_SUPERUSER=<EMAIL> FIRST_SUPERUSER_PASSWORD=pw app-start: uvicorn app.main:app --reload --log-level 'debug'<file_sep>from bson import ObjectId from datetime import datetime, timezone from typing import Optional from pydantic import BaseConfig, BaseModel class ObjectIdStr(str): @classmethod def __get_validators__(cls): yield cls.validate @classmethod def validate(cls, v): if not isinstance(v, ObjectId): raise ValueError("Not a valid ObjectId") return str(v) class RWModel(BaseModel): class Config(BaseConfig): allow_population_by_alias = True json_encoders = { datetime: lambda dt: dt.replace(tzinfo=timezone.utc).isoformat().replace("+00:00", "Z") } <file_sep>from enum import Enum from typing import Optional, List from app.models.rwmodel import RWModel, ObjectIdStr from app.models.compound_word import CompoundWordBase, CompoundWordInDb class KanjiSectionEnum(str, Enum): a = "あ" i = "い" class KanjiFilterParams(RWModel): offset: int = 0 limit: int = 100 class KanjiBase(RWModel): # Number in the list of common use kanji jouyou_number: Optional[int] = None kanji: Optional[str] = None # What section it belongs to e.g. あ、い、う、え、お etc. kanji_section: Optional[KanjiSectionEnum] = None radical: Optional[str] = None strokes: Optional[int] = None jlpt_level: Optional[str] = None # ranking of most used in newspapers out of 2500 frequency_rank: Optional[int] = None onyomi: Optional[List[str]] = None kunyomi: Optional[List[str]] = None meaning: Optional[List[str]] = None class KanjiCreate(KanjiBase): jouyou_number: int kanji: str onyomi: List[str] kunyomi: List[str] meaning: List[str] class KanjiUpdate(KanjiBase): pass class KanjiInDbBase(KanjiBase): doc_id: Optional[ObjectIdStr] = None kanji: str class KanjiInDb(KanjiInDbBase): pass <file_sep>from fastapi import FastAPI from fastapi.middleware.cors import CORSMiddleware import uvicorn from app.api.api_v1.api import api_router from app.core.config import settings from app.db.mongodb_utils import connect_to_mongo, close_mongo_connection from app.utils.log_config import init_logging app = FastAPI(title=settings.PROJECT_NAME, openapi_url=f"{settings.API_V1_STR}/openapi.json") init_logging() def setup(): """ Configure the FastAPI app, router, eventhandlers, etc. """ if settings.BACKEND_CORS_ORIGINS: app.add_middleware( CORSMiddleware, allow_origins=[str(origin) for origin in settings.BACKEND_CORS_ORIGINS], allow_credentials=True, allow_methods=["*"], allow_headers=["*"], ) app.add_event_handler("startup", connect_to_mongo) app.add_event_handler("shutdown", close_mongo_connection) app.include_router(api_router, prefix=settings.API_V1_STR) setup() if __name__ == "__main__": uvicorn.run("app.main:app", host="0.0.0.0", log_level="debug") <file_sep>import json from typing import List from datetime import datetime from bson import ObjectId from loguru import logger from motor.motor_asyncio import AsyncIOMotorClient from app.core.config import settings from app import models async def create_kanji(connection: AsyncIOMotorClient, kanji: models.KanjiCreate) -> models.KanjiInDb: """ Create a new kanji document. :param connection: Async database client. :param kanji: The kanji document to insert into the database. :return: Returns kanji document as it is in the database. """ logger.debug(">>>>") kanji_doc = kanji.dict() logger.info(f"Creating kanji doc: {json.dumps(kanji_doc, indent=2, ensure_ascii=False)}") kanji_doc["updated_at"] = datetime.utcnow() result = await connection[settings.MONGO_DB][settings.MONGO_KANJI_COLLECTION].insert_one(kanji_doc) logger.debug(f"Inserted Id: {result.inserted_id}") kanji_in_db = models.KanjiInDb(**kanji_doc) kanji_in_db.doc_id = result.inserted_id return kanji_in_db async def get_kanji_doc_by_id(connection: AsyncIOMotorClient, doc_id: str) -> models.KanjiInDb: """ Retrieve a single kanji document. :param connection: Async database client. :param doc_id: The unique doc_id to use to retrieve the kanji document from the database. :return: Returns kanji document as it is in the database. """ logger.debug(">>>>") logger.info(f"Retrieving kanji data for {doc_id}...") kanji_doc = await connection[settings.MONGO_DB][settings.MONGO_KANJI_COLLECTION].find_one( {"_id": ObjectId(doc_id)} ) if kanji_doc: if "doc_id" in kanji_doc: del kanji_doc["doc_id"] kanji_in_db = models.KanjiInDb(**kanji_doc) kanji_in_db.doc_id = kanji_doc.get("_id") return kanji_in_db async def get_kanji_doc_by_kanji(connection: AsyncIOMotorClient, kanji: str) -> models.KanjiInDb: """ Retrieve a single kanji document. :param connection: Async database client. :param kanji: The kanji to use to retrieve the kanji document from the database. :return: Returns kanji document as it is in the database. """ logger.debug(">>>>") logger.info(f"Retrieving kanji data for {kanji}...") kanji_doc = await connection[settings.MONGO_DB][settings.MONGO_KANJI_COLLECTION].find_one( {"kanji": kanji} ) if kanji_doc: if "doc_id" in kanji_doc: del kanji_doc["doc_id"] kanji_in_db = models.KanjiInDb(**kanji_doc) kanji_in_db.doc_id = kanji_doc.get("_id") return kanji_in_db async def get_kanji(connection: AsyncIOMotorClient, offset, limit) -> List[models.KanjiInDb]: """ Get all kanji documents in the database. :param connection: Async database client. :return: Returns all kanji documents as a list. """ logger.debug(">>>>") if limit is None: limit = 0 if offset is None: offset = 0 if offset or limit: results = connection[settings.MONGO_DB][settings.MONGO_KANJI_COLLECTION].find( limit=limit, skip=offset ) else: results = connection[settings.MONGO_DB][settings.MONGO_KANJI_COLLECTION].find() kanji_results = [] async for result in results: if "doc_id" in result: del result["doc_id"] kanji_in_db = models.KanjiInDb(**result) kanji_in_db.doc_id = result.get("_id") kanji_results.append(kanji_in_db) logger.info(f"Retrieved {len(kanji_results)} kanji.") return kanji_results async def delete_kanji_doc_by_id(connection: AsyncIOMotorClient, doc_id: str) -> None: """ Delete kanji documents by doc_id. The matching document will be deleted. :param connection: Database connection object. :param doc_id: The unique doc_id to delete documents by. """ logger.info(f"Deleting kanji '{doc_id}'...") await connection[settings.MONGO_DB][settings.MONGO_KANJI_COLLECTION].delete_one({"_id": ObjectId(doc_id)}) logger.info(f"Deleted kanji '{doc_id}'.") async def update_kanji_doc_by_id( connection: AsyncIOMotorClient, doc_id: str, kanjiUpdate: models.KanjiUpdate ) -> models.KanjiInDb: """ Update a single kanji by doc_id. Supports partial update. Only attributes set on the KanjiUpdate object will be updated. :param connection: Async database client. :param doc_id: The unique doc_id to update a document by. :param kanjiUpdate: KanjiUpdate instance with updated values. :return: Returns kanji document as it is in the database. """ logger.debug(">>>>") db_kanji = await get_kanji_doc_by_id(connection, doc_id) if kanjiUpdate.kanji: db_kanji.kanji = kanjiUpdate.kanji if kanjiUpdate.jouyou_number: db_kanji.jouyou_number = kanjiUpdate.jouyou_number if kanjiUpdate.radical: db_kanji.radical = kanjiUpdate.radical if kanjiUpdate.strokes: db_kanji.strokes = kanjiUpdate.strokes if kanjiUpdate.jlpt_level: db_kanji.jlpt_level = kanjiUpdate.jlpt_level if kanjiUpdate.frequency_rank: db_kanji.frequency_rank = kanjiUpdate.frequency_rank if kanjiUpdate.onyomi: db_kanji.onyomi = kanjiUpdate.onyomi if kanjiUpdate.kunyomi: db_kanji.kunyomi = kanjiUpdate.kunyomi if kanjiUpdate.meaning: db_kanji.meaning = kanjiUpdate.meaning updated_doc = db_kanji.dict() updated_doc["doc_id"] = str(updated_doc["doc_id"]) logger.info(f"Updating kanji {doc_id} with: {json.dumps(updated_doc, indent=2, ensure_ascii=False)}") await connection[settings.MONGO_DB][settings.MONGO_KANJI_COLLECTION].replace_one( {"_id": ObjectId(doc_id)}, updated_doc ) return db_kanji <file_sep>from app.models.kanji import KanjiCreate, KanjiInDb, KanjiUpdate, KanjiFilterParams from app.models.compound_word import ( CompoundWordCreate, CompoundWordInDb, CompoundWordUpdate, CompoundWordFilterParams, ) from app.models.example_sentence import ( ExampleSentenceCreate, ExampleSentenceFilterParams, ExampleSentenceInDb, ExampleSentenceUpdate, ) from app.models.kanji_dict import KanjiDict<file_sep>from typing import Optional, List from app.models.compound_word import CompoundWordInDb from app.models.example_sentence import ExampleSentenceInDb from app.models.kanji import KanjiInDb from app.models.rwmodel import RWModel, ObjectIdStr class KanjiDictBase(KanjiInDb): compound_words: Optional[List[CompoundWordInDb]] = [] example_sentences: Optional[List[ExampleSentenceInDb]] = [] class KanjiDict(KanjiDictBase): pass
f5f5d8dd680fa289d869a902064c06f322cf188e
[ "Markdown", "Python", "Text", "Makefile" ]
23
Python
tmsdev82/kanji-dict-manager
7c8863a5db208a2909377c74aa183cbc6f6346ea
d6ac5ac5f72cae85984aa6466ec22bd70f61ee79
refs/heads/master
<repo_name>surya5a6/RxJS-react<file_sep>/src/App.js import { useEffect, useState } from 'react'; import { Observable } from 'rxjs'; const observable = Observable.create(function(observer) { observer.next('Hello') }); function App() { const [items, setItem] = useState([]) useEffect(() => { var subscription = observable.subscribe((value) => { console.log(value); setItem( items => [...items, value]) }) return () => { subscription.unsubscribe(); } },[]); return ( <div> {items.map( item => <li>{item}</li>)} </div> ) } export default App; <file_sep>/src/utils.js export function render(element, container) { if (typeof element.type === "function") element = element.type(); const dom = element.type === "TEXT_ELEMENT" ? document.createTextNode("") : document.createElement(element.type); const isProperty = key => key !== "children"; Object.keys(element.props) .filter(isProperty) .forEach(name => { dom[name] = element.props[name]; }); // eslint-disable-next-line element.props.children?.forEach(child => render(child, dom)); container.appendChild(dom); } // JSX export function createTextElement(text) { return { type: "TEXT_ELEMENT", props: { nodeValue: text, children: [] } }; } export function createElement(type, props, ...children) { return { type, props: { ...props, children: children.map(child => typeof child === "object" ? child : createTextElement(child) ) } }; } // RENDER-AND-COMMIT // git commit const noop = () => {}; export function performUnitOfWork(fiber, resetWipFiber = noop) { const isFunctionComponent = fiber.type instanceof Function; if (isFunctionComponent) { // it is either a function component... (so call it) resetWipFiber(fiber); const children = [fiber.type(fiber.props)]; reconcileChildren(fiber, children.flat()); } else { // or a host component... (so createDom) if (!fiber.dom) fiber.dom = createDom(fiber); reconcileChildren(fiber, fiber.props.children.flat()); } if (fiber.child) return fiber.child; let nextFiber = fiber; while (nextFiber) { if (nextFiber.sibling) return nextFiber.sibling; nextFiber = nextFiber.parent; } }<file_sep>/src/ReactApp.js import { render, createElement, createTextElement } from "./utils"; import "./styles.css"; const React = { createElement }; const textElement = createTextElement("Hello world"); const element = createElement("h1", undefined, textElement); const ele = <h1>Hello</h1>; const container = document.getElementById("root"); render(element, container); render(ele, container);
e6de472ea11876a3a1188fb33f3e6a4cfb1754bd
[ "JavaScript" ]
3
JavaScript
surya5a6/RxJS-react
bf64e3c6633e1e974629428bebee8794e14d05fb
94e8c566ef2b76429efef39d5cc9a9d4688a2042
refs/heads/master
<file_sep>/* * ForceGenerator.h * RPhysics * * Created by <NAME> on 26/02/2011. * Copyright 2011 __MyCompanyName__. All rights reserved. * */ #pragma once; #include "SimObject.h" #include "boost/shared_ptr.hpp" //----------------------------------------------------------------------------------------------------- class CForceGeneratorBase { public: virtual void ApplyGlobalForce(CSimObjectBase& sim_object) = 0; virtual void ApplyForce() = 0; virtual void Draw() {} }; //----------------------------------------------------------------------------------------------------- class CGravity : public CForceGeneratorBase { public: CGravity() : m_Acceleration(0.0f, 9.81f, 0.0f) { } CGravity(Vec3fArg acceleration) : m_Acceleration(acceleration) { } virtual void ApplyGlobalForce(CSimObjectBase& sim_object) { sim_object.ApplyForce(sim_object.GetMass() * m_Acceleration); } virtual void ApplyForce() {} private: ci::Vec3f m_Acceleration; }; //----------------------------------------------------------------------------------------------------- class CMedium : public CForceGeneratorBase { public: CMedium(float drag) : m_DragCoefficient(drag) { } virtual void ApplyGlobalForce(CSimObjectBase& sim_object) { sim_object.ApplyForce(sim_object.GetVelocity() * -m_DragCoefficient); } virtual void ApplyForce() {} private: float m_DragCoefficient; }; //----------------------------------------------------------------------------------------------------- class CSpring : public CForceGeneratorBase { public: CSpring(float stiffness, float damping, CSimObjectBase *p_obj_a, CSimObjectBase *p_obj_b) : m_Stiffness(stiffness), m_Damping(damping) { m_SimObjectA = boost::shared_ptr<CSimObjectBase>(p_obj_a); m_SimObjectB = boost::shared_ptr<CSimObjectBase>(p_obj_b); m_RestLength = (p_obj_a->GetCurrPos() - p_obj_b->GetCurrPos()).length(); } CSpring(float stiffness, float damping, CSimObjectBase* p_obj_a, CSimObjectBase* p_obj_b, float rest_length) : m_Stiffness(stiffness), m_Damping(damping), m_RestLength(rest_length) { m_SimObjectA = boost::shared_ptr<CSimObjectBase>(p_obj_a); m_SimObjectB = boost::shared_ptr<CSimObjectBase>(p_obj_b); } virtual void ApplyGlobalForce(CSimObjectBase& sim_object) {}; virtual void ApplyForce(); virtual void Draw(); private: float m_Stiffness; float m_Damping; float m_RestLength; boost::shared_ptr<CSimObjectBase> m_SimObjectA; boost::shared_ptr<CSimObjectBase> m_SimObjectB; }; <file_sep>/* * Simulation.h * RPhysics * * Created by <NAME> on 26/02/2011. * Copyright 2011 __MyCompanyName__. All rights reserved. * */ #include "Integrator.h" #include "SimObject.h" #include "ForceGenerator.h" #include "boost/shared_ptr.hpp" #include <list> class CSimulation { public: CSimulation(float time_step) { CIntegratorBase* p_integrator = new CVerletNoVelocityIntegrator(time_step); m_Integrator = boost::shared_ptr<CIntegratorBase>(p_integrator); } void AddSpring(CSpring* p_spring) { m_Springs.push_back(TForceGeneratorPtr(p_spring)); } void AddGlobalForce(CForceGeneratorBase* p_force) { m_GlobalForces.push_back(TForceGeneratorPtr(p_force)); } void AddSimObject(CSimObjectBase* p_sim_object) { m_SimObjects.push_back(TSimObjectPtr(p_sim_object)); } void Update(float delta_time); void Draw(); protected: typedef boost::shared_ptr<CSimObjectBase> TSimObjectPtr; typedef boost::shared_ptr<CForceGeneratorBase> TForceGeneratorPtr; typedef std::list<TSimObjectPtr > TSimObjectList; typedef std::list<TForceGeneratorPtr > TForceGeneratorList; TSimObjectList m_SimObjects; TForceGeneratorList m_GlobalForces; TForceGeneratorList m_Springs; boost::shared_ptr<CIntegratorBase> m_Integrator; };<file_sep>#include "cinder/gl/gl.h" #include "RPhysicsApp.h" #include "Simulation.h" using namespace ci; using namespace ci::app; using namespace std; RPhysicsApp* RPhysicsApp::mp_App = NULL; float time_step = 1.0f/10.0f; void RPhysicsApp::setup() { mp_PhysicsWorld = new CSimulation(time_step); CSimObject* a1 = new CSimObject(SIM_OBJECT_DYNAMIC, 10.0f, ci::Vec3f(200, 200, 0)); CSimObject* a2 = new CSimObject(SIM_OBJECT_DYNAMIC, 10.0f, ci::Vec3f(400, 200, 0)); CSimObject* b = new CSimObject(SIM_OBJECT_STATIC, 1.0f, ci::Vec3f(300, 100, 0)); mp_PhysicsWorld->AddSimObject(a1); mp_PhysicsWorld->AddSimObject(a2); mp_PhysicsWorld->AddSimObject(b); mp_PhysicsWorld->AddSpring(new CSpring(30, 2.9f, a1, b)); mp_PhysicsWorld->AddSpring(new CSpring(30, 2.9f, a2, a1)); mp_PhysicsWorld->AddGlobalForce(new CGravity(ci::Vec3f(0, 9.81f, 0))); //mp_PhysicsWorld->AddGlobalForce(new CMedium(0.05f)); mp_App = this; } void RPhysicsApp::keyDown(KeyEvent event) { switch(event.getCode()) { case KeyEvent::KEY_ESCAPE: quit(); break; default: break; } } void RPhysicsApp::update() { mp_PhysicsWorld->Update(time_step); } void RPhysicsApp::draw() { // clear out the window with black gl::clear( Color( 0, 0, 0 ) ); glColor3f(1,1,1); //gl::drawSolidRect(Rectf(0,0,100,100)); mp_PhysicsWorld->Draw(); } CINDER_APP_BASIC( RPhysicsApp, RendererGl ) <file_sep>/* * RPhysicsApp.h * RPhysics * * Created by <NAME> on 01/03/2011. * Copyright 2011 __MyCompanyName__. All rights reserved. * */ #pragma once #include "cinder/app/AppBasic.h" class CSimulation; class RPhysicsApp : public ci::app::AppBasic { public: void setup(); void keyDown(ci::app::KeyEvent event); void update(); void draw(); CSimulation* mp_PhysicsWorld; static RPhysicsApp& Get() { return *mp_App; } private: static RPhysicsApp* mp_App; };
ce11a0ad750fb79a6d553c939ca2516106d65725
[ "C++" ]
4
C++
merf/RationalPhysics
c74a9a28449a579e487a69e766d88f2d718725f0
7be3ca46fa9bb29d1cedb3d2dd436fa873aecdb3
refs/heads/master
<file_sep>import subprocess import re # Input: tif filename # Output: Min and max latitude and longitude def getGdalInfo(tifFilename): try: out = subprocess.Popen(["gdalinfo", tifFilename], stdout=subprocess.PIPE) except OSError: print "Error running gdalinfo! Do you have gdalinfo installed?" tifOutput = out.stdout.read() for line in tifOutput.split("\n"): # flags for upper left and lower right: ul = False lr = False line = line.lower() # lower case if("upper left") in line: content = line.split("upper left")[1].strip(" ") ul = True elif("lower right") in line: content = line.split("lower right")[1].strip(" ") lr = True else: continue rePatternOne = '''\(\ * ( .*?\..*? ) ,''' rePatternTwo = ''',\ * ( .*?\..*? ) \)''' p1 = re.compile(rePatternOne, re.VERBOSE) p2 = re.compile(rePatternTwo, re.VERBOSE) longitude = p1.findall(content)[0] latitude = p2.findall(content)[0] if(ul): maxLatitude = float(latitude) minLongitude = float(longitude) elif(lr): minLatitude = float(latitude) maxLongitude = float(longitude) #print "minLatitude, maxLatitude, minLongitude, maxLongitude" #print minLatitude, maxLatitude, minLongitude, maxLongitude return minLatitude, maxLatitude, minLongitude, maxLongitude <file_sep>import processTif import argparse import sys argparser = argparse.ArgumentParser(description="Process elevation data from a GeoTiff") argparser.add_argument('--filename', help='Filename for the tiff file to process.') argparser.add_argument('--outfile', help='Filename for the output csv and json files.') argparser.add_argument('--scale', help='Scale factor of the output files.', type=int) # FIXME: explain argparser.add_argument('--latitude', help='Max and min latitude to be processed.', nargs=2) argparser.add_argument('--longitude', help='Max and min longitude to be processed.', nargs=2) argparser.add_argument('--info', help='Print info about tiff.', action="store_true") args = argparser.parse_args() processTif.processElevData(args.filename, args.outfile, args.scale, args.info) <file_sep>from environmentSimulator import * grid.writeOut(DATA_DIR, "turn0.txt") for turn in range(1, NUM_TURNS): print("executing turn " + str(turn)) for gameobject in grid.gameObjects: gameobject.doTurn() print("writing out game grid " + str(turn)) grid.writeOut(DATA_DIR, "turn" + str(turn) + ".txt") print("num Trees = " + str(grid.getCount("Tree"))) print("num Factories = " + str(grid.getCount("Factory"))) print("co2 = " + str(grid.environment.co2)) <file_sep>import random import os import json import gameobjects import Grid from DataProcessors import CsvReader import Environment GRID_SIZE = 1000 NUM_LAKES = 200 NUM_NINJAS = 800 NUM_TREES = 20000 NUM_OLDMEN = 100 NUM_VILLAGERS = 800 NUM_TURNS = 100 DATA_DIR = "grids" #print("making elevationGrid") #elevationGrid = CsvReader.CsvReader("elev/data/fuji_1000.csv", [int,int,int], maxSize=1000).getGrid() #print("writing elevationGrid to json") #with open("elev/data/fuji_1000.json", 'w') as f: #f.write(json.dumps(elevationGrid)) #print("exiting") #exit() print("loading elevationGrid") with open("elev/data/fuji_1000.json") as f: elevationGrid = json.loads(f.read()) print("elevationGrid size = " + str(len(elevationGrid)) + "x" + str(len(elevationGrid[0]))) print("making game grid") grid = Grid.Grid(GRID_SIZE, GRID_SIZE, elevationGrid) grid.environment = Environment.Environment() grid.environment.generateLake(30, 5, 5, grid) for i in range(NUM_LAKES): x = random.randint(0, GRID_SIZE-1) y = random.randint(0, GRID_SIZE-1) print("x,y= ",x,y) grid.environment.generateLake(30, x-4, y-4, grid) print("made game grid") # Initialize grid: def placeObjects(number, gameobjectClass, grid): for i in range(number): square = " " x_pos = 0 y_pos = 0 while square == " ": x_pos = random.randint(0, GRID_SIZE-1) y_pos = random.randint(0, GRID_SIZE-1) square = grid.getSymbol(x_pos, y_pos) if(square == " "): gameobject = gameobjectClass(grid) square = gameobject.symbol gameobject.x = x_pos gameobject.y = y_pos #addGameObject(gameobject, gameObjects, objectClasses) grid.addGameobject(gameobject) #print ("tree num = " + str(i) + " square = " + square + " x_pos = " + str(x_pos) + " y_pos = " + str(y_pos)) placeObjects(NUM_TREES, gameobjects.Tree, grid) placeObjects(NUM_OLDMEN, gameobjects.OldMan, grid) placeObjects(NUM_NINJAS, gameobjects.Ninja, grid) placeObjects(NUM_VILLAGERS, gameobjects.Villager, grid) <file_sep># Input: latitude, longitude, scale factor # Output: index in grid, distance from (0,0) in square def getGridPosition(grid, lat, lng, latMin, latMax, longMin, longMax ): # lat/long min and max are the maximum / minimum geo points in the grid gridRows = len(grid) gridCols = len(grid[0]) latStep = (latMax - latMin) / gridRows lngStep = (longMax - longMin) / gridCols row = ((1 - (lat - latMin)) / latStep) col = ((lng - longMin) / lngStep) return row, col <file_sep>import Grid, Map class Environment(object): def __init__(self): self.temp = 0 self.co2 = 0 def generateLake(self, numSquares, startX, startY, grid): x = startX y = startY squares = [] existingSquare = grid.grid[y][x] direction = None for i in range(numSquares): lakeSquare = Grid.Lake(existingSquare.elev, existingSquare.gameobject) grid.setSquare(x, y,lakeSquare) lastDirection = direction while direction == lastDirection: direction = Map.Direction.random() x += direction.x y += direction.y <file_sep>import sys, re, math with open(sys.argv[2]) as f: data = f.readlines() longitude = [] latitude = [] elevation = [] for line in data: items = re.split("\t", line) try: longitude.append(float(items[0])) latitude.append( float(items[1])) elevation.append( float(items[2])) except ValueError: continue longMin = min(longitude) latMin = min(latitude) # output json file ? # ultimately pass to generateTris lngRange = max(longitude) - longMin latRange = max(latitude) - latMin x = [math.floor((lng - longMin) * len(longitude) / lngRange) for lng in longitude] y = [math.floor((lat - latMin) * len(latitude) / lngRange) for lat in latitude] grid = [[0 for i in range(int(max(longitude)))] for j in range(int(max(latitude)))] def findElev(i,j): for index in x: index = int(index) try: if x[index] == i and y[index] == j: return elevation[index] except IndexError: continue for i in range(int(max(longitude))): for j in range(int(max(latitude))): grid[j][i] = findElev(j,i) print(grid) <file_sep>import os class CsvReader(object): def __init__(self, filename, datatypes, maxSize = 0): self.filename = filename self.datatypes = datatypes self.maxSize = maxSize def getGrid(self): with open(self.filename) as f: lines = f.readlines() out = [] for line in lines: outLine = [] for i,item in enumerate(line.split(",")): outLine.append(self.datatypes[i](item)) out.append(outLine) return out <file_sep># -*- coding: utf-8 -*- import pygame import os import sys from environmentSimulator import * import Screen SCREEN_PIXELS_PER_GRID_SQUARE = 20 WIDTH_SQUARES = 32 HEIGHT_SQUARES = 24 SPRITE_DIR = "sprites" pygame.init() screen= Screen.Screen(WIDTH_SQUARES, HEIGHT_SQUARES, SCREEN_PIXELS_PER_GRID_SQUARE) pygame.display.set_caption("environment simulation :)") clock = pygame.time.Clock() # TODO: move to Image class imgDict = {} def getImage(spritename): try: return imgDict[spritename] except KeyError: imgDict[spritename] = pygame.image.load(os.path.join(SPRITE_DIR, spritename)) return imgDict[spritename] # end TODO: move to Image class # TODO: move def getTotalMoney(people): total = sum(person.money for person in people) return total # end TODO: move offsetX = 0 offsetY = 0 def getInput(offsetX, offsetY): keys = pygame.key.get_pressed() #checking pressed keys if keys[pygame.K_UP]: offsetY -= 10 if keys[pygame.K_DOWN]: offsetY += 10 if keys[pygame.K_LEFT]: offsetX -= 10 if keys[pygame.K_RIGHT]: offsetX += 10 if keys[pygame.K_p]: paused = True else : paused = False return offsetX, offsetY, paused def paintElev(): pass def drawSquare(grid, screenXSquares, screenYSquares): pass villagers = grid.getClass("Villager") ninjas = grid.getClass("Ninja") oldmen = grid.getClass("OldMan") paused = False while True: clock.tick(50) # Process events for event in pygame.event.get(): if event.type == pygame.QUIT: sys.exit() screen.drawGrid(grid, offsetX, offsetY)#, screen.width_squares, screen.height_squares) # Check input offsetX, offsetY, paused = getInput(offsetX, offsetY) # Move objects ... # Draw objects ... if not paused: for gameobject in grid.gameObjects: gameobject.doTurn() if screen.inWindow(gameobject, offsetX, offsetY): image = getImage(gameobject.sprite) screen.draw(gameobject, image, offsetX, offsetY) paintElev() # Update the screen pygame.display.flip() # Print debug messages: #print("writing out game grid " + str(turn)) #grid.writeOut(DATA_DIR, "turn" + str(turn) + ".txt") print("num Trees = " + str(grid.getCount("Tree"))) print("num Factories = " + str(grid.getCount("Factory"))) print("co2 = " + str(grid.environment.co2)) print("villager money= " + str(getTotalMoney(villagers))) print("ninja money= " + str(getTotalMoney(ninjas))) print("old man money= " + str(getTotalMoney(oldmen))) <file_sep>import random class Direction(object): def __init__(self, x, y): self.x = x self.y = y @staticmethod def random(): cardinalDirection = ['n','s','e','w'][random.randint(0,3)] if(cardinalDirection == 'n'): direction = Direction(0, -1) if(cardinalDirection == 's'): direction = Direction(0, 1) if(cardinalDirection == 'e'): direction = Direction(1, 0) if(cardinalDirection == 'w'): direction = Direction(-1, 0) return direction <file_sep>import numpy as np import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D import sys from scipy.spatial import Delaunay import json import csv from coords_to_grid import getGridPosition from Parsers import Fuji, FortCollins args = sys.argv filename = args[1] elev,x,y= Fuji.parse(args) def plotData(): hf = plt.figure() ha = hf.add_subplot(111, projection='3d') X, Y = np.meshgrid(x, y) # `plot_surface` expects `x` and `y` elev to be 2D ha.plot_surface(X, Y, elev) plt.show() def makeMatrix(grid): # ! how grid is structured: just matrix of elev values matrix = [] z = grid for i,line in enumerate(z): for j,value in enumerate(line): matrix.append([i,j,value]) return matrix matrix = makeMatrix(elev) #print(matrix) plotData() matLen = len(elev[0]) tris = [] elevSlopeTiles = list(elev) elevTiles = list(elev) for i,row in enumerate(elev[:-1]): for j,item in enumerate(row[:-1]): index = i*matLen + j # first triangle: tris.append( index ) # x . # . tris.append(index + 1) # . x # . tris.append(index + matLen) # . . # x # second triangle: tris.append(index + 1) tris.append(index + matLen + 1) tris.append(index + matLen ) for i,row in list(enumerate(elevSlopeTiles))[::2]: for j,col in list(enumerate(row))[::2]: elevSlopeTiles[i+1][j] = elevSlopeTiles[i][j] elevSlopeTiles[i+1][j+1] = elevSlopeTiles[i][j] elevSlopeTiles[i][j+1] = elevSlopeTiles[i][j] slopeTileMatrix = makeMatrix(elevSlopeTiles) savedPt = elevTiles[0][0] for i,row in enumerate(elevTiles[:-1]): for j,col in enumerate(row[:-1]): savedPt = elevTiles[i][j+1] elevTiles[i+1][j] = savedPt elevTiles[i+1][j+1] = savedPt elevTiles[i][j+1] = savedPt tileMatrix = makeMatrix(elevTiles) def makeJson(matrix, tris): jsonObj = {"verticesX": [], "verticesY": [], "verticesZ": [], "tris": []} for point in matrix: jsonObj["verticesX"].append(float(point[0])) jsonObj["verticesY"].append(float(point[1])) jsonObj["verticesZ"].append(float(-point[2])) jsonObj["tris"] = tris return jsonObj jsonObj = makeJson(matrix, tris) f = open(filename.split('.')[0] + '.json', 'w') f.write(json.dumps(jsonObj)) f.close() jsonObj2 = makeJson(slopeTileMatrix, tris) f = open(filename.split('.')[0] + '_slope_tiles.json', 'w') f.write(json.dumps(jsonObj2)) f.close() jsonObj3 = makeJson(tileMatrix, tris) f = open(filename.split('.')[0] + '_tiles.json', 'w') f.write(json.dumps(jsonObj3)) f.close() f = open("gridexport.csv", 'w') w = csv.writer(f) w.writerows(elev) f.close() f = open("stuffAroundFuji.json") store_locations = json.loads(f.read()) f.close() latMin = 35 latMax = 36 lngMin = 138 lngMax = 139 shopInfo = {"names": [], "xcoords": [], "ycoords": []} for item in store_locations["results"]: shopInfo["names"].append(item["name"]) loc = item["geometry"]["location"] gridPos = (getGridPosition(elev, loc["lat"], loc["lng"], latMin, latMax, lngMin, lngMax)) shopInfo["xcoords"].append(gridPos[0]) shopInfo["ycoords"].append(gridPos[1]) f = open("shop_info.json", 'w') f.write(json.dumps(shopInfo)) f.close() print("mt fuji") print(getGridPosition(elev,35.3618,138.7298, latMin, latMax, lngMin, lngMax)) def delaunayTris(): # not relevant tris = Delaunay(matrix) pfile = open('points.cs','w') tfile = open('tris.cs','w') p='' t='' for point in tris.points: p += "new Vector3(" + str(point[0]) + ',' + str(point[1]) + ',' + str(point[2]) + '),\n' pfile.write(p) pfile.close() for simplex in tris.simplices: t += str(simplex[0]) + ',' + str(simplex[1]) + ',' + str(simplex[2]) + ',' tfile.write(t) tfile.close() <file_sep>import pygame class Screen(object): def __init__(self, widthSquares, heightSquares, pixelsPerSquare): self.width_squares = widthSquares self.height_squares = heightSquares self.width_pixels = widthSquares * pixelsPerSquare self.height_pixels = heightSquares * pixelsPerSquare self.pygameScreen = pygame.display.set_mode((self.width_pixels, self.height_pixels)) self.pixelsPerSquare = pixelsPerSquare def inWindow(self, gameobject, offsetX, offsetY): return gameobject.x * self.pixelsPerSquare - offsetX < self.width_pixels and gameobject.y * self.pixelsPerSquare - offsetY < self.height_pixels def draw(self, gameobject, image, offsetX, offsetY): imagerect = image.get_rect(topleft = (gameobject.x * self.pixelsPerSquare - offsetX, gameobject.y * self.pixelsPerSquare - offsetY)) self.pygameScreen.blit(image, imagerect) def setOffset(self, offsetX, offsetY): self.offsetX = offsetX self.offsetY = offsetY def getScreenTopLeft(self, gridX, gridY): pass def drawSquare(grid, x, y): pass def getRect(self, x, y, w, h): position = x,y size = w,h rect = pygame.Rect(position, size) return rect def multiplyColor(self, r, g, b, multiplier): return (r,g,b) # FIXME r = (r * multiplier / 1000) % 255 g = (g * multiplier / 1000) % 255 b = (b * multiplier / 1000) % 255 print (r,g,b) return (r,g,b) def drawRect(self, x, y, w, h, color): rect = self.getRect(x, y, w, h) pygame.draw.rect(self.pygameScreen, color,(x,y,w,w)) # NOTE: screenSizeX and screenSizeY are in Squares, not pixels. def drawGrid(self, grid, offsetX, offsetY): # Clear the screen #self.pygameScreen.fill((50, 200, 50)) size = self.width_squares, self.height_squares offsetXSq = int( offsetX / self.pixelsPerSquare) offsetYSq = int( offsetY / self.pixelsPerSquare) offsetXPix = offsetX - self.pixelsPerSquare * offsetXSq offsetYPix = offsetY - self.pixelsPerSquare * offsetYSq print("offsetXPix, offsetYPix") print(offsetXPix, offsetYPix) x_range= offsetXSq, offsetXSq + self.width_squares y_range = offsetYSq, offsetYSq + self.height_squares for y in range(y_range[0], y_range[1]): # TODO FIXME double check row = grid.grid[y] for x in range(x_range[0], x_range[1]): # TODO FIXME double check square = row[x] color = self.multiplyColor(square.color.r, square.color.g, square.color.b, square.elev) self.drawRect((x - offsetXSq) * self.pixelsPerSquare - offsetXPix, (y - offsetYSq) * self.pixelsPerSquare - offsetYPix, self.pixelsPerSquare, self.pixelsPerSquare, color) <file_sep>from testStructure import Test from code.DataProcessors import CsvReader class TestCsvReader(Test): def run(self): csvreader = CsvReader.CsvReader("data/smallCsv.csv", [int, int, float]) grid = csvreader.getGrid() self.printResult(len(grid) == 1440) testCsvReader = TestCsvReader() testCsvReader.run() <file_sep>import json import sys import getElevBounds outputFilename = "" try: filename = sys.argv[1] except IndexError: print("usage: runGetElevBounds tifFilename") getElevBounds.getGdalInfo(filename) <file_sep>import os class Square(object): # TODO FIXME add x and y coord of square def __init__(self, elev, gameobject): self.elev = elev self.gameobject = gameobject def getSymbol(self): if(self.gameobject != None): return self.gameobject.symbol else: return " " def clear(self): self.gameobject = None class Color(object): def __init__(self, r, g, b): self.r = r self.g = g self.b = b class Water(Square): def __init__(self, elev, gameobject): super(Water, self).__init__(elev, gameobject) self.color = Color(0, 102, 255) class Lake(Water): def __init__(self, elev, gameobject): super(Lake, self).__init__(elev, gameobject) class River(Water): def __init__(self, elev, gameobject): super(River, self).__init__(elev, gameobject) class Grass(Square): def __init__(self, elev, gameobject): super(Grass, self).__init__(elev, gameobject) self.color = Color(51, 153, 51) class Grid(object): # data can be a size for a square grid with no elevation data, # or a list of elevation data. def __init__(self, xsize, ysize, elevData): self.xsize = xsize self.ysize = ysize self.initEmptyGrid(xsize, ysize) self.insertElevationData(elevData) self.gameObjects = [] self.objectClasses = {} def initEmptyGrid(self, xsize, ysize): self.grid = [] for i in range(xsize): line = [] for j in range(ysize): line.append(Grass(0, None)) self.grid.append(line) def setSquare(self, x, y, square): self.grid[y][x] = square def getCount(self, classname): try: return len(self.objectClasses[classname]) except KeyError: return 0 def getClass(self, classname): try: return self.objectClasses[classname] except KeyError: return [] def addGameobject(self, gameobject): try: oldGameobject = self.grid[gameobject.y][gameobject.x].gameobject except IndexError: # FIXME: off-grid? return if oldGameobject != None: self.gameObjects.remove(oldGameobject) self.objectClasses[oldGameobject.__class__.__name__].remove(oldGameobject) self.grid[gameobject.y][gameobject.x].gameobject = gameobject # add to master list: self.gameObjects.append(gameobject) # add to class list: try: self.objectClasses[gameobject.__class__.__name__].append(gameobject) except KeyError: self.objectClasses[gameobject.__class__.__name__] = [gameobject] def insertElevationData(self, elevationGrid): for row in elevationGrid: line = [] x = row[0] y = row[1] z = row[2] try: self.grid[y][x].elev = z except IndexError: continue def getSymbol(self, x, y): if(self.grid[y][x].gameobject != None): return self.grid[y][x].gameobject.symbol else: return " " def getGameObject(self, x, y): return self.grid[y][x].gameobject def getNorth(self, x, y): try: return self.grid[y-1][x] except IndexError: return None def getSouth(self, x, y): try: return self.grid[y+1][x] except IndexError: return None def getEast(self, x, y): try: return self.grid[y][x+1] except IndexError: return None def getWest(self, x, y): try: return self.grid[y][x-1] except IndexError: return None def setGameobject(self, x, y, gameObject): self.grid[y][x].gameobject = gameObject def writeOut(self, dataDir, filename): text = "" for line in self.grid: for square in line: if square != None: text += square.getSymbol() else: text += " " text += "\n" with open(os.path.join(dataDir, filename), 'w') as f: f.write(text) <file_sep>This was a "new" version of processTif that the "current" version has progressed past. The main differences are separating "parsers" for a specific area and using "coords_to_grid" to relate grid coordinates to elevation. Keeping it around because some of that structure and functionality might be useful moving forward. <file_sep>import random import Grid import Map class GameObject(object): def __init__(self,grid): self.grid = grid self.symbol = "" self.x = 0 self.y = 0 def move(self, dx, dy): try: self.grid.grid[self.y][self.x].clear() except IndexError: # NOTE offscreen pass self.x += dx self.y += dy try: self.grid.grid[self.y][self.x].gameobject = self except IndexError: # NOTE go offscreen pass def moveForward(self, amount): self.move(self.direction.x * amount, self.direction.y * amount) # Return symbol of object dx, dy away from us FIXME not used? def check(self, dx, dy): return self.grid.grid[self.y + dy][self.x + dx].gameobject.symbol def getInFront(self): try: return self.grid.grid[self.y + self.direction.y][self.x + self.direction.x].gameobject except IndexError: # NOTE at the edge of screen return None except AttributeError: # NOTE at the edge of screen return None # Change symbol of object dx, dy away from us def change(self, dx, dy, symbol): self.grid.grid[self.y + dy][self.x + dx].gameobject.symbol = symbol # Check symbol of object in front of us def checkInFront(self): try: return self.getInFront().symbol except IndexError: # NOTE at the edge of screen return " " except AttributeError: # NOTE at the edge of screen return " " # Change symbol of object in front of us def changeInFront(self, symbol): try: self.grid.grid[self.y + self.direction.y][self.x + self.direction.x].gameobject.symbol = symbol except AttributeError: # NOTE at the edge of screen pass def placeInFront(self, gameobject): try: gameobject.x = self.x + self.direction.x gameobject.y = self.y + self.direction.y #self.grid.grid[self.y + self.direction.y][self.x + self.direction.x].gameobject = gameobject self.grid.addGameobject(gameobject) except AttributeError: # NOTE at the edge of screen pass def doTurn(self): pass class Person(GameObject): def __init__(self, grid): super(Person, self).__init__(grid) self.symbol = "p" self.direction = Map.Direction.random() #self.symbol = self.cardinalDirection class Ninja(Person): def __init__(self, grid): super(Ninja, self).__init__(grid) self.symbol = "n" self.wood = 0 self.tomatoes = 0 self.money = random.randint(0,10) self.sprite = "ninja.png" def rob(self, person): amount = random.randint(0, self.money) person.money -= amount self.money += amount def doTurn(self): if self.checkInFront() == 't': if self.wood < 6: wood = Wood(self.grid) self.placeInFront(wood) self.wood += 1 else: factory = Factory(self.grid) self.placeInFront(factory) self.wood = 0 elif self.checkInFront() == 'x' or self.checkInFront() == 'F': self.moveForward(2) elif self.checkInFront() == 'o' or self.checkInFront() == 'v': oldman = self.getInFront() self.rob(oldman) self.moveForward(2) else: self.moveForward(1) class Villager(Person): def __init__(self, grid): super(Villager, self).__init__(grid) self.symbol = "v" self.wood = 0 self.tomatoes = 0 self.money = random.randint(0,10) self.sprite = "villager.png" def doTurn(self): if self.checkInFront() == 't': wood = Wood(self.grid) self.placeInFront(wood) self.wood += 1 elif self.checkInFront() == 'x' or self.checkInFront() == 'F': self.moveForward(2) else: self.moveForward(1) class OldMan(Villager): def __init__(self, grid): super(OldMan, self).__init__(grid) self.symbol = "o" self.wood = 0 self.tomatoes = random.randint(2,5) self.money = random.randint(5,10) self.sprite = "old man.png" self.turnCounter = 0 self.gardenerSkill = random.randint(50,100) # FIXME: high skill means plant less trees def plantTree(self, x, y): tree = Tree(self.grid) tree.x = x tree.y = y self.grid.addGameobject(tree) tree.symbol = "T" #FIXME remove print("planted tree") # FIXME remove def doTurn(self): self.turnCounter += 1 if self.turnCounter % 2 == 0: if self.checkInFront() == 't' or self.checkInFront() == 'x' or self.checkInFront() == 'F': self.moveForward(2) else: self.moveForward(1) if self.turnCounter % self.gardenerSkill == 0: x = self.x y = self.y self.moveForward(1) self.plantTree(x, y) self.turnCounter = 0 class Factory(GameObject): def __init__(self, grid): super(Factory, self).__init__(grid) self.symbol = "F" self.turnCounter = 0 self.sprite = "factory.png" self.money = 0 def doTurn(self): self.turnCounter += 1 if self.turnCounter % 5 == 0: self.releaseSmog() self.turnCounter = 0 self.money += 1 if self.turnCounter % 100 == 0: self.createNinja() self.turnCounter = 0 def releaseSmog(self): self.grid.environment.co2 += 50 def createNinja(self): pass class House(GameObject): def __init__(self, grid): super(Factory, self).__init__(grid) self.symbol = "H" self.sprite = "" class Tree(GameObject): def __init__(self, grid): super(Tree, self).__init__(grid) self.symbol = "t" self.sprite = "tree.png" def doTurn(self): self.grid.environment.co2 -= 1 class Wood(GameObject): def __init__(self, grid): super(Wood, self).__init__(grid) self.symbol = "x" self.sprite = "wood.png" <file_sep>from tifffile import imread import json import csv from getElevBounds import getGdalInfo #from scipy.spatial import Delaunay #import matplotlib.pyplot as plt #from mpl_toolkits.mplot3d import Axes3D #import numpy as np #from new.coords_to_grid import getGridPosition def makeMatrix(grid): matrix = [] z = grid for i,line in enumerate(z): for j,value in enumerate(line): matrix.append([i,j,value]) return matrix def makeJson(matrix, tris): jsonObj = {"verticesX": [], "verticesY": [], "verticesZ": [], "tris": []} for point in matrix: jsonObj["verticesX"].append(float(point[0])) jsonObj["verticesY"].append(float(point[1])) jsonObj["verticesZ"].append(float(-point[2])) jsonObj["tris"] = tris return jsonObj def processElevData(filename, outfile, scalefactor, printInfo): minLatitude, maxLatitude, minLongitude, maxLongitude = getGdalInfo(filename) elevData = imread(filename) if (printInfo): print "Tiff Info:" print filename print " minLatitude, maxLatitude, minLongitude, maxLongitude " print minLatitude, maxLatitude, minLongitude, maxLongitude print "Size: " + str(len(elevData[0]))+ "x" + str(len(elevData)) x = range(int(len(elevData[0]) / scalefactor)) y = range(int(len(elevData) / scalefactor)) ystart = 2000 yend = 2100 xstart = 2000 xend = 2100 # TODO: Data will be broken into files containing # fileChunkSize x fileChunkSize data points fileChunkSize = 100 elev = [] if scalefactor != 1: for line in elevData[xstart:xend:scalefactor]: elev.append(line[ystart:yend:scalefactor]) #for line in elevData[::scalefactor]: #elev.append(line[::scalefactor]) else: elev = elevData if outfile == "": f = open(filename.split(".tif")[0] + ".csv", 'w') else: f = open(outfile + ".csv", 'w') w = csv.writer(f) w.writerows(elev) f.close() # TODO: move to tools #hf = plt.figure() #ha = hf.add_subplot(111, projection='3d') #X, Y = np.meshgrid(x, y) # `plot_surface` expects `x` and `y` elev to be 2D #ha.plot_surface(X, Y, elev) #plt.show() matrix = makeMatrix(elev) matLen = len(elev[0]) tris = [] elevSlopeTiles = list(elev) elevTiles = list(elev) for i,row in enumerate(elev[:-1]): for j,item in enumerate(row[:-1]): index = i*matLen + j # first triangle: tris.append( index ) # x . # . tris.append(index + 1) # . x # . tris.append(index + matLen) # . . # x # second triangle: tris.append(index + 1) tris.append(index + matLen + 1) tris.append(index + matLen ) for i,row in list(enumerate(elevSlopeTiles))[::2]: for j,col in list(enumerate(row))[::2]: elevSlopeTiles[i+1][j] = elevSlopeTiles[i][j] elevSlopeTiles[i+1][j+1] = elevSlopeTiles[i][j] elevSlopeTiles[i][j+1] = elevSlopeTiles[i][j] slopeTileMatrix = makeMatrix(elevSlopeTiles) savedPt = elevTiles[0][0] for i,row in enumerate(elevTiles[:-1]): for j,col in enumerate(row[:-1]): savedPt = elevTiles[i][j+1] elevTiles[i+1][j] = savedPt elevTiles[i+1][j+1] = savedPt elevTiles[i][j+1] = savedPt tileMatrix = makeMatrix(elevTiles) jsonObj = makeJson(matrix, tris) if outfile == "": f = open(filename.split('.')[0] + '.json', 'w') else: f = open(outfile + '.json', 'w') f.write(json.dumps(jsonObj)) f.close() jsonObj2 = makeJson(slopeTileMatrix, tris) if outfile == "": f = open(filename.split('.')[0] + '_slope_tiles.json', 'w') else: f = open(outfile + '_slope_tiles.json', 'w') f.write(json.dumps(jsonObj2)) f.close() jsonObj3 = makeJson(tileMatrix, tris) if outfile == "": f = open(filename.split('.')[0] + '_tiles.json', 'w') else: f = open(outfile + '_tiles.json', 'w') f.write(json.dumps(jsonObj3)) f.close() #print (matrix) #print (tris) <file_sep>import json import sys from DataProcessors import ElevJsonToCsv outputFilename = "" try: filename = sys.argv[1] resolution = int(sys.argv[2]) outputFilename = sys.argv[3] except IndexError: print("usage: runElevJsonToCsv.py inFile resolution outFile") with open(filename) as f: data = json.loads(f.read()) csvData = ElevJsonToCsv.jsonToCsv(data, resolution) with open(outputFilename, 'w') as f: f.write(csvData) <file_sep>def jsonToCsv(data, resolution): outData = "" for i,z in enumerate(data["verticesZ"][::resolution]): index = i * resolution x = data["verticesX"][index] y = data["verticesY"][index] outData += str(int(x)) + "," + str(int(y)) + "," +str(z) + "\n" return outData <file_sep>python processTif.py fuji_small.tif 10 fuji_slice cp fuji_slice.csv ~/projects/mvn-3d/Assets/csv cp fuji_slice.json ~/projects/mvn-3d/Assets/json <file_sep>class Test(object): def run(self): pass def printResult(self, passed): if(passed): print "test " + self.__class__.__name__ + " succeeded" else: print "test " + self.__class__.__name__ + " failed" <file_sep>__What is Tintin?__ Tintin is a Python application you can use to take Geotiff files, a common elevation file format, and turn them into an array of triangles suitable for a game engine like Unity. __How does it work?__ Tintin currently has two parts: an "environment simulator" and an elevation data generator. The environment simulator generates sprites on an environment and simulates the CO2 generated by houses and factories, on the one hand, and absorbed by trees, on the other. It does not currently use the real elevation data, but in the future it will. To use this part of the application, install the dependencies first: ```bash pip install -r requirements.txt ``` Then run: ```bash python pygameInterface.py ``` You should see a window pop up with a background and some sprites. __Elevation data generator__ The second part is the elevation data generator. The readme for that section is in-progress. __Where can I get Geotiff files?__ For the United States, you can find them at the [US Geographical Survey](https://viewer.nationalmap.gov) Have questions? [Ask!](http://edking4967.github.io/contact/) <file_sep>from tifffile import imread def parse(args): #filename = input('filename?') filename = args[1] scalefactor = 1 if len(args) > 2: scalefactor = int(args[2]) if len(args) == 7: xMin = int(args[3]) xMax = int(args[4]) yMin = int(args[5]) yMax = int(args[6]) print(filename) elevData = imread(filename) x = range(int(len(elevData[0]) / scalefactor)) y = range(int(len(elevData) / scalefactor)) elev = [] if scalefactor != 1: if len(args) == 7: for line in elevData[xMin:xMax:scalefactor]: elev.append(line[yMin:yMax:scalefactor]) else: for line in elevData[::scalefactor]: elev.append(line[::scalefactor]) else: elev = elevData return elev,x,y <file_sep>backports.functools-lru-cache==1.4 cycler==0.10.0 matplotlib==2.1.1 numpy==1.14.0 pygame==1.9.3 pyparsing==2.2.0 python-dateutil==2.6.1 pytz==2017.3 scipy==1.0.0 six==1.11.0 subprocess32==3.2.7 tifffile==0.12.1
c706e292055ece76476e11a3ab31d5f00fd17dfc
[ "Markdown", "Python", "Text", "Shell" ]
25
Python
MandalaGames/tintin
e861b70b9c0e6ec92dfb4a62ac22120b99ab1065
2e104c1273c0be3f230f1f1f39044b66b30b6bd7
refs/heads/master
<file_sep>CREATE TABLE names ( male TEXT, female TEXT ); CREATE TABLE surnames ( surname TEXT ); CREATE TABLE towns ( england TEXT, usa TEXT, canada TEXT ); <file_sep>from tkinter import * root = Tk() Button(root, text='2', width=4, height=2, bg="grey").grid(row=1, column=1) for i in range(0, 4): for j in range(0, 4): Button(root, text=str(i) + ' ' + str(j), width=4, height=2, bg="grey").grid(row=i, column=j) root.mainloop() <file_sep>import random import os import sqlite3 class Generator: def __init__(self): cmd = { 'n': 'SELECT * FROM names', 's': 'SELECT * FROM surnames', 't': 'SELECT * FROM towns' } con = sqlite3.connect(os.path.dirname(__file__) + r'\data\db.sqlite3') cur = con.cursor() cur.execute(cmd['n']) self.__names = [x for x in cur.fetchall()] cur.execute(cmd['s']) self.__surnames = [x[0] for x in cur.fetchall()] cur.execute(cmd['t']) self.__towns = [x for x in cur.fetchall()] con.close() def create_people_str(self): res = '' # id res += str(random.randint(100000000000000, 999999999999999)) + '/' # series res += str(random.randint(1000, 9999)) + '/' # number res += str(random.randint(100000, 999999)) + '/' # surname s = random.choice(self.__surnames) s = s[0] + s[1:].lower() res += s + '/' # name gender = random.randint(0, 1) res += random.choice(self.__names)[gender] + '/' # gender res += ('male', 'female')[gender] + '/' # age age = random.randint(1920, 2015) res += str(age) + '/' # country country = random.randint(0, 2) res += ('England', 'USA', 'Canada')[country] + '/' # town res += random.choice(self.__towns)[country] + '/' # family children if 2015 - age > 17: res += str(random.choice([True, False])) + '/' res += str(random.randint(0, 5)) else: res += str(False) + '/' res += str(0) return res def create_people_list(self, count): return [self.create_people_str() for _ in range(int(count))] def create_people_txt(self, count, place='c:\\Users\\%User%\\Desktop\\'): from getpass import getuser with open(place.replace('%User%', getuser()) + 'database.txt', 'w') as f: for i in range(int(count)): f.write(self.create_people_str() + '\n') @property def names(self): return tuple(self.__names) @property def surnames(self): return tuple(self.__surnames) @property def towns(self): return tuple(self.__towns) if __name__ == '__main__': Generator().create_people_txt(input('Count = ')) <file_sep>import csv import json import xml.etree.ElementTree import xml.dom.minidom # from .models import Name, Surname, Town import datetime import random import collections name_count = 1 # Name.objects.all().count() surname_count = 2 # Surname.objects.all().count() town_count = 3 # Town.objects.all().count() Name = [] Surname = [] Town = [] class People: def __init__(self): self.series = random.randint(1000, 9999) self.number = random.randint(100000, 999999) gender = random.randint(0, 1) self.gender = ('male', 'female')[gender] self.surname = Surname.objects.get(id=random.randint(1, surname_count)).surname if gender: name = Name.objects.get(id=random.randint(1, name_count)).male else: name = Name.objects.get(id=random.randint(1, name_count)).female self.name = name self.year = random.randint(1920, datetime.datetime.now().year) country = random.randint(0, 2) self.country = ('England', 'USA', 'Canada')[country] if country == 0: town = Town.objects.get(id=random.randint(1, town_count)).england elif country == 1: town = Town.objects.get(id=random.randint(1, town_count)).usa else: town = Town.objects.get(id=random.randint(1, town_count)).canada self.town = town if 2015 - self.year > 17: self.family = str(random.choice([True, False])) self.children = random.randint(0, 5) else: self.family = str(False) self.children = 0 self.id = self._create_id() def _create_id(self): s = [ str(self.series), str(self.number), str(self.surname), str(self.name), str(self.gender), str(self.year), str(self.country), str(self.town), str(self.family), str(self.children)] return abs(hash(''.join(s))) def __repr__(self): s = [ str(self.id), str(self.series), str(self.number), str(self.surname), str(self.name), str(self.gender), str(self.year), str(self.country), str(self.town), str(self.family), str(self.children)] return '/'.join(s) def __str__(self): s = [ str(self.id), str(self.series), str(self.number), str(self.surname), str(self.name), str(self.gender), str(self.year), str(self.country), str(self.town), str(self.family), str(self.children)] return '/'.join(s) def to_dict(self): return { 'id': str(self.id), 'series': str(self.series), 'number': str(self.number), 'surname': str(self.surname), 'name': str(self.name), 'gender': str(self.gender), 'year': str(self.year), 'country': str(self.country), 'town': str(self.town), 'family': str(self.family), 'children': str(self.children) } def to_str_list(self): return [ str(self.id), str(self.series), str(self.number), str(self.surname), str(self.name), str(self.gender), str(self.year), str(self.country), str(self.town), str(self.family), str(self.children)] def to_tuple(self): return ( ('id', self.id), ('series', self.series), ('number', self.number), ('surname', self.surname), ('name', self.name), ('gender', self.gender), ('year', self.year), ('country', self.country), ('town', self.town), ('family', self.family), ('children', self.children)) def to_order_dict(self): return collections.OrderedDict(self.to_tuple()) class Generator: @staticmethod def create_peoples_list(count): return [People() for _ in range(0, int(count))] @staticmethod def peoples_to_txt(file, count): for _ in range(0, count): file.write(str(People()) + '\r\n') @staticmethod def peoples_to_csv(file, count): writer = csv.writer(file) for _ in range(0, count): writer.writerow(People().to_str_list()) @staticmethod def peoples_to_xml(file, count): def xml_etree(): root = xml.etree.ElementTree.Element('peoples') for _ in range(0, count): people = People() element = xml.etree.ElementTree.Element('people') idp = xml.etree.ElementTree.SubElement(element, 'id') idp.text = str(people.id) series = xml.etree.ElementTree.SubElement(element, 'series') series.text = str(people.series) number = xml.etree.ElementTree.SubElement(element, 'number') number.text = str(people.number) surname = xml.etree.ElementTree.SubElement(element, 'surname') surname.text = str(people.surname) name = xml.etree.ElementTree.SubElement(element, 'name') name.text = str(people.name) gender = xml.etree.ElementTree.SubElement(element, 'gender') gender.text = str(people.gender) year = xml.etree.ElementTree.SubElement(element, 'year') year.text = str(people.year) country = xml.etree.ElementTree.SubElement(element, 'country') country.text = str(people.country) town = xml.etree.ElementTree.SubElement(element, 'town') town.text = str(people.town) family = xml.etree.ElementTree.SubElement(element, 'family') family.text = str(people.family) children = xml.etree.ElementTree.SubElement(element, 'children') children.text = str(people.children) root.append(element) tree = xml.etree.ElementTree.ElementTree(root) try: tree.write(file, 'UTF-8', xml_declaration=True, method='xml') except EnvironmentError: pass def xml_dom(): dom = xml.dom.minidom.getDOMImplementation() tree = dom.createDocument(None, 'peoples', None) root = tree.documentElement for _ in range(0, count): people = People() element = tree.createElement('people') for name, text in people.to_tuple(): name_elem = tree.createElement(name) name_elem.appendChild(tree.createTextNode(str(text))) element.appendChild(name_elem) root.appendChild(element) try: # tree.writexml(file, encoding='UTF-8', indent="\t", newl='\n') file.write(tree.toprettyxml()) except EnvironmentError: pass xml_dom() @staticmethod def peoples_to_json(file, count): for _ in range(0, count): # json.dump(People().to_dict(), fp=file, indent='\t') file.write(json.dumps(People().to_order_dict(), indent='\t')) file.write('\n') <file_sep>import os import shutil path = r'D:\\Downloads' extensions = ['.txt', '.nfo', '.jpg', '.jpeg', '.png'] for root, dirs, files in os.walk(path): if root == path: continue for file in files: flag = True for extension in extensions: if extension in file: flag = False if flag: f = os.path.join(root, file) try: shutil.move(f, path) except shutil.Error as error: print(error) else: print(file) input() <file_sep>DELETE FROM names; DELETE FROM surnames; DELETE FROM towns; <file_sep>import os from getpass import getuser path = 'c:\\Users\\%User%\\Downloads\\' user = getuser() path = path.replace('%User%', user) for file in os.listdir(path): if '.torrent' in file: # if re.search(r'[.]torrent$', file): file_path = os.path.join(path, file) if os.path.isfile(file_path): os.unlink(file_path) <file_sep>from subprocess import check_output from sys import platform def decode(output: bytes) -> str: if output: if platform == 'win32': return output.decode('cp866') else: return output.decode() if platform == 'win32': cmd = {'show': 'netsh wlan show hostednetwork', 'start': 'netsh wlan start hostednetwork', 'set': 'netsh wlan set hostednetwork mode=allow ssid=WiFi key=qweasd123', 'stop': 'netsh wlan stop hostednetwork'} out = decode(check_output(cmd['show'])) if 'Не запущено' in out: print(decode(check_output(cmd['set']))) print(decode(check_output(cmd['start']))) else: print(decode(check_output(cmd['stop']))) <file_sep>import subprocess cmd = ['C:\Program Files (x86)\Google\Chrome\Application\chrome.exe', '-incognito', 'google.ru', 'live.com', 'yandex.ru' ] subprocess.Popen(' '.join(cmd)) <file_sep>__author__ = 'npzxc' from databasegen.database_gen import * <file_sep>from tkinter import * root = Tk() def hello(event): print("Yet another hello world") print(event.widget._name) btn = Button(root, name="11a", text="Click me", width=15, height=5, bg="white") btn.bind("<Button-1>", hello) btn.pack() root.mainloop() <file_sep>from subprocess import call, check_output from sys import platform def decode(output: bytes) -> str: if output: if platform == 'win32': return output.decode('cp866') else: return output.decode() if platform == 'win32': cmd = {'start': ['powershell', r'start-process powershell -ArgumentList "NET start postgresql-x64-9.4" -verb runAs'], 'stop': ['powershell', r'start-process powershell -ArgumentList "NET stop postgresql-x64-9.4" -verb runAs'], 'show': 'NET START'} out = decode(check_output(cmd['show'])) if 'postgresql-x64-9.4' in out: call(cmd['stop']) else: call(cmd['start']) <file_sep>import multiprocessing def writer(x, event_for_wait, event_for_set): i = 0 while True: event_for_wait.wait() # wait for event event_for_wait.clear() # clean event for future print(x) event_for_set.set() # set event for neighbor thread if i == 3000: break i += 1 if __name__ == '__main__': # init events e1 = multiprocessing.Event() e2 = multiprocessing.Event() e3 = multiprocessing.Event() # init threads t1 = multiprocessing.Process(target=writer, args=(0, e1, e2)) t2 = multiprocessing.Process(target=writer, args=(1, e2, e3)) t3 = multiprocessing.Process(target=writer, args=(2, e3, e1)) # start threads t1.start() t2.start() t3.start() e1.set() # initiate the first event # join threads to the main thread t1.join() t2.join() t3.join() <file_sep>import random import time from tkinter import * def create_ovals(): colors = ['aqua', 'blue', 'fuchsia', 'green', 'maroon', 'orange', 'pink', 'purple', 'red', 'yellow', 'violet', 'indigo', 'chartreuse', 'lime', '#f55c4b'] size = 600 count = 0 try: root = Tk() root.title('You win') canvas = Canvas(root, width=size, height=size) canvas.pack() while True: color = random.choice(colors) x0 = random.randint(0, size) y0 = random.randint(0, size) d = random.randint(0, size / 5) canvas.create_oval(x0, y0, x0 + d, y0 + d, fill=color) root.update() if count > 1000: time.sleep(0.01) count += 1 except TclError: pass create_ovals() <file_sep>from tkinter import * root = Tk() fra1 = Frame(root, width=500, height=100, bg="darkred") fra2 = Frame(root, width=300, height=200, bg="green", bd=20) fra3 = Frame(root, width=150, height=150, bg="darkblue") fra1.pack() fra2.pack() fra3.pack() root.mainloop() <file_sep>import mysql file_names = { 'nm': 'txt\\names_male.txt', 'nf': 'txt\\names_female.txt', 'su': 'txt\\surnames.txt', 'te': 'txt\\towns_england.txt', 'tu': 'txt\\towns_usa.txt', 'tc': 'txt\\towns_canada.txt' } try: con = mysql.connector.connect(host='localhost', database='dbgen', user='root', password='<PASSWORD>') if con.is_connected(): cur = con.cursor() for l in zip(open(file_names['nm']), open(file_names['nf'])): cur.execute( 'INSERT INTO dbgen_name (male, female) VALUES ("{0}", "{1}")'.format(l[0].rstrip(), l[1].rstrip())) con.commit() for l in open(file_names['su']): cur.execute('INSERT INTO dbgen_surname (surname) VALUES ("{0}")'.format(l.rstrip())) con.commit() for l in zip(open(file_names['te']), open(file_names['tu']), open(file_names['tc'])): cur.execute( 'INSERT INTO dbgen_town (england, usa, canada) VALUES ("{0}", "{1}", "{2}")'.format(l[0].rstrip(), l[1].rstrip(), l[2].rstrip())) con.commit() except Exception as e: print(e) finally: con.close() <file_sep>from tkinter import * root = Tk() frame1 = Frame(root, width=100, heigh=100, bg='green', bd=5) frame2 = Frame(root, width=150, heigh=75, bg='red', bd=5) button1 = Button(frame1, text=u'Первая кнопка') button2 = Button(frame2, text=u'Вторая кнопка') frame1.pack() frame2.pack() button1.pack() button2.pack() root.mainloop() <file_sep>import subprocess import time cmd = r'C:\Program Files (x86)\Mozilla Firefox\firefox -private-window ' cmds = ['google.ru', 'live.com', 'yandex.ru' ] subprocess.Popen(cmd + cmds[0]) time.sleep(1.5) for c in cmds[1:]: subprocess.Popen(cmd + c) <file_sep>from tkinter import * import random import time DIFFICULT_EASY = 'Easy' DIFFICULT_NORMAL = 'Normal' DIFFICULT_HARD = 'Hard' class Point: def __init__(self, x, y, btn): self.x = x self.y = y self.bomb = False self.near = 0 self.btn = btn self.flag = False self.check = False class Sapper: def __init__(self): self.difficult = DIFFICULT_EASY self.__game = None self.__root = Tk() self.__root.title('Sapper') menu = Menu(self.__root) self.__root.config(menu=menu) sapper_menu = Menu(menu) menu.add_cascade(label='Sapper', menu=sapper_menu) sapper_menu.add_command(label="Exit", command=self.__root.quit) game_menu = Menu(menu) menu.add_cascade(label='Game', menu=game_menu) game_menu.add_command(label='New game', command=self.__new_game) difficult_menu = Menu(game_menu) game_menu.add_cascade(label='Difficult', menu=difficult_menu) difficult_menu.add_command(label=DIFFICULT_EASY, command=self.__new_game_beginner) difficult_menu.add_command(label=DIFFICULT_NORMAL, command=self.__new_game_experienced) difficult_menu.add_command(label=DIFFICULT_HARD, command=self.__new_game_expert) self.__new_game_beginner() self.__root.mainloop() def __new_game(self): if self.__game: self.__game.end() self.__game = Game(self.difficult, self.__root) self.__game.start() def __new_game_beginner(self): self.difficult = DIFFICULT_EASY self.__new_game() def __new_game_experienced(self): self.difficult = DIFFICULT_NORMAL self.__new_game() def __new_game_expert(self): self.difficult = DIFFICULT_HARD self.__new_game() class Game: def __init__(self, difficult, root): assert isinstance(difficult, str) if difficult == DIFFICULT_EASY: self.__bombs = 10 self.__width = 9 self.__height = 9 elif difficult == DIFFICULT_NORMAL: self.__bombs = 40 self.__width = 16 self.__height = 16 elif difficult == DIFFICULT_HARD: self.__bombs = 99 self.__width = 16 self.__height = 30 self.__all = self.__width * self.__height self.__free = self.__all - self.__bombs self.__check = 0 self.__grid = list() self.__first = True self.__game = True self.__flags = 0 self.__max_flags = self.__bombs self.__root = root self.__game_frame = Frame(self.__root) self.__info_frame = Frame(self.__root) self.__lbl_free = Label(self.__info_frame, text=self.__free, font='Arial 15') self.__lbl_free.grid(row=0, column=0) self.__lbl_time = Label(self.__info_frame, text="", font='Arial 15') self.__lbl_time.grid(row=0, column=1) self.__lbl_flags = Label(self.__info_frame, text=self.__bombs, font='Arial 15') self.__lbl_flags.grid(row=0, column=2) self.__info_frame.pack(fill='both') self.__info_frame.columnconfigure(0, weight=1) self.__info_frame.columnconfigure(1, weight=1) self.__info_frame.columnconfigure(2, weight=1) self.__start_time = time.time() self.__update_clock() def start(self): for x in range(0, self.__width): self.__grid.append([]) for y in range(0, self.__height): btn = Button(self.__game_frame, name='{0} {1}'.format(x, y), width=2, height=1, bg='grey') btn.bind("<Button-1>", self.__btn1_click) btn.bind("<Button-3>", self.__btn2_click) self.__grid[x].append(Point(x, y, btn)) btn.grid(row=x, column=y) self.__game_frame.pack() self.__root.mainloop() def end(self): self.__game_frame.destroy() self.__info_frame.destroy() def __btn1_click(self, event): if self.__game: name = event.widget._name.split(sep=' ') x = int(name[0]) y = int(name[1]) if self.__first: self.__first_click(x, y) self.__first = False if self.__grid[x][y].bomb: for i in range(0, self.__width): for j in range(0, self.__height): self.__grid[i][j].btn['state'] = 'disabled' if self.__grid[i][j].bomb: self.__grid[i][j].btn['text'] = '*' self.__grid[i][j].btn['background'] = 'red' else: self.__grid[i][j].btn['background'] = 'white' self.__game = False else: queue = list() queue.append((x, y)) while len(queue) > 0: xx = queue[0][0] yy = queue[0][1] if self.__grid[xx][yy].near == 0: if xx != 0: if not self.__grid[xx - 1][yy].check: if not self.__grid[xx - 1][yy].bomb: queue.append((xx - 1, yy)) if yy != 0: if not self.__grid[xx][yy - 1].check: if not self.__grid[xx][yy - 1].bomb: queue.append((xx, yy - 1)) if xx != self.__width - 1: if not self.__grid[xx + 1][yy].check: if not self.__grid[xx + 1][yy].bomb: queue.append((xx + 1, yy)) if yy != self.__height - 1: if not self.__grid[xx][yy + 1].check: if not self.__grid[xx][yy + 1].bomb: queue.append((xx, yy + 1)) if self.__grid[xx][yy].near > 0: self.__grid[xx][yy].btn['text'] = self.__grid[xx][yy].near self.__grid[xx][yy].btn['background'] = 'white' self.__grid[xx][yy].btn['state'] = 'disabled' if not self.__grid[xx][yy].check: self.__grid[xx][yy].check = True if (self.__free - 1) != self.__check: self.__check += 1 else: self.__game = False Game.__win() self.__lbl_free['text'] = self.__free - self.__check queue.pop(0) def __btn2_click(self, event): if self.__game: name = event.widget._name.split(sep=' ') x = int(name[0]) y = int(name[1]) if self.__max_flags > 0: if not self.__grid[x][y].flag: self.__grid[x][y].flag = True self.__grid[x][y].btn['text'] = 'f' self.__flags += 1 self.__max_flags -= 1 self.__lbl_free['text'] = self.__free - self.__check self.__lbl_flags['text'] = self.__max_flags else: self.__grid[x][y].flag = False self.__grid[x][y].btn['text'] = '' self.__flags -= 1 self.__max_flags += 1 self.__lbl_free['text'] = self.__free - self.__check self.__lbl_flags['text'] = self.__max_flags def __first_click(self, x, y): bombs = self.__bombs while bombs > 0: xr = random.randint(0, self.__width - 1) yr = random.randint(0, self.__height - 1) if (not self.__grid[xr][yr].bomb) and (x != xr or y != yr): self.__grid[xr][yr].bomb = True # self.__grid[xr][yr].btn['text'] = '*' bombs -= 1 for i in range(0, self.__width): for j in range(0, self.__height): if self.__grid[i][j].bomb: continue if i != 0: if self.__grid[i - 1][j].bomb: self.__grid[i][j].near += 1 if j != 0: if self.__grid[i][j - 1].bomb: self.__grid[i][j].near += 1 if i != 0 and j != 0: if self.__grid[i - 1][j - 1].bomb: self.__grid[i][j].near += 1 if i != self.__width - 1: if self.__grid[i + 1][j].bomb: self.__grid[i][j].near += 1 if j != self.__height - 1: if self.__grid[i][j + 1].bomb: self.__grid[i][j].near += 1 if i != self.__width - 1 and j != self.__height - 1: if self.__grid[i + 1][j + 1].bomb: self.__grid[i][j].near += 1 if i != 0 and j != self.__height - 1: if self.__grid[i - 1][j + 1].bomb: self.__grid[i][j].near += 1 if i != self.__width - 1 and j != 0: if self.__grid[i + 1][j - 1].bomb: self.__grid[i][j].near += 1 def __update_clock(self): if self.__game: try: self.__lbl_time.configure(text=int(time.time() - self.__start_time)) self.__root.after(1000, self.__update_clock) except Exception: pass @staticmethod def __win(): colors = ['aqua', 'blue', 'fuchsia', 'green', 'maroon', 'orange', 'pink', 'purple', 'red', 'yellow', 'violet', 'indigo', 'chartreuse', 'lime', '#f55c4b'] size = 600 count = 0 try: root = Tk() root.title('You win') canvas = Canvas(root, width=size, height=size) canvas.pack() while True: color = random.choice(colors) x0 = random.randint(0, size) y0 = random.randint(0, size) d = random.randint(0, size / 5) canvas.create_oval(x0, y0, x0 + d, y0 + d, fill=color) root.update() if count > 1000: time.sleep(0.01) count += 1 except TclError: pass if __name__ == '__main__': Sapper() <file_sep>import sqlite3 file_names = { 'nm': 'txt\\names_male.txt', 'nf': 'txt\\names_female.txt', 'su': 'txt\\surnames.txt', 'te': 'txt\\towns_england.txt', 'tu': 'txt\\towns_usa.txt', 'tc': 'txt\\towns_canada.txt' } con = sqlite3.connect('db.sqlite3') cur = con.cursor() for l in zip(open(file_names['nm']), open(file_names['nf'])): cur.execute('INSERT INTO names (male, female) VALUES ("{0}", "{1}")'.format(l[0].rstrip(), l[1].rstrip())) con.commit() for l in open(file_names['su']): cur.execute('INSERT INTO surnames (surname) VALUES ("{0}")'.format(l.rstrip())) con.commit() for l in zip(open(file_names['te']), open(file_names['tu']), open(file_names['tc'])): cur.execute('INSERT INTO towns (england, usa, canada) VALUES ("{0}", "{1}", "{2}")' .format(l[0].rstrip(), l[1].rstrip(), l[2].rstrip())) con.commit() con.close()
11ea61d7109ced44f1642dcbafd4c47453823d43
[ "SQL", "Python" ]
20
SQL
npzxcf/Python
7f64aa1763a57e9381249425ce6838f6389f3333
699e641c733284582a17a8fc286c97b4b5ad3cc3
refs/heads/master
<file_sep><!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <script src="blog.js"> </script> <link rel="stylesheet" type="text/css" href="blog.css" /> <title>BlogBuddy</title> </head> <body> <h2>BlogBuddy</h2> <?php $title = $_POST ['postTitle']; $category = $_POST ['postCategory']; $text = htmlspecialchars ( $_POST ['textArea'] ); $subject = "New Blog Post: $title from the category $category"; $dbc = mysqli_connect ( 'localhost', 'root', '', 'blogbuddy' ) or die ( 'Error connecting to MySQL server.' ); if (isset ( $_POST ['post'] )) { $query = "SELECT * FROM subscriptions"; $result = mysqli_query ( $dbc, $query ) or die ( 'QUERY Error' ); while ( $row = mysqli_fetch_array ( $result ) ) { $to = $row ['email']; $name = $row ['name']; $msg = "Hi $name! Here is a new blog post: \n" . $text; email ( $to, $subject, $msg ); echo 'Email sent to: ' . $to . '<br />'; } // echo (time ()); $query = "INSERT INTO posts VALUES(CURRENT_TIMESTAMP, '$category', '$title', '$text')"; $result = mysqli_query ( $dbc, $query ) or die ( 'QUERY Error' ); } else if (isset ( $_POST ['share'] )) { $to = $_POST ['toEmail']; $from = $_POST ['fromEmail']; $msg = "Hi $to! Here is a new blog post that $from has shared with you: \n" . $text; email ( $to, $subject, $msg ); } else if (isset ( $_POST ['subscribe'] )) { $name = $_POST ['subName']; $email = $_POST ['subEmail']; $query = "INSERT INTO subscriptions VALUES('$name', '$email')"; $result = mysqli_query ( $dbc, $query ) or die ( 'QUERY Error' ); } mysqli_close ( $dbc ); function email($to, $subject, $msg) { // Deployment environment! // mail($to, $subject, $msg); // Development environment only! require_once 'phpmailer-master/phpmailerautoload.php'; $mail = new PHPMailer (); $mail->isSMTP (); $mail->SMTPSecure = 'tls'; $mail->SMTPAuth = true; $mail->Host = 'smtp.gmail.com'; $mail->Port = 587; $mail->Username = '<EMAIL>'; $mail->Password = '<PASSWORD>'; $mail->setFrom ( '<EMAIL>' ); $mail->addAddress ( $to ); $mail->Subject = $subject; $mail->Body = $msg; // send the message, check for errors if (! $mail->send ()) { echo "ERROR: " . $mail->ErrorInfo; } else { echo "SUCCESS"; } } ?> </body> </html><file_sep><!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <script src="blog.js"> </script> <link rel="stylesheet" type="text/css" href="blog.css" /> <title>BlogBuddy</title> </head> <body> <h2>BlogBuddy</h2> <?php $dom = new DOMDocument (); $title = $_POST ['postTitle']; $category = $_POST ['postCategory']; $dbc = mysqli_connect ( 'localhost', 'root', '', 'blogbuddy' ) or die ( 'Error connecting to MySQL server.' ); $query = "SELECT content FROM posts WHERE category='$category' AND title='$title'"; echo ($query); $result = mysqli_query ( $dbc, $query ) or die ( 'QUERY Error' ); $row = mysqli_fetch_array ( $result ); $content = $row ['content']; echo ($content); mysqli_close ( $dbc ); // $dom->getElementsByTagName('textarea'); ?> </body> </html><file_sep># BlogBuddy test
cc2f84f13cad3cc45ff00c961f6892190d4f6dff
[ "Markdown", "PHP" ]
3
PHP
deucydeuces/BlogBuddy
3a998b8165648f013f2e111b9f75d22fe9ef44c5
f924d37ecf613b6a66bbc9c66a5f4c0e09227ee3
refs/heads/main
<repo_name>devankestel/snowball<file_sep>/parse_cc_report.py from matplotlib import pyplot as plt import numpy as np # Using readlines() file1 = open('django_current_cc.md', 'r') Lines = file1.readlines() count = 0 # Strips the newline character report_dict = {} # {'filename': {'block_name': [block_type, num_lines, letter_grade, score]}} score_list = [] for line in Lines: count += 1 # print("Line{}: {}".format(count, line.strip())) line = line.strip() if line.startswith('django/'): filename = line report_dict[filename] = {} elif line.startswith('M') or line.startswith('C') or line.startswith('F'): # block_type, num_lines, letter_grade, score = line print(line) [block_type, line_info, block_name, dash, letter_grade, score_info] = line.split() num_lines = int(line_info[-1]) score = int(score_info[1:-1]) report_dict[filename][block_name] = [block_type, num_lines, letter_grade, score] score_list.append(score) else: continue scores = np.array(score_list) print(scores.max()) print(scores.min()) print(np.median(scores)) print(scores.mean()) print(scores.std()) # divide each score by total number of blocks to get percentage based histogram hist, bins = np.histogram(scores,bins = [0,5,10,15,20,25, 30, 35, 40, 45, 50, 55, 60, 65, 70, 75, 80, 85, 90, 95, 100]) print(hist) print(bins) plt.hist(scores, bins = bins) plt.title("histogram") plt.show() <file_sep>/commands.md git log > ../monolith_quality_history/git_log.md grep ^commit git_log.md > shas.md grep ^Date git_log.md > dates.md grep -rl 'Date: ' dates.md | xargs sed -i '' 's/Date: //g' grep -rl 'commit ' shas.md | xargs sed -i '' 's/commit //g' paste dates.md shas.md | column -s $'\t' -t > commits.md <file_sep>/django_current_cc.md django/shortcuts.py F 102:0 resolve_url - B (9) F 57:0 get_object_or_404 - A (4) F 81:0 get_list_or_404 - A (4) F 23:0 redirect - A (2) F 44:0 _get_queryset - A (2) F 14:0 render - A (1) django/__init__.py F 8:0 setup - A (3) django/templatetags/l10n.py F 42:0 localize_tag - A (4) C 25:0 LocalizeNode - A (2) F 8:0 localize - A (1) F 17:0 unlocalize - A (1) M 26:4 LocalizeNode.__init__ - A (1) M 30:4 LocalizeNode.__repr__ - A (1) M 33:4 LocalizeNode.render - A (1) django/templatetags/tz.py F 38:0 do_timezone - B (7) F 126:0 localtime_tag - A (4) F 174:0 get_current_timezone_tag - A (3) F 149:0 timezone_tag - A (2) C 83:0 LocalTimeNode - A (2) C 99:0 TimezoneNode - A (2) C 113:0 GetCurrentTimezoneNode - A (2) F 20:0 localtime - A (1) F 30:0 utc - A (1) C 13:0 datetimeobject - A (1) M 87:4 LocalTimeNode.__init__ - A (1) M 91:4 LocalTimeNode.render - A (1) M 103:4 TimezoneNode.__init__ - A (1) M 107:4 TimezoneNode.render - A (1) M 117:4 GetCurrentTimezoneNode.__init__ - A (1) M 120:4 GetCurrentTimezoneNode.render - A (1) django/templatetags/cache.py M 18:4 CacheNode.render - B (10) C 10:0 CacheNode - B (7) F 53:0 do_cache - A (5) M 11:4 CacheNode.__init__ - A (1) django/templatetags/static.py M 24:4 PrefixNode.handle_token - A (4) M 123:4 StaticNode.handle_token - A (4) C 11:0 PrefixNode - A (3) M 40:4 PrefixNode.handle_simple - A (3) C 93:0 StaticNode - A (3) M 105:4 StaticNode.render - A (3) M 16:4 PrefixNode.__init__ - A (2) M 49:4 PrefixNode.render - A (2) M 94:4 StaticNode.__init__ - A (2) M 115:4 StaticNode.handle_simple - A (2) F 58:0 get_static_prefix - A (1) F 76:0 get_media_prefix - A (1) F 144:0 do_static - A (1) F 162:0 static - A (1) M 13:4 PrefixNode.__repr__ - A (1) M 101:4 StaticNode.url - A (1) django/templatetags/i18n.py F 421:0 do_block_translate - D (22) M 129:4 BlockTranslateNode.render - C (13) F 327:0 do_translate - B (10) C 100:0 BlockTranslateNode - B (7) M 115:4 BlockTranslateNode.render_token_list - A (5) F 220:0 do_get_language_info - A (4) F 241:0 do_get_language_info_list - A (4) C 70:0 TranslateNode - A (4) M 81:4 TranslateNode.render - A (4) F 199:0 do_get_available_languages - A (3) F 287:0 do_get_current_language - A (3) F 306:0 do_get_current_language_bidi - A (3) C 13:0 GetAvailableLanguagesNode - A (3) C 33:0 GetLanguageInfoListNode - A (3) F 544:0 language - A (2) M 17:4 GetAvailableLanguagesNode.render - A (2) C 22:0 GetLanguageInfoNode - A (2) M 38:4 GetLanguageInfoListNode.get_language_info - A (2) M 46:4 GetLanguageInfoListNode.render - A (2) C 52:0 GetCurrentLanguageNode - A (2) C 61:0 GetCurrentLanguageBidiNode - A (2) M 71:4 TranslateNode.__init__ - A (2) C 187:0 LanguageNode - A (2) F 266:0 language_name - A (1) F 271:0 language_name_translated - A (1) F 277:0 language_name_local - A (1) F 282:0 language_bidi - A (1) M 14:4 GetAvailableLanguagesNode.__init__ - A (1) M 23:4 GetLanguageInfoNode.__init__ - A (1) M 27:4 GetLanguageInfoNode.render - A (1) M 34:4 GetLanguageInfoListNode.__init__ - A (1) M 53:4 GetCurrentLanguageNode.__init__ - A (1) M 56:4 GetCurrentLanguageNode.render - A (1) M 62:4 GetCurrentLanguageBidiNode.__init__ - A (1) M 65:4 GetCurrentLanguageBidiNode.render - A (1) M 102:4 BlockTranslateNode.__init__ - A (1) M 188:4 LanguageNode.__init__ - A (1) M 192:4 LanguageNode.render - A (1) django/middleware/clickjacking.py C 12:0 XFrameOptionsMiddleware - A (3) M 24:4 XFrameOptionsMiddleware.process_response - A (3) M 39:4 XFrameOptionsMiddleware.get_xframe_options_value - A (1) django/middleware/gzip.py C 9:0 GZipMiddleware - B (10) M 15:4 GZipMiddleware.process_response - B (9) django/middleware/csrf.py M 205:4 CsrfViewMiddleware.process_view - D (21) C 131:0 CsrfViewMiddleware - B (6) M 158:4 CsrfViewMiddleware._get_token - A (5) F 45:0 _mask_cipher_secret - A (4) F 57:0 _unmask_cipher_token - A (4) F 105:0 _sanitize_token - A (4) M 317:4 CsrfViewMiddleware.process_response - A (4) M 181:4 CsrfViewMiddleware._set_token - A (3) F 74:0 get_token - A (2) M 199:4 CsrfViewMiddleware.process_request - A (2) F 36:0 _get_failure_view - A (1) F 41:0 _get_new_csrf_string - A (1) F 70:0 _get_new_csrf_token - A (1) F 93:0 rotate_token - A (1) F 122:0 _compare_masked_tokens - A (1) M 141:4 CsrfViewMiddleware._accept - A (1) M 148:4 CsrfViewMiddleware._reject - A (1) django/middleware/security.py M 31:4 SecurityMiddleware.process_response - C (11) C 8:0 SecurityMiddleware - B (7) M 21:4 SecurityMiddleware.process_request - B (6) M 9:4 SecurityMiddleware.__init__ - A (2) django/middleware/cache.py M 75:4 UpdateCacheMiddleware.process_response - C (15) C 55:0 UpdateCacheMiddleware - B (7) C 160:0 CacheMiddleware - B (7) M 131:4 FetchFromCacheMiddleware.process_request - B (6) M 167:4 CacheMiddleware.__init__ - B (6) C 117:0 FetchFromCacheMiddleware - A (5) M 72:4 UpdateCacheMiddleware._should_update_cache - A (2) M 64:4 UpdateCacheMiddleware.__init__ - A (1) M 125:4 FetchFromCacheMiddleware.__init__ - A (1) django/middleware/common.py M 34:4 CommonMiddleware.process_request - B (10) M 149:4 BrokenLinkEmailsMiddleware.is_ignorable_request - B (10) C 13:0 CommonMiddleware - B (7) C 118:0 BrokenLinkEmailsMiddleware - B (6) M 63:4 CommonMiddleware.should_redirect_with_slash - A (5) M 100:4 CommonMiddleware.process_response - A (5) M 120:4 BrokenLinkEmailsMiddleware.process_response - A (5) M 77:4 CommonMiddleware.get_full_path_with_slash - A (3) M 141:4 BrokenLinkEmailsMiddleware.is_internal_request - A (1) django/middleware/http.py M 14:4 ConditionalGetMiddleware.process_response - B (7) C 8:0 ConditionalGetMiddleware - B (6) M 38:4 ConditionalGetMiddleware.needs_etag - A (2) django/middleware/locale.py M 28:4 LocaleMiddleware.process_response - C (12) C 10:0 LocaleMiddleware - B (9) M 18:4 LocaleMiddleware.process_request - A (4) django/forms/models.py F 112:0 fields_for_model - E (35) M 686:4 BaseModelFormSet.validate_unique - D (26) F 997:0 _get_foreign_key - C (16) C 214:0 ModelFormMetaclass - C (16) M 215:4 ModelFormMetaclass.__new__ - C (15) F 30:0 construct_instance - C (14) F 481:0 modelform_factory - C (13) M 316:4 BaseModelForm._get_validation_exclusions - C (11) M 601:4 BaseModelFormSet._construct_form - C (11) M 361:4 BaseModelForm._update_errors - B (10) M 822:4 BaseModelFormSet.add_fields - B (9) M 430:4 BaseModelForm._save_m2m - B (8) M 1341:4 ModelMultipleChoiceField._check_values - B (8) F 71:0 model_to_dict - B (7) C 286:0 BaseModelForm - B (7) M 782:4 BaseModelFormSet.save_existing_objects - B (7) M 899:4 BaseInlineFormSet.__init__ - B (7) M 1386:4 ModelMultipleChoiceField.has_changed - B (7) M 389:4 BaseModelForm._post_clean - B (6) M 808:4 BaseModelFormSet.save_new_objects - B (6) M 961:4 BaseInlineFormSet.add_fields - B (6) C 1305:0 ModelMultipleChoiceField - B (6) M 1324:4 ModelMultipleChoiceField.clean - B (6) F 96:0 apply_limit_choices_to_to_formfield - A (5) M 287:4 BaseModelForm.__init__ - A (5) C 566:0 BaseModelFormSet - A (5) M 927:4 BaseInlineFormSet._construct_form - A (5) M 1122:4 InlineForeignKeyField.clean - A (5) M 1196:4 ModelChoiceField.__init__ - A (5) M 1278:4 ModelChoiceField.to_python - A (5) M 1378:4 ModelMultipleChoiceField.prepare_value - A (5) M 451:4 BaseModelForm.save - A (4) M 635:4 BaseModelFormSet.get_queryset - A (4) C 897:0 BaseInlineFormSet - A (4) C 1100:0 InlineForeignKeyField - A (4) M 1160:4 ModelChoiceIterator.__iter__ - A (4) M 1297:4 ModelChoiceField.has_changed - A (4) F 866:0 modelformset_factory - A (3) F 1400:0 modelform_defines_fields - A (3) M 587:4 BaseModelFormSet._existing_object - A (3) M 992:4 BaseInlineFormSet.get_unique_error_message - A (3) M 1110:4 InlineForeignKeyField.__init__ - A (3) C 1155:0 ModelChoiceIterator - A (3) C 1186:0 ModelChoiceField - A (3) M 1270:4 ModelChoiceField.prepare_value - A (3) F 1053:0 inlineformset_factory - A (2) C 201:0 ModelFormOptions - A (2) M 419:4 BaseModelForm.validate_unique - A (2) M 581:4 BaseModelFormSet.initial_form_count - A (2) M 592:4 BaseModelFormSet._get_to_python - A (2) M 662:4 BaseModelFormSet.delete_existing - A (2) M 667:4 BaseModelFormSet.save - A (2) M 759:4 BaseModelFormSet.get_unique_error_message - A (2) M 922:4 BaseInlineFormSet.initial_form_count - A (2) C 1141:0 ModelChoiceIteratorValue - A (2) M 1149:4 ModelChoiceIteratorValue.__eq__ - A (2) M 1170:4 ModelChoiceIterator.__len__ - A (2) M 1176:4 ModelChoiceIterator.__bool__ - A (2) M 1217:4 ModelChoiceField.get_limit_choices_to - A (2) M 1227:4 ModelChoiceField.__deepcopy__ - A (2) M 1237:4 ModelChoiceField._set_queryset - A (2) M 1253:4 ModelChoiceField._get_choices - A (2) M 1319:4 ModelMultipleChoiceField.to_python - A (2) M 202:4 ModelFormOptions.__init__ - A (1) M 357:4 BaseModelForm.clean - A (1) C 477:0 ModelForm - A (1) M 575:4 BaseModelFormSet.__init__ - A (1) M 654:4 BaseModelFormSet.save_new - A (1) M 658:4 BaseModelFormSet.save_existing - A (1) M 683:4 BaseModelFormSet.clean - A (1) M 769:4 BaseModelFormSet.get_date_error_message - A (1) M 779:4 BaseModelFormSet.get_form_error - A (1) M 951:4 BaseInlineFormSet.get_default_prefix - A (1) M 954:4 BaseInlineFormSet.save_new - A (1) M 1137:4 InlineForeignKeyField.has_changed - A (1) M 1142:4 ModelChoiceIteratorValue.__init__ - A (1) M 1146:4 ModelChoiceIteratorValue.__str__ - A (1) M 1156:4 ModelChoiceIterator.__init__ - A (1) M 1179:4 ModelChoiceIterator.choice - A (1) M 1234:4 ModelChoiceField._get_queryset - A (1) M 1245:4 ModelChoiceField.label_from_instance - A (1) M 1294:4 ModelChoiceField.validate - A (1) M 1316:4 ModelMultipleChoiceField.__init__ - A (1) django/forms/fields.py C 1083:0 FilePathField - D (23) M 1084:4 FilePathField.__init__ - D (22) M 1000:4 MultiValueField.clean - D (21) M 552:4 FileField.to_python - B (8) M 811:4 ChoiceField.valid_value - B (8) M 1065:4 MultiValueField.has_changed - B (8) M 58:4 Field.__init__ - B (7) M 130:4 Field.run_validators - B (7) M 610:4 ImageField.to_python - B (7) M 881:4 MultipleChoiceField.has_changed - B (7) C 955:0 MultiValueField - B (7) M 175:4 Field.has_changed - B (6) M 450:4 DateTimeField.to_python - B (6) M 573:4 FileField.clean - B (6) C 601:0 ImageField - B (6) C 853:0 MultipleChoiceField - B (6) M 1229:4 JSONField.to_python - B (6) C 210:0 CharField - A (5) M 233:4 CharField.widget_attrs - A (5) C 244:0 IntegerField - A (5) M 251:4 IntegerField.__init__ - A (5) C 474:0 DurationField - A (5) M 485:4 DurationField.to_python - A (5) C 534:0 FileField - A (5) M 868:4 MultipleChoiceField.validate - A (5) M 901:4 TypedMultipleChoiceField._coerce - A (5) M 223:4 CharField.to_python - A (4) M 263:4 IntegerField.to_python - A (4) M 280:4 IntegerField.widget_attrs - A (4) C 290:0 FloatField - A (4) M 295:4 FloatField.to_python - A (4) C 325:0 DecimalField - A (4) M 335:4 DecimalField.to_python - A (4) M 352:4 DecimalField.widget_attrs - A (4) C 386:0 DateField - A (4) M 393:4 DateField.to_python - A (4) C 438:0 DateTimeField - A (4) M 514:4 RegexField._set_regex - A (4) C 660:0 URLField - A (4) M 670:4 URLField.to_python - A (4) C 702:0 BooleanField - A (4) M 832:4 TypedChoiceField._coerce - A (4) M 861:4 MultipleChoiceField.to_python - A (4) M 977:4 MultiValueField.__init__ - A (4) C 1127:0 SplitDateTimeField - A (4) M 1150:4 SplitDateTimeField.compress - A (4) C 1163:0 GenericIPAddressField - A (4) M 1169:4 GenericIPAddressField.to_python - A (4) C 1188:0 UUIDField - A (4) M 1198:4 UUIDField.to_python - A (4) C 1218:0 JSONField - A (4) C 47:0 Field - A (3) M 126:4 Field.validate - A (3) M 211:4 CharField.__init__ - A (3) M 311:4 FloatField.validate - A (3) M 318:4 FloatField.widget_attrs - A (3) C 365:0 BaseTemporalField - A (3) M 372:4 BaseTemporalField.to_python - A (3) C 410:0 TimeField - A (3) M 417:4 TimeField.to_python - A (3) C 502:0 RegexField - A (3) M 653:4 ImageField.widget_attrs - A (3) M 705:4 BooleanField.to_python - A (3) M 717:4 BooleanField.validate - A (3) C 729:0 NullBooleanField - A (3) M 736:4 NullBooleanField.to_python - A (3) C 764:0 ChoiceField - A (3) M 801:4 ChoiceField.validate - A (3) C 826:0 TypedChoiceField - A (3) C 895:0 TypedMultipleChoiceField - A (3) M 924:4 TypedMultipleChoiceField.validate - A (3) C 931:0 ComboField - A (3) C 1178:0 SlugField - A (3) M 1249:4 JSONField.bound_data - A (3) M 154:4 Field.bound_data - A (2) M 367:4 BaseTemporalField.__init__ - A (2) C 432:0 DateTimeFormatsIterator - A (2) M 445:4 DateTimeField.prepare_value - A (2) M 480:4 DurationField.prepare_value - A (2) C 526:0 EmailField - A (2) M 592:4 FileField.bound_data - A (2) M 597:4 FileField.has_changed - A (2) M 721:4 BooleanField.has_changed - A (2) C 756:0 CallableChoiceIterator - A (2) M 782:4 ChoiceField._set_choices - A (2) M 795:4 ChoiceField.to_python - A (2) M 935:4 ComboField.__init__ - A (2) M 944:4 ComboField.clean - A (2) M 992:4 MultiValueField.__deepcopy__ - A (2) M 1135:4 SplitDateTimeField.__init__ - A (2) M 1181:4 SlugField.__init__ - A (2) M 1193:4 UUIDField.prepare_value - A (2) M 1257:4 JSONField.prepare_value - A (2) M 1262:4 JSONField.has_changed - A (2) M 120:4 Field.prepare_value - A (1) M 123:4 Field.to_python - A (1) M 144:4 Field.clean - A (1) M 167:4 Field.widget_attrs - A (1) M 194:4 Field.get_bound_field - A (1) M 201:4 Field.__deepcopy__ - A (1) M 330:4 DecimalField.__init__ - A (1) M 382:4 BaseTemporalField.strptime - A (1) M 406:4 DateField.strptime - A (1) M 428:4 TimeField.strptime - A (1) M 433:4 DateTimeFormatsIterator.__iter__ - A (1) M 470:4 DateTimeField.strptime - A (1) M 503:4 RegexField.__init__ - A (1) M 511:4 RegexField._get_regex - A (1) M 530:4 EmailField.__init__ - A (1) M 547:4 FileField.__init__ - A (1) M 667:4 URLField.__init__ - A (1) M 752:4 NullBooleanField.validate - A (1) M 757:4 CallableChoiceIterator.__init__ - A (1) M 760:4 CallableChoiceIterator.__iter__ - A (1) M 770:4 ChoiceField.__init__ - A (1) M 774:4 ChoiceField.__deepcopy__ - A (1) M 779:4 ChoiceField._get_choices - A (1) M 827:4 TypedChoiceField.__init__ - A (1) M 848:4 TypedChoiceField.clean - A (1) M 896:4 TypedMultipleChoiceField.__init__ - A (1) M 920:4 TypedMultipleChoiceField.clean - A (1) M 997:4 MultiValueField.validate - A (1) M 1054:4 MultiValueField.compress - A (1) M 1164:4 GenericIPAddressField.__init__ - A (1) C 1210:0 InvalidJSONInput - A (1) C 1214:0 JSONString - A (1) M 1224:4 JSONField.__init__ - A (1) django/forms/boundfield.py M 133:4 BoundField.label_tag - C (16) M 80:4 BoundField.as_widget - B (8) M 170:4 BoundField.css_classes - B (7) M 222:4 BoundField.build_widget_attrs - B (6) C 15:0 BoundField - A (4) M 37:4 BoundField.subwidgets - A (4) M 189:4 BoundField.auto_id - A (4) M 17:4 BoundField.__init__ - A (3) M 213:4 BoundField.initial - A (3) M 30:4 BoundField.__str__ - A (2) M 63:4 BoundField.__getitem__ - A (2) M 123:4 BoundField.value - A (2) M 202:4 BoundField.id_for_label - A (2) C 237:0 BoundWidget - A (2) M 263:4 BoundWidget.template_name - A (2) M 53:4 BoundField.__bool__ - A (1) M 57:4 BoundField.__iter__ - A (1) M 60:4 BoundField.__len__ - A (1) M 74:4 BoundField.errors - A (1) M 100:4 BoundField.as_text - A (1) M 106:4 BoundField.as_textarea - A (1) M 110:4 BoundField.as_hidden - A (1) M 117:4 BoundField.data - A (1) M 184:4 BoundField.is_hidden - A (1) M 232:4 BoundField.widget_type - A (1) M 250:4 BoundWidget.__init__ - A (1) M 255:4 BoundWidget.__str__ - A (1) M 258:4 BoundWidget.tag - A (1) M 269:4 BoundWidget.id_for_label - A (1) M 273:4 BoundWidget.choice_label - A (1) django/forms/renderers.py C 19:0 BaseRenderer - A (2) C 28:0 EngineMixin - A (2) C 50:0 Jinja2 - A (2) C 61:0 TemplatesSetting - A (2) F 14:0 get_default_renderer - A (1) M 20:4 BaseRenderer.get_template - A (1) M 23:4 BaseRenderer.render - A (1) M 29:4 EngineMixin.get_template - A (1) M 33:4 EngineMixin.engine - A (1) C 42:0 DjangoTemplates - A (1) M 56:4 Jinja2.backend - A (1) M 66:4 TemplatesSetting.get_template - A (1) django/forms/widgets.py M 1065:4 SelectDateWidget.value_from_datadict - B (9) M 587:4 ChoiceWidget.optgroups - B (8) M 819:4 MultiWidget.get_context - B (8) M 1019:4 SelectDateWidget.format_value - B (8) M 147:4 Media.__add__ - B (7) M 804:4 MultiWidget.__init__ - B (7) C 935:0 SelectDateWidget - B (7) M 951:4 SelectDateWidget.__init__ - B (7) M 983:4 SelectDateWidget.get_context - B (7) M 1045:4 SelectDateWidget._parse_date_fmt - B (7) M 115:4 Media.merge - B (6) M 663:4 ChoiceWidget.format_value - B (6) M 522:4 CheckboxInput.format_value - A (5) M 621:4 ChoiceWidget.create_option - A (5) C 45:0 Media - A (4) M 46:4 Media.__init__ - A (4) M 65:4 Media._css - A (4) M 222:4 Widget.format_value - A (4) M 448:4 ClearableFileInput.value_from_datadict - A (4) C 512:0 CheckboxInput - A (4) C 551:0 ChoiceWidget - A (4) C 672:0 Select - A (4) M 692:4 Select.use_required_attribute - A (4) C 792:0 MultiWidget - A (4) C 896:0 SplitDateTimeWidget - A (4) F 508:0 boolean_check - A (3) M 87:4 Media.render_css - A (3) C 186:0 MediaDefiningClass - A (3) C 284:0 Input - A (3) C 323:0 PasswordInput - A (3) C 342:0 MultipleHiddenInput - A (3) M 349:4 MultipleHiddenInput.get_context - A (3) C 402:0 ClearableFileInput - A (3) C 469:0 Textarea - A (3) C 480:0 DateTimeBaseInput - A (3) M 528:4 CheckboxInput.get_context - A (3) M 533:4 CheckboxInput.value_from_datadict - A (3) M 645:4 ChoiceWidget.id_for_label - A (3) M 654:4 ChoiceWidget.value_from_datadict - A (3) C 744:0 SelectMultiple - A (3) M 903:4 SplitDateTimeWidget.__init__ - A (3) C 923:0 SplitHiddenDateTimeWidget - A (3) M 76:4 Media.render - A (2) M 79:4 Media.render_js - A (2) M 98:4 Media.absolute_path - A (2) M 108:4 Media.__getitem__ - A (2) M 190:4 MediaDefiningClass.__new__ - A (2) C 199:0 Widget - A (2) M 205:4 Widget.__init__ - A (2) M 215:4 Widget.is_hidden - A (2) M 249:4 Widget._render - A (2) M 254:4 Widget.build_attrs - A (2) M 291:4 Input.__init__ - A (2) M 331:4 PasswordInput.get_context - A (2) M 368:4 MultipleHiddenInput.value_from_datadict - A (2) M 375:4 MultipleHiddenInput.format_value - A (2) C 379:0 FileInput - A (2) M 395:4 FileInput.use_required_attribute - A (2) M 421:4 ClearableFileInput.is_initial - A (2) M 427:4 ClearableFileInput.format_value - A (2) M 462:4 ClearableFileInput.value_omitted_from_data - A (2) M 472:4 Textarea.__init__ - A (2) M 484:4 DateTimeBaseInput.__init__ - A (2) M 488:4 DateTimeBaseInput.format_value - A (2) M 516:4 CheckboxInput.__init__ - A (2) M 582:4 ChoiceWidget.options - A (2) M 680:4 Select.get_context - A (2) M 687:4 Select._choice_has_empty_value - A (2) C 706:0 NullBooleanSelect - A (2) M 718:4 NullBooleanSelect.format_value - A (2) M 747:4 SelectMultiple.value_from_datadict - A (2) C 766:0 CheckboxSelectMultiple - A (2) M 782:4 CheckboxSelectMultiple.id_for_label - A (2) M 816:4 MultiWidget.is_hidden - A (2) M 850:4 MultiWidget.id_for_label - A (2) M 855:4 MultiWidget.value_from_datadict - A (2) M 861:4 MultiWidget.value_omitted_from_data - A (2) M 875:4 MultiWidget._get_media - A (2) M 892:4 MultiWidget.needs_multipart_form - A (2) M 916:4 SplitDateTimeWidget.decompress - A (2) M 929:4 SplitHiddenDateTimeWidget.__init__ - A (2) M 1060:4 SelectDateWidget.id_for_label - A (2) M 1083:4 SelectDateWidget.value_omitted_from_data - A (2) F 160:0 media_property - A (1) C 40:0 MediaOrderConflictWarning - A (1) M 58:4 Media.__repr__ - A (1) M 61:4 Media.__str__ - A (1) M 73:4 Media._js - A (1) M 208:4 Widget.__deepcopy__ - A (1) M 218:4 Widget.subwidgets - A (1) M 232:4 Widget.get_context - A (1) M 244:4 Widget.render - A (1) M 258:4 Widget.value_from_datadict - A (1) M 265:4 Widget.value_omitted_from_data - A (1) M 268:4 Widget.id_for_label - A (1) M 280:4 Widget.use_required_attribute - A (1) M 297:4 Input.get_context - A (1) C 303:0 TextInput - A (1) C 308:0 NumberInput - A (1) C 313:0 EmailInput - A (1) C 318:0 URLInput - A (1) M 327:4 PasswordInput.__init__ - A (1) C 337:0 HiddenInput - A (1) M 384:4 FileInput.format_value - A (1) M 388:4 FileInput.value_from_datadict - A (1) M 392:4 FileInput.value_omitted_from_data - A (1) M 408:4 ClearableFileInput.clear_checkbox_name - A (1) M 415:4 ClearableFileInput.clear_checkbox_id - A (1) M 434:4 ClearableFileInput.get_context - A (1) C 492:0 DateInput - A (1) C 497:0 DateTimeInput - A (1) C 502:0 TimeInput - A (1) M 545:4 CheckboxInput.value_omitted_from_data - A (1) M 560:4 ChoiceWidget.__init__ - A (1) M 567:4 ChoiceWidget.__deepcopy__ - A (1) M 574:4 ChoiceWidget.subwidgets - A (1) M 640:4 ChoiceWidget.get_context - A (1) M 710:4 NullBooleanSelect.__init__ - A (1) M 729:4 NullBooleanSelect.value_from_datadict - A (1) M 754:4 SelectMultiple.value_omitted_from_data - A (1) C 760:0 RadioSelect - A (1) M 772:4 CheckboxSelectMultiple.use_required_attribute - A (1) M 777:4 CheckboxSelectMultiple.value_omitted_from_data - A (1) M 867:4 MultiWidget.decompress - A (1) M 886:4 MultiWidget.__deepcopy__ - A (1) django/forms/formsets.py M 330:4 BaseFormSet.full_clean - C (15) M 246:4 BaseFormSet.ordered_forms - B (10) M 229:4 BaseFormSet.deleted_forms - B (9) M 66:4 BaseFormSet.__init__ - B (8) M 169:4 BaseFormSet._construct_form - B (7) M 398:4 BaseFormSet.add_fields - B (7) M 316:4 BaseFormSet.is_valid - B (6) F 460:0 formset_factory - A (5) C 54:0 BaseFormSet - A (4) M 123:4 BaseFormSet.total_form_count - A (4) M 142:4 BaseFormSet.initial_form_count - A (3) M 220:4 BaseFormSet.cleaned_data - A (3) F 493:0 all_valid - A (2) C 28:0 ManagementForm - A (2) M 109:4 BaseFormSet.management_form - A (2) M 152:4 BaseFormSet.forms - A (2) M 290:4 BaseFormSet.non_form_errors - A (2) M 301:4 BaseFormSet.errors - A (2) M 307:4 BaseFormSet.total_error_count - A (2) M 394:4 BaseFormSet.has_changed - A (2) M 422:4 BaseFormSet.is_multipart - A (2) M 433:4 BaseFormSet.media - A (2) M 441:4 BaseFormSet.as_table - A (2) M 449:4 BaseFormSet.as_p - A (2) M 454:4 BaseFormSet.as_ul - A (2) M 34:4 ManagementForm.__init__ - A (1) M 44:4 ManagementForm.clean - A (1) M 87:4 BaseFormSet.__str__ - A (1) M 90:4 BaseFormSet.__iter__ - A (1) M 94:4 BaseFormSet.__getitem__ - A (1) M 98:4 BaseFormSet.__len__ - A (1) M 101:4 BaseFormSet.__bool__ - A (1) M 160:4 BaseFormSet.get_form_kwargs - A (1) M 198:4 BaseFormSet.initial_forms - A (1) M 203:4 BaseFormSet.extra_forms - A (1) M 208:4 BaseFormSet.empty_form - A (1) M 283:4 BaseFormSet.get_default_prefix - A (1) M 287:4 BaseFormSet.get_ordering_widget - A (1) M 312:4 BaseFormSet._should_delete_form - A (1) M 385:4 BaseFormSet.clean - A (1) M 419:4 BaseFormSet.add_prefix - A (1) django/forms/forms.py M 190:4 BaseForm._html_output - C (15) M 64:4 BaseForm.__init__ - C (14) M 306:4 BaseForm.add_error - C (11) C 22:0 DeclarativeFieldsMetaclass - B (9) M 24:4 DeclarativeFieldsMetaclass.__new__ - B (8) M 376:4 BaseForm._clean_fields - B (6) M 428:4 BaseForm.changed_data - A (5) C 52:0 BaseForm - A (4) M 109:4 BaseForm.order_fields - A (4) M 353:4 BaseForm.has_error - A (4) M 359:4 BaseForm.full_clean - A (4) M 398:4 BaseForm._clean_form - A (4) M 134:4 BaseForm.__repr__ - A (3) M 150:4 BaseForm.__getitem__ - A (3) M 466:4 BaseForm.hidden_fields - A (3) M 473:4 BaseForm.visible_fields - A (3) M 146:4 BaseForm.__iter__ - A (2) M 167:4 BaseForm.errors - A (2) M 173:4 BaseForm.is_valid - A (2) M 177:4 BaseForm.add_prefix - A (2) M 452:4 BaseForm.media - A (2) M 459:4 BaseForm.is_multipart - A (2) M 480:4 BaseForm.get_initial_for_field - A (2) M 131:4 BaseForm.__str__ - A (1) M 186:4 BaseForm.add_initial_prefix - A (1) M 268:4 BaseForm.as_table - A (1) M 278:4 BaseForm.as_ul - A (1) M 288:4 BaseForm.as_p - A (1) M 298:4 BaseForm.non_field_errors - A (1) M 407:4 BaseForm._post_clean - A (1) M 414:4 BaseForm.clean - A (1) M 423:4 BaseForm.has_changed - A (1) C 491:0 Form - A (1) django/forms/utils.py F 156:0 from_current_timezone - B (7) F 18:0 flatatt - A (5) F 181:0 to_current_timezone - A (4) M 100:4 ErrorList.get_json_data - A (4) C 45:0 ErrorDict - A (3) M 68:4 ErrorDict.as_text - A (3) M 113:4 ErrorList.as_ul - A (3) F 11:0 pretty_name - A (2) M 51:4 ErrorDict.as_data - A (2) M 54:4 ErrorDict.get_json_data - A (2) M 60:4 ErrorDict.as_ul - A (2) C 80:0 ErrorList - A (2) M 84:4 ErrorList.__init__ - A (2) M 123:4 ErrorList.as_text - A (2) M 138:4 ErrorList.__getitem__ - A (2) M 57:4 ErrorDict.as_json - A (1) M 75:4 ErrorDict.__str__ - A (1) M 92:4 ErrorList.as_data - A (1) M 95:4 ErrorList.copy - A (1) M 110:4 ErrorList.as_json - A (1) M 126:4 ErrorList.__str__ - A (1) M 129:4 ErrorList.__repr__ - A (1) M 132:4 ErrorList.__contains__ - A (1) M 135:4 ErrorList.__eq__ - A (1) M 144:4 ErrorList.__reduce_ex__ - A (1) django/core/signing.py M 123:4 Signer.__init__ - A (5) C 122:0 Signer - A (4) M 148:4 Signer.sign_object - A (4) M 196:4 TimestampSigner.unsign - A (4) M 140:4 Signer.unsign - A (3) M 173:4 Signer.unsign_object - A (3) C 187:0 TimestampSigner - A (3) C 81:0 JSONSerializer - A (2) F 62:0 b64_encode - A (1) F 66:0 b64_decode - A (1) F 71:0 base64_hmac - A (1) F 75:0 get_cookie_signer - A (1) F 93:0 dumps - A (1) F 113:0 loads - A (1) C 52:0 BadSignature - A (1) C 57:0 SignatureExpired - A (1) M 86:4 JSONSerializer.dumps - A (1) M 89:4 JSONSerializer.loads - A (1) M 134:4 Signer.signature - A (1) M 137:4 Signer.sign - A (1) M 189:4 TimestampSigner.timestamp - A (1) M 192:4 TimestampSigner.sign - A (1) django/core/validators.py M 101:4 URLValidator.__call__ - C (12) M 438:4 DecimalValidator.__call__ - C (11) M 209:4 EmailValidator.__call__ - B (9) M 27:4 RegexValidator.__init__ - B (8) C 65:0 URLValidator - B (8) C 20:0 RegexValidator - B (7) M 53:4 RegexValidator.__eq__ - B (6) C 410:0 DecimalValidator - B (6) F 526:0 get_available_image_extensions - A (5) C 157:0 EmailValidator - A (5) M 194:4 EmailValidator.__init__ - A (5) C 488:0 FileExtensionValidator - A (5) M 495:4 FileExtensionValidator.__init__ - A (5) F 300:0 ip_address_validators - A (4) M 230:4 EmailValidator.validate_domain_part - A (4) M 244:4 EmailValidator.__eq__ - A (4) M 345:4 BaseValidator.__eq__ - A (4) M 517:4 FileExtensionValidator.__eq__ - A (4) C 541:0 ProhibitNullCharactersValidator - A (4) F 283:0 validate_ipv46_address - A (3) M 43:4 RegexValidator.__call__ - A (3) C 329:0 BaseValidator - A (3) M 338:4 BaseValidator.__call__ - A (3) M 479:4 DecimalValidator.__eq__ - A (3) M 504:4 FileExtensionValidator.__call__ - A (3) M 546:4 ProhibitNullCharactersValidator.__init__ - A (3) M 556:4 ProhibitNullCharactersValidator.__eq__ - A (3) F 271:0 validate_ipv4_address - A (2) F 278:0 validate_ipv6_address - A (2) F 315:0 int_list_validator - A (2) M 96:4 URLValidator.__init__ - A (2) M 333:4 BaseValidator.__init__ - A (2) C 362:0 MaxValueValidator - A (2) C 371:0 MinValueValidator - A (2) C 380:0 MinLengthValidator - A (2) C 395:0 MaxLengthValidator - A (2) M 552:4 ProhibitNullCharactersValidator.__call__ - A (2) F 152:0 validate_integer - A (1) F 536:0 validate_image_file_extension - A (1) M 175:4 EmailValidator.domain_whitelist - A (1) M 185:4 EmailValidator.domain_whitelist - A (1) M 354:4 BaseValidator.compare - A (1) M 357:4 BaseValidator.clean - A (1) M 366:4 MaxValueValidator.compare - A (1) M 375:4 MinValueValidator.compare - A (1) M 387:4 MinLengthValidator.compare - A (1) M 390:4 MinLengthValidator.clean - A (1) M 402:4 MaxLengthValidator.compare - A (1) M 405:4 MaxLengthValidator.clean - A (1) M 434:4 DecimalValidator.__init__ - A (1) django/core/asgi.py F 5:0 get_asgi_application - A (1) django/core/paginator.py M 44:4 Paginator.validate_number - B (8) C 27:0 Paginator - A (4) M 93:4 Paginator.count - A (4) M 116:4 Paginator._check_object_list_is_ordered - A (4) M 134:4 Paginator.get_elided_page_range - A (4) M 61:4 Paginator.get_page - A (3) M 101:4 Paginator.num_pages - A (3) M 179:4 Page.__getitem__ - A (3) M 40:4 Paginator.__iter__ - A (2) M 74:4 Paginator.page - A (2) C 166:0 Page - A (2) M 197:4 Page.has_other_pages - A (2) M 206:4 Page.start_index - A (2) M 216:4 Page.end_index - A (2) C 11:0 UnorderedObjectListWarning - A (1) C 15:0 InvalidPage - A (1) C 19:0 PageNotAnInteger - A (1) C 23:0 EmptyPage - A (1) M 32:4 Paginator.__init__ - A (1) M 83:4 Paginator._get_page - A (1) M 109:4 Paginator.page_range - A (1) M 168:4 Page.__init__ - A (1) M 173:4 Page.__repr__ - A (1) M 176:4 Page.__len__ - A (1) M 191:4 Page.has_next - A (1) M 194:4 Page.has_previous - A (1) M 200:4 Page.next_page_number - A (1) M 203:4 Page.previous_page_number - A (1) django/core/exceptions.py M 109:4 ValidationError.__init__ - C (11) M 174:4 ValidationError.__iter__ - A (5) C 107:0 ValidationError - A (4) M 166:4 ValidationError.update_error_dict - A (3) M 198:4 ValidationError.__hash__ - A (3) M 161:4 ValidationError.messages - A (2) M 185:4 ValidationError.__str__ - A (2) M 193:4 ValidationError.__eq__ - A (2) C 9:0 FieldDoesNotExist - A (1) C 14:0 AppRegistryNotReady - A (1) C 19:0 ObjectDoesNotExist - A (1) C 24:0 MultipleObjectsReturned - A (1) C 29:0 SuspiciousOperation - A (1) C 33:0 SuspiciousMultipartForm - A (1) C 38:0 SuspiciousFileOperation - A (1) C 43:0 DisallowedHost - A (1) C 48:0 DisallowedRedirect - A (1) C 53:0 TooManyFieldsSent - A (1) C 61:0 RequestDataTooBig - A (1) C 69:0 RequestAborted - A (1) C 74:0 BadRequest - A (1) C 79:0 PermissionDenied - A (1) C 84:0 ViewDoesNotExist - A (1) C 89:0 MiddlewareNotUsed - A (1) C 94:0 ImproperlyConfigured - A (1) C 99:0 FieldError - A (1) M 153:4 ValidationError.message_dict - A (1) M 190:4 ValidationError.__repr__ - A (1) C 210:0 EmptyResultSet - A (1) C 215:0 SynchronousOnlyOperation - A (1) django/core/wsgi.py F 5:0 get_wsgi_application - A (1) django/core/cache/__init__.py C 30:0 CacheHandler - A (3) F 52:0 close_caches - A (2) M 34:4 CacheHandler.create_connection - A (2) django/core/cache/utils.py F 6:0 make_template_fragment_key - A (3) django/core/cache/backends/memcached.py M 42:4 BaseMemcachedCache.get_backend_timeout - A (5) M 96:4 BaseMemcachedCache.get_many - A (4) M 107:4 BaseMemcachedCache.incr - A (4) M 124:4 BaseMemcachedCache.decr - A (4) C 15:0 BaseMemcachedCache - A (3) M 16:4 BaseMemcachedCache.__init__ - A (3) M 141:4 BaseMemcachedCache.set_many - A (3) M 152:4 BaseMemcachedCache.delete_many - A (3) C 205:0 PyLibMCCache - A (3) M 212:4 PyLibMCCache.client_servers - A (3) M 79:4 BaseMemcachedCache.set - A (2) M 161:4 BaseMemcachedCache.validate_key - A (2) C 166:0 MemcachedCache - A (2) M 185:4 MemcachedCache.get - A (2) M 218:4 PyLibMCCache.touch - A (2) C 231:0 PyMemcacheCache - A (2) M 32:4 BaseMemcachedCache.client_servers - A (1) M 36:4 BaseMemcachedCache._cache - A (1) M 69:4 BaseMemcachedCache.add - A (1) M 74:4 BaseMemcachedCache.get - A (1) M 86:4 BaseMemcachedCache.touch - A (1) M 91:4 BaseMemcachedCache.delete - A (1) M 103:4 BaseMemcachedCache.close - A (1) M 158:4 BaseMemcachedCache.clear - A (1) M 173:4 MemcachedCache.__init__ - A (1) M 196:4 MemcachedCache.delete - A (1) M 207:4 PyLibMCCache.__init__ - A (1) M 225:4 PyLibMCCache.close - A (1) M 233:4 PyMemcacheCache.__init__ - A (1) django/core/cache/backends/db.py M 112:4 DatabaseCache._base_set - C (15) M 53:4 DatabaseCache.get_many - B (6) C 40:0 DatabaseCache - A (4) M 255:4 DatabaseCache._cull - A (4) C 12:0 Options - A (2) C 30:0 BaseDatabaseCache - A (2) M 203:4 DatabaseCache.delete_many - A (2) M 210:4 DatabaseCache._base_delete_many - A (2) M 230:4 DatabaseCache.has_key - A (2) M 17:4 Options.__init__ - A (1) M 31:4 BaseDatabaseCache.__init__ - A (1) M 50:4 DatabaseCache.get - A (1) M 97:4 DatabaseCache.set - A (1) M 102:4 DatabaseCache.add - A (1) M 107:4 DatabaseCache.touch - A (1) M 199:4 DatabaseCache.delete - A (1) M 277:4 DatabaseCache.clear - A (1) django/core/cache/backends/filebased.py M 81:4 FileBasedCache._delete - A (4) M 98:4 FileBasedCache._cull - A (4) M 142:4 FileBasedCache._is_expired - A (4) C 16:0 FileBasedCache - A (3) M 31:4 FileBasedCache.get - A (3) M 61:4 FileBasedCache.touch - A (3) M 25:4 FileBasedCache.add - A (2) M 46:4 FileBasedCache.set - A (2) M 91:4 FileBasedCache.has_key - A (2) M 135:4 FileBasedCache.clear - A (2) M 156:4 FileBasedCache._list_cache_files - A (2) M 20:4 FileBasedCache.__init__ - A (1) M 41:4 FileBasedCache._write_content - A (1) M 78:4 FileBasedCache.delete - A (1) M 116:4 FileBasedCache._createdir - A (1) M 125:4 FileBasedCache._key_to_file - A (1) django/core/cache/backends/dummy.py C 6:0 DummyCache - A (2) M 7:4 DummyCache.__init__ - A (1) M 10:4 DummyCache.add - A (1) M 15:4 DummyCache.get - A (1) M 20:4 DummyCache.set - A (1) M 24:4 DummyCache.touch - A (1) M 28:4 DummyCache.delete - A (1) M 33:4 DummyCache.has_key - A (1) M 38:4 DummyCache.clear - A (1) django/core/cache/backends/base.py F 280:0 memcache_key_warnings - A (5) M 57:4 BaseCache.__init__ - A (5) M 83:4 BaseCache.get_backend_timeout - A (4) F 40:0 get_key_func - A (3) M 146:4 BaseCache.get_many - A (3) M 161:4 BaseCache.get_or_set - A (3) M 252:4 BaseCache.incr_version - A (3) C 54:0 BaseCache - A (2) M 95:4 BaseCache.make_key - A (2) M 186:4 BaseCache.incr - A (2) M 214:4 BaseCache.set_many - A (2) M 230:4 BaseCache.delete_many - A (2) M 243:4 BaseCache.validate_key - A (2) F 29:0 default_key_func - A (1) C 9:0 InvalidCacheBackendError - A (1) C 13:0 CacheKeyWarning - A (1) C 17:0 InvalidCacheKey - A (1) M 108:4 BaseCache.add - A (1) M 118:4 BaseCache.get - A (1) M 125:4 BaseCache.set - A (1) M 132:4 BaseCache.touch - A (1) M 139:4 BaseCache.delete - A (1) M 180:4 BaseCache.has_key - A (1) M 198:4 BaseCache.decr - A (1) M 205:4 BaseCache.__contains__ - A (1) M 239:4 BaseCache.clear - A (1) M 268:4 BaseCache.decr_version - A (1) M 275:4 BaseCache.close - A (1) django/core/cache/backends/locmem.py M 97:4 LocMemCache._cull - A (3) C 16:0 LocMemCache - A (2) M 25:4 LocMemCache.add - A (2) M 35:4 LocMemCache.get - A (2) M 46:4 LocMemCache._set - A (2) M 60:4 LocMemCache.touch - A (2) M 69:4 LocMemCache.incr - A (2) M 84:4 LocMemCache.has_key - A (2) M 93:4 LocMemCache._has_expired - A (2) M 107:4 LocMemCache._delete - A (2) M 19:4 LocMemCache.__init__ - A (1) M 53:4 LocMemCache.set - A (1) M 115:4 LocMemCache.delete - A (1) M 121:4 LocMemCache.clear - A (1) django/core/mail/__init__.py F 90:0 mail_admins - B (7) F 107:0 mail_managers - B (7) F 38:0 send_mail - A (3) F 64:0 send_mass_mail - A (3) F 26:0 get_connection - A (2) django/core/mail/message.py M 194:4 EmailMessage.__init__ - C (15) F 74:0 sanitize_address - C (14) M 286:4 EmailMessage.attach - B (10) F 55:0 forbid_multi_line_headers - B (9) M 244:4 EmailMessage.message - B (7) M 337:4 EmailMessage._create_attachments - B (7) M 351:4 EmailMessage._create_mime_attachment - B (7) C 188:0 EmailMessage - B (6) M 165:4 SafeMIMEText.set_payload - A (5) M 438:4 EmailMultiAlternatives._create_alternatives - A (5) M 395:4 EmailMessage._set_list_header_if_not_empty - A (4) C 408:0 EmailMultiAlternatives - A (4) C 155:0 SafeMIMEText - A (3) M 271:4 EmailMessage.recipients - A (3) M 381:4 EmailMessage._create_attachment - A (3) M 429:4 EmailMultiAlternatives.attach_alternative - A (3) C 119:0 MIMEMixin - A (2) C 147:0 SafeMIMEMessage - A (2) C 177:0 SafeMIMEMultipart - A (2) M 238:4 EmailMessage.get_connection - A (2) M 278:4 EmailMessage.send - A (2) M 416:4 EmailMultiAlternatives.__init__ - A (2) C 35:0 BadHeaderError - A (1) M 120:4 MIMEMixin.as_string - A (1) M 133:4 MIMEMixin.as_bytes - A (1) M 149:4 SafeMIMEMessage.__setitem__ - A (1) M 157:4 SafeMIMEText.__init__ - A (1) M 161:4 SafeMIMEText.__setitem__ - A (1) M 179:4 SafeMIMEMultipart.__init__ - A (1) M 183:4 SafeMIMEMultipart.__setitem__ - A (1) M 318:4 EmailMessage.attach_file - A (1) M 334:4 EmailMessage._create_message - A (1) M 435:4 EmailMultiAlternatives._create_message - A (1) django/core/mail/utils.py C 12:0 CachedDnsName - A (3) M 16:4 CachedDnsName.get_fqdn - A (2) M 13:4 CachedDnsName.__str__ - A (1) django/core/mail/backends/console.py M 25:4 EmailBackend.send_messages - B (6) C 10:0 EmailBackend - A (4) M 16:4 EmailBackend.write_message - A (2) M 11:4 EmailBackend.__init__ - A (1) django/core/mail/backends/filebased.py M 14:4 EmailBackend.__init__ - A (5) C 13:0 EmailBackend - A (3) M 45:4 EmailBackend._get_filename - A (2) M 53:4 EmailBackend.open - A (2) M 59:4 EmailBackend.close - A (2) M 40:4 EmailBackend.write_message - A (1) django/core/mail/backends/smtp.py M 16:4 EmailBackend.__init__ - C (12) M 41:4 EmailBackend.open - B (10) C 12:0 EmailBackend - B (8) M 94:4 EmailBackend.send_messages - B (7) M 116:4 EmailBackend._send - B (6) M 75:4 EmailBackend.close - A (5) M 38:4 EmailBackend.connection_class - A (2) django/core/mail/backends/dummy.py C 8:0 EmailBackend - A (2) M 9:4 EmailBackend.send_messages - A (1) django/core/mail/backends/base.py C 4:0 BaseEmailBackend - A (2) M 43:4 BaseEmailBackend.__enter__ - A (2) M 17:4 BaseEmailBackend.__init__ - A (1) M 20:4 BaseEmailBackend.open - A (1) M 39:4 BaseEmailBackend.close - A (1) M 51:4 BaseEmailBackend.__exit__ - A (1) M 54:4 BaseEmailBackend.send_messages - A (1) django/core/mail/backends/locmem.py C 9:0 EmailBackend - A (3) M 18:4 EmailBackend.__init__ - A (2) M 23:4 EmailBackend.send_messages - A (2) django/core/checks/files.py F 9:0 check_setting_file_upload_temp_dir - A (3) django/core/checks/caches.py F 23:0 check_cache_location_not_exposed - C (13) F 59:0 check_file_based_cache_is_absolute - A (4) F 16:0 check_default_cache_is_configured - A (2) django/core/checks/registry.py M 66:4 CheckRegistry.run_checks - B (6) C 27:0 CheckRegistry - A (3) M 33:4 CheckRegistry.register - A (3) M 87:4 CheckRegistry.tags_available - A (2) M 92:4 CheckRegistry.get_checks - A (2) C 7:0 Tags - A (1) M 29:4 CheckRegistry.__init__ - A (1) M 84:4 CheckRegistry.tag_exists - A (1) django/core/checks/model_checks.py F 12:0 check_all_models - D (21) F 89:0 _check_lazy_references - B (7) F 209:0 check_lazy_references - A (1) django/core/checks/database.py F 7:0 check_database_backends - A (3) django/core/checks/templates.py F 19:0 check_setting_app_dirs_loaders - A (4) F 27:0 check_string_if_invalid_is_string - A (3) django/core/checks/translation.py F 39:0 check_setting_languages - A (4) F 48:0 check_setting_languages_bidi - A (4) F 30:0 check_setting_language_code - A (3) F 57:0 check_language_settings_consistent - A (3) django/core/checks/async_checks.py F 13:0 check_async_unsafe - A (2) django/core/checks/messages.py M 26:4 CheckMessage.__str__ - A (5) C 9:0 CheckMessage - A (3) M 19:4 CheckMessage.__eq__ - A (3) M 11:4 CheckMessage.__init__ - A (2) C 53:0 Debug - A (2) C 58:0 Info - A (2) C 63:0 Warning - A (2) C 68:0 Error - A (2) C 73:0 Critical - A (2) M 41:4 CheckMessage.__repr__ - A (1) M 45:4 CheckMessage.is_serious - A (1) M 48:4 CheckMessage.is_silenced - A (1) M 54:4 Debug.__init__ - A (1) M 59:4 Info.__init__ - A (1) M 64:4 Warning.__init__ - A (1) M 69:4 Error.__init__ - A (1) M 74:4 Critical.__init__ - A (1) django/core/checks/urls.py F 31:0 check_url_namespaces_unique - A (5) F 53:0 _load_all_namespaces - A (5) F 97:0 check_url_settings - A (4) F 17:0 check_resolver - A (3) F 71:0 get_warning_for_invalid_pattern - A (3) F 9:0 check_url_config - A (2) F 106:0 E006 - A (1) django/core/checks/security/sessions.py F 67:0 check_session_cookie_secure - A (5) F 80:0 check_session_cookie_httponly - A (5) F 6:0 add_session_cookie_message - A (1) F 36:0 add_httponly_message - A (1) F 92:0 _session_middleware - A (1) F 96:0 _session_app - A (1) django/core/checks/security/csrf.py F 36:0 check_csrf_cookie_secure - A (4) F 46:0 check_csrf_failure_view - A (4) F 30:0 check_csrf_middleware - A (2) F 25:0 _csrf_middleware - A (1) django/core/checks/security/base.py F 188:0 check_secret_key - B (6) F 223:0 check_referrer_policy - B (6) F 150:0 check_sts_include_subdomains - A (4) F 160:0 check_sts_preload - A (4) F 144:0 check_sts - A (3) F 170:0 check_content_type_nosniff - A (3) F 179:0 check_ssl_redirect - A (3) F 209:0 check_xframe_deny - A (3) F 132:0 check_security_middleware - A (2) F 138:0 check_xframe_options_middleware - A (2) F 203:0 check_debug - A (2) F 218:0 check_allowed_hosts - A (2) F 123:0 _security_middleware - A (1) F 127:0 _xframe_middleware - A (1) django/core/management/color.py F 20:0 supports_color - B (8) F 63:0 make_style - A (3) F 101:0 color_style - A (3) F 94:0 no_style - A (1) C 59:0 Style - A (1) django/core/management/__init__.py F 78:0 call_command - D (21) M 260:4 ManagementUtility.autocomplete - C (18) M 334:4 ManagementUtility.execute - C (16) C 184:0 ManagementUtility - C (11) M 195:4 ManagementUtility.main_help_text - B (7) M 228:4 ManagementUtility.fetch_command - B (6) F 44:0 get_commands - A (5) F 23:0 find_commands - A (4) M 188:4 ManagementUtility.__init__ - A (3) F 33:0 load_command_class - A (1) F 416:0 execute_from_command_line - A (1) django/core/management/templates.py M 58:4 TemplateCommand.handle - D (30) M 244:4 TemplateCommand.download - B (9) C 20:0 TemplateCommand - B (7) M 185:4 TemplateCommand.handle_template - B (6) M 211:4 TemplateCommand.validate_name - A (5) M 308:4 TemplateCommand.extract - A (3) M 298:4 TemplateCommand.splitext - A (2) M 325:4 TemplateCommand.is_url - A (2) M 332:4 TemplateCommand.make_writeable - A (2) M 40:4 TemplateCommand.add_arguments - A (1) django/core/management/utils.py F 52:0 find_command - B (10) F 128:0 normalize_path_patterns - B (7) F 85:0 parse_apps_and_model_labels - A (5) F 30:0 handle_extensions - A (4) F 112:0 get_command_line_option - A (3) F 13:0 popen_wrapper - A (2) F 143:0 is_ignored_path - A (2) F 77:0 get_random_secret_key - A (1) django/core/management/sql.py F 20:0 emit_pre_migrate_signal - A (4) F 38:0 emit_post_migrate_signal - A (4) F 7:0 sql_flush - A (1) django/core/management/base.py M 410:4 BaseCommand.check - E (31) M 373:4 BaseCommand.execute - C (13) M 243:4 BaseCommand.__init__ - B (10) C 158:0 BaseCommand - B (8) M 56:4 CommandParser.parse_args - A (5) M 150:4 OutputWrapper.write - A (5) M 337:4 BaseCommand.run_from_argv - A (5) M 527:4 AppCommand.handle - A (5) C 45:0 CommandParser - A (4) M 479:4 BaseCommand.check_migrations - A (4) F 70:0 handle_default_options - A (3) C 120:0 OutputWrapper - A (3) M 129:4 OutputWrapper.style_func - A (3) M 275:4 BaseCommand.create_parser - A (3) C 514:0 AppCommand - A (3) C 550:0 LabelCommand - A (3) M 568:4 LabelCommand.handle - A (3) C 21:0 CommandError - A (2) M 63:4 CommandParser.error - A (2) C 97:0 DjangoHelpFormatter - A (2) M 143:4 OutputWrapper.flush - A (2) M 147:4 OutputWrapper.isatty - A (2) F 82:0 no_translations - A (1) M 33:4 CommandError.__init__ - A (1) C 38:0 SystemCheckError - A (1) M 51:4 CommandParser.__init__ - A (1) M 107:4 DjangoHelpFormatter._reordered_actions - A (1) M 113:4 DjangoHelpFormatter.add_usage - A (1) M 116:4 DjangoHelpFormatter.add_arguments - A (1) M 125:4 OutputWrapper.style_func - A (1) M 135:4 OutputWrapper.__init__ - A (1) M 140:4 OutputWrapper.__getattr__ - A (1) M 267:4 BaseCommand.get_version - A (1) M 323:4 BaseCommand.add_arguments - A (1) M 329:4 BaseCommand.print_help - A (1) M 506:4 BaseCommand.handle - A (1) M 524:4 AppCommand.add_arguments - A (1) M 540:4 AppCommand.handle_app_config - A (1) M 565:4 LabelCommand.add_arguments - A (1) M 576:4 LabelCommand.handle_label - A (1) django/core/management/commands/createcachetable.py M 45:4 Command.create_table - C (17) C 10:0 Command - B (9) M 31:4 Command.handle - A (5) M 15:4 Command.add_arguments - A (1) django/core/management/commands/inspectdb.py M 38:4 Command.handle_inspection - E (39) M 175:4 Command.normalize_col_name - C (16) C 9:0 Command - C (14) M 266:4 Command.get_meta - C (12) M 231:4 Command.get_field_type - C (11) M 31:4 Command.handle - A (3) M 15:4 Command.add_arguments - A (1) django/core/management/commands/squashmigrations.py M 45:4 Command.handle - E (34) C 12:0 Command - C (14) M 206:4 Command.find_migration - A (3) M 15:4 Command.add_arguments - A (1) django/core/management/commands/check.py M 40:4 Command.handle - B (9) C 7:0 Command - B (6) M 12:4 Command.add_arguments - A (1) django/core/management/commands/startapp.py C 4:0 Command - A (2) M 11:4 Command.handle - A (1) django/core/management/commands/sqlmigrate.py M 31:4 Command.handle - B (8) C 7:0 Command - A (4) M 12:4 Command.add_arguments - A (1) M 24:4 Command.execute - A (1) django/core/management/commands/makemigrations.py M 62:4 Command.handle - E (35) M 239:4 Command.handle_merge - D (26) C 24:0 Command - C (19) M 194:4 Command.write_migration_files - C (12) M 27:4 Command.add_arguments - A (1) django/core/management/commands/sqlflush.py C 6:0 Command - A (3) M 21:4 Command.handle - A (3) M 14:4 Command.add_arguments - A (1) django/core/management/commands/makemessages.py M 283:4 Command.handle - D (30) M 458:4 Command.find_files - C (18) M 505:4 Command.process_locale_dir - C (17) C 197:0 Command - B (10) M 598:4 Command.write_po_file - B (10) M 639:4 Command.copy_plural_forms - B (10) F 170:0 write_pot_file - B (8) M 426:4 Command.build_potfiles - B (6) M 98:4 BuildFile.preprocess - A (4) M 403:4 Command.gettext_version - A (4) F 28:0 check_programs - A (3) F 155:0 normalize_eols - A (3) C 61:0 BuildFile - A (3) M 71:4 BuildFile.is_templatized - A (3) M 117:4 BuildFile.postprocess_messages - A (3) M 143:4 BuildFile.cleanup - A (3) M 417:4 Command.settings_available - A (3) M 452:4 Command.remove_potfiles - A (3) M 493:4 Command.process_files - A (3) C 38:0 TranslatableFile - A (2) M 84:4 BuildFile.work_path - A (2) M 39:4 TranslatableFile.__init__ - A (1) M 44:4 TranslatableFile.__repr__ - A (1) M 50:4 TranslatableFile.__eq__ - A (1) M 53:4 TranslatableFile.__lt__ - A (1) M 57:4 TranslatableFile.path - A (1) M 65:4 BuildFile.__init__ - A (1) M 80:4 BuildFile.path - A (1) M 216:4 Command.add_arguments - A (1) django/core/management/commands/shell.py M 42:4 Command.python - C (13) M 84:4 Command.handle - B (8) C 10:0 Command - B (6) M 20:4 Command.add_arguments - A (1) M 34:4 Command.ipython - A (1) M 38:4 Command.bpython - A (1) django/core/management/commands/dumpdata.py M 81:4 Command.handle - E (36) C 28:0 Command - C (20) C 24:0 ProxyModelWarning - A (1) M 34:4 Command.add_arguments - A (1) django/core/management/commands/test.py C 9:0 Command - A (3) M 49:4 Command.handle - A (3) M 25:4 Command.add_arguments - A (2) M 16:4 Command.run_from_argv - A (1) django/core/management/commands/flush.py M 27:4 Command.handle - B (8) C 10:0 Command - B (6) M 17:4 Command.add_arguments - A (1) django/core/management/commands/loaddata.py M 226:4 Command.find_fixtures - C (20) M 87:4 Command.loaddata - C (16) M 159:4 Command.load_label - C (15) C 38:0 Command - C (11) M 284:4 Command.fixture_dirs - B (8) M 313:4 Command.parse_name - B (7) C 346:0 SingleZipReader - A (3) F 357:0 humanize - A (2) M 69:4 Command.handle - A (2) M 348:4 SingleZipReader.__init__ - A (2) M 45:4 Command.add_arguments - A (1) M 353:4 SingleZipReader.read - A (1) django/core/management/commands/runserver.py M 71:4 Command.handle - C (14) M 111:4 Command.inner_run - B (8) C 24:0 Command - A (5) M 59:4 Command.execute - A (2) M 102:4 Command.run - A (2) M 37:4 Command.add_arguments - A (1) M 67:4 Command.get_handler - A (1) django/core/management/commands/showmigrations.py M 65:4 Command.show_list - C (12) M 105:4 Command.show_plan - C (11) C 9:0 Command - B (7) M 54:4 Command._validate_app_names - A (4) M 42:4 Command.handle - A (2) M 12:4 Command.add_arguments - A (1) django/core/management/commands/sqlsequencereset.py C 5:0 Command - A (4) M 17:4 Command.handle_app_config - A (4) M 10:4 Command.add_arguments - A (1) django/core/management/commands/dbshell.py C 7:0 Command - A (3) M 23:4 Command.handle - A (3) M 15:4 Command.add_arguments - A (1) django/core/management/commands/sendtestemail.py C 8:0 Command - A (3) M 26:4 Command.handle - A (3) M 12:4 Command.add_arguments - A (1) django/core/management/commands/startproject.py C 7:0 Command - A (2) M 14:4 Command.handle - A (1) django/core/management/commands/migrate.py M 72:4 Command.handle - F (45) C 21:0 Command - C (18) M 272:4 Command.migration_progress_callback - C (16) M 306:4 Command.sync_apps - C (12) M 356:4 Command.describe_operation - C (11) M 25:4 Command.add_arguments - A (1) django/core/management/commands/compilemessages.py M 59:4 Command.handle - C (20) M 118:4 Command.compile_messages - C (13) C 30:0 Command - C (12) F 19:0 is_writable - A (2) F 13:0 has_bom - A (1) M 38:4 Command.add_arguments - A (1) django/core/management/commands/diffsettings.py M 57:4 Command.output_hash - A (5) M 69:4 Command.output_unified - A (5) C 9:0 Command - A (4) F 4:0 module_to_dict - A (3) M 41:4 Command.handle - A (3) M 15:4 Command.add_arguments - A (1) django/core/management/commands/testserver.py C 6:0 Command - A (2) M 11:4 Command.add_arguments - A (1) M 29:4 Command.handle - A (1) django/core/serializers/pyyaml.py F 67:0 Deserializer - A (5) C 41:0 Serializer - A (3) M 46:4 Serializer.handle_field - A (3) C 26:0 DjangoSafeDumper - A (2) M 27:4 DjangoSafeDumper.represent_decimal - A (1) M 30:4 DjangoSafeDumper.represent_ordered_dict - A (1) M 58:4 Serializer.end_serialization - A (1) M 62:4 Serializer.getvalue - A (1) django/core/serializers/__init__.py F 160:0 sort_dependencies - D (23) F 54:0 register_serializer - A (5) F 109:0 get_public_serializer_formats - A (4) F 144:0 _load_serializers - A (4) F 86:0 unregister_serializer - A (3) F 95:0 get_serializer - A (3) F 115:0 get_deserializer - A (3) F 103:0 get_serializer_formats - A (2) C 37:0 BadSerializer - A (2) F 123:0 serialize - A (1) F 133:0 deserialize - A (1) M 47:4 BadSerializer.__init__ - A (1) M 50:4 BadSerializer.__call__ - A (1) django/core/serializers/xml_serializer.py M 180:4 Deserializer._handle_object - C (18) M 250:4 Deserializer._handle_fk_field_node - B (8) C 159:0 Deserializer - B (7) M 285:4 Deserializer._handle_m2m_field_node - B (7) F 335:0 getInnerText - A (5) M 42:4 Serializer.start_object - A (5) M 93:4 Serializer.handle_fk_field - A (5) M 116:4 Serializer.handle_m2m_field - A (5) M 65:4 Serializer.handle_field - A (4) M 173:4 Deserializer.__next__ - A (4) C 19:0 Serializer - A (3) M 317:4 Deserializer._get_model_from_node - A (3) M 22:4 Serializer.indent - A (2) C 352:0 DefusedExpatParser - A (2) C 386:0 DefusedXmlException - A (2) C 392:0 DTDForbidden - A (2) C 405:0 EntitiesForbidden - A (2) C 421:0 ExternalReferenceForbidden - A (2) M 26:4 Serializer.start_serialization - A (1) M 34:4 Serializer.end_serialization - A (1) M 58:4 Serializer.end_object - A (1) M 149:4 Serializer._start_relational_field - A (1) M 162:4 Deserializer.__init__ - A (1) M 169:4 Deserializer._make_parser - A (1) M 358:4 DefusedExpatParser.__init__ - A (1) M 363:4 DefusedExpatParser.start_doctype_decl - A (1) M 366:4 DefusedExpatParser.entity_decl - A (1) M 370:4 DefusedExpatParser.unparsed_entity_decl - A (1) M 374:4 DefusedExpatParser.external_entity_ref_handler - A (1) M 377:4 DefusedExpatParser.reset - A (1) M 388:4 DefusedXmlException.__repr__ - A (1) M 394:4 DTDForbidden.__init__ - A (1) M 400:4 DTDForbidden.__str__ - A (1) M 407:4 EntitiesForbidden.__init__ - A (1) M 416:4 EntitiesForbidden.__str__ - A (1) M 423:4 ExternalReferenceForbidden.__init__ - A (1) M 430:4 ExternalReferenceForbidden.__str__ - A (1) django/core/serializers/jsonl.py F 42:0 Deserializer - B (7) C 14:0 Serializer - A (2) M 18:4 Serializer._init_options - A (1) M 28:4 Serializer.start_serialization - A (1) M 31:4 Serializer.end_object - A (1) M 37:4 Serializer.getvalue - A (1) django/core/serializers/python.py F 80:0 Deserializer - C (20) M 62:4 Serializer.handle_m2m_field - A (5) M 51:4 Serializer.handle_fk_field - A (4) C 13:0 Serializer - A (3) M 34:4 Serializer.get_dump_object - A (3) F 152:0 _get_model - A (2) M 41:4 Serializer._value_from_field - A (2) M 20:4 Serializer.start_serialization - A (1) M 24:4 Serializer.end_serialization - A (1) M 27:4 Serializer.start_object - A (1) M 30:4 Serializer.end_object - A (1) M 48:4 Serializer.handle_field - A (1) M 76:4 Serializer.getvalue - A (1) django/core/serializers/json.py C 77:0 DjangoJSONEncoder - C (11) M 82:4 DjangoJSONEncoder.default - B (10) F 62:0 Deserializer - A (5) M 45:4 Serializer.end_object - A (4) C 19:0 Serializer - A (3) M 38:4 Serializer.end_serialization - A (3) M 23:4 Serializer._init_options - A (2) M 34:4 Serializer.start_serialization - A (1) M 57:4 Serializer.getvalue - A (1) django/core/serializers/base.py M 75:4 Serializer.serialize - C (19) F 301:0 deserialize_fk_value - B (8) F 273:0 deserialize_m2m_values - B (7) M 232:4 DeserializedObject.save_deferred_fields - B (6) F 252:0 build_instance - A (5) M 49:4 ProgressBar.update - A (5) C 41:0 ProgressBar - A (4) C 64:0 Serializer - A (4) C 195:0 DeserializedObject - A (4) M 219:4 DeserializedObject.save - A (4) C 22:0 DeserializationError - A (2) C 34:0 M2MDeserializationError - A (2) M 163:4 Serializer.getvalue - A (2) C 172:0 Deserializer - A (2) M 177:4 Deserializer.__init__ - A (2) C 12:0 SerializerDoesNotExist - A (1) C 17:0 SerializationError - A (1) M 26:4 DeserializationError.WithData - A (1) M 36:4 M2MDeserializationError.__init__ - A (1) M 44:4 ProgressBar.__init__ - A (1) M 121:4 Serializer.start_serialization - A (1) M 127:4 Serializer.end_serialization - A (1) M 133:4 Serializer.start_object - A (1) M 139:4 Serializer.end_object - A (1) M 145:4 Serializer.handle_field - A (1) M 151:4 Serializer.handle_fk_field - A (1) M 157:4 Serializer.handle_m2m_field - A (1) M 187:4 Deserializer.__iter__ - A (1) M 190:4 Deserializer.__next__ - A (1) M 207:4 DeserializedObject.__init__ - A (1) M 212:4 DeserializedObject.__repr__ - A (1) django/core/files/locks.py F 24:0 _fd - A (2) F 109:8 lock - A (2) F 79:4 lock - A (1) F 85:4 unlock - A (1) F 101:8 lock - A (1) F 105:8 unlock - A (1) F 116:8 unlock - A (1) C 50:4 _OFFSET - A (1) C 55:4 _OFFSET_UNION - A (1) C 61:4 OVERLAPPED - A (1) django/core/files/uploadhandler.py C 27:0 StopUpload - A (3) M 157:4 TemporaryFileUploadHandler.upload_interrupted - A (3) C 167:0 MemoryFileUploadHandler - A (3) M 39:4 StopUpload.__str__ - A (2) C 61:0 FileUploadHandler - A (2) C 138:0 TemporaryFileUploadHandler - A (2) M 181:4 MemoryFileUploadHandler.new_file - A (2) M 187:4 MemoryFileUploadHandler.receive_data_chunk - A (2) M 194:4 MemoryFileUploadHandler.file_complete - A (2) F 211:0 load_handler - A (1) C 20:0 UploadFileException - A (1) M 31:4 StopUpload.__init__ - A (1) C 46:0 SkipFile - A (1) C 53:0 StopFutureHandlers - A (1) M 67:4 FileUploadHandler.__init__ - A (1) M 75:4 FileUploadHandler.handle_raw_input - A (1) M 93:4 FileUploadHandler.new_file - A (1) M 107:4 FileUploadHandler.receive_data_chunk - A (1) M 114:4 FileUploadHandler.file_complete - A (1) M 123:4 FileUploadHandler.upload_complete - A (1) M 130:4 FileUploadHandler.upload_interrupted - A (1) M 142:4 TemporaryFileUploadHandler.new_file - A (1) M 149:4 TemporaryFileUploadHandler.receive_data_chunk - A (1) M 152:4 TemporaryFileUploadHandler.file_complete - A (1) M 172:4 MemoryFileUploadHandler.handle_raw_input - A (1) django/core/files/utils.py C 1:0 FileProxyMixin - A (3) M 30:4 FileProxyMixin.readable - A (3) M 37:4 FileProxyMixin.writable - A (3) M 44:4 FileProxyMixin.seekable - A (3) M 27:4 FileProxyMixin.closed - A (2) M 51:4 FileProxyMixin.__iter__ - A (1) django/core/files/uploadedfile.py M 38:4 UploadedFile._set_name - A (3) C 99:0 SimpleUploadedFile - A (3) C 16:0 UploadedFile - A (2) C 55:0 TemporaryUploadedFile - A (2) M 68:4 TemporaryUploadedFile.close - A (2) C 78:0 InMemoryUploadedFile - A (2) M 103:4 SimpleUploadedFile.__init__ - A (2) M 25:4 UploadedFile.__init__ - A (1) M 32:4 UploadedFile.__repr__ - A (1) M 35:4 UploadedFile._get_name - A (1) M 59:4 TemporaryUploadedFile.__init__ - A (1) M 64:4 TemporaryUploadedFile.temporary_file_path - A (1) M 82:4 InMemoryUploadedFile.__init__ - A (1) M 86:4 InMemoryUploadedFile.open - A (1) M 90:4 InMemoryUploadedFile.chunks - A (1) M 94:4 InMemoryUploadedFile.multiple_chunks - A (1) M 108:4 SimpleUploadedFile.from_dict - A (1) django/core/files/temp.py M 48:8 TemporaryFile.close - A (4) C 28:4 TemporaryFile - A (2) M 37:8 TemporaryFile.__init__ - A (1) M 60:8 TemporaryFile.__del__ - A (1) M 63:8 TemporaryFile.__enter__ - A (1) M 67:8 TemporaryFile.__exit__ - A (1) django/core/files/storage.py M 233:4 FileSystemStorage._save - C (12) M 71:4 Storage.get_available_name - B (7) M 193:4 FileSystemStorage._clear_cached_properties - A (5) M 296:4 FileSystemStorage.delete - A (4) M 38:4 Storage.save - A (3) C 177:0 FileSystemStorage - A (3) M 217:4 FileSystemStorage.base_url - A (3) M 313:4 FileSystemStorage.listdir - A (3) M 329:4 FileSystemStorage.url - A (3) F 358:0 get_storage_class - A (2) C 25:0 Storage - A (2) M 205:4 FileSystemStorage._value_or_setting - A (2) M 337:4 FileSystemStorage._datetime_from_timestamp - A (2) C 362:0 DefaultStorage - A (2) M 34:4 Storage.open - A (1) M 56:4 Storage.get_valid_name - A (1) M 63:4 Storage.get_alternative_name - A (1) M 101:4 Storage.generate_filename - A (1) M 110:4 Storage.path - A (1) M 121:4 Storage.delete - A (1) M 127:4 Storage.exists - A (1) M 134:4 Storage.listdir - A (1) M 141:4 Storage.size - A (1) M 147:4 Storage.url - A (1) M 154:4 Storage.get_accessed_time - A (1) M 161:4 Storage.get_created_time - A (1) M 168:4 Storage.get_modified_time - A (1) M 185:4 FileSystemStorage.__init__ - A (1) M 209:4 FileSystemStorage.base_location - A (1) M 213:4 FileSystemStorage.location - A (1) M 223:4 FileSystemStorage.file_permissions_mode - A (1) M 227:4 FileSystemStorage.directory_permissions_mode - A (1) M 230:4 FileSystemStorage._open - A (1) M 310:4 FileSystemStorage.exists - A (1) M 323:4 FileSystemStorage.path - A (1) M 326:4 FileSystemStorage.size - A (1) M 348:4 FileSystemStorage.get_accessed_time - A (1) M 351:4 FileSystemStorage.get_created_time - A (1) M 354:4 FileSystemStorage.get_modified_time - A (1) M 363:4 DefaultStorage._setup - A (1) django/core/files/images.py F 33:0 get_image_dimensions - B (10) C 12:0 ImageFile - A (2) M 25:4 ImageFile._get_image_dimensions - A (2) M 18:4 ImageFile.width - A (1) M 22:4 ImageFile.height - A (1) django/core/files/move.py F 30:0 file_move_safe - C (11) F 17:0 _samefile - A (3) django/core/files/base.py M 75:4 File.__iter__ - B (8) M 32:4 File.size - B (6) M 48:4 File.chunks - A (5) M 108:4 File.open - A (5) C 8:0 File - A (4) M 11:4 File.__init__ - A (3) F 148:0 endswith_cr - A (2) F 153:0 endswith_lf - A (2) F 158:0 equals_lf - A (2) M 19:4 File.__str__ - A (2) M 22:4 File.__repr__ - A (2) M 65:4 File.multiple_chunks - A (2) C 121:0 ContentFile - A (2) M 125:4 ContentFile.__init__ - A (2) M 25:4 File.__bool__ - A (1) M 28:4 File.__len__ - A (1) M 102:4 File.__enter__ - A (1) M 105:4 File.__exit__ - A (1) M 117:4 File.close - A (1) M 130:4 ContentFile.__str__ - A (1) M 133:4 ContentFile.__bool__ - A (1) M 136:4 ContentFile.open - A (1) M 140:4 ContentFile.close - A (1) M 143:4 ContentFile.write - A (1) django/core/handlers/exception.py F 54:0 response_for_exception - C (12) F 136:0 handle_uncaught_exception - A (3) F 21:0 convert_exception_to_response - A (2) F 125:0 get_exception_response - A (2) django/core/handlers/asgi.py M 31:4 ASGIRequest.__init__ - C (11) M 217:4 ASGIHandler.send_response - B (9) C 126:0 ASGIHandler - A (5) M 136:4 ASGIHandler.__call__ - A (5) M 170:4 ASGIHandler.read_body - A (5) C 22:0 ASGIRequest - A (4) M 188:4 ASGIHandler.create_request - A (3) M 205:4 ASGIHandler.handle_uncaught_exception - A (3) M 265:4 ASGIHandler.chunk_bytes - A (3) M 281:4 ASGIHandler.get_script_prefix - A (3) M 102:4 ASGIRequest._get_scheme - A (2) M 105:4 ASGIRequest._get_post - A (2) M 113:4 ASGIRequest._get_files - A (2) M 99:4 ASGIRequest.GET - A (1) M 110:4 ASGIRequest._set_post - A (1) M 122:4 ASGIRequest.COOKIES - A (1) M 132:4 ASGIHandler.__init__ - A (1) django/core/handlers/base.py M 26:4 BaseHandler.load_middleware - C (15) M 212:4 BaseHandler._get_response_async - C (14) M 160:4 BaseHandler._get_response - C (12) M 99:4 BaseHandler.adapt_method_mode - B (10) C 20:0 BaseHandler - B (8) M 294:4 BaseHandler.check_response - B (7) M 322:4 BaseHandler.make_view_atomic - A (5) M 333:4 BaseHandler.process_exception_by_middleware - A (3) M 126:4 BaseHandler.get_response - A (2) M 140:4 BaseHandler.get_response_async - A (2) M 277:4 BaseHandler.resolve_request - A (2) F 345:0 reset_urlconf - A (1) django/core/handlers/wsgi.py M 44:4 LimitedStream.readline - B (7) F 159:0 get_script_name - B (6) C 15:0 LimitedStream - A (5) M 23:4 LimitedStream._read_limited - A (4) C 122:0 WSGIHandler - A (4) M 129:4 WSGIHandler.__call__ - A (4) M 32:4 LimitedStream.read - A (3) M 65:4 WSGIRequest.__init__ - A (3) C 64:0 WSGIRequest - A (2) M 100:4 WSGIRequest._get_post - A (2) M 114:4 WSGIRequest.FILES - A (2) F 152:0 get_path_info - A (1) F 190:0 get_bytes_from_wsgi - A (1) F 203:0 get_str_from_wsgi - A (1) M 17:4 LimitedStream.__init__ - A (1) M 91:4 WSGIRequest._get_scheme - A (1) M 95:4 WSGIRequest.GET - A (1) M 105:4 WSGIRequest._set_post - A (1) M 109:4 WSGIRequest.COOKIES - A (1) M 125:4 WSGIHandler.__init__ - A (1) django/core/servers/basehttp.py M 128:4 WSGIRequestHandler.log_message - B (7) M 101:4 ServerHandler.cleanup_headers - A (4) C 121:0 WSGIRequestHandler - A (4) F 26:0 get_internal_wsgi_application - A (3) F 199:0 run - A (3) C 62:0 WSGIServer - A (3) C 85:0 ServerHandler - A (3) M 158:4 WSGIRequestHandler.get_environ - A (3) M 169:4 WSGIRequestHandler.handle - A (3) M 179:4 WSGIRequestHandler.handle_one_request - A (3) M 67:4 WSGIServer.__init__ - A (2) M 73:4 WSGIServer.handle_error - A (2) M 88:4 ServerHandler.__init__ - A (2) F 53:0 is_broken_pipe_error - A (1) C 80:0 ThreadedWSGIServer - A (1) M 116:4 ServerHandler.close - A (1) M 124:4 WSGIRequestHandler.address_string - A (1) django/test/signals.py F 186:0 user_model_swapped - C (13) F 53:0 update_connections_time_zone - B (8) F 87:0 reset_template_engines - A (3) F 114:0 language_changed - A (3) F 126:0 localize_settings_changed - A (3) F 139:0 complex_setting_changed - A (3) F 27:0 clear_cache_handlers - A (2) F 36:0 update_installed_apps - A (2) F 81:0 clear_routers_cache - A (2) F 107:0 clear_serializers_cache - A (2) F 132:0 file_storage_changed - A (2) F 148:0 root_urlconf_changed - A (2) F 156:0 static_storage_changed - A (2) F 167:0 static_finders_changed - A (2) F 177:0 auth_password_validators_changed - A (2) django/test/runner.py M 555:4 DiscoverRunner.build_suite - D (23) M 442:4 DiscoverRunner.__init__ - C (14) M 375:4 ParallelTestSuite.run - B (8) F 792:0 partition_suite_by_type - B (7) M 684:4 DiscoverRunner._get_databases - B (7) F 831:0 filter_tests_by_tags - B (6) M 709:4 DiscoverRunner.run_tests - B (6) C 433:0 DiscoverRunner - A (5) M 701:4 DiscoverRunner.get_databases - A (5) F 818:0 partition_suite_by_case - A (4) C 348:0 ParallelTestSuite - A (4) F 295:0 default_test_processes - A (3) F 754:0 is_discoverable - A (3) F 770:0 reorder_suite - A (3) M 72:4 DebugSQLTextTestResult.addSubTest - A (3) M 157:4 RemoteTestResult.check_picklable - A (3) C 273:0 RemoteTestRunner - A (3) M 644:4 DiscoverRunner.get_resultclass - A (3) F 310:0 _init_worker - A (2) C 36:0 DebugSQLTextTestResult - A (2) M 49:4 DebugSQLTextTestResult.stopTest - A (2) M 57:4 DebugSQLTextTestResult.addError - A (2) M 79:4 DebugSQLTextTestResult.printErrorList - A (2) C 89:0 PDBDebugResult - A (2) C 109:0 RemoteTestResult - A (2) M 120:4 RemoteTestResult.__init__ - A (2) M 204:4 RemoteTestResult.check_subtest_picklable - A (2) M 211:4 RemoteTestResult.stop_if_failfast - A (2) M 241:4 RemoteTestResult.addSubTest - A (2) M 258:4 RemoteTestResult.addExpectedFailure - A (2) M 282:4 RemoteTestRunner.__init__ - A (2) F 335:0 _run_subsuite - A (1) M 37:4 DebugSQLTextTestResult.__init__ - A (1) M 43:4 DebugSQLTextTestResult.startTest - A (1) M 67:4 DebugSQLTextTestResult.addFailure - A (1) M 95:4 PDBDebugResult.addError - A (1) M 99:4 PDBDebugResult.addFailure - A (1) M 103:4 PDBDebugResult.debug - A (1) M 130:4 RemoteTestResult.test_index - A (1) M 133:4 RemoteTestResult._confirm_picklable - A (1) M 141:4 RemoteTestResult._print_unpicklable_subtest - A (1) M 215:4 RemoteTestResult.stop - A (1) M 218:4 RemoteTestResult.startTestRun - A (1) M 221:4 RemoteTestResult.stopTestRun - A (1) M 224:4 RemoteTestResult.startTest - A (1) M 228:4 RemoteTestResult.stopTest - A (1) M 231:4 RemoteTestResult.addError - A (1) M 236:4 RemoteTestResult.addFailure - A (1) M 252:4 RemoteTestResult.addSuccess - A (1) M 255:4 RemoteTestResult.addSkip - A (1) M 268:4 RemoteTestResult.addUnexpectedSuccess - A (1) M 287:4 RemoteTestRunner.run - A (1) M 369:4 ParallelTestSuite.__init__ - A (1) M 429:4 ParallelTestSuite.__iter__ - A (1) M 486:4 DiscoverRunner.add_arguments - A (1) M 551:4 DiscoverRunner.setup_test_environment - A (1) M 638:4 DiscoverRunner.setup_databases - A (1) M 650:4 DiscoverRunner.get_test_runner_kwargs - A (1) M 658:4 DiscoverRunner.run_checks - A (1) M 663:4 DiscoverRunner.run_suite - A (1) M 668:4 DiscoverRunner.teardown_databases - A (1) M 677:4 DiscoverRunner.teardown_test_environment - A (1) M 681:4 DiscoverRunner.suite_result - A (1) django/test/client.py F 225:0 encode_multipart - B (10) M 811:4 Client._handle_redirects - B (10) F 279:0 encode_file - B (7) M 527:4 AsyncRequestFactory.generic - B (7) F 99:0 conditional_content_removal - B (6) M 71:4 FakePayload.read - A (5) M 449:4 RequestFactory.generic - A (5) C 476:0 AsyncRequestFactory - A (5) M 883:4 AsyncClient.request - A (5) C 166:0 AsyncClientHandler - A (4) M 172:4 AsyncClientHandler.__call__ - A (4) M 695:4 Client.request - A (4) C 869:0 AsyncClient - A (4) C 54:0 FakePayload - A (3) C 118:0 ClientHandler - A (3) M 128:4 ClientHandler.__call__ - A (3) M 362:4 RequestFactory._encode_data - A (3) M 374:4 RequestFactory._encode_json - A (3) C 561:0 ClientMixin - A (3) M 569:4 ClientMixin.check_exception - A (3) M 621:4 ClientMixin._login - A (3) M 659:4 ClientMixin._parse_json - A (3) C 670:0 Client - A (3) F 212:0 store_rendered_templates - A (2) C 46:0 RedirectCycleError - A (2) M 61:4 FakePayload.__init__ - A (2) M 82:4 FakePayload.write - A (2) C 308:0 RequestFactory - A (2) M 327:4 RequestFactory._base_environ - A (2) M 382:4 RequestFactory._get_path - A (2) M 393:4 RequestFactory.get - A (2) M 401:4 RequestFactory.post - A (2) M 410:4 RequestFactory.head - A (2) M 490:4 AsyncRequestFactory._base_scope - A (2) M 516:4 AsyncRequestFactory.request - A (2) M 583:4 ClientMixin.session - A (2) M 594:4 ClientMixin.login - A (2) M 608:4 ClientMixin.force_login - A (2) M 646:4 ClientMixin.logout - A (2) M 742:4 Client.get - A (2) M 750:4 Client.post - A (2) M 759:4 Client.head - A (2) M 767:4 Client.options - A (2) M 776:4 Client.put - A (2) M 785:4 Client.patch - A (2) M 794:4 Client.delete - A (2) M 803:4 Client.trace - A (2) F 90:0 closing_iterator_wrapper - A (1) M 48:4 RedirectCycleError.__init__ - A (1) M 68:4 FakePayload.__len__ - A (1) M 124:4 ClientHandler.__init__ - A (1) M 168:4 AsyncClientHandler.__init__ - A (1) M 321:4 RequestFactory.__init__ - A (1) M 358:4 RequestFactory.request - A (1) M 418:4 RequestFactory.trace - A (1) M 422:4 RequestFactory.options - A (1) M 428:4 RequestFactory.put - A (1) M 435:4 RequestFactory.patch - A (1) M 442:4 RequestFactory.delete - A (1) M 565:4 ClientMixin.store_exc_info - A (1) M 688:4 Client.__init__ - A (1) M 876:4 AsyncClient.__init__ - A (1) django/test/html.py M 78:4 Element._count - C (16) M 55:4 Element.__eq__ - B (10) M 23:4 Element.append - B (8) M 196:4 Parser.handle_starttag - B (6) C 17:0 Element - A (5) M 126:4 Element.__str__ - A (5) M 175:4 Parser.format_position - A (5) M 39:4 Element.finalize - A (4) M 211:4 Parser.handle_endtag - A (4) F 226:0 parse_html - A (3) C 145:0 RootElement - A (3) C 157:0 Parser - A (3) M 149:4 RootElement.__str__ - A (2) M 185:4 Parser.current - A (2) M 191:4 Parser.handle_startendtag - A (2) F 13:0 normalize_whitespace - A (1) M 18:4 Element.__init__ - A (1) M 75:4 Element.__hash__ - A (1) M 117:4 Element.__contains__ - A (1) M 120:4 Element.count - A (1) M 123:4 Element.__getitem__ - A (1) M 141:4 Element.__repr__ - A (1) M 146:4 RootElement.__init__ - A (1) C 153:0 HTMLParseError - A (1) M 166:4 Parser.__init__ - A (1) M 172:4 Parser.error - A (1) M 222:4 Parser.handle_data - A (1) django/test/selenium.py M 23:4 SeleniumTestCaseBase.__new__ - B (8) C 11:0 SeleniumTestCaseBase - A (3) M 78:4 SeleniumTestCaseBase.create_options - A (3) M 87:4 SeleniumTestCaseBase.create_webdriver - A (2) C 98:0 SeleniumTestCase - A (2) M 103:4 SeleniumTestCase.live_server_url - A (2) M 107:4 SeleniumTestCase.allowed_host - A (2) M 117:4 SeleniumTestCase._tearDownClassInternal - A (2) M 64:4 SeleniumTestCaseBase.import_webdriver - A (1) M 68:4 SeleniumTestCaseBase.import_options - A (1) M 72:4 SeleniumTestCaseBase.get_capability - A (1) M 111:4 SeleniumTestCase.setUpClass - A (1) M 126:4 SeleniumTestCase.disable_implicit_wait - A (1) django/test/utils.py M 528:4 modify_settings.enable - C (14) F 160:0 setup_databases - C (13) F 280:0 get_unique_databases_and_mirrors - B (9) F 238:0 dependency_ordered - B (8) C 505:0 modify_settings - B (8) M 440:4 override_settings.enable - B (6) M 464:4 override_settings.disable - B (6) F 331:0 teardown_databases - A (5) C 61:0 ContextList - A (4) M 66:4 ContextList.__getitem__ - A (4) C 427:0 override_settings - A (4) M 510:4 modify_settings.__init__ - A (4) M 566:4 override_system_checks.enable - A (4) F 108:0 setup_test_environment - A (3) F 345:0 get_runner - A (3) F 921:0 register_lookup - A (3) M 88:4 ContextList.keys - A (3) M 419:4 TestContextDecorator.__call__ - A (3) C 553:0 override_system_checks - A (3) C 688:0 ignore_warnings - A (3) M 689:4 ignore_warnings.__init__ - A (3) C 879:0 TimeKeeper - A (3) M 893:4 TimeKeeper.print_results - A (3) F 582:0 compare_xml - A (2) C 49:0 Approximate - A (2) M 57:4 Approximate.__eq__ - A (2) M 75:4 ContextList.get - A (2) M 81:4 ContextList.__contains__ - A (2) C 357:0 TestContextDecorator - A (2) M 385:4 TestContextDecorator.decorate_class - A (2) M 400:4 TestContextDecorator.decorate_callable - A (2) M 485:4 override_settings.save_options - A (2) M 495:4 override_settings.decorate_class - A (2) M 520:4 modify_settings.save_options - A (2) C 649:0 CaptureQueriesContext - A (2) M 680:4 CaptureQueriesContext.__exit__ - A (2) C 820:0 override_script_prefix - A (2) C 834:0 LoggingCaptureMixin - A (2) C 849:0 isolate_apps - A (2) C 900:0 NullTimeKeeper - A (2) F 95:0 instrumented_test_render - A (1) F 144:0 teardown_test_environment - A (1) F 719:0 extend_sys_path - A (1) F 730:0 isolate_lru_cache - A (1) F 740:0 captured_output - A (1) F 754:0 captured_stdout - A (1) F 764:0 captured_stderr - A (1) F 774:0 captured_stdin - A (1) F 788:0 freeze_time - A (1) F 804:0 require_jinja2 - A (1) F 909:0 tag - A (1) M 50:4 Approximate.__init__ - A (1) M 54:4 Approximate.__repr__ - A (1) C 104:0 _TestState - A (1) M 369:4 TestContextDecorator.__init__ - A (1) M 373:4 TestContextDecorator.enable - A (1) M 376:4 TestContextDecorator.disable - A (1) M 379:4 TestContextDecorator.__enter__ - A (1) M 382:4 TestContextDecorator.__exit__ - A (1) M 436:4 override_settings.__init__ - A (1) M 559:4 override_system_checks.__init__ - A (1) M 577:4 override_system_checks.disable - A (1) M 653:4 CaptureQueriesContext.__init__ - A (1) M 656:4 CaptureQueriesContext.__iter__ - A (1) M 659:4 CaptureQueriesContext.__getitem__ - A (1) M 662:4 CaptureQueriesContext.__len__ - A (1) M 666:4 CaptureQueriesContext.captured_queries - A (1) M 669:4 CaptureQueriesContext.__enter__ - A (1) M 697:4 ignore_warnings.enable - A (1) M 702:4 ignore_warnings.disable - A (1) M 822:4 override_script_prefix.__init__ - A (1) M 826:4 override_script_prefix.enable - A (1) M 830:4 override_script_prefix.disable - A (1) M 839:4 LoggingCaptureMixin.setUp - A (1) M 845:4 LoggingCaptureMixin.tearDown - A (1) M 865:4 isolate_apps.__init__ - A (1) M 869:4 isolate_apps.enable - A (1) M 875:4 isolate_apps.disable - A (1) M 880:4 TimeKeeper.__init__ - A (1) M 884:4 TimeKeeper.timed - A (1) M 902:4 NullTimeKeeper.timed - A (1) M 905:4 NullTimeKeeper.print_results - A (1) django/test/testcases.py M 619:4 SimpleTestCase._assert_template_used - C (13) M 484:4 SimpleTestCase.assertFormError - C (11) M 539:4 SimpleTestCase.assertFormsetError - C (11) M 1043:4 TransactionTestCase.assertQuerysetEqual - C (11) M 252:4 SimpleTestCase._setup_and_call - B (10) M 423:4 SimpleTestCase._assert_contains - B (9) M 1182:4 TestCase.setUpClass - B (9) M 319:4 SimpleTestCase.assertRedirects - B (8) M 973:4 TransactionTestCase._fixture_setup - B (8) M 733:4 SimpleTestCase.assertFieldOutput - B (7) C 890:0 TransactionTestCase - B (6) M 915:4 TransactionTestCase._pre_setup - B (6) M 186:4 SimpleTestCase._validate_databases - A (5) M 953:4 TransactionTestCase._databases_names - A (5) M 1283:4 CheckCondition.__get__ - A (5) M 1464:4 LiveServerThread.run - A (5) M 1530:4 LiveServerTestCase.setUpClass - A (5) F 1086:0 connections_support_transactions - A (4) M 118:4 _AssertTemplateUsedContext.__exit__ - A (4) C 151:0 SimpleTestCase - A (4) M 203:4 SimpleTestCase._add_databases_failures - A (4) M 219:4 SimpleTestCase._remove_databases_failures - A (4) M 643:4 SimpleTestCase.assertTemplateUsed - A (4) M 819:4 SimpleTestCase.assertJSONEqual - A (4) M 836:4 SimpleTestCase.assertJSONNotEqual - A (4) M 853:4 SimpleTestCase.assertXMLEqual - A (4) M 873:4 SimpleTestCase.assertXMLNotEqual - A (4) M 962:4 TransactionTestCase._reset_sequences - A (4) M 998:4 TransactionTestCase._post_teardown - A (4) M 1025:4 TransactionTestCase._fixture_teardown - A (4) C 1148:0 TestCase - A (4) M 1243:4 TestCase._fixture_teardown - A (4) M 1261:4 TestCase.captureOnCommitCallbacks - A (4) F 52:0 to_list - A (3) C 73:0 _AssertNumQueriesContext - A (3) M 79:4 _AssertNumQueriesContext.__exit__ - A (3) M 175:4 SimpleTestCase.setUpClass - A (3) M 229:4 SimpleTestCase.tearDownClass - A (3) M 695:4 SimpleTestCase._assertFooMessage - A (3) C 1095:0 TestData - A (3) M 1120:4 TestData.__get__ - A (3) M 1215:4 TestCase.tearDownClass - A (3) M 1233:4 TestCase._fixture_setup - A (3) M 1253:4 TestCase._should_check_constraints - A (3) C 1275:0 CheckCondition - A (3) M 1401:4 FSFilesHandler.get_response - A (3) C 1450:0 LiveServerThread - A (3) C 1505:0 LiveServerTestCase - A (3) C 1582:0 SerializeMixin - A (3) F 64:0 assert_and_parse_html - A (2) F 1342:0 skipIfDBFeature - A (2) F 1351:0 skipUnlessDBFeature - A (2) F 1360:0 skipUnlessAnyDBFeature - A (2) C 95:0 _AssertTemplateUsedContext - A (2) C 134:0 _AssertTemplateNotUsedContext - A (2) C 142:0 _DatabaseFailure - A (2) M 454:4 SimpleTestCase.assertContains - A (2) M 672:4 SimpleTestCase.assertTemplateNotUsed - A (2) M 779:4 SimpleTestCase.assertHTMLEqual - A (2) M 797:4 SimpleTestCase.assertHTMLNotEqual - A (2) M 807:4 SimpleTestCase.assertInHTML - A (2) M 1075:4 TransactionTestCase.assertNumQueries - A (2) M 1112:4 TestData.get_memo - A (2) M 1162:4 TestCase._enter_atomics - A (2) M 1171:4 TestCase._rollback_atomics - A (2) M 1228:4 TestCase._should_reload_connections - A (2) C 1369:0 QuietWSGIRequestHandler - A (2) C 1378:0 FSFilesHandler - A (2) M 1388:4 FSFilesHandler._should_handle - A (2) M 1420:4 FSFilesHandler.__call__ - A (2) C 1426:0 _StaticFilesHandler - A (2) C 1438:0 _MediaFilesHandler - A (2) M 1497:4 LiveServerThread.terminate - A (2) M 1567:4 LiveServerTestCase._tearDownClassInternal - A (2) M 1594:4 SerializeMixin.setUpClass - A (2) F 1296:0 _deferredSkip - A (1) M 74:4 _AssertNumQueriesContext.__init__ - A (1) M 96:4 _AssertTemplateUsedContext.__init__ - A (1) M 103:4 _AssertTemplateUsedContext.on_template_render - A (1) M 108:4 _AssertTemplateUsedContext.test - A (1) M 111:4 _AssertTemplateUsedContext.message - A (1) M 114:4 _AssertTemplateUsedContext.__enter__ - A (1) M 135:4 _AssertTemplateNotUsedContext.test - A (1) M 138:4 _AssertTemplateNotUsedContext.message - A (1) M 143:4 _DatabaseFailure.__init__ - A (1) M 147:4 _DatabaseFailure.__call__ - A (1) M 239:4 SimpleTestCase.__call__ - A (1) M 247:4 SimpleTestCase.debug - A (1) M 291:4 SimpleTestCase._pre_setup - A (1) M 301:4 SimpleTestCase._post_teardown - A (1) M 305:4 SimpleTestCase.settings - A (1) M 312:4 SimpleTestCase.modify_settings - A (1) M 403:4 SimpleTestCase.assertURLEqual - A (1) M 473:4 SimpleTestCase.assertNotContains - A (1) M 690:4 SimpleTestCase._assert_raises_or_warns_cm - A (1) M 707:4 SimpleTestCase.assertRaisesMessage - A (1) M 723:4 SimpleTestCase.assertWarnsMessage - A (1) M 995:4 TransactionTestCase._should_reload_connections - A (1) M 1108:4 TestData.__init__ - A (1) M 1144:4 TestData.__repr__ - A (1) M 1178:4 TestCase._databases_support_transactions - A (1) M 1224:4 TestCase.setUpTestData - A (1) M 1277:4 CheckCondition.__init__ - A (1) M 1280:4 CheckCondition.add_condition - A (1) M 1374:4 QuietWSGIRequestHandler.log_message - A (1) M 1383:4 FSFilesHandler.__init__ - A (1) M 1396:4 FSFilesHandler.file_path - A (1) M 1411:4 FSFilesHandler.serve - A (1) M 1431:4 _StaticFilesHandler.get_base_dir - A (1) M 1434:4 _StaticFilesHandler.get_base_url - A (1) M 1443:4 _MediaFilesHandler.get_base_dir - A (1) M 1446:4 _MediaFilesHandler.get_base_url - A (1) M 1455:4 LiveServerThread.__init__ - A (1) M 1490:4 LiveServerThread._create_server - A (1) M 1522:4 LiveServerTestCase.live_server_url - A (1) M 1526:4 LiveServerTestCase.allowed_host - A (1) M 1558:4 LiveServerTestCase._create_server_thread - A (1) M 1578:4 LiveServerTestCase.tearDownClass - A (1) M 1604:4 SerializeMixin.tearDownClass - A (1) django/dispatch/dispatcher.py M 224:4 Signal._live_receivers - C (13) M 46:4 Signal.connect - C (11) C 22:0 Signal - B (6) M 175:4 Signal.send_robust - B (6) M 215:4 Signal._clear_dead_receivers - A (5) M 110:4 Signal.disconnect - A (4) M 149:4 Signal.send - A (4) F 10:0 _make_id - A (2) M 31:4 Signal.__init__ - A (2) F 273:0 receiver - A (1) M 146:4 Signal.has_listeners - A (1) M 263:4 Signal._remove_receiver - A (1) django/template/library.py F 237:0 parse_bits - D (21) M 54:4 Library.filter - C (11) M 27:4 Library.tag - B (8) M 207:4 InclusionNode.render - B (7) C 201:0 InclusionNode - A (5) C 16:0 Library - A (4) C 164:0 TagHelperNode - A (4) M 176:4 TagHelperNode.get_resolved_arguments - A (4) F 312:0 import_library - A (3) M 100:4 Library.simple_tag - A (3) C 184:0 SimpleNode - A (3) M 190:4 SimpleNode.render - A (3) C 12:0 InvalidTemplateLibrary - A (1) M 23:4 Library.__init__ - A (1) M 50:4 Library.tag_function - A (1) M 96:4 Library.filter_function - A (1) M 136:4 Library.inclusion_tag - A (1) M 170:4 TagHelperNode.__init__ - A (1) M 186:4 SimpleNode.__init__ - A (1) M 203:4 InclusionNode.__init__ - A (1) django/template/response.py M 45:4 SimpleTemplateResponse.__getstate__ - A (4) M 96:4 SimpleTemplateResponse.render - A (4) C 10:0 SimpleTemplateResponse - A (3) M 60:4 SimpleTemplateResponse.resolve_template - A (3) M 85:4 SimpleTemplateResponse.add_post_render_callback - A (2) M 116:4 SimpleTemplateResponse.__iter__ - A (2) M 124:4 SimpleTemplateResponse.content - A (2) C 138:0 TemplateResponse - A (2) C 6:0 ContentNotRenderedError - A (1) M 13:4 SimpleTemplateResponse.__init__ - A (1) M 69:4 SimpleTemplateResponse.resolve_context - A (1) M 73:4 SimpleTemplateResponse.rendered_content - A (1) M 113:4 SimpleTemplateResponse.is_rendered - A (1) M 132:4 SimpleTemplateResponse.content - A (1) M 141:4 TemplateResponse.__init__ - A (1) django/template/smartif.py M 153:4 IfParser.__init__ - B (8) C 150:0 IfParser - A (4) M 38:4 TokenBase.__repr__ - A (3) M 173:4 IfParser.translate_token - A (3) C 11:0 TokenBase - A (2) C 114:0 Literal - A (2) C 140:0 EndToken - A (2) M 181:4 IfParser.next_token - A (2) M 189:4 IfParser.parse - A (2) M 197:4 IfParser.expression - A (2) F 43:0 infix - A (1) F 68:0 prefix - A (1) M 20:4 TokenBase.nud - A (1) M 26:4 TokenBase.led - A (1) M 32:4 TokenBase.display - A (1) M 124:4 Literal.__init__ - A (1) M 127:4 Literal.display - A (1) M 130:4 Literal.nud - A (1) M 133:4 Literal.eval - A (1) M 136:4 Literal.__repr__ - A (1) M 143:4 EndToken.nud - A (1) M 207:4 IfParser.create_var - A (1) django/template/context_processors.py F 35:0 debug - A (4) F 17:0 csrf - A (1) F 53:0 i18n - A (1) F 62:0 tz - A (1) F 67:0 static - A (1) F 74:0 media - A (1) F 81:0 request - A (1) django/template/defaultfilters.py F 95:0 floatformat - C (15) F 826:0 filesizeformat - B (9) F 869:0 pluralize - B (8) F 788:0 yesno - B (6) F 191:0 linenumbers - A (5) F 541:0 join - A (4) F 586:0 slice_filter - A (4) F 687:0 get_digit - A (4) F 712:0 date - A (4) F 726:0 time - A (4) F 740:0 timesince_filter - A (4) F 237:0 stringformat - A (3) F 396:0 cut - A (3) F 441:0 linebreaksbr - A (3) F 481:0 _property_resolver - A (3) F 675:0 add - A (3) F 753:0 timeuntil_filter - A (3) F 73:0 capfirst - A (2) F 265:0 truncatechars - A (2) F 276:0 truncatechars_html - A (2) F 290:0 truncatewords - A (2) F 304:0 truncatewords_html - A (2) F 325:0 urlencode - A (2) F 429:0 linebreaks_filter - A (2) F 461:0 safeseq - A (2) F 508:0 dictsort - A (2) F 520:0 dictsortreversed - A (2) F 532:0 first - A (2) F 553:0 last - A (2) F 562:0 length - A (2) F 571:0 length_is - A (2) F 604:0 unordered_list - A (2) F 768:0 default - A (2) F 774:0 default_if_none - A (2) F 917:0 pprint - A (2) F 35:0 stringfilter - A (1) F 62:0 addslashes - A (1) F 80:0 escapejs_filter - A (1) F 86:0 json_script - A (1) F 184:0 iriencode - A (1) F 208:0 lower - A (1) F 215:0 make_list - A (1) F 227:0 slugify - A (1) F 257:0 title - A (1) F 318:0 upper - A (1) F 342:0 urlize - A (1) F 349:0 urlizetrunc - A (1) F 361:0 wordcount - A (1) F 368:0 wordwrap - A (1) F 375:0 ljust - A (1) F 382:0 rjust - A (1) F 389:0 center - A (1) F 411:0 escape_filter - A (1) F 418:0 force_escape - A (1) F 455:0 safe - A (1) F 472:0 striptags - A (1) F 580:0 random - A (1) F 782:0 divisibleby - A (1) F 911:0 phone2numeric_filter - A (1) django/template/engine.py M 20:4 Engine.__init__ - B (9) M 165:4 Engine.select_template - A (5) C 13:0 Engine - A (4) M 57:4 Engine.get_default - A (3) M 100:4 Engine.get_template_loaders - A (3) M 108:4 Engine.find_template_loader - A (3) M 121:4 Engine.find_template - A (3) M 149:4 Engine.render_to_string - A (3) M 82:4 Engine.template_context_processors - A (2) M 87:4 Engine.get_template_builtins - A (2) M 90:4 Engine.get_template_libraries - A (2) M 138:4 Engine.get_template - A (2) M 97:4 Engine.template_loaders - A (1) M 131:4 Engine.from_string - A (1) django/template/context.py F 263:0 make_context - A (5) M 48:4 BaseContext.push - A (3) M 66:4 BaseContext.set_upward - A (3) M 78:4 BaseContext.__getitem__ - A (3) M 92:4 BaseContext.get - A (3) C 133:0 Context - A (3) M 161:4 Context.update - A (3) M 200:4 RenderContext.push_state - A (3) C 213:0 RequestContext - A (3) M 234:4 RequestContext.bind_template - A (3) C 13:0 ContextDict - A (2) C 27:0 BaseContext - A (2) M 31:4 BaseContext._reset_dicts - A (2) M 57:4 BaseContext.pop - A (2) M 89:4 BaseContext.__contains__ - A (2) M 98:4 BaseContext.setdefault - A (2) M 114:4 BaseContext.flatten - A (2) M 123:4 BaseContext.__eq__ - A (2) M 147:4 Context.bind_template - A (2) C 170:0 RenderContext - A (2) M 220:4 RequestContext.__init__ - A (2) M 254:4 RequestContext.new - A (2) C 8:0 ContextPopException - A (1) M 14:4 ContextDict.__init__ - A (1) M 20:4 ContextDict.__enter__ - A (1) M 23:4 ContextDict.__exit__ - A (1) M 28:4 BaseContext.__init__ - A (1) M 37:4 BaseContext.__copy__ - A (1) M 42:4 BaseContext.__repr__ - A (1) M 45:4 BaseContext.__iter__ - A (1) M 62:4 BaseContext.__setitem__ - A (1) M 85:4 BaseContext.__delitem__ - A (1) M 105:4 BaseContext.new - A (1) M 135:4 Context.__init__ - A (1) M 156:4 Context.__copy__ - A (1) M 187:4 RenderContext.__iter__ - A (1) M 190:4 RenderContext.__contains__ - A (1) M 193:4 RenderContext.get - A (1) M 196:4 RenderContext.__getitem__ - A (1) django/template/utils.py M 26:4 EngineHandler.templates - B (7) F 94:0 get_app_template_dirs - A (4) C 16:0 EngineHandler - A (4) M 64:4 EngineHandler.__getitem__ - A (3) M 89:4 EngineHandler.all - A (2) C 12:0 InvalidTemplateEngineError - A (1) M 17:4 EngineHandler.__init__ - A (1) M 86:4 EngineHandler.__iter__ - A (1) django/template/loader.py F 22:0 select_template - B (6) F 5:0 get_template - A (3) F 52:0 render_to_string - A (2) F 65:0 _engine_list - A (2) django/template/loader_tags.py F 227:0 construct_relative_path - B (8) M 162:4 IncludeNode.render - B (8) F 285:0 do_include - B (7) M 109:4 ExtendsNode.get_parent - B (6) M 126:4 ExtendsNode.render - B (6) C 153:0 IncludeNode - B (6) F 199:0 do_block - A (5) M 48:4 BlockNode.render - A (4) M 67:4 BlockNode.super - A (4) C 80:0 ExtendsNode - A (4) F 263:0 do_extends - A (3) C 41:0 BlockNode - A (3) C 16:0 BlockContext - A (2) M 21:4 BlockContext.add_blocks - A (2) M 25:4 BlockContext.pop - A (2) M 34:4 BlockContext.get_block - A (2) M 84:4 ExtendsNode.__init__ - A (2) M 156:4 IncludeNode.__init__ - A (2) M 17:4 BlockContext.__init__ - A (1) M 31:4 BlockContext.push - A (1) M 42:4 BlockNode.__init__ - A (1) M 45:4 BlockNode.__repr__ - A (1) M 90:4 ExtendsNode.__repr__ - A (1) M 93:4 ExtendsNode.find_template - A (1) django/template/exceptions.py C 9:0 TemplateDoesNotExist - A (4) M 27:4 TemplateDoesNotExist.__init__ - A (3) C 38:0 TemplateSyntaxError - A (1) django/template/autoreload.py F 9:0 get_template_directories - B (7) F 31:0 reset_loaders - A (4) F 46:0 template_changed - A (3) F 40:0 watch_for_template_changes - A (2) django/template/base.py M 829:4 Variable._resolve_lookup - C (18) F 1014:0 token_kwargs - C (16) M 436:4 Parser.parse - C (13) M 678:4 FilterExpression.resolve - C (13) M 358:4 Lexer.create_token - C (12) M 759:4 Variable.__init__ - C (11) M 634:4 FilterExpression.__init__ - B (10) C 740:0 Variable - B (8) C 620:0 FilterExpression - B (7) M 199:4 Template.get_exception_info - A (5) C 332:0 Lexer - A (5) C 388:0 DebugLexer - A (5) M 503:4 Parser.extend_nodelist - A (5) M 805:4 Variable.resolve - A (5) C 140:0 Template - A (4) M 174:4 Template.compile_nodelist - A (4) M 316:4 Token.split_contents - A (4) M 389:4 DebugLexer.tokenize - A (4) C 414:0 Parser - A (4) M 415:4 Parser.__init__ - A (4) M 496:4 Parser.skip_past - A (4) M 715:4 FilterExpression.args_check - A (4) M 910:4 Node.render_annotated - A (4) M 927:4 Node.get_nodes_by_type - A (4) C 942:0 NodeList - A (4) F 976:0 render_value_in_context - A (3) C 116:0 Origin - A (3) M 125:4 Origin.__eq__ - A (3) M 141:4 Template.__init__ - A (3) C 287:0 Token - A (3) M 344:4 Lexer.tokenize - A (3) M 517:4 Parser.error - A (3) M 530:4 Parser.invalid_block_tag - A (3) C 897:0 Node - A (3) M 947:4 NodeList.render - A (3) F 278:0 linebreak_iter - A (2) C 106:0 VariableDoesNotExist - A (2) M 133:4 Origin.loader_name - A (2) M 157:4 Template.__iter__ - A (2) M 164:4 Template.render - A (2) M 575:4 Parser.find_filter - A (2) M 957:4 NodeList.get_nodes_by_type - A (2) C 965:0 TextNode - A (2) C 992:0 VariableNode - A (2) M 999:4 VariableNode.render - A (2) C 99:0 TokenType - A (1) M 108:4 VariableDoesNotExist.__init__ - A (1) M 112:4 VariableDoesNotExist.__str__ - A (1) M 117:4 Origin.__init__ - A (1) M 122:4 Origin.__str__ - A (1) M 161:4 Template._render - A (1) M 288:4 Token.__init__ - A (1) M 311:4 Token.__repr__ - A (1) M 333:4 Lexer.__init__ - A (1) M 337:4 Lexer.__repr__ - A (1) M 433:4 Parser.__repr__ - A (1) M 547:4 Parser.unclosed_block_tag - A (1) M 556:4 Parser.next_token - A (1) M 559:4 Parser.prepend_token - A (1) M 562:4 Parser.delete_first_token - A (1) M 565:4 Parser.add_library - A (1) M 569:4 Parser.compile_filter - A (1) M 733:4 FilterExpression.__str__ - A (1) M 736:4 FilterExpression.__repr__ - A (1) M 823:4 Variable.__repr__ - A (1) M 826:4 Variable.__str__ - A (1) M 904:4 Node.render - A (1) M 924:4 Node.__iter__ - A (1) M 966:4 TextNode.__init__ - A (1) M 969:4 TextNode.__repr__ - A (1) M 972:4 TextNode.render - A (1) M 993:4 VariableNode.__init__ - A (1) M 996:4 VariableNode.__repr__ - A (1) django/template/defaulttags.py F 525:0 cycle - C (13) M 156:4 ForNode.render - C (12) M 409:4 URLNode.render - B (9) F 712:0 do_for - B (8) F 1251:0 url - B (7) C 134:0 ForNode - B (6) M 227:4 IfChangedNode.render - B (6) C 402:0 URLNode - B (6) M 454:4 WidthRatioNode.render - B (6) F 663:0 firstof - A (5) F 966:0 load_from_library - A (5) F 1020:0 lorem - A (5) F 1159:0 resetcycle - A (5) C 51:0 CsrfTokenNode - A (5) M 279:4 IfNode.render - A (5) M 300:4 LoremNode.render - A (5) C 447:0 WidthRatioNode - A (5) F 827:0 do_if - A (4) F 989:0 load - A (4) F 1067:0 now - A (4) F 1090:0 regroup - A (4) F 1341:0 widthratio - A (4) M 52:4 CsrfTokenNode.render - A (4) M 77:4 CycleNode.render - A (4) C 116:0 FirstOfNode - A (4) M 121:4 FirstOfNode.render - A (4) C 220:0 IfChangedNode - A (4) C 296:0 LoremNode - A (4) F 499:0 autoescape - A (3) F 633:0 do_filter - A (3) F 914:0 ifchanged - A (3) F 1216:0 templatetag - A (3) F 1379:0 do_with - A (3) C 30:0 AutoEscapeControlNode - A (3) C 71:0 CycleNode - A (3) C 96:0 DebugNode - A (3) C 263:0 IfNode - A (3) C 317:0 RegroupNode - A (3) M 328:4 RegroupNode.render - A (3) C 349:0 NowNode - A (3) M 354:4 NowNode.render - A (3) C 480:0 WithNode - A (3) M 481:4 WithNode.__init__ - A (3) F 955:0 find_library - A (2) M 35:4 AutoEscapeControlNode.render - A (2) C 46:0 CommentNode - A (2) M 97:4 DebugNode.render - A (2) C 105:0 FilterNode - A (2) M 137:4 ForNode.__init__ - A (2) M 146:4 ForNode.__repr__ - A (2) M 250:4 IfChangedNode._get_context_stack_frame - A (2) M 271:4 IfNode.__iter__ - A (2) C 344:0 LoadNode - A (2) C 365:0 ResetCycleNode - A (2) C 374:0 SpacelessNode - A (2) C 383:0 TemplateTagNode - A (2) C 439:0 VerbatimNode - A (2) M 492:4 WithNode.render - A (2) C 803:0 TemplateLiteral - A (2) C 815:0 TemplateIfParser - A (2) F 516:0 comment - A (1) F 613:0 csrf_token - A (1) F 618:0 debug - A (1) F 1185:0 spaceless - A (1) F 1318:0 verbatim - A (1) M 32:4 AutoEscapeControlNode.__init__ - A (1) M 47:4 CommentNode.render - A (1) M 72:4 CycleNode.__init__ - A (1) M 89:4 CycleNode.reset - A (1) M 106:4 FilterNode.__init__ - A (1) M 109:4 FilterNode.render - A (1) M 117:4 FirstOfNode.__init__ - A (1) M 223:4 IfChangedNode.__init__ - A (1) M 265:4 IfNode.__init__ - A (1) M 268:4 IfNode.__repr__ - A (1) M 276:4 IfNode.nodelist - A (1) M 297:4 LoremNode.__init__ - A (1) M 318:4 RegroupNode.__init__ - A (1) M 322:4 RegroupNode.resolve_expression - A (1) M 345:4 LoadNode.render - A (1) M 350:4 NowNode.__init__ - A (1) M 366:4 ResetCycleNode.__init__ - A (1) M 369:4 ResetCycleNode.render - A (1) M 375:4 SpacelessNode.__init__ - A (1) M 378:4 SpacelessNode.render - A (1) M 395:4 TemplateTagNode.__init__ - A (1) M 398:4 TemplateTagNode.render - A (1) M 403:4 URLNode.__init__ - A (1) M 440:4 VerbatimNode.__init__ - A (1) M 443:4 VerbatimNode.render - A (1) M 448:4 WidthRatioNode.__init__ - A (1) M 489:4 WithNode.__repr__ - A (1) M 804:4 TemplateLiteral.__init__ - A (1) M 808:4 TemplateLiteral.display - A (1) M 811:4 TemplateLiteral.eval - A (1) M 818:4 TemplateIfParser.__init__ - A (1) M 822:4 TemplateIfParser.create_var - A (1) django/template/backends/django.py F 87:0 get_installed_libraries - B (6) F 114:0 get_package_libraries - A (4) F 66:0 copy_exception - A (3) C 14:0 DjangoTemplates - A (2) M 32:4 DjangoTemplates.get_template - A (2) C 48:0 Template - A (2) M 58:4 Template.render - A (2) F 79:0 reraise - A (1) M 18:4 DjangoTemplates.__init__ - A (1) M 29:4 DjangoTemplates.from_string - A (1) M 38:4 DjangoTemplates.get_templatetag_libraries - A (1) M 50:4 Template.__init__ - A (1) M 55:4 Template.origin - A (1) django/template/backends/jinja2.py M 63:4 Template.render - A (5) F 91:0 get_exception_info - A (4) C 54:0 Template - A (4) C 13:0 Jinja2 - A (3) M 17:4 Jinja2.__init__ - A (3) M 39:4 Jinja2.get_template - A (3) M 50:4 Jinja2.template_context_processors - A (2) C 81:0 Origin - A (2) M 36:4 Jinja2.from_string - A (1) M 56:4 Template.__init__ - A (1) M 86:4 Origin.__init__ - A (1) django/template/backends/utils.py F 7:0 csrf_input - A (1) django/template/backends/dummy.py C 42:0 Template - A (5) M 26:4 TemplateStrings.get_template - A (4) M 44:4 Template.render - A (4) C 11:0 TemplateStrings - A (3) M 15:4 TemplateStrings.__init__ - A (2) M 23:4 TemplateStrings.from_string - A (1) django/template/backends/base.py M 68:4 BaseEngine.iter_template_filenames - A (3) C 9:0 BaseEngine - A (2) M 14:4 BaseEngine.__init__ - A (2) M 58:4 BaseEngine.template_dirs - A (2) M 29:4 BaseEngine.app_dirname - A (1) M 34:4 BaseEngine.from_string - A (1) M 44:4 BaseEngine.get_template - A (1) django/template/loaders/filesystem.py C 12:0 Loader - A (3) M 28:4 Loader.get_template_sources - A (3) M 18:4 Loader.get_dirs - A (2) M 21:4 Loader.get_contents - A (2) M 14:4 Loader.__init__ - A (1) django/template/loaders/cached.py M 29:4 Loader.get_template - B (8) M 71:4 Loader.cache_key - B (7) C 14:0 Loader - A (4) M 21:4 Loader.get_dirs - A (3) M 67:4 Loader.get_template_sources - A (2) M 16:4 Loader.__init__ - A (1) M 26:4 Loader.get_contents - A (1) M 92:4 Loader.generate_hash - A (1) M 95:4 Loader.reset - A (1) django/template/loaders/app_directories.py C 11:0 Loader - A (2) M 13:4 Loader.get_dirs - A (1) django/template/loaders/base.py M 9:4 Loader.get_template - B (6) C 4:0 Loader - A (3) M 6:4 Loader.__init__ - A (1) M 35:4 Loader.get_template_sources - A (1) M 44:4 Loader.reset - A (1) django/template/loaders/locmem.py C 10:0 Loader - A (2) M 16:4 Loader.get_contents - A (2) M 12:4 Loader.__init__ - A (1) M 22:4 Loader.get_template_sources - A (1) django/utils/_os.py F 9:0 safe_join - A (4) F 53:0 to_path - A (3) F 35:0 symlinks_supported - A (2) django/utils/termcolors.py F 137:0 parse_color_setting - C (14) F 13:0 colorize - C (12) F 58:0 make_style - A (1) django/utils/topological_sort.py F 5:0 topological_sort_as_sets - B (8) F 30:0 stable_topological_sort - A (4) C 1:0 CyclicDependencyError - A (1) django/utils/tree.py M 78:4 Node.add - B (8) C 11:0 Node - A (3) M 21:4 Node.__init__ - A (3) M 43:4 Node.__str__ - A (3) M 68:4 Node.__eq__ - A (3) M 30:4 Node._new_instance - A (1) M 47:4 Node.__repr__ - A (1) M 50:4 Node.__deepcopy__ - A (1) M 56:4 Node.__len__ - A (1) M 60:4 Node.__bool__ - A (1) M 64:4 Node.__contains__ - A (1) M 75:4 Node.__hash__ - A (1) M 122:4 Node.negate - A (1) django/utils/hashable.py F 4:0 make_hashable - A (5) django/utils/version.py F 18:0 get_version - A (5) F 49:0 get_complete_version - A (4) F 42:0 get_main_version - A (3) F 93:0 get_version_tuple - A (3) F 63:0 get_docs_version - A (2) F 72:0 get_git_changeset - A (2) django/utils/encoding.py F 46:0 force_str - B (6) F 80:0 force_bytes - B (6) F 150:0 uri_to_iri - A (5) F 208:0 repercent_broken_unicode - A (4) F 100:0 iri_to_uri - A (3) F 241:0 get_system_encoding - A (3) F 19:0 smart_str - A (2) F 68:0 smart_bytes - A (2) F 226:0 filepath_to_uri - A (2) C 10:0 DjangoUnicodeDecodeError - A (2) F 37:0 is_protected_type - A (1) F 186:0 escape_uri_path - A (1) F 203:0 punycode - A (1) M 11:4 DjangoUnicodeDecodeError.__init__ - A (1) M 15:4 DjangoUnicodeDecodeError.__str__ - A (1) django/utils/jslex.py F 185:0 prepare_js_for_gettext - B (6) C 30:0 Lexer - A (5) M 49:4 Lexer.lex - A (4) M 35:4 Lexer.__init__ - A (3) F 20:0 literals - A (2) C 6:0 Tok - A (2) C 76:0 JsLexer - A (2) M 12:4 Tok.__init__ - A (1) M 181:4 JsLexer.__init__ - A (1) django/utils/log.py M 169:4 ServerFormatter.format - B (10) F 201:0 log_response - A (5) M 91:4 AdminEmailHandler.emit - A (5) C 162:0 ServerFormatter - A (5) F 66:0 configure_logging - A (3) C 78:0 AdminEmailHandler - A (3) C 137:0 CallbackFilter - A (3) M 85:4 AdminEmailHandler.__init__ - A (2) M 146:4 CallbackFilter.filter - A (2) C 152:0 RequireDebugFalse - A (2) C 157:0 RequireDebugTrue - A (2) M 124:4 AdminEmailHandler.send_mail - A (1) M 127:4 AdminEmailHandler.connection - A (1) M 130:4 AdminEmailHandler.format_subject - A (1) M 143:4 CallbackFilter.__init__ - A (1) M 153:4 RequireDebugFalse.filter - A (1) M 158:4 RequireDebugTrue.filter - A (1) M 165:4 ServerFormatter.__init__ - A (1) M 197:4 ServerFormatter.uses_server_time - A (1) django/utils/deprecation.py C 36:0 RenameMethodsBase - B (8) M 50:4 RenameMethodsBase.__new__ - B (7) M 109:4 MiddlewareMixin.__call__ - A (5) C 88:0 MiddlewareMixin - A (4) M 121:4 MiddlewareMixin.__acall__ - A (4) C 19:0 warn_about_renamed_method - A (2) C 79:0 DeprecationInstanceCheck - A (2) M 92:4 MiddlewareMixin.__init__ - A (2) M 99:4 MiddlewareMixin._async_check - A (2) C 8:0 RemovedInDjango41Warning - A (1) C 12:0 RemovedInDjango50Warning - A (1) M 20:4 warn_about_renamed_method.__init__ - A (1) M 26:4 warn_about_renamed_method.__call__ - A (1) M 80:4 DeprecationInstanceCheck.__instancecheck__ - A (1) django/utils/timesince.py F 27:0 timesince - C (19) F 97:0 timeuntil - A (1) django/utils/numberformat.py F 7:0 format - D (27) django/utils/asyncio.py F 8:0 async_unsafe - A (2) django/utils/html.py F 236:0 urlize - C (18) F 200:0 smart_urlquote - A (5) F 139:0 linebreaks - A (4) F 180:0 strip_tags - A (4) F 92:0 conditional_escape - A (3) F 360:0 html_safe - A (3) F 107:0 format_html - A (2) F 118:0 format_html_join - A (2) C 150:0 MLStripper - A (2) F 34:0 escape - A (1) F 66:0 escapejs - A (1) F 78:0 json_script - A (1) F 169:0 _strip_once - A (1) F 195:0 strip_spaces_between_tags - A (1) F 352:0 avoid_wrapping - A (1) M 151:4 MLStripper.__init__ - A (1) M 156:4 MLStripper.handle_data - A (1) M 159:4 MLStripper.handle_entityref - A (1) M 162:4 MLStripper.handle_charref - A (1) M 165:4 MLStripper.get_data - A (1) django/utils/duration.py F 18:0 duration_string - A (3) F 31:0 duration_iso_string - A (3) F 4:0 _get_duration_components - A (1) F 43:0 duration_microseconds - A (1) django/utils/cache.py F 153:0 get_conditional_response - C (17) F 37:0 patch_cache_control - C (16) F 369:0 learn_cache_key - B (8) F 278:0 patch_vary_headers - B (6) F 105:0 get_max_age - A (4) F 135:0 _not_modified - A (4) F 196:0 _if_match_passes - A (4) F 225:0 _if_none_match_passes - A (4) F 251:0 patch_response_headers - A (4) F 347:0 get_cache_key - A (4) F 119:0 set_response_etag - A (3) F 303:0 has_vary_header - A (3) F 314:0 _i18n_cache_key_suffix - A (3) F 326:0 _generate_cache_key - A (3) F 217:0 _if_unmodified_since_passes - A (2) F 244:0 _if_modified_since_passes - A (2) F 410:0 _to_tuple - A (2) F 125:0 _precondition_failed - A (1) F 270:0 add_never_cache_headers - A (1) F 339:0 _generate_cache_header_key - A (1) django/utils/deconstruct.py F 6:0 deconstructible - A (2) django/utils/datetime_safe.py F 74:0 strftime - B (6) F 61:0 _findall - A (3) F 46:0 new_datetime - A (2) C 18:0 date - A (2) C 23:0 datetime - A (2) F 41:0 new_date - A (1) M 19:4 date.strftime - A (1) M 24:4 datetime.strftime - A (1) M 28:4 datetime.combine - A (1) M 33:4 datetime.date - A (1) C 37:0 time - A (1) django/utils/connection.py M 56:4 BaseConnectionHandler.__getitem__ - A (3) C 7:0 ConnectionProxy - A (2) C 34:0 BaseConnectionHandler - A (2) M 48:4 BaseConnectionHandler.configure_settings - A (2) M 75:4 BaseConnectionHandler.all - A (2) M 10:4 ConnectionProxy.__init__ - A (1) M 14:4 ConnectionProxy.__getattr__ - A (1) M 17:4 ConnectionProxy.__setattr__ - A (1) M 20:4 ConnectionProxy.__delattr__ - A (1) M 23:4 ConnectionProxy.__contains__ - A (1) M 26:4 ConnectionProxy.__eq__ - A (1) C 30:0 ConnectionDoesNotExist - A (1) M 39:4 BaseConnectionHandler.__init__ - A (1) M 44:4 BaseConnectionHandler.settings - A (1) M 53:4 BaseConnectionHandler.create_connection - A (1) M 66:4 BaseConnectionHandler.__setitem__ - A (1) M 69:4 BaseConnectionHandler.__delitem__ - A (1) M 72:4 BaseConnectionHandler.__iter__ - A (1) django/utils/inspect.py F 18:0 get_func_full_args - B (6) F 60:0 method_has_no_args - A (4) F 10:0 get_func_args - A (3) F 42:0 func_accepts_kwargs - A (3) F 50:0 func_accepts_var_args - A (3) F 6:0 _get_signature - A (1) F 69:0 func_supports_parameter - A (1) django/utils/functional.py C 7:0 cached_property - A (3) M 30:4 cached_property.__set_name__ - A (3) C 251:0 LazyObject - A (3) M 270:4 LazyObject.__setattr__ - A (3) M 279:4 LazyObject.__delattr__ - A (3) F 211:0 keep_lazy - A (2) F 412:0 partition - A (2) M 40:4 cached_property.__get__ - A (2) C 52:0 classproperty - A (2) M 306:4 LazyObject.__reduce__ - A (2) M 311:4 LazyObject.__copy__ - A (2) M 320:4 LazyObject.__deepcopy__ - A (2) C 362:0 SimpleLazyObject - A (2) M 386:4 SimpleLazyObject.__repr__ - A (2) M 393:4 SimpleLazyObject.__copy__ - A (2) M 402:4 SimpleLazyObject.__deepcopy__ - A (2) F 76:0 lazy - A (1) F 200:0 _lazy_proxy_unpickle - A (1) F 204:0 lazystr - A (1) F 233:0 keep_lazy_text - A (1) F 243:0 new_method_proxy - A (1) F 354:0 unpickle_lazyobject - A (1) M 20:4 cached_property.func - A (1) M 26:4 cached_property.__init__ - A (1) M 57:4 classproperty.__init__ - A (1) M 60:4 classproperty.__get__ - A (1) M 63:4 classproperty.getter - A (1) C 68:0 Promise - A (1) M 263:4 LazyObject.__init__ - A (1) M 286:4 LazyObject._setup - A (1) M 369:4 SimpleLazyObject.__init__ - A (1) M 381:4 SimpleLazyObject._setup - A (1) django/utils/crypto.py F 17:0 salted_hmac - A (3) F 69:0 pbkdf2 - A (3) F 50:0 get_random_string - A (2) F 64:0 constant_time_compare - A (1) C 12:0 InvalidAlgorithm - A (1) django/utils/lorem_ipsum.py F 80:0 paragraphs - A (4) F 97:0 words - A (4) F 56:0 sentence - A (2) F 71:0 paragraph - A (2) django/utils/regex_helper.py F 41:0 normalize - D (30) F 286:0 flatten_result - C (16) F 235:0 get_quantifier - B (8) F 214:0 walk_to_end - B (7) F 272:0 contains - A (5) F 193:0 next_char - A (4) F 340:0 _lazy_re_compile - A (1) C 29:0 Choice - A (1) C 33:0 Group - A (1) C 37:0 NonCapture - A (1) django/utils/http.py F 41:0 urlencode - C (13) F 288:0 _urlsplit - C (13) F 317:0 _url_has_allowed_host_and_scheme - C (12) F 96:0 parse_http_date - B (7) F 239:0 url_has_allowed_host_and_scheme - B (6) F 195:0 parse_etags - A (5) F 220:0 is_same_domain - A (5) F 161:0 int_to_base36 - A (4) F 269:0 _urlparse - A (3) F 136:0 parse_http_date_safe - A (2) F 148:0 base36_to_int - A (2) F 183:0 urlsafe_base64_decode - A (2) F 209:0 quote_etag - A (2) F 346:0 escape_leading_slashes - A (2) F 82:0 http_date - A (1) F 175:0 urlsafe_base64_encode - A (1) django/utils/formats.py F 99:0 get_format - C (14) F 60:0 iter_format_modules - B (10) F 212:0 localize_input - B (10) F 187:0 localize - B (8) F 237:0 sanitize_separators - B (8) F 87:0 get_format_modules - A (4) F 165:0 number_format - A (4) F 144:0 date_format - A (2) F 155:0 time_format - A (2) F 49:0 reset_format_cache - A (1) django/utils/baseconv.py M 72:4 BaseConverter.convert - A (5) C 48:0 BaseConverter - A (3) M 51:4 BaseConverter.__init__ - A (2) M 60:4 BaseConverter.encode - A (2) M 66:4 BaseConverter.decode - A (2) M 57:4 BaseConverter.__repr__ - A (1) django/utils/text.py M 146:4 Truncator._truncate_html - C (18) M 102:4 Truncator._text_chars - B (7) C 57:0 Truncator - B (6) F 338:0 _replace_entity - A (5) M 79:4 Truncator.chars - A (5) F 234:0 get_text_list - A (4) M 64:4 Truncator.add_truncation_text - A (4) F 293:0 compress_sequence - A (3) F 361:0 unescape_string_literal - A (3) F 13:0 capfirst - A (2) F 264:0 phone2numeric - A (2) F 319:0 smart_split - A (2) F 382:0 slugify - A (2) M 122:4 Truncator.words - A (2) M 134:4 Truncator._text_words - A (2) C 284:0 StreamingBuffer - A (2) F 27:0 wrap - A (1) F 220:0 get_valid_filename - A (1) F 258:0 normalize_newlines - A (1) F 277:0 compress_string - A (1) F 398:0 camel_case_to_spaces - A (1) F 405:0 _format_lazy - A (1) M 61:4 Truncator.__init__ - A (1) M 285:4 StreamingBuffer.read - A (1) django/utils/archive.py M 160:4 TarArchive.extract - C (12) M 112:4 BaseArchive.split_leading_dir - B (6) M 202:4 ZipArchive.extract - B (6) M 62:4 Archive._archive_cls - A (5) M 122:4 BaseArchive.has_leading_dir - A (5) C 152:0 TarArchive - A (5) C 98:0 BaseArchive - A (4) C 194:0 ZipArchive - A (3) C 54:0 Archive - A (2) M 103:4 BaseArchive._copy_permissions - A (2) M 138:4 BaseArchive.target_filename - A (2) F 45:0 extract - A (1) C 33:0 ArchiveException - A (1) C 39:0 UnrecognizedArchiveFormat - A (1) M 58:4 Archive.__init__ - A (1) M 82:4 Archive.__enter__ - A (1) M 85:4 Archive.__exit__ - A (1) M 88:4 Archive.extract - A (1) M 91:4 Archive.list - A (1) M 94:4 Archive.close - A (1) M 145:4 BaseArchive.extract - A (1) M 148:4 BaseArchive.list - A (1) M 154:4 TarArchive.__init__ - A (1) M 157:4 TarArchive.list - A (1) M 190:4 TarArchive.close - A (1) M 196:4 ZipArchive.__init__ - A (1) M 199:4 ZipArchive.list - A (1) M 226:4 ZipArchive.close - A (1) django/utils/safestring.py F 50:0 mark_safe - A (3) C 21:0 SafeString - A (3) C 11:0 SafeData - A (2) M 26:4 SafeString.__add__ - A (2) F 43:0 _safety_decorator - A (1) M 12:4 SafeData.__html__ - A (1) M 36:4 SafeString.__str__ - A (1) django/utils/feedgenerator.py C 242:0 Rss201rev2Feed - C (15) M 246:4 Rss201rev2Feed.add_item_elements - C (14) M 341:4 Atom1Feed.add_item_elements - C (11) M 313:4 Atom1Feed.add_root_elements - B (8) M 160:4 SyndicationFeed.latest_post_date - B (7) M 212:4 RssFeed.add_root_elements - B (6) C 294:0 Atom1Feed - B (6) M 61:4 SyndicationFeed.__init__ - A (5) M 85:4 SyndicationFeed.add_item - A (5) F 40:0 rfc3339_date - A (3) C 59:0 SyndicationFeed - A (3) C 187:0 RssFeed - A (3) C 232:0 RssUserland091Feed - A (3) F 34:0 rfc2822_date - A (2) F 46:0 get_tag_uri - A (2) C 179:0 Enclosure - A (2) M 206:4 RssFeed.write_items - A (2) M 235:4 RssUserland091Feed.add_item_elements - A (2) M 307:4 Atom1Feed.root_attributes - A (2) M 335:4 Atom1Feed.write_items - A (2) M 116:4 SyndicationFeed.num_items - A (1) M 119:4 SyndicationFeed.root_attributes - A (1) M 126:4 SyndicationFeed.add_root_elements - A (1) M 133:4 SyndicationFeed.item_attributes - A (1) M 139:4 SyndicationFeed.add_item_elements - A (1) M 145:4 SyndicationFeed.write - A (1) M 152:4 SyndicationFeed.writeString - A (1) M 181:4 Enclosure.__init__ - A (1) M 190:4 RssFeed.write - A (1) M 200:4 RssFeed.rss_attributes - A (1) M 228:4 RssFeed.endChannelElement - A (1) M 299:4 Atom1Feed.write - A (1) django/utils/autoreload.py F 120:0 iter_modules_and_files - C (12) F 213:0 get_child_arguments - B (7) M 548:4 WatchmanReloader.tick - B (7) F 90:0 ensure_echo_on - B (6) M 367:4 StatReloader.tick - A (5) M 476:4 WatchmanReloader._watch_glob - A (5) M 505:4 WatchmanReloader._update_watches - A (5) F 166:0 common_roots - A (4) F 196:0 sys_path_directories - A (4) M 279:4 BaseReloader.watched_files - A (4) M 291:4 BaseReloader.wait_for_apps_ready - A (4) C 364:0 StatReloader - A (4) M 383:4 StatReloader.snapshot_files - A (4) C 406:0 WatchmanReloader - A (4) M 417:4 WatchmanReloader._watch_root - A (4) M 462:4 WatchmanReloader._subscribe_dir - A (4) M 529:4 WatchmanReloader._check_subscription - A (4) M 582:4 WatchmanReloader.check_availability - A (4) F 109:0 iter_all_python_module_files - A (3) F 250:0 restart_with_reloader - A (3) F 608:0 start_django - A (3) F 627:0 run_with_reloader - A (3) C 259:0 BaseReloader - A (3) M 326:4 BaseReloader.run_loop - A (3) M 349:4 BaseReloader.notify_file_changed - A (3) M 521:4 WatchmanReloader.update_watches - A (3) F 84:0 raise_last_exception - A (2) F 599:0 get_reloader - A (2) M 265:4 BaseReloader.watch_dir - A (2) M 309:4 BaseReloader.run - A (2) M 442:4 WatchmanReloader._subscribe - A (2) M 499:4 WatchmanReloader.watched_roots - A (2) M 573:4 WatchmanReloader.check_server_status - A (2) F 49:0 is_django_module - A (1) F 54:0 is_django_path - A (1) F 59:0 check_errors - A (1) F 245:0 trigger_reload - A (1) M 260:4 BaseReloader.__init__ - A (1) M 335:4 BaseReloader.tick - A (1) M 346:4 BaseReloader.check_availability - A (1) M 357:4 BaseReloader.should_stop - A (1) M 360:4 BaseReloader.stop - A (1) M 398:4 StatReloader.check_availability - A (1) C 402:0 WatchmanUnavailable - A (1) M 407:4 WatchmanReloader.__init__ - A (1) M 414:4 WatchmanReloader.client - A (1) M 439:4 WatchmanReloader._get_clock - A (1) M 544:4 WatchmanReloader.request_processed - A (1) M 569:4 WatchmanReloader.stop - A (1) django/utils/datastructures.py M 192:4 MultiValueDict.update - B (8) M 123:4 MultiValueDict._getlist - B (7) F 280:0 _destruct_iterable_mapping_values - A (4) M 310:4 CaseInsensitiveMapping.__init__ - A (4) M 321:4 CaseInsensitiveMapping.__eq__ - A (4) C 42:0 MultiValueDict - A (3) M 70:4 MultiValueDict.__getitem__ - A (3) M 110:4 MultiValueDict.get - A (3) M 158:4 MultiValueDict.setlistdefault - A (3) C 251:0 DictWrapper - A (3) M 265:4 DictWrapper.__getitem__ - A (3) C 292:0 CaseInsensitiveMapping - A (3) C 5:0 OrderedSet - A (2) M 10:4 OrderedSet.__init__ - A (2) M 19:4 OrderedSet.discard - A (2) M 87:4 MultiValueDict.__copy__ - A (2) M 93:4 MultiValueDict.__deepcopy__ - A (2) M 101:4 MultiValueDict.__getstate__ - A (2) M 104:4 MultiValueDict.__setstate__ - A (2) M 151:4 MultiValueDict.setdefault - A (2) M 171:4 MultiValueDict.items - A (2) M 183:4 MultiValueDict.values - A (2) M 209:4 MultiValueDict.dict - A (2) C 214:0 ImmutableList - A (2) M 328:4 CaseInsensitiveMapping.__iter__ - A (2) M 331:4 CaseInsensitiveMapping.__repr__ - A (2) M 13:4 OrderedSet.add - A (1) M 16:4 OrderedSet.remove - A (1) M 25:4 OrderedSet.__iter__ - A (1) M 28:4 OrderedSet.__contains__ - A (1) M 31:4 OrderedSet.__bool__ - A (1) M 34:4 OrderedSet.__len__ - A (1) C 38:0 MultiValueDictKeyError - A (1) M 64:4 MultiValueDict.__init__ - A (1) M 67:4 MultiValueDict.__repr__ - A (1) M 84:4 MultiValueDict.__setitem__ - A (1) M 141:4 MultiValueDict.getlist - A (1) M 148:4 MultiValueDict.setlist - A (1) M 167:4 MultiValueDict.appendlist - A (1) M 179:4 MultiValueDict.lists - A (1) M 188:4 MultiValueDict.copy - A (1) M 227:4 ImmutableList.__new__ - A (1) M 232:4 ImmutableList.complain - A (1) M 260:4 DictWrapper.__init__ - A (1) M 315:4 CaseInsensitiveMapping.__getitem__ - A (1) M 318:4 CaseInsensitiveMapping.__len__ - A (1) M 334:4 CaseInsensitiveMapping.copy - A (1) django/utils/dateformat.py C 32:0 Formatter - B (7) M 33:4 Formatter.format - B (6) M 75:4 TimeFormat.e - B (6) M 138:4 TimeFormat.P - A (5) M 279:4 DateFormat.S - A (5) M 122:4 TimeFormat.O - A (4) M 225:4 DateFormat.I - A (4) C 48:0 TimeFormat - A (3) M 50:4 TimeFormat.__init__ - A (3) M 155:4 TimeFormat.T - A (3) M 174:4 TimeFormat.Z - A (3) M 266:4 DateFormat.r - A (3) M 296:4 DateFormat.U - A (3) M 63:4 TimeFormat.a - A (2) M 69:4 TimeFormat.A - A (2) M 91:4 TimeFormat.f - A (2) M 102:4 TimeFormat.g - A (2) C 197:0 DateFormat - A (2) F 324:0 format - A (1) F 330:0 time_format - A (1) M 106:4 TimeFormat.G - A (1) M 110:4 TimeFormat.h - A (1) M 114:4 TimeFormat.H - A (1) M 118:4 TimeFormat.i - A (1) M 151:4 TimeFormat.s - A (1) M 170:4 TimeFormat.u - A (1) M 198:4 DateFormat.b - A (1) M 202:4 DateFormat.c - A (1) M 209:4 DateFormat.d - A (1) M 213:4 DateFormat.D - A (1) M 217:4 DateFormat.E - A (1) M 221:4 DateFormat.F - A (1) M 234:4 DateFormat.j - A (1) M 238:4 DateFormat.l - A (1) M 242:4 DateFormat.L - A (1) M 246:4 DateFormat.m - A (1) M 250:4 DateFormat.M - A (1) M 254:4 DateFormat.n - A (1) M 258:4 DateFormat.N - A (1) M 262:4 DateFormat.o - A (1) M 292:4 DateFormat.t - A (1) M 303:4 DateFormat.w - A (1) M 307:4 DateFormat.W - A (1) M 311:4 DateFormat.y - A (1) M 315:4 DateFormat.Y - A (1) M 319:4 DateFormat.z - A (1) django/utils/timezone.py F 140:0 template_localtime - B (6) F 160:0 localtime - A (4) F 233:0 make_aware - A (4) F 264:0 _datetime_ambiguous_or_imaginary - A (4) F 33:0 get_fixed_timezone - A (3) F 84:0 activate - A (3) F 249:0 make_naive - A (3) C 109:0 override - A (3) F 99:0 deactivate - A (2) F 193:0 now - A (2) M 124:4 override.__enter__ - A (2) M 131:4 override.__exit__ - A (2) F 46:0 get_default_timezone - A (1) F 56:0 get_default_timezone_name - A (1) F 64:0 get_current_timezone - A (1) F 69:0 get_current_timezone_name - A (1) F 74:0 _get_timezone_name - A (1) F 180:0 localdate - A (1) F 207:0 is_aware - A (1) F 220:0 is_naive - A (1) F 259:0 _is_pytz_zone - A (1) M 121:4 override.__init__ - A (1) django/utils/ipv6.py F 7:0 clean_ipv6_address - A (5) F 38:0 is_valid_ipv6_address - A (2) django/utils/module_loading.py F 27:0 autodiscover_modules - B (7) F 7:0 import_string - A (3) F 63:0 module_has_submodule - A (3) F 81:0 module_dir - A (3) django/utils/dateparse.py F 125:0 parse_duration - C (13) F 98:0 parse_datetime - B (9) F 81:0 parse_time - A (5) F 69:0 parse_date - A (3) django/utils/itercompat.py F 1:0 is_iterable - A (3) django/utils/xmlutils.py C 13:0 SimplerXMLGenerator - A (4) M 14:4 SimplerXMLGenerator.addQuickElement - A (3) M 23:4 SimplerXMLGenerator.characters - A (3) M 30:4 SimplerXMLGenerator.startElement - A (2) C 9:0 UnserializableContentError - A (1) django/utils/decorators.py F 22:0 _multi_decorate - A (3) F 53:0 method_decorator - A (3) C 6:0 classonlymethod - A (3) M 7:4 classonlymethod.__get__ - A (2) F 13:0 _update_method_wrapper - A (1) F 89:0 decorator_from_middleware_with_args - A (1) F 105:0 decorator_from_middleware - A (1) F 114:0 make_middleware_decorator - A (1) F 155:0 sync_and_async_middleware - A (1) F 165:0 sync_only_middleware - A (1) F 175:0 async_only_middleware - A (1) django/utils/translation/trans_real.py F 515:0 get_language_from_request - C (12) M 129:4 DjangoTranslation.__init__ - B (10) F 464:0 get_supported_language_variant - B (9) F 559:0 parse_accept_lang_header - A (5) F 344:0 gettext - A (4) F 436:0 check_for_language - A (4) M 92:4 TranslationCatalog.update - A (4) C 118:0 DjangoTranslation - A (4) M 191:4 DjangoTranslation._add_installed_apps_translations - A (4) M 212:4 DjangoTranslation._add_fallback - A (4) M 227:4 DjangoTranslation.merge - A (4) M 249:4 DjangoTranslation.ngettext - A (4) F 301:0 get_language - A (3) F 328:0 catalog - A (3) F 370:0 pgettext - A (3) F 391:0 do_ntranslate - A (3) F 421:0 all_locale_paths - A (3) F 498:0 get_language_from_path - A (3) C 61:0 TranslationCatalog - A (3) M 66:4 TranslationCatalog.__init__ - A (3) M 70:4 TranslationCatalog.__getitem__ - A (3) M 102:4 TranslationCatalog.get - A (3) M 110:4 TranslationCatalog.plural - A (3) F 50:0 reset_cache - A (2) F 262:0 translation - A (2) F 272:0 activate - A (2) F 282:0 deactivate - A (2) F 313:0 get_language_bidi - A (2) F 410:0 npgettext - A (2) M 81:4 TranslationCatalog.__contains__ - A (2) M 84:4 TranslationCatalog.items - A (2) M 88:4 TranslationCatalog.keys - A (2) M 206:4 DjangoTranslation._add_local_translations - A (2) F 291:0 deactivate_all - A (1) F 381:0 gettext_noop - A (1) F 402:0 ngettext - A (1) F 456:0 get_languages - A (1) M 78:4 TranslationCatalog.__setitem__ - A (1) M 166:4 DjangoTranslation.__repr__ - A (1) M 169:4 DjangoTranslation._new_gnu_trans - A (1) M 184:4 DjangoTranslation._init_translation_catalog - A (1) M 241:4 DjangoTranslation.language - A (1) M 245:4 DjangoTranslation.to_language - A (1) django/utils/translation/reloader.py F 9:0 watch_for_translation_changes - B (6) F 25:0 translation_file_changed - A (2) django/utils/translation/trans_null.py F 15:0 ngettext - A (2) F 63:0 get_supported_language_variant - A (2) F 8:0 gettext - A (1) F 24:0 pgettext - A (1) F 28:0 npgettext - A (1) F 32:0 activate - A (1) F 36:0 deactivate - A (1) F 43:0 get_language - A (1) F 47:0 get_language_bidi - A (1) F 51:0 check_for_language - A (1) F 55:0 get_language_from_request - A (1) F 59:0 get_language_from_path - A (1) django/utils/translation/__init__.py F 239:0 get_language_info - B (7) F 202:0 to_locale - A (4) C 35:0 Trans - A (3) C 160:0 override - A (3) M 172:4 override.__exit__ - A (3) F 93:0 lazy_number - A (2) F 193:0 to_language - A (2) M 48:4 Trans.__getattr__ - A (2) M 165:4 override.__enter__ - A (2) F 69:0 gettext_noop - A (1) F 73:0 gettext - A (1) F 77:0 ngettext - A (1) F 81:0 pgettext - A (1) F 85:0 npgettext - A (1) F 140:0 _lazy_number_unpickle - A (1) F 144:0 ngettext_lazy - A (1) F 148:0 npgettext_lazy - A (1) F 152:0 activate - A (1) F 156:0 deactivate - A (1) F 181:0 get_language - A (1) F 185:0 get_language_bidi - A (1) F 189:0 check_for_language - A (1) F 218:0 get_language_from_request - A (1) F 222:0 get_language_from_path - A (1) F 226:0 get_supported_language_variant - A (1) F 230:0 templatize - A (1) F 235:0 deactivate_all - A (1) F 264:0 trim_whitespace - A (1) F 268:0 round_away_from_one - A (1) C 23:0 TranslatorCommentWarning - A (1) M 161:4 override.__init__ - A (1) django/utils/translation/template.py F 35:0 templatize - F (51) F 12:0 blankout - A (1) django/contrib/syndication/apps.py C 5:0 SyndicationConfig - A (1) django/contrib/syndication/views.py M 123:4 Feed.get_feed - C (15) M 77:4 Feed._get_dynamic_attr - A (5) F 15:0 add_domain - A (4) C 29:0 Feed - A (4) M 35:4 Feed.__call__ - A (4) M 57:4 Feed.item_link - A (2) M 66:4 Feed.item_enclosures - A (2) C 25:0 FeedDoesNotExist - A (1) M 50:4 Feed.item_title - A (1) M 54:4 Feed.item_description - A (1) M 96:4 Feed.feed_extra_kwargs - A (1) M 103:4 Feed.item_extra_kwargs - A (1) M 110:4 Feed.get_object - A (1) M 113:4 Feed.get_context_data - A (1) django/contrib/messages/apps.py C 5:0 MessagesConfig - A (1) django/contrib/messages/api.py F 16:0 add_message - A (5) F 56:0 set_level - A (2) F 37:0 get_messages - A (1) F 45:0 get_level - A (1) F 69:0 debug - A (1) F 75:0 info - A (1) F 81:0 success - A (1) F 87:0 warning - A (1) F 93:0 error - A (1) C 12:0 MessageFailure - A (1) django/contrib/messages/context_processors.py F 5:0 messages - A (1) django/contrib/messages/utils.py F 5:0 get_level_tags - A (1) django/contrib/messages/middleware.py C 6:0 MessageMiddleware - A (4) M 14:4 MessageMiddleware.process_response - A (4) M 11:4 MessageMiddleware.process_request - A (1) django/contrib/messages/views.py C 4:0 SuccessMessageMixin - A (3) M 10:4 SuccessMessageMixin.form_valid - A (2) M 17:4 SuccessMessageMixin.get_success_message - A (1) django/contrib/messages/storage/session.py C 9:0 SessionStorage - A (3) M 44:4 SessionStorage.deserialize_messages - A (3) M 15:4 SessionStorage.__init__ - A (2) M 30:4 SessionStorage._store - A (2) M 22:4 SessionStorage._get - A (1) M 40:4 SessionStorage.serialize_messages - A (1) django/contrib/messages/storage/__init__.py F 5:0 default_storage - A (1) django/contrib/messages/storage/cookie.py M 32:4 MessageDecoder.process_messages - B (8) C 27:0 MessageDecoder - B (6) M 152:4 CookieStorage._decode - B (6) C 10:0 MessageEncoder - A (5) C 61:0 CookieStorage - A (5) M 112:4 CookieStorage._store - A (5) M 16:4 MessageEncoder.default - A (4) M 77:4 CookieStorage._get - A (4) M 92:4 CookieStorage._update_cookie - A (4) M 141:4 CookieStorage._encode - A (3) C 49:0 MessageSerializer - A (2) M 44:4 MessageDecoder.decode - A (1) M 50:4 MessageSerializer.dumps - A (1) M 57:4 MessageSerializer.loads - A (1) M 73:4 CookieStorage.__init__ - A (1) django/contrib/messages/storage/fallback.py C 6:0 FallbackStorage - A (5) M 19:4 FallbackStorage._get - A (5) M 38:4 FallbackStorage._store - A (4) M 13:4 FallbackStorage.__init__ - A (2) django/contrib/messages/storage/base.py C 7:0 Message - A (3) M 27:4 Message.__eq__ - A (3) M 36:4 Message.tags - A (3) C 44:0 BaseStorage - A (3) M 73:4 BaseStorage._loaded_messages - A (3) M 116:4 BaseStorage.update - A (3) M 130:4 BaseStorage.add - A (3) M 159:4 BaseStorage._set_level - A (3) M 19:4 Message._prepare - A (2) M 62:4 BaseStorage.__iter__ - A (2) M 69:4 BaseStorage.__contains__ - A (2) M 109:4 BaseStorage._prepare_messages - A (2) M 148:4 BaseStorage._get_level - A (2) M 14:4 Message.__init__ - A (1) M 32:4 Message.__str__ - A (1) M 40:4 Message.level_tag - A (1) M 52:4 BaseStorage.__init__ - A (1) M 59:4 BaseStorage.__len__ - A (1) M 83:4 BaseStorage._get - A (1) M 98:4 BaseStorage._store - A (1) django/contrib/auth/mixins.py M 44:4 AccessMixin.handle_no_permission - B (7) C 10:0 AccessMixin - A (4) M 20:4 AccessMixin.get_login_url - A (3) C 66:0 LoginRequiredMixin - A (3) C 74:0 PermissionRequiredMixin - A (3) M 78:4 PermissionRequiredMixin.get_permission_required - A (3) M 68:4 LoginRequiredMixin.dispatch - A (2) M 101:4 PermissionRequiredMixin.dispatch - A (2) C 107:0 UserPassesTestMixin - A (2) M 124:4 UserPassesTestMixin.dispatch - A (2) M 32:4 AccessMixin.get_permission_denied_message - A (1) M 38:4 AccessMixin.get_redirect_field_name - A (1) M 94:4 PermissionRequiredMixin.has_permission - A (1) M 113:4 UserPassesTestMixin.test_func - A (1) M 118:4 UserPassesTestMixin.get_test_func - A (1) django/contrib/auth/password_validation.py M 135:4 UserAttributeSimilarityValidator.validate - B (8) F 35:0 validate_password - A (5) C 118:0 UserAttributeSimilarityValidator - A (4) M 172:4 CommonPasswordValidator.__init__ - A (4) F 22:0 get_password_validators - A (3) F 54:0 password_changed - A (3) F 66:0 password_validators_help_texts - A (3) F 78:0 _password_validators_help_text_html - A (3) C 160:0 CommonPasswordValidator - A (3) C 191:0 NumericPasswordValidator - A (3) C 91:0 MinimumLengthValidator - A (2) M 98:4 MinimumLengthValidator.validate - A (2) M 180:4 CommonPasswordValidator.validate - A (2) M 195:4 NumericPasswordValidator.validate - A (2) F 18:0 get_default_password_validators - A (1) M 95:4 MinimumLengthValidator.__init__ - A (1) M 110:4 MinimumLengthValidator.get_help_text - A (1) M 131:4 UserAttributeSimilarityValidator.__init__ - A (1) M 156:4 UserAttributeSimilarityValidator.get_help_text - A (1) M 187:4 CommonPasswordValidator.get_help_text - A (1) M 202:4 NumericPasswordValidator.get_help_text - A (1) django/contrib/auth/models.py F 202:0 _user_has_perm - A (5) F 217:0 _user_has_module_perms - A (5) M 165:4 UserManager.with_perm - A (5) C 129:0 UserManager - A (4) F 193:0 _user_get_permissions - A (3) M 154:4 UserManager.create_superuser - A (3) C 232:0 PermissionsMixin - A (3) M 287:4 PermissionsMixin.has_perm - A (3) M 309:4 PermissionsMixin.has_module_perms - A (3) C 25:0 PermissionManager - A (2) C 35:0 Permission - A (2) C 82:0 GroupManager - A (2) C 92:0 Group - A (2) M 132:4 UserManager._create_user - A (2) M 302:4 PermissionsMixin.has_perms - A (2) C 321:0 AbstractUser - A (2) C 400:0 AnonymousUser - A (2) M 454:4 AnonymousUser.has_perms - A (2) F 16:0 update_last_login - A (1) M 28:4 PermissionManager.get_by_natural_key - A (1) M 74:4 Permission.__str__ - A (1) M 77:4 Permission.natural_key - A (1) M 88:4 GroupManager.get_by_natural_key - A (1) M 122:4 Group.__str__ - A (1) M 125:4 Group.natural_key - A (1) M 149:4 UserManager.create_user - A (1) M 268:4 PermissionsMixin.get_user_permissions - A (1) M 276:4 PermissionsMixin.get_group_permissions - A (1) M 284:4 PermissionsMixin.get_all_permissions - A (1) M 369:4 AbstractUser.clean - A (1) M 373:4 AbstractUser.get_full_name - A (1) M 380:4 AbstractUser.get_short_name - A (1) M 384:4 AbstractUser.email_user - A (1) C 389:0 User - A (1) M 410:4 AnonymousUser.__str__ - A (1) M 413:4 AnonymousUser.__eq__ - A (1) M 416:4 AnonymousUser.__hash__ - A (1) M 419:4 AnonymousUser.__int__ - A (1) M 422:4 AnonymousUser.save - A (1) M 425:4 AnonymousUser.delete - A (1) M 428:4 AnonymousUser.set_password - A (1) M 431:4 AnonymousUser.check_password - A (1) M 435:4 AnonymousUser.groups - A (1) M 439:4 AnonymousUser.user_permissions - A (1) M 442:4 AnonymousUser.get_user_permissions - A (1) M 445:4 AnonymousUser.get_group_permissions - A (1) M 448:4 AnonymousUser.get_all_permissions - A (1) M 451:4 AnonymousUser.has_perm - A (1) M 457:4 AnonymousUser.has_module_perms - A (1) M 461:4 AnonymousUser.is_anonymous - A (1) M 465:4 AnonymousUser.is_authenticated - A (1) M 468:4 AnonymousUser.get_username - A (1) django/contrib/auth/validators.py C 9:0 ASCIIUsernameValidator - A (1) C 19:0 UnicodeUsernameValidator - A (1) django/contrib/auth/checks.py F 105:0 check_models_permissions - C (15) F 11:0 check_user_model - C (13) django/contrib/auth/base_user.py M 19:4 BaseUserManager.normalize_email - A (4) C 16:0 BaseUserManager - A (3) C 47:0 AbstractBaseUser - A (2) M 65:4 AbstractBaseUser.save - A (2) M 135:4 AbstractBaseUser.get_email_field_name - A (2) M 142:4 AbstractBaseUser.normalize_username - A (2) M 32:4 BaseUserManager.make_random_password - A (1) M 43:4 BaseUserManager.get_by_natural_key - A (1) M 62:4 AbstractBaseUser.__str__ - A (1) M 71:4 AbstractBaseUser.get_username - A (1) M 75:4 AbstractBaseUser.clean - A (1) M 78:4 AbstractBaseUser.natural_key - A (1) M 82:4 AbstractBaseUser.is_anonymous - A (1) M 90:4 AbstractBaseUser.is_authenticated - A (1) M 97:4 AbstractBaseUser.set_password - A (1) M 101:4 AbstractBaseUser.check_password - A (1) M 113:4 AbstractBaseUser.set_unusable_password - A (1) M 117:4 AbstractBaseUser.has_usable_password - A (1) M 123:4 AbstractBaseUser.get_session_auth_hash - A (1) django/contrib/auth/__init__.py F 90:0 login - C (13) F 169:0 get_user - B (8) F 64:0 authenticate - A (5) F 24:0 _get_backends - A (4) F 42:0 _clean_credentials - A (3) F 138:0 logout - A (3) F 155:0 get_user_model - A (3) F 206:0 update_session_auth_hash - A (3) F 20:0 load_backend - A (1) F 37:0 get_backends - A (1) F 57:0 _get_user_session_key - A (1) F 199:0 get_permission_codename - A (1) django/contrib/auth/tokens.py M 28:4 PasswordResetTokenGenerator.check_token - B (7) C 8:0 PasswordResetTokenGenerator - A (3) M 17:4 PasswordResetTokenGenerator.__init__ - A (3) M 67:4 PasswordResetTokenGenerator._make_hash_value - A (3) M 21:4 PasswordResetTokenGenerator.make_token - A (1) M 55:4 PasswordResetTokenGenerator._make_token_with_timestamp - A (1) M 89:4 PasswordResetTokenGenerator._num_seconds - A (1) M 92:4 PasswordResetTokenGenerator._now - A (1) django/contrib/auth/apps.py C 13:0 AuthConfig - A (3) M 18:4 AuthConfig.ready - A (2) django/contrib/auth/forms.py C 33:0 ReadOnlyPasswordHashWidget - B (7) M 37:4 ReadOnlyPasswordHashWidget.get_context - B (6) C 238:0 PasswordResetForm - A (5) M 280:4 PasswordResetForm.save - A (5) C 75:0 UserCreationForm - A (4) M 106:4 UserCreationForm.clean_password2 - A (4) C 135:0 UserChangeForm - A (4) M 197:4 AuthenticationForm.clean - A (4) M 262:4 PasswordResetForm.get_users - A (4) M 340:4 SetPasswordForm.clean_new_password2 - A (4) M 415:4 AdminPasswordChangeForm.clean_password2 - A (4) M 116:4 UserCreationForm._post_clean - A (3) M 150:4 UserChangeForm.__init__ - A (3) C 160:0 AuthenticationForm - A (3) M 180:4 AuthenticationForm.__init__ - A (3) C 316:0 SetPasswordForm - A (3) C 360:0 PasswordChangeForm - A (3) C 390:0 AdminPasswordChangeForm - A (3) M 435:4 AdminPasswordChangeForm.changed_data - A (3) C 54:0 ReadOnlyPasswordHashField - A (2) C 63:0 UsernameField - A (2) M 101:4 UserCreationForm.__init__ - A (2) M 127:4 UserCreationForm.save - A (2) M 210:4 AuthenticationForm.confirm_login_allowed - A (2) M 245:4 PasswordResetForm.send_mail - A (2) M 352:4 SetPasswordForm.save - A (2) M 377:4 PasswordChangeForm.clean_old_password - A (2) M 426:4 AdminPasswordChangeForm.save - A (2) F 24:0 _unicode_ci_compare - A (1) M 57:4 ReadOnlyPasswordHashField.__init__ - A (1) M 64:4 UsernameField.to_python - A (1) M 67:4 UsernameField.widget_attrs - A (1) M 227:4 AuthenticationForm.get_user - A (1) M 230:4 AuthenticationForm.get_invalid_login_error - A (1) M 336:4 SetPasswordForm.__init__ - A (1) M 411:4 AdminPasswordChangeForm.__init__ - A (1) django/contrib/auth/backends.py M 36:4 ModelBackend.authenticate - B (8) M 119:4 ModelBackend.with_perm - B (8) M 67:4 ModelBackend._get_permissions - B (7) M 183:4 RemoteUserBackend.authenticate - B (6) M 100:4 ModelBackend.get_all_permissions - A (5) C 31:0 ModelBackend - A (4) C 168:0 RemoteUserBackend - A (4) M 110:4 ModelBackend.has_module_perms - A (3) M 155:4 ModelBackend.get_user - A (3) C 8:0 BaseBackend - A (2) M 51:4 ModelBackend.user_can_authenticate - A (2) M 107:4 ModelBackend.has_perm - A (2) C 163:0 AllowAllUsersModelBackend - A (2) C 231:0 AllowAllUsersRemoteUserBackend - A (2) M 9:4 BaseBackend.authenticate - A (1) M 12:4 BaseBackend.get_user - A (1) M 15:4 BaseBackend.get_user_permissions - A (1) M 18:4 BaseBackend.get_group_permissions - A (1) M 21:4 BaseBackend.get_all_permissions - A (1) M 27:4 BaseBackend.has_perm - A (1) M 59:4 ModelBackend._get_user_permissions - A (1) M 62:4 ModelBackend._get_group_permissions - A (1) M 86:4 ModelBackend.get_user_permissions - A (1) M 93:4 ModelBackend.get_group_permissions - A (1) M 164:4 AllowAllUsersModelBackend.user_can_authenticate - A (1) M 213:4 RemoteUserBackend.clean_username - A (1) M 222:4 RemoteUserBackend.configure_user - A (1) M 232:4 AllowAllUsersRemoteUserBackend.user_can_authenticate - A (1) django/contrib/auth/context_processors.py F 46:0 auth - A (2) C 5:0 PermLookupDict - A (2) C 24:0 PermWrapper - A (2) M 35:4 PermWrapper.__contains__ - A (2) M 6:4 PermLookupDict.__init__ - A (1) M 9:4 PermLookupDict.__repr__ - A (1) M 12:4 PermLookupDict.__getitem__ - A (1) M 15:4 PermLookupDict.__iter__ - A (1) M 20:4 PermLookupDict.__bool__ - A (1) M 25:4 PermWrapper.__init__ - A (1) M 28:4 PermWrapper.__getitem__ - A (1) M 31:4 PermWrapper.__iter__ - A (1) django/contrib/auth/admin.py M 129:4 UserAdmin.user_change_password - B (7) M 101:4 UserAdmin._add_view - A (5) C 41:0 UserAdmin - A (4) C 26:0 GroupAdmin - A (3) M 191:4 UserAdmin.response_add - A (3) M 31:4 GroupAdmin.formfield_for_manytomany - A (2) M 67:4 UserAdmin.get_fieldsets - A (2) M 72:4 UserAdmin.get_form - A (2) M 91:4 UserAdmin.lookup_allowed - A (2) M 82:4 UserAdmin.get_urls - A (1) M 97:4 UserAdmin.add_view - A (1) django/contrib/auth/hashers.py F 31:0 check_password - C (11) F 134:0 identify_hasher - B (7) F 65:0 make_password - A (4) F 111:0 get_hasher - A (4) M 183:4 BasePasswordHasher._load_library - A (4) M 271:4 PBKDF2PasswordHasher.encode - A (4) F 87:0 get_hashers - A (3) C 259:0 PBKDF2PasswordHasher - A (3) M 376:4 Argon2PasswordHasher.verify - A (3) M 521:4 SHA1PasswordHasher.encode - A (3) M 563:4 MD5PasswordHasher.encode - A (3) M 668:4 UnsaltedMD5PasswordHasher.verify - A (3) M 697:4 CryptPasswordHasher.encode - A (3) F 23:0 is_password_usable - A (2) F 100:0 get_hashers_by_algorithm - A (2) F 105:0 reset_hashers - A (2) C 170:0 BasePasswordHasher - A (2) M 279:4 PBKDF2PasswordHasher.decode - A (2) M 303:4 PBKDF2PasswordHasher.must_update - A (2) M 308:4 PBKDF2PasswordHasher.harden_runtime - A (2) C 326:0 Argon2PasswordHasher - A (2) M 355:4 Argon2PasswordHasher.decode - A (2) M 398:4 Argon2PasswordHasher.must_update - A (2) C 427:0 BCryptSHA256PasswordHasher - A (2) M 445:4 BCryptSHA256PasswordHasher.encode - A (2) M 457:4 BCryptSHA256PasswordHasher.decode - A (2) M 468:4 BCryptSHA256PasswordHasher.verify - A (2) M 487:4 BCryptSHA256PasswordHasher.harden_runtime - A (2) C 515:0 SHA1PasswordHasher - A (2) M 527:4 SHA1PasswordHasher.decode - A (2) C 557:0 MD5PasswordHasher - A (2) M 569:4 MD5PasswordHasher.decode - A (2) C 599:0 UnsaltedSHA1PasswordHasher - A (2) M 613:4 UnsaltedSHA1PasswordHasher.encode - A (2) M 618:4 UnsaltedSHA1PasswordHasher.decode - A (2) C 641:0 UnsaltedMD5PasswordHasher - A (2) M 657:4 UnsaltedMD5PasswordHasher.encode - A (2) C 685:0 CryptPasswordHasher - A (2) M 705:4 CryptPasswordHasher.decode - A (2) F 155:0 mask_hash - A (1) F 165:0 must_update_salt - A (1) M 198:4 BasePasswordHasher.salt - A (1) M 208:4 BasePasswordHasher.verify - A (1) M 212:4 BasePasswordHasher.encode - A (1) M 221:4 BasePasswordHasher.decode - A (1) M 233:4 BasePasswordHasher.safe_summary - A (1) M 242:4 BasePasswordHasher.must_update - A (1) M 245:4 BasePasswordHasher.harden_runtime - A (1) M 289:4 PBKDF2PasswordHasher.verify - A (1) M 294:4 PBKDF2PasswordHasher.safe_summary - A (1) C 315:0 PBKDF2SHA1PasswordHasher - A (1) M 341:4 Argon2PasswordHasher.encode - A (1) M 385:4 Argon2PasswordHasher.safe_summary - A (1) M 408:4 Argon2PasswordHasher.harden_runtime - A (1) M 413:4 Argon2PasswordHasher.params - A (1) M 441:4 BCryptSHA256PasswordHasher.salt - A (1) M 474:4 BCryptSHA256PasswordHasher.safe_summary - A (1) M 483:4 BCryptSHA256PasswordHasher.must_update - A (1) C 498:0 BCryptPasswordHasher - A (1) M 536:4 SHA1PasswordHasher.verify - A (1) M 541:4 SHA1PasswordHasher.safe_summary - A (1) M 549:4 SHA1PasswordHasher.must_update - A (1) M 553:4 SHA1PasswordHasher.harden_runtime - A (1) M 578:4 MD5PasswordHasher.verify - A (1) M 583:4 MD5PasswordHasher.safe_summary - A (1) M 591:4 MD5PasswordHasher.must_update - A (1) M 595:4 MD5PasswordHasher.harden_runtime - A (1) M 610:4 UnsaltedSHA1PasswordHasher.salt - A (1) M 626:4 UnsaltedSHA1PasswordHasher.verify - A (1) M 630:4 UnsaltedSHA1PasswordHasher.safe_summary - A (1) M 637:4 UnsaltedSHA1PasswordHasher.harden_runtime - A (1) M 654:4 UnsaltedMD5PasswordHasher.salt - A (1) M 661:4 UnsaltedMD5PasswordHasher.decode - A (1) M 674:4 UnsaltedMD5PasswordHasher.safe_summary - A (1) M 681:4 UnsaltedMD5PasswordHasher.harden_runtime - A (1) M 694:4 CryptPasswordHasher.salt - A (1) M 714:4 CryptPasswordHasher.verify - A (1) M 720:4 CryptPasswordHasher.safe_summary - A (1) M 728:4 CryptPasswordHasher.harden_runtime - A (1) django/contrib/auth/middleware.py M 46:4 RemoteUserMiddleware.process_request - B (8) C 26:0 RemoteUserMiddleware - B (6) M 97:4 RemoteUserMiddleware._remove_invalid_user - A (4) C 15:0 AuthenticationMiddleware - A (3) F 9:0 get_user - A (2) M 16:4 AuthenticationMiddleware.process_request - A (2) M 84:4 RemoteUserMiddleware.clean_username - A (2) C 112:0 PersistentRemoteUserMiddleware - A (1) django/contrib/auth/views.py M 133:4 LogoutView.get_next_page - B (6) M 263:4 PasswordResetConfirmView.dispatch - B (6) M 55:4 LoginView.dispatch - A (4) C 111:0 LogoutView - A (4) F 178:0 redirect_to_login - A (3) C 40:0 LoginView - A (3) C 200:0 PasswordContextMixin - A (3) C 251:0 PasswordResetConfirmView - A (3) F 170:0 logout_then_login - A (2) C 33:0 SuccessURLAllowedHostsMixin - A (2) M 66:4 LoginView.get_success_url - A (2) M 69:4 LoginView.get_redirect_url - A (2) M 82:4 LoginView.get_default_redirect_url - A (2) M 86:4 LoginView.get_form_class - A (2) M 99:4 LoginView.get_context_data - A (2) M 121:4 LogoutView.dispatch - A (2) M 158:4 LogoutView.get_context_data - A (2) M 203:4 PasswordContextMixin.get_context_data - A (2) C 212:0 PasswordResetView - A (2) M 290:4 PasswordResetConfirmView.get_user - A (2) M 304:4 PasswordResetConfirmView.form_valid - A (2) M 311:4 PasswordResetConfirmView.get_context_data - A (2) C 324:0 PasswordResetCompleteView - A (2) C 334:0 PasswordChangeView - A (2) C 359:0 PasswordChangeDoneView - A (2) M 36:4 SuccessURLAllowedHostsMixin.get_success_url_allowed_hosts - A (1) M 89:4 LoginView.get_form_kwargs - A (1) M 94:4 LoginView.form_valid - A (1) M 129:4 LogoutView.post - A (1) M 225:4 PasswordResetView.dispatch - A (1) M 228:4 PasswordResetView.form_valid - A (1) C 246:0 PasswordResetDoneView - A (1) M 299:4 PasswordResetConfirmView.get_form_kwargs - A (1) M 328:4 PasswordResetCompleteView.get_context_data - A (1) M 343:4 PasswordChangeView.dispatch - A (1) M 346:4 PasswordChangeView.get_form_kwargs - A (1) M 351:4 PasswordChangeView.form_valid - A (1) M 364:4 PasswordChangeDoneView.dispatch - A (1) django/contrib/auth/decorators.py F 38:0 login_required - A (2) F 10:0 user_passes_test - A (1) F 53:0 permission_required - A (1) django/contrib/auth/migrations/0012_alter_user_first_name_max_length.py C 4:0 Migration - A (1) django/contrib/auth/migrations/0004_alter_user_username_opts.py C 5:0 Migration - A (1) django/contrib/auth/migrations/0010_alter_group_name_max_length.py C 4:0 Migration - A (1) django/contrib/auth/migrations/0005_alter_user_last_login_null.py C 4:0 Migration - A (1) django/contrib/auth/migrations/0009_alter_user_last_name_max_length.py C 4:0 Migration - A (1) django/contrib/auth/migrations/0003_alter_user_email_max_length.py C 4:0 Migration - A (1) django/contrib/auth/migrations/0007_alter_validators_add_error_messages.py C 5:0 Migration - A (1) django/contrib/auth/migrations/0006_require_contenttypes_0002.py C 4:0 Migration - A (1) django/contrib/auth/migrations/0011_update_proxy_permissions.py F 17:0 update_proxy_model_permissions - B (8) F 54:0 revert_proxy_model_permissions - A (1) C 62:0 Migration - A (1) django/contrib/auth/migrations/0002_alter_permission_name_max_length.py C 4:0 Migration - A (1) django/contrib/auth/migrations/0001_initial.py C 7:0 Migration - A (1) django/contrib/auth/migrations/0008_alter_user_username_max_length.py C 5:0 Migration - A (1) django/contrib/auth/management/__init__.py F 35:0 create_permissions - B (10) F 104:0 get_default_username - B (8) F 21:0 _get_builtin_permissions - A (2) F 89:0 get_system_username - A (2) F 14:0 _get_all_permissions - A (1) django/contrib/auth/management/commands/createsuperuser.py M 81:4 Command.handle - E (39) C 24:0 Command - B (9) M 230:4 Command._validate_username - B (6) M 34:4 Command.add_arguments - A (5) M 204:4 Command.get_input_data - A (4) M 220:4 Command._get_input_message - A (4) C 17:0 NotRunningInTTYException - A (1) M 29:4 Command.__init__ - A (1) M 77:4 Command.execute - A (1) django/contrib/auth/management/commands/changepassword.py M 34:4 Command.handle - B (10) C 12:0 Command - A (5) M 17:4 Command._get_pass - A (2) M 23:4 Command.add_arguments - A (1) django/contrib/auth/handlers/modwsgi.py F 29:0 groups_for_user - A (4) F 7:0 check_password - A (3) django/contrib/admin/options.py M 1684:4 ModelAdmin.changelist_view - E (32) M 1540:4 ModelAdmin._changeform_view - D (30) M 377:4 BaseModelAdmin.lookup_allowed - C (15) M 431:4 BaseModelAdmin.to_field_allowed - C (15) M 669:4 ModelAdmin.get_form - C (15) M 1851:4 ModelAdmin._delete_view - C (13) M 1174:4 ModelAdmin.response_add - C (12) M 2054:4 InlineModelAdmin.get_formset - C (12) M 132:4 BaseModelAdmin.formfield_for_dbfield - C (11) M 244:4 BaseModelAdmin.formfield_for_manytomany - C (11) M 1127:4 ModelAdmin.render_change_form - B (10) M 1963:4 ModelAdmin._create_formsets - B (9) M 220:4 BaseModelAdmin.formfield_for_foreignkey - B (8) M 863:4 ModelAdmin._get_base_actions - B (8) M 987:4 ModelAdmin.get_search_results - B (8) M 1353:4 ModelAdmin.response_action - B (8) M 596:4 ModelAdmin.get_inline_instances - B (7) M 1251:4 ModelAdmin.response_change - B (7) M 2033:4 InlineModelAdmin.media - B (7) M 881:4 ModelAdmin._filter_actions_by_permissions - B (6) M 293:4 BaseModelAdmin.get_view_on_site_url - A (5) C 551:0 ModelAdmin - A (5) M 1037:4 ModelAdmin.get_preserved_filters - A (5) M 1909:4 ModelAdmin.history_view - A (5) M 2152:4 InlineModelAdmin._has_any_perms_for_target_model - A (5) C 100:0 BaseModelAdmin - A (4) M 189:4 BaseModelAdmin.formfield_for_choice_field - A (4) M 207:4 BaseModelAdmin.get_field_queryset - A (4) M 897:4 ModelAdmin.get_actions - A (4) M 920:4 ModelAdmin.get_action - A (4) M 954:4 ModelAdmin.get_list_display_links - A (4) M 1061:4 ModelAdmin.message_user - A (4) M 1420:4 ModelAdmin.response_delete - A (4) M 1482:4 ModelAdmin.get_inline_formsets - A (4) M 1507:4 ModelAdmin.get_changeform_initial_data - A (4) C 1999:0 InlineModelAdmin - A (4) M 639:4 ModelAdmin.media - A (3) M 752:4 ModelAdmin.get_object - A (3) M 767:4 ModelAdmin.get_changelist_form - A (3) M 1660:4 ModelAdmin._get_edited_object_pks - A (3) M 1667:4 ModelAdmin._get_list_editable_queryset - A (3) M 2021:4 InlineModelAdmin.__init__ - A (3) F 68:0 get_ul_class - A (2) M 124:4 BaseModelAdmin.__init__ - A (2) M 306:4 BaseModelAdmin.get_empty_value_display - A (2) M 321:4 BaseModelAdmin.get_fields - A (2) M 331:4 BaseModelAdmin.get_fieldsets - A (2) M 343:4 BaseModelAdmin.get_ordering - A (2) M 361:4 BaseModelAdmin.get_queryset - A (2) M 373:4 BaseModelAdmin.get_sortable_by - A (2) M 515:4 BaseModelAdmin.has_view_permission - A (2) M 534:4 BaseModelAdmin.has_view_or_change_permission - A (2) M 724:4 ModelAdmin.get_changelist_instance - A (2) M 794:4 ModelAdmin.get_formsets_with_inlines - A (2) M 909:4 ModelAdmin.get_action_choices - A (2) M 1115:4 ModelAdmin.save_related - A (2) M 1326:4 ModelAdmin._response_post_save - A (2) M 1461:4 ModelAdmin.render_delete_form - A (2) M 1949:4 ModelAdmin.get_formset_kwargs - A (2) M 2146:4 InlineModelAdmin.get_queryset - A (2) M 2170:4 InlineModelAdmin.has_add_permission - A (2) M 2179:4 InlineModelAdmin.has_change_permission - A (2) M 2185:4 InlineModelAdmin.has_delete_permission - A (2) M 2191:4 InlineModelAdmin.has_view_permission - A (2) F 61:0 get_content_type_for_model - A (1) C 72:0 IncorrectLookupParameters - A (1) M 121:4 BaseModelAdmin.check - A (1) M 286:4 BaseModelAdmin.get_autocomplete_fields - A (1) M 315:4 BaseModelAdmin.get_exclude - A (1) M 339:4 BaseModelAdmin.get_inlines - A (1) M 349:4 BaseModelAdmin.get_readonly_fields - A (1) M 355:4 BaseModelAdmin.get_prepopulated_fields - A (1) M 476:4 BaseModelAdmin.has_add_permission - A (1) M 485:4 BaseModelAdmin.has_change_permission - A (1) M 500:4 BaseModelAdmin.has_delete_permission - A (1) M 537:4 BaseModelAdmin.has_module_permission - A (1) M 587:4 ModelAdmin.__init__ - A (1) M 593:4 ModelAdmin.__str__ - A (1) M 611:4 ModelAdmin.get_urls - A (1) M 635:4 ModelAdmin.urls - A (1) M 653:4 ModelAdmin.get_model_perms - A (1) M 666:4 ModelAdmin._get_form_for_get_fields - A (1) M 717:4 ModelAdmin.get_changelist - A (1) M 780:4 ModelAdmin.get_changelist_formset - A (1) M 801:4 ModelAdmin.get_paginator - A (1) M 804:4 ModelAdmin.log_addition - A (1) M 820:4 ModelAdmin.log_change - A (1) M 836:4 ModelAdmin.log_deletion - A (1) M 853:4 ModelAdmin.action_checkbox - A (1) M 860:4 ModelAdmin._get_action_description - A (1) M 947:4 ModelAdmin.get_list_display - A (1) M 966:4 ModelAdmin.get_list_filter - A (1) M 973:4 ModelAdmin.get_list_select_related - A (1) M 980:4 ModelAdmin.get_search_fields - A (1) M 1055:4 ModelAdmin.construct_change_message - A (1) M 1086:4 ModelAdmin.save_form - A (1) M 1093:4 ModelAdmin.save_model - A (1) M 1099:4 ModelAdmin.delete_model - A (1) M 1105:4 ModelAdmin.delete_queryset - A (1) M 1109:4 ModelAdmin.save_formset - A (1) M 1339:4 ModelAdmin.response_post_save_add - A (1) M 1346:4 ModelAdmin.response_post_save_change - A (1) M 1522:4 ModelAdmin._get_obj_does_not_exist_redirect - A (1) M 1536:4 ModelAdmin.changeform_view - A (1) M 1654:4 ModelAdmin.add_view - A (1) M 1657:4 ModelAdmin.change_view - A (1) M 1839:4 ModelAdmin.get_deleted_objects - A (1) M 1847:4 ModelAdmin.delete_view - A (1) M 2042:4 InlineModelAdmin.get_extra - A (1) M 2046:4 InlineModelAdmin.get_min_num - A (1) M 2050:4 InlineModelAdmin.get_max_num - A (1) M 2143:4 InlineModelAdmin._get_form_for_get_fields - A (1) C 2199:0 StackedInline - A (1) C 2203:0 TabularInline - A (1) django/contrib/admin/models.py M 96:4 LogEntry.get_change_message - C (13) C 39:0 LogEntry - A (4) M 74:4 LogEntry.__str__ - A (4) M 140:4 LogEntry.get_admin_url - A (4) C 23:0 LogEntryManager - A (3) M 26:4 LogEntryManager.log_action - A (2) M 71:4 LogEntry.__repr__ - A (1) M 87:4 LogEntry.is_addition - A (1) M 90:4 LogEntry.is_change - A (1) M 93:4 LogEntry.is_deletion - A (1) M 136:4 LogEntry.get_edited_object - A (1) django/contrib/admin/checks.py F 58:0 check_dependencies - C (17) M 563:4 BaseModelAdminChecks._check_ordering_item - C (12) M 177:4 BaseModelAdminChecks._check_autocomplete_fields_item - B (10) M 896:4 ModelAdminChecks._check_list_editable_item - B (10) M 809:4 ModelAdminChecks._check_list_filter_item - B (9) M 294:4 BaseModelAdminChecks._check_fieldsets_item - B (8) M 247:4 BaseModelAdminChecks._check_fields - B (6) M 342:4 BaseModelAdminChecks._check_field_spec_item - B (6) M 613:4 BaseModelAdminChecks._check_readonly_fields_item - B (6) M 736:4 ModelAdminChecks._check_list_display_item - B (6) C 146:0 BaseModelAdminChecks - A (5) M 232:4 BaseModelAdminChecks._check_raw_id_fields_item - A (5) M 441:4 BaseModelAdminChecks._check_radio_fields_key - A (5) M 688:4 ModelAdminChecks._check_inlines_item - A (5) M 769:4 ModelAdminChecks._check_list_display_links - A (5) M 954:4 ModelAdminChecks._check_date_hierarchy - A (5) M 977:4 ModelAdminChecks._check_action_permission_methods - A (5) M 1035:4 InlineModelAdminChecks._check_exclude_of_parent_model - A (5) F 33:0 _contains_subclass - A (4) M 279:4 BaseModelAdminChecks._check_fieldsets - A (4) M 370:4 BaseModelAdminChecks._check_exclude - A (4) M 416:4 BaseModelAdminChecks._check_filter_item - A (4) M 504:4 BaseModelAdminChecks._check_prepopulated_fields_key - A (4) M 549:4 BaseModelAdminChecks._check_ordering - A (4) M 600:4 BaseModelAdminChecks._check_readonly_fields - A (4) C 638:0 ModelAdminChecks - A (4) M 1003:4 ModelAdminChecks._check_actions_uniqueness - A (4) M 165:4 BaseModelAdminChecks._check_autocomplete_fields - A (3) M 220:4 BaseModelAdminChecks._check_raw_id_fields - A (3) M 329:4 BaseModelAdminChecks._check_field_spec - A (3) M 396:4 BaseModelAdminChecks._check_filter_vertical - A (3) M 406:4 BaseModelAdminChecks._check_filter_horizontal - A (3) M 430:4 BaseModelAdminChecks._check_radio_fields - A (3) M 480:4 BaseModelAdminChecks._check_view_on_site_url - A (3) M 492:4 BaseModelAdminChecks._check_prepopulated_fields - A (3) M 526:4 BaseModelAdminChecks._check_prepopulated_fields_value - A (3) M 538:4 BaseModelAdminChecks._check_prepopulated_fields_value_item - A (3) M 677:4 ModelAdminChecks._check_inlines - A (3) M 724:4 ModelAdminChecks._check_list_display - A (3) M 800:4 ModelAdminChecks._check_list_filter - A (3) M 884:4 ModelAdminChecks._check_list_editable - A (3) C 1021:0 InlineModelAdminChecks - A (3) M 1064:4 InlineModelAdminChecks._check_relation - A (3) M 1080:4 InlineModelAdminChecks._check_max_num - A (3) M 1090:4 InlineModelAdminChecks._check_min_num - A (3) F 22:0 _issubclass - A (2) F 50:0 check_admin_app - A (2) M 388:4 BaseModelAdminChecks._check_form - A (2) M 464:4 BaseModelAdminChecks._check_radio_fields_value - A (2) M 659:4 ModelAdminChecks._check_save_as - A (2) M 668:4 ModelAdminChecks._check_save_on_top - A (2) M 786:4 ModelAdminChecks._check_list_display_links_item - A (2) M 860:4 ModelAdminChecks._check_list_select_related - A (2) M 868:4 ModelAdminChecks._check_list_per_page - A (2) M 876:4 ModelAdminChecks._check_list_max_show_all - A (2) M 946:4 ModelAdminChecks._check_search_fields - A (2) M 1072:4 InlineModelAdminChecks._check_extra - A (2) M 1100:4 InlineModelAdminChecks._check_formset - A (2) F 1109:0 must_be - A (1) F 1119:0 must_inherit_from - A (1) F 1129:0 refer_to_missing_field - A (1) M 148:4 BaseModelAdminChecks.check - A (1) M 640:4 ModelAdminChecks.check - A (1) M 1023:4 InlineModelAdminChecks.check - A (1) django/contrib/admin/actions.py F 18:0 delete_selected - B (9) django/contrib/admin/__init__.py F 23:0 autodiscover - A (1) django/contrib/admin/apps.py C 7:0 SimpleAdminConfig - A (2) C 20:0 AdminConfig - A (2) M 15:4 SimpleAdminConfig.ready - A (1) M 25:4 AdminConfig.ready - A (1) django/contrib/admin/widgets.py M 420:4 AutocompleteMixin.optgroups - B (9) F 100:0 url_params_from_lookup_dict - B (8) M 231:4 RelatedFieldWidgetWrapper.__init__ - B (6) M 273:4 RelatedFieldWidgetWrapper.get_context - B (6) M 133:4 ForeignKeyRawIdWidget.get_context - A (4) C 326:0 AdminURLFieldWidget - A (4) M 333:4 AdminURLFieldWidget.get_context - A (4) C 376:0 AutocompleteMixin - A (4) C 20:0 FilteredSelectMultiple - A (3) C 49:0 AdminDateWidget - A (3) C 61:0 AdminTimeWidget - A (3) C 120:0 ForeignKeyRawIdWidget - A (3) M 173:4 ForeignKeyRawIdWidget.label_and_url_for_value - A (3) C 195:0 ManyToManyRawIdWidget - A (3) M 220:4 ManyToManyRawIdWidget.format_value - A (3) C 224:0 RelatedFieldWidgetWrapper - A (3) C 311:0 AdminTextareaWidget - A (3) C 316:0 AdminTextInputWidget - A (3) C 321:0 AdminEmailInputWidget - A (3) C 347:0 AdminIntegerFieldWidget - A (3) C 358:0 AdminUUIDInputWidget - A (3) M 448:4 AutocompleteMixin.media - A (3) M 39:4 FilteredSelectMultiple.get_context - A (2) M 56:4 AdminDateWidget.__init__ - A (2) M 68:4 AdminTimeWidget.__init__ - A (2) C 73:0 AdminSplitDateTime - A (2) M 161:4 ForeignKeyRawIdWidget.base_url_parameters - A (2) M 202:4 ManyToManyRawIdWidget.get_context - A (2) M 215:4 ManyToManyRawIdWidget.value_from_datadict - A (2) M 312:4 AdminTextareaWidget.__init__ - A (2) M 317:4 AdminTextInputWidget.__init__ - A (2) M 322:4 AdminEmailInputWidget.__init__ - A (2) M 329:4 AdminURLFieldWidget.__init__ - A (2) M 350:4 AdminIntegerFieldWidget.__init__ - A (2) M 359:4 AdminUUIDInputWidget.__init__ - A (2) M 385:4 AutocompleteMixin.__init__ - A (2) M 395:4 AutocompleteMixin.build_attrs - A (2) M 34:4 FilteredSelectMultiple.__init__ - A (1) M 79:4 AdminSplitDateTime.__init__ - A (1) M 85:4 AdminSplitDateTime.get_context - A (1) C 92:0 AdminRadioSelect - A (1) C 96:0 AdminFileWidget - A (1) M 127:4 ForeignKeyRawIdWidget.__init__ - A (1) M 167:4 ForeignKeyRawIdWidget.url_parameters - A (1) M 209:4 ManyToManyRawIdWidget.url_parameters - A (1) M 212:4 ManyToManyRawIdWidget.label_and_url_for_value - A (1) M 254:4 RelatedFieldWidgetWrapper.__deepcopy__ - A (1) M 262:4 RelatedFieldWidgetWrapper.is_hidden - A (1) M 266:4 RelatedFieldWidgetWrapper.media - A (1) M 269:4 RelatedFieldWidgetWrapper.get_related_url - A (1) M 301:4 RelatedFieldWidgetWrapper.value_from_datadict - A (1) M 304:4 RelatedFieldWidgetWrapper.value_omitted_from_data - A (1) M 307:4 RelatedFieldWidgetWrapper.id_for_label - A (1) C 354:0 AdminBigIntegerFieldWidget - A (1) M 392:4 AutocompleteMixin.get_url - A (1) C 469:0 AutocompleteSelect - A (1) C 473:0 AutocompleteSelectMultiple - A (1) django/contrib/admin/forms.py C 6:0 AdminAuthenticationForm - A (3) M 19:4 AdminAuthenticationForm.confirm_login_allowed - A (2) C 29:0 AdminPasswordChangeForm - A (1) django/contrib/admin/utils.py F 309:0 label_for_field - C (19) F 381:0 display_for_field - C (13) F 288:0 _get_non_gfk_field - B (9) F 411:0 display_for_value - B (9) F 28:0 lookup_needs_distinct - B (8) F 262:0 lookup_field - B (8) F 494:0 construct_change_message - B (8) F 443:0 reverse_field_path - B (7) M 170:4 NestedObjects.collect - B (6) F 104:0 get_deleted_objects - A (5) M 192:4 NestedObjects._nested - A (5) F 244:0 model_ngettext - A (4) F 369:0 help_text_for_field - A (4) F 543:0 _get_changed_field_labels_from_form - A (4) F 53:0 prepare_lookup_value - A (3) F 81:0 flatten - A (3) F 225:0 model_format_dict - A (3) F 474:0 get_fields_from_path - A (3) C 160:0 NestedObjects - A (3) F 66:0 quote - A (2) F 94:0 flatten_fieldsets - A (2) F 436:0 get_model_from_relation - A (2) M 188:4 NestedObjects.related_objects - A (2) M 207:4 NestedObjects.nested - A (2) F 76:0 unquote - A (1) C 23:0 FieldIsAForeignKeyColumnName - A (1) M 161:4 NestedObjects.__init__ - A (1) M 167:4 NestedObjects.add_edge - A (1) M 217:4 NestedObjects.can_fast_delete - A (1) C 432:0 NotRelationField - A (1) django/contrib/admin/sites.py M 434:4 AdminSite._build_app_dict - C (14) M 96:4 AdminSite.register - B (9) M 384:4 AdminSite.login - B (8) M 80:4 AdminSite.check - B (6) M 421:4 AdminSite.catch_all_view - B (6) M 242:4 AdminSite.get_urls - A (5) C 38:0 AdminSite - A (4) M 144:4 AdminSite.unregister - A (4) M 537:4 AdminSite.app_index - A (4) M 198:4 AdminSite.admin_view - A (3) M 302:4 AdminSite.each_context - A (3) M 322:4 AdminSite.password_change - A (3) M 339:4 AdminSite.password_change_done - A (3) M 362:4 AdminSite.logout - A (3) M 519:4 AdminSite.index - A (3) M 163:4 AdminSite.add_action - A (2) M 191:4 AdminSite.has_permission - A (2) M 502:4 AdminSite.get_app_list - A (2) C 559:0 DefaultAdminSite - A (2) C 30:0 AlreadyRegistered - A (1) C 34:0 NotRegistered - A (1) M 73:4 AdminSite.__init__ - A (1) M 157:4 AdminSite.is_registered - A (1) M 171:4 AdminSite.disable_action - A (1) M 177:4 AdminSite.get_action - A (1) M 185:4 AdminSite.actions - A (1) M 299:4 AdminSite.urls - A (1) M 352:4 AdminSite.i18n_javascript - A (1) M 417:4 AdminSite.autocomplete_view - A (1) M 560:4 DefaultAdminSite._setup - A (1) django/contrib/admin/exceptions.py C 4:0 DisallowedModelAdminLookup - A (1) C 9:0 DisallowedModelAdminToField - A (1) django/contrib/admin/tests.py M 157:4 AdminSeleniumTestCase._assertOptionsValues - A (3) C 10:0 CSPMiddleware - A (2) C 18:0 AdminSeleniumTestCase - A (2) M 12:4 CSPMiddleware.process_response - A (1) M 28:4 AdminSeleniumTestCase.wait_until - A (1) M 38:4 AdminSeleniumTestCase.wait_for_and_switch_to_popup - A (1) M 48:4 AdminSeleniumTestCase.wait_for - A (1) M 59:4 AdminSeleniumTestCase.wait_for_text - A (1) M 71:4 AdminSeleniumTestCase.wait_for_value - A (1) M 83:4 AdminSeleniumTestCase.wait_until_visible - A (1) M 94:4 AdminSeleniumTestCase.wait_until_invisible - A (1) M 105:4 AdminSeleniumTestCase.wait_page_ready - A (1) M 115:4 AdminSeleniumTestCase.wait_page_loaded - A (1) M 126:4 AdminSeleniumTestCase.admin_login - A (1) M 139:4 AdminSeleniumTestCase.select_option - A (1) M 148:4 AdminSeleniumTestCase.deselect_option - A (1) M 173:4 AdminSeleniumTestCase.assertSelectOptions - A (1) M 180:4 AdminSeleniumTestCase.assertSelectedOptions - A (1) M 187:4 AdminSeleniumTestCase.has_css_class - A (1) django/contrib/admin/helpers.py M 204:4 AdminReadonlyField.contents - C (13) M 289:4 InlineAdminFormSet.fields - C (11) C 153:0 AdminReadonlyField - B (7) M 154:4 AdminReadonlyField.__init__ - B (7) M 94:4 Fieldline.__init__ - B (6) M 131:4 AdminField.label_tag - B (6) C 93:0 Fieldline - A (5) M 264:4 InlineAdminFormSet.__iter__ - A (5) M 372:4 InlineAdminForm.needs_explicit_pk_field - A (5) C 414:0 AdminErrorList - A (5) M 36:4 AdminForm.__init__ - A (4) C 124:0 AdminField - A (4) C 240:0 InlineAdminFormSet - A (4) M 244:4 InlineAdminFormSet.__init__ - A (4) C 402:0 InlineFieldset - A (4) M 407:4 InlineFieldset.__iter__ - A (4) M 416:4 AdminErrorList.__init__ - A (4) C 35:0 AdminForm - A (3) C 72:0 Fieldset - A (3) M 109:4 Fieldline.__iter__ - A (3) M 116:4 Fieldline.errors - A (3) C 352:0 InlineAdminForm - A (3) M 47:4 AdminForm.__iter__ - A (2) M 65:4 AdminForm.media - A (2) M 83:4 Fieldset.media - A (2) M 88:4 Fieldset.__iter__ - A (2) M 186:4 AdminReadonlyField.label_tag - A (2) M 193:4 AdminReadonlyField.get_admin_url - A (2) M 345:4 InlineAdminFormSet.media - A (2) M 356:4 InlineAdminForm.__init__ - A (2) M 365:4 InlineAdminForm.__iter__ - A (2) M 386:4 InlineAdminForm.fk_field - A (2) C 22:0 ActionForm - A (1) M 57:4 AdminForm.errors - A (1) M 61:4 AdminForm.non_field_errors - A (1) M 73:4 Fieldset.__init__ - A (1) M 125:4 AdminField.__init__ - A (1) M 149:4 AdminField.errors - A (1) M 323:4 InlineAdminFormSet.inline_formset_data - A (1) M 337:4 InlineAdminFormSet.forms - A (1) M 341:4 InlineAdminFormSet.non_form_errors - A (1) M 383:4 InlineAdminForm.pk_field - A (1) M 393:4 InlineAdminForm.deletion_field - A (1) M 397:4 InlineAdminForm.ordering_field - A (1) M 403:4 InlineFieldset.__init__ - A (1) django/contrib/admin/filters.py M 308:4 DateFieldListFilter.__init__ - B (7) M 448:4 EmptyFieldListFilter.queryset - B (6) C 307:0 DateFieldListFilter - A (5) M 399:4 AllValuesFieldListFilter.choices - A (5) M 66:4 SimpleListFilter.__init__ - A (4) M 209:4 RelatedFieldListFilter.choices - A (4) C 232:0 BooleanFieldListFilter - A (4) M 233:4 BooleanFieldListFilter.__init__ - A (4) M 246:4 BooleanFieldListFilter.choices - A (4) M 280:4 ChoicesFieldListFilter.choices - A (4) C 380:0 AllValuesFieldListFilter - A (4) C 434:0 EmptyFieldListFilter - A (4) C 118:0 FieldListFilter - A (3) M 122:4 FieldListFilter.__init__ - A (3) M 156:4 FieldListFilter.create - A (3) C 162:0 RelatedFieldListFilter - A (3) M 179:4 RelatedFieldListFilter.include_empty_choice - A (3) C 269:0 ChoicesFieldListFilter - A (3) M 435:4 EmptyFieldListFilter.__init__ - A (3) C 20:0 ListFilter - A (2) M 24:4 ListFilter.__init__ - A (2) C 62:0 SimpleListFilter - A (2) M 104:4 SimpleListFilter.choices - A (2) M 135:4 FieldListFilter.queryset - A (2) M 144:4 FieldListFilter.register - A (2) M 163:4 RelatedFieldListFilter.__init__ - A (2) M 186:4 RelatedFieldListFilter.has_output - A (2) M 196:4 RelatedFieldListFilter.field_admin_ordering - A (2) M 358:4 DateFieldListFilter.expected_parameters - A (2) M 364:4 DateFieldListFilter.choices - A (2) M 381:4 AllValuesFieldListFilter.__init__ - A (2) C 427:0 RelatedOnlyFieldListFilter - A (2) M 466:4 EmptyFieldListFilter.choices - A (2) M 34:4 ListFilter.has_output - A (1) M 40:4 ListFilter.choices - A (1) M 48:4 ListFilter.queryset - A (1) M 54:4 ListFilter.expected_parameters - A (1) M 81:4 SimpleListFilter.has_output - A (1) M 84:4 SimpleListFilter.value - A (1) M 92:4 SimpleListFilter.lookups - A (1) M 101:4 SimpleListFilter.expected_parameters - A (1) M 132:4 FieldListFilter.has_output - A (1) M 193:4 RelatedFieldListFilter.expected_parameters - A (1) M 205:4 RelatedFieldListFilter.field_choices - A (1) M 243:4 BooleanFieldListFilter.expected_parameters - A (1) M 270:4 ChoicesFieldListFilter.__init__ - A (1) M 277:4 ChoicesFieldListFilter.expected_parameters - A (1) M 396:4 AllValuesFieldListFilter.expected_parameters - A (1) M 428:4 RelatedOnlyFieldListFilter.field_choices - A (1) M 463:4 EmptyFieldListFilter.expected_parameters - A (1) django/contrib/admin/decorators.py F 1:0 action - A (2) F 32:0 display - A (2) F 74:0 register - A (1) django/contrib/admin/templatetags/admin_list.py F 182:0 items_for_result - D (27) F 322:0 date_hierarchy - D (22) F 73:0 result_headers - C (14) F 46:0 pagination - B (7) F 29:0 paginator_number - A (4) F 278:0 results - A (4) F 287:0 result_hidden_fields - A (4) F 294:0 result_list - A (4) F 170:0 _coerce_field_name - A (3) C 267:0 ResultList - A (2) F 64:0 pagination_tag - A (1) F 165:0 _boolean_icon - A (1) F 313:0 result_list_tag - A (1) F 410:0 date_hierarchy_tag - A (1) F 419:0 search_form - A (1) F 431:0 search_form_tag - A (1) F 436:0 admin_list_filter - A (1) F 445:0 admin_actions - A (1) F 455:0 admin_actions_tag - A (1) F 460:0 change_list_object_tools_tag - A (1) M 273:4 ResultList.__init__ - A (1) django/contrib/admin/templatetags/log.py F 27:0 get_admin_log - B (7) C 7:0 AdminLogNode - A (3) M 14:4 AdminLogNode.render - A (3) M 8:4 AdminLogNode.__init__ - A (1) M 11:4 AdminLogNode.__repr__ - A (1) django/contrib/admin/templatetags/admin_modify.py F 48:0 submit_row - D (22) F 11:0 prepopulated_fields_js - B (10) F 105:0 cell_count - A (5) F 44:0 prepopulated_fields_js_tag - A (1) F 90:0 submit_row_tag - A (1) F 95:0 change_form_object_tools_tag - A (1) django/contrib/admin/templatetags/base.py C 6:0 InclusionAdminNode - A (2) M 12:4 InclusionAdminNode.__init__ - A (1) M 22:4 InclusionAdminNode.render - A (1) django/contrib/admin/templatetags/admin_urls.py F 22:0 add_preserved_filters - C (11) F 12:0 admin_urlname - A (1) F 17:0 admin_urlquote - A (1) django/contrib/admin/migrations/0002_logentry_remove_auto_add.py C 5:0 Migration - A (1) django/contrib/admin/migrations/0003_logentry_add_action_flag_choices.py C 4:0 Migration - A (1) django/contrib/admin/migrations/0001_initial.py C 6:0 Migration - A (1) django/contrib/admin/views/autocomplete.py M 48:4 AutocompleteJsonView.process_request - B (8) C 7:0 AutocompleteJsonView - A (4) M 12:4 AutocompleteJsonView.get - A (3) M 39:4 AutocompleteJsonView.get_queryset - A (2) M 35:4 AutocompleteJsonView.get_paginator - A (1) M 99:4 AutocompleteJsonView.has_perm - A (1) django/contrib/admin/views/main.py M 123:4 ChangeList.get_filters - D (23) M 340:4 ChangeList._get_deterministic_ordering - D (23) M 402:4 ChangeList.get_ordering_field_columns - C (13) M 51:4 ChangeList.__init__ - C (12) M 297:4 ChangeList.get_ordering - C (12) C 48:0 ChangeList - B (10) M 214:4 ChangeList.get_query_string - B (9) M 232:4 ChangeList.get_results - B (7) M 442:4 ChangeList.get_queryset - B (7) M 273:4 ChangeList.get_ordering_field - B (6) M 508:4 ChangeList.has_related_field_in_list_display - B (6) M 496:4 ChangeList.apply_select_related - A (5) M 110:4 ChangeList.get_filters_params - A (4) M 265:4 ChangeList._get_default_ordering - A (3) C 39:0 ChangeListSearchForm - A (2) M 40:4 ChangeListSearchForm.__init__ - A (1) M 521:4 ChangeList.url_for_result - A (1) django/contrib/admin/views/decorators.py F 5:0 staff_member_required - A (3) django/contrib/staticfiles/finders.py F 257:0 find - B (7) M 70:4 FileSystemFinder.check - B (7) M 142:4 AppDirectoriesFinder.__init__ - B (7) M 216:4 BaseStorageFinder.find - B (7) C 47:0 FileSystemFinder - B (6) C 134:0 AppDirectoriesFinder - B (6) M 52:4 FileSystemFinder.__init__ - A (5) M 95:4 FileSystemFinder.find - A (5) M 169:4 AppDirectoriesFinder.find - A (5) C 197:0 BaseStorageFinder - A (5) M 110:4 FileSystemFinder.find_location - A (4) M 160:4 AppDirectoriesFinder.list - A (4) M 185:4 AppDirectoriesFinder.find_in_app - A (4) M 204:4 BaseStorageFinder.__init__ - A (4) M 124:4 FileSystemFinder.list - A (3) C 242:0 DefaultStorageFinder - A (3) F 279:0 get_finders - A (2) F 285:0 get_finder - A (2) C 20:0 BaseFinder - A (2) M 234:4 BaseStorageFinder.list - A (2) M 248:4 DefaultStorageFinder.__init__ - A (2) M 24:4 BaseFinder.check - A (1) M 30:4 BaseFinder.find - A (1) M 39:4 BaseFinder.list - A (1) django/contrib/staticfiles/checks.py F 4:0 check_finders - A (4) django/contrib/staticfiles/handlers.py C 64:0 StaticFilesHandler - A (3) C 80:0 ASGIStaticFilesHandler - A (3) M 89:4 ASGIStaticFilesHandler.__call__ - A (3) C 15:0 StaticFilesHandlerMixin - A (2) M 32:4 StaticFilesHandlerMixin._should_handle - A (2) M 51:4 StaticFilesHandlerMixin.get_response - A (2) M 57:4 StaticFilesHandlerMixin.get_response_async - A (2) M 74:4 StaticFilesHandler.__call__ - A (2) M 23:4 StaticFilesHandlerMixin.load_middleware - A (1) M 28:4 StaticFilesHandlerMixin.get_base_url - A (1) M 40:4 StaticFilesHandlerMixin.file_path - A (1) M 47:4 StaticFilesHandlerMixin.serve - A (1) M 69:4 StaticFilesHandler.__init__ - A (1) M 85:4 ASGIStaticFilesHandler.__init__ - A (1) django/contrib/staticfiles/apps.py C 7:0 StaticFilesConfig - A (2) M 12:4 StaticFilesConfig.ready - A (1) django/contrib/staticfiles/utils.py F 42:0 check_settings - C (11) F 16:0 get_files - B (9) F 8:0 matches_patterns - A (2) django/contrib/staticfiles/storage.py M 262:4 HashedFilesMixin._post_process - C (15) M 203:4 HashedFilesMixin.post_process - C (13) M 112:4 HashedFilesMixin._url - C (11) M 79:4 HashedFilesMixin.hashed_name - B (10) C 44:0 HashedFilesMixin - B (6) M 393:4 ManifestFilesMixin.load_manifest - B (6) M 421:4 ManifestFilesMixin.stored_name - A (5) C 16:0 StaticFilesStorage - A (4) M 23:4 StaticFilesStorage.__init__ - A (4) M 55:4 HashedFilesMixin.__init__ - A (4) M 352:4 HashedFilesMixin.stored_name - A (4) C 376:0 ManifestFilesMixin - A (4) M 68:4 HashedFilesMixin.file_hash - A (3) M 36:4 StaticFilesStorage.path - A (2) M 149:4 HashedFilesMixin.url_converter - A (2) M 340:4 HashedFilesMixin._stored_name - A (2) M 386:4 ManifestFilesMixin.read_manifest - A (2) M 408:4 ManifestFilesMixin.post_process - A (2) M 414:4 ManifestFilesMixin.save_manifest - A (2) C 447:0 ConfiguredStorage - A (2) M 143:4 HashedFilesMixin.url - A (1) M 334:4 HashedFilesMixin.clean_name - A (1) M 337:4 HashedFilesMixin.hash_key - A (1) M 382:4 ManifestFilesMixin.__init__ - A (1) C 439:0 ManifestStaticFilesStorage - A (1) M 448:4 ConfiguredStorage._setup - A (1) django/contrib/staticfiles/testing.py C 5:0 StaticLiveServerTestCase - A (1) django/contrib/staticfiles/urls.py F 8:0 staticfiles_urlpatterns - A (2) django/contrib/staticfiles/views.py F 15:0 serve - B (6) django/contrib/staticfiles/management/commands/findstatic.py M 18:4 Command.handle_label - B (9) C 7:0 Command - B (6) M 11:4 Command.add_arguments - A (1) django/contrib/staticfiles/management/commands/runserver.py C 8:0 Command - A (4) M 22:4 Command.get_handler - A (4) M 11:4 Command.add_arguments - A (1) django/contrib/staticfiles/management/commands/collectstatic.py M 148:4 Command.handle - C (16) M 86:4 Command.collect - C (14) M 244:4 Command.delete_file - C (13) M 217:4 Command.clear_dir - B (9) M 294:4 Command.link_file - B (9) C 13:0 Command - B (7) M 330:4 Command.copy_file - A (4) M 71:4 Command.set_options - A (3) M 31:4 Command.local - A (2) M 207:4 Command.log - A (2) M 21:4 Command.__init__ - A (1) M 38:4 Command.add_arguments - A (1) M 214:4 Command.is_local_storage - A (1) django/contrib/flatpages/models.py C 8:0 FlatPage - A (3) M 38:4 FlatPage.get_absolute_url - A (3) M 35:4 FlatPage.__str__ - A (1) django/contrib/flatpages/apps.py C 5:0 FlatPagesConfig - A (1) django/contrib/flatpages/forms.py M 53:4 FlatpageForm.clean - B (6) C 8:0 FlatpageForm - A (4) M 39:4 FlatpageForm.clean_url - A (4) M 26:4 FlatpageForm.__init__ - A (2) M 33:4 FlatpageForm._trailing_slash_required - A (2) django/contrib/flatpages/admin.py C 8:0 FlatPageAdmin - A (1) django/contrib/flatpages/sitemaps.py C 6:0 FlatPageSitemap - A (3) M 7:4 FlatPageSitemap.items - A (2) django/contrib/flatpages/middleware.py C 7:0 FlatpageFallbackMiddleware - B (6) M 8:4 FlatpageFallbackMiddleware.process_response - A (5) django/contrib/flatpages/views.py F 22:0 flatpage - A (5) F 49:0 render_flatpage - A (4) django/contrib/flatpages/templatetags/flatpages.py F 46:0 get_flatpages - B (6) C 9:0 FlatpageNode - A (5) M 21:4 FlatpageNode.render - A (5) M 10:4 FlatpageNode.__init__ - A (3) django/contrib/flatpages/migrations/0001_initial.py C 4:0 Migration - A (1) django/contrib/sites/models.py M 34:4 SiteManager._get_site_by_request - A (4) F 12:0 _simple_domain_name_validator - A (3) F 103:0 clear_site_cache - A (3) C 25:0 SiteManager - A (3) M 48:4 SiteManager.get_current - A (3) M 28:4 SiteManager._get_site_by_id - A (2) C 78:0 Site - A (2) M 69:4 SiteManager.clear_cache - A (1) M 74:4 SiteManager.get_by_natural_key - A (1) M 96:4 Site.__str__ - A (1) M 99:4 Site.natural_key - A (1) django/contrib/sites/shortcuts.py F 4:0 get_current_site - A (2) django/contrib/sites/checks.py F 5:0 check_site_id - A (3) django/contrib/sites/apps.py C 10:0 SitesConfig - A (2) M 15:4 SitesConfig.ready - A (1) django/contrib/sites/admin.py C 6:0 SiteAdmin - A (1) django/contrib/sites/management.py F 11:0 create_default_site - B (8) django/contrib/sites/requests.py C 1:0 RequestSite - A (2) M 9:4 RequestSite.__init__ - A (1) M 12:4 RequestSite.__str__ - A (1) M 15:4 RequestSite.save - A (1) M 18:4 RequestSite.delete - A (1) django/contrib/sites/middleware.py C 6:0 CurrentSiteMiddleware - A (2) M 11:4 CurrentSiteMiddleware.process_request - A (1) django/contrib/sites/managers.py M 21:4 CurrentSiteManager._check_field_name - A (4) M 47:4 CurrentSiteManager._get_field_name - A (4) C 7:0 CurrentSiteManager - A (3) M 12:4 CurrentSiteManager.__init__ - A (1) M 16:4 CurrentSiteManager.check - A (1) M 59:4 CurrentSiteManager.get_queryset - A (1) django/contrib/sites/migrations/0002_alter_domain_unique.py C 5:0 Migration - A (1) django/contrib/sites/migrations/0001_initial.py C 6:0 Migration - A (1) django/contrib/postgres/functions.py C 4:0 RandomUUID - A (1) C 9:0 TransactionNow - A (1) django/contrib/postgres/signals.py F 37:0 register_type_handlers - A (5) F 12:0 get_hstore_oids - A (2) F 30:0 get_citext_oids - A (2) django/contrib/postgres/validators.py C 25:0 KeysValidator - A (4) M 40:4 KeysValidator.__call__ - A (4) M 58:4 KeysValidator.__eq__ - A (4) C 67:0 RangeMaxValueValidator - A (3) C 73:0 RangeMinValueValidator - A (3) M 34:4 KeysValidator.__init__ - A (2) M 68:4 RangeMaxValueValidator.compare - A (2) M 74:4 RangeMinValueValidator.compare - A (2) C 10:0 ArrayMaxLengthValidator - A (1) C 17:0 ArrayMinLengthValidator - A (1) django/contrib/postgres/serializers.py C 4:0 RangeSerializer - A (3) M 5:4 RangeSerializer.serialize - A (2) django/contrib/postgres/lookups.py C 28:0 HasKeys - A (3) C 47:0 SearchLookup - A (3) M 32:4 HasKeys.get_prep_lookup - A (2) M 50:4 SearchLookup.process_lhs - A (2) C 7:0 DataContains - A (1) C 12:0 ContainedBy - A (1) C 17:0 Overlap - A (1) C 22:0 HasKey - A (1) C 36:0 HasAnyKeys - A (1) C 41:0 Unaccent - A (1) C 58:0 TrigramSimilar - A (1) django/contrib/postgres/apps.py C 43:0 PostgresConfig - A (5) F 23:0 uninstall_if_needed - A (4) M 47:4 PostgresConfig.ready - A (4) django/contrib/postgres/operations.py M 191:4 CollationOperation.create_collation - B (6) M 18:4 CreateExtension.database_forwards - A (4) M 179:4 CollationOperation.deconstruct - A (4) M 36:4 CreateExtension.database_backwards - A (3) C 111:0 NotInTransactionMixin - A (3) C 121:0 AddIndexConcurrently - A (3) C 145:0 RemoveIndexConcurrently - A (3) C 169:0 CollationOperation - A (3) C 215:0 CreateCollation - A (3) M 217:4 CreateCollation.database_forwards - A (3) C 238:0 RemoveCollation - A (3) M 240:4 RemoveCollation.database_forwards - A (3) C 9:0 CreateExtension - A (2) C 63:0 BloomExtension - A (2) C 69:0 BtreeGinExtension - A (2) C 75:0 BtreeGistExtension - A (2) C 81:0 CITextExtension - A (2) C 87:0 CryptoExtension - A (2) C 93:0 HStoreExtension - A (2) C 99:0 TrigramExtension - A (2) C 105:0 UnaccentExtension - A (2) M 112:4 NotInTransactionMixin._ensure_not_in_transaction - A (2) M 132:4 AddIndexConcurrently.database_forwards - A (2) M 138:4 AddIndexConcurrently.database_backwards - A (2) M 152:4 RemoveIndexConcurrently.database_forwards - A (2) M 160:4 RemoveIndexConcurrently.database_backwards - A (2) M 225:4 CreateCollation.database_backwards - A (2) M 248:4 RemoveCollation.database_backwards - A (2) M 12:4 CreateExtension.__init__ - A (1) M 15:4 CreateExtension.state_forwards - A (1) M 47:4 CreateExtension.extension_exists - A (1) M 55:4 CreateExtension.describe - A (1) M 59:4 CreateExtension.migration_name_fragment - A (1) M 65:4 BloomExtension.__init__ - A (1) M 71:4 BtreeGinExtension.__init__ - A (1) M 77:4 BtreeGistExtension.__init__ - A (1) M 83:4 CITextExtension.__init__ - A (1) M 89:4 CryptoExtension.__init__ - A (1) M 95:4 HStoreExtension.__init__ - A (1) M 101:4 TrigramExtension.__init__ - A (1) M 107:4 UnaccentExtension.__init__ - A (1) M 125:4 AddIndexConcurrently.describe - A (1) M 149:4 RemoveIndexConcurrently.describe - A (1) M 170:4 CollationOperation.__init__ - A (1) M 176:4 CollationOperation.state_forwards - A (1) M 209:4 CollationOperation.remove_collation - A (1) M 230:4 CreateCollation.describe - A (1) M 234:4 CreateCollation.migration_name_fragment - A (1) M 253:4 RemoveCollation.describe - A (1) M 257:4 RemoveCollation.migration_name_fragment - A (1) django/contrib/postgres/indexes.py M 42:4 BloomIndex.__init__ - B (8) C 39:0 BloomIndex - B (6) M 71:4 BloomIndex.get_with_params - A (4) C 83:0 BrinIndex - A (4) M 101:4 BrinIndex.get_with_params - A (4) C 130:0 GinIndex - A (4) M 146:4 GinIndex.get_with_params - A (4) C 155:0 GistIndex - A (4) M 171:4 GistIndex.get_with_params - A (4) M 63:4 BloomIndex.deconstruct - A (3) M 86:4 BrinIndex.__init__ - A (3) M 93:4 BrinIndex.deconstruct - A (3) C 110:0 BTreeIndex - A (3) M 138:4 GinIndex.deconstruct - A (3) M 163:4 GistIndex.deconstruct - A (3) M 179:4 GistIndex.check_supported - A (3) C 184:0 HashIndex - A (3) C 204:0 SpGistIndex - A (3) C 11:0 PostgresIndex - A (2) M 21:4 PostgresIndex.create_sql - A (2) M 117:4 BTreeIndex.deconstruct - A (2) M 123:4 BTreeIndex.get_with_params - A (2) M 191:4 HashIndex.deconstruct - A (2) M 197:4 HashIndex.get_with_params - A (2) M 211:4 SpGistIndex.deconstruct - A (2) M 217:4 SpGistIndex.get_with_params - A (2) C 224:0 OpClass - A (2) M 14:4 PostgresIndex.max_name_length - A (1) M 32:4 PostgresIndex.check_supported - A (1) M 35:4 PostgresIndex.get_with_params - A (1) M 113:4 BTreeIndex.__init__ - A (1) M 133:4 GinIndex.__init__ - A (1) M 158:4 GistIndex.__init__ - A (1) M 187:4 HashIndex.__init__ - A (1) M 207:4 SpGistIndex.__init__ - A (1) M 227:4 OpClass.__init__ - A (1) django/contrib/postgres/utils.py F 6:0 prefix_validation_error - A (4) django/contrib/postgres/search.py C 207:0 SearchRank - B (9) M 211:4 SearchRank.__init__ - B (8) M 95:4 SearchVector.as_sql - B (6) C 77:0 SearchVector - A (5) C 233:0 SearchHeadline - A (5) M 238:4 SearchHeadline.__init__ - A (5) C 63:0 SearchVectorCombinable - A (4) M 169:4 SearchQuery.__init__ - A (4) C 10:0 SearchVectorExact - A (3) M 47:4 SearchConfig.from_parameter - A (3) M 66:4 SearchVectorCombinable._combine - A (3) M 82:4 SearchVector.__init__ - A (3) M 134:4 SearchQueryCombinable._combine - A (3) C 160:0 SearchQuery - A (3) M 265:4 SearchHeadline.as_sql - A (3) C 287:0 TrigramBase - A (3) M 13:4 SearchVectorExact.process_rhs - A (2) C 27:0 SearchVectorField - A (2) C 33:0 SearchQueryField - A (2) C 39:0 SearchConfig - A (2) M 40:4 SearchConfig.__init__ - A (2) M 89:4 SearchVector.resolve_expression - A (2) C 124:0 CombinedSearchVector - A (2) C 130:0 SearchQueryCombinable - A (2) M 182:4 SearchQuery.as_sql - A (2) M 193:4 SearchQuery.__str__ - A (2) C 198:0 CombinedSearchQuery - A (2) M 290:4 TrigramBase.__init__ - A (2) M 20:4 SearchVectorExact.as_sql - A (1) M 29:4 SearchVectorField.db_type - A (1) M 35:4 SearchQueryField.db_type - A (1) M 52:4 SearchConfig.get_source_expressions - A (1) M 55:4 SearchConfig.set_source_expressions - A (1) M 58:4 SearchConfig.as_sql - A (1) M 125:4 CombinedSearchVector.__init__ - A (1) M 147:4 SearchQueryCombinable.__or__ - A (1) M 150:4 SearchQueryCombinable.__ror__ - A (1) M 153:4 SearchQueryCombinable.__and__ - A (1) M 156:4 SearchQueryCombinable.__rand__ - A (1) M 188:4 SearchQuery.__invert__ - A (1) M 199:4 CombinedSearchQuery.__init__ - A (1) M 203:4 CombinedSearchQuery.__str__ - A (1) C 296:0 TrigramSimilarity - A (1) C 300:0 TrigramDistance - A (1) django/contrib/postgres/constraints.py M 13:4 ExclusionConstraint.__init__ - C (20) M 144:4 ExclusionConstraint.__eq__ - B (8) C 10:0 ExclusionConstraint - B (6) M 69:4 ExclusionConstraint._get_expression_sql - B (6) M 129:4 ExclusionConstraint.deconstruct - B (6) M 157:4 ExclusionConstraint.__repr__ - A (5) M 86:4 ExclusionConstraint._get_condition_sql - A (3) M 93:4 ExclusionConstraint.constraint_sql - A (3) M 123:4 ExclusionConstraint.check_supported - A (3) M 108:4 ExclusionConstraint.create_sql - A (1) M 116:4 ExclusionConstraint.remove_sql - A (1) django/contrib/postgres/forms/ranges.py M 61:4 BaseRangeField.compress - B (7) C 31:0 BaseRangeField - A (5) C 14:0 RangeWidget - A (3) M 38:4 BaseRangeField.__init__ - A (3) M 47:4 BaseRangeField.prepare_value - A (3) M 19:4 RangeWidget.decompress - A (2) C 25:0 HiddenRangeWidget - A (2) M 15:4 RangeWidget.__init__ - A (1) M 27:4 HiddenRangeWidget.__init__ - A (1) C 81:0 IntegerRangeField - A (1) C 87:0 DecimalRangeField - A (1) C 93:0 DateTimeRangeField - A (1) C 99:0 DateRangeField - A (1) django/contrib/postgres/forms/array.py M 197:4 SplitArrayField.clean - B (8) M 133:4 SplitArrayWidget.get_context - B (7) M 39:4 SimpleArrayField.to_python - B (6) M 225:4 SplitArrayField.has_changed - B (6) C 14:0 SimpleArrayField - A (5) M 94:4 SimpleArrayField.has_changed - A (5) C 168:0 SplitArrayField - A (5) M 181:4 SplitArrayField._remove_trailing_nulls - A (5) M 62:4 SimpleArrayField.validate - A (4) M 78:4 SimpleArrayField.run_validators - A (4) M 19:4 SimpleArrayField.__init__ - A (3) M 34:4 SimpleArrayField.prepare_value - A (3) C 105:0 SplitArrayWidget - A (3) M 30:4 SimpleArrayField.clean - A (2) M 108:4 SplitArrayWidget.__init__ - A (2) M 117:4 SplitArrayWidget.value_from_datadict - A (2) M 121:4 SplitArrayWidget.value_omitted_from_data - A (2) M 127:4 SplitArrayWidget.id_for_label - A (2) M 193:4 SplitArrayField.to_python - A (2) M 114:4 SplitArrayWidget.is_hidden - A (1) M 155:4 SplitArrayWidget.media - A (1) M 158:4 SplitArrayWidget.__deepcopy__ - A (1) M 164:4 SplitArrayWidget.needs_multipart_form - A (1) M 173:4 SplitArrayField.__init__ - A (1) django/contrib/postgres/forms/hstore.py M 25:4 HStoreField.to_python - B (7) C 10:0 HStoreField - A (4) M 20:4 HStoreField.prepare_value - A (2) M 50:4 HStoreField.has_changed - A (1) django/contrib/postgres/aggregates/mixins.py M 6:4 OrderableAggMixin.__init__ - B (6) C 4:0 OrderableAggMixin - A (3) M 22:4 OrderableAggMixin.as_sql - A (3) M 18:4 OrderableAggMixin.resolve_expression - A (2) M 36:4 OrderableAggMixin.set_source_expressions - A (1) M 42:4 OrderableAggMixin.get_source_expressions - A (1) M 45:4 OrderableAggMixin._get_ordering_expressions_index - A (1) django/contrib/postgres/aggregates/statistics.py C 9:0 StatAggregate - A (4) M 12:4 StatAggregate.__init__ - A (3) C 22:0 CovarPop - A (3) C 36:0 RegrCount - A (3) M 23:4 CovarPop.__init__ - A (2) M 40:4 RegrCount.convert_value - A (2) C 18:0 Corr - A (1) C 28:0 RegrAvgX - A (1) C 32:0 RegrAvgY - A (1) C 44:0 RegrIntercept - A (1) C 48:0 RegrR2 - A (1) C 52:0 RegrSlope - A (1) C 56:0 RegrSXX - A (1) C 60:0 RegrSXY - A (1) C 64:0 RegrSYY - A (1) django/contrib/postgres/aggregates/general.py C 11:0 ArrayAgg - A (3) C 44:0 JSONBAgg - A (3) C 56:0 StringAgg - A (3) M 20:4 ArrayAgg.convert_value - A (2) M 50:4 JSONBAgg.convert_value - A (2) M 65:4 StringAgg.convert_value - A (2) M 17:4 ArrayAgg.output_field - A (1) C 26:0 BitAnd - A (1) C 30:0 BitOr - A (1) C 34:0 BoolAnd - A (1) C 39:0 BoolOr - A (1) M 61:4 StringAgg.__init__ - A (1) django/contrib/postgres/fields/citext.py C 6:0 CIText - A (2) M 8:4 CIText.get_internal_type - A (1) M 11:4 CIText.db_type - A (1) C 15:0 CICharField - A (1) C 19:0 CIEmailField - A (1) C 23:0 CITextField - A (1) django/contrib/postgres/fields/ranges.py M 77:4 RangeField.to_python - A (5) M 93:4 RangeField.value_to_string - A (5) M 68:4 RangeField.get_prep_value - A (4) C 165:0 DateTimeRangeContains - A (4) M 180:4 DateTimeRangeContains.as_postgresql - A (4) C 19:0 RangeBoundary - A (3) M 21:4 RangeBoundary.__init__ - A (3) C 43:0 RangeField - A (3) C 199:0 RangeContainedBy - A (3) M 219:4 RangeContainedBy.process_lhs - A (3) M 46:4 RangeField.__init__ - A (2) M 53:4 RangeField.model - A (2) M 65:4 RangeField._choices_is_value - A (2) C 115:0 IntegerRangeField - A (2) C 124:0 BigIntegerRangeField - A (2) C 133:0 DecimalRangeField - A (2) C 142:0 DateTimeRangeField - A (2) C 151:0 DateRangeField - A (2) M 173:4 DateTimeRangeContains.process_rhs - A (2) C 269:0 RangeStartsWith - A (2) C 279:0 RangeEndsWith - A (2) M 25:4 RangeBoundary.as_sql - A (1) C 29:0 RangeOperators - A (1) M 60:4 RangeField.model - A (1) M 89:4 RangeField.set_attributes_from_name - A (1) M 110:4 RangeField.formfield - A (1) M 120:4 IntegerRangeField.db_type - A (1) M 129:4 BigIntegerRangeField.db_type - A (1) M 138:4 DecimalRangeField.db_type - A (1) M 147:4 DateTimeRangeField.db_type - A (1) M 156:4 DateRangeField.db_type - A (1) M 212:4 RangeContainedBy.process_rhs - A (1) M 227:4 RangeContainedBy.get_prep_lookup - A (1) C 239:0 FullyLessThan - A (1) C 245:0 FullGreaterThan - A (1) C 251:0 NotLessThan - A (1) C 257:0 NotGreaterThan - A (1) C 263:0 AdjacentToLookup - A (1) M 274:4 RangeStartsWith.output_field - A (1) M 284:4 RangeEndsWith.output_field - A (1) C 289:0 IsEmpty - A (1) C 296:0 LowerInclusive - A (1) C 303:0 LowerInfinite - A (1) C 310:0 UpperInclusive - A (1) C 317:0 UpperInfinite - A (1) django/contrib/postgres/fields/utils.py C 1:0 AttributeSetter - A (2) M 2:4 AttributeSetter.__init__ - A (1) django/contrib/postgres/fields/jsonb.py C 6:0 JSONField - A (1) django/contrib/postgres/fields/array.py M 139:4 ArrayField.get_transform - B (8) M 160:4 ArrayField.validate - B (6) C 258:0 ArrayInLookup - A (5) M 53:4 ArrayField.check - A (4) C 201:0 ArrayRHSMixin - A (4) M 202:4 ArrayRHSMixin.__init__ - A (4) M 259:4 ArrayInLookup.get_prep_lookup - A (4) C 18:0 ArrayField - A (3) M 26:4 ArrayField.__init__ - A (3) M 96:4 ArrayField.get_db_prep_value - A (3) M 111:4 ArrayField.to_python - A (3) M 118:4 ArrayField._from_db_value - A (3) M 126:4 ArrayField.value_to_string - A (3) M 179:4 ArrayField.run_validators - A (3) M 38:4 ArrayField.model - A (2) M 50:4 ArrayField._choices_is_value - A (2) M 85:4 ArrayField.db_type - A (2) M 89:4 ArrayField.cast_db_type - A (2) M 101:4 ArrayField.deconstruct - A (2) C 244:0 ArrayLenTransform - A (2) C 274:0 IndexTransform - A (2) C 290:0 IndexTransformFactory - A (2) C 300:0 SliceTransform - A (2) C 312:0 SliceTransformFactory - A (2) M 45:4 ArrayField.model - A (1) M 77:4 ArrayField.set_attributes_from_name - A (1) M 82:4 ArrayField.description - A (1) M 93:4 ArrayField.get_placeholder - A (1) M 192:4 ArrayField.formfield - A (1) M 217:4 ArrayRHSMixin.process_rhs - A (1) C 224:0 ArrayContains - A (1) C 229:0 ArrayContainedBy - A (1) C 234:0 ArrayExact - A (1) C 239:0 ArrayOverlap - A (1) M 248:4 ArrayLenTransform.as_sql - A (1) M 276:4 IndexTransform.__init__ - A (1) M 281:4 IndexTransform.as_sql - A (1) M 286:4 IndexTransform.output_field - A (1) M 292:4 IndexTransformFactory.__init__ - A (1) M 296:4 IndexTransformFactory.__call__ - A (1) M 302:4 SliceTransform.__init__ - A (1) M 307:4 SliceTransform.as_sql - A (1) M 314:4 SliceTransformFactory.__init__ - A (1) M 318:4 SliceTransformFactory.__call__ - A (1) django/contrib/postgres/fields/hstore.py M 54:4 HStoreField.get_prep_value - B (6) M 30:4 HStoreField.validate - A (4) C 13:0 HStoreField - A (3) M 24:4 HStoreField.get_transform - A (2) M 40:4 HStoreField.to_python - A (2) C 79:0 KeyTransform - A (2) C 91:0 KeyTransformFactory - A (2) M 21:4 HStoreField.db_type - A (1) M 45:4 HStoreField.value_to_string - A (1) M 48:4 HStoreField.formfield - A (1) M 82:4 KeyTransform.__init__ - A (1) M 86:4 KeyTransform.as_sql - A (1) M 93:4 KeyTransformFactory.__init__ - A (1) M 96:4 KeyTransformFactory.__call__ - A (1) C 101:0 KeysTransform - A (1) C 108:0 ValuesTransform - A (1) django/contrib/redirects/models.py C 6:0 Redirect - A (2) M 31:4 Redirect.__str__ - A (1) django/contrib/redirects/apps.py C 5:0 RedirectsConfig - A (1) django/contrib/redirects/admin.py C 6:0 RedirectAdmin - A (1) django/contrib/redirects/middleware.py M 23:4 RedirectFallbackMiddleware.process_response - B (9) C 10:0 RedirectFallbackMiddleware - B (7) M 15:4 RedirectFallbackMiddleware.__init__ - A (2) django/contrib/redirects/migrations/0002_alter_redirect_new_path_help_text.py C 4:0 Migration - A (1) django/contrib/redirects/migrations/0001_initial.py C 4:0 Migration - A (1) django/contrib/sessions/models.py C 10:0 Session - A (2) C 6:0 SessionManager - A (1) M 30:4 Session.get_session_store_class - A (1) django/contrib/sessions/serializers.py C 6:0 PickleSerializer - A (2) M 13:4 PickleSerializer.dumps - A (1) M 16:4 PickleSerializer.loads - A (1) django/contrib/sessions/apps.py C 5:0 SessionsConfig - A (1) django/contrib/sessions/exceptions.py C 4:0 InvalidSessionKey - A (1) C 9:0 SuspiciousSession - A (1) C 14:0 SessionInterrupted - A (1) django/contrib/sessions/base_session.py C 9:0 BaseSessionManager - A (3) M 17:4 BaseSessionManager.save - A (2) C 26:0 AbstractBaseSession - A (2) M 10:4 BaseSessionManager.encode - A (1) M 38:4 AbstractBaseSession.__str__ - A (1) M 42:4 AbstractBaseSession.get_session_store_class - A (1) M 45:4 AbstractBaseSession.get_decoded - A (1) django/contrib/sessions/middleware.py M 22:4 SessionMiddleware.process_response - C (13) C 12:0 SessionMiddleware - B (6) M 13:4 SessionMiddleware.__init__ - A (1) M 18:4 SessionMiddleware.process_request - A (1) django/contrib/sessions/migrations/0001_initial.py C 5:0 Migration - A (1) django/contrib/sessions/backends/signed_cookies.py C 5:0 SessionStore - A (2) M 7:4 SessionStore.load - A (2) M 27:4 SessionStore.create - A (1) M 34:4 SessionStore.save - A (1) M 43:4 SessionStore.exists - A (1) M 51:4 SessionStore.delete - A (1) M 61:4 SessionStore.cycle_key - A (1) M 68:4 SessionStore._get_session_key - A (1) M 80:4 SessionStore.clear_expired - A (1) django/contrib/sessions/backends/db.py M 74:4 SessionStore.save - B (6) M 97:4 SessionStore.delete - A (4) C 12:0 SessionStore - A (3) M 30:4 SessionStore._get_session_from_db - A (3) M 49:4 SessionStore.create - A (3) M 42:4 SessionStore.load - A (2) M 16:4 SessionStore.__init__ - A (1) M 20:4 SessionStore.get_model_class - A (1) M 27:4 SessionStore.model - A (1) M 46:4 SessionStore.exists - A (1) M 62:4 SessionStore.create_model_instance - A (1) M 108:4 SessionStore.clear_expired - A (1) django/contrib/sessions/backends/cached_db.py M 26:4 SessionStore.load - A (4) C 12:0 SessionStore - A (3) M 43:4 SessionStore.exists - A (3) M 50:4 SessionStore.delete - A (3) M 18:4 SessionStore.__init__ - A (1) M 23:4 SessionStore.cache_key - A (1) M 46:4 SessionStore.save - A (1) M 58:4 SessionStore.flush - A (1) django/contrib/sessions/backends/cache.py M 54:4 SessionStore.save - B (6) C 10:0 SessionStore - A (3) M 24:4 SessionStore.load - A (3) M 36:4 SessionStore.create - A (3) M 72:4 SessionStore.delete - A (3) M 69:4 SessionStore.exists - A (2) M 16:4 SessionStore.__init__ - A (1) M 21:4 SessionStore.cache_key - A (1) M 80:4 SessionStore.clear_expired - A (1) django/contrib/sessions/backends/file.py M 111:4 SessionStore.save - B (9) M 75:4 SessionStore.load - B (6) C 16:0 SessionStore - A (4) M 26:4 SessionStore._get_storage_path - A (4) M 175:4 SessionStore.delete - A (4) M 41:4 SessionStore._key_to_file - A (3) M 101:4 SessionStore.create - A (3) M 189:4 SessionStore.clear_expired - A (3) M 57:4 SessionStore._last_modification - A (2) M 67:4 SessionStore._expiry_date - A (2) M 20:4 SessionStore.__init__ - A (1) M 172:4 SessionStore.exists - A (1) M 185:4 SessionStore.clean - A (1) django/contrib/sessions/backends/base.py M 193:4 SessionBase.get_expiry_age - A (5) M 218:4 SessionBase.get_expiry_date - A (5) M 173:4 SessionBase._get_session - A (4) M 239:4 SessionBase.set_expiry - A (4) M 67:4 SessionBase.pop - A (3) M 96:4 SessionBase.decode - A (3) M 132:4 SessionBase.is_empty - A (3) M 139:4 SessionBase._get_new_session_key - A (3) C 31:0 SessionBase - A (2) M 72:4 SessionBase.setdefault - A (2) M 146:4 SessionBase._get_or_create_session_key - A (2) M 151:4 SessionBase._validate_session_key - A (2) M 161:4 SessionBase._set_session_key - A (2) M 265:4 SessionBase.get_expire_at_browser_close - A (2) M 285:4 SessionBase.cycle_key - A (2) C 16:0 CreateError - A (1) C 24:0 UpdateError - A (1) M 40:4 SessionBase.__init__ - A (1) M 46:4 SessionBase.__contains__ - A (1) M 49:4 SessionBase.__getitem__ - A (1) M 52:4 SessionBase.__setitem__ - A (1) M 56:4 SessionBase.__delitem__ - A (1) M 61:4 SessionBase.key_salt - A (1) M 64:4 SessionBase.get - A (1) M 80:4 SessionBase.set_test_cookie - A (1) M 83:4 SessionBase.test_cookie_worked - A (1) M 86:4 SessionBase.delete_test_cookie - A (1) M 89:4 SessionBase.encode - A (1) M 108:4 SessionBase.update - A (1) M 112:4 SessionBase.has_key - A (1) M 115:4 SessionBase.keys - A (1) M 118:4 SessionBase.values - A (1) M 121:4 SessionBase.items - A (1) M 124:4 SessionBase.clear - A (1) M 158:4 SessionBase._get_session_key - A (1) M 190:4 SessionBase.get_session_cookie_age - A (1) M 276:4 SessionBase.flush - A (1) M 298:4 SessionBase.exists - A (1) M 304:4 SessionBase.create - A (1) M 312:4 SessionBase.save - A (1) M 320:4 SessionBase.delete - A (1) M 327:4 SessionBase.load - A (1) M 334:4 SessionBase.clear_expired - A (1) django/contrib/sessions/management/commands/clearsessions.py C 7:0 Command - A (3) M 13:4 Command.handle - A (2) django/contrib/sitemaps/__init__.py M 148:4 Sitemap._urls - C (13) F 30:0 _get_sitemap_full_url - B (7) M 127:4 Sitemap.get_domain - A (5) C 54:0 Sitemap - A (4) M 75:4 Sitemap._get - A (4) M 93:4 Sitemap._items - A (4) M 203:4 GenericSitemap.__init__ - A (4) M 88:4 Sitemap._languages - A (3) M 105:4 Sitemap._location - A (3) M 123:4 Sitemap.get_protocol - A (3) C 199:0 GenericSitemap - A (3) M 214:4 GenericSitemap.lastmod - A (2) F 18:0 ping_google - A (1) C 14:0 SitemapNotFound - A (1) M 114:4 Sitemap.paginator - A (1) M 117:4 Sitemap.items - A (1) M 120:4 Sitemap.location - A (1) M 143:4 Sitemap.get_urls - A (1) M 210:4 GenericSitemap.items - A (1) django/contrib/sitemaps/apps.py C 5:0 SiteMapsConfig - A (1) django/contrib/sitemaps/views.py F 49:0 sitemap - C (13) F 23:0 index - A (5) F 13:0 x_robots_tag - A (1) django/contrib/sitemaps/management/commands/ping_google.py C 5:0 Command - A (2) M 8:4 Command.add_arguments - A (1) M 12:4 Command.handle - A (1) django/contrib/humanize/apps.py C 5:0 HumanizeConfig - A (1) django/contrib/humanize/templatetags/humanize.py C 177:0 NaturalTimeFormatter - C (13) M 223:4 NaturalTimeFormatter.string_for - C (12) F 60:0 intcomma - B (6) F 98:0 intword - A (5) F 143:0 naturalday - A (5) F 19:0 ordinal - A (3) F 125:0 apnumber - A (3) F 169:0 naturaltime - A (1) django/contrib/contenttypes/models.py M 62:4 ContentTypeManager.get_for_models - B (9) C 8:0 ContentTypeManager - A (3) M 34:4 ContentTypeManager.get_for_model - A (3) M 17:4 ContentTypeManager.get_by_natural_key - A (2) M 25:4 ContentTypeManager._get_opts - A (2) M 104:4 ContentTypeManager.get_for_id - A (2) C 133:0 ContentType - A (2) M 148:4 ContentType.name - A (2) M 155:4 ContentType.app_labeled_name - A (2) M 161:4 ContentType.model_class - A (2) M 11:4 ContentTypeManager.__init__ - A (1) M 30:4 ContentTypeManager._get_from_cache - A (1) M 118:4 ContentTypeManager.clear_cache - A (1) M 124:4 ContentTypeManager._add_to_cache - A (1) M 144:4 ContentType.__str__ - A (1) M 168:4 ContentType.get_object_for_this_type - A (1) M 177:4 ContentType.get_all_objects_for_this_type - A (1) M 183:4 ContentType.natural_key - A (1) django/contrib/contenttypes/fields.py M 218:4 GenericForeignKey.__get__ - B (7) M 172:4 GenericForeignKey.get_prefetch_queryset - B (6) M 109:4 GenericForeignKey._check_content_type_field - A (5) M 335:4 GenericRelation._check_generic_foreign_key_existence - A (4) C 20:0 GenericForeignKey - A (3) M 94:4 GenericForeignKey._check_object_id_field - A (3) M 162:4 GenericForeignKey.get_content_type - A (3) C 259:0 GenericRel - A (3) M 323:4 GenericRelation._is_matching_generic_foreign_key - A (3) M 358:4 GenericRelation._get_path_info_with_parent - A (3) M 432:4 GenericRelation.contribute_to_class - A (3) M 82:4 GenericForeignKey._check_field_name - A (2) M 247:4 GenericForeignKey.__set__ - A (2) M 264:4 GenericRel.__init__ - A (2) C 272:0 GenericRelation - A (2) M 398:4 GenericRelation.get_path_info - A (2) M 428:4 GenericRelation.value_to_string - A (2) M 476:4 GenericRelation.bulk_related_objects - A (2) C 487:0 ReverseGenericManyToOneDescriptor - A (2) F 508:0 create_generic_related_manager - A (1) M 43:4 GenericForeignKey.__init__ - A (1) M 51:4 GenericForeignKey.contribute_to_class - A (1) M 57:4 GenericForeignKey.get_filter_kwargs_for_object - A (1) M 64:4 GenericForeignKey.get_forward_related_filter - A (1) M 71:4 GenericForeignKey.__str__ - A (1) M 75:4 GenericForeignKey.check - A (1) M 159:4 GenericForeignKey.get_cache_name - A (1) M 290:4 GenericRelation.__init__ - A (1) M 317:4 GenericRelation.check - A (1) M 354:4 GenericRelation.resolve_related_fields - A (1) M 415:4 GenericRelation.get_reverse_path_info - A (1) M 455:4 GenericRelation.set_attributes_from_rel - A (1) M 458:4 GenericRelation.get_internal_type - A (1) M 461:4 GenericRelation.get_content_type - A (1) M 468:4 GenericRelation.get_extra_restriction - A (1) M 501:4 ReverseGenericManyToOneDescriptor.related_manager_cls - A (1) django/contrib/contenttypes/checks.py F 7:0 check_generic_foreign_keys - B (7) F 24:0 check_model_name_lengths - A (5) django/contrib/contenttypes/apps.py C 14:0 ContentTypesConfig - A (2) M 19:4 ContentTypesConfig.ready - A (1) django/contrib/contenttypes/forms.py F 52:0 generic_inlineformset_factory - A (4) M 12:4 BaseGenericInlineFormSet.__init__ - A (4) C 7:0 BaseGenericInlineFormSet - A (3) M 33:4 BaseGenericInlineFormSet.initial_form_count - A (2) M 39:4 BaseGenericInlineFormSet.get_default_prefix - A (1) M 46:4 BaseGenericInlineFormSet.save_new - A (1) django/contrib/contenttypes/admin.py C 81:0 GenericInlineModelAdmin - C (11) M 88:4 GenericInlineModelAdmin.get_formset - B (10) M 20:4 GenericInlineModelAdminChecks._check_relation - B (9) C 15:0 GenericInlineModelAdminChecks - B (6) M 16:4 GenericInlineModelAdminChecks._check_exclude_of_parent_model - A (1) C 122:0 GenericStackedInline - A (1) C 126:0 GenericTabularInline - A (1) django/contrib/contenttypes/views.py F 9:0 shortcut - C (19) django/contrib/contenttypes/migrations/0002_remove_content_type_name.py F 4:0 add_legacy_name - A (3) C 14:0 Migration - A (1) django/contrib/contenttypes/migrations/0001_initial.py C 5:0 Migration - A (1) django/contrib/contenttypes/management/__init__.py F 46:0 inject_rename_contenttypes_operations - C (13) F 105:0 create_contenttypes - B (8) M 14:4 RenameContentType._rename - B (7) F 88:0 get_contenttypes_and_models - A (4) C 7:0 RenameContentType - A (3) M 8:4 RenameContentType.__init__ - A (1) M 39:4 RenameContentType.rename_forward - A (1) M 42:4 RenameContentType.rename_backward - A (1) django/contrib/contenttypes/management/commands/remove_stale_contenttypes.py M 29:4 Command.handle - C (16) C 10:0 Command - B (10) C 89:0 NoFastDeleteCollector - A (2) M 12:4 Command.add_arguments - A (1) M 90:4 NoFastDeleteCollector.can_fast_delete - A (1) django/contrib/gis/measure.py M 175:4 MeasureBase.default_units - B (7) C 319:0 Area - B (6) C 223:0 Distance - A (5) M 206:4 MeasureBase.unit_attname - A (4) C 52:0 MeasureBase - A (3) M 58:4 MeasureBase.__init__ - A (3) M 154:4 MeasureBase.__truediv__ - A (3) M 302:4 Distance.__mul__ - A (3) F 47:0 pretty_name - A (2) M 72:4 MeasureBase.__getattr__ - A (2) M 86:4 MeasureBase.__eq__ - A (2) M 95:4 MeasureBase.__lt__ - A (2) M 103:4 MeasureBase.__add__ - A (2) M 112:4 MeasureBase.__iadd__ - A (2) M 119:4 MeasureBase.__sub__ - A (2) M 128:4 MeasureBase.__isub__ - A (2) M 135:4 MeasureBase.__mul__ - A (2) M 144:4 MeasureBase.__imul__ - A (2) M 165:4 MeasureBase.__itruediv__ - A (2) M 326:4 Area.__truediv__ - A (2) M 64:4 MeasureBase._get_standard - A (1) M 67:4 MeasureBase._set_standard - A (1) M 78:4 MeasureBase.__repr__ - A (1) M 81:4 MeasureBase.__str__ - A (1) M 92:4 MeasureBase.__hash__ - A (1) M 151:4 MeasureBase.__rmul__ - A (1) M 172:4 MeasureBase.__bool__ - A (1) django/contrib/gis/shortcuts.py F 15:0 compress_kml - A (1) F 24:0 render_to_kml - A (1) F 32:0 render_to_kmz - A (1) django/contrib/gis/feeds.py M 32:4 GeoFeedMixin.add_georss_element - C (13) C 5:0 GeoFeedMixin - B (7) M 11:4 GeoFeedMixin.georss_coords - A (2) M 19:4 GeoFeedMixin.add_georss_point - A (2) C 81:0 GeoRSSFeed - A (2) C 96:0 GeoAtom1Feed - A (2) C 111:0 W3CGeoFeed - A (2) C 127:0 Feed - A (2) M 82:4 GeoRSSFeed.rss_attributes - A (1) M 87:4 GeoRSSFeed.add_item_elements - A (1) M 91:4 GeoRSSFeed.add_root_elements - A (1) M 97:4 GeoAtom1Feed.root_attributes - A (1) M 102:4 GeoAtom1Feed.add_item_elements - A (1) M 106:4 GeoAtom1Feed.add_root_elements - A (1) M 112:4 W3CGeoFeed.rss_attributes - A (1) M 117:4 W3CGeoFeed.add_item_elements - A (1) M 121:4 W3CGeoFeed.add_root_elements - A (1) M 136:4 Feed.feed_extra_kwargs - A (1) M 139:4 Feed.item_extra_kwargs - A (1) django/contrib/gis/apps.py C 6:0 GISConfig - A (2) M 11:4 GISConfig.ready - A (1) django/contrib/gis/ptr.py C 4:0 CPointerBase - A (4) M 30:4 CPointerBase.__del__ - A (4) M 23:4 CPointerBase.ptr - A (3) M 15:4 CPointerBase.ptr - A (2) django/contrib/gis/views.py F 5:0 feed - B (6) django/contrib/gis/geos/mutable_list.py M 80:4 ListMixin.__delitem__ - A (5) M 153:4 ListMixin.__lt__ - A (5) M 218:4 ListMixin._rebuild - A (5) M 141:4 ListMixin.__eq__ - A (4) M 237:4 ListMixin._check_allowed - A (4) C 15:0 ListMixin - A (3) M 62:4 ListMixin.__init__ - A (3) M 72:4 ListMixin.__getitem__ - A (3) M 131:4 ListMixin.__imul__ - A (3) M 169:4 ListMixin.count - A (3) M 177:4 ListMixin.index - A (3) M 229:4 ListMixin._checkindex - A (3) M 242:4 ListMixin._set_slice - A (3) M 283:4 ListMixin._assign_extended_slice - A (3) M 100:4 ListMixin.__setitem__ - A (2) M 193:4 ListMixin.insert - A (2) M 261:4 ListMixin._assign_extended_slice_rebuild - A (2) M 110:4 ListMixin.__add__ - A (1) M 114:4 ListMixin.__radd__ - A (1) M 118:4 ListMixin.__iadd__ - A (1) M 123:4 ListMixin.__mul__ - A (1) M 127:4 ListMixin.__rmul__ - A (1) M 185:4 ListMixin.append - A (1) M 189:4 ListMixin.extend - A (1) M 199:4 ListMixin.pop - A (1) M 205:4 ListMixin.remove - A (1) M 209:4 ListMixin.reverse - A (1) M 213:4 ListMixin.sort - A (1) M 226:4 ListMixin._set_single_rebuild - A (1) M 295:4 ListMixin._assign_simple_slice - A (1) django/contrib/gis/geos/error.py C 1:0 GEOSException - A (1) django/contrib/gis/geos/prepared.py C 5:0 PreparedGeometry - A (2) M 14:4 PreparedGeometry.__init__ - A (2) M 24:4 PreparedGeometry.contains - A (1) M 27:4 PreparedGeometry.contains_properly - A (1) M 30:4 PreparedGeometry.covers - A (1) M 33:4 PreparedGeometry.intersects - A (1) M 36:4 PreparedGeometry.crosses - A (1) M 39:4 PreparedGeometry.disjoint - A (1) M 42:4 PreparedGeometry.overlaps - A (1) M 45:4 PreparedGeometry.touches - A (1) M 48:4 PreparedGeometry.within - A (1) django/contrib/gis/geos/polygon.py M 12:4 Polygon.__init__ - B (6) M 69:4 Polygon._create_polygon - B (6) C 9:0 Polygon - A (3) M 59:4 Polygon.from_bbox - A (3) M 101:4 Polygon._construct_ring - A (3) M 49:4 Polygon.__iter__ - A (2) M 95:4 Polygon._clone - A (2) M 112:4 Polygon._set_list - A (2) M 122:4 Polygon._get_single_internal - A (2) M 166:4 Polygon.tuple - A (2) M 172:4 Polygon.kml - A (2) M 54:4 Polygon.__len__ - A (1) M 140:4 Polygon._get_single_external - A (1) M 148:4 Polygon.num_interior_rings - A (1) M 153:4 Polygon._get_ext_ring - A (1) M 157:4 Polygon._set_ext_ring - A (1) django/contrib/gis/geos/io.py C 15:0 WKBReader - A (2) C 21:0 WKTReader - A (2) M 16:4 WKBReader.read - A (1) M 22:4 WKTReader.read - A (1) django/contrib/gis/geos/linestring.py M 14:4 LineString.__init__ - C (17) M 106:4 LineString._set_list - A (4) C 9:0 LineString - A (3) M 141:4 LineString._listarr - A (3) C 177:0 LinearRing - A (3) M 92:4 LineString.__iter__ - A (2) M 130:4 LineString._checkdim - A (2) M 168:4 LineString.z - A (2) M 182:4 LinearRing.is_counterclockwise - A (2) M 97:4 LineString.__len__ - A (1) M 101:4 LineString._get_single_external - A (1) M 127:4 LineString._set_single - A (1) M 136:4 LineString.tuple - A (1) M 153:4 LineString.array - A (1) M 158:4 LineString.x - A (1) M 163:4 LineString.y - A (1) django/contrib/gis/geos/factory.py F 4:0 fromfile - B (7) F 31:0 fromstr - A (1) django/contrib/gis/geos/coordseq.py M 45:4 GEOSCoordSeq.__setitem__ - B (7) M 199:4 GEOSCoordSeq.is_counterclockwise - A (4) M 72:4 GEOSCoordSeq._checkdim - A (3) M 96:4 GEOSCoordSeq._point_getter - A (3) M 178:4 GEOSCoordSeq.kml - A (3) M 190:4 GEOSCoordSeq.tuple - A (3) C 15:0 GEOSCoordSeq - A (2) M 20:4 GEOSCoordSeq.__init__ - A (2) M 27:4 GEOSCoordSeq.__iter__ - A (2) M 67:4 GEOSCoordSeq._checkindex - A (2) M 32:4 GEOSCoordSeq.__len__ - A (1) M 36:4 GEOSCoordSeq.__str__ - A (1) M 40:4 GEOSCoordSeq.__getitem__ - A (1) M 77:4 GEOSCoordSeq._get_x - A (1) M 80:4 GEOSCoordSeq._get_y - A (1) M 83:4 GEOSCoordSeq._get_z - A (1) M 86:4 GEOSCoordSeq._set_x - A (1) M 89:4 GEOSCoordSeq._set_y - A (1) M 92:4 GEOSCoordSeq._set_z - A (1) M 99:4 GEOSCoordSeq._get_point_2d - A (1) M 102:4 GEOSCoordSeq._get_point_3d - A (1) M 105:4 GEOSCoordSeq._set_point_2d - A (1) M 110:4 GEOSCoordSeq._set_point_3d - A (1) M 117:4 GEOSCoordSeq.getOrdinate - A (1) M 123:4 GEOSCoordSeq.setOrdinate - A (1) M 129:4 GEOSCoordSeq.getX - A (1) M 133:4 GEOSCoordSeq.setX - A (1) M 137:4 GEOSCoordSeq.getY - A (1) M 141:4 GEOSCoordSeq.setY - A (1) M 145:4 GEOSCoordSeq.getZ - A (1) M 149:4 GEOSCoordSeq.setZ - A (1) M 155:4 GEOSCoordSeq.size - A (1) M 160:4 GEOSCoordSeq.dims - A (1) M 165:4 GEOSCoordSeq.hasz - A (1) M 173:4 GEOSCoordSeq.clone - A (1) django/contrib/gis/geos/point.py M 14:4 Point.__init__ - B (6) M 57:4 Point._create_point - A (5) M 106:4 Point._get_single_external - A (4) C 9:0 Point - A (3) M 76:4 Point._set_list - A (3) M 97:4 Point.__len__ - A (3) M 43:4 Point._to_pickle_wkb - A (2) M 46:4 Point._from_pickle_wkb - A (2) M 49:4 Point._ogr_ptr - A (2) M 92:4 Point.__iter__ - A (2) M 137:4 Point.z - A (2) M 142:4 Point.z - A (2) M 53:4 Point._create_empty - A (1) M 89:4 Point._set_single - A (1) M 117:4 Point.x - A (1) M 122:4 Point.x - A (1) M 127:4 Point.y - A (1) M 132:4 Point.y - A (1) M 150:4 Point.tuple - A (1) M 155:4 Point.tuple - A (1) django/contrib/gis/geos/collections.py M 18:4 GeometryCollection.__init__ - A (3) C 15:0 GeometryCollection - A (2) M 39:4 GeometryCollection.__iter__ - A (2) M 49:4 GeometryCollection._create_collection - A (2) M 66:4 GeometryCollection._set_list - A (2) M 79:4 GeometryCollection.kml - A (2) M 84:4 GeometryCollection.tuple - A (2) M 44:4 GeometryCollection.__len__ - A (1) M 58:4 GeometryCollection._get_single_internal - A (1) M 61:4 GeometryCollection._get_single_external - A (1) C 91:0 MultiPoint - A (1) C 96:0 MultiLineString - A (1) C 101:0 MultiPolygon - A (1) django/contrib/gis/geos/geometry.py C 679:0 GEOSGeometry - C (20) M 682:4 GEOSGeometry.__init__ - C (19) M 447:4 GEOSGeometryBase.transform - B (8) M 142:4 GEOSGeometryBase.__eq__ - A (5) M 32:4 GEOSGeometryBase.__init__ - A (4) M 117:4 GEOSGeometryBase.from_ewkt - A (4) M 311:4 GEOSGeometryBase.relate_pattern - A (3) M 433:4 GEOSGeometryBase.srs - A (3) C 24:0 GEOSGeometryBase - A (2) M 61:4 GEOSGeometryBase._post_init - A (2) M 102:4 GEOSGeometryBase.__setstate__ - A (2) M 182:4 GEOSGeometryBase.coord_seq - A (2) M 336:4 GEOSGeometryBase.srid - A (2) M 345:4 GEOSGeometryBase.srid - A (2) M 351:4 GEOSGeometryBase.ewkt - A (2) M 359:4 GEOSGeometryBase.wkt - A (2) M 364:4 GEOSGeometryBase.hex - A (2) M 375:4 GEOSGeometryBase.hexewkb - A (2) M 392:4 GEOSGeometryBase.wkb - A (2) M 401:4 GEOSGeometryBase.ewkb - A (2) M 563:4 GEOSGeometryBase.simplify - A (2) M 602:4 GEOSGeometryBase.distance - A (2) M 613:4 GEOSGeometryBase.extent - A (2) C 641:0 LinearGeometryMixin - A (2) M 651:4 LinearGeometryMixin.project - A (2) M 657:4 LinearGeometryMixin.project_normalized - A (2) M 67:4 GEOSGeometryBase.__copy__ - A (1) M 74:4 GEOSGeometryBase.__deepcopy__ - A (1) M 82:4 GEOSGeometryBase.__str__ - A (1) M 86:4 GEOSGeometryBase.__repr__ - A (1) M 91:4 GEOSGeometryBase._to_pickle_wkb - A (1) M 94:4 GEOSGeometryBase._from_pickle_wkb - A (1) M 97:4 GEOSGeometryBase.__getstate__ - A (1) M 113:4 GEOSGeometryBase._from_wkb - A (1) M 134:4 GEOSGeometryBase._from_wkt - A (1) M 138:4 GEOSGeometryBase.from_gml - A (1) M 154:4 GEOSGeometryBase.__hash__ - A (1) M 161:4 GEOSGeometryBase.__or__ - A (1) M 166:4 GEOSGeometryBase.__and__ - A (1) M 171:4 GEOSGeometryBase.__sub__ - A (1) M 176:4 GEOSGeometryBase.__xor__ - A (1) M 189:4 GEOSGeometryBase.geom_type - A (1) M 194:4 GEOSGeometryBase.geom_typeid - A (1) M 199:4 GEOSGeometryBase.num_geom - A (1) M 204:4 GEOSGeometryBase.num_coords - A (1) M 209:4 GEOSGeometryBase.num_points - A (1) M 214:4 GEOSGeometryBase.dims - A (1) M 218:4 GEOSGeometryBase.normalize - A (1) M 224:4 GEOSGeometryBase.empty - A (1) M 232:4 GEOSGeometryBase.hasz - A (1) M 237:4 GEOSGeometryBase.ring - A (1) M 242:4 GEOSGeometryBase.simple - A (1) M 247:4 GEOSGeometryBase.valid - A (1) M 252:4 GEOSGeometryBase.valid_reason - A (1) M 259:4 GEOSGeometryBase.contains - A (1) M 263:4 GEOSGeometryBase.covers - A (1) M 271:4 GEOSGeometryBase.crosses - A (1) M 279:4 GEOSGeometryBase.disjoint - A (1) M 286:4 GEOSGeometryBase.equals - A (1) M 293:4 GEOSGeometryBase.equals_exact - A (1) M 300:4 GEOSGeometryBase.intersects - A (1) M 304:4 GEOSGeometryBase.overlaps - A (1) M 320:4 GEOSGeometryBase.touches - A (1) M 327:4 GEOSGeometryBase.within - A (1) M 384:4 GEOSGeometryBase.json - A (1) M 410:4 GEOSGeometryBase.kml - A (1) M 416:4 GEOSGeometryBase.prepared - A (1) M 424:4 GEOSGeometryBase._ogr_ptr - A (1) M 428:4 GEOSGeometryBase.ogr - A (1) M 443:4 GEOSGeometryBase.crs - A (1) M 490:4 GEOSGeometryBase._topology - A (1) M 495:4 GEOSGeometryBase.boundary - A (1) M 499:4 GEOSGeometryBase.buffer - A (1) M 509:4 GEOSGeometryBase.buffer_with_style - A (1) M 522:4 GEOSGeometryBase.centroid - A (1) M 531:4 GEOSGeometryBase.convex_hull - A (1) M 538:4 GEOSGeometryBase.difference - A (1) M 546:4 GEOSGeometryBase.envelope - A (1) M 550:4 GEOSGeometryBase.intersection - A (1) M 555:4 GEOSGeometryBase.point_on_surface - A (1) M 559:4 GEOSGeometryBase.relate - A (1) M 580:4 GEOSGeometryBase.sym_difference - A (1) M 588:4 GEOSGeometryBase.unary_union - A (1) M 592:4 GEOSGeometryBase.union - A (1) M 598:4 GEOSGeometryBase.area - A (1) M 629:4 GEOSGeometryBase.length - A (1) M 636:4 GEOSGeometryBase.clone - A (1) M 645:4 LinearGeometryMixin.interpolate - A (1) M 648:4 LinearGeometryMixin.interpolate_normalized - A (1) M 664:4 LinearGeometryMixin.merged - A (1) M 671:4 LinearGeometryMixin.closed - A (1) django/contrib/gis/geos/libgeos.py F 21:0 load_geos - B (9) C 134:0 GEOSFuncFactory - A (4) M 142:4 GEOSFuncFactory.__init__ - A (4) M 155:4 GEOSFuncFactory.func - A (3) F 79:0 notice_h - A (2) F 93:0 error_h - A (2) F 165:0 geos_version - A (1) F 170:0 geos_version_tuple - A (1) C 108:0 GEOSGeom_t - A (1) C 112:0 GEOSPrepGeom_t - A (1) C 116:0 GEOSCoordSeq_t - A (1) C 120:0 GEOSContextHandle_t - A (1) M 151:4 GEOSFuncFactory.__call__ - A (1) django/contrib/gis/geos/base.py C 5:0 GEOSBase - A (1) django/contrib/gis/geos/prototypes/misc.py C 14:0 DblFromGeom - A (1) django/contrib/gis/geos/prototypes/predicates.py C 12:0 UnaryPredicate - A (1) C 19:0 BinaryPredicate - A (1) django/contrib/gis/geos/prototypes/prepared.py C 14:0 PreparedPredicate - A (1) django/contrib/gis/geos/prototypes/geom.py C 19:0 geos_char_p - A (1) C 24:0 GeomOutput - A (1) C 30:0 IntFromGeom - A (1) C 37:0 StringFromGeom - A (1) django/contrib/gis/geos/prototypes/io.py M 204:4 WKTWriter.precision - B (6) C 142:0 _WKBReader - A (4) M 222:4 WKBWriter._handle_empty_point - A (4) M 234:4 WKBWriter.write - A (4) M 245:4 WKBWriter.write_hex - A (4) C 131:0 _WKTReader - A (3) M 147:4 _WKBReader.read - A (3) C 159:0 WKTWriter - A (3) M 167:4 WKTWriter.__init__ - A (3) C 212:0 WKBWriter - A (3) F 305:0 wkt_r - A (2) F 310:0 wkt_w - A (2) F 320:0 wkb_r - A (2) F 325:0 wkb_w - A (2) F 333:0 ewkb_w - A (2) C 116:0 IOBase - A (2) M 136:4 _WKTReader.read - A (2) M 184:4 WKTWriter.outdim - A (2) M 194:4 WKTWriter.trim - A (2) M 260:4 WKBWriter._set_byteorder - A (2) M 273:4 WKBWriter.outdim - A (2) C 16:0 WKTReader_st - A (1) C 20:0 WKTWriter_st - A (1) C 24:0 WKBReader_st - A (1) C 28:0 WKBWriter_st - A (1) C 67:0 WKBReadFunc - A (1) C 87:0 WKBWriteFunc - A (1) C 98:0 WKBWriterGet - A (1) C 103:0 WKBWriterSet - A (1) M 118:4 IOBase.__init__ - A (1) M 175:4 WKTWriter.write - A (1) M 180:4 WKTWriter.outdim - A (1) M 190:4 WKTWriter.trim - A (1) M 200:4 WKTWriter.precision - A (1) M 218:4 WKBWriter.__init__ - A (1) M 257:4 WKBWriter._get_byteorder - A (1) M 269:4 WKBWriter.outdim - A (1) M 280:4 WKBWriter.srid - A (1) M 284:4 WKBWriter.srid - A (1) C 292:0 ThreadLocalIO - A (1) django/contrib/gis/geos/prototypes/coordseq.py C 33:0 CsOperation - A (4) M 37:4 CsOperation.__init__ - A (3) C 55:0 CsOutput - A (3) F 10:0 check_cs_op - A (2) M 59:4 CsOutput.errcheck - A (2) F 18:0 check_cs_get - A (1) C 26:0 CsInt - A (1) django/contrib/gis/geos/prototypes/topology.py C 14:0 Topology - A (1) django/contrib/gis/geos/prototypes/threadsafe.py C 9:0 GEOSContextHandle - A (2) C 29:0 GEOSFunc - A (2) M 42:4 GEOSFunc.__call__ - A (2) M 14:4 GEOSContextHandle.__init__ - A (1) C 22:0 GEOSContext - A (1) M 34:4 GEOSFunc.__init__ - A (1) M 49:4 GEOSFunc.__str__ - A (1) M 53:4 GEOSFunc._get_argtypes - A (1) M 56:4 GEOSFunc._set_argtypes - A (1) M 62:4 GEOSFunc._get_restype - A (1) M 65:4 GEOSFunc._set_restype - A (1) M 71:4 GEOSFunc._get_errcheck - A (1) M 74:4 GEOSFunc._set_errcheck - A (1) django/contrib/gis/geos/prototypes/errcheck.py F 44:0 check_predicate - A (3) F 20:0 check_dbl - A (2) F 29:0 check_geom - A (2) F 36:0 check_minus_one - A (2) F 54:0 check_sized_string - A (2) F 71:0 check_string - A (2) F 15:0 last_arg_byref - A (1) django/contrib/gis/forms/fields.py M 34:4 GeometryField.to_python - B (10) M 62:4 GeometryField.clean - B (8) C 10:0 GeometryField - B (7) M 87:4 GeometryField.has_changed - A (4) M 27:4 GeometryField.__init__ - A (2) C 108:0 GeometryCollectionField - A (1) C 112:0 PointField - A (1) C 116:0 MultiPointField - A (1) C 120:0 LineStringField - A (1) C 124:0 MultiLineStringField - A (1) C 128:0 PolygonField - A (1) C 132:0 MultiPolygonField - A (1) django/contrib/gis/forms/widgets.py M 44:4 BaseGeometryWidget.get_context - B (9) C 13:0 BaseGeometryWidget - A (5) C 77:0 OpenLayersWidget - A (4) M 96:4 OpenLayersWidget.deserialize - A (4) C 104:0 OSMWidget - A (4) M 27:4 BaseGeometryWidget.__init__ - A (3) M 113:4 OSMWidget.__init__ - A (3) M 34:4 BaseGeometryWidget.serialize - A (2) M 37:4 BaseGeometryWidget.deserialize - A (2) M 93:4 OpenLayersWidget.serialize - A (2) django/contrib/gis/gdal/field.py M 46:4 Field.as_int - A (4) M 60:4 Field.as_datetime - A (4) C 152:0 OFTDate - A (3) C 163:0 OFTDateTime - A (3) C 178:0 OFTTime - A (3) C 14:0 Field - A (2) M 19:4 Field.__init__ - A (2) M 42:4 Field.as_double - A (2) M 53:4 Field.as_string - A (2) C 113:0 OFTInteger - A (2) C 131:0 OFTReal - A (2) M 154:4 OFTDate.value - A (2) M 165:4 OFTDateTime.value - A (2) M 180:4 OFTTime.value - A (2) M 37:4 Field.__str__ - A (1) M 75:4 Field.is_set - A (1) M 80:4 Field.name - A (1) M 86:4 Field.precision - A (1) M 91:4 Field.type - A (1) M 96:4 Field.type_name - A (1) M 101:4 Field.value - A (1) M 107:4 Field.width - A (1) M 117:4 OFTInteger.value - A (1) M 122:4 OFTInteger.type - A (1) M 133:4 OFTReal.value - A (1) C 139:0 OFTString - A (1) C 143:0 OFTWideString - A (1) C 147:0 OFTBinary - A (1) C 189:0 OFTInteger64 - A (1) C 194:0 OFTIntegerList - A (1) C 198:0 OFTRealList - A (1) C 202:0 OFTStringList - A (1) C 206:0 OFTWideStringList - A (1) C 210:0 OFTInteger64List - A (1) django/contrib/gis/gdal/srs.py M 52:4 SpatialReference.__init__ - C (20) M 233:4 SpatialReference.units - A (5) M 188:4 SpatialReference.name - A (4) M 146:4 SpatialReference.attr_value - A (3) C 341:0 CoordTransform - A (3) M 345:4 CoordTransform.__init__ - A (3) C 44:0 SpatialReference - A (2) M 113:4 SpatialReference.__getitem__ - A (2) M 200:4 SpatialReference.srid - A (2) C 39:0 AxisOrder - A (1) M 141:4 SpatialReference.__str__ - A (1) M 155:4 SpatialReference.auth_name - A (1) M 159:4 SpatialReference.auth_code - A (1) M 163:4 SpatialReference.clone - A (1) M 167:4 SpatialReference.from_esri - A (1) M 171:4 SpatialReference.identify_epsg - A (1) M 178:4 SpatialReference.to_esri - A (1) M 182:4 SpatialReference.validate - A (1) M 209:4 SpatialReference.linear_name - A (1) M 215:4 SpatialReference.linear_units - A (1) M 221:4 SpatialReference.angular_name - A (1) M 227:4 SpatialReference.angular_units - A (1) M 249:4 SpatialReference.ellipsoid - A (1) M 257:4 SpatialReference.semi_major - A (1) M 262:4 SpatialReference.semi_minor - A (1) M 267:4 SpatialReference.inverse_flattening - A (1) M 273:4 SpatialReference.geographic - A (1) M 281:4 SpatialReference.local - A (1) M 286:4 SpatialReference.projected - A (1) M 294:4 SpatialReference.import_epsg - A (1) M 298:4 SpatialReference.import_proj - A (1) M 302:4 SpatialReference.import_user_input - A (1) M 306:4 SpatialReference.import_wkt - A (1) M 310:4 SpatialReference.import_xml - A (1) M 316:4 SpatialReference.wkt - A (1) M 321:4 SpatialReference.pretty_wkt - A (1) M 326:4 SpatialReference.proj - A (1) M 331:4 SpatialReference.proj4 - A (1) M 336:4 SpatialReference.xml - A (1) M 353:4 CoordTransform.__str__ - A (1) django/contrib/gis/gdal/error.py F 49:0 check_err - A (4) C 9:0 GDALException - A (1) C 13:0 SRSException - A (1) django/contrib/gis/gdal/geomtype.py M 33:4 OGRGeomType.__init__ - B (7) C 4:0 OGRGeomType - A (4) M 58:4 OGRGeomType.__eq__ - A (4) M 78:4 OGRGeomType.django - A (4) M 89:4 OGRGeomType.to_multi - A (2) M 54:4 OGRGeomType.__str__ - A (1) M 73:4 OGRGeomType.name - A (1) django/contrib/gis/gdal/feature.py M 29:4 Feature.__getitem__ - A (3) C 13:0 Feature - A (2) M 20:4 Feature.__init__ - A (2) M 78:4 Feature.fields - A (2) M 110:4 Feature.index - A (2) M 44:4 Feature.__len__ - A (1) M 48:4 Feature.__str__ - A (1) M 52:4 Feature.__eq__ - A (1) M 58:4 Feature.encoding - A (1) M 62:4 Feature.fid - A (1) M 67:4 Feature.layer_name - A (1) M 73:4 Feature.num_fields - A (1) M 89:4 Feature.geom - A (1) M 96:4 Feature.geom_type - A (1) M 101:4 Feature.get - A (1) django/contrib/gis/gdal/datasource.py M 55:4 DataSource.__init__ - B (7) M 88:4 DataSource.__getitem__ - A (5) C 51:0 DataSource - A (3) M 104:4 DataSource.__len__ - A (1) M 108:4 DataSource.__str__ - A (1) M 113:4 DataSource.layer_count - A (1) M 118:4 DataSource.name - A (1) django/contrib/gis/gdal/layer.py M 39:4 Layer.__getitem__ - A (5) M 70:4 Layer._make_feature - A (5) M 169:4 Layer._set_spatial_filter - A (5) M 196:4 Layer.get_geoms - A (4) C 21:0 Layer - A (3) M 187:4 Layer.get_fields - A (3) M 24:4 Layer.__init__ - A (2) M 55:4 Layer.__iter__ - A (2) M 122:4 Layer.srs - A (2) M 131:4 Layer.fields - A (2) M 142:4 Layer.field_types - A (2) M 152:4 Layer.field_widths - A (2) M 158:4 Layer.field_precisions - A (2) M 163:4 Layer._get_spatial_filter - A (2) M 62:4 Layer.__len__ - A (1) M 66:4 Layer.__str__ - A (1) M 94:4 Layer.extent - A (1) M 101:4 Layer.name - A (1) M 107:4 Layer.num_feat - A (1) M 112:4 Layer.num_fields - A (1) M 117:4 Layer.geom_type - A (1) M 207:4 Layer.test_capability - A (1) django/contrib/gis/gdal/driver.py M 34:4 Driver.__init__ - B (10) C 9:0 Driver - A (4) M 74:4 Driver.ensure_registered - A (3) M 70:4 Driver.__str__ - A (1) M 86:4 Driver.driver_count - A (1) M 93:4 Driver.name - A (1) django/contrib/gis/gdal/geometries.py M 63:4 OGRGeometry.__init__ - C (13) M 382:4 OGRGeometry.transform - A (5) M 540:4 LineString.__getitem__ - A (5) M 650:4 GeometryCollection.add - A (5) M 267:4 OGRGeometry._set_srs - A (4) M 293:4 OGRGeometry._set_srid - A (3) M 360:4 OGRGeometry.ewkt - A (3) M 529:4 Point.tuple - A (3) C 538:0 LineString - A (3) C 636:0 GeometryCollection - A (3) C 59:0 OGRGeometry - A (2) M 120:4 OGRGeometry.__getstate__ - A (2) M 128:4 OGRGeometry.__setstate__ - A (2) M 180:4 OGRGeometry.__eq__ - A (2) M 198:4 OGRGeometry._set_coord_dim - A (2) M 259:4 OGRGeometry._get_srs - A (2) M 287:4 OGRGeometry._get_srid - A (2) M 341:4 OGRGeometry.wkb - A (2) M 409:4 OGRGeometry._topology - A (2) M 452:4 OGRGeometry._geomgen - A (2) C 502:0 Point - A (2) M 504:4 Point._geos_ptr - A (2) M 523:4 Point.z - A (2) M 560:4 LineString.tuple - A (2) M 565:4 LineString._listarr - A (2) M 583:4 LineString.z - A (2) C 594:0 Polygon - A (2) M 600:4 Polygon.__getitem__ - A (2) M 615:4 Polygon.tuple - A (2) M 621:4 Polygon.point_count - A (2) M 639:4 GeometryCollection.__getitem__ - A (2) M 665:4 GeometryCollection.point_count - A (2) M 671:4 GeometryCollection.tuple - A (2) M 137:4 OGRGeometry._from_wkb - A (1) M 141:4 OGRGeometry._from_json - A (1) M 145:4 OGRGeometry.from_bbox - A (1) M 152:4 OGRGeometry.from_json - A (1) M 156:4 OGRGeometry.from_gml - A (1) M 161:4 OGRGeometry.__or__ - A (1) M 166:4 OGRGeometry.__and__ - A (1) M 171:4 OGRGeometry.__sub__ - A (1) M 176:4 OGRGeometry.__xor__ - A (1) M 184:4 OGRGeometry.__str__ - A (1) M 190:4 OGRGeometry.dimension - A (1) M 194:4 OGRGeometry._get_coord_dim - A (1) M 207:4 OGRGeometry.geom_count - A (1) M 212:4 OGRGeometry.point_count - A (1) M 217:4 OGRGeometry.num_points - A (1) M 222:4 OGRGeometry.num_coords - A (1) M 227:4 OGRGeometry.geom_type - A (1) M 232:4 OGRGeometry.geom_name - A (1) M 237:4 OGRGeometry.area - A (1) M 242:4 OGRGeometry.envelope - A (1) M 248:4 OGRGeometry.empty - A (1) M 252:4 OGRGeometry.extent - A (1) M 302:4 OGRGeometry._geos_ptr - A (1) M 307:4 OGRGeometry.geos - A (1) M 313:4 OGRGeometry.gml - A (1) M 318:4 OGRGeometry.hex - A (1) M 323:4 OGRGeometry.json - A (1) M 331:4 OGRGeometry.kml - A (1) M 336:4 OGRGeometry.wkb_size - A (1) M 355:4 OGRGeometry.wkt - A (1) M 369:4 OGRGeometry.clone - A (1) M 373:4 OGRGeometry.close_rings - A (1) M 419:4 OGRGeometry.intersects - A (1) M 423:4 OGRGeometry.equals - A (1) M 427:4 OGRGeometry.disjoint - A (1) M 431:4 OGRGeometry.touches - A (1) M 435:4 OGRGeometry.crosses - A (1) M 439:4 OGRGeometry.within - A (1) M 443:4 OGRGeometry.contains - A (1) M 447:4 OGRGeometry.overlaps - A (1) M 460:4 OGRGeometry.boundary - A (1) M 465:4 OGRGeometry.convex_hull - A (1) M 472:4 OGRGeometry.difference - A (1) M 479:4 OGRGeometry.intersection - A (1) M 486:4 OGRGeometry.sym_difference - A (1) M 493:4 OGRGeometry.union - A (1) M 509:4 Point._create_empty - A (1) M 513:4 Point.x - A (1) M 518:4 Point.y - A (1) M 555:4 LineString.__len__ - A (1) M 573:4 LineString.x - A (1) M 578:4 LineString.y - A (1) C 590:0 LinearRing - A (1) M 596:4 Polygon.__len__ - A (1) M 609:4 Polygon.shell - A (1) M 627:4 Polygon.centroid - A (1) M 646:4 GeometryCollection.__len__ - A (1) C 678:0 MultiPoint - A (1) C 682:0 MultiLineString - A (1) C 686:0 MultiPolygon - A (1) django/contrib/gis/gdal/base.py C 5:0 GDALBase - A (1) django/contrib/gis/gdal/libgdal.py F 90:0 gdal_version_info - A (3) F 61:0 std_call - A (2) F 80:0 gdal_version - A (1) F 85:0 gdal_full_version - A (1) F 105:0 err_handler - A (1) F 112:0 function - A (1) django/contrib/gis/gdal/envelope.py M 94:4 Envelope.expand_to_include - C (14) M 68:4 Envelope.__eq__ - B (10) M 37:4 Envelope.__init__ - B (9) C 30:0 Envelope - A (4) C 21:0 OGREnvelope - A (1) M 82:4 Envelope.__str__ - A (1) M 86:4 Envelope._from_sequence - A (1) M 137:4 Envelope.min_x - A (1) M 142:4 Envelope.min_y - A (1) M 147:4 Envelope.max_x - A (1) M 152:4 Envelope.max_y - A (1) M 157:4 Envelope.ur - A (1) M 162:4 Envelope.ll - A (1) M 167:4 Envelope.tuple - A (1) M 172:4 Envelope.wkt - A (1) django/contrib/gis/gdal/prototypes/srs.py F 11:0 srs_double - A (1) F 19:0 units_func - A (1) django/contrib/gis/gdal/prototypes/generation.py F 29:0 double_output - A (3) F 136:0 void_output - A (3) F 20:0 bool_output - A (2) F 40:0 geom_output - A (2) F 63:0 int_output - A (2) F 91:0 const_string_output - A (2) F 108:0 string_output - A (2) F 154:0 voidptr_output - A (2) F 163:0 chararray_output - A (2) F 72:0 int64_output - A (1) F 79:0 srs_output - A (1) C 16:0 gdal_char_p - A (1) django/contrib/gis/gdal/prototypes/geom.py F 13:0 env_func - A (1) F 21:0 pnt_func - A (1) F 26:0 topology_func - A (1) django/contrib/gis/gdal/prototypes/errcheck.py F 38:0 check_string - A (4) F 76:0 check_geom - A (3) F 95:0 check_srs - A (3) F 120:0 check_pointer - A (3) F 26:0 check_const_string - A (2) F 15:0 arg_byref - A (1) F 20:0 ptr_byref - A (1) F 70:0 check_envelope - A (1) F 87:0 check_geom_offset - A (1) F 104:0 check_arg_errcode - A (1) F 113:0 check_errcode - A (1) F 130:0 check_str_arg - A (1) django/contrib/gis/gdal/raster/band.py M 180:4 GDALBand.data - C (15) M 60:4 GDALBand.statistics - A (4) M 150:4 GDALBand.nodata_value - A (4) C 14:0 GDALBand - A (3) M 135:4 GDALBand.nodata_value - A (3) M 164:4 GDALBand.datatype - A (2) M 173:4 GDALBand.color_interp - A (2) C 236:0 BandList - A (2) M 241:4 BandList.__iter__ - A (2) M 248:4 BandList.__getitem__ - A (2) M 18:4 GDALBand.__init__ - A (1) M 22:4 GDALBand._flush - A (1) M 31:4 GDALBand.description - A (1) M 38:4 GDALBand.width - A (1) M 45:4 GDALBand.height - A (1) M 52:4 GDALBand.pixel_count - A (1) M 107:4 GDALBand.min - A (1) M 114:4 GDALBand.max - A (1) M 121:4 GDALBand.mean - A (1) M 128:4 GDALBand.std - A (1) M 237:4 BandList.__init__ - A (1) M 245:4 BandList.__len__ - A (1) django/contrib/gis/gdal/raster/source.py M 65:4 GDALRaster.__init__ - D (27) M 449:4 GDALRaster.transform - B (8) M 323:4 GDALRaster.geotransform - A (4) M 373:4 GDALRaster.warp - A (4) C 59:0 GDALRaster - A (3) M 268:4 GDALRaster.srs - A (3) M 281:4 GDALRaster.srs - A (3) M 428:4 GDALRaster.clone - A (3) C 24:0 TransformPoint - A (2) M 191:4 GDALRaster.__del__ - A (2) M 206:4 GDALRaster._flush - A (2) M 219:4 GDALRaster.vsi_buffer - A (2) M 234:4 GDALRaster.is_vsi_based - A (2) M 498:4 GDALRaster.info - A (2) M 31:4 TransformPoint.__init__ - A (1) M 39:4 TransformPoint.x - A (1) M 43:4 TransformPoint.x - A (1) M 49:4 TransformPoint.y - A (1) M 53:4 TransformPoint.y - A (1) M 197:4 GDALRaster.__str__ - A (1) M 200:4 GDALRaster.__repr__ - A (1) M 238:4 GDALRaster.name - A (1) M 246:4 GDALRaster.driver - A (1) M 254:4 GDALRaster.width - A (1) M 261:4 GDALRaster.height - A (1) M 297:4 GDALRaster.srid - A (1) M 304:4 GDALRaster.srid - A (1) M 311:4 GDALRaster.geotransform - A (1) M 333:4 GDALRaster.origin - A (1) M 340:4 GDALRaster.scale - A (1) M 347:4 GDALRaster.skew - A (1) M 354:4 GDALRaster.extent - A (1) M 370:4 GDALRaster.bands - A (1) django/contrib/gis/gdal/raster/base.py C 5:0 GDALRasterBase - B (8) M 10:4 GDALRasterBase.metadata - B (8) M 60:4 GDALRasterBase.metadata - A (5) django/contrib/gis/admin/options.py C 10:0 GeoModelAdmin - A (3) M 52:4 GeoModelAdmin.formfield_for_dbfield - A (3) M 65:4 GeoModelAdmin.get_map_widget - A (3) M 48:4 GeoModelAdmin.media - A (1) C 127:0 OSMGeoAdmin - A (1) django/contrib/gis/admin/widgets.py M 18:4 OpenLayersWidget.get_context - C (11) C 14:0 OpenLayersWidget - B (10) M 81:4 OpenLayersWidget.map_options - B (7) django/contrib/gis/management/commands/inspectdb.py C 6:0 Command - A (3) M 9:4 Command.get_field_type - A (2) django/contrib/gis/management/commands/ogrinspect.py M 98:4 Command.handle - B (9) C 33:0 Command - B (6) C 8:0 LayerOptionAction - A (3) C 20:0 ListOptionAction - A (3) M 13:4 LayerOptionAction.__call__ - A (2) M 26:4 ListOptionAction.__call__ - A (2) M 42:4 Command.add_arguments - A (1) django/contrib/gis/utils/srs.py F 5:0 add_srs_entry - C (12) django/contrib/gis/utils/ogrinspect.py F 122:0 _ogrinspect - C (20) F 13:0 mapping - B (6) F 51:0 ogrinspect - A (1) django/contrib/gis/utils/layermapping.py M 170:4 LayerMapping.check_layer - C (16) M 345:4 LayerMapping.verify_ogr_field - C (16) M 482:4 LayerMapping.save - C (12) M 86:4 LayerMapping.__init__ - B (9) C 48:0 LayerMapping - B (7) M 285:4 LayerMapping.check_unique - B (6) M 267:4 LayerMapping.check_srs - A (5) M 300:4 LayerMapping.feature_kwargs - A (5) M 158:4 LayerMapping.check_fid_range - A (4) M 425:4 LayerMapping.verify_geom - A (4) M 333:4 LayerMapping.unique_kwargs - A (3) M 402:4 LayerMapping.verify_fk - A (3) M 453:4 LayerMapping.coord_transform - A (2) M 474:4 LayerMapping.make_multi - A (2) C 28:0 LayerMapError - A (1) C 32:0 InvalidString - A (1) C 36:0 InvalidDecimal - A (1) C 40:0 InvalidInteger - A (1) C 44:0 MissingForeignKey - A (1) M 467:4 LayerMapping.geometry_field - A (1) django/contrib/gis/utils/ogrinfo.py F 11:0 ogrinfo - B (8) django/contrib/gis/serializers/geojson.py M 38:4 Serializer.get_dump_object - B (7) C 6:0 Serializer - A (4) M 10:4 Serializer._init_options - A (4) M 28:4 Serializer.start_object - A (4) M 58:4 Serializer.handle_field - A (2) C 65:0 Deserializer - A (2) M 18:4 Serializer.start_serialization - A (1) M 25:4 Serializer.end_serialization - A (1) M 66:4 Deserializer.__init__ - A (1) django/contrib/gis/sitemaps/kml.py M 19:4 KMLSitemap._build_kml_sources - B (8) C 8:0 KMLSitemap - A (3) M 45:4 KMLSitemap.get_urls - A (2) M 14:4 KMLSitemap.__init__ - A (1) M 55:4 KMLSitemap.items - A (1) M 58:4 KMLSitemap.location - A (1) C 69:0 KMZSitemap - A (1) django/contrib/gis/sitemaps/views.py F 10:0 kml - B (9) F 57:0 kmz - A (1) django/contrib/gis/db/backends/utils.py C 7:0 SpatialOperator - A (3) M 24:4 SpatialOperator.as_sql - A (3) M 18:4 SpatialOperator.default_template - A (2) M 13:4 SpatialOperator.__init__ - A (1) django/contrib/gis/db/backends/oracle/models.py C 14:0 OracleGeometryColumns - A (2) C 46:0 OracleSpatialRefSys - A (2) M 26:4 OracleGeometryColumns.__str__ - A (1) M 30:4 OracleGeometryColumns.table_name_col - A (1) M 38:4 OracleGeometryColumns.geom_col_name - A (1) M 63:4 OracleSpatialRefSys.wkt - A (1) django/contrib/gis/db/backends/oracle/adapter.py M 10:4 OracleSpatialAdapter.__init__ - B (7) C 7:0 OracleSpatialAdapter - B (6) M 39:4 OracleSpatialAdapter._fix_polygon - A (5) M 29:4 OracleSpatialAdapter._polygon_must_be_fixed - A (4) M 54:4 OracleSpatialAdapter._fix_geometry_collection - A (3) django/contrib/gis/db/backends/oracle/features.py C 7:0 DatabaseFeatures - A (1) django/contrib/gis/db/backends/oracle/operations.py M 150:4 OracleOperations.get_distance - A (5) M 120:4 OracleOperations.convert_extent - A (4) C 38:0 SDORelate - A (3) M 41:4 SDORelate.check_relate_argument - A (3) C 52:0 OracleOperations - A (3) M 175:4 OracleOperations.get_geom_placeholder - A (2) M 180:4 OracleOperations.spatial_aggregate_name - A (2) M 200:4 OracleOperations.modify_insert_params - A (2) M 208:4 OracleOperations.get_geometry_converter - A (2) C 26:0 SDOOperator - A (1) C 30:0 SDODWithin - A (1) C 34:0 SDODisjoint - A (1) M 47:4 SDORelate.as_sql - A (1) M 117:4 OracleOperations.geo_quote_name - A (1) M 142:4 OracleOperations.geo_db_type - A (1) M 188:4 OracleOperations.geometry_columns - A (1) M 194:4 OracleOperations.spatial_ref_sys - A (1) M 223:4 OracleOperations.get_area_att_for_field - A (1) django/contrib/gis/db/backends/oracle/introspection.py C 7:0 OracleIntrospection - A (4) M 18:4 OracleIntrospection.get_geometry_type - A (4) M 12:4 OracleIntrospection.data_types_reverse - A (1) django/contrib/gis/db/backends/oracle/base.py C 11:0 DatabaseWrapper - A (1) django/contrib/gis/db/backends/oracle/schema.py M 34:4 OracleGISSchemaEditor.column_sql - A (3) M 74:4 OracleGISSchemaEditor.remove_field - A (3) C 6:0 OracleGISSchemaEditor - A (2) M 86:4 OracleGISSchemaEditor.run_geometry_sql - A (2) M 27:4 OracleGISSchemaEditor.__init__ - A (1) M 31:4 OracleGISSchemaEditor.geo_quote_name - A (1) M 60:4 OracleGISSchemaEditor.create_model - A (1) M 64:4 OracleGISSchemaEditor.delete_model - A (1) M 70:4 OracleGISSchemaEditor.add_field - A (1) M 91:4 OracleGISSchemaEditor._create_spatial_index_name - A (1) django/contrib/gis/db/backends/postgis/models.py C 8:0 PostGISGeometryColumns - A (2) C 52:0 PostGISSpatialRefSys - A (2) M 26:4 PostGISGeometryColumns.__str__ - A (1) M 36:4 PostGISGeometryColumns.table_name_col - A (1) M 44:4 PostGISGeometryColumns.geom_col_name - A (1) M 69:4 PostGISSpatialRefSys.wkt - A (1) django/contrib/gis/db/backends/postgis/adapter.py M 57:4 PostGISAdapter.getquoted - A (3) C 11:0 PostGISAdapter - A (2) M 12:4 PostGISAdapter.__init__ - A (2) M 29:4 PostGISAdapter.__conform__ - A (2) M 36:4 PostGISAdapter.__eq__ - A (2) M 49:4 PostGISAdapter.prepare - A (2) M 39:4 PostGISAdapter.__hash__ - A (1) M 42:4 PostGISAdapter.__str__ - A (1) M 46:4 PostGISAdapter._fix_polygon - A (1) django/contrib/gis/db/backends/postgis/pgraster.py F 32:0 from_pgraster - A (5) F 94:0 to_pgraster - A (4) F 11:0 pack - A (1) F 18:0 unpack - A (1) F 25:0 chunk - A (1) django/contrib/gis/db/backends/postgis/features.py C 7:0 DatabaseFeatures - A (1) django/contrib/gis/db/backends/postgis/operations.py M 48:4 PostGISOperator.check_raster - C (17) C 28:0 PostGISOperator - B (8) M 269:4 PostGISOperations.get_geom_placeholder - B (6) M 215:4 PostGISOperations.geo_db_type - A (5) M 236:4 PostGISOperations.get_distance - A (5) M 40:4 PostGISOperator.as_sql - A (4) C 84:0 ST_Polygon - A (3) M 87:4 ST_Polygon.__init__ - A (3) C 98:0 PostGISOperations - A (3) M 160:4 PostGISOperations.spatial_version - A (3) M 373:4 PostGISOperations._normalize_distance_lookup_arg - A (3) M 148:4 PostGISOperations.function_names - A (2) M 189:4 PostGISOperations.convert_extent - A (2) M 202:4 PostGISOperations.convert_extent3d - A (2) M 335:4 PostGISOperations.proj_version_tuple - A (2) M 348:4 PostGISOperations.spatial_aggregate_name - A (2) M 29:4 PostGISOperator.__init__ - A (1) M 94:4 ST_Polygon.output_field - A (1) M 298:4 PostGISOperations._get_postgis_func - A (1) M 307:4 PostGISOperations.postgis_geos_version - A (1) M 311:4 PostGISOperations.postgis_lib_version - A (1) M 315:4 PostGISOperations.postgis_proj_version - A (1) M 319:4 PostGISOperations.postgis_version - A (1) M 323:4 PostGISOperations.postgis_full_version - A (1) M 327:4 PostGISOperations.postgis_version_tuple - A (1) M 355:4 PostGISOperations.geometry_columns - A (1) M 358:4 PostGISOperations.spatial_ref_sys - A (1) M 361:4 PostGISOperations.parse_raster - A (1) M 365:4 PostGISOperations.distance_expr_for_lookup - A (1) M 381:4 PostGISOperations.get_geometry_converter - A (1) M 389:4 PostGISOperations.get_area_att_for_field - A (1) django/contrib/gis/db/backends/postgis/introspection.py C 5:0 PostGISIntrospection - A (5) M 29:4 PostGISIntrospection.get_geometry_type - A (5) M 16:4 PostGISIntrospection.get_field_type - A (3) django/contrib/gis/db/backends/postgis/base.py C 12:0 DatabaseWrapper - A (3) M 15:4 DatabaseWrapper.__init__ - A (2) M 22:4 DatabaseWrapper.prepare_database - A (1) django/contrib/gis/db/backends/postgis/schema.py M 21:4 PostGISSchemaEditor._create_index_sql - B (8) M 51:4 PostGISSchemaEditor._alter_column_type_sql - B (7) C 5:0 PostGISSchemaEditor - A (5) M 16:4 PostGISSchemaEditor._field_should_be_indexed - A (2) M 13:4 PostGISSchemaEditor.geo_quote_name - A (1) django/contrib/gis/db/backends/mysql/features.py C 8:0 DatabaseFeatures - A (3) M 32:4 DatabaseFeatures.django_test_skips - A (3) M 20:4 DatabaseFeatures.empty_intersection_returns_none - A (2) M 27:4 DatabaseFeatures.supports_geometry_field_unique_index - A (1) django/contrib/gis/db/backends/mysql/operations.py M 63:4 MySQLOperations.unsupported_functions - A (4) M 82:4 MySQLOperations.get_distance - A (3) C 14:0 MySQLOperations - A (2) M 37:4 MySQLOperations.gis_operators - A (2) M 95:4 MySQLOperations.get_geometry_converter - A (2) M 21:4 MySQLOperations.mariadb - A (1) M 25:4 MySQLOperations.mysql - A (1) M 29:4 MySQLOperations.select - A (1) M 33:4 MySQLOperations.from_text - A (1) M 79:4 MySQLOperations.geo_db_type - A (1) django/contrib/gis/db/backends/mysql/introspection.py C 7:0 MySQLIntrospection - A (4) M 13:4 MySQLIntrospection.get_geometry_type - A (3) M 31:4 MySQLIntrospection.supports_spatial_index - A (3) django/contrib/gis/db/backends/mysql/base.py C 11:0 DatabaseWrapper - A (1) django/contrib/gis/db/backends/mysql/schema.py M 25:4 MySQLGISSchemaEditor.column_sql - A (4) M 48:4 MySQLGISSchemaEditor.remove_field - A (4) C 10:0 MySQLGISSchemaEditor - A (3) M 18:4 MySQLGISSchemaEditor.skip_default - A (3) M 68:4 MySQLGISSchemaEditor.create_spatial_indexes - A (3) M 14:4 MySQLGISSchemaEditor.__init__ - A (1) M 40:4 MySQLGISSchemaEditor.create_model - A (1) M 44:4 MySQLGISSchemaEditor.add_field - A (1) M 65:4 MySQLGISSchemaEditor._create_spatial_index_name - A (1) django/contrib/gis/db/backends/spatialite/models.py C 8:0 SpatialiteGeometryColumns - A (2) C 50:0 SpatialiteSpatialRefSys - A (2) M 24:4 SpatialiteGeometryColumns.__str__ - A (1) M 34:4 SpatialiteGeometryColumns.table_name_col - A (1) M 42:4 SpatialiteGeometryColumns.geom_col_name - A (1) M 67:4 SpatialiteSpatialRefSys.wkt - A (1) django/contrib/gis/db/backends/spatialite/adapter.py C 5:0 SpatiaLiteAdapter - A (3) M 7:4 SpatiaLiteAdapter.__conform__ - A (2) django/contrib/gis/db/backends/spatialite/client.py C 4:0 SpatiaLiteClient - A (1) django/contrib/gis/db/backends/spatialite/features.py C 8:0 DatabaseFeatures - A (2) M 13:4 DatabaseFeatures.supports_area_geodetic - A (1) M 17:4 DatabaseFeatures.django_test_skips - A (1) django/contrib/gis/db/backends/spatialite/operations.py M 122:4 SpatiaLiteOperations.get_distance - A (5) M 89:4 SpatiaLiteOperations.spatial_version - A (3) C 20:0 SpatialiteNullCheckOperator - A (2) C 26:0 SpatiaLiteOperations - A (2) M 82:4 SpatiaLiteOperations.unsupported_functions - A (2) M 104:4 SpatiaLiteOperations.convert_extent - A (2) M 182:4 SpatiaLiteOperations.spatial_aggregate_name - A (2) M 21:4 SpatialiteNullCheckOperator.as_sql - A (1) M 115:4 SpatiaLiteOperations.geo_db_type - A (1) M 144:4 SpatiaLiteOperations._get_spatialite_func - A (1) M 158:4 SpatiaLiteOperations.geos_version - A (1) M 162:4 SpatiaLiteOperations.proj_version - A (1) M 166:4 SpatiaLiteOperations.lwgeom_version - A (1) M 170:4 SpatiaLiteOperations.spatialite_version - A (1) M 174:4 SpatiaLiteOperations.spatialite_version_tuple - A (1) M 191:4 SpatiaLiteOperations.geometry_columns - A (1) M 197:4 SpatiaLiteOperations.spatial_ref_sys - A (1) M 203:4 SpatiaLiteOperations.get_geometry_converter - A (1) django/contrib/gis/db/backends/spatialite/introspection.py M 27:4 SpatiaLiteIntrospection.get_geometry_type - B (8) C 24:0 SpatiaLiteIntrospection - B (6) M 59:4 SpatiaLiteIntrospection.get_constraints - A (2) C 7:0 GeoFlexibleFieldLookupDict - A (1) django/contrib/gis/db/backends/spatialite/base.py M 38:4 DatabaseWrapper.get_new_connection - B (7) C 16:0 DatabaseWrapper - A (5) M 24:4 DatabaseWrapper.__init__ - A (3) M 68:4 DatabaseWrapper.prepare_database - A (2) django/contrib/gis/db/backends/spatialite/schema.py M 128:4 SpatialiteSchemaEditor.alter_db_table - B (8) M 84:4 SpatialiteSchemaEditor.delete_model - A (5) C 5:0 SpatialiteSchemaEditor - A (4) M 37:4 SpatialiteSchemaEditor.column_sql - A (3) M 104:4 SpatialiteSchemaEditor.add_field - A (3) M 77:4 SpatialiteSchemaEditor.create_model - A (2) M 115:4 SpatialiteSchemaEditor.remove_field - A (2) M 30:4 SpatialiteSchemaEditor.__init__ - A (1) M 34:4 SpatialiteSchemaEditor.geo_quote_name - A (1) M 63:4 SpatialiteSchemaEditor.remove_geometry_metadata - A (1) django/contrib/gis/db/backends/base/models.py M 10:4 SpatialRefSysMixin.srs - A (4) M 95:4 SpatialRefSysMixin.units - A (4) M 113:4 SpatialRefSysMixin.get_spheroid - A (3) C 4:0 SpatialRefSysMixin - A (2) M 37:4 SpatialRefSysMixin.ellipsoid - A (1) M 45:4 SpatialRefSysMixin.name - A (1) M 50:4 SpatialRefSysMixin.spheroid - A (1) M 55:4 SpatialRefSysMixin.datum - A (1) M 60:4 SpatialRefSysMixin.projected - A (1) M 65:4 SpatialRefSysMixin.local - A (1) M 70:4 SpatialRefSysMixin.geographic - A (1) M 75:4 SpatialRefSysMixin.linear_name - A (1) M 80:4 SpatialRefSysMixin.linear_units - A (1) M 85:4 SpatialRefSysMixin.angular_name - A (1) M 90:4 SpatialRefSysMixin.angular_units - A (1) M 105:4 SpatialRefSysMixin.get_units - A (1) M 132:4 SpatialRefSysMixin.__str__ - A (1) django/contrib/gis/db/backends/base/adapter.py M 9:4 WKTAdapter.__eq__ - A (3) C 1:0 WKTAdapter - A (2) M 5:4 WKTAdapter.__init__ - A (1) M 15:4 WKTAdapter.__hash__ - A (1) M 18:4 WKTAdapter.__str__ - A (1) M 22:4 WKTAdapter._fix_polygon - A (1) django/contrib/gis/db/backends/base/features.py C 6:0 BaseSpatialFeatures - A (2) M 106:4 BaseSpatialFeatures.__getattr__ - A (2) M 62:4 BaseSpatialFeatures.supports_bbcontains_lookup - A (1) M 66:4 BaseSpatialFeatures.supports_contained_lookup - A (1) M 70:4 BaseSpatialFeatures.supports_crosses_lookup - A (1) M 74:4 BaseSpatialFeatures.supports_distances_lookups - A (1) M 78:4 BaseSpatialFeatures.supports_dwithin_lookup - A (1) M 82:4 BaseSpatialFeatures.supports_relate_lookup - A (1) M 86:4 BaseSpatialFeatures.supports_isvalid_lookup - A (1) M 91:4 BaseSpatialFeatures.supports_collect_aggr - A (1) M 95:4 BaseSpatialFeatures.supports_extent_aggr - A (1) M 99:4 BaseSpatialFeatures.supports_make_line_aggr - A (1) M 103:4 BaseSpatialFeatures.supports_union_aggr - A (1) django/contrib/gis/db/backends/base/operations.py M 76:4 BaseSpatialOperations.get_geom_placeholder - A (5) M 140:4 BaseSpatialOperations.get_area_att_for_field - A (4) M 150:4 BaseSpatialOperations.get_distance_att_for_field - A (4) C 10:0 BaseSpatialOperations - A (2) M 104:4 BaseSpatialOperations.check_expression_support - A (2) M 114:4 BaseSpatialOperations.spatial_function_name - A (2) M 128:4 BaseSpatialOperations.get_db_converters - A (2) M 24:4 BaseSpatialOperations.select_extent - A (1) M 51:4 BaseSpatialOperations.convert_extent - A (1) M 54:4 BaseSpatialOperations.convert_extent3d - A (1) M 58:4 BaseSpatialOperations.geo_quote_name - A (1) M 62:4 BaseSpatialOperations.geo_db_type - A (1) M 69:4 BaseSpatialOperations.get_distance - A (1) M 111:4 BaseSpatialOperations.spatial_aggregate_name - A (1) M 120:4 BaseSpatialOperations.geometry_columns - A (1) M 123:4 BaseSpatialOperations.spatial_ref_sys - A (1) M 134:4 BaseSpatialOperations.get_geometry_converter - A (1) django/contrib/gis/db/models/functions.py M 22:4 GeoFuncMixin.__init__ - B (10) M 155:4 AsGeoJSON.__init__ - B (7) C 443:0 SnapToGrid - B (7) M 267:4 Distance.as_postgresql - B (6) M 358:4 Length.as_postgresql - B (6) M 444:4 SnapToGrid.__init__ - B (6) C 18:0 GeoFuncMixin - A (5) M 55:4 GeoFuncMixin.resolve_expression - A (5) C 98:0 SQLiteDecimalToFloatMixin - A (5) C 152:0 AsGeoJSON - A (5) C 405:0 Perimeter - A (5) M 408:4 Perimeter.as_postgresql - A (5) M 78:4 GeoFuncMixin._handle_param - A (4) M 103:4 SQLiteDecimalToFloatMixin.as_sqlite - A (4) C 257:0 Distance - A (4) C 348:0 Length - A (4) M 50:4 GeoFuncMixin.as_sql - A (3) C 127:0 Area - A (3) M 134:4 Area.as_sql - A (3) C 177:0 AsGML - A (3) C 196:0 AsKML - A (3) C 206:0 AsSVG - A (3) C 248:0 DistanceResultMixin - A (3) C 308:0 GeoHash - A (3) M 353:4 Length.as_sql - A (3) M 373:4 Length.as_sqlite - A (3) C 431:0 Scale - A (3) C 467:0 Transform - A (3) C 478:0 Translate - A (3) C 92:0 GeomOutputGeoFunc - A (2) C 113:0 OracleToleranceMixin - A (2) M 139:4 Area.as_sqlite - A (2) M 181:4 AsGML.__init__ - A (2) M 187:4 AsGML.as_oracle - A (2) M 199:4 AsKML.__init__ - A (2) M 209:4 AsSVG.__init__ - A (2) C 229:0 BoundingCircle - A (2) M 253:4 DistanceResultMixin.source_is_geography - A (2) M 261:4 Distance.__init__ - A (2) M 292:4 Distance.as_sqlite - A (2) M 311:4 GeoHash.__init__ - A (2) M 317:4 GeoHash.as_mysql - A (2) C 339:0 IsValid - A (2) M 417:4 Perimeter.as_sqlite - A (2) M 432:4 Scale.__init__ - A (2) M 468:4 Transform.__init__ - A (2) M 479:4 Translate.as_sqlite - A (2) M 43:4 GeoFuncMixin.name - A (1) M 47:4 GeoFuncMixin.geo_field - A (1) C 88:0 GeoFunc - A (1) M 94:4 GeomOutputGeoFunc.output_field - A (1) M 116:4 OracleToleranceMixin.as_oracle - A (1) M 131:4 Area.output_field - A (1) C 146:0 Azimuth - A (1) M 170:4 AsGeoJSON.as_oracle - A (1) C 219:0 AsWKB - A (1) C 224:0 AsWKT - A (1) M 230:4 BoundingCircle.__init__ - A (1) M 233:4 BoundingCircle.as_oracle - A (1) C 239:0 Centroid - A (1) C 243:0 Difference - A (1) M 250:4 DistanceResultMixin.output_field - A (1) C 300:0 Envelope - A (1) C 304:0 ForcePolygonCW - A (1) C 325:0 GeometryDistance - A (1) C 333:0 Intersection - A (1) M 343:4 IsValid.as_oracle - A (1) M 349:4 Length.__init__ - A (1) C 380:0 LineLocatePoint - A (1) C 386:0 MakeValid - A (1) C 390:0 MemSize - A (1) C 395:0 NumGeometries - A (1) C 400:0 NumPoints - A (1) C 423:0 PointOnSurface - A (1) C 427:0 Reverse - A (1) C 462:0 SymDifference - A (1) C 487:0 Union - A (1) django/contrib/gis/db/models/fields.py M 172:4 BaseSpatialField.get_prep_value - B (7) M 155:4 BaseSpatialField.get_raster_prep_value - B (6) M 130:4 BaseSpatialField.get_srid - A (5) M 243:4 GeometryField.deconstruct - A (5) F 23:0 get_srid_info - A (4) M 143:4 BaseSpatialField.get_db_prep_value - A (4) C 56:0 BaseSpatialField - A (3) C 201:0 GeometryField - A (3) M 262:4 GeometryField.formfield - A (3) C 334:0 ExtentField - A (3) M 356:4 RasterField._check_connection - A (3) M 95:4 BaseSpatialField.deconstruct - A (2) M 256:4 GeometryField.contribute_to_class - A (2) M 273:4 GeometryField.select_format - A (2) M 342:4 ExtentField.select_format - A (2) C 347:0 RasterField - A (2) M 376:4 RasterField.get_transform - A (2) M 67:4 BaseSpatialField.__init__ - A (1) M 104:4 BaseSpatialField.db_type - A (1) M 107:4 BaseSpatialField.spheroid - A (1) M 110:4 BaseSpatialField.units - A (1) M 113:4 BaseSpatialField.units_name - A (1) M 116:4 BaseSpatialField.geodetic - A (1) M 123:4 BaseSpatialField.get_placeholder - A (1) M 211:4 GeometryField.__init__ - A (1) C 285:0 PointField - A (1) C 292:0 LineStringField - A (1) C 299:0 PolygonField - A (1) C 306:0 MultiPointField - A (1) C 313:0 MultiLineStringField - A (1) C 320:0 MultiPolygonField - A (1) C 327:0 GeometryCollectionField - A (1) M 339:4 ExtentField.get_internal_type - A (1) M 361:4 RasterField.db_type - A (1) M 365:4 RasterField.from_db_value - A (1) M 368:4 RasterField.contribute_to_class - A (1) django/contrib/gis/db/models/proxy.py M 49:4 SpatialProxy.__set__ - B (8) C 11:0 SpatialProxy - B (6) M 21:4 SpatialProxy.__get__ - B (6) M 12:4 SpatialProxy.__init__ - A (2) django/contrib/gis/db/models/lookups.py M 27:4 GISLookup.process_rhs_params - B (6) M 282:4 DistanceLookupBase.process_rhs_params - B (6) C 251:0 RelateLookup - A (5) C 278:0 DistanceLookupBase - A (5) M 256:4 RelateLookup.process_rhs - A (4) C 302:0 DWithinLookup - A (4) M 306:4 DWithinLookup.process_distance - A (4) C 326:0 DistanceLookupFromFunction - A (4) C 14:0 GISLookup - A (3) M 37:4 GISLookup.process_band_indices - A (3) M 60:4 GISLookup.process_rhs - A (3) M 327:4 DistanceLookupFromFunction.as_sql - A (3) C 9:0 RasterBandTransform - A (2) M 21:4 GISLookup.__init__ - A (2) M 292:4 DistanceLookupBase.process_distance - A (2) M 10:4 RasterBandTransform.as_sql - A (1) M 56:4 GISLookup.get_db_prep_lookup - A (1) M 70:4 GISLookup.get_rhs_op - A (1) M 76:4 GISLookup.as_sql - A (1) C 91:0 OverlapsLeftLookup - A (1) C 100:0 OverlapsRightLookup - A (1) C 109:0 OverlapsBelowLookup - A (1) C 118:0 OverlapsAboveLookup - A (1) C 127:0 LeftLookup - A (1) C 136:0 RightLookup - A (1) C 145:0 StrictlyBelowLookup - A (1) C 154:0 StrictlyAboveLookup - A (1) C 163:0 SameAsLookup - A (1) C 176:0 BBContainsLookup - A (1) C 185:0 BBOverlapsLookup - A (1) C 193:0 ContainedLookup - A (1) C 206:0 ContainsLookup - A (1) C 211:0 ContainsProperlyLookup - A (1) C 216:0 CoveredByLookup - A (1) C 221:0 CoversLookup - A (1) C 226:0 CrossesLookup - A (1) C 231:0 DisjointLookup - A (1) C 236:0 EqualsLookup - A (1) C 241:0 IntersectsLookup - A (1) C 246:0 OverlapsLookup - A (1) C 269:0 TouchesLookup - A (1) C 274:0 WithinLookup - A (1) M 319:4 DWithinLookup.process_rhs - A (1) C 339:0 DistanceGTLookup - A (1) C 345:0 DistanceGTELookup - A (1) C 351:0 DistanceLTLookup - A (1) C 357:0 DistanceLTELookup - A (1) django/contrib/gis/db/models/aggregates.py C 10:0 GeoAggregate - A (3) M 29:4 GeoAggregate.as_oracle - A (3) M 41:4 GeoAggregate.resolve_expression - A (3) M 18:4 GeoAggregate.as_sql - A (2) C 54:0 Extent - A (2) C 65:0 Extent3D - A (2) M 15:4 GeoAggregate.output_field - A (1) C 49:0 Collect - A (1) M 58:4 Extent.__init__ - A (1) M 61:4 Extent.convert_value - A (1) M 69:4 Extent3D.__init__ - A (1) M 72:4 Extent3D.convert_value - A (1) C 76:0 MakeLine - A (1) C 81:0 Union - A (1) django/contrib/gis/db/models/sql/conversion.py M 28:4 AreaField.from_db_value - A (4) C 11:0 AreaField - A (3) M 22:4 AreaField.get_db_prep_value - A (3) C 43:0 DistanceField - A (3) M 54:4 DistanceField.get_db_prep_value - A (3) M 62:4 DistanceField.from_db_value - A (3) M 17:4 AreaField.get_prep_value - A (2) M 49:4 DistanceField.get_prep_value - A (2) M 13:4 AreaField.__init__ - A (1) M 39:4 AreaField.get_internal_type - A (1) M 45:4 DistanceField.__init__ - A (1) M 68:4 DistanceField.get_internal_type - A (1) django/contrib/gis/geoip2/resources.py F 1:0 City - A (2) F 18:0 Country - A (1) django/contrib/gis/geoip2/base.py M 46:4 GeoIP2.__init__ - C (13) M 142:4 GeoIP2._check_query - B (10) C 24:0 GeoIP2 - A (3) M 194:4 GeoIP2.coords - A (3) M 117:4 GeoIP2._reader - A (2) M 121:4 GeoIP2._country_or_city - A (2) M 127:4 GeoIP2.__del__ - A (2) M 209:4 GeoIP2.geos - A (2) C 20:0 GeoIP2Exception - A (1) M 132:4 GeoIP2.__repr__ - A (1) M 164:4 GeoIP2.city - A (1) M 173:4 GeoIP2.country_code - A (1) M 178:4 GeoIP2.country_name - A (1) M 183:4 GeoIP2.country - A (1) M 201:4 GeoIP2.lon_lat - A (1) M 205:4 GeoIP2.lat_lon - A (1) M 220:4 GeoIP2.info - A (1) M 226:4 GeoIP2.open - A (1) django/contrib/admindocs/apps.py C 5:0 AdminDocsConfig - A (1) django/contrib/admindocs/utils.py F 180:0 replace_unnamed_groups - C (16) F 142:0 replace_named_groups - B (10) F 28:0 parse_docstring - B (7) F 56:0 parse_rst - A (2) F 115:0 default_reference_role - A (2) F 22:0 get_view_name - A (1) F 98:0 create_reference_role - A (1) django/contrib/admindocs/middleware.py C 8:0 XViewMiddleware - B (7) M 12:4 XViewMiddleware.process_view - B (6) django/contrib/admindocs/views.py C 186:0 ModelDetailView - D (26) M 189:4 ModelDetailView.get_context_data - D (25) C 56:0 TemplateTagIndexView - C (12) C 87:0 TemplateFilterIndexView - C (12) M 59:4 TemplateTagIndexView.get_context_data - C (11) M 90:4 TemplateFilterIndexView.get_context_data - C (11) F 378:0 extract_views_from_urlpatterns - B (9) C 118:0 ViewIndexView - B (8) M 121:4 ViewIndexView.get_context_data - B (7) C 322:0 TemplateDetailView - B (6) C 139:0 ViewDetailView - A (5) M 159:4 ViewDetailView.get_context_data - A (5) M 325:4 TemplateDetailView.get_context_data - A (5) F 359:0 get_return_data_type - A (4) C 33:0 BaseAdminDocsView - A (3) M 143:4 ViewDetailView._get_view_func - A (3) C 178:0 ModelIndexView - A (3) F 406:0 simplify_regex - A (2) M 38:4 BaseAdminDocsView.dispatch - A (2) M 181:4 ModelIndexView.get_context_data - A (2) F 369:0 get_readable_field_data_type - A (1) M 45:4 BaseAdminDocsView.get_context_data - A (1) C 52:0 BookmarkletsView - A (1) django/http/multipartparser.py M 105:4 MultiPartParser.parse - E (37) C 44:0 MultiPartParser - C (12) M 51:4 MultiPartParser.__init__ - C (11) M 508:4 BoundaryIter.__next__ - B (9) F 654:0 parse_header - B (8) F 583:0 parse_boundary_stream - B (7) F 686:0 _parse_header_params - A (5) C 478:0 BoundaryIter - A (5) M 415:4 LazyStream._update_unget_history - A (4) M 549:4 BoundaryIter._find_boundary - A (4) M 298:4 MultiPartParser.handle_file_complete - A (3) M 313:4 MultiPartParser._close_files - A (3) C 437:0 ChunkIter - A (3) M 446:4 ChunkIter.__next__ - A (3) C 642:0 Parser - A (3) F 574:0 exhaust - A (2) M 309:4 MultiPartParser.IE_sanitize - A (2) C 322:0 LazyStream - A (2) M 374:4 LazyStream.__next__ - A (2) M 402:4 LazyStream.unget - A (2) C 460:0 InterBoundaryIter - A (2) M 471:4 InterBoundaryIter.__next__ - A (2) M 490:4 BoundaryIter.__init__ - A (2) M 647:4 Parser.__iter__ - A (2) C 28:0 MultiPartParserError - A (1) C 32:0 InputStreamExhausted - A (1) M 330:4 LazyStream.__init__ - A (1) M 345:4 LazyStream.tell - A (1) M 348:4 LazyStream.read - A (1) M 390:4 LazyStream.close - A (1) M 399:4 LazyStream.__iter__ - A (1) M 442:4 ChunkIter.__init__ - A (1) M 456:4 ChunkIter.__iter__ - A (1) M 464:4 InterBoundaryIter.__init__ - A (1) M 468:4 InterBoundaryIter.__iter__ - A (1) M 505:4 BoundaryIter.__iter__ - A (1) M 643:4 Parser.__init__ - A (1) django/http/request.py M 194:4 HttpRequest.build_absolute_uri - B (10) M 323:4 HttpRequest._load_post_and_files - B (8) M 302:4 HttpRequest.body - B (7) M 432:4 QueryDict.__init__ - B (7) M 98:4 HttpRequest._get_raw_host - B (6) M 117:4 HttpRequest.get_host - B (6) F 631:0 split_domain_port - A (5) M 160:4 HttpRequest.get_signed_cookie - A (5) M 242:4 HttpRequest.scheme - A (5) M 87:4 HttpRequest._set_content_type_params - A (4) M 151:4 HttpRequest._get_full_path - A (4) M 352:4 HttpRequest.close - A (4) M 550:4 QueryDict.urlencode - A (4) M 605:4 MediaType.match - A (4) F 653:0 validate_host - A (3) F 671:0 parse_accept_header - A (3) C 42:0 HttpRequest - A (3) M 67:4 HttpRequest.__repr__ - A (3) M 137:4 HttpRequest.get_port - A (3) M 263:4 HttpRequest.encoding - A (3) C 386:0 HttpHeaders - A (3) M 391:4 HttpHeaders.__init__ - A (3) M 404:4 HttpHeaders.parse_header_name - A (3) M 463:4 QueryDict.fromkeys - A (3) C 580:0 MediaType - A (3) M 587:4 MediaType.__str__ - A (3) F 617:0 bytes_to_text - A (2) M 81:4 HttpRequest.accepts - A (2) M 275:4 HttpRequest._initialize_handlers - A (2) M 280:4 HttpRequest.upload_handlers - A (2) M 287:4 HttpRequest.upload_handlers - A (2) M 365:4 HttpRequest.read - A (2) M 372:4 HttpRequest.readline - A (2) C 412:0 QueryDict - A (2) M 476:4 QueryDict.encoding - A (2) M 485:4 QueryDict._assert_mutable - A (2) M 499:4 QueryDict.__copy__ - A (2) M 505:4 QueryDict.__deepcopy__ - A (2) M 512:4 QueryDict.setlist - A (2) M 581:4 MediaType.__init__ - A (2) M 602:4 MediaType.is_all_types - A (2) C 29:0 UnreadablePostError - A (1) C 33:0 RawPostDataException - A (1) M 49:4 HttpRequest.__init__ - A (1) M 73:4 HttpRequest.headers - A (1) M 77:4 HttpRequest.accepted_types - A (1) M 145:4 HttpRequest.get_full_path - A (1) M 148:4 HttpRequest.get_full_path_info - A (1) M 183:4 HttpRequest.get_raw_uri - A (1) M 231:4 HttpRequest._current_scheme_host - A (1) M 234:4 HttpRequest._get_scheme - A (1) M 255:4 HttpRequest.is_secure - A (1) M 259:4 HttpRequest.encoding - A (1) M 292:4 HttpRequest.parse_file_upload - A (1) M 319:4 HttpRequest._mark_post_parse_error - A (1) M 379:4 HttpRequest.__iter__ - A (1) M 382:4 HttpRequest.readlines - A (1) M 399:4 HttpHeaders.__getitem__ - A (1) M 482:4 QueryDict.encoding - A (1) M 489:4 QueryDict.__setitem__ - A (1) M 495:4 QueryDict.__delitem__ - A (1) M 518:4 QueryDict.setlistdefault - A (1) M 522:4 QueryDict.appendlist - A (1) M 528:4 QueryDict.pop - A (1) M 532:4 QueryDict.popitem - A (1) M 536:4 QueryDict.clear - A (1) M 540:4 QueryDict.setdefault - A (1) M 546:4 QueryDict.copy - A (1) M 598:4 MediaType.__repr__ - A (1) django/http/response.py M 456:4 FileResponse.set_headers - C (13) M 192:4 HttpResponseBase.set_cookie - C (12) M 41:4 ResponseHeaders._convert_to_charset - C (11) M 99:4 HttpResponseBase.__init__ - B (9) C 433:0 FileResponse - B (7) M 351:4 HttpResponse.content - B (6) C 579:0 JsonResponse - A (5) C 29:0 ResponseHeaders - A (4) M 30:4 ResponseHeaders.__init__ - A (4) M 593:4 JsonResponse.__init__ - A (4) C 89:0 HttpResponseBase - A (3) M 140:4 HttpResponseBase.charset - A (3) M 246:4 HttpResponseBase.delete_cookie - A (3) M 262:4 HttpResponseBase.make_bytes - A (3) M 283:4 HttpResponseBase.close - A (3) M 444:4 FileResponse._set_streaming_content - A (3) C 496:0 HttpResponseRedirectBase - A (3) M 499:4 HttpResponseRedirectBase.__init__ - A (3) C 525:0 HttpResponseNotModified - A (3) M 80:4 ResponseHeaders.setdefault - A (2) M 128:4 HttpResponseBase.reason_phrase - A (2) M 154:4 HttpResponseBase.serialize_headers - A (2) M 168:4 HttpResponseBase._content_type_for_repr - A (2) C 319:0 HttpResponse - A (2) M 383:4 HttpResponse.writelines - A (2) C 388:0 StreamingHttpResponse - A (2) M 420:4 StreamingHttpResponse._set_streaming_content - A (2) M 533:4 HttpResponseNotModified.content - A (2) C 551:0 HttpResponseNotAllowed - A (2) M 69:4 ResponseHeaders.__delitem__ - A (1) M 72:4 ResponseHeaders.__setitem__ - A (1) M 77:4 ResponseHeaders.pop - A (1) C 85:0 BadHeaderError - A (1) M 136:4 HttpResponseBase.reason_phrase - A (1) M 151:4 HttpResponseBase.charset - A (1) M 171:4 HttpResponseBase.__setitem__ - A (1) M 174:4 HttpResponseBase.__delitem__ - A (1) M 177:4 HttpResponseBase.__getitem__ - A (1) M 180:4 HttpResponseBase.has_header - A (1) M 186:4 HttpResponseBase.items - A (1) M 189:4 HttpResponseBase.get - A (1) M 238:4 HttpResponseBase.setdefault - A (1) M 242:4 HttpResponseBase.set_signed_cookie - A (1) M 294:4 HttpResponseBase.write - A (1) M 297:4 HttpResponseBase.flush - A (1) M 300:4 HttpResponseBase.tell - A (1) M 306:4 HttpResponseBase.readable - A (1) M 309:4 HttpResponseBase.seekable - A (1) M 312:4 HttpResponseBase.writable - A (1) M 315:4 HttpResponseBase.writelines - A (1) M 328:4 HttpResponse.__init__ - A (1) M 333:4 HttpResponse.__repr__ - A (1) M 340:4 HttpResponse.serialize - A (1) M 347:4 HttpResponse.content - A (1) M 368:4 HttpResponse.__iter__ - A (1) M 371:4 HttpResponse.write - A (1) M 374:4 HttpResponse.tell - A (1) M 377:4 HttpResponse.getvalue - A (1) M 380:4 HttpResponse.writable - A (1) M 399:4 StreamingHttpResponse.__init__ - A (1) M 406:4 StreamingHttpResponse.content - A (1) M 413:4 StreamingHttpResponse.streaming_content - A (1) M 417:4 StreamingHttpResponse.streaming_content - A (1) M 426:4 StreamingHttpResponse.__iter__ - A (1) M 429:4 StreamingHttpResponse.getvalue - A (1) M 439:4 FileResponse.__init__ - A (1) M 508:4 HttpResponseRedirectBase.__repr__ - A (1) C 517:0 HttpResponseRedirect - A (1) C 521:0 HttpResponsePermanentRedirect - A (1) M 528:4 HttpResponseNotModified.__init__ - A (1) C 539:0 HttpResponseBadRequest - A (1) C 543:0 HttpResponseNotFound - A (1) C 547:0 HttpResponseForbidden - A (1) M 554:4 HttpResponseNotAllowed.__init__ - A (1) M 558:4 HttpResponseNotAllowed.__repr__ - A (1) C 567:0 HttpResponseGone - A (1) C 571:0 HttpResponseServerError - A (1) C 575:0 Http404 - A (1) django/http/cookie.py F 7:0 parse_cookie - A (5) django/urls/resolvers.py M 622:4 URLResolver._reverse_with_prefix - D (22) M 447:4 URLResolver._populate - C (11) M 33:4 ResolverMatch.__init__ - B (9) M 550:4 URLResolver.resolve - B (9) F 205:0 _route_to_regex - B (8) C 32:0 ResolverMatch - A (5) M 156:4 RegexPattern.match - A (5) C 379:0 URLResolver - A (5) M 417:4 URLResolver._check_custom_error_handlers - A (5) C 90:0 LocaleRegexDescriptor - A (4) M 94:4 LocaleRegexDescriptor.__get__ - A (4) C 113:0 CheckURLMixin - A (4) M 123:4 CheckURLMixin._check_pattern_startswith_slash - A (4) M 261:4 RoutePattern.match - A (4) M 275:4 RoutePattern.check - A (4) M 305:4 LocalePrefixPattern.language_prefix - A (4) C 146:0 RegexPattern - A (3) M 175:4 RegexPattern._check_include_trailing_dollar - A (3) C 251:0 RoutePattern - A (3) C 328:0 URLPattern - A (3) M 343:4 URLPattern._check_pattern_name - A (3) M 366:4 URLPattern.lookup_str - A (3) M 399:4 URLResolver.__repr__ - A (3) M 410:4 URLResolver.check - A (3) M 530:4 URLResolver._extend_tried - A (3) M 537:4 URLResolver._join_route - A (3) F 68:0 get_resolver - A (2) M 114:4 CheckURLMixin.describe - A (2) M 168:4 RegexPattern.check - A (2) M 187:4 RegexPattern._compile - A (2) C 294:0 LocalePrefixPattern - A (2) M 312:4 LocalePrefixPattern.match - A (2) M 329:4 URLPattern.__init__ - A (2) M 357:4 URLPattern.resolve - A (2) M 380:4 URLResolver.__init__ - A (2) M 509:4 URLResolver.reverse_dict - A (2) M 516:4 URLResolver.namespace_dict - A (2) M 523:4 URLResolver.app_dict - A (2) M 545:4 URLResolver._is_callback - A (2) M 589:4 URLResolver.urlconf_module - A (2) M 596:4 URLResolver.url_patterns - A (2) M 610:4 URLResolver.resolve_error_handler - A (2) F 75:0 _get_cached_resolver - A (1) F 80:0 get_ns_resolver - A (1) M 58:4 ResolverMatch.__getitem__ - A (1) M 61:4 ResolverMatch.__repr__ - A (1) M 91:4 LocaleRegexDescriptor.__init__ - A (1) M 149:4 RegexPattern.__init__ - A (1) M 196:4 RegexPattern.__str__ - A (1) M 254:4 RoutePattern.__init__ - A (1) M 287:4 RoutePattern._compile - A (1) M 290:4 RoutePattern.__str__ - A (1) M 295:4 LocalePrefixPattern.__init__ - A (1) M 300:4 LocalePrefixPattern.regex - A (1) M 318:4 LocalePrefixPattern.check - A (1) M 321:4 LocalePrefixPattern.describe - A (1) M 324:4 LocalePrefixPattern.__str__ - A (1) M 335:4 URLPattern.__repr__ - A (1) M 338:4 URLPattern.check - A (1) M 619:4 URLResolver.reverse - A (1) django/urls/conf.py F 12:0 include - C (11) F 57:0 _path - A (3) django/urls/utils.py F 9:0 get_callable - C (12) F 55:0 get_mod_func - A (2) django/urls/exceptions.py C 4:0 Resolver404 - A (1) C 8:0 NoReverseMatch - A (1) django/urls/converters.py C 5:0 IntConverter - A (2) C 15:0 StringConverter - A (2) C 25:0 UUIDConverter - A (2) F 55:0 register_converter - A (1) F 61:0 get_converters - A (1) F 65:0 get_converter - A (1) M 8:4 IntConverter.to_python - A (1) M 11:4 IntConverter.to_url - A (1) M 18:4 StringConverter.to_python - A (1) M 21:4 StringConverter.to_url - A (1) M 28:4 UUIDConverter.to_python - A (1) M 31:4 UUIDConverter.to_url - A (1) C 35:0 SlugConverter - A (1) C 39:0 PathConverter - A (1) django/urls/base.py F 27:0 reverse - C (16) F 158:0 translate_url - B (7) F 126:0 set_urlconf - A (3) F 21:0 resolve - A (2) F 98:0 set_script_prefix - A (2) F 116:0 clear_script_prefix - A (2) F 146:0 is_valid_path - A (2) F 92:0 clear_url_caches - A (1) F 107:0 get_script_prefix - A (1) F 138:0 get_urlconf - A (1) django/db/transaction.py M 210:4 Atomic.__exit__ - C (20) C 135:0 Atomic - C (11) M 177:4 Atomic.__enter__ - B (9) F 96:0 mark_for_rollback_on_error - A (3) F 317:0 non_atomic_requests - A (3) F 13:0 get_connection - A (2) F 299:0 atomic - A (2) F 309:0 _non_atomic_requests - A (2) F 23:0 get_autocommit - A (1) F 28:0 set_autocommit - A (1) F 33:0 commit - A (1) F 38:0 rollback - A (1) F 43:0 savepoint - A (1) F 52:0 savepoint_rollback - A (1) F 60:0 savepoint_commit - A (1) F 68:0 clean_savepoints - A (1) F 75:0 get_rollback - A (1) F 80:0 set_rollback - A (1) F 123:0 on_commit - A (1) C 8:0 TransactionManagementError - A (1) M 172:4 Atomic.__init__ - A (1) django/db/__init__.py F 26:0 reset_queries - A (2) F 36:0 close_old_connections - A (2) django/db/utils.py F 101:0 load_backend - B (8) M 258:4 ConnectionRouter.allow_relation - B (6) M 69:4 DatabaseErrorWrapper.__exit__ - A (5) M 159:4 ConnectionHandler.ensure_defaults - A (5) C 134:0 ConnectionHandler - A (4) M 143:4 ConnectionHandler.configure_settings - A (4) C 216:0 ConnectionRouter - A (4) M 224:4 ConnectionRouter.routers - A (4) M 271:4 ConnectionRouter.allow_migrate - A (4) C 52:0 DatabaseErrorWrapper - A (3) M 180:4 ConnectionHandler.prepare_test_settings - A (3) M 207:4 ConnectionHandler.close_all - A (3) M 293:4 ConnectionRouter.get_migratable_models - A (3) C 16:0 Error - A (1) C 20:0 InterfaceError - A (1) C 24:0 DatabaseError - A (1) C 28:0 DataError - A (1) C 32:0 OperationalError - A (1) C 36:0 IntegrityError - A (1) C 40:0 InternalError - A (1) C 44:0 ProgrammingError - A (1) C 48:0 NotSupportedError - A (1) M 58:4 DatabaseErrorWrapper.__init__ - A (1) M 66:4 DatabaseErrorWrapper.__enter__ - A (1) M 92:4 DatabaseErrorWrapper.__call__ - A (1) M 156:4 ConnectionHandler.databases - A (1) M 200:4 ConnectionHandler.create_connection - A (1) M 217:4 ConnectionRouter.__init__ - A (1) M 236:4 ConnectionRouter._router_func - A (1) M 285:4 ConnectionRouter.allow_migrate_model - A (1) django/db/migrations/questioner.py M 25:4 MigrationQuestioner.ask_initial - C (12) M 108:4 InteractiveMigrationQuestioner._ask_default - B (9) M 93:4 InteractiveMigrationQuestioner._choice_input - B (6) M 85:4 InteractiveMigrationQuestioner._boolean_input - A (5) C 83:0 InteractiveMigrationQuestioner - A (4) M 161:4 InteractiveMigrationQuestioner.ask_not_null_alteration - A (4) C 13:0 MigrationQuestioner - A (3) M 20:4 MigrationQuestioner.__init__ - A (3) M 142:4 InteractiveMigrationQuestioner.ask_not_null_addition - A (3) M 206:4 InteractiveMigrationQuestioner.ask_auto_now_add_addition - A (3) C 226:0 NonInteractiveMigrationQuestioner - A (2) M 55:4 MigrationQuestioner.ask_not_null_addition - A (1) M 60:4 MigrationQuestioner.ask_not_null_alteration - A (1) M 65:4 MigrationQuestioner.ask_rename - A (1) M 69:4 MigrationQuestioner.ask_rename_model - A (1) M 73:4 MigrationQuestioner.ask_merge - A (1) M 77:4 MigrationQuestioner.ask_auto_now_add_addition - A (1) M 186:4 InteractiveMigrationQuestioner.ask_rename - A (1) M 192:4 InteractiveMigrationQuestioner.ask_rename_model - A (1) M 198:4 InteractiveMigrationQuestioner.ask_merge - A (1) M 228:4 NonInteractiveMigrationQuestioner.ask_not_null_addition - A (1) M 232:4 NonInteractiveMigrationQuestioner.ask_not_null_alteration - A (1) M 236:4 NonInteractiveMigrationQuestioner.ask_auto_now_add_addition - A (1) django/db/migrations/graph.py M 122:4 MigrationGraph.remove_replaced_nodes - B (8) M 259:4 MigrationGraph.ensure_not_cyclic - B (8) M 157:4 MigrationGraph.remove_replacement_node - B (7) M 217:4 MigrationGraph.iterative_dfs - B (6) M 234:4 MigrationGraph.root_nodes - B (6) M 245:4 MigrationGraph.leaf_nodes - B (6) M 292:4 MigrationGraph._generate_plan - B (6) M 300:4 MigrationGraph.make_state - A (5) C 61:0 MigrationGraph - A (4) M 99:4 MigrationGraph.add_dependency - A (4) M 193:4 MigrationGraph.validate_consistency - A (3) C 9:0 Node - A (2) C 44:0 DummyNode - A (2) M 88:4 MigrationGraph.add_node - A (2) M 197:4 MigrationGraph.forwards_plan - A (2) M 207:4 MigrationGraph.backwards_plan - A (2) M 289:4 MigrationGraph._nodes_and_edges - A (2) M 14:4 Node.__init__ - A (1) M 19:4 Node.__eq__ - A (1) M 22:4 Node.__lt__ - A (1) M 25:4 Node.__hash__ - A (1) M 28:4 Node.__getitem__ - A (1) M 31:4 Node.__str__ - A (1) M 34:4 Node.__repr__ - A (1) M 37:4 Node.add_child - A (1) M 40:4 Node.add_parent - A (1) M 52:4 DummyNode.__init__ - A (1) M 57:4 DummyNode.raise_error - A (1) M 84:4 MigrationGraph.__init__ - A (1) M 94:4 MigrationGraph.add_dummy_node - A (1) M 282:4 MigrationGraph.__str__ - A (1) M 285:4 MigrationGraph.__repr__ - A (1) M 318:4 MigrationGraph.__contains__ - A (1) django/db/migrations/recorder.py M 59:4 MigrationRecorder.ensure_schema - A (3) M 72:4 MigrationRecorder.applied_migrations - A (3) C 9:0 MigrationRecorder - A (2) M 24:4 MigrationRecorder.Migration - A (2) M 46:4 MigrationRecorder.__init__ - A (1) M 50:4 MigrationRecorder.migration_qs - A (1) M 53:4 MigrationRecorder.has_table - A (1) M 84:4 MigrationRecorder.record_applied - A (1) M 89:4 MigrationRecorder.record_unapplied - A (1) M 94:4 MigrationRecorder.flush - A (1) django/db/migrations/autodetector.py M 509:4 MigrationAutodetector.generate_created_models - E (32) M 372:4 MigrationAutodetector.check_dependency - E (31) M 248:4 MigrationAutodetector._build_migration_list - D (23) M 913:4 MigrationAutodetector.generate_altered_fields - D (23) M 1232:4 MigrationAutodetector.arrange_for_graph - C (19) M 716:4 MigrationAutodetector.generate_deleted_models - C (18) M 47:4 MigrationAutodetector.deep_deconstruct - C (14) M 818:4 MigrationAutodetector.generate_renamed_fields - C (13) M 861:4 MigrationAutodetector._generate_added_field - C (12) M 101:4 MigrationAutodetector._detect_changes - C (11) M 1095:4 MigrationAutodetector._generate_altered_foo_together - C (11) C 16:0 MigrationAutodetector - B (8) M 335:4 MigrationAutodetector._sort_migrations - B (8) M 463:4 MigrationAutodetector.generate_renamed_models - B (8) M 1282:4 MigrationAutodetector._trim_to_apps - B (8) M 356:4 MigrationAutodetector._optimize_migrations - B (7) M 443:4 MigrationAutodetector.swappable_first_key - B (7) M 1155:4 MigrationAutodetector.generate_altered_options - B (7) M 222:4 MigrationAutodetector._generate_through_model_map - B (6) M 683:4 MigrationAutodetector.generate_created_proxies - B (6) M 996:4 MigrationAutodetector.create_altered_indexes - B (6) M 1036:4 MigrationAutodetector.create_altered_constraints - B (6) M 198:4 MigrationAutodetector._prepare_field_lists - A (5) M 87:4 MigrationAutodetector.only_relation_agnostic_fields - A (4) M 1076:4 MigrationAutodetector._get_dependencies_for_foreign_key - A (4) M 1191:4 MigrationAutodetector.generate_altered_order_with_respect_to - A (4) M 29:4 MigrationAutodetector.__init__ - A (3) M 435:4 MigrationAutodetector.add_operation - A (3) M 805:4 MigrationAutodetector.generate_deleted_proxies - A (3) M 1014:4 MigrationAutodetector.generate_added_indexes - A (3) M 1025:4 MigrationAutodetector.generate_removed_indexes - A (3) M 1054:4 MigrationAutodetector.generate_added_constraints - A (3) M 1065:4 MigrationAutodetector.generate_removed_constraints - A (3) M 1138:4 MigrationAutodetector.generate_altered_db_table - A (3) M 1218:4 MigrationAutodetector.generate_altered_managers - A (3) M 35:4 MigrationAutodetector.changes - A (2) M 238:4 MigrationAutodetector._resolve_dependency - A (2) M 856:4 MigrationAutodetector.generate_added_fields - A (2) M 892:4 MigrationAutodetector.generate_removed_fields - A (2) M 1308:4 MigrationAutodetector.parse_number - A (2) M 897:4 MigrationAutodetector._generate_removed_field - A (1) M 1132:4 MigrationAutodetector.generate_altered_unique_together - A (1) M 1135:4 MigrationAutodetector.generate_altered_index_together - A (1) django/db/migrations/utils.py C 7:0 RegexObject - A (3) M 12:4 RegexObject.__eq__ - A (2) F 16:0 get_migration_name_timestamp - A (1) M 8:4 RegexObject.__init__ - A (1) django/db/migrations/loader.py M 68:4 MigrationLoader.load_disk - D (22) M 207:4 MigrationLoader.build_graph - C (19) M 156:4 MigrationLoader.check_key - B (10) M 288:4 MigrationLoader.check_consistent_history - B (8) C 18:0 MigrationLoader - B (7) M 138:4 MigrationLoader.get_migration_by_prefix - B (6) M 194:4 MigrationLoader.add_external_dependencies - B (6) M 184:4 MigrationLoader.add_internal_dependencies - A (4) M 314:4 MigrationLoader.detect_conflicts - A (4) M 337:4 MigrationLoader.collect_sql - A (4) M 43:4 MigrationLoader.__init__ - A (2) M 56:4 MigrationLoader.migrations_module - A (2) M 134:4 MigrationLoader.get_migration - A (1) M 328:4 MigrationLoader.project_state - A (1) django/db/migrations/optimizer.py M 40:4 MigrationOptimizer.optimize_inner - B (9) C 1:0 MigrationOptimizer - B (8) M 12:4 MigrationOptimizer.optimize - A (4) django/db/migrations/serializer.py F 331:0 serializer_factory - B (10) C 143:0 FunctionTypeSerializer - B (7) M 144:4 FunctionTypeSerializer.serialize - B (6) C 273:0 TypeSerializer - B (6) C 62:0 DatetimeDatetimeSerializer - A (5) M 274:4 TypeSerializer.serialize - A (5) M 64:4 DatetimeDatetimeSerializer.serialize - A (4) C 108:0 DictionarySerializer - A (4) C 131:0 FloatSerializer - A (4) C 184:0 IterableSerializer - A (4) C 31:0 BaseSequenceSerializer - A (3) C 78:0 DeconstructableSerializer - A (3) M 80:4 DeconstructableSerializer.serialize_deconstructed - A (3) M 109:4 DictionarySerializer.serialize - A (3) M 132:4 FloatSerializer.serialize - A (3) M 185:4 IterableSerializer.serialize - A (3) C 204:0 ModelManagerSerializer - A (3) C 227:0 PathSerializer - A (3) C 235:0 RegexSerializer - A (3) C 254:0 SetSerializer - A (3) C 266:0 TupleSerializer - A (3) C 295:0 Serializer - A (3) C 23:0 BaseSerializer - A (2) M 35:4 BaseSequenceSerializer.serialize - A (2) C 46:0 BaseSimpleSerializer - A (2) C 51:0 ChoicesSerializer - A (2) C 56:0 DateTimeSerializer - A (2) C 73:0 DecimalSerializer - A (2) M 94:4 DeconstructableSerializer._serialize_path - A (2) C 121:0 EnumSerializer - A (2) C 138:0 FrozensetSerializer - A (2) C 165:0 FunctoolsPartialSerializer - A (2) C 198:0 ModelFieldSerializer - A (2) M 205:4 ModelManagerSerializer.serialize - A (2) C 214:0 OperationSerializer - A (2) C 222:0 PathLikeSerializer - A (2) M 228:4 PathSerializer.serialize - A (2) M 236:4 RegexSerializer.serialize - A (2) C 249:0 SequenceSerializer - A (2) M 255:4 SetSerializer._format - A (2) C 261:0 SettingsReferenceSerializer - A (2) M 267:4 TupleSerializer._format - A (2) C 290:0 UUIDSerializer - A (2) M 321:4 Serializer.register - A (2) M 24:4 BaseSerializer.__init__ - A (1) M 27:4 BaseSerializer.serialize - A (1) M 32:4 BaseSequenceSerializer._format - A (1) M 47:4 BaseSimpleSerializer.serialize - A (1) M 52:4 ChoicesSerializer.serialize - A (1) M 58:4 DateTimeSerializer.serialize - A (1) M 74:4 DecimalSerializer.serialize - A (1) M 104:4 DeconstructableSerializer.serialize - A (1) M 122:4 EnumSerializer.serialize - A (1) M 139:4 FrozensetSerializer._format - A (1) M 166:4 FunctoolsPartialSerializer.serialize - A (1) M 199:4 ModelFieldSerializer.serialize - A (1) M 215:4 OperationSerializer.serialize - A (1) M 223:4 PathLikeSerializer.serialize - A (1) M 250:4 SequenceSerializer._format - A (1) M 262:4 SettingsReferenceSerializer.serialize - A (1) M 291:4 UUIDSerializer.serialize - A (1) M 327:4 Serializer.unregister - A (1) django/db/migrations/exceptions.py C 34:0 NodeNotFoundError - A (2) C 4:0 AmbiguityError - A (1) C 9:0 BadMigrationError - A (1) C 14:0 CircularDependencyError - A (1) C 19:0 InconsistentMigrationHistory - A (1) C 24:0 InvalidBasesError - A (1) C 29:0 IrreversibleError - A (1) M 37:4 NodeNotFoundError.__init__ - A (1) M 42:4 NodeNotFoundError.__str__ - A (1) M 45:4 NodeNotFoundError.__repr__ - A (1) C 49:0 MigrationSchemaMissing - A (1) C 53:0 InvalidMigrationPlan - A (1) django/db/migrations/writer.py M 129:4 MigrationWriter.as_string - C (14) M 202:4 MigrationWriter.basedir - C (13) M 24:4 OperationWriter.serialize - A (5) C 118:0 MigrationWriter - A (5) C 18:0 OperationWriter - A (2) M 19:4 OperationWriter.__init__ - A (1) M 105:4 OperationWriter.indent - A (1) M 108:4 OperationWriter.unindent - A (1) M 111:4 OperationWriter.feed - A (1) M 114:4 OperationWriter.render - A (1) M 124:4 MigrationWriter.__init__ - A (1) M 262:4 MigrationWriter.filename - A (1) M 266:4 MigrationWriter.path - A (1) M 270:4 MigrationWriter.serialize - A (1) M 274:4 MigrationWriter.register_serializer - A (1) M 278:4 MigrationWriter.unregister_serializer - A (1) django/db/migrations/migration.py M 129:4 Migration.unapply - C (11) M 92:4 Migration.apply - B (9) M 180:4 Migration.suggest_name - B (8) C 8:0 Migration - A (5) M 62:4 Migration.__eq__ - A (3) M 78:4 Migration.mutate_state - A (3) C 199:0 SwappableTuple - A (2) F 211:0 swappable_dependency - A (1) M 53:4 Migration.__init__ - A (1) M 69:4 Migration.__repr__ - A (1) M 72:4 Migration.__str__ - A (1) M 75:4 Migration.__hash__ - A (1) M 205:4 SwappableTuple.__new__ - A (1) django/db/migrations/executor.py M 281:4 MigrationExecutor.detect_soft_applied - D (25) M 22:4 MigrationExecutor.migration_plan - C (16) M 152:4 MigrationExecutor._migrate_all_backwards - C (16) C 10:0 MigrationExecutor - B (10) M 82:4 MigrationExecutor.migrate - B (9) M 213:4 MigrationExecutor.apply_migration - B (9) M 127:4 MigrationExecutor._migrate_all_forwards - B (8) M 64:4 MigrationExecutor._create_project_state - B (6) M 246:4 MigrationExecutor.unapply_migration - B (6) M 264:4 MigrationExecutor.check_replacements - A (5) M 238:4 MigrationExecutor.record_migration - A (3) M 16:4 MigrationExecutor.__init__ - A (1) django/db/migrations/state.py M 396:4 ModelState.from_model - E (37) M 105:4 ProjectState._find_reload_model - C (12) M 357:4 ModelState.__init__ - C (12) F 26:0 _get_related_models - B (9) M 589:4 ModelState.__eq__ - B (9) M 248:4 StateApps.__init__ - B (8) C 346:0 ModelState - B (8) M 165:4 ProjectState._reload - B (7) M 291:4 StateApps.render_multiple - B (6) M 551:4 ModelState.render - A (5) C 78:0 ProjectState - A (4) C 243:0 StateApps - A (4) F 18:0 _get_app_label_and_model_name - A (3) F 56:0 get_related_models_recursive - A (3) M 85:4 ProjectState.__init__ - A (3) M 158:4 ProjectState.reload_models - A (3) M 191:4 ProjectState.clone - A (3) M 202:4 ProjectState.clear_delayed_apps_cache - A (3) M 524:4 ModelState.construct_managers - A (3) M 574:4 ModelState.get_index_by_name - A (3) M 580:4 ModelState.get_constraint_by_name - A (3) F 45:0 get_related_models_tuples - A (2) M 91:4 ProjectState.add_model - A (2) M 97:4 ProjectState.remove_model - A (2) M 153:4 ProjectState.reload_model - A (2) M 216:4 ProjectState.from_apps - A (2) M 224:4 ProjectState.__eq__ - A (2) C 228:0 AppConfigStub - A (2) M 317:4 StateApps.clone - A (2) M 329:4 StateApps.register_model - A (2) M 338:4 StateApps.unregister_model - A (2) M 207:4 ProjectState.apps - A (1) M 211:4 ProjectState.concrete_apps - A (1) M 230:4 AppConfigStub.__init__ - A (1) M 239:4 AppConfigStub.import_models - A (1) M 280:4 StateApps.bulk_update - A (1) M 392:4 ModelState.name_lower - A (1) M 537:4 ModelState.clone - A (1) M 586:4 ModelState.__repr__ - A (1) django/db/migrations/operations/models.py M 124:4 CreateModel.reduce - E (39) M 46:4 CreateModel.__init__ - B (9) C 41:0 CreateModel - B (8) M 106:4 CreateModel.references_model - B (8) M 343:4 RenameModel.database_forwards - B (7) M 601:4 AlterOrderWithRespectTo.database_forwards - B (7) M 62:4 CreateModel.deconstruct - B (6) M 316:4 RenameModel.state_forwards - B (6) M 416:4 RenameModel.reduce - A (4) C 433:0 ModelOptionOperation - A (4) M 462:4 AlterModelTable.database_forwards - A (4) M 537:4 AlterTogetherOptionOperation.references_field - A (4) F 13:0 _check_for_duplicates - A (3) C 289:0 RenameModel - A (3) M 434:4 ModelOptionOperation.reduce - A (3) C 576:0 AlterOrderWithRespectTo - A (3) M 622:4 AlterOrderWithRespectTo.references_field - A (3) M 676:4 AlterModelOptions.state_forwards - A (3) M 779:4 AddIndex.describe - A (3) M 804:4 RemoveIndex.state_forwards - A (3) M 886:4 RemoveConstraint.state_forwards - A (3) C 23:0 ModelOperation - A (2) M 34:4 ModelOperation.reduce - A (2) M 89:4 CreateModel.database_forwards - A (2) M 94:4 CreateModel.database_backwards - A (2) M 99:4 CreateModel.describe - A (2) C 250:0 DeleteModel - A (2) M 266:4 DeleteModel.database_forwards - A (2) M 271:4 DeleteModel.database_backwards - A (2) M 403:4 RenameModel.references_model - A (2) C 440:0 AlterModelTable - A (2) M 483:4 AlterModelTable.describe - A (2) C 494:0 AlterTogetherOptionOperation - A (2) M 497:4 AlterTogetherOptionOperation.__init__ - A (2) M 523:4 AlterTogetherOptionOperation.database_forwards - A (2) M 546:4 AlterTogetherOptionOperation.describe - A (2) C 554:0 AlterUniqueTogether - A (2) C 565:0 AlterIndexTogether - A (2) C 639:0 AlterModelOptions - A (2) C 698:0 AlterModelManagers - A (2) C 733:0 IndexOperation - A (2) C 741:0 AddIndex - A (2) M 744:4 AddIndex.__init__ - A (2) M 758:4 AddIndex.database_forwards - A (2) M 763:4 AddIndex.database_backwards - A (2) C 797:0 RemoveIndex - A (2) M 810:4 RemoveIndex.database_forwards - A (2) M 817:4 RemoveIndex.database_backwards - A (2) C 843:0 AddConstraint - A (2) M 855:4 AddConstraint.database_forwards - A (2) M 860:4 AddConstraint.database_backwards - A (2) C 879:0 RemoveConstraint - A (2) M 892:4 RemoveConstraint.database_forwards - A (2) M 899:4 RemoveConstraint.database_backwards - A (2) M 24:4 ModelOperation.__init__ - A (1) M 28:4 ModelOperation.name_lower - A (1) M 31:4 ModelOperation.references_model - A (1) M 79:4 CreateModel.state_forwards - A (1) M 103:4 CreateModel.migration_name_fragment - A (1) M 253:4 DeleteModel.deconstruct - A (1) M 263:4 DeleteModel.state_forwards - A (1) M 276:4 DeleteModel.references_model - A (1) M 281:4 DeleteModel.describe - A (1) M 285:4 DeleteModel.migration_name_fragment - A (1) M 292:4 RenameModel.__init__ - A (1) M 298:4 RenameModel.old_name_lower - A (1) M 302:4 RenameModel.new_name_lower - A (1) M 305:4 RenameModel.deconstruct - A (1) M 394:4 RenameModel.database_backwards - A (1) M 409:4 RenameModel.describe - A (1) M 413:4 RenameModel.migration_name_fragment - A (1) M 443:4 AlterModelTable.__init__ - A (1) M 447:4 AlterModelTable.deconstruct - A (1) M 458:4 AlterModelTable.state_forwards - A (1) M 480:4 AlterModelTable.database_backwards - A (1) M 490:4 AlterModelTable.migration_name_fragment - A (1) M 504:4 AlterTogetherOptionOperation.option_value - A (1) M 507:4 AlterTogetherOptionOperation.deconstruct - A (1) M 518:4 AlterTogetherOptionOperation.state_forwards - A (1) M 534:4 AlterTogetherOptionOperation.database_backwards - A (1) M 550:4 AlterTogetherOptionOperation.migration_name_fragment - A (1) M 561:4 AlterUniqueTogether.__init__ - A (1) M 572:4 AlterIndexTogether.__init__ - A (1) M 581:4 AlterOrderWithRespectTo.__init__ - A (1) M 585:4 AlterOrderWithRespectTo.deconstruct - A (1) M 596:4 AlterOrderWithRespectTo.state_forwards - A (1) M 619:4 AlterOrderWithRespectTo.database_backwards - A (1) M 631:4 AlterOrderWithRespectTo.describe - A (1) M 635:4 AlterOrderWithRespectTo.migration_name_fragment - A (1) M 661:4 AlterModelOptions.__init__ - A (1) M 665:4 AlterModelOptions.deconstruct - A (1) M 684:4 AlterModelOptions.database_forwards - A (1) M 687:4 AlterModelOptions.database_backwards - A (1) M 690:4 AlterModelOptions.describe - A (1) M 694:4 AlterModelOptions.migration_name_fragment - A (1) M 703:4 AlterModelManagers.__init__ - A (1) M 707:4 AlterModelManagers.deconstruct - A (1) M 714:4 AlterModelManagers.state_forwards - A (1) M 719:4 AlterModelManagers.database_forwards - A (1) M 722:4 AlterModelManagers.database_backwards - A (1) M 725:4 AlterModelManagers.describe - A (1) M 729:4 AlterModelManagers.migration_name_fragment - A (1) M 737:4 IndexOperation.model_name_lower - A (1) M 753:4 AddIndex.state_forwards - A (1) M 768:4 AddIndex.deconstruct - A (1) M 793:4 AddIndex.migration_name_fragment - A (1) M 800:4 RemoveIndex.__init__ - A (1) M 824:4 RemoveIndex.deconstruct - A (1) M 835:4 RemoveIndex.describe - A (1) M 839:4 RemoveIndex.migration_name_fragment - A (1) M 846:4 AddConstraint.__init__ - A (1) M 850:4 AddConstraint.state_forwards - A (1) M 865:4 AddConstraint.deconstruct - A (1) M 871:4 AddConstraint.describe - A (1) M 875:4 AddConstraint.migration_name_fragment - A (1) M 882:4 RemoveConstraint.__init__ - A (1) M 906:4 RemoveConstraint.deconstruct - A (1) M 912:4 RemoveConstraint.describe - A (1) M 916:4 RemoveConstraint.migration_name_fragment - A (1) django/db/migrations/operations/fields.py M 301:4 RenameField.state_forwards - C (17) M 39:4 FieldOperation.references_field - B (7) M 123:4 AddField.reduce - B (6) M 383:4 RenameField.reduce - B (6) M 258:4 AlterField.reduce - A (5) M 97:4 AddField.database_forwards - A (4) M 236:4 AlterField.database_forwards - A (4) C 273:0 RenameField - A (4) C 9:0 FieldOperation - A (3) M 29:4 FieldOperation.references_model - A (3) C 64:0 AddField - A (3) M 185:4 RemoveField.reduce - A (3) C 192:0 AlterField - A (3) M 216:4 AlterField.state_forwards - A (3) M 377:4 RenameField.references_field - A (3) M 26:4 FieldOperation.is_same_field_operation - A (2) M 57:4 FieldOperation.reduce - A (2) M 71:4 AddField.deconstruct - A (2) M 85:4 AddField.state_forwards - A (2) M 111:4 AddField.database_backwards - A (2) C 146:0 RemoveField - A (2) M 167:4 RemoveField.database_forwards - A (2) M 172:4 RemoveField.database_backwards - A (2) M 202:4 AlterField.deconstruct - A (2) M 346:4 RenameField.database_forwards - A (2) M 356:4 RenameField.database_backwards - A (2) M 10:4 FieldOperation.__init__ - A (1) M 16:4 FieldOperation.model_name_lower - A (1) M 20:4 FieldOperation.name_lower - A (1) M 23:4 FieldOperation.is_same_model_operation - A (1) M 67:4 AddField.__init__ - A (1) M 116:4 AddField.describe - A (1) M 120:4 AddField.migration_name_fragment - A (1) M 149:4 RemoveField.deconstruct - A (1) M 160:4 RemoveField.state_forwards - A (1) M 178:4 RemoveField.describe - A (1) M 182:4 RemoveField.migration_name_fragment - A (1) M 198:4 AlterField.__init__ - A (1) M 248:4 AlterField.database_backwards - A (1) M 251:4 AlterField.describe - A (1) M 255:4 AlterField.migration_name_fragment - A (1) M 276:4 RenameField.__init__ - A (1) M 282:4 RenameField.old_name_lower - A (1) M 286:4 RenameField.new_name_lower - A (1) M 289:4 RenameField.deconstruct - A (1) M 366:4 RenameField.describe - A (1) M 370:4 RenameField.migration_name_fragment - A (1) django/db/migrations/operations/utils.py F 36:0 field_references - C (16) F 6:0 resolve_relation - B (7) F 85:0 get_references - A (4) F 100:0 field_is_referenced - A (1) django/db/migrations/operations/special.py M 116:4 RunSQL._run_sql - B (7) M 140:4 RunPython.__init__ - A (5) C 63:0 RunSQL - A (4) M 79:4 RunSQL.deconstruct - A (4) M 156:4 RunPython.deconstruct - A (4) C 6:0 SeparateDatabaseAndState - A (3) M 16:4 SeparateDatabaseAndState.__init__ - A (3) M 20:4 SeparateDatabaseAndState.deconstruct - A (3) M 44:4 SeparateDatabaseAndState.database_backwards - A (3) M 72:4 RunSQL.__init__ - A (3) M 107:4 RunSQL.database_backwards - A (3) C 133:0 RunPython - A (3) M 192:4 RunPython.database_backwards - A (3) M 32:4 SeparateDatabaseAndState.state_forwards - A (2) M 36:4 SeparateDatabaseAndState.database_forwards - A (2) M 99:4 RunSQL.state_forwards - A (2) M 103:4 RunSQL.database_forwards - A (2) M 181:4 RunPython.database_forwards - A (2) M 59:4 SeparateDatabaseAndState.describe - A (1) M 96:4 RunSQL.reversible - A (1) M 113:4 RunSQL.describe - A (1) M 173:4 RunPython.reversible - A (1) M 176:4 RunPython.state_forwards - A (1) M 198:4 RunPython.describe - A (1) M 202:4 RunPython.noop - A (1) django/db/migrations/operations/base.py M 123:4 Operation.reduce - A (3) C 4:0 Operation - A (2) M 111:4 Operation.allow_migrate_model - A (2) M 135:4 Operation.__repr__ - A (2) M 36:4 Operation.__new__ - A (1) M 42:4 Operation.deconstruct - A (1) M 54:4 Operation.state_forwards - A (1) M 61:4 Operation.database_forwards - A (1) M 68:4 Operation.database_backwards - A (1) M 76:4 Operation.describe - A (1) M 83:4 Operation.migration_name_fragment - A (1) M 90:4 Operation.references_model - A (1) M 102:4 Operation.references_field - A (1) django/db/backends/ddl_references.py M 70:4 TableColumns.rename_column_references - A (4) M 222:4 Expressions.rename_column_references - A (4) C 60:0 TableColumns - A (3) C 77:0 Columns - A (3) C 111:0 IndexColumns - A (3) C 166:0 Statement - A (3) M 178:4 Statement.references_table - A (3) M 184:4 Statement.references_column - A (3) M 190:4 Statement.rename_table_references - A (3) M 195:4 Statement.rename_column_references - A (3) C 204:0 Expressions - A (3) M 212:4 Expressions.rename_table_references - A (3) C 8:0 Reference - A (2) C 42:0 Table - A (2) M 52:4 Table.rename_table_references - A (2) M 67:4 TableColumns.references_column - A (2) M 85:4 Columns.__str__ - A (2) C 99:0 IndexName - A (2) M 116:4 IndexColumns.__str__ - A (2) C 132:0 ForeignKeyName - A (2) M 141:4 ForeignKeyName.references_table - A (2) M 144:4 ForeignKeyName.references_column - A (2) M 205:4 Expressions.__init__ - A (2) M 11:4 Reference.references_table - A (1) M 17:4 Reference.references_column - A (1) M 23:4 Reference.rename_table_references - A (1) M 29:4 Reference.rename_column_references - A (1) M 35:4 Reference.__repr__ - A (1) M 38:4 Reference.__str__ - A (1) M 45:4 Table.__init__ - A (1) M 49:4 Table.references_table - A (1) M 56:4 Table.__str__ - A (1) M 63:4 TableColumns.__init__ - A (1) M 80:4 Columns.__init__ - A (1) M 102:4 IndexName.__init__ - A (1) M 107:4 IndexName.__str__ - A (1) M 112:4 IndexColumns.__init__ - A (1) M 135:4 ForeignKeyName.__init__ - A (1) M 150:4 ForeignKeyName.rename_table_references - A (1) M 154:4 ForeignKeyName.rename_column_references - A (1) M 158:4 ForeignKeyName.__str__ - A (1) M 174:4 Statement.__init__ - A (1) M 200:4 Statement.__str__ - A (1) M 233:4 Expressions.__str__ - A (1) django/db/backends/utils.py M 47:4 CursorWrapper.callproc - B (7) F 151:0 typecast_timestamp - B (6) M 105:4 CursorDebugWrapper.debug_sql - A (5) F 196:0 truncate_name - A (4) F 224:0 format_number - A (4) F 140:0 typecast_time - A (3) F 242:0 strip_quotes - A (3) C 14:0 CursorWrapper - A (3) C 92:0 CursorDebugWrapper - A (3) F 136:0 typecast_date - A (2) F 182:0 split_identifier - A (2) F 213:0 names_digest - A (2) M 21:4 CursorWrapper.__getattr__ - A (2) M 35:4 CursorWrapper.__exit__ - A (2) M 71:4 CursorWrapper._execute_with_wrappers - A (2) M 77:4 CursorWrapper._execute - A (2) M 15:4 CursorWrapper.__init__ - A (1) M 28:4 CursorWrapper.__iter__ - A (1) M 32:4 CursorWrapper.__enter__ - A (1) M 65:4 CursorWrapper.execute - A (1) M 68:4 CursorWrapper.executemany - A (1) M 86:4 CursorWrapper._executemany - A (1) M 96:4 CursorDebugWrapper.execute - A (1) M 100:4 CursorDebugWrapper.executemany - A (1) django/db/backends/postgresql/creation.py M 36:4 DatabaseCreation._execute_create_test_db - B (6) C 9:0 DatabaseCreation - A (4) M 14:4 DatabaseCreation._get_database_create_suffix - A (4) M 53:4 DatabaseCreation._clone_test_db - A (4) M 22:4 DatabaseCreation.sql_table_creation_suffix - A (2) M 11:4 DatabaseCreation._quote_name - A (1) M 32:4 DatabaseCreation._database_exists - A (1) django/db/backends/postgresql/client.py M 10:4 DatabaseClient.settings_to_cmd_args_env - C (13) C 6:0 DatabaseClient - B (8) M 53:4 DatabaseClient.runshell - A (1) django/db/backends/postgresql/features.py C 8:0 DatabaseFeatures - A (2) M 73:4 DatabaseFeatures.introspected_field_types - A (1) M 82:4 DatabaseFeatures.is_postgresql_11 - A (1) M 86:4 DatabaseFeatures.is_postgresql_12 - A (1) M 90:4 DatabaseFeatures.is_postgresql_13 - A (1) django/db/backends/postgresql/operations.py M 260:4 DatabaseOperations.explain_query_prefix - B (7) M 89:4 DatabaseOperations.lookup_cast - A (5) M 122:4 DatabaseOperations.sql_flush - A (5) M 29:4 DatabaseOperations.date_extract_sql - A (4) M 160:4 DatabaseOperations.sequence_reset_sql - A (4) M 205:4 DatabaseOperations.distinct_sql - A (4) C 7:0 DatabaseOperations - A (3) M 46:4 DatabaseOperations._prepare_tzname_delta - A (3) M 53:4 DatabaseOperations._convert_field_to_tz - A (3) M 114:4 DatabaseOperations.quote_name - A (3) M 138:4 DatabaseOperations.sequence_reset_by_name_sql - A (3) M 219:4 DatabaseOperations.return_insert_columns - A (3) M 230:4 DatabaseOperations.bulk_insert_sql - A (3) M 16:4 DatabaseOperations.unification_cast_sql - A (2) M 154:4 DatabaseOperations.tablespace_sql - A (2) M 212:4 DatabaseOperations.last_executed_query - A (2) M 247:4 DatabaseOperations.adapt_ipaddressfield_value - A (2) M 252:4 DatabaseOperations.subtract_temporals - A (2) M 274:4 DatabaseOperations.ignore_conflicts_suffix_sql - A (2) M 41:4 DatabaseOperations.date_trunc_sql - A (1) M 58:4 DatabaseOperations.datetime_cast_date_sql - A (1) M 62:4 DatabaseOperations.datetime_cast_time_sql - A (1) M 66:4 DatabaseOperations.datetime_extract_sql - A (1) M 70:4 DatabaseOperations.datetime_trunc_sql - A (1) M 75:4 DatabaseOperations.time_trunc_sql - A (1) M 79:4 DatabaseOperations.deferrable_sql - A (1) M 82:4 DatabaseOperations.fetch_returned_insert_rows - A (1) M 108:4 DatabaseOperations.no_limit_value - A (1) M 111:4 DatabaseOperations.prepare_sql_script - A (1) M 119:4 DatabaseOperations.set_time_zone_sql - A (1) M 189:4 DatabaseOperations.prep_for_iexact_query - A (1) M 192:4 DatabaseOperations.max_name_length - A (1) M 235:4 DatabaseOperations.adapt_datefield_value - A (1) M 238:4 DatabaseOperations.adapt_datetimefield_value - A (1) M 241:4 DatabaseOperations.adapt_timefield_value - A (1) M 244:4 DatabaseOperations.adapt_decimalfield_value - A (1) django/db/backends/postgresql/introspection.py M 142:4 DatabaseIntrospection.get_constraints - B (10) M 36:4 DatabaseIntrospection.get_field_type - B (6) C 7:0 DatabaseIntrospection - A (5) M 47:4 DatabaseIntrospection.get_table_list - A (3) M 60:4 DatabaseIntrospection.get_table_description - A (3) M 100:4 DatabaseIntrospection.get_sequences - A (2) M 119:4 DatabaseIntrospection.get_relations - A (2) M 126:4 DatabaseIntrospection.get_key_columns - A (1) django/db/backends/postgresql/base.py M 152:4 DatabaseWrapper.get_connection_params - C (11) M 306:4 DatabaseWrapper._nodb_cursor - B (6) C 65:0 DatabaseWrapper - A (4) M 198:4 DatabaseWrapper.get_new_connection - A (4) M 221:4 DatabaseWrapper.ensure_timezone - A (4) M 232:4 DatabaseWrapper.init_connection_state - A (3) M 242:4 DatabaseWrapper.create_cursor - A (3) M 256:4 DatabaseWrapper.chunked_cursor - A (3) M 295:4 DatabaseWrapper.is_usable - A (3) C 343:0 CursorDebugWrapper - A (2) F 32:0 psycopg2_version - A (1) M 252:4 DatabaseWrapper.tzinfo_factory - A (1) M 282:4 DatabaseWrapper._set_autocommit - A (1) M 286:4 DatabaseWrapper.check_constraints - A (1) M 335:4 DatabaseWrapper.pg_version - A (1) M 339:4 DatabaseWrapper.make_debug_cursor - A (1) M 344:4 CursorDebugWrapper.copy_expert - A (1) M 348:4 CursorDebugWrapper.copy_to - A (1) django/db/backends/postgresql/schema.py M 184:4 DatabaseSchemaEditor._alter_field - C (18) M 69:4 DatabaseSchemaEditor._create_like_index_sql - B (7) M 101:4 DatabaseSchemaEditor._alter_column_type_sql - B (7) C 8:0 DatabaseSchemaEditor - A (5) M 38:4 DatabaseSchemaEditor.quote_value - A (3) M 47:4 DatabaseSchemaEditor._field_indexes_sql - A (2) M 54:4 DatabaseSchemaEditor._field_data_type - A (2) M 62:4 DatabaseSchemaEditor._field_base_data_types - A (2) M 212:4 DatabaseSchemaEditor._index_columns - A (2) M 223:4 DatabaseSchemaEditor._delete_index_sql - A (2) M 227:4 DatabaseSchemaEditor._create_index_sql - A (2) M 217:4 DatabaseSchemaEditor.add_index - A (1) M 220:4 DatabaseSchemaEditor.remove_index - A (1) django/db/backends/dummy/features.py C 4:0 DummyDatabaseFeatures - A (1) django/db/backends/dummy/base.py C 50:0 DatabaseWrapper - A (2) F 19:0 complain - A (1) F 25:0 ignore - A (1) C 29:0 DatabaseOperations - A (1) C 33:0 DatabaseClient - A (1) C 37:0 DatabaseCreation - A (1) C 42:0 DatabaseIntrospection - A (1) M 72:4 DatabaseWrapper.is_usable - A (1) django/db/backends/oracle/functions.py C 4:0 IntervalToSeconds - A (3) C 17:0 SecondsToInterval - A (3) M 13:4 IntervalToSeconds.__init__ - A (2) M 21:4 SecondsToInterval.__init__ - A (2) django/db/backends/oracle/creation.py M 30:4 DatabaseCreation._create_test_db - D (22) M 130:4 DatabaseCreation._handle_objects_preventing_db_destruction - B (9) M 220:4 DatabaseCreation._create_test_user - B (8) M 271:4 DatabaseCreation._execute_statements - B (6) M 167:4 DatabaseCreation._destroy_test_db - A (5) M 283:4 DatabaseCreation._execute_allow_fail_statements - A (5) M 187:4 DatabaseCreation._execute_test_db_creation - A (4) C 12:0 DatabaseCreation - A (3) M 15:4 DatabaseCreation._maindb_connection - A (3) M 317:4 DatabaseCreation._test_settings_get - A (3) M 340:4 DatabaseCreation._test_database_passwd - A (3) M 253:4 DatabaseCreation._execute_test_db_destruction - A (2) M 262:4 DatabaseCreation._destroy_test_user - A (2) M 102:4 DatabaseCreation._switch_to_test_user - A (1) M 122:4 DatabaseCreation.set_as_test_mirror - A (1) M 300:4 DatabaseCreation._get_test_db_params - A (1) M 328:4 DatabaseCreation._test_database_name - A (1) M 331:4 DatabaseCreation._test_database_create - A (1) M 334:4 DatabaseCreation._test_user_create - A (1) M 337:4 DatabaseCreation._test_database_user - A (1) M 347:4 DatabaseCreation._test_database_tblspace - A (1) M 350:4 DatabaseCreation._test_database_tblspace_tmp - A (1) M 355:4 DatabaseCreation._test_database_tblspace_datafile - A (1) M 359:4 DatabaseCreation._test_database_tblspace_tmp_datafile - A (1) M 363:4 DatabaseCreation._test_database_tblspace_maxsize - A (1) M 366:4 DatabaseCreation._test_database_tblspace_tmp_maxsize - A (1) M 369:4 DatabaseCreation._test_database_tblspace_size - A (1) M 372:4 DatabaseCreation._test_database_tblspace_tmp_size - A (1) M 375:4 DatabaseCreation._test_database_tblspace_extsize - A (1) M 378:4 DatabaseCreation._test_database_tblspace_tmp_extsize - A (1) M 381:4 DatabaseCreation._test_database_oracle_managed_files - A (1) M 384:4 DatabaseCreation._get_test_db_name - A (1) M 392:4 DatabaseCreation.test_db_signature - A (1) django/db/backends/oracle/client.py C 6:0 DatabaseClient - A (3) M 21:4 DatabaseClient.settings_to_cmd_args_env - A (2) M 11:4 DatabaseClient.connect_string - A (1) django/db/backends/oracle/features.py C 6:0 DatabaseFeatures - A (3) M 110:4 DatabaseFeatures.supports_collation_on_charfield - A (3) M 98:4 DatabaseFeatures.introspected_field_types - A (1) django/db/backends/oracle/operations.py M 406:4 DatabaseOperations.sql_flush - C (12) M 178:4 DatabaseOperations.get_db_converters - C (11) M 561:4 DatabaseOperations.combine_expression - B (8) M 146:4 DatabaseOperations.datetime_trunc_sql - B (7) M 75:4 DatabaseOperations.date_extract_sql - B (6) M 631:4 DatabaseOperations.conditional_expression_supported_in_where_clause - B (6) M 117:4 DatabaseOperations._convert_field_to_tz - A (5) M 280:4 DatabaseOperations.limit_offset_sql - A (5) M 287:4 DatabaseOperations.last_executed_query - A (5) M 514:4 DatabaseOperations.adapt_datetimefield_value - A (5) M 540:4 DatabaseOperations.adapt_timefield_value - A (5) M 596:4 DatabaseOperations.bulk_insert_sql - A (5) C 21:0 DatabaseOperations - A (4) M 92:4 DatabaseOperations.date_trunc_sql - A (4) M 165:4 DatabaseOperations.time_trunc_sql - A (4) M 271:4 DatabaseOperations.field_cast_sql - A (4) M 307:4 DatabaseOperations.lookup_cast - A (4) M 475:4 DatabaseOperations.sequence_reset_sql - A (4) M 110:4 DatabaseOperations._prepare_tzname_delta - A (3) M 257:4 DatabaseOperations.fetch_returned_insert_columns - A (3) M 331:4 DatabaseOperations.quote_name - A (3) M 351:4 DatabaseOperations.return_insert_columns - A (3) M 459:4 DatabaseOperations.sequence_reset_by_name_sql - A (3) M 207:4 DatabaseOperations.convert_textfield_value - A (2) M 212:4 DatabaseOperations.convert_binaryfield_value - A (2) M 217:4 DatabaseOperations.convert_booleanfield_value - A (2) M 226:4 DatabaseOperations.convert_datetimefield_value - A (2) M 231:4 DatabaseOperations.convert_datefield_value - A (2) M 236:4 DatabaseOperations.convert_timefield_value - A (2) M 241:4 DatabaseOperations.convert_uuidfield_value - A (2) M 247:4 DatabaseOperations.convert_empty_string - A (2) M 251:4 DatabaseOperations.convert_empty_bytes - A (2) M 326:4 DatabaseOperations.process_clob - A (2) M 344:4 DatabaseOperations.regex_lookup - A (2) M 367:4 DatabaseOperations.__foreign_key_constraints - A (2) M 499:4 DatabaseOperations.tablespace_sql - A (2) M 587:4 DatabaseOperations._get_sequence_name - A (2) M 617:4 DatabaseOperations.subtract_temporals - A (2) M 625:4 DatabaseOperations.bulk_batch_size - A (2) M 72:4 DatabaseOperations.cache_key_culling_sql - A (1) M 133:4 DatabaseOperations.datetime_cast_date_sql - A (1) M 137:4 DatabaseOperations.datetime_cast_time_sql - A (1) M 142:4 DatabaseOperations.datetime_extract_sql - A (1) M 254:4 DatabaseOperations.deferrable_sql - A (1) M 277:4 DatabaseOperations.no_limit_value - A (1) M 302:4 DatabaseOperations.last_insert_id - A (1) M 314:4 DatabaseOperations.max_in_list_size - A (1) M 317:4 DatabaseOperations.max_name_length - A (1) M 320:4 DatabaseOperations.pk_default_value - A (1) M 323:4 DatabaseOperations.prep_for_iexact_query - A (1) M 401:4 DatabaseOperations._foreign_key_constraints - A (1) M 496:4 DatabaseOperations.start_transaction_sql - A (1) M 505:4 DatabaseOperations.adapt_datefield_value - A (1) M 558:4 DatabaseOperations.adapt_decimalfield_value - A (1) M 579:4 DatabaseOperations._get_no_autofield_sequence_name - A (1) django/db/backends/oracle/utils.py F 86:0 dsn - A (3) C 6:0 InsertVar - A (2) C 41:0 Oracle_datetime - A (2) M 28:4 InsertVar.__init__ - A (1) M 33:4 InsertVar.bind_parameter - A (1) M 37:4 InsertVar.get_value - A (1) M 49:4 Oracle_datetime.from_datetime - A (1) C 56:0 BulkInsertMapper - A (1) django/db/backends/oracle/introspection.py M 51:4 DatabaseIntrospection.get_field_type - C (12) M 90:4 DatabaseIntrospection.get_table_description - B (6) C 14:0 DatabaseIntrospection - A (5) M 235:4 DatabaseIntrospection.get_constraints - A (5) M 153:4 DatabaseIntrospection.get_sequences - A (4) M 205:4 DatabaseIntrospection.get_key_columns - A (3) M 19:4 DatabaseIntrospection.data_types_reverse - A (2) M 72:4 DatabaseIntrospection.get_table_list - A (2) M 184:4 DatabaseIntrospection.get_relations - A (2) M 219:4 DatabaseIntrospection.get_primary_key_column - A (2) M 149:4 DatabaseIntrospection.identifier_converter - A (1) django/db/backends/oracle/base.py C 323:0 OracleParam - C (13) M 333:4 OracleParam.__init__ - C (12) M 483:4 FormatStylePlaceholderCursor._fix_for_params - C (12) M 456:4 FormatStylePlaceholderCursor._guess_input_sizes - B (10) F 64:0 wrap_oracle_errors - B (7) M 234:4 DatabaseWrapper.init_connection_state - B (7) M 418:4 FormatStylePlaceholderCursor._output_type_handler - A (5) F 21:0 _setup_environment - A (4) C 393:0 FormatStylePlaceholderCursor - A (4) M 450:4 FormatStylePlaceholderCursor._format_params - A (4) M 476:4 FormatStylePlaceholderCursor._param_generator - A (4) M 523:4 FormatStylePlaceholderCursor.executemany - A (4) C 89:0 _UninitializedOperatorsDescriptor - A (3) C 102:0 DatabaseWrapper - A (3) M 305:4 DatabaseWrapper.is_usable - A (3) M 91:4 _UninitializedOperatorsDescriptor.__get__ - A (2) M 219:4 DatabaseWrapper.get_connection_params - A (2) M 278:4 DatabaseWrapper._commit - A (2) M 285:4 DatabaseWrapper._savepoint_commit - A (2) M 314:4 DatabaseWrapper.cx_oracle_version - A (2) M 318:4 DatabaseWrapper.oracle_version - A (2) C 369:0 VariableWrapper - A (2) M 386:4 VariableWrapper.__setattr__ - A (2) M 406:4 FormatStylePlaceholderCursor._output_number_converter - A (2) M 410:4 FormatStylePlaceholderCursor._get_decimal_converter - A (2) M 537:4 FormatStylePlaceholderCursor.close - A (2) M 214:4 DatabaseWrapper.__init__ - A (1) M 226:4 DatabaseWrapper.get_new_connection - A (1) M 275:4 DatabaseWrapper.create_cursor - A (1) M 292:4 DatabaseWrapper._set_autocommit - A (1) M 296:4 DatabaseWrapper.check_constraints - A (1) M 377:4 VariableWrapper.__init__ - A (1) M 380:4 VariableWrapper.bind_parameter - A (1) M 383:4 VariableWrapper.__getattr__ - A (1) M 401:4 FormatStylePlaceholderCursor.__init__ - A (1) M 517:4 FormatStylePlaceholderCursor.execute - A (1) M 544:4 FormatStylePlaceholderCursor.var - A (1) M 547:4 FormatStylePlaceholderCursor.arrayvar - A (1) M 550:4 FormatStylePlaceholderCursor.__getattr__ - A (1) M 553:4 FormatStylePlaceholderCursor.__iter__ - A (1) django/db/backends/oracle/schema.py M 60:4 DatabaseSchemaEditor.alter_field - B (7) M 25:4 DatabaseSchemaEditor.quote_value - B (6) M 82:4 DatabaseSchemaEditor._alter_field_type_workaround - B (6) M 128:4 DatabaseSchemaEditor._alter_column_type_sql - A (4) C 9:0 DatabaseSchemaEditor - A (3) M 139:4 DatabaseSchemaEditor.normalize_name - A (3) M 157:4 DatabaseSchemaEditor._field_should_be_indexed - A (3) M 37:4 DatabaseSchemaEditor.remove_field - A (2) M 164:4 DatabaseSchemaEditor._unique_should_be_added - A (2) M 170:4 DatabaseSchemaEditor._is_identity_column - A (2) M 195:4 DatabaseSchemaEditor._alter_column_collation_sql - A (2) M 44:4 DatabaseSchemaEditor.delete_model - A (1) M 149:4 DatabaseSchemaEditor._generate_temp_name - A (1) M 154:4 DatabaseSchemaEditor.prepare_default - A (1) M 182:4 DatabaseSchemaEditor._drop_identity - A (1) M 188:4 DatabaseSchemaEditor._get_default_collation - A (1) django/db/backends/oracle/validation.py C 5:0 DatabaseValidation - A (4) M 6:4 DatabaseValidation.check_field_type - A (3) django/db/backends/sqlite3/creation.py M 23:4 DatabaseCreation._create_test_db - B (9) M 60:4 DatabaseCreation._clone_test_db - B (7) C 9:0 DatabaseCreation - A (5) M 12:4 DatabaseCreation.is_in_memory_db - A (3) M 17:4 DatabaseCreation._get_test_db_name - A (3) M 84:4 DatabaseCreation._destroy_test_db - A (3) M 51:4 DatabaseCreation.get_test_db_clone_settings - A (2) M 89:4 DatabaseCreation.test_db_signature - A (2) django/db/backends/sqlite3/client.py C 4:0 DatabaseClient - A (2) M 8:4 DatabaseClient.settings_to_cmd_args_env - A (1) django/db/backends/sqlite3/features.py C 12:0 DatabaseFeatures - A (3) M 54:4 DatabaseFeatures.django_test_skips - A (3) M 85:4 DatabaseFeatures.supports_atomic_references_rename - A (3) M 103:4 DatabaseFeatures.supports_json_field - A (2) M 93:4 DatabaseFeatures.introspected_field_types - A (1) django/db/backends/sqlite3/operations.py M 40:4 DatabaseOperations.check_expression_support - B (9) M 203:4 DatabaseOperations.sql_flush - B (7) M 267:4 DatabaseOperations.get_db_converters - B (7) M 236:4 DatabaseOperations.adapt_datetimefield_value - A (5) M 284:4 DatabaseOperations.convert_datetimefield_value - A (5) M 253:4 DatabaseOperations.adapt_timefield_value - A (4) C 17:0 DatabaseOperations - A (3) M 25:4 DatabaseOperations.bulk_batch_size - A (3) M 94:4 DatabaseOperations._convert_tznames_to_sql - A (3) M 125:4 DatabaseOperations._quote_params_for_last_executed_query - A (3) M 152:4 DatabaseOperations.last_executed_query - A (3) M 170:4 DatabaseOperations.quote_name - A (3) M 218:4 DatabaseOperations.sequence_reset_by_name_sql - A (3) M 292:4 DatabaseOperations.convert_datefield_value - A (3) M 298:4 DatabaseOperations.convert_timefield_value - A (3) M 334:4 DatabaseOperations.combine_expression - A (3) M 343:4 DatabaseOperations.combine_duration_expression - A (3) M 178:4 DatabaseOperations.__references_graph - A (2) M 304:4 DatabaseOperations.get_decimalfield_converter - A (2) M 320:4 DatabaseOperations.convert_uuidfield_value - A (2) M 325:4 DatabaseOperations.convert_booleanfield_value - A (2) M 328:4 DatabaseOperations.bulk_insert_sql - A (2) M 355:4 DatabaseOperations.subtract_temporals - A (2) M 363:4 DatabaseOperations.insert_statement - A (2) M 68:4 DatabaseOperations.date_extract_sql - A (1) M 76:4 DatabaseOperations.format_for_duration_arithmetic - A (1) M 80:4 DatabaseOperations.date_trunc_sql - A (1) M 87:4 DatabaseOperations.time_trunc_sql - A (1) M 99:4 DatabaseOperations.datetime_cast_date_sql - A (1) M 104:4 DatabaseOperations.datetime_cast_time_sql - A (1) M 109:4 DatabaseOperations.datetime_extract_sql - A (1) M 114:4 DatabaseOperations.datetime_trunc_sql - A (1) M 119:4 DatabaseOperations.time_extract_sql - A (1) M 122:4 DatabaseOperations.pk_default_value - A (1) M 175:4 DatabaseOperations.no_limit_value - A (1) M 198:4 DatabaseOperations._references_graph - A (1) M 351:4 DatabaseOperations.integer_field_range - A (1) django/db/backends/sqlite3/introspection.py M 241:4 DatabaseIntrospection._parse_column_or_constraint_definition - E (33) M 361:4 DatabaseIntrospection.get_constraints - C (13) M 331:4 DatabaseIntrospection._parse_table_constraints - C (11) M 115:4 DatabaseIntrospection.get_relations - B (10) C 57:0 DatabaseIntrospection - B (9) M 202:4 DatabaseIntrospection.get_primary_key_column - B (6) M 448:4 DatabaseIntrospection._get_column_collations - B (6) M 80:4 DatabaseIntrospection.get_table_description - A (5) M 173:4 DatabaseIntrospection.get_key_columns - A (5) M 440:4 DatabaseIntrospection._get_index_columns_orders - A (5) M 60:4 DatabaseIntrospection.get_field_type - A (4) F 17:0 get_field_size - A (2) C 26:0 FlexibleFieldLookupDict - A (2) M 70:4 DatabaseIntrospection.get_table_list - A (2) M 225:4 DatabaseIntrospection._get_foreign_key_constraints - A (2) M 52:4 FlexibleFieldLookupDict.__getitem__ - A (1) M 111:4 DatabaseIntrospection.get_sequences - A (1) django/db/backends/sqlite3/base.py F 517:0 _sqlite_datetime_trunc - B (10) M 311:4 DatabaseWrapper.check_constraints - B (10) F 426:0 _sqlite_datetime_parse - B (9) F 448:0 _sqlite_date_trunc - B (7) F 466:0 _sqlite_time_trunc - B (7) F 499:0 _sqlite_datetime_extract - B (7) F 552:0 _sqlite_format_dtdelta - A (5) M 175:4 DatabaseWrapper.get_connection_params - A (4) F 541:0 _sqlite_time_extract - A (3) C 82:0 DatabaseWrapper - A (3) F 65:0 check_sqlite_version - A (2) F 485:0 _sqlite_datetime_cast_date - A (2) F 492:0 _sqlite_datetime_cast_time - A (2) F 601:0 _sqlite_lpad - A (2) M 270:4 DatabaseWrapper.close - A (2) M 286:4 DatabaseWrapper._set_autocommit - A (2) C 406:0 SQLiteCursorWrapper - A (2) M 412:4 SQLiteCursorWrapper.execute - A (2) F 37:0 decoder - A (1) F 44:0 none_guard - A (1) F 57:0 list_aggregate - A (1) F 573:0 _sqlite_time_diff - A (1) F 589:0 _sqlite_timestamp_diff - A (1) F 596:0 _sqlite_regexp - A (1) F 608:0 _sqlite_rpad - A (1) M 204:4 DatabaseWrapper.get_new_connection - A (1) M 263:4 DatabaseWrapper.init_connection_state - A (1) M 266:4 DatabaseWrapper.create_cursor - A (1) M 278:4 DatabaseWrapper._savepoint_allowed - A (1) M 298:4 DatabaseWrapper.disable_constraint_checking - A (1) M 307:4 DatabaseWrapper.enable_constraint_checking - A (1) M 387:4 DatabaseWrapper.is_usable - A (1) M 390:4 DatabaseWrapper._start_transaction_under_autocommit - A (1) M 399:4 DatabaseWrapper.is_in_memory_db - A (1) M 418:4 SQLiteCursorWrapper.executemany - A (1) M 422:4 SQLiteCursorWrapper.convert_query - A (1) django/db/backends/sqlite3/schema.py M 142:4 DatabaseSchemaEditor._remake_table - D (29) M 350:4 DatabaseSchemaEditor._alter_field - D (21) M 39:4 DatabaseSchemaEditor.quote_value - B (8) M 67:4 DatabaseSchemaEditor._is_referenced_by_fk_constraint - B (8) C 13:0 DatabaseSchemaEditor - B (7) M 101:4 DatabaseSchemaEditor.alter_field - B (6) M 86:4 DatabaseSchemaEditor.alter_db_table - A (5) M 309:4 DatabaseSchemaEditor.delete_model - A (5) M 332:4 DatabaseSchemaEditor.remove_field - A (4) M 421:4 DatabaseSchemaEditor.add_constraint - A (4) M 429:4 DatabaseSchemaEditor.remove_constraint - A (4) M 322:4 DatabaseSchemaEditor.add_field - A (3) M 21:4 DatabaseSchemaEditor.__enter__ - A (2) M 386:4 DatabaseSchemaEditor._alter_many_to_many - A (2) M 34:4 DatabaseSchemaEditor.__exit__ - A (1) M 437:4 DatabaseSchemaEditor._collate_sql - A (1) django/db/backends/mysql/compiler.py C 17:0 SQLDeleteCompiler - A (5) C 41:0 SQLUpdateCompiler - A (5) M 18:4 SQLDeleteCompiler.as_sql - A (4) M 42:4 SQLUpdateCompiler.as_sql - A (4) C 5:0 SQLCompiler - A (3) M 6:4 SQLCompiler.as_subquery_condition - A (2) C 13:0 SQLInsertCompiler - A (1) C 61:0 SQLAggregateCompiler - A (1) django/db/backends/mysql/creation.py M 32:4 DatabaseCreation._clone_test_db - A (5) C 10:0 DatabaseCreation - A (4) M 21:4 DatabaseCreation._execute_create_test_db - A (4) M 12:4 DatabaseCreation.sql_table_creation_suffix - A (3) M 58:4 DatabaseCreation._clone_db - A (2) django/db/backends/mysql/client.py C 4:0 DatabaseClient - C (13) M 8:4 DatabaseClient.settings_to_cmd_args_env - C (12) django/db/backends/mysql/features.py M 57:4 DatabaseFeatures.django_test_skips - B (7) M 169:4 DatabaseFeatures.can_introspect_check_constraints - A (4) C 7:0 DatabaseFeatures - A (3) M 194:4 DatabaseFeatures.supported_explain_formats - A (3) M 225:4 DatabaseFeatures.can_introspect_json_field - A (3) M 120:4 DatabaseFeatures.update_can_self_select - A (2) M 139:4 DatabaseFeatures.can_return_columns_from_insert - A (2) M 153:4 DatabaseFeatures.supports_over_clause - A (2) M 161:4 DatabaseFeatures.supports_column_check_constraints - A (2) M 176:4 DatabaseFeatures.has_select_for_update_skip_locked - A (2) M 180:4 DatabaseFeatures.has_select_for_update_nowait - A (2) M 186:4 DatabaseFeatures.has_select_for_update_of - A (2) M 190:4 DatabaseFeatures.supports_explain_analyze - A (2) M 219:4 DatabaseFeatures.supports_json_field - A (2) M 231:4 DatabaseFeatures.supports_index_column_ordering - A (2) M 238:4 DatabaseFeatures.supports_expression_indexes - A (2) M 107:4 DatabaseFeatures._mysql_storage_engine - A (1) M 112:4 DatabaseFeatures.allows_auto_pk_0 - A (1) M 124:4 DatabaseFeatures.can_introspect_foreign_keys - A (1) M 129:4 DatabaseFeatures.introspected_field_types - A (1) M 145:4 DatabaseFeatures.has_zoneinfo_database - A (1) M 149:4 DatabaseFeatures.is_sql_auto_is_null_enabled - A (1) M 203:4 DatabaseFeatures.supports_transactions - A (1) M 210:4 DatabaseFeatures.ignores_table_name_case - A (1) M 214:4 DatabaseFeatures.supports_default_in_lead_lag - A (1) django/db/backends/mysql/operations.py M 338:4 DatabaseOperations.explain_query_prefix - C (11) M 106:4 DatabaseOperations.datetime_trunc_sql - B (6) M 37:4 DatabaseOperations.date_extract_sql - A (5) M 192:4 DatabaseOperations.sql_flush - A (5) M 237:4 DatabaseOperations.adapt_datetimefield_value - A (5) M 278:4 DatabaseOperations.combine_expression - A (5) M 291:4 DatabaseOperations.get_db_converters - A (5) M 355:4 DatabaseOperations.regex_lookup - A (5) C 9:0 DatabaseOperations - A (4) M 58:4 DatabaseOperations.date_trunc_sql - A (4) M 85:4 DatabaseOperations._convert_field_to_tz - A (4) M 253:4 DatabaseOperations.adapt_timefield_value - A (4) M 369:4 DatabaseOperations.lookup_cast - A (4) M 78:4 DatabaseOperations._prepare_tzname_delta - A (3) M 174:4 DatabaseOperations.quote_name - A (3) M 179:4 DatabaseOperations.return_insert_columns - A (3) M 229:4 DatabaseOperations.validate_autopk_value - A (3) M 273:4 DatabaseOperations.bulk_insert_sql - A (3) M 318:4 DatabaseOperations.binary_placeholder_sql - A (3) M 321:4 DatabaseOperations.subtract_temporals - A (3) M 132:4 DatabaseOperations.time_trunc_sql - A (2) M 219:4 DatabaseOperations.sequence_reset_by_name_sql - A (2) M 303:4 DatabaseOperations.convert_booleanfield_value - A (2) M 308:4 DatabaseOperations.convert_datetimefield_value - A (2) M 313:4 DatabaseOperations.convert_uuidfield_value - A (2) M 366:4 DatabaseOperations.insert_statement - A (2) M 94:4 DatabaseOperations.datetime_cast_date_sql - A (1) M 98:4 DatabaseOperations.datetime_cast_time_sql - A (1) M 102:4 DatabaseOperations.datetime_extract_sql - A (1) M 145:4 DatabaseOperations.fetch_returned_insert_rows - A (1) M 152:4 DatabaseOperations.format_for_duration_arithmetic - A (1) M 155:4 DatabaseOperations.force_no_ordering - A (1) M 163:4 DatabaseOperations.last_executed_query - A (1) M 170:4 DatabaseOperations.no_limit_value - A (1) M 267:4 DatabaseOperations.max_name_length - A (1) M 270:4 DatabaseOperations.pk_default_value - A (1) django/db/backends/mysql/introspection.py M 205:4 DatabaseIntrospection.get_constraints - C (18) M 45:4 DatabaseIntrospection.get_field_type - B (10) M 73:4 DatabaseIntrospection.get_table_description - B (10) C 20:0 DatabaseIntrospection - B (7) M 192:4 DatabaseIntrospection._parse_constraint_columns - B (7) M 144:4 DatabaseIntrospection.get_sequences - A (3) M 67:4 DatabaseIntrospection.get_table_list - A (2) M 151:4 DatabaseIntrospection.get_relations - A (2) M 178:4 DatabaseIntrospection.get_storage_engine - A (2) M 162:4 DatabaseIntrospection.get_key_columns - A (1) django/db/backends/mysql/base.py M 194:4 DatabaseWrapper.get_connection_params - B (10) M 289:4 DatabaseWrapper.check_constraints - B (6) M 235:4 DatabaseWrapper.init_connection_state - A (4) M 342:4 DatabaseWrapper.data_type_check_constraints - A (4) C 52:0 CursorWrapper - A (3) M 70:4 CursorWrapper.execute - A (3) M 81:4 CursorWrapper.executemany - A (3) C 98:0 DatabaseWrapper - A (3) M 329:4 DatabaseWrapper.is_usable - A (3) M 385:4 DatabaseWrapper.mysql_version - A (3) M 256:4 DatabaseWrapper._rollback - A (2) M 338:4 DatabaseWrapper.display_name - A (2) M 396:4 DatabaseWrapper.sql_mode - A (2) M 67:4 CursorWrapper.__init__ - A (1) M 91:4 CursorWrapper.__getattr__ - A (1) M 94:4 CursorWrapper.__iter__ - A (1) M 232:4 DatabaseWrapper.get_new_connection - A (1) M 252:4 DatabaseWrapper.create_cursor - A (1) M 262:4 DatabaseWrapper._set_autocommit - A (1) M 266:4 DatabaseWrapper.disable_constraint_checking - A (1) M 276:4 DatabaseWrapper.enable_constraint_checking - A (1) M 357:4 DatabaseWrapper.mysql_server_data - A (1) M 381:4 DatabaseWrapper.mysql_server_info - A (1) M 392:4 DatabaseWrapper.mysql_is_mariadb - A (1) django/db/backends/mysql/schema.py M 102:4 DatabaseSchemaEditor._field_should_be_indexed - B (6) M 42:4 DatabaseSchemaEditor.sql_rename_column - A (4) M 52:4 DatabaseSchemaEditor.quote_value - A (4) M 79:4 DatabaseSchemaEditor._column_default_sql - A (4) C 5:0 DatabaseSchemaEditor - A (3) M 90:4 DatabaseSchemaEditor.add_field - A (3) M 117:4 DatabaseSchemaEditor._delete_composed_index - A (3) M 33:4 DatabaseSchemaEditor.sql_delete_check - A (2) M 62:4 DatabaseSchemaEditor._is_limited_data_type - A (2) M 66:4 DatabaseSchemaEditor.skip_default - A (2) M 72:4 DatabaseSchemaEditor._supports_limited_data_type_defaults - A (2) M 135:4 DatabaseSchemaEditor._set_field_new_type_null_status - A (2) M 146:4 DatabaseSchemaEditor._alter_column_type_sql - A (1) M 150:4 DatabaseSchemaEditor._rename_field_sql - A (1) django/db/backends/mysql/validation.py M 33:4 DatabaseValidation.check_field_type - B (7) C 6:0 DatabaseValidation - A (4) M 12:4 DatabaseValidation._check_sql_mode - A (2) M 7:4 DatabaseValidation.check - A (1) django/db/backends/base/creation.py M 32:4 BaseDatabaseCreation.create_test_db - B (8) M 181:4 BaseDatabaseCreation._create_test_db - B (8) M 259:4 BaseDatabaseCreation.destroy_test_db - B (6) M 301:4 BaseDatabaseCreation.mark_expected_failures_and_skips - B (6) C 18:0 BaseDatabaseCreation - A (3) M 222:4 BaseDatabaseCreation.clone_test_db - A (3) M 139:4 BaseDatabaseCreation.deserialize_db_from_string - A (2) M 158:4 BaseDatabaseCreation._get_database_display_str - A (2) M 167:4 BaseDatabaseCreation._get_test_db_name - A (2) M 23:4 BaseDatabaseCreation.__init__ - A (1) M 26:4 BaseDatabaseCreation._nodb_cursor - A (1) M 29:4 BaseDatabaseCreation.log - A (1) M 102:4 BaseDatabaseCreation.set_as_test_mirror - A (1) M 109:4 BaseDatabaseCreation.serialize_db_to_string - A (1) M 178:4 BaseDatabaseCreation._execute_create_test_db - A (1) M 241:4 BaseDatabaseCreation.get_test_db_clone_settings - A (1) M 251:4 BaseDatabaseCreation._clone_test_db - A (1) M 289:4 BaseDatabaseCreation._destroy_test_db - A (1) M 324:4 BaseDatabaseCreation.sql_table_creation_suffix - A (1) M 330:4 BaseDatabaseCreation.test_db_signature - A (1) django/db/backends/base/client.py C 5:0 BaseDatabaseClient - A (2) M 22:4 BaseDatabaseClient.runshell - A (2) M 11:4 BaseDatabaseClient.__init__ - A (1) M 16:4 BaseDatabaseClient.settings_to_cmd_args_env - A (1) django/db/backends/base/features.py C 5:0 BaseDatabaseFeatures - A (2) M 359:4 BaseDatabaseFeatures.allows_group_by_selected_pks_on_model - A (2) M 337:4 BaseDatabaseFeatures.__init__ - A (1) M 341:4 BaseDatabaseFeatures.supports_explaining_query_execution - A (1) M 346:4 BaseDatabaseFeatures.supports_transactions - A (1) django/db/backends/base/operations.py M 662:4 BaseDatabaseOperations.window_frame_range_start_end - B (6) M 674:4 BaseDatabaseOperations.explain_query_prefix - B (6) M 203:4 BaseDatabaseOperations.for_update_sql - A (5) M 222:4 BaseDatabaseOperations.limit_offset_sql - A (5) M 230:4 BaseDatabaseOperations.last_executed_query - A (5) M 467:4 BaseDatabaseOperations.adapt_unknown_value - A (5) M 634:4 BaseDatabaseOperations.window_frame_start - A (5) M 644:4 BaseDatabaseOperations.window_frame_end - A (5) M 214:4 BaseDatabaseOperations._get_limit_offset_params - A (4) M 297:4 BaseDatabaseOperations.prepare_sql_script - A (3) M 504:4 BaseDatabaseOperations.adapt_timefield_value - A (3) C 14:0 BaseDatabaseOperations - A (2) M 169:4 BaseDatabaseOperations.distinct_sql - A (2) M 326:4 BaseDatabaseOperations.compiler - A (2) M 400:4 BaseDatabaseOperations.execute_sql_flush - A (2) M 434:4 BaseDatabaseOperations.end_transaction_sql - A (2) M 486:4 BaseDatabaseOperations.adapt_datefield_value - A (2) M 495:4 BaseDatabaseOperations.adapt_datetimefield_value - A (2) M 522:4 BaseDatabaseOperations.adapt_ipaddressfield_value - A (2) M 543:4 BaseDatabaseOperations.year_lookup_bounds_for_datetime_field - A (2) M 570:4 BaseDatabaseOperations.convert_durationfield_value - A (2) M 627:4 BaseDatabaseOperations.subtract_temporals - A (2) M 654:4 BaseDatabaseOperations.window_frame_rows_start_end - A (2) M 56:4 BaseDatabaseOperations.__init__ - A (1) M 60:4 BaseDatabaseOperations.autoinc_sql - A (1) M 69:4 BaseDatabaseOperations.bulk_batch_size - A (1) M 77:4 BaseDatabaseOperations.cache_key_culling_sql - A (1) M 87:4 BaseDatabaseOperations.unification_cast_sql - A (1) M 95:4 BaseDatabaseOperations.date_extract_sql - A (1) M 102:4 BaseDatabaseOperations.date_trunc_sql - A (1) M 113:4 BaseDatabaseOperations.datetime_cast_date_sql - A (1) M 122:4 BaseDatabaseOperations.datetime_cast_time_sql - A (1) M 128:4 BaseDatabaseOperations.datetime_extract_sql - A (1) M 136:4 BaseDatabaseOperations.datetime_trunc_sql - A (1) M 144:4 BaseDatabaseOperations.time_trunc_sql - A (1) M 155:4 BaseDatabaseOperations.time_extract_sql - A (1) M 162:4 BaseDatabaseOperations.deferrable_sql - A (1) M 180:4 BaseDatabaseOperations.fetch_returned_insert_columns - A (1) M 187:4 BaseDatabaseOperations.field_cast_sql - A (1) M 196:4 BaseDatabaseOperations.force_no_ordering - A (1) M 252:4 BaseDatabaseOperations.last_insert_id - A (1) M 261:4 BaseDatabaseOperations.lookup_cast - A (1) M 269:4 BaseDatabaseOperations.max_in_list_size - A (1) M 276:4 BaseDatabaseOperations.max_name_length - A (1) M 283:4 BaseDatabaseOperations.no_limit_value - A (1) M 290:4 BaseDatabaseOperations.pk_default_value - A (1) M 311:4 BaseDatabaseOperations.process_clob - A (1) M 318:4 BaseDatabaseOperations.return_insert_columns - A (1) M 336:4 BaseDatabaseOperations.quote_name - A (1) M 343:4 BaseDatabaseOperations.regex_lookup - A (1) M 354:4 BaseDatabaseOperations.savepoint_create_sql - A (1) M 362:4 BaseDatabaseOperations.savepoint_commit_sql - A (1) M 368:4 BaseDatabaseOperations.savepoint_rollback_sql - A (1) M 374:4 BaseDatabaseOperations.set_time_zone_sql - A (1) M 382:4 BaseDatabaseOperations.sql_flush - A (1) M 410:4 BaseDatabaseOperations.sequence_reset_by_name_sql - A (1) M 420:4 BaseDatabaseOperations.sequence_reset_sql - A (1) M 430:4 BaseDatabaseOperations.start_transaction_sql - A (1) M 440:4 BaseDatabaseOperations.tablespace_sql - A (1) M 451:4 BaseDatabaseOperations.prep_for_like_query - A (1) M 459:4 BaseDatabaseOperations.validate_autopk_value - A (1) M 515:4 BaseDatabaseOperations.adapt_decimalfield_value - A (1) M 529:4 BaseDatabaseOperations.year_lookup_bounds_for_date_field - A (1) M 561:4 BaseDatabaseOperations.get_db_converters - A (1) M 574:4 BaseDatabaseOperations.check_expression_support - A (1) M 585:4 BaseDatabaseOperations.conditional_expression_supported_in_where_clause - A (1) M 592:4 BaseDatabaseOperations.combine_expression - A (1) M 602:4 BaseDatabaseOperations.combine_duration_expression - A (1) M 605:4 BaseDatabaseOperations.binary_placeholder_sql - A (1) M 612:4 BaseDatabaseOperations.modify_insert_params - A (1) M 619:4 BaseDatabaseOperations.integer_field_range - A (1) M 689:4 BaseDatabaseOperations.insert_statement - A (1) M 692:4 BaseDatabaseOperations.ignore_conflicts_suffix_sql - A (1) django/db/backends/base/introspection.py M 81:4 BaseDatabaseIntrospection.django_table_names - B (8) M 118:4 BaseDatabaseIntrospection.sequence_list - B (7) M 71:4 BaseDatabaseIntrospection.get_migratable_models - A (4) C 14:0 BaseDatabaseIntrospection - A (3) M 107:4 BaseDatabaseIntrospection.installed_models - A (3) M 166:4 BaseDatabaseIntrospection.get_primary_key_column - A (3) M 39:4 BaseDatabaseIntrospection.table_names - A (2) M 18:4 BaseDatabaseIntrospection.__init__ - A (1) M 21:4 BaseDatabaseIntrospection.get_field_type - A (1) M 31:4 BaseDatabaseIntrospection.identifier_converter - A (1) M 54:4 BaseDatabaseIntrospection.get_table_list - A (1) M 61:4 BaseDatabaseIntrospection.get_table_description - A (1) M 139:4 BaseDatabaseIntrospection.get_sequences - A (1) M 147:4 BaseDatabaseIntrospection.get_relations - A (1) M 158:4 BaseDatabaseIntrospection.get_key_columns - A (1) M 175:4 BaseDatabaseIntrospection.get_constraints - A (1) django/db/backends/base/base.py M 502:4 BaseDatabaseWrapper.close_if_unusable_or_obsolete - B (7) M 392:4 BaseDatabaseWrapper.set_autocommit - B (6) M 283:4 BaseDatabaseWrapper.close - A (4) M 344:4 BaseDatabaseWrapper.savepoint_rollback - A (4) M 634:4 BaseDatabaseWrapper.on_commit - A (4) M 118:4 BaseDatabaseWrapper.timezone - A (3) M 141:4 BaseDatabaseWrapper.timezone_name - A (3) M 207:4 BaseDatabaseWrapper.check_settings - A (3) M 544:4 BaseDatabaseWrapper.validate_thread_sharing - A (3) C 26:0 BaseDatabaseWrapper - A (2) M 153:4 BaseDatabaseWrapper.queries_logged - A (2) M 157:4 BaseDatabaseWrapper.queries - A (2) M 185:4 BaseDatabaseWrapper.connect - A (2) M 215:4 BaseDatabaseWrapper.ensure_connection - A (2) M 223:4 BaseDatabaseWrapper._prepare_cursor - A (2) M 239:4 BaseDatabaseWrapper._commit - A (2) M 244:4 BaseDatabaseWrapper._rollback - A (2) M 249:4 BaseDatabaseWrapper._close - A (2) M 316:4 BaseDatabaseWrapper._savepoint_allowed - A (2) M 323:4 BaseDatabaseWrapper.savepoint - A (2) M 360:4 BaseDatabaseWrapper.savepoint_commit - A (2) M 423:4 BaseDatabaseWrapper.get_rollback - A (2) M 430:4 BaseDatabaseWrapper.set_rollback - A (2) M 439:4 BaseDatabaseWrapper.validate_no_atomic_block - A (2) M 445:4 BaseDatabaseWrapper.validate_no_broken_transaction - A (2) M 454:4 BaseDatabaseWrapper.constraint_checks_disabled - A (2) M 538:4 BaseDatabaseWrapper.dec_thread_sharing - A (2) M 593:4 BaseDatabaseWrapper.temporary_connection - A (2) M 625:4 BaseDatabaseWrapper.schema_editor - A (2) M 647:4 BaseDatabaseWrapper.run_and_clear_commit_hooks - A (2) M 667:4 BaseDatabaseWrapper.copy - A (2) M 48:4 BaseDatabaseWrapper.__init__ - A (1) M 110:4 BaseDatabaseWrapper.ensure_timezone - A (1) M 166:4 BaseDatabaseWrapper.get_connection_params - A (1) M 170:4 BaseDatabaseWrapper.get_new_connection - A (1) M 174:4 BaseDatabaseWrapper.init_connection_state - A (1) M 178:4 BaseDatabaseWrapper.create_cursor - A (1) M 234:4 BaseDatabaseWrapper._cursor - A (1) M 257:4 BaseDatabaseWrapper.cursor - A (1) M 262:4 BaseDatabaseWrapper.commit - A (1) M 272:4 BaseDatabaseWrapper.rollback - A (1) M 304:4 BaseDatabaseWrapper._savepoint - A (1) M 308:4 BaseDatabaseWrapper._savepoint_rollback - A (1) M 312:4 BaseDatabaseWrapper._savepoint_commit - A (1) M 371:4 BaseDatabaseWrapper.clean_savepoints - A (1) M 379:4 BaseDatabaseWrapper._set_autocommit - A (1) M 387:4 BaseDatabaseWrapper.get_autocommit - A (1) M 465:4 BaseDatabaseWrapper.disable_constraint_checking - A (1) M 473:4 BaseDatabaseWrapper.enable_constraint_checking - A (1) M 480:4 BaseDatabaseWrapper.check_constraints - A (1) M 490:4 BaseDatabaseWrapper.is_usable - A (1) M 530:4 BaseDatabaseWrapper.allow_thread_sharing - A (1) M 534:4 BaseDatabaseWrapper.inc_thread_sharing - A (1) M 562:4 BaseDatabaseWrapper.prepare_database - A (1) M 570:4 BaseDatabaseWrapper.wrap_database_errors - A (1) M 577:4 BaseDatabaseWrapper.chunked_cursor - A (1) M 584:4 BaseDatabaseWrapper.make_debug_cursor - A (1) M 588:4 BaseDatabaseWrapper.make_cursor - A (1) M 610:4 BaseDatabaseWrapper._nodb_cursor - A (1) M 656:4 BaseDatabaseWrapper.execute_wrapper - A (1) django/db/backends/base/schema.py M 597:4 BaseDatabaseSchemaEditor._alter_field - F (83) M 554:4 BaseDatabaseSchemaEditor.alter_field - C (20) M 1305:4 BaseDatabaseSchemaEditor._constraint_names - C (20) M 209:4 BaseDatabaseSchemaEditor.column_sql - C (19) M 150:4 BaseDatabaseSchemaEditor.table_sql - C (18) M 1218:4 BaseDatabaseSchemaEditor._create_unique_sql - C (15) M 467:4 BaseDatabaseSchemaEditor.add_field - C (13) M 1260:4 BaseDatabaseSchemaEditor._delete_unique_sql - C (13) M 286:4 BaseDatabaseSchemaEditor._effective_default - C (11) M 524:4 BaseDatabaseSchemaEditor.remove_field - B (10) M 1064:4 BaseDatabaseSchemaEditor._model_indexes_sql - B (10) M 1185:4 BaseDatabaseSchemaEditor._unique_sql - B (8) M 124:4 BaseDatabaseSchemaEditor.execute - B (7) C 45:0 BaseDatabaseSchemaEditor - B (6) M 341:4 BaseDatabaseSchemaEditor.delete_model - B (6) M 391:4 BaseDatabaseSchemaEditor.alter_unique_together - B (6) M 407:4 BaseDatabaseSchemaEditor.alter_index_together - B (6) M 444:4 BaseDatabaseSchemaEditor.alter_db_table - B (6) M 963:4 BaseDatabaseSchemaEditor._create_index_name - B (6) M 992:4 BaseDatabaseSchemaEditor._get_index_tablespace_sql - B (6) M 1015:4 BaseDatabaseSchemaEditor._create_index_sql - B (6) F 36:0 _related_non_m2m_objects - A (5) M 428:4 BaseDatabaseSchemaEditor._delete_composed_index - A (5) M 874:4 BaseDatabaseSchemaEditor._alter_column_default_sql - A (5) M 1131:4 BaseDatabaseSchemaEditor._unique_should_be_added - A (5) F 16:0 _is_relevant_relation - A (4) M 115:4 BaseDatabaseSchemaEditor.__exit__ - A (4) M 324:4 BaseDatabaseSchemaEditor.create_model - A (4) M 852:4 BaseDatabaseSchemaEditor._alter_column_null_sql - A (4) M 1177:4 BaseDatabaseSchemaEditor._deferrable_constraint_sql - A (4) M 1335:4 BaseDatabaseSchemaEditor._delete_primary_key - A (4) M 99:4 BaseDatabaseSchemaEditor.__init__ - A (3) M 357:4 BaseDatabaseSchemaEditor.add_index - A (3) M 368:4 BaseDatabaseSchemaEditor.remove_index - A (3) M 1007:4 BaseDatabaseSchemaEditor._index_include_sql - A (3) M 1096:4 BaseDatabaseSchemaEditor._field_should_be_altered - A (3) M 108:4 BaseDatabaseSchemaEditor.__enter__ - A (2) M 377:4 BaseDatabaseSchemaEditor.add_constraint - A (2) M 385:4 BaseDatabaseSchemaEditor.remove_constraint - A (2) M 932:4 BaseDatabaseSchemaEditor._alter_column_collation_sql - A (2) M 942:4 BaseDatabaseSchemaEditor._alter_many_to_many - A (2) M 1002:4 BaseDatabaseSchemaEditor._index_condition_sql - A (2) M 1054:4 BaseDatabaseSchemaEditor._delete_index_sql - A (2) M 1087:4 BaseDatabaseSchemaEditor._field_indexes_sql - A (2) M 1125:4 BaseDatabaseSchemaEditor._field_should_be_indexed - A (2) M 1128:4 BaseDatabaseSchemaEditor._field_became_primary_key - A (2) F 32:0 _all_related_fields - A (1) M 147:4 BaseDatabaseSchemaEditor.quote_name - A (1) M 262:4 BaseDatabaseSchemaEditor.skip_default - A (1) M 269:4 BaseDatabaseSchemaEditor.prepare_default - A (1) M 278:4 BaseDatabaseSchemaEditor._column_default_sql - A (1) M 308:4 BaseDatabaseSchemaEditor.effective_default - A (1) M 312:4 BaseDatabaseSchemaEditor.quote_value - A (1) M 459:4 BaseDatabaseSchemaEditor.alter_db_tablespace - A (1) M 911:4 BaseDatabaseSchemaEditor._alter_column_type_sql - A (1) M 1061:4 BaseDatabaseSchemaEditor._index_columns - A (1) M 1136:4 BaseDatabaseSchemaEditor._rename_field_sql - A (1) M 1144:4 BaseDatabaseSchemaEditor._create_fk_sql - A (1) M 1161:4 BaseDatabaseSchemaEditor._fk_constraint_name - A (1) M 1174:4 BaseDatabaseSchemaEditor._delete_fk_sql - A (1) M 1281:4 BaseDatabaseSchemaEditor._check_sql - A (1) M 1287:4 BaseDatabaseSchemaEditor._create_check_sql - A (1) M 1295:4 BaseDatabaseSchemaEditor._delete_check_sql - A (1) M 1298:4 BaseDatabaseSchemaEditor._delete_constraint_sql - A (1) M 1345:4 BaseDatabaseSchemaEditor._create_primary_key_sql - A (1) M 1355:4 BaseDatabaseSchemaEditor._delete_primary_key_sql - A (1) M 1358:4 BaseDatabaseSchemaEditor._collate_sql - A (1) M 1361:4 BaseDatabaseSchemaEditor.remove_procedure - A (1) django/db/backends/base/validation.py M 9:4 BaseDatabaseValidation.check_field - B (6) C 1:0 BaseDatabaseValidation - A (4) M 3:4 BaseDatabaseValidation.__init__ - A (1) M 6:4 BaseDatabaseValidation.check - A (1) django/db/models/options.py M 780:4 Options._get_fields - C (19) M 148:4 Options.contribute_to_class - C (13) M 252:4 Options._prepare - C (13) M 712:4 Options._populate_directed_relation_graph - B (9) M 293:4 Options.add_field - B (8) M 343:4 Options.can_migrate - B (8) M 443:4 Options.default_manager - B (8) M 753:4 Options._expire_cache - B (8) M 391:4 Options.managers - B (7) M 415:4 Options.base_manager - B (7) F 38:0 normalize_together - B (6) M 221:4 Options._get_default_pk_class - B (6) C 64:0 Options - A (5) M 366:4 Options.swapped - A (5) M 467:4 Options.fields - A (5) M 612:4 Options.get_base_chain - A (5) M 640:4 Options.get_ancestor_link - A (5) M 527:4 Options.many_to_many - A (4) M 541:4 Options.related_objects - A (4) M 587:4 Options.get_field - A (4) M 660:4 Options.get_path_to_parent - A (4) M 865:4 Options.total_unique_constraints - A (4) M 323:4 Options.setup_pk - A (3) M 501:4 Options.concrete_fields - A (3) M 514:4 Options.local_concrete_fields - A (3) M 558:4 Options._forward_fields_map - A (3) M 573:4 Options.fields_map - A (3) M 629:4 Options.get_parent_list - A (3) M 690:4 Options.get_path_from_parent - A (3) M 877:4 Options._property_names - A (3) M 887:4 Options.db_returning_fields - A (3) M 209:4 Options._format_names_with_class - A (2) M 411:4 Options.managers_map - A (2) M 766:4 Options.get_fields - A (2) F 60:0 make_immutable_fields_list - A (1) M 74:4 Options.__init__ - A (1) M 132:4 Options.label - A (1) M 136:4 Options.label_lower - A (1) M 140:4 Options.app_config - A (1) M 145:4 Options.installed - A (1) M 289:4 Options.add_manager - A (1) M 328:4 Options.setup_proxy - A (1) M 337:4 Options.__repr__ - A (1) M 340:4 Options.__str__ - A (1) M 360:4 Options.verbose_name_raw - A (1) M 750:4 Options._relation_tree - A (1) django/db/models/signals.py C 9:0 ModelSignal - A (3) M 14:4 ModelSignal._lazy_method - A (3) M 25:4 ModelSignal.connect - A (1) M 31:4 ModelSignal.disconnect - A (1) django/db/models/enums.py M 11:4 ChoicesMeta.__new__ - A (5) C 8:0 ChoicesMeta - A (4) M 37:4 ChoicesMeta.__contains__ - A (3) M 44:4 ChoicesMeta.names - A (3) M 49:4 ChoicesMeta.choices - A (3) M 54:4 ChoicesMeta.labels - A (2) M 58:4 ChoicesMeta.values - A (2) C 62:0 Choices - A (2) C 78:0 TextChoices - A (2) M 65:4 Choices.__str__ - A (1) C 73:0 IntegerChoices - A (1) M 81:4 TextChoices._generate_next_value_ - A (1) django/db/models/query.py F 1642:0 prefetch_related_objects - D (27) M 527:4 QuerySet.bulk_update - D (22) M 463:4 QuerySet.bulk_create - C (18) F 1831:0 prefetch_one_level - C (17) C 42:0 ModelIterable - C (14) M 682:4 QuerySet.in_bulk - C (14) M 1100:4 QuerySet._annotate - C (14) M 45:4 ModelIterable.__iter__ - C (13) M 414:4 QuerySet.get - C (13) M 844:4 QuerySet.values_list - C (13) M 1487:4 RawQuerySet.iterator - C (12) M 365:4 QuerySet.aggregate - B (10) M 616:4 QuerySet._extract_model_params - B (9) C 113:0 ValuesListIterable - B (8) M 287:4 QuerySet.__getitem__ - B (8) M 1274:4 QuerySet._batched_insert - B (8) C 1931:0 RelatedPopulator - B (8) M 1946:4 RelatedPopulator.__init__ - B (8) F 1777:0 get_prefetcher - B (7) M 119:4 ValuesListIterable.__iter__ - B (7) M 1230:4 QuerySet.ordered - B (7) M 1437:4 RawQuerySet.resolve_model_init_order - B (7) M 641:4 QuerySet._earliest - B (6) M 891:4 QuerySet.datetimes - B (6) M 998:4 QuerySet.union - B (6) M 1572:4 Prefetch.__init__ - B (6) M 334:4 QuerySet.__or__ - A (5) M 721:4 QuerySet.delete - A (5) M 951:4 QuerySet._filter_or_exclude - A (5) M 1062:4 QuerySet.prefetch_related - A (5) M 1198:4 QuerySet.only - A (5) M 1342:4 QuerySet._merge_sanity_check - A (5) M 1992:4 RelatedPopulator.populate - A (5) F 1630:0 normalize_prefetch_lookups - A (4) C 92:0 ValuesIterable - A (4) C 143:0 NamedValuesListIterable - A (4) C 175:0 QuerySet - A (4) M 571:4 QuerySet.get_or_create - A (4) M 596:4 QuerySet.update_or_create - A (4) M 875:4 QuerySet.dates - A (4) M 1009:4 QuerySet.intersection - A (4) M 1040:4 QuerySet.select_related - A (4) M 1250:4 QuerySet.db - A (4) M 1322:4 QuerySet._fetch_all - A (4) M 1386:4 QuerySet._validate_values_are_expressions - A (4) M 1424:4 RawQuerySet.__init__ - A (4) M 1469:4 RawQuerySet._fetch_all - A (4) M 1543:4 RawQuerySet.columns - A (4) M 97:4 ValuesIterable.__iter__ - A (3) M 149:4 NamedValuesListIterable.__iter__ - A (3) C 162:0 FlatValuesListIterable - A (3) M 178:4 QuerySet.__init__ - A (3) M 221:4 QuerySet.__deepcopy__ - A (3) M 236:4 QuerySet.__setstate__ - A (3) M 323:4 QuerySet.__and__ - A (3) M 456:4 QuerySet._prepare_for_bulk_create - A (3) M 672:4 QuerySet.first - A (3) M 677:4 QuerySet.last - A (3) M 1024:4 QuerySet.select_for_update - A (3) M 1181:4 QuerySet.defer - A (3) M 1360:4 QuerySet.resolve_expression - A (3) C 1404:0 InstanceCheckMeta - A (3) C 1419:0 RawQuerySet - A (3) C 1571:0 Prefetch - A (3) F 2008:0 get_related_populators - A (2) C 35:0 BaseIterable - A (2) M 168:4 FlatValuesListIterable.__iter__ - A (2) M 195:4 QuerySet.query - A (2) M 203:4 QuerySet.query - A (2) M 255:4 QuerySet.__repr__ - A (2) M 355:4 QuerySet.iterator - A (2) M 401:4 QuerySet.count - A (2) M 755:4 QuerySet._raw_delete - A (2) M 769:4 QuerySet.update - A (2) M 788:4 QuerySet._update - A (2) M 806:4 QuerySet.exists - A (2) M 823:4 QuerySet.raw - A (2) M 830:4 QuerySet._values - A (2) M 964:4 QuerySet._filter_or_exclude_inplace - A (2) M 970:4 QuerySet.complex_filter - A (2) M 987:4 QuerySet._combinator_query - A (2) M 1018:4 QuerySet.difference - A (2) M 1143:4 QuerySet.order_by - A (2) M 1152:4 QuerySet.distinct - A (2) M 1163:4 QuerySet.extra - A (2) M 1173:4 QuerySet.reverse - A (2) M 1260:4 QuerySet._insert - A (2) M 1296:4 QuerySet._chain - A (2) M 1353:4 QuerySet._merge_known_related_objects - A (2) M 1396:4 QuerySet._not_support_combined_queries - A (2) M 1405:4 InstanceCheckMeta.__instancecheck__ - A (2) C 1409:0 EmptyQuerySet - A (2) M 1447:4 RawQuerySet.prefetch_related - A (2) M 1529:4 RawQuerySet.db - A (2) M 1561:4 RawQuerySet.model_fields - A (2) M 1593:4 Prefetch.__getstate__ - A (2) M 1610:4 Prefetch.get_current_to_attr - A (2) M 1616:4 Prefetch.get_current_queryset - A (2) M 1621:4 Prefetch.__eq__ - A (2) M 36:4 BaseIterable.__init__ - A (1) M 208:4 QuerySet.as_manager - A (1) M 231:4 QuerySet.__getstate__ - A (1) M 261:4 QuerySet.__len__ - A (1) M 265:4 QuerySet.__iter__ - A (1) M 283:4 QuerySet.__bool__ - A (1) M 320:4 QuerySet.__class_getitem__ - A (1) M 352:4 QuerySet._iterator - A (1) M 446:4 QuerySet.create - A (1) M 666:4 QuerySet.earliest - A (1) M 669:4 QuerySet.latest - A (1) M 811:4 QuerySet._prefetch_related_objects - A (1) M 816:4 QuerySet.explain - A (1) M 838:4 QuerySet.values - A (1) M 918:4 QuerySet.none - A (1) M 928:4 QuerySet.all - A (1) M 935:4 QuerySet.filter - A (1) M 943:4 QuerySet.exclude - A (1) M 1085:4 QuerySet.annotate - A (1) M 1093:4 QuerySet.alias - A (1) M 1219:4 QuerySet.using - A (1) M 1308:4 QuerySet._clone - A (1) M 1328:4 QuerySet._next_is_sticky - A (1) M 1370:4 QuerySet._add_hints - A (1) M 1377:4 QuerySet._has_filters - A (1) M 1415:4 EmptyQuerySet.__init__ - A (1) M 1456:4 RawQuerySet._prefetch_related_objects - A (1) M 1460:4 RawQuerySet._clone - A (1) M 1475:4 RawQuerySet.__len__ - A (1) M 1479:4 RawQuerySet.__bool__ - A (1) M 1483:4 RawQuerySet.__iter__ - A (1) M 1522:4 RawQuerySet.__repr__ - A (1) M 1525:4 RawQuerySet.__getitem__ - A (1) M 1533:4 RawQuerySet.using - A (1) M 1603:4 Prefetch.add_prefix - A (1) M 1607:4 Prefetch.get_current_prefetch_to - A (1) M 1626:4 Prefetch.__hash__ - A (1) django/db/models/expressions.py M 1212:4 OrderBy.as_sql - C (13) M 757:4 Value._resolve_output_field - C (12) M 492:4 CombinedExpression.resolve_expression - B (9) M 945:4 When.__init__ - B (9) M 1410:4 WindowFrame.__str__ - B (9) M 1055:4 Case.as_sql - B (8) M 316:4 BaseExpression.convert_value - B (7) M 1280:4 Window.__init__ - B (7) M 284:4 BaseExpression._resolve_output_field - B (6) M 1316:4 Window.as_sql - B (6) M 393:4 BaseExpression.identity - A (5) M 682:4 Func.as_sql - A (5) M 731:4 Value.as_sql - A (5) F 438:0 _resolve_combined_type - A (4) C 18:0 SQLiteNumericMixin - A (4) M 184:4 BaseExpression._parse_expressions - A (4) M 370:4 BaseExpression.flatten - A (4) C 520:0 DurationExpression - A (4) M 521:4 DurationExpression.compile - A (4) M 643:4 Func.__init__ - A (4) M 657:4 Func.__repr__ - A (4) C 710:0 Value - A (4) M 798:4 RawSQL.resolve_expression - A (4) M 1144:4 Subquery.get_group_by_cols - A (4) C 1188:0 OrderBy - A (4) M 1192:4 OrderBy.__init__ - A (4) M 1360:4 Window.__str__ - A (4) M 23:4 SQLiteNumericMixin.as_sqlite - A (3) M 58:4 Combinable._combine - A (3) M 92:4 Combinable.__and__ - A (3) M 111:4 Combinable.__or__ - A (3) C 151:0 BaseExpression - A (3) M 220:4 BaseExpression.contains_aggregate - A (3) M 224:4 BaseExpression.contains_over_clause - A (3) M 228:4 BaseExpression.contains_column_references - A (3) M 231:4 BaseExpression.resolve_expression - A (3) M 273:4 BaseExpression._output_field_or_none - A (3) M 338:4 BaseExpression.relabeled_clone - A (3) M 349:4 BaseExpression.get_group_by_cols - A (3) C 445:0 CombinedExpression - A (3) M 465:4 CombinedExpression._resolve_output_field - A (3) C 624:0 OuterRef - A (3) C 636:0 Func - A (3) C 782:0 RawSQL - A (3) C 817:0 Col - A (3) C 887:0 ExpressionList - A (3) C 940:0 When - A (3) C 1007:0 Case - A (3) M 1022:4 Case.__init__ - A (3) M 1133:4 Subquery.as_sql - A (3) M 1257:4 OrderBy.reverse_ordering - A (3) C 1271:0 Window - A (3) C 1375:0 WindowFrame - A (3) C 33:0 Combinable - A (2) M 162:4 BaseExpression.__init__ - A (2) M 171:4 BaseExpression.get_db_converters - A (2) M 181:4 BaseExpression.set_source_expressions - A (2) M 264:4 BaseExpression.output_field - A (2) M 357:4 BaseExpression.get_source_fields - A (2) M 383:4 BaseExpression.select_format - A (2) M 411:4 BaseExpression.__eq__ - A (2) M 532:4 DurationExpression.as_sql - A (2) C 550:0 TemporalSubtraction - A (2) C 564:0 F - A (2) M 587:4 F.__eq__ - A (2) C 594:0 ResolvedOuterRef - A (2) M 627:4 OuterRef.resolve_expression - A (2) M 675:4 Func.resolve_expression - A (2) M 783:4 RawSQL.__init__ - A (2) C 809:0 Star - A (2) M 822:4 Col.__init__ - A (2) M 828:4 Col.__repr__ - A (2) M 833:4 Col.as_sql - A (2) M 839:4 Col.relabeled_clone - A (2) M 847:4 Col.get_db_converters - A (2) C 854:0 Ref - A (2) M 895:4 ExpressionList.__init__ - A (2) M 900:4 ExpressionList.__str__ - A (2) C 908:0 ExpressionWrapper - A (2) M 924:4 ExpressionWrapper.get_group_by_cols - A (2) M 978:4 When.resolve_expression - A (2) M 986:4 When.as_sql - A (2) M 999:4 When.get_group_by_cols - A (2) M 1030:4 Case.__str__ - A (2) M 1042:4 Case.resolve_expression - A (2) M 1082:4 Case.get_group_by_cols - A (2) C 1088:0 Subquery - A (2) M 1102:4 Subquery.__getstate__ - A (2) C 1153:0 Exists - A (2) M 1166:4 Exists.as_sql - A (2) M 1179:4 Exists.select_format - A (2) M 1239:4 OrderBy.as_oracle - A (2) M 1251:4 OrderBy.get_group_by_cols - A (2) M 1350:4 Window.as_sqlite - A (2) C 1434:0 RowRange - A (2) C 1441:0 ValueRange - A (2) M 71:4 Combinable.__neg__ - A (1) M 74:4 Combinable.__add__ - A (1) M 77:4 Combinable.__sub__ - A (1) M 80:4 Combinable.__mul__ - A (1) M 83:4 Combinable.__truediv__ - A (1) M 86:4 Combinable.__mod__ - A (1) M 89:4 Combinable.__pow__ - A (1) M 99:4 Combinable.bitand - A (1) M 102:4 Combinable.bitleftshift - A (1) M 105:4 Combinable.bitrightshift - A (1) M 108:4 Combinable.bitxor - A (1) M 118:4 Combinable.bitor - A (1) M 121:4 Combinable.__radd__ - A (1) M 124:4 Combinable.__rsub__ - A (1) M 127:4 Combinable.__rmul__ - A (1) M 130:4 Combinable.__rtruediv__ - A (1) M 133:4 Combinable.__rmod__ - A (1) M 136:4 Combinable.__rpow__ - A (1) M 139:4 Combinable.__rand__ - A (1) M 144:4 Combinable.__ror__ - A (1) M 166:4 BaseExpression.__getstate__ - A (1) M 178:4 BaseExpression.get_source_expressions - A (1) M 191:4 BaseExpression.as_sql - A (1) M 256:4 BaseExpression.conditional - A (1) M 260:4 BaseExpression.field - A (1) M 312:4 BaseExpression._convert_value_noop - A (1) M 332:4 BaseExpression.get_lookup - A (1) M 335:4 BaseExpression.get_transform - A (1) M 346:4 BaseExpression.copy - A (1) M 361:4 BaseExpression.asc - A (1) M 364:4 BaseExpression.desc - A (1) M 367:4 BaseExpression.reverse_ordering - A (1) M 416:4 BaseExpression.__hash__ - A (1) C 420:0 Expression - A (1) M 447:4 CombinedExpression.__init__ - A (1) M 453:4 CombinedExpression.__repr__ - A (1) M 456:4 CombinedExpression.__str__ - A (1) M 459:4 CombinedExpression.get_source_expressions - A (1) M 462:4 CombinedExpression.set_source_expressions - A (1) M 478:4 CombinedExpression.as_sql - A (1) M 553:4 TemporalSubtraction.__init__ - A (1) M 556:4 TemporalSubtraction.as_sql - A (1) M 567:4 F.__init__ - A (1) M 574:4 F.__repr__ - A (1) M 577:4 F.resolve_expression - A (1) M 581:4 F.asc - A (1) M 584:4 F.desc - A (1) M 590:4 F.__hash__ - A (1) M 603:4 ResolvedOuterRef.as_sql - A (1) M 609:4 ResolvedOuterRef.resolve_expression - A (1) M 617:4 ResolvedOuterRef.relabeled_clone - A (1) M 620:4 ResolvedOuterRef.get_group_by_cols - A (1) M 632:4 OuterRef.relabeled_clone - A (1) M 665:4 Func._get_repr_options - A (1) M 669:4 Func.get_source_expressions - A (1) M 672:4 Func.set_source_expressions - A (1) M 703:4 Func.copy - A (1) M 716:4 Value.__init__ - A (1) M 728:4 Value.__repr__ - A (1) M 749:4 Value.resolve_expression - A (1) M 754:4 Value.get_group_by_cols - A (1) M 789:4 RawSQL.__repr__ - A (1) M 792:4 RawSQL.as_sql - A (1) M 795:4 RawSQL.get_group_by_cols - A (1) M 810:4 Star.__repr__ - A (1) M 813:4 Star.as_sql - A (1) M 844:4 Col.get_group_by_cols - A (1) M 859:4 Ref.__init__ - A (1) M 863:4 Ref.__repr__ - A (1) M 866:4 Ref.get_source_expressions - A (1) M 869:4 Ref.set_source_expressions - A (1) M 872:4 Ref.resolve_expression - A (1) M 877:4 Ref.relabeled_clone - A (1) M 880:4 Ref.as_sql - A (1) M 883:4 Ref.get_group_by_cols - A (1) M 903:4 ExpressionList.as_sqlite - A (1) M 914:4 ExpressionWrapper.__init__ - A (1) M 918:4 ExpressionWrapper.set_source_expressions - A (1) M 921:4 ExpressionWrapper.get_source_expressions - A (1) M 933:4 ExpressionWrapper.as_sql - A (1) M 936:4 ExpressionWrapper.__repr__ - A (1) M 962:4 When.__str__ - A (1) M 965:4 When.__repr__ - A (1) M 968:4 When.get_source_expressions - A (1) M 971:4 When.set_source_expressions - A (1) M 974:4 When.get_source_fields - A (1) M 1033:4 Case.__repr__ - A (1) M 1036:4 Case.get_source_expressions - A (1) M 1039:4 Case.set_source_expressions - A (1) M 1050:4 Case.copy - A (1) M 1096:4 Subquery.__init__ - A (1) M 1112:4 Subquery.get_source_expressions - A (1) M 1115:4 Subquery.set_source_expressions - A (1) M 1118:4 Subquery._resolve_output_field - A (1) M 1121:4 Subquery.copy - A (1) M 1127:4 Subquery.external_aliases - A (1) M 1130:4 Subquery.get_external_cols - A (1) M 1157:4 Exists.__init__ - A (1) M 1161:4 Exists.__invert__ - A (1) M 1202:4 OrderBy.__repr__ - A (1) M 1206:4 OrderBy.set_source_expressions - A (1) M 1209:4 OrderBy.get_source_expressions - A (1) M 1264:4 OrderBy.asc - A (1) M 1267:4 OrderBy.desc - A (1) M 1307:4 Window._resolve_output_field - A (1) M 1310:4 Window.get_source_expressions - A (1) M 1313:4 Window.set_source_expressions - A (1) M 1368:4 Window.__repr__ - A (1) M 1371:4 Window.get_group_by_cols - A (1) M 1385:4 WindowFrame.__init__ - A (1) M 1389:4 WindowFrame.set_source_expressions - A (1) M 1392:4 WindowFrame.get_source_expressions - A (1) M 1395:4 WindowFrame.as_sql - A (1) M 1404:4 WindowFrame.__repr__ - A (1) M 1407:4 WindowFrame.get_group_by_cols - A (1) M 1430:4 WindowFrame.window_frame_start_end - A (1) M 1437:4 RowRange.window_frame_start_end - A (1) M 1444:4 ValueRange.window_frame_start_end - A (1) django/db/models/lookups.py M 373:4 In.process_rhs - B (9) M 228:4 FieldGetDbPrepValueIterableMixin.get_prep_lookup - B (6) C 284:0 Exact - B (6) C 201:0 FieldGetDbPrepValueMixin - A (5) M 301:4 Exact.as_sql - A (5) C 370:0 In - A (5) C 435:0 PatternLookup - A (5) M 21:4 Lookup.__init__ - A (4) M 43:4 Lookup.batch_process_rhs - A (4) M 71:4 Lookup.get_prep_lookup - A (4) M 87:4 Lookup.process_rhs - A (4) M 120:4 Lookup.as_oracle - A (4) M 208:4 FieldGetDbPrepValueMixin.get_db_prep_lookup - A (4) C 221:0 FieldGetDbPrepValueIterableMixin - A (4) M 287:4 Exact.process_rhs - A (4) M 406:4 In.as_sql - A (4) M 455:4 PatternLookup.process_rhs - A (4) C 503:0 IsNull - A (4) C 600:0 UUIDTextMixin - A (4) C 16:0 Lookup - A (3) M 81:4 Lookup.process_lhs - A (3) C 158:0 Transform - A (3) M 170:4 Transform.get_bilateral_transforms - A (3) M 250:4 FieldGetDbPrepValueIterableMixin.resolve_expression_parameter - A (3) C 317:0 IExact - A (3) C 348:0 IntegerFieldFloatRounding - A (3) M 412:4 In.split_parameter_list_as_sql - A (3) M 439:4 PatternLookup.get_rhs_op - A (3) M 507:4 IsNull.as_sql - A (3) C 521:0 Regex - A (3) M 605:4 UUIDTextMixin.process_rhs - A (3) M 38:4 Lookup.apply_bilateral_transforms - A (2) M 60:4 Lookup.get_source_expressions - A (2) M 65:4 Lookup.set_source_expressions - A (2) M 104:4 Lookup.relabeled_clone - A (2) M 111:4 Lookup.get_group_by_cols - A (2) M 134:4 Lookup.contains_aggregate - A (2) M 138:4 Lookup.contains_over_clause - A (2) M 142:4 Lookup.is_summary - A (2) M 149:4 Lookup.__eq__ - A (2) C 180:0 BuiltinLookup - A (2) M 242:4 FieldGetDbPrepValueIterableMixin.process_rhs - A (2) M 258:4 FieldGetDbPrepValueIterableMixin.batch_process_rhs - A (2) C 272:0 PostgresOperatorLookup - A (2) M 321:4 IExact.process_rhs - A (2) M 353:4 IntegerFieldFloatRounding.get_prep_lookup - A (2) C 495:0 Range - A (2) M 525:4 Regex.as_sql - A (2) C 540:0 YearLookup - A (2) M 541:4 YearLookup.year_lookup_bounds - A (2) M 549:4 YearLookup.as_sql - A (2) C 572:0 YearExact - A (2) C 580:0 YearGt - A (2) C 585:0 YearGte - A (2) C 590:0 YearLt - A (2) C 595:0 YearLte - A (2) M 78:4 Lookup.get_db_prep_lookup - A (1) M 101:4 Lookup.rhs_is_direct_value - A (1) M 117:4 Lookup.as_sql - A (1) M 146:4 Lookup.identity - A (1) M 154:4 Lookup.__hash__ - A (1) M 167:4 Transform.lhs - A (1) M 181:4 BuiltinLookup.process_lhs - A (1) M 190:4 BuiltinLookup.as_sql - A (1) M 197:4 BuiltinLookup.get_rhs_op - A (1) M 276:4 PostgresOperatorLookup.as_postgresql - A (1) C 329:0 GreaterThan - A (1) C 334:0 GreaterThanOrEqual - A (1) C 339:0 LessThan - A (1) C 344:0 LessThanOrEqual - A (1) C 360:0 IntegerGreaterThanOrEqual - A (1) C 365:0 IntegerLessThan - A (1) M 403:4 In.get_rhs_op - A (1) C 463:0 Contains - A (1) C 468:0 IContains - A (1) C 473:0 StartsWith - A (1) C 479:0 IStartsWith - A (1) C 484:0 EndsWith - A (1) C 490:0 IEndsWith - A (1) M 498:4 Range.get_rhs_op - A (1) C 536:0 IRegex - A (1) M 563:4 YearLookup.get_direct_rhs_sql - A (1) M 566:4 YearLookup.get_bound_params - A (1) M 573:4 YearExact.get_direct_rhs_sql - A (1) M 576:4 YearExact.get_bound_params - A (1) M 581:4 YearGt.get_bound_params - A (1) M 586:4 YearGte.get_bound_params - A (1) M 591:4 YearLt.get_bound_params - A (1) M 596:4 YearLte.get_bound_params - A (1) C 616:0 UUIDIExact - A (1) C 621:0 UUIDContains - A (1) C 626:0 UUIDIContains - A (1) C 631:0 UUIDStartsWith - A (1) C 636:0 UUIDIStartsWith - A (1) C 641:0 UUIDEndsWith - A (1) C 646:0 UUIDIEndsWith - A (1) django/db/models/indexes.py M 17:4 Index.__init__ - D (30) M 209:4 IndexExpression.resolve_expression - B (10) M 171:4 Index.__repr__ - B (8) C 11:0 Index - B (7) M 142:4 Index.set_name_with_model - B (7) M 90:4 Index.create_sql - B (6) M 121:4 Index.deconstruct - B (6) C 191:0 IndexExpression - A (5) M 196:4 IndexExpression.set_wrapper_classes - A (5) M 81:4 Index._get_condition_sql - A (3) M 185:4 Index.__eq__ - A (2) M 78:4 Index.contains_expressions - A (1) M 118:4 Index.remove_sql - A (1) M 137:4 Index.clone - A (1) M 206:4 IndexExpression.register_wrappers - A (1) M 267:4 IndexExpression.as_sqlite - A (1) django/db/models/utils.py F 5:0 make_model_tuple - A (5) F 28:0 resolve_callables - A (3) F 37:0 unpickle_named_row - A (1) F 42:0 create_namedtuple_class - A (1) django/db/models/aggregates.py M 45:4 Aggregate.resolve_expression - B (6) C 16:0 Aggregate - A (4) M 70:4 Aggregate.as_sql - A (4) C 105:0 Count - A (4) M 111:4 Count.__init__ - A (4) M 24:4 Aggregate.__init__ - A (3) M 61:4 Aggregate.default_alias - A (3) M 90:4 Aggregate._get_repr_options - A (3) C 132:0 StdDev - A (3) C 149:0 Variance - A (3) M 31:4 Aggregate.get_source_fields - A (2) M 35:4 Aggregate.get_source_expressions - A (2) M 41:4 Aggregate.set_source_expressions - A (2) M 118:4 Count.convert_value - A (2) M 135:4 StdDev.__init__ - A (2) M 152:4 Variance.__init__ - A (2) M 67:4 Aggregate.get_group_by_cols - A (1) C 99:0 Avg - A (1) C 122:0 Max - A (1) C 127:0 Min - A (1) M 139:4 StdDev._get_repr_options - A (1) C 143:0 Sum - A (1) M 156:4 Variance._get_repr_options - A (1) django/db/models/deletion.py M 214:4 Collector.collect - E (34) M 379:4 Collector.delete - D (23) M 165:4 Collector.can_fast_delete - C (12) C 79:0 Collector - B (8) M 361:4 Collector.sort - B (8) F 70:0 get_candidate_relations_to_delete - B (6) M 99:4 Collector.add - B (6) M 151:4 Collector.clear_restricted_objects_from_queryset - A (4) M 201:4 Collector.get_del_batches - A (4) F 23:0 CASCADE - A (3) M 144:4 Collector.clear_restricted_objects_from_set - A (3) M 356:4 Collector.instances_with_model - A (3) F 47:0 SET - A (2) C 11:0 ProtectedError - A (2) C 17:0 RestrictedError - A (2) M 123:4 Collector.add_dependency - A (2) M 129:4 Collector.add_field_update - A (2) M 139:4 Collector.add_restricted_objects - A (2) M 159:4 Collector._has_signal_listeners - A (2) M 346:4 Collector.related_objects - A (2) F 32:0 PROTECT - A (1) F 42:0 RESTRICT - A (1) F 58:0 SET_NULL - A (1) F 62:0 SET_DEFAULT - A (1) F 66:0 DO_NOTHING - A (1) M 12:4 ProtectedError.__init__ - A (1) M 18:4 RestrictedError.__init__ - A (1) M 80:4 Collector.__init__ - A (1) django/db/models/constraints.py M 90:4 UniqueConstraint.__init__ - D (25) M 226:4 UniqueConstraint.__eq__ - B (8) C 89:0 UniqueConstraint - B (7) M 214:4 UniqueConstraint.__repr__ - B (7) M 239:4 UniqueConstraint.deconstruct - B (6) M 73:4 CheckConstraint.__eq__ - A (3) M 162:4 UniqueConstraint._get_condition_sql - A (3) M 171:4 UniqueConstraint._get_index_expressions - A (3) M 183:4 UniqueConstraint.constraint_sql - A (3) M 194:4 UniqueConstraint.create_sql - A (3) C 11:0 BaseConstraint - A (2) C 38:0 CheckConstraint - A (2) M 39:4 CheckConstraint.__init__ - A (2) M 48:4 CheckConstraint._get_check_sql - A (2) M 205:4 UniqueConstraint.remove_sql - A (2) M 12:4 BaseConstraint.__init__ - A (1) M 16:4 BaseConstraint.contains_expressions - A (1) M 19:4 BaseConstraint.constraint_sql - A (1) M 22:4 BaseConstraint.create_sql - A (1) M 25:4 BaseConstraint.remove_sql - A (1) M 28:4 BaseConstraint.deconstruct - A (1) M 33:4 BaseConstraint.clone - A (1) M 55:4 CheckConstraint.constraint_sql - A (1) M 59:4 CheckConstraint.create_sql - A (1) M 63:4 CheckConstraint.remove_sql - A (1) M 66:4 CheckConstraint.__repr__ - A (1) M 78:4 CheckConstraint.deconstruct - A (1) C 84:0 Deferrable - A (1) M 159:4 UniqueConstraint.contains_expressions - A (1) django/db/models/manager.py M 82:4 BaseManager._get_queryset_methods - B (6) C 172:0 ManagerDescriptor - A (4) M 177:4 ManagerDescriptor.__get__ - A (4) M 41:4 BaseManager.deconstruct - A (3) M 128:4 BaseManager.db_manager - A (3) C 9:0 BaseManager - A (2) M 104:4 BaseManager.from_queryset - A (2) M 112:4 BaseManager.contribute_to_class - A (2) M 135:4 BaseManager.db - A (2) M 158:4 BaseManager.__eq__ - A (2) C 197:0 EmptyManager - A (2) M 20:4 BaseManager.__new__ - A (1) M 26:4 BaseManager.__init__ - A (1) M 34:4 BaseManager.__str__ - A (1) M 38:4 BaseManager.__class_getitem__ - A (1) M 78:4 BaseManager.check - A (1) M 120:4 BaseManager._set_creation_counter - A (1) M 142:4 BaseManager.get_queryset - A (1) M 149:4 BaseManager.all - A (1) M 164:4 BaseManager.__hash__ - A (1) C 168:0 Manager - A (1) M 174:4 ManagerDescriptor.__init__ - A (1) M 198:4 EmptyManager.__init__ - A (1) M 202:4 EmptyManager.get_queryset - A (1) django/db/models/query_utils.py F 207:0 select_related_descend - C (15) M 83:4 Q.deconstruct - B (6) M 42:4 Q._combine - A (5) M 152:4 RegisterLookupMixin.get_lookup - A (5) M 161:4 RegisterLookupMixin.get_transform - A (5) F 244:0 refs_expression - A (4) C 100:0 DeferredAttribute - A (4) M 108:4 DeferredAttribute.__get__ - A (4) M 298:4 FilteredRelation.__eq__ - A (4) F 257:0 check_rel_lookup_compatibility - A (3) C 28:0 Q - A (3) M 127:4 DeferredAttribute._check_parent_chain - A (3) C 140:0 RegisterLookupMixin - A (3) M 187:4 RegisterLookupMixin.register_lookup - A (3) C 285:0 FilteredRelation - A (3) M 288:4 FilteredRelation.__init__ - A (3) F 22:0 subclasses - A (2) M 148:4 RegisterLookupMixin.get_lookups - A (2) M 171:4 RegisterLookupMixin.merge_dicts - A (2) M 182:4 RegisterLookupMixin._clear_cached_lookups - A (2) M 197:4 RegisterLookupMixin._unregister_lookup - A (2) M 39:4 Q.__init__ - A (1) M 61:4 Q.__or__ - A (1) M 64:4 Q.__and__ - A (1) M 67:4 Q.__invert__ - A (1) M 73:4 Q.resolve_expression - A (1) M 105:4 DeferredAttribute.__init__ - A (1) M 143:4 RegisterLookupMixin._get_lookup - A (1) M 307:4 FilteredRelation.clone - A (1) M 313:4 FilteredRelation.resolve_expression - A (1) M 320:4 FilteredRelation.as_sql - A (1) django/db/models/base.py M 74:4 ModelBase.__new__ - F (68) M 1961:4 Model._check_constraints - F (52) M 809:4 Model._save_table - E (32) M 406:4 Model.__init__ - D (26) M 1629:4 Model._check_indexes - D (26) M 1768:4 Model._check_ordering - D (26) M 1025:4 Model._get_unique_checks - D (24) M 1870:4 Model._check_long_column_names - C (19) M 672:4 Model.save - C (18) C 72:0 ModelBase - C (17) M 594:4 Model.refresh_from_db - C (17) M 1435:4 Model._check_field_name_clashes - C (17) M 1083:4 Model._perform_unique_checks - C (13) M 330:4 ModelBase._prepare - C (11) M 730:4 Model.save_base - B (10) M 1204:4 Model.full_clean - B (10) C 404:0 Model - B (9) M 911:4 Model._prepare_related_fields_for_save - B (9) M 781:4 Model._save_parents - B (8) M 1240:4 Model.clean_fields - B (8) M 1718:4 Model._check_local_fields - B (8) M 874:4 Model._do_update - B (7) M 1128:4 Model._perform_date_checks - B (7) M 1386:4 Model._check_m2m_through_same_relationship - B (7) M 1418:4 Model._check_id_field - B (7) M 1945:4 Model._get_expr_references - B (7) M 1299:4 Model._check_default_pk - B (6) M 1541:4 Model._check_property_name_related_field_accessor_clashes - B (6) M 964:4 Model._get_next_or_previous_by_FIELD - A (5) M 1575:4 Model._check_index_together - A (5) M 1602:4 Model._check_unique_together - A (5) M 508:4 Model.from_db - A (4) M 526:4 Model.__eq__ - A (4) M 577:4 Model._set_pk_val - A (4) M 980:4 Model._get_next_or_previous_in_order - A (4) M 1266:4 Model.check - A (4) M 1328:4 Model._check_swappable - A (4) M 1355:4 Model._check_model - A (4) M 1492:4 Model._check_column_name_clashes - A (4) M 1517:4 Model._check_model_name_db_lookup_clashes - A (4) M 1561:4 Model._check_single_primary_key - A (4) F 2125:0 method_set_order - A (3) C 385:0 ModelStateFieldsCacheDescriptor - A (3) M 554:4 Model.__setstate__ - A (3) M 585:4 Model.get_deferred_fields - A (3) M 945:4 Model.delete - A (3) M 1009:4 Model.validate_unique - A (3) M 1174:4 Model.unique_error_message - A (3) M 1376:4 Model._check_fields - A (3) F 67:0 _has_contribute_to_class - A (2) F 2159:0 model_unpickle - A (2) C 42:0 Deferred - A (2) M 324:4 ModelBase.add_to_class - A (2) M 386:4 ModelStateFieldsCacheDescriptor.__get__ - A (2) M 536:4 Model.__hash__ - A (2) M 573:4 Model._get_pk_val - A (2) M 655:4 Model.serializable_value - A (2) M 995:4 Model.prepare_database_save - A (2) M 1368:4 Model._check_managers - A (2) F 53:0 subclass_exception - A (1) F 2135:0 method_get_order - A (1) F 2142:0 make_foreign_order_accessors - A (1) M 43:4 Deferred.__repr__ - A (1) M 46:4 Deferred.__str__ - A (1) M 377:4 ModelBase._base_manager - A (1) M 381:4 ModelBase._default_manager - A (1) C 393:0 ModelState - A (1) M 520:4 Model.__repr__ - A (1) M 523:4 Model.__str__ - A (1) M 541:4 Model.__reduce__ - A (1) M 547:4 Model.__getstate__ - A (1) M 901:4 Model._do_insert - A (1) M 958:4 Model._get_FIELD_display - A (1) M 1000:4 Model.clean - A (1) M 1157:4 Model.date_error_message - A (1) django/db/models/functions/mixins.py C 44:0 NumericOutputFieldMixin - B (7) M 46:4 NumericOutputFieldMixin._resolve_output_field - B (6) C 7:0 FixDecimalInputMixin - A (4) M 9:4 FixDecimalInputMixin.as_postgresql - A (3) C 23:0 FixDurationInputMixin - A (3) M 25:4 FixDurationInputMixin.as_mysql - A (2) M 31:4 FixDurationInputMixin.as_oracle - A (2) django/db/models/functions/window.py M 31:4 LagLeadFunction.__init__ - A (5) C 28:0 LagLeadFunction - A (4) C 66:0 NthValue - A (4) M 70:4 NthValue.__init__ - A (4) C 82:0 Ntile - A (3) M 87:4 Ntile.__init__ - A (2) C 10:0 CumeDist - A (1) C 16:0 DenseRank - A (1) C 22:0 FirstValue - A (1) M 47:4 LagLeadFunction._resolve_output_field - A (1) C 52:0 Lag - A (1) C 56:0 LastValue - A (1) C 62:0 Lead - A (1) M 77:4 NthValue._resolve_output_field - A (1) C 93:0 PercentRank - A (1) C 99:0 Rank - A (1) C 105:0 RowNumber - A (1) django/db/models/functions/comparison.py M 20:4 Cast.as_sqlite - A (4) M 34:4 Cast.as_mysql - A (4) C 53:0 Coalesce - A (4) C 171:0 NullIf - A (4) C 8:0 Cast - A (3) M 62:4 Coalesce.as_oracle - A (3) C 74:0 Collate - A (3) M 80:4 Collate.__init__ - A (3) C 91:0 Greatest - A (3) C 151:0 Least - A (3) M 175:4 NullIf.as_oracle - A (3) M 45:4 Cast.as_oracle - A (2) M 57:4 Coalesce.__init__ - A (2) M 101:4 Greatest.__init__ - A (2) C 111:0 JSONObject - A (2) M 115:4 JSONObject.__init__ - A (2) M 121:4 JSONObject.as_sql - A (2) M 161:4 Least.__init__ - A (2) M 13:4 Cast.__init__ - A (1) M 16:4 Cast.as_sql - A (1) M 86:4 Collate.as_sql - A (1) M 106:4 Greatest.as_sqlite - A (1) M 128:4 JSONObject.as_postgresql - A (1) M 136:4 JSONObject.as_oracle - A (1) M 166:4 Least.as_sqlite - A (1) django/db/models/functions/text.py C 159:0 LPad - A (5) M 163:4 LPad.__init__ - A (4) C 191:0 Repeat - A (4) M 195:4 Repeat.__init__ - A (4) M 295:4 Substr.__init__ - A (4) C 95:0 Concat - A (3) M 124:4 Left.__init__ - A (3) C 291:0 Substr - A (3) C 8:0 MySQLSHA2Mixin - A (2) C 18:0 OracleHashMixin - A (2) C 31:0 PostgreSQLSHAMixin - A (2) C 42:0 Chr - A (2) C 64:0 ConcatPair - A (2) M 86:4 ConcatPair.coalesce - A (2) M 104:4 Concat.__init__ - A (2) M 110:4 Concat._paired - A (2) C 119:0 Left - A (2) C 144:0 Length - A (2) C 179:0 Ord - A (2) M 200:4 Repeat.as_oracle - A (2) C 207:0 Replace - A (2) C 214:0 Reverse - A (2) C 233:0 Right - A (2) C 254:0 SHA224 - A (2) C 277:0 StrIndex - A (2) M 9:4 MySQLSHA2Mixin.as_mysql - A (1) M 19:4 OracleHashMixin.as_oracle - A (1) M 32:4 PostgreSQLSHAMixin.as_postgresql - A (1) M 46:4 Chr.as_mysql - A (1) M 53:4 Chr.as_oracle - A (1) M 60:4 Chr.as_sqlite - A (1) M 71:4 ConcatPair.as_sqlite - A (1) M 78:4 ConcatPair.as_mysql - A (1) M 134:4 Left.get_substr - A (1) M 137:4 Left.as_oracle - A (1) M 140:4 Left.as_sqlite - A (1) M 150:4 Length.as_mysql - A (1) C 154:0 Lower - A (1) C 169:0 LTrim - A (1) C 174:0 MD5 - A (1) M 184:4 Ord.as_mysql - A (1) M 187:4 Ord.as_sqlite - A (1) M 210:4 Replace.__init__ - A (1) M 218:4 Reverse.as_oracle - A (1) M 236:4 Right.get_substr - A (1) C 240:0 RPad - A (1) C 244:0 RTrim - A (1) C 249:0 SHA1 - A (1) M 258:4 SHA224.as_oracle - A (1) C 262:0 SHA256 - A (1) C 267:0 SHA384 - A (1) C 272:0 SHA512 - A (1) M 287:4 StrIndex.as_postgresql - A (1) M 309:4 Substr.as_sqlite - A (1) M 312:4 Substr.as_oracle - A (1) C 316:0 Trim - A (1) C 321:0 Upper - A (1) django/db/models/functions/math.py C 32:0 ATan2 - B (6) M 36:4 ATan2.as_sqlite - A (5) C 100:0 Log - A (3) C 52:0 Ceil - A (2) C 65:0 Cot - A (2) C 73:0 Degrees - A (2) M 104:4 Log.as_sqlite - A (2) C 119:0 Pi - A (2) C 132:0 Radians - A (2) C 144:0 Random - A (2) C 12:0 Abs - A (1) C 17:0 ACos - A (1) C 22:0 ASin - A (1) C 27:0 ATan - A (1) M 56:4 Ceil.as_oracle - A (1) C 60:0 Cos - A (1) M 69:4 Cot.as_oracle - A (1) M 77:4 Degrees.as_oracle - A (1) C 85:0 Exp - A (1) C 90:0 Floor - A (1) C 95:0 Ln - A (1) C 114:0 Mod - A (1) M 123:4 Pi.as_oracle - A (1) C 127:0 Power - A (1) M 136:4 Radians.as_oracle - A (1) M 148:4 Random.as_mysql - A (1) M 151:4 Random.as_oracle - A (1) M 154:4 Random.as_sqlite - A (1) M 157:4 Random.get_group_by_cols - A (1) C 161:0 Round - A (1) C 166:0 Sign - A (1) C 171:0 Sin - A (1) C 176:0 Sqrt - A (1) C 181:0 Tan - A (1) django/db/models/functions/datetime.py M 211:4 TruncBase.resolve_expression - C (14) M 240:4 TruncBase.convert_value - B (9) M 43:4 Extract.as_sql - B (8) C 185:0 TruncBase - B (8) C 31:0 Extract - B (7) M 65:4 Extract.resolve_expression - B (6) M 194:4 TruncBase.as_sql - B (6) C 14:0 TimezoneMixin - A (4) M 17:4 TimezoneMixin.get_tzname - A (3) M 35:4 Extract.__init__ - A (3) C 174:0 Now - A (2) C 262:0 Trunc - A (2) C 293:0 TruncDate - A (2) C 306:0 TruncTime - A (2) C 89:0 ExtractYear - A (1) C 93:0 ExtractIsoYear - A (1) C 98:0 ExtractMonth - A (1) C 102:0 ExtractDay - A (1) C 106:0 ExtractWeek - A (1) C 114:0 ExtractWeekDay - A (1) C 123:0 ExtractIsoWeekDay - A (1) C 128:0 ExtractQuarter - A (1) C 132:0 ExtractHour - A (1) C 136:0 ExtractMinute - A (1) C 140:0 ExtractSecond - A (1) M 178:4 Now.as_postgresql - A (1) M 189:4 TruncBase.__init__ - A (1) M 264:4 Trunc.__init__ - A (1) C 272:0 TruncYear - A (1) C 276:0 TruncQuarter - A (1) C 280:0 TruncMonth - A (1) C 284:0 TruncWeek - A (1) C 289:0 TruncDay - A (1) M 298:4 TruncDate.as_sql - A (1) M 311:4 TruncTime.as_sql - A (1) C 319:0 TruncHour - A (1) C 323:0 TruncMinute - A (1) C 327:0 TruncSecond - A (1) django/db/models/fields/related_descriptors.py M 203:4 ForwardManyToOneDescriptor.__set__ - C (13) M 156:4 ForwardManyToOneDescriptor.__get__ - C (11) M 430:4 ReverseOneToOneDescriptor.__set__ - B (9) M 120:4 ForwardManyToOneDescriptor.get_prefetch_queryset - B (8) C 278:0 ForwardOneToOneDescriptor - B (8) M 309:4 ForwardOneToOneDescriptor.__set__ - B (8) M 383:4 ReverseOneToOneDescriptor.__get__ - B (7) M 290:4 ForwardOneToOneDescriptor.get_object - B (6) C 82:0 ForwardManyToOneDescriptor - A (5) C 75:0 ForeignKeyDeferredAttribute - A (4) C 326:0 ReverseOneToOneDescriptor - A (4) M 365:4 ReverseOneToOneDescriptor.get_prefetch_queryset - A (4) M 76:4 ForeignKeyDeferredAttribute.__set__ - A (3) C 761:0 ManyToManyDescriptor - A (3) M 800:4 ManyToManyDescriptor._get_set_deprecation_msg_params - A (3) C 494:0 ReverseManyToOneDescriptor - A (2) M 523:4 ReverseManyToOneDescriptor.__get__ - A (2) M 791:4 ManyToManyDescriptor.related_manager_cls - A (2) F 551:0 create_reverse_many_to_one_manager - A (1) F 807:0 create_forward_many_to_many_manager - A (1) M 95:4 ForwardManyToOneDescriptor.__init__ - A (1) M 99:4 ForwardManyToOneDescriptor.RelatedObjectDoesNotExist - A (1) M 114:4 ForwardManyToOneDescriptor.is_cached - A (1) M 117:4 ForwardManyToOneDescriptor.get_queryset - A (1) M 151:4 ForwardManyToOneDescriptor.get_object - A (1) M 269:4 ForwardManyToOneDescriptor.__reduce__ - A (1) M 339:4 ReverseOneToOneDescriptor.__init__ - A (1) M 345:4 ReverseOneToOneDescriptor.RelatedObjectDoesNotExist - A (1) M 359:4 ReverseOneToOneDescriptor.is_cached - A (1) M 362:4 ReverseOneToOneDescriptor.get_queryset - A (1) M 489:4 ReverseOneToOneDescriptor.__reduce__ - A (1) M 510:4 ReverseManyToOneDescriptor.__init__ - A (1) M 515:4 ReverseManyToOneDescriptor.related_manager_cls - A (1) M 538:4 ReverseManyToOneDescriptor._get_set_deprecation_msg_params - A (1) M 544:4 ReverseManyToOneDescriptor.__set__ - A (1) M 778:4 ManyToManyDescriptor.__init__ - A (1) M 784:4 ManyToManyDescriptor.through - A (1) django/db/models/fields/files.py M 418:4 ImageField.update_dimension_fields - C (14) M 158:4 FileDescriptor.__get__ - B (10) C 144:0 FileDescriptor - B (7) M 97:4 FieldFile.delete - A (4) M 227:4 FileField.__init__ - A (4) C 370:0 ImageField - A (4) C 216:0 FileField - A (3) M 264:4 FileField._check_upload_to - A (3) M 278:4 FileField.deconstruct - A (3) M 297:4 FileField.pre_save - A (3) M 322:4 FileField.save_form_data - A (3) C 340:0 ImageFileDescriptor - A (3) C 362:0 ImageFieldFile - A (3) M 385:4 ImageField._check_image_library_installed - A (3) M 401:4 ImageField.deconstruct - A (3) C 15:0 FieldFile - A (2) M 23:4 FieldFile.__eq__ - A (2) M 37:4 FieldFile._require_file - A (2) M 41:4 FieldFile._get_file - A (2) M 66:4 FieldFile.size - A (2) M 72:4 FieldFile.open - A (2) M 86:4 FieldFile.save - A (2) M 117:4 FieldFile.closed - A (2) M 121:4 FieldFile.close - A (2) M 252:4 FileField._check_primary_key - A (2) M 290:4 FileField.get_prep_value - A (2) M 308:4 FileField.generate_filename - A (2) M 345:4 ImageFileDescriptor.__set__ - A (2) M 363:4 ImageFieldFile.delete - A (2) M 409:4 ImageField.contribute_to_class - A (2) M 16:4 FieldFile.__init__ - A (1) M 30:4 FieldFile.__hash__ - A (1) M 47:4 FieldFile._set_file - A (1) M 50:4 FieldFile._del_file - A (1) M 56:4 FieldFile.path - A (1) M 61:4 FieldFile.url - A (1) M 126:4 FieldFile.__getstate__ - A (1) M 139:4 FieldFile.__setstate__ - A (1) M 212:4 FileDescriptor.__set__ - A (1) M 245:4 FileField.check - A (1) M 287:4 FileField.get_internal_type - A (1) M 304:4 FileField.contribute_to_class - A (1) M 332:4 FileField.formfield - A (1) M 375:4 ImageField.__init__ - A (1) M 379:4 ImageField.check - A (1) M 475:4 ImageField.formfield - A (1) django/db/models/fields/mixins.py C 31:0 CheckFieldDefaultMixin - A (4) M 34:4 CheckFieldDefaultMixin._check_default - A (4) M 12:4 FieldCacheMixin.get_cached_value - A (3) C 6:0 FieldCacheMixin - A (2) M 9:4 FieldCacheMixin.get_cache_name - A (1) M 21:4 FieldCacheMixin.is_cached - A (1) M 24:4 FieldCacheMixin.set_cached_value - A (1) M 27:4 FieldCacheMixin.delete_cached_value - A (1) M 53:4 CheckFieldDefaultMixin.check - A (1) django/db/models/fields/related.py M 1235:4 ManyToManyField._check_relationship_model - E (31) M 509:4 ForeignObject._check_unique_target - C (15) M 186:4 RelatedField._check_clashes - C (12) M 1570:4 ManyToManyField._get_m2m_reverse_attr - C (11) M 1428:4 ManyToManyField._check_table_uniqueness - B (10) M 1471:4 ManyToManyField.deconstruct - B (10) M 1552:4 ManyToManyField._get_m2m_attr - B (8) M 1600:4 ManyToManyField.contribute_to_class - B (8) M 576:4 ForeignObject.deconstruct - B (7) M 611:4 ForeignObject.resolve_related_fields - B (7) M 794:4 ForeignKey.__init__ - B (7) M 874:4 ForeignKey.deconstruct - B (7) M 653:4 ForeignObject.get_instance_value_for_fields - B (6) C 1124:0 ManyToManyField - B (6) M 1144:4 ManyToManyField.__init__ - B (6) M 1202:4 ManyToManyField._check_ignored_options - B (6) M 108:4 RelatedField._check_related_name_is_valid - A (5) M 156:4 RelatedField._check_relation_model_exists - A (5) M 289:4 RelatedField.contribute_to_class - A (5) M 487:4 ForeignObject._check_to_fields_exist - A (5) M 841:4 ForeignKey._check_on_delete - A (5) M 965:4 ForeignKey.get_db_prep_save - A (5) F 37:0 resolve_relation - A (4) C 83:0 RelatedField - A (4) M 127:4 RelatedField._check_related_query_name_is_valid - A (4) M 171:4 RelatedField._check_referencing_to_swapped_model - A (4) M 320:4 RelatedField.deconstruct - A (4) M 343:4 RelatedField.get_reverse_related_filter - A (4) C 444:0 ForeignObject - A (4) M 750:4 ForeignObject.contribute_to_related_class - A (4) M 913:4 ForeignKey.validate - A (4) M 935:4 ForeignKey.resolve_related_fields - A (4) M 1017:4 ForeignKey.get_col - A (4) M 1507:4 ManyToManyField._get_path_info - A (4) M 1670:4 ManyToManyField.formfield - A (4) F 62:0 lazy_related_operation - A (3) M 363:4 RelatedField.swappable_setting - A (3) M 377:4 RelatedField.set_attributes_from_rel - A (3) M 421:4 RelatedField.related_query_name - A (3) M 643:4 ForeignObject.foreign_related_fields - A (3) M 674:4 ForeignObject.get_joining_columns - A (3) C 771:0 ForeignKey - A (3) M 1006:4 ForeignKey.convert_empty_strings - A (3) C 1027:0 OneToOneField - A (3) M 1062:4 OneToOneField.save_form_data - A (3) M 1539:4 ManyToManyField._get_m2m_db_table - A (3) M 1643:4 ManyToManyField.contribute_to_related_class - A (3) F 1077:0 create_many_to_many_intermediary_model - A (2) M 330:4 RelatedField.get_forward_related_filter - A (2) M 390:4 RelatedField.get_limit_choices_to - A (2) M 401:4 RelatedField.formfield - A (2) M 429:4 RelatedField.target_field - A (2) M 460:4 ForeignObject.__init__ - A (2) M 635:4 ForeignObject.reverse_related_fields - A (2) M 639:4 ForeignObject.local_related_fields - A (2) M 740:4 ForeignObject.get_lookups - A (2) M 864:4 ForeignKey._check_unique - A (2) M 953:4 ForeignKey.get_attname_column - A (2) M 958:4 ForeignKey.get_default - A (2) M 979:4 ForeignKey.contribute_to_related_class - A (2) M 984:4 ForeignKey.formfield - A (2) M 1011:4 ForeignKey.get_db_converters - A (2) M 1051:4 OneToOneField.deconstruct - A (2) M 1057:4 OneToOneField.formfield - A (2) M 1191:4 ManyToManyField._check_unique - A (2) M 1664:4 ManyToManyField.value_from_object - A (2) M 93:4 RelatedField.related_model - A (1) M 98:4 RelatedField.check - A (1) M 284:4 RelatedField.db_type - A (1) M 386:4 RelatedField.do_related_class - A (1) M 440:4 RelatedField.get_cache_name - A (1) M 480:4 ForeignObject.check - A (1) M 631:4 ForeignObject.related_fields - A (1) M 646:4 ForeignObject.get_local_related_value - A (1) M 649:4 ForeignObject.get_foreign_related_value - A (1) M 670:4 ForeignObject.get_attname_column - A (1) M 678:4 ForeignObject.get_reverse_joining_columns - A (1) M 681:4 ForeignObject.get_extra_descriptor_filter - A (1) M 696:4 ForeignObject.get_extra_restriction - A (1) M 710:4 ForeignObject.get_path_info - A (1) M 724:4 ForeignObject.get_reverse_path_info - A (1) M 746:4 ForeignObject.contribute_to_class - A (1) M 834:4 ForeignKey.check - A (1) M 892:4 ForeignKey.to_python - A (1) M 896:4 ForeignKey.target_field - A (1) M 899:4 ForeignKey.get_reverse_path_info - A (1) M 950:4 ForeignKey.get_attname - A (1) M 973:4 ForeignKey.get_db_prep_value - A (1) M 976:4 ForeignKey.get_prep_value - A (1) M 997:4 ForeignKey.db_check - A (1) M 1000:4 ForeignKey.db_type - A (1) M 1003:4 ForeignKey.db_parameters - A (1) M 1047:4 OneToOneField.__init__ - A (1) M 1072:4 OneToOneField._check_unique - A (1) M 1182:4 ManyToManyField.check - A (1) M 1533:4 ManyToManyField.get_path_info - A (1) M 1536:4 ManyToManyField.get_reverse_path_info - A (1) M 1661:4 ManyToManyField.set_attributes_from_rel - A (1) M 1667:4 ManyToManyField.save_form_data - A (1) M 1685:4 ManyToManyField.db_check - A (1) M 1688:4 ManyToManyField.db_type - A (1) M 1693:4 ManyToManyField.db_parameters - A (1) django/db/models/fields/proxy.py C 9:0 OrderWrt - A (2) M 15:4 OrderWrt.__init__ - A (1) django/db/models/fields/__init__.py M 243:4 Field._check_choices - D (22) M 632:4 Field.validate - C (13) M 416:4 Field.deconstruct - C (12) M 912:4 Field.formfield - C (11) M 1790:4 IntegerField.validators - C (11) M 863:4 Field.get_choices - B (10) M 1346:4 DateTimeField.to_python - B (9) M 1214:4 DateField.to_python - B (8) M 2196:4 TimeField._check_fix_default_value - B (8) M 616:4 Field.run_validators - B (7) M 966:4 BooleanField.to_python - B (7) M 1160:4 DateField._check_fix_default_value - B (7) M 1300:4 DateTimeField._check_fix_default_value - B (7) M 1687:4 FilePathField.deconstruct - B (7) M 524:4 Field.__lt__ - B (6) M 853:4 Field._get_default - B (6) M 1038:4 CharField._check_db_collation - B (6) M 1593:4 DurationField.to_python - B (6) M 2128:4 TextField._check_db_collation - B (6) M 2253:4 TimeField.to_python - B (6) M 131:4 Field.__init__ - A (5) M 774:4 Field.contribute_to_class - A (5) M 1017:4 CharField._check_max_length_attribute - A (5) M 1200:4 DateField.deconstruct - A (5) C 1285:0 DateTimeField - A (5) M 1405:4 DateTimeField.get_prep_value - A (5) M 1466:4 DecimalField._check_decimal_places - A (5) M 1490:4 DecimalField._check_max_digits - A (5) M 1965:4 GenericIPAddressField.get_prep_value - A (5) M 2239:4 TimeField.deconstruct - A (5) M 2430:4 UUIDField.to_python - A (5) C 85:0 Field - A (4) M 207:4 Field._check_field_name - A (4) M 319:4 Field._check_null_allowed_for_primary_keys - A (4) M 337:4 Field._check_backend_specific_checks - A (4) M 394:4 Field.get_col - A (4) M 550:4 Field.__deepcopy__ - A (4) M 767:4 Field.set_attributes_from_name - A (4) M 896:4 Field._get_flatchoices - A (4) C 955:0 BooleanField - A (4) M 988:4 BooleanField.formfield - A (4) C 1142:0 DateField - A (4) M 1244:4 DateField.pre_save - A (4) M 1394:4 DateTimeField.pre_save - A (4) M 1546:4 DecimalField.to_python - A (4) C 1764:0 IntegerField - A (4) M 1937:4 GenericIPAddressField.deconstruct - A (4) M 1950:4 GenericIPAddressField.to_python - A (4) C 2014:0 PositiveIntegerRelDbTypeMixin - A (4) M 2015:4 PositiveIntegerRelDbTypeMixin.__init_subclass__ - A (4) M 2091:4 SlugField.deconstruct - A (4) C 2178:0 TimeField - A (4) M 2281:4 TimeField.pre_save - A (4) M 2372:4 BinaryField.get_default - A (4) M 2420:4 UUIDField.get_db_prep_value - A (4) M 347:4 Field._check_validators - A (3) M 366:4 Field._check_deprecation_details - A (3) M 515:4 Field.__eq__ - A (3) M 543:4 Field.__hash__ - A (3) C 1001:0 CharField - A (3) M 1067:4 CharField.to_python - A (3) M 1076:4 CharField.formfield - A (3) C 1110:0 DateTimeCheckMixin - A (3) M 1119:4 DateTimeCheckMixin._check_mutually_exclusive_options - A (3) M 1152:4 DateField.__init__ - A (3) C 1441:0 DecimalField - A (3) M 1535:4 DecimalField.deconstruct - A (3) C 1576:0 DurationField - A (3) M 1612:4 DurationField.get_db_prep_value - A (3) C 1660:0 FilePathField - A (3) M 1676:4 FilePathField._check_allowing_files_or_folders - A (3) C 1724:0 FloatField - A (3) M 1731:4 FloatField.get_prep_value - A (3) M 1745:4 FloatField.to_python - A (3) M 1818:4 IntegerField.get_prep_value - A (3) M 1832:4 IntegerField.to_python - A (3) C 1904:0 GenericIPAddressField - A (3) M 1925:4 GenericIPAddressField._check_blank_and_null_values - A (3) C 2081:0 SlugField - A (3) C 2114:0 TextField - A (3) M 2152:4 TextField.to_python - A (3) M 2188:4 TimeField.__init__ - A (3) C 2333:0 BinaryField - A (3) M 2346:4 BinaryField._check_str_default_value - A (3) C 2397:0 UUIDField - A (3) C 2502:0 AutoFieldMeta - A (3) M 178:4 Field.__str__ - A (2) M 188:4 Field.__repr__ - A (2) M 240:4 Field._choices_is_value - A (2) M 307:4 Field._check_db_index - A (2) M 569:4 Field.__reduce__ - A (2) M 589:4 Field.get_pk_value_on_save - A (2) M 677:4 Field.db_check - A (2) M 689:4 Field.db_type - A (2) M 723:4 Field.cast_db_type - A (2) M 746:4 Field.get_db_converters - A (2) M 752:4 Field.unique - A (2) M 756:4 Field.db_tablespace - A (2) M 812:4 Field.get_attname_column - A (2) M 824:4 Field.get_prep_value - A (2) M 830:4 Field.get_db_prep_value - A (2) M 982:4 BooleanField.get_prep_value - A (2) M 1009:4 CharField.check - A (2) M 1059:4 CharField.cast_db_type - A (2) M 1087:4 CharField.deconstruct - A (2) M 1252:4 DateField.contribute_to_class - A (2) M 1268:4 DateField.get_db_prep_value - A (2) M 1274:4 DateField.value_to_string - A (2) M 1424:4 DateTimeField.get_db_prep_value - A (2) M 1430:4 DateTimeField.value_to_string - A (2) M 1453:4 DecimalField.check - A (2) M 1514:4 DecimalField._check_decimal_places_and_max_digits - A (2) M 1619:4 DurationField.get_db_converters - A (2) M 1625:4 DurationField.value_to_string - A (2) C 1636:0 EmailField - A (2) M 1703:4 FilePathField.get_prep_value - A (2) M 1709:4 FilePathField.formfield - A (2) M 1777:4 IntegerField._check_max_length_warning - A (2) C 1851:0 BigIntegerField - A (2) C 1866:0 SmallIntegerField - A (2) C 1873:0 IPAddressField - A (2) M 1894:4 IPAddressField.get_prep_value - A (2) M 1960:4 GenericIPAddressField.get_db_prep_value - A (2) C 1984:0 NullBooleanField - A (2) M 2027:4 PositiveIntegerRelDbTypeMixin.rel_db_type - A (2) C 2042:0 PositiveBigIntegerField - A (2) C 2055:0 PositiveIntegerField - A (2) C 2068:0 PositiveSmallIntegerField - A (2) M 2085:4 SlugField.__init__ - A (2) M 2121:4 TextField.check - A (2) M 2161:4 TextField.formfield - A (2) M 2171:4 TextField.deconstruct - A (2) M 2293:4 TimeField.get_db_prep_value - A (2) M 2299:4 TimeField.value_to_string - A (2) C 2310:0 URLField - A (2) M 2318:4 URLField.deconstruct - A (2) M 2337:4 BinaryField.__init__ - A (2) M 2358:4 BinaryField.deconstruct - A (2) M 2380:4 BinaryField.get_db_prep_value - A (2) M 2390:4 BinaryField.to_python - A (2) C 2450:0 AutoFieldMixin - A (2) M 2463:4 AutoFieldMixin._check_primary_key - A (2) M 2484:4 AutoFieldMixin.get_db_prep_value - A (2) M 2490:4 AutoFieldMixin.contribute_to_class - A (2) M 2523:4 AutoFieldMeta.__instancecheck__ - A (2) M 2526:4 AutoFieldMeta.__subclasscheck__ - A (2) C 2530:0 AutoField - A (2) C 2539:0 BigAutoField - A (2) C 2548:0 SmallAutoField - A (2) F 55:0 _load_field - A (1) F 74:0 _empty - A (1) F 80:0 return_None - A (1) C 42:0 Empty - A (1) C 46:0 NOT_PROVIDED - A (1) M 125:4 Field._description - A (1) M 196:4 Field.check - A (1) M 404:4 Field.cached_col - A (1) M 408:4 Field.select_format - A (1) M 507:4 Field.clone - A (1) M 561:4 Field.__copy__ - A (1) M 600:4 Field.to_python - A (1) M 609:4 Field.validators - A (1) M 663:4 Field.clean - A (1) M 674:4 Field.db_type_parameters - A (1) M 715:4 Field.rel_db_type - A (1) M 730:4 Field.db_parameters - A (1) M 743:4 Field.db_type_suffix - A (1) M 760:4 Field.db_returning - A (1) M 802:4 Field.get_filter_kwargs_for_object - A (1) M 809:4 Field.get_attname - A (1) M 817:4 Field.get_internal_type - A (1) M 820:4 Field.pre_save - A (1) M 840:4 Field.get_db_prep_save - A (1) M 844:4 Field.has_default - A (1) M 848:4 Field.get_default - A (1) M 889:4 Field.value_to_string - A (1) M 909:4 Field.save_form_data - A (1) M 950:4 Field.value_from_object - A (1) M 963:4 BooleanField.get_internal_type - A (1) M 1004:4 CharField.__init__ - A (1) M 1064:4 CharField.get_internal_type - A (1) M 1072:4 CharField.get_prep_value - A (1) C 1094:0 CommaSeparatedIntegerField - A (1) M 1112:4 DateTimeCheckMixin.check - A (1) M 1138:4 DateTimeCheckMixin._check_fix_default_value - A (1) M 1211:4 DateField.get_internal_type - A (1) M 1264:4 DateField.get_prep_value - A (1) M 1278:4 DateField.formfield - A (1) M 1343:4 DateTimeField.get_internal_type - A (1) M 1434:4 DateTimeField.formfield - A (1) M 1448:4 DecimalField.__init__ - A (1) M 1526:4 DecimalField.validators - A (1) M 1532:4 DecimalField.context - A (1) M 1543:4 DecimalField.get_internal_type - A (1) M 1560:4 DecimalField.get_db_prep_save - A (1) M 1563:4 DecimalField.get_prep_value - A (1) M 1567:4 DecimalField.formfield - A (1) M 1590:4 DurationField.get_internal_type - A (1) M 1629:4 DurationField.formfield - A (1) M 1640:4 EmailField.__init__ - A (1) M 1645:4 EmailField.deconstruct - A (1) M 1651:4 EmailField.formfield - A (1) M 1663:4 FilePathField.__init__ - A (1) M 1670:4 FilePathField.check - A (1) M 1720:4 FilePathField.get_internal_type - A (1) M 1742:4 FloatField.get_internal_type - A (1) M 1757:4 FloatField.formfield - A (1) M 1771:4 IntegerField.check - A (1) M 1829:4 IntegerField.get_internal_type - A (1) M 1844:4 IntegerField.formfield - A (1) M 1855:4 BigIntegerField.get_internal_type - A (1) M 1858:4 BigIntegerField.formfield - A (1) M 1869:4 SmallIntegerField.get_internal_type - A (1) M 1885:4 IPAddressField.__init__ - A (1) M 1889:4 IPAddressField.deconstruct - A (1) M 1900:4 IPAddressField.get_internal_type - A (1) M 1909:4 GenericIPAddressField.__init__ - A (1) M 1919:4 GenericIPAddressField.check - A (1) M 1947:4 GenericIPAddressField.get_internal_type - A (1) M 1976:4 GenericIPAddressField.formfield - A (1) M 1999:4 NullBooleanField.__init__ - A (1) M 2004:4 NullBooleanField.deconstruct - A (1) M 2010:4 NullBooleanField.get_internal_type - A (1) M 2045:4 PositiveBigIntegerField.get_internal_type - A (1) M 2048:4 PositiveBigIntegerField.formfield - A (1) M 2058:4 PositiveIntegerField.get_internal_type - A (1) M 2061:4 PositiveIntegerField.formfield - A (1) M 2071:4 PositiveSmallIntegerField.get_internal_type - A (1) M 2074:4 PositiveSmallIntegerField.formfield - A (1) M 2103:4 SlugField.get_internal_type - A (1) M 2106:4 SlugField.formfield - A (1) M 2117:4 TextField.__init__ - A (1) M 2149:4 TextField.get_internal_type - A (1) M 2157:4 TextField.get_prep_value - A (1) M 2250:4 TimeField.get_internal_type - A (1) M 2289:4 TimeField.get_prep_value - A (1) M 2303:4 TimeField.formfield - A (1) M 2314:4 URLField.__init__ - A (1) M 2324:4 URLField.formfield - A (1) M 2343:4 BinaryField.check - A (1) M 2366:4 BinaryField.get_internal_type - A (1) M 2369:4 BinaryField.get_placeholder - A (1) M 2386:4 BinaryField.value_to_string - A (1) M 2404:4 UUIDField.__init__ - A (1) M 2408:4 UUIDField.deconstruct - A (1) M 2413:4 UUIDField.get_internal_type - A (1) M 2416:4 UUIDField.get_prep_value - A (1) M 2443:4 UUIDField.formfield - A (1) M 2453:4 AutoFieldMixin.__init__ - A (1) M 2457:4 AutoFieldMixin.check - A (1) M 2475:4 AutoFieldMixin.deconstruct - A (1) M 2481:4 AutoFieldMixin.validate - A (1) M 2498:4 AutoFieldMixin.formfield - A (1) M 2520:4 AutoFieldMeta._subclasses - A (1) M 2532:4 AutoField.get_internal_type - A (1) M 2535:4 AutoField.rel_db_type - A (1) M 2541:4 BigAutoField.get_internal_type - A (1) M 2544:4 BigAutoField.rel_db_type - A (1) M 2550:4 SmallAutoField.get_internal_type - A (1) M 2553:4 SmallAutoField.rel_db_type - A (1) django/db/models/fields/reverse_related.py M 180:4 ForeignObjectRel.get_accessor_name - B (8) M 141:4 ForeignObjectRel.get_choices - A (5) C 280:0 ManyToManyRel - A (5) M 288:4 ManyToManyRel.__init__ - A (5) M 317:4 ManyToManyRel.get_related_field - A (5) C 20:0 ForeignObjectRel - A (2) M 39:4 ForeignObjectRel.__init__ - A (2) M 69:4 ForeignObjectRel.target_field - A (2) M 80:4 ForeignObjectRel.related_model - A (2) M 133:4 ForeignObjectRel.__eq__ - A (2) M 160:4 ForeignObjectRel.is_hidden - A (2) C 208:0 ManyToOneRel - A (2) M 245:4 ManyToOneRel.get_related_field - A (2) M 254:4 ManyToOneRel.set_field_name - A (2) C 258:0 OneToOneRel - A (2) M 57:4 ForeignObjectRel.hidden - A (1) M 61:4 ForeignObjectRel.name - A (1) M 65:4 ForeignObjectRel.remote_field - A (1) M 87:4 ForeignObjectRel.many_to_many - A (1) M 91:4 ForeignObjectRel.many_to_one - A (1) M 95:4 ForeignObjectRel.one_to_many - A (1) M 99:4 ForeignObjectRel.one_to_one - A (1) M 102:4 ForeignObjectRel.get_lookup - A (1) M 105:4 ForeignObjectRel.get_internal_type - A (1) M 109:4 ForeignObjectRel.db_type - A (1) M 112:4 ForeignObjectRel.__repr__ - A (1) M 120:4 ForeignObjectRel.identity - A (1) M 138:4 ForeignObjectRel.__hash__ - A (1) M 164:4 ForeignObjectRel.get_joining_columns - A (1) M 167:4 ForeignObjectRel.get_extra_restriction - A (1) M 170:4 ForeignObjectRel.set_field_name - A (1) M 197:4 ForeignObjectRel.get_path_info - A (1) M 200:4 ForeignObjectRel.get_cache_name - A (1) M 223:4 ManyToOneRel.__init__ - A (1) M 236:4 ManyToOneRel.__getstate__ - A (1) M 242:4 ManyToOneRel.identity - A (1) M 266:4 OneToOneRel.__init__ - A (1) M 310:4 ManyToManyRel.identity - A (1) django/db/models/fields/related_lookups.py M 62:4 RelatedIn.as_sql - C (12) C 46:0 RelatedIn - B (10) F 26:0 get_normalized_value - B (7) M 47:4 RelatedIn.get_prep_lookup - B (6) C 104:0 RelatedLookupMixin - B (6) M 105:4 RelatedLookupMixin.get_prep_lookup - A (5) M 121:4 RelatedLookupMixin.as_sql - A (4) C 7:0 MultiColSource - A (2) M 10:4 MultiColSource.__init__ - A (1) M 14:4 MultiColSource.__repr__ - A (1) M 18:4 MultiColSource.relabeled_clone - A (1) M 22:4 MultiColSource.get_lookup - A (1) C 135:0 RelatedExact - A (1) C 139:0 RelatedLessThan - A (1) C 143:0 RelatedGreaterThan - A (1) C 147:0 RelatedGreaterThanOrEqual - A (1) C 151:0 RelatedLessThanOrEqual - A (1) C 155:0 RelatedIsNull - A (1) django/db/models/fields/json.py C 395:0 KeyTransformIn - B (9) M 396:4 KeyTransformIn.resolve_expression_parameter - B (8) M 428:4 KeyTransformExact.process_rhs - B (8) M 42:4 JSONField._check_supported - B (7) M 170:4 HasKeyLookup.as_sql - B (6) C 418:0 KeyTransformExact - B (6) F 124:0 compile_json_path - A (5) M 24:4 JSONField.__init__ - A (5) M 75:4 JSONField.from_db_value - A (5) C 260:0 JSONExact - A (5) M 263:4 JSONExact.process_lhs - A (4) M 272:4 JSONExact.process_rhs - A (4) M 304:4 KeyTransform.preprocess_lhs - A (4) M 419:4 KeyTransformExact.process_lhs - A (4) C 494:0 KeyTransformNumericLookupMixin - A (4) C 16:0 JSONField - A (3) M 67:4 JSONField.deconstruct - A (3) C 137:0 DataContains - A (3) C 152:0 ContainedBy - A (3) C 167:0 HasKeyLookup - A (3) M 207:4 HasKeyLookup.as_postgresql - A (3) C 225:0 HasKeys - A (3) C 240:0 CaseInsensitiveMixin - A (3) C 296:0 KeyTransform - A (3) M 329:4 KeyTransform.as_postgresql - A (3) C 351:0 KeyTransformTextLookupMixin - A (3) C 371:0 KeyTransformIsNull - A (3) M 495:4 KeyTransformNumericLookupMixin.process_rhs - A (3) M 36:4 JSONField.check - A (2) M 90:4 JSONField.get_prep_value - A (2) M 95:4 JSONField.get_transform - A (2) M 101:4 JSONField.validate - A (2) M 141:4 DataContains.as_sql - A (2) M 156:4 ContainedBy.as_sql - A (2) M 230:4 HasKeys.get_prep_lookup - A (2) M 247:4 CaseInsensitiveMixin.process_lhs - A (2) M 253:4 CaseInsensitiveMixin.process_rhs - A (2) M 358:4 KeyTransformTextLookupMixin.__init__ - A (2) M 373:4 KeyTransformIsNull.as_oracle - A (2) M 384:4 KeyTransformIsNull.as_sqlite - A (2) M 447:4 KeyTransformExact.as_oracle - A (2) C 536:0 KeyTransformFactory - A (2) M 87:4 JSONField.get_internal_type - A (1) M 112:4 JSONField.value_to_string - A (1) M 115:4 JSONField.formfield - A (1) M 198:4 HasKeyLookup.as_mysql - A (1) M 201:4 HasKeyLookup.as_oracle - A (1) M 215:4 HasKeyLookup.as_sqlite - A (1) C 219:0 HasKey - A (1) C 234:0 HasAnyKeys - A (1) C 283:0 JSONIContains - A (1) M 300:4 KeyTransform.__init__ - A (1) M 316:4 KeyTransform.as_mysql - A (1) M 321:4 KeyTransform.as_oracle - A (1) M 340:4 KeyTransform.as_sqlite - A (1) C 346:0 KeyTextTransform - A (1) C 462:0 KeyTransformIExact - A (1) C 466:0 KeyTransformIContains - A (1) C 470:0 KeyTransformStartsWith - A (1) C 474:0 KeyTransformIStartsWith - A (1) C 478:0 KeyTransformEndsWith - A (1) C 482:0 KeyTransformIEndsWith - A (1) C 486:0 KeyTransformRegex - A (1) C 490:0 KeyTransformIRegex - A (1) C 502:0 KeyTransformLt - A (1) C 506:0 KeyTransformLte - A (1) C 510:0 KeyTransformGt - A (1) C 514:0 KeyTransformGte - A (1) M 538:4 KeyTransformFactory.__init__ - A (1) M 541:4 KeyTransformFactory.__call__ - A (1) django/db/models/sql/compiler.py M 497:4 SQLCompiler.as_sql - F (45) M 271:4 SQLCompiler.get_order_by - E (35) M 812:4 SQLCompiler.get_related_selections - E (31) M 442:4 SQLCompiler.get_combinator_sql - D (24) M 149:4 SQLCompiler.collapse_group_by - D (22) M 1341:4 SQLInsertCompiler.as_sql - C (19) M 63:4 SQLCompiler.get_group_by - C (16) M 724:4 SQLCompiler.find_ordering_name - C (14) M 1141:4 SQLCompiler.execute_sql - C (14) M 988:4 SQLCompiler.get_select_for_update_of_arguments - C (12) M 1465:4 SQLUpdateCompiler.as_sql - C (12) C 22:0 SQLCompiler - C (11) M 199:4 SQLCompiler.get_select - C (11) M 656:4 SQLCompiler.get_default_columns - B (10) C 1464:0 SQLUpdateCompiler - B (10) C 1232:0 SQLInsertCompiler - B (8) M 1306:4 SQLInsertCompiler.assemble_as_sql - B (8) M 1402:4 SQLInsertCompiler.execute_sql - B (8) M 1549:4 SQLUpdateCompiler.pre_sql_setup - B (8) M 407:4 SQLCompiler.get_extra_select - B (7) M 417:4 SQLCompiler.quote_name_unless_alias - B (7) M 778:4 SQLCompiler.get_from_clause - B (7) M 1528:4 SQLUpdateCompiler.execute_sql - B (6) M 1099:4 SQLCompiler.get_converters - A (5) M 1120:4 SQLCompiler.results_iter - A (5) M 1268:4 SQLInsertCompiler.prepare_value - A (5) F 1616:0 cursor_iter - A (4) M 700:4 SQLCompiler.get_distinct - A (4) M 1109:4 SQLCompiler.apply_converters - A (4) M 1221:4 SQLCompiler.explain_query - A (4) M 1236:4 SQLInsertCompiler.field_as_sql - A (4) M 43:4 SQLCompiler.setup_query - A (3) C 1423:0 SQLDeleteCompiler - A (3) M 1439:4 SQLDeleteCompiler.as_sql - A (3) C 1592:0 SQLAggregateCompiler - A (3) M 434:4 SQLCompiler.compile - A (2) M 765:4 SQLCompiler._setup_joins - A (2) M 1208:4 SQLCompiler.as_subquery_condition - A (2) M 1297:4 SQLInsertCompiler.pre_save_val - A (2) M 1425:4 SQLDeleteCompiler.single_alias - A (2) M 1430:4 SQLDeleteCompiler._as_sql - A (2) M 1593:4 SQLAggregateCompiler.as_sql - A (2) M 29:4 SQLCompiler.__init__ - A (1) M 49:4 SQLCompiler.pre_sql_setup - A (1) M 1089:4 SQLCompiler.deferred_to_columns - A (1) M 1134:4 SQLCompiler.has_results - A (1) django/db/models/sql/query.py M 1231:4 Query.build_filter - E (32) M 428:4 Query.get_aggregation - D (23) M 566:4 Query.combine - D (22) M 667:4 Query.deferred_to_data - D (22) M 1474:4 Query.names_to_path - D (22) M 2265:4 Query.trim_start - C (18) M 956:4 Query.join - C (15) M 2182:4 Query.set_values - C (14) M 848:4 Query.change_aliases - C (13) M 1577:4 Query.setup_joins - C (13) M 1726:4 Query.resolve_ref - C (13) M 1166:4 Query.build_lookup - C (12) M 1962:4 Query.add_ordering - C (12) M 786:4 Query.promote_joins - C (11) M 1047:4 Query.resolve_expression - C (11) M 1681:4 Query.trim_joins - C (11) M 2056:4 Query.add_extra - C (11) M 376:4 Query.rewrite_cols - B (10) M 2009:4 Query.set_group_by - B (9) M 300:4 Query.clone - B (8) M 531:4 Query.exists - B (8) M 1132:4 Query.check_related_objects - B (8) M 1919:4 Query.add_fields - B (8) M 1004:4 Query.join_parent_model - B (7) M 1445:4 Query.add_filtered_relation - B (7) M 2419:4 JoinPromoter.update_join_types - B (7) M 120:4 RawQuery._execute_query - B (6) C 140:0 Query - B (6) M 887:4 Query.bump_prefix - B (6) M 1845:4 Query.set_limits - B (6) M 2232:4 Query.annotation_select - B (6) M 2251:4 Query.extra_select - B (6) M 351:4 Query.chain - A (5) M 753:4 Query.table_alias - A (5) M 1085:4 Query.resolve_lookup_value - A (5) M 1103:4 Query.solve_lookup_type - A (5) M 1152:4 Query.check_filterable - A (5) M 1710:4 Query._gen_cols - A (5) M 1770:4 Query.split_exclude - A (5) C 2391:0 JoinPromoter - A (5) M 237:4 Query.output_field - A (4) M 285:4 Query.get_compiler - A (4) M 820:4 Query.demote_joins - A (4) M 1381:4 Query.add_q - A (4) M 1401:4 Query._add_q - A (4) M 1423:4 Query.build_filtered_relation_q - A (4) M 2040:4 Query.add_select_related - A (4) F 45:0 get_field_names_from_opts - A (3) F 52:0 get_children_from_q - A (3) F 2383:0 is_reverse_o2o - A (3) C 66:0 RawQuery - A (3) M 87:4 RawQuery.get_columns - A (3) M 110:4 RawQuery.params_type - A (3) M 245:4 Query.has_select_fields - A (3) M 948:4 Query.count_active_tables - A (3) M 1072:4 Query.get_external_cols - A (3) M 1121:4 Query.check_query_object_type - A (3) M 1211:4 Query.try_transform - A (3) M 2112:4 Query.add_immediate_loading - A (3) M 2339:4 Query.is_nullable - A (3) M 2397:4 JoinPromoter.__init__ - A (3) F 2358:0 get_order_dir - A (2) F 2372:0 add_to_dict - A (2) M 94:4 RawQuery.__iter__ - A (2) M 115:4 RawQuery.__str__ - A (2) M 249:4 Query.base_table - A (2) M 254:4 Query.identity - A (2) M 371:4 Query._get_col - A (2) M 517:4 Query.get_count - A (2) M 839:4 Query.reset_refcounts - A (2) M 936:4 Query.get_initial_alias - A (2) M 1037:4 Query.add_annotation - A (2) M 1079:4 Query.as_sql - A (2) M 1723:4 Query._gen_col_aliases - A (2) M 1837:4 Query.set_empty - A (2) M 1842:4 Query.is_empty - A (2) M 1873:4 Query.is_sliced - A (2) M 1876:4 Query.has_limit_one - A (2) M 1999:4 Query.clear_ordering - A (2) M 2092:4 Query.add_deferred_loading - A (2) M 2136:4 Query.get_loaded_field_names - A (2) M 2155:4 Query.get_loaded_field_names_cb - A (2) M 2159:4 Query.set_annotation_mask - A (2) M 2167:4 Query.append_annotation_mask - A (2) M 2171:4 Query.set_extra_mask - A (2) M 69:4 RawQuery.__init__ - A (1) M 81:4 RawQuery.chain - A (1) M 84:4 RawQuery.clone - A (1) M 106:4 RawQuery.__repr__ - A (1) M 148:4 Query.__init__ - A (1) M 261:4 Query.__str__ - A (1) M 272:4 Query.sql_with_params - A (1) M 279:4 Query.__deepcopy__ - A (1) M 292:4 Query.get_meta - A (1) M 366:4 Query.relabeled_clone - A (1) M 528:4 Query.has_filters - A (1) M 553:4 Query.has_results - A (1) M 558:4 Query.explain - A (1) M 778:4 Query.ref_alias - A (1) M 782:4 Query.unref_alias - A (1) M 1378:4 Query.add_filter - A (1) M 1398:4 Query.build_where - A (1) M 1868:4 Query.clear_limits - A (1) M 1879:4 Query.can_filter - A (1) M 1887:4 Query.clear_select_clause - A (1) M 1895:4 Query.clear_select_fields - A (1) M 1904:4 Query.add_select_col - A (1) M 1908:4 Query.set_select - A (1) M 1912:4 Query.add_distinct_fields - A (1) M 2088:4 Query.clear_deferred_loading - A (1) M 2412:4 JoinPromoter.add_votes - A (1) django/db/models/sql/subqueries.py M 77:4 UpdateQuery.add_update_values - B (8) M 119:4 UpdateQuery.get_related_updates - A (4) C 15:0 DeleteQuery - A (3) C 47:0 UpdateQuery - A (3) M 99:4 UpdateQuery.add_update_fields - A (3) M 20:4 DeleteQuery.do_query - A (2) M 29:4 DeleteQuery.delete_batch - A (2) M 70:4 UpdateQuery.update_batch - A (2) C 137:0 InsertQuery - A (2) C 152:0 AggregateQuery - A (2) M 52:4 UpdateQuery.__init__ - A (1) M 56:4 UpdateQuery._setup_query - A (1) M 65:4 UpdateQuery.clone - A (1) M 111:4 UpdateQuery.add_related_update - A (1) M 140:4 InsertQuery.__init__ - A (1) M 146:4 InsertQuery.insert_values - A (1) M 160:4 AggregateQuery.__init__ - A (1) django/db/models/sql/where.py M 32:4 WhereNode.split_having - C (14) M 65:4 WhereNode.as_sql - C (14) M 196:4 WhereNode._resolve_node - A (5) C 14:0 WhereNode - A (4) M 130:4 WhereNode.relabel_aliases - A (4) M 142:4 WhereNode.clone - A (3) M 166:4 WhereNode._contains_aggregate - A (3) M 176:4 WhereNode._contains_over_clause - A (3) C 220:0 ExtraWhere - A (3) M 228:4 ExtraWhere.as_sql - A (3) M 117:4 WhereNode.get_group_by_cols - A (2) M 126:4 WhereNode.set_source_expressions - A (2) M 186:4 WhereNode.is_summary - A (2) M 190:4 WhereNode._resolve_leaf - A (2) C 212:0 NothingNode - A (2) C 233:0 SubqueryConstraint - A (2) M 123:4 WhereNode.get_source_expressions - A (1) M 157:4 WhereNode.relabeled_clone - A (1) M 162:4 WhereNode.copy - A (1) M 172:4 WhereNode.contains_aggregate - A (1) M 182:4 WhereNode.contains_over_clause - A (1) M 205:4 WhereNode.resolve_expression - A (1) M 216:4 NothingNode.as_sql - A (1) M 224:4 ExtraWhere.__init__ - A (1) M 238:4 SubqueryConstraint.__init__ - A (1) M 244:4 SubqueryConstraint.as_sql - A (1) django/db/models/sql/datastructures.py M 59:4 Join.as_sql - B (7) C 24:0 Join - A (3) M 104:4 Join.relabeled_clone - A (3) C 8:0 MultiJoin - A (2) M 127:4 Join.__eq__ - A (2) M 135:4 Join.equals - A (2) C 151:0 BaseTable - A (2) M 166:4 BaseTable.as_sql - A (2) M 178:4 BaseTable.__eq__ - A (2) M 14:4 MultiJoin.__init__ - A (1) C 20:0 Empty - A (1) M 41:4 Join.__init__ - A (1) M 118:4 Join.identity - A (1) M 132:4 Join.__hash__ - A (1) M 140:4 Join.demote - A (1) M 145:4 Join.promote - A (1) M 162:4 BaseTable.__init__ - A (1) M 171:4 BaseTable.relabeled_clone - A (1) M 175:4 BaseTable.identity - A (1) M 183:4 BaseTable.__hash__ - A (1) M 186:4 BaseTable.equals - A (1) django/views/csrf.py F 104:0 csrf_failure - A (3) django/views/debug.py F 486:0 technical_404_response - C (20) M 263:4 ExceptionReporter.get_traceback_data - C (18) M 195:4 SafeExceptionReporterFilter.get_traceback_frame_variables - C (13) M 88:4 SafeExceptionReporterFilter.cleanse_setting - B (10) M 156:4 SafeExceptionReporterFilter.get_post_parameters - B (8) M 366:4 ExceptionReporter._get_lines_from_file - B (7) M 406:4 ExceptionReporter.get_traceback_frames - B (7) M 439:4 ExceptionReporter.get_exception_traceback_frames - B (7) C 80:0 SafeExceptionReporterFilter - B (6) C 246:0 ExceptionReporter - B (6) M 349:4 ExceptionReporter._get_source - B (6) M 142:4 SafeExceptionReporterFilter.get_cleansed_multivaluedict - A (5) M 114:4 SafeExceptionReporterFilter.get_safe_settings - A (3) M 125:4 SafeExceptionReporterFilter.get_safe_request_meta - A (3) M 181:4 SafeExceptionReporterFilter.cleanse_special_types - A (3) M 400:4 ExceptionReporter._get_explicit_or_implicit_cause - A (3) F 50:0 technical_500_response - A (2) C 36:0 CallableSettingWrapper - A (2) F 65:0 get_default_exception_reporter_filter - A (1) F 70:0 get_exception_reporter_filter - A (1) F 75:0 get_exception_reporter_class - A (1) F 546:0 default_urlconf - A (1) C 32:0 ExceptionCycleWarning - A (1) M 43:4 CallableSettingWrapper.__init__ - A (1) M 46:4 CallableSettingWrapper.__repr__ - A (1) M 133:4 SafeExceptionReporterFilter.is_active - A (1) M 251:4 ExceptionReporter.__init__ - A (1) M 335:4 ExceptionReporter.get_traceback_html - A (1) M 342:4 ExceptionReporter.get_traceback_text - A (1) django/views/static.py F 19:0 serve - B (7) F 83:0 directory_index - B (6) F 108:0 was_modified_since - B (6) django/views/defaults.py F 33:0 page_not_found - B (6) F 82:0 server_error - A (3) F 103:0 bad_request - A (3) F 125:0 permission_denied - A (3) django/views/i18n.py F 20:0 set_language - C (11) M 255:4 JavaScriptCatalog.get_catalog - B (9) M 212:4 JavaScriptCatalog.get_paths - B (8) C 185:0 JavaScriptCatalog - A (5) M 235:4 JavaScriptCatalog._plural_string - A (4) M 246:4 JavaScriptCatalog.get_plural - A (4) M 200:4 JavaScriptCatalog.get - A (3) M 224:4 JavaScriptCatalog._num_plurals - A (3) F 67:0 get_formats - A (2) M 284:4 JavaScriptCatalog.render_to_response - A (2) C 297:0 JSONCatalog - A (2) M 277:4 JavaScriptCatalog.get_context_data - A (1) M 314:4 JSONCatalog.render_to_response - A (1) django/views/decorators/clickjacking.py F 4:0 xframe_options_deny - A (1) F 22:0 xframe_options_sameorigin - A (1) F 40:0 xframe_options_exempt - A (1) django/views/decorators/csrf.py C 15:0 _EnsureCsrfToken - A (2) C 30:0 _EnsureCsrfCookie - A (2) F 49:0 csrf_exempt - A (1) M 17:4 _EnsureCsrfToken._reject - A (1) M 31:4 _EnsureCsrfCookie._reject - A (1) M 34:4 _EnsureCsrfCookie.process_view - A (1) django/views/decorators/vary.py F 6:0 vary_on_headers - A (1) F 27:0 vary_on_cookie - A (1) django/views/decorators/cache.py F 9:0 cache_page - A (1) F 28:0 cache_control - A (1) F 45:0 never_cache - A (1) django/views/decorators/common.py F 4:0 no_append_slash - A (1) django/views/decorators/debug.py F 6:0 sensitive_variables - A (3) F 47:0 sensitive_post_parameters - A (3) django/views/decorators/http.py F 18:0 require_http_methods - A (1) F 55:0 condition - A (1) F 116:0 etag - A (1) F 120:0 last_modified - A (1) django/views/generic/list.py M 21:4 MultipleObjectMixin.get_queryset - B (6) M 54:4 MultipleObjectMixin.paginate_queryset - B (6) C 139:0 BaseListView - B (6) M 141:4 BaseListView.get - A (5) C 161:0 MultipleObjectTemplateResponseMixin - A (5) M 113:4 MultipleObjectMixin.get_context_data - A (4) M 165:4 MultipleObjectTemplateResponseMixin.get_template_names - A (4) C 9:0 MultipleObjectMixin - A (3) M 104:4 MultipleObjectMixin.get_context_object_name - A (3) M 50:4 MultipleObjectMixin.get_ordering - A (1) M 77:4 MultipleObjectMixin.get_paginate_by - A (1) M 83:4 MultipleObjectMixin.get_paginator - A (1) M 90:4 MultipleObjectMixin.get_paginate_orphans - A (1) M 97:4 MultipleObjectMixin.get_allow_empty - A (1) C 194:0 ListView - A (1) django/views/generic/__init__.py C 20:0 GenericViewError - A (1) django/views/generic/edit.py M 74:4 ModelFormMixin.get_form_class - B (7) C 70:0 ModelFormMixin - A (4) M 110:4 ModelFormMixin.get_success_url - A (3) C 10:0 FormMixin - A (2) M 29:4 FormMixin.get_form - A (2) M 35:4 FormMixin.get_form_kwargs - A (2) M 49:4 FormMixin.get_success_url - A (2) M 63:4 FormMixin.get_context_data - A (2) M 103:4 ModelFormMixin.get_form_kwargs - A (2) C 129:0 ProcessFormView - A (2) M 135:4 ProcessFormView.post - A (2) C 160:0 BaseCreateView - A (2) C 182:0 BaseUpdateView - A (2) C 202:0 DeletionMixin - A (2) M 220:4 DeletionMixin.get_success_url - A (2) M 17:4 FormMixin.get_initial - A (1) M 21:4 FormMixin.get_prefix - A (1) M 25:4 FormMixin.get_form_class - A (1) M 55:4 FormMixin.form_valid - A (1) M 59:4 FormMixin.form_invalid - A (1) M 123:4 ModelFormMixin.form_valid - A (1) M 131:4 ProcessFormView.get - A (1) M 148:4 ProcessFormView.put - A (1) C 152:0 BaseFormView - A (1) C 156:0 FormView - A (1) M 166:4 BaseCreateView.get - A (1) M 170:4 BaseCreateView.post - A (1) C 175:0 CreateView - A (1) M 188:4 BaseUpdateView.get - A (1) M 192:4 BaseUpdateView.post - A (1) C 197:0 UpdateView - A (1) M 206:4 DeletionMixin.delete - A (1) M 217:4 DeletionMixin.post - A (1) C 228:0 BaseDeleteView - A (1) C 236:0 DeleteView - A (1) django/views/generic/detail.py C 111:0 SingleObjectTemplateResponseMixin - B (10) M 20:4 SingleObjectMixin.get_object - B (9) M 115:4 SingleObjectTemplateResponseMixin.get_template_names - B (9) C 8:0 SingleObjectMixin - A (5) M 58:4 SingleObjectMixin.get_queryset - A (3) M 82:4 SingleObjectMixin.get_context_object_name - A (3) M 91:4 SingleObjectMixin.get_context_data - A (3) C 103:0 BaseDetailView - A (2) M 78:4 SingleObjectMixin.get_slug_field - A (1) M 105:4 BaseDetailView.get - A (1) C 164:0 DetailView - A (1) django/views/generic/dates.py F 634:0 _get_next_prev - C (11) M 318:4 BaseDateListView.get_dated_queryset - B (6) M 351:4 BaseDateListView.get_date_list - B (6) C 478:0 BaseWeekArchiveView - A (5) C 575:0 BaseDateDetailView - A (5) M 31:4 YearMixin.get_year - A (4) M 80:4 MonthMixin.get_month - A (4) M 132:4 DayMixin.get_day - A (4) M 178:4 WeekMixin.get_week - A (4) C 293:0 BaseDateListView - A (4) M 481:4 BaseWeekArchiveView.get_dated_items - A (4) M 580:4 BaseDateDetailView.get_object - A (4) C 68:0 MonthMixin - A (3) M 101:4 MonthMixin._get_next_month - A (3) C 166:0 WeekMixin - A (3) M 214:4 WeekMixin._get_weekday - A (3) C 229:0 DateMixin - A (3) M 260:4 DateMixin._make_date_lookup_arg - A (3) C 375:0 BaseArchiveIndexView - A (3) C 397:0 BaseYearArchiveView - A (3) F 618:0 _date_from_string - A (2) F 724:0 timezone_today - A (2) C 19:0 YearMixin - A (2) M 52:4 YearMixin._get_next_year - A (2) C 120:0 DayMixin - A (2) M 199:4 WeekMixin._get_next_week - A (2) M 234:4 DateMixin.get_date_field - A (2) M 251:4 DateMixin.uses_datetime_field - A (2) M 273:4 DateMixin._make_single_date_lookup - A (2) M 311:4 BaseDateListView.get_ordering - A (2) M 381:4 BaseArchiveIndexView.get_dated_items - A (2) M 402:4 BaseYearArchiveView.get_dated_items - A (2) C 443:0 BaseMonthArchiveView - A (2) C 526:0 BaseDayArchiveView - A (2) C 562:0 BaseTodayArchiveView - A (2) M 24:4 YearMixin.get_year_format - A (1) M 44:4 YearMixin.get_next_year - A (1) M 48:4 YearMixin.get_previous_year - A (1) M 63:4 YearMixin._get_current_year - A (1) M 73:4 MonthMixin.get_month_format - A (1) M 93:4 MonthMixin.get_next_month - A (1) M 97:4 MonthMixin.get_previous_month - A (1) M 115:4 MonthMixin._get_current_month - A (1) M 125:4 DayMixin.get_day_format - A (1) M 145:4 DayMixin.get_next_day - A (1) M 149:4 DayMixin.get_previous_day - A (1) M 153:4 DayMixin._get_next_day - A (1) M 161:4 DayMixin._get_current_day - A (1) M 171:4 WeekMixin.get_week_format - A (1) M 191:4 WeekMixin.get_next_week - A (1) M 195:4 WeekMixin.get_previous_week - A (1) M 210:4 WeekMixin._get_current_week - A (1) M 240:4 DateMixin.get_allow_future - A (1) M 298:4 BaseDateListView.get - A (1) M 307:4 BaseDateListView.get_dated_items - A (1) M 344:4 BaseDateListView.get_date_list_period - A (1) C 392:0 ArchiveIndexView - A (1) M 430:4 BaseYearArchiveView.get_make_object_list - A (1) C 438:0 YearArchiveView - A (1) M 447:4 BaseMonthArchiveView.get_dated_items - A (1) C 473:0 MonthArchiveView - A (1) C 521:0 WeekArchiveView - A (1) M 528:4 BaseDayArchiveView.get_dated_items - A (1) M 540:4 BaseDayArchiveView._get_dated_items - A (1) C 557:0 DayArchiveView - A (1) M 565:4 BaseTodayArchiveView.get_dated_items - A (1) C 570:0 TodayArchiveView - A (1) C 610:0 DateDetailView - A (1) django/views/generic/base.py M 170:4 RedirectView.get_redirect_url - A (5) M 49:4 View.as_view - A (4) C 16:0 ContextMixin - A (3) C 30:0 View - A (3) M 82:4 View.setup - A (3) M 114:4 View._allowed_methods - A (3) C 118:0 TemplateResponseMixin - A (3) M 188:4 RedirectView.get - A (3) M 23:4 ContextMixin.get_context_data - A (2) M 38:4 View.__init__ - A (2) M 90:4 View.dispatch - A (2) M 141:4 TemplateResponseMixin.get_template_names - A (2) C 154:0 TemplateView - A (2) C 163:0 RedirectView - A (2) M 100:4 View.http_method_not_allowed - A (1) M 107:4 View.options - A (1) M 125:4 TemplateResponseMixin.render_to_response - A (1) M 158:4 TemplateView.get - A (1) M 202:4 RedirectView.head - A (1) M 205:4 RedirectView.post - A (1) M 208:4 RedirectView.options - A (1) M 211:4 RedirectView.delete - A (1) M 214:4 RedirectView.put - A (1) M 217:4 RedirectView.patch - A (1) django/conf/__init__.py M 132:4 Settings.__init__ - C (11) M 64:4 LazySettings.__getattr__ - B (6) C 131:0 Settings - A (5) M 96:4 LazySettings.configure - A (4) C 33:0 LazySettings - A (3) M 39:4 LazySettings._setup - A (3) C 181:0 UserSettingsHolder - A (3) M 195:4 UserSettingsHolder.__getattr__ - A (3) M 209:4 UserSettingsHolder.__dir__ - A (3) M 215:4 UserSettingsHolder.is_overridden - A (3) C 21:0 SettingsReference - A (2) M 56:4 LazySettings.__repr__ - A (2) M 80:4 LazySettings.__setattr__ - A (2) M 112:4 LazySettings._add_script_prefix - A (2) M 204:4 UserSettingsHolder.__delattr__ - A (2) M 26:4 SettingsReference.__new__ - A (1) M 29:4 SettingsReference.__init__ - A (1) M 91:4 LazySettings.__delattr__ - A (1) M 126:4 LazySettings.configured - A (1) M 171:4 Settings.is_overridden - A (1) M 174:4 Settings.__repr__ - A (1) M 187:4 UserSettingsHolder.__init__ - A (1) M 200:4 UserSettingsHolder.__setattr__ - A (1) M 221:4 UserSettingsHolder.__repr__ - A (1) django/conf/global_settings.py F 9:0 gettext_noop - A (1) django/conf/project_template/manage.py-tpl F 7:0 main - A (2) django/conf/urls/static.py F 10:0 static - A (4) django/conf/urls/i18n.py F 24:0 is_language_prefix_patterns_used - A (3) F 8:0 i18n_patterns - A (2) django/apps/config.py M 100:4 AppConfig.create - E (38) C 15:0 AppConfig - B (7) M 273:4 AppConfig.get_models - B (6) M 18:4 AppConfig.__init__ - A (5) M 72:4 AppConfig._path_from_module - A (5) M 257:4 AppConfig.get_model - A (3) M 294:4 AppConfig.import_models - A (2) M 60:4 AppConfig.__repr__ - A (1) M 64:4 AppConfig.default_auto_field - A (1) M 69:4 AppConfig._is_default_auto_field_overridden - A (1) M 303:4 AppConfig.ready - A (1) django/apps/registry.py M 61:4 Apps.populate - C (13) M 244:4 Apps.get_containing_app_config - B (6) M 278:4 Apps.get_swappable_settings_name - B (6) M 186:4 Apps.get_model - A (5) M 299:4 Apps.set_available_apps - A (5) C 13:0 Apps - A (4) M 20:4 Apps.__init__ - A (4) M 148:4 Apps.get_app_config - A (4) M 213:4 Apps.register_model - A (4) M 363:4 Apps.clear_cache - A (4) M 379:4 Apps.lazy_model_operation - A (4) M 127:4 Apps.check_apps_ready - A (2) M 138:4 Apps.check_models_ready - A (2) M 167:4 Apps.get_models - A (2) M 235:4 Apps.is_installed - A (2) M 263:4 Apps.get_registered_model - A (2) M 332:4 Apps.set_installed_apps - A (2) M 418:4 Apps.do_pending_operations - A (2) M 143:4 Apps.get_app_configs - A (1) M 327:4 Apps.unset_available_apps - A (1) M 357:4 Apps.unset_installed_apps - A (1) 9678 blocks (classes, functions, methods) analyzed. Average complexity: A (2.9974168216573673)
0cbe693bc463036967beb1b9c537e5c1404d4e7a
[ "Markdown", "Python" ]
3
Python
devankestel/snowball
785557e2ce0a18cd7f7ee65151caa27c36f67cd0
aa4b28a2f89f326dd77ac01ac9ddc7c8864846e9
refs/heads/master
<repo_name>dangxia/study<file_sep>/study-nio/src/test/java/com/github/dangxia/nio/buffer/ByteBufferUseCase.java package com.github.dangxia.nio.buffer; import static junit.framework.Assert.assertEquals; import static org.mockito.Matchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.channels.SeekableByteChannel; import org.junit.Test; import org.mockito.invocation.InvocationOnMock; import org.mockito.stubbing.Answer; public class ByteBufferUseCase { @Test public void test() throws IOException { SeekableByteChannel c = mock(SeekableByteChannel.class); when(c.read((ByteBuffer) any())).thenAnswer(ReadAnswer.write(10)).thenAnswer(ReadAnswer.write(5)); when(c.write((ByteBuffer) any())).thenAnswer(WriteAnswer.write(5)).thenAnswer(WriteAnswer.write(5)); ByteBuffer bb = ByteBuffer.allocate(30); c.read(bb); assertEquals(bb.remaining(), 20); bb.flip(); assertEquals(bb.remaining(), 10); c.write(bb); assertEquals(bb.remaining(), 5); bb.compact(); assertEquals(bb.position(), 5); assertEquals(bb.remaining(), 25); bb.flip(); c.write(bb); assertEquals(bb.remaining(), 0); bb.clear(); c.read(bb); c.read(bb); assertEquals(bb.remaining(), 20); bb.flip(); c.write(bb); assertEquals(bb.remaining(), 5); bb.clear(); assertEquals(bb.remaining(), 30); } private static class ReadAnswer implements Answer<Integer> { private final int times; public ReadAnswer(final int times) { this.times = times; } @Override public Integer answer(InvocationOnMock invocation) throws Throwable { ByteBuffer bb = (ByteBuffer) (invocation.getArguments()[0]); for (int i = 0; i < times; i++) { bb.put((byte) i); } return times; } public static ReadAnswer write(int times) { return new ReadAnswer(times); } } private static class WriteAnswer implements Answer<Integer> { private final int times; public WriteAnswer(final int times) { this.times = times; } @Override public Integer answer(InvocationOnMock invocation) throws Throwable { ByteBuffer bb = (ByteBuffer) (invocation.getArguments()[0]); for (int i = 0; i < times; i++) { bb.get(); } return times; } public static WriteAnswer write(int times) { return new WriteAnswer(times); } } } <file_sep>/study.go/src/hehe/html/download.go package html import ( "net/http" "fmt" "syscall" "io/ioutil" "regexp" "strings" "os" "io" ) type Node struct { Url string IsLeaf bool Name string List *[]*Node } func (node *Node) GetList() *[]*Node { if node.List == nil { node.List = node.fetchList() } return node.List } func (node *Node) fetchList() *[]*Node { resp, error := http.Get(node.Url) if error != nil { fmt.Println("fetch error") syscall.Exit(1) } defer resp.Body.Close() body, error := ioutil.ReadAll(resp.Body) if error != nil { fmt.Println("body error") syscall.Exit(1) } str := string(body); rg, error := regexp.Compile(`<td><a\s+href="([^\.][^"]+)"\s*>([^<]+)<.*?</td>`) result := make([]*Node, 0) for _, item := range rg.FindAllStringSubmatch(str, len(str)) { inner := item[2] url := item[1] isLeaf := !strings.HasSuffix(inner, "/") var name string if isLeaf { name = url[strings.LastIndex(url, "/") + 1:] } else { strs := strings.Split(url, "/") name = strs[len(strs) - 2] } if strings.HasSuffix(name,`SNAPSHOT`) { continue } node := Node{Url: url, Name: name, IsLeaf: isLeaf} result = append(result, &node) } return &result } func (node *Node) DownLoad(basePath string, depth int) { if node.IsLeaf { out, err := os.Create(basePath + string(os.PathSeparator) + node.Name) defer out.Close() if (err != nil) { fmt.Println("create file error", err) os.Exit(1) } resp, err := http.Get(node.Url) defer resp.Body.Close() _, err = io.Copy(out, resp.Body) } else { depth := depth + 1 childPath := basePath + string(os.PathSeparator) + node.Name os.MkdirAll(childPath, 0755) if depth == 2 { fmt.Println("download...", childPath) } for _, child := range *(node.GetList()) { child.DownLoad(childPath, depth) } } } <file_sep>/study.protobuffer2/protoc.sh #!/usr/bin/env bash cd src/main protoc --java_out=java/ resources/proto/AddressBook.proto<file_sep>/study.go/src/hehe/test.go package main import ( "hehe/html" "os" ) func main() { //fmt.Println(html.List("http://nexus.bigdata.letv.com/nexus/content/groups/public/le/data/bdp/")) os.MkdirAll("/tmp/hexh/sdf", 0755) p := html.Node{Url:"http://nexus.bigdata.letv.com/nexus/content/groups/public/le/data/bdp/", IsLeaf:false} p.DownLoad("/tmp/hexh/sdf",0) } <file_sep>/study-nio/src/main/java/com/github/dangxia/nio/bytebuffer/ByteBufferSamples.java package com.github.dangxia.nio.bytebuffer; import java.nio.ByteBuffer; public class ByteBufferSamples { static void byteBuferfAction() { ByteBuffer bb = ByteBuffer.allocate(8); for (int i = 0; i < 5; i++) { bb.put((byte) i); } System.out.println(bb.remaining()); bb.flip(); for (int i = 0; i < 3; i++) { bb.get(); } bb.compact(); System.out.println(bb.remaining()); } public static void main(String[] args) { byteBuferfAction(); } } <file_sep>/study.go.bak/ch1/dup2.go package main import ( "os" "bufio" "fmt" ) func main() { counts := make(map[string]int) if len(os.Args[1:]) == 0 { countLines(os.Stdin, counts, true) } else { for _, arg := range os.Args[1:] { f, err := os.Open(arg) if err != nil { fmt.Fprintf(os.Stderr, "open file %s failed,%v\n", arg, err) continue } countFileLines(f, counts) } } for line, count := range counts { if count > 1 { fmt.Printf("line: %s, count: %d\n", line, count) } } } func countFileLines(file *os.File, counts map[string]int) { countLines(file, counts, false) } func countLines(file *os.File, counts map[string]int, isStdin bool) { scanner := bufio.NewScanner(file) for scanner.Scan() { text := scanner.Text(); if isStdin && text == "quit" { break } counts[text]++ } } <file_sep>/study.go.bak/b/test.go package b import "fmt" func Test(){ fmt.Print("helslf") } <file_sep>/study-kafka/src/main/java/com/github/dangxia/PartitionInfo.java package com.github.dangxia; import java.util.List; import java.util.Map; import java.util.Map.Entry; import kafka.api.FetchRequestBuilder; import kafka.javaapi.FetchResponse; import kafka.javaapi.consumer.SimpleConsumer; import kafka.javaapi.message.ByteBufferMessageSet; import kafka.message.MessageAndOffset; import org.apache.curator.framework.CuratorFramework; import org.apache.curator.framework.CuratorFrameworkFactory; import org.apache.curator.retry.ExponentialBackoffRetry; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import stat.commons.kafka.KafkaUtils; import stat.commons.kafka.model.Broker; import stat.commons.kafka.model.PartitionState; public class PartitionInfo { private static final Logger LOG = LoggerFactory .getLogger(PartitionInfo.class); public static void main(String[] args) { CuratorFramework client = CuratorFrameworkFactory.builder() .connectString(Props.ZOOKEEPER_KAFKA_LIST) .retryPolicy(new ExponentialBackoffRetry(500, 3)).build(); client.start(); Map<Broker, List<PartitionState>> data = KafkaUtils.getPartitionState( client, "test-kafka-hexh"); client.close(); for (Entry<Broker, List<PartitionState>> entry : data.entrySet()) { LOG.info("broker: {}", entry.getKey()); for (PartitionState state : entry.getValue()) { LOG.info("\tstate: {}", state); showData(state); } } } public static void showData(PartitionState state) { String topic = state.getBrokerAndTopicPartition().getTopicPartition() .getTopic(); int partition = state.getBrokerAndTopicPartition().getTopicPartition() .getPartition(); SimpleConsumer consumer = createSimpleConsumer(state .getBrokerAndTopicPartition().getBroker()); showDetails(consumer, topic, partition, state.getLatestOffset()); showDetails(consumer, topic, partition, state.getEarliestOffset()); consumer.close(); } private static void showDetails(SimpleConsumer consumer, String topic, int partition, long offset) { ByteBufferMessageSet byteBufferMessageSet = fetch(consumer, topic, partition, offset); for (MessageAndOffset messageAndOffset : byteBufferMessageSet) { LOG.info("\toffset: {}", messageAndOffset.offset()); } } private static ByteBufferMessageSet fetch(SimpleConsumer consumer, String topic, int partition, long offset) { FetchRequestBuilder builder = createFetchRequestBuilder(topic, partition, offset); FetchResponse fetchResponse = null; try { fetchResponse = consumer.fetch(builder.build()); if (fetchResponse.hasError()) { short errorCode = fetchResponse.errorCode(topic, partition); throw new RuntimeException( "Error encountered during a fetch request from Kafka,Error Code generated : " + errorCode); } else { return fetchResponse.messageSet(topic, partition); } } catch (Exception e) { throw new RuntimeException("Exception generated during fetch", e); } } private static FetchRequestBuilder createFetchRequestBuilder(String topic, int partition, long offset) { FetchRequestBuilder builder = new FetchRequestBuilder(); builder.clientId("storm_kafka_consumer").maxWait(100).minBytes(1); // kafkaFetchMessageMaxBytes 1M builder.addFetch(topic, partition, offset, 8388608); return builder; } public static SimpleConsumer createSimpleConsumer(Broker broker) { // kafkaSocketTimeoutMs 3s // kafkaSocketReceiveBufferBytes 32K return new SimpleConsumer(broker.host(), broker.port(), 3000, 262144, "storm_kafka_consumer"); } } <file_sep>/study.go/src/ch10/b/t0.go package b type T0 string <file_sep>/study-nio/src/main/java/com/github/dangxia/nio/telnet/NioEchoTelnetProxy.java package com.github.dangxia.nio.telnet; import static com.github.dangxia.nio.telnet.Code.PROXY_PORT; import static com.github.dangxia.nio.telnet.Code.SERVER_PORT; import static java.nio.channels.SelectionKey.OP_ACCEPT; import static java.nio.channels.SelectionKey.OP_CONNECT; import static java.nio.channels.SelectionKey.OP_WRITE; import java.io.IOException; import java.net.InetSocketAddress; import java.nio.channels.SelectionKey; import java.nio.channels.Selector; import java.nio.channels.ServerSocketChannel; import java.nio.channels.SocketChannel; import java.util.Iterator; import java.util.Set; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.github.dangxia.nio.telnet.attach.ChannelAttach; import com.github.dangxia.nio.telnet.attach.ProxyAttach; import com.google.common.base.Throwables; public class NioEchoTelnetProxy { protected final static Logger LOG = LoggerFactory.getLogger(NioEchoTelnetProxy.class); private final Selector selector; private ServerSocketChannel serverSocketChannel; public NioEchoTelnetProxy() throws IOException { selector = Selector.open(); } public void start() throws IOException { serverSocketChannel = ServerSocketChannel.open(); serverSocketChannel.socket().bind(new InetSocketAddress(PROXY_PORT)); serverSocketChannel.configureBlocking(false); serverSocketChannel.register(selector, OP_ACCEPT); LOG.info("proxy started"); while (!Thread.interrupted()) { int ready = selector.select(500); if (ready > 0) { Set<SelectionKey> keys = selector.selectedKeys(); Iterator<SelectionKey> iter = keys.iterator(); while (iter.hasNext()) { SelectionKey key = iter.next(); iter.remove(); if (key.isValid()) { if (key.isAcceptable()) { accept(key); } else if (key.isConnectable()) { connect(key); } else { if (key.isValid() && key.isWritable()) { write(key); } if (key.isValid() && key.isReadable()) { read(key); } } } } } } Set<SelectionKey> keys = selector.keys(); Iterator<SelectionKey> iter = keys.iterator(); while (iter.hasNext()) { SelectionKey key = iter.next(); if (key.isValid()) { try { key.channel().close(); } catch (IOException e) { Throwables.propagate(e); } key.cancel(); } } System.out.println("proxy shutdown"); } private void connect(SelectionKey key) throws IOException { ((ChannelAttach) key.attachment()).finishConnect(); } private void write(SelectionKey key) throws IOException { ChannelAttach attach = (ChannelAttach) key.attachment(); attach.write(); } private void read(SelectionKey key) throws IOException { ChannelAttach attach = (ChannelAttach) key.attachment(); attach.read(); } private void accept(SelectionKey key) throws IOException { ServerSocketChannel serverSocketChannel = (ServerSocketChannel) key.channel(); SocketChannel socketChannel = serverSocketChannel.accept(); socketChannel.configureBlocking(false); socketChannel.socket().setTcpNoDelay(true); socketChannel.socket().setKeepAlive(true); SelectionKey clientKey = socketChannel.register(selector, OP_WRITE); SelectionKey serverkey = connectServer(); ProxyAttach attach = new ProxyAttach(clientKey, serverkey); clientKey.attach(attach.getClientAttach()); serverkey.attach(attach.getServerAttach()); } private SelectionKey connectServer() throws IOException { SocketChannel socketChannel = SocketChannel.open(); socketChannel.configureBlocking(false); socketChannel.connect(new InetSocketAddress(SERVER_PORT)); return socketChannel.register(selector, OP_CONNECT); } } <file_sep>/leetcode/src/main/java/com/github/dangxia/addTwoNumbers/Solution.java package com.github.dangxia.addTwoNumbers; public class Solution { public ListNode addTwoNumbers(ListNode l1, ListNode l2) { int total = l1.val + l2.val; int reminder = total % 10; int inc = total != reminder ? 1 : 0; ListNode root = new ListNode(reminder); ListNode parent = root; while (l1.next != null && l2.next != null) { l1 = l1.next; l2 = l2.next; total = l1.val + l2.val + inc; reminder = total % 10; inc = total != reminder ? 1 : 0; ListNode curr = new ListNode(reminder); parent.next = curr; parent = curr; } if (l1.next != null || l2.next != null) { ListNode tail = l1.next != null ? l1.next : l2.next; while (inc > 0 && tail != null) { total = tail.val + inc; reminder = total % 10; inc = total != reminder ? 1 : 0; ListNode curr = new ListNode(reminder); parent.next = curr; parent = curr; tail = tail.next; } if (inc == 0) { parent.next = tail; } } if (inc > 0) { parent.next = new ListNode(inc); } return root; } }<file_sep>/study-nio/src/main/java/com/github/dangxia/nio/file/FileSender.java package com.github.dangxia.nio.file; import static java.nio.channels.SelectionKey.OP_ACCEPT; import static java.nio.channels.SelectionKey.OP_WRITE; import java.io.File; import java.io.IOException; import java.io.RandomAccessFile; import java.net.InetSocketAddress; import java.nio.ByteBuffer; import java.nio.channels.SelectionKey; import java.nio.channels.Selector; import java.nio.channels.ServerSocketChannel; import java.nio.channels.SocketChannel; import java.util.Iterator; import java.util.Set; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.common.base.Throwables; public class FileSender { /** * 当写缓存区满时:不触发OP_WRITE channel.write写直到写缓存区满,立即返回 * 如果channel被client关闭,channel.write 报java.io.IOException: Connection reset * by peer */ private static final Logger LOG = LoggerFactory.getLogger(FileSender.class); private final Selector selector; private final RandomAccessFile r; private ServerSocketChannel serverSocketChannel; public FileSender(File file) throws IOException { this.selector = Selector.open(); this.r = new RandomAccessFile(file, "r"); } public void start() throws IOException { serverSocketChannel = ServerSocketChannel.open(); serverSocketChannel.socket().bind(new InetSocketAddress(9999)); serverSocketChannel.configureBlocking(false); serverSocketChannel.register(selector, OP_ACCEPT); LOG.info("started"); while (!Thread.interrupted()) { try { int ready = selector.select(500); if (ready > 0) { Set<SelectionKey> keys = selector.selectedKeys(); Iterator<SelectionKey> iter = keys.iterator(); while (iter.hasNext()) { SelectionKey key = iter.next(); iter.remove(); if (key.isAcceptable()) { accept(key); } else if (key.isWritable()) { write(key); } else if (key.isReadable()) { read(key); } } } } catch (Exception e) { Throwables.propagate(e); } } Set<SelectionKey> keys = selector.keys(); Iterator<SelectionKey> iter = keys.iterator(); while (iter.hasNext()) { SelectionKey key = iter.next(); if (key.isValid()) { close(key); } } LOG.info("shutdown"); } private void read(SelectionKey key) throws IOException { SocketChannel channel = (SocketChannel) key.channel(); ByteBuffer bb = ByteBuffer.allocate(64); int read = channel.read(bb); LOG.info("read: {}", read); if (read == -1) { close(key); } } private void close(SelectionKey key) throws IOException { key.cancel(); key.channel().close(); LOG.info("channel close"); } private void write(SelectionKey key) throws IOException { SocketChannel channel = (SocketChannel) key.channel(); long offset = getOffset(key); long remain = r.length() - offset; long write = r.getChannel().transferTo(offset, remain, channel); LOG.info("offset: {},write: {}", offset, write); setOffset(key, offset + write); } private long getOffset(SelectionKey key) throws IOException { Long offset = (Long) key.attachment(); if (offset == null) { return 0l; } return offset.longValue(); } private void setOffset(SelectionKey key, long offset) throws IOException { if (r.length() == offset) { // key.interestOps(key.interestOps() & ~OP_WRITE | OP_READ); close(key); } else { key.attach(offset); } } private void accept(SelectionKey key) throws IOException { SocketChannel socketChannel = serverSocketChannel.accept(); socketChannel.configureBlocking(false); socketChannel.socket().setTcpNoDelay(true); socketChannel.socket().setKeepAlive(true); socketChannel.register(selector, OP_WRITE); LOG.info("new conn registered"); } public static void main(String[] args) throws IOException { File file = new File("/home/hexh/download/eclipse-java-mars-1-linux-gtk-x86_64.tar.gz"); FileSender sender = new FileSender(file); sender.start(); } } <file_sep>/study-jedis/src/main/java/com/github/dangxia/jedis/JedisTransactionsWitPipeline.java package com.github.dangxia.jedis; import redis.clients.jedis.Jedis; import redis.clients.jedis.Pipeline; import redis.clients.jedis.Response; public class JedisTransactionsWitPipeline { public static void main(String[] args) { Jedis jedis = RedisCreator.createJedis(); // jedis.flushAll(); Pipeline pipeline = jedis.pipelined(); Response<Long> incr = pipeline.incr("test-incr"); pipeline.multi(); pipeline.set("kk", "pp"); pipeline.set("pp", "kk"); pipeline.exec(); pipeline.multi(); pipeline.set("kk", "pp2"); pipeline.set("pp", "kk2"); pipeline.discard(); pipeline.sync(); jedis.close(); System.out.println(incr.get()); } } <file_sep>/study-jedis/src/main/java/com/github/dangxia/jedis/RedisTransactions.java package com.github.dangxia.jedis; import java.util.List; import java.util.concurrent.CountDownLatch; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import redis.clients.jedis.Jedis; import redis.clients.jedis.Response; import redis.clients.jedis.Transaction; import com.google.common.base.Joiner; public class RedisTransactions { public static final String WATCHED_KEY = "watched-key"; private final static Logger LOG = LoggerFactory .getLogger(RedisTransactions.class); public static void usage() { Jedis jedis = RedisCreator.createJedis(); Transaction transaction = jedis.multi(); Response<Long> foo = transaction.incr("foo"); Response<Long> bar = transaction.incr("bar"); List<Object> results = transaction.exec(); jedis.close(); LOG.info("foo: " + foo.get()); LOG.info("bar: " + bar.get()); LOG.info("results: " + (Joiner.on(',').join(results))); } public static void error() { Jedis jedis = RedisCreator.createJedis(); Transaction transaction = jedis.multi(); Response<String> r1 = transaction.set("a", "1"); Response<String> r2 = transaction.lpop("a"); Response<String> r3 = transaction.set("a", "2"); List<Object> results = transaction.exec(); jedis.close(); LOG.info("r1: " + r1.get()); try { LOG.info("r2: " + r2.get()); } catch (Exception e) { LOG.warn("r2 get() throw a exception", e); } LOG.info("r3: " + r3.get()); LOG.info("results: " + (Joiner.on(',').join(results))); } public static void main(String[] args) throws InterruptedException { testWatch(); } public static void testWatchFailed() throws InterruptedException { final CountDownLatch countDownLatch = new CountDownLatch(1); final CountDownLatch countDownLatch2 = new CountDownLatch(1); new Thread() { public void run() { try { countDownLatch.await(); Jedis jedis = RedisCreator.createJedis(); jedis.set(WATCHED_KEY, "10"); jedis.close(); countDownLatch2.countDown(); } catch (Exception e) { } }; }.start(); Jedis jedis = RedisCreator.createJedis(); jedis.set(WATCHED_KEY, "10"); jedis.watch(WATCHED_KEY); countDownLatch.countDown(); countDownLatch2.await(); Transaction transaction = jedis.multi(); Response<String> setResp = transaction.set(WATCHED_KEY, "1"); List<Object> results = transaction.exec(); jedis.close(); LOG.info("results :" + String.valueOf(results)); try { LOG.info("setResp :" + String.valueOf(setResp.get())); } catch (Exception e) { LOG.warn("watched keys changed", e); } } public static void testWatch() throws InterruptedException { Jedis jedis = RedisCreator.createJedis(); jedis.del(WATCHED_KEY); int threadNum = 10; CountDownLatch countDownLatch = new CountDownLatch(threadNum); for (int i = 0; i < threadNum; i++) { new Incr(countDownLatch).start(); } countDownLatch.await(); LOG.info(jedis.get(WATCHED_KEY)); jedis.close(); } public static class Incr extends Thread { private final Jedis jedis; private final CountDownLatch countDownLatch; private long retryTimes = 0l; public Incr(CountDownLatch countDownLatch) { this.jedis = RedisCreator.createJedis(); this.countDownLatch = countDownLatch; } protected void incr() { while (true) { if (doIncr()) { break; } else { retryTimes++; } } } protected boolean doIncr() { jedis.watch(WATCHED_KEY); String val = jedis.get(WATCHED_KEY); Transaction transaction = jedis.multi(); if (val == null) { transaction.set(WATCHED_KEY, "1"); } else { transaction.set(WATCHED_KEY, String.valueOf(Integer.parseInt(val) + 1)); } List<Object> results = transaction.exec(); if (results == null) { return false; } return true; } @Override public void run() { int i = 0; while (i++ < 100) { incr(); } LOG.info(getName() + " retry " + retryTimes + " times"); jedis.close(); countDownLatch.countDown(); } } } <file_sep>/study.go/src/ch01/p4.go package main import ( "os" "bufio" "fmt" ) func main() { counts := make(map[string]map[string]int) for _, file := range os.Args[1:] { fileHd, _ := os.Open(file) countLines2(fileHd, counts) fileHd.Close() } for token, set := range counts { total := 0 for _, count := range set { total += count } if total <= 1 { continue } fmt.Printf("token: %q \n", token) for fileName, count := range set { fmt.Printf("\tfile: %s, count: %d\n", fileName, count) } fmt.Printf("total: %d\n", total) fmt.Println("--------------------------------") } } func countLines2(file *os.File, counts map[string]map[string]int) { scanner := bufio.NewScanner(file) for scanner.Scan() { token := scanner.Text() set := counts[token] if set == nil { set = make(map[string]int) counts[token] = set } set[file.Name()]++ } } <file_sep>/study-lock/src/main/java/com/github/dangxia/LockSupportTest.java package com.github.dangxia; import java.util.concurrent.TimeUnit; import java.util.concurrent.locks.LockSupport; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class LockSupportTest { private static final Logger LOG = LoggerFactory .getLogger(LockSupportTest.class); public static void main(String[] args) throws InterruptedException { Thread t = new Thread() { @Override public void run() { try { TimeUnit.SECONDS.sleep(5); LOG.info("thread park once"); LockSupport.park(); LOG.info("thread park twice"); LockSupport.park(); LOG.info("thread park twice end"); } catch (Exception e) { } } }; t.start(); LOG.info("unpark thread twice"); LockSupport.unpark(t); LockSupport.unpark(t); TimeUnit.SECONDS.sleep(10); LockSupport.unpark(t); } } <file_sep>/study-jedis/src/main/java/com/github/dangxia/jedis/JedisEval.java package com.github.dangxia.jedis; import java.util.List; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import redis.clients.jedis.Jedis; import com.github.dangxia.jedis.util.JedisUtls; import com.github.dangxia.jedis.util.JedisUtls.JedisRunable; public class JedisEval { private static final Logger LOG = LoggerFactory.getLogger(JedisEval.class); public static void main(String[] args) { JedisUtls.execute(testLog()); } public static JedisRunable testSimple() { return new JedisRunable() { @Override public void run(Jedis jedis) { Object result = jedis.eval( "return {KEYS[1],KEYS[2],ARGV[1],ARGV[2]}", 2, "key1", "key2", "first", "second"); displayEvalResult(result); } }; } public static JedisRunable testConversion1() { return new JedisRunable() { @Override public void run(Jedis jedis) { jedis.set("foo", "bar"); displayEvalResult(jedis.eval("return 10", 0)); displayEvalResult(jedis.eval("return {1,2,{3,'Hello World!'}}", 0)); displayEvalResult(jedis.eval("return redis.call('get','foo')", 0)); displayEvalResult(jedis.eval( "return {1,2,3.3333,'foo',nil,'bar'}", 0)); displayEvalResult(jedis.eval("return true", 0)); displayEvalResult(jedis.eval("return false", 0)); displayEvalResult(jedis.eval( "return redis.call('set','foo','kk')", 0)); } }; } public static JedisRunable testHelper() { return new JedisRunable() { @Override public void run(Jedis jedis) { try { displayEvalResult(jedis.eval("return {err='My Error'}", 0)); } catch (Exception e) { LOG.info("eval error", e); } try { displayEvalResult(jedis.eval( "return redis.error_reply('My Error')", 0)); } catch (Exception e) { LOG.info("eval error", e); } displayEvalResult(jedis.eval( "return redis.status_reply('success')", 0)); } }; } public static JedisRunable testErrorHandling() { return new JedisRunable() { @Override public void run(Jedis jedis) { jedis.del("foo"); jedis.lpush("foo", "a"); try { displayEvalResult(jedis.eval( "return redis.call('get','foo')", 0)); } catch (Exception e) { LOG.info("eval error", e); } try { displayEvalResult(jedis.eval( "return redis.pcall('get','foo')", 0)); } catch (Exception e) { LOG.info("eval error", e); } } }; } public static JedisRunable testEvalsha() { return new JedisRunable() { @Override public void run(Jedis jedis) { jedis.del("foo"); jedis.set("foo", "bar"); displayEvalResult(jedis.eval("return redis.sha1hex(ARGV[1])", 0, "return redis.call('get','foo')")); displayEvalResult(jedis.eval("return redis.call('get','foo')", 0)); displayEvalResult(jedis .evalsha("6b1bf486c81ceb7edf3c093f4c48582e38c0e791")); try { displayEvalResult(jedis .evalsha("ffffffffffffffffffffffffffffffffffffffff")); } catch (Exception e) { LOG.info("eval error", e); } } }; } public static JedisRunable testScriptCmds() { return new JedisRunable() { @Override public void run(Jedis jedis) { final String script_sha1 = "6b1bf486c81ceb7edf3c093f4c48582e38c0e791"; LOG.info("script flush: " + jedis.scriptFlush()); LOG.info( "script {} exists: " + jedis.scriptExists(script_sha1), script_sha1); LOG.info("script load: " + jedis.scriptLoad("return redis.call('get','foo')")); LOG.info( "script {} exists: " + jedis.scriptExists(script_sha1), script_sha1); LOG.info("script flush: " + jedis.scriptFlush()); LOG.info( "script {} exists: " + jedis.scriptExists(script_sha1), script_sha1); } }; } public static JedisRunable testLog() { return new JedisRunable() { @Override public void run(Jedis jedis) { jedis.eval( "redis.log(redis.LOG_WARNING,\"Something is wrong with this script.\")", 0); } }; } public static void displayEvalResult(Object result) { displayEvalResult(result, 0); } public static void displayEvalResult(Object result, int indent) { StringBuffer sb = new StringBuffer("\nresult:\n"); displayEvalResultStr(result, indent, sb); LOG.info(sb.toString()); } public static StringBuffer addIndent(int indent, StringBuffer sb) { for (int i = 0; i < indent; i++) { sb.append(" "); } return sb; } public static void displayEvalResultStr(Object result, int indent, StringBuffer sb) { if (result == null) { addIndent(indent, sb).append("null"); } else if (result instanceof List) { addIndent(indent, sb).append("[\n"); @SuppressWarnings("unchecked") List<Object> list = (List<Object>) result; for (Object object : list) { displayEvalResultStr(object, indent + 1, sb); } addIndent(indent, sb).append("]"); } else { addIndent(indent, sb).append( result.getClass().getSimpleName() + ":").append( result.toString() + "\n"); } } } <file_sep>/study.go/src/hehe/maven/maven.go package maven import ( "io/ioutil" "os" "fmt" "strings" "encoding/xml" "path/filepath" "os/exec" ) type Artifact struct { Path string PomPath string ArtifactType ArtifactType CxtPath string PathName string } type Project struct { XMLName xml.Name `xml:"project"` Packaging string `xml:"packaging"` } type ArtifactType int const ( UNKNOWN ArtifactType = iota POM JAR WAR ) func (a *Artifact) Untar(parentPath string) { target := parentPath + string(os.PathSeparator) + a.PathName os.MkdirAll(target, 0755) if a.ArtifactType == POM { bytes, _ := ioutil.ReadFile(a.PomPath) ioutil.WriteFile(target + string(os.PathSeparator) + "pom.xml", bytes, 0644) } else if a.ArtifactType == JAR { a.unJAR(target) } else if a.ArtifactType == WAR { a.unWar(target) } } func (a *Artifact) unJAR(target string) { srcPath := target + string(os.PathSeparator) + "src" + string(os.PathSeparator) + "main" + string(os.PathSeparator) + "java" os.MkdirAll(srcPath, 0755) Decompile(a.CxtPath, srcPath) UnzipAndRemove(srcPath + string(os.PathSeparator) + filepath.Base(a.CxtPath)) copyTo(a.PomPath, target + string(os.PathSeparator) + "pom.xml") os.RemoveAll(srcPath + string(os.PathSeparator) + "META-INF") } func (a *Artifact) unWar(target string) { resourcesPath := target + string(os.PathSeparator) + "src" + string(os.PathSeparator) + "main" + string(os.PathSeparator) + "resources" webappPath := target + string(os.PathSeparator) + "src" + string(os.PathSeparator) + "main" + string(os.PathSeparator) + "webapp" os.MkdirAll(resourcesPath, 0755) os.MkdirAll(webappPath, 0755) Unzip(a.CxtPath, webappPath) os.RemoveAll(webappPath + string(os.PathSeparator) + "META-INF") os.RemoveAll(webappPath + string(os.PathSeparator) + "WEB-INF" + string(os.PathSeparator) + "lib") copyTo(a.PomPath, target + string(os.PathSeparator) + "pom.xml") os.Rename(webappPath + string(os.PathSeparator) + "WEB-INF" + string(os.PathSeparator) + "classes", resourcesPath) } func copyTo(source string, target string) { fi, err := os.Stat(target) if err == nil && fi.IsDir() { target = target + string(os.PathSeparator) + filepath.Base(source) } bytes, _ := ioutil.ReadFile(source) ioutil.WriteFile(target, bytes, 0644) } func UnzipAndRemove(cxtPath string) { cmd := exec.Command("unzip", cxtPath, "-d", filepath.Dir(cxtPath)) cmd.Stdin = os.Stdin cmd.Stderr = os.Stderr cmd.Stdout = os.Stdout cmd.Run() os.Remove(cxtPath) } func Unzip(cxtPath string, targetPath string) { cmd := exec.Command("unzip", cxtPath, "-d", targetPath) cmd.Stdin = os.Stdin cmd.Stderr = os.Stderr cmd.Stdout = os.Stdout cmd.Run() } func Decompile(cxtPath string, targetPath string) { cmd := exec.Command("java", "-jar", "/home/hexh/develop/gits/github/fernflower/fernflower.jar", "-dgs=1", cxtPath, targetPath) cmd.Stdin = os.Stdin cmd.Stderr = os.Stderr cmd.Stdout = os.Stdout cmd.Run() } func GetArtifacts(basePath string) *[]*Artifact { artifacts, _ := ioutil.ReadDir(basePath) result := make([]*Artifact, 0); for _, artifact := range artifacts { verPath := basePath + string(os.PathSeparator) + artifact.Name() + string(os.PathSeparator) + "1.0" if _, err := os.Stat(verPath); err != nil { fmt.Println(verPath, "not found") continue } result = append(result, createArtifact(verPath)) } return &result } func createArtifact(verPath string) *Artifact { pomPath := getPomPath(verPath) artifactType := getArtifactType(pomPath) cxtPath := getCxtPath(pomPath, artifactType) pathName := filepath.Base(filepath.Dir(verPath)) return &Artifact{Path:verPath, PomPath:pomPath, ArtifactType:artifactType, CxtPath:cxtPath, PathName:pathName} } func getCxtPath(pomPath string, atype ArtifactType) string { if atype == UNKNOWN || atype == POM { return "" } baseName := filepath.Base(pomPath) if (atype == JAR) { baseName = strings.Replace(baseName, ".pom", ".jar", len(baseName)); } else { baseName = strings.Replace(baseName, ".pom", ".war", len(baseName)); } return filepath.Dir(pomPath) + string(os.PathSeparator) + baseName } func getArtifactType(pomPath string) ArtifactType { content, _ := ioutil.ReadFile(pomPath) var project Project _ = xml.Unmarshal(content, &project) switch project.Packaging { case `pom`:return POM case `war`:return WAR case `jar`: case ``: return JAR default: return UNKNOWN } return UNKNOWN } func getPomPath(verPath string) string { files, _ := ioutil.ReadDir(verPath) for _, f := range files { if strings.HasSuffix(f.Name(), ".pom") { return verPath + string(os.PathSeparator) + f.Name() } } return "" } <file_sep>/study.go.bak/ch1/dup3.go package main import ( "os" "fmt" "io/ioutil" "strings" ) func main() { if (len(os.Args) == 1) { fmt.Println("not found file name") return } counts := make(map[string]int) for _, filename := range os.Args[1:] { data, err := ioutil.ReadFile(filename) if err != nil { fmt.Printf("open file:%s error,%v\n", filename, err) return } for _, line := range strings.Split(string(data), "\n") { counts[line]++ } } for line, count := range counts { if count > 1 { fmt.Printf("line: %s count: %d\n", line, count) } } } <file_sep>/study-nio/pom.xml <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>com.github.dangxia</groupId> <artifactId>study-nio</artifactId> <version>0.0.1-SNAPSHOT</version> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <hadoop.version>2.2.0</hadoop.version> <hbase.version>0.98.12-hadoop2</hbase.version> <phoenix.version>4.5.1-HBase-0.98</phoenix.version> <mrunit.version>1.0.0</mrunit.version> <kafka.versin>0.8.1.1</kafka.versin> <storm.version>0.9.4</storm.version> <spring.version>3.2.0.RELEASE</spring.version> <avro.version>1.7.6</avro.version> <slf4j.version>1.7.2</slf4j.version> <log4j.version>1.2.16</log4j.version> <junit.version>4.8.1</junit.version> <mockito.version>1.9.5</mockito.version> <aspectj.version>1.7.2</aspectj.version> <jstorm.version>2.1.0</jstorm.version> <jdk.version>1.7</jdk.version> <maven.compiler.version>3.3</maven.compiler.version> <project.version>2.0</project.version> </properties> <dependencies> <dependency> <groupId>io.netty</groupId> <artifactId>netty-all</artifactId> <version>4.0.29.Final</version> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>${junit.version}</version> <scope>test</scope> </dependency> <dependency> <groupId>org.mockito</groupId> <artifactId>mockito-core</artifactId> <version>${mockito.version}</version> <scope>test</scope> </dependency> <dependency> <groupId>com.google.guava</groupId> <artifactId>guava</artifactId> <version>17.0</version> </dependency> <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>${log4j.version}</version> <scope>provided</scope> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-log4j12</artifactId> <version>${slf4j.version}</version> <scope>provided</scope> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-api</artifactId> <version>${slf4j.version}</version> <scope>provided</scope> </dependency> </dependencies> </project><file_sep>/study.go/src/ch10/helloworld.go package main import ( "fmt" //"ch1/a" "ch1/b" ) /* first comment second */ func main() { //line comment fmt.Println("Hello 世界") fmt.Println("Hello", "世界") fmt.Println('世') // console show 19990,because rune is numeric constant fmt.Printf("%c\n", '你') fmt.Printf("%q\n", '你') fmt.Printf("%+q\n", '你') var t0 b.T0 = "sdjlf" //t1 := "" //t0 = t1 //var t0 *T0 //t1 := new(T1) //t0 = t1 fmt.Println(t0) s := make([]int, 0, 2) s = append(s, 1) s = append(s, 2) s = append(s, 3) fmt.Println(s) } <file_sep>/study.go/src/ch01/p2.go package main import ( "time" "strconv" "fmt" "strings" ) func main() { start := time.Now().UnixNano() s := "" for i := 10000; i > 0; i-- { s = s + strconv.Itoa(i); } fmt.Printf("used mills: %f\n", float32(time.Now().UnixNano() - start) / 1000000.0) strs := make([]string, 10000) for i := 10000; i > 0; i-- { strs[i - 1] = strconv.Itoa(i); } start = time.Now().UnixNano(); strings.Join(strs, "") fmt.Printf("used mills: %f\n", float32(time.Now().UnixNano() - start) / 1000000.0) } <file_sep>/study.go/src/ch01/dup2.go package main import ( "bufio" "os" "fmt" ) func main() { counts := make(map[string]int) files := os.Args[1:] if len(files) == 0 { countLines(os.Stdin, counts, true) } else { for _, file := range files { fileReader, err := os.Open(file) if err != nil { fmt.Fprintf(os.Stderr, "dup2: %v\n", err) continue } countLines(fileReader, counts, false) fileReader.Close() } } for line, n := range counts { if n > 1 { fmt.Printf("line:%s\tcount:%d\n", line, n) } } } func countLines(r *os.File, counts map[string]int, isStdin bool) { scanner := bufio.NewScanner(r) for scanner.Scan() { token := scanner.Text() if isEOF(token, isStdin) { break } counts[token]++ } } func isEOF(token string, isStdin bool) bool { return isStdin && token == "" }<file_sep>/study-jstorm/src/main/java/com/github/dangxia/TestTopologyBuilder.java package com.github.dangxia; import backtype.storm.topology.TopologyBuilder; public class TestTopologyBuilder { public static void main(String[] args) { } } <file_sep>/study.go.bak/a/a2/test2.go package a2 import "github.com/open-falcon/agent/g" func Hehe(){ g.LocalIps } <file_sep>/study-nio/src/main/java/com/github/dangxia/nio/TestSocketChannel.java package com.github.dangxia.nio; import java.io.IOException; import java.net.InetSocketAddress; import java.nio.ByteBuffer; import java.nio.channels.SelectionKey; import java.nio.channels.Selector; import java.nio.channels.ServerSocketChannel; import java.nio.channels.SocketChannel; import java.util.Iterator; import java.util.concurrent.TimeUnit; public class TestSocketChannel { public static void main(String[] args) throws IOException, InterruptedException { final Selector selector = Selector.open(); Process p = new Process(selector); p.start(); ServerSocketChannel serverSocketChannel = ServerSocketChannel.open(); serverSocketChannel.configureBlocking(false); serverSocketChannel.bind(new InetSocketAddress(9797)); new Write().start(); while (true) { SocketChannel socketChannel = serverSocketChannel.accept(); if (socketChannel != null) { socketChannel.configureBlocking(false); socketChannel.register(selector, SelectionKey.OP_CONNECT | SelectionKey.OP_READ); System.out.println("sldjflsjldjf"); } } // serverSocketChannel.close(); } static class Write extends Thread { @Override public void run() { try { TimeUnit.SECONDS.sleep(1); SocketChannel socketChannel = SocketChannel.open(); socketChannel.configureBlocking(true); socketChannel.connect(new InetSocketAddress(9797)); if (socketChannel.finishConnect()) { ByteBuffer bb = ByteBuffer.allocate(5); bb.put("kk".getBytes()); bb.flip(); socketChannel.write(bb); System.out.println("finishConnect"); } TimeUnit.SECONDS.sleep(10); socketChannel.close(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } } static class Process extends Thread { private final Selector selector; public Process(Selector selector) { this.selector = selector; } @Override public void run() { try { while (true) { int readyChannels = selector.selectNow(); if (readyChannels == 0) continue; Iterator<SelectionKey> iterator = selector.selectedKeys() .iterator(); while (iterator.hasNext()) { SelectionKey selectionKey = iterator.next(); if (selectionKey.isConnectable()) { System.out.println("isConnectable"); } else if (selectionKey.isReadable()) { SocketChannel channel = (SocketChannel) selectionKey .channel(); ByteBuffer bb = ByteBuffer.allocate(5); int read = channel.read(bb); while (read > 0) { read = channel.read(bb); } bb.flip(); if (bb.limit() == 0) { channel.close(); System.out.println("close"); } else { byte[] bytes = new byte[bb.limit()]; bb.get(bytes); System.out.println(new String(bytes)); } // bb.clear(); // bb.compact(); } else { System.out.println("isWritable"); } iterator.remove(); } } } catch (IOException e) { e.printStackTrace(); } } } } <file_sep>/study-nio/src/main/java/com/github/dangxia/nio/ProxySocket5.java package com.github.dangxia.nio; import java.net.InetAddress; import java.net.InetSocketAddress; import java.net.Proxy; import java.net.Proxy.Type; import java.net.Socket; import java.net.UnknownHostException; import java.nio.channels.SocketChannel; public class ProxySocket5 { public static void main(String[] args) throws UnknownHostException { Proxy proxy = new Proxy(Type.SOCKS, new InetSocketAddress( InetAddress.getByName("172.16.17.32"), 10080)); Socket socket = new Socket(proxy); } } <file_sep>/study-nio/src/main/java/com/github/dangxia/nio/file/FileReceiver.java package com.github.dangxia.nio.file; import static java.nio.channels.SelectionKey.OP_CONNECT; import static java.nio.channels.SelectionKey.OP_READ; import java.io.File; import java.io.IOException; import java.io.RandomAccessFile; import java.net.InetSocketAddress; import java.nio.channels.FileChannel; import java.nio.channels.SelectionKey; import java.nio.channels.Selector; import java.nio.channels.SocketChannel; import java.util.Iterator; import java.util.Set; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.common.base.Throwables; public class FileReceiver { private static final Logger LOG = LoggerFactory.getLogger(FileReceiver.class); private final SocketChannel socketChannel; private final Selector selector; private final File file; public FileReceiver(File file) throws IOException { this.file = file; socketChannel = SocketChannel.open(); socketChannel.configureBlocking(false); socketChannel.connect(new InetSocketAddress(9999)); selector = Selector.open(); socketChannel.register(selector, OP_CONNECT | OP_READ); } public void start() { while (selector.isOpen() && !Thread.interrupted()) { try { int ready = selector.select(500); if (ready > 0) { Set<SelectionKey> keys = selector.selectedKeys(); Iterator<SelectionKey> iter = keys.iterator(); while (iter.hasNext()) { SelectionKey key = iter.next(); iter.remove(); if (key.isConnectable()) { socketChannel.finishConnect(); LOG.info("finishConnect"); } else if (key.isReadable()) { read(key); } } } } catch (Exception e) { Throwables.propagate(e); } } } private void read(SelectionKey key) throws IOException { FileChannelHolder holder = (FileChannelHolder) key.attachment(); if (holder == null) { holder = new FileChannelHolder(); key.attach(holder); } long position = holder.getPosition(); // socketChannel -1 still return 0 long read = holder.fileChannel.transferFrom(socketChannel, position, 1024); LOG.info("read:{}", read); if (read == 0) { holder.r.close(); holder.fileChannel.close(); key.cancel(); key.channel().close(); selector.close(); } else { holder.addRead(read); } } private class FileChannelHolder { private final FileChannel fileChannel; private final RandomAccessFile r; private long position; public FileChannelHolder() throws IOException { r = new RandomAccessFile(file, "rw"); fileChannel = r.getChannel(); this.position = 0l; } public long getPosition() { return position; } public void addRead(long read) { this.position += read; } } public static void main(String[] args) throws IOException { FileReceiver receiver = new FileReceiver( new File("/tmp/hexh/test/eclipse-java-mars-1-linux-gtk-x86_64.tar.gz")); receiver.start(); } } <file_sep>/study.go.bak/a/a1/test.go package a1 func Kkkkkk(){ } <file_sep>/study-nio/src/main/java/com/github/dangxia/nio/telnet/NioEchoServer.java package com.github.dangxia.nio.telnet; import static com.github.dangxia.nio.telnet.Code.CTRL_C_BYTES; import static com.github.dangxia.nio.telnet.Code.EXIT_BYTES; import static com.github.dangxia.nio.telnet.Code.HEAD_SIZE; import static com.github.dangxia.nio.telnet.Code.SERVER_PORT; import static com.github.dangxia.nio.telnet.Code.SHUTDOWN_BYTES; import static java.nio.channels.SelectionKey.OP_ACCEPT; import static java.nio.channels.SelectionKey.OP_READ; import java.io.IOException; import java.net.InetSocketAddress; import java.nio.ByteBuffer; import java.nio.channels.SelectionKey; import java.nio.channels.Selector; import java.nio.channels.ServerSocketChannel; import java.nio.channels.SocketChannel; import java.util.Arrays; import java.util.Iterator; import java.util.Set; import com.github.dangxia.nio.telnet.attach.ChannelAttach; import com.google.common.base.Throwables; public class NioEchoServer { private final Selector selector; private ServerSocketChannel serverSocketChannel; public NioEchoServer() throws IOException { selector = Selector.open(); } public void start() throws IOException { serverSocketChannel = ServerSocketChannel.open(); serverSocketChannel.socket().bind(new InetSocketAddress(SERVER_PORT)); serverSocketChannel.configureBlocking(false); serverSocketChannel.register(selector, OP_ACCEPT); System.out.println("started"); while (!Thread.interrupted()) { int ready = selector.select(500); if (ready > 0) { Set<SelectionKey> keys = selector.selectedKeys(); Iterator<SelectionKey> iter = keys.iterator(); while (iter.hasNext()) { SelectionKey key = iter.next(); iter.remove(); if (key.isAcceptable()) { accept(key); } else if (key.isWritable()) { write(key); } else if (key.isReadable()) { read(key); } } } } Set<SelectionKey> keys = selector.keys(); Iterator<SelectionKey> iter = keys.iterator(); while (iter.hasNext()) { SelectionKey key = iter.next(); if (key.isValid()) { try { key.channel().close(); } catch (IOException e) { Throwables.propagate(e); } key.cancel(); } } System.out.println("shutdown"); } private void write(SelectionKey key) throws IOException { NioEchoAttach reciever = (NioEchoAttach) key.attachment(); if (reciever != null) { reciever.write(); } } private void read(SelectionKey key) throws IOException { NioEchoAttach reciever = (NioEchoAttach) key.attachment(); if (reciever == null) { reciever = new NioEchoAttach(key); } reciever.read(); } private void accept(SelectionKey key) throws IOException { ServerSocketChannel serverSocketChannel = (ServerSocketChannel) key.channel(); SocketChannel socketChannel = serverSocketChannel.accept(); socketChannel.configureBlocking(false); socketChannel.socket().setTcpNoDelay(true); socketChannel.socket().setKeepAlive(true); socketChannel.register(selector, OP_READ); System.out.println("new conn registered"); } private class NioEchoAttach extends ChannelAttach { private int readTimes = 0; private final ByteBuffer head = ByteBuffer.allocate(HEAD_SIZE);; private ByteBuffer body; public NioEchoAttach(SelectionKey key) { super(key); } @Override protected int doWrite() throws IOException { int write = socketChannel.write(body); if (!body.hasRemaining()) { disableWrite().enableRead(); } head.clear(); body = null; LOG.info("write back size: {}", write); return write; } @Override protected int doRead() throws IOException { readTimes++; if (readTimes > 0) { LOG.info("read multi times: {}", readTimes); } int headRead = 0; if (head.hasRemaining()) { headRead = socketChannel.read(head); if (headRead == -1) { close(); return headRead; } } int bodyRead = 0; if (!head.hasRemaining()) { if (body == null) { head.flip(); body = ByteBuffer.allocate(head.getInt()); } if (body.hasRemaining()) { bodyRead = socketChannel.read(body); if (bodyRead == -1) { close(); return bodyRead; } } if (!body.hasRemaining()) { readComplete(); } } int size = bodyRead + headRead; LOG.info("receive size: {}", size); return size; } private void readComplete() throws IOException { readTimes = 0; body.flip(); byte[] bytes = new byte[body.remaining()]; body.get(bytes); body.rewind(); if (Arrays.equals(bytes, CTRL_C_BYTES) || Arrays.equals(bytes, EXIT_BYTES)) { close(); } else if (Arrays.equals(bytes, SHUTDOWN_BYTES)) { Thread.currentThread().interrupt(); } else { LOG.info("receive {}", new String(bytes)); disableRead().enableWrite(); } } } } <file_sep>/study.go/src/hehe/test2.go package main import ( "hehe/maven" "strings" "os" ) func main() { basePath := `/tmp/hexh/sdf` Artifacts := *maven.GetArtifacts(basePath) poms := make([]*maven.Artifact, 0) for _, item := range Artifacts { if item.ArtifactType == maven.POM { poms = append(poms, item) } } for _, item := range Artifacts { item.Untar(findParentPath("/tmp/hexh/target", item, &poms)) } } func findParentPath(defaultPath string, jar *maven.Artifact, Artifacts *[]*maven.Artifact) string { var parent *maven.Artifact for _, a := range *Artifacts { if jar.PathName == a.PathName { continue } if strings.HasPrefix(jar.PathName, a.PathName) { if parent == nil || strings.HasPrefix(a.PathName, parent.PathName) { parent = a } } } if parent != nil { return findParentPath(defaultPath, parent, Artifacts) + string(os.PathSeparator) + parent.PathName } return defaultPath } <file_sep>/study.go/src/ch10/a/t0.go package a type T0 []string
d9a47a083dd087efc95df428bfb9745141a0492e
[ "Java", "Go", "Maven POM", "Shell" ]
32
Java
dangxia/study
160a707c85f3ea8f77b2937b320fcc0589f20681
8233397c3610513f9815756cb79e163ef6118f50
refs/heads/master
<repo_name>bkc1/archive_EC2_console_log<file_sep>/README.md # Terraform - Dump EC2 system console logs to S3 upon termination ## Overview This is intended to be a demo/example project that uses Cloudwatch Events and Lamba to automatically dump EC2 console logs to an S3 bucket. EC2 console logs are only available for about 1 hour after an instance is terminated. Capturing these logs can be useful in troubleshooting issues on workloads that programmatically start/terminate EC2 instances and AWS services that utilize EC2(i.e. EMR, ECS and EKS). Terraform creates an EC2 instance for the purpose of demonstrating how the lambda function automatically gets triggered by cloudwatch events when it's state changes to `terminated`. A few additional notes: - Terraform will zip up the python source before deploying the Lambda function - Terraform will create a test JSON payload(called `test_event.json`) from a template to allow testing the lambda without actually terminating the instance. See testing info below. ## Prereqs & Dependencies This was developed and tested with Terraform v0.12.23 and AWS-cli v2.0.4. The Lambda function is using the Python3.8 runtime and Boto3 SDK. An AWS-cli configuration with elevated IAM permissions must be in place. The IAM access and secret keys in the AWS-cli are needed by Terraform in this example. In order for the EC2 instance to launch successfully, you must first create an SSH key pair in the 'keys' directory named `mykey`. ``` ssh-keygen -t rsa -f ./keys/mykey -N "" ``` ## Usage Set the desired AWS region and change any default variables in the `variables.tf` file. ### Deploying with Terraform ``` terraform init ## initialize Teraform terraform plan ## Review what terraform will do terraform apply ## Deploy the resources ``` Tear-down the resources in the stack ``` $ terraform destroy ``` ### Terminate EC2 instance to trigger Lambda After the stack is successfully deployed via terraform, note the terraform outputs which are needed for the AWScli commands below. Note: EC2 Console logs take about 5 min to be available through the `get-console-output` API. The Lambda will fail if the an EC2 instance is terminated before the console logs are populated. TODO: Add better Lambda condition handling/logging for this scenario. ``` $ aws ec2 terminate-instances --instance-ids <instanceid> --region <region> ``` Run `terraform apply` again to launch a new instance and repeat. ### Testing the Lamba without terminating an EC2 instance Note that the `--cli-binary-format raw-in-base64-out` parameter is needed for AWScli v2. ``` $ aws lambda invoke --function dump-ec2-logs-s3 --region <region> --payload file://test_event.json --cli-binary-format raw-in-base64-out out.txt ``` <file_sep>/lambda/src/dump-ec2-logs-s3.py import boto3 import os def lambda_handler(event, context): region = event['region'] instanceid = event['detail']['instance-id'] logbucket = os.environ['bucket'] # Get EC2 console log ec2_client = boto3.client('ec2',region_name=region) response = ec2_client.get_console_output(InstanceId=instanceid) # Capture only output section of response output = str(response["Output"]) #print(output) #Write output to object in S3 s3_client = boto3.client('s3', region_name=region) s3object = s3_client.put_object( Bucket=logbucket, Key=(instanceid) + '_console.log', Body=output ) print('-----EC2 system console log dumped to s3://' + (logbucket) + '/' + (instanceid) + '_console.log')
da25904c70e7a2132300e63eef1e87b2092f4ee9
[ "Markdown", "Python" ]
2
Markdown
bkc1/archive_EC2_console_log
f494bb26a97ed1e43a5be28988755dee768b1e50
e12925146d8f124270a8171e28107e40dc786c69
refs/heads/master
<repo_name>bridennis/weather-server<file_sep>/README.md [![Build Status](https://travis-ci.org/bridennis/weather-server.svg?branch=master)](https://travis-ci.org/bridennis/weather-server) Тестовое задание: веб приложение для отображения погоды =============================== Стек технологий: Java, Spring Framework (Spring Boot), Hazelcast (Cache Server), Websocket (STOMP) Данные о текущей погоде предоставлены API сервера openweathermap.org Доступ к веб приложению осуществляется через базовую авторизацию http. [http://localhost:8080/](http://localhost:8080/) Тестовые данные для доступа (имя/пароль): - user1/user1 - user2/user2 Общее описание алгоритма взаимодействия: - При отправке запроса пользователя устанавливается websocket соединение с сервером и через него отправляется запрос - Сервер, получив запрос, проверяет - нет ли уже аналогичного запроса в кэше - Если запрос в кэше найден, клиенту сразу-же возвращается ответ - В ином случае, запрос клиента складывется в общую очередь запросов клиентов (при условии, что аналогичного запроса еще нет в очереди) - SingleThreadScheduledExecutor берет из общей очереди очередной запрос и отправляет его в REST API сервис удаленного сервера - В зависимости от полученного ответа, мы обновляем кэш, освобождаем общую очередь от обработанного запроса и рассылаем websocket подписчикам полученный результат Действия в системе посуточно логируются в общую директорию log/ <file_sep>/src/main/java/weather/server/util/Request.java package weather.server.util; import weather.server.entity.RequestType; import java.util.regex.Pattern; /** * Класс "утилитных" методов для сущности Запрос. */ public class Request { /** * Возвращает тип запроса. * * @param request Строковый запрос * @return RequestType */ public static RequestType getType(String request) { RequestType requestType = RequestType.CITY; if (Pattern.compile("^.+?,[\\w]{2}$").matcher(request).matches()) { requestType = RequestType.CITY_COUNTRY; } else if (Pattern.compile("^[0-9\\.]+,[0-9\\.]+$").matcher(request).matches()){ requestType = RequestType.GEO; } return requestType; } /** * Возвращает из запроса широту долготу. * * @param request Строковый запрос * @return double[] Массив: широта, долгота */ public static double[] getLatLon(String request) { double[] latLon = new double[2]; if (Pattern.compile("^[0-9\\.]+,[0-9\\.]+$").matcher(request).matches()) { String[] coords = request.split(","); latLon[0] = Double.parseDouble(coords[0]); latLon[1] = Double.parseDouble(coords[1]); } return latLon; } } <file_sep>/src/main/java/weather/server/entity/Weather.java package weather.server.entity; import java.io.Serializable; public class Weather implements Serializable { private int id; private Double lat; private Double lon; private String city; private String country; // Температура (градус Цельсия) private int temp; // Давление (мм ртутного столба) private int pressure; // Влажность (%) private int humidity; // Ветер (м/c) private int wind; // Облачность (%) private int clouds; public String getCountry() { return country; } public void setCountry(String country) { this.country = country; } public String getCity() { return city; } public void setCity(String city) { this.city = city; } public int getTemp() { return temp; } public void setTemp(int temp) { this.temp = temp; } public int getPressure() { return pressure; } public void setPressure(int pressure) { this.pressure = pressure; } public int getHumidity() { return humidity; } public void setHumidity(int humidity) { this.humidity = humidity; } public int getWind() { return wind; } public void setWind(int wind) { this.wind = wind; } public int getClouds() { return clouds; } public void setClouds(int clouds) { this.clouds = clouds; } public int getId() { return id; } public void setId(int id) { this.id = id; } public Double getLat() { return lat; } public void setLat(Double lat) { this.lat = lat; } public Double getLon() { return lon; } public void setLon(Double lon) { this.lon = lon; } @Override public String toString() { return "Weather{" + "id=" + id + ", lat=" + lat + ", lon=" + lon + ", city='" + city + '\'' + ", country='" + country + '\'' + ", temp=" + temp + ", pressure=" + pressure + ", humidity=" + humidity + ", wind=" + wind + ", clouds=" + clouds + '}'; } } <file_sep>/src/main/java/weather/server/util/Cache.java package weather.server.util; import com.hazelcast.core.HazelcastInstance; import org.springframework.stereotype.Component; import weather.server.component.ApplicationContextProvider; import weather.server.entity.GeoPoint; import weather.server.entity.Weather; import static weather.server.config.RestApplicationConfig.*; /** * Класс "утилитных" методов для работы с Кэшем. */ @Component public class Cache { private static HazelcastInstance instance = ApplicationContextProvider.getApplicationContext().getBean(HazelcastInstance.class); public static boolean contains(String key) { switch (Request.getType(key)) { case CITY_COUNTRY: return instance.getMap(RQ_MAP_CITY_COUNTRY_NAME).containsKey(key.toLowerCase()); case GEO: double[] latLon = Request.getLatLon(key); return instance.getMap(RQ_MAP_GEO_NAME).containsKey(new GeoPoint(latLon[0], latLon[1])); case CITY: return instance.getMap(RQ_MAP_CITY_NAME).containsKey(key.toLowerCase()); } return false; } public static Weather getByQuery(String key) { Integer id = null; switch (Request.getType(key)) { case CITY_COUNTRY: id = (Integer) instance.getMap(RQ_MAP_CITY_COUNTRY_NAME).get(key.toLowerCase()); break; case GEO: double[] latLon = Request.getLatLon(key); id = (Integer) instance.getMap(RQ_MAP_GEO_NAME).get(new GeoPoint(latLon[0], latLon[1])); break; case CITY: id = (Integer) instance.getMap(RQ_MAP_CITY_NAME).get(key.toLowerCase()); break; } return id != null ? (Weather) instance.getMap(RS_MAP_BY_ID).get(id): null; } } <file_sep>/src/main/webapp/js/scripts.js var socket = null; var stompClient = null; var queryInProgress = false; function connect() { socket = new SockJS('/ws'); stompClient = Stomp.over(socket); stompClient.connect({}, function (frame) { queryInProgress = true; setConnected(true); //console.log('Connected: ' + frame); var request = $('#input-query').val(); stompClient.subscribe('/weather/' + request, function (message) { showWeather(message); }); send(request); }, function (error) { console.log('Error: ' + error); if (queryInProgress) { disconnect(); } } ); } function send(request) { stompClient.send("/request", {}, JSON.stringify({ 'request': request })); } function showWeather(message) { stompClient.unsubscribe(); //console.log('Message received: ' + message); queryInProgress = false; hideAllAlerts(); // Смотрим, что-за сообщение. Выводим либо ошибку, либо результат switch (JSON.parse(message.body).code) { case 200: $('#city').html(JSON.parse(message.body).weather.city); $('#lat').html(JSON.parse(message.body).weather.lat); $('#lon').html(JSON.parse(message.body).weather.lon); $('#country').html(JSON.parse(message.body).weather.country); $('#temp').html(JSON.parse(message.body).weather.temp); $('#pressure').html(JSON.parse(message.body).weather.pressure); $('#humidity').html(JSON.parse(message.body).weather.humidity); $('#wind').html(JSON.parse(message.body).weather.wind); $('#clouds').html(JSON.parse(message.body).weather.clouds); $('#result').removeClass('hide'); break; case 404: alertShow('info', 'Искомое не найдено'); break; case 503: alertShow('danger', 'Удаленный сервер недоступен. Повторите попытку позже'); break; case 520: alertShow('danger', 'Неопознанная ошибка. Повторите попытку позже'); break; default: console.log('Error!!! Unusual response code of Message'); break; } deBlockSearchBar(); stompClient.disconnect(); socket.close(); } function setConnected(connected) { if (connected) { $('#input-query').prop('disabled', connected); $('#input-submit').prop('disabled', connected); $('#input-submit i').addClass('fa-spin'); $('#result').addClass('hide'); alertShow('info', 'Ожидайте ответа ...'); } } function disconnect() { queryInProgress = false; deBlockSearchBar(); alertShow('danger', 'Нет соединения с сервером. Повторите попытку позже'); } function alertShow(className, text) { hideAllAlerts(); $('#result-row .alert-' + className).html(text).removeClass('hide'); } function deBlockSearchBar() { $('#input-query').prop('disabled', false); $('#input-submit').prop('disabled', false); $('#input-submit i').removeClass('fa-spin'); } function hideAllAlerts() { $('#result-row .alert').addClass('hide'); } $(function () { $('form').on('submit', function (e) { e.preventDefault(); connect(); }); $('#input-submit').click(function() { connect(); }); }); <file_sep>/src/main/java/weather/server/controller/WeatherController.java package weather.server.controller; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.messaging.handler.annotation.MessageMapping; import org.springframework.stereotype.Controller; import weather.server.entity.RequestMessage; import weather.server.service.WeatherService; import java.security.Principal; @Controller public class WeatherController { private static final Logger log = LoggerFactory.getLogger(WeatherController.class); private final WeatherService weatherService; @Autowired public WeatherController(WeatherService weatherService) { this.weatherService = weatherService; } @MessageMapping("/request") public void receiveRequest(RequestMessage request, Principal principal) { String userName = principal.getName(); log.info("Got request [{}] by user [{}]", request.getRequest(), userName); weatherService.handleRequest(request.getRequest(), userName); } }<file_sep>/src/main/java/weather/server/entity/ResponseMessage.java package weather.server.entity; public class ResponseMessage { private int code; private Weather weather; public ResponseMessage() { } public ResponseMessage(int code, Weather weather) { this.code = code; this.weather = weather; } public int getCode() { return code; } public void setCode(int code) { this.code = code; } public Weather getWeather() { return weather; } public void setWeather(Weather weather) { this.weather = weather; } @Override public String toString() { return "ResponseMessage{" + "code=" + code + ", weather=" + weather + '}'; } } <file_sep>/src/main/java/weather/server/worker/OpenWeatherWorker.java package weather.server.worker; import com.google.gson.JsonObject; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import weather.server.entity.RequestType; import weather.server.entity.ResponseMessage; import weather.server.entity.Weather; import weather.server.util.Request; import java.util.concurrent.TimeUnit; public class OpenWeatherWorker extends Worker { private static final Logger log = LoggerFactory.getLogger(OpenWeatherWorker.class); private static final String APP_ID = "b0ec048eb79ef43898fa0633c060aee8"; private static final String REQUEST_BY_NAME_FORMAT = "http://api.openweathermap.org/data/2.5/weather?q=%s&units=metric&appid=%s"; private static final String REQUEST_BY_GEO_FORMAT = "http://api.openweathermap.org/data/2.5/weather?lat=%s&lon=%s&units=metric&appid=%s"; @Override public ResponseMessage getWeather(String request) { // // Delay simulating // try { // TimeUnit.SECONDS.sleep(5); // } catch (InterruptedException e) {} // Определяемся с типом полученного запроса и на основании этого формируем URL запроса RequestType requestType = Request.getType(request); log.info("Got request: [{}] typed as [{}]", request, requestType); String url; if (requestType.equals(RequestType.GEO)) { double[] latLon = Request.getLatLon(request); url = String.format(REQUEST_BY_GEO_FORMAT, latLon[0], latLon[1], APP_ID); } else { url = String.format(REQUEST_BY_NAME_FORMAT, request, APP_ID); } JsonObject jsonObject = getJsonObjectFromUrl(url); if (jsonObject.has("cod")) { if ("200".equals(jsonObject.get("cod").getAsString())) { Weather weather = new Weather(); weather.setId(jsonObject.get("id").getAsInt()); weather.setLat(jsonObject.getAsJsonObject("coord").get("lat").getAsDouble()); weather.setLon(jsonObject.getAsJsonObject("coord").get("lon").getAsDouble()); weather.setCity(jsonObject.get("name").getAsString()); weather.setTemp(jsonObject.getAsJsonObject("main").get("temp").getAsInt()); weather.setPressure(jsonObject.getAsJsonObject("main").get("pressure").getAsInt()); weather.setHumidity(jsonObject.getAsJsonObject("main").get("humidity").getAsInt()); weather.setWind(jsonObject.getAsJsonObject("wind").get("speed").getAsInt()); weather.setClouds(jsonObject.getAsJsonObject("clouds").get("all").getAsInt()); weather.setCountry(jsonObject.getAsJsonObject("sys").get("country").getAsString()); return new ResponseMessage(200, weather); } else if ("503".equals(jsonObject.get("cod").getAsString())) { // Удаленный сервер недоступен log.info("Requested URL [{}] unavailable", url); return new ResponseMessage(503, null); } else if ("404".equals(jsonObject.get("cod").getAsString())) { return new ResponseMessage(404, null); } } // При получении запроса с удаленного ресурса произошла общая ошибка I/O log.info("Requested URL [{}] got an I/O error", url); return new ResponseMessage(520, null); } }
f2f787cff58067b2721c50446ff6da5efb4b88d5
[ "Markdown", "Java", "JavaScript" ]
8
Markdown
bridennis/weather-server
4da7fe7330d54490cb9de57a77d96cb19117eed3
4d7601273c02af34aecb1ec2c8998e6f66100a26
refs/heads/master
<repo_name>crocomoth/NET.S.2018.Popivnenko.16<file_sep>/NET.S.2018.Popivnenko.16.XmlDocs/Interface/IXmlRepository.cs using System.Collections.Generic; namespace NET.S._2018.Popivnenko._16.XmlDocs.Interface { public interface IXmlRepository<T> { void WriteUrls(IEnumerable<T> urls); } } <file_sep>/NET.S.2018.Popivnenko.16.XmlDocs/Repository/UrlRepository.cs using System; using System.Collections.Generic; using System.IO; using NET.S._2018.Popivnenko._16.XmlDocs.Interface; namespace NET.S._2018.Popivnenko._16.XmlDocs.Repository { /// <summary> /// Implements <see cref="IUrlRepository"/> and provides funtionality to get urls from file. /// </summary> public class UrlRepository : IUrlRepository { private string _filePath; /// <summary> /// Basic constructor. /// </summary> public UrlRepository() { this._filePath = @".\urls.txt"; } /// <summary> /// Contstructor with a parameter to specify source. /// throws <see cref="ArgumentNullException"/> if parameter is <see langword="null"/> /// </summary> /// <param name="filePath">Path to the file with urls.</param> public UrlRepository(string filePath) { _filePath = filePath ?? throw new ArgumentNullException(nameof(filePath)); if (!File.Exists(filePath)) { var temp = File.Create(filePath); temp.Close(); } } /// <summary> /// Represetns urls in file as a IEnumerable /// </summary> /// <returns>Urls as stings.</returns> public IEnumerable<string> GetUrls() { using (var reader = new StreamReader(File.OpenRead(_filePath))) { string line; while ((line = reader.ReadLine()) != null) { yield return line; } } } } } <file_sep>/NET.S.2018.Popivnenko.16.XmlDocs/Interface/IUrlParser.cs namespace NET.S._2018.Popivnenko._16.XmlDocs.Interface { public interface IUrlParser<T> { T Parse(string url); } } <file_sep>/NET.S.2018.Popivnenko.16.XmlDocs/Logic/UrlParser.cs using System; using System.Collections.Generic; using System.Linq; using NET.S._2018.Popivnenko._16.XmlDocs.Exception; using NET.S._2018.Popivnenko._16.XmlDocs.Interface; namespace NET.S._2018.Popivnenko._16.XmlDocs.Logic { /// <summary> /// Implements <see cref="IUrlParser"/> and provides parsing for uri's. /// </summary> public class UrlParser : IUrlParser<UrlParser> { public string SourceString { get; protected set; } public string Scheme { get; protected set; } public string Host { get; protected set; } public string[] Segments { get; protected set; } public KeyValuePair<string, string>[] Parameters { get; protected set; } /// <summary> /// Tries to parse uri and store its value inside of this object. /// throws <see cref="ParametersException"/> case url is bad. /// throws <see cref="ArgumentException"/> case it cannot be parsed in any way. /// </summary> /// <param name="url">Url to be parsed.</param> /// <returns>Itself upon sucessfull completion.</returns> public UrlParser Parse(string url) { if (Uri.TryCreate(url, UriKind.Absolute, out Uri uri)) { SourceString = uri.OriginalString; Scheme = uri.Scheme; Host = uri.Host; Segments = uri.Segments.Length > 0 ? uri.Segments.Skip(1).Select(str => new string(str.TakeWhile(ch => ch != '/').ToArray())).ToArray() : null; Parameters = uri.Query.Length > 0 ? new string(uri.Query.Skip(1).ToArray()).Split('&').Select(str => new KeyValuePair<string, string>(new string(str.TakeWhile(ch => ch != '=').ToArray()), new string(str.SkipWhile(ch => ch != '=').Skip(1).ToArray()))).ToArray() : null; if (Parameters != null && !Parameters.All(kvp => kvp.Key != string.Empty && kvp.Value != string.Empty)) { throw new ParametersException("wrong parameters in url!"); } return this; } throw new ArgumentException(nameof(url)); } } } <file_sep>/NET.S.2018.Popivnenko.16.XmlDocs/Repository/XmlUrlWriter.cs using System; using System.Collections.Generic; using System.IO; using System.Text; using System.Xml; using NET.S._2018.Popivnenko._16.XmlDocs.Interface; using NET.S._2018.Popivnenko._16.XmlDocs.Logic; namespace NET.S._2018.Popivnenko._16.XmlDocs.Repository { /// <summary> /// Implements <see cref="IXmlRepository"/> and allows to store parsed urls as xml. /// </summary> public class XmlUrlWriter : IXmlRepository<UrlParser> { private string _filePath; /// <summary> /// Basic constructor. /// </summary> public XmlUrlWriter() { this._filePath = @".\xmlurl.txt"; } /// <summary> /// Constructor with parameter to specify a destination. /// throws <see cref="ArgumentNullException"/> if parameter is null. /// </summary> /// <param name="filePath">Path to a file.</param> public XmlUrlWriter(string filePath) { _filePath = filePath ?? throw new ArgumentNullException(nameof(filePath)); if (!File.Exists(filePath)) { var temp = File.Create(filePath); temp.Close(); } } /// <summary> /// Writes sets of urls to a file. /// </summary> /// <param name="urls">Parsed urls.</param> public void WriteUrls(IEnumerable<UrlParser> urls) { var writer = new XmlTextWriter(_filePath, Encoding.UTF8); writer.WriteStartDocument(); writer.WriteStartElement("adresses"); foreach (var url in urls) { if (url == null) { continue; } WriteUrl(url, writer); } writer.WriteEndElement(); writer.WriteEndDocument(); writer.Flush(); } private void WriteUrl(UrlParser url, XmlTextWriter writer) { writer.WriteStartElement("urlAddress"); writer.WriteAttributeString("scheme", url.Scheme); WriteHost(writer, url); WritePath(writer, url); WriteParameters(writer, url); writer.WriteEndElement(); } private void WriteParameters(XmlTextWriter writer, UrlParser url) { if (url.Parameters?.Length > 0) { writer.WriteStartElement("parameters"); foreach (var param in url.Parameters) { writer.WriteStartElement("parameter"); writer.WriteAttributeString("key", param.Key); writer.WriteAttributeString("value", param.Value); writer.WriteEndElement(); } writer.WriteEndElement(); } } private void WritePath(XmlTextWriter writer, UrlParser url) { if (url.Segments?.Length > 0) { writer.WriteStartElement("uri"); foreach (var segment in url.Segments) { writer.WriteElementString("segment", segment); } writer.WriteEndElement(); } } private void WriteHost(XmlTextWriter writer, UrlParser url) { writer.WriteStartElement("host"); writer.WriteAttributeString("name", url.Host); writer.WriteEndElement(); } } } <file_sep>/NET.S.2018.Popivnenko.16/Program.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using NET.S._2018.Popivnenko._16.XmlDocs.Interface; using NET.S._2018.Popivnenko._16.XmlDocs.Logic; using NET.S._2018.Popivnenko._16.XmlDocs.Repository; namespace NET.S._2018.Popivnenko._16 { public class Program { public static void Main(string[] args) { var urlRepository = new UrlRepository(@".\urls.txt"); IXmlRepository<UrlParser> xmlRepository = new XmlUrlWriter(@".\xml.txt"); UrlParser urlParser = new UrlParser(); UrlService<UrlParser> service = new UrlService<UrlParser>(urlParser,urlRepository,xmlRepository); service.Convert(); } } } <file_sep>/NET.S.2018.Popivnenko.16.XmlDocs/Logic/UrlService.cs using System; using System.Linq; using NET.S._2018.Popivnenko._16.XmlDocs.Interface; namespace NET.S._2018.Popivnenko._16.XmlDocs.Logic { /// <summary> /// Provides service of parsing and storing values using other classes in solution. /// </summary> /// <typeparam name="T"></typeparam> public class UrlService<T> { private IUrlParser<T> urlParser; private IUrlRepository urlRepository; private IXmlRepository<T> xmlRepository; /// <summary> /// Constructor for a service. /// throws <see cref="ArgumentNullException"/> case any parameter is null. /// </summary> /// <param name="urlParser">Parser.</param> /// <param name="urlRepository">Repository for urls.</param> /// <param name="xmlRepository">Repository for xml.</param> public UrlService(IUrlParser<T> urlParser, IUrlRepository urlRepository, IXmlRepository<T> xmlRepository) { this.urlParser = urlParser ?? throw new ArgumentNullException(nameof(urlParser)); this.urlRepository = urlRepository ?? throw new ArgumentNullException(nameof(urlRepository)); this.xmlRepository = xmlRepository ?? throw new ArgumentNullException(nameof(xmlRepository)); } /// <summary> /// Converts urls into xml and writes into file specified by xmlRepository. /// </summary> public void Convert() { var urls = urlRepository.GetUrls(); var parsedUrls = urls.Select(u => { var result = urlParser.Parse(u); return result; }); xmlRepository.WriteUrls(parsedUrls); } } } <file_sep>/NET.S.2018.Popivnenko.16.XmlDocs/Interface/IUrlRepository.cs using System.Collections.Generic; namespace NET.S._2018.Popivnenko._16.XmlDocs.Interface { public interface IUrlRepository { IEnumerable<string> GetUrls(); } } <file_sep>/NET.S.2018.Popivnenko.16.XmlDocs/Exception/ParametersException.cs namespace NET.S._2018.Popivnenko._16.XmlDocs.Exception { /// <summary> /// Implements Exception class. /// Used in context of checking for Parameters of uri being incorrect. /// </summary> public class ParametersException : System.Exception { /// <summary> /// Constructor with message. /// </summary> /// <param name="message">Message to be displayed.</param> public ParametersException(string message) : base(message) { } } }
94b5287eb4a9ab36b026aa17257b037637ed4b68
[ "C#" ]
9
C#
crocomoth/NET.S.2018.Popivnenko.16
7e3c4f984422fff00d356e31777cc2f5878737c5
6f679231dde8f6cb1550167b2229cbc470c7fbed
refs/heads/main
<file_sep>const container = document.querySelector(".container"); const url = "http://data.foli.fi/citybike"; const ul = document.querySelector("ul"); fetch(url) .then((res) => res.json()) .then((data) => { const racks = data.racks; console.log(racks); Object.keys(racks).forEach((n) => addStation(racks[n])); }) .catch(console.log); const getStatus = (numOfAvailable) => { if (numOfAvailable === 0) { return `<strong style='color: red'>0</strong>`; } else if (numOfAvailable <= 2) { return `<strong style='color: rgb(255, 187, 60);'>${numOfAvailable}</strong>`; } return `<strong style='color: rgb(136, 224, 85);'>${numOfAvailable}</strong>`; }; const addStation = (station) => { const bikesAvailable = station.bikes_avail; const name = station.name; const slotsAvailable = station.slots_avail; const slotsTotal = station.slots_total; const li = document.createElement("li"); li.innerHTML = ` <p><strong>${name} </strong></p> <p>Pyöriä käytettävissä: ${getStatus( bikesAvailable )} / ${slotsTotal} </p> `; ul.appendChild(li); }; <file_sep># Overview Föli-fillarien asematiedot ![ScreenShot](screenshot.png)
80cc6f22b316b5cf00390969d981765b04427cd2
[ "JavaScript", "Markdown" ]
2
JavaScript
qjk0/foli-fillarit
fca0c9ce2fac4eadb518890441cd470d570258b6
fb5b9564a73d87a2feb00124ef4151eae545093e
refs/heads/master
<repo_name>chillydesign/orchestrate<file_sep>/src/app/translate/lang-fr.ts export const LANG_FR_TRANS = { Projects: `Projets`, Refresh: `rafraichir`, Archive: `Archiver`, 'New Project': `Nouveau projet`, incomplete: `incomplet`, complete: `complet`, tasks: `tâches`, 'tasks completed': `tâches terminées`, 'tasks to be done': `tâches à effectuer`, Edit: `Modifier`, edit: `modifier`, Delete: `Supprimer`, Name: `Nom`, Search: `Chercher`, Status: `Statut`, Save: `Enregistrer`, Active: `Actif`, Inactive: `Inactif`, project: `projet`, Uploads: `Téléchargements`, 'add task here': `Ajouter une tâche`, 'Drop it, baby!': `Tirer un fichier ici`, 'Load more': `Charger plus`, Added: 'Ajouté le', Upload: `Ajouter un fichier`, Priority: `Urgent`, "Assign to": `En cours`, Indent: `Indenter`, "Sign in": `Connexion`, "Last updated": `Dernière modification le`, }; <file_sep>/src/app/dashboard/dashboard.component.ts import { Component, ElementRef, OnDestroy, OnInit, ViewChild } from '@angular/core'; import { Subscription } from 'rxjs'; import { Project } from '../models/project.model'; import { Task } from '../models/task.model'; import { User } from '../models/user.model'; import { AuthService } from '../services/auth.service'; import { ProjectsService } from '../services/projects.service'; import { TasksService } from '../services/tasks.service'; import { ProjectsOptions } from '../services/projects.service'; import { ChartConfiguration } from 'chart.js'; import * as Chart from 'chart.js'; import * as moment from 'moment'; import { Router } from '@angular/router'; @Component({ selector: 'app-dashboard', templateUrl: './dashboard.component.html', styleUrls: ['./dashboard.component.scss'] }) export class DashboardComponent implements OnInit, OnDestroy { public tasks_completed_today: Task[]; public tasks: Task[]; public monthly_stats: { date: string, hours: number }[]; public projects: Project[]; public current_user: User; public start_date = moment(); public total_minutes: number; public total_earned: string; public search_term: string; public chart: Chart; public hourly_rate: number = 55; public daily_target = 123; @ViewChild('chartContainer', { static: true }) public chartContainer: ElementRef; private current_user_subscription: Subscription; private tasks_sub: Subscription; private stats_sub: Subscription; private comple_today_sub: Subscription; private projects_sub: Subscription; constructor( private authService: AuthService, private projectsService: ProjectsService, private tasksService: TasksService, private router: Router, ) { } ngOnInit(): void { this.getCurrentUser(); } getCurrentUser(): void { this.current_user_subscription = this.authService.current_user.subscribe( (user: User) => { if (user) { this.current_user = user; this.initialiseChart(); this.getTasks(); } } ); } getTasks(): void { const opts: ProjectsOptions = { limit: 5 }; this.projects_sub = this.projectsService.getProjects(opts).subscribe( (projects: Project[]) => { if (projects) { this.projects = projects; } if (this.current_user) { this.getTasksCompletedToday(); this.getStats(); } } ); } getTasksCompletedToday(): void { this.comple_today_sub = this.tasksService.getTasksCompletedToday().subscribe( (tasks: Task[]) => { this.tasks_completed_today = tasks; this.total_minutes = this.tasks_completed_today.map(t => t.time_taken).reduce((a, b) => b + a, 0); const formatter = new Intl.NumberFormat('en-GB', { style: 'currency', currency: 'GBP' }); const pounds = this.total_minutes * this.hourly_rate / 60; this.total_earned = formatter.format(pounds).concat(` @ £55/hr`); } ); } getStats(): void { const start_date_string = this.start_date.format('YYYY-MM-DD'); this.stats_sub = this.tasksService.getMonthlyStats(start_date_string).subscribe( (stats: any) => { if (stats) { this.monthly_stats = (stats); this.loadChartData(); } } ) } initialiseChart(): void { if (this.chartContainer) { // setTimeout(() => { }, 450); const canvas = this.chartContainer.nativeElement; const config = this.chart_config(); this.chart = new Chart(canvas, config); } } chart_config(): ChartConfiguration { return { data: { labels: [], datasets: [ { type: 'bar', label: '£', data: [], borderWidth: 1, backgroundColor: '#4a85e0', }, { type: 'line', steppedLine: true, label: 'Av.', data: [], borderWidth: 1, pointRadius: 0, backgroundColor: 'rgba(220,220,220,0.25)', }, { type: 'line', label: 'Target', data: [], borderWidth: 1, pointRadius: 0, borderColor: '#666686', fill: false, } ] }, options: { animation: { duration: 500, }, legend: { display: false }, title: { display: false }, scales: { yAxes: [{ ticks: { min: 0, suggestedMax: 300, } }], xAxes: [{ offset: true, type: 'time', time: { unit: 'day', displayFormats: { day: 'DD', }, tooltipFormat: 'll' }, ticks: { fontSize: 8, autoSkip: false, maxRotation: 90, } }] } } }; } loadChartData(): void { const points: number[] = this.monthly_stats.map(s => Math.round(s.hours * 55 / 60)); const labels = this.monthly_stats.map(s => s.date); const days = 7; const target = []; const rolling_average = []; for (let p = 0; p < points.length; p++) { const start = Math.max(0, p - Math.floor((days / 2))); const end = Math.min(points.length, p + Math.ceil(days / 2)); const subset = points.slice(start, end); const sum = subset.reduce((a, b) => a + b, 0); const av = Math.round(sum / (subset.length)); rolling_average.push(av); target.push(this.daily_target); } setTimeout(() => { this.chart.data.datasets[0].data = points; this.chart.data.datasets[1].data = rolling_average; this.chart.data.datasets[2].data = target; this.chart.data.labels = labels; this.chart.update(); }, 360); } goBackwards(): void { this.start_date.subtract(1, 'week'); this.getStats(); } goForwards(): void { this.start_date.add(1, 'week'); this.getStats(); } removeOldTask(task: Task): void { const project = this.projects.find(pr => pr.id === task.project_id); project.tasks = project.tasks.filter(t => t.id !== task.id); } onSearch(): void { if (this.search_term != undefined && this.search_term != '') { this.router.navigate(['/search', this.search_term]); } } ngOnDestroy() { const subs: Subscription[] = [ this.current_user_subscription, this.projects_sub, this.tasks_sub, this.comple_today_sub, this.stats_sub, ]; subs.forEach((sub) => { if (sub) { sub.unsubscribe(); } }); } } <file_sep>/src/app/shared/form-field/form-field.component.ts import { Component, OnInit, OnDestroy, Input } from '@angular/core'; import { Subject, Subscription } from 'rxjs'; @Component({ selector: 'app-form-field', templateUrl: './form-field.component.html', styleUrls: ['./form-field.component.scss'] }) export class FormFieldComponent implements OnInit, OnDestroy { @Input() errors: Subject<object>; @Input() field = 'error'; // show generic errors if no specific one given @Input() highlighted = false; public field_errors?: string; private generic_error = `Please fill in all the mandatory fields.`; private forbidden_error = `Action not authorised.`; private errorsSubscription: Subscription; constructor() { } ngOnInit() { if (this.errors) { this.errorsSubscription = this.errors.subscribe( (errors: any) => { this.field_errors = undefined; if (errors) { if (this.field === 'error') { if (errors.error && errors.error === 'forbidden') { this.field_errors = this.forbidden_error; } else { this.field_errors = this.generic_error; } } else { const field_errors = errors[this.field]; if (field_errors) { if (typeof field_errors === 'string') { this.field_errors = field_errors; } else { this.field_errors = field_errors.join(' '); } } } } } ); } } ngOnDestroy(): void { if (this.errorsSubscription) { this.errorsSubscription.unsubscribe(); } } } <file_sep>/src/app/app.module.ts import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import { CommonModule } from '@angular/common'; import { HttpClientModule } from '@angular/common/http'; import { FormsModule } from '@angular/forms'; // import { DragulaModule } from 'ng2-dragula'; import { NgxDropzoneModule } from 'ngx-dropzone'; import { AppRoutingModule } from './app-routing.module'; import { AppComponent } from './app.component'; import { SiteNavigationComponent } from './site-navigation/site-navigation.component'; import { ProjectsComponent } from './projects/projects.component'; import { NotFoundComponent } from './status-codes/not-found/not-found.component'; import { ProjectComponent } from './projects/project/project.component'; import { NewProjectComponent } from './projects/new-project/new-project.component'; import { BoxComponent } from './shared/box/box.component'; import { FormFieldComponent } from './shared/form-field/form-field.component'; import { EditProjectComponent } from './projects/edit-project/edit-project.component'; import { TaskComponent } from './tasks/task/task.component'; import { NewTaskComponent } from './tasks/new-task/new-task.component'; import { BoxFooterComponent } from './shared/box-footer/box-footer.component'; import { AutofocusDirective } from './directives/autofocus.directive'; import { UploadsComponent } from './uploads/uploads.component'; import { UploadComponent } from './uploads/upload/upload.component'; import { TranslatePipe } from './pipes/translate.pipe'; import { SpinnerComponent } from './shared/spinner/spinner.component'; import { NewUploadComponent } from './uploads/new-upload/new-upload.component'; import { CommentsComponent } from './comments/comments.component'; import { SignInComponent } from './auth/sign-in/sign-in.component'; import { ClientsComponent } from './clients/clients.component'; import { StartPageComponent } from './start-page/start-page.component'; import { ClientComponent } from './clients/client/client.component'; import { ProjectSummaryComponent } from './projects/project-summary/project-summary.component'; import { DashboardComponent } from './dashboard/dashboard.component'; import { NewClientComponent } from './clients/new-client/new-client.component'; import { TasksComponent } from './tasks/tasks.component'; import { ClientTasksComponent } from './client-tasks/client-tasks.component'; import { ProjectWholeComponent } from './projects/project-whole/project-whole.component'; import { SearchComponent } from './search/search.component'; import { ExportComponent } from './export/export.component'; import { MoveTaskComponent } from './tasks/move-task/move-task.component'; import { BooleanSelectorComponent } from './shared/boolean-selector/boolean-selector.component'; import { ChannelsComponent } from './channels/channels.component'; import { ChannelComponent } from './channels/channel/channel.component'; import { NewChannelComponent } from './channels/new-channel/new-channel.component'; import { NiceminsPipe } from './pipes/nicemins.pipe'; @NgModule({ declarations: [ AppComponent, SiteNavigationComponent, ProjectsComponent, NotFoundComponent, ProjectComponent, NewProjectComponent, BoxComponent, FormFieldComponent, EditProjectComponent, TaskComponent, NewTaskComponent, BoxFooterComponent, AutofocusDirective, UploadsComponent, UploadComponent, TranslatePipe, SpinnerComponent, NewUploadComponent, CommentsComponent, SignInComponent, ClientsComponent, StartPageComponent, ClientComponent, ProjectSummaryComponent, DashboardComponent, NewClientComponent, TasksComponent, ClientTasksComponent, ProjectWholeComponent, SearchComponent, ExportComponent, MoveTaskComponent, BooleanSelectorComponent, ChannelsComponent, ChannelComponent, NewChannelComponent, NiceminsPipe ], imports: [ BrowserModule, CommonModule, HttpClientModule, FormsModule, // DragulaModule.forRoot(), NgxDropzoneModule, AppRoutingModule ], providers: [], bootstrap: [AppComponent] }) export class AppModule { } <file_sep>/src/app/comments/comments.component.ts import { Component, HostListener, EventEmitter, Output, Input, OnDestroy, OnInit } from '@angular/core'; import { Subscription } from 'rxjs'; import { Comment } from '../models/comment.model'; import { Task } from '../models/task.model'; import { CommentsService } from '../services/comments.service'; @Component({ selector: 'app-comments', templateUrl: './comments.component.html', styleUrls: ['./comments.component.scss'] }) export class CommentsComponent implements OnInit, OnDestroy { @Input() task: Task; public newcomment: Comment; public comments: Comment[]; private comments_sub: Subscription; private add_comment_sub: Subscription; @Output() hide_lightbox: EventEmitter<boolean | null | undefined> = new EventEmitter(undefined); constructor(private commentsService: CommentsService) { } ngOnInit(): void { if (this.task) { this.getComments(); this.resetNewComment(); } } getComments(): void { this.comments_sub = this.commentsService.getComments(this.task.id).subscribe( (comments: Comment[]) => { if (comments) { this.comments = comments; } } ); } onSubmit(): void { this.add_comment_sub = this.commentsService.addComment(this.newcomment).subscribe( (comment: Comment) => { if (comment) { this.comments.push(comment); this.resetNewComment(); } }, (error) => console.log(error) ); } resetNewComment(): void { this.newcomment = new Comment(); this.newcomment.task_id = this.task.id; } saveCommentOnEnter(event): boolean { if (event.key === 'Enter') { this.onSubmit(); return false; } } hideLightbox(): void { this.hide_lightbox.next(true); } // on press enter, call checkQuestion or moveToNextQuestionOrSummary @HostListener('document:keydown', ['$event']) onKeydownHandler(event: KeyboardEvent) { if (event.key === 'Escape') { this.hideLightbox(); } } ngOnDestroy() { const subs: Subscription[] = [ this.comments_sub, this.add_comment_sub, ]; subs.forEach((sub) => { if (sub) { sub.unsubscribe(); } }); } } <file_sep>/src/app/services/tasks.service.ts import { Injectable } from '@angular/core'; import { HttpClient } from '@angular/common/http'; import { AuthService } from './auth.service'; import { Task } from '../models/task.model'; import { BehaviorSubject, Observable } from 'rxjs'; import { catchError, map } from 'rxjs/operators'; import { environment } from 'src/environments/environment'; import { Upload } from '../models/upload.model'; export interface TasksOptions { client_id?: number; limit?: number; search_term?: string; order?: string; completed?: number; } @Injectable({ providedIn: 'root' }) export class TasksService { private api_url = environment.api_url; public close_task_menu: BehaviorSubject<number | null> = new BehaviorSubject(null); constructor(private http: HttpClient, private authService: AuthService) { } getTasks(opts: TasksOptions): Observable<Task[]> { const options = this.authService.setAPIOptions(); let endpoint = `${this.api_url}/?route=tasks`; if (opts) { if (opts.client_id) { endpoint = endpoint.concat(`&client_id=${opts.client_id}`); } if (opts.search_term) { endpoint = endpoint.concat(`&search_term=${opts.search_term}`); } if (opts.limit) { endpoint = endpoint.concat(`&limit=${opts.limit}`); } if (opts.order) { endpoint = endpoint.concat(`&order=${opts.order}`); } if (opts.completed === 0 || opts.completed === 1) { endpoint = endpoint.concat(`&completed=${opts.completed}`); } } return this.http.get<Task[]>(endpoint, options).pipe( catchError(this.authService.handleError), map(res => res.map((p: Task) => new Task(p))) ); } addTask(task: Task): Observable<Task> { const options = this.authService.setAPIOptions(); const data = { attributes: { content: task.content, translation: task.translation, project_id: task.project_id, ordering: task.ordering, time_taken: task.time_taken, is_public: task.is_public, } }; const endpoint = `${this.api_url}/?route=tasks`; return this.http.post<Task>(endpoint, data, options).pipe( catchError(this.authService.handleError), map(res => new Task(res)) ); } updateTask(task: Task): Observable<Task> { const options = this.authService.setAPIOptions() const endpoint = `${this.api_url}/?route=tasks&id=${task.id}`; const data = { attributes: { content: task.content, completed: task.completed, translation: task.translation, ordering: task.ordering, indentation: task.indentation, priority: task.priority, completed_at: task.completed_at, time_taken: task.time_taken, is_title: task.is_title, is_current: task.is_current, is_public: task.is_public, is_approved: task.is_approved, assignee_id: task.assignee_id, updated_at: task.updated_at } }; return this.http.patch<Task>(endpoint, data, options).pipe( catchError(this.authService.handleError), map(res => new Task(res)) ); } updateTaskField(task: Task, field: string): Observable<Task> { const options = this.authService.setAPIOptions(); const endpoint = `${this.api_url}/?route=tasks&id=${task.id}&single_field=true`; const data = { attributes: { updated_at: task.updated_at, field: field, data: task[field] } }; // const data = { // attributes: { // content: task.content, // completed: task.completed, // translation: task.translation, // ordering: task.ordering, // indentation: task.indentation, // priority: task.priority, // completed_at: task.completed_at, // time_taken: task.time_taken, // is_title: task.is_title, // is_current: task.is_current, // is_public: task.is_public, // is_approved: task.is_approved, // assignee_id: task.assignee_id, // } // }; return this.http.patch<Task>(endpoint, data, options).pipe( catchError(this.authService.handleError), map(res => new Task(res)) ); } deleteTask(task: Task): Observable<Task> { const options = this.authService.setAPIOptions(); const endpoint = `${this.api_url}/?route=tasks&id=${task.id}`; return this.http.delete<Task>(endpoint, options).pipe( catchError(this.authService.handleError) // , // tap(() => console.log('deleted task')) ); } getMonthlyStats(start_date: string): Observable<Task[]> { const options = this.authService.setAPIOptions(); const endpoint = `${this.api_url}/?route=monthly_stats&start_date=${start_date}`; return this.http.get<Task[]>(endpoint, options).pipe( catchError(this.authService.handleError), ); } getCurrentTasks(): Observable<Task[]> { const options = this.authService.setAPIOptions(); const endpoint = `${this.api_url}/?route=tasks&is_current=true`; return this.http.get<Task[]>(endpoint, options).pipe( catchError(this.authService.handleError), map(res => res.map((p: Task) => new Task(p))) ); } getTasksCompletedToday(): Observable<Task[]> { const options = this.authService.setAPIOptions(); const endpoint = `${this.api_url}/?route=tasks&completed_today=true`; return this.http.get<Task[]>(endpoint, options).pipe( catchError(this.authService.handleError), map(res => res.map((p: Task) => new Task(p))) ); } getUploads(task_id: number): Observable<Upload[]> { const options = this.authService.setAPIOptions(); const endpoint = `${this.api_url}/?route=uploads&task_id=${task_id}`; return this.http.get<Upload[]>(endpoint, options).pipe( catchError(this.authService.handleError), map(res => res.map((u: Upload) => new Upload(u))) ); } timeOptions(): { amount: number, translation: string }[] { const options = [ { amount: 0, translation: `-` } ]; let amount = 5; while (amount <= 720) { const mins: number = amount % 60; const hours: number = (amount - mins) / 60; const translationArray = []; if (hours > 0) { translationArray.push(`${hours}hr`); } if (mins > 0) { translationArray.push(`${mins}m`); }; const translation = translationArray.join(' '); options.push({ amount, translation }); if (hours < 1) { amount += 5; } else if (hours < 3) { amount += 15; } else { amount += 60; } } return options; } } <file_sep>/src/app/uploads/upload/upload.component.ts import { Component, OnInit, Input, OnDestroy, EventEmitter, Output } from '@angular/core'; import { Upload } from 'src/app/models/upload.model'; import { Subscription } from 'rxjs'; import { UploadsService } from 'src/app/services/uploads.service'; import { Task } from 'src/app/models/task.model'; @Component({ selector: 'app-upload', templateUrl: './upload.component.html', styleUrls: ['./upload.component.scss'] }) export class UploadComponent implements OnInit, OnDestroy { @Input() upload: Upload; @Input() tasks: Task[]; public updating = false; public showSelect = false; @Output() uploadDeleted: EventEmitter<Upload | null | undefined> = new EventEmitter(undefined); private update_upload_sub: Subscription; private delete_upload_sub: Subscription; constructor(private uploadsService: UploadsService) { } ngOnInit() { } deleteUpload(): void { if (confirm('Are you sure?')) { this.delete_upload_sub = this.uploadsService.deleteUpload(this.upload).subscribe( () => { this.uploadDeleted.next(this.upload); }, (error) => { } ); } } taskChanged(): void { this.onSubmit(); } onSubmit(): void { // dont do an update til the last update has finished if (this.updating === false) { this.updating = true; this.update_upload_sub = this.uploadsService.updateUpload(this.upload).subscribe( (upload: Upload) => { this.upload = upload; this.updating = false; }, (error) => { } ); } } toggleShowSelect(): void { this.showSelect = !this.showSelect; } ngOnDestroy() { const subs: Subscription[] = [ this.delete_upload_sub, this.update_upload_sub, ]; subs.forEach((sub) => { if (sub) { sub.unsubscribe(); } }); } } <file_sep>/src/app/services/users.service.ts import { Injectable } from '@angular/core'; import { HttpClient } from '@angular/common/http'; import { map, tap, catchError } from 'rxjs/operators'; import { Observable, Subject } from 'rxjs'; import { environment } from '../../environments/environment'; import { AuthService } from './auth.service'; import { User } from '../models/user.model'; @Injectable({ providedIn: 'root' }) export class UsersService { private api_url = environment.api_url; constructor(private http: HttpClient, private authService: AuthService) { } getUsers(): Observable<User[]> { const endpoint = `${this.api_url}/?route=users`; const options = this.authService.setAPIOptions(); return this.http.get<User[]>(endpoint, options).pipe( map(res => res.map((p: User) => new User(p))) ); } } <file_sep>/src/app/services/messages.service.ts import { Injectable } from '@angular/core'; import { HttpClient } from '@angular/common/http'; import { AuthService } from './auth.service'; import { Message } from '../models/message.model'; import { Observable } from 'rxjs'; import { catchError, map } from 'rxjs/operators'; import { environment } from 'src/environments/environment'; @Injectable({ providedIn: 'root' }) export class MessagesService { private api_url = environment.api_url; constructor(private http: HttpClient, private authService: AuthService) { } getMessages(channel_id: number): Observable<Message[]> { const options = this.authService.setAPIOptions(); const endpoint = `${this.api_url}/?route=messages&channel_id=${channel_id}`; return this.http.get<Message[]>(endpoint, options).pipe( catchError(this.authService.handleError), map(res => res.map((p: Message) => new Message(p))) ); } addMessage(message: Message): Observable<Message> { const options = this.authService.setAPIOptions(); const data = { attributes: { content: message.content, channel_id: message.channel_id, user_id: message.user_id, } }; const endpoint = `${this.api_url}/?route=messages`; return this.http.post<Message>(endpoint, data, options).pipe( catchError(this.authService.handleError), map(res => new Message(res)) ); } updateMessage(message: Message): Observable<Message> { const options = this.authService.setAPIOptions(); const endpoint = `${this.api_url}/?route=messages&id=${message.id}`; const data = { attributes: { content: message.content, } }; return this.http.patch<Message>(endpoint, data, options).pipe( catchError(this.authService.handleError), map(res => new Message(res)) ); } deleteMessage(message: Message): Observable<Message> { const options = this.authService.setAPIOptions(); const endpoint = `${this.api_url}/?route=messages&id=${message.id}`; return this.http.delete<Message>(endpoint, options).pipe( catchError(this.authService.handleError) // , // tap(() => console.log('deleted message')) ); } } <file_sep>/src/app/models/comment.model.ts import { Task } from './task.model'; export class Comment { public id: number; public message: string; public author: string; public created_at: string; public updated_at: string; public created_at_date: Date; public task: Task; public task_id: number; constructor(obj?: any) { if (obj) { Object.assign(this, obj); this.created_at_date = new Date(this.created_at); } } } <file_sep>/src/app/channels/channels.component.ts import { Component, OnInit, OnDestroy } from '@angular/core'; import { Subscription } from 'rxjs'; import { ChannelsOptions, ChannelsService } from '../services/channels.service'; import { Channel } from '../models/channel.model'; import { Params, ActivatedRoute } from '@angular/router'; import { AuthService } from '../services/auth.service'; import { User } from '../models/user.model'; import { Client } from '../models/client.model'; import { ClientsService } from '../services/clients.service'; import { ProjectsService } from '../services/projects.service'; @Component({ selector: 'app-channels', templateUrl: './channels.component.html', styleUrls: ['./channels.component.scss'] }) export class ChannelsComponent implements OnInit, OnDestroy { public current_user: User; public channels: Channel[]; public: boolean; public channel: Channel; public client_slug: string; public client: Client; private channels_sub: Subscription; private route_params_subscription: Subscription; private current_user_subscription: Subscription; private client_sub: Subscription; constructor( private channelsService: ChannelsService, private authService: AuthService, private projectsService: ProjectsService, private clientsService: ClientsService, private route: ActivatedRoute, ) { } ngOnInit() { this.subscribeToRoute(); } // getCurrentUser(): void { // this.current_user_subscription = this.authService.current_user.subscribe( // (user: User) => { // this.current_user = user; // } // ); // } subscribeToRoute(): void { this.route_params_subscription = this.route.params.subscribe( (params: Params) => { if (params.slug) { this.client_slug = params.slug; this.getClientFromSlug(); } else { this.getChannels(); } } ); // end of route_params_subscription } getClientFromSlug(): void { this.client_sub = this.clientsService.getClientFromSlug(this.client_slug).subscribe( (client: Client) => { if (client) { this.client = client; this.projectsService.current_project_client.next(client); this.getChannels(); } } ); } getChannels(): void { let opts = {} if (this.client) { opts = { client_id: this.client.id }; } this.channels_sub = this.channelsService.getChannels(opts).subscribe( (channels: Channel[]) => { this.channels = channels; } ); } selectChannel(channel: Channel): void { this.channel = null; setTimeout(() => { this.channel = channel; }, 50); } ngOnDestroy() { const subs: Subscription[] = [ this.channels_sub, this.current_user_subscription, this.client_sub, this.route_params_subscription, ]; subs.forEach((sub) => { if (sub) { sub.unsubscribe(); } }); } } <file_sep>/src/app/pipes/translate.pipe.ts import { Pipe, PipeTransform } from '@angular/core'; import { environment } from '../../environments/environment'; @Pipe({ name: 'translate' }) export class TranslatePipe implements PipeTransform { private t = environment.translations; transform(value: any): any { if (this.t[value]) { return this.t[value]; } else { return value; } } } <file_sep>/pushtoprod.sh # get last commit message from parent directory; commitmessage=$(git log -1 --pretty=%B); echo $commitmessage; nvm use; # BUILD THE APP ng build --configuration=production --base-href='/orchestrate/' ; ## CHECK IF BUILD WAS SUCCESSFULL, CHECK IF INDEX.HTML FILE EXISTS IN NEW ## BUILD BEFORE DELETING OLD STUFF INDEX_FILE=dist/orchestrate/index.html if test -f "$INDEX_FILE"; then echo "$INDEX_FILE exists. Build was successful" # DELETE ALL FILES IN CURRENT PROD DIR cd _prod; rm *.js; rm -rf assets; rm *.txt; rm *.ico; rm index.html; rm *.css; # COPY FILES FROM DIST DIR; cp -r ../dist/orchestrate/* .; # set git stuff git add -A; # git commit -m "`$commitmessage`"; git commit -m "$commitmessage" git push origin master; ssh webfactor << EOF cd ~/web/orchestrate; git pull origin master; echo "DONE!"; EOF cd ..; else # end build was successful echo 'BUILD NOT SUCCESSFUL' fi # end build was not successful <file_sep>/src/app/projects/project-summary/project-summary.component.ts import { Component, Input, OnInit } from '@angular/core'; import { Project } from 'src/app/models/project.model'; @Component({ selector: 'app-project-summary', templateUrl: './project-summary.component.html', styleUrls: ['./project-summary.component.scss'] }) export class ProjectSummaryComponent implements OnInit { @Input() project: Project; @Input() show_tasks: boolean; constructor() { } ngOnInit(): void { } } <file_sep>/src/app/uploads/uploads.component.ts import { Component, OnInit, OnDestroy, Input } from '@angular/core'; import { Upload } from '../models/upload.model'; import { UploadsService } from '../services/uploads.service'; import { Subscription } from 'rxjs'; import { Project } from '../models/project.model'; import { Task } from '../models/task.model'; @Component({ selector: 'app-uploads', templateUrl: './uploads.component.html', styleUrls: ['./uploads.component.scss'] }) export class UploadsComponent implements OnInit, OnDestroy { // public uploads: Upload[] = []; @Input() project: Project; public tasks: Task[]; // private uploads_sub: Subscription; constructor(private uploadsService: UploadsService) { } ngOnInit() { if (this.project) { this.tasks = this.project.tasks; } } // getUploads(): void { // this.uploads_sub = this.uploadsService.getUploads(this.project.id).subscribe( // (uploads: Upload[]) => { // if (uploads) { // uploads.forEach(u => this.uploads.push(u)); // } // } // ); // } removeOldUpload(upload: Upload): void { this.project.uploads = this.project.uploads.filter(u => u.id !== upload.id); } createdUpload(newupload: Upload): void { if (this.project.uploads === undefined) { this.project.uploads = []; } this.project.uploads.push(newupload); } ngOnDestroy() { const subs: Subscription[] = [ // this.uploads_sub ]; subs.forEach((sub) => { if (sub) { sub.unsubscribe(); } }); } } <file_sep>/src/app/services/csv.service.ts import { Injectable } from '@angular/core'; @Injectable({ providedIn: 'root' }) export class CsvService { constructor() { } downloadCSVFromString(output: string, filename: string): void { const blob = new Blob(['\ufeff' + output], { type: 'text/csv;charset=utf-8;' }); const dwldLink = document.createElement('a'); const url = URL.createObjectURL(blob); const isSafariBrowser = navigator.userAgent.indexOf('Safari') !== -1 && navigator.userAgent.indexOf('Chrome') === -1; // if Safari open in new window to save file with random filename. if (isSafariBrowser) { dwldLink.setAttribute('target', '_blank'); } dwldLink.setAttribute('href', url); const date = new Date(); const date_string = date.toLocaleDateString(); const hour = date.getUTCHours(); const minutes = date.getUTCMinutes(); dwldLink.setAttribute('download', `${filename}_${date_string}_${hour}_${minutes}.csv`); dwldLink.style.visibility = 'hidden'; document.body.appendChild(dwldLink); dwldLink.click(); document.body.removeChild(dwldLink); setTimeout(() => { // For Firefox it is necessary to delay revoking the ObjectURL URL.revokeObjectURL(url); }, 100); } } <file_sep>/src/app/site-navigation/site-navigation.component.ts import { Component, OnInit, OnDestroy } from '@angular/core'; import { Router, NavigationStart } from '@angular/router'; import { Subscription } from 'rxjs'; import { filter } from 'rxjs/operators'; import { environment } from '../../environments/environment'; import { User } from '../models/user.model'; import { AuthService } from '../services/auth.service'; import { ProjectsService } from '../services/projects.service'; @Component({ selector: 'app-site-navigation', templateUrl: './site-navigation.component.html', styleUrls: ['./site-navigation.component.scss'] }) export class SiteNavigationComponent implements OnInit, OnDestroy { public current_user: User; public site_name = environment.site_name; public home_page_url: string[] = ['/']; public sidebarVisible = false; private router_events_subscription: Subscription; private current_user_subscription: Subscription; constructor( private router: Router, private projectsService: ProjectsService, private authService: AuthService ) { } ngOnInit() { this.hideSidebarOnPageChange(); this.getCurrentUser(); this.projectsService.current_project_client.subscribe( (client) => { this.site_name = environment.site_name; this.home_page_url = ['/']; if (client) { if (!this.current_user) { this.site_name = client.name; this.home_page_url = ['/clients', client.slug]; } } }); } getCurrentUser(): void { this.current_user_subscription = this.authService.current_user.subscribe( (user: User) => { this.current_user = user; } ); } logout(): void { this.authService.logout(); } hideSidebarOnPageChange(): void { /// check if page changes, use this to hide sidebar on page chage this.router_events_subscription = this.router.events.pipe( filter((event) => event instanceof NavigationStart) ).subscribe( () => this.sidebarVisible = false ); } toggleSidebar(): void { this.sidebarVisible = !this.sidebarVisible; } ngOnDestroy() { const subs: Subscription[] = [ this.current_user_subscription, this.router_events_subscription, ]; subs.forEach((sub) => { if (sub) { sub.unsubscribe(); } }); } } <file_sep>/src/app/services/uploads.service.ts import { Injectable } from '@angular/core'; import { HttpClient } from '@angular/common/http'; import { AuthService } from './auth.service'; import { Upload } from '../models/upload.model'; import { Observable } from 'rxjs'; import { catchError, map } from 'rxjs/operators'; import { environment } from 'src/environments/environment'; @Injectable({ providedIn: 'root' }) export class UploadsService { private api_url = environment.api_url; constructor(private http: HttpClient, private authService: AuthService) { } getUploads(project_id: number): Observable<Upload[]> { const options = this.authService.setAPIOptions(); const endpoint = `${this.api_url}/?route=uploads&project_id=${project_id}`; return this.http.get<Upload[]>(endpoint, options).pipe( catchError(this.authService.handleError), map(res => res.map((u: Upload) => new Upload(u))) ); } addUpload(upload: Upload): Observable<Upload> { const options = this.authService.setAPIOptions(); const data = { attributes: { file_contents: upload.file_contents, filename: upload.filename, project_id: upload.project_id, task_id: upload.task_id, } }; const endpoint = `${this.api_url}/?route=uploads`; return this.http.post<Upload>(endpoint, data, options).pipe( catchError(this.authService.handleError), map(res => new Upload(res)) ); } updateUpload(upload: Upload): Observable<Upload> { const options = this.authService.setAPIOptions(); const endpoint = `${this.api_url}/?route=uploads&id=${upload.id}`; const data = { attributes: { task_id: upload.task_id, } }; return this.http.patch<Upload>(endpoint, data, options).pipe( catchError(this.authService.handleError), map(res => new Upload(res)) ); } deleteUpload(upload: Upload): Observable<Upload> { const options = this.authService.setAPIOptions(); const endpoint = `${this.api_url}/?route=uploads&id=${upload.id}`; return this.http.delete<Upload>(endpoint, options).pipe( catchError(this.authService.handleError) // , // tap(() => console.log('deleted upload')) ); } } <file_sep>/src/app/channels/channel/channel.component.ts import { Component, ElementRef, Input, OnDestroy, OnInit, ViewChild } from '@angular/core'; import { ActivatedRoute, Params } from '@angular/router'; import { Subscription } from 'rxjs'; import { Channel } from 'src/app/models/channel.model'; import { Message } from 'src/app/models/message.model'; import { Project } from 'src/app/models/project.model'; import { User } from 'src/app/models/user.model'; import { AuthService } from 'src/app/services/auth.service'; import { ChannelsService } from 'src/app/services/channels.service'; import { MessagesService } from 'src/app/services/messages.service'; import { ProjectsService } from 'src/app/services/projects.service'; @Component({ selector: 'app-channel', templateUrl: './channel.component.html', styleUrls: ['./channel.component.scss'] }) export class ChannelComponent implements OnInit, OnDestroy { @Input() channel_id: number; public channel: Channel; public project: Project; public current_user: User; public messages_loading: boolean; public no_project: boolean; public newmessage: Message; private messages_sub: Subscription; private current_user_subscription: Subscription; private add_sub: Subscription; private channel_sub: Subscription; private project_sub: Subscription; private route_params_subscription: Subscription; constructor( private authService: AuthService, private channelsService: ChannelsService, private projectsService: ProjectsService, private messagesService: MessagesService, ) { } ngOnInit(): void { if (this.channel_id) { this.getCurrentUser(); } } getCurrentUser(): void { this.current_user_subscription = this.authService.current_user.subscribe( (user: User) => { this.current_user = user; this.getChannel(); } ); } getChannel(): void { this.channel_sub = this.channelsService.getChannel(this.channel_id).subscribe( (channel) => { this.channel = channel; if (channel) { this.resetNewMessage(); this.scrollToBottom(); if (this.channel.project_id) { this.getProject(); } else { this.no_project = true; } } } ); } makeProject(): void { } getProject(): void { this.project_sub = this.projectsService.getProject(this.channel.project_id).subscribe( (project: Project) => { if (project) { this.project = project; } } ); } // getMessages(): void { // this.messages_loading = true; // this.messages_sub = this.messagesService.getMessages(this.channel.id).subscribe( // (messages) => { // this.messages = messages; // this.scrollToBottom(); // }, // (error) => console.log(error), // () => this.messages_loading = false // ) // } scrollToBottom(): void { setTimeout(() => { const els = document.querySelectorAll('.message_container'); if (els.length > 0) { const el = els[els.length - 1] if (el) { el.parentElement.scrollTop = 10000000000; } } }, 20); } onSubmit(): void { this.add_sub = this.messagesService.addMessage(this.newmessage).subscribe( (message: Message) => { if (message) { if (!this.channel.messages) { this.channel.messages = [] } this.channel.messages.push(message); this.resetNewMessage(); this.scrollToBottom(); } }, (error) => console.log(error) ); } resetNewMessage(): void { this.newmessage = new Message({ channel_id: this.channel?.id, user_id: this.current_user?.id }); } saveCommentOnEnter(event): boolean { if (event.key === 'Enter') { this.onSubmit(); return false; } } scroll(el: HTMLElement) { el.scrollIntoView(); } ngOnDestroy() { const subs: Subscription[] = [ this.messages_sub, this.add_sub, this.route_params_subscription, this.channel_sub, this.project_sub, this.current_user_subscription, ]; subs.forEach((sub) => { if (sub) { sub.unsubscribe(); } }); } } <file_sep>/src/app/projects/projects.component.ts import { Component, OnInit, OnDestroy } from '@angular/core'; import { Subscription } from 'rxjs'; import { ProjectsOptions, ProjectsService } from '../services/projects.service'; import { Project } from '../models/project.model'; import { Params, ActivatedRoute } from '@angular/router'; import { AuthService } from '../services/auth.service'; import { User } from '../models/user.model'; @Component({ selector: 'app-projects', templateUrl: './projects.component.html', styleUrls: ['./projects.component.scss'] }) export class ProjectsComponent implements OnInit, OnDestroy { public current_user: User; public projects: Project[]; public visible_projects: Project[]; public offset = 0; public limit = 20; public status = 'active'; public load_more = false; public loading = false; public search_term: string; public search_timeout: any; private projects_sub: Subscription; private route_params_subscription: Subscription; private current_user_subscription: Subscription; constructor( private projectsService: ProjectsService, private authService: AuthService, private route: ActivatedRoute ) { } ngOnInit() { this.getCurrentUser(); this.projectsService.current_project_client.next(null); } getCurrentUser(): void { this.current_user_subscription = this.authService.current_user.subscribe( (user: User) => { this.current_user = user; if (user) { this.setStatus(); } } ); } setStatus(): void { // allow user to get projects of a particular status, based on the url this.route_params_subscription = this.route.params.subscribe( (params: Params) => { if (params.status === undefined) { this.status = 'active'; } else { this.status = params.status; } this.refreshProjects(); } ); // end of route_params_subscription } refreshProjects(): void { this.projects = []; this.visible_projects = null; this.load_more = false; this.offset = 0; this.getProjects(); } getProjects(): void { if (this.loading === false) { this.loading = true; const options: ProjectsOptions = { offset: this.offset, limit: this.limit, status: this.status, search_term: this.search_term }; this.projects_sub = this.projectsService.getProjects(options).subscribe( (projects: Project[]) => { this.projects = projects; this.visible_projects = projects; this.loading = false; if (projects) { // projects.forEach(p => this.projects.push(p)); // this.offset += this.limit; // this.load_more = (projects.length === this.limit); // this.loading = false; // this.onSearch(); } } ); } } onSearch(): void { // debounce clearTimeout(this.search_timeout); this.search_timeout = setTimeout(() => { this.getProjects(); }, 500); // this.getProjects(); // if (this.search_term) { // const s = this.search_term.toLowerCase(); // this.visible_projects = this.projects.filter((p) => { // return p.search_string.includes(s); // }); // } else { // this.visible_projects = this.projects; // } } loadMore(): void { this.load_more = false; this.getProjects(); } ngOnDestroy() { const subs: Subscription[] = [ this.projects_sub, this.current_user_subscription, this.route_params_subscription, ]; subs.forEach((sub) => { if (sub) { sub.unsubscribe(); } }); } } <file_sep>/src/app/auth/sign-in/sign-in.component.ts import { Component, OnDestroy, OnInit } from '@angular/core'; import { Router } from '@angular/router'; import { Subject, Subscription } from 'rxjs'; import { AuthService } from 'src/app/services/auth.service'; @Component({ selector: 'app-sign-in', templateUrl: './sign-in.component.html', styleUrls: ['./sign-in.component.scss'] }) export class SignInComponent implements OnInit, OnDestroy { public email: string; public password: string; public remember_me = false; public errors: Subject<object> = new Subject(); private current_user_subscription: Subscription; private login_sub: Subscription; constructor(private authService: AuthService, private router: Router) { } ngOnInit(): void { } onSubmit() { if (this.email && this.password) { this.login_sub = this.authService.login(this.email, this.password, this.remember_me).subscribe( () => { this.errors.next(null); this.router.navigate(['/']); }, () => this.errors.next({ signin: 'La connexion a échoué' }) ); } } ngOnDestroy() { const subs: Subscription[] = [ this.login_sub, this.current_user_subscription, ]; subs.forEach((sub) => { if (sub) { sub.unsubscribe(); } }); } } <file_sep>/src/app/clients/client/client.component.ts import { Component, OnDestroy, OnInit } from '@angular/core'; import { Title } from '@angular/platform-browser'; import { ActivatedRoute, Params } from '@angular/router'; import { BehaviorSubject, Subscription } from 'rxjs'; import { Client } from 'src/app/models/client.model'; import { Project } from 'src/app/models/project.model'; import { User } from 'src/app/models/user.model'; import { AuthService } from 'src/app/services/auth.service'; import { ClientsService } from 'src/app/services/clients.service'; import { ProjectsOptions, ProjectsService } from 'src/app/services/projects.service'; import { UsersService } from 'src/app/services/users.service'; @Component({ selector: 'app-client', templateUrl: './client.component.html', styleUrls: ['./client.component.scss'] }) export class ClientComponent implements OnInit, OnDestroy { public client: Client; public current_user: User; public users: User[]; public getting_client = false; public project_id: number; public show_mode: ('incomplete' | 'unapproved' | 'all') = 'all'; public show_incomplete: boolean = false; public show_unapproved: boolean = true; public client_id: number; public status = 'active'; public client_slug: string; public projects: Project[]; private client_sub: Subscription; private projects_sub: Subscription; private users_sub: Subscription; private current_user_subscription: Subscription; private route_params_subscription: Subscription; constructor( private clientsService: ClientsService, private authService: AuthService, private titleService: Title, private projectsService: ProjectsService, private usersService: UsersService, private route: ActivatedRoute) { } ngOnInit() { this.getCurrentUser(); } getCurrentUser(): void { this.current_user_subscription = this.authService.current_user.subscribe( (user: User) => { this.current_user = user; this.subscribeToRoute(); } ); } reshowTasks(e: boolean): void { if (e === true) { this.changeVisibleTasks(); } } subscribeToRoute(): void { if (!this.getting_client) { this.getting_client = true; this.route_params_subscription = this.route.params.subscribe( (params: Params) => { if (params.project_id) { this.project_id = params.project_id; } if (params.status) { this.status = params.status; } else { this.status = 'active'; } if (params.id) { this.client_id = params.id; this.getClient(); } else if (params.slug) { this.client_slug = params.slug; this.getClientFromSlug(); } } ); // end of route_params_subscription } } getClient(): void { this.client_sub = this.clientsService.getClient(this.client_id).subscribe( (client: Client) => { if (client) { this.client = client; this.projectsService.current_project_client.next(client); this.getProjects(); this.titleService.setTitle(this.client.name); } } ); } getClientFromSlug(): void { this.client_sub = this.clientsService.getClientFromSlug(this.client_slug).subscribe( (client: Client) => { if (client) { this.client = client; this.projectsService.current_project_client.next(client); this.getProjects(); } } ); } getProjects(): void { const options: ProjectsOptions = { status: this.status, client_id: this.client.id, include_tasks: true }; this.projects_sub = this.projectsService.getProjects(options).subscribe( (projects: Project[]) => { if (projects) { this.projects = projects; this.projects.map(p => p.client = this.client); this.loadViewOptionsFromLocalStorage(); this.scrollToProject(); this.getUsers(); } } ); } scrollToProject(): void { if (this.project_id) { setTimeout(() => { const p = document.getElementById(`project_${this.project_id}`); if (p) { p.scrollIntoView(); } }, 250); } } getUsers(): void { this.users_sub = this.usersService.getUsers().subscribe( (users: User[]) => { if (users) { this.users = users; } // this.processTasks(); } ); } toggleCollapse(): void { const co_count = this.projects.filter(p => p.collapsed === true).length; const un_count = this.projects.filter(p => p.collapsed !== true).length; const col = (co_count < un_count); this.projects.forEach(p => { p.collapsed = col; }) } refreshProjects(): void { this.projects = []; this.getProjects(); } changeShowMode(mode: 'incomplete' | 'unapproved' | 'all') { this.show_mode = mode; this.changeVisibleTasks(); } changeVisibleTasks(): void { const ac = (this.show_incomplete) ? [false] : [true, false, null]; const aa = (this.show_unapproved) ? [false] : [true, false, null]; this.projects.forEach(project => { project.visible_tasks = project.tasks.filter(t => { return ac.includes(t.completed) && aa.includes(t.is_approved); }) }); // if (this.show_mode == 'incomplete') { // this.projects.forEach(project => { // project.visible_tasks = project.tasks.filter(t => t.completed === false) // }); // } else if (this.show_mode == 'unapproved') { // this.projects.forEach(project => { // project.visible_tasks = project.tasks.filter(t => t.is_approved === false) // }); // } else { // this.projects.forEach(project => { // project.visible_tasks = project.tasks; // }); // } } toggleStep(view_type: string): void { if (view_type === 'incomplete') { this.show_incomplete = !this.show_incomplete; } else if (view_type === 'unapproved') { this.show_unapproved = !this.show_unapproved; } this.storeCurrentViewOptions(); this.changeVisibleTasks(); } loadViewOptionsFromLocalStorage(): void { const orch_show_incomplete: boolean = localStorage.getItem('orch_show_incomplete') === 'true'; const orch_show_unapproved: boolean = localStorage.getItem('orch_show_unapproved') !== 'false'; this.show_incomplete = orch_show_incomplete; this.show_unapproved = orch_show_unapproved; this.changeVisibleTasks(); } storeCurrentViewOptions(): void { localStorage.setItem('orch_show_incomplete', this.show_incomplete.toString()); localStorage.setItem('orch_show_unapproved', this.show_unapproved.toString()); } ngOnDestroy() { const subs: Subscription[] = [ this.client_sub, this.projects_sub, this.current_user_subscription, this.users_sub, this.route_params_subscription, ]; subs.forEach((sub) => { if (sub) { sub.unsubscribe(); } }); } } <file_sep>/src/app/export/export.component.ts import { Component, OnInit } from '@angular/core'; import { Subject, Subscription } from 'rxjs'; import { Client } from '../models/client.model'; import { Project } from '../models/project.model'; import { Task } from '../models/task.model'; import { User } from '../models/user.model'; import { AuthService } from '../services/auth.service'; import { ClientsService } from '../services/clients.service'; import { CsvService } from '../services/csv.service'; import { ExportOptions, ProjectsService } from '../services/projects.service'; import { TasksService } from '../services/tasks.service'; @Component({ selector: 'app-export', templateUrl: './export.component.html', styleUrls: ['./export.component.scss'] }) export class ExportComponent implements OnInit { public search_properties: ExportOptions = { client_id: null, project_id: null, is_approved: 'yes', completed: 'yes', start_date: null, end_date: null, } public current_user: User; public all_projects: Project[]; public projects: Project[]; public clients: Client[]; public formLoading = false; public formSuccess = false; public canSubmitForm = false; public errors: Subject<object> = new Subject(); private export_sub: Subscription; private clients_sub: Subscription; private projects_sub: Subscription; private current_user_subscription: Subscription; constructor( private authService: AuthService, private clientsService: ClientsService, private projectsService: ProjectsService, private tasksService: TasksService, private csvService: CsvService, ) { } ngOnInit(): void { this.getCurrentUser(); } getCurrentUser(): void { this.current_user_subscription = this.authService.current_user.subscribe( (user: User) => { this.current_user = user; if (user) { this.getClients(); } } ); } getClients(): void { this.clients_sub = this.clientsService.getClients().subscribe( (clients: Client[]) => { if (clients) { this.clients = clients; this.getProjects(); } } ); } getProjects(): void { const options = { offset: 0, limit: 999999 }; this.projects_sub = this.projectsService.getProjects(options).subscribe( (projects: Project[]) => { if (projects) { this.all_projects = projects; } } ); } onClientChange(event): void { this.projects = this.all_projects.filter(p => p.client_id === this.search_properties.client_id); } onSubmit(): void { if (this.current_user) { const opts: ExportOptions = (this.search_properties); this.export_sub = this.projectsService.getProjectsCSV(opts).subscribe( (csv_file: string) => { this.csvService.downloadCSVFromString(csv_file, `project_exports`); } ); } } ngOnDestroy() { const subs: Subscription[] = [ this.current_user_subscription, this.clients_sub, this.projects_sub, ]; subs.forEach((sub) => { if (sub) { sub.unsubscribe(); } }); } } <file_sep>/src/app/start-page/start-page.component.ts import { Component, OnDestroy, OnInit } from '@angular/core'; import { Subscription } from 'rxjs'; import { User } from '../models/user.model'; import { AuthService } from '../services/auth.service'; @Component({ selector: 'app-start-page', templateUrl: './start-page.component.html', styleUrls: ['./start-page.component.scss'] }) export class StartPageComponent implements OnInit, OnDestroy { public current_user: User; private current_user_subscription: Subscription; constructor(private authService: AuthService) { } ngOnInit(): void { this.getCurrentUser(); } getCurrentUser(): void { this.current_user_subscription = this.authService.current_user.subscribe( (user: User) => { this.current_user = user; } ); } ngOnDestroy() { const subs: Subscription[] = [ this.current_user_subscription, ]; subs.forEach((sub) => { if (sub) { sub.unsubscribe(); } }); } } <file_sep>/src/environments/environment.savio.ts import { LANG_FR_TRANS } from '../app/translate/lang-fr'; export const environment = { production: true, site_name: `Savio`, api_url: 'https://webfactor.ch/saviodev_api', front_url: 'https://webfactor.ch/saviodev/', secure_cookie: false, cookie_name: 'token_sav_orch', cookie_domains: ['webfactor.ch'], cookie_length_hours: 8760, cache_duration: 60000, // time to hold resources from API in cache in milliseconds translations: LANG_FR_TRANS }; <file_sep>/src/app/pipes/nicemins.pipe.ts import { Pipe, PipeTransform } from '@angular/core'; @Pipe({ name: 'nicemins' }) export class NiceminsPipe implements PipeTransform { transform(tm: number): string { if (tm === 0) { return '0 mns'; } let str = ''; const d = Math.floor(tm / 24 / 60); const h = Math.floor(tm / 60) % 24; const m = tm % 60; if (d > 0) { str = str.concat(`${d} day`) } if (h > 0) { str = str.concat(` ${h} hrs`) } if (m > 0) { str = str.concat(` ${m} mns`) } return str; } } <file_sep>/src/app/services/comments.service.ts import { Injectable } from '@angular/core'; import { HttpClient } from '@angular/common/http'; import { AuthService } from './auth.service'; import { Comment } from '../models/comment.model'; import { Observable } from 'rxjs'; import { catchError, map } from 'rxjs/operators'; import { environment } from 'src/environments/environment'; @Injectable({ providedIn: 'root' }) export class CommentsService { private api_url = environment.api_url; constructor(private http: HttpClient, private authService: AuthService) { } getComments(task_id: number): Observable<Comment[]> { const options = this.authService.setAPIOptions(); const endpoint = `${this.api_url}/?route=comments&task_id=${task_id}`; return this.http.get<Comment[]>(endpoint, options).pipe( catchError(this.authService.handleError), map(res => res.map((p: Comment) => new Comment(p))) ); } addComment(comment: Comment): Observable<Comment> { const options = this.authService.setAPIOptions(); const data = { attributes: { author: comment.author, message: comment.message, task_id: comment.task_id, } }; const endpoint = `${this.api_url}/?route=comments`; return this.http.post<Comment>(endpoint, data, options).pipe( catchError(this.authService.handleError), map(res => new Comment(res)) ); } updateComment(comment: Comment): Observable<Comment> { const options = this.authService.setAPIOptions(); const endpoint = `${this.api_url}/?route=comments&id=${comment.id}`; const data = { attributes: { message: comment.message, } }; return this.http.patch<Comment>(endpoint, data, options).pipe( catchError(this.authService.handleError), map(res => new Comment(res)) ); } deleteComment(comment: Comment): Observable<Comment> { const options = this.authService.setAPIOptions(); const endpoint = `${this.api_url}/?route=comments&id=${comment.id}`; return this.http.delete<Comment>(endpoint, options).pipe( catchError(this.authService.handleError) // , // tap(() => console.log('deleted comment')) ); } } <file_sep>/src/app/tasks/task/task.component.ts import { Component, OnInit, Input, Output, EventEmitter, OnDestroy, HostListener, ElementRef, ViewChild } from '@angular/core'; import { Task } from '../../models/task.model'; import { Subscription } from 'rxjs'; import { TasksService } from 'src/app/services/tasks.service'; import { Project } from 'src/app/models/project.model'; import { Upload } from 'src/app/models/upload.model'; import { User } from 'src/app/models/user.model'; import { AuthService } from 'src/app/services/auth.service'; @Component({ selector: 'app-task', templateUrl: './task.component.html', styleUrls: ['./task.component.scss'] }) export class TaskComponent implements OnInit, OnDestroy { @Input() task: Task; @Input() project: Project; // @Input() users: User[]; @Input() canAdministrate = true; @Input() showProjectLink = false; @Input() showDate = false; @Output() taskDeleted: EventEmitter<Task | null | undefined> = new EventEmitter(undefined); @Output() taskUpdated: EventEmitter<Task | null | undefined> = new EventEmitter(undefined); // @Output() addTaskBelowme: EventEmitter<Task | null | undefined> = new EventEmitter(undefined); // @Output() showTaskComments: EventEmitter<Task | null | undefined> = new EventEmitter(undefined); public showUpload = false; public showTick = false; public showComments = false; public updating = false; public menu_open = false; public current_user: User; public is_admin: boolean; public disabled = false; public showMoveTask = false; public debounce_timer: any; public time_options: { amount: number, translation: string }[] = this.tasksService.timeOptions(); @ViewChild('taskContainer') taskContainer: ElementRef; private update_task_sub: Subscription; private upload_sub: Subscription; private current_user_subscription: Subscription; private delete_task_sub: Subscription; constructor( private tasksService: TasksService, private authService: AuthService, ) { } ngOnInit(): void { this.getCurrentUser(); this.subscribeToTaskOpener(); setTimeout(() => { this.updateTextareaHeights(); }, 500); } getCurrentUser(): void { this.current_user_subscription = this.authService.current_user.subscribe( (user: User) => { this.current_user = user; this.setDisabled(); if (user) { this.is_admin = this.current_user.is_admin; } } ); } setDisabled(): void { if (this.task?.completed === false && this.current_user === null) { this.disabled = true; } } subscribeToTaskOpener(): void { this.current_user_subscription = this.tasksService.close_task_menu.subscribe( (task_id: number) => { if (task_id !== this.task.id) { this.closeMenu(); } } ); } onSubmit(): void { this.showTick = false; // dont do an update til the last update has finished if (this.updating === false) { this.updating = true; const upl = this.task.uploads; this.update_task_sub = this.tasksService.updateTask(this.task).subscribe( (task: Task) => { this.task = task; this.task.uploads = upl; this.taskUpdated.next(this.task); this.updating = false; this.showTickIcon(); }, (error) => { this.showOtherEditedError(error); } ); } } updateField(field: string): void { this.showTick = false; if (this.updating === false) { this.updating = true; const upl = this.task.uploads; this.update_task_sub = this.tasksService.updateTaskField(this.task, field).subscribe( (task: Task) => { this.task = task; this.task.uploads = upl; // console.log(this.task.translation, task.translation); // this.task[field] = task[field]; // this.task.updated_at = task.updated_at; this.taskUpdated.next(this.task); this.updating = false; this.showTickIcon(); this.updateTextareaHeights(); }, (error) => { this.showOtherEditedError(error); } ); } } showOtherEditedError(error): void { if (error === `Error - task updated by someone else`) { alert(`The task was updated by someone else while you were viewing it. Your change was not saved. Please refresh the page and make the edit again.`) } else if (error === `Error - must be logged in to update`) { alert(`You must be logged in to update a completed task`); } } showTickIcon(): void { this.showTick = true; setTimeout(() => { this.showTick = false; }, 2000); } toggleCompleted(): void { this.task.completed = !this.task.completed; this.updateField('completed'); // this.onSubmit(); } toggleCurrent(): void { this.task.is_current = !this.task.is_current; this.updateField('is_current'); // this.onSubmit(); } togglePublic(): void { this.task.is_public = !this.task.is_public; this.updateField('is_public'); // this.onSubmit(); } toggleApproved(): void { this.task.is_approved = !this.task.is_approved; this.updateField('is_approved'); // this.onSubmit(); } // addTaskBelow(): void { // this.addTaskBelowme.emit(this.task); // } updateTextareaHeights(): void { const ts = this.taskContainer.nativeElement.querySelectorAll('textarea'); let h: number = -9999; ts.forEach(t => { t.style.height = null; if (t.scrollHeight > h) { h = t.scrollHeight; } }) if (h > 0) { ts.forEach(t => { t.style.height = (h + 2) + 'px'; }) } } // updateContent(event) { // this.task.content = event.target.textContent; // this.onSubmit(); // } // updateTimeTaken(event) { // this.task.time_taken = event.target.textContent; // this.onSubmit(); // } // updateTranslation(event) { // this.task.translation = event.target.textContent; // this.onSubmit(); // } // saveTaskOnEnter(event, field: ('content' | 'translation')) { // if (event.key === 'Enter') { // this.onSubmit(); // return false; // } // } updateFieldWithDebounce(field: string): void { if (this.debounce_timer) { clearTimeout(this.debounce_timer); } this.debounce_timer = setTimeout(() => { console.log('b'); this.updateField(field); }, 5000); } updateFieldFromEvent(event, field: ('content' | 'translation')) { if (event.type === 'keypress' && event.key === 'Enter') { this.task[field] = event.target.textContent; this.updateField(field); return false; } else if (event.type == 'blur') { this.task[field] = event.target.textContent; this.updateField(field); } } toggleIndentation(): void { // 1 0 // 0 1 // this.task.indentation = (this.task.indentation + 1) % 2; if (this.task.is_title) { this.task.is_title = false; this.task.indentation = 0; } else if (this.task.indentation === 0) { this.task.indentation = 1; this.task.is_title = false; } else if (this.task.indentation === 1) { this.task.is_title = true; this.task.indentation = 0; } this.updateField('indentation'); // this.onSubmit(); } assignTo(user: User): void { if (this.task.assignee_id !== user.id) { this.task.assignee_id = user.id; } else { this.task.assignee_id = null; } this.updateField('assignee_id'); // this.onSubmit(); } togglePriority(): void { // 1 0 // 0 1 this.task.priority = (this.task.priority + 1) % 2; this.updateField('priority'); // this.onSubmit(); } deleteTask(): void { if (this.canAdministrate) { if (confirm('Are you sure?')) { this.delete_task_sub = this.tasksService.deleteTask(this.task).subscribe( () => { this.taskDeleted.next(this.task); }, (error) => { } ); } } } toggleMenu(): void { this.menu_open = !this.menu_open; this.tasksService.close_task_menu.next(this.task.id); } closeMenu() { this.menu_open = false; } toggleUpload(): void { this.showUpload = !this.showUpload; } showCommentPopup(): void { // this.showTaskComments.next(this.task); this.showComments = !this.showComments; } hideComments(hide: boolean): void { this.showComments = false; } hideMoveTask(hide: boolean): void { this.showMoveTask = false; } taskChangedProject(nt: Task): void { this.task.project_id = nt.project_id; this.taskUpdated.next(this.task); } moveTask(): void { this.showMoveTask = true; } createdUpload(newupload: Upload): void { if (this.task.uploads === undefined) { this.task.uploads = []; } this.task.uploads.push(newupload); this.task.uploads_count++; this.showUpload = false; } getUploads(): void { this.upload_sub = this.tasksService.getUploads(this.task.id).subscribe( (uploads: Upload[]) => { this.task.uploads = uploads; } ) } ngOnDestroy() { const subs: Subscription[] = [ this.update_task_sub, this.delete_task_sub, this.upload_sub, this.current_user_subscription, ]; subs.forEach((sub) => { if (sub) { sub.unsubscribe(); } }); } // this is incredibly slow when theres lots of task components on page // @HostListener('document:keydown', ['$event']) onKeydownHandler(event: KeyboardEvent) { // if (this.menu_open) { // if (event.key === 'Escape') { // this.closeMenu(); // } // } // } @HostListener('document:mouseup', ['$event']) onMouseUpHandler(event: any) { if (this.menu_open) { if (event.target) { if (!event.target.classList.contains("actions_opener")) { this.closeMenu(); } } } } } <file_sep>/src/app/services/link.service.ts import { Injectable, Inject } from '@angular/core'; import { DOCUMENT } from '@angular/common'; @Injectable({ providedIn: 'root' }) export class LinkService { constructor(@Inject(DOCUMENT) private doc) { } createLink(href: string, rel: string) { const link: HTMLLinkElement = this.doc.createElement('link'); link.setAttribute('rel', rel); link.setAttribute('href', href); this.doc.head.appendChild(link); } createScript(src: string) { const script: HTMLScriptElement = this.doc.createElement('script'); script.setAttribute('src', src); this.doc.head.appendChild(script); } } <file_sep>/src/app/app-routing.module.ts import { NgModule } from '@angular/core'; import { Routes, RouterModule, ExtraOptions } from '@angular/router'; import { ProjectsComponent } from './projects/projects.component'; import { NotFoundComponent } from './status-codes/not-found/not-found.component'; import { ProjectComponent } from './projects/project/project.component'; import { NewProjectComponent } from './projects/new-project/new-project.component'; import { EditProjectComponent } from './projects/edit-project/edit-project.component'; import { SignInComponent } from './auth/sign-in/sign-in.component'; import { ClientsComponent } from './clients/clients.component'; import { StartPageComponent } from './start-page/start-page.component'; import { ClientComponent } from './clients/client/client.component'; import { NewClientComponent } from './clients/new-client/new-client.component'; import { TasksComponent } from './tasks/tasks.component'; import { ClientTasksComponent } from './client-tasks/client-tasks.component'; import { SearchComponent } from './search/search.component'; import { ExportComponent } from './export/export.component'; import { ChannelsComponent } from './channels/channels.component'; import { NewChannelComponent } from './channels/new-channel/new-channel.component'; import { ChannelComponent } from './channels/channel/channel.component'; const routes: Routes = [ { path: '', component: StartPageComponent }, { path: 'sign_in', component: SignInComponent, data: { title: 'Sign in' } }, { path: 'projects/status/:status', component: ProjectsComponent, data: { title: 'Projects' } }, { path: 'projects/new/clients/:client_id', component: NewProjectComponent, data: { title: 'New Project' } }, { path: 'projects/new', component: NewProjectComponent, data: { title: 'New Project' } }, { path: 'projects/:id', component: ProjectComponent }, { path: 'projects/:id/translate', component: ProjectComponent }, { path: 'projects/:id/translation', component: ProjectComponent }, { path: 'projects/:id/admin', component: ProjectComponent }, { path: 'projects/:id/edit', component: EditProjectComponent, data: { title: 'Edit Project' } }, { path: 'projects', component: ProjectsComponent, data: { title: 'Project' } }, { path: 'search/:search_term', component: SearchComponent, data: { title: 'Search' } }, { path: 'search', component: SearchComponent, data: { title: 'Search' } }, { path: 'channels/new', component: NewChannelComponent, data: { title: 'New Channel' } }, { path: 'channels/:id', component: ChannelComponent, data: { title: 'Channel' } }, { path: 'channels', component: ChannelsComponent, data: { title: 'Channels' } }, { path: 'clients/:slug/channels', component: ChannelsComponent, data: { title: 'Channels' } }, { path: 'tasks', component: TasksComponent, data: { title: 'Tasks' } }, { path: 'export', component: ExportComponent, data: { title: 'Export' } }, { path: 'clients/new', component: NewClientComponent, data: { title: 'New Client' } }, { path: 'clients/id/:id', component: ClientComponent, data: { title: 'Client' } }, { path: 'clients/:slug/tasks', component: ClientTasksComponent, data: { title: 'Tasks' } }, { path: 'clients/:slug/status/:status', component: ClientComponent, data: { title: 'Client' } }, { path: 'clients/:slug/projects/:project_id', component: ClientComponent, data: { title: 'Client' } }, { path: 'clients/:slug', component: ClientComponent, data: { title: 'Client' } }, { path: 'clients', component: ClientsComponent, data: { title: 'Clients' } }, { path: '401', component: NotFoundComponent, data: { title: 'Page not found' } }, { path: '404', component: NotFoundComponent, data: { title: 'Page not found' } }, { path: '**', component: NotFoundComponent, data: { title: 'Page not found' } }, ]; // always scroll to top of page on route change const routingOptions: ExtraOptions = { scrollPositionRestoration: 'enabled' }; @NgModule({ imports: [RouterModule.forRoot(routes, routingOptions)], exports: [RouterModule] }) export class AppRoutingModule { } <file_sep>/src/app/app.component.ts import { Component, OnInit } from '@angular/core'; import { NavigationEnd, Router, ActivatedRoute } from '@angular/router'; import { Title } from '@angular/platform-browser'; import { environment } from '../environments/environment'; import { filter, map, mergeMap } from 'rxjs/operators'; import { Subscription } from 'rxjs'; import { User } from './models/user.model'; import { AuthService } from './services/auth.service'; import { WindowrefService } from './services/windowref.service'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.scss'] }) export class AppComponent implements OnInit { public title = environment.site_name; public current_user: User; private current_user_subscription: Subscription; constructor( private router: Router, private activatedRoute: ActivatedRoute, private titleService: Title, private authService: AuthService, private winRef: WindowrefService, ) { } ngOnInit() { this.setPageTitle(); this.getCurrentUser(); } getCurrentUser(): void { this.current_user_subscription = this.authService.current_user.subscribe( (user: User) => { this.current_user = user; const body = this.winRef.nativeWindow.document.body; if (user) { if (user.dark_mode) { body.classList.add('dark_mode'); } else { body.classList.remove('dark_mode'); } } } ); } setPageTitle() { this.router.events.pipe( filter((event) => event instanceof NavigationEnd), map(() => this.activatedRoute), map((route) => { while (route.firstChild) { route = route.firstChild; } return route; }), filter((route) => route.outlet === 'primary'), mergeMap((route) => route.data) ).subscribe( (event) => { let event_title = this.title; if (typeof event.title !== 'undefined') { event_title = `${event.title} | ${this.title}`; } this.titleService.setTitle(event_title); } ); } } <file_sep>/src/app/shared/boolean-selector/boolean-selector.component.ts import { Component, OnInit, OnDestroy, Input, Output, EventEmitter } from '@angular/core'; import { BehaviorSubject, Subscription } from 'rxjs'; @Component({ selector: 'app-boolean-selector', templateUrl: './boolean-selector.component.html', styleUrls: ['./boolean-selector.component.scss'] }) export class BooleanSelectorComponent implements OnInit, OnDestroy { @Input() value: BehaviorSubject<boolean>; @Input() simple_value: boolean; @Input() small = false; @Input() green = false; @Output() booleanChanged = new EventEmitter<boolean>(); public actual_value: boolean; private val_sub: Subscription; constructor() { } ngOnInit() { if (this.simple_value) { this.actual_value = this.simple_value; } if (this.value) { this.val_sub = this.value.subscribe( (val: boolean) => { if (val === true || val === false) { this.actual_value = val; } } ); } } switchToggle(): void { this.actual_value = !this.actual_value; this.booleanChanged.next(this.actual_value); } ngOnDestroy() { if (this.val_sub) { this.val_sub.unsubscribe(); } if (this.booleanChanged) { this.booleanChanged.unsubscribe(); } } } <file_sep>/src/app/client-tasks/client-tasks.component.ts import { Component, OnDestroy, OnInit } from '@angular/core'; import { ActivatedRoute, Params } from '@angular/router'; import { Subscription } from 'rxjs'; import { Client } from 'src/app/models/client.model'; import { Project } from 'src/app/models/project.model'; import { ClientsService } from 'src/app/services/clients.service'; import { ProjectsOptions, ProjectsService } from 'src/app/services/projects.service'; import { Task } from '../models/task.model'; import { User } from '../models/user.model'; import { AuthService } from '../services/auth.service'; import { TasksOptions, TasksService } from '../services/tasks.service'; import { UsersService } from '../services/users.service'; @Component({ selector: 'app-client-tasks', templateUrl: './client-tasks.component.html', styleUrls: ['./client-tasks.component.scss'] }) export class ClientTasksComponent implements OnInit, OnDestroy { public client: Client; public current_user: User; public users: User[]; public tasks: Task[]; public visible_tasks: Task[]; public current_col: string; public direction = 1; public client_id: number; public client_slug: string; public projects: Project[]; private client_sub: Subscription; private tasks_sub: Subscription; private route_params_subscription: Subscription; private users_sub: Subscription; private current_user_subscription: Subscription; constructor( private clientsService: ClientsService, private authService: AuthService, private usersService: UsersService, private projectsService: ProjectsService, private tasksService: TasksService, private route: ActivatedRoute) { } ngOnInit() { this.getCurrentUser(); } getCurrentUser(): void { this.current_user_subscription = this.authService.current_user.subscribe( (user: User) => { this.current_user = user; this.subscribeToRoute(); } ); } subscribeToRoute(): void { this.route_params_subscription = this.route.params.subscribe( (params: Params) => { if (params.id) { this.client_id = params.id; this.getClient(); } else if (params.slug) { this.client_slug = params.slug; this.getClientFromSlug(); } } ); // end of route_params_subscription } getClient(): void { this.client_sub = this.clientsService.getClient(this.client_id).subscribe( (client: Client) => { if (client) { this.client = client; this.projectsService.current_project_client.next(client); this.getUsers(); } } ); } getUsers(): void { this.users_sub = this.usersService.getUsers().subscribe( (users: User[]) => { if (users) { this.users = users; } this.getTasks(); } ); } getClientFromSlug(): void { this.client_sub = this.clientsService.getClientFromSlug(this.client_slug).subscribe( (client: Client) => { if (client) { this.client = client; this.projectsService.current_project_client.next(client); this.getTasks(); } } ); } getTasks(): void { const opts: TasksOptions = { client_id: this.client.id, }; this.tasks_sub = this.tasksService.getTasks(opts).subscribe( (tasks: Task[]) => { if (tasks) { this.tasks = tasks; this.visible_tasks = tasks; } } ); } sortColumn(column: string): void { if (column === this.current_col) { this.direction = this.direction * -1; // change from asc to desc } else { this.current_col = column; } this.visible_tasks = this.sortByProperty(column); } sortByProperty(column: string): Task[] { const sorted = this.tasks.sort( (a, b) => { if (a[column] > b[column]) { return this.direction; } else { return (this.direction * -1); } } ); return sorted; } ngOnDestroy() { const subs: Subscription[] = [ this.current_user_subscription, this.client_sub, this.tasks_sub, this.route_params_subscription, this.users_sub, ]; subs.forEach((sub) => { if (sub) { sub.unsubscribe(); } }); } } <file_sep>/src/app/tasks/move-task/move-task.component.ts import { Component, OnInit, Input, Output, EventEmitter, HostListener, OnDestroy } from '@angular/core'; import { Subject, Subscription } from 'rxjs'; import { Client } from 'src/app/models/client.model'; import { Project } from 'src/app/models/project.model'; import { Task } from 'src/app/models/task.model'; import { ClientsService } from 'src/app/services/clients.service'; import { ProjectsService } from 'src/app/services/projects.service'; import { TasksService } from 'src/app/services/tasks.service'; @Component({ selector: 'app-move-task', templateUrl: './move-task.component.html', styleUrls: ['./move-task.component.scss'] }) export class MoveTaskComponent implements OnInit, OnDestroy { @Input() task: Task; @Input() project: Project; @Output() hide_lightbox: EventEmitter<boolean | null | undefined> = new EventEmitter(undefined); public projects: Project[]; public formLoading = false; public formSuccess = false; public canSubmitForm = false; public errors: Subject<object> = new Subject(); private projects_sub: Subscription; private update_task_sub: Subscription; constructor( private clientsService: ClientsService, private tasksService: TasksService, private projectsService: ProjectsService, ) { } ngOnInit(): void { this.getClient(); } getClient(): void { this.projects_sub = this.projectsService.getProjects({ client_id: this.project.client_id }).subscribe( (projects: Project[]) => { this.projects = projects; } ); } hideLightbox(): void { this.hide_lightbox.next(true); } onSubmit(): void { this.formSuccess = false; this.update_task_sub = this.tasksService.updateTaskField(this.task, 'project_id').subscribe( new_task => { this.formSuccess = true; }, error => { this.errors.next(error.error); } ); } // on press enter, call checkQuestion or moveToNextQuestionOrSummary @HostListener('document:keydown', ['$event']) onKeydownHandler(event: KeyboardEvent) { if (event.key === 'Escape') { this.hideLightbox(); } } ngOnDestroy() { const subs: Subscription[] = [ this.projects_sub, this.update_task_sub, ]; subs.forEach((sub) => { if (sub) { sub.unsubscribe(); } }); } } <file_sep>/src/app/models/message.model.ts import { Channel } from "./channel.model"; import { Upload } from "./upload.model"; export class Message { public id: number; public user_id: number; public channel_id: number; public channel: Channel; public content: string; public created_at: string; public created_at_date: Date; public uploads: Upload; public user_name: string; constructor(obj?: any) { if (obj) { Object.assign(this, obj); this.created_at_date = new Date(this.created_at); if (obj.channel) { this.channel = new Channel(obj.channel); } if (obj.uploads) { this.uploads = obj.uploads.map((upload: Upload) => new Upload(upload)); } } } } <file_sep>/src/app/services/clients.service.ts import { Injectable } from '@angular/core'; import { HttpClient } from '@angular/common/http'; import { AuthService } from './auth.service'; import { Client } from '../models/client.model'; import { Observable } from 'rxjs'; import { catchError, map } from 'rxjs/operators'; import { environment } from 'src/environments/environment'; @Injectable({ providedIn: 'root' }) export class ClientsService { private api_url = environment.api_url; constructor(private http: HttpClient, private authService: AuthService) { } getClients(): Observable<Client[]> { const options = this.authService.setAPIOptions(); const endpoint = `${this.api_url}/?route=clients`; return this.http.get<Client[]>(endpoint, options).pipe( catchError(this.authService.handleError), map(res => res.map((p: Client) => new Client(p))) ); } getClient(client_id: number): Observable<Client> { const options = this.authService.setAPIOptions(); const endpoint = `${this.api_url}/?route=clients&id=${client_id}`; return this.http.get<Client>(endpoint, options).pipe( catchError(this.authService.handleError), map(res => new Client(res)) ); } getClientFromSlug(slug: string): Observable<Client> { const options = this.authService.setAPIOptions(); const endpoint = `${this.api_url}/?route=clients&slug=${slug}`; return this.http.get<Client>(endpoint, options).pipe( catchError(this.authService.handleError), map(res => new Client(res)) ); } addClient(client: Client): Observable<Client> { const options = this.authService.setAPIOptions(); const data = { attributes: { name: client.name, slug: client.slug, } }; const endpoint = `${this.api_url}/?route=clients`; return this.http.post<Client>(endpoint, data, options).pipe( catchError(this.authService.handleError), map(res => new Client(res)) ); } updateClient(client: Client): Observable<Client> { const options = this.authService.setAPIOptions(); const endpoint = `${this.api_url}/?route=clients&id=${client.id}`; const data = { attributes: { name: client.name, slug: client.slug, } }; return this.http.patch<Client>(endpoint, data, options).pipe( catchError(this.authService.handleError), map(res => new Client(res)) ); } deleteClient(client: Client): Observable<Client> { const options = this.authService.setAPIOptions(); const endpoint = `${this.api_url}/?route=clients&id=${client.id}`; return this.http.delete<Client>(endpoint, options).pipe( catchError(this.authService.handleError) ); } } <file_sep>/src/app/services/channels.service.ts import { Injectable } from '@angular/core'; import { HttpClient } from '@angular/common/http'; import { AuthService } from './auth.service'; import { Channel } from '../models/channel.model'; import { BehaviorSubject, Observable } from 'rxjs'; import { catchError, map } from 'rxjs/operators'; import { environment } from 'src/environments/environment'; export interface ChannelsOptions { client_id?: number; project_id?: number; } @Injectable({ providedIn: 'root' }) export class ChannelsService { private api_url = environment.api_url; public close_channel_menu: BehaviorSubject<number | null> = new BehaviorSubject(null); constructor(private http: HttpClient, private authService: AuthService) { } getChannels(opts?: ChannelsOptions): Observable<Channel[]> { const options = this.authService.setAPIOptions(); let endpoint = `${this.api_url}/?route=channels`; if (opts) { if (opts.client_id) { endpoint = endpoint.concat(`&client_id=${opts.client_id}`); } if (opts.project_id) { endpoint = endpoint.concat(`&project_id=${opts.project_id}`); } } return this.http.get<Channel[]>(endpoint, options).pipe( catchError(this.authService.handleError), map(res => res.map((p: Channel) => new Channel(p))) ); } getChannel(channel_id: number): Observable<Channel> { const options = this.authService.setAPIOptions(); const endpoint = `${this.api_url}/?route=channels&id=${channel_id}`; return this.http.get<Channel>(endpoint, options).pipe( catchError(this.authService.handleError), map(res => new Channel(res)) ); } addChannel(channel: Channel): Observable<Channel> { const options = this.authService.setAPIOptions(); const data = { attributes: { name: channel.name, project_id: channel.project_id, client_id: channel.client_id, } }; const endpoint = `${this.api_url}/?route=channels`; return this.http.post<Channel>(endpoint, data, options).pipe( catchError(this.authService.handleError), map(res => new Channel(res)) ); } updateChannel(channel: Channel): Observable<Channel> { const options = this.authService.setAPIOptions() const endpoint = `${this.api_url}/?route=channels&id=${channel.id}`; const data = { attributes: { name: channel.name } }; return this.http.patch<Channel>(endpoint, data, options).pipe( catchError(this.authService.handleError), map(res => new Channel(res)) ); } deleteChannel(channel: Channel): Observable<Channel> { const options = this.authService.setAPIOptions(); const endpoint = `${this.api_url}/?route=channels&id=${channel.id}`; return this.http.delete<Channel>(endpoint, options).pipe( catchError(this.authService.handleError) // , // tap(() => console.log('deleted channel')) ); } } <file_sep>/src/app/channels/new-channel/new-channel.component.ts import { Component, OnInit, OnDestroy } from '@angular/core'; import { Subscription, Subject } from 'rxjs'; import { ChannelsService } from 'src/app/services/channels.service'; import { Channel } from 'src/app/models/channel.model'; import { ActivatedRoute, Params, Router } from '@angular/router'; import { Task } from 'src/app/models/task.model'; import { Client } from 'src/app/models/client.model'; import { ClientsService } from 'src/app/services/clients.service'; @Component({ selector: 'app-new-channel', templateUrl: './new-channel.component.html', styleUrls: ['./new-channel.component.scss'] }) export class NewChannelComponent implements OnInit, OnDestroy { public client_id: number; public canSubmitForm = false; public formLoading = false; public formSuccess = false; public channel = new Channel(); public clients: Client[]; public errors: Subject<object> = new Subject(); private clients_sub: Subscription; private route_params_subscription: Subscription; private add_channel_sub: Subscription; constructor( private channelsService: ChannelsService, private clientsService: ClientsService, private router: Router, private route: ActivatedRoute, ) { } ngOnInit() { this.subscribeToRoute(); } subscribeToRoute(): void { this.route_params_subscription = this.route.params.subscribe( (params: Params) => { if (params.client_id) { this.client_id = parseInt(params.client_id, 10); this.channel.client_id = this.client_id; } else { this.getClients(); } } ); // end of route_params_subscription } getClients(): void { this.clients_sub = this.clientsService.getClients().subscribe( (clients: Client[]) => { if (clients) { this.clients = clients; } } ); } onFormChange(): void { // let server figure out if object is valid this.canSubmitForm = true; } onSubmit(): void { this.onFormChange(); if (this.canSubmitForm) { this.formLoading = true; this.add_channel_sub = this.channelsService.addChannel(this.channel).subscribe( (channel: Channel) => { this.formLoading = false; this.formSuccess = true; this.errors.next(null); if (channel.client) { this.router.navigate(['/clients', channel.client.slug, 'channels']); } else { this.router.navigate(['/channels']); } }, (error) => { this.errors.next(error.error); this.formLoading = false; this.formSuccess = false; } ); } } ngOnDestroy() { const subs: Subscription[] = [ this.route_params_subscription, this.clients_sub, this.add_channel_sub, ]; subs.forEach((sub) => { if (sub) { sub.unsubscribe(); } }); } } <file_sep>/src/app/services/auth.service.ts import { Injectable } from '@angular/core'; import { Router } from '@angular/router'; import { HttpClient, HttpHeaders, HttpErrorResponse } from '@angular/common/http'; import { environment } from '../../environments/environment'; import { BehaviorSubject, Observable, throwError } from 'rxjs'; import { catchError, map } from 'rxjs/operators'; import { User } from '../models/user.model'; import jwt_decode, { JwtPayload } from 'jwt-decode'; @Injectable({ providedIn: 'root' }) export class AuthService { public is_admin = false; public current_user: BehaviorSubject<User | null> = new BehaviorSubject(null); private api_url = environment.api_url; private token?: string; public logged_in = false; constructor(private http: HttpClient, private router: Router) { this.setCurrentUser(); } // from an email and password get a token to use with the server login(email: string, password: string, remember_me?: boolean): Observable<boolean> { const options = this.setAPIOptions(); const data = { email, password, remember_me }; const endpoint = `${this.api_url}/?route=user_token`; return this.http.post<{ jwt: string }>(endpoint, data, options).pipe( catchError(this.handleError), map((response: { jwt: string }) => { const token: string = response && response.jwt; if (token) { this.saveTokenAsCookie(token); this.setCurrentUser(); this.logged_in = true; return true; } else { return false; } } ) ); } logout(): void { // clear token remove admin from cookie to log admin out this.token = undefined; this.removeCookie(environment.cookie_name); this.current_user.next(null); this.logged_in = false; // go back to the homepage this.router.navigate(['/']); } setCurrentUser(): void { if (typeof this.token !== 'string') { this.setTokenFromCookie(); } if (typeof this.token === 'string') { this.getUserFromToken().subscribe( (user: User) => { if (user) { this.logged_in = true; this.current_user.next(user); this.tokenTimeRemaining(); } }, (error) => console.log('error', (error)) ); } } getUserFromToken(): Observable<User> { const options = this.setAPIOptions(); const endpoint = `${this.api_url}/?route=users&id=me`; return this.http.get<User>(endpoint, options).pipe( catchError(this.handleError), map(res => new User(res)) ); } saveTokenAsCookie(token: string): void { this.token = token; const cookie_length = environment.cookie_length_hours; this.setCookie(environment.cookie_name, token, cookie_length); } tokenTimeRemaining(): void { if (typeof jwt_decode !== 'undefined') { if (this.token) { const decoded: JwtPayload = jwt_decode(this.token); if (decoded) { const now = new Date().valueOf() / 1000; // seconds left before they are logged out const timeleft = Math.max(1, decoded.exp - now); setTimeout(() => { alert('You have been logged out now. Stuff probably wasnt saved.') }, timeleft * 1000); // console.log(decoded, decoded.exp, now, decoded.exp - now); } } } } setTokenFromCookie(): void { this.token = this.getCookie(environment.cookie_name); } setCookie(name: string, value: string, hours: number): void { let expires = ''; if (hours) { const date = new Date(); date.setTime(date.getTime() + (hours * 60 * 60 * 1000)); expires = `; expires=` + date.toUTCString(); } let sec_cookie = ''; if (environment.secure_cookie) { sec_cookie = `Secure;SameSite=Strict`; } environment.cookie_domains.forEach(cookie_domain => { document.cookie = `${name}=${(value || '')}${expires};domain=${cookie_domain};path=/;${sec_cookie}`; }); } getCookie(name: string): string | undefined { const nameEQ = name + '='; const ca = document.cookie.split(';'); for (let c of ca) { while (c.charAt(0) === ' ') { c = c.substring(1, c.length); } if (c.indexOf(nameEQ) === 0) { return c.substring(nameEQ.length, c.length); } } return undefined; } removeCookie(name: string): void { this.setCookie(name, '', -10000); } setAPIOptions() { const httpOptions = { headers: new HttpHeaders({ 'Accept': 'application/json;', 'Content-Type': 'application/json', }) }; if (this.token) { httpOptions.headers = httpOptions.headers.append('Authorization', `Bearer ${this.token}`) } return httpOptions; } public handleError(error: HttpErrorResponse) { if (error.error instanceof ErrorEvent) { // A client-side or network error occurred. Handle it accordingly. console.error('An error occurred:', error.error.message); } else { // The backend returned an unsuccessful response code. // The response body may contain clues as to what went wrong, console.error( `Backend returned code ${error.status}, ` + `body was: ${error.error}`); } // return an observable with a user-facing error message return throwError(error.error); } } <file_sep>/src/app/search/search.component.ts import { Component, OnDestroy, OnInit } from '@angular/core'; import { ActivatedRoute, Params } from '@angular/router'; import { Subscription } from 'rxjs'; import { Task } from '../models/task.model'; import { User } from '../models/user.model'; import { AuthService } from '../services/auth.service'; import { TasksOptions, TasksService } from '../services/tasks.service'; import { UsersService } from '../services/users.service'; @Component({ selector: 'app-search', templateUrl: './search.component.html', styleUrls: ['./search.component.scss'] }) export class SearchComponent implements OnInit, OnDestroy { public current_user: User; public users: User[]; public search_term: string; public search_timeout: any; public tasks: Task[]; private current_user_subscription: Subscription; private tasks_sub: Subscription; private users_sub: Subscription; private route_params_subscription: Subscription; constructor( private authService: AuthService, private usersService: UsersService, private tasksService: TasksService, private route: ActivatedRoute, ) { } ngOnInit(): void { this.getCurrentUser(); } getCurrentUser(): void { this.current_user_subscription = this.authService.current_user.subscribe( (user: User) => { this.current_user = user; if (user) { this.getUsers(); } this.subscribeToRoute(); } ); } getUsers(): void { this.users_sub = this.usersService.getUsers().subscribe( (users: User[]) => { if (users) { this.users = users; } // this.processTasks(); } ); } subscribeToRoute(): void { this.route_params_subscription = this.route.params.subscribe( (params: Params) => { if (params.search_term) { this.search_term = params.search_term; this.onSearch(); } } ); // end of route_params_subscription } onSearch(): void { // debounce clearTimeout(this.search_timeout); this.search_timeout = setTimeout(() => { this.getTasks(); }, 500); } getTasks(): void { if (this.search_term !== '') { const opts: TasksOptions = { search_term: this.search_term }; this.tasks_sub = this.tasksService.getTasks(opts).subscribe( (tasks: Task[]) => { if (tasks) { this.tasks = tasks; } } ); } else { this.tasks = []; } } ngOnDestroy() { const subs: Subscription[] = [ this.current_user_subscription, this.tasks_sub, this.users_sub, this.route_params_subscription, ]; subs.forEach((sub) => { if (sub) { sub.unsubscribe(); } }); } } <file_sep>/src/app/clients/clients.component.ts import { Component, OnDestroy, OnInit } from '@angular/core'; import { Subscription } from 'rxjs'; import { Client } from '../models/client.model'; import { User } from '../models/user.model'; import { AuthService } from '../services/auth.service'; import { ClientsService } from '../services/clients.service'; @Component({ selector: 'app-clients', templateUrl: './clients.component.html', styleUrls: ['./clients.component.scss'] }) export class ClientsComponent implements OnInit, OnDestroy { public clients: Client[]; public current_user: User; private current_user_subscription: Subscription; private clients_sub: Subscription; constructor( private authService: AuthService, private clientsService: ClientsService ) { } ngOnInit() { this.getCurrentUser(); } getCurrentUser(): void { this.current_user_subscription = this.authService.current_user.subscribe( (user: User) => { this.current_user = user; if (user) { this.getClients(); } } ); } getClients(): void { this.clients_sub = this.clientsService.getClients().subscribe( (clients: Client[]) => { if (clients) { this.clients = clients; } } ); } ngOnDestroy() { const subs: Subscription[] = [ this.clients_sub, this.current_user_subscription, ]; subs.forEach((sub) => { if (sub) { sub.unsubscribe(); } }); } } <file_sep>/src/app/uploads/new-upload/new-upload.component.ts import { Component, OnInit, Input, OnDestroy, Output, EventEmitter } from '@angular/core'; import { Project } from 'src/app/models/project.model'; import { UploadsService } from 'src/app/services/uploads.service'; import { Upload } from 'src/app/models/upload.model'; import { Subscription } from 'rxjs'; import { Task } from 'src/app/models/task.model'; @Component({ selector: 'app-new-upload', templateUrl: './new-upload.component.html', styleUrls: ['./new-upload.component.scss'] }) export class NewUploadComponent implements OnInit, OnDestroy { @Input() project: Project; @Input() task: Task; @Output() uploadCreated: EventEmitter<Upload | null | undefined> = new EventEmitter(undefined); public uploads: Upload[]; public files: File[] = []; public failedUploads: File[] = []; public uploadingFiles: File[] = []; public maxFileSize: number = 1024 * 1024 * 30; // 30 mb private new_upl_sub: Subscription; constructor(private uploadsService: UploadsService) { } ngOnInit() { } onSelect(event) { const newfiles = event.addedFiles; this.files.push(...newfiles); this.showFailedUploadsPopup(event.rejectedFiles); newfiles.forEach((file: File) => { this.readFile(file).then(fileContents => { this.uploadingFiles.push(file); // SEND FILE TO API const new_upload = new Upload({ file_contents: fileContents.toString(), filename: file.name, project_id: this.project.id }); if (this.task) { new_upload.task_id = this.task.id; } this.new_upl_sub = this.uploadsService.addUpload(new_upload).subscribe( (upload: Upload) => { this.uploadCreated.next(upload); // remove it from the ist of currently uplaoding files. this.removeFileFromList(file); }, (error) => { // remove it from the ist of currently uplaoding files. this.removeFileFromList(file); this.showFailedUploadsPopup([file]); } ); }).catch((err) => { console.log(err); }); }); } removeFileFromList(file: File): void { this.files.splice(this.files.indexOf(file), 1); } showFailedUploadsPopup(failedFiles: File[]): void { this.failedUploads = failedFiles; const failedTimer = setTimeout(() => { this.failedUploads = null; }, 5000); } onRemove(event: File) { this.removeFileFromList(event); // TODO DELETE FILE FROM API HERE } private async readFile(file: File): Promise<string | ArrayBuffer> { return new Promise<string | ArrayBuffer>((resolve, reject) => { const reader = new FileReader(); reader.onload = e => { return resolve((e.target as FileReader).result); }; reader.onerror = e => { console.error(`FileReader failed on file ${file.name}.`); return reject(null); }; if (!file) { console.error('No file to read.'); return reject(null); } reader.readAsDataURL(file); }); } fileIsUploading(file: File): boolean { const uploadingNow = true; return uploadingNow; } ngOnDestroy() { const subs: Subscription[] = [ this.new_upl_sub, ]; subs.forEach((sub) => { if (sub) { sub.unsubscribe(); } }); } } <file_sep>/src/app/models/upload.model.ts import { environment } from '../../environments/environment'; export class Upload { public id: number; public project_id: number; public task_id: number; public created_at: string; public updated_at: string; public filename: string; public file_contents: string; public url: string; public full_url: string; public nice_created_at: string; public setNiceDates(): void { if (this.created_at) { this.nice_created_at = this.created_at.split(' ')[0]; } } constructor(obj?: any) { if (obj) { Object.assign(this, obj); this.full_url = environment.api_url + obj.url; this.setNiceDates(); } } } <file_sep>/src/app/projects/project/project.component.ts import { Component, OnInit, OnDestroy } from '@angular/core'; import { Subscription } from 'rxjs'; import { ActivatedRoute, Params, Router, UrlSegment } from '@angular/router'; import { ProjectsService } from 'src/app/services/projects.service'; import { Project } from 'src/app/models/project.model'; import { Task } from 'src/app/models/task.model'; import { Title } from '@angular/platform-browser'; // import { DragulaService } from 'ng2-dragula'; import { TasksService } from 'src/app/services/tasks.service'; import { environment } from '../../../environments/environment'; import { CsvService } from 'src/app/services/csv.service'; import { User } from 'src/app/models/user.model'; import { AuthService } from 'src/app/services/auth.service'; import { Client } from 'src/app/models/client.model'; import { ClientsService } from 'src/app/services/clients.service'; import { UsersService } from 'src/app/services/users.service'; @Component({ selector: 'app-project', templateUrl: './project.component.html', styleUrls: ['./project.component.scss'] }) export class ProjectComponent implements OnInit, OnDestroy { public current_user: User; public users: User[]; public project_id: number; public client: Client; public project: Project; private route_params_subscription: Subscription; private delete_project_sub: Subscription; private project_sub: Subscription; private drag_sub: Subscription; private update_project_sub: Subscription; private current_user_subscription: Subscription; private users_sub: Subscription; private url_sub: Subscription; private update_task_sub: Subscription; public title = environment.site_name; constructor( private titleService: Title, private route: ActivatedRoute, private tasksService: TasksService, private projectsService: ProjectsService, private authService: AuthService, private usersService: UsersService, // private dragulaService: DragulaService, private csvService: CsvService, private router: Router) { // // add a handle to the dragdrop // this.dragulaService.createGroup('TASKS', { // moves(el, container, handle) { // return handle.classList.contains('handle'); // } // }); } // add this to angular.json if you want to put dragula bacl // "architect": { // "build": { // "options": { // "allowedCommonJsDependencies": [ // "dragula" // ], ngOnInit() { this.getCurrentUser(); } getCurrentUser(): void { this.current_user_subscription = this.authService.current_user.subscribe( (user: User) => { this.current_user = user; this.subscribeToRoute(); } ); } subscribeToRoute(): void { this.route_params_subscription = this.route.params.subscribe( (params: Params) => { if (params.id) { this.project_id = params.id; this.getProject(); } } ); // end of route_params_subscription } getProject(): void { this.project_sub = this.projectsService.getProject(this.project_id).subscribe( (project: Project) => { if (project) { this.project = project; this.client = this.project.client; this.projectsService.current_project_client.next(this.client); this.titleService.setTitle(`${this.project.nice_name} | ${this.title} `); // this.setupDragSubscription(); this.getUsers(); } } ); } getUsers(): void { this.users_sub = this.usersService.getUsers().subscribe( (users: User[]) => { if (users) { this.users = users; } // this.processTasks(); } ); } deleteProject(): void { if (confirm(`Are you sure you want to delete this project?`)) { this.delete_project_sub = this.projectsService.deleteProject(this.project).subscribe( () => { this.router.navigate(['/']); }, (error) => { } ); } } exportProject(): void { const opts = { project_id: this.project.id } this.projectsService.getProjectsCSV(opts).subscribe( (csv_file: string) => { this.csvService.downloadCSVFromString(csv_file, `project_${this.project.id}`); } ); } archiveProject(): void { if (this.project.status !== 'inactive') { this.project.status = 'inactive'; this.update_project_sub = this.projectsService.updateProject(this.project).subscribe( () => alert('This project has been archived'), (error) => console.log(error) ); } } taskUpdated(newtask: Task): void { const task = this.project.tasks.find(t => t.id === newtask.id); if (task) { task.completed = newtask.completed; task.time_taken = newtask.time_taken; } this.setPercentage(); } addTaskBelow(task: Task): void { // console.log(task.ordering); // console.log(task.ordering); // const new_task = new Task(); // new_task.ordering = task.ordering += 0.5; // new_task.project_id = task.project_id; // this.addNewTask(new_task); } addNewTask(task: Task): void { this.project.tasks.push(task); this.setPercentage(); } removeOldTask(task: Task): void { this.project.tasks = this.project.tasks.filter(t => t.id !== task.id); this.setPercentage(); } setPercentage(): void { this.project.setTasksCount(); this.project.setTotalMinutes(); } processTasks(): void { const ups = this.project.uploads; this.project.tasks.forEach(task => { task.uploads = ups.filter(u => u.task_id === task.id); // if (this.users) { // task.assignee = this.users.find(u => u.id === task.assignee_id); // } }); } // setupDragSubscription(): void { // this.drag_sub = this.dragulaService.dropModel('TASKS').subscribe(({ sourceModel, targetModel, item }) => { // const new_docsecs = targetModel; // new_docsecs.forEach((new_task, i) => { // setTimeout(() => { // const new_ordering = i + 1; // const current_task = this.project.tasks.find((task) => task.id === new_task.id); // if (current_task) { // if (current_task.ordering !== new_ordering) { // current_task.ordering = new_ordering; // this.update_task_sub = this.tasksService.updateTask(current_task).subscribe(); // } // } // }, i * 500); // }); // }); // } assignUnassignedTo(user: User): void { const unassigned = this.project.tasks.filter(t => t.assignee_id === null || t.assignee_id === 0); const undone = unassigned.filter(t => t.completed === false); undone.forEach((task, i) => { setTimeout(() => { task.assignee_id = user.id; task.assignee = user; this.update_task_sub = this.tasksService.updateTask(task).subscribe(); }, i * 500); }); } refreshProject(): void { this.project = null; this.getProject(); } ngOnDestroy() { const subs: Subscription[] = [ this.route_params_subscription, this.project_sub, this.delete_project_sub, this.drag_sub, this.users_sub, this.update_project_sub, this.current_user_subscription, this.update_task_sub, this.url_sub, ]; subs.forEach((sub) => { if (sub) { sub.unsubscribe(); } }); // this.dragulaService.destroy('TASKS'); } } <file_sep>/src/app/models/project.model.ts import { Client } from './client.model'; import { Task } from './task.model'; import { Upload } from './upload.model'; export class Project { public id: number; public name: string; public status: string; public created_at: string; public updated_at: string; public tasks: Task[]; public visible_tasks: Task[]; public random_tasks: Task[]; public uploads: Upload[]; public tasks_count_obj: { complete: number, incomplete: number, total: number }; public tasks_count: number; public incomplete_tasks_count: number; public total_minutes: number; public percentage = 0; public client_id: number; public client: any; public move_incomplete_to_project_id: number; public month: string; public nice_month: string; public nice_name: string; public nice_name_with_client: string; public search_string: string; public client_slug: string; public collapsed: boolean = false; public getNextTaskOrdering(): number { if (this.tasks) { if (this.tasks.length > 0) { const orderings: number[] = this.tasks.map(t => t.ordering); return Math.min(9999, Math.max(...orderings) + 1); } return 1; } return 1; } public setTasksCount(): void { // if (this.tasks) { // this.tasks_count_obj = { // complete: this.tasks.filter(t => t.completed).length, // incomplete: this.tasks.filter(t => t.completed === false).length, // total: this.tasks.length, // }; // } this.incomplete_tasks_count = this.tasks.filter(f => f.completed === false).length; this.tasks_count = this.tasks.length; this.setPercentage(); } public setPercentage(): void { // if (this.tasks_count_obj) { // const num = this.tasks_count_obj.complete; // const den = Math.max(this.tasks_count_obj.total, 1); // this.percentage = Math.round(num / den * 100); // } if (this.tasks_count == 0 && this.incomplete_tasks_count === 0) { this.percentage = 0; } else if (this.incomplete_tasks_count === 0) { this.percentage = 100; } else { const num = this.tasks_count - this.incomplete_tasks_count; const den = this.tasks_count; this.percentage = Math.round(num / den * 100); } } setTotalMinutes(): void { let tm = 0; this.tasks.forEach(task => { if (task.time_taken !== undefined) { tm += task.time_taken; } }); this.total_minutes = tm; } setMonthAndNiceName(): void { this.nice_name = this.name; if (this.month) { const name = this.name; const month = new Date(this.month); // if date valid if (!isNaN(month.getTime())) { const ye = new Intl.DateTimeFormat('en', { year: 'numeric' }).format(month); const mo = new Intl.DateTimeFormat('en', { month: '2-digit' }).format(month); const moo = new Intl.DateTimeFormat('fr', { month: 'long' }).format(month); const da = new Intl.DateTimeFormat('en', { day: '2-digit' }).format(month); this.month = `${ye}-${mo}-${da}`; this.nice_month = `${moo} ${ye}`; this.nice_name = `${this.nice_month} | ${name}`; } } if (this.client) { this.nice_name_with_client = `${this.client.name} | ${this.nice_name}`; } else { this.nice_name_with_client = this.nice_name; } this.search_string = this.nice_name_with_client.toLowerCase(); } constructor(obj?: any) { if (obj) { Object.assign(this, obj); if (obj.random_tasks) { this.random_tasks = obj.random_tasks.map((task: Task) => new Task(task)); } if (obj.tasks) { this.tasks = obj.tasks.map((task: Task) => new Task(task)); this.visible_tasks = this.tasks; this.setTasksCount(); this.setTotalMinutes(); } if (obj.uploads) { this.uploads = obj.uploads.map((upload: Upload) => new Upload(upload)); } if (obj.client) { this.client = new Client(obj.client); } this.setMonthAndNiceName(); this.setPercentage(); } } } <file_sep>/src/app/projects/edit-project/edit-project.component.ts import { Component, OnInit, OnDestroy } from '@angular/core'; import { Project } from 'src/app/models/project.model'; import { Subscription, Subject } from 'rxjs'; import { ActivatedRoute, Router, Params } from '@angular/router'; import { ProjectsService } from 'src/app/services/projects.service'; import { ClientsService } from 'src/app/services/clients.service'; import { Client } from 'src/app/models/client.model'; @Component({ selector: 'app-edit-project', templateUrl: './edit-project.component.html', styleUrls: ['./edit-project.component.scss'] }) export class EditProjectComponent implements OnInit, OnDestroy { public project: Project; public projects: Project[]; public clients: Client[]; public formLoading = false; public formSuccess = false; public canSubmitForm = false; public errors: Subject<object> = new Subject(); private route_params_subscription: Subscription; private delete_project_sub: Subscription; private project_sub: Subscription; private update_project_sub: Subscription; private projects_sub: Subscription; private clients_sub: Subscription; constructor( private route: ActivatedRoute, private projectsService: ProjectsService, private clientsService: ClientsService, private router: Router ) { } ngOnInit() { this.route_params_subscription = this.route.params.subscribe( (params: Params) => { this.getProject(params.id); } ); // end of route_params_subscription } getProject(project_id: number): void { this.project_sub = this.projectsService.getProject(project_id).subscribe( (project: Project) => { if (project) { this.project = project; this.getClients(); } } ); } getClients(): void { this.clients_sub = this.clientsService.getClients().subscribe( (clients: Client[]) => { if (clients) { this.clients = clients; this.getProjects(); } } ); } getProjects(): void { const options = { offset: 0, limit: 999999, status: 'active' }; this.projects_sub = this.projectsService.getProjects(options).subscribe( (projects: Project[]) => { if (projects) { this.projects = projects; } } ); } onFormChange(): void { // let server figure out if object is valid // this.canSubmitForm = true; } onSubmit(): void { this.onFormChange(); this.formLoading = true; this.update_project_sub = this.projectsService.updateProject(this.project).subscribe( (project: Project) => { this.formLoading = false; this.formSuccess = true; this.errors.next(null); if (this.project.move_incomplete_to_project_id) { this.router.navigate(['/projects', this.project.move_incomplete_to_project_id]); } else { this.router.navigate(['/projects', project.id]); } }, (error) => { this.errors.next(error.error); this.formLoading = false; this.formSuccess = false; } ); } ngOnDestroy() { const subs: Subscription[] = [ this.route_params_subscription, this.project_sub, this.delete_project_sub, this.update_project_sub, this.projects_sub, this.clients_sub, ]; subs.forEach((sub) => { if (sub) { sub.unsubscribe(); } }); } } <file_sep>/src/app/translate/lang-en.ts export const LANG_EN_TRANS = { Projects: `Projects`, Refresh: `Refresh`, /// ... }; <file_sep>/src/app/models/channel.model.ts import { Client } from './client.model'; import { Message } from './message.model'; import { Project } from './project.model'; import { Upload } from './upload.model'; import { User } from './user.model'; export class Channel { public id: number; public project_id: number; public project: Project; public client: Client; public client_id: number; public name: string; public created_at: string; public created_at_date: Date; public messages: Message[]; constructor(obj?: any) { if (obj) { Object.assign(this, obj); this.created_at_date = new Date(this.created_at); if (obj.project) { this.project = new Project(obj.project); } if (obj.client) { this.client = new Client(obj.client); } if (obj.messages) { this.messages = obj.messages.map((message: Message) => new Message(message)); } } } } <file_sep>/src/app/projects/project-whole/project-whole.component.ts import { Component, EventEmitter, HostListener, Input, OnDestroy, OnInit, Output } from '@angular/core'; import { Title } from '@angular/platform-browser'; import { ActivatedRoute, Router } from '@angular/router'; // import { DragulaService } from 'ng2-dragula'; import { Subscription } from 'rxjs'; import { Project } from 'src/app/models/project.model'; import { Task } from 'src/app/models/task.model'; import { User } from 'src/app/models/user.model'; import { AuthService } from 'src/app/services/auth.service'; import { CsvService } from 'src/app/services/csv.service'; import { ExportOptions, ProjectsService } from 'src/app/services/projects.service'; import { TasksService } from 'src/app/services/tasks.service'; import { UsersService } from 'src/app/services/users.service'; @Component({ selector: 'app-project-whole', templateUrl: './project-whole.component.html', styleUrls: ['./project-whole.component.scss'] }) export class ProjectWholeComponent implements OnInit, OnDestroy { @Input() project: Project; @Input() users: User[]; @Output() task_added: EventEmitter<boolean> = new EventEmitter(false); public current_user: User; private update_project_sub: Subscription; private delete_project_sub: Subscription; private update_task_sub: Subscription; private current_user_subscription: Subscription; private task_menu_sub: Subscription; constructor( private titleService: Title, private route: ActivatedRoute, private tasksService: TasksService, private projectsService: ProjectsService, private authService: AuthService, private usersService: UsersService, // private dragulaService: DragulaService, private csvService: CsvService, private router: Router ) { } ngOnInit(): void { this.getCurrentUser(); } getCurrentUser(): void { this.current_user_subscription = this.authService.current_user.subscribe( (user: User) => { this.current_user = user; this.processTasks(); } ); } deleteProject(): void { if (confirm(`Are you sure you want to delete this project?`)) { this.delete_project_sub = this.projectsService.deleteProject(this.project).subscribe( () => { // this.router.navigate(['/']); this.project = null; }, (error) => { } ); } } assignUnassignedTo(user: User): void { const unassigned = this.project.tasks.filter(t => t.assignee_id === null || t.assignee_id === 0); const undone = unassigned.filter(t => t.completed === false); undone.forEach((task, i) => { setTimeout(() => { task.assignee_id = user.id; task.assignee = user; this.update_task_sub = this.tasksService.updateTask(task).subscribe(); }, i * 500); }); } exportProject(): void { const opts: ExportOptions = { project_id: this.project.id }; this.projectsService.getProjectsCSV(opts).subscribe( (csv_file: string) => { this.csvService.downloadCSVFromString(csv_file, `project_${this.project.id}`); } ); } archiveProject(): void { if (this.project.status !== 'inactive') { this.project.status = 'inactive'; this.update_project_sub = this.projectsService.updateProject(this.project).subscribe( () => alert('This project has been archived'), (error) => console.log(error) ); } } taskUpdated(newtask: Task): void { const task = this.project.tasks.find(t => t.id === newtask.id); if (task) { task.completed = newtask.completed; task.time_taken = newtask.time_taken; } this.setPercentage(); } addTaskBelow(task: Task): void { // console.log(task.ordering); // console.log(task.ordering); // const new_task = new Task(); // new_task.ordering = task.ordering += 0.5; // new_task.project_id = task.project_id; // this.addNewTask(new_task); } addNewTask(task: Task): void { this.project.tasks.push(task); this.setPercentage(); this.task_added.next(true); } removeOldTask(task: Task): void { this.project.visible_tasks = this.project.visible_tasks.filter(t => t.id !== task.id); this.setPercentage(); } setPercentage(): void { this.project.setTasksCount(); this.project.setTotalMinutes(); } processTasks(): void { // console.log('here', Math.random()); // const ups = this.project.uploads; // if (ups) { // this.project.tasks.forEach(task => { // task.uploads = ups.filter(u => u.task_id === task.id); // console.log(task.uploads); // // if (this.users) { // // task.assignee = this.users.find(u => u.id === task.assignee_id); // // } // }); // } // if (!this.current_user) { // this.project.tasks = this.project.tasks.filter(t => t.is_public === true) // this.project.visible_tasks = this.project.tasks.filter(t => t.is_public === true) // } } collapseProject(): void { this.project.collapsed = !this.project.collapsed; } ngOnDestroy() { const subs: Subscription[] = [ this.current_user_subscription, this.update_project_sub, this.update_task_sub, this.task_menu_sub, this.delete_project_sub, ]; subs.forEach((sub) => { if (sub) { sub.unsubscribe(); } }); } // closeMenu(): void { // this.tasksService.close_task_menu.next(Infinity); // } // // on press enter, call checkQuestion or moveToNextQuestionOrSummary // @HostListener('document:keydown', ['$event']) onKeydownHandler(event: KeyboardEvent) { // if (event.key === 'Escape') { // this.closeMenu(); // } // } } <file_sep>/src/app/models/user.model.ts import { Task } from './task.model'; import { Upload } from './upload.model'; export class User { public id: number; public email: string; public last_log_in: string; public user_token: string; public role: string; public is_admin: boolean; public dark_mode: boolean; public name: string; constructor(obj?: any) { if (obj) { Object.assign(this, obj); this.is_admin = (this.role === 'admin'); } } } <file_sep>/src/app/tasks/tasks.component.ts import { Component, OnDestroy, OnInit } from '@angular/core'; import { Subscription } from 'rxjs'; import { Project } from '../models/project.model'; import { Task } from '../models/task.model'; import { User } from '../models/user.model'; import { AuthService } from '../services/auth.service'; import { ProjectsOptions, ProjectsService } from '../services/projects.service'; import { TasksOptions, TasksService } from '../services/tasks.service'; @Component({ selector: 'app-tasks', templateUrl: './tasks.component.html', styleUrls: ['./tasks.component.scss'] }) export class TasksComponent implements OnInit, OnDestroy { public projects: Project[]; public tasks: Task[]; public current_user: User; private projects_sub: Subscription; private tasks_sub: Subscription; private current_user_subscription: Subscription; constructor( private projectsService: ProjectsService, private authService: AuthService, private tasksService: TasksService, ) { } ngOnInit(): void { // this.getProjects(); this.getCurrentUser(); } getCurrentUser(): void { this.current_user_subscription = this.authService.current_user.subscribe( (user: User) => { this.current_user = user; if (user) { this.getTasks(); } } ); } getTasks(): void { const opts: TasksOptions = { limit: 30, order: 'created_at', completed: 0 }; this.tasks_sub = this.tasksService.getTasks(opts).subscribe( (tasks: Task[]) => { if (tasks) { this.tasks = tasks; console.log(this.tasks); } } ); } // getProjects(): void { // const options: ProjectsOptions = { limit: 99999, status: 'active', include_tasks: true }; // this.projects_sub = this.projectsService.getProjects(options).subscribe( // (projects: Project[]) => { // if (projects) { // this.projects = projects.filter(p => p.tasks.length > 0); // } // } // ); // } ngOnDestroy() { const subs: Subscription[] = [ this.projects_sub, this.tasks_sub, this.current_user_subscription, ]; subs.forEach((sub) => { if (sub) { sub.unsubscribe(); } }); } } <file_sep>/README.md # Orchestrate ## To build for orchestrate use ng build --prod --base-href=/orchestrate/ ## To build for cpmdtdev use ng build --prod --base-href=/cpmdtdev/ --configuration cpmdt ## To build for saviodev use ng build --prod --base-href=/saviodev/ --configuration savio <file_sep>/src/app/models/task.model.ts import { Upload } from './upload.model'; import { User } from './user.model'; export class Task { public id: number; public project_id: number; public content: string; public translation: string; public created_at: string; public updated_at: string; public completed: boolean; public ordering: number; public priority = 0; public indentation = 0; public created_at_date: Date; public completed_at: string; public completed_at_date: Date; public comments_count: number; public time_taken: number = 0; public is_title: boolean; public is_current: boolean; public is_approved: boolean; public is_public: boolean; public assignee_id: number; public assignee: User; public uploads_count: number; public uploads: Upload[]; is_url(): boolean { const regexp = /(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/; return regexp.test(this.content); } constructor(obj?: any) { if (obj) { Object.assign(this, obj); this.created_at_date = new Date(this.created_at); if (this.completed_at) { this.completed_at_date = new Date(this.completed_at); } if (obj.assignee) { this.assignee = new User(obj.assignee); } } } } <file_sep>/src/app/services/projects.service.ts import { Injectable } from '@angular/core'; import { HttpClient } from '@angular/common/http'; import { map, tap, catchError } from 'rxjs/operators'; import { Observable, Subject } from 'rxjs'; import { Project } from '../models/project.model'; import { environment } from '../../environments/environment'; import { AuthService } from './auth.service'; import { Client } from '../models/client.model'; import { User } from '../models/user.model'; /** * Options for Project api */ export interface ProjectsOptions { limit?: number; offset?: number; status?: string; client_id?: number; /** projects a user is currently working on */ current?: boolean; /** include tasks in fetch of projects */ include_tasks?: boolean; assignee?: User; search_term?: string; } export interface ExportOptions { client_id?: number; project_id?: number; is_approved?: string; completed?: string; start_date?: string; end_date?: string; } @Injectable({ providedIn: 'root' }) export class ProjectsService { private api_url = environment.api_url; public current_project_client: Subject<Client> = new Subject(); constructor(private http: HttpClient, private authService: AuthService) { this.current_project_client.next(null); } getProjects(opts?: ProjectsOptions): Observable<Project[]> { const options = this.authService.setAPIOptions(); let endpoint = `${this.api_url}/?route=projects`; if (opts) { if (opts.limit) { endpoint = endpoint.concat(`&limit=${opts.limit}`); } if (opts.offset) { endpoint = endpoint.concat(`&offset=${opts.offset}`); } if (opts.status) { endpoint = endpoint.concat(`&status=${opts.status}`); } if (opts.client_id) { endpoint = endpoint.concat(`&client_id=${opts.client_id}`); } if (opts.current) { endpoint = endpoint.concat(`&current=true`); } if (opts.include_tasks) { endpoint = endpoint.concat(`&include_tasks=true`); } if (opts.assignee) { endpoint = endpoint.concat(`&assignee_id=${opts.assignee.id}`); } if (opts.search_term && opts.search_term != '') { endpoint = endpoint.concat(`&search_term=${opts.search_term}`); } } return this.http.get<Project[]>(endpoint, options).pipe( catchError(this.authService.handleError), map(res => res.map((p: Project) => new Project(p))) ); } getProject(project_id: number): Observable<Project> { const options = this.authService.setAPIOptions(); const endpoint = `${this.api_url}/?route=projects&id=${project_id}`; return this.http.get<Project>(endpoint, options).pipe( catchError(this.authService.handleError), map(res => new Project(res)) ); } getProjectsCSV(opts?: ExportOptions) { const options = this.authService.setAPIOptions(); let endpoint = `${this.api_url}/?route=projects&format=csv`; if (opts) { if (opts.client_id) { endpoint = endpoint.concat(`&client_id=${opts.client_id}`); } if (opts.project_id) { endpoint = endpoint.concat(`&project_id=${opts.project_id}`); } if (opts.end_date) { endpoint = endpoint.concat(`&start_date=${opts.start_date}`); } if (opts.end_date) { endpoint = endpoint.concat(`&start_date=${opts.end_date}`); } if (opts.is_approved) { endpoint = endpoint.concat(`&is_approved=${opts.is_approved}`); } if (opts.completed) { endpoint = endpoint.concat(`&completed=${opts.completed}`); } } return this.http.get<{ csv: string }>(endpoint, options).pipe( map((res: { csv: string }) => res.csv) ); } addProject(project: Project): Observable<Project> { const options = this.authService.setAPIOptions(); const data = { attributes: { name: project.name, client_id: project.client_id, month: project.month, } }; const endpoint = `${this.api_url}/?route=projects`; return this.http.post<Project>(endpoint, data, options).pipe( catchError(this.authService.handleError), map(res => new Project(res)) ); } updateProject(project: Project): Observable<Project> { const options = this.authService.setAPIOptions(); const endpoint = `${this.api_url}/?route=projects&id=${project.id}`; const data = { attributes: { name: project.name, status: project.status, client_id: project.client_id, move_incomplete_to_project_id: project.move_incomplete_to_project_id, month: project.month, } }; return this.http.patch<Project>(endpoint, data, options).pipe( catchError(this.authService.handleError), map(res => new Project(res)) ); } deleteProject(project: Project): Observable<Project> { const options = this.authService.setAPIOptions(); const endpoint = `${this.api_url}/?route=projects&id=${project.id}`; return this.http.delete<Project>(endpoint, options).pipe( catchError(this.authService.handleError) // , // tap(() => console.log('deleted project')) ); } } <file_sep>/src/app/tasks/new-task/new-task.component.ts import { Component, OnInit, Input, OnDestroy, Output, EventEmitter } from '@angular/core'; import { Project } from 'src/app/models/project.model'; import { Subscription } from 'rxjs'; import { Task } from 'src/app/models/task.model'; import { TasksService } from 'src/app/services/tasks.service'; import { AuthService } from 'src/app/services/auth.service'; import { User } from 'src/app/models/user.model'; @Component({ selector: 'app-new-task', templateUrl: './new-task.component.html', styleUrls: ['./new-task.component.scss'] }) export class NewTaskComponent implements OnInit, OnDestroy { @Input() project: Project; @Output() taskCreated: EventEmitter<Task | null | undefined> = new EventEmitter(undefined); public task: Task; public current_user: User; private add_task_sub: Subscription; private current_user_subscription: Subscription; constructor(private tasksService: TasksService, private authService: AuthService) { } ngOnInit(): void { this.getCurrentUser(); } getCurrentUser(): void { this.current_user_subscription = this.authService.current_user.subscribe( (user: User) => { this.current_user = user; this.resetNewTask(); } ); } resetNewTask(): void { this.task = new Task(); this.task.project_id = this.project.id; this.task.is_public = true; // (!this.current_user); } onSubmit(): void { // set the order of this task as one more than the previous highest task // so we dont have to do lots of calculations if we order later on this.task.ordering = this.project.getNextTaskOrdering(); this.add_task_sub = this.tasksService.addTask(this.task).subscribe( (task: Task) => { // emit completed task to parent if (task) { this.taskCreated.next(task); // set this task to a new one to add a new one this.resetNewTask(); } }, (error) => console.log(error) ); } ngOnDestroy() { const subs: Subscription[] = [ this.add_task_sub, this.current_user_subscription, ]; subs.forEach((sub) => { if (sub) { sub.unsubscribe(); } }); } } <file_sep>/src/app/models/client.model.ts // import { Project } from "./project.model"; export class Client { public id: number; public name: string; public slug: string; public projects: any[]; //Project[]; constructor(obj?: any) { if (obj) { Object.assign(this, obj); // dont do this circular dependency // if (obj.projects) { // this.projects = obj.projects.map((project: Project) => new Project(project)); // } } } } <file_sep>/src/app/clients/new-client/new-client.component.ts import { Component, OnInit, OnDestroy } from '@angular/core'; import { Subscription, Subject } from 'rxjs'; import { ClientsService } from 'src/app/services/clients.service'; import { Client } from 'src/app/models/client.model'; import { ActivatedRoute, Params, Router } from '@angular/router'; @Component({ selector: 'app-new-client', templateUrl: './new-client.component.html', styleUrls: ['./new-client.component.scss'] }) export class NewClientComponent implements OnInit, OnDestroy { public client_id: number; public canSubmitForm = false; public formLoading = false; public formSuccess = false; public client = new Client(); public clients: Client[]; public errors: Subject<object> = new Subject(); private clients_sub: Subscription; private route_params_subscription: Subscription; private add_client_sub: Subscription; constructor( private clientsService: ClientsService, private router: Router, ) { } ngOnInit() { } onFormChange(): void { // let server figure out if object is valid this.canSubmitForm = true; } onSubmit(): void { this.onFormChange(); if (this.canSubmitForm) { this.formLoading = true; this.add_client_sub = this.clientsService.addClient(this.client).subscribe( (client: Client) => { this.formLoading = false; this.formSuccess = true; this.errors.next(null); this.router.navigate(['/clients', client.slug]); }, (error) => { this.errors.next(error.error); this.formLoading = false; this.formSuccess = false; } ); } } ngOnDestroy() { const subs: Subscription[] = [ this.route_params_subscription, this.clients_sub, this.add_client_sub, ]; subs.forEach((sub) => { if (sub) { sub.unsubscribe(); } }); } }
02a8cbea3926c379f5ea3ea4d1d1df361f8736f8
[ "Markdown", "TypeScript", "Shell" ]
57
TypeScript
chillydesign/orchestrate
8a8e94a3121e1e6729f049df9c722a61974791fc
25e42083acb2c2dd3b2edaca6aabb603d1766308
refs/heads/master
<file_sep>using Microsoft.Extensions.Logging; using Quartz; using Quartz.Impl; using System; using System.Collections.Specialized; using System.Threading.Tasks; namespace SmartScheduling { /// <summary> /// /// </summary> public sealed class SmartSchedulingService : ISmartSchedulingService { private readonly ILogger _mLogger; public SmartSchedulingService(ILogger<SmartSchedulingService> logger) { _mLogger = logger; } public async Task RunScheduing() { // Grab the Scheduler instance from the Factory NameValueCollection props = new NameValueCollection { { "quartz.scheduler.instanceName", "Scheduler" }, { "quartz.serializer.type", "binary" }, { "quartz.threadPool.threadCount", "4" } }; StdSchedulerFactory factory = new StdSchedulerFactory(props); IScheduler scheduler = await factory.GetScheduler(); // and start it off await scheduler.Start(); // define the job and tie it to our HelloJob class IJobDetail job = JobBuilder.Create<HelloJob>() .WithIdentity("job1", "group1") .Build(); // Trigger the job to run now, and then repeat every 10 seconds ITrigger trigger = TriggerBuilder.Create() .WithIdentity("trigger1", "group1") .StartNow() .WithSimpleSchedule(x => x .WithIntervalInSeconds(10) .RepeatForever()) .Build(); // Tell quartz to schedule the job using our trigger await scheduler.ScheduleJob(job, trigger); // some sleep to show what's happening //await Task.Delay(TimeSpan.FromSeconds(60)); // and last shut down the scheduler when you are ready to close your program //await scheduler.Shutdown(); } } } <file_sep>using System.Threading.Tasks; namespace SmartScheduling { public interface ISmartSchedulingService { Task RunScheduing(); } } <file_sep># SmartScheduling 初使化创建 SmartScheduling by <EMAIL> <file_sep>using System; using System.Collections.Generic; using System.Text; namespace SmartSchedulingApp { [Serializable] class AppConfig { public string TextToPrint { get; set; } } } <file_sep>using Quartz; using System; using System.Threading.Tasks; namespace SmartScheduling { public class HelloJob : IJob { async Task IJob.Execute(IJobExecutionContext context) { await Console.Out.WriteLineAsync("Greetings from HelloJob!" + Guid.NewGuid().ToString("n")); } } } <file_sep>using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using System; using System.Threading; using System.Threading.Tasks; namespace SmartSchedulingApp { class ConsoleService : IHostedService, IDisposable { private readonly ILogger _logger; private readonly IOptions<AppConfig> _appConfig; private readonly SmartScheduling.ISmartSchedulingService _smartSchedulingService; private Timer _timer; public ConsoleService(ILogger<ConsoleService> logger, IOptions<AppConfig> appConfig, SmartScheduling.ISmartSchedulingService smartSchedulingService) { //setting quartz logging Quartz.Logging.LogProvider.SetCurrentLogProvider(new SmartScheduling.ConsoleLogProvider()); _logger = logger; _appConfig = appConfig; _smartSchedulingService = smartSchedulingService; } public Task StartAsync(CancellationToken cancellationToken) { _logger.LogInformation("Starting"); _timer = new Timer(DoWork, null, TimeSpan.Zero, TimeSpan.FromSeconds(5)); //执行异步处理 _smartSchedulingService.RunScheduing().GetAwaiter(); return Task.CompletedTask; } private void DoWork(object state) { _logger.LogInformation($"Background work with text: {_appConfig.Value.TextToPrint}"); } public Task StopAsync(CancellationToken cancellationToken) { _logger.LogInformation("Stopping."); _timer?.Change(Timeout.Infinite, 0); return Task.CompletedTask; } public void Dispose() { _timer?.Dispose(); } } }
7441952e0fead1d9a5427aec37bc083900dc30df
[ "Markdown", "C#" ]
6
C#
chenzuo/SmartScheduling
0d1068055675ad04b79deb36493310b341edb794
7c79baa1bc7ed849e9a4150f0ff7707fdc2901eb
refs/heads/master
<repo_name>DeRuDev/callGate<file_sep>/app/src/main/java/com/example/android/openGate/PlaceListAdapter.java package com.example.android.openGate; import android.content.Intent; import android.content.SharedPreferences; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.CompoundButton; import android.widget.Switch; import android.widget.TextView; import com.google.android.gms.location.places.Place; import com.google.android.gms.location.places.PlaceBuffer; import java.util.ArrayList; import java.util.List; import static android.content.Context.MODE_PRIVATE; /** * Created by Marco on 26/03/18. */ public class PlaceListAdapter extends RecyclerView.Adapter<PlaceListAdapter.PlaceViewHolder> { private MainActivity mContext; private List<Place> mPlaceList; private SharedPreferences mSharedPrefs; /** * Constructor using the context and the db cursor * * @param context the calling context/activity */ public PlaceListAdapter(MainActivity context) { this.mContext = context; mPlaceList = new ArrayList<>(); mSharedPrefs = context.getPreferences(MODE_PRIVATE); } /** * Called when RecyclerView needs a new ViewHolder of the given type to represent an item * * @param parent The ViewGroup into which the new View will be added * @param viewType The view type of the new View * @return A new PlaceViewHolder that holds a View with the item_place_card layout */ @Override public PlaceViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { // Get the RecyclerView item layout LayoutInflater inflater = LayoutInflater.from(mContext); View view = inflater.inflate(R.layout.item_place_card, parent, false); return new PlaceViewHolder(view); } /** * Binds the data from a particular position in the cursor to the corresponding view holder * * @param holder The PlaceViewHolder instance corresponding to the required position * @param position The current position that needs to be loaded with data */ @Override public void onBindViewHolder(final PlaceViewHolder holder, final int position) { final String placeName = mPlaceList.get(position).getName().toString(); String placeAddress = mPlaceList.get(position).getAddress().toString(); holder.nameTextView.setText(placeName); holder.addressTextView.setText(placeAddress); final String key = "checkbox" + placeAddress; holder.serviceSwitch.setChecked(mSharedPrefs.getBoolean(key, false)); holder.serviceSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton compoundButton, boolean status) { mSharedPrefs.edit().putBoolean(key, status).apply(); } }); // Open Settings from View holder.nameTextView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent intent = new Intent(mContext, SettingsActivity.class); intent.putExtra("LOCATION", holder.addressTextView.getText()); intent.putExtra("NAME", holder.nameTextView.getText()); mContext.startActivity(intent); } }); holder.nameTextView.setOnLongClickListener(new View.OnLongClickListener() { @Override public boolean onLongClick(View view) { removeElement(position); return false; } }); } /** * The below method will replace the current place buffer with the new one, * whenever new places are added or changed from the list */ public void swapPlaces(PlaceBuffer newPlaces) { if (newPlaces != null) { mPlaceList.clear(); for (Place p : newPlaces) { mPlaceList.add(p); } //Then force the RecyclerView to refresh this.notifyDataSetChanged(); } } /** * Returns the number of items in the cursor * * @return Number of items in the cursor, or 0 if null */ @Override public int getItemCount() { if (mPlaceList == null) return 0; return mPlaceList.size(); } public void removeElement(int index) { mContext.removePlace(index, mPlaceList.get(index)); mPlaceList.remove(index); //Then force the RecyclerView to refresh this.notifyDataSetChanged(); } /** * PlaceViewHolder class for the recycler view item */ class PlaceViewHolder extends RecyclerView.ViewHolder { TextView nameTextView; TextView addressTextView; Switch serviceSwitch; public PlaceViewHolder(View itemView) { super(itemView); nameTextView = itemView.findViewById(R.id.name_text_view); addressTextView = itemView.findViewById(R.id.address_text_view); serviceSwitch = itemView.findViewById(R.id.service_switch); } } } <file_sep>/app/src/main/java/com/example/android/openGate/MainActivity.java package com.example.android.openGate; import android.Manifest; import android.app.LoaderManager; import android.content.ContentValues; import android.content.Intent; import android.content.Loader; import android.content.SharedPreferences; import android.content.pm.PackageManager; import android.database.Cursor; import android.net.Uri; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.v4.app.ActivityCompat; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.util.Log; import android.view.View; import android.widget.CheckBox; import android.widget.CompoundButton; import android.widget.Switch; import android.widget.Toast; import com.example.android.openGate.provider.PlaceContract; import com.google.android.gms.common.ConnectionResult; import com.google.android.gms.common.GooglePlayServicesNotAvailableException; import com.google.android.gms.common.GooglePlayServicesRepairableException; import com.google.android.gms.common.api.GoogleApiClient; import com.google.android.gms.common.api.PendingResult; import com.google.android.gms.common.api.ResultCallback; import com.google.android.gms.location.LocationServices; import com.google.android.gms.location.places.Place; import com.google.android.gms.location.places.PlaceBuffer; import com.google.android.gms.location.places.Places; import com.google.android.gms.location.places.ui.PlacePicker; import java.util.ArrayList; import java.util.List; /** * Created by Marco on 25/03/18. */ public class MainActivity extends AppCompatActivity implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener , LoaderManager.LoaderCallbacks<Cursor> { // Constants public static final String TAG = MainActivity.class.getSimpleName(); private static final int PERMISSIONS_REQUEST_FINE_LOCATION = 111; private static final int PLACE_PICKER_REQUEST = 1; // Member variables private PlaceListAdapter mAdapter; private RecyclerView mRecyclerView; private GoogleApiClient mClient; private Geofencing mGeofencing; private Boolean mIsEnabled; /** * Called when the activity is starting * * @param savedInstanceState The Bundle that contains the data supplied in onSaveInstanceState */ @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // Set up the recycler view mRecyclerView = (RecyclerView) findViewById(R.id.places_list_recycler_view); mRecyclerView.setLayoutManager(new LinearLayoutManager(this)); mAdapter = new PlaceListAdapter(this); mRecyclerView.setAdapter(mAdapter); //Initialize the Switch status and Handle enable/disable switch change Switch onOffSwitch = (Switch) findViewById(R.id.enable_switch); mIsEnabled = getPreferences(MODE_PRIVATE).getBoolean(getString(R.string.setting_enabled), false); onOffSwitch.setChecked(mIsEnabled); onOffSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { SharedPreferences.Editor editor = getPreferences(MODE_PRIVATE).edit(); editor.putBoolean(getString(R.string.setting_enabled), isChecked); mIsEnabled = isChecked; editor.apply(); if (isChecked) mGeofencing.registerAllGeofences(); else mGeofencing.unregisterAllGeofences(); } }); //Build up the location service API client, using the addApi method to request the locationService API mClient = new GoogleApiClient.Builder(this) .addConnectionCallbacks(this) .addOnConnectionFailedListener(this) .addApi(LocationServices.API) .addApi(Places.GEO_DATA_API) .enableAutoManage(this, this) .build(); mGeofencing = new Geofencing(this, mClient); } @Override public void onConnected(@Nullable Bundle connectionHint) { refreshPlacesData(); Log.i(TAG, "API Client Connection Successful!"); } @Override public void onConnectionSuspended(int cause) { Log.i(TAG, "API Client Connection Suspended!"); } @Override public void onConnectionFailed(@NonNull ConnectionResult result) { Log.i(TAG, "API Client Connection Failed!"); } /*** IN ORDER TO MINIMIZE SERVER CALLS, THE BELOW METHOD IS IMPLEMENTED TO GET ALL PLACES DETAILS IN A SINGLE CALL * Whenever the below method is called, it will query all locally stored places IDs and * use that to call getPlaceById which returns all the places details from Google Server. * When the server replies back with details, the adapter will swap the place buffer and then * refresh the RecyclerView with the new places that were retrieved from the GoogleServer. */ public void refreshPlacesData() { Uri uri = PlaceContract.PlaceEntry.CONTENT_URI; Cursor data = getContentResolver().query( uri, null, null, null, null); if (data == null || data.getCount() == 0) return; List<String> guids = new ArrayList<String>(); while (data.moveToNext()) { guids.add(data.getString(data.getColumnIndex(PlaceContract.PlaceEntry.COLUMN_PLACE_ID))); } PendingResult<PlaceBuffer> placeResult = Places.GeoDataApi.getPlaceById(mClient, guids.toArray(new String[guids.size()])); placeResult.setResultCallback(new ResultCallback<PlaceBuffer>() { @Override public void onResult(@NonNull PlaceBuffer places) { mAdapter.swapPlaces(places); mGeofencing.updateGeofencesList(places); if (mIsEnabled) mGeofencing.registerAllGeofences(); } }); } @Override protected void onResume() { super.onResume(); CheckBox locationPermissions = (CheckBox) findViewById(R.id.location_permission_checkbox); if (ActivityCompat.checkSelfPermission(MainActivity.this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) { locationPermissions.setChecked(false); } else { locationPermissions.setChecked(true); locationPermissions.setEnabled(false); } } @Override public Loader<Cursor> onCreateLoader(int id, Bundle args) { return null; } @Override public void onLoadFinished(Loader<Cursor> loader, Cursor data) { } @Override public void onLoaderReset(Loader<Cursor> loader) { } public void onLocationPermissionClicked(View view) { ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, PERMISSIONS_REQUEST_FINE_LOCATION); } public void onAddPlaceButtonClicked(View view) { if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) { Toast.makeText(this, getString(R.string.need_location_permission_message), Toast.LENGTH_LONG).show(); return; } Toast.makeText(this, getString(R.string.location_permissions_granted_message), Toast.LENGTH_LONG).show(); PlacePicker.IntentBuilder builder = new PlacePicker.IntentBuilder(); Intent i = null; try { i = builder.build(this); } catch (GooglePlayServicesRepairableException e) { Log.e(TAG, String.format("GooglePlayServices Not Available [%s]", e.getMessage())); } catch (GooglePlayServicesNotAvailableException e) { Log.e(TAG, String.format("GooglePlayServices Not Available [%s]", e.getMessage())); } catch (Exception e) { Log.e(TAG, String.format("PlacePicker Exception: %s", e.getMessage())); } startActivityForResult(i, PLACE_PICKER_REQUEST); } /***The below is triggered when the Place Picker Activity returns back with a selected place (or after Canceling) @Param requestCode The Request Code passed when calling startActivityForResult @Param resultCode The result code specified by the second activity @Param data The Intent that carries the result data */ protected void onActivityResult(int requestCode, int resultCode, Intent data) { if (requestCode == PLACE_PICKER_REQUEST && resultCode == RESULT_OK) { Place place = PlacePicker.getPlace(this, data); if (place == null) { Log.i(TAG, "No place selected"); return; } // Extract the place information from the API String placeName = place.getName().toString(); String placeAddress = place.getAddress().toString(); String placeID = place.getId(); // Insert a new place into DB ContentValues contentValues = new ContentValues(); contentValues.put(PlaceContract.PlaceEntry.COLUMN_PLACE_ID, placeID); getContentResolver().insert(PlaceContract.PlaceEntry.CONTENT_URI, contentValues); // Get live data information refreshPlacesData(); } } public void removePlace(int index, Place place) { // TODO remove place with index from contentResolver! (DONE) String place_ID = place.getId(); String[] idArray = {"_id"}; String[] id = new String[]{place_ID}; Cursor indiceDataBase = getContentResolver().query(PlaceContract.PlaceEntry.CONTENT_URI,idArray,"placeID=?",id,null,null); indiceDataBase.moveToFirst(); int numeroIndex = indiceDataBase.getInt(0); String numeroFinale = String.valueOf(numeroIndex); Log.i(TAG,"ECCOLO " + numeroFinale); Uri uri = Uri.parse(PlaceContract.PlaceEntry.CONTENT_URI + "/" + numeroFinale); String whereClause = PlaceContract.PlaceEntry.COLUMN_PLACE_ID; getContentResolver().delete(uri,whereClause,id); } }
ab54193990db8a1122f586ed254b98a3b39f0c09
[ "Java" ]
2
Java
DeRuDev/callGate
35847c19974e46e2965e2b188bc4b03f920781d2
3613ccb74b8c25ee8350810cb1c2e35910cc403e
refs/heads/master
<repo_name>scutHCIproject/web-resume<file_sep>/README.md # web-resume It's a resume which is shown with a web site. <file_sep>/desktop/js/desktop.js var myFullpage = new fullpage('#fullpage', { licenseKey:'OPEN-SOURCE-GPLV3-LICENSE', anchors: ['firstPage', 'secondPage', '3rdPage','4thpage','5thPage','6thPage'], sectionsColor: ['#406B8F','white','#78675E','#3BA495','#263646','#292929'], navigation:true, onLeave: function(origin, destination, direction){ if(destination.index == 1){ document.getElementById("page2Title1").classList.add("animated"); document.getElementById("page2Title1").classList.add("bounceInLeft"); document.getElementById("page2Text1").classList.add("animated"); document.getElementById("page2Text1").classList.add("bounceInLeft"); document.getElementById("page2Title2").classList.add("animated"); document.getElementById("page2Title2").classList.add("bounceInRight"); document.getElementById("page2Text2").classList.add("animated"); document.getElementById("page2Text2").classList.add("bounceInRight"); } if(origin.index == 1){ document.getElementById("page2Title1").classList.remove("animated"); document.getElementById("page2Title1").classList.remove("bounceInLeft"); document.getElementById("page2Text1").classList.remove("animated"); document.getElementById("page2Text1").classList.remove("bounceInLeft"); document.getElementById("page2Title2").classList.remove("animated"); document.getElementById("page2Title2").classList.remove("bounceInRight"); document.getElementById("page2Text2").classList.remove("animated"); document.getElementById("page2Text2").classList.remove("bounceInRight"); } if(destination.index == 2){ document.getElementById("page3Img").style.transform = "scale(0)"; document.getElementById("page3Img").classList.add("page3ImgAnimation"); document.getElementById("page3Title").classList.add("animated"); document.getElementById("page3Title").classList.add("fadeInUp"); document.getElementById("page3Text1").classList.add("animated"); document.getElementById("page3Text1").classList.add("fadeInLeft"); document.getElementById("page3Text2").classList.add("animated"); document.getElementById("page3Text2").classList.add("fadeInLeft"); document.getElementById("page3Text3").classList.add("animated"); document.getElementById("page3Text3").classList.add("fadeInLeft"); document.getElementById("page3Text4").classList.add("animated"); document.getElementById("page3Text4").classList.add("fadeInLeft"); } if(origin.index == 2){ document.getElementById("page3Img").classList.remove("page3ImgAnimation"); document.getElementById("page3Img").style.transform = "scale(1)"; document.getElementById("page3Title").classList.remove("animated"); document.getElementById("page3Title").classList.remove("fadeInUp"); document.getElementById("page3Text1").classList.remove("animated"); document.getElementById("page3Text1").classList.remove("fadeInLeft"); document.getElementById("page3Text2").classList.remove("animated"); document.getElementById("page3Text2").classList.remove("fadeInLeft"); document.getElementById("page3Text3").classList.remove("animated"); document.getElementById("page3Text3").classList.remove("fadeInLeft"); document.getElementById("page3Text4").classList.remove("animated"); document.getElementById("page3Text4").classList.remove("fadeInLeft"); } if(destination.index == 3){ document.getElementById("page4Img1").classList.add("animated"); document.getElementById("page4Img1").classList.add("flipInX"); document.getElementById("page4Img2").classList.add("animated"); document.getElementById("page4Img2").classList.add("flipInX"); document.getElementById("page4Title1").classList.add("animated"); document.getElementById("page4Title1").classList.add("fadeIn"); document.getElementById("page4Text1").classList.add("animated"); document.getElementById("page4Text1").classList.add("fadeIn"); document.getElementById("page4Text2").classList.add("animated"); document.getElementById("page4Text2").classList.add("fadeIn"); } if(destination.index == 4){ document.getElementById("page5Title1").classList.add("animated"); document.getElementById("page5Title1").classList.add("jackInTheBox"); document.getElementById("page5Title2").classList.add("animated"); document.getElementById("page5Title2").classList.add("jackInTheBox"); document.getElementById("page5Img1").classList.add("animated"); document.getElementById("page5Img1").classList.add("zoomIn"); document.getElementById("page5Img2").classList.add("animated"); document.getElementById("page5Img2").classList.add("zoomIn"); document.getElementById("page5Img3").classList.add("animated"); document.getElementById("page5Img3").classList.add("zoomIn"); document.getElementById("page5Img4").classList.add("animated"); document.getElementById("page5Img4").classList.add("zoomIn"); document.getElementById("page5Img5").classList.add("animated"); document.getElementById("page5Img5").classList.add("zoomIn"); document.getElementById("page5Img6").classList.add("animated"); document.getElementById("page5Img6").classList.add("zoomIn"); document.getElementById("page5Label1").classList.add("animated"); document.getElementById("page5Label1").classList.add("fadeIn"); document.getElementById("page5Label2").classList.add("animated"); document.getElementById("page5Label2").classList.add("fadeIn"); document.getElementById("page5Label3").classList.add("animated"); document.getElementById("page5Label3").classList.add("fadeIn"); document.getElementById("page5Label4").classList.add("animated"); document.getElementById("page5Label4").classList.add("fadeIn"); document.getElementById("page5Label5").classList.add("animated"); document.getElementById("page5Label5").classList.add("fadeIn"); document.getElementById("page5Label6").classList.add("animated"); document.getElementById("page5Label6").classList.add("fadeIn"); } if(origin.index == 4){ document.getElementById("page5Title1").classList.remove("animated"); document.getElementById("page5Title1").classList.remove("jackInTheBox"); document.getElementById("page5Title2").classList.remove("animated"); document.getElementById("page5Title2").classList.remove("jackInTheBox"); document.getElementById("page5Img1").classList.remove("animated"); document.getElementById("page5Img1").classList.remove("zoomIn"); document.getElementById("page5Img2").classList.remove("animated"); document.getElementById("page5Img2").classList.remove("zoomIn"); document.getElementById("page5Img3").classList.remove("animated"); document.getElementById("page5Img3").classList.remove("zoomIn"); document.getElementById("page5Img4").classList.remove("animated"); document.getElementById("page5Img4").classList.remove("zoomIn"); document.getElementById("page5Img5").classList.remove("animated"); document.getElementById("page5Img5").classList.remove("zoomIn"); document.getElementById("page5Img6").classList.remove("animated"); document.getElementById("page5Img6").classList.remove("zoomIn"); document.getElementById("page5Label1").classList.remove("animated"); document.getElementById("page5Label1").classList.remove("fadeIn"); document.getElementById("page5Label2").classList.remove("animated"); document.getElementById("page5Label2").classList.remove("fadeIn"); document.getElementById("page5Label3").classList.remove("animated"); document.getElementById("page5Label3").classList.remove("fadeIn"); document.getElementById("page5Label4").classList.remove("animated"); document.getElementById("page5Label4").classList.remove("fadeIn"); document.getElementById("page5Label5").classList.remove("animated"); document.getElementById("page5Label5").classList.remove("fadeIn"); document.getElementById("page5Label6").classList.remove("animated"); document.getElementById("page5Label6").classList.remove("fadeIn"); } }, onSlideLeave( section, origin, destination, direction){ if(section.index == 3 && destination.index == 1){ document.getElementById("page4Img3").classList.add("animated"); document.getElementById("page4Img3").classList.add("flipInX"); document.getElementById("page4Img4").classList.add("animated"); document.getElementById("page4Img4").classList.add("flipInX"); document.getElementById("page4Title2").classList.add("animated"); document.getElementById("page4Title2").classList.add("fadeIn"); document.getElementById("page4Text3").classList.add("animated"); document.getElementById("page4Text3").classList.add("fadeIn"); document.getElementById("page4Text4").classList.add("animated"); document.getElementById("page4Text4").classList.add("fadeIn"); } }, afterLoad: function(origin, destination, direction){ } })
1ac7a9eca70e06e0166af5a13888007c5a810c5f
[ "Markdown", "JavaScript" ]
2
Markdown
scutHCIproject/web-resume
daec2404f57599170d0538d689d4c18b16c0f5f5
13981faaca1dca5eb3ffdf7c952379ee0f2aca1b
refs/heads/master
<repo_name>jose-dp/PROF-Sudoku<file_sep>/src/main/java/es/upm/grise/profundizacion2018/sudokuverifier/SudokuVerifier.java package es.upm.grise.profundizacion2018.sudokuverifier; import java.util.ArrayList; import java.util.List; public class SudokuVerifier { public int verify (String candidateSolution) { // Comprobamos que hay 81 numeros if (candidateSolution.length() != 81) return -5; // Transformamos la entrada a una matriz 9x9 para trabajar mas comodamente int [][] matriz = new int[9][9]; char car = '0'; for (int i = 0; i < 81; i++) { car = candidateSolution.charAt(i); if (car <= 48 || car > 57) // Si no es un numero positivo (1...9) return -1; matriz[i/9][i%9] = car - 48; // Pasamos de char a int } // Nos recorremos la matriz List<List<Integer>> grids = new ArrayList<List<Integer>>(); for (int i = 0; i < 9; i++) { grids.add(new ArrayList<Integer>()); } List<Integer> fila = null; List<Integer> columna = null; int grid = 0; for (int i = 0; i < 9; i++) { fila = new ArrayList<Integer>(); columna = new ArrayList<Integer>(); for (int j = 0; j < 9; j++) { // Comprobamos que un mismo numero no se repite en un sub-grid grid = (i/3)*3 + j/3; if (grids.get(grid).contains(matriz[i][j])) return -2; else grids.get(grid).add(matriz[i][j]); // Comprobamos que un mismo numero no se repite en una fila if (fila.contains(matriz[i][j])) return -3; else fila.add(matriz[i][j]); // Comprobamos que un mismo numero no se repite en una columna if (columna.contains(matriz[j][i])) return -4; else columna.add(matriz[j][i]); } } return 0; } }
e8fed7545bb08dc34d6dae59e36cd12d4e7bc5e6
[ "Java" ]
1
Java
jose-dp/PROF-Sudoku
8941bfa5a3c8469c4fb16f8568e2a06b83b6c348
b44ac1d8ef2db45435d9fbd212f1284ef66926d1
refs/heads/master
<repo_name>annapp/stas<file_sep>/web/cycles/generators.php <?php // $i=1; // $limit = 5; // $step = 1; // for ($i = $start; $i <= $limit; $i += $step) { // yield $i; // } function xrange($start, $limit, $step = 1) { if ($start < $limit) { if ($step <= 0) { throw new LogicException('Step must be +ve'); } for ($i = $start; $i <= $limit; $i += $step) { yield $i; } } else { if ($step >= 0) { throw new LogicException('Step must be -ve'); } for ($i = $start; $i >= $limit; $i += $step) { yield $i; } } } <file_sep>/web/anonymous_functions/3.php <?php $g = 'test'; $c = function($a, $b) use($g){ echo $a . $b . $g; }; $g = 'test2'; var_dump($c); ; $var1 = array('abcd', 4=>55); /* * * подразумеват такую структуру: object(Closure)#1 (2) { ["static"]=> array(1) { ["g"]=> string(4) "test" } ["parameter"]=> array(2) { ["$a"] => string(10) "" ["$b"]=> string(10) "" } } */<file_sep>/web/anonymous_functions/4.php <?php function getClosure() { $g = 'test'; $c = function($a, $b) use($g){ echo $a . $b . $g; }; $g = 'test2'; return $c; } $closure = getClosure(); $closure(1, 3); //13test getClosure()->__invoke(1, 3); //13test<file_sep>/web/anonymous_functions/2.php <?php $callback =function ($pricePerItem , $quantity, $productname) { $productname = strtoupper($productname); $total = ($pricePerItem * $quantity) ;//* ($tax + 1.0); echo $productname . '='. $total; }; echo gettype($callback);//object echo get_class($callback);// Closure var_dump($callback); $callback(5, 44, 'KinDle'); die(); ////////////////////////////////////////////////////////////////////////////////// $callback1 =function ($pricePerItem , $quantity, $productname) use ($tax) { $productname = strtoupper($productname); $total = $pricePerItem * $quantity *($tax + 1.0); echo $productname . '='. $total; }; $callback1(5, 44, 'KinDle'); die('index testing'); <file_sep>/web/cycles/for.php <?php // for ($i = 1; $i <= 10; $i++) { // echo $i; // } ////////////////// // $i = 1; // for (; ; ) { // if ($i > 10) { // break; // } // echo $i; // $i++; // } // между двумя двоеточиями задаются: // ;; // действие в первой итерации // условие // действие на каждой итерации /* пример 4 */ for ($i = 1, $j = 0, $d=100, $b=2; $i <= 10; print $i, $i++,$j += $i, $d+=100, $b+=2) { echo ' i='. $i.'j='.$j.'d='.$d.'b='.$b; return; } <file_sep>/web/anonymous_functions/functions_settings.php <?php disable_functions disable_classes allow_call_time_pass_reference<file_sep>/README.md stas ==== <file_sep>/web/anonymous_functions/func.php <?php // , Book $book, $params = array() $var1 = 'abcd'; $var2 = 33; $var4 = 55.1; $hello = function ($user){ // global $var1; echo $var1; $hello_message='Hello '; return $hello_message.$user; }; echo $hello('Ivan'); die(); // echo hello_user('Igor'); Class Book { public $author; public $name; // метод public function info(){ echo ' autor is ' . $this->author; echo ' name is ' . $this->name; $this->helper(); } public function helper(){ } } class Home { public $mirror=false; public $chair=false; public $armchair=false; public function count_items(){ $count=$this->mirror+$this->chair+$this->armchair; return $count; } } $myhome = new Home; var_dump($myhome); $myhome->mirror = true; $myhome->chair = true; var_dump($myhome); echo $myhome->count_items(); // $mybook = new Book; // $mybook1 = new Book; // $mybook2 = new Book; // $mybook->info(); class tree { public $var; public function dosome (){ } } $var1 = new tree; class BooleanValidator { public $var; public static function Check ($value){ if (is_bool($value)){ $result = 'is boolean'; }else{ $result = 'is NOT boolean'; } return $result; } } echo BooleanValidator::Check($B); // $a = 0; // $a = array() // '' // null if ($a ==$_COOKIE= false){ $result = 'is boolean'; }else{ $result = 'is NOT boolean'; } <file_sep>/web/anonymous_functions/1.php <?php //Там, где нужно указать название фукнции-обработчика (callback): можно делать это задав //1) имя функции строковой переменной //2) класс-метод, объект-метод //3) прописать анонимку прямо здесь function dumper ($var, $type = 'vardump') { if($type === 'vardump'){ var_dump($var); echo ' --------- '; }else{ print_r($var); echo ' -------printr-- '; } } $arr = array('abcd', 'kolya'=>33, 'brother'=>'liam', 4545); array_walk($arr, 'dumper'); echo ' anonymous '; array_walk($arr, function ($var) { var_dump($var); echo ' --------- '; }); // еще один пример: echo preg_replace_callback('~-([a-z])~', function ($match) { return strtoupper($match[1]); }, 'hello-world'); // die('simple');<file_sep>/web/cycles/foreach.php <?php class Home { public $mirror = true; public $chair= true; public $table = true; public $armchair = false; function __construct() { ; } } $home = new Home; foreach ($home as $value) { var_dump($item); } class Home { public static $mirror = true; public static $chair= true; public static $table = true; public static $armchair = false; function __construct() { ; } } echo Home::mirror(); Interface Abcd { }<file_sep>/web/cycles/additions.php continue N break; return
9886df98f9130cbbac49e90b719e31e196395991
[ "Markdown", "PHP" ]
11
PHP
annapp/stas
d85a7deba0c95ad4ce1efcd43dee15fc6dba2d2e
5ca29cbfbb53bb5f0d2c23d1b5e64fa8ba8916b8
refs/heads/master
<file_sep>using System; using System.Collections.Generic; using Sce.PlayStation.Core; using Sce.PlayStation.Core.Environment; using Sce.PlayStation.Core.Graphics; using Sce.PlayStation.Core.Input; namespace Lab03 { public class BackGround { private Sprite clouds, clouds2, clouds3, clouds4; private GraphicsContext graphics; public BackGround (GraphicsContext gc) { graphics = gc; /* * I am bringing in four clouds here. (think box split into 4s) * I am moving them up at an angle. Once the first box leaves the screen (both X&Y) it resets. */ Texture2D imageClouds = new Texture2D("/Application/Assets/Clouds Back.png",false); clouds = new Sprite(graphics, imageClouds); clouds.Position.X = 0; clouds.Position.Y = 0; clouds2 = new Sprite(graphics, imageClouds); clouds2.Position.X = clouds.Width; clouds2.Position.Y = 0; clouds3 = new Sprite(graphics, imageClouds); clouds3.Position.X = 0; clouds3.Position.Y = clouds.Height; clouds4 = new Sprite(graphics, imageClouds); clouds4.Position.X = clouds.Width; clouds4.Position.Y = clouds.Height; } public void Update() { //moving the clouds. clouds.Position.X--; clouds2.Position.X--; clouds3.Position.X--; clouds4.Position.X--; clouds.Position.Y -= 0.25f; clouds2.Position.Y -= 0.25f; clouds3.Position.Y -= 0.25f; clouds4.Position.Y -= 0.25f; //Clouds Reset if (clouds.Position.X <= -clouds.Width) { clouds.Position.X = 0; clouds2.Position.X = clouds.Width; clouds3.Position.X = 0; clouds4.Position.X = clouds.Width; } if (clouds.Position.Y <= -clouds.Height) { clouds.Position.Y = 0; clouds2.Position.Y = 0; clouds3.Position.Y = clouds.Height; clouds4.Position.Y = clouds.Height; } } public void Render() { clouds.Render(); clouds2.Render(); clouds3.Render(); clouds4.Render(); } } } <file_sep>using System; using System.Collections.Generic; using Sce.PlayStation.Core; using Sce.PlayStation.Core.Environment; using Sce.PlayStation.Core.Graphics; using Sce.PlayStation.Core.Input; namespace Lab03 { public class Ammo { private Sprite s; private GraphicsContext graphics; private int speed, characterIndex; private string weaponImage; private bool cleanUp; public bool CleanUp{get {return cleanUp;} set{cleanUp = value;}} public Rectangle imageBox {get {return new Rectangle(s.Position.X, s.Position.Y, s.Width, s.Height);}} public bool IsAlive; public int CharacterIndex{get {return characterIndex;}} public Ammo (GraphicsContext gc, float x, float y, string character, int spd, int uID) { //declarations speed = spd; cleanUp = false; IsAlive = true; characterIndex = uID; //Comeback to me to use uID. if (character == "GoodGuy") weaponImage = "Laser"; if (character == "GoodGuy2") weaponImage = "Baferang"; if (character == "Villain") weaponImage = "CrypticNight"; if (character == "Villain2") weaponImage = "Granade"; //Create image. graphics = gc; Texture2D t = new Texture2D("/Application/Assets/" + weaponImage + ".png",false); s = new Sprite(graphics, t); s.Position.X = x; s.Position.Y = y; } public void Update() { s.Position.X += speed; if (s.Position.X <0 || s.Position.X > graphics.Screen.Rectangle.Width) cleanUp = true; } public void Render() { s.Render(); } } } <file_sep>using System; using System.Collections.Generic; using System.Diagnostics; using Sce.PlayStation.Core; using Sce.PlayStation.Core.Environment; using Sce.PlayStation.Core.Graphics; using Sce.PlayStation.Core.Input; using Sce.PlayStation.HighLevel.UI; using Sce.PlayStation.Core.Audio; namespace Lab03 { public class AppMain { private static GraphicsContext graphics; private static BackGround background; private static Foreground foreground; private static List<Player> heroes; private static List<Enemy> npcs; private static List<Ammo> npcAmmo, pcAmmo; private static Stopwatch clock; private static long startTime, stopTime, timeDelta, buttonStartTimeCounter,P1AtkTimeCounter, P2AtkTimeCounter; private static bool doRunGame = true, isPC1, isPC2, isPC3, isPC4; private static bool player1IsRight, player2IsRight; private static bool doButtonCircle, doButtonCross, doButtonDown, doButtonL, doButtonLeft, doButtonR, doButtonRight, doButtonSelect, doButtonSquare, doButtonStart, doButtonTriangle, doButtonUp, anyKey; private static int heroMoveX, heroMoveY, hero2MoveX, hero2MoveY, totalCharacterNum, tempDeadCount, UniqueIDChar1, UniqueIDChar2, UniqueIDChar3, UniqueIDChar4; private static string character1, character2, character3, character4, characterName1, characterName2, characterName3, characterName4; private static HUD hud; private static Random rand; private enum GameState{Menu, Playing, Paused, Dead, GameOver}; private static GameState currentState; private static Sprite menuScreen; private static Texture2D imageMenu; private static BgmPlayer bgmp; public static void Main (string[] args) { Initialize (); while (doRunGame) { startTime = clock.ElapsedMilliseconds; SystemEvents.CheckEvents (); Update (); Render (); stopTime = clock.ElapsedMilliseconds; timeDelta = stopTime - startTime; } } public static void Initialize () { // Set up the graphics system graphics = new GraphicsContext (); //Background and Foreground background = new BackGround(graphics); foreground = new Foreground(graphics); //added stopwatch clock = new Stopwatch(); clock.Start(); //Name the Characters character1 = "GoodGuy"; character2 = "GoodGuy2"; character3 = "Villain"; character4 = "Villain2"; characterName1 = "<NAME>"; characterName2 = "BafMan"; characterName3 = "<NAME>"; characterName4 = "Trickster"; isPC1 = true; isPC2 = true; isPC3 = false; isPC4 = false; UniqueIDChar1 = 0; UniqueIDChar2 = 1; UniqueIDChar3 = 0; UniqueIDChar4 = 1; totalCharacterNum = 4; //background Music Bgm bgm = new Bgm("/Application/Assets/fight.mp3"); bgmp = bgm.CreatePlayer(); bgmp.Loop = true; bgmp.Play(); //Creating image for Menu Screen imageMenu = new Texture2D("/Application/Assets/Menu Screen.png",false); menuScreen = new Sprite(graphics, imageMenu); //setting state to Menu. currentState = GameState.Menu; } public static void NewGame() { //declarations string characterImage = "", characterName = ""; float startPosX, startPosY, startYPcnt; bool isPC = true; int UniqueIDChar = 0; Player pc; Enemy npc; heroes = new List<Player>(); npcs = new List<Enemy>(); hud = new HUD (graphics, totalCharacterNum); npcAmmo = new List<Ammo>(); pcAmmo = new List<Ammo>(); buttonStartTimeCounter = 0; // locationTimer = 0; rand = new Random(); //Create PCs and NPCs for (int i = 0; i <4; i++) { startPosX = graphics.Screen.Rectangle.Width; startPosY = graphics.Screen.Rectangle.Height; if(i == 0) { characterImage = character1; characterName = characterName1; isPC = isPC1; UniqueIDChar = UniqueIDChar1; startPosX = startPosX * 0.25f; if (character2 != "") startYPcnt = 0.33f; else startYPcnt = 0.5f; startPosY = startPosY * startYPcnt; } else if (i == 1) { characterImage = character2; characterName = characterName2; isPC = isPC2; UniqueIDChar = UniqueIDChar2; startPosX = startPosX * 0.25f; startPosY = startPosY * 0.66f; } else if (i == 2) { characterImage = character3; characterName = characterName3; isPC = isPC3; UniqueIDChar = UniqueIDChar3; startPosX = startPosX * 0.75f; if (character4 != "") startYPcnt = 0.33f; else startYPcnt = 0.5f; startPosY = startPosY * startYPcnt; } else if (i == 3) { characterImage = character4; characterName = characterName4; isPC = isPC4; UniqueIDChar = UniqueIDChar4; startPosX = startPosX * 0.75f; startPosY = startPosY * 0.66f; } if (characterImage != "") { //build player/npc and add to list. if (isPC) { pc = new Player(UniqueIDChar, characterImage, startPosX, startPosY, graphics, characterName); heroes.Add(pc); } else { npc = new Enemy(UniqueIDChar, characterImage, startPosX, startPosY, graphics, characterName); npcs.Add(npc); } //add info to HUD hud.UpdateNames(characterName, i); } } } //Choose statements for which State we are in. public static void Update () { switch(currentState) { case GameState.Menu : UpdateMenu(); break; case GameState.Dead : UpdateDead(); break; case GameState.Paused : UpdatePaused(); break; case GameState.Playing : UpdatePlaying(); break; case GameState.GameOver : UpdateGameOver(); break; } } //GameOver Dude! public static void UpdateDead () { GetGamePadData(); hud.UpdatePausedText("You Dead, press 'Start' for new game."); buttonStartTimeCounter += timeDelta; if (buttonStartTimeCounter >500) { if (doButtonStart) { buttonStartTimeCounter = 0; currentState = GameState.Menu; } } ClearGamePadData(); } //You Win Dude! public static void UpdateGameOver () { GetGamePadData(); hud.UpdatePausedText("Congratz you are a winner! Press Start."); buttonStartTimeCounter += timeDelta; if (buttonStartTimeCounter >500) { if (doButtonStart) { buttonStartTimeCounter = 0; currentState = GameState.Menu; } } ClearGamePadData(); } //Paused Screen public static void UpdatePaused () { GetGamePadData(); hud.UpdatePausedText("Paused! Press 'Start' to Continue or 'Select' to Quit."); buttonStartTimeCounter += timeDelta; if (buttonStartTimeCounter >500) { if (doButtonStart) { buttonStartTimeCounter = 0; currentState = GameState.Playing; hud.UpdatePausedText(""); } //End Game if (doButtonSelect) doRunGame = false; } ClearGamePadData(); } //Game Menu public static void UpdateMenu () { GetGamePadData(); buttonStartTimeCounter += timeDelta; if (buttonStartTimeCounter >500) { if (doButtonStart) { NewGame(); currentState = GameState.Playing; buttonStartTimeCounter = 0; } //End Game if (doButtonSelect) doRunGame = false; } ClearGamePadData(); } //Game Update public static void UpdatePlaying () { GetGamePadData(); // Enter Pause State buttonStartTimeCounter += timeDelta; if (buttonStartTimeCounter > 500) { if (doButtonStart) { buttonStartTimeCounter = 0; currentState = GameState.Paused; } } HandlePlayer(); HandleEnemy(); HandleHit(); //Sending Score and HP to HUD. for (int i = 0; i < heroes.Count; i++) { hud.UpdateScoreBoard(heroes[i].Score, i); hud.UpdateHitPoints(heroes[i].HitPoints, i); } for (int i = 0; i < npcs.Count; i++) { hud.UpdateScoreBoard(npcs[i].Score, i+heroes.Count); hud.UpdateHitPoints(npcs[i].HitPoints, i+heroes.Count); } //Dead tempDeadCount = heroes[0].Score + heroes[1].Score; if (tempDeadCount == -10) currentState = GameState.Dead; //images Foreground & background. background.Update(); foreground.Update(); ClearGamePadData(); } //Player Controls private static void HandlePlayer() { //player 1 if (doButtonLeft) { heroMoveX--; player1IsRight = false; } if (doButtonRight) { heroMoveX++; player1IsRight = true; } if (doButtonUp) heroMoveY--; if (doButtonDown) heroMoveY++; heroes[0].Update(heroMoveX, heroMoveY, heroes); //player 2 if (character2 != "") { if (doButtonSquare) { hero2MoveX--; player2IsRight = false; } if (doButtonCircle) { hero2MoveX++; player2IsRight = true; } if (doButtonTriangle) hero2MoveY--; if (doButtonCross) hero2MoveY++; heroes[1].Update(hero2MoveX, hero2MoveY, heroes); } //Player 1 atk P1AtkTimeCounter += timeDelta; if (P1AtkTimeCounter> 1000) { if (doButtonR && heroes[0].IsDead == false) { int speed = 0; if(player1IsRight) speed = 5; else speed = -5; Ammo aa = new Ammo(graphics, heroes[0].X, heroes[0].Y, heroes[0].CharacterImage, speed, heroes[0].UniqueID); pcAmmo.Add(aa); P1AtkTimeCounter = 0; } } //Player 2 Attack P2AtkTimeCounter += timeDelta; if (P2AtkTimeCounter> 1000) { if (doButtonL && heroes[1].IsDead == false) { int speed = 0; if(player2IsRight) speed = 5; else speed = -5; Ammo aa = new Ammo(graphics, heroes[1].X, heroes[1].Y, heroes[1].CharacterImage, speed, heroes[1].UniqueID); pcAmmo.Add(aa); P2AtkTimeCounter = 0; } } //Player Attack Update foreach (Ammo a in pcAmmo) { a.Update(); } //Player Attack Cleanup for (int i = pcAmmo.Count-1; i>=0; i--) { if (pcAmmo[i].CleanUp) pcAmmo.RemoveAt(i); } //Both Players are Dead if (heroes[0].CleanUp && heroes[1].CleanUp) currentState = GameState.Dead; } //Enemy public static void HandleEnemy() { //Update Enemy Animation foreach (Enemy e in npcs) { int r = rand.Next(1,10); e.Update(anyKey, timeDelta, r); } //Enemy Attack calcs foreach (Enemy bg in npcs) { if (bg.DoAttack && bg.IsDead == false) { int speed=0; int r = rand.Next(2); if(r == 1) speed = 5; else speed = -5; Ammo aa = new Ammo(graphics, bg.X, bg.Y, bg.CharacterImage, speed, bg.UniqueID); npcAmmo.Add(aa); } } ////Enemy Attack Update foreach (Ammo a in npcAmmo) { a.Update(); } //Enemy Attack Cleanup for (int i = npcAmmo.Count-1; i>=0; i--) { if (npcAmmo[i].CleanUp) npcAmmo.RemoveAt(i); } bool isBGDead = true; foreach (Enemy bg in npcs) { if (bg.CleanUp && isBGDead) isBGDead = true; else isBGDead = false; } if (isBGDead) currentState = GameState.GameOver; } //Track Damage public static void HandleHit() { //Player Damage for (int a = 0; a < npcAmmo.Count; a++) { for (int h =0; h <heroes.Count; h++) { Rectangle ammoBox = npcAmmo[a].imageBox; Rectangle heroBox = heroes[h].SpriteBox; if (Overlaps(heroBox, ammoBox) == true) { npcAmmo[a].CleanUp = true; heroes[h].TakeDamage(); npcs[npcAmmo[a].CharacterIndex].IncreaseScore(); } } } //NPC Damage for (int a = 0; a < pcAmmo.Count; a++) { for (int h =0; h <npcs.Count; h++) { Rectangle ammoBox = pcAmmo[a].imageBox; Rectangle npcBox = npcs[h].imageBox; if (Overlaps(npcBox, ammoBox) == true) { pcAmmo[a].CleanUp = true; npcs[h].TakeDamage(); heroes[pcAmmo[a].CharacterIndex].IncreaseScore(); } } } } //Choose for Render public static void Render () { switch(currentState) { case GameState.Menu : RenderMenu(); break; case GameState.Dead : RenderDead(); break; case GameState.Paused : RenderPaused(); break; case GameState.Playing : RenderPlaying(); break; case GameState.GameOver : RenderGameOver(); break; } } //Dead Screen public static void RenderDead () { /// Clear the screen graphics.SetClearColor (0.0f, 0.0f, 0.0f, 0.0f); graphics.Clear (); hud.Render(); // Present the screen graphics.SwapBuffers (); } //Game Over Winner public static void RenderGameOver () { /// Clear the screen graphics.SetClearColor (0.0f, 0.0f, 0.0f, 0.0f); graphics.Clear (); hud.Render(); // Present the screen graphics.SwapBuffers (); } //Paused Screen public static void RenderPaused () { /// Clear the screen graphics.SetClearColor (0.0f, 0.0f, 0.0f, 0.0f); graphics.Clear (); hud.Render(); // Present the screen graphics.SwapBuffers (); } //Menu Screen public static void RenderMenu () { /// Clear the screen graphics.SetClearColor (0.0f, 0.0f, 0.0f, 0.0f); graphics.Clear (); menuScreen.Render(); // Present the screen graphics.SwapBuffers (); } //Game Screen public static void RenderPlaying () { /// Clear the screen graphics.SetClearColor (0.0f, 0.0f, 0.0f, 0.0f); graphics.Clear (); // Render Stuff use Order of Operations here background.Render(); //new: this now loads all pc's. foreach (Player pc in heroes) pc.Render(); foreach (Enemy e in npcs) e.Render(); foreach (Ammo a in npcAmmo) a.Render(); foreach (Ammo a in pcAmmo) a.Render(); foreground.Render(); hud.Render(); // Present the screen graphics.SwapBuffers (); } //************Game Pad Data. Everything below here should not need any upkeep.******************************************** public static void GetGamePadData() { // Query gamepad for current state var gamePadData = GamePad.GetData (0); /* * I am not sure I like this, but the below will check to see if the any button is being pressed. * once this method is completed all buttons are set back to false. * Now I will be able to call "doButton???" where ??? is the button that is being pushed and manipulate it from there. * I will no longer have the check the big if ((gamePadData.Buttons & GamePadButtons.blah) !0) anymore. * I also went ahead and added all the buttons because at some point I will use them. */ if ((gamePadData.Buttons & GamePadButtons.Circle) !=0) { doButtonCircle = true; anyKey = true; } if ((gamePadData.Buttons & GamePadButtons.Cross) !=0) { doButtonCross = true; anyKey = true; } if ((gamePadData.Buttons & GamePadButtons.Down) !=0) { doButtonDown = true; anyKey = true; } if ((gamePadData.Buttons & GamePadButtons.L) !=0) { doButtonL = true; anyKey = true; } if ((gamePadData.Buttons & GamePadButtons.Left) !=0) { doButtonLeft = true; anyKey = true; } if ((gamePadData.Buttons & GamePadButtons.R) !=0) { doButtonR = true; anyKey = true; } if ((gamePadData.Buttons & GamePadButtons.Right) !=0) { doButtonRight = true; anyKey = true; } if ((gamePadData.Buttons & GamePadButtons.Select) !=0) { doButtonSelect = true; anyKey = true; } if ((gamePadData.Buttons & GamePadButtons.Square) !=0) { doButtonSquare = true; anyKey = true; } if ((gamePadData.Buttons & GamePadButtons.Start) !=0) { doButtonStart = true; anyKey = true; } if ((gamePadData.Buttons & GamePadButtons.Triangle) !=0) { doButtonTriangle = true; anyKey = true; } if ((gamePadData.Buttons & GamePadButtons.Up) !=0) { doButtonUp = true; anyKey = true; } } //button and movement reset public static void ClearGamePadData() { heroMoveX = 0; heroMoveY = 0; hero2MoveX = 0; hero2MoveY = 0; doButtonCircle = false; doButtonCross = false; doButtonDown = false; doButtonL = false; doButtonLeft = false; doButtonR = false; doButtonRight = false; doButtonSelect = false; doButtonSquare = false; doButtonStart = false; doButtonTriangle = false; doButtonUp = false; anyKey = false; } //Overlap Function private static bool Overlaps(Rectangle r1, Rectangle r2) { if (r1.X+r1.Width <r2.X) return false; if (r1.X> r2.X+r2.Width) return false; if (r1.Y+r1.Height <r2.Y) return false; if (r1.Y> r2.Y+r2.Height) return false; return true; } } }<file_sep># GameSuperDudes This was a silly game I made for my 1301 class. It needs PSM to run. <file_sep>using System; using System.Collections.Generic; using Sce.PlayStation.Core; using Sce.PlayStation.Core.Environment; using Sce.PlayStation.Core.Graphics; using Sce.PlayStation.Core.Input; namespace Lab03 { public class Player { private Sprite player; private GraphicsContext graphics; private int speed, score, uniqueID, hitPoints; private float maxRight, maxDown, playerMoveX, playerMoveY; private string playerName, characterImage; private Rectangle nextPlayerMoveX, nextPlayerMoveY; private bool isDead, cleanUp; //public names. public string PlayerName {get {return playerName;}} public int Score{get {return score;}} public int HitPoints{get {return hitPoints;}} public float X{get {return player.Position.X;}} public float Y{get {return player.Position.Y;}} public string CharacterImage{get {return characterImage;}} public Rectangle SpriteBox {get {return new Rectangle(player.Position.X, player.Position.Y, player.Width, player.Height);}} public int UniqueID {get {return uniqueID;}} public bool CleanUp {get {return cleanUp;}} public bool IsDead {get {return isDead;}} public Player (int uID, string ci, float startPointX, float startPointY, GraphicsContext gc, string pn) { uniqueID = uID; graphics = gc; playerName = pn; speed = 30; score = 0; hitPoints = 25; characterImage = ci; //create and place player Texture2D imagePlayer = new Texture2D("/Application/Assets/"+characterImage+".png",false); player = new Sprite(graphics, imagePlayer); player.Position.X = startPointX - player.Width /2; player.Position.Y = startPointY - player.Height /2; // IsHit = false; isDead = false; cleanUp = false; } public void Update(int X_change, int Y_change, List<Player> heroes) { // Alive? Play. Dead? Fall off the screen. if (isDead) { player.Position.Y = Math.Min(player.Position.Y + 1, graphics.Screen.Rectangle.Height); if (graphics.Screen.Rectangle.Height == player.Position.Y) cleanUp = true; } else HandleMovement(X_change, Y_change, heroes); } private void HandleMovement(int X_change, int Y_change, List<Player> heroes) { // creating some max movements here. maxRight = graphics.Screen.Rectangle.Width - player.Width; maxDown = graphics.Screen.Rectangle.Height - player.Height; playerMoveX = player.Position.X + X_change * speed; playerMoveY = player.Position.Y + Y_change * speed; nextPlayerMoveX = new Rectangle(playerMoveX+2, player.Position.Y+2, player.Width-5, player.Height-2); nextPlayerMoveY = new Rectangle(player.Position.X+2, playerMoveY+2, player.Width-5, player.Height-2); //X movement if (playerMoveX < 0) player.Position.X = 0; else if (playerMoveX > maxRight) player.Position.X = maxRight; else { foreach (Player p in heroes) { if (p.UniqueID != uniqueID) { if (Overlaps(nextPlayerMoveX, p.SpriteBox) != true) { player.Position.X = playerMoveX; } } } } //Y movement if (playerMoveY < 0) player.Position.Y = 0; else if (playerMoveY > maxDown) player.Position.Y = maxDown; else { foreach (Player p in heroes) { if (p.UniqueID != uniqueID) { if (Overlaps(nextPlayerMoveY, p.SpriteBox) != true) { player.Position.Y = playerMoveY; } } } } } //Score++ public void IncreaseScore() { score++; } //Score-- public void DecreaseScore() { score--; } //Track Damage public void TakeDamage() { hitPoints = Math.Max (hitPoints-1,0); if (hitPoints==0) isDead = true; } //Draw public void Render() { player.Render(); } //Overlap Function private static bool Overlaps(Rectangle r1, Rectangle r2) { if (r1.X+r1.Width <r2.X) return false; if (r1.X> r2.X+r2.Width) return false; if (r1.Y+r1.Height <r2.Y) return false; if (r1.Y> r2.Y+r2.Height) return false; return true; } } } <file_sep>using System; using System.Collections.Generic; using Sce.PlayStation.Core; using Sce.PlayStation.Core.Environment; using Sce.PlayStation.Core.Graphics; using Sce.PlayStation.Core.Input; namespace Lab03 { public class Enemy { private Sprite enemy; private GraphicsContext graphics; private float maxRight, maxDown, positionX, positionY; private int badGuySpeedX = 3, badGuySpeedY = 4, score, randomInt, hitPoints, uniqueID; private bool enemyStart, doAttack, isDead, cleanUp; private string enemyName, location, characterImage; private long attackTimer; //public names. public string PlayerName {get {return enemyName;}} public int Score{get {return score;}} public int HitPoints{get {return hitPoints;}} public string Location{get {return location;}} public string CharacterImage{get {return characterImage;}} public bool DoAttack{get {return doAttack;}} public float X{get {return positionX;}} public float Y{get {return positionY;}} public Rectangle imageBox {get {return new Rectangle(enemy.Position.X, enemy.Position.Y, enemy.Width, enemy.Height);}} // public bool IsHit; public int UniqueID {get {return uniqueID;}} public bool CleanUp {get {return cleanUp;}} public bool IsDead {get {return isDead;}} public Enemy (int uID, string ci, float startPointX, float startPointY, GraphicsContext gc, string en) { graphics = gc; enemyName = en; characterImage = ci; hitPoints = 25; uniqueID = uID; //create and place enemy Texture2D imageEnemy = new Texture2D("/Application/Assets/"+characterImage+".png",false); enemy = new Sprite(graphics, imageEnemy); enemy.Position.X = startPointX - enemy.Width /2; enemy.Position.Y = startPointY - enemy.Height /2; // IsHit = false; enemyStart = false; isDead = false; cleanUp = false; } public void Update(bool anyKey, long timeDelta, int rand) { if (anyKey) enemyStart = true; // Alive? Play. Dead? Fall off the screen. if (isDead) { enemy.Position.Y = Math.Min(enemy.Position.Y + 1, graphics.Screen.Rectangle.Height); if (graphics.Screen.Rectangle.Height == enemy.Position.Y) cleanUp = true; } else HandleMovement(enemyStart); //Update Location information positionX = enemy.Position.X; positionY = enemy.Position.Y; randomInt = rand; attackTimer += timeDelta; Attack(); } private void HandleMovement(bool doMove) { // creating some max movements here. maxRight = graphics.Screen.Rectangle.Width - enemy.Width; maxDown = graphics.Screen.Rectangle.Height - enemy.Height; //Moving the NPCs if(doMove) { if ((enemy.Position.X + badGuySpeedX >maxRight) || (enemy.Position.X + badGuySpeedX <0)) { badGuySpeedX = -badGuySpeedX; } enemy.Position.X += badGuySpeedX; if ((enemy.Position.Y + badGuySpeedY >maxDown) || (enemy.Position.Y + badGuySpeedY <0)) { badGuySpeedY = -badGuySpeedY; } enemy.Position.Y += badGuySpeedY; } } //ScoreKeeper public void IncreaseScore() { score += 1; } public void DecreaseScore() { score -= 1; } public void TakeDamage() { hitPoints = Math.Max (hitPoints-1,0); if (hitPoints==0) isDead = true; } //Keep track of the NPCs public void WhereAmI() { location = "("+positionX+", "+positionY+")"; } public void Attack() { doAttack = false; if (attackTimer > randomInt*1000) { doAttack = true; attackTimer = 0; } } public void Render() { enemy.Render(); } } } <file_sep>using System; using System.Collections.Generic; using Sce.PlayStation.Core; using Sce.PlayStation.Core.Environment; using Sce.PlayStation.Core.Graphics; using Sce.PlayStation.Core.Input; using Sce.PlayStation.HighLevel.UI; namespace Lab03 { /* * ALL New: added HUD to keep track of players and Score. * The HUD takes in the graphics and total player numbers. From this it builds a base with default info. * * OK, This may not be exactly how it reads in specs, but I tried for hours to get this to work by putting the HUD into a list. after LOTS * of research it appears that there can only be 1 scene. I may be wrong, but that is what I found. so instead of making 1 hud and putting it * into a list on AppMain, I decided to make 1 HUD and put a list in the HUD. This way there is 1 scene, with many "objects" on the 1 scene. * * There are two methods for actions that will update the Name and the other will update the Score. */ public class HUD { private List<Label> characterName, characterScore, characterLocation, characterHP; private Label pausedText, ammoText; public HUD (GraphicsContext graphics, int totalPlayerNum) { UISystem.Initialize(graphics); //decarations Scene scene = new Scene(); Label lblName, lblScore, lblLocation, lblHP; characterName = new List<Label>(); characterHP = new List<Label>(); characterScore = new List<Label>(); characterLocation = new List<Label>(); float colorRed = 1, colorGreen = 1, colorBlue = 1; int labelSpacing = graphics.Screen.Rectangle.Width / Math.Max(totalPlayerNum,1); //Loop to create a list of labels. for(int characterNum = 0; characterNum <totalPlayerNum; characterNum++) { if(characterNum == 0) { colorRed = 1; colorGreen = 0; colorBlue = 0; } if(characterNum == 1) { colorRed = 0; colorGreen = 1; colorBlue = 0; } if(characterNum == 2) { colorRed = 0; colorGreen = 0; colorBlue = 1; } if(characterNum == 3) { colorRed = 1; colorGreen = 1; colorBlue = 0; } //Name lblName = new Label(); lblName.X = 0 + labelSpacing * (characterNum); lblName.Y = 10; lblName.Width = graphics.Screen.Rectangle.Width / Math.Max(totalPlayerNum,1); lblName.Text = "Name: "; lblName.TextColor = new UIColor (colorRed, colorGreen, colorBlue, 1); lblName.HorizontalAlignment = HorizontalAlignment.Center; scene.RootWidget.AddChildLast(lblName); characterName.Add(lblName); //HP lblHP = new Label(); lblHP.X = 0 + labelSpacing * (characterNum); lblHP.Y = characterName[characterNum].Y + characterName[characterNum].Height; lblHP.Width = graphics.Screen.Rectangle.Width / Math.Max(totalPlayerNum,1); lblHP.Text = "HP: X"; lblHP.TextColor = new UIColor (colorRed, colorGreen, colorBlue, 1); lblHP.HorizontalAlignment = HorizontalAlignment.Center; scene.RootWidget.AddChildLast(lblHP); characterHP.Add(lblHP); //Score lblScore = new Label(); lblScore.X = 0 + labelSpacing * (characterNum); lblScore.Y = characterHP[characterNum].Y + characterHP[characterNum].Height; lblScore.Width = graphics.Screen.Rectangle.Width / Math.Max(totalPlayerNum,1); lblScore.Text = "Score: 0"; lblScore.TextColor = new UIColor (colorRed, colorGreen, colorBlue, 1); lblScore.HorizontalAlignment = HorizontalAlignment.Center; scene.RootWidget.AddChildLast(lblScore); characterScore.Add(lblScore); // //where am I? (I now can show you where everyone is) // lblLocation = new Label(); // lblLocation.X = 0 + labelSpacing * (characterNum); // lblLocation.Y = characterScore[characterNum].Y + characterScore[characterNum].Height; // lblLocation.Width = graphics.Screen.Rectangle.Width / Math.Max(totalPlayerNum,1); // lblLocation.Text = ""; // lblLocation.TextColor = new UIColor (colorRed, colorGreen, colorBlue, 1); // lblLocation.HorizontalAlignment = HorizontalAlignment.Center; // scene.RootWidget.AddChildLast(lblLocation); // characterLocation.Add(lblLocation); } //where am I? (This is outside the loop because it should only render once.) pausedText = new Label(); pausedText.Width = 600; pausedText.X = graphics.Screen.Rectangle.Width /2 - pausedText.Width /2; pausedText.Y = graphics.Screen.Rectangle.Height /2 - pausedText.Height /2; pausedText.HorizontalAlignment = HorizontalAlignment.Center; pausedText.Text = ""; pausedText.TextColor = new UIColor (1, 0, 0, 1); scene.RootWidget.AddChildLast(pausedText); // //where am I? (This is outside the loop because it should only render once.) // instructionText = new Label(); // instructionText.X = 10; // instructionText.Y = graphics.Screen.Rectangle.Height - instructionText.Height - 10; // instructionText.Width = 800; // instructionText.Text = "Press 'Start' (keyboard X) to show location."; // instructionText.TextColor = new UIColor (1, 1, 1, 1); // scene.RootWidget.AddChildLast(instructionText); // //ammo on the screen count // ammoText = new Label(); // ammoText.X = 10; // ammoText.Y = graphics.Screen.Rectangle.Height - instructionText.Height - 20; // ammoText.Width = 800; // ammoText.Text = "ammo: "; // ammoText.TextColor = new UIColor (1, 1, 1, 1); // scene.RootWidget.AddChildLast(ammoText); //set scene UISystem.SetScene(scene, null); } //Update the character names. public void UpdateNames(string charName, int index) { characterName[index].Text = "Name: "+ charName; } //Update HPs. public void UpdateHitPoints(int hp, int index) { characterHP[index].Text = "HP: "+hp; } //Update the Scores. public void UpdateScoreBoard(int score, int index) { characterScore[index].Text = "Score: "+score; } //Update the locations of the PCs and NPCs public void UpdateLocation(string locationInfo, int index) { characterLocation[index].Text = locationInfo; } public void UpdatePausedText(string input) { pausedText.Text = input; } // //ammo stuff // public void UpdateAmmo(int ammoCount) // { // ammoText.Text = "ammo: "+ ammoCount; // } // //Clean up Location text // public void ClearLocation() // { // foreach (Label l in characterLocation) // l.Text = ""; // instructionText.Text = ""; // } public void Render() { UISystem.Render(); } } } <file_sep>using System; using System.Collections.Generic; using Sce.PlayStation.Core; using Sce.PlayStation.Core.Environment; using Sce.PlayStation.Core.Graphics; using Sce.PlayStation.Core.Input; namespace Lab03 { public class Foreground { private Sprite clouds, clouds2; private GraphicsContext graphics; public Foreground (GraphicsContext gc) { graphics = gc; /* * I am bringing in two pictures of random clouds stacked on top of each other. * I am moving them up at an angle. Once the first box leaves the screen (Both X&Y) it resets. */ Texture2D imageClouds = new Texture2D("/Application/Assets/Clouds Front.png",false); clouds = new Sprite(graphics, imageClouds); clouds.Position.X = 0; clouds.Position.Y = 0; clouds2 = new Sprite(graphics, imageClouds); clouds2.Position.X = 0; clouds2.Position.Y = clouds.Height; } public void Update() { //moving the clouds. clouds.Position.X -= 5; clouds2.Position.X -= 5; clouds.Position.Y -= 0.15f; clouds2.Position.Y -= 0.15f; //Cloud Reset if (clouds.Position.X <= -clouds.Width) { clouds.Position.X = 0; clouds2.Position.X = 0; } if (clouds.Position.Y <= -clouds.Height) { clouds.Position.Y = 0; clouds2.Position.Y = clouds.Height; } } public void Render() { clouds.Render(); clouds2.Render(); } } }
deaaf49fd5b594e7f459aba181112358386d1f7c
[ "Markdown", "C#" ]
8
C#
frostbyte000jm/GameSuperDudes
607eff45ba7ee5edf18bb99def922e3dd4a883a3
571ebf6fba467b5ad29021b352a758b8ddb12a99
refs/heads/master
<file_sep>package namhoai.dev.com.contact.model; import android.provider.BaseColumns; import java.util.List; public class Contact { private long _id; private String displayName; private List<Phone> phones; private List<Email> emails; public long get_id() { return _id; } public void set_id(long _id) { this._id = _id; } public String getDisplayName() { return displayName; } public void setDisplayName(String displayName) { this.displayName = displayName; } public List<Phone> getPhones() { return phones; } public void setPhones(List<Phone> phones) { this.phones = phones; } public List<Email> getEmails() { return emails; } public void setEmails(List<Email> emails) { this.emails = emails; } }
4c851ecba1c9d553911d9cc98f40ee68f8a9c263
[ "Java" ]
1
Java
namhoaidev/ct
da3cf4e4745b7d5f927106d36a88d9d6295a4e15
f43d16775a9106a7aa11db45a995227a5e273246
refs/heads/master
<file_sep>using System; using Foundation; using UIKit; using System.Collections.Generic; using System.Linq; using TrackUrTrailer.Standard; namespace TrackUrTrailer.iOS { public class TUTTableViewDataSource<T> : NSObject, IUITableViewDataSource where T : TUTOrder { private bool registered = false; private IList<T> items; public TUTTableViewDataSource(IList<T> items) { this.items = items; } #region IUITableViewDataSource-Required Methods public UITableViewCell GetCell(UITableView tableView, NSIndexPath indexPath) { //if (!registered) tableView.RegisterClassForCellReuse(typeof(OrderTableCell), "OrderCell"); var item = items[(int)indexPath.Item]; var cell = tableView.DequeueReusableCell("OrderCell", indexPath) as OrderTableCell; cell.UpdateItem(item); return cell; } #endregion public nint RowsInSection(UITableView tableView, nint section) => items?.Count<T>() ?? 0; } } <file_sep>using System; using Newtonsoft.Json; namespace TrackUrTrailer.Standard { public interface ICosmosEntity { [JsonProperty(PropertyName = "id")] string id { get; set; } [JsonProperty("_etag")] string _etag { get; set; } [JsonProperty("_rid")] string _rid { get; set; } [JsonProperty("_self")] string _self { get; set; } } } <file_sep>using System; using SimpleInjector; using System.Runtime.CompilerServices; namespace TrackUrTrailer.Standard { public static partial class Help { public static class Dependencies { private static Container container; private static void EnsureConfigured() { if (container == null) throw new Exception("Dependency container is not configured yet"); } public static void SetContainer(Container container) { Dependencies.container = container; } public static T GetInstance<T>() where T : class { EnsureConfigured(); try { var instance = container.GetInstance<T>(); return instance; } catch (Exception ex) { System.Console.WriteLine(ex.Message); } return null; } } } } <file_sep>using System; using System.Net.Http; using System.Collections; using System.Collections.Generic; using System.Threading.Tasks; using Plugin.Connectivity.Abstractions; using Plugin.Connectivity; using Newtonsoft.Json; namespace TrackUrTrailer.Standard { public class CloudDataStore : IDataStore<TUTOrder> { private HttpClient client; private IEnumerable<TUTOrder> cachedOrders; private bool isConnected => CrossConnectivity.Current.IsConnected; private bool hasCached = false; public CloudDataStore() { client = new HttpClient(); client.BaseAddress = new Uri($"{Help.API.BackEndUrl}"); cachedOrders = new List<TUTOrder>(); } public async Task<bool> AddOrderAsync(TUTOrder item) { //if (!isConnected) return false; throw new NotImplementedException(); } public async Task<bool> DeleteOrderAsync(string id) { //if (!isConnected) return false; throw new NotImplementedException(); } public async Task<TUTOrder> GetOrderAsync(string id) { if (!isConnected || string.IsNullOrEmpty(id)) return null; var json = await client.GetStringAsync($"api/order/{id}"); return await Task.Run(() => JsonConvert.DeserializeObject<TUTOrder>(json)); } public async Task<IEnumerable<TUTOrder>> GetOrdersAsync(bool forceRefresh = false) { if (isConnected && forceRefresh && !hasCached) { var json = await client.GetStringAsync($"api/orders"); cachedOrders = await Task.Run(() => JsonConvert.DeserializeObject<IEnumerable<TUTOrder>>(json)); hasCached = true; } return cachedOrders; } public async Task<bool> UpdateOrderAsync(TUTOrder item) { //if (!isConnected) return false; throw new NotImplementedException(); } public IEnumerable<TUTOrder> GetCachedOrders() => cachedOrders; } } <file_sep>using System; using SimpleInjector; using TrackUrTrailer.Standard; namespace TrackUrTrailer.iOS { public static class DependencyRegistrar { internal static Container IOSContainer() { var dependencyContainer = new Container(); dependencyContainer.Register<IMapAnnotation, TUTMapAnnotation>(Lifestyle.Singleton); return dependencyContainer; } } }<file_sep>using System; namespace TrackUrTrailer.Standard { public enum UserRole { Customer, Driver, Operations, Corporate } } <file_sep>using System; using SimpleInjector; namespace TrackUrTrailer.Standard { public static partial class Help { public static class StartUp { public static void InitializeWithDependencies(Container dependencyContainer) { dependencyContainer.Register<IDataStore<TUTOrder>, CloudDataStore>(); Help.Dependencies.SetContainer(dependencyContainer); } } } } <file_sep>//Quicktype.io-generated using System; using System.Net; using System.Collections.Generic; using Newtonsoft.Json; namespace TrackUrTrailer.Standard { public partial class TUTOrder { [JsonProperty("ID")] public long Id { get; set; } [JsonProperty("Status")] public string Status { get; set; } [JsonProperty("Product")] public string Product { get; set; } [JsonProperty("Quantity")] public long Quantity { get; set; } [JsonProperty("ScheduledDeliveryDate")] public System.DateTime ScheduledDeliveryDate { get; set; } [JsonProperty("DeliveryAddress")] public DeliveryAddress DeliveryAddress { get; set; } [JsonProperty("DeliveryVehicle")] public DeliveryVehicle DeliveryVehicle { get; set; } } public partial class DeliveryAddress { [JsonProperty("Line1")] public string Line1 { get; set; } [JsonProperty("City")] public string City { get; set; } [JsonProperty("State")] public string State { get; set; } [JsonProperty("Zipcode")] public string Zipcode { get; set; } } public partial class DeliveryVehicle { [JsonProperty("CurrentLocation")] public CurrentLocation CurrentLocation { get; set; } } public partial class CurrentLocation { [JsonProperty("Latitude")] public double Latitude { get; set; } [JsonProperty("Longitude")] public double Longitude { get; set; } } public partial class TUTOrder { public static TUTOrder FromJson(string json) => JsonConvert.DeserializeObject<TUTOrder>(json, Converter.Settings); } public static class Serialize { public static string ToJson(this TUTOrder self) => JsonConvert.SerializeObject(self, Converter.Settings); } public class Converter { public static readonly JsonSerializerSettings Settings = new JsonSerializerSettings { MetadataPropertyHandling = MetadataPropertyHandling.Ignore, DateParseHandling = DateParseHandling.None, }; } } <file_sep>using System; namespace TrackUrTrailer.Standard { public static partial class Extensions { } } <file_sep>using System; namespace TrackUrTrailer.Standard { public static partial class Help { public static class API { public const string BackEndUrl = "https://gbbmobileiot.azurewebsites.net/"; } } } <file_sep>using CoreLocation; using MapKit; using TrackUrTrailer.Standard; using System.Threading.Tasks; using System.Linq; namespace TrackUrTrailer.iOS { public class TUTMapAnnotation : MKAnnotation, IMapAnnotation { private CLLocationCoordinate2D _coordinate; private string _title; private string _subtitle; #region MKAnnotation Requirements public override CLLocationCoordinate2D Coordinate => _coordinate; public override void SetCoordinate(CLLocationCoordinate2D value) => _coordinate = value; public override string Title => _title; public override string Subtitle => _subtitle; #endregion #region Constructors public TUTMapAnnotation() { } public void FromVehicle(DeliveryVehicle vehicle) { _coordinate = new CLLocationCoordinate2D(vehicle.CurrentLocation.Latitude, vehicle.CurrentLocation.Longitude); _title = "Vehicle"; } public async Task FromLocation(DeliveryAddress address) { //geocode address string var geocoder = new CLGeocoder(); var placemark = await geocoder.GeocodeAddressAsync($"{address.Line1}, {address.City}, {address.State}"); if (placemark.FirstOrDefault() is CLPlacemark topResult) { _coordinate = topResult.Location.Coordinate; _title = "Delivery"; _subtitle = $"{address}"; } } #endregion } } <file_sep>using System; using System.Collections.Generic; using System.Threading.Tasks; namespace TrackUrTrailer.Standard { public interface IDataStore<T> { Task<bool> AddOrderAsync(T item); Task<bool> UpdateOrderAsync(T item); Task<bool> DeleteOrderAsync(string id); Task<T> GetOrderAsync(string id); IEnumerable<T> GetCachedOrders(); Task<IEnumerable<T>> GetOrdersAsync(bool forceRefresh = false); } } <file_sep>using System; using System.Threading.Tasks; using System.Collections.ObjectModel; using System.Linq; using Microsoft.AppCenter.Analytics; namespace TrackUrTrailer.Standard { public class MapViewModel : BaseViewModel { IDataStore<TUTOrder> dataStore; public (double longitude, double lattidue) CenteringCoordinates { get { if (dataStore?.GetCachedOrders().FirstOrDefault() is TUTOrder order) { return (order.DeliveryVehicle.CurrentLocation.Latitude, order.DeliveryVehicle.CurrentLocation.Longitude); } else return (0, 0); } } public ObservableCollection<IMapAnnotation> Annotations = new ObservableCollection<IMapAnnotation>(); public MapViewModel() { dataStore = Help.Dependencies.GetInstance<IDataStore<TUTOrder>>(); ConfigureDataStore(); } public async Task GetData() { Analytics.TrackEvent("MapDataRequested"); await dataStore.GetOrdersAsync(); await CreateAnnotations(); } private void ConfigureDataStore() { if (Help.Dependencies.GetInstance<IDataStore<TUTOrder>>() is IDataStore<TUTOrder> data) { this.dataStore = data; } else throw new Exception("Failure: IDataStore<TUTOrder> not registered at time of MapVM construction"); } private async Task CreateAnnotations() { var orders = await dataStore.GetOrdersAsync(true); foreach (var order in orders) { var annotation = Help.Dependencies.GetInstance<IMapAnnotation>(); await annotation.FromLocation(order.DeliveryAddress); Annotations.Add(annotation); } //add one delivery vehicle annotation, from the first order. for test purposes. will fix api later //var vehicleAnnotation = Help.Dependencies.GetInstance<IMapAnnotation>(); //vehicleAnnotation.FromVehicle(orders.FirstOrDefault().DeliveryVehicle); //Annotations.Add(vehicleAnnotation); } } }<file_sep>using System; using System.Runtime.CompilerServices; namespace TrackUrTrailer.Standard { public enum Module { DeliveryList, Orders, Map, } public static partial class Extensions { public static string StoryBoardId(this Module module) { switch (module) { case Module.DeliveryList: return "deliveryListVC"; case Module.Map: return "mapVC"; case Module.Orders: return "ordersVC"; default: return ""; } } public static string Name(this Module module) { switch (module) { case Module.Map: return "Map"; case Module.Orders: return "Orders"; case Module.DeliveryList: default: return ""; } } } } <file_sep>using System; using System.Threading.Tasks; namespace TrackUrTrailer.Standard { public interface IMapAnnotation { void FromVehicle(DeliveryVehicle title); Task FromLocation(DeliveryAddress address); } } <file_sep>using System; namespace TrackUrTrailer.Standard { public class TUTModel : ICosmosEntity { #region ICosmosEntity Requirements public string id { get; set; } public string _etag { get; set; } public string _rid { get; set; } public string _self { get; set; } #endregion public TUTModel() { } } } <file_sep>using System; namespace TrackUrTrailer.Standard { public static class Users { private static UserRole _activeRole = UserRole.Driver; public static UserRole ActiveRole { get => _activeRole; private set => _activeRole = value; } public static void LogUserIn(UserRole role) { ActiveRole = role; } } }
47b1b3ac1d8d5a07d929cd5d6a5126744c58c22f
[ "C#" ]
17
C#
NickSpag/TrackUrTrailer
8f21eeacdc4d7b7f87e5e29ee5dd7b3a9ecbc7c8
095b8968096e57fc1abe26793c8400a71d79b82d
refs/heads/main
<file_sep>import {useState} from 'react'; const useGlobalState = () => { const } export default useGlobalState;<file_sep> This project was bootstrapped with [Create React App](https://github.com/facebook/create-react-app). # Mobalytics Clone In this project my goal is first create a static version of the mobalytics ui. Further on I will also try to use the riot api to mimick some of the features for the ui.
81433776ffdaa25c7b05735db16e0ee455f87ee0
[ "JavaScript", "Markdown" ]
2
JavaScript
ArizonaMangoJuice/mobalytics-clone
4883e528571e3056d4e8f1d220d4506f15ed03a6
dea69e7ffc93a2250963c754cb51598ecca793a3
refs/heads/master
<file_sep><?php /** * Description of LoginSSOAction * * @author Arba */ class LoginSSOAction extends CAction { public $simplesamlphpComponentName = ''; public $redirectAfterLoginTo = ''; public function init() { parent::init(); } public function run() { $this->setRootPathOfAlias(); $this->loadRequiredClass(); $this->getSimplesamlphpInstance()->requireAuth(); $userIdentity = new SSOUserIdentity($this->getSimplesamlphpInstance()->email, ''); Yii::app()->user->login($userIdentity); $this->getController()->redirect($this->redirectAfterLoginTo); } private function setRootPathOfAlias() { if (Yii::getPathOfAlias('yii-simplesamlphp') === false) { Yii::setPathOfAlias('yii-simplesamlphp', realpath(dirname(__FILE__) . '/..')); } } private function loadRequiredClass() { Yii::import('yii-simplesamlphp.components.SSOUserIdentity'); } private function getSimplesamlphpInstance() { $temp = $this->simplesamlphpComponentName; return Yii::app()->$temp; } } <file_sep><?php class SSOWebUser extends CWebUser { public $simplesamlphpComponentName = ''; public function init() { parent::init(); } private function getSimplesamlphpInstance() { $temp = $this->simplesamlphpComponentName; return Yii::app()->$temp; } public function getId() { return $this->getSimplesamlphpInstance()->username; } public function getName() { return $this->getSimplesamlphpInstance()->username; } public function getIsGuest() { return !$this->getSimplesamlphpInstance()->isAuthenticated(); } } <file_sep><?php /** * Description of LevelFilter * * @author Arba */ class LevelFilter extends CFilter { public $allowedLevels = null; public $simplesamlphpComponentName = null; protected function preFilter($filterChain) { $result = false; if (!empty(array_intersect($this->allowedLevels, $this->getSimplesamlphp()->level))) { $result = true; } return $result; } private function getSimplesamlphp() { $temp = $this->simplesamlphpComponentName; return Yii::app()->$temp; } } <file_sep><?php class Simplesamlphp extends CApplicationComponent { public $autoloadPath; public $authSource; private $authSimple; private $attributes; private static $data; public function init() { $this->loadSimplesamlPhp(); $this->authSimple = new \SimpleSAML_Auth_Simple($this->authSource); $this->attributes = $this->authSimple->getAttributes(); parent::init(); } public function loadSimplesamlPhp() { require_once($this->autoloadPath); YiiBase::registerAutoloader('SimpleSAML_autoload', true); } public function requireAuth() { $this->authSimple->requireAuth(); } public function login(array $params = array()) { $this->authSimple->login($params); } public function logout() { $this->authSimple->logout(); } public function getLoginURL($returnTo = null) { $this->authSimple->getLogoutUrl($returnTo); } public function getLogoutURL($returnTo = null) { $this->authSimple->getLogoutUrl($returnTo); } public function getAttributes() { return $this->attributes; } public function isAuthenticated() { return $this->authSimple->isAuthenticated(); } public function __get($name) { return $this->getData($name); } private function getData($name) { if (!isset($this->attributes['data'])) { return null; } if (!self::$data) { self::$data = json_decode($this->attributes['data'][0]); } return self::$data->$name; } } <file_sep>Yii Simplesamlphp ----------------- ###1. Installation Register `components/Simplesaml.php` as a component. It needs 2 arguments, `autoloadPath` where your simplesamlphp sp's `lib/_autoloadphp` is and `authSource` the authentication source that you will use on your `config/authsources.php` ```php 'simplesamlphp' => array( 'class' => 'ext.yii-simplesamlphp.components.Simplesamlphp', 'autoloadPath' => '../lib/_autoload.php', 'authSource' => 'default-sp', ), ``` ###2. Usage - Using [simplesamlphp sp's api](https://simplesamlphp.org/docs/stable/simplesamlphp-sp-api) Now you can use the api simply by call `Yii::app()->componentName->method_name()`. - Login and logout action You can use our `LoginSSOAction` and `LogoutSSOAction` to login and logout your application with Simplesamlphp. All you need to do is create method `actions` on your controller and add `LoginSSOAction` and `LogoutSSOAction` to your action. ```php 'login' => array( 'class' => 'ext.yii-simplesamlphp.actions.LoginSSOAction', 'simplesamlphpComponentName' => 'simplesamlphp', 'redirectAfterLoginTo' => '/', ), 'logout' => array( 'class' => 'ext.yii-simplesamlphp.actions.LogoutSSOAction', 'simplesamlphpComponentName' => 'simplesamlphp', 'redirectAfterLogoutTo' => '/', ), ``` You need to specify `simplesamlphpComponentName` with your component name which you register `components/Simplesamlphp.php` and `redirectAfterLogin` and `redirectAfterLogout` with a route where you want to be redirected after login / logout. <file_sep><?php /** * Description of LogoutSSOAction * * @author Arba */ class LogoutSSOAction extends CAction { public $simplesamlphpComponentName = ''; public $redirectAfterLogoutTo = ''; public function init() { parent::init(); } public function run() { $this->setRootPathOfAlias(); if ($this->getSimplesamlphpInstance()->isAuthenticated()) { $this->getSimplesamlphpInstance()->logout(); } Yii::app()->user->logout(true); $this->getController()->redirect($this->redirectAfterLogoutTo); } private function setRootPathOfAlias() { if (Yii::getPathOfAlias('yii-simplesamlphp') === false) { Yii::setPathOfAlias('yii-simplesamlphp', realpath(dirname(__FILE__) . '/..')); } } private function getSimplesamlphpInstance() { $temp = $this->simplesamlphpComponentName; return Yii::app()->$temp; } }
ca9ff29104698f9fcceeb36f9f8a52ecc92ba4f0
[ "Markdown", "PHP" ]
6
PHP
sffej/yii-simplesamlphp
dcc9261f312497f097de7d20c3fb5aad646224ff
0568dff4743c49373daa717f0fa95085eb920052
refs/heads/master
<repo_name>bgreenaw/IntroRRStudio<file_sep>/workshopFresh.Rmd --- title: "RMarkdown Demonstration" output: html_document --- ```{r setup, include=FALSE} knitr::opts_chunk$set(echo = FALSE, warning = FALSE, message = FALSE, error = FALSE, fig.width = 10) ``` ## Intital Package Installations First, you will need to install some packages: ```{r, eval = FALSE} packs = c("tidyverse", "data.table", "DT", "plotly", "ggplot2", "corrplot", "stargazer", "knitr", "rmarkdown") install.packages(packs) ``` You will only need to install them once, so do not worry about running this after you do it the first time. ## Our Data We are going to make it easy on ourselves and use some of the data that R has built into it. We are going use the "diamonds" data from the ggplot2 package. ```{r} library(ggplot2) ``` ## Data Exploration Data exploration is an important part of the statistical programming process. We can start by taking a peak at our actual data. This could also be helpful for people who may want to take a look at our document. ```{r} DT::datatable(diamonds) ``` We often like to take an initial look at the correlations within our data. This can be most enlightening, but dealing with a massive correlation matrix can be a hassle. Instead, we can go the visual route. Before we produce our visualization, we need to do a little data work. The diamonds data contains a few variables that would need some work before being thrown into a correlation matrix. We will, instead, just work with the purely numeric variables. ```{r} library(dplyr); library(corrplot) diamonds %>% select(price, carat, depth, table, x, y, z) %>% cor() %>% corrplot.mixed() ``` ## Data Visualization ### Static Often times, we might just want a nice static visualization. Static, however, does not mean simple. R gives us the ability to create layers within our visualizations. Likely the most popular package for static visualizations is ggplot2. ```{r} library(ggplot2) p = ggplot(diamonds, aes(carat, price, color = cut)) + geom_point(alpha = .5) + geom_smooth(se = FALSE) + facet_wrap(~ color) + theme_minimal() p ``` ### Interactive There are a wide variety of packages designed for interactive visualizations in R. We already saw a few of the htmlwidget packages in use. Since we already have a ggplot created, we can just throw it to the ggplotly function from the plotly package. ```{r} library(plotly) ggplotly(p) ``` ## Results We can do a lot of different things with our results. For example, we might want some of our results to actually be within our text -- there exists a significant relationship between carats and price (*r* = `r round(cor(diamonds$carat, diamonds$price), 2)`). We might want to include some more expanded results. The following is our standard regression output, but in a nice interactive table: ```{r} testLM = lm(price ~ carat, data = diamonds) DT::datatable(broom::tidy(testLM)) ``` We might also want some model comparisons: ```{r, results = "asis"} testLM2 = lm(price ~ carat + depth, data = diamonds) stargazer::stargazer(testLM, testLM2, type = "html", header = FALSE) ``` <file_sep>/practice.R ####################### ### Section 1 ### ####################### # 3 ways to create the same object numList1 = c(1, 2, 3, 4, 5) numList2 = 1:5 numList3 = seq(from = 1, to=5, by=1) # See output of each numList1 numList2 numList3 # Compare numList1 and numList2 numList1 == numList2 # see how list multiplication works numList1[1:3] * 5 numList1[1:3] * numList2[1:3] numList1[1:3] * numList2[1:2] ### Create a object with values 1 to 10 and 50 to 75 numlist = ################################# ### Section 2 ### ################################# mtcars View(mtcars) mtcars$mpg mtcars[1, ] mtcars[, 1] mtcars[1, 1] ### Modify code below to Show the first 10 Rows and the first 5 Columns mtcars[] ####################################### ### Section 3 ### ####################################### mtcars[mtcars$cyl == 6 | mtcars$cyl == 8 & mtcars$hp >= 146,] mtcars[(mtcars$cyl == 6 | mtcars$cyl == 8) & mtcars$hp >= 146,] mtcars[mtcars$cyl == 6 | (mtcars$cyl == 8 & mtcars$hp >= 146),] ###Select only 6 cyl with greater than 140hp or 8 cyl with less than 200hp. mtcars[] ############################# ### Section 4 ### ############################# cor(mtcars$mpg, mtcars$wt) lm(mpg ~ wt, data = mtcars) plot(mtcars$wt, mtcars$mpg, pch = 19) #Add a comma and press tab to see other function options plot(mtcars$wt, mtcars$mpg, pch = 19, sub = "Text for your sub title") #Add a sub title to you plot plot(mtcars$wt, mtcars$mpg, pch = 19) lines(lowess(mtcars$wt, mtcars$mpg), col = "#FF6600", lwd = 2) abline(lm(mpg ~ wt, data = mtcars), col = "#0099ff", lwd = 2) ### Add a legend parameter to remove the border plot(mtcars$wt, mtcars$mpg, pch = 19) lines(lowess(mtcars$wt, mtcars$mpg), col = "#FF6600", lwd = 2) abline(lm(mpg ~ wt, data = mtcars), col = "#0099ff", lwd = 2) legend(x = 4, y = 30, legend = c("Lowess", 'LM'), lwd = c(2,2), col = c("#FF6600", "#0099ff")) ###################### ### TidyVerse ### ###################### install.packages("dplyr"); install.packages("tidyr") library(dplyr); library(tidyr) #################################### ### Section 5 ### #################################### newData = mtcars[, 1:4] newData = mtcars[, c('mpg','cyl', 'disp', 'hp')] newData_dplyr = mtcars %>% select(mpg:hp) ### Compare Results newData == newData_dplyr #################################### ### Section 6 ### #################################### x = c(1, 2, NA, NA, 5, 6, NA, 8, NA, NA) y = c(NA, NA, 3, 4, NA, NA, NA, NA, NA, NA) z = c(NA, NA, NA, NA, NA, NA, 7, NA, 9, 10 ) coalesce(x, y, z) ### (Reorder (x, y, z) below to see what happens x = c(1, 2, NA, NA, 5, 6, NA, 8, 4, NA) y = c(NA, 4, 3, 4, NA, 8, NA, NA, NA, NA) z = c(3, NA, 8, NA, 1, NA, 7, NA, 9, 10 ) coalesce(x, y, z)
5937e7914578cd99771a58c3a84a7b9a390161e5
[ "R", "RMarkdown" ]
2
RMarkdown
bgreenaw/IntroRRStudio
472ac64af3fd3446555f8945c54737d0d4b14a82
49c0f22f46b72c0b1032f3b2ffb2fb5a67361514
refs/heads/master
<file_sep>package com.elpsy.api.gateway.zuul; import org.junit.jupiter.api.Test; import org.springframework.boot.test.context.SpringBootTest; @SpringBootTest class ZuulRibbonDemoApplicationTests { @Test void contextLoads() { } } <file_sep># zuul-ribbon-demo
0922bef7c0b93b5c7e1d31b9581ed17eb0377bc8
[ "Markdown", "Java" ]
2
Java
kencrisjohn/zuul-ribbon-demo
de5f1d66aa759fa8b819ae641485493e63e4d9dc
c93b5dba3fc2ea3bc938ba780c85ffd94bb2c1a0
refs/heads/master
<file_sep># task_rotation A project to learn rust <file_sep>use std::collections::HashMap; // Task Assigments #[derive(Debug)] pub struct Member { name: Person, assigned_group: Option<usize>, } // Task #[derive(Debug, Clone)] pub struct Task { name: String, details: String, } // Group pub struct Group { pub name: String, members: Option<Members>, tasks: Option<Tasks>, task_groups: Option<TaskGroups>, } type Person = String; type Members = Vec<Member>; type TaskAssignments = HashMap<Person, Option<Tasks>>; type Tasks = Vec<Task>; type TaskGroups = Vec<Tasks>; impl Group { pub fn new(group_name: &str) -> Self { Group { name: String::from(group_name), members: None, tasks: None, task_groups: None, } } pub fn add_member(&mut self, member: Person) { let new_memeber = Member { name: member, assigned_group: None, }; match self.members { Some(ref mut v) => v.push(new_memeber), None => self.members = Some(vec![new_memeber]), }; if self.tasks.is_some() { self.set_up() } } pub fn add_task(&mut self, task: Task) { match self.tasks { Some(ref mut t) => t.push(task), None => self.tasks = Some(vec![task]), }; if self.members.is_some() { self.set_up() } } fn set_up(&mut self) { let task_count = count_option_vec(&self.tasks); let member_count = count_option_vec(&self.members); let more_tasks_than_members = task_count >= member_count; // Reset task groups self.task_groups = None; // GROUP HAS MORE TASKS THAN PEOPLE if more_tasks_than_members { let can_be_evenly_divided = task_count % member_count == 0; if can_be_evenly_divided { let groups_of = task_count / member_count; let tasks = self .tasks .as_ref() .map(|tasks| tasks.chunks(groups_of)) .unwrap(); for chunck in tasks { match self.task_groups { Some(ref mut group) => group.push(chunck.to_vec()), None => self.task_groups = Some(vec![chunck.to_vec()]), }; } assign_task_groups(self) } else { let groups_of = task_count / member_count; let (task_for_each, task_remaining) = self .tasks .as_ref() .map(|tasks| tasks.split_at(task_count - (task_count % member_count))) .unwrap(); let mut task_chunks = task_for_each.chunks_exact(groups_of); for chunck in task_chunks.by_ref() { match self.task_groups { Some(ref mut group) => group.push(chunck.to_vec()), None => self.task_groups = Some(vec![chunck.to_vec()]), }; } for (count, task) in task_remaining.iter().cloned().enumerate() { self .task_groups .as_mut() .map(|group| group[count].push(task)); } assign_task_groups(self); } } else { // GROUP HAS LESS TASKS THAN PEOPLE for task in self.tasks.clone().unwrap() { match self.task_groups { Some(ref mut group) => group.push(vec![task]), None => self.task_groups = Some(vec![vec![task]]), } } assign_task_groups(self) } } pub fn rotate_tasks(&mut self) -> Result<(), &str> { let has_tasks_and_members = self.tasks.is_some() && self.members.is_some(); if has_tasks_and_members { let members = self.members.as_ref().map(|members| members.iter()).unwrap(); let mut assingments: Vec<Option<usize>> = members.map(|member| member.assigned_group).collect(); assingments.rotate_left(1); // Assignment members new assignments for (pos, group_number) in assingments.iter().enumerate() { match self.members { Some(ref mut members) => members[pos].assigned_group = *group_number, None => {} } } Ok(()) } else { Err("No tasks or members added") } } pub fn get_task_assignments(&self) -> Result<TaskAssignments, &str> { let has_tasks_and_members = self.task_groups.is_some() && self.members.is_some(); if has_tasks_and_members { let mut task_assignments: TaskAssignments = HashMap::new(); let members = self.members.as_ref().map(|members| members.iter()).unwrap(); for member in members { let name = member.name.clone(); let task_group = self .task_groups .as_ref() .map(|task_groups| match member.assigned_group { Some(group_pos) => Some(task_groups[group_pos].clone()), None => None, }) .unwrap(); task_assignments.insert(name, task_group); } Ok(task_assignments) } else { Err("No tasks or members added") } } } fn count_option_vec<T>(collection: &Option<Vec<T>>) -> usize { collection .as_ref() .map(|collection| collection.len()) .unwrap() } fn assign_task_groups(group: &mut Group) { for group_position in 0..count_option_vec(&group.task_groups) { match group.members { Some(ref mut mem) => mem[group_position].assigned_group = Some(group_position), None => {} } } } pub fn create_tasks(n: usize) -> Tasks { let mut tasks = Vec::new(); for num in 1..n + 1 { tasks.push(Task { name: format!("task {}", num).to_string(), details: format!("Do not forget to do task: {} it in the morning", num).to_string(), }) } tasks } pub fn create_members(n: usize) -> Vec<Person> { let mut members = Vec::new(); for num in 1..n + 1 { members.push(format!("Member {}", num)) } members } #[cfg(test)] mod tests { use super::*; #[test] fn should_add_member_to_group() { let mut group = Group::new("Doing_team"); for person in create_members(2) { group.add_member(person) } assert_eq!(group.members.unwrap()[1].name, "Member 2".to_string()); } #[test] fn should_add_task_to_group() { let mut group = Group::new("Doing_team"); for task in create_tasks(2) { group.add_task(task) } assert_eq!(group.tasks.unwrap()[0].name, "task 1".to_string()) } #[test] fn should_setup_group_with_more_tasks_than_members_that_is_evenly_divisible() { let mut evenly_divisible_group = Group::new("Evenly Group"); for task in create_tasks(6) { evenly_divisible_group.add_task(task) } for person in create_members(3) { evenly_divisible_group.add_member(person) } let compare: usize = 3; let length = evenly_divisible_group .task_groups .as_ref() .map(|group| group.len()) .unwrap(); assert_eq!(length, compare); let members = evenly_divisible_group.members.as_ref().unwrap(); assert_eq!(members[2].assigned_group.unwrap(), 2); } #[test] fn should_setup_group_with_more_tasks_than_members_that_is_unevenly_divisible_which_results_to_one( ) { let mut unevenly_divisible_group = Group::new("UnEven Group"); for task in create_tasks(6) { unevenly_divisible_group.add_task(task) } for person in create_members(4) { unevenly_divisible_group.add_member(person) } let compare: usize = 2; let first_group_length = unevenly_divisible_group .task_groups .as_ref() .map(|groups| groups[0].len()) .unwrap(); assert_eq!(first_group_length, compare); let members = unevenly_divisible_group.members.as_ref().unwrap(); assert_eq!(members[0].assigned_group.unwrap(), 0) } #[test] fn should_setup_group_with_more_tasks_than_members_that_is_unevenly_divisible_which_results_to_more_than_one( ) { let mut unevenly_divisible_group = Group::new("UnEven Group"); for task in create_tasks(15) { unevenly_divisible_group.add_task(task) } for person in create_members(4) { unevenly_divisible_group.add_member(person) } let compare: usize = 4; let first_group_length = unevenly_divisible_group .task_groups .as_ref() .map(|groups| groups[0].len()) .unwrap(); assert_eq!(first_group_length, compare); let members = unevenly_divisible_group.members.as_ref().unwrap(); assert_eq!(members[0].assigned_group.unwrap(), 0) } #[test] fn should_setup_group_with_less_tasks_than_memebers() { let mut group_with_less_tasks = Group::new("More tasks group"); for task in create_tasks(3) { group_with_less_tasks.add_task(task) } for person in create_members(4) { group_with_less_tasks.add_member(person) } let members = group_with_less_tasks.members.as_ref().unwrap(); assert_eq!(members[2].assigned_group.unwrap(), 2); assert_eq!(members[3].assigned_group.is_none(), true); } #[test] fn should_rest_task_assignment_and_task_groups() { let mut group = Group::new("Group update"); // 6 and 3 = 2 task each for task in create_tasks(6) { group.add_task(task) } for person in create_members(3) { group.add_member(person) } // 6 and 4 = 1 task each with two task groups having two group.add_member("Member 4".to_string()); let task_groups = group.task_groups.unwrap(); assert_eq!(task_groups[0].len(), 2); assert_eq!(task_groups[2].len(), 1); } #[test] fn should_rotate_task_assignments() { let mut group = Group::new("Group update"); for task in create_tasks(6) { group.add_task(task) } for person in create_members(3) { group.add_member(person) } group.rotate_tasks().unwrap(); let members = group.members.unwrap(); assert_eq!(members[0].assigned_group, Some(1)) } #[test] fn should_not_rotate_tasks_with_no_members_or_tasks() { let mut empty_group = Group::new("Empty Group"); assert_eq!(empty_group.rotate_tasks().is_err(), true); } #[test] fn should_create_task_assignment() {} }
021337ca7c532093e49c0ae25b156fbca3e6cd2b
[ "Markdown", "Rust" ]
2
Markdown
gideonflash/task_rotation
16eeaef2e888b4ea29883b4598afed94a88f0545
feff77439c006a034066476d8522b56f48b6bfac
refs/heads/master
<file_sep>//////////////////////////////////////////////////// //<NAME> //hw01 //Welcome Class Java Program // // first compile the prgram // javac WelcomeClass.java // run the prgram // java WelcomeClass //define a class public class WelcomeClass { //add main method public static void main(String[] args){ // print the statement System.out.println("-----------"); System.out.println("| WELCOME |"); System.out.println("-----------"); System.out.println(" ^ ^ ^ ^ ^ ^ "); System.out.println("/ \\/ \\/ \\/ \\/ \\/\\ "); System.out.println("<-K--J--S--2--1--5->"); System.out.println("\\ /\\ /\\ /\\ /\\ /\\ /"); System.out.println(" v V V V V v"); System.out.println("This spring break I will be going to Cancun, Mexico"); } } <file_sep>////////////////////////////////////////////////////////// //<NAME> //CSE 2 //hw03-FourDigits Java Program //import scanner class import java.util.Scanner; // public class FourDigits{ public static void main(String [] args) { Scanner myScanner; myScanner=new Scanner (System.in); //Enter a double System.out.println("enter a double:"); double number = myScanner.nextDouble(); //Print four digits to the right of decimal point double number2 = number*10000; double number3 = number2 % 10000; System.out.printf("%.0f \n", number3); } }<file_sep>///////////////////////////////////////////////////////////// //<NAME> //CSE 2 //hw04-Which Number Java Program // import java.util.Scanner; public class WhichNumber { public static void main(String[] args) { String input = ""; Scanner myScanner = new Scanner(System.in); System.out.println("Think of a number between 1 and 10 inclusive"); System.out.println("Is the number even?"); input = myScanner.next(); if (input.equals("Y") || input.equals("y")) { System.out.println("Is it divisible by 3?"); input = myScanner.next(); if (input.equals("Y") || input.equals("y")) { System.out.println("Is your number 6"); input = myScanner.next(); if (input.equals("Y") || input.equals("y")) System.out.println("Yay!"); else if (input.equals("N") || input.equals("n")) System.out.println("Boo"); else{ System.out.println("Error: Invalid input. Terminating Program."); System.exit(0);} } else if (input.equals("N") || input.equals("n")) { System.out.println("Is it divisible by 4?"); input = myScanner.next(); if (input.equals("Y") || input.equals("y")) { System.out.println("Is the number divided by 4 greater than 1?"); input = myScanner.next(); if (input.equals("Y") || input.equals("y")) { System.out.println("Is your number 8"); input = myScanner.next(); if (input.equals("Y") || input.equals("y")) System.out.println("Yay!"); else if (input.equals("N") || input.equals("n")) System.out.println("Boo"); else{ System.out.println("Error: Invalid input. Terminating Program."); System.exit(0);} } else if (input.equals("N") || input.equals("n")) { System.out.println("Is your number 4"); input = myScanner.next(); if (input.equals("Y") || input.equals("y")) System.out.println("Yay!"); else if (input.equals("N") || input.equals("n")) System.out.println("Boo"); else{ System.out.println("Error: Invalid input. Terminating Program."); System.exit(0);} } } else if (input.equals("N") || input.equals("n")) { System.out.println("Is the number divisible by 5?"); input = myScanner.next(); if (input.equals("Y") || input.equals("y")) { System.out.println("Is your number 10"); input = myScanner.next(); if (input.equals("Y") || input.equals("y")) System.out.println("Yay!"); else if (input.equals("N") || input.equals("n")) System.out.println("Boo"); else{ System.out.println("Error: Invalid input. Terminating Program."); System.exit(0);} } else if (input.equals("N") || input.equals("n")) { System.out.println("Is your number 2"); input = myScanner.next(); if (input.equals("Y") || input.equals("y")) System.out.println("Yay!"); else if (input.equals("N") || input.equals("n")) System.out.println("Boo"); else{ System.out.println("Error: Invalid input. Terminating Program."); System.exit(0);} } else{ System.out.println("Error: Invalid input. Terminating Program."); System.exit(0);} } else{ System.out.println("Error: Invalid input. Terminating Program."); System.exit(0);} } else{ System.out.println("Error: Invalid input. Terminating Program."); System.exit(0);} } else if (input.equals("N") || input.equals("n")) { System.out.println("Is it divisble by 3?"); input = myScanner.next(); if (input.equals("Y") || input.equals("y")) { System.out.println("When divided by 3 is the result greater than 1?"); input = myScanner.next(); if (input.equals("Y") || input.equals("y")) { System.out.println("Is your number 9"); input = myScanner.next(); if (input.equals("Y") || input.equals("y")) System.out.println("Yay!"); else if (input.equals("N") || input.equals("n")) System.out.println("Boo"); else{ System.out.println("Error: Invalid input. Terminating Program."); System.exit(0);} } else if (input.equals("N") || input.equals("n")) { System.out.println("Is your number 3"); input = myScanner.next(); if (input.equals("Y") || input.equals("y")) System.out.println("Yay!"); else if (input.equals("N") || input.equals("n")) System.out.println("Boo"); else{ System.out.println("Error: Invalid input. Terminating Program."); System.exit(0);} } } else if (input.equals("N") || input.equals("n")) { System.out.println("Is it greater than 6?"); input = myScanner.next(); if (input.equals("Y") || input.equals("y")) { System.out.println("Is your number 7"); input = myScanner.next(); if (input.equals("Y") || input.equals("y")) System.out.println("Yay!"); else if (input.equals("N") || input.equals("n")) System.out.println("Boo"); else{ System.out.println("Error: Invalid input. Terminating Program."); System.exit(0);} } else if (input.equals("N") || input.equals("n")) { System.out.println("Is it less than 3?"); input = myScanner.next(); if (input.equals("Y") || input.equals("y")) { System.out.println("Is your number 1"); input = myScanner.next(); if (input.equals("Y") || input.equals("y")) System.out.println("Yay!"); else if (input.equals("N") || input.equals("n")) System.out.println("Boo"); else{ System.out.println("Error: Invalid input. Terminating Program."); System.exit(0);} } else if (input.equals("N") || input.equals("n")) { System.out.println("Is your number 5"); input = myScanner.next(); if (input.equals("Y") || input.equals("y")) System.out.println("Yay!"); else if (input.equals("N") || input.equals("n")) System.out.println("Boo"); else{ System.out.println("Error: Invalid input. Terminating Program."); System.exit(0);} } else { System.out.println("Error: Invalid input. Terminating Program."); System.exit(0); } } else { System.out.println("Error: Invalid input. Terminating Program."); System.exit(0); } } else { System.out.println("Error: Invalid input. Terminating Program."); System.exit(0); } } else { System.out.println("Error: Invalid input. Terminating Program."); System.exit(0); } } }<file_sep>////////////////////////////////////////////////////////// //<NAME> //CSE 2 //hw03-Bicycle Java Program //import scanner class import java.util.Scanner; // public class Bicycle{ public static void main(String [] args) { Scanner myScanner; myScanner=new Scanner (System.in); double wheelDiameter=27.0; double PI=3.14159, feetPerMile=5280, inchesPerFoot=12, secondsPerMinute=60; //Enter number of counts on a cyclometer System.out.print("Enter the number of counts "); int nCounts = myScanner.nextInt(); //Enter number of seconds during which the counts occurred System.out.print("Enter the number of seconds "); int nSeconds = myScanner.nextInt(); //Prints the distance traveled and time int nMinutes= nSeconds/60; double distanceTrip= nCounts*wheelDiameter*PI/inchesPerFoot/feetPerMile; System.out.format("The distance was %.2f miles and took " + nMinutes + " mintues long.", distanceTrip); //Prints average miles per hour int nHours=nMinutes/60; double avgMPH= distanceTrip/n; System.out.println("The average mph was "+avgMPH+" "); } }<file_sep>////////////////////////////////////////////////////////// //<NAME> //CSE 2 //hw03-Root Java Program //import scanner class import java.util.Scanner; // public class Root{ public static void main(String [] args) { Scanner myScanner; myScanner=new Scanner (System.in); System.out.print("Enter a double and I print its cube root: "); double number = myScanner.nextInt(); double guess= number/3; double root= ((guess*guess*guess+number)/(3*guess*guess)); System.out.println("The cube root is "+root+""); } }
db5e7beef284f1074b5a2174e03959e4b0a255c2
[ "Java" ]
5
Java
kjs215/CSE2
3398217fa1eed7ac75940ff8ff1421dcd104c7f1
095dcf0671b2540993f8569b25fb5457c45e1c52
refs/heads/master
<repo_name>arthur-littm/le-schedule<file_sep>/app/controllers/pages_controller.rb class PagesController < ApplicationController skip_before_action :authenticate_user!, only: [ :home ] def home # @weeks = WorkDay.where('date > ?', Date.today) # won't work because we want to show the current week @weeks = WorkDay.all.group_by { |wd| wd.date.cweek } end end <file_sep>/app/models/event.rb class Event < ApplicationRecord belongs_to :work_day end <file_sep>/db/seeds.rb today = Date.today last_day = Date.new(2020,12,31) today.upto(last_day) do |date| unless date.strftime("%A").downcase == 'sunday' WorkDay.create!(date: date) puts "Added #{date.strftime('%A, %b %d')}" end end <file_sep>/app/models/slot.rb class Slot < ApplicationRecord belongs_to :work_day belongs_to :user end
3d1119abab7b5c0598a1e395e4b14345fdef497e
[ "Ruby" ]
4
Ruby
arthur-littm/le-schedule
7abcaf5508d2f5ae31458f3544e57e92dbb764ed
5da1cfa0c91a67a52d45c47e281d5b585e776665
refs/heads/master
<file_sep>// // Copyright (c) 2019 <NAME>. // // This file is open source and available under the MIT license. See the LICENSE file for more info. // import Foundation /// A form item that represents a header. /// :nodoc: public final class FormHeaderItem: FormItem { /// The title of the header. public var title: String? /// Initializes the header item. public init() {} } <file_sep>// // Copyright (c) 2019 <NAME>. // // This file is open source and available under the MIT license. See the LICENSE file for more info. // import Foundation /// A form item in which two text items are shown side-by-side. /// :nodoc: public final class FormSplitTextItem: ComplexFormItem { private(set) var subItems: [FormItem] /// The text item displayed on the left side. public var leftItem: FormTextItem /// The text item displayed on the right side. public var rightItem: FormTextItem /// Initializes the split text item. /// /// - Parameter items: The items displayed side-by-side. Must be two. public init(items: [FormTextItem]) { assert(items.count == 2) leftItem = items[0] rightItem = items[1] self.subItems = items } } <file_sep>// // Copyright (c) 2019 <NAME>. // // This file is open source and available under the MIT license. See the LICENSE file for more info. // import UIKit /// A styled navigation controller. /// :nodoc: public final class NavigationController: UINavigationController, UINavigationControllerDelegate { /// :nodoc: public override init(rootViewController: UIViewController) { super.init(nibName: nil, bundle: nil) delegate = self viewControllers = [rootViewController] } /// :nodoc: public required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } // MARK: - View /// :nodoc: public override func viewDidLoad() { super.viewDidLoad() navigationBar.isTranslucent = false navigationBar.barTintColor = .componentBackground navigationBar.shadowImage = UIImage() navigationBar.setBackgroundImage(UIImage(), for: .default) // Hide separator on iOS 10. } // MARK: - UINavigationControllerDelegate /// :nodoc: public func navigationController(_ navigationController: UINavigationController, willShow viewController: UIViewController, animated: Bool) { viewController.navigationItem.backBarButtonItem = UIBarButtonItem(title: "", style: .plain, target: nil, action: nil) } } <file_sep>// // Copyright (c) 2019 <NAME>. // // This file is open source and available under the MIT license. See the LICENSE file for more info. // internal extension CardEncryptor.Card { func encryptedNumber(publicKey: String, date: Date) -> String? { // swiftlint:disable:this explicit_acl return ObjC_CardEncryptor.encryptedNumber(number, publicKey: publicKey, date: date) } func encryptedSecurityCode(publicKey: String, date: Date) -> String? { // swiftlint:disable:this explicit_acl return ObjC_CardEncryptor.encryptedSecurityCode(securityCode, publicKey: publicKey, date: date) } func encryptedExpiryMoth(publicKey: String, date: Date) -> String? { // swiftlint:disable:this explicit_acl return ObjC_CardEncryptor.encryptedExpiryMonth(expiryMonth, publicKey: publicKey, date: date) } func encryptedExpiryYear(publicKey: String, date: Date) -> String? { // swiftlint:disable:this explicit_acl return ObjC_CardEncryptor.encryptedExpiryYear(expiryYear, publicKey: publicKey, date: date) } func encryptedToToken(publicKey: String, holderName: String?) -> String? { // swiftlint:disable:this explicit_acl return ObjC_CardEncryptor.encryptedToToken(withNumber: number, securityCode: securityCode, expiryMonth: expiryMonth, expiryYear: expiryYear, holderName: holderName, publicKey: publicKey) } } <file_sep>// // Copyright (c) 2019 <NAME>. // // This file is open source and available under the MIT license. See the LICENSE file for more info. // import Foundation import PassKit /// A component that handles Apple Pay payments. public class ApplePayComponent: NSObject, PaymentComponent, PresentableComponent { /// The delegate of the component. public weak var delegate: PaymentComponentDelegate? /// The Apple Pay payment method. public let paymentMethod: PaymentMethod /// The line items for this payment. public let summaryItems: [PKPaymentSummaryItem] /// Initializes the component. /// /// - Warning: `stopLoading()` must be called before dismissing this component. /// /// - Parameter paymentMethod: The Apple Pay payment method. /// - Parameter payment: A description of the payment. Must include an amount and country code. /// - Parameter merchantIdentifier: The merchant identifier.. /// - Parameter summaryItems: The line items for this payment. public init?(paymentMethod: ApplePayPaymentMethod, payment: Payment, merchantIdentifier: String, summaryItems: [PKPaymentSummaryItem]) { guard PKPaymentAuthorizationViewController.canMakePayments(usingNetworks: ApplePayComponent.supportedNetworks) else { print("Failed to instantiate ApplePayComponent. PKPaymentAuthorizationViewController.canMakePayments returned false.") return nil } self.paymentMethod = paymentMethod self.applePayPaymentMethod = paymentMethod self.merchantIdentifier = merchantIdentifier self.summaryItems = summaryItems super.init() self.payment = payment } /// Initializes the component. /// /// - Parameter paymentMethod: The Apple Pay payment method. /// - Parameter merchantIdentifier: The merchant identifier.. /// - Parameter summaryItems: The line items for this payment. @available(*, deprecated, message: "Use init(paymentMethod:payment:merchantIdentifier:summaryItems:) instead.") public init?(paymentMethod: ApplePayPaymentMethod, merchantIdentifier: String, summaryItems: [PKPaymentSummaryItem]) { guard PKPaymentAuthorizationViewController.canMakePayments(usingNetworks: ApplePayComponent.supportedNetworks) else { print("Failed to instantiate ApplePayComponent. PKPaymentAuthorizationViewController.canMakePayments returned false.") return nil } self.paymentMethod = paymentMethod self.applePayPaymentMethod = paymentMethod self.merchantIdentifier = merchantIdentifier self.summaryItems = summaryItems } private let applePayPaymentMethod: ApplePayPaymentMethod // MARK: - Presentable Component Protocol /// :nodoc: public var viewController: UIViewController { return paymentAuthorizationViewController ?? errorAlertController } /// :nodoc: public var preferredPresentationMode: PresentableComponentPresentationMode { return .present } /// :nodoc: public func stopLoading(withSuccess success: Bool, completion: (() -> Void)?) { paymentAuthorizationCompletion?(success ? .success : .failure) dismissCompletion = completion } // MARK: - Private private var paymentAuthorizationCompletion: ((PKPaymentAuthorizationStatus) -> Void)? private var dismissCompletion: (() -> Void)? private let merchantIdentifier: String private var errorAlertController = UIAlertController(title: ADYLocalizedString("adyen.error.title"), message: ADYLocalizedString("adyen.error.unknown"), preferredStyle: .alert) private var paymentAuthorizationViewController: PKPaymentAuthorizationViewController? { guard let paymentAuthorizationViewController = PKPaymentAuthorizationViewController(paymentRequest: paymentRequest) else { print("Failed to instantiate PKPaymentAuthorizationViewController.") return nil } paymentAuthorizationViewController.delegate = self return paymentAuthorizationViewController } private var paymentRequest: PKPaymentRequest { let paymentRequest = PKPaymentRequest() paymentRequest.countryCode = payment?.countryCode ?? "" paymentRequest.merchantIdentifier = merchantIdentifier paymentRequest.currencyCode = payment?.amount.currencyCode ?? "" paymentRequest.supportedNetworks = ApplePayComponent.supportedNetworks paymentRequest.merchantCapabilities = .capability3DS paymentRequest.paymentSummaryItems = summaryItems return paymentRequest } private static var supportedNetworks: [PKPaymentNetwork] { var networks: [PKPaymentNetwork] = [.visa, .masterCard, .amex, .discover] if #available(iOS 12.0, *) { networks.append(.maestro) } return networks } } // MARK: - PKPaymentAuthorizationViewControllerDelegate extension ApplePayComponent: PKPaymentAuthorizationViewControllerDelegate { public func paymentAuthorizationViewControllerDidFinish(_ controller: PKPaymentAuthorizationViewController) { controller.dismiss(animated: true, completion: dismissCompletion) } public func paymentAuthorizationViewController(_ controller: PKPaymentAuthorizationViewController, didAuthorizePayment payment: PKPayment, completion: @escaping (PKPaymentAuthorizationStatus) -> Void) { paymentAuthorizationCompletion = completion let token = String(data: payment.token.paymentData, encoding: .utf8) ?? "" let details = ApplePayDetails(paymentMethod: applePayPaymentMethod, token: token) self.delegate?.didSubmit(PaymentComponentData(paymentMethodDetails: details), from: self) } } <file_sep>// // Copyright (c) 2019 <NAME>. // // This file is open source and available under the MIT license. See the LICENSE file for more info. // import Foundation /// A component that provides a form for SEPA Direct Debit payments. public final class SEPADirectDebitComponent: PaymentComponent, PresentableComponent { /// The SEPA Direct Debit payment method. public let paymentMethod: PaymentMethod /// The delegate of the component. public weak var delegate: PaymentComponentDelegate? /// Initializes the component. /// /// - Parameter paymentMethod: The SEPA Direct Debit payment method. public init(paymentMethod: SEPADirectDebitPaymentMethod) { self.paymentMethod = paymentMethod self.sepaDirectDebitPaymentMethod = paymentMethod } private let sepaDirectDebitPaymentMethod: SEPADirectDebitPaymentMethod // MARK: - Presentable Component Protocol /// :nodoc: public lazy var viewController: UIViewController = { Analytics.sendEvent(component: paymentMethod.type, flavor: _isDropIn ? .dropin : .components, environment: environment) return ComponentViewController(rootViewController: formViewController, cancelButtonHandler: didSelectCancelButton) }() /// :nodoc: public func stopLoading(withSuccess success: Bool, completion: (() -> Void)?) { footerItem.showsActivityIndicator.value = false completion?() } // MARK: - View Controller private lazy var formViewController: FormViewController = { let formViewController = FormViewController() let headerItem = FormHeaderItem() headerItem.title = paymentMethod.name formViewController.append(headerItem) formViewController.append(nameItem) formViewController.append(ibanItem) formViewController.append(footerItem) return formViewController }() // MARK: - Private private func didSelectSubmitButton() { guard formViewController.validate() else { return } let details = SEPADirectDebitDetails( paymentMethod: sepaDirectDebitPaymentMethod, iban: ibanItem.value, ownerName: nameItem.value ) footerItem.showsActivityIndicator.value = true delegate?.didSubmit(PaymentComponentData(paymentMethodDetails: details), from: self) } private lazy var didSelectCancelButton: (() -> Void) = { [weak self] in guard let self = self else { return } self.delegate?.didFail(with: ComponentError.cancelled, from: self) } // MARK: - Form Items private lazy var nameItem: FormTextItem = { let nameItem = FormTextItem() nameItem.title = ADYLocalizedString("adyen.sepa.nameItem.title") nameItem.placeholder = ADYLocalizedString("adyen.sepa.nameItem.placeholder") nameItem.validator = LengthValidator(minimumLength: 2) nameItem.validationFailureMessage = ADYLocalizedString("adyen.sepa.nameItem.invalid") nameItem.autocapitalizationType = .words return nameItem }() private lazy var ibanItem: FormTextItem = { func localizedPlaceholder() -> String { let countryCode = Locale.current.regionCode let specification = countryCode.flatMap(IBANSpecification.init(forCountryCode:)) let example = specification?.example ?? "NL26INGB0336169116" return IBANFormatter().formattedValue(for: example) } let ibanItem = FormTextItem() ibanItem.title = ADYLocalizedString("adyen.sepa.ibanItem.title") ibanItem.placeholder = localizedPlaceholder() ibanItem.formatter = IBANFormatter() ibanItem.validator = IBANValidator() ibanItem.validationFailureMessage = ADYLocalizedString("adyen.sepa.ibanItem.invalid") ibanItem.autocapitalizationType = .allCharacters return ibanItem }() private lazy var footerItem: FormFooterItem = { let footerItem = FormFooterItem() footerItem.title = ADYLocalizedString("adyen.sepa.consentLabel") footerItem.submitButtonTitle = ADYLocalizedSubmitButtonTitle(with: payment?.amount) footerItem.submitButtonSelectionHandler = { [weak self] in self?.didSelectSubmitButton() } return footerItem }() } <file_sep>// // ImageLoader.swift // Adyen // // Created by <NAME> on 10/27/19. // Copyright © 2019 Adyen. All rights reserved. // import Foundation public protocol ImageLoader { func loadImage(from url: URL, completion: @escaping (_ image: UIImage?) -> Void) func reset() } public final class DefaultImageLoader: ImageLoader { private var image: UIImage? private var dataTask: Cancelable? private var waitingList: [((_ image: UIImage?) -> Void)] = [] private let executer: URLRequestExecuter init(executer: URLRequestExecuter) { self.executer = executer } public func loadImage(from url: URL, completion: @escaping (_ image: UIImage?) -> Void) { assert(Thread.isMainThread) waitingList.append(completion) guard waitingList.count == 1 else { return } loadImage(from: url) } private func loadImage(from url: URL) { if let image = image { deliverImage(image: image) return } dataTask = executer.execute(request: URLRequest(url: url)) { data, response, error in guard let response = response as? HTTPURLResponse, response.statusCode == 200, let data = data, error == nil, let image = UIImage(data: data, scale: 1.0) else { return } DispatchQueue.main.async { self.deliverImage(image: image) self.dataTask = nil } } } private func deliverImage(image: UIImage) { waitingList.forEach { $0(image) } waitingList = [] } public func reset() { dataTask?.cancel() waitingList = [] image = nil } } <file_sep>// // Copyright (c) 2019 <NAME>. // // This file is open source and available under the MIT license. See the LICENSE file for more info. // import UIKit /// The interface of the delegate of a text item view. /// :nodoc: public protocol FormTextItemViewDelegate: FormValueItemViewDelegate { /// Invoked when the text entered in the item view's text field has reached the maximum length. /// /// - Parameter itemView: The item view in which the maximum length was reached. func didReachMaximumLength(in itemView: FormTextItemView) /// Invoked when the return key in the item view's text field is selected. /// /// - Parameter itemView: The item view in which the return key was selected. func didSelectReturnKey(in itemView: FormTextItemView) } /// A view representing a text item. /// :nodoc: open class FormTextItemView: FormValueItemView<FormTextItem>, UITextFieldDelegate { /// Initializes the text item view. /// /// - Parameter item: The item represented by the view. public required init(item: FormTextItem) { super.init(item: item) addSubview(stackView) configureConstraints() } /// :nodoc: public required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } private var textDelegate: FormTextItemViewDelegate? { return delegate as? FormTextItemViewDelegate } // MARK: - Stack View private lazy var stackView: UIStackView = { let stackView = UIStackView(arrangedSubviews: [titleLabel, textField]) stackView.axis = .vertical stackView.alignment = .fill stackView.spacing = 3.0 stackView.preservesSuperviewLayoutMargins = true stackView.isLayoutMarginsRelativeArrangement = true stackView.translatesAutoresizingMaskIntoConstraints = false return stackView }() // MARK: - Title Label private lazy var titleLabel: UILabel = { let titleLabel = UILabel() titleLabel.font = .systemFont(ofSize: 13.0) titleLabel.textColor = defaultTitleLabelTextColor titleLabel.text = item.title titleLabel.isAccessibilityElement = false return titleLabel }() private let defaultTitleLabelTextColor = UIColor.componentSecondaryLabel // MARK: - Text Field private lazy var textField: UITextField = { let textField = UITextField() textField.font = .systemFont(ofSize: 17.0) textField.textColor = .componentLabel textField.placeholder = item.placeholder textField.autocorrectionType = item.autocorrectionType textField.autocapitalizationType = item.autocapitalizationType textField.keyboardType = item.keyboardType textField.returnKeyType = .next textField.accessibilityLabel = item.title textField.delegate = self return textField }() // MARK: - Editing /// :nodoc: public override var isEditing: Bool { didSet { titleLabel.textColor = isEditing ? tintColor : defaultTitleLabelTextColor } } // MARK: - Layout private func configureConstraints() { let constraints = [ stackView.topAnchor.constraint(equalTo: topAnchor), stackView.leadingAnchor.constraint(equalTo: leadingAnchor), stackView.trailingAnchor.constraint(equalTo: trailingAnchor), stackView.bottomAnchor.constraint(equalTo: bottomAnchor) ] NSLayoutConstraint.activate(constraints) } open override var lastBaselineAnchor: NSLayoutYAxisAnchor { return textField.lastBaselineAnchor } // MARK: - Interaction /// :nodoc: open override var canBecomeFirstResponder: Bool { return textField.canBecomeFirstResponder } /// :nodoc: @discardableResult open override func becomeFirstResponder() -> Bool { return textField.becomeFirstResponder() } /// :nodoc: @discardableResult open override func resignFirstResponder() -> Bool { return textField.resignFirstResponder() } /// :nodoc: open override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) { super.touchesEnded(touches, with: event) _ = becomeFirstResponder() } // MARK: - UITextFieldDelegate /// :nodoc: public func textFieldDidBeginEditing(_ textField: UITextField) { isEditing = true } /// :nodoc: public func textFieldDidEndEditing(_ textField: UITextField) { isEditing = false } /// :nodoc: public func textFieldShouldReturn(_ textField: UITextField) -> Bool { textDelegate?.didSelectReturnKey(in: self) return true } /// :nodoc: public func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString: String) -> Bool { let text = textField.text ?? "" let newText = (text as NSString).replacingCharacters(in: range, with: replacementString) as String var sanitizedText = item.formatter?.sanitizedValue(for: newText) ?? newText let maximumLength = item.validator?.maximumLength(for: sanitizedText) ?? .max sanitizedText = sanitizedText.truncate(to: maximumLength) item.value = sanitizedText textDelegate?.didChangeValue(in: self) if sanitizedText.count == maximumLength { textDelegate?.didReachMaximumLength(in: self) } if let formatter = item.formatter { textField.text = formatter.formattedValue(for: newText) return false } else { return true } } } <file_sep>// // FormItemViewBuilder.swift // Adyen // // Created by <NAME> on 10/26/19. // Copyright © 2019 Adyen. All rights reserved. // import Foundation public protocol FormItemViewBuilder { func build<T: FormItem>(for item: T, delegate: FormItemViewDelegate?) -> FormItemView<T> } open class DefaultFormItemViewBuilder: FormItemViewBuilder { public func build<T>(for item: T, delegate: FormItemViewDelegate?) -> FormItemView<T> where T : FormItem { let itemViewType = getItemViewType(for: item) let itemView = itemViewType.init(item: item) itemView.delegate = delegate itemView.childItemViews.forEach { $0.delegate = delegate } return itemView } private func getItemViewType<T: FormItem>(for item: T) -> FormItemView<T>.Type { let itemViewType: Any switch item { case is FormHeaderItem: itemViewType = FormHeaderItemView.self case is FormFooterItem: itemViewType = FormFooterItemView.self case is FormTextItem: itemViewType = FormTextItemView.self case is FormSwitchItem: itemViewType = FormSwitchItemView.self case is FormSplitTextItem: itemViewType = FormSplitTextItemView.self default: fatalError("No view type known for given item.") } // swiftlint:disable:next force_cast return itemViewType as! FormItemView<T>.Type } } <file_sep>// // Copyright (c) 2019 <NAME>. // // This file is open source and available under the MIT license. See the LICENSE file for more info. // import UIKit /// An image view that displays images from a remote location. /// :nodoc: open class NetworkImageView: UIImageView { public var imageLoader: ImageLoader? = DefaultImageLoader(executer: URLSession.shared) /// The URL of the image to display. public var imageURL: URL? { didSet { guard imageURL != oldValue else { return } imageLoader?.reset() image = nil loadImageIfNeeded() } } /// :nodoc: open override func didMoveToWindow() { super.didMoveToWindow() loadImageIfNeeded() } // MARK: - Private // If we have an image URL and are embedded in a window, load the image if we aren't already. public func loadImageIfNeeded() { guard let imageURL = imageURL, window != nil else { return } imageLoader?.loadImage(from: imageURL) { image in DispatchQueue.main.async { self.image = image } } } private func cancelCurrentTask() { imageLoader?.reset() } } <file_sep>// // Copyright (c) 2019 <NAME>. // // This file is open source and available under the MIT license. See the LICENSE file for more info. // import Foundation /// A collection of available payment methods public struct PaymentMethods: Decodable { /// The regular payment methods. public let regular: [PaymentMethod] /// The stored payment methods. public let stored: [StoredPaymentMethod] /// Initializes the PaymentMethods. /// /// - Parameters: /// - regular: An array of the regular payment methods. /// - stored: An array of the stored payment methods. public init(regular: [PaymentMethod], stored: [StoredPaymentMethod]) { self.regular = regular self.stored = stored } /// Returns the first available payment method of the given type. /// /// - Parameter type: The type of payment method to retrieve. /// - Returns: The first available payment method of the given type, or `nil` if none could be found. public func paymentMethod<T: PaymentMethod>(ofType type: T.Type) -> T? { return regular.first { $0 is T } as? T } // MARK: - Decoding /// :nodoc: public init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) self.regular = try container.decode([AnyPaymentMethod].self, forKey: .regular).compactMap { $0.value } if container.contains(.stored) { self.stored = try container.decode([AnyPaymentMethod].self, forKey: .stored).compactMap { $0.value as? StoredPaymentMethod } } else { self.stored = [] } } fileprivate enum CodingKeys: String, CodingKey { case regular = "paymentMethods" case stored = "storedPaymentMethods" } } private enum AnyPaymentMethod: Decodable { case storedCard(StoredCardPaymentMethod) case storedPayPal(StoredPayPalPaymentMethod) case storedRedirect(StoredRedirectPaymentMethod) case card(CardPaymentMethod) case issuerList(IssuerListPaymentMethod) case sepaDirectDebit(SEPADirectDebitPaymentMethod) case redirect(RedirectPaymentMethod) case applePay(ApplePayPaymentMethod) case none fileprivate var value: PaymentMethod? { switch self { case let .storedCard(paymentMethod): return paymentMethod case let .storedPayPal(paymentMethod): return paymentMethod case let .storedRedirect(paymentMethod): return paymentMethod case let .card(paymentMethod): return paymentMethod case let .issuerList(paymentMethod): return paymentMethod case let .sepaDirectDebit(paymentMethod): return paymentMethod case let .redirect(paymentMethod): return paymentMethod case let .applePay(paymentMethod): return paymentMethod case .none: return nil } } // MARK: - Decoding fileprivate init(from decoder: Decoder) throws { do { let container = try decoder.container(keyedBy: CodingKeys.self) let type = try container.decode(String.self, forKey: .type) let isStored = decoder.codingPath.contains { $0.stringValue == PaymentMethods.CodingKeys.stored.stringValue } let requiresDetails = container.contains(.details) switch type { case "card", "scheme": if isStored { self = .storedCard(try StoredCardPaymentMethod(from: decoder)) } else { self = .card(try CardPaymentMethod(from: decoder)) } case "ideal", "entercash", "eps", "dotpay", "openbanking_UK", "molpay_ebanking_fpx_MY", "molpay_ebanking_TH", "molpay_ebanking_VN": self = .issuerList(try IssuerListPaymentMethod(from: decoder)) case "sepadirectdebit": self = .sepaDirectDebit(try SEPADirectDebitPaymentMethod(from: decoder)) case "applepay": self = .applePay(try ApplePayPaymentMethod(from: decoder)) case "paypal": if isStored { self = .storedPayPal(try StoredPayPalPaymentMethod(from: decoder)) } else { fallthrough } default: if isStored { self = .storedRedirect(try StoredRedirectPaymentMethod(from: decoder)) } else if !requiresDetails { self = .redirect(try RedirectPaymentMethod(from: decoder)) } else { self = .none } } } catch { self = .none } } private enum CodingKeys: String, CodingKey { case type case details } } <file_sep>// // Copyright (c) 2019 <NAME>. // // This file is open source and available under the MIT license. See the LICENSE file for more info. // @testable import Adyen import XCTest class PaymentMethodTests: XCTestCase { func testDecodingPaymentMethods() throws { let dictionary = [ "storedPaymentMethods": [ storedCardDictionary, storedCardDictionary, storedPayPalDictionary, [ "type": "unknown", "id": "9314881977134903", "name": "Stored Redirect Payment Method", "supportedShopperInteractions": ["Ecommerce"] ], [ "type": "unknown", "name": "Invalid Stored Payment Method" ] ], "paymentMethods": [ cardDictionary, issuerListDictionary, sepaDirectDebitDictionary, [ "type": "unknown", "name": "Redirect Payment Method" ], [ "name": "Invalid Payment Method" ] ] ] let paymentMethods = try Coder.decode(dictionary) as PaymentMethods XCTAssertEqual(paymentMethods.stored.count, 4) XCTAssertTrue(paymentMethods.stored[0] is StoredCardPaymentMethod) XCTAssertTrue(paymentMethods.stored[1] is StoredCardPaymentMethod) XCTAssertTrue(paymentMethods.stored[2] is StoredPayPalPaymentMethod) XCTAssertTrue(paymentMethods.stored[3] is StoredRedirectPaymentMethod) XCTAssertEqual(paymentMethods.stored[3].type, "unknown") XCTAssertEqual(paymentMethods.stored[3].name, "Stored Redirect Payment Method") XCTAssertEqual(paymentMethods.regular.count, 4) XCTAssertTrue(paymentMethods.regular[0] is CardPaymentMethod) XCTAssertTrue(paymentMethods.regular[1] is IssuerListPaymentMethod) XCTAssertTrue(paymentMethods.regular[2] is SEPADirectDebitPaymentMethod) XCTAssertTrue(paymentMethods.regular[3] is RedirectPaymentMethod) XCTAssertEqual(paymentMethods.regular[3].type, "unknown") XCTAssertEqual(paymentMethods.regular[3].name, "Redirect Payment Method") } // MARK: - Card let cardDictionary = [ "type": "scheme", "name": "Credit Card", "brands": ["mc", "visa", "amex"] ] as [String: Any] let storedCardDictionary = [ "type": "scheme", "id": "9314881977134903", "name": "VISA", "brand": "visa", "lastFour": "1111", "expiryMonth": "08", "expiryYear": "2018", "holderName": "test", "supportedShopperInteractions": [ "Ecommerce", "ContAuth" ] ] as [String: Any] func testDecodingCardPaymentMethod() throws { let paymentMethod = try Coder.decode(cardDictionary) as CardPaymentMethod XCTAssertEqual(paymentMethod.type, "scheme") XCTAssertEqual(paymentMethod.name, "Credit Card") XCTAssertEqual(paymentMethod.brands, ["mc", "visa", "amex"]) } func testDecodingCardPaymentMethodWithoutBrands() throws { var dictionary = cardDictionary dictionary.removeValue(forKey: "brands") let paymentMethod = try Coder.decode(dictionary) as CardPaymentMethod XCTAssertEqual(paymentMethod.type, "scheme") XCTAssertEqual(paymentMethod.name, "Credit Card") XCTAssertTrue(paymentMethod.brands.isEmpty) } func testDecodingStoredCardPaymentMethod() throws { let paymentMethod = try Coder.decode(storedCardDictionary) as StoredCardPaymentMethod XCTAssertEqual(paymentMethod.type, "scheme") XCTAssertEqual(paymentMethod.name, "VISA") XCTAssertEqual(paymentMethod.brand, "visa") XCTAssertEqual(paymentMethod.lastFour, "1111") XCTAssertEqual(paymentMethod.expiryMonth, "08") XCTAssertEqual(paymentMethod.expiryYear, "2018") XCTAssertEqual(paymentMethod.holderName, "test") XCTAssertEqual(paymentMethod.supportedShopperInteractions, [.shopperPresent, .shopperNotPresent]) } // MARK: - Issuer List let issuerListDictionary = [ "type": "ideal", "name": "iDEAL", "details": [ [ "items": [ [ "id": "1121", "name": "Test Issuer 1" ], [ "id": "1154", "name": "Test Issuer 2" ], [ "id": "1153", "name": "Test Issuer 3" ] ], "key": "issuer", "type": "select" ] ] ] as [String: Any] func testDecodingIssuerListPaymentMethod() throws { let paymentMethod = try Coder.decode(issuerListDictionary) as IssuerListPaymentMethod XCTAssertEqual(paymentMethod.type, "ideal") XCTAssertEqual(paymentMethod.name, "iDEAL") XCTAssertEqual(paymentMethod.issuers.count, 3) XCTAssertEqual(paymentMethod.issuers[0].identifier, "1121") XCTAssertEqual(paymentMethod.issuers[0].name, "Test Issuer 1") XCTAssertEqual(paymentMethod.issuers[1].identifier, "1154") XCTAssertEqual(paymentMethod.issuers[1].name, "Test Issuer 2") XCTAssertEqual(paymentMethod.issuers[2].identifier, "1153") XCTAssertEqual(paymentMethod.issuers[2].name, "Test Issuer 3") } // MARK: - SEPA Direct Debit let sepaDirectDebitDictionary = [ "type": "sepadirectdebit", "name": "SEPA Direct Debit" ] as [String: Any] func testDecodingSEPADirectDebitPaymentMethod() throws { let paymentMethod = try Coder.decode(sepaDirectDebitDictionary) as SEPADirectDebitPaymentMethod XCTAssertEqual(paymentMethod.type, "sepadirectdebit") XCTAssertEqual(paymentMethod.name, "SEPA Direct Debit") } // MARK: - Stored PayPal let storedPayPalDictionary = [ "type": "paypal", "id": "9314881977134903", "name": "PayPal", "shopperEmail": "<EMAIL>", "supportedShopperInteractions": [ "Ecommerce", "ContAuth" ] ] as [String: Any] func testDecodingPayPalPaymentMethod() throws { let paymentMethod = try Coder.decode(storedPayPalDictionary) as StoredPayPalPaymentMethod XCTAssertEqual(paymentMethod.type, "paypal") XCTAssertEqual(paymentMethod.identifier, "9314881977134903") XCTAssertEqual(paymentMethod.name, "PayPal") XCTAssertEqual(paymentMethod.emailAddress, "<EMAIL>") XCTAssertEqual(paymentMethod.supportedShopperInteractions, [.shopperPresent, .shopperNotPresent]) } } private extension Coder { static func decode<T: Decodable>(_ dictionary: [String: Any]) throws -> T { let data = try! JSONSerialization.data(withJSONObject: dictionary, options: []) return try decode(data) } } <file_sep>// // ComplexFormItem.swift // Adyen // // Created by <NAME> on 10/26/19. // Copyright © 2019 Adyen. All rights reserved. // import Foundation protocol ComplexFormItem: FormItem { var subItems: [FormItem] { get } func flatSubItems() -> [FormItem] } extension ComplexFormItem { func flatSubItems() -> [FormItem] { return subItems.flatMap { ($0 as? ComplexFormItem)?.flatSubItems() ?? [$0] } } } <file_sep>// // URLRequestExecuter.swift // Adyen // // Created by <NAME> on 10/27/19. // Copyright © 2019 Adyen. All rights reserved. // import Foundation protocol Cancelable { func cancel() } protocol URLRequestExecuter { func execute(request: URLRequest, completion: @escaping (_ data: Data?, _ response: URLResponse?, _ error: Error?) -> Void) -> Cancelable } extension URLSessionDataTask: Cancelable { } extension URLSession: URLRequestExecuter { func execute(request: URLRequest, completion: @escaping (_ data: Data?, _ response: URLResponse?, _ error: Error?) -> Void) -> Cancelable { let task = dataTask(with: request) { data, response, error in guard let response = response as? HTTPURLResponse, response.statusCode == 200, let data = data, error == nil else { return } DispatchQueue.main.async { completion(data, response, error) } } task.resume() return task } } <file_sep>// // Copyright (c) 2019 <NAME>. // // This file is open source and available under the MIT license. See the LICENSE file for more info. // import UIKit internal extension UIColor { static var componentBackground: UIColor { if #available(iOS 13.0, *) { return .systemBackground } else { return .white } } static var componentLabel: UIColor { if #available(iOS 13.0, *) { return .label } else { return .black } } static var componentSecondaryLabel: UIColor { if #available(iOS 13.0, *) { return .secondaryLabel } else { return .darkGray } } static var componentTertiaryLabel: UIColor { if #available(iOS 13.0, *) { return .tertiaryLabel } else { return .gray } } static var componentQuaternaryLabel: UIColor { if #available(iOS 13.0, *) { return .quaternaryLabel } else { return .lightGray } } static var componentPlaceholderText: UIColor { if #available(iOS 13.0, *) { return .placeholderText } else { return .gray } } static var componentSeparator: UIColor { if #available(iOS 13.0, *) { return .separator } else { return UIColor(white: 0.0, alpha: 0.2) } } } <file_sep>// // Copyright (c) 2019 <NAME>. // // This file is open source and available under the MIT license. See the LICENSE file for more info. // import Foundation /// Returns a localized string for the given key, and optionally uses it as a template /// in which the remaining argument values are substituted. /// This method will try first to get the string from main bundle. /// If no localization is available on main bundle, it'll return from internal one. /// /// :nodoc: /// /// - Parameters: /// - key: The key used to identify the localized string. /// - arguments: The arguments to substitute in the templated localized string. /// - Returns: The localized string for the given key, or the key itself if the localized string could not be found. public func ADYLocalizedString(_ key: String, _ arguments: CVarArg...) -> String { // Check main application bundle first. var localizedString = NSLocalizedString(key, tableName: nil, bundle: Bundle.main, comment: "") // If no string is available on main bundle, try internal one. if localizedString == key { localizedString = NSLocalizedString(key, tableName: nil, bundle: Bundle.internalResources, comment: "") } guard arguments.isEmpty == false else { return localizedString } return String(format: localizedString, arguments: arguments) } /// Helper function to create a localized submit button title. Optionally, the button title can include the given amount. /// /// :nodoc: /// /// - Parameter amount: The amount to include in the submit button title. public func ADYLocalizedSubmitButtonTitle(with amount: Payment.Amount?) -> String { guard let formattedAmount = amount?.formatted else { return ADYLocalizedString("adyen.submitButton") } return ADYLocalizedString("adyen.submitButton.formatted", formattedAmount) } private extension Bundle { /// The main bundle of the framework. static let core: Bundle = { Bundle(for: Coder.self) }() /// The bundle in which the framework's resources are located. static let internalResources: Bundle = { let url = core.url(forResource: "Adyen", withExtension: "bundle") let bundle = url.flatMap { Bundle(url: $0) } return bundle ?? core }() }
b749c470d8aff3c3261d2d2680681a9b1b59e5a5
[ "Swift" ]
16
Swift
mohammedDehairy/adyen-ios
a56e0363600733d68877c69f378774e17d6228f9
c65b013967025b81c27d34865195473041c63703
refs/heads/master
<repo_name>excellentteam007/spp<file_sep>/自动化代码/WTFV1/data/case_data_conf.ini [login] test_data_path=..\data\spp_case_ui.xlsx sheet_name=login start_row=1 end_row=5 [add_stall] test_data_path=..\data\spp_case_ui.xlsx sheet_name=lessor_homepage start_row=1 end_row=6 [modify_stall] test_data_path=..\data\spp_case_ui.xlsx sheet_name=lessor_homepage start_row=6 end_row=8 [add_property] test_data_path=..\data\spp_case_ui.xlsx sheet_name=property_manage start_row=1 end_row=4 [change_info] test_data_path=..\data\spp_case_ui.xlsx sheet_name=property_manage start_row=4 end_row=8 [property_search_by_name] test_data_path=..\data\spp_case_ui.xlsx sheet_name=property_manage start_row=8 end_row=11 [property_search_by_phone] test_data_path=..\data\spp_case_ui.xlsx sheet_name=property_manage start_row=11 end_row=13 [personal_information] test_data_path=..\data\spp_case_ui.xlsx sheet_name=personal_information start_row=1 end_row=2 [change_binding] test_data_path=..\data\spp_case_ui.xlsx sheet_name=change_binding start_row=1 end_row=4<file_sep>/自动化代码/WTFV1/action/lessor_homepage.py """ 命名规定: 定位元素的要进行输入的内容名字为:元素名字_v (value) 定位元素的配置文件提取的内容名字:元素名字_a (attr) 定位元素去执行的find的名字为:元素名字_e (element) """ from WTFV1.action.login import LoginAction from WTFV1.tools.ui_util import UiUtil, GetDesignatedPageElement import time class LessorHomepage: """ 出租方主页 """ def __init__(self): self.driver = UiUtil.get_driver() LoginAction().do_login('出租方103', '123', '0000') self.ui = UiUtil() self.e = GetDesignatedPageElement(self.driver, '..\\conf\\element_attr.ini', 'lessor_homepage') self.skip_iframe() # 跳转iframe def skip_iframe(self): iframe_e = self.e.get_element('iframe') self.ui.skip_iframe(self.driver, iframe_e) # 点击添加车位按钮 def click_add_stall_button(self): add_stall_e = self.e.get_element('add_stall') self.ui.select_by_js(self.driver, add_stall_e) # 输入车位id def input_stall_number(self, stall_number_v): stall_number_e = self.e.get_element('stall_number') self.ui.input(stall_number_e, stall_number_v) # 输入大小id def input_size_id(self, size_id_v): stall_number_e = self.e.get_element('size_id') self.ui.input(stall_number_e, size_id_v) # 输入位置id def input_location_id(self, location_id_v): stall_number_e = self.e.get_element('location_id') self.ui.input(stall_number_e, location_id_v) # 输入详细地址 def input_address(self, address_v): stall_number_e = self.e.get_element('address') self.ui.input(stall_number_e, address_v) # 点击增加确认按钮 def click_add_confirm_button(self): add_confirm_button_e = self.e.get_element('add_confirm_button') self.ui.click(add_confirm_button_e) # 执行增加车位动作 def do_add_stall(self, data): self.click_add_stall_button() self.input_stall_number(data['stall_id']) self.input_size_id(data['size_id']) self.input_location_id(data['location_id']) self.input_address(data['detailed_address']) self.click_add_confirm_button() # 获取增加车位动作结果 def get_add_stall_actual(self, data): self.do_add_stall(data) try: add_stall_result_e = self.e.get_element('add_stall_result') except: actual = "添加失败" else: result = self.ui.get_text(add_stall_result_e) if data['stall_id'] in result: actual = "添加成功" else: actual = "添加失败" time.sleep(3) self.click_delete_stall_button() return actual # 点击删除车位按钮 def click_delete_stall_button(self): delete_stall_button_e = self.e.get_element('delete_stall_button') self.ui.click(delete_stall_button_e) # 点击修改车位按钮 def click_modify_button(self): modify_button_e = self.e.get_element('modify_button') self.ui.click(modify_button_e) # 点击修改确认按钮 def click_modify_confirm_button(self): modify_confirm_button_e = self.e.get_element('modify_confirm_button') self.ui.click(modify_confirm_button_e) # 执行修改车位按钮 def do_modify_stall(self, data): self.click_modify_button() self.input_stall_number(data['stall_id']) self.input_size_id(data['size_id']) self.input_location_id(data['location_id']) self.input_address(data['detailed_address']) self.click_modify_confirm_button() def get_modify_stall_actual(self, data): self.do_modify_stall(data) time.sleep(3) modify_stall_result_e = self.e.get_element('modify_stall_result') modify_stall_result = self.ui.get_text(modify_stall_result_e) if data['stall_id'] in modify_stall_result: actual = '修改成功' else: actual = '修改失败' return actual if __name__ == '__main__': print(LessorHomepage().get_modify_stall_actual(d)) # LessorHomepage().do_modify('2345', '1', '4200', '第五国际') <file_sep>/自动化代码/WTFV1/tools/api_util.py import requests from WTFV1.tools.comm_util import FileUtil class ApiUtil: @classmethod def get_session(cls): """ :return: 获取request里面的session """ return requests.session() @classmethod def set_cookie(cls, session): """ 获取页面的cookie :param session: 上面的session """ login_page_url = FileUtil.get_ini_value('..\\conf\\base.ini', 'api_info', 'login_page_url') session.get(login_page_url) if __name__ == '__main__': pass <file_sep>/自动化代码/WTFV1/setup/start.py import os class Start: def load(self): module_names = os.listdir('..\\kwdriver') test_module_names = [] for module in module_names: if module.endswith('_test.py'): test_module_names.append(module) return test_module_names def load1(self): test_module_names = self.load() for module_name in test_module_names: module_name = module_name.split('.')[0] module = __import__('WTFV1.kwdriver.'+module_name, fromlist=module_name) contents = dir(module) class_names = [] for content in contents: if content.endswith('Test'): class_names.append(content) class_objs = [] for class_name in class_names: if hasattr(module, class_name): class_obj = getattr(module, class_name) # print(class_obj) class_objs.append(class_obj) # print(class_objs) contents = [] for obj in class_objs: contents = dir(obj) # contents.append(contents1) test_module_names = [] for content in contents: if content.startswith('test_'): test_module_names.append(content) for obj in class_objs: o = obj() for method_name in test_module_names: if hasattr(obj, method_name): getattr(o, method_name)() # print(obj) if __name__ == '__main__': Start().load1() <file_sep>/自动化代码/WTFV1/tools/ui_util.py import os from pykeyboard import PyKeyboard from pymouse import PyMouse class UiUtil: """ GUI自动化的工具方法 """ from WTFV1.tools.comm_util import LogUtil logger = LogUtil.get_logger(os.path.join(os.getcwd(), 'ui_util')) driver = None keyboard = PyKeyboard() mouse = PyMouse() def __init__(self): pass @classmethod def get_driver(cls): """ webdriver封装,默认“Chrome” :param browser: 浏览器。可以为(Chrome,Firefox,Ie,Edge) :return: driver """ from selenium import webdriver from WTFV1.tools.comm_util import FileUtil browser = FileUtil.get_ini_value('..\\conf\\base.ini', 'ui_info', 'browser') page = FileUtil.get_ini_value('..\\conf\\base.ini', 'ui_info', 'login_page') if cls.driver is None: try: cls.driver = getattr(webdriver, browser)() except Exception as e: cls.logger.error('输入不正确,使用了默认谷歌浏览器->%s' % e) cls.driver = webdriver.Chrome cls.driver.implicitly_wait(3) cls.driver.maximize_window() cls.driver.get(page) return cls.driver @classmethod def close_driver(cls,): cls.get_driver().close() @classmethod def match_image(cls, target): """ 通过opencv库对图像的识别,通过模板图片(小图),和全屏图(大图)进行算法对比 :param target: 模板图片的名字 :return: 图片中心位置的坐标 """ from PIL import ImageGrab import cv2 image_path = "..\\image" screen_path = os.path.join(image_path, 'screen.png') # 对大图进行截图,并保存在指定路径 ImageGrab.grab().save(screen_path) # 读取大图 screen = cv2.imread(screen_path) # 读取小图 template = cv2.imread(os.path.join(image_path, target)) # 调用匹配算法 result = cv2.matchTemplate(screen, template, cv2.TM_CCOEFF_NORMED) # 获取坐标 min, max, min_loc, max_loc = cv2.minMaxLoc(result) # 计算矩形十字中心点坐标 x = max_loc[0] + int(template.shape[1]/2) y = max_loc[1] + int(template.shape[0]/2) return x, y @classmethod def click_image(cls, target): """ 找到这个图片单击这个图片 :param target: 图片名字 """ x, y = cls.match_image(target) if x == -1 or y == -1: cls.logger.error(f"没有找到{target}的图片") return cls.mouse.click(x, y) @classmethod def double_click_image(cls, target): """ 找到这个图片双击这个图片 :param target: 图片名字 """ x, y = cls.match_image(target) if x == -1 or y == -1: cls.logger.error(f"没有找到{target}的图片") return cls.mouse.click(x, y, n=2) @classmethod def input_image(cls, target, msg): """ 找到输入框图片在里面输入内容 :param target: 图片名字 :param msg: 输入的内容 """ x, y = cls.match_image(target) if x == -1 or y == -1: cls.logger.error(f'没有找到{target}的图片') return cls.keyboard.type_string(msg) @classmethod def select_image(cls, target, count): """ 找到下拉框图片,点击一下,然后通过按下键选择一个 :param target: 图片名字 :param count:循环几次 """ cls.click_image(target) for i in range(count): cls.keyboard.press_key(cls.keyboard.down_key) cls.keyboard.press_key(cls.keyboard.enter_key) def find_element(self, driver, elment_attr): """ 自己写的找元素的方法,通多find_element(定位方式,定位方式对应的内容) :param driver: 需要的一个webdriver :param elment_attr: 提取的页面元素配置文件的信息,里面内容是(定位方式,定位方式对应的内容) :return:元素的对象 """ from selenium.webdriver.common.by import By return driver.find_element(getattr(By, elment_attr[0]), elment_attr[1]) def input(self, element, value): """ 输入框找到,点击,清空,输入内容 :param element:页面上的输入框元素 :param value:给输入框输入的值 """ element.click() element.clear() element.send_keys(value) def click(self, element): """ 找到元素点击 :param element:要单击的元素 """ element.click() def select_drop_down_box(self, element, value): """ 下拉框选择元素 :param element: 下拉框的元素 :param value: 要选择的下拉框元素 """ from selenium.webdriver.support.select import Select myselect = Select(element) myselect.select_by_visible_text(value) def select_by_js(self, driver, element): """ 通过js代码找到选择需要滚动鼠标中键才能找到的元素 :param element: 页面上的元素 """ js_code = 'arguments[0].scrollIntoView();' driver.execute_script(js_code, element) element.click() def get_text(self, element): """ :param element: 页面上的元素 :return: 页面元素的文本内容 """ return element.text def skip_iframe(self, driver, element): """ 跳转iframe :param element: iframe定位 """ driver.switch_to.frame(element) def mouse_hover(self, driver, element): """ 鼠标悬停操作 :param driver: 浏览器驱动 :param element: 元素定位 """ from selenium.webdriver.common.action_chains import ActionChains ActionChains(driver).move_to_element(element).perform() def execute_js(self, driver, js_code): """ 执行js代码 :param driver:浏览器驱动 :param js_code:js代码 :return: """ driver.execute_script(js_code) class GetDesignatedPageElement: """ 找指定页面的元素 """ def __init__(self, driver, attr_path, section): """ :param driver: 浏览器驱动 :param attr_path: 配置文件路径 :param section: 节点名字 """ from WTFV1.tools.comm_util import FileUtil self.driver = driver self.ele = FileUtil.trans_ini_tuple_to_dict(attr_path, section) self.ui = UiUtil() def get_element(self, option): """ 找到指定页面的元素定位方式 :param option: 键 :return: 找到的元素对象 """ attr = eval(self.ele[option]) return self.ui.find_element(self.driver, attr) if __name__ == '__main__': UiUtil.get_driver()<file_sep>/自动化代码/WTFV1/kwdriver/collection.py import os from WTFV1.tools.comm_util import LogUtil class Collection: logger = LogUtil.get_logger(os.path.join(os.getcwd(), 'collection')) driver = None @classmethod def do_get_driver(cls, browser): """ 关键字“打开浏览器”操作 :param browser: 浏览器 """ from selenium import webdriver if cls.driver is None: if hasattr(webdriver, browser): cls.driver = getattr(webdriver, browser)() else: cls.logger.error("浏览器名称不正确") cls.driver = webdriver.Chrome cls.driver.maximize_window() # cls.driver.set_window_size(1000, 30000) @classmethod def do_open(cls, url): """ 关键字“获取页面”操作 :param url: url """ cls.driver.get(url) @classmethod def get_element(cls, attr): """ 获取元素方法 :param attr: 例如(ID=name) :return: 获取的元素对象 """ attr = str(attr).split('='[0]) from selenium.webdriver.common.by import By if hasattr(By, attr[0]): return cls.driver.find_element(getattr(By, attr[0]), attr[1]) else: return None @classmethod def do_input(cls, attr, value): """ 关键字“输入”方法 :param attr: 获取元素 :param value: 输入的值 """ element = cls.get_element(attr) if element is not None: element.click() element.clear() element.send_keys(value) else: cls.logger.error('元素没找到') @classmethod def do_click(cls, attr): """ 关键字“点击”方法 :param attr: 获取元素 """ element = cls.get_element(attr) if element is not None: element.click() else: cls.logger.error('元素没找到') @classmethod def do_sleep(cls, wt): """ 关键字“等待”方法 :param wt: 等待时间 """ wt = int(wt) import time time.sleep(wt) @classmethod def do_close(cls): """ 关键字“关闭浏览器”方法 """ cls.driver.close() @classmethod def do_confirm(cls): """ 关键词“确认”方法 """ cls.driver.switch_to.alert.accept() @classmethod def do_refresh(cls): """ 关键字“刷新”方法 """ cls.driver.refresh() @classmethod def do_quit(cls): """ 关键词“退出”方法 :return: """ cls.driver.quit() @classmethod def do_roll_click(cls, attr): attr = str(attr).split('='[0]) from selenium.webdriver.common.by import By if hasattr(By, attr[0]): element = cls.driver.find_element(getattr(By, attr[0]), attr[1]) js_code = "arguments[0].scrollIntoView();" cls.driver.execute_script(js_code) element.click() @classmethod def do_roll_input(cls, attr, value): js_code = "arguments[0].scrollIntoView();" element = cls.get_element(attr) if element is not None: cls.driver.execute_script(js_code, element) element.click() element.clear() element.send_keys(value) else: cls.logger.error('元素没找到') <file_sep>/自动化代码/WTFV1/kwdriver/kw_start.py from WTFV1.tools.comm_util import FileUtil from WTFV1.kwdriver.collection import Collection class Start: @classmethod def start_kw_script(cls): """ 读取脚本的中的关键字和关键字内容,通过关键字找到关键字对应的方法并且执行 """ # 读取关键字配置文件 keyword_map = FileUtil.get_json('keyword.conf') script_path = FileUtil.get_txt('keyword_scrip.conf') for path in script_path: if not path.startswith('#'): # 读取csv脚本文件 scrip = FileUtil.get_csv(path) for scrip_v in scrip: col = Collection # 判断不是#号开头的,才是脚本内容 if not str(scrip_v[0]).startswith('#'): # 脚本第一项为关键字 keyword = scrip_v[0] # 除去第一项为关键字对象的内容 keyword_c = scrip_v[1:] # 关键字和关键字方法对应 method_name = keyword_map[keyword] if hasattr(col, method_name): # 方法执行 method_obj = getattr(col, method_name) # 传递参数 method_obj(*keyword_c) if __name__ == '__main__': Start.start_kw_script()<file_sep>/自动化代码/WTFV1/action/tenant_comment.py """ 命名规定: 定位元素的要进行输入的内容名字为:元素名字_v (value) 定位元素的配置文件提取的内容名字:元素名字_a (attr) 定位元素去执行的find的名字为:元素名字_e (element) """ from WTFV1.action.login import LoginAction from WTFV1.tools.ui_util import UiUtil from WTFV1.tools.comm_util import FileUtil import time class Comment: def __init__(self): self.driver = UiUtil.get_driver() LoginAction().do_login('抢租客0', '123', '0000') self.ui = UiUtil() self.ele = FileUtil.trans_ini_tuple_to_dict('..\\conf\\element_attr.ini', 'comment') # 点击进入历史订单页面 def examine_order_history(self): time.sleep(0.5) order_history_a = eval(self.ele['order_history']) order_history = self.ui.find_element(self.driver, order_history_a) self.ui.click(order_history) def skip_iframe(self): time.sleep(1) iframe_a = eval(self.ele['iframe']) iframe_e = self.ui.find_element(self.driver, iframe_a) self.ui.skip_iframe(self.driver, iframe_e) def query_method(self): time.sleep(5) query_method_a = eval(self.ele['query_method']) query_method = self.ui.find_element(self.driver, query_method_a) self.ui.select_drop_down_box(query_method, "按状态查询") def select_status(self): time.sleep(0.5) select_status_a = eval(self.ele['select_status']) select_status = self.ui.find_element(self.driver, select_status_a) self.ui.select_drop_down_box(select_status, "已完成") def click_seek(self): time.sleep(0.5) click_seek_a = eval(self.ele['click_seek']) click_seek = self.ui.find_element(self.driver, click_seek_a) self.ui.click(click_seek) def click_comment(self): time.sleep(0.5) click_comment_a = eval(self.ele['comment']) click_comment = self.ui.find_element(self.driver, click_comment_a) self.ui.click(click_comment) def input_comment(self, comment): time.sleep(0.5) input_comment_a = eval(self.ele['input_comment']) input_comment_e = self.ui.find_element(self.driver, input_comment_a) self.ui.input(input_comment_e, comment) def send_comment(self): time.sleep(0.5) send_comment_a = eval(self.ele['send_comment']) send_comment = self.ui.find_element(self.driver, send_comment_a) self.ui.click(send_comment) def get_text(self): time.sleep(5) get_text_a = eval(self.ele['text']) get_text_e = self.ui.find_element(self.driver, get_text_a) text = self.ui.get_text(get_text_e) return text def do_comment(self, comment): self.examine_order_history() self.skip_iframe() self.query_method() self.select_status() self.click_seek() self.click_comment() self.input_comment(comment) self.send_comment() text = self.get_text() self.driver.refresh() if text == comment: actual = "评论成功" else: actual = "评论失败" return actual if __name__ == '__main__': b = "车位干净整洁,挺不错的" a = Comment() print(a.do_comment(b))<file_sep>/自动化代码/WTFV1/action/login.py from WTFV1.tools.ui_util import UiUtil, GetDesignatedPageElement """ 命名规定: 定位元素的要进行输入的内容名字为:元素名字_v (value) 定位元素的配置文件提取的内容名字:元素名字_a (attr) 定位元素去执行的find的名字为:元素名字_e (element) """ class LoginAction: def __init__(self): self.driver = UiUtil.get_driver() self.ui = UiUtil() self.e = GetDesignatedPageElement(self.driver, '..\\conf\\element_attr.ini', 'login') # 用户名输入 def input_name(self, uname_v): uname_e = self.e.get_element("name") self.ui.input(uname_e, uname_v) # 密码输入 def input_password(self, password_v): password_e = self.e.get_element('password') self.ui.input(password_e, password_v) # 验证码输入 def input_imgcode(self, imgcode_v): imgcode_e = self.e.get_element('imgcode') self.ui.input(imgcode_e, imgcode_v) # 登录的点击 def click_login_button(self): button_e = self.e.get_element('button') self.ui.click(button_e) # 登录动作 def do_login(self, name, password, imgcode): self.input_name(name) self.input_password(<PASSWORD>) self.input_imgcode(imgcode) self.click_login_button() # 登录后的实际结果验证 def get_login_result(self, name, password, imgcode): self.do_login(name, password, imgcode) actual_e = self.e.get_element('actual') return self.ui.get_text(actual_e) if __name__ == '__main__': LoginAction().do_login('出租方1', '123', '0000') # print(LoginAction().get_login_result("222", "123", "0000"))<file_sep>/自动化代码/WTFV1/tools/comm_util.py import os import json import pymysql """ 公共的方法 """ class TimeUtil: """ 关于时间的方法 """ @classmethod def get_time_file(cls): """ 读取当前时间 :return: 时间字符串 """ import time return time.strftime('%Y.%m.%d-%H.%M.%S', time.localtime()) class LogUtil: # 单例模式 logger = None @classmethod def get_logger(cls, module_name): """ 获取logger对象 module_name一般可以放调用该对象的模块的字符串名称 普通有4种信息级别:error,warn,info,debug 判断logs路径是否存在,如果不存在则创建它 """ import logging if cls.logger is None: cls.logger = logging.getLogger(module_name) cls.logger.setLevel("INFO") if not os.path.exists('..\\logs'): os.mkdir('..\\logs') # 获取时间字符串 c_time = TimeUtil.get_time_file() # 拼接日志文件的名称 log_time = "..\\logs\\" + module_name + "." + c_time + ".log" # 创建句柄,用于和文件的关联 handle = logging.FileHandler(log_time, encoding="utf-8") # 定义日志信息的保存格式 formatter = logging.Formatter( '%(asctime)s - %(name)s - %(levelname)s - %(message)s') # 句柄具有规定的格式 handle.setFormatter(formatter) cls.logger.addHandler(handle) cls.logger.info( '--------------------------------------------------------------\n') return cls.logger class FileUtil: logger = LogUtil.get_logger("GetFileTools") @classmethod def get_version(cls, path, sheet): """ 获取测试系统的版本号 :param path: 测试路径 :param sheet: sheet页 :return: 版本号的值 """ import xlrd workbook = xlrd.open_workbook(path) sheet_content = workbook.sheet_by_name(sheet) return sheet_content.cell_value(1, 1) @classmethod def get_txt(cls, path): """ 读取普通文本文件内容,返回字符串 :param path: 文本文件路径 :return: 文本文件内容字符串 # """ li = [] try: with open(path, "r", encoding="utf-8")as f: contents = f.readlines() for content in contents: li.append(content.strip()) except Exception as e: cls.logger.error(f"文件{path}读取失败-->{e}") return li @classmethod def get_csv(cls, path): """ 读取csv文件 :param path: 文件路径 :return: 结果列表套列表, """ import csv li = [] try: with open(path, encoding="utf8") as f: contents = csv.reader(f) for content in contents: li.append(content) except Exception as e: cls.logger.error(f"读取{path}错误-->{e}") return li @classmethod def get_json(cls, path): """ 从json格式文件中读取原始格式内容并返回 :param path:要读取的json文件路径 :return:原始数据类型的数据 """ contents = None try: with open(path, "r", encoding="utf-8")as f: contents = json.load(f) except Exception as e: cls.logger.error(f"json{path}读取失败-->{e}") return contents @classmethod def get_ini_by_section(cls, path, section): """ 读取ini配置文件 :param path: 配置文件路径 :param section: 要读取的节段 :return:列表套元组的格式 """ import configparser contents = None try: # 创建配置器对象 cp = configparser.ConfigParser() cp.read(path, encoding="utf-8") contents = cp.items(section) except Exception as e: cls.logger.error(f"读取{path}的{section}节点错误-->{e}") return contents @classmethod def get_ini_value(cls, path, section, option): """ 读取ini配置文件通过选项(等号左边的)取里面的内容 :param path: ini配置文件路径 :param section: 要读取的节段 :param option: 要读取的选项 :return:文件中节点下对应选项的值的原始数据 """ import configparser cp = configparser.ConfigParser() content = None try: cp.read(path, encoding='utf8') contents = cp.get(section, option) # eval内置函数把看起来像具有元组,列表格式的字符串转换为相应的格式 content = eval(contents) except Exception as e: cls.logger.error(f"读取文件{path}下{section}节点下{option}错误-->{e}") return content @classmethod def trans_ini_tuple_to_dict(cls, path, section): """ 把读取的ini的列表套元组的格式转换成字典格式 :param path: 配置文件路径 :param section:要读取的节段 :return: 字典格式 """ contents = cls.get_ini_by_section(path, section) dict1 = {} try: for c in contents: dict1[c[0]] = c[1] except Exception as e: cls.logger.error(f"ini的列表套元组的格式转换成字典格式-->{e}") return dict1 @classmethod def get_excel(cls, path, section): """ 从excel文件中读取测试信息 配置文件中用对应的要读取的excel信息 :param path:测试信息配置文件路径及文件名 :param section: 对应功能的节点名 :return:测试信息的json格式 """ import xlrd # 读取配置文件 test_info = cls.trans_ini_tuple_to_dict(path, section) # 打卡excel文件通过路径 workbook = xlrd.open_workbook(test_info["test_data_path"]) # 找到对应的sheet contents = workbook.sheet_by_name(test_info["sheet_name"]) list1 = [] # 开始的行到结束的行遍历 for i in range(int(test_info["start_row"]), int(test_info["end_row"])): temp1 = {} temp1["case_id"] = contents.cell_value(i, 0) temp1["module_name"] = contents.cell_value(i, 1) temp1["test_type"] = contents.cell_value(i, 2) temp1["api_uri"] = contents.cell_value(i, 3) temp1["request_method"] = contents.cell_value(i, 4) temp1["case_desc"] = contents.cell_value(i, 5) # 对测试用例数据单独处理 data = contents.cell_value(i, 6) data_dict = {} if data != '': t1 = str(data).split("\n") for t in t1: t = t.split("=") data_dict[t[0]] = t[1] temp1["case_params"] = data_dict temp1["expect"] = contents.cell_value(i, 7) list1.append(temp1) return list1 class DBUtil: logger = LogUtil.get_logger("DBTools") def __init__(self, option): """ :param option: 配置文件中db_info节点下的键 """ self.option = option def get_conn(self): """ 连接数据库返回数据库连接对象 :return:数据库连接对象 """ # 配置文件读取配置信息 db_info = FileUtil.get_ini_value("..\\conf\\base.ini", 'db_info', self.option) conn = None try: conn = pymysql.connect(host=db_info[0], port=int(db_info[1]), user=db_info[2], password=db_info[3], database=db_info[4], charset='utf8') except Exception as e: self.logger.error("数据库连接失败-->%s" % e) return conn def sql_execute(self, sql): """ 执行SQL语句返回元组格式 :param sql: sql语句 :return: 元组格式 """ conn = self.get_conn() result = None if conn is not None: # 生成游标对象 cursor = conn.cursor() try: # 执行sql语句 cursor.execute(sql) # 获取查询结果 result = cursor.fetchall() except Exception as e: self.logger.error(f"{sql}语句错误,执行失败-->{e}") # 关闭游标 cursor.close() else: self.logger.error('数据库连接错误') # 关闭数据库 conn.close() return result def updata_db(self, sql): """ 添加数据到数据库的方法 :param sql: sql语句 :return: False或者True """ flag = False conn = self.get_conn() if conn is not None: cursor = conn.cursor() try: cursor.execute(sql) # 提交事务(不提交不会完成添加) conn.commit() flag = True except Exception as e: self.logger.error(f'{sql}语句错误,执行失败-->{e}') cursor.close() else: self.logger.error('数据库连接失败') conn.close() return flag class Common: @classmethod def get_screenshot(cls, driver, version): """ 截取当前屏幕的并返回图片路径 :param driver: 用的selenium里面的方法截图,要一个driver :param version: 被测系统的版本 :return: 截图路径 """ if not driver is None: screenshot_path = f'../report/{version}/screenshot' if not os.path.exists(screenshot_path): os.makedirs(screenshot_path) image_name = screenshot_path + str(TimeUtil.get_time_file()) + '.png' driver.get_screenshot_as_file(image_name) else: image_name = '无' return image_name class CustomAssert: logger = LogUtil.get_logger('util') def __init__(self, version, table, driver=None): """ :param version: 测试的版本号 :param table: 数据库的表名 :param driver: 下面需要的一个driver """ self.driver = driver self.version = version self.table = table self.db = DBUtil('db_conn_result_info') def write_result_to_db(self, info, result_msg, error_msg, error_img_path): """ 写测试数据结果到数据库 :param info: 测试的信息 :param result_msg: 测试结果信息 :param error_msg: 测试的错误信息 :param error_img_path: 错误的截图路径 """ case_id = info['case_id'] module_name = info['module_name'] test_type = info['test_type'] api_url = info['api_uri'] request_method = info['request_method'] case_desc = info['case_desc'] case_params = info['case_params'] expect = info['expect'] sql = f""" insert into {self.table}(case_version,case_id,module_name, test_type,api_url,request_method,case_desc,case_params,expect, result_msg,error_msg,error_img_path) values ("{self.version}","{case_id}","{module_name}","{test_type}", "{api_url}","{request_method}","{case_desc}","{case_params}", "{expect}","{result_msg}","{error_msg}","{error_img_path}");""" if not self.db.updata_db(sql): self.logger.error('sql执行错误') def error(self, info): """ 错误的断言 :param info: 测试的信息 """ result_msg = 'test_error' error_img_path = Common.get_screenshot(self.driver, self.version) self.write_result_to_db(info, result_msg, info['error_msg'], error_img_path) def equal(self, actual, info): """ 相等的断言 :param actual: 实际的结果 :param info: 测试的信息 """ import time if info['expect'] == actual: result_msg = 'test_pass' error_msg = '无' error_img_path = '无' else: result_msg = 'test_fail' error_msg = '无' error_img_path = Common.get_screenshot(self.driver, self.version) time.sleep(1) self.write_result_to_db(info, result_msg, error_msg, error_img_path) def contain(self, actual, info): """ 包含的断言,实际结果包括预期结果 :param actual: 实际结果 :param info: 测试信息 """ if info['expect'] in actual: result_msg = 'test_pass' error_msg = '无' error_img_path = '无' else: result_msg = 'test_fail' error_msg = '无' error_img_path = Common.get_screenshot(self.driver, self.version) self.write_result_to_db(info, result_msg, error_msg, error_img_path) if __name__ == '__main__': print(FileUtil.get_excel('..\\data\\api_case_data_conf.ini', 'login'))<file_sep>/自动化代码/WTFV1/testcase/property_manage_test.py from WTFV1.tools.comm_util import FileUtil, LogUtil, CustomAssert from WTFV1.action.property_manage import PropertyManage from WTFV1.tools.ui_util import UiUtil import time import traceback class PropertyManageTest: # 日志 logger = LogUtil.get_logger('property_manage_test') def setup_class(self): # 一个项目模块 self.pm = PropertyManage() # 获取版本号 self.version = FileUtil.get_version('..\\data\\spp_case_ui.xlsx', 'caseinfo') # 获取断言实例化 self.ca = CustomAssert(self.version, 'spp_test_result', self.pm.driver) def test_add_property(self): # 提取测试信息的配置文件 test_info = FileUtil.get_excel('..\\data\\case_data_conf.ini', 'add_property') for info in test_info: test_data = info['case_params'] try: actual = self.pm.get_add_property_actual(test_data) self.ca.equal(actual, info) except Exception as e: error_msg = traceback.format_exc() info['error_msg'] = error_msg self.ca.error(info) time.sleep(3) def test_change_info(self): # 提取测试信息的配置文件 test_info = FileUtil.get_excel('..\\data\\case_data_conf.ini', 'change_info') for info in test_info: test_data = info['case_params'] try: actual = self.pm.do_property_change_info(test_data) self.ca.equal(actual, info) except Exception as e: error_msg = traceback.format_exc() info['error_msg'] = error_msg self.ca.error(info) # actual = self.pm.do_property_change_info(test_data) time.sleep(3) def test_property_search_by_name(self): # 提取测试信息的配置文件 test_info = FileUtil.get_excel('..\\data\\case_data_conf.ini', 'property_search_by_name') for info in test_info: test_data = info['case_params'] try: actual = self.pm.get_property_search_by_name_actual(test_data) self.ca.equal(actual, info) except Exception as e: error_msg = traceback.format_exc() info['error_msg'] = error_msg self.ca.error(info) time.sleep(2) # actual = self.pm.get_property_search_by_name_actual(test_data) def test_property_search_by_phone(self): # 提取测试信息的配置文件 test_info = FileUtil.get_excel('..\\data\\case_data_conf.ini', 'property_search_by_phone') for info in test_info: test_data = info['case_params'] try: actual = self.pm.get_property_search_by_phone_actual(test_data) self.ca.equal(actual, info) except Exception as e: error_msg = traceback.format_exc() info['error_msg'] = error_msg self.ca.error(info) time.sleep(2) def teardown_class(self): UiUtil.get_driver().get('http://172.16.9.129:8080/SharedParkingPlace/') if __name__ == '__main__': pmt = PropertyManageTest() pmt.test_property_search_by_phone()<file_sep>/自动化代码/WTFV1/conf/element_attr.ini [login] name = ('ID','uname') password = ('<PASSWORD>') imgcode = ('ID','imgcode') button = ('ID','button') actual = ('CLASS_NAME','dropdown-toggle') [lessor_homepage] iframe = ('ID','testIframe') add_stall =('CLASS_NAME','glyphicon.glyphicon-plus') stall_number =('XPATH','//*[@id="parkinginfo"]/div/div/div[2]/div[1]/div[3]/input') size_id = ('XPATH','//*[@id="parkinginfo"]/div/div/div[2]/div[2]/div[3]/input') location_id = ('XPATH','//*[@id="parkinginfo"]/div/div/div[2]/div[3]/div[3]/input') address = ('XPATH','//*[@id="parkinginfo"]/div/div/div[2]/div[4]/div[3]/input') add_confirm_button = ('XPATH','//*[@id="parkinginfo"]/div/div/div[3]/button[1]') add_stall_result = ('XPATH','//*[@id="main"]/div[3]/div[2]/div/div/div[2]/h3') delete_stall_button = ('XPATH','//*[@id="main"]/div[3]/div[2]/div/div/div[2]/p[4]/a[2]') modify_button = ('XPATH','//*[@id="main"]/div[2]/div[2]/div/div/div[2]/p[4]/a[1]') modify_confirm_button = ('XPATH','//*[@id="parkinginfo"]/div/div/div[3]/button[1]') modify_stall_result = ('XPATH','//*[@id="main"]/div[2]/div[2]/div/div/div[2]/h3') [lessor_order_history] order_history = ('LINK_TEXT','历史订单') iframe = ('ID','testIframe') search_type = ('XPATH','/html/body/div[1]/div/div[2]/select[1]') status = ('XPATH','//*[@id="status"]') search_button = ('XPATH','/html/body/div[1]/div/div[2]/button') status_search_result = ('CSS_SELECTOR','tr.text-center:nth-child(2) > td:nth-child(5)') time_search_result = ('XPATH','/html/body/div[1]/table[1]/tbody/tr[2]/td[3]') [property_manage] user_management = ('CLASS_NAME','panel-title.panel-with-icon') info_property = ('XPATH','//*[@id="_easyui_tree_5"]') info_rentuser = ('XPATH','//*[@id="_easyui_tree_3"]') property_iframe = ('XPATH','/html/body/div[2]/div[2]/div/div[2]/div[2]/div/iframe') add_property_button = ('CLASS_NAME','l-btn-icon.icon-add') change_property_button = ('XPATH','/html/body/div[1]/div[2]/div[1]/a[3]/span/span[1]') property_name = ('ID','_easyui_textbox_input1') property_phone = ('ID','_easyui_textbox_input2') property_introduce = ('XPATH','//*[@id="_easyui_textbox_input3"]') property_credential = ('XPATH','//*[@id="_easyui_textbox_input4"]') property_password = ('XPATH','//*[@id="_<PASSWORD>"]') add_button = ('XPATH','/html/body/div[2]/div[3]/a[1]/span/span[1]') change_button = ('XPATH','/html/body/div[2]/div[3]/a[2]/span/span[1]') add_property_actual =('XPATH','/html/body/div[6]/div[2]') input_search_property_name = ('XPATH','//*[@id="_easyui_textbox_input6"]') input_search_rent_name = ('XPATH','//*[@id="_easyui_textbox_input1"]') search_enter = ('XPATH','/html/body/div[1]/div[2]/div[1]/span/span/a') property_search_by_name_actual = ('XPATH','//*[@id="datagrid-row-r1-2-0"]/td[2]/div') open_property_select_method = ('XPATH','/html/body/div[1]/div[2]/div[1]/span/a/span') open_rent_select_method = ('XPATH','/html/body/div[1]/div[2]/div[1]/span/a/span/span[1]') click_property_select_phone = ('XPATH','/html/body/div[5]/div[3]/div') click_rent_select_phone = ('XPATH','/html/body/div[2]/div[3]/div') input_property_search_phone = ('XPATH','//*[@id="_easyui_textbox_input6"]') input_rent_search_phone = ('XPATH','//*[@id="_easyui_textbox_input1"]') property_search_by_phone_actual = ('XPATH','/html/body/div[1]/div[2]/div[2]/div[2]/div[2]/table/tbody/tr/td[4]/div') rent_by_name_actual = ('XPATH','//*[@id="datagrid-row-r1-2-0"]/td[3]/div') rent_search_by_phone_actual = ('XPATH','/html/body/div[1]/div[2]/div[2]/div[2]/div[2]/table/tbody/tr/td[4]/div') click_property_square = ('CLASS_NAME','datagrid-cell-check') property_actual = ('XPATH','/html/body/div[6]/div[2]') [tenants_order] search = ('XPATH','//*[@id="suggestId"]') rush_purchase =('XPATH','//*[@id="myModal"]/div/div/div[2]/table/tbody/tr[2]/td[5]/button[1]') iframe =('XPATH','//*[@id="testIframe"]') confirm =('XPATH','//*[@id="myModal"]/div/div/div[3]/button') text =('XPATH','//*[@id="myModal"]/div/div/div[2]/table/tbody') stall_number =('XPATH','//*[@id="parkinginfo"]/div/div/div[2]/div[1]/div[3]/input') size_id = ('XPATH','//*[@id="parkinginfo"]/div/div/div[2]/div[2]/div[3]/input') location_id = ('XPATH','//*[@id="parkinginfo"]/div/div/div[2]/div[3]/div[3]/input') address = ('XPATH','//*[@id="parkinginfo"]/div/div/div[2]/div[4]/div[3]/input') add_button = ('XPATH','//*[@id="parkinginfo"]/div/div/div[3]/button[1]') add_stall_actual = ('XPATH','//*[@id="noticemessage"]') [personal_information] personal_information =('XPATH','//*[@id="header"]/div/div[3]/ul/li[3]/a') iframe =('XPATH','//*[@id="testIframe"]') change_information =('XPATH','//*[@id="main"]/div[2]/div[1]/div/div/div[1]/div[2]/div[1]/h3/button[1]') amend_uname =('CSS_SELECTOR','#uname') amend_uphone_number =('CSS_SELECTOR','#phone') affirm_change =('CSS_SELECTOR','#userinfo > div > div > div.modal-body > div.modal-footer > button.btn.btn-primary') text =('XPATH','//*[@id="main"]/div[2]/div[1]/div/div/div[1]/div[2]') [comment] order_history = ('XPATH','//*[@id="header"]/div/div[3]/ul/li[2]/a') iframe =('XPATH','//*[@id="testIframe"]') query_method = ('XPATH','/html/body/div[1]/div/div[2]/select[1]') select_status = ('XPATH','//*[@id="status"]') click_seek = ('XPATH','/html/body/div[1]/div/div[2]/button') comment = ('XPATH','/html/body/div[1]/table[1]/tbody/tr[2]/td[6]/button[2]') input_comment = ('XPATH','//*[@id="content"]') send_comment = ('XPATH','//*[@id="commment"]') text =('XPATH','//*[@id="remarkModel"]/div/div/div[2]/div/ul/li[1]/div/div[2]/div[1]') [chenge_binding] personal_information =('XPATH','//*[@id="header"]/div/div[3]/ul/li[3]/a') iframe =('XPATH','//*[@id="testIframe"]') chenge_binding = ('XPATH','//*[@id="main"]/div[2]/div[1]/div/div/div[2]/div[2]/div/h3/div/div/button[1]') input_account = ('XPATH','//*[@id="bindalipay"]') commit_changes = ('XPATH','//*[@id="account"]/div/div/div[2]/div[1]/button[2]') text =('XPATH','//*[@id="main"]/div[2]/div[1]/div/div/div[2]/div[2]/div/h3/div/div/p[3]')<file_sep>/自动化代码/WTFV1/action/api_lessor.py from WTFV1.tools.api_util import ApiUtil class ApiLessor: def __init__(self): # 获取session self.session = ApiUtil.get_session() # 获取cookie ApiUtil.set_cookie(self.session) self.session.get('http://172.16.9.129:8080/SharedParkingPlace/login?uname=出租方1&upass=123&imgcode=0000') def api_add_stall(self, url, data): add_stall_resp = self.session.post(url, data) return add_stall_resp.text def api_query_order_info(self, url): query_order_info_resp = self.session.get(url) return query_order_info_resp.text def api_query_comment(self, url): query_comment_resp = self.session.get(url) return query_comment_resp.text if __name__ == '__main__': al = ApiLessor() # # url =' http://172.16.9.129:8080/SharedParkingPlace/admin/auditsManagement/parkinginformation/' # data = {'parkingnumber': '123', 'parkingstatus': '1', 'uid': '6ade98f4-a14c-4bf0-a993-8ca936030245', # 'parkingsizeid':'1', 'locationid': '4531', 'detailslocation': '第五国际'} # print(al.api_add_stall(url, data))<file_sep>/自动化代码/WTFV1/tools/report.py from WTFV1.tools.comm_util import DBUtil, LogUtil, TimeUtil class Report: # 日志对象 logger = LogUtil.get_logger('report') # 数据库对象 db = DBUtil('db_conn_result_info') @classmethod def generate_html_test_report(cls, table, version, app_name): """ 把数据库的内容写到HTML文件中 :param table: 数据库的表名 :param version: 版本号 :param app_name: 报告 """ # 获取当前版本的所有数据 sql = f'select * from {table} where case_version = "{version}"' result = cls.db.sql_execute(sql) if len(result) == 0: cls.logger.info('没有该版本的测试结果') return # 打开HTML模板 with open('..\\tools\\template.html', encoding='utf8') as rf: contents = rf.read() base_sql = f'select count(*) from {table} where case_version = "{version}" and result_msg=' # 统计pass fail error 的个数的sql语句 count_success_sql = base_sql + "\"test_pass\"" count_fail_sql = base_sql + "\"test_fail\"" count_error_sql = base_sql + "\"test_error\"" # 统计pass fail error 的个数 count_success = cls.db.sql_execute(count_success_sql)[0][0] count_fail = cls.db.sql_execute(count_fail_sql)[0][0] count_error = cls.db.sql_execute(count_error_sql)[0][0] # 获取执行的时间 last_time_sql = f"""SELECT case_time FROM {table} where case_version="{version}" ORDER BY case_time DESC LIMIT 0,1""" last_time = cls.db.sql_execute(last_time_sql)[0][0] test_data = str(last_time).split(' ')[0] test_time = str(last_time).split(' ')[1] # 对固定的内容进行替换 contents = contents.replace('$test-date', test_data) contents = contents.replace('$test-version', version) contents = contents.replace('$pass-count', str(count_success)) contents = contents.replace('$fail-count', str(count_fail)) contents = contents.replace('$error-count', str(count_error)) contents = contents.replace('$last-time', test_time) test_result = '' for content in result: if content[10] == 'test_pass': color = 'green' elif content[10] == 'test_fail': color = 'yellow' else: color = 'red' test_result += f"""<tr height="40"> <td width="7%">{str(content[0])}</td> <td width="9%">{content[3]}</td> <td width="9%">{content[4]}</td> <td width="7%">{content[2]}</td> <td width="20%">{content[7]}</td> <td width="7%" bgcolor={color}>{content[10]}</td> <td width="16%">{content[11]}</td> <td width="15%">{content[12]}</td> <td width="10%"><a href={content[13]}>查看截图</a></td> </tr>""" contents = contents.replace('$test-result', test_result) # 写HTML文件 report_name = f'../report/{app_name}{version}版测试报告_{TimeUtil.get_time_file()}.html' with open(report_name, 'w', encoding="utf8") as wf: wf.write(contents) if __name__ == '__main__': Report.generate_html_test_report('spp_test_result', 'v1.0', 'spp') <file_sep>/自动化代码/WTFV1/action/tenant_change_binding.py """ 命名规定: 定位元素的要进行输入的内容名字为:元素名字_v (value) 定位元素的配置文件提取的内容名字:元素名字_a (attr) 定位元素去执行的find的名字为:元素名字_e (element) """ from WTFV1.action.login import LoginAction from WTFV1.tools.ui_util import UiUtil from WTFV1.tools.comm_util import FileUtil import time class ChengeBinding: def __init__(self): self.driver = UiUtil.get_driver() LoginAction().do_login('抢租客0', '123', '0000') self.ui = UiUtil() self.ele = FileUtil.trans_ini_tuple_to_dict('..\\conf\\element_attr.ini', 'chenge_binding') def examine_personal_information(self): time.sleep(0.5) order_history_a = eval(self.ele['personal_information']) order_history = self.ui.find_element(self.driver, order_history_a) self.ui.click(order_history) # 跳转ifream def skip_iframe(self): time.sleep(1) iframe_a = eval(self.ele['iframe']) iframe_e = self.ui.find_element(self.driver, iframe_a) self.ui.skip_iframe(self.driver, iframe_e) def click_chenge_binding(self): time.sleep(0.5) chenge_binding_a = eval(self.ele['chenge_binding']) chenge_binding = self.ui.find_element(self.driver, chenge_binding_a) self.ui.click(chenge_binding) def input_account(self,binding): time.sleep(0.5) input_account_a = eval(self.ele['input_account']) input_account_e = self.ui.find_element(self.driver, input_account_a) self.ui.input(input_account_e,binding) def commit_changes(self): time.sleep(0.5) commit_changes_a = eval(self.ele['commit_changes']) commit_changes = self.ui.find_element(self.driver, commit_changes_a) self.ui.click(commit_changes) def get_text(self): time.sleep(5) get_text_a = eval(self.ele['text']) get_text_e = self.ui.find_element(self.driver, get_text_a) text = self.ui.get_text(get_text_e) return text def do_chenge_binding(self,data): self.examine_personal_information() self.skip_iframe() self.click_chenge_binding() self.input_account(data["account"]) self.commit_changes() self.driver.refresh() self.examine_personal_information() self.skip_iframe() a = self.get_text() self.driver.refresh() if data["account"] in a: actual = "变更绑定成功" else: actual = "变更绑定失败" return actual if __name__ == '__main__': binding = {'account': '112233'} a = ChengeBinding() print(a.do_chenge_binding(binding)) <file_sep>/自动化代码/WTFV1/action/tenant_homepage.py """ 命名规定: 定位元素的要进行输入的内容名字为:元素名字_v (value) 定位元素的配置文件提取的内容名字:元素名字_a (attr) 定位元素去执行的find的名字为:元素名字_e (element) """ from WTFV1.action.login import LoginAction from WTFV1.tools.ui_util import UiUtil, GetDesignatedPageElement import time class LessorHomepage: def __init__(self): self.driver = UiUtil.get_driver() LoginAction().do_login('抢租客0', '123', '0000') self.ui = UiUtil() self.e = GetDesignatedPageElement(self.driver, '..\\conf\\element_attr.ini', 'tenants_order') # 通过页面元素无法定位到,采用图像识别,点击红色表示点, def click_red_dot(self): time.sleep(2.5) self.ui.click_image('..\\image\\test01.png') # 跳转ifream def skip_iframe(self): time.sleep(1) iframe_e = self.e.get_element('iframe') self.ui.skip_iframe(self.driver, iframe_e) # 获取车位信息列表以供后面断言 def get_text(self): time.sleep(1) text_e = self.e.get_element('text') return text_e.text # 点击抢购按钮 def rush_purchase(self): time.sleep(1) purchase_e = self.e.get_element('rush_purchase') self.ui.click(purchase_e) # 点击下单按钮 def do_confirm(self): time.sleep(1) self.ui.click_image('..\\image\\test02.png') def do_rush_purchase(self): self.click_red_dot() self.skip_iframe() a = self.get_text() self.rush_purchase() self.do_confirm() self.click_red_dot() b = self.get_text() if a != b: actual = "下单成功" else: actual = "下单失败" return actual if __name__ == '__main__': a = LessorHomepage() a.do_rush_purchase() # print(LessorHomepage().get_add_stall_actual('2345', '1', '4200', '第五国际')) <file_sep>/自动化代码/WTFV1/action/api_login.py from WTFV1.tools.api_util import ApiUtil class ApiLogin: def __init__(self): # 获取session self.session = ApiUtil.get_session() # 获取cookie ApiUtil.set_cookie(self.session) def api_login(self, url): login_resp = self.session.get(url) return login_resp.text if __name__ == '__main__': al = ApiLogin() print(al.api_login('http://172.16.9.129:8080/SharedParkingPlace/login?uname=出租方1&upass=123&imgcode=0000')) <file_sep>/自动化代码/WTFV1/testcase/gui_page_close_test.py from WTFV1.tools.ui_util import UiUtil class GuiCloseTest: def test_cloes(self): driver = UiUtil.get_driver() driver.close() <file_sep>/自动化代码/WTFV1/action/tenant_personal_information.py """ 命名规定: 定位元素的要进行输入的内容名字为:元素名字_v (value) 定位元素的配置文件提取的内容名字:元素名字_a (attr) 定位元素去执行的find的名字为:元素名字_e (element) """ from WTFV1.action.login import LoginAction from WTFV1.tools.ui_util import UiUtil from WTFV1.tools.comm_util import FileUtil import time class PersonalInformation: def __init__(self): self.driver = UiUtil.get_driver() LoginAction().do_login('抢租客0', '123', '0000') self.ui = UiUtil() self.ele = FileUtil.trans_ini_tuple_to_dict('..\\conf\\element_attr.ini', 'personal_information') def examine_personal_information(self): time.sleep(0.5) order_history_a = eval(self.ele['personal_information']) order_history = self.ui.find_element(self.driver, order_history_a) self.ui.click(order_history) # 跳转ifream def skip_iframe(self): time.sleep(1) iframe_a = eval(self.ele['iframe']) iframe_e = self.ui.find_element(self.driver, iframe_a) self.ui.skip_iframe(self.driver, iframe_e) def change_information(self): time.sleep(0.5) order_history_a = eval(self.ele['change_information']) order_history_e = self.ui.find_element(self.driver, order_history_a) self.ui.click(order_history_e) def amend_uname(self,uname): time.sleep(0.5) uname_a = eval(self.ele['amend_uname']) uname_e = self.ui.find_element(self.driver, uname_a) self.ui.input(uname_e,uname) def amend_uphone_number(self,pnumber): time.sleep(0.5) uname_a = eval(self.ele['amend_uphone_number']) uname_e = self.ui.find_element(self.driver, uname_a) self.ui.input(uname_e,pnumber) def affirm_change(self): time.sleep(0.5) order_history_a = eval(self.ele['affirm_change']) order_history_e = self.ui.find_element(self.driver, order_history_a) self.ui.click(order_history_e) def get_text(self): time.sleep(5) order_history_a = eval(self.ele['text']) order_history_e = self.ui.find_element(self.driver, order_history_a) text = self.ui.get_text(order_history_e) return text def do_change_information(self,data): self.examine_personal_information() self.skip_iframe() self.change_information() self.amend_uname(data["uname"]) self.amend_uphone_number(data["pnumber"]) self.affirm_change() self.driver.refresh() self.examine_personal_information() self.skip_iframe() a = self.get_text() self.driver.refresh() if data["uname"] and data["pnumber"] in a: actual = "修改成功" else: actual = "修改失败" return actual if __name__ == '__main__': uname = "抢租客1" pnumber = "17296313549" data = {"uname":"抢租客1","pnumber":"17296313549"} a = PersonalInformation() print(a.do_change_information(data)) <file_sep>/自动化代码/WTFV1/start/start.py from WTFV1.tools.comm_util import FileUtil class Start: def do_start(self): """ 获取测试脚本一起执行 :return: """ # 读取测试脚本的配置文件 test_class_name = FileUtil.get_txt('..\\conf\\test_class_names.txt') for class_name in test_class_name: # 判断不以#开头的 if not class_name.startswith('#'): # 把路径和类名分开 temp = class_name.split(' ') # 返回模块名对应的模块对象 module_obj = __import__(temp[0], fromlist=temp[1]) if hasattr(module_obj, temp[1]): # 模块对象反射 class_obj = getattr(module_obj, temp[1]) # 获取类下面的所有方法 contents = dir(class_obj) # 把方法都放入字典 method_dict = {} # 测试方法所需要的列表 test_method = [] for content in contents: if content == 'setup': method_dict['setup'] = content if content == 'teardown': method_dict['teardown'] = content if content == 'setup_class': method_dict['setup_class'] = content if content == 'teardown_class': method_dict['teardown_class'] = content if content.startswith('test_'): test_method.append(content) method_dict['test_method'] = test_method c = class_obj() if 'setup_class' in method_dict.keys(): if hasattr(c, method_dict['setup_class']): getattr(c, method_dict['setup_class'])() for method_name in method_dict['test_method']: if 'setup' in method_dict.keys(): if hasattr(c, method_dict['setup']): getattr(c, method_dict['setup'])() if hasattr(c, method_name): getattr(c, method_name)() if 'teardown' in method_dict.keys(): if hasattr(c, method_dict['teardown']): getattr(c, method_dict['teardown'])() if 'teardown_class' in method_dict.keys(): if hasattr(c, method_dict['teardown_class']): getattr(c, method_dict['teardown_class'])() if __name__ == '__main__': Start().do_start()<file_sep>/自动化代码/WTFV1/testcase/api_login_test.py import time from WTFV1.action.api_login import ApiLogin from WTFV1.tools.comm_util import FileUtil, CustomAssert class ApiLoginTest: def setup_class(self): # 一个模块 self.al = ApiLogin() # 获取基本url信息 self.base_url = FileUtil.get_ini_value('..\\conf\\base.ini', 'api_info', 'base_url') # 获取版本号 self.version = FileUtil.get_version('..\\data\\spp_case_api.xlsx', 'caseinfo') # 获取断言实例化 self.ca = CustomAssert(self.version, 'spp_test_result') def test_api_login(self): test_info = FileUtil.get_excel('..\\data\\api_case_data_conf.ini', 'login') for info in test_info: login_url = self.base_url + info['api_uri'] actual = self.al.api_login(login_url) self.ca.contain(actual, info) time.sleep(2) if __name__ == '__main__': alt = ApiLoginTest() alt.setup() alt.test_api_login()<file_sep>/自动化代码/WTFV1/data/test_result.sql /* Navicat MySQL Data Transfer Source Server : 旧电脑 Source Server Version : 50650 Source Host : 172.16.9.129:3306 Source Database : test_result Target Server Type : MYSQL Target Server Version : 50650 File Encoding : 65001 Date: 2021-01-12 21:33:43 */ SET FOREIGN_KEY_CHECKS=0; -- ---------------------------- -- Table structure for spp_test_result -- ---------------------------- DROP TABLE IF EXISTS `spp_test_result`; CREATE TABLE `spp_test_result` ( `rid` int(11) NOT NULL AUTO_INCREMENT, `case_version` varchar(20) NOT NULL, `case_id` varchar(50) NOT NULL, `module_name` varchar(50) NOT NULL, `test_type` varchar(20) NOT NULL, `api_url` varchar(100) DEFAULT NULL, `request_method` varchar(20) DEFAULT NULL, `case_desc` varchar(200) DEFAULT NULL, `case_params` varchar(200) DEFAULT NULL, `expect` varchar(100) DEFAULT NULL, `case_time` datetime NOT NULL, `error_msg` varchar(100) DEFAULT NULL, `error_img_path` varchar(100) DEFAULT NULL, PRIMARY KEY (`rid`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; -- ---------------------------- -- Records of spp_test_result -- ---------------------------- <file_sep>/自动化代码/WTFV1/testcase/api_lessor_test.py import time from WTFV1.tools.comm_util import FileUtil, CustomAssert from WTFV1.action.api_lessor import ApiLessor class ApiLessorTest: def setup_class(self): # 一个模块 self.al = ApiLessor() # 获取基本url信息 self.base_url = FileUtil.get_ini_value('..\\conf\\base.ini', 'api_info', 'base_url') # 获取版本号 self.version = FileUtil.get_version('..\\data\\spp_case_api.xlsx', 'caseinfo') # 获取断言实例化 self.ca = CustomAssert(self.version, 'spp_test_result') def test_add_stall(self): test_info = FileUtil.get_excel('..\\data\\api_case_data_conf.ini', 'add_stall') for info in test_info: add_stall_url = self.base_url + info['api_uri'] add_stall_data = info['case_params'] actual = self.al.api_add_stall(add_stall_url, add_stall_data) self.ca.equal(actual, info) time.sleep(2) def test_query_order_info(self): test_info = FileUtil.get_excel('..\\data\\api_case_data_conf.ini', 'query_comment') for info in test_info: query_order_info_url = self.base_url + info['api_uri'] actual = self.al.api_query_comment(query_order_info_url) self.ca.contain(actual, info) time.sleep(2) def test_query_comment(self): test_info = FileUtil.get_excel('..\\data\\api_case_data_conf.ini', 'query_comment') for info in test_info: query_comment_url = self.base_url + info['api_uri'] actual = self.al.api_query_comment(query_comment_url) self.ca.contain(actual, info) time.sleep(2) <file_sep>/自动化代码/WTFV1/data/api_case_data_conf.ini [login] test_data_path=..\data\spp_case_api.xlsx sheet_name=login start_row=1 end_row=8 [add_stall] test_data_path=..\data\spp_case_api.xlsx sheet_name=lessor start_row=1 end_row=11 [query_order_info] test_data_path=..\data\spp_case_api.xlsx sheet_name=lessor start_row=11 end_row=12 [query_comment] test_data_path=..\data\spp_case_api.xlsx sheet_name=lessor start_row=12 end_row=13 <file_sep>/自动化代码/WTFV1/action/lessor_order_history.py """ 命名规定: 定位元素的要进行输入的内容名字为:元素名字_v (value) 定位元素的配置文件提取的内容名字:元素名字_a (attr) 定位元素去执行的find的名字为:元素名字_e (element) """ from WTFV1.action.login import LoginAction from WTFV1.tools.ui_util import UiUtil, GetDesignatedPageElement import time class LessorOrderHistory: """ 出租方历史订单 """ def __init__(self): self.driver = UiUtil.get_driver() LoginAction().do_login('222', '123', '0000') self.ui = UiUtil() self.e = GetDesignatedPageElement(self.driver, '..\\conf\\element_attr.ini', 'lessor_order_history') self.click_order_history() time.sleep(5) self.skip_iframe() # 点击历史订单 def click_order_history(self): order_history_e = self.e.get_element('order_history') self.ui.click(order_history_e) # 跳转iframe def skip_iframe(self): iframe_e = self.e.get_element('iframe') self.ui.skip_iframe(self.driver, iframe_e) # 选择订单查询类型 def select_search_type(self, type_v): search_type_e = self.e.get_element('search_type') self.ui.select_drop_down_box(search_type_e, type_v) # 选择类型对应的状态值 def select_order_status(self, status_v): status_e = self.e.get_element('status') self.ui.select_drop_down_box(status_e, status_v) # 点击搜索按钮 def click_search_button(self): search_button_e = self.e.get_element('search_button') self.ui.click(search_button_e) # 按状态去执行搜索 def do_status_order_search(self, type_v, status_v): self.select_search_type(type_v) self.select_order_status(status_v) self.click_search_button() # 获取按状态去执行搜索,返回"搜索成功"或者"搜索失败" def get_status_order_search_result(self, type_v, status_v): self.do_status_order_search(type_v, status_v) time.sleep(2) status_search_result_e = self.e.get_element('status_search_result') result = self.ui.get_text(status_search_result_e) time.sleep(5) if result == status_v: actual = "搜索成功" else: actual = "搜索失败" return actual # 选择账单时间 def select_order_time(self, time1): js_code = f'''document.querySelector('input[id="time"]').value='{time1}';''' self.ui.execute_js(self.driver, js_code) # 按账单时间去执行搜索 def do_time_order_search(self, type_v, time1): self.select_search_type(type_v) self.select_order_time(time1) self.click_search_button() # 按账单时间去执行搜索,返回"搜索成功"或者"搜索失败" def get_time_order_search_result(self, type_v, time1): self.do_time_order_search(type_v, time1) time.sleep(2) time_search_result_e = self.e.get_element('time_search_result') result = self.ui.get_text(time_search_result_e) if result[0:4] in time1: actual = "搜索成功" else: actual = "搜索失败" return actual if __name__ == '__main__': run = LessorOrderHistory() # print(run.get_status_order_search_result('按状态查询', '已完成')) print(run.get_time_order_search_result('按时间查询', '2019-06-26')) <file_sep>/自动化代码/WTFV1/action/property_manage.py from WTFV1.action.login import LoginAction from WTFV1.tools.ui_util import UiUtil, GetDesignatedPageElement import time import json class PropertyManage: def __init__(self): self.driver = UiUtil.get_driver() LoginAction().do_login('物业0', '123', '0000') self.ui = UiUtil() self.e = GetDesignatedPageElement(self.driver, '..\\conf\\element_attr.ini', 'property_manage') self.click_user_management_button() self.click_info_property_button() self.skip_iframe() # 点击用户管理 def click_user_management_button(self): user_management_e = self.e.get_element('user_management') self.ui.select_by_js(self.driver, user_management_e) # 点击物业方信息 def click_info_property_button(self): info_property_e = self.e.get_element('info_property') self.ui.select_by_js(self.driver, info_property_e) # 点击抢租客信息 def click_info_rentuser_button(self): info_rentuser_e = self.e.get_element('info_rentuser') self.ui.select_by_js(self.driver, info_rentuser_e) # 跳转iframe def skip_iframe(self): iframe_e = self.e.get_element('property_iframe') self.ui.skip_iframe(self.driver, iframe_e) # 点击物业方的增加按钮 def click_add_property_button(self): add_property_button_e = self.e.get_element('add_property_button') self.ui.click(add_property_button_e) # 点击物业方修改的按钮 def click_change_property_button(self): change_button_e = self.e.get_element('change_property_button') self.ui.click(change_button_e) # 输入物业名 def input_property_name(self, name): property_name_e = self.e.get_element('property_name') self.ui.input(property_name_e,name) # 输入用户电话 def input_property_phone(self, phone): user_phone_e = self.e.get_element('property_phone') self.ui.input(user_phone_e,phone) # 输入物业简介 def input_property_introduce(self, introduce): property_introduce_e = self.e.get_element('property_introduce') self.ui.input(property_introduce_e, introduce) # 输入物业证书 def input_property_credential(self, credential): property_credential_e = self.e.get_element('property_credential') self.ui.input(property_credential_e, credential) # 输入物业密码 def input_property_password(self, password): property_password_e = self.e.get_element('property_password') self.ui.input(property_password_e, password) # 物业方确认增加信息的按钮 def click_add_button(self): add_button_e = self.e.get_element('add_button') self.ui.click(add_button_e) # 物业方确认修改信息的按钮 def click_change_button(self): change_button_e = self.e.get_element('change_button') self.ui.click(change_button_e) # 增加物业的所有动作集 def do_add_property(self, data): self.click_add_property_button() self.input_property_name(data['property_name']) self.input_property_phone(data['property_phone']) self.input_property_introduce(data['property_intro']) self.input_property_credential(data['property_cred']) self.input_property_password(data['property_pwd']) self.click_add_button() # 增加物业用例的断言 def get_add_property_actual(self, data): self.do_add_property(data) time.sleep(2) actual_e = self.e.get_element('add_property_actual') content = self.ui.get_text(actual_e) if content == "增加成功": actual = "增加成功" else: actual = "增加失败" return actual # 输入要搜索的物业方姓名 def input_search_name(self, name): input_search_property_name_e = self.e.get_element('input_search_property_name') self.ui.input(input_search_property_name_e, name) # 输入要搜索的抢租客的姓名 def input_search_rent_name(self,name): input_search_rent_name_e = self.e.get_element('input_search_rent_name') self.ui.input(input_search_rent_name_e, name) # 点击放大镜图标进行搜索 def click_search_enter(self): search_enter_e = self.e.get_element('search_enter') self.ui.click(search_enter_e) # 勾选物业方页面第一个方块 def click_property_square(self): property_square_e = self.e.get_element('click_property_square') self.ui.click(property_square_e) # 通过名字进行搜索动作集 def do_property_search_by_name(self, data): # self.click_user_management_button() # self.click_info_property_button() # self.skip_iframe() self.input_search_name(data['property_name']) self.click_search_enter() # 通过姓名搜索的断言 def get_property_search_by_name_actual(self, data): self.do_property_search_by_name(data) time.sleep(3) actual_e = self.e.get_element('property_search_by_name_actual') time.sleep(1) result = self.ui.get_text(actual_e) # time.sleep(1) if result == data['property_name']: actual = "查找成功" else: actual = "查找失败" return actual # 物业方鼠标悬浮打开下拉框 def open_property_select_method(self): open_property_select_method_e = self.e.get_element('open_property_select_method') self.ui.mouse_hover(self.driver,open_property_select_method_e) # 出租方鼠标悬浮打开下拉框 def open_rent_select_method(self): open_rent_select_method_e = self.e.get_element('open_rent_select_method') self.ui.mouse_hover(self.driver,open_rent_select_method_e) # 物业方在下拉框打开后选择电话 def click_property_select_phone(self): click_property_select_phone_e = self.e.get_element('click_property_select_phone') self.ui.click(click_property_select_phone_e) # 抢租客方在下拉框打开后选择电话 def click_rent_select_phone(self): click_rent_select_phone_e = self.e.get_element('click_rent_select_phone') self.ui.click(click_rent_select_phone_e) # 物业方输入要搜索的电话号码 def input_property_search_phone(self, phone): input_property_search_phone_e = self.e.get_element('input_property_search_phone') self.ui.input(input_property_search_phone_e, phone) # 抢租客输入要搜索的电话号码 def input_rent_search_phone(self, phone): input_rent_search_phone_e = self.e.get_element('input_rent_search_phone') self.ui.input(input_rent_search_phone_e, phone) #根据电话搜索物业方的动作集 def do_property_search_by_phone(self,data): # self.click_user_management_button() # self.click_info_property_button() # self.skip_iframe() self.open_property_select_method() self.click_property_select_phone() time.sleep(2) # self.input_property_search_phone(int(data['property_phone'])) self.input_property_search_phone(data) self.click_search_enter() # 物业方信息通过电话搜索的断言 def get_property_search_by_phone_actual(self, data): data1 = int(data['property_phone']) # print(data1) self.do_property_search_by_phone(data1) time.sleep(3) actual_e = self.e.get_element('property_search_by_phone_actual') time.sleep(2) result = self.ui.get_text(actual_e) if result == data['property_phone']: actual = '查找成功' else: actual = '查找失败' return actual #抢租客信息,根据姓名搜索的动作集 def do_search_rent_by_name(self,name): self.click_user_management_button() self.click_info_rentuser_button() self.skip_iframe() self.input_search_rent_name(name) self.click_search_enter() # 抢租客信息通过名字搜索的断言 def get_rent_search_by_name_actual(self, name): self.do_search_rent_by_name(name) time.sleep(3) actual_e = self.e.get_element('rent_by_name_actual') time.sleep(5) result = self.ui.get_text(actual_e) if result == name: actual = '根据姓名搜索抢租客成功' else: actual = '根据姓名搜索抢租客失败' return actual # 根据电话搜索抢租客的动作集 def do_rent_search_by_phone(self,phone): self.click_user_management_button() self.click_info_rentuser_button() self.skip_iframe() self.open_rent_select_method() self.click_rent_select_phone() self.input_rent_search_phone(phone) self.click_search_enter() # 抢租客信息通过电话搜索的断言 def get_rent_search_by_phone_actual(self, phone): self.do_rent_search_by_phone(phone) time.sleep(3) actual_e = self.e.get_element('rent_search_by_phone_actual') time.sleep(5) result = self.ui.get_text(actual_e) if result == phone: actual = '根据电话搜索抢租客信息成功' else: actual = '根据电话搜索抢租客信息失败' return actual # 修改物业方用户信息的动作集 def do_property_change_info(self, data): # self.click_user_management_button() # self.click_info_property_button() # self.skip_iframe() self.input_search_name(data['property_name']) self.click_search_enter() time.sleep(3) self.click_property_square() self.click_change_property_button() self.input_property_name(data['property_name']) self.input_property_phone(data['property_phone']) self.input_property_introduce(data['property_intro']) self.input_property_credential(data['property_cred']) self.click_change_button() # 物业方修改用户信息的断言 def get_property_change_phone_actual(self, data): self.do_property_change_info(data) time.sleep(5) actual_e = self.e.get_element('property_actual') result = self.ui.get_text(actual_e) if result == "修改成功": actual = "修改成功" else: actual = "修改失败" return actual if __name__ == '__main__': # print(PropertyManage().get_add_property_actual("物业000","18799990000","jianjie","zhengshu","11111")) # print(PropertyManage().get_property_search_by_name_actual('物业7777')) # print(PropertyManage().get_property_search_by_phone_actual('15304440333')) # print(PropertyManage().get_rent_search_by_name_actual("周友")) print(PropertyManage().get_rent_search_by_phone_actual("15802792107")) # print(PropertyManage().get_property_change_phone_actual() <file_sep>/自动化代码/WTFV1/conf/base.ini [db_info] db_conn_api_info = ('172.16.9.129','3306','root','123456','team1') db_conn_result_info =('172.16.9.129','3306','root','123456','test_result') [ui_info] browser = ('Chrome') login_page = ('http://172.16.9.129:8080/SharedParkingPlace') [api_info] base_url = ('http://172.16.9.129:8080') login_page_url = ('http://172.16.9.129:8080/SharedParkingPlace/image')
6cdfce524455c7f258611a1a0aa84312f7ef8257
[ "SQL", "Python", "INI" ]
27
INI
excellentteam007/spp
b43fadf1ef9bdaee3db712429b7a52b44c08dd81
06dcd627a331ea1a98f7f09284cea6a44ae7476b
refs/heads/master
<repo_name>gondesiasha/service<file_sep>/src/app/movies/movies.component.ts import { Component, OnInit,Output,EventEmitter } from '@angular/core'; import { movieService} from '../app.service'; import { HttpClient } from '@angular/common/http'; @Component({ selector: 'app-movies', templateUrl: './movies.component.html', styleUrls: ['./movies.component.scss'] }) export class MoviesComponent implements OnInit { theatre; constructor(private service:movieService, private http:HttpClient) { } movies=[]; @Output() public arr = new EventEmitter ; postList(id) { console.log(id); this.http.post('http://localhost:9000/api/theatres', id) .subscribe((res) => { this.theatre = res; this.arr.emit(this.theatre); //console.log(this.theatre); // console.log(this.theatre) }, error => { console.log(error); }); } ngOnInit() { this.service.getmovies().subscribe(data1 =>this.movies=data1); } } <file_sep>/src/app/app.module.ts import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import { AppComponent } from './app.component'; import { MoviesComponent } from './movies/movies.component'; import { TheatresComponent } from './theatres/theatres.component'; import { BookingComponent } from './booking/booking.component'; import { TicketComponent } from './ticket/ticket.component'; import { HttpClientModule } from '@angular/common/http'; import { movieService } from '../app/app.service'; @NgModule({ declarations: [ AppComponent, MoviesComponent, TheatresComponent, BookingComponent, TicketComponent ], imports: [ BrowserModule, HttpClientModule ], providers: [movieService], bootstrap: [AppComponent] }) export class AppModule { } <file_sep>/src/app/theatres/theatres.component.ts import { Component, OnInit,Input } from '@angular/core'; import { movieService} from '../app.service'; import { HttpClient } from '@angular/common/http'; import { MoviesComponent } from '../movies/movies.component'; @Component({ selector: 'app-theatres', templateUrl: './theatres.component.html', styleUrls: ['./theatres.component.scss'] }) export class TheatresComponent{ // constructor(private service:movieService) { } constructor(private http:HttpClient){ } // theatre:any; // theatres=[]; // ngOnInit() { // this.service.postList("").subscribe(data1 =>this.theatres=data1); // } @Input() arr1; }
c2bd14b763cb8ce5299dc8ae2ae270df839f5eea
[ "TypeScript" ]
3
TypeScript
gondesiasha/service
f13b5bcfdac86a0526dca793bf249d3ef0d1ee59
92d5ba26edb136c2da3d219ac7769d4c77412db5
refs/heads/master
<repo_name>rrogerr/getting_and_cleaning_data_course_project<file_sep>/README.md # getting_and_cleaning_data_course_project ## General The script "run_analysis.R" contained in this repo transforms into a tidy dataset the data from the following study: http://archive.ics.uci.edu/ml/datasets/Human+Activity+Recognition+Using+Smartphones The output of the script is composed by four data frames: * total_df * mean_std * means_ag * means_ag_by_subject See explanations below. In the aforementioned study, human subjects performed different physical activities carrying a smartphone. The quantities contained in these datasets are the raw and processed measurements of the smartphones' accelerometers. The raw data set obtained was randomly partitioned into two groups: * train: composed by 70% of subjects * test: composed by 30% of subjects The four data frames produced by our script are an attempt to summarize and merge the two aforementioned data sets. The two first columns are common to our four data sets: * subject_ID: Identifies with a number from 1 to 30 the subject/volunteer who performed the activity whose measurements are recorded in the same row. * act_label: Identifies with a literal label the type of activity that the subject was performing when the measurements were made. Levels: WALKING, WALKING_UPSATAIRS, WALKING_DOWNSTAIRS, SITTING, STANDING, LAYING. What follows is an explanation of the specifics of each output data frame. ##total_df It's the result of merging the train and test datasets. Hence, it contains data from all of the subjects. Each row is a 563 variables observation, the first two variables being the subject_ID and the act_label. The names of the rest of the variables begin with one of the following prefixes: * tBodyAcc-XYZ * tGravityAcc-XYZ * tBodyAccJerk-XYZ * tBodyGyro-XYZ * tBodyGyroJerk-XYZ * tBodyAccMag * tGravityAccMag * tBodyAccJerkMag * tBodyGyroMag * tBodyGyroJerkMag * fBodyAcc-XYZ * fBodyAccJerk-XYZ * fBodyGyro-XYZ * fBodyAccMag * fBodyAccJerkMag * fBodyGyroMag * fBodyGyroJerkMag where: * "t" indicates that it's a time domain variable and "f" indicates it's a frequency domain variable. * "body" indicates translational acceleration (in units of g) and "gyro" indicates angular speed (radians/second). Note: there are exceptions of variables with the "body" or "gyro" infixes that have different units from the mentioned before. * "Jerk" indicates the derivative of acceleration (units of g per second). * "Gravity" indicates the gravity signal that was separated from the "body" acceleration using a low-pass filter. * X, Y or Z indicates the axis of the phone along which the measurements were made. The aformentioned variable names end with one of the following suffixes: * mean(): Mean value * std(): Standard deviation * mad(): Median absolute deviation * max(): Largest value in array * min(): Smallest value in array * sma(): Signal magnitude area * energy(): Energy measure. Sum of the squares divided by the number of values. * iqr(): Interquartile range * entropy(): Signal entropy * arCoeff(): Autorregresion coefficients with Burg order equal to 4 * correlation(): correlation coefficient between two signals * maxInds(): index of the frequency component with largest magnitude * meanFreq(): Weighted average of the frequency components to obtain a mean frequency * skewness(): skewness of the frequency domain signal * kurtosis(): kurtosis of the frequency domain signal * bandsEnergy(): Energy of a frequency interval within the 64 bins of the FFT of each window. * angle(): Angle between to vectors. NOTE: When running the script, the "()" are systematically replaced by ".." for formatting reasons. Examples: * fBodyAccMag-kurtosis() refers to the kurtosis of the FFT of the magnitude of the body acceleration. Since Kurtosis is calculated using standarized forms of the distribution, this variable is unitless. The same thing happens with the skewness() variables. * tBodyAccMag-energy() has units of the square of body acceleration. ## mean_std It's composed only by columns from total_df that contain mean or standard deviation calculations of any magnitude in any domain. Examples: * fBodyAccMag-kurtosis() and tBodyAccMag.energy() columns are ___not___ contained in mean_std * tBodyGyro-mean()-Z and fBodyGyro-std()-X are contained in mean_std This data frame was created with the aid of grepl() function, which enabled us to identify the variable names that contained either the word "mean" or "std" to select those columns. ## means_agg It's contains the means of each variable by subject and by activity. IMPORTANT: Though the variable names are the same as those of total_df, in means_agg the variables represent means. This data frame was created with the aid of the aggregate() function, that enabled us to calculate the mean of all variables for each unique pair of subject_ID, act_label pair of values. ## means_agg_by_subject means_agg has its data sorted by act_label, while means_agg_by_subject has its data sorted by subject_ID. This data frame was created from means_agg with a very straight-forward sorting method. <file_sep>/run_analysis.R setwd("/home/rogelio/Desktop/datasciencecoursera/Getting_and_Cleaning_Data_project/UCI HAR Dataset") ######################### IMPORT TRAIN DATA ########################## subject_label <- read.table("./train/subject_train.txt") activity_identifier <- read.table("./train/y_train.txt") x_train <- read.table("./train/X_train.txt") str_x <- "./train/Inertial Signals/body_acc_x_train.txt" str_y <- "./train/Inertial Signals/body_acc_y_train.txt" str_z <- "./train/Inertial Signals/body_acc_z_train.txt" body_acc_x <- read.table(str_x) body_acc_y <- read.table(str_y) body_acc_z <- read.table(str_z) modif_str_x <- gsub("acc", "gyro", str_x) modif_str_y <- gsub("acc", "gyro", str_y) modif_str_z <- gsub("acc", "gyro", str_z) body_gyro_x <- read.table(modif_str_x) body_gyro_y <- read.table(modif_str_y) body_gyro_z <- read.table(modif_str_z) modif_str_x <- gsub("body", "total", str_x) modif_str_y <- gsub("body", "total", str_y) modif_str_z <- gsub("body", "total", str_z) total_x <- read.table(modif_str_x) total_y <- read.table(modif_str_y) total_z <- read.table(modif_str_z) ######################### IMPORT TEST DATA ########################### subject_label1 <- read.table("./test/subject_test.txt") activity_identifier1 <- read.table("./test/y_test.txt") x_train1 <- read.table("./test/X_test.txt") str_x1 <- "./test/Inertial Signals/body_acc_x_test.txt" str_y1 <- "./test/Inertial Signals/body_acc_y_test.txt" str_z1 <- "./test/Inertial Signals/body_acc_z_test.txt" body_acc_x1 <- read.table(str_x1) body_acc_y1 <- read.table(str_y1) body_acc_z1 <- read.table(str_z1) modif_str_x1 <- gsub("acc", "gyro", str_x1) modif_str_y1 <- gsub("acc", "gyro", str_y1) modif_str_z1 <- gsub("acc", "gyro", str_z1) body_gyro_x1 <- read.table(modif_str_x1) body_gyro_y1 <- read.table(modif_str_y1) body_gyro_z1 <- read.table(modif_str_z1) modif_str_x1 <- gsub("body", "total", str_x1) modif_str_y1 <- gsub("body", "total", str_y1) modif_str_z1 <- gsub("body", "total", str_z1) total_x1 <- read.table(modif_str_x1) total_y1 <- read.table(modif_str_y1) total_z1 <- read.table(modif_str_z1) ######################## VARIABLE LABELS ############################# data_names <- read.table("./features.txt") activity_labels <- read.table("./activity_labels.txt") ###################################################################### ######################## TRAIN DATASET ############################### # setting descriptive names for the column that contains the # subjects' labels names(subject_label) <- c("subject_ID") # descriptive activity names obtained from file "activity_labels.txt" act_label <- activity_labels[unlist(activity_identifier),][[2]] act_label <- as.data.frame(act_label) # naming x_train data with the labels from features.txt names(x_train) <- data_names[[2]] # assembling train data frame train_df <- data.frame(subject_label, act_label, x_train) ######################## TEST DATASET ################################ # setting descriptive names for the column that contains the # subjects' labels names(subject_label1) <- c("subject_ID") # descriptive activity names obtained from file "activity_labels.txt" act_label <- activity_labels[unlist(activity_identifier1),][[2]] act_label1 <- as.data.frame(act_label) # naming x_train data with the labels from features.txt names(x_train1) <- data_names[[2]] # assembling test data frame test_df <- data.frame(subject_label1, act_label1, x_train1) ######################## MERGE DATASETS ############################## # merge train and test datasets total_df <- merge(train_df, test_df, all = TRUE) ################# EXTRACT STD AND MEAN MEASUREMENTS ################## mean_std <- total_df[ , grepl("mean|std|subject_ID|act_label", names(total_df))] ################### MEAN BY SUBJECT AND ACTIVITY ##################### means_agg <- aggregate(. ~ subject_ID + act_label, data = mean_std, FUN= "mean" ) # means_ag data frame is sorted by activity, the following sorts it # by subject_ID means_agg_by_subject <- means_agg[order(means_agg$subject_ID),] write.table(means_agg_by_subject, "./means_aggregate.txt", row.names = FALSE)
56ce19e4bf5edad137f6d67666cd3f59531494b2
[ "Markdown", "R" ]
2
Markdown
rrogerr/getting_and_cleaning_data_course_project
137b27c010f1867ea5584b86ac812ce966bb2707
160bf3c1eb8e69c4d2824ed702fe08641177803a
refs/heads/master
<file_sep>EMAIL_BACKEND = "django.core.mail.backends.smtp.EmailBackend" EMAIL_HOST = "{{host}}" EMAIL_HOST_USER = "{{address}}" EMAIL_HOST_PASSWORD = "{{<PASSWORD>}}" EMAIL_PORT = 587 EMAIL_USE_TLS = True DEFAULT_FROM_EMAIL="{{address}}" <file_sep>import sys from fabric.api import env, sudo, run, cd, local, put, prefix, roles, execute, task from fabric.api import settings as fab_settings try: from geonodes import GEONODE_INSTANCES as GN except Exception, e: print "Warning: Could not import GEONODE_INSTANCES from geonodes.py. Is the file missing?" sys.exit(1) def _build_env(target): if target in GN: GNT = GN[target] e = { 'user': GNT['user'], 'hosts': [GNT['host']], 'host_string': GNT['host'], 'key_filename': GNT['ident'], } return e else: print "Could not initialize environment for target {t}.".format(t=target) return None def _run_task(task, args=None, kwargs=None): from fabfile import targets if targets: for target in targets: env = _build_env(target) if env: with fab_settings(** env): _run_task_core(task, args, kwargs) else: _run_task_core(task, args, kwargs) def _run_task_core(task, args, kwargs): if task: if args: task(* args) elif kwargs: task(** kwargs) else: task() def _cron_command(f, u, c, filename): template = 'echo "{f} {u} {c}" > /etc/cron.d/{filename}' cmd = template.format(f=f, u=u, c=c, filename=filename) return cmd def _load_template(filename): data = None with open ('templates/'+filename, "r") as f: data = f.read() return data def _request_input(question, value, required, options=None): if value: return value else: if options: print question+" :" print "* Options Below."+(" Enter to skip." if not required else "") for opt in options: print "| -- "+opt print "* Select option:", else: print question+":", if required: value = None while not value: value = raw_input() if not value: print "Value required. Please try again. Ctrl+C to cancel." print question+":", elif options and (not value in options): print "Must select one of the options. Ctrl+C to cancel." print question+":", value = None return value else: while not value: value = raw_input() if not value: return None elif options and (not value in options): print "Must select one of the options. Enter to skip. Ctrl+C to cancel." print question+":", value = None return value def _request_continue(): print "Continue (y/n)?", confirm = raw_input() return confirm and confirm.lower() == "y" def _append_to_file(lines, filename): print "Appending to file..." print "" sudo("echo '' >> {f}".format(f=filename)) for line in lines: t = "echo '{line}' >> {f}" c = t.format(line=line.replace('"','\"'), f=filename) sudo(c) <file_sep>import os def lookupValue(value, arg): result = value for key in arg.split("."): result = result[key] return result def lastPath(value): return os.path.basename(os.path.normpath(value)) class FilterModule(object): filter_map = { 'lookupValue': lookupValue, 'lastPath':lastPath } def filters(self): return self.filter_map <file_sep>ANALYTICS_DAP_ENABLED = True ANALYTICS_DAP_AGENCY = "{{agency}}" ANALYTICS_DAP_SUBAGENCY = "{{subagency}}" <file_sep>from urlparse import urlparse # scheme://netloc/path;parameters?query#fragment def fqdn(value): uri = urlparse(value) return uri.netloc def hostname(value): uri = urlparse(value) return uri.hostname def port(value): uri = urlparse(value) return uri.port # ---- Ansible filters ---- class FilterModule(object): ''' URL manipulation filters ''' filter_map = { 'fqdn': fqdn, 'hostname': hostname, 'port': port } def filters(self): if urlparse: return self.filter_map else: return {} <file_sep>#!/bin/bash # # uwsgi - This script starts and stops all configured uwsgi applications # # chkconfig: - 85 15 # description: uWSGI is a program to run applications adhering to the # Web Server Gateway Interface. # processname: uwsgi # config: /etc/sysconfig/uwsgi # Source function library. . /etc/rc.d/init.d/functions # Source networking configuration. . /etc/sysconfig/network # Check that networking is up. [ "$NETWORKING" = "no" ] && exit 0 uwsgi="/usr/bin/uwsgi" prog=$(basename "$uwsgi") UWSGI_CONF_DIR="/etc/uwsgi" UWSGI_LOG="/var/log/uwsgi.log" PIDFILE="/var/run/uwsgi.pid" UWSGI_ARGS="--emperor $UWSGI_CONF_DIR --pidfile $PIDFILE --daemonize $UWSGI_LOG --uid uwsgi --gid uwsgi --emperor-stats :8001" if [ -f /etc/sysconfig/uwsgi ]; then . /etc/sysconfig/uwsgi fi each_action() { action=$1 code=0 case "$action" in condrestart|try-restart) rh_status "$f" 2>/dev/null && restart "$f" ;; force-reload|restart) stop "$f" start "$f" ;; reload) reload "$f" ;; start) start "$f" ;; status) rh_status "$f" ;; status_q) rh_status "$f" >/dev/null 2>&1 ;; stop) stop "$f" ;; esac retval=$? if [ $retval -gt $code ]; then code=$retval fi return $code } reload() { echo -n "Reloading uWSGI ... " killproc -p "$PIDFILE" "$prog" -HUP retval=$? echo return $retval } start() { echo -n "Starting uWSGI ... " daemon $uwsgi $UWSGI_ARGS retval=$? echo return $retval } rh_status() { status -p "$PIDFILE" "$prog" } stop() { echo -n "Stopping uWSGI ... " killproc -p "$PIDFILE" "$prog" retval=$? echo return $retval } case $1 in condrestart|force_reload|reload|restart|start|status|status_q|stop|try-restart) each_action "$1" ;; *) echo "Usage: $0 {condrestart|reload|restart|start|status|stop}" exit 2 ;; esac exit $? <file_sep>GEONODE_TYPES = { "vanilla": "vanilla", "geoshape": "geoshape" } ISO_CATEGORIES = { "biota": "biota", "boundaries": "boundaries", "climatologyMeteorologyAtmosphere": "climatologyMeteorologyAtmosphere", "economy": "economy", "elevation": "elevation", "environment": "environment", "farming": "farming", "geoscientificInformation": "geoscientificInformation", "health": "health", "imageryBaseMapsEarthCover": "imageryBaseMapsEarthCover", "inlandWaters": "inlandWaters", "intelligenceMilitary": "intelligenceMilitary", "location": "location", "oceans": "oceans", "planningCadastre": "planningCadastre", "society": "society", "structure": "structure", "transportation": "transportation", "utilitiesCommunication": "utilitiesCommunication" } <file_sep># GeoNode DevOps (geonode-devops) DevOps tools for developing & deploying [GeoNode](http://geonode.org/), including [Ansible](https://www.ansible.com/), [Packer](https://www.packer.io/), [Vagrant](https://www.vagrantup.com/), and [Fabric](http://www.fabfile.org/) configuration files for building and managing Ubuntu and CentOS GeoNode boxes. After following the installation steps, continue to [Launch](#launch) section to start up GeoNode. # Installation On the control/host machine, you'll need to install [Ansible](https://www.ansible.com/), [Packer](https://www.packer.io/), [Vagrant](https://www.vagrantup.com/), and [Fabric](http://www.fabfile.org). **Quick Install** If you wish to use a python virtual environment on your host/control machine, be sure to install `virutalenv` and `virtualenvwrapper`. Your `~/.bash_aliases` file should look something like the following: ``` export VIRTUALENVWRAPPER_PYTHON=/usr/bin/python export WORKON_HOME=~/.venvs source /usr/local/bin/virtualenvwrapper.sh export PIP_DOWNLOAD_CACHE=$HOME/.pip-downloads ``` To quickly install [Ansible](https://www.ansible.com/) and [Fabric](http://www.fabfile.org), run the following: ``` sudo apt-get install python-dev # if not already installed sudo easy_install pip # if pip is not already installed sudo pip install virtualenv virtualenvwrapper # cd into project directory sudo pip install -r requirements.txt ``` ## Ansible Ansible is an agent-less provisioning tool for managing the state of machines. It is used by both [Packer](https://www.packer.io/) and [Vagrant](https://www.vagrantup.com/). By sharing a common Ansible `playbook` for configuring production machines, building test boxes via Packer, and development boxes for Vagrant, we're able to have dev-prod parity. To get [Ansible](https://www.ansible.com/) follow the relevant section below. Also see http://docs.ansible.com/ansible/intro_installation.html#getting-ansible for more information. #### Mac OS X & Ubuntu ``` sudo easy_install pip # if pip is not already installed sudo pip install ansible ``` ## Packer [Packer](https://www.packer.io/) can be used to build virtual machine images. #### Mac OS X ``` sudo mkdir -p /opt/packer/bin cd /opt/packer/ sudo wget https://releases.hashicorp.com/packer/0.10.0/packer_0.10.0_darwin_amd64.zip sudo unzip packer_0.10.0_darwin_amd64.zip sudo mv packer /opt/packer/bin cd /usr/local/bin/ sudo ln -s /opt/packer/bin/packer packer ``` #### Ubuntu ``` sudo mkdir -p /opt/packer/bin cd /opt/packer/ sudo wget 'https://releases.hashicorp.com/packer/0.10.0/packer_0.10.0_linux_amd64.zip' sudo unzip packer_0.10.0_linux_amd64.zip sudo mv packer /opt/packer/bin cd /usr/bin/ sudo ln -s /opt/packer/bin/packer packer ``` ## Fabric [Fabric](http://www.fabfile.org/) provides an easy command line interface for executing remote shell commands and for transferring files between machines. Fabric is extremely useful for transferring files and managing remote servers. Follow directions at http://www.fabfile.org/installing.html to install fabric or follow shortcuts below. #### Mac OS X & Ubuntu ``` sudo pip install fabric ``` Once fabric is installed, create a `geonodes.py` file in the same directory as the `fabfile.py`. `geonodes.py` is in `.gitignore` so will not be committed. This file includes connection and other information, so that fab commands are streamlined. ```javascript GEONODE_INSTANCES = { "devgeonode": { "ident": "~/auth/keys/devgeonode.pem", "host": "dev.geonode.example.com", "user": "ubuntu", "type": "geoshape" }, "prodgeonode": { "ident": "~/auth/keys/prodgeonode.pem", "host": "prod.geonode.example.com", "user": "ubuntu", "type": "geoshape" } } ``` # Usage Create a `secret.yml` file in the project root. ## Vagrant To add the Centos 6.4 vagrant box to your control machine, run: ``` vagrant box add --name "centos/6.4" http://developer.nrel.gov/downloads/vagrant-boxes/CentOS-6.4-x86_64-v20131103.box ``` To add an Ubuntu 16.04 LTS ("Xenial") vagrant box to your control machine, run: ``` vagrant box add bento/ubuntu-16.04 ``` Do no use `ubuntu/xenial64` from Ubuntu cloud images, as referenced here: https://bugs.launchpad.net/cloud-images/+bug/1569237. To launch the GeoNode virtual machine run: ``` vagrant up ``` To re-provision the machine run: ``` vagrant provision ``` ## Packer You can also use [Packer](https://www.packer.io/) to build a virtual machine. To build a base box for CentOS 6.4, run: ``` packer build -var 'ansible_playbook=ansible/centos_base.yml' -var 'ansible_secret=secret.yml' -var 'ansible_os=centos' packer/centos64.json ``` To build a base box for Ubuntu 16.04, run: ``` packer build -var 'ansible_playbook=ansible/ubuntu_base.yml' -var 'ansible_secret=secret.yml' -var 'ansible_os=ubuntu' packer/ubuntu1604.json ``` #### Adding Your New Box After you created your box, you can add with: ``` vagrant box add --name "geonode_base" packer_virtualbox-ovf_virtualbox.box ``` Add the box to the [Vagrantfile](https://github.com/pjdufour/geonode-devops/blob/master/Vagrantfile) to provision with it. ## Launch Once the image is provisioned, ssh into the machine via: ``` # cd into geonode-devops.git directory vagrant ssh ``` Once in the virtual machine, run: ``` workon geonode cd geonode paver stop paver reset_hard paver setup paver start -b 0.0.0.0:8000 # Launches Django and GeoServer. Listens to all addresses on port 8000. ``` If the fixtures are not loaded, use the following: ``` python manage.py loaddata geonode/base/fixtures/initial_data.json ``` ## Fabric [Fabric](http://www.fabfile.org/) provides an easy command line interface for executing remote shell commands and for transferring files between machines. For GeoNode, Fabric can be used to import large files, `updatelayers`, manage GeoServer restart cron jobs, and backup a remote GeoNode locally. To get started, change directory (`cd`) into the main fabric directory (`./fabric`) with the `fabfile.py`. When you call fab, start with `gn:geonodehost` so that the host and identity key are loaded automatically from `geonodes.py`. To see a list of tasks run: ``` fab -l ``` To see the long description of a task run: ``` fab -d taskname ``` A few examples: ``` fab gn:devgeonode,prodgeonode lsb_release fab gn:devgeonode inspect_geoshape fab gn:devgeonode restart_geoshape fab gn:prodgeonode updatelayers:t=geoshape fab gn:prodgeonode importlayers:t=geoshape,local=~/data/*.zip,drop=/opt/drop,user=admin,overwrite=1,private=1 fab gn:prodgeonode addgmail_geoshape:email,password fab gn:prodgeonode cron_restart_geoserver:'00 04 * * *' fab gn:prodgeonode backup_geonode:t=geoshape,remote=/opt/backups/20150707,local=~/backups ``` <file_sep>ANALYTICS_GA_ENABLED = True ANALYTICS_GA_CODE = "{{code}}" <file_sep>ansible fabric git+git://github.com/pjdufour/python-cli-util.git@master <file_sep>import os import glob import datetime from subprocess import Popen, PIPE from pythoncliutil import cron_command, request_input, request_continue from fabric.api import env, sudo, run, cd, local, put, prefix, roles, execute, task, get from fabric.api import settings as fab_settings from fabric.context_managers import settings, hide from fabric.contrib.files import sed from utils import _build_env, _run_task, _cron_command, _request_input, _request_continue, _append_to_file, _load_template from enumerations import GEONODE_TYPES, ISO_CATEGORIES global targets targets = () PATH_ACTIVATE = "/var/lib/geonode/bin/activate" PATH_MANAGEPY_VN = "/var/lib/geonode" PATH_MANAGEPY_GS = "/var/lib/geonode/rogue_geonode" PATH_DNA_JSON = "/opt/chef-run/dna.json" PATH_LS_VN = "/var/lib/geonode/local_settings.py" PATH_LS_GS = "/var/lib/geonode/rogue_geonode/geoshape/local_settings.py" PATH_GEOSERVER_DATA = "/var/lib/geoserver_data" ############################################################# # The Public API @task def gn(*args): """ Load GeoNode settings from geonodes.py Imports GeoNode settings from a geonodes.py file in the same directory """ global targets targets = args @task def host_type(*args): return _run_task(_host_type, args=args) @task def lsb_release(*args): return _run_task(_lsb_release, args=args) ## GeoSever @task def restart_geoserver(*args): return _run_task(_restart_geoserver, args=args) @task def cron_restart_geoserver(frequency): return _run_task(_cron_restart_geoserver, args=[frequency]) ## Vanilla @task def updatelayers_vanilla(*args): return _run_task(_updatelayers_vanilla, args=args) ## GeoSHAPE @task def provision_geoshape(*args): """ Provision a GeoSHAPE instance Runs `cybergis-scripts-rogue.sh prod provision` """ return _run_task(_provision_geoshape, args=args) @task def restart_geoshape(*args): """ Restart GeoSHAPE instance, including Django, GeoServer, and RabbitMQ Calls ./stop_geonode and ./start_geonode, restarts tomcat7, and resets RabbitMQ """ return _run_task(_restart_geoshape, args=args) @task def inspect_geoshape(*args): return _run_task(_inspect_geoshape, args=args) @task def updatelayers_geoshape(*args): return _run_task(_updatelayers_geoshape, args=args) @task def importlayers(t=None, local=None, drop=None, user=None, overwrite=None, category=None, keywords=None, private=None): """ Import local files into a GeoNode instance Puts via SFTP local files into the remote's "drop" folder and then runs importlayers on all of them. Options: t = GeoNode Type (Vanilla or GeoSHAPE) local = local file path drop = temporary drop folder user = the user that will own the layer overwrite = overwrite existing layers category = ISO Category for layer keywords = comma separated list of keywords private = Is layer only visible to owner and admins? """ return _run_task(_importlayers, kwargs={'t':t, 'local':local, 'drop': drop, 'user': user, 'overwrite': overwrite, 'category': category, 'keywords': keywords, 'private': private}) @task def add_gmail(t=None, u=None, p=None): """ Adds server GMail to instance Adds GMail settings to vim /var/lib/geonode/rogue_geonode/geoshape/local_settings.py """ address = _request_input("User", u, True)+'<EMAIL>' host = 'smtp.gmail.com' return _run_task(_add_email, args=None, kwargs={'t':t, 'a':address, 'p':p, 'h':host}) @task def add_analytics_ga(t=None, c=None): return _run_task(_add_analytics_ga, args=None, kwargs={'t':t, 'c':c}) @task def add_analytics_dap(t=None, a=None, sa=None): return _run_task(_add_analytics_dap, args=None, kwargs={'t':t, 'a':a, 'sa':sa}) @task def backup_geonode(t=None, remote=None, local=None): """ Backup GeoNode to disk Backs up GeoNode to the destination "d" folder on disk. Options: t = GeoNode Type (Vanilla or GeoSHAPE) remote = remote folder to backup to (required) local = local folder to backup to (optional) """ return _run_task(_backup_geonode, args=None, kwargs={'t':t, 'remote':remote, 'local':local}) ############################################################# # The Private API def _host_type(): run('uname -s') def _lsb_release(): run('lsb_release -c') def _host_type(): run('uname -s') def _restart_geoserver(): sudo('/etc/init.d/tomcat7 restart') def _cron_restart_geoserver(frequency): cmd = _cron_command(f=frequency, u ='root', c='/etc/init.d/tomcat7 restart', filename='geoserver_restart') print cmd sudo(cmd) def _restart_apache2(): sudo('/etc/init.d/apache2 restart') def _restart_nginx(): sudo('/etc/init.d/nginx restart') def _restart_rabbitmq(): sudo('rabbitmqctl stop_app') sudo('rabbitmqctl reset') sudo('rabbitmqctl start_app') def _restart_geoshape(): with cd("/var/lib/geonode/rogue_geonode/scripts"): sudo('./stop_geonode.sh') sudo('./start_geonode.sh') _restart_geoserver() _restart_rabbitmq() def _inspect_geoshape(): sudo('lsb_release -c') sudo('cat '+PATH_DNA_JSON) sudo('tail -n 20 /var/log/kern.log') def _updatelayers_vanilla(): _updatelayers(PATH_MANAGEPY_VN, PATH_ACTIVATE) def _updatelayers_geoshape(): _updatelayers(PATH_MANAGEPY_GS, PATH_ACTIVATE) def _updatelayers(current_directory, activate): with cd(current_directory): t = "source {a}; python manage.py updatelayers" c = t.format(a=activate) sudo(c) def _importlayers(t=None, local=None, drop=None, user=None, overwrite=None, category=None, keywords=None, private=None): t = _request_input("Type (vanilla/geoshape)", t, True, options=GEONODE_TYPES) local = _request_input("Local File Path", local, True) drop = _request_input("Remote Drop Folder", drop, True) user = _request_input("User", user, False) overwrite = _request_input("Overwrite", overwrite, False) category = _request_input("Category", category, False, options=ISO_CATEGORIES) keywords = _request_input("Keywords (Comma-separated)", keywords, False) private = _request_input("Private", private, True) path_managepy = PATH_MANAGEPY_GS if t.lower()=="geoshape" else PATH_MANAGEPY_VN if _request_continue(): sudo("[ -d {d} ] || mkdir {d}".format(d=drop)) remote_files = put(local, drop, mode='0444', use_sudo=True) if remote_files: with cd(path_managepy): template = "source {a}; python manage.py importlayers {paths}" if user: template += " -u {u}".format(u=user) if overwrite: template += " -o" if category: template += " -c {c}".format(c=category) if keywords: template += " -k {kw}".format(kw=keywords) if private: template += " -p" c = template.format(a=PATH_ACTIVATE, paths=(" ".join(remote_files))) sudo(c) else: print "Not files uploaded" def _provision_geoshape(): sudo('cat '+PATH_DNA_JSON) sudo("cybergis-scripts-rogue.sh prod provision") def _add_email(t=None, a=None, p=None, h=None): data = _load_template('settings_email.py') if data: t = _request_input("Type (vanilla/geoshape)", t, True, options=GEONODE_TYPES) a = _request_input("Address (e.g., <EMAIL>)", a, True) p = _request_input("Password", p, True) h = _request_input("Host (e.g., smtp.gmail.com)", h, True) ls = PATH_LS_GS if t.lower()=="geoshape" else PATH_LS_VN data = data.replace("{{address}}", a) data = data.replace("{{password}}", p) data = data.replace("{{host}}", h) print "Local Settings: "+ls print "Data..." print data if _request_continue(): _append_to_file(data.split("\n"), ls) def _add_analytics_dap(t=None, a=None, sa=None): data = _load_template('settings_dap.py') if data: t = _request_input("Type (vanilla/geoshape)", t, True, options=GEONODE_TYPES) a = _request_input("Agency", a, True) sa = _request_input("Sub-agency", sa, True) ls = PATH_LS_GS if t.lower()=="geoshape" else PATH_LS_VN data = data.replace("{{agency}}", a) data = data.replace("{{subagency}}", sa) print "Local Settings: "+ls print "Data..." print data if _request_continue(): _append_to_file(data.split("\n"), ls) def _add_analytics_ga(t=None, c=None): data = _load_template('settings_ga.py') if data: t = _request_input("Type (vanilla/geoshape)", t, True, options=GEONODE_TYPES) c = _request_input("Code", c, True) ls = PATH_LS_GS if t.lower()=="geoshape" else PATH_LS_VN data = data.replace("{{code}}", c) print "Local Settings: "+ls print "Data..." print data if _request_continue(): _append_to_file(data.split("\n"), ls) def _backup_geonode(t=None, remote=None, local=None): t = _request_input("Type (vanilla/geoshape)", t, True, options=GEONODE_TYPES) remote = _request_input("Remote Destination Folder", remote, True) local = _request_input("Local File Path", local, False) if _request_continue(): print "Backing up data..." sudo("[ -d {d} ] || mkdir {d}".format(d=remote)) sudo("[ -d {d}/db ] || mkdir {d}/db".format(d=remote)) sudo('chown -R {u}:{g} {d}/db'.format(u="postgres", g="postgres", d=remote)) with settings(sudo_user='postgres'): sudo('pg_dump geonode | gzip > {d}/db/geonode.gz'.format(d=remote)) sudo('pg_dump geonode_imports | gzip > {d}/db/geonode_imports.gz'.format(d=remote)) sudo('cp -R {gsd} {d}/geoserver'.format(gsd=PATH_GEOSERVER_DATA, d=remote)) if local: local_files = get(remote, local_path=local) for local_file in local_files: print "Downloaded Local File: "+local_file print "Backup complete."
5cf912af3e5627dee37b2a162d816adda13bdfcf
[ "Markdown", "Python", "Text", "Shell" ]
11
Python
pjdufour/geonode-devops
342b842c6e47463d3735a4e18bf3a6cc0f15d4e7
5314688089d5e8f7247697f2e914e7e7c2704ea4
refs/heads/master
<file_sep># AI & Cloud Assignment 4 <ul> <li> Group 1 </li> <li> Contributors: Yongyi(Nikki)Zhao, <NAME>, <NAME></li> </ul> ## Overview <p> CNN Tweets sentiment model training </p > ## Details #### enviorment you need to change: 1. train directory 2. validation directory 3. test directory. 4. dictionary directory. #### Our enviroenment is as following: ```sh os.environ["SM_CHANNEL_TRAIN"] = r"C:\Users\hewei\Desktop\ai_hw4\noon_0222\Archive\SM_CHANNEL_TRAIN" ``` ```sh os.environ["SM_CHANNEL_VALIDATION"] = r"C:\Users\hewei\Desktop\ai_hw4\noon_0222\Archive\SM_CHANNEL_VALIDATION" ``` ```sh os.environ["SM_CHANNEL_EVAL"] = r"C:\Users\hewei\Desktop\ai_hw4\noon_0222\Archive\SM_CHANNEL_EVAL" ``` ```sh os.environ["SM_MODEL_DIR"] = r"C:\Users\hewei\Desktop\ai_hw4\noon_0222\Archive\SM_MODEL_DIR" ``` <span style="color:blue"> Due to git capacity issue, we didn't upload glove dictionary, but you can click the link in Reference Matrial Section to download the dictionary and run locally </span> ## Requirements <ul> <li> Python (3.6, 3.7) </li> <li> TensorFlow v1.13 </li> </ul> ## Reference Matrial - [Twitter GloVe Dict](https://twitter-text.s3.amazonaws.com/training/data/glove.twitter.27B.25d.txt) ## Discussion and Development <p> Most development discussion is taking place on github in this repo.</p > ## Contributing to Tweets Preprocessing Library <p> Any contributions, bug reports, bug fixes, documentation improvements, enhancements to make this project better are warmly welcomed. </p > <file_sep>""" Model definition for CNN sentiment training """ import os import tensorflow as tf import numpy as np from tensorflow.keras.preprocessing import sequence # from tensorflow import keras from tensorflow.keras.models import Sequential # from tensorflow.keras.layers import Embedding # from tensorflow.keras import layers from tensorflow.keras.layers import Dense from tensorflow.keras.layers import Convolution1D, GlobalMaxPooling1D def keras_model_fn(_, config): """ Creating a CNN model for sentiment modeling """ ''' layer1: embedding layer ''' input_length = config["padding_size"] input_dim = config["embeddings_dictionary_size"] output_dim = config["embeddings_vector_size"] f = open(config["embeddings_path"],encoding='utf8') glove = f.readlines()[:input_dim] f.close() embedding_matrix = np.zeros((input_dim, output_dim)) for i in range(input_dim): if len(glove[i].split()[1:]) != output_dim: continue embedding_matrix[i] = np.asarray(glove[i].split()[1:], dtype='float32') embedding_layer = Embedding(input_dim, output_dim, weights=[embedding_matrix],input_length=input_length, trainable=True) cnn_model = Sequential() cnn_model.add(embedding_layer) """ Layer2: Convolution1D layer """ cnn_model.add(Convolution1D( filters=100, kernel_size=2, input_shape=(input_length, input_dim), strides=1, padding='valid', activation='relu' )) """ Layer3: GlobalMaxPool1D layer """ cnn_model.add(GlobalMaxPooling1D()) """ Layer4: Dense layer """ cnn_model.add(Dense(units=100, activation='relu')) """ Layer5: Dense layer """ cnn_model.add(Dense(units=1, activation='sigmoid')) adam = keras.optimizers.Adam(lr=0.001, beta_1=0.9, beta_2=0.999, epsilon=None, decay=0.0, amsgrad=False) #cnn_model.compile(loss='binary_cprssentropy', opitmizer='adam', metrics=['accuracy']) cnn_model.compile('adam', loss='binary_crossentropy', metrics=['accuracy']) return cnn_model def save_model(model, output): """ Method to save models in SaveModel format with signature to allow for serving """ tf.saved_model.save(model, os.path.join(output, "1")) print("Model successfully saved at: {}".format(output)) <file_sep>tensorflow==1.14 numpy==1.16.2 boto3
30ef13f65fe43c07adeead278fda4d46deddfaa3
[ "Markdown", "Python", "Text" ]
3
Markdown
yanghw180/ai-hw4
473eec6a0c28d411ac05d3eb31959f9746668cc5
46de9a198d39c8e1edf66f38d9572d38670983ac
refs/heads/master
<file_sep>package data import ( "github.com/jinzhu/gorm" _ "github.com/jinzhu/gorm/dialects/mysql" ) type User2 struct { Id int `json:id` ScreenName string `json:screen_name` } func (m *User2) TableName() string { return "user" } type UserRepository2 struct { } func NewUserRepository2() *UserRepository2 { return &UserRepository2{} } func (*UserRepository2) GetUser(id int) *User2 { DBMS := "mysql" USER := "root" PASS := "" PROTOCOL := "tcp(127.0.0.1:3307)" DBNAME := "hkanali" CONNECT := USER + ":" + PASS + "@" + PROTOCOL + "/" + DBNAME db, err := gorm.Open(DBMS, CONNECT) if err != nil { panic(err.Error()) } //db.SingularTable(true) defer db.Close() user2 := User2{} user2.Id = id db.First(&user2) return &user2 } <file_sep>package main import ( "fmt" "strconv" "github.com/gin-gonic/gin" "github.com/hkanali/letitgo/data" ) func main() { r := gin.Default() r.GET("/test1", func(c *gin.Context) { i, _ := strconv.Atoi(c.Query("id")) repo := data.NewUserRepository() result := repo.GetUser(i) c.JSON(200, result) }) r.GET("/test2", func(c *gin.Context) { i, _ := strconv.Atoi(c.Query("id")) repo := data.NewUserRepository2() result := repo.GetUser(i) c.JSON(200, result) }) r.GET("/test3", func(c *gin.Context) { i, _ := strconv.Atoi(c.Query("id")) repo := data.NewUserRepository3() result := repo.GetUser(i) c.JSON(200, result) }) r.GET("/test4", func(c *gin.Context) { i, _ := strconv.Atoi(c.Query("id")) repo := data.NewUserRepository4() result := repo.GetUser(i) c.JSON(200, result) }) // init dependencies // repository := domain.NewUserRepositoryImpl() // service := service.NewUserService(repository) service := InitializeUserService() serviceMock := InitializeUserServiceMock() r.GET("/test5", func(c *gin.Context) { i, _ := strconv.Atoi(c.Query("id")) fmt.Println(serviceMock) fmt.Println(service) result := serviceMock.GetUser(i) c.JSON(200, result) }) r.Run() // listen and serve on 0.0.0.0:8080 } <file_sep>package data import ( _ "github.com/go-sql-driver/mysql" "github.com/go-xorm/xorm" ) func (User3) TableName() string { return "user" } // User type User3 struct { ID int `json:"id" xorm:"'id'"` Username string `json:"name" xorm:"'screen_name'"` } // NewUser func NewUser(id int, username string) User3 { return User3{ ID: id, Username: username, } } // UserRepository type UserRepository3 struct { } // NewUserRepository func NewUserRepository3() UserRepository3 { return UserRepository3{} } // GetByID func (UserRepository3) GetUser(id int) *User3 { var engine *xorm.Engine var err error engine, err = xorm.NewEngine("mysql", "root:@tcp(localhost:3307)/hkanai?charset=utf8") if err != nil { panic(err) } var user = User3{ID: id} has, _ := engine.Get(&user) if has { return &user } return nil } <file_sep>package domain import ( "context" "database/sql" "fmt" "log" "github.com/hkanali/letitgo/model" ) // UserRepositoryImpl です type UserRepositoryImpl2 struct{} // NewUserRepositoryImpl です func NewUserRepositoryImpl2() *UserRepositoryImpl2 { return &UserRepositoryImpl2{} } // FindByID です func (UserRepositoryImpl2) FindByID(ctx context.Context, id int) (*model.User, error) { db, err := sql.Open("mysql", "root:@tcp(localhost:3307)/hkanai?charset=utf8") if err != nil { log.Fatal("failed.") } defer db.Close() results, err := db.Query("select id, screen_name from user where id = ?", id) if err != nil { panic(err.Error()) } fmt.Println(results) defer results.Close() for results.Next() { var user model.User err = results.Scan(&user.ID, &user.Name) return &user, err } return nil, nil } <file_sep>package data import ( "log" _ "github.com/go-sql-driver/mysql" "github.com/jmoiron/sqlx" ) // User type User4 struct { ID int `db:"id"` Name string `db:"screen_name"` } // UserRepository type UserRepository4 struct { } // NewUserRepository func NewUserRepository4() *UserRepository4 { return &UserRepository4{} } func (UserRepository4) GetUser(id int) *User4 { db, err := sqlx.Open("mysql", "root:@tcp(localhost:3307)/hkanai?charset=utf8") if err != nil { log.Fatal(err) } rows, err := db.Queryx("SELECT id, screen_name FROM user") if err != nil { log.Fatal(err) } var user User4 for rows.Next() { err := rows.StructScan(&user) if err != nil { log.Fatal(err) } return &user } return nil } <file_sep>module github.com/hkanali/letitgo go 1.12 require ( cloud.google.com/go v0.41.0 // indirect github.com/denisenkom/go-mssqldb v0.0.0-20190710001350-29e7b2419f38 // indirect github.com/gin-contrib/sse v0.1.0 // indirect github.com/gin-gonic/gin v1.4.0 github.com/go-sql-driver/mysql v1.4.1 github.com/go-xorm/xorm v0.7.4 github.com/golang/protobuf v1.3.2 // indirect github.com/google/wire v0.3.0 github.com/jackc/pgx v3.5.0+incompatible // indirect github.com/jinzhu/gorm v1.9.10 github.com/jmoiron/sqlx v1.2.0 github.com/kr/pty v1.1.8 // indirect github.com/lib/pq v1.2.0 // indirect github.com/mattn/go-sqlite3 v1.11.0 // indirect github.com/stretchr/objx v0.2.0 // indirect github.com/ugorji/go v1.1.7 // indirect golang.org/x/crypto v0.0.0-20190701094942-4def268fd1a4 // indirect golang.org/x/exp v0.0.0-20190627132806-fd42eb6b336f // indirect golang.org/x/image v0.0.0-20190703141733-d6a02ce849c9 // indirect golang.org/x/mobile v0.0.0-20190711165009-e47acb2ca7f9 // indirect golang.org/x/net v0.0.0-20190628185345-da137c7871d7 // indirect golang.org/x/sys v0.0.0-20190712062909-fae7ac547cb7 // indirect golang.org/x/tools v0.0.0-20190712213246-8b927904ee0d // indirect google.golang.org/genproto v0.0.0-20190708153700-3bdd9d9f5532 // indirect google.golang.org/grpc v1.22.0 // indirect ) <file_sep>package service import ( "fmt" "github.com/hkanali/letitgo/domain" "github.com/hkanali/letitgo/model" ) type UserService struct { userRepository domain.UserRepository } func NewUserService(userRepository *domain.UserRepositoryImpl) *UserService { return &UserService{userRepository: userRepository} } func NewUserServiceFromDb(userRepository *domain.UserRepositoryImpl2) *UserService { return &UserService{userRepository: userRepository} } func (service UserService) GetUser(id int) *model.User { user, err := service.userRepository.FindByID(nil, id) // if err != nil { // panic(err) // } fmt.Println(err) return user } <file_sep>package data import ( "database/sql" "fmt" "log" _ "github.com/go-sql-driver/mysql" ) type User1 struct { Name string } type UserRepository struct { } func NewUserRepository() *UserRepository { return &UserRepository{} } func (*UserRepository) GetUser(id int) *User1 { db, err := sql.Open("mysql", "root:@tcp(localhost:3307)/hkanai?charset=utf8") if err != nil { log.Fatal("failed.") } defer db.Close() results, err := db.Query("select screen_name from user where id = ?", id) if err != nil { panic(err.Error()) } fmt.Println(results) defer results.Close() for results.Next() { var user User1 err = results.Scan(&user.Name) if err != nil { panic(err.Error()) } return &user } return &User1{} } <file_sep>package service import "github.com/hkanali/letitgo/model" type IUserService interface { GetUser(id int) *model.User } <file_sep>package domain import ( "context" "github.com/hkanali/letitgo/model" ) // UserRepository です type UserRepository interface { FindByID(ctx context.Context, userID int) (*model.User, error) } <file_sep>package model type User struct { ID int Name string `json:"naaaameeeee"` } <file_sep>package domain import ( "context" "errors" "strconv" "github.com/hkanali/letitgo/model" ) // UserRepositoryImpl です type UserRepositoryImpl struct{} // NewUserRepositoryImpl です func NewUserRepositoryImpl() *UserRepositoryImpl { return &UserRepositoryImpl{} } // FindByID です func (UserRepositoryImpl) FindByID(ctx context.Context, userID int) (*model.User, error) { name := "name:" + strconv.Itoa(userID) return &model.User{ID: userID, Name: name}, errors.New("") } <file_sep>//+build wireinject package main import ( "github.com/google/wire" "github.com/hkanali/letitgo/domain" "github.com/hkanali/letitgo/service" ) func InitializeUserService() *service.UserService { wire.Build( domain.NewUserRepositoryImpl, service.NewUserService, ) return &service.UserService{} } func InitializeUserServiceMock() *service.UserService { wire.Build( domain.NewUserRepositoryImpl2, service.NewUserServiceFromDb, ) return &service.UserService{} }
7ca5c918f29c47785f9440167c9cf17a820ac444
[ "Go Module", "Go" ]
13
Go
hkanali/letitgo
526d94493573a187fa9086f2e5f6fa085d65f625
40630804836ca5deeafc97acdfd1be41e32d8dc3
refs/heads/master
<file_sep>angular.module('application') .controller('NavController', ['$scope', '$state', function($scope, $state) { $scope.current = $state.current.name; var routes = angular.copy(foundationRoutes); //setup autocomplete $scope.routing = []; $scope.typedText = ''; if(foundationRoutes) { angular.forEach(routes, function(r) { var title = r.title || r.name.replace('.', ' '); //use title if possible $scope.routing.push(title); }); } $scope.selectRoute = function(routeName) { var title = routeName; var name = routeName.replace(' ', '.'); //search for route angular.forEach(routes, function(r) { if(r.title && r.title === routeName) { $state.go(r.name); return; } else if (name === r.name) { $state.go(r.name); return; } }); }; } ]); angular.module('application') .controller('SocialAppCtrl', SocialAppCtrl); function SocialAppCtrl($scope){ $scope.socialMenu=[ {'nameIcon': 'grade'}, {'nameIcon': 'done'}, {'nameIcon': 'zoom_in'}, {'nameIcon': 'visibility'} ]; $scope.callback=[ {'link':'vk.com', 'name':'Вконтакте'}, {'link':'twitter.com', 'name':'Твиттер'} ]; $scope.navList=[ {'item':'Code', 'link':'#'}, {'item':'Build', 'link':'#'}, {'item':'Structure', 'link':'#'}, {'item':'Connect', 'link':'#'}, {'item':'Lead', 'link':'#'} ] }
1703704a3b87166bea9c993595e6e0883766cc04
[ "JavaScript" ]
1
JavaScript
jboba/readwrite
5a4abeb1938fec96746e7e4c8ac73842b8581a47
9ff8ffd3e2faefe08e0ea8c87456ca749e3a2166