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/main
<repo_name>ryannolly/rsa-plus-rot-13<file_sep>/index.php <?php if(isset($_GET['status'])){ if($_GET['status'] == "true"){ echo "Pastikan Jumlah Karakter dari Kalimat Enkripsi Lebih kecil atau sama dengan dengan Password"; echo "<br>"; }else if($_GET['status'] == "truee"){ echo "Harap memulai program dari sini!"; echo "<br>"; } } ?> <!doctype html> <html lang="en"> <head> <!-- Required meta tags --> <meta charset="utf-16"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <!-- Bootstrap CSS --> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="<KEY>" crossorigin="anonymous"> <title>Kriptografi RNA + OTP</title> </head> <body> <div class="container-fluid mt-2"> <form action="prosesenkripsiRSA.php" method="POST" accept-charset="iso-8859-1"> <div class="form-group"> <label for="exampleInputEmail1">Masukkan Kalimat yang Ingin Dienkripsi</label> <input type="text" class="form-control" placeholder="Masukkan Kalimat" name="kalimatEnkripsi" required> </div> <button type="submit" class="btn btn-primary" name="submit">Encrypt</button> </form> </div> <!-- Optional JavaScript --> <!-- jQuery first, then Popper.js, then Bootstrap JS --> <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="<KEY>" crossorigin="anonymous"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js" integrity="<KEY>" crossorigin="anonymous"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js" integrity="<KEY>" crossorigin="anonymous"></script> </body> </html><file_sep>/prosesdekripsi.php <?php header('Content-Type: text/html; charset=iso-8859-1'); if(!isset($_POST['submit'])){ header('Location: index.php?status=truee'); } ?> <?php $time_start = microtime(true); function fastModularExpo($a, $n, $modular){ if($n == 0){ return 1; } if($n % 2 == 0){ return fastModularExpo($a * $a % $modular, $n/2, $modular); }else{ return ($a * fastModularExpo($a, $n-1, $modular)) % $modular; } } ?> <!doctype html> <html lang="en"> <head> <!-- Required meta tags --> <meta charset="UTF-16"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <title>Hasil Enkripsi</title> <!-- Bootstrap CSS --> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="<KEY>" crossorigin="anonymous"> </head> <body> <?php $kalimatDekripsiOTP = ""; for($i = 0; $i < sizeof($_POST['hasilenkripsiRSAOTP']) ; $i++){ if(($_POST['hasilenkripsiRSAOTP'][$i] - ord($_POST['passwordOTP'][$i])) > 0){ $dekripsiOTP[$i] = (($_POST['hasilenkripsiRSAOTP'][$i] - ord($_POST['passwordOTP'][$i]))) % 256; }else{ $dekripsiOTP[$i] = (($_POST['hasilenkripsiRSAOTP'][$i] - ord($_POST['passwordOTP'][$i]))) + 256; } $kalimatDekripsiOTP .= chr($dekripsiOTP[$i]); } ?> <div class="container-fluid-mt-2"> <h4>Kalimat Setelah Didekripsi Menggunakan Algoritma OTP</h4> <p><b><center><?php echo $kalimatDekripsiOTP ?></center></b></p> <h4>Kalimat Setelah Didekripsi Menggunakan Algoritma OTP dalam ASCII</h4> <table class="table" align="center"> <tr> <th>Karakter</th> <th>Dalam ASCII</th> </tr> <?php for($i = 0; $i<strlen($kalimatDekripsiOTP); $i++){ ?> <tr> <td><?php echo chr($dekripsiOTP[$i]) ?></td> <td><?php echo $dekripsiOTP[$i] ?></td> </tr> <?php } ?> </table> </div> <?php $kalimatDekripsiRSA = ""; for($i = 0; $i< sizeof($dekripsiOTP); $i++){ $dekripsiRSA[$i] = fastModularExpo($dekripsiOTP[$i], 23, 187); $kalimatDekripsiRSA .= chr($dekripsiRSA[$i]); } ?> <div class="container-fluid-mt-2"> <h4>Kalimat Setelah Didekripsi Menggunakan Algoritma OTP + RSA</h4> <p><b><center><?php echo $kalimatDekripsiRSA ?></center></b></p> <h4>Kalimat Setelah Didekripsi Menggunakan Algoritma OTP + RSA dalam ASCII</h4> <table class="table" align="center"> <tr> <th>Karakter</th> <th>Dalam ASCII</th> </tr> <?php for($i = 0; $i<strlen($kalimatDekripsiRSA); $i++){ ?> <tr> <td><?php echo chr($dekripsiRSA[$i]) ?></td> <td><?php echo $dekripsiRSA[$i] ?></td> </tr> <?php } ?> </table> </div> <a href="index.php" class="btn btn-info mb-4">Uji Coba Lagi</a> <?php $time_end = microtime(true); $execution_time = ($time_end - $time_start); echo '<b>Total Execution Time:</b> '.(double) $execution_time.' Second'; ?> </body> </html><file_sep>/prosesenkripsiOTP.php <?php header('Content-Type: text/html; charset=iso-8859-1'); if(!isset($_POST['submit'])){ header('Location: index.php?status=truee'); } $time_start = microtime(true); if(strlen($_POST['kalimatAwal']) > strlen($_POST['passwordOTP'])){ $banyakPengulang = ceil(strlen($_POST['kalimatAwal'])/strlen($_POST['passwordOTP'])); $kalimatAwal = $_POST['passwordOTP']; for($i = 0; $i<$banyakPengulang; $i++){ $_POST['passwordOTP'] .= $kalimatAwal; } } ?> <?php function fastModularExpo($a, $n, $modular){ if($n == 0){ return 1; } if($n % 2 == 0){ return fastModularExpo($a * $a % $modular, $n/2, $modular); }else{ return ($a * fastModularExpo($a, $n-1, $modular)) % $modular; } } ?> <!doctype html> <html lang="en"> <head> <!-- Required meta tags --> <meta charset="UTF-16"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <title>Hasil Enkripsi</title> <!-- Bootstrap CSS --> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="<KEY>" crossorigin="anonymous"> </head> <body> <div class="container-fluid-mt-2"> <h4>Password Algoritma OTP</h4> <p><b><center><?php echo $_POST['passwordOTP'] ?></center></b></p> <h4>Password Algoritma OTP dalam ASCII</h4> <table class="table" align="center"> <tr> <th>Karakter</th> <th>Dalam ASCII</th> </tr> <?php for($i = 0; $i<strlen($_POST['passwordOTP']); $i++){ ?> <tr> <td><?php echo $_POST['passwordOTP'][$i] ?></td> <td><?php echo ord($_POST['passwordOTP'][$i]) ?></td> </tr> <?php } ?> </table> </div> <?php $kalimatEnkripsiOTP = ""; for($i = 0; $i< strlen($_POST['hasilenkripsiRSA']); $i++){ $enkripsiOTP[$i] = (ord($_POST['hasilenkripsiRSA'][$i]) + ord($_POST['passwordOTP'][$i])) % 256; $kalimatEnkripsiOTP .= chr($enkripsiOTP[$i]); } ?> <div class="container-fluid-mt-2"> <h4>Kalimat Hasil Enkripsi Setelah menggunakan Algoritma RSA + OTP</h4> <p><b><center><?php echo $kalimatEnkripsiOTP ?></center></b></p> <h4>Kalimat Hasil Enkripsi Setelah Menggunakan Algoritma RSA + OTP dalam ASCII</h4> <table class="table" align="center"> <tr> <th>Karakter</th> <th>Dalam ASCII</th> </tr> <?php for($i = 0; $i<strlen($kalimatEnkripsiOTP); $i++){ ?> <tr> <td><?php echo chr($enkripsiOTP[$i]) ?></td> <td><?php echo $enkripsiOTP[$i] ?></td> </tr> <?php } ?> </table> </div> <form action="prosesdekripsi.php" method="POST" accept-charset="iso-8859-1"> <?php for($i = 0; $i<strlen($kalimatEnkripsiOTP); $i++) : ?> <input type="hidden" name="hasilenkripsiRSAOTP[]" value="<?php echo $enkripsiOTP[$i] ?>"> <?php endfor ?> <input type="hidden" name="passwordOTP" value="<?php echo $_POST['passwordOTP'] ?>"> <input type="submit" value="Dekripsikan" name="submit" class="btn btn-info"> </form> <?php $time_end = microtime(true); $execution_time = ($time_end - $time_start); echo '<b>Total Execution Time:</b> '.(double) $execution_time.' Second'; ?> </body> </html>
9a15f5f8630f9a66e4247c4142074ab6da8e803d
[ "PHP" ]
3
PHP
ryannolly/rsa-plus-rot-13
95ce2f5dffc1047b368a37057fb4c1895513bdbb
64b674a839c4d02957f2cdcf89ff64efc756f61a
refs/heads/master
<file_sep>from flask import Flask from flask import render_template, request, redirect app = Flask(__name__) @app.route('/') def index(): return render_template('index.html', pageTitle='Loan Calculator') @app.route('/calculate', methods=['GET', 'POST']) def loan(): if request.method == 'POST': form = request.form A = int(form['Loan_Amount']) n = int(form['Years'])*12 i = float(form['Interest_Rate'])/12 D = (((1+i)**n)-1)/(i*(1+i)**n) Payment = "$" + str((round(A/D,2))) return render_template('index.html', display=Payment, pageTitle='Loan Calculator') return redirect("/") if __name__ == '__main__': app.run(debug=True)
8a4265f42773900811cde30365e58cacab7319e0
[ "Python" ]
1
Python
LakotaLarson/flask
d1e0e11857e3113813c06307c6f8c514cc043817
d19adba5042ca984c60f67b18fe84422957e87b1
refs/heads/master
<repo_name>jorge-garcia-clickit/k3s-setup<file_sep>/bin/functions.sh #!/bin/bash export ANSIBLE_HOST_KEY_CHECKING=False create_cluster() { cd terraform terraform apply sleep 15 #just give the EC2 instances some time to initialize cd ../ansible ansible-playbook site.yml -i inventory/my-cluster/hosts.ini sed cd ../terraform export tempvar=$( grep path_to_download_kube_config terraform.tfvars | cut -d\" -f2 ) [[ -z "$tempvar" ]] && export tempvar="$HOME/.kube/config" sed -i -e "s@server: https://.*:6443@server: https://$( terraform output -raw k3s_cluster_ip ):6443@" $tempvar #replace private ip to public ip in local kube config file echo -e "\033[0;32mCLUSTER CREATED CORRECTLY" echo "Kube Config file saved to $tempvar" echo "K3s Cluster IP is $( terraform output -raw k3s_cluster_ip )" } delete_cluster() { cd terraform terraform destroy } deploy_manifiests() { find k3s -name "*.yml" -exec kubectl apply -f {} \; } configure_tfvars() { if test -f "terraform/terraform.tfvars"; then read -p "This action will remove the previous config, do you want to proceed? y/n: " tempvar if [[ $tempvar =~ ^[Yy]$ ]] then echo "Deleting previous configuration" rm terraform/terraform.tfvars else exit echo "Abort.." fi unset tempvar else echo "Creating new configuration" fi echo "AWS Region in which to create the aws resources" read -p "aws_region: " tempvar [[ ! -z "$tempvar" ]] && echo "aws_region = \"$tempvar\"" >> terraform/terraform.tfvars unset tempvar echo "AWS profile to select from aws config to create resources" read -p "aws_profile: " tempvar [[ ! -z "$tempvar" ]] && echo "aws_profile = \"$tempvar\"" >> terraform/terraform.tfvars unset tempvar echo "Name of the EC2 instances created for the K3s Cluster" read -p "cluster_name: " tempvar [[ ! -z "$tempvar" ]] && echo "cluster_name = \"$tempvar\"" >> terraform/terraform.tfvars unset tempvar echo "Number of EC2 instances to be created as K3s Agent Nodes, this is additional to the One K3s Master node" read -p "number_of_nodes: " tempvar [[ ! -z "$tempvar" ]] && echo "number_of_nodes = $tempvar" >> terraform/terraform.tfvars unset tempvar echo "Name of the keypair required for ansible to ssh into the EC2 instances" read -p "key_name: " tempvar [[ ! -z "$tempvar" ]] && echo "key_name = \"$tempvar\"" >> terraform/terraform.tfvars unset tempvar echo "Instance type of the master k3s instance" read -p "master_instance_type: " tempvar [[ ! -z "$tempvar" ]] && echo "master_instance_type = \"$tempvar\"" >> terraform/terraform.tfvars unset tempvar echo "Instance type of the node k3s instances" read -p "node_instance_type: " tempvar [[ ! -z "$tempvar" ]] && echo "node_instance_type = \"$tempvar\"" >> terraform/terraform.tfvars unset tempvar echo "User that ansible will use to connect to the k3s instances via ssh" read -p "ansible_user: " tempvar [[ ! -z "$tempvar" ]] && echo "ansible_user = \"$tempvar\"" >> terraform/terraform.tfvars unset tempvar echo "Ssh key for the ansible user to connect to the k3s instances" read -p "ansible_ssh_private_key_file: " tempvar [[ ! -z "$tempvar" ]] && echo "ansible_ssh_private_key_file = \"$tempvar\"" >> terraform/terraform.tfvars unset tempvar echo "version of k3s to install in the servers" read -p "k3s_version: " tempvar [[ ! -z "$tempvar" ]] && echo "k3s_version = \"$tempvar\"" >> terraform/terraform.tfvars unset tempvar echo "Additional arguments required to start k3s on the master server" read -p "extra_server_args: " tempvar [[ ! -z "$tempvar" ]] && echo "extra_server_args = \"$tempvar\"" >> terraform/terraform.tfvars unset tempvar echo "Additional arguments required to start k3s on the node servers" read -p "extra_agent_args: " tempvar [[ ! -z "$tempvar" ]] && echo "extra_agent_args = \"$tempvar\"" >> terraform/terraform.tfvars unset tempvar echo "Number of desired master nodes for a high availability k3s cluster, setting this value to a number greater than 1 will aditionally create a haproxy server and a rds mysql server" read -p "number_of_master_servers: " tempvar [[ ! -z "$tempvar" ]] && echo "number_of_master_servers = $tempvar" >> terraform/terraform.tfvars unset tempvar echo "Path for .kube/config to be saved" read -p "path_to_download_kube_config: " tempvar [[ ! -z "$tempvar" ]] && echo "path_to_download_kube_config = \"$tempvar\"" >> terraform/terraform.tfvars unset tempvar }<file_sep>/README.md ## To run properly this tool requires the following: * Terraform v0.14.6 or greater * ansible 2.10.7 * An AWS cli profile already configured ## Usage Page ```sh NAME k3s-setup - DESCRIPTION This section explains default behavior and notations in the commands provided. COMMANDS AVAILABLE create Create terraform resources and provision k3s cluster If the configure is not executed before a create command execution then default values in terraform/variables.tf will be used, depending on your configuration you can add additional master nodes, a RDS database and a haproxy server to enable a highly available k3s cluster. After the creation of the terraform resources ansible will provision the k3s cluster and it will copy the .kube/config file from the remote master server to your local environment delete Basically just a terraform destroy deploy Automatically looks for k8s manifests located in the k3s directory or in any given directory during configure, the cluster needs to be created first before running this command, files shall be named with a XX- number prefix, example given: 00-Deployment.yml 01-Service.yml 02-ingress.yml usage -h --help Prints this message. ``` ## Usage Examples ``` ./main.sh create ``` ``` ./main.sh delete ``` ``` ./main.sh deploy ``` ``` ./main.sh usage ``` <file_sep>/main.sh #!/bin/bash source bin/functions.sh ##Global Variables usage() { echo " NAME k3s-setup - DESCRIPTION This section explains default behavior and notations in the commands provided. COMMANDS AVAILABLE create Create terraform resources and provision k3s cluster If the configure is not executed before a create command execution then default values in terraform/variables.tf will be used, depending on your configuration you can add additional master nodes, a RDS database and a haproxy server to enable a highly available k3s cluster. After the creation of the terraform resources ansible will provision the k3s cluster and it will copy the .kube/config file from the remote master server to your local environment delete Basically just a terraform destroy deploy Automatically looks for k8s manifests located in the k3s directory or in any given directory during configure, the cluster needs to be created first before running this command, files shall be named with a XX- number prefix, example given: 00-Deployment.yml 01-Service.yml 02-ingress.yml usage -h --help Prints this message. " } ##########################################################Main script################################################################### #check if subcommand exists, then go to subcommand function, else print usage information and exit with error code 1 case $1 in create ) create_cluster ;; delete ) delete_cluster ;; deploy ) deploy_manifiests ;; configure ) configure_tfvars ;; -h | --help | usage ) usage ;; * ) echo "Error: Invalid option" usage exit 1 esac shift
98d04e3c246012766dbd89bd62a49ade8c8aa03f
[ "Markdown", "Shell" ]
3
Shell
jorge-garcia-clickit/k3s-setup
8183ca60a716adc0f3ece354e2ce16765baaf9d6
aec9e28edff6f6c48de9674f77bcabd16d8951b3
refs/heads/master
<repo_name>yogasol/miniAlipay<file_sep>/app/CollectionModel.php <?php namespace App; use Illuminate\Database\Eloquent\Model; class CollectionModel extends Model { //收藏 protected $table="collection"; protected $fillable=["id","user_id","type","field","questionNum","created_at"]; } <file_sep>/app/StatsModel.php <?php namespace App; use Illuminate\Database\Eloquent\Model; class StatsModel extends Model { //做题情况记录表 protected $table="stats"; protected $fillable=["id","user_id","type","field","statistical_error","error_count","time","score","created_at"]; } <file_sep>/README.md # miniAlipay ## 安装使用 ``` # 从仓库中下载 $ git clone https://github.com/icharle/miniAlipay # 进入代码根目录安装依赖 $ composer install # copy .env文件 $ cp .env.example .env # 生成项目key $ php artisan key:generate # 配置小程序appID && 支付宝公钥私钥路径(路径按照下面填写即可) ALIPAY_APP_ID= APP_PRIVATE_KEY_PATH=pem/private.txt ALIPAY_PUBLIC_KEY_PATH=pem/public.txt ```<file_sep>/app/Http/Controllers/AuthController.php <?php namespace App\Http\Controllers; use App\User; use Illuminate\Http\Request; use Icharle\Alipaytool\Alipaytool; use Illuminate\Support\Facades\Auth; class AuthController extends Controller { /** * 支付宝授权登录尝试 * code值反馈 * 40002 => authCode(授权码code)无效 * 40006 => ISV权限不足,建议在开发者中心检查对应功能是否已经添加 * 10000 => 请求成功 */ function __construct() { $this->middleware('refresh.token', ['except' => ['login']]); // 多个方法可以这样写 ['login','xxxx'] 这样就会拦截出login方法 } public function login(Request $request) { $data = $request->all(); $authtoken = $data['authCode']; $app = new Alipaytool(); $alipay_system_oauth_token_response = $app::getAccessToken($authtoken); if (isset($alipay_system_oauth_token_response['code']) && $alipay_system_oauth_token_response['code'] == 40002) { exit('授权码code无效'); } // echo $alipay_system_oauth_token_response['access_token']; /** * 执行成功后 $alipay_system_oauth_token_response => 可以得到如下 * "access_token" => "<PASSWORD>" * "alipay_user_id" => "20880009409744196066652292516889" * "expires_in" => 1296000 * "re_expires_in" => 2592000 * "refresh_token" => "<PASSWORD>" * "user_id" => "2088122358263891" */ $alipay_user_info_share_response = $app::getUserInfoByAccessToken($alipay_system_oauth_token_response['access_token']); if (isset($alipay_user_info_share_response['code']) && $alipay_user_info_share_response['code'] == 40006) { exit('ISV权限不足,建议在开发者中心检查对应功能是否已经添加'); } $usermsg = User::updateOrCreate( // 用户多次登录 用户存在时候就更新 不存在的时候就插入 [ 'user_id' => $alipay_user_info_share_response['user_id'], ], ['nick_name' => $alipay_user_info_share_response['nick_name'], 'avatar' => $alipay_user_info_share_response['avatar'], ] ); $token = Auth::guard('api')->fromUser($usermsg); return response()->json([ 'token' => "Bearer " . $token, 'type' => $usermsg->type ]); /** * 执行成功后 $alipay_user_info_share_response => 可以得到如下(按照需要存入数据库中) * "code" => "10000" * "msg" => "Success" * "avatar" => "https://tfs.alipayobjects.com/images/partner/T1tsxxXi0eXXXXXXXX" * "city" => "梅州市" * "gender" => "m" * "is_certified" => "T" * "is_student_certified" => "T" * "nick_name" => "*****超" * "province" => "广东省" * "user_id" => "2088122358263891" * "user_status" => "T" * "user_type" => "2" */ } /* * 6 */ //个人页面,更改备考科目 public function Personal(Request $request) { $data = $request->all(); $newtype = $data['type']; $userInfo = Auth::guard('api')->user(); $usermsg = User::where('user_id', '=', $userInfo['user_id'])->updateOrCreate( ['user_id'=>$userInfo['user_id']], ['type' => $newtype] ); if ($usermsg) { return response()->json('60001'); } } } <file_sep>/routes/api.php <?php use Illuminate\Http\Request; use Illuminate\Routing\Router; /* |-------------------------------------------------------------------------- | API Routes |-------------------------------------------------------------------------- | | Here is where you can register API routes for your application. These | routes are loaded by the RouteServiceProvider within a group which | is assigned the "api" middleware group. Enjoy building your API! | */ Route::middleware('auth:api')->get('/user', function (Request $request) { return $request->user(); }); Route::prefix('auth')->group(function($router) { $router->post('login', 'AuthController@login'); $router->any('CountDown', 'ExaminationController@CountDown'); $router->post('QuestionsData', 'ExaminationController@QuestionsData'); $router->post('ScoreStats', 'ExaminationController@ScoreStats'); $router->post('Personal', 'AuthController@Personal'); $router->get('ExamTitle', 'ExaminationController@ExamTitle'); $router->post('FeekBack', 'ExaminationController@FeekBack'); $router->post('Collection', 'ExaminationController@Collection'); $router->post('SearchCollect', 'ExaminationController@SearchCollect'); $router->post('DelectCollect', 'ExaminationController@DelectCollect'); }); <file_sep>/app/FeekBackModel.php <?php namespace App; use Illuminate\Database\Eloquent\Model; class FeekBackModel extends Model { // protected $table="feekback"; protected $fillable=["id","user_id","content","created_at","updated_at"]; } <file_sep>/app/Http/Controllers/ExaminationController.php <?php namespace App\Http\Controllers; use App\CollectionModel; use App\CxyModel; use App\DzswModel; use App\ExaminationModel; use App\FeekBackModel; use App\MediaModel; use App\QrsModel; use App\RjpcsModel; use App\SjkModel; use App\StatsModel; use App\User; use App\WlghModel; use App\WlglModel; use App\WlModel; use App\XtfxModel; use App\XtghModel; use App\XtjcModel; use App\XtjgModel; use App\XxaqModel; use App\XxclModel; use App\XxModel; use App\XxxtModel; use App\XxxtxmModel; use Illuminate\Http\Request; use Illuminate\Support\Facades\DB; use Illuminate\Support\Facades\Auth; class ExaminationController extends Controller { function __construct() { $this->middleware('refresh.token', ['except' => ['login']]); // 多个方法可以这样写 ['login','xxxx'] 这样就会拦截出login方法 } //倒计时 统计受欢迎题目排行 public function CountDown() { $pretime = time(); $examtime1 = strtotime('2019-5-25'); // 到时间手动改吧 // todo 一般软考上半年都在5月25号 下半年都在11月10号 通过自动判断确定那一次考试 $sub = ceil(($examtime1 - $pretime) / 86400); $userInfo = Auth::guard('api')->user(); $type = $userInfo->type; // 直接获取就可以了 搞这么复杂干啥 if ($type == '0') { // 即 未选择备考科目的时候直接返回倒计时 return response()->json([ 'countdown'=>$sub, 'list'=>[] ]); } //此段查询语句返回 stats表中 field 重复次数最多的5条记录各自总值 $chartsmax=StatsModel::where('type','=',$type)->select(DB::raw('count(*) as count')) ->groupBy('field') ->orderBy('count','desc') ->limit(5)->get(); //此段查询语句返回 stats表中 field 重复次数最多的5条记录的试卷号 $charts=StatsModel::where('type','=',$type)->select('field') ->groupBy('field') ->orderBy(DB::raw('count(*)'),'desc') ->limit(5) ->get(); $arr=[]; foreach($charts as $k=>$v){ $arr[] = array( "title" => $this->changeToTitle($v['field']), 'total' => $chartsmax[$k]['count'], ); } return response()->json([ 'countdown'=>$sub, 'list'=>$arr ]); } //根据用户type列出对应的试题数据 public function QuestionsData(Request $request) { $data = $request->all(); $field = $data['field']; $userInfo = Auth::guard('api')->user(); $type = $userInfo->type; // 直接获取就可以了 //根据type id返回对应试题信息 /* type= * rjsj软件设计师(morning软件设计师上午题目) * dzsw电子商务设计师(上午题) * media多媒体应用设计师(上午题) * qrs嵌入式系统设计师(上午题) * rjpcs软件评测师(上午题) * sjk数据库系统工程师(上午题) * wlgh网络规划设计师(上午题) * wl网络工程师(上午题) * xtfx系统分析师(上午题) * xtgh系统规划与管理师(上午题) * xtjc系统集成项目管理工程师(上午题) * xtjg系统架构设计师(上午题) * xxaq信息安全工程师(上午题) * xx信息系统监理师(上午题) * xxxt信息系统管理工程师(上午题) * xxxtxm信息系统项目管理师(上午题) * * cxy程序员(上午题) * xxcl信息处理技术员 * wlgl网络管理员 * 信息系统运行管理员 */ //查找试题信息 if ($type=='rjsj'){ $ques_content = ExaminationModel::where('field', '=', $field)->orderBy('questionNum','asc')->get(); } elseif ($type=='dzsw'){ $ques_content = DzswModel::where('field', '=', $field)->orderBy('questionNum','asc')->get(); } elseif ($type=='media'){ $ques_content = MediaModel::where('field', '=', $field)->orderBy('questionNum','asc')->get(); } elseif ($type=='qrs'){ $ques_content = QrsModel::where('field', '=', $field)->orderBy('questionNum','asc')->get(); } elseif ($type=='rjpcs'){ $ques_content = RjpcsModel::where('field', '=', $field)->orderBy('questionNum','asc')->get(); } elseif ($type=='sjk'){ $ques_content = SjkModel::where('field', '=', $field)->orderBy('questionNum','asc')->get(); } elseif ($type=='wlgh'){ $ques_content = WlghModel::where('field', '=', $field)->orderBy('questionNum','asc')->get(); } elseif ($type=='wl'){ $ques_content = WlModel::where('field', '=', $field)->orderBy('questionNum','asc')->get(); } elseif ($type=='xtfx'){ $ques_content = XtfxModel::where('field', '=', $field)->orderBy('questionNum','asc')->get(); } elseif ($type=='xtgh'){ $ques_content = XtghModel::where('field', '=', $field)->orderBy('questionNum','asc')->get(); } elseif ($type=='xtjc'){ $ques_content = XtjcModel::where('field', '=', $field)->orderBy('questionNum','asc')->get(); } elseif ($type=='xtjg'){ $ques_content = XtjgModel::where('field', '=', $field)->orderBy('questionNum','asc')->get(); } elseif ($type=='xxaq'){ $ques_content = XxaqModel::where('field', '=', $field)->orderBy('questionNum','asc')->get(); } elseif ($type=='xx'){ $ques_content = XxModel::where('field', '=', $field)->orderBy('questionNum','asc')->get(); } elseif ($type=='xxxt'){ $ques_content = XxxtModel::where('field', '=', $field)->orderBy('questionNum','asc')->get(); } elseif ($type=='xxxtxm'){ $ques_content = XxxtxmModel::where('field', '=', $field)->orderBy('questionNum','asc')->get(); } elseif ($type=='cxy'){ $ques_content = CxyModel::where('field', '=', $field)->orderBy('questionNum','asc')->get(); } elseif ($type=='xxcl'){ $ques_content = XxclModel::where('field', '=', $field)->orderBy('questionNum','asc')->get(); } elseif ($type=='wlgl'){ $ques_content = WlglModel::where('field', '=', $field)->orderBy('questionNum','asc')->get(); } else { return response()->json(); // 未选择备考科目直接返回空 防止出现500不友好错误 } if (isset($field)){ $cnt = 0; if ($ques_content) { foreach ($ques_content as $val) { if ($cnt == 0) { $id = $val->id; $question = $val->question; $questionImg=$val->questionImg; $optiona = $val->optiona; $optionb = $val->optionb; $optionc = $val->optionc; $optiond = $val->optiond; $answer = $val->answer; $questionNum=$val->questionNum; $answeranalysis = $val->answeranalysis; $all[] = array("id" => $id, 'question' => $question, 'questionImg'=>$questionImg, 'optiona' => $optiona, 'optionb' => $optionb, 'optionc' => $optionc, 'optiond' => $optiond, 'answer' => $answer, 'questionNum'=>$questionNum, 'answeranalysis' => $answeranalysis,); } } return response()->json(["message"=>$all]); } }else{ return response()->json(); } } //试卷提交,做题情况入库 public function ScoreStats(Request $request){ $data=$request->all(); $errorques=$request['errorquestions']; //错题题号 $score=$request['score'];//总分 $field=$request['field'];//套题编号 $userInfo = Auth::guard('api')->user();//用户id $errorcount=$data['errorcount'];//错题数 $time=$request['time']; //用时 $stats=StatsModel::create([ 'user_id'=>$userInfo['user_id'], 'statistical_error' => $errorques, 'field'=>$field, 'type'=>$userInfo['type'], 'error_count'=>$errorcount, 'score'=>$score, 'time'=>$time ]); if($stats){ return response()->json('30001'); }else{ return response()->json('30002'); } } //获取备考科目试题列表 public function ExamTitle(){ //get user_id $userInfo = Auth::guard('api')->user();//用户id $type = $userInfo->type; // 直接获取就可以了 $user_id = $userInfo['user_id']; // 用户ID //查找试题field if ($type=='rjsj'){ //查找上午试题信息 $field = ExaminationModel::select(DB::raw('field')) ->groupBy('field') ->orderBy('field','desc') ->get(); } else if ($type=='dzsw'){ $field = DzswModel::select(DB::raw('field')) ->groupBy('field') ->orderBy('field','desc') ->get(); } else if ($type=="media"){ $field = MediaModel::select(DB::raw('field')) ->groupBy('field') ->orderBy('field','desc') ->get(); } else if ($type=='qrs'){ $field= QrsModel::select(DB::raw('field')) ->groupBy('field') ->orderBy('field','desc') ->get(); } else if ($type=='rjpcs'){ $field = RjpcsModel::select(DB::raw('field')) ->groupBy('field') ->orderBy('field','desc') ->get(); } else if ($type=='sjk'){ $field = SjkModel::select(DB::raw('field')) ->groupBy('field') ->orderBy('field','desc') ->get(); } else if ($type=='wlgh'){ $field = WlghModel::select(DB::raw('field')) ->groupBy('field') ->orderBy('field','desc') ->get(); } else if ($type=="wl"){ $field = WlModel::select(DB::raw('field')) ->groupBy('field') ->orderBy('field','desc') ->get(); } else if ($type=='xtfx'){ $field = XtfxModel::select(DB::raw('field')) ->groupBy('field') ->orderBy('field','desc') ->get(); } else if ($type=='xtgh'){ $field = XtghModel::select(DB::raw('field')) ->groupBy('field') ->orderBy('field','desc') ->get(); } else if ($type=='xtjc'){ $field = XtjcModel::select(DB::raw('field')) ->groupBy('field') ->orderBy('field','desc') ->get(); } else if ($type=='xtjg'){ $field = XtjgModel::select(DB::raw('field')) ->groupBy('field') ->orderBy('field','desc') ->get(); } else if ($type=='xxaq'){ $field = XxaqModel::select(DB::raw('field')) ->groupBy('field') ->orderBy('field','desc') ->get(); } else if ($type=='xx'){ $field = XxModel::select(DB::raw('field')) ->groupBy('field') ->orderBy('field','desc') ->get(); } else if ($type=='xxxt'){ $field = XxxtModel::select(DB::raw('field')) ->groupBy('field') ->orderBy('field','desc') ->get(); } else if ($type=='xxxtxm'){ $field = XxxtxmModel::select(DB::raw('field')) ->groupBy('field') ->orderBy('field','desc') ->get(); } else if ($type=='cxy'){ $field = CxyModel::select(DB::raw('field')) ->groupBy('field') ->orderBy('field','desc') ->get(); } else if ($type=='xxcl'){ $field = XxaqModel::select(DB::raw('field')) ->groupBy('field') ->orderBy('field','desc') ->get(); } else if ($type=='wlgl'){ $field = WlglModel::select(DB::raw('field')) ->groupBy('field') ->orderBy('field','desc') ->get(); } else { return response()->json(); // 未选择备考科目直接返回空 防止出现500不友好错误 } $time_error= DB::select('SELECT time,field,error_count FROM stats WHERE user_id = ? AND created_at IN ( SELECT MAX(created_at) created_at FROM stats WHERE user_id = ? GROUP BY field)',[$user_id,$user_id]); $arr = []; // 结果集 foreach ($field as $t){ // 遍历所有场次 $flag = false; foreach ($time_error as $a) { // 遍历所有已经答题的信息 if ($t->field == $a->field){ // 如果有答题记录 使用答题记录的值 $arr[] =array( 'title' => $this->changeToTitle($a->field), 'field' => $a->field, 'time' => $a->time, 'error' => $a->error_count, ); $flag = true; } } if (!$flag){ // 如果不存在答题记录 使用0 $arr[] =array( 'title' => $this->changeToTitle($t->field), 'field' => $t->field, 'time' => '00:00', 'error' => '0', ); } } return response()->json($arr); } // 通过field转成具体中文 public function changeToTitle($field) { $year = substr($field,0,4); $msg = substr($field,4,1) == "1" ? "上半年" : "下半年"; return $year ."年" .$msg; } /* * '70001'=>反馈成功 * '70004'=>反馈异常,请重新提交 * '70003'=>反馈不能为空 */ //用户反馈 public function FeekBack(Request $request){ $data=$request->all(); //获取用户user_id $userInfo = Auth::guard('api')->user(); //获取前端传来的反馈意见值 $feekback=$data['feekback']; if ($feekback){ $addcontent=FeekBackModel::create([ 'user_id'=>$userInfo['user_id'], 'content'=>$feekback ]); }else{ return response()->json('70003'); } if ($addcontent){ return response()->json('70001'); }else{ return response()->json('70004'); } } /* * 80001=>收藏成功 * 80002=>收藏失败或未授权,users表无该用户信息 * */ //收藏功能 public function Collection(Request $request){ $data=$request->all(); $field=$data['field']; $questionid=$data['questionid']; $userInfo = Auth::guard('api')->user(); // 使用JWT默认设置了关联user表的了 这么一句相当于查询了一次用户表 因此所有字段都可以获取到 //获取用户备考科目type $type = $userInfo->type; //获取users表该用户的id $user_id = $userInfo->id; //入库 $collection=CollectionModel::create([ 'user_id'=>$user_id, 'field'=>$field, 'type'=>$type, 'questionNum'=>$questionid ]); if ($collection){ return response()->json('80001'); }else{ return response()->json('80002'); } } //查询收藏的题目信息(明日再写) public function SearchCollect(Request $request){ $userInfo = Auth::guard('api')->user(); //获取users表该用户的id $users=User::where('user_id','=',$userInfo['user_id'])->get(['id']); //获取users表该用户的id $user_id = $userInfo->id; $searchcollection=CollectionModel::where('user_id','=',$user_id)->get(); } //删除收藏的题目信息(明日再写)) public function DelectCollect(Request $request){ $userInfo = Auth::guard('api')->user(); //获取users表该用户的id $user_id = $userInfo->id; } } <file_sep>/app/SjkModel.php <?php namespace App; use Illuminate\Database\Eloquent\Model; class SjkModel extends Model { //数据库系统工程师(上午题) protected $table="sjk_morning"; protected $fillable=["id","question","questionImg","optiona","optionb","optionc","optiond","answer","answeranalysis","field","questionNum","knowledgeOne","knowledgeTwo"]; }
4d3b2d0762c9cea9065882d2101bbe6d405a6b07
[ "Markdown", "PHP" ]
8
PHP
yogasol/miniAlipay
d12021d4691f63f7e76c8ab5ead622b37420a687
5cd504340f75aec58fc3aaa6f0fb75d5a89d5772
refs/heads/master
<repo_name>XudongOliverShen/POSTagger<file_sep>/README.md # part-of-speech (POS) tagger with char+word embedding and BiLSTM ## Introduction This project implements a part-of-speech (POS) tagger. It uses a convolutional neural network for character-level embedding, along with word-level embedding. POS tagging is achieved by bidirectional LSTM. And it is super fast! ## Usage Firstly clone this project from this repo. To build the tagger ```python python3.5 buildtagger.py sents.train tagger ``` To tag corpus ```python python3.5 runtagger.py sents.test tagger sents.out ``` To evaluate results ```python python3.5 eval.py sents.out sents.answer ``` ## Contributors <NAME> (<EMAIL>) <file_sep>/runtagger.py # python3.5 runtagger.py <test_file_absolute_path> <model_file_absolute_path> <output_file_absolute_path> import os import math import sys import datetime import numpy as np import torch from torch import optim from torch import nn from torch.utils import data import torch.nn.functional as F from collections import defaultdict import itertools from torch.nn.utils.rnn import pack_padded_sequence, pad_packed_sequence WORD_EMBEDDING_DIM = 300 CHAR_EMBEDDING_DIM = 60 CHAR_CONV_K = 3 CHAR_CONV_L = 300 CHAR_CONV_PADDING = 1 LSTM_HIDDEN_SIZE = 1024 LSTM_NUM_LAYERS = 2 DROPOUT_RATE = 0.5 BATCH_SIZE = 64 # move to GPU if possible device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') print('device: ', device) class word_char_embding_model(nn.Module): def __init__(self, size_vocab, size_char): super(word_char_embding_model, self).__init__() self.word2vec = nn.Embedding( num_embeddings = size_vocab, embedding_dim = WORD_EMBEDDING_DIM, padding_idx = word_pad_value) self.char2vec = nn.Embedding( num_embeddings = size_char, embedding_dim = CHAR_EMBEDDING_DIM, padding_idx = char_pad_value) self.char_cnn = nn.Conv1d(in_channels = CHAR_EMBEDDING_DIM, out_channels = CHAR_CONV_L, kernel_size = CHAR_CONV_K, padding = CHAR_CONV_PADDING) def forward(self, padded_words_idx, padded_chars_idx, lengths): # char-level embding # [number of words, CHAR_EMBEDDING_DIM, max number of chars] c_embding = self.char2vec(padded_chars_idx).permute(0,2,1).contiguous() c_embding = self.char_cnn(c_embding) c_embding = c_embding.max(dim=-1)[0] w_embding = self.word2vec(padded_words_idx) add_c_embding = torch.zeros([BATCH_SIZE, w_embding.size(1),CHAR_CONV_L]) start = 0 for i_line, length in enumerate(lengths): add_c_embding[i_line, :length,:] = c_embding[start:start+length] start += length w_embding = torch.cat((w_embding, add_c_embding), dim=2) packed_w_embding = pack_padded_sequence(w_embding, lengths,\ batch_first=True, enforce_sorted=False) return packed_w_embding class POS_tag_model(nn.Module): def __init__(self): super(POS_tag_model, self).__init__() self.BiLSTM = nn.LSTM(input_size = WORD_EMBEDDING_DIM+CHAR_CONV_L, hidden_size = LSTM_HIDDEN_SIZE, num_layers = LSTM_NUM_LAYERS, batch_first = True, bidirectional = True) # self.h0 = torch.randn(LSTM_NUM_LAYERS * 2, # MAX_SENTENCE_SIZE, # LSTM_HIDDEN_SIZE) # self.c0 = torch.randn(LSTM_NUM_LAYERS * 2, # MAX_SENTENCE_SIZE, # LSTM_HIDDEN_SIZE) self.fc = nn.Linear(LSTM_HIDDEN_SIZE * 2, Num_tags) self.softmax = nn.Softmax(dim=-1) def forward(self,x): x = x.view(1, x.size(0), x.size(1)).contiguous() x, (hn, cn) = self.BiLSTM(x) x = self.fc(x) tags = self.softmax(x) return tags class joint_model(nn.Module): def __init__(self, size_vocab, size_char, size_tag): super(joint_model, self).__init__() # language model self.word2vec = nn.Embedding( num_embeddings = size_vocab, embedding_dim = WORD_EMBEDDING_DIM, padding_idx = word_pad_value) self.char2vec = nn.Embedding( num_embeddings = size_char, embedding_dim = CHAR_EMBEDDING_DIM, padding_idx = char_pad_value) self.char_cnn = nn.Conv1d(in_channels = CHAR_EMBEDDING_DIM, out_channels = CHAR_CONV_L, kernel_size = CHAR_CONV_K, padding = CHAR_CONV_PADDING) # POSTAG model self.BiLSTM = nn.LSTM(input_size = WORD_EMBEDDING_DIM+CHAR_CONV_L, hidden_size = LSTM_HIDDEN_SIZE, num_layers = LSTM_NUM_LAYERS, batch_first = True, bidirectional = True) self.fc = nn.Linear(LSTM_HIDDEN_SIZE * 2, Num_tags) self.softmax = nn.Softmax(dim=-1) def forward(self, padded_words_idx, padded_chars_idx, lengths): # language model # char-level embding # [number of words, CHAR_EMBEDDING_DIM, max number of chars] c_embding = self.char2vec(padded_chars_idx).permute(0,2,1).contiguous() c_embding = self.char_cnn(c_embding) c_embding = c_embding.max(dim=-1)[0] w_embding = self.word2vec(padded_words_idx) add_c_embding = torch.zeros([w_embding.size(0), w_embding.size(1),CHAR_CONV_L]).to(device) start = 0 for i_line, length in enumerate(lengths): add_c_embding[i_line, :length,:] = c_embding[start:start+length] start += length w_embding = torch.cat((w_embding, add_c_embding), dim=2) packed_w_embding = pack_padded_sequence(w_embding, lengths,\ batch_first=True) # POSTAG model packed_w_embding, (hn, cn) = self.BiLSTM(packed_w_embding) padded_w_embding, _ = pad_packed_sequence(packed_w_embding, batch_first=True) # TODO this operation will sort the lines in decreasing oder #prediction tags = F.dropout(padded_w_embding, DROPOUT_RATE) tags = self.fc(padded_w_embding) tags = self.softmax(tags) return tags def tag_sentence(test_file, model_file, out_file): # write your code here. You can add functions as well. global Num_words, Num_chars, Num_tags global word_pad_value, char_pad_value # load data idx_dicts, model_state_dict = torch.load(model_file) # char_set = idx_dicts['char_set'] word_set = idx_dicts['word_set'] # tag_set = idx_dicts['tag_set'] char_to_idx_dict = idx_dicts['char_to_idx_dict'] # idx_to_char_dict = idx_dicts['idx_to_char_dict'] word_to_idx_dict = idx_dicts['word_to_idx_dict'] # idx_to_word_dict = idx_dicts['idx_to_word_dict'] # tag_to_idx_dict = idx_dicts['tag_to_idx_dict'] idx_to_tag_dict = idx_dicts['idx_to_tag_dict'] pad_token = '<PAD>' word_pad_value = word_to_idx_dict[pad_token] char_pad_value = char_to_idx_dict[pad_token] Num_words = len(word_set) Num_chars = len(char_to_idx_dict) Num_tags = len(idx_to_tag_dict) # load test examples # get char, word, tag set test_lines_list = [] with open(test_file) as f_in: lines = f_in.read() lines_list = lines.split('\n') # remove empty set while '' in lines_list: lines_list.remove('') Num_lines = len(lines_list) # 1993 for line in lines_list: line_list = line.split() test_lines_list.append(line_list) # words and chars idx list test_words_idx_list = [[word_to_idx_dict[w] if w in word_set\ else word_to_idx_dict['unknown']\ for w in word_list] for word_list in test_lines_list] test_chars_idx_list = [[[char_to_idx_dict[c] for c in w]\ for w in word_list] for word_list in test_lines_list] # instantiate model model = joint_model(size_vocab=Num_words, size_char=Num_chars, size_tag=Num_tags).to(device) model.load_state_dict(model_state_dict) # predict in batches test_lengths = [len(sent) for sent in test_words_idx_list] Num_B = int(np.ceil(Num_lines/BATCH_SIZE)) for i_batch in range(Num_B): if i_batch == (Num_B-1): ori_order = list(range(i_batch*BATCH_SIZE, Num_lines)) else: ori_order = list(range(i_batch*BATCH_SIZE, (i_batch+1)*BATCH_SIZE)) sorted_order = sorted(ori_order, key = lambda i:test_lengths[i], reverse=True) # retrive a batch of words, tags, and chars batch_words_idx = [test_words_idx_list[i] for i in sorted_order] batch_chars_idx = [test_chars_idx_list[i] for i in sorted_order] #pad them to the same length lengths = [len(s) for s in batch_words_idx] padded_words_idx = list(itertools.zip_longest(*batch_words_idx, fillvalue=word_pad_value)) padded_words_idx = torch.LongTensor(padded_words_idx).permute(1,0).to(device) padded_chars_idx= [batch_chars_idx[i][j] for i in range(len(lengths)) for j in range(lengths[i])] padded_chars_idx = list(itertools.zip_longest(*padded_chars_idx, fillvalue=char_pad_value)) padded_chars_idx = torch.LongTensor(padded_chars_idx).permute(1,0).to(device) # predicate pred_tags = model.forward(padded_words_idx,padded_chars_idx, lengths) pred_tags = pred_tags.max(dim=-1)[1].to('cpu') # print converted_tags_idx = [pred_tags[sorted_order.index(i),:] for i in ori_order] output = '' for i in ori_order: try: single_output = ' '.join([test_lines_list[i][j]+'/'+idx_to_tag_dict[int(converted_tags_idx[i-i_batch*BATCH_SIZE][j])]\ for j in range(len(test_lines_list[i]))]) output = output + single_output + '\n' except: ipdb.set_trace() with open(out_file,'a') as f_out: f_out.write(output) print('Finished...') if __name__ == "__main__": # make no changes here test_file = sys.argv[1] model_file = sys.argv[2] out_file = sys.argv[3] start_time = datetime.datetime.now() tag_sentence(test_file, model_file, out_file) end_time = datetime.datetime.now() print('Time:', end_time - start_time)<file_sep>/buildtagger.py # python3.5 buildtagger.py <train_file_absolute_path> <model_file_absolute_path> import os import math import sys import datetime import numpy as np import torch from torch import optim from torch import nn from torch.utils import data import torch.nn.functional as F from collections import defaultdict import random import itertools from torch.nn.utils.rnn import pack_padded_sequence, pad_packed_sequence WORD_EMBEDDING_DIM = 300 CHAR_EMBEDDING_DIM = 60 CHAR_CONV_K = 3 CHAR_CONV_L = 300 CHAR_CONV_PADDING = 1 LSTM_HIDDEN_SIZE = 1024 LSTM_NUM_LAYERS = 2 DROPOUT_RATE = 0.5 BATCH_SIZE = 64 SAVE_FILE = 'test.log' # move to GPU if possible device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') print('device: ', device) class joint_model(nn.Module): def __init__(self, size_vocab, size_char, size_tag): super(joint_model, self).__init__() # language model self.word2vec = nn.Embedding( num_embeddings = size_vocab, embedding_dim = WORD_EMBEDDING_DIM, padding_idx = word_pad_value) self.char2vec = nn.Embedding( num_embeddings = size_char, embedding_dim = CHAR_EMBEDDING_DIM, padding_idx = char_pad_value) self.char_cnn = nn.Conv1d(in_channels = CHAR_EMBEDDING_DIM, out_channels = CHAR_CONV_L, kernel_size = CHAR_CONV_K, padding = CHAR_CONV_PADDING) # POSTAG model self.BiLSTM = nn.LSTM(input_size = WORD_EMBEDDING_DIM+CHAR_CONV_L, hidden_size = LSTM_HIDDEN_SIZE, num_layers = LSTM_NUM_LAYERS, batch_first = True, bidirectional = True) self.fc = nn.Linear(LSTM_HIDDEN_SIZE * 2, Num_tags) self.softmax = nn.Softmax(dim=-1) def forward(self, padded_words_idx, padded_chars_idx, lengths): # language model # char-level embding # [number of words, CHAR_EMBEDDING_DIM, max number of chars] c_embding = self.char2vec(padded_chars_idx).permute(0,2,1).contiguous() c_embding = self.char_cnn(c_embding) c_embding = c_embding.max(dim=-1)[0] w_embding = self.word2vec(padded_words_idx) add_c_embding = torch.zeros([BATCH_SIZE, w_embding.size(1),CHAR_CONV_L]).to(device) start = 0 for i_line, length in enumerate(lengths): add_c_embding[i_line, :length,:] = c_embding[start:start+length] start += length w_embding = torch.cat((w_embding, add_c_embding), dim=2) packed_w_embding = pack_padded_sequence(w_embding, lengths,\ batch_first=True) # POSTAG model packed_w_embding, (hn, cn) = self.BiLSTM(packed_w_embding) padded_w_embding, _ = pad_packed_sequence(packed_w_embding, batch_first=True) # TODO this operation will sort the lines in decreasing oder #prediction tags = F.dropout(padded_w_embding, DROPOUT_RATE) tags = self.fc(padded_w_embding) tags = self.softmax(tags) return tags def train_model(train_file, model_file): global char_set, word_set, tag_set global Num_words, Num_chars, Num_tags, Num_lines global char_to_idx_dict, word_to_idx_dict, tag_to_idx_dict global idx_to_char_dict, idx_to_word_dict, idx_to_tag_dict global word_pad_value, char_pad_value # initialize sets word_set = set() # word set char_set = set() # char set tag_set = set() # word tag set training_words_list = [] training_tags_list = [] # get char, word, tag set with open(train_file) as f_in: lines = f_in.read() lines_list = lines.split('\n') # remove empty set while '' in lines_list: lines_list.remove('') Num_lines = len(lines_list) # 39832 for line in lines_list: line_list = line.split() word_list = [w_t_pair[:w_t_pair.rindex('/')] for w_t_pair in line_list] tag_list = [w_t_pair[w_t_pair.rindex('/')+1:] for w_t_pair in line_list] training_words_list.append(word_list) training_tags_list.append(tag_list) word_set.update(set(word_list)) tag_set.update(set(tag_list)) char_set.update(set([c for w in word_list for c in w])) # indexing char_to_idx_dict = {c: (i+1) for i, c in enumerate(char_set)} idx_to_char_dict = {(i+1): c for i, c in enumerate(char_set)} word_to_idx_dict = {w: (i+2) for i, w in enumerate(word_set)} idx_to_word_dict = {(i+2): w for i, w in enumerate(word_set)} tag_to_idx_dict = {t: i for i, t in enumerate(tag_set)} idx_to_tag_dict = {i: t for i, t in enumerate(tag_set)} #add unknown & pad word_set.add('unkown') word_set.add('<PAD>') word_to_idx_dict['<PAD>'] = 0 idx_to_word_dict[0] = '<PAD>' word_to_idx_dict['unknown'] = 1 idx_to_word_dict[1] = 'unknown' char_set.add('<PAD>') char_to_idx_dict['<PAD>'] = 0 idx_to_char_dict[0] = '<PAD>' # calculate number of words, tags, chars, including unknown and <PAD> Num_words = len(word_set) # 44391 Num_chars = len(char_set) # 85 Num_tags = len(tag_set) # 45 # all training examples convert to idxs training_words_idx_list = [[word_to_idx_dict[w] for w in word_list]\ for word_list in training_words_list] training_chars_idx_list = [[[char_to_idx_dict[c] for c in w]\ for w in word_list] for word_list in training_words_list] training_tags_idx_list = [[tag_to_idx_dict[t] for t in tag_list]\ for tag_list in training_tags_list] idx_dicts = {} idx_dicts['char_set'] = char_set idx_dicts['word_set'] = word_set idx_dicts['tag_set'] = tag_set idx_dicts['char_to_idx_dict'] = char_to_idx_dict idx_dicts['idx_to_char_dict'] = idx_to_char_dict idx_dicts['word_to_idx_dict'] = word_to_idx_dict idx_dicts['idx_to_word_dict'] = idx_to_word_dict idx_dicts['tag_to_idx_dict'] = tag_to_idx_dict idx_dicts['idx_to_tag_dict'] = idx_to_tag_dict # idx_dicts['training_words_list'] = training_words_list # idx_dicts['training_tags_list'] = training_tags_list # idx_dicts['training_words_idx_list'] = training_words_idx_list # idx_dicts['training_chars_idx_list'] = training_chars_idx_list # idx_dicts['training_tags_idx_list'] = training_tags_idx_list # with open('idx_dicts', 'wb') as f: # pickle.dump(idx_dicts, f) # # directly load following data for debugging efficiency # idx_dicts = pickle.load(open("idx_dicts", "rb")) # char_set = idx_dicts['char_set'] # word_set = idx_dicts['word_set'] # tag_set = idx_dicts['tag_set'] # char_to_idx_dict = idx_dicts['char_to_idx_dict'] # idx_to_char_dict = idx_dicts['idx_to_char_dict'] # word_to_idx_dict = idx_dicts['word_to_idx_dict'] # idx_to_word_dict = idx_dicts['idx_to_word_dict'] # tag_to_idx_dict = idx_dicts['tag_to_idx_dict'] # idx_to_tag_dict = idx_dicts['idx_to_tag_dict'] # training_words_list = idx_dicts['training_words_list'] # training_tags_list = idx_dicts['training_tags_list'] # training_words_idx_list = idx_dicts['training_words_idx_list'] # training_chars_idx_list = idx_dicts['training_chars_idx_list'] # training_tags_idx_list = idx_dicts['training_tags_idx_list'] # Num_words = len(word_set) # 44391 # Num_chars = len(char_set) # 85 # Num_tags = len(tag_set) # 45 # Num_lines = len(training_words_list) # 39832 pad_token = '<PAD>' word_pad_value = word_to_idx_dict[pad_token] char_pad_value = char_to_idx_dict[pad_token] # put data on GPU model = joint_model(size_vocab=Num_words, size_char=Num_chars, size_tag=Num_tags).to(device) adam = optim.Adam(model.parameters(), lr=0.001) loss = nn.CrossEntropyLoss(ignore_index=-100, reduction='elementwise_mean') Num_B = int(Num_lines/BATCH_SIZE) for i_epoch in range(4): # adjust learning rate if i_epoch == 3: for param_group in adam.param_groups: param_group['lr'] = 0.0001 training_lengths = [len(sent) for sent in training_words_idx_list] for i_batch in range(Num_B): # sort in decreasing order ori_order = list(range(i_batch*BATCH_SIZE, (i_batch+1)*BATCH_SIZE)) sorted_order = sorted(ori_order, key = lambda i:training_lengths[i], reverse=True) # retrive a batch of words, tags, and chars batch_words_idx = [training_words_idx_list[i] for i in sorted_order] batch_chars_idx = [training_chars_idx_list[i] for i in sorted_order] batch_tags_idx = [training_tags_idx_list[i] for i in sorted_order] #pad them to the same length lengths = [len(s) for s in batch_words_idx] padded_words_idx = list(itertools.zip_longest(*batch_words_idx, fillvalue=word_pad_value)) padded_words_idx = torch.LongTensor(padded_words_idx).permute(1,0).to(device) padded_tags_idx = list(itertools.zip_longest(*batch_tags_idx, fillvalue=-100)) padded_tags_idx = torch.LongTensor(padded_tags_idx).permute(1,0).to(device) padded_chars_idx= [batch_chars_idx[i][j] for i in range(BATCH_SIZE) for j in range(lengths[i])] padded_chars_idx = list(itertools.zip_longest(*padded_chars_idx, fillvalue=char_pad_value)) padded_chars_idx = torch.LongTensor(padded_chars_idx).permute(1,0).to(device) #train model pred_tags = model.forward(padded_words_idx,padded_chars_idx, lengths) # [1, number of words, 45] pred_tags = pred_tags.permute(0,2,1) loss_value = loss(pred_tags, padded_tags_idx) adam.zero_grad() loss_value.backward() adam.step() print("Time",datetime.datetime.now(), "Epoch:", i_epoch+1, "Loss:", loss_value.data.item()) to_be_shuffled_list = list(zip(training_words_idx_list, training_chars_idx_list, training_tags_idx_list)) random.shuffle(to_be_shuffled_list) training_words_idx_list[:], training_chars_idx_list[:], training_tags_idx_list[:] = zip(*to_be_shuffled_list) torch.save((idx_dicts, model.state_dict()), model_file) print('Finished...') if __name__ == "__main__": # make no changes here train_file = sys.argv[1] model_file = sys.argv[2] start_time = datetime.datetime.now() train_model(train_file, model_file) end_time = datetime.datetime.now() print('Time:', end_time - start_time)
0dca6ee7f4056911ade4c6d9d19ce9e6088531de
[ "Markdown", "Python" ]
3
Markdown
XudongOliverShen/POSTagger
e282b5c287e04a17ad83345c82e85e9e98da45c8
2f6327225151e9052e15066fe0c5ada5d0c8aa2a
refs/heads/master
<repo_name>nmrichards/oyster_card<file_sep>/spec/station_spec.rb require 'station' describe Station do subject(:station){described_class.new( location: 'London', zone: 1 )} describe '#initialize' do it 'stores a location' do expect(station.location).to eq "London" end it 'stores a zone' do expect(station.zone).to eq 1 end end end <file_sep>/lib/journeylog.rb require_relative 'journey' class JourneyLog attr_reader :journey, :current_journey def initialize @journeys = [] @current_journey = {{entry_station: nil} => {exit_station: nil}} end def start(entry_station) @current_journey = {{entry_station: entry_station} => {exit_station: nil}} end def finish(exit_station) @current_journey.values[0][:exit_station] = exit_station complete_journey end def complete_journey @journeys << current_journey return Journey.new.fare(complete?) @current_journey = {{entry_station: nil} => {exit_station: nil}} end def complete? current_journey.keys[0].values[0].nil? || current_journey.values[0].values[0].nil? ? false : true end def in_journey? !!current_journey.keys[0].values[0] end def journeys @journeys.dup end end <file_sep>/spec/journeylog_spec.rb require 'journeylog' describe JourneyLog do let(:entry_station) { double :entry_station } let(:exit_station ) { double :exit_station } subject(:journeylog) { described_class.new } let(:journey) { {{entry_station: entry_station} => {exit_station: exit_station}} } it 'remembers journey history' do journeylog.start entry_station journeylog.finish exit_station expect(journeylog.journeys).to include journey end # describe '#complete' do # # let(:journey) { {{entry_station: entry_station} => {exit_station: nil}} } # it 'starts a journey' do # expect(journey).to receive(:new) # end # end end <file_sep>/lib/journey.rb class Journey MINIMUM_FARE = 1 PENALTY_FARE = 6 def fare(complete) complete ? MINIMUM_FARE : PENALTY_FARE end end <file_sep>/lib/station.rb class Station attr_reader :location, :zone def initialize(location_zone = {}) @location = location_zone[:location] @zone = location_zone[:zone] end end <file_sep>/spec/journey_spec.rb require 'journey' describe Journey do subject(:journey){described_class.new} it 'takes off the minimum fare'do expect(journey.fare(true)).to eq Journey::MINIMUM_FARE end it 'charges a penalty' do expect(journey.fare(false)).to be Journey::PENALTY_FARE end end
9921937541ba876dc6fc6c6cdb2048730242a85a
[ "Ruby" ]
6
Ruby
nmrichards/oyster_card
a297d22fbf3a925f601b2194c17b449c6bce32b4
232a23e67953352d4c50ff22f5ec7aed61e73249
refs/heads/master
<file_sep>import tweepy # tweepy api wrapper import settings # settings module import keys # dev keys from modules import streamlistener def main(): """ Tweepy oAuth handling. Uses settings taken from settings.py """ auth = tweepy.OAuthHandler(keys.consumer_key, keys.consumer_secret) auth.set_access_token(keys.access_token, keys.access_token_secret) api = tweepy.API(auth) """ Instantiate listener and filter incoming tweets to only select from a particular set of tags """ myStreamListener = streamlistener.StreamListener(api=api, account=keys.account_name, azurekey=keys.azurekey) myStream = tweepy.Stream(auth=api.auth, listener=myStreamListener) myStream.filter(track=settings.stock_list) """ Some weird python thing to make main work(?). Look into this. """ if __name__ == "__main__": main() <file_sep>#so I can import this directory <file_sep># TODO: # Figure out how to tell which tweet is to which company # write it to azure already # scores are in a dict, just for reference import tweepy from vaderanalysis import SentimentAnalysis from tableaccess import TableAccess class StreamListener(tweepy.StreamListener): def __init__(self, api, account, azurekey): self.api = api self.analyzer = SentimentAnalysis() self.writer = TableAccess(account, azurekey) """ @param status: The tweet that the listener found Listener function. Will check hashtags and delete if target hashtag is found """ def on_status(self, status): score = self.analyzer.return_scores(status.text.encode('utf-8')) print status.text neg = score['neg'] neu = score['neu'] pos = score['pos'] print "pos: " print score['pos'] print "neu: " print neu print "neg: " print neg #self.writer.write_to_table(stock="STOCKHERE", pos, neu, neg) def on_delete(self, status_id, user_id): """Called when a delete notice arrives for a status""" pass def on_limit(self, track): """Called when a limitation notice arrives""" pass def on_error(self, status_code): """Called when a non-200 status code is returned""" print 'An error has occured! Status code = %s' % status_code return True # keep stream alive def on_timeout(self): """Called when stream connection times out""" print 'Snoozing Zzzzzz' def on_disconnect(self, notice): """Called when twitter sends a disconnect notice Disconnect codes are listed here: https://dev.twitter.com/docs/streaming-apis/messages#Disconnect_messages_disconnect """ print (notice) def on_warning(self, notice): """Called when a disconnection warning message arrives""" print (notice) <file_sep># Put your twitter application keys and access tokens here consumer_key = "" consumer_secret = "" access_token = "" access_token_secret = "" # Put your azure information here account_key = "" azurekey = "" # Stocks to follow stock_list = ["MSFT", "AAPL", "JNJ"] <file_sep>adal==0.4.6 asn1crypto==0.22.0 azure==2.0.0 azure-batch==3.0.0 azure-common==1.1.8 azure-datalake-store==0.0.15 azure-graphrbac==0.30.0 azure-keyvault==0.3.6 azure-mgmt==1.0.0 azure-mgmt-authorization==0.30.0 azure-mgmt-batch==4.0.0 azure-mgmt-cdn==0.30.3 azure-mgmt-cognitiveservices==1.0.0 azure-mgmt-compute==1.0.0 azure-mgmt-containerregistry==0.2.1 azure-mgmt-datalake-analytics==0.1.6 azure-mgmt-datalake-nspkg==2.0.0 azure-mgmt-datalake-store==0.1.6 azure-mgmt-devtestlabs==2.0.0 azure-mgmt-dns==1.0.1 azure-mgmt-documentdb==0.1.3 azure-mgmt-iothub==0.2.2 azure-mgmt-keyvault==0.31.0 azure-mgmt-logic==2.1.0 azure-mgmt-monitor==0.2.1 azure-mgmt-network==1.0.0 azure-mgmt-nspkg==2.0.0 azure-mgmt-rdbms==0.1.0 azure-mgmt-redis==4.1.0 azure-mgmt-resource==1.1.0 azure-mgmt-scheduler==1.1.2 azure-mgmt-sql==0.5.3 azure-mgmt-storage==1.0.0 azure-mgmt-trafficmanager==0.30.0 azure-mgmt-web==0.32.0 azure-nspkg==2.0.0 azure-servicebus==0.21.1 azure-servicefabric==5.6.130 azure-servicemanagement-legacy==0.20.6 azure-storage==0.34.3 certifi==2017.7.27.1 cffi==1.10.0 chardet==3.0.4 cryptography==2.0.3 enum34==1.1.6 futures==3.1.1 idna==2.6 ipaddress==1.0.18 isodate==0.5.4 keyring==10.4.0 msrest==0.4.12 msrestazure==0.4.11 nltk==3.2.4 numpy==1.13.1 oauthlib==2.0.2 pathlib2==2.3.0 pycparser==2.18 PyJWT==1.5.2 python-dateutil==2.6.1 requests==2.18.4 requests-oauthlib==0.8.0 scandir==1.5 six==1.10.0 tweepy==3.5.0 urllib3==1.22 vaderSentiment==2.5 <file_sep># TODO: # Document this short module # lol from vaderSentiment.vaderSentiment import SentimentIntensityAnalyzer class SentimentAnalysis(): def __init__(self): self.analyzer = SentimentIntensityAnalyzer() def return_scores(self, sentence): snt = self.analyzer.polarity_scores(sentence) return snt <file_sep># TODO: # Query for latest entry # fix writing # test schema # SCHEMA: # PARTITION KEY = date # ROW KEY = an int that increases by 1 # stock is an attribute # pos, neu, neg are attributes from azure.storage.table import TableService, Entity import datetime class TableAccess(): def __init__(self, account, azurekey): self.account = account self.azurekey = azurekey self.table_service = TableService(account_name=account, account_key=azurekey) def create_table(self, table_name): self.table_service.create_table(table_name) def write_to_table(self, stock, pos, neu, neg): now = datetime.datetime.now() task = Entity() task.PartitionKey = now.month + "-" + now.date + "-" + now.year #task.RowKey = self.get_latest_entry(table_name) task.pos = pos task.neu = neu task.neg = neg task.stock = stock self.table_service.insert_entity(table_name, task) def query_table(self, table_name): pass def delete_entity(self, table_name): pass def get_latest_entry(self, table_name): #return id of latest entry for rowkey pass
7e713c282d8e1f06f68c480f21f91598e2c5b87f
[ "Python", "Text" ]
7
Python
alew104/StockSentiment
18ad272226cac789f86f1ec72e129a689841f4e7
ac5870acc5c3526fea415c16bf578c7693cfad0f
refs/heads/master
<repo_name>DvDs20/4-praktinis-IS<file_sep>/src/controllers/LoginAndRegistrationWindowController.java package controllers; import backEnd.UserRepository; import javafx.event.ActionEvent; import javafx.fxml.FXML; import javafx.fxml.FXMLLoader; import javafx.scene.Parent; import javafx.scene.Scene; import javafx.scene.control.Button; import javafx.scene.control.PasswordField; import javafx.scene.control.TextField; import javafx.scene.layout.Pane; import javafx.stage.Stage; import models.User; import security.EncryptDecryptFile; import javax.swing.*; import java.io.File; import java.io.IOException; import java.io.PrintWriter; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; public class LoginAndRegistrationWindowController { @FXML private Pane loginPane; @FXML private TextField usernameTextField; @FXML private PasswordField passwordField; @FXML private Button signInButton; @FXML private Button signUpButton; @FXML private Pane registrationPane; @FXML private TextField usernameForRegistrationTextField; @FXML private PasswordField passwordForRegistrationField; @FXML private PasswordField confirmPasswordField; @FXML private Button backToSignInPaneButton; @FXML private Button confirmRegistrationButton; UserRepository userRepository = new UserRepository(); public void signInButtonClicked(ActionEvent actionEvent) throws IOException { signInButton.getScene().getWindow().hide(); try { User user = userRepository.login(usernameTextField.getText(), passwordField.getText()); if (user != null) { userRepository.setUser(user); EncryptDecryptFile.decryptFile("C:\\Users\\deivi\\Documents\\Informacijos saugumas\\4 praktinis darbas\\UsersFiles\\" + user.getUsername() + ".txt"); FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource("../frontEnd/mainWindow.fxml")); Parent parent = fxmlLoader.load(); Stage stage = new Stage(); stage.setTitle(user.getUsername()); stage.setScene(new Scene(parent)); stage.setResizable(false); stage.show(); } else { throw new Exception("user = null"); } } catch (Exception exception) { JOptionPane.showMessageDialog(null, exception.getMessage()); Parent parent = FXMLLoader.load(getClass().getResource("../frontEnd/login&RegistrationWindow.fxml")); Stage stage = new Stage(); stage.setTitle("Sign in | Sign up"); stage.setScene(new Scene(parent)); stage.show(); } } public void signUpButtonClicked(ActionEvent actionEvent) { loginPane.setVisible(!loginPane.isVisible()); registrationPane.setVisible(!registrationPane.isVisible()); } public void backToSignInPaneButtonClicked(ActionEvent actionEvent) { registrationPane.setVisible(!registrationPane.isVisible()); loginPane.setVisible(!loginPane.isVisible()); } public void confirmRegistrationButtonClicked(ActionEvent actionEvent) { try { userRepository.register(usernameForRegistrationTextField.getText(), passwordForRegistrationField.getText(), confirmPasswordField.getText()); Path path = Paths.get("C:\\Users\\deivi\\Documents\\Informacijos saugumas\\4 praktinis darbas\\UsersFiles\\" + usernameForRegistrationTextField.getText() + ".txt"); try { Path filePath = Files.createFile(path); System.out.println("File created at path: " + filePath); } catch (IOException ioException) { ioException.printStackTrace(); } EncryptDecryptFile.encryptFile(String.valueOf(path)); JOptionPane.showMessageDialog(null, "Registration successful!"); registrationPane.setVisible(!registrationPane.isVisible()); loginPane.setVisible(!loginPane.isVisible()); } catch (Exception exception) { JOptionPane.showMessageDialog(null, exception.getMessage()); } } } <file_sep>/src/dataBase/DataBaseConnection.java package dataBase; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; public class DataBaseConnection extends DataBaseConfig{ Connection connection; public Connection getConnection() throws ClassNotFoundException, SQLException { String connectionString = "jdbc:mysql://" + dataBaseHost + ":" + dataBasePort + "/" + dataBaseName; Class.forName("com.mysql.cj.jdbc.Driver"); connection = DriverManager.getConnection(connectionString, dataBaseUser, dataBasePassword); return connection; } } <file_sep>/src/security/HashPassword.java package security; import org.springframework.security.crypto.bcrypt.BCrypt; import java.math.BigInteger; import java.nio.charset.StandardCharsets; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; public class HashPassword { public static String hashPassword(String passwordPlainText) throws NoSuchAlgorithmException { MessageDigest MD5 = MessageDigest.getInstance("MD5"); byte[] digest = MD5.digest(passwordPlainText.getBytes(StandardCharsets.UTF_8)); return String.format("%032x%n", new BigInteger(1, digest)); } } <file_sep>/src/security/EncryptDecryptFile.java package security; import javax.crypto.Cipher; import javax.crypto.spec.IvParameterSpec; import javax.crypto.spec.SecretKeySpec; import java.io.*; import java.nio.charset.StandardCharsets; import java.security.MessageDigest; import java.util.Base64; public class EncryptDecryptFile { private static final String ALGORITHM = "AES"; private static final String KEY = "VerySecretKey"; private static final String IV = "AAAASSSSDDDDFFFF"; public static void encryptFile(String filePath) throws Exception { String fileText = readFile(filePath); String encryptedFileText = encrypt(KEY, IV, fileText); PrintWriter writer = new PrintWriter(filePath, StandardCharsets.UTF_8); writer.print(encryptedFileText); writer.close(); } public static void decryptFile(String filePath) throws Exception { String fileText = readFile(filePath); String decryptedFileText = decrypt(KEY, IV, fileText); PrintWriter writer = new PrintWriter(filePath, StandardCharsets.UTF_8); writer.print(decryptedFileText); writer.close(); } public static String encrypt(String key, String iv, String fileText) throws Exception { byte[] bytesOfKey = key.getBytes(StandardCharsets.UTF_8); MessageDigest messageDigest = MessageDigest.getInstance("MD5"); byte[] keyBytes = messageDigest.digest(bytesOfKey); final byte[] ivBytes = iv.getBytes(); SecretKeySpec secretKeySpec = new SecretKeySpec(keyBytes, ALGORITHM); Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec, new IvParameterSpec(ivBytes)); final byte[] resultBytes = cipher.doFinal(fileText.getBytes()); return Base64.getMimeEncoder().encodeToString(resultBytes); } public static String decrypt(String key, String iv, String encryptedFileText) throws Exception{ byte[] bytesOfKey = key.getBytes(StandardCharsets.UTF_8); MessageDigest messageDigest = MessageDigest.getInstance("MD5"); byte[] keyBytes = messageDigest.digest(bytesOfKey); final byte[] ivBytes = iv.getBytes(); final byte[] encryptedBytes = Base64.getMimeDecoder().decode(encryptedFileText); SecretKeySpec secretKeySpec = new SecretKeySpec(keyBytes, ALGORITHM); Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); cipher.init(Cipher.DECRYPT_MODE, secretKeySpec, new IvParameterSpec(ivBytes)); final byte[] resultBytes = cipher.doFinal(encryptedBytes); return new String(resultBytes); } public static String readFile(String fileName) throws Exception { BufferedReader bufferedReader = new BufferedReader(new FileReader(fileName)); try { StringBuilder stringBuilder = new StringBuilder(); String line = bufferedReader.readLine(); while (line != null) { stringBuilder.append(line); stringBuilder.append(System.lineSeparator()); line = bufferedReader.readLine(); } return stringBuilder.toString(); } finally { bufferedReader.close(); } } }
4fcf6310f9f946faaa13d8d3167055d84ac9af2e
[ "Java" ]
4
Java
DvDs20/4-praktinis-IS
a0b5265dc0d44d90a96300d0dcd3829264fc31c0
22ddf66053b351349ae7f7892f6f7a3757b550fe
refs/heads/master
<repo_name>AishwaryaVelumani/Entity-Recognition-In-Resumes-SpaCy<file_sep>/env/Lib/site-packages/wasabi/tables.py # coding: utf8 from __future__ import unicode_literals, print_function import os from .util import COLORS from .util import color as _color from .util import supports_ansi, to_string, zip_longest, basestring_ ALIGN_MAP = {"l": "<", "r": ">", "c": "^"} def table( data, header=None, footer=None, divider=False, widths="auto", max_col=30, spacing=3, aligns=None, multiline=False, env_prefix="WASABI", color_values=None, fg_colors=None, bg_colors=None, ): """Format tabular data. data (iterable / dict): The data to render. Either a list of lists (one per row) or a dict for two-column tables. header (iterable): The header columns. footer (iterable): The footer columns. divider (bool): Show a divider line between header/footer and body. widths (iterable or 'auto'): Column widths in order. If "auto", widths will be calculated automatically based on the largest value. max_col (int): Maximum column width. spacing (int): Spacing between columns, in spaces. aligns (iterable / unicode): Column alignments in order. 'l' (left, default), 'r' (right) or 'c' (center). If a string, value is used for all columns. multiline (bool): If a cell value is a list of a tuple, render it on multiple lines, with one value per line. env_prefix (unicode): Prefix for environment variables, e.g. WASABI_LOG_FRIENDLY. color_values (dict): Add or overwrite color values, name mapped to value. fg_colors (iterable): Foreground colors, one per column. None can be specified for individual columns to retain the default foreground color. bg_colors (iterable): Background colors, one per column. None can be specified for individual columns to retain the default background color. RETURNS (unicode): The formatted table. """ if fg_colors is not None or bg_colors is not None: colors = dict(COLORS) if color_values is not None: colors.update(color_values) if fg_colors is not None: fg_colors = [colors.get(fg_color, fg_color) for fg_color in fg_colors] if bg_colors is not None: bg_colors = [colors.get(bg_color, bg_color) for bg_color in bg_colors] if isinstance(data, dict): data = list(data.items()) if multiline: zipped_data = [] for i, item in enumerate(data): vals = [v if isinstance(v, (list, tuple)) else [v] for v in item] zipped_data.extend(list(zip_longest(*vals, fillvalue=""))) if i < len(data) - 1: zipped_data.append(["" for i in item]) data = zipped_data if widths == "auto": widths = _get_max_widths(data, header, footer, max_col) settings = { "widths": widths, "spacing": spacing, "aligns": aligns, "env_prefix": env_prefix, "fg_colors": fg_colors, "bg_colors": bg_colors, } divider_row = row(["-" * width for width in widths], **settings) rows = [] if header: rows.append(row(header, **settings)) if divider: rows.append(divider_row) for i, item in enumerate(data): rows.append(row(item, **settings)) if footer: if divider: rows.append(divider_row) rows.append(row(footer, **settings)) return "\n{}\n".format("\n".join(rows)) def row( data, widths="auto", spacing=3, aligns=None, env_prefix="WASABI", fg_colors=None, bg_colors=None, ): """Format data as a table row. data (iterable): The individual columns to format. widths (list, int or 'auto'): Column widths, either one integer for all columns or an iterable of values. If "auto", widths will be calculated automatically based on the largest value. spacing (int): Spacing between columns, in spaces. aligns (list / unicode): Column alignments in order. 'l' (left, default), 'r' (right) or 'c' (center). If a string, value is used for all columns. env_prefix (unicode): Prefix for environment variables, e.g. WASABI_LOG_FRIENDLY. fg_colors (list): Foreground colors for the columns, in order. None can be specified for individual columns to retain the default foreground color. bg_colors (list): Background colors for the columns, in order. None can be specified for individual columns to retain the default background color. RETURNS (unicode): The formatted row. """ env_log_friendly = os.getenv("{}_LOG_FRIENDLY".format(env_prefix), False) show_colors = ( supports_ansi() and not env_log_friendly and (fg_colors is not None or bg_colors is not None) ) cols = [] if isinstance(aligns, basestring_): # single align value aligns = [aligns for _ in data] if not hasattr(widths, "__iter__") and widths != "auto": # single number widths = [widths for _ in range(len(data))] for i, col in enumerate(data): align = ALIGN_MAP.get(aligns[i] if aligns and i < len(aligns) else "l") col_width = len(col) if widths == "auto" else widths[i] tpl = "{:%s%d}" % (align, col_width) col = tpl.format(to_string(col)) if show_colors: fg = fg_colors[i] if fg_colors is not None else None bg = bg_colors[i] if bg_colors is not None else None col = _color(col, fg=fg, bg=bg) cols.append(col) return (" " * spacing).join(cols) def _get_max_widths(data, header, footer, max_col): all_data = list(data) if header: all_data.append(header) if footer: all_data.append(footer) widths = [[len(to_string(col)) for col in item] for item in all_data] return [min(max(w), max_col) for w in list(zip(*widths))] <file_sep>/train.py ############################################ NOTE ######################################################## # # Creates NER training data in Spacy format from JSON downloaded from Dataturks. # # Outputs the Spacy training data which can be used for Spacy training. # ############################################################################################################ import json import random import logging from sklearn.metrics import classification_report from sklearn.metrics import precision_recall_fscore_support from spacy.gold import GoldParse from spacy.scorer import Scorer from sklearn.metrics import accuracy_score def convert_dataturks_to_spacy(dataturks_JSON_FilePath): try: training_data = [] lines=[] #with open(dataturks_JSON_FilePath, 'r') as f: with open(dataturks_JSON_FilePath, 'r', encoding='utf-8') as f: lines = f.readlines() for line in lines: #data = json.loads(line) data = json.load(line) text = data['content'] entities = [] for annotation in data['annotation']: #only a single point in text annotation. point = annotation['points'][0] labels = annotation['label'] # handle both list of labels or a single label. if not isinstance(labels, list): labels = [labels] for label in labels: #dataturks indices are both inclusive [start, end] but spacy is not [start, end) entities.append((point['start'], point['end'] + 1 ,label)) training_data.append((text, {"entities" : entities})) return training_data except Exception as e: logging.exception("Unable to process " + dataturks_JSON_FilePath + "\n" + "error = " + str(e)) return None import spacy ################### Train Spacy NER.########### def train_spacy(): TRAIN_DATA = convert_dataturks_to_spacy("traindata.json") nlp = spacy.blank('en') # create blank Language class # create the built-in pipeline components and add them to the pipeline # nlp.create_pipe works for built-ins that are registered with spaCy if 'ner' not in nlp.pipe_names: ner = nlp.create_pipe('ner') nlp.add_pipe(ner, last=True) # add labels for _, annotations in TRAIN_DATA: for ent in annotations.get('entities'): ner.add_label(ent[2]) # get names of other pipes to disable them during training other_pipes = [pipe for pipe in nlp.pipe_names if pipe != 'ner'] with nlp.disable_pipes(*other_pipes): # only train NER optimizer = nlp.begin_training() for itn in range(10): print("Statring iteration " + str(itn)) random.shuffle(TRAIN_DATA) losses = {} for text, annotations in TRAIN_DATA: nlp.update( [text], # batch of texts [annotations], # batch of annotations drop=0.2, # dropout - make it harder to memorise data sgd=optimizer, # callable to update weights losses=losses) print(losses) #test the model and evaluate it #examples = convert_dataturks_to_spacy("/home/abhishekn/dataturks/entityrecognition/testdata.json") examples = convert_dataturks_to_spacy("testdata.json") tp=0 tr=0 tf=0 ta=0 c=0 for text,annot in examples: f=open("resume"+str(c)+".txt","w") doc_to_test=nlp(text) d={} for ent in doc_to_test.ents: d[ent.label_]=[] for ent in doc_to_test.ents: d[ent.label_].append(ent.text) for i in set(d.keys()): f.write("\n\n") f.write(i +":"+"\n") for j in set(d[i]): f.write(j.replace('\n','')+"\n") d={} for ent in doc_to_test.ents: d[ent.label_]=[0,0,0,0,0,0] for ent in doc_to_test.ents: doc_gold_text= nlp.make_doc(text) gold = GoldParse(doc_gold_text, entities=annot.get("entities")) y_true = [ent.label_ if ent.label_ in x else 'Not '+ent.label_ for x in gold.ner] y_pred = [x.ent_type_ if x.ent_type_ ==ent.label_ else 'Not '+ent.label_ for x in doc_to_test] if(d[ent.label_][0]==0): #f.write("For Entity "+ent.label_+"\n") #f.write(classification_report(y_true, y_pred)+"\n") (p,r,f,s)= precision_recall_fscore_support(y_true,y_pred,average='weighted') a=accuracy_score(y_true,y_pred) d[ent.label_][0]=1 d[ent.label_][1]+=p d[ent.label_][2]+=r d[ent.label_][3]+=f d[ent.label_][4]+=a d[ent.label_][5]+=1 c+=1 for i in d: print("\n For Entity "+i+"\n") print("Accuracy : "+str((d[i][4]/d[i][5])*100)+"%") print("Precision : "+str(d[i][1]/d[i][5])) print("Recall : "+str(d[i][2]/d[i][5])) print("F-score : "+str(d[i][3]/d[i][5])) train_spacy() #BREAK UP ON JSON OBJECT #{"content": "Govardhana K #\nSenior Software Engineer # \n\nBengaluru, Karnataka, Karnataka - # Email me on Indeed: indeed.com/r/Govardhana-K/\nb2de315d95905b68\n # \nTotal IT experience 5 Years 6 Months # \nCloud Lending Solutions INC 4 Month • Salesforce Developer # \nOracle 5 Years 2 Month • Core Java Developer # \nLanguages Core Java, Go Lang\nOracle PL-SQL programming,\nSales Force Developer with APEX. # \n\nDesignations & Promotions # \n\nWilling to relocate: Anywhere # \n\nWORK EXPERIENCE\n\nSenior Software Engineer # \n\nCloud Lending Solutions - Bangalore, Karnataka -\n\nJanuary 2018 to Present # \n\nPresent\n\nSenior Consultant\n\nOracle - Bangalore, Karnataka -\n # \nNovember 2016 to December 2017\n\nStaff Consultant\n\nOracle - Bangalore, Karnataka -\n # \nJanuary 2014 to October 2016\n # \nAssociate Consultant\n\nOracle - Bangalore, Karnataka -\n # \nNovember 2012 to December 2013\n # \nEDUCATION\n\nB.E in Computer Science Engineering\n # \nAdithya Institute of Technology - Tamil Nadu\n\nSeptember 2008 to June 2012\n # \nhttps://www.indeed.com/r/Govardhana-K/b2de315d95905b68?isid=rex-download&ikw=download-top&co=IN\nhttps://www.indeed.com/r/Govardhana-K/b2de315d95905b68?isid=rex-download&ikw=download-top&co=IN\n\n\nSKILLS\n\nAPEX. # (Less than 1 year), Data Structures (3 years), FLEXCUBE (5 years), Oracle (5 years),\nAlgorithms (3 years)\n # \nLINKS\n\nhttps://www.linkedin.com/in/govardhana-k-61024944/\n # \nADDITIONAL INFORMATION\n\nTechnical Proficiency:\n\nLanguages: Core Java, Go Lang, Data Structures & Algorithms, Oracle\nPL-SQL programming, Sales Force with APEX. # \nTools: RADTool, Jdeveloper, NetBeans, Eclipse, SQL developer, # \nPL/SQL Developer, WinSCP, Putty # \nWeb Technologies: JavaScript, XML, HTML, Webservice\n # \nOperating Systems: Linux, Windows # \nVersion control system SVN & Git-Hub # \nDatabases: Oracle\nMiddleware: Web logic, OC4J # \nProduct FLEXCUBE: Oracle FLEXCUBE Versions 10.x, 11.x and 12.x # \n\nhttps://www.linkedin.com/in/govardhana-k-61024944/", # # "annotation":[ # {"label":["Companies worked at"], # "points":[{"start":1749,"end":1754,"text":"Oracle"}]}, # {"label":["Companies worked at"], # "points":[{"start":1696,"end":1701,"text":"Oracle"}]}, # {"label":["Companies worked at"], # "points":[{"start":1417,"end":1422,"text":"Oracle"}]}, # {"label":["Skills"], # "points":[{"start":1356,"end":1792,"text":"Languages: Core Java, Go Lang, Data Structures & Algorithms, Oracle # \nPL-SQL programming, Sales Force with APEX. # \nTools: RADTool, Jdeveloper, NetBeans, Eclipse, SQL developer, # \nPL/SQL Developer, WinSCP, Putty # \nWeb Technologies: JavaScript, XML, HTML, Webservice # \n\nOperating Systems: Linux, Windows # \nVersion control system SVN & Git-Hub # \nDatabases: Oracle # \nMiddleware: Web logic, OC4J # \nProduct FLEXCUBE: Oracle FLEXCUBE Versions 10.x, 11.x and 12.x"}]}, # {"label":["Companies worked at"], # "points":[{"start":1209,"end":1214,"text":"Oracle"}]}, # {"label":["Skills"], # "points":[{"start":1136,"end":1247,"text":"APEX. (Less than 1 year), Data Structures (3 years), FLEXCUBE (5 years), Oracle (5 years), # \nAlgorithms (3 years)\n"}]}, # {"label":["Graduation Year"], # "points":[{"start":928,"end":931,"text":"2012"}]}, # {"label":["College Name"], # "points":[{"start":858,"end":888,"text":"Adithya Institute of Technology"}]}, # {"label":["Degree"], # "points":[{"start":821,"end":855,"text":"B.E in Computer Science Engineering"}]}, # {"label":["Graduation Year"], # "points":[{"start":787,"end":790,"text":"2012"}]}, # {"label":["Companies worked at"], # "points":[{"start":744,"end":749,"text":"Oracle"}]}, # {"label":["Designation"], # "points":[{"start":722,"end":741,"text":"Associate Consultant"}]}, # {"label":["Companies worked at"], # "points":[{"start":658,"end":663,"text":"Oracle"}]}, # {"label":["Designation"], # "points":[{"start":640,"end":655,"text":"Staff Consultant"}]}, # {"label":["Companies worked at"], # "points":[{"start":574,"end":579,"text":"Oracle"}]}, # {"label":["Designation"], # "points":[{"start":555,"end":572,"text":"Senior Consultant\n"}]}, # {"label":["Companies worked at"], # "points":[{"start":470,"end":492,"text":"Cloud Lending Solutions"}]}, # {"label":["Designation"], # "points":[{"start":444,"end":468,"text":"Senior Software Engineer\n"}]}, # {"label":["Companies worked at"], # "points":[{"start":308,"end":313,"text":"Oracle"}]}, # {"label":["Companies worked at"], # "points":[{"start":234,"end":239,"text":"Oracle"}]}, # {"label":["Companies worked at"], # "points":[{"start":175,"end":197,"text":"Cloud Lending Solutions"}]}, # {"label":["Email Address"], # "points":[{"start":93,"end":136,"text":"indeed.com/r/Govardhana-K/\nb2de315d95905b68\n"}]}, # {"label":["Location"], # "points":[{"start":39,"end":47,"text":"Bengaluru"}]}, # {"label":["Designation"], # "points":[{"start":13,"end":37,"text":"Senior Software Engineer\n"}]}, # {"label":["Name"],"points":[{"start":0,"end":11,"text":"<NAME>"}]}]}
d310754f9ba59b4b5cfb73bd45c5be9f679ecb41
[ "Python" ]
2
Python
AishwaryaVelumani/Entity-Recognition-In-Resumes-SpaCy
65c2b3690f599c3222a6e85fb432421d49652b8f
24f4ced58171733c7d5523d66df149c7ef54bbc7
refs/heads/master
<repo_name>DavidSilwal/Ocelot<file_sep>/src/Ocelot/Request/Builder/HttpRequestCreator.cs using System.Threading.Tasks; using Ocelot.Responses; using Ocelot.Requester.QoS; using System.Net.Http; namespace Ocelot.Request.Builder { public sealed class HttpRequestCreator : IRequestCreator { public async Task<Response<Request>> Build( HttpRequestMessage httpRequestMessage, bool isQos, IQoSProvider qosProvider, bool useCookieContainer, bool allowAutoRedirect) { return new OkResponse<Request>(new Request(httpRequestMessage, isQos, qosProvider, allowAutoRedirect, useCookieContainer)); } } }<file_sep>/test/Ocelot.ManualTest/ManualTestStartup.cs using System; using CacheManager.Core; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using Ocelot.DependencyInjection; using Ocelot.Middleware; using ConfigurationBuilder = Microsoft.Extensions.Configuration.ConfigurationBuilder; namespace Ocelot.ManualTest { public class ManualTestStartup { public void ConfigureServices(IServiceCollection services) { Action<ConfigurationBuilderCachePart> settings = (x) => { x.WithDictionaryHandle(); }; services.AddAuthentication() .AddJwtBearer("TestKey", x => { x.Authority = "test"; x.Audience = "test"; }); services.AddOcelot() .AddCacheManager(settings) .AddAdministration("/administration", "secret"); } public void Configure(IApplicationBuilder app) { app.UseOcelot().Wait(); } } } <file_sep>/src/Ocelot/Request/Builder/IRequestCreator.cs namespace Ocelot.Request.Builder { using System.Net.Http; using System.Threading.Tasks; using Ocelot.Requester.QoS; using Ocelot.Responses; public interface IRequestCreator { Task<Response<Request>> Build( HttpRequestMessage httpRequestMessage, bool isQos, IQoSProvider qosProvider, bool useCookieContainer, bool allowAutoRedirect); } } <file_sep>/test/Ocelot.IntegrationTests/RaftStartup.cs using System; using System.IO; using System.Linq; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Http; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using Newtonsoft.Json; using Ocelot.DependencyInjection; using Ocelot.Middleware; using Ocelot.Raft; using Rafty.Concensus; using Rafty.FiniteStateMachine; using Rafty.Infrastructure; using Rafty.Log; using ConfigurationBuilder = Microsoft.Extensions.Configuration.ConfigurationBuilder; namespace Ocelot.IntegrationTests { public class RaftStartup { public RaftStartup(IHostingEnvironment env) { var builder = new ConfigurationBuilder() .SetBasePath(env.ContentRootPath) .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true) .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true) .AddJsonFile("peers.json", optional: true, reloadOnChange: true) .AddJsonFile("configuration.json") .AddEnvironmentVariables(); Configuration = builder.Build(); } public IConfiguration Configuration { get; } public virtual void ConfigureServices(IServiceCollection services) { services .AddOcelot(Configuration) .AddAdministration("/administration", "secret") .AddRafty(); } public virtual void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) { app.UseOcelot().Wait(); } } }
fe04d1719a720512cdc1558a74d6ec4af5be6747
[ "C#" ]
4
C#
DavidSilwal/Ocelot
ec7b4ff8fa2d6b470b388596397fea12e07dca12
259dbdfd3db11d4da26fa7645ae6eb2b1655e405
refs/heads/master
<file_sep>const request = require('request-promise-native') const hn = 'https://hacker-news.firebaseio.com/v0/'; const topNews = () => { return request.get(`${hn}/newstories.json`).then(r => JSON.parse(r)); } const getNews = (id) => { return request.get(`${hn}/item/${id}.json`).then(r => JSON.parse(r)); } module.exports = {topNews , getNews} // const hn = require('./hn'); // hn.topNews().then(results=>{ // const r = results.slice(-5).map( // v => hn.getNews(v) // ) // return Promise.all(r) // }).then(results=>{ // console.log("News\n", results) // }) // .catch(err=>{ // console.log("err", err); // })<file_sep>const express = require('express'); const morgan = require('morgan'); const request = require('request-promise-native'); const cors = require('cors'); const PORTNUMBER = parseInt(process.argv[2] || process.env.PORT) || 3000; const TOKEN = require('./config').token; const WEBHOOK = `${process.argv[2]}/${TOKEN}`; const bot = require('./telegram'); const setWebhook = bot(TOKEN, 'setWebhook'); const sendMessage = bot(TOKEN, 'sendMessage'); const app = express(); app.use(morgan('tiny')); app.use(cors()); app.use(express.json()); app.use(express.urlencoded({ extended: true })); console.log(WEBHOOK); const botMessage = (req, resp, next) => { let m = {}; if ('message' in req.body) m = req.body.message; else if ('edited_message' in req.body) m = req.body.edited_message; req.telegram = { type: '', message_id: m.message_id, chat_id: m.chat.id, first_name: m.chat.first_name, date: m.date, text: m.text, entities: m.entities || [] } if (req.telegram.text == '/start') { req.telegram.type = 'start' } else if (req.telegram.text.startsWith('/newstories')) { req.telegram.type = 'newstories' } else { req.telegram.type = 'error' } next(); } app.post(`/${TOKEN}`, botMessage, (req, resp) => { console.log(req.telegram) sendMessage(req.telegram) resp.status(200).json({}); } ) setWebhook({ url: WEBHOOK }).then(result => { // console.log("result", result); app.listen(PORTNUMBER, () => { console.log(`App started, listening on ${PORTNUMBER}`) }) }).catch(err => { console.log("error,", err) })
3af6bf2510b02ad4efc721c409e84616be5e609b
[ "JavaScript" ]
2
JavaScript
yekai7/day19
5085854442a50f1e3930e65c01d1e317f7389141
eca391865ed49b30f33bb2e714007dd39e54006d
refs/heads/master
<file_sep>import lightgbm as lgb from sklearn import * import pandas as pd import numpy as np #from top scoring kernels and blends - for testing only sub1 = pd.read_csv('../input/best-ensemble-score-made-available-0-68/SHAZ13_ENS_LEAKS.csv') sub2 = pd.read_csv('../input/best-ensemble-score-made-available-0-67/SHAZ13_ENS_LEAKS.csv') sub3 = pd.read_csv('../input/feature-scoring-vs-zeros/leaky_submission.csv') #standard train = pd.read_csv('../input/santander-value-prediction-challenge/train.csv') test = pd.read_csv('../input/santander-value-prediction-challenge/test.csv') print(train.shape, test.shape) col = [c for c in train.columns if c not in ['ID', 'target']] leak_col = [] for c in col: leak1 = np.sum((train[c]==train['target']).astype(int)) leak2 = np.sum((((train[c] - train['target']) / train['target']) < 0.05).astype(int)) if leak1 > 30 and leak2 > 3500: leak_col.append(c) print(len(leak_col), leak_col) col = list(leak_col) train = train[col + ['ID', 'target']] test = test[col + ['ID']] #https://www.kaggle.com/johnfarrell/baseline-with-lag-select-fake-rows-dropped train["nz_mean"] = train[col].apply(lambda x: x[x!=0].mean(), axis=1) train["nz_max"] = train[col].apply(lambda x: x[x!=0].max(), axis=1) train["nz_min"] = train[col].apply(lambda x: x[x!=0].min(), axis=1) train["ez"] = train[col].apply(lambda x: len(x[x==0]), axis=1) train["mean"] = train[col].apply(lambda x: x.mean(), axis=1) train["max"] = train[col].apply(lambda x: x.max(), axis=1) train["min"] = train[col].apply(lambda x: x.min(), axis=1) test["nz_mean"] = test[col].apply(lambda x: x[x!=0].mean(), axis=1) test["nz_max"] = test[col].apply(lambda x: x[x!=0].max(), axis=1) test["nz_min"] = test[col].apply(lambda x: x[x!=0].min(), axis=1) test["ez"] = test[col].apply(lambda x: len(x[x==0]), axis=1) test["mean"] = test[col].apply(lambda x: x.mean(), axis=1) test["max"] = test[col].apply(lambda x: x.max(), axis=1) test["min"] = test[col].apply(lambda x: x.min(), axis=1) col += ['nz_mean', 'nz_max', 'nz_min', 'ez', 'mean', 'max', 'min'] for i in range(2, 100): train['index'+str(i)] = ((train.index + 2) % i == 0).astype(int) test['index'+str(i)] = ((test.index + 2) % i == 0).astype(int) col.append('index'+str(i)) test = pd.merge(test, sub3, how='left', on='ID',) from scipy.sparse import csr_matrix, vstack train = train.replace(0, np.nan) test = test.replace(0, np.nan) train = pd.concat((train, test), axis=0, ignore_index=True) test['target'] = 0.0 folds = 5 for fold in range(folds): x1, x2, y1, y2 = model_selection.train_test_split(train[col], np.log1p(train.target.values), test_size=0.20, random_state=fold) params = {'learning_rate': 0.02, 'max_depth': 7, 'boosting': 'gbdt', 'objective': 'regression', 'metric': 'rmse', 'is_training_metric': True, 'feature_fraction': 0.9, 'bagging_fraction': 0.8, 'bagging_freq': 5, 'seed':fold} model = lgb.train(params, lgb.Dataset(x1, label=y1), 3000, lgb.Dataset(x2, label=y2), verbose_eval=200, early_stopping_rounds=100) test['target'] += np.expm1(model.predict(test[col], num_iteration=model.best_iteration)) test['target'] /= folds test[['ID', 'target']].to_csv('submission.csv', index=False) <file_sep>import lightgbm as lgb import pandas as pd import keras_train import numpy as np # import config def lgbm_train(train_part, train_part_label, valide_part, valide_part_label, fold_seed, fold = 5, train_weight = None, valide_weight = None, flags = None): """ LGBM Training """ CATEGORY_FEATURES = keras_train.USED_FEATURE_LIST FEATURE_LIST = keras_train.USED_FEATURE_LIST if flags.stacking: FEATURE_LIST += ['emb_' + str(i) for i in range(len(CATEGORY_FEATURES) * 5)] + ['k_pred'] print("-----LGBM training-----") d_train = lgb.Dataset(train_part[FEATURE_LIST].values, train_part_label, weight = train_weight, feature_name = FEATURE_LIST) #, categorical_feature = CATEGORY_FEATURES) #, init_score = train_part[:, -1]) d_valide = lgb.Dataset(valide_part[FEATURE_LIST].values, valide_part_label, weight = valide_weight, feature_name = FEATURE_LIST) #, categorical_feature = CATEGORY_FEATURES) #, init_score = valide_part[:, -1]) params = { # 'num_leaves':-1, 'task': 'train', 'min_sum_hessian_in_leaf':None, 'max_depth':10, 'learning_rate':0.005, 'feature_fraction':0.8, 'verbose':-1, 'objective': 'multiclass', 'num_class':6, 'metric': 'multi_logloss', 'num_boost_round':3000, 'drop_rate':None, 'bagging_fraction':0.6, 'bagging_freq':5, 'early_stopping_round':100, # 'min_data_in_leaf':100, 'max_bin': None, 'scale_pos_weight':None, } # params.update(config.all_params) print ("lightgbm params: {0}\n".format(params)) bst = lgb.train( params , d_train, verbose_eval = 200, valid_sets = [d_train, d_valide], # feature_name= keras_train.DENSE_FEATURE_LIST, #feval = gini_lgbm #num_boost_round = 1 ) #pred = model_eval(bst, 'l', valide_part) #print(pred[:10]) #print(valide_part_label[:10]) #print(valide_part[:10, -1]) # exit(0) feature_imp = bst.feature_importance(importance_type = 'gain') sort_ind = np.argsort(feature_imp)[::-1] print (np.c_[np.array(FEATURE_LIST)[sort_ind], feature_imp[sort_ind]][:10]) # print (np.array(keras_train.FEATURE_LIST)[np.argsort(feature_imp)]) # exit(0) # cv_result = lgb.cv(params, d_train, nfold=fold) #, feval = gini_lgbm) # pd.DataFrame(cv_result).to_csv('cv_result', index = False) # exit(0) return bst
20c57bba58e16270ea5d68b6c4013c3ce1abd8c9
[ "Python" ]
2
Python
ifuding/ASAC
469eb3b378004ca796628199f09342cfe3b73c0f
357fcb94c03f8825a0b6914a49164d315fe76716
refs/heads/master
<file_sep>package kwiscale import "github.com/gorilla/websocket" var ( // keep connection by path. rooms = make(map[string]*wsroom, 0) ) type wsroom struct { // connections for the room conns map[*WebSocketHandler]bool } // Returns the room named "path", or create one if not exists. func getRoom(path string) *wsroom { if r, ok := rooms[path]; !ok { r = new(wsroom) r.conns = make(map[*WebSocketHandler]bool) rooms[path] = r } return rooms[path] } // Add a websocket handler to the room. func (room *wsroom) add(c *WebSocketHandler) { room.conns[c] = true } // Remove a websocket handler from the room. func (room *wsroom) remove(c *WebSocketHandler) { if _, ok := room.conns[c]; ok { Log("Remove websocket connection", c) delete(room.conns, c) } } // WSHandler is the base interface to implement to be able to use // Websocket. type WSHandler interface { // Serve is the method to implement inside the project upgrade() error OnConnect() error OnClose() error GetConnection() *websocket.Conn Close() } // WebSocketHandler type to compose a web socket handler. // To use it, compose a handler with this type and implement one of // OnJSON(), OnMessage() or Serve() method. // Example: // // type Example_WebSocketHandler struct{ WebSocketHandler } // // func (m *Example_WebSocketHandler) OnJSON(i interface{}, err error) { // if err != nil { // m.SendJSON(map[string]string{ // "error": err.Error(), // }) // return // } // // m.SendJSON(map[string]interface{}{ // "greeting": "Hello !", // "data": i, // }) // } // // Previous example send back the message + a greeting message type WebSocketHandler struct { BaseHandler conn *websocket.Conn } // upgrade protocol to use websocket communication func (ws *WebSocketHandler) upgrade() error { upgrader := websocket.Upgrader{ ReadBufferSize: 1024, WriteBufferSize: 1024, } var err error ws.conn, err = upgrader.Upgrade(ws.response, ws.request, nil) if err == nil { // record room and append connection path := ws.request.URL.Path room := getRoom(path) room.add(ws) } return err } // GetConnection returns the websocket client connection. func (ws *WebSocketHandler) GetConnection() *websocket.Conn { return ws.conn } // OnConnect is called when a client connection is opened. func (ws *WebSocketHandler) OnConnect() error { return nil } // OnClose is called when a client connection is closed. func (ws *WebSocketHandler) OnClose() error { return nil } func (ws *WebSocketHandler) Write(b []byte) error { return ws.conn.WriteMessage(websocket.TextMessage, b) } // WriteString is an alias to SendText. func (ws *WebSocketHandler) WriteString(m string) error { return ws.SendText(m) } // WriteJSON is an alias for SendJSON. func (ws *WebSocketHandler) WriteJSON(i interface{}) error { return ws.SendJSON(i) } // SendJSON send interface "i" in json form to the current client. func (ws *WebSocketHandler) SendJSON(i interface{}) error { return ws.conn.WriteJSON(i) } // SendText send string "s" to the current client. func (ws *WebSocketHandler) SendText(s string) error { return ws.conn.WriteMessage(websocket.TextMessage, []byte(s)) } // SendJSONToThisRoom send interface "i" in json form to the client connected // to the same room of the current client connection. func (ws *WebSocketHandler) SendJSONToThisRoom(i interface{}) { ws.SendJSONToRoom(ws.request.URL.Path, i) } // SendJSONToRoom send the interface "i" in json form to the client connected // to the the room named "name". func (ws *WebSocketHandler) SendJSONToRoom(room string, i interface{}) { for w := range rooms[room].conns { w.SendJSON(i) } } // SendJSONToAll send the interface "i" in json form to the entire // client list. func (ws *WebSocketHandler) SendJSONToAll(i interface{}) { for name := range rooms { ws.SendJSONToRoom(name, i) } } // SendTextToThisRoom send message s to the room of the // current client connection. func (ws *WebSocketHandler) SendTextToThisRoom(s string) { ws.SendTextToRoom(ws.request.URL.Path, s) } // SendTextToRoom send message "s" to the room named "name". func (ws *WebSocketHandler) SendTextToRoom(name, s string) { for w := range rooms[name].conns { w.SendText(s) } } // SendTextToAll send message "s" to the entire list of connected clients. func (ws *WebSocketHandler) SendTextToAll(s string) { for name := range rooms { ws.SendTextToRoom(name, s) } } // Close connection after having removed handler from the rooms stack. func (ws *WebSocketHandler) Close() { defer ws.conn.Close() if room, ok := rooms[ws.request.URL.Path]; ok { room.remove(ws) if len(room.conns) == 0 { delete(rooms, ws.request.URL.Path) } } } // WSServerHandler interface to serve continuously. type WSServerHandler interface { Serve() } // WSJsonHandler interface, framework will // read socket and call OnJSON each time a json message is received. type WSJsonHandler interface { OnJSON(interface{}, error) } // WSStringHandler interface, framework // will read socket and call OnMessage() each time a string is received. type WSStringHandler interface { OnMessage(int, string, error) } func serveWS(w WSHandler) { defer w.Close() w.(WSServerHandler).Serve() } // Serve JSON. func serveJSON(w WSHandler) { c := w.GetConnection() defer w.Close() for { var i interface{} err := c.ReadJSON(&i) w.(WSJsonHandler).OnJSON(i, err) if err != nil { return } } } // Serve string messages func serveString(w WSHandler) { c := w.GetConnection() defer w.Close() for { i, p, err := c.ReadMessage() w.(WSStringHandler).OnMessage(i, string(p), err) if err != nil { return } } } <file_sep>package kwiscale import ( "log" "net/http" "net/url" ) // Deprecated functions that will disapear // GetApp returns the app that holds this handler. // // DEPRECATED -- see App() func (b *BaseHandler) GetApp() *App { log.Println("[WARN] GetApp() is deprecated, please use App() method instead.") return b.App() } // GetResponse returns the current response. // // DEPRECATED -- see Response() func (b *BaseHandler) GetResponse() http.ResponseWriter { log.Println("[WARN] GetResponse() is deprecated, please use Response() method instead.") return b.Response() } // GetRequest returns the current request. // // DEPRECATED -- see Request() func (b *BaseHandler) GetRequest() *http.Request { log.Println("[WARN] GetRequest() is deprecated, please use Request() method instead.") return b.Request() } // GetPost return the post data for the given "name" argument. // // DEPRECATED -- see PostVar() func (b *BaseHandler) GetPost(name string) string { log.Println("[WARN] GetPost() is deprecated, please use PostValue() method instead.") return b.PostValue(name, "") } // GetURL return an url based on the declared route and given string pair. // // DEPRECATED -- see URL() func (b *BaseHandler) GetURL(s ...string) (*url.URL, error) { log.Println("[WARN] GetURL() is deprecated, please use URL() method instead.") return b.URL(s...) } // GetPayload returns the Body content. // // DEPRECATED - see Payload() func (b *BaseHandler) GetPayload() []byte { log.Println("[WARN] GetPauload() is deprecated, please use Payload() method instead.") return b.Payload() } // GetPostValues returns the entire posted values. // // DEPRECATED - see PostValues() func (b *BaseHandler) GetPostValues() url.Values { log.Println("[WARN] GetPostValues() is deprecated, please use PostValues() method instead.") return b.PostValues() } // GetJSONPayload unmarshal body to the "v" interface. // // DEPRECATED - see JSONPayload() func (b *BaseHandler) GetJSONPayload(v interface{}) error { log.Println("[WARN] GetJSONPayload() is deprecated, please use JSONPayload() method instead.") return b.JSONPayload(v) } // GlobalCtx Returns global template context. // // Deprecated: use handler.App().Context instead func (b *RequestHandler) GlobalCtx() map[string]interface{} { log.Println("[WARN] GlobalCtx() is deprecated, please use App().Context instead.") return b.App().Context } <file_sep>package kwiscale // There, we define HTTP handlers - they are based on BaseHandler import ( "encoding/json" "errors" "net/http" ) // HTTPRequestHandler interface which declare HTTP verbs. type HTTPRequestHandler interface { Get() Post() Put() Head() Patch() Delete() Options() Trace() Redirect(url string) RedirectWithStatus(url string, httpStatus int) GlobalCtx() map[string]interface{} Error(status int, message string, details ...interface{}) } // RequestHandler that should be composed by users. type RequestHandler struct { BaseHandler } // Get implements IRequestHandler Method - default "not found". func (r *RequestHandler) Get() { r.App().Error(http.StatusNotFound, r.getResponse(), ErrNotFound) } // Put implements IRequestHandler Method - default "not found". func (r *RequestHandler) Put() { r.App().Error(http.StatusNotFound, r.getResponse(), ErrNotFound) } // Post implements IRequestHandler Method - default "not found". func (r *RequestHandler) Post() { r.App().Error(http.StatusNotFound, r.getResponse(), ErrNotFound) } // Delete implements IRequestHandler Method - default "not found". func (r *RequestHandler) Delete() { r.App().Error(http.StatusNotFound, r.getResponse(), ErrNotFound) } // Head implements IRequestHandler Method - default "not found". func (r *RequestHandler) Head() { r.App().Error(http.StatusNotFound, r.getResponse(), ErrNotFound) } // Patch implements IRequestHandler Method - default "not found". func (r *RequestHandler) Patch() { r.App().Error(http.StatusNotFound, r.getResponse(), ErrNotFound) } // Options implements IRequestHandler Method - default "not found". func (r *RequestHandler) Options() { r.App().Error(http.StatusNotFound, r.getResponse(), ErrNotFound) } // Trace implements IRequestHandler Method - default "not found". func (r *RequestHandler) Trace() { r.App().Error(http.StatusNotFound, r.getResponse(), ErrNotFound) } // Write is an alias to RequestHandler.Request.Write. That implements io.Writer. func (r *RequestHandler) Write(data []byte) (int, error) { return r.response.Write(data) } // WriteString is converts param to []byte then use Write method. func (r *RequestHandler) WriteString(data string) (int, error) { return r.Write([]byte(data)) } // WriteJSON converts data to json then send bytes. // This methods set content-type to application/json (RFC 4627) func (r *RequestHandler) WriteJSON(data interface{}) (int, error) { b, err := json.Marshal(data) if err != nil { return -1, err } r.response.Header().Add("Content-Type", "application/json") return r.Write(b) } // Status write int status to header (use htt.StatusXXX as status). func (r *RequestHandler) Status(status int) { r.response.WriteHeader(status) } // Render calls assigned template engine Render method. // This method copies globalCtx and write ctx inside. So, contexts are not overriden, it // only merge 2 context in a new one that is passed to template. func (r *RequestHandler) Render(file string, ctx map[string]interface{}) error { // merge global context with the given // ctx should override gobal context newctx := make(map[string]interface{}) for k, v := range r.GlobalCtx() { newctx[k] = v } for k, v := range ctx { newctx[k] = v } return r.app.GetTemplate().Render(r, file, newctx) } // redirect client with http status. func (r *RequestHandler) redirect(uri string, status int) { r.response.Header().Add("Location", uri) if status < 0 { // by default, we use SeeOther status. This status // should change HTTP verb to GET status = http.StatusSeeOther } r.Status(status) } // Redirect will redirect client to uri using http.StatusSeeOther. func (r *RequestHandler) Redirect(uri string) { r.redirect(uri, -1) } // RedirectWithStatus will redirect client to uri using given status. func (r *RequestHandler) RedirectWithStatus(uri string, status int) { r.redirect(uri, status) } func (r *RequestHandler) Error(status int, message string, details ...interface{}) { r.App().Error(status, r.response, errors.New(message), details...) } <file_sep>package kwiscale import ( "encoding/json" "io" "io/ioutil" "mime/multipart" "net/http" "net/url" "os" "github.com/gorilla/mux" ) // PayloadType represents a payload type for Websocket. type PayloadType int const ( // JSON payload type in Websocket. JSON PayloadType = iota // BYTES payload type in Websocket. BYTES // STRING payload type in Websocket. STRING ) // Enable debug logs. var debug = false // SetDebug changes debug mode. func SetDebug(mode bool) { debug = mode } // WebHandler is the main handler interface that every handler sould // implement. type WebHandler interface { setVars(map[string]string, http.ResponseWriter, *http.Request) setApp(*App) App() *App setRoute(*mux.Route) getRequest() *http.Request getResponse() http.ResponseWriter Request() *http.Request Response() http.ResponseWriter GetSession(interface{}) (interface{}, error) SetSession(interface{}, interface{}) setSessionStore(SessionStore) Init() (status int, message error) Destroy() URL(...string) (*url.URL, error) // GetApp() *App // deprecated // GetURL(...string) (*url.URL, error) // deprecated // GetRequest() *http.Request // deprecated // GetResponse() http.ResponseWriter // deprecated } // BaseHandler is the parent struct of every Handler. // Implement WebHandler. type BaseHandler struct { response http.ResponseWriter request *http.Request Vars map[string]string sessionStore SessionStore route *mux.Route app *App routepath string } // Init is called before the begin of response (before Get, Post, and so on). // If error is not nil, framework will write response with the second argument as http status. func (b *BaseHandler) Init() (int, error) { return -1, nil } // Destroy is called as defered function after response. func (b *BaseHandler) Destroy() {} // setVars initialize vars from url func (b *BaseHandler) setVars(v map[string]string, w http.ResponseWriter, req *http.Request) { b.Vars = v b.response = w b.request = req } // setApp assign App to the handler func (b *BaseHandler) setApp(a *App) { b.app = a } // setRoute register mux.Route in the handler. func (b *BaseHandler) setRoute(r *mux.Route) { b.route = r } // getReponse returns the current response. func (b *BaseHandler) getResponse() http.ResponseWriter { return b.response } // getRequest returns the current request. func (b *BaseHandler) getRequest() *http.Request { return b.request } // Response returns the current response. func (b *BaseHandler) Response() http.ResponseWriter { return b.getResponse() } // Request returns the current request. func (b *BaseHandler) Request() *http.Request { return b.getRequest() } // SetSessionStore defines the session store to use. func (b *BaseHandler) setSessionStore(store SessionStore) { b.sessionStore = store } // GetSession return the session value of "key". func (b *BaseHandler) GetSession(key interface{}) (interface{}, error) { return b.sessionStore.Get(b, key) } // SetSession set the "key" session to "value". func (b *BaseHandler) SetSession(key interface{}, value interface{}) { b.sessionStore.Set(b, key, value) } // CleanSession remove every key/value of the current session. func (b *BaseHandler) CleanSession() { b.sessionStore.Clean(b) } // Payload returns the Body content. func (b *BaseHandler) Payload() []byte { content, err := ioutil.ReadAll(b.request.Body) if err != nil { return nil } return content } // JSONPayload unmarshal body to the "v" interface. func (b *BaseHandler) JSONPayload(v interface{}) error { return json.Unmarshal(b.Payload(), v) } // PostValue returns the post data for the given "name" argument. // If POST value is empty, return "def" instead. If no "def" is provided, return an empty string by default. func (b *BaseHandler) PostValue(name string, def ...string) string { if res := b.request.PostFormValue(name); res != "" { return res } if len(def) > 0 { return def[0] } return "" } // PostValues returns the entire posted values. func (b *BaseHandler) PostValues() url.Values { b.request.ParseForm() return b.request.PostForm } // GetPostFile returns the "name" file pointer and information from the post data. func (b *BaseHandler) GetPostFile(name string) (multipart.File, *multipart.FileHeader, error) { b.request.ParseForm() return b.request.FormFile(name) } // SavePostFile save the given "name" file to the "to" path. func (b *BaseHandler) SavePostFile(name, to string) error { b.request.ParseForm() file, _, err := b.GetPostFile(name) if err != nil { return err } defer file.Close() out, err := os.Create(to) if err != nil { return err } defer out.Close() _, err = io.Copy(out, file) return err } // URL return an url based on the declared route and given string pair. func (b *BaseHandler) URL(s ...string) (*url.URL, error) { return b.route.URL(s...) } // App returns the current application. func (b *BaseHandler) App() *App { return b.app } <file_sep>package kwiscale import ( "crypto/md5" "fmt" "net/http" "os" "path/filepath" ) // StaticHandler handle static files handlers. Use App.SetStatic(path) that create the static handler type staticHandler struct { RequestHandler } // Use http.FileServer to serve file after adding ETag. func (s *staticHandler) Get() { file := s.Vars["file"] abs, _ := filepath.Abs(s.app.Config.StaticDir) file = filepath.Join(abs, file) // control or add etag if etag, err := eTag(file); err == nil { s.response.Header().Add("ETag", etag) } // create a fileserver for the static dir fs := http.FileServer(http.Dir(s.app.Config.StaticDir)) // stip directory name and serve the file http.StripPrefix("/"+filepath.Base(s.app.Config.StaticDir), fs). ServeHTTP(s.Response(), s.Request()) } // Get a etag for the file. It's constuct with a md5 sum of // <filename> + "." + <modification-time> func eTag(file string) (string, error) { stat, err := os.Stat(file) if err != nil { return "", err } s := md5.Sum([]byte(stat.Name() + "." + stat.ModTime().String())) return fmt.Sprintf("%x", s), nil } <file_sep>package kwiscale import ( "errors" "fmt" "text/template" ) var ( // ErrNotFound error type. ErrNotFound = errors.New("Not found") // ErrNotImplemented error type. ErrNotImplemented = errors.New("Not implemented") // ErrInternalError for internal error. ErrInternalError = errors.New("Internal server error") ) // HTTPErrorHandler interface. type HTTPErrorHandler interface { // Error returns the error. GetError() error // Details returns some detail inteface. Details() interface{} // Status returns the http status code. Status() int setStatus(int) setError(error) setDetails(interface{}) } // ErrorHandler is a basic error handler that // displays error in a basic webpage. type ErrorHandler struct { RequestHandler status int err error details interface{} } func (dh *ErrorHandler) setStatus(s int) { dh.status = s } func (dh *ErrorHandler) setError(err error) { dh.err = err } func (dh *ErrorHandler) setDetails(d interface{}) { dh.details = d } // GetError returns error that was set by handlers. func (dh *ErrorHandler) GetError() error { return dh.err } // Details returns details or nil if none. func (dh *ErrorHandler) Details() interface{} { return dh.details } // Status returns the error HTTP Status set by handlers. func (dh *ErrorHandler) Status() int { return dh.status } // Get shows a standard error in HTML. func (dh *ErrorHandler) Get() { tpl := `<!doctype html> <html> <head> <title>ERROR {{.Status}}</title> <style> html, body { font-family: Sans, sans-serif; } main { margin: auto; width: 80%; border: 2px solid #880000; padding: 2em; } </style> </head> <body> <main> <h1>ERROR {{ .Status}}</h1> <p>{{ .Error }}</p> <pre>{{ range .Details }}{{ . }}{{ end }}</pre> </main> </body> </html>` t, err := template.New("error").Parse(tpl) if err != nil { fmt.Println(err) return } dh.Response().WriteHeader(dh.Status()) t.Execute(dh.Response(), map[string]interface{}{ "Status": dh.Status(), "Error": dh.GetError(), "Details": dh.Details(), }) } <file_sep>package kwiscale import ( "fmt" "io/ioutil" "net/http" "net/http/httptest" "testing" ) // Let each handler to get "*testing.T" var T = make(map[*App]*testing.T) // A test handler (simple). type TestHandler struct { RequestHandler } func (th *TestHandler) Get() { th.WriteString("Hello") } // A test handler with method that handle paramters type TestParamHandler struct{ RequestHandler } func (th *TestParamHandler) Get(id int, name string, activated bool) { th.WriteString(fmt.Sprintf("%d %s %v", id, name, activated)) } // Handler to test reversed route. type TestReverseRoute struct{ RequestHandler } func (th *TestReverseRoute) Get() { // Test to get route from app app := th.App() t := T[app] u, err := app.GetRoute("kwiscale.TestReverseRoute").URL("category", "test") if err != nil { t.Error("Route from app returns error:", err) } if u.String() != "/product/test" { t.Error("Route from app is not /product/test: ", u) } route, err := th.URL("category", "foo") if err != nil { fmt.Println(err) } th.WriteString(route.String()) } // Create app. func initApp(t *testing.T) *App { conf := &Config{} app := NewApp(conf) T[app] = t return app } // Test the app "soft close". func TestCloser(t *testing.T) { app := initApp(t) app.AddRoute("/foo", &TestHandler{}) <-app.SoftStop() } // TestSimpleRequest should respond whit 200 and print "hello". func TestSimpleRequest(t *testing.T) { r, _ := http.NewRequest("GET", "http://example.com/foo", nil) w := httptest.NewRecorder() app := initApp(t) app.AddRoute("/foo", &TestHandler{}) app.ServeHTTP(w, r) if w.Code != http.StatusOK { t.Error("HTTP Status is not ok: ", w.Code) } resp, _ := ioutil.ReadAll(w.Body) if string(resp) != "Hello" { t.Error("Handler didn't respond with 'hello': ", string(resp)) } } // Try to call a bad route. func TestBadRequest(t *testing.T) { r, _ := http.NewRequest("GET", "http://example.com/bad", nil) w := httptest.NewRecorder() app := initApp(t) app.AddRoute("/foo", &TestHandler{}) app.ServeHTTP(w, r) if w.Code != http.StatusNotFound { t.Error(`HTTP Status is not "not found": `, w.Code) } } // Test the reverse route to get url. func TestRouteReverse(t *testing.T) { r, _ := http.NewRequest("GET", "http://example.com/product/test", nil) w := httptest.NewRecorder() app := initApp(t) app.AddRoute("/product/{category:.+}", &TestReverseRoute{}) app.ServeHTTP(w, r) resp, _ := ioutil.ReadAll(w.Body) if string(resp) != "/product/foo" { t.Fatal(resp, "!=", "/product/foo") } } // Test to get reverse route from app. func TestReverseURLFromApp(t *testing.T) { app := initApp(t) app.AddRoute("/product/{category:.+}", &TestReverseRoute{}) u, err := app.GetRoute("kwiscale.TestReverseRoute").URL("category", "second") if err != nil { t.Fatal(err) } if u.String() != "/product/second" { t.Fatal(u.String(), "!=", "/product/second") } } // BUG: This is a limit case we really need to study func _TestBestRoute(t *testing.T) { r, _ := http.NewRequest("GET", "http://example.com/test/route", nil) //w := httptest.NewRecorder() app := initApp(t) app.AddRoute("/test/route", &TestHandler{}) app.AddRoute("/{p:.*}", &TestReverseRoute{}) name, _, _ := getBestRoute(app, r) if name != "kwiscale.TestReverseRoute" { t.Fatal("For /test/route, the handler that matches should be kwiscale.TestReverseRoute and not", name) } } func TestMethodWithArguments(t *testing.T) { app := initApp(t) app.AddRoute(`/user/{id:\d+}/{name:.*}/{activated:.*}`, &TestParamHandler{}) r, _ := http.NewRequest("GET", "http://example.com/user/42/foo/true", nil) w := httptest.NewRecorder() app.ServeHTTP(w, r) content, err := ioutil.ReadAll(w.Body) if string(content) != "42 foo true" { t.Fatal("Bad argument match:", string(content), "instead of 42 foo true", err) } } func TestMethodWithBadArgument(t *testing.T) { app := initApp(t) app.AddRoute(`/user/{id:\d+}/{name:.*}/{activated:.*}`, &TestParamHandler{}) r, _ := http.NewRequest("GET", "http://example.com/user/42/foo/BAR", nil) w := httptest.NewRecorder() app.ServeHTTP(w, r) content, err := ioutil.ReadAll(w.Body) if w.Code != 500 { t.Fatal("Handler should crash with 500 Error for bad match parameter, we've got", w.Code, content, err) } } <file_sep>package kwiscale import ( "errors" "fmt" "io/ioutil" "log" "net/http" "os" "path/filepath" "reflect" "regexp" "strconv" "strings" "github.com/gorilla/mux" "gopkg.in/yaml.v2" ) // handlerManagerRegistry is a map of [name]handlerManager. var handlerManagerRegistry = make(map[string]*handlerManager) // handlerRegistry keep the entire handlers - map[name]type. var handlerRegistry = make(map[string]reflect.Type) // regexp to find url ordered params from gorilla form. var urlParamRegexp = regexp.MustCompile(`\{(.+?):`) // Register takes webhandler and keep type in handlerRegistry. // It can be called directly (to set handler accessible // by configuration file), or implicitally by "AddRoute" and "AddNamedRoute()". func Register(h WebHandler) { elem := reflect.ValueOf(h).Elem().Type() name := elem.String() if _, exists := handlerRegistry[name]; !exists { handlerRegistry[name] = elem } } type handlerRouteMap struct { handlername string route string } // App handles router and handlers. type App struct { // configuration Config *Config // Global context shared to handlers Context map[string]interface{} // session store sessionstore SessionStore // Template engine instance. //templateEngine Template // The router that will be used router *mux.Router // List of handler "names" mapped to route (will be create by a factory) handlers map[*mux.Route]handlerRouteMap // Handler name for error handler. errorHandler string } // NewApp Create new *App - App constructor. func NewApp(config *Config) *App { // fill up config for non-set values config = initConfig(config) Log(fmt.Sprintf("%+v\n", config)) // generate app, assign config, router and handlers map a := &App{ Config: config, router: mux.NewRouter(), handlers: make(map[*mux.Route]handlerRouteMap), Context: make(map[string]interface{}), } // set sessstion store a.sessionstore = sessionEngine[config.SessionEngine] a.sessionstore.Name(config.SessionName) a.sessionstore.SetSecret(config.SessionSecret) a.sessionstore.SetOptions(config.SessionEngineOptions) a.sessionstore.Init() if config.StaticDir != "" { a.SetStatic(config.StaticDir) } a.router.StrictSlash(config.StrictSlash) // keep config a.Config = config return a } // NewAppFromConfigFile import config file and returns *App. func NewAppFromConfigFile(filename ...string) *App { if len(filename) > 1 { panic(errors.New("You should give only one file in NewAppFromConfigFile")) } file := "kwiscale.yml" if len(filename) > 0 { file = filename[0] } else { if _, err := os.Stat("config.yml"); err == nil { log.Println("[WARN] - congig.yml is deprecated, please move to kwiscale.yml") file = "config.yml" } } content, err := ioutil.ReadFile(file) if err != nil { panic(err) } cfg := yamlConf{} yaml.Unmarshal(content, &cfg) app := NewApp(cfg.parse()) for route, v := range cfg.Routes { if handler, ok := handlerRegistry[v.Handler]; ok { h := reflect.New(handler).Interface().(WebHandler) log.Println(route, h, v.Alias) app.addRoute(route, h, v.Alias) } else { panic("Handler not found: " + v.Handler) } } return app } // ListenAndServe calls http.ListenAndServe method func (app *App) ListenAndServe(port ...string) { p := app.Config.Port if len(port) > 0 { p = port[0] } log.Println("Listening", p) log.Fatal(http.ListenAndServe(p, app)) } // SetStatic set the route "prefix" to serve files configured in Config.StaticDir func (app *App) SetStatic(prefix string) { path, _ := filepath.Abs(prefix) prefix = filepath.Base(path) s := &staticHandler{} app.AddNamedRoute("/"+prefix+"/{file:.*}", s, "statics") } // Implement http.Handler ServeHTTP method. func (app *App) ServeHTTP(w http.ResponseWriter, r *http.Request) { // try to recover panic if possible, and display // an Error page defer func() { if err := recover(); err != nil { app.Error(http.StatusInternalServerError, w, errors.New("An unexpected error occured"), err, ) } }() var handler WebHandler handlerName, route, match := getBestRoute(app, r) // if non match if _, ok := handlerManagerRegistry[handlerName]; !ok { app.Error(http.StatusNotFound, w, ErrNotFound, r.URL) return } // wait for a built handler from registry handler = <-handlerManagerRegistry[handlerName].produce() Log("Handler found ", handler) //assign some vars handler.setRoute(route) handler.setVars(match.Vars, w, r) handler.setApp(app) handler.setSessionStore(app.sessionstore) // Call Init before starting response if code, err := handler.Init(); err != nil { Log(err) // if returned status is <0, let Init() method do the work if code <= 0 { Log("Init method returns no error but a status <= 0") return } // Init() stops the request with error and with a status code to use app.Error(code, w, err) return } // Nothing stops the process calling Init(), so we can // prepare defered destroy defer handler.Destroy() // Websocket case if h, ok := handler.(WSHandler); ok { if err := h.upgrade(); err != nil { log.Println("Error upgrading Websocket protocol", err) return } defer h.OnClose() h.OnConnect() switch h.(type) { case WSServerHandler: serveWS(h) case WSJsonHandler: serveJSON(h) case WSStringHandler: serveString(h) default: app.Error(http.StatusNotImplemented, w, ErrNotImplemented) } return } // Standard Request if h, ok := handler.(HTTPRequestHandler); ok { // RequestHandler case w.Header().Add("Connection", "close") Log("Respond to RequestHandler", r.Method, h) if h == nil { app.Error(http.StatusNotFound, w, ErrNotFound, r.Method, h) return } switch r.Method { case "GET": h.Get() case "PUT": h.Put() case "POST": h.Post() case "DELETE": h.Delete() case "HEAD": h.Post() case "PATCH": h.Patch() case "OPTIONS": h.Options() case "TRACE": h.Trace() default: app.Error(http.StatusNotImplemented, w, ErrNotImplemented) } return } // if the method have parameters, we can try to call it. if app.callMethodWithParameters(r, handler, route, &match) { return } // we should NEVER go to this, but in case of... details := "" + fmt.Sprintf("Registry: %+v\n", handlerManagerRegistry) + fmt.Sprintf("RequestWriter: %+v\n", w) + fmt.Sprintf("Reponse: %+v", r) + fmt.Sprintf("KwiscaleHandler: %+v\n", handler) Log(details) app.Error(http.StatusInternalServerError, w, ErrInternalError, details) } // Append handler in handlerRegistry and start producing. // return the name of the handler. func (app *App) handle(h WebHandler, name string) string { handlerType := reflect.ValueOf(h).Elem().Type() handlerName := handlerType.String() if name == "" { name = handlerType.String() } Log("Register ", name) Register(h) if _, ok := handlerManagerRegistry[name]; ok { // do not create registry manager if it exists Log("Registry manager for", name, "already exists") return name } // Append a new handler manager in registry hm := &handlerManager{ handler: handlerName, closer: make(chan int, 0), producer: make(chan WebHandler, app.Config.NbHandlerCache), } handlerManagerRegistry[name] = hm // to be able to fetch handler by real name, only if alias is not given if name != handlerName { handlerManagerRegistry[handlerName] = hm } // start to produce handlers go handlerManagerRegistry[name].produceHandlers() // return the handler name return name } // AddRoute appends route mapped to handler. Note that rh parameter should // implement IRequestHandler (generally a struct composing RequestHandler or WebSocketHandler). func (app *App) AddRoute(route string, handler WebHandler) { app.addRoute(route, handler, "") } // AddNamedRoute does the same as AddRoute but set the route name instead of // using the handler name. If the given name already exists or is empty, the method // panics. func (app *App) AddNamedRoute(route string, handler WebHandler, name string) { name = strings.TrimSpace(name) if len(name) == 0 { panic(errors.New("The given name is empty")) } app.addRoute(route, handler, name) } // Add route to the stack. func (app *App) addRoute(route string, handler WebHandler, routename string) { var name string handlerType := reflect.ValueOf(handler).Elem().Type() if len(routename) == 0 { name = handlerType.String() } else { name = routename } // record a route r := app.router.NewRoute() r.Path(route) r.Name(name) app.handlers[r] = handlerRouteMap{name, route} app.handle(handler, name) } // SoftStop stops each handler manager goroutine (useful for testing). func (app *App) SoftStop() chan int { c := make(chan int, 0) go func() { for name, closer := range handlerManagerRegistry { Log("Closing ", name) closer.closer <- 1 Log("Closed ", name) } c <- 1 }() return c } // GetRoute return the *mux.Route that have the given name. func (app *App) GetRoute(name string) *mux.Route { for route := range app.handlers { if route.GetName() == name { return route } } return nil } // GetTemplate returns a new instance of Template. func (app *App) GetTemplate() Template { engine := templateEngine[app.Config.TemplateEngine] //ttype := reflect.TypeOf(engine) t := reflect.New(engine).Interface().(Template) t.SetTemplateDir(app.Config.TemplateDir) t.SetTemplateOptions(app.Config.TemplateEngineOptions) return t } // GetRoutes get all routes for a handler func (app *App) GetRoutes(name string) []*mux.Route { routes := []*mux.Route{} for route := range app.handlers { if route.GetName() == name { routes = append(routes, route) } } return routes } // DB returns the App.database configured from Config. /*func (app *App) DB() DB { if app.Config.DB != "" { dtype := dbdrivers[app.Config.DB] database := reflect.New(dtype).Interface().(DB) database.SetOptions(app.Config.DBOptions) database.Init() return database } Log("No db selected") return nil }*/ // SetErrorHandler set error handler to replace the default ErrorHandler. func (app *App) SetErrorHandler(h WebHandler) { app.errorHandler = app.handle(h, "") } // Error displays an error page with details if any. func (app *App) Error(status int, w http.ResponseWriter, err error, details ...interface{}) { Log(err, details) var handler WebHandler if app.errorHandler == "" { handler = &ErrorHandler{} } else { handler = <-handlerManagerRegistry[app.errorHandler].produce() } handler.setApp(app) handler.setVars(nil, w, nil) handler.(HTTPErrorHandler).setStatus(status) handler.(HTTPErrorHandler).setError(err) handler.(HTTPErrorHandler).setDetails(details) handler.(HTTPRequestHandler).Get() } // Try to call method with parameters (if found) func (app *App) callMethodWithParameters(r *http.Request, handler WebHandler, route *mux.Route, match *mux.RouteMatch) bool { h := reflect.ValueOf(handler) method := h.MethodByName(strings.Title(strings.ToLower(r.Method))) if method.Kind() == reflect.Invalid { return false } // if method is not a parametrized method, return false if method.Type().NumIn() == 0 { return false } maps := urlParamRegexp.FindAllStringSubmatch(app.handlers[route].route, -1) // build reflect.Value from match.Vars args := []reflect.Value{} for _, v := range maps { args = append(args, reflect.ValueOf(match.Vars[v[1]])) } // convert parameters, for now we can manage string (default), float, int and bool for i := 0; i < method.Type().NumIn(); i++ { typ := method.Type().In(i) // function arg type arg := reflect.ValueOf(args[i]) // argument to map switch typ.Kind() { case reflect.Float32, reflect.Float64: v, err := strconv.ParseFloat(args[i].String(), 10) if err != nil { panic(err) } arg = reflect.ValueOf(v) case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: v, err := strconv.ParseInt(args[i].String(), 10, 64) if err != nil { panic(err) } arg = reflect.ValueOf(v) case reflect.Bool: switch strings.ToLower(args[i].String()) { case "true", "1", "yes", "on": arg = reflect.ValueOf(true) case "false", "0", "no", "off": arg = reflect.ValueOf(false) default: panic(fmt.Errorf("Boolean URL '%s' value is not reconized", args[i])) } } // convertion if typ.Kind() != reflect.String { args[i] = arg.Convert(typ) } } method.Call(args) return true } <file_sep>package kwiscale import ( "errors" "github.com/gorilla/sessions" ) var sessionEngine = make(map[string]SessionStore, 0) // SessionEngineOptions set options for session engine. type SessionEngineOptions map[string]interface{} // RegisterSessionEngine can register session engine that implements // ISessionStore. The name is used to let configuration to select it. func RegisterSessionEngine(name string, engine SessionStore) { sessionEngine[name] = engine } // Register cookiesessionstore by default. func init() { RegisterSessionEngine("default", &CookieSessionStore{}) } // SessionStore to implement to give a session storage type SessionStore interface { // Init is called when store is initialized while App is initialized Init() // Name should set the session name Name(string) // SetOptions set some optionnal values to session engine SetOptions(SessionEngineOptions) // SetSecret should register a string to encode cookie (not mandatory // but you should implement this to respect interface) SetSecret([]byte) // Get a value from storage , interface param is the key Get(WebHandler, interface{}) (interface{}, error) // Set a value in the storage, first interface param is the key, // second interface is the value to store Set(WebHandler, interface{}, interface{}) // Clean, should cleanup files Clean(WebHandler) } // CookieSessionStore is a basic cookie based on gorilla.session. type CookieSessionStore struct { store *sessions.CookieStore name string secret []byte } // Init prepare the cookie storage. func (s *CookieSessionStore) Init() { s.store = sessions.NewCookieStore(s.secret) } // SetSecret record a string to encode cookie func (s *CookieSessionStore) SetSecret(secret []byte) { s.secret = secret } // Name set session name func (s *CookieSessionStore) Name(name string) { s.name = name } // SetOptions does nothing for the engine func (*CookieSessionStore) SetOptions(SessionEngineOptions) {} // Get a value from session by name. func (s *CookieSessionStore) Get(handler WebHandler, key interface{}) (interface{}, error) { session, err := s.store.Get(handler.getRequest(), s.name) if err != nil { return nil, err } Log("Getting session", key, session.Values[key]) if session.Values[key] == nil { return nil, errors.New("empty session") } return session.Values[key], nil } // Set a named value in sessionstore. func (s *CookieSessionStore) Set(handler WebHandler, key interface{}, val interface{}) { Log("Writing session", key, val) session, _ := s.store.Get(handler.getRequest(), s.name) session.Values[key] = val session.Save(handler.getRequest(), handler.getResponse()) } // Clean removes the entire session values for current session. func (s *CookieSessionStore) Clean(handler WebHandler) { session, _ := s.store.Get(handler.getRequest(), s.name) session.Values = make(map[interface{}]interface{}) session.Save(handler.getRequest(), handler.getResponse()) } <file_sep>package kwiscale // Config structure that holds configuration type Config struct { // Root directory where TemplateEngine will get files TemplateDir string // Port to listen Port string // Number of handler to prepare NbHandlerCache int // TemplateEngine to use (default, pango2...) TemplateEngine string // Template engine options (some addons need options) TemplateEngineOptions TplOptions // SessionEngine (default is a file storage) SessionEngine string // SessionName is the name of session, eg. Cookie name, default is "kwiscale-session" SessionName string // A secret string to encrypt cookie SessionSecret []byte // Configuration for SessionEngine SessionEngineOptions SessionEngineOptions // Static directory (to put css, images, and so on...) StaticDir string // Activate static in memory cache StaticCacheEnabled bool // StrictSlash allows to match route that have trailing slashes StrictSlash bool // Datastrore //DB string //DBOptions DBOptions } // Initialize config default values if some are not defined func initConfig(config *Config) *Config { if config == nil { config = new(Config) } if config.Port == "" { config.Port = ":8000" } if config.NbHandlerCache == 0 { config.NbHandlerCache = 5 } if config.TemplateEngine == "" { config.TemplateEngine = "basic" } if config.TemplateEngineOptions == nil { config.TemplateEngineOptions = make(TplOptions) } if config.SessionEngine == "" { config.SessionEngine = "default" } if config.SessionName == "" { config.SessionName = "kwiscale-session" } if config.SessionSecret == nil { config.SessionSecret = []byte("A very long secret string you should change") } if config.SessionEngineOptions == nil { config.SessionEngineOptions = make(SessionEngineOptions) } return config } /* type ymlDB struct { Engine string `yml:"engine"` Options DBOptions `yml:"options"` } */ type ymlSession struct { Name string `yaml:"name,omitempty"` Engine string `yaml:"engine,omitempty"` Secret []byte `yaml:"secret,omitempty"` Options SessionEngineOptions `yaml:"options,omitempty"` } type ymlTemplate struct { Dir string `yaml:"dir,omitempty"` Engine string `yaml:"engine,omitempty"` Options TplOptions `yaml:"options,omitempty"` } type ymlRoute struct { Handler string `yaml:"handler"` Alias string `yaml:"alias"` } // yamlConf is used to make yaml configuration easiest to write. type yamlConf struct { Port string `yaml:"listen,omitempty"` NbHandlerCache int `yaml:"nbhandler,omitempty"` StaticDir string `yaml:"staticdir,omitempty"` StaticCacheEnabled bool `yaml:"staticcache,omitempty"` StrictSlash bool `yaml:"strictslash,omitempty"` Template ymlTemplate `yaml:"template,omitempty"` Session ymlSession `yaml:"session,omitempty"` Routes map[string]ymlRoute `yaml:"routes"` //DB ymlDB `yaml:"db,omitempty"` } // parse returns the *Config from yaml struct. func (y yamlConf) parse() *Config { return &Config{ Port: y.Port, NbHandlerCache: y.NbHandlerCache, StaticDir: y.StaticDir, StrictSlash: y.StrictSlash, SessionEngine: y.Session.Engine, SessionName: y.Session.Name, SessionSecret: y.Session.Secret, SessionEngineOptions: y.Session.Options, TemplateDir: y.Template.Dir, TemplateEngine: y.Template.Engine, TemplateEngineOptions: y.Template.Options, //DB: y.DB.Engine, //DBOptions: y.DB.Options, } } <file_sep>/* Kwiscale command line interface. */ package main import ( "fmt" "io/ioutil" "log" "os" "path/filepath" "strings" "text/template" "github.com/codegangsta/cli" "gopkg.in/yaml.v2" ) var GOPATH = os.Getenv("GOPATH") const ( PROJECT_OPT = "project" // argument to set project name HANDLER_OPT = "handlers" // argument to set handlers name PROJECT_DEFAULT = "kwiscale-app" // default project name HANDLER_DEFAULT = "handlers" // default handlers package name DEPRECATED_CONFIGNAME = "config.yml" // deprecated configuration filename CONFIGNAME = "kwiscale.yml" // configname FILEMODE = 0664 DIRMODE = 0775 ) type ymlstruct map[string]interface{} func main() { out := cli.StringFlag{ Name: PROJECT_OPT, Value: PROJECT_DEFAULT, Usage: "project name, will set " + GOPATH + "/src/[projectname]", EnvVar: "KWISCALE_PROJECT", } handlers := cli.StringFlag{ Name: HANDLER_OPT, Value: HANDLER_DEFAULT, Usage: "handlers package name", EnvVar: "KWISCALE_HANDLERS", } app := cli.NewApp() app.Flags = []cli.Flag{out, handlers} app.Name = "kwiscale" app.Usage = "tool to manage kwiscale application" app.Version = "0.0.1" app.EnableBashCompletion = true app.Commands = []cli.Command{ { Name: "new", Usage: "Generate resources (application, handlers...)", Subcommands: []cli.Command{ { Name: "app", Usage: "Create application", Action: newApplication, }, { Name: "handler", Usage: "Create handler", Action: newHandler, }, }, }, { Name: "generate", Usage: "Parse configuration and generate handlers, main file...", Action: parseConfig, }, } app.Run(os.Args) } // create an application func newApplication(c *cli.Context) { out := getProjectPath(c) log.Println("Create application in directory:", out) createDirectories(out, c.GlobalString(HANDLER_OPT)) createConfig(c) createApp(c) } // add handler in yml func newHandler(c *cli.Context) { var ( y = loadYaml(c) hpkg = c.GlobalString(HANDLER_OPT) name = c.Args().First() //handler short name realname = c.Args().Get(2) //alias if any handlername = hpkg + "." + strings.Title(name) + "Handler" route = c.Args().Get(1) m = map[string]string{} //a simple map to handle route for template ) // create handler file createHandlerFile(handlername, c.GlobalString(HANDLER_OPT), getProjectPath(c)) // change configuration file m["handler"] = handlername if realname != "" { m["alias"] = realname } if _, ok := y["routes"]; !ok { y["routes"] = make(map[interface{}]interface{}) } // append handler routes := y["routes"].(map[interface{}]interface{}) routes[route] = m b, _ := yaml.Marshal(y) cfg := filepath.Join(getProjectPath(c), configFile()) ioutil.WriteFile(cfg, b, FILEMODE) } // parse config file to generate handler file in handlers package // by calling createHandlerFile, then // call addHandlerInApp to append handlers in main.go func parseConfig(c *cli.Context) { y := loadYaml(c) if _, ok := y["routes"]; !ok { log.Fatal("There are no route to create in configuration file") } routes := y["routes"] handlers := make([]map[string]string, 0) for route, v := range routes.(map[interface{}]interface{}) { handlername := v.(map[interface{}]interface{})["handler"].(string) alias := "" if a, ok := v.(map[interface{}]interface{})["alias"]; ok { alias = a.(string) } createHandlerFile(handlername, c.GlobalString(HANDLER_OPT), getProjectPath(c)) handlers = append(handlers, map[string]string{ "handler": handlername, "route": route.(string), "alias": alias, }) } } // create handler file. func createHandlerFile(handler, handlerpkg, where string) { var ( parts = strings.Split(handler, ".") name = parts[1] filename = strings.ToLower(strings.Replace(name, "Handler", "", -1)) path = filepath.Join(where, handlerpkg, filename+".go") ) if _, err := os.Stat(path); err == nil { log.Println("Handler file already exists:", path) return } tpl, _ := template.New("handler").Parse(TPLHANDLER) f, err := os.OpenFile(path, os.O_CREATE|os.O_WRONLY, FILEMODE) if err != nil { log.Fatal(err) } tpl.Execute(f, map[string]string{ "Handler": name, "HandlersPKG": handlerpkg, }) log.Println("Handler created:", path) } // create directory tree func createDirectories(out, hpkg string) { for _, p := range []string{ hpkg, "templates", "statics", } { path := filepath.Join(out, p) if err := os.MkdirAll(path, DIRMODE); err != nil { log.Println(err) } } // create a basic package.go file in handlers str := fmt.Sprintf("// Handlers documentation\npackage %s", hpkg) ioutil.WriteFile(filepath.Join(out, hpkg, "package.go"), []byte(str), FILEMODE) } // create a config.yml file func createConfig(c *cli.Context) { out := getProjectPath(c) appname := c.GlobalString(PROJECT_OPT) p := filepath.Join(out, CONFIGNAME) y := ymlstruct{ "listen": ":8000", "staticdir": "./statics", "session": map[string]string{ "secret": "<PASSWORD>", "name": appname, }, "template": map[string]string{ "dir": "./templates", }, } b, _ := yaml.Marshal(y) ioutil.WriteFile(p, b, FILEMODE) } // create application in project func createApp(c *cli.Context) { out := getProjectPath(c) p := filepath.Join(out, "main.go") f, err := os.OpenFile(p, os.O_CREATE|os.O_WRONLY, FILEMODE) if err != nil { log.Print(err) return } defer f.Close() tpl, _ := template.New("main").Parse(TPLAPP) tpl.Execute(f, map[string]string{ "Project": getProjectName(c), "HandlersPKG": c.GlobalString(HANDLER_OPT), }) } // returns the project name. func getProjectName(c *cli.Context) string { if c.Command.Name == "app" { if len(c.Args()) > 0 { return c.Args()[0] } } return c.GlobalString(PROJECT_OPT) } // returns project path. func getProjectPath(c *cli.Context) string { _, err := os.Stat(configFile()) if err == nil { r, err := filepath.Abs(".") if err != nil { log.Fatal(err) } return r } to := c.GlobalString(PROJECT_OPT) args := c.Args() if len(args) > 0 { to = args[0] } return filepath.Join(GOPATH, "src", to) } // load config.yml file func loadYaml(c *cli.Context) ymlstruct { out := getProjectPath(c) out = filepath.Join(out, configFile()) b, err := ioutil.ReadFile(out) if err != nil { log.Fatal(err) } y := ymlstruct{} yaml.Unmarshal(b, y) return y } // configFile returns the used "configuration yaml" filename func configFile() string { _, err := os.Stat(DEPRECATED_CONFIGNAME) if err == nil { log.Println("[WARN] config.yml file is now deprecated name, please move your file to kwiscale.yml") return DEPRECATED_CONFIGNAME } return CONFIGNAME } <file_sep>package kwiscale import ( "log" "net/http" "strings" "github.com/gorilla/mux" ) // Log print logs on STDOUT if debug is activated. func Log(v ...interface{}) { if debug { log.Println(v...) } } // Error prints error on STDOUT. func Error(v ...interface{}) { msg := []interface{}{"[ERROR]"} msg = append(msg, v...) log.Println(msg...) } // getMatchRoute returns the better handler that matched request url. // It returns handlername, mux.Route and mux.RouteMatch. // // Rule is simple: // - if A url path length is greater than B url path length, B wins // - if A url path length is equal that B url path length, then: // - if A number of path vars is greater than B number if path vars, B wins // // So: // // - /path/A vs /B => B wins // - /path/A/{foo:.*} vs /path/B/bar => B wins func getBestRoute(app *App, r *http.Request) (handlerName string, route *mux.Route, match mux.RouteMatch) { points := -1 for handlerRoute, handler := range app.handlers { var routematch mux.RouteMatch if handlerRoute.Match(r, &routematch) { plength := len(strings.Split(r.URL.Path, "/")) + len(routematch.Vars) if points == -1 { points = plength } else if plength > points { continue } Log("Matches route vars", handler, routematch.Vars) points = plength Log("Handler to fetch", handler) handlerName = handler.handlername route = handlerRoute match = routematch } } return } <file_sep>kwiscale ======== [![Join the chat at https://gitter.im/kwiscale/framework](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/kwiscale/framework?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge) [![Build Status](https://drone.io/github.com/kwiscale/framework/status.png)](https://drone.io/github.com/kwiscale/framework/latest) [![Coverage Status](https://coveralls.io/repos/kwiscale/framework/badge.svg?branch=master&service=github)](https://coveralls.io/github/kwiscale/framework?branch=master) [![Documentation Status](https://readthedocs.org/projects/kwiscale/badge/?version=latest)](http://kwiscale.readthedocs.org/en/latest/?badge=latest) [![GoDoc](https://godoc.org/gopkg.in/kwiscale/framework.v1?status.svg)](https://godoc.org/gopkg.in/kwiscale/framework.v1) Web Middleware for Golang At this time, Kwiscale is at the very begining of developpement. But you can test and give'em some pull-request to improve it. Features ======== - Implement your handlers as structs with HTTP Verbs as method - Plugin system for template engines, session engines and ORM - Use gorilla to manipulate routes and mux - Handler spawned with concurrency How to use ========== Install with "go get" command: go get gopkg.in/kwiscale/framework.v1 go get gopkg.in/kwiscale/framework.v1/cmd/kwiscale Create a project: kwiscale new app myapp cd $GOPATH/myapp Create a handler kwiscale new handler index / homepage Open generated `handlers/index.go` and append "Get" method: ```go package handlers import ( "gopkg.in/kwiscale/framework.v1" ) func init(){ kwiscale.Register(&IndexHandler{}) } type IndexHandler struct { kwiscale.RequestHandler } func (handler *IndexHandler) Get(){ handler.WriteString("Hello you !") } ``` And run the app !: ```bash go run *.go ``` Now, go to http://127.0.0.1:8000 - you should see "Hello You!". If not, check "kwiscale.yml" file if port is "8000", check error log, and so on. If really there is a problem, please submit an issue. Basic Templates =============== Kwiscale provides a "basic" template engine that use `http/template`. Kwiscale only add a "very basic template override system". If you plan to have a complete override system, please use http://gopkg.in/kwiscale/template-pongo2.v1 that implements pango2 template. See the following example. Append templates directory: mkdir templates Then create templates/main.html: ```html <!DOCTYPE html> <html> <head> <title>{{ if .title }}{{.title}}{{ else }} Default title {{ end }}</title> </head> <body> {{/* Remember to use "." as context */}} {{ template "CONTENT" . }} </body> </html> ``` Now create templates/home directory: mkdir templates/home Create templates/home/welcome.html: {{/* override "main.html" */}} {{ define "CONTENT" }} This the welcome message {{ .msg }} {{ end }} This template overrides "main.html" (in `./templates/` directory) and append "CONTENT" template definition. So, the "CONTENT" block will appear at `template "CONTENT"` in "main.html". That's all. In handlers/index.go you may now ask for template rendering: ```go func (h *IndexHandler) Get() { h.Render("home/welcome.html", map[string]string{ "title" : "Welcome !!!", "msg" : "Hello you", }) } ``` You can override template directory using App configuration passed to the constructor: ```go app := kwiscale.NewApp(&kswiscale.Config{ TemplateDir: "./my-template-dir", }) ``` TODO ==== Features in progress: - [ ] Database ORM interface - [ ] Custom Error handler <file_sep>package kwiscale import ( "fmt" "html/template" "io" "io/ioutil" "path/filepath" "reflect" "regexp" "strings" ) var templateEngine = make(map[string]reflect.Type) // TplOptions are template options to pass to template engines if needed type TplOptions map[string]interface{} // RegisterTemplateEngine records template engine that implements Template // interface. The name is used to let config select the template engine. func RegisterTemplateEngine(name string, tpl Template) { templateEngine[name] = reflect.ValueOf(tpl).Elem().Type() } // register basic template engine by default. func init() { RegisterTemplateEngine("basic", &BuiltInTemplate{}) } // Template should be implemented by other template implementation to // allow RequestHandlers to use Render() method type Template interface { // Render method to implement to compile and run template // then write to RequestHandler "w" that is a io.Writer. Render(w io.Writer, template string, ctx interface{}) error // SetTemplateDir should set the template base directory SetTemplateDir(string) // SetOptions pass TplOptions to template engine SetTemplateOptions(TplOptions) } // BuiltInTemplate is Basic template engine that use html/template. type BuiltInTemplate struct { files []string tpldir string funcMap template.FuncMap } // SetTemplateDir set the directory where are found templates. func (tpl *BuiltInTemplate) SetTemplateDir(path string) { t, err := filepath.Abs(path) if err != nil { panic(err) } tpl.tpldir = t Log("Template dir set to ", tpl.tpldir) } // Render method for the basic Template system. // Allow {{/* override "path.html" */}}, no cache, very basic. func (tpl *BuiltInTemplate) Render(w io.Writer, file string, ctx interface{}) error { var err error defer func() { if err != nil { Error(err) } }() file = filepath.Join(tpl.tpldir, file) tpl.files = make([]string, 0) content, err := ioutil.ReadFile(file) // panic if read file breaks if err != nil { panic(err) } tpl.parseOverride(content) tpl.files = append(tpl.files, file) Log(tpl.files) if tpl.funcMap == nil { tpl.funcMap = template.FuncMap{} } tpl.funcMap["static"] = func(file string) string { app := w.(WebHandler).App() url, err := app.GetRoute("statics").URL("file", file) if err != nil { return err.Error() } return url.String() } tpl.funcMap["url"] = func(handler string, args ...interface{}) string { pairs := []string{} for _, p := range args { pairs = append(pairs, fmt.Sprintf("%v", p)) } h := w.(WebHandler).App().GetRoutes(handler) base := []string{} for _, r := range h { url, err := r.URL(pairs...) if err != nil { continue } route := strings.Split(url.String(), "/") if len(route) >= len(base) { base = route } } if len(base) == 0 { return "handler url not realized - please check" } return strings.Join(base, "/") } t, err := template. New(filepath.Base(tpl.files[0])). Funcs(tpl.funcMap). ParseFiles(tpl.files...) // panic if template breaks in parse if err != nil { panic(err) } err = t.Execute(w, ctx) // return error there ! return err } // SetTemplateOptions set needed options to template engine. For BuiltInTemplate // there are no option at this time. func (tpl *BuiltInTemplate) SetTemplateOptions(opts TplOptions) { if m, ok := opts["funcs"]; ok { for name, fn := range m.(template.FuncMap) { tpl.funcMap[name] = fn } } } // parseOverride will append overriden templates to be integrating in the // template list to render func (tpl *BuiltInTemplate) parseOverride(content []byte) { re := regexp.MustCompile(`\{\{/\*\s*override\s*\"?(.*?)\"?\s*\*/\}\}`) matches := re.FindAllSubmatch(content, -1) for _, m := range matches { // find bottom templates tplfile := filepath.Join(tpl.tpldir, string(m[1])) c, _ := ioutil.ReadFile(tplfile) tpl.parseOverride(c) tpl.files = append(tpl.files, tplfile) } } <file_sep>/* Kwiscale is a framework that provides Handling System. That means that you will be able to create Handlers that handles HTTP Verbs methods. Kwiscale can handle basic HTTP Verbs as Get, Post, Delete, Patch, Head and Option. Kwiscale can also serve Websockets. Kwiscale provides a basic template system based on http/template from Go SDK and has got a plugin system to provides other template engines. The built-in template allows to override templates. Example: // templates/main.go <body> {{ template "CONTENT" .}} </body> // template/home/index.go (remove the "\" in override directive) {{/* override "main.go" *\/}} {{ define "CONTENT" }} <p>Hello workd</p> {{ end }} Also, built-in template provides two functions: - url: gives url of a handler with parameters - static: gives static resource url Example: <link rel="stylesheet" href="{{static "/css/styles.css"}}" /> <a href="{{ url "home" }}">Home</a> <a href="{{ url "user" "id" 12345 }}">User</a> <a href="{{ url "handlers.UserHandler" "id" 12345 }}">User</a> For "url" function, the first argument can be: - alias for handler - handler name Others arguments are the pair "key value". See http://gopkg.in/kwiscale/template-pongo2.v1 to use Pongo2. To handle HTTP Verbs: type HomeHandler struct {kwiscale.RequestHandler} func (home *HomeHandler) Get(){ // This will respond to GET call home.WriteString("Hello !") } func main(){ app := kwiscale.NewApp(nil) app.AddRoute("/home", &HomeHandler{}) // Default listening on 8000 port app.ListenAndServe() } To be able to use configuration file (yaml), you MUST register handlers. The common way to do is to use "init()" function in you handlers package: package handlers import "gopkg.in/kwiscale/framework.v1" func init(){ kwiscale.Register(&HomeHandler{}) } type HomeHandler struct {kwiscale.HomeHandler} //... Note: if you're using kwiscale CLI, `kwiscale new handler` command create the register call for you. Kwiscale provide a way to have method with parameter that are mapped from the given route. Example: app.AddRoute(`/user/{name:.+/}{id:\d+}/`, UserHandler{}) //... type UserHandler struct {kwiscale.RequestHandler} func (handler *UserHandler) Get(name string, id int) { // ... } Note that parameters names for Get() method are not used to map url values. Kwiscale maps values repecting the order found in the route. So you may declare Get() method like this: func (handler *UserHandler) Get(a string, b int) { // ... } Anyway, you always may use "UserHandler.Vars": UserHandler.Vars["id"] and UserHandler.Vars["name"] that are `string` typed. You may use Init() and Destroy() method that are called before and after HTTP verb invocation. You may, for example, open database connection in "Init" and close the connection in "Destroy". Kwiscale provides a CLI: go get gopkg.in/framework/kwiscale kwiscale --help NAME: kwiscale - tool to manage kwiscale application USAGE: kwiscale [global options] command [command options] [arguments...] VERSION: 0.0.1 COMMANDS: new Generate resources (application, handlers...) generate Parse configuration and generate handlers, main file... help, h Shows a list of commands or help for one command GLOBAL OPTIONS: --project "kwiscale-app" project name, will set $GOPATH/src/[projectname] [$KWISCALE_PROJECT] --handlers "handlers" handlers package name [$KWISCALE_HANDLERS] --help, -h show help --generate-bash-completion --version, -v print the version See http://readthedocs.org/projects/kwiscale/ */ package kwiscale <file_sep>package main // The main package template. const TPLAPP = `package main import ( "gopkg.in/kwiscale/framework.v1" _ "{{.Project}}/{{.HandlersPKG}}" ) func main(){ app := kwiscale.NewAppFromConfigFile() app.ListenAndServe() } ` // the main.go template. const TPLHANDLER = `package {{.HandlersPKG}} import ( "gopkg.in/kwiscale/framework.v1" ) func init(){ kwiscale.Register(&{{.Handler}}{}) } type {{.Handler}} struct { kwiscale.RequestHandler } ` // Generate a handler register call. const TPLADDNAMEDROUTE = " kwiscale.Register(&{{.Route.handler}}{})" <file_sep>package kwiscale import ( "io/ioutil" "log" "net/http" "net/http/httptest" "os" "path/filepath" "testing" ) // A basic request handler type templateHandler struct{ RequestHandler } // Respond to GET func (h *templateHandler) Get() { h.Render("main.html", map[string]interface{}{ "Foo": "bar", }) } // Test a template rendering with a not found file. func TestRenderError(t *testing.T) { r, _ := http.NewRequest("GET", "http://www.test.com/", nil) w := httptest.NewRecorder() app := NewApp(&Config{ TemplateDir: "./", }) log.Println("An error SHOULD appear and it's expected !") app.AddRoute("/", &templateHandler{}) app.ServeHTTP(w, r) if w.Code != http.StatusInternalServerError { t.Fatal("A non existing template should do a 500 error, but it returns ", w.Code) } } // Test a template rendering with found template. func TestRenderVar(t *testing.T) { tpl := `<p>{{ .Foo }}</p>` d, err := ioutil.TempDir("", "kwiscale-") if err != nil { t.Fatal(err) } defer os.RemoveAll(d) err = ioutil.WriteFile(filepath.Join(d, "main.html"), []byte(tpl), 0644) if err != nil { t.Fatal(err) } r, _ := http.NewRequest("GET", "http://www.test.com/", nil) w := httptest.NewRecorder() app := NewApp(&Config{ TemplateDir: d, }) app.AddRoute("/", &templateHandler{}) app.ServeHTTP(w, r) expected := "<p>bar</p>" body := w.Body.String() if body != expected { t.Errorf("rendered template failed: %s != %s", expected, body) } } <file_sep>package kwiscale import "reflect" // handlerManager is used to manage handler production. type handlerManager struct { // the handler type to produce handler string // record closers closer chan int // chan that provides handler producer chan WebHandler } // newWebHandler produce a WebHandler from registry. func (manager handlerManager) newWebHandler() WebHandler { defer func() { if err := recover(); err != nil { Error(err, handlerRegistry) } }() return reflect.New(handlerRegistry[manager.handler]).Interface().(WebHandler) } // produce returns the producer chan. func (manager handlerManager) produce() <-chan WebHandler { return manager.producer } // produceHandlers continuously generates new handlers. // The number of handlers to generate in cache is set by // Config.NbHandlerCache. func (manager handlerManager) produceHandlers() { // forever produce handlers until closer is filled for { select { case manager.producer <- manager.newWebHandler(): Log("Produced handler ", manager.handler) case <-manager.closer: Log("Handler production closed") break } } }
72e8f9895e11df2d0b9f060ff0896ca37eb05b68
[ "Markdown", "Go" ]
18
Go
gabrielsagnard/framework
161720454e03ccbb1b158e8a304d12954a62cfc1
6de193b1163adc84dc06bf2d35abd12e339674e0
refs/heads/master
<repo_name>msmith9393/Idea-Board<file_sep>/client/js/inspirationForm.js class InspirationForm extends React.Component { constructor(props) { super(props); } back() { this.props.back(); } changeValue(e) { var categoryId = e.target.value; this.props.getUnsplashPhoto(categoryId); } render() { const { back, inspiringPhoto } = this.props; return ( <div> <form className='insp-form'> <div className='back-to-ideas-btn' onClick={() => this.back()}>back to ideas</div> <label>Choose a Category: <select onChange={e => this.changeValue(e)}> <option></option> <option value={2}>Buildings</option> <option value={3}>Food & Drinks</option> <option value={4}>Nature</option> <option value={8}>Objects</option> <option value={6}>People</option> <option value={7}>Technology</option> </select> </label> </form> {!inspiringPhoto ? null : <div id='image'><img className="image-display" src={inspiringPhoto} /></div>} </div> ) } } window.InspirationForm = InspirationForm; <file_sep>/client/js/newIdeaForm.js class NewIdeaForm extends React.Component { constructor(props) { super(props); } addIdeaToForm() { console.log(); var idea = { title: $('.title')[0].value, description: $('.description')[0].value, creator: $('.creator')[0].value, starred: false } this.props.addIdea(idea); } render() { const { exit, addIdea } = this.props; return ( <form className='form'> <div onClick={() => exit()} className='cancel'>X</div> <label>Title: <input className='title' type='text' placeholder='enter idea here' /></label> <label>Description: <input className='description' type='text' placeholder='enter description here' /></label> <label>Creator: <input className='creator' type='text' placeholder='enter creator here' /></label> <div onClick={this.addIdeaToForm.bind(this)} className='add-idea-button'>add idea</div> </form> ) } } window.NewIdeaForm = NewIdeaForm;<file_sep>/server/server.js var express = require('express'); var app = express(); var port = 3000; //MYMY //once again another test // app.set('trust proxy', 1) // app.use(session({ // secret: 'keyboard cat', // cookie: {} // })) // app.use(bodyParser.urlencoded({extended: true})); // app.use(bodyParser.json()) app.use(express.static(__dirname + '/../client')); app.get('/', function(req, res) { // var sess = req.session.save(function(err) { // if (err) { // console.log(err); // } else { res.send(express.static('index')); // } // }) }); app.listen(port, function() { console.log('App listening on port ', port); }); module.exports = app;<file_sep>/client/lib/searchUnsplash.js var searchUnsplash = (options, callback) => { $.ajax({ type: 'GET', url: 'https://api.unsplash.com/categories/' + options.category_id + '/photos?client_id=' + UNSPLASH_APPLICATION_ID, success: function(photos) { console.log('Success in searchUnsplash!'); callback(photos); }, error: function(data) { console.log('Ajax error in searchUnsplash'); } }); }; window.searchUnsplash = searchUnsplash;<file_sep>/client/js/ideaVisualizeDisplay.js class IdeaVisualizeDisplay extends React.Component { constructor(props) { super(props); } handleClick() { this.props.showVisualization(); } back() { this.props.back(); } showIdeas() { var starredIdeas = this.props.starredIdeas var ideas = this.props.ideas var allIdeas = ideas.concat(starredIdeas).map(function(obj, index) { obj.index = index+1; return obj; }); if (allIdeas.length) { d3it(allIdeas); } } render() { const { showVisualization } = this.props; return ( <div> <div className='back-to-ideas-btn' onClick={() => this.back()}>back to ideas</div> <div className='back-to-ideas-btn' onClick={() => this.showIdeas()}>show ideas</div> <div id='graph'></div> </div> ) } } window.IdeaVisualizeDisplay = IdeaVisualizeDisplay; <file_sep>/client/js/app.js class App extends React.Component { constructor(props) { super(props); this.state = { displayAddForm: false, displayInspirationForm: false, showVisualization: false, showIdeas: true, ideas: [], starredIdeas: [], inspiringPhoto: null }; } getUnsplashPhoto(catId) { var options = { category_id: catId, }; searchUnsplash(options, (photos) => { var num = photos.length - 1; var randNum = Math.floor(Math.random() * num); var randPhoto = photos[randNum].urls.regular; console.log('CATID', catId) console.log('RAND PHOTO', randPhoto) this.setState({inspiringPhoto: randPhoto}) }) }; show() { this.setState({displayAddForm: true}); } hide() { this.setState({displayAddForm: false}); } addIdea(idea) { var newIdeas = this.state.ideas.concat([idea]); this.setState({ideas: newIdeas, displayAddForm: false}) } getInspiration() { this.setState({showIdeas: false, displayAddForm: false, showVisualization: false, displayInspirationForm: true}) } getVisualization() { this.setState({showIdeas: false, displayAddForm: false, displayInspirationForm: false, showVisualization: true}) } handleStar() { console.log('handleStar'); var allIdeas = this.state.ideas.concat(this.state.starredIdeas); var newIdeas = []; var newStarredIdeas = []; allIdeas.forEach(function(idea) { if (idea.starred) { newStarredIdeas.push(idea); } else { newIdeas.push(idea); } }); this.setState({ideas: newIdeas, starredIdeas: newStarredIdeas}) } goBack() { this.setState({displayInspirationForm: false, showVisualization: false, showIdeas: true}) } deleteIdea(index) { console.log(index); var oldIdeas = this.state.ideas; oldIdeas.splice(index, 1); this.setState({ideas: oldIdeas}); } deleteStarIdea(index) { console.log(index); var oldIdeas = this.state.starredIdeas oldIdeas.splice(index, 1); this.setState({starredIdeas: oldIdeas}); } render() { const { displayAddForm, displayInspirationForm, ideas, starredIdeas, showVisualization, showIdeas, inspiringPhoto } = this.state; return ( <div className='header'> <h3>IDEA BOARD</h3> <img className='divider' src='assets/squiggly.png' /> {displayInspirationForm || showVisualization ? null : <div className='btns'> <div className='inspiration-btn' onClick={() => this.getInspiration()}>inspiration?</div> <div className='new-button' onClick={() => this.show()}>new idea</div> <div className='bubble-button' onClick={() => this.getVisualization()}>visualize</div> </div> } {showVisualization ? <IdeaVisualizeDisplay ideas={ideas} starredIdeas={starredIdeas} back={this.goBack.bind(this)} /> : null } {displayAddForm ? <NewIdeaForm exit={this.hide.bind(this)} addIdea={this.addIdea.bind(this)} /> : null} {displayInspirationForm ? <InspirationForm inspiringPhoto={inspiringPhoto} getUnsplashPhoto={this.getUnsplashPhoto.bind(this)} back={this.goBack.bind(this)} /> : null } {showIdeas ? <ListOfIdeas deleteIdea={this.deleteIdea.bind(this)} deleteStarIdea={this.deleteStarIdea.bind(this)} handleStar={this.handleStar.bind(this)} ideas={ideas} starredIdeas={starredIdeas} /> : null } </div> ) } } window.App = App; <file_sep>/client/js/listOfIdeas.js class ListOfIdeas extends React.Component { constructor(props) { super(props); } render() { const { ideas, starredIdeas, handleStar, deleteIdea, deleteStarIdea } = this.props; return ( <div id='container'> <div id='regular'> {ideas.length ? <h4 className='list-title'>IDEAS</h4> : null} {ideas.map((idea, index) => <Idea handleStar={handleStar} key={index} idea={idea} deleteIdea={deleteIdea.bind(this, index)} /> )} </div> <div id='stars'> {starredIdeas.length ? <h4 className='list-title'>&#9734; STARRED IDEAS</h4> : null} {starredIdeas.map((idea, index) => <Idea deleteStarIdea={deleteStarIdea.bind(this, index)} handleStar={handleStar} key={index} idea={idea} /> )} </div> </div> ) } } window.ListOfIdeas = ListOfIdeas;<file_sep>/client/js/d3/d3test.js function d3it(data) { // var starredIdeas = [ // {title: 'War', description: 'build a war app', creator: 'allison', starred: true}, // {title: 'Coding', description: 'build a coding app', creator: 'megan', starred: true}, // {title: 'Weather', description: 'build a weather app', creator: 'megan', starred: true}, // {title: 'Cooking', description: 'build a cooking app', creator: 'allison', starred: true} // ]; // var ideas = [ // {title: 'Vegetable', description: 'build a vegetable app', creator: 'ashley', starred: false}, // {title: 'Dessert ', description: 'build a dessert app', creator: 'kyle', starred: false}, // {title: 'Fruit', description: 'build a fruit app', creator: 'ashley', starred: false}, // {title: 'Garten', description: 'build a garten app', creator: 'kyle', starred: false} // ]; // var allIdeas = ideas.concat(starredIdeas).map(function(obj, index) { // obj.index = index+1; // return obj; // }); var json = JSON.stringify(data); // D3 Bubble Chart var diameter = 500; var color = d3.scale.category20b(); var svg = d3.select('#graph').append('svg') .attr('width', diameter) .attr('height', diameter); var bubble = d3.layout.pack() .size([diameter, diameter]) .value(function(d) { return d.size; }).sort(function(a, b) { return -(a.value - b.value) }).padding(30); // generate data with calculated layout values var nodes = bubble.nodes(processData(data)) .filter(function(d) { return !d.children; }); // filter out the outer bubble var bubbles = svg.selectAll('circle') .data(nodes); bubbles.enter().append('circle') .style("fill", function(d) { return color(d.value); }) .attr('transform', function(d) { return 'translate(' + d.x + ',' + d.y + ')'; }) .attr('r', function(d) { return d.r; }) .attr('class', function(d) { return d.className; }); bubbles.enter().append('text') .attr('x', function(d) { return d.x; }) .attr('y', function(d) { return d.y + 5; }) .attr('font-size', function(d) { return 8 + d.size + 'px' }) .attr('text-anchor', 'middle') .text(function(d) { return d.name; }) .style({ 'fill': 'white', 'font-family': 'Arial' }); function processData(data) { var newDataSet = []; for (var i=0; i<data.length; i++) { if (data[i].starred) { var name = String.fromCharCode(9734) + ' ' + data[i].title; var useClass = 'starredBubble'; } else { var name = data[i].title; var useClass = 'regularBubble'; } newDataSet.push({name: name, othername: data[i].title, className: useClass + ' ' + data[i].title, size: data[i].index}) } return {children: newDataSet}; }; bubbles.on('mouseover', function(bubble) { d3.selectAll('.' + bubble.othername).transition('linear').duration(500) .attr('r', function(d) { return 1.25 * d.r; }) }); bubbles.on('mouseleave', function(bubble) { d3.selectAll('.' + bubble.othername).transition('linear').duration(500) .attr('r', function(d) { return d.r; }) }); }; window.d3it = d3it;<file_sep>/client/js/idea.js class Idea extends React.Component { constructor(props) { super(props); } toggleStar() { this.props.idea.starred = !this.props.idea.starred; console.log(this.props.idea.starred) this.props.handleStar(); } delete(idea) { if (idea.starred) { this.props.deleteStarIdea(); } else { this.props.deleteIdea(); } } render() { const { idea } = this.props; return ( <div className='idea'> {idea.starred ? <div onClick={this.toggleStar.bind(this)} className='starClicked'>&#9734; </div> : <div onClick={this.toggleStar.bind(this)} className='star'>&#9734; </div>} <h4>Title: {idea.title}</h4> <p>Description: {idea.description}</p> <p>Created By: {idea.creator}</p> <p onClick={() => this.delete(idea) } className='delete'>delete</p> </div> ) } } window.Idea = Idea; <file_sep>/README.md # Idea-Board This is a simple web app that I completed in two days as an MVP project at hack reactor ## Technologies/APIs * React * D3.js * Node * Express * Unsplash API
bdada83a1e8c5d41179f68213e1dd4e838073725
[ "JavaScript", "Markdown" ]
10
JavaScript
msmith9393/Idea-Board
07906e4a2209d25dcd48f76fedd94d0822bbbc18
3779c8c85bdb09b63f618f641778f552124c9cb4
refs/heads/master
<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Web; /// <summary> /// Descripción breve de LibroGenero /// </summary> public class LibroGenero { public LibroGenero() {} public int Codigo_id { get; set; } public int Libro_id { get; set; } public int Genero_id { get; set; } }<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Services; using System.Web.UI; using System.Web.UI.WebControls; namespace KOSetup { public partial class LearnKO : System.Web.UI.Page { /// <summary> /// Page Load Method /// </summary> /// <param name="sender"></param> /// <param name="e"></param> protected void Page_Load(object sender, EventArgs e) { } #region Public Web Methods. /// <summary> /// Gets Student Details /// </summary> /// <returns></returns> [WebMethod] public static Student[] FetchStudents() { LearningKOEntities dbEntities = new LearningKOEntities(); var data = (from item in dbEntities.Students orderby item.StudentId select item).Take(5); return data.ToArray(); } /// <summary> /// Saves Student Details /// </summary> /// <param name="data"></param> /// <returns></returns> [WebMethod] public static string SaveStudent(Student[] data) { try { var dbContext = new LearningKOEntities(); var studentList = from dbStududent in dbContext.Students select dbStududent; foreach (Student userDetails in data) { var student = new Student(); if (userDetails != null) { student.StudentId = userDetails.StudentId; student.FirstName = userDetails.FirstName; student.LastName = userDetails.LastName; student.Address = userDetails.Address; student.Age = userDetails.Age; student.Gender = userDetails.Gender; student.Batch = userDetails.Batch; student.Class = userDetails.Class; student.School = userDetails.School; student.Domicile = userDetails.Domicile; } Student stud=(from st in studentList where st.StudentId==student.StudentId select st).FirstOrDefault(); if (stud == null) dbContext.Students.Add(student); dbContext.SaveChanges(); } return "Data saved to database!"; } catch (Exception ex) { return "Error: " + ex.Message; } } /// <summary> /// Deletes Student Details /// </summary> /// <param name="data"></param> /// <returns></returns> [WebMethod] public static string DeleteStudent(Student data) { try { var dbContext = new LearningKOEntities(); var student = dbContext.Students.FirstOrDefault(userId => userId.StudentId == data.StudentId); if (student != null) { if (student != null) { dbContext.Students.Remove(student); dbContext.SaveChanges(); } } return "Data deleted from database!"; } catch (Exception ex) { return "Error: " + ex.Message; } } #endregion } }<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Web; /// <summary> /// Descripción breve de AutorBLL /// </summary> public class AutorBLL { public AutorBLL() { // // TODO: Agregar aquí la lógica del constructor // } public static int InsertarAutor(Autor obj) { if (obj == null) throw new ArgumentException("El objeto a insertar no puede ser nulo"); if (string.IsNullOrEmpty(obj.nombre)) throw new ArgumentException("El nombre no puede ser nulo o vacio"); if (string.IsNullOrEmpty(obj.foto)) throw new ArgumentException("La descripcion no puede ser nula o vacio"); int? idAutor = 0; AutorDSTableAdapters.AutorTableAdapter adapter = new AutorDSTableAdapters.AutorTableAdapter(); adapter.Insert(obj.nombre, obj.foto, ref idAutor); return idAutor.Value; } public static void ModificarAutor(Autor obj) { if (obj == null) throw new ArgumentException("El objeto a modificar no puede ser nulo"); AutorDSTableAdapters.AutorTableAdapter adapter = new AutorDSTableAdapters.AutorTableAdapter(); adapter.Update(obj.nombre, obj.foto, obj.idAutor); } public static void EliminarAutor(int id) { AutorDSTableAdapters.AutorTableAdapter adapter = new AutorDSTableAdapters.AutorTableAdapter(); adapter.Delete(id); } public static List<Autor> GetAutores() { AutorDSTableAdapters.AutorTableAdapter adapter = new AutorDSTableAdapters.AutorTableAdapter(); AutorDS.AutorDataTable table = adapter.Autores(); List<Autor> result = new List<Autor>(); foreach (var row in table) { result.Add(new Autor() { idAutor = row.idAutor, nombre = row.nombre, foto = row.foto }); } return result; } public static Autor GetAutorById(int idautor) { if (idautor <= 0) throw new ArgumentException("El id no puede ser nulo ni vacio"); AutorDSTableAdapters.AutorTableAdapter adapter = new AutorDSTableAdapters.AutorTableAdapter(); AutorDS.AutorDataTable table = adapter.GetAutoresById(idautor); Autor result = null; if (table.Rows.Count == 1) { AutorDS.AutorRow row = table[0]; result = new Autor() { idAutor = row.idAutor, nombre = row.nombre, foto = row.foto }; } return result; } public static List<Autor> GetAutorByIdToList(int idautor) { AutorDSTableAdapters.AutorTableAdapter adapter = new AutorDSTableAdapters.AutorTableAdapter(); AutorDS.AutorDataTable table = adapter.Autores(); List<Autor> result = new List<Autor>(); foreach (var row in table) { if (row.idAutor == idautor) { result.Add(new Autor() { idAutor = row.idAutor, nombre = row.nombre, foto = row.foto }); } } return result; } }<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Web; /// <summary> /// Descripción breve de GeneroLibro /// </summary> public class GeneroLibro { public GeneroLibro() { } public int id { get; set; } public int idLibro { get; set; } public int idGenero { get; set; } public string nombreGenero { get; set; } public string NombreLibro { get; set; } public Libro LibroSeleccionado { get { return LibroBLL.SelectById(idLibro); } } }<file_sep><?php include_once './DAO/DAL/Connection.php'; include_once './DAO/DTO/Juego.php'; include_once './DAO/BLL/JuegoBLL.php'; $juegoBLL = new JuegoBLL(); $id = 0; $objJuego = null; if (isset($_REQUEST["id"])) { $id = $_REQUEST["id"]; } ?> <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title></title> <link href="css/bootstrap.min.css" rel="stylesheet" type="text/css"/> <link href="css/bootstrap-theme.min.css" rel="stylesheet" type="text/css"/> <script src="js/bootstrap.min.js" type="text/javascript"></script> <link href="css/estilo.css" rel="stylesheet" type="text/css"/> </head> <body> <div class="container"> <div class="row"> <div class="col-md-6"> <div class="panel panel-primary"> <div class="panel panel-heading"> Agregar Foto de Juego </div> <div class="panel panel-body"> <form action="abmJuego.php" enctype="multipart/form-data" method="post"> <input type="hidden" value="fotoperfil" name="tarea"/> <input type="hidden" value="<?php echo $id; ?>" name="id" /> <div class="form-group"> <input type="file" name="archivo" required="required"/> <image class="tamanioimg" src="img/<?php echo $id; ?>.jpg" /> </div> <div class="form-group"> <input class="btn btn-primary" type="submit" value="subir foto" /> <a href="fotoJuego.php" class="btn btn-danger">Cancelar</a> </div> </form> </div> </div> </div> </div> </div> </body> </html> <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; public partial class formularioLibro : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { string id = Request.QueryString["id"]; if (id != null) { Libro objLibro = LibroBLL.SelectById(Convert.ToInt32(id)); if (objLibro != null) { isbntxt.Text = objLibro.isbn; titulotxt.Text = objLibro.titulo; editorialtxt.Text = objLibro.editorial; anotxt.Text = Convert.ToString(objLibro.ano); autortxt.Text = Convert.ToString(objLibro.id_Autor); hdnId.Value = objLibro.id_Libro.ToString(); } } } } protected void btnguardar_Click(object sender, EventArgs e) { string isbn = isbntxt.Text; string titulo = titulotxt.Text; int idautor = Convert.ToInt32(autortxt.Text); string editorial = editorialtxt.Text; int ano = Convert.ToInt32(anotxt.Text); guardarimagenes.SaveAs(Server.MapPath("~/imagenes/") + isbn + ".jpg"); try { if (string.IsNullOrEmpty(hdnId.Value)) { LibroBLL.Insert(isbn, titulo, editorial, ano, idautor); } else { LibroBLL.Update(isbn, titulo, editorial, ano, idautor, Convert.ToInt32(hdnId.Value)); } Response.Redirect("~/listaLibro.aspx"); } catch (Exception) { } } }<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.EntityFrameworkCore; using MVCPeliculas.Models; namespace MVCPeliculas.Context { public class ProyectoPeliculaContext : DbContext { public ProyectoPeliculaContext(DbContextOptions options): base(options) { } public DbSet<Genero> Genero { get; set; } public DbSet<Director> Director { get; set; } public DbSet<Pelicula> Peliculas { get; set; } public DbSet<GeneroPelicula> GeneroPeli { get; set; } protected override void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder.Entity<Pelicula>().ToTable("Pelicula"); modelBuilder.Entity<Genero>().ToTable("Genero"); modelBuilder.Entity<Director>().ToTable("Director"); modelBuilder.Entity<GeneroPelicula>().ToTable("GeneroPelicula"); } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace PeliculasMVC.Models { public class Pelicula { public int PeliculaID { get; set; } public string Titulo { get; set; } public string Imagen { get; set; } public string Descripcion { get; set; } public string Horarios { get; set; } public int Puntuacion { get; set; } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; public partial class formularioLibroGenero : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { //if (!IsPostBack) //{ // string id = Request.QueryString["id"]; // if (id != null) // { // GeneroLibroEdiciones objGeneroLibroEdiciones = GeneroLibroEdicionesBLL.SelectByIdGeneroLibro(Convert.ToInt32(id)); // if (objGeneroLibroEdiciones != null) // { // prueba.Text = Convert.ToString(objGeneroLibroEdiciones.IdLibro); // } // } //} } protected void btnGuardar_Click(object sender, EventArgs e) { int idLibro = Convert.ToInt32(cblibro.SelectedValue); int idGenero1 = Convert.ToInt32(cbgenero1.SelectedValue.ToString()); try { if (string.IsNullOrEmpty(hdnId.Value)) { GeneroLibroEdicionesBLL.Insert(idLibro, idGenero1); } Response.Redirect("~/abmLibro.aspx"); } catch (Exception) { } } }<file_sep><?php /** * Description of CategoriaPadreBLL * * @author ANDREA_ORTIZ */ class CategoriaPadreBLL { public function insert($nombre) { $objConexion = new Connection(); $objConexion->queryWithParams("INSERT INTO tbl_categoriapadre(nombre) VALUES (:pNombre)", array( ":pNombre" => $nombre )); } public function update($nombre, $id) { $objConexion = new Connection(); $objConexion->queryWithParams("UPDATE tbl_categoriapadre SET nombre = :pNombre WHERE id = :pId", array( ":pNombre" => $nombre, ":pId" => $id )); } public function delete($id) { $objConexion = new Connection(); $objConexion->queryWithParams(" DELETE From tbl_categoriapadre WHERE id = :pId", array( ":pId" => $id )); } public function selectAll() { $listaCategoriasPadre = array(); $objConexion = new Connection(); $res = $objConexion->query(" SELECT id,nombre FROM tbl_categoriapadre"); while ($row = $res->fetch(PDO::FETCH_ASSOC)) { $objCategoriaPadre = $this->rowToDto($row); $listaCategoriasPadre[] = $objCategoriaPadre; } return $listaCategoriasPadre; } public function select($id) { $objConexion = new Connection(); $res = $objConexion->queryWithParams(" SELECT id,nombre FROM tbl_categoriapadre WHERE id = :pId", array( ":pId" => $id )); if ($res->rowCount() == 0) { return null; } $row = $res->fetch(PDO::FETCH_ASSOC); return $this->rowToDto($row); } function rowToDto($row) { $objCategoriaPadre = new CategoriaPadre(); $objCategoriaPadre->setId($row["id"]); $objCategoriaPadre->setNombre($row["nombre"]); return $objCategoriaPadre; } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using CarteleraMVC.Context; using CarteleraMVC.Models; namespace CarteleraMVC.Controllers { public class HomeController : Controller { private readonly CarteleraContextMVC db; public HomeController(CarteleraContextMVC context) { db = context; } public IActionResult Index() { db.Database.EnsureCreated(); var pelicula = new Pelicula { titulo = "Titanic", horarios = "18:30 / 22:00 ", puntaje = 4 }; db.Peliculas.Add(pelicula); var categoria = new Categoria { nombre = "Drama" }; db.Categorias.Add(categoria); var categoriasPelicula = new CategoriasPelicula { Pelicula = pelicula, Categoria = categoria, PeliculaID = pelicula.PeliculaID, CategoriaID = categoria.CategoriaID }; db.CategoriasPeliculas.Add(categoriasPelicula); db.SaveChanges(); return View(); } public IActionResult About() { ViewData["Message"] = "Your application description page."; return View(); } public IActionResult Contact() { ViewData["Message"] = "Your contact page."; return View(); } public IActionResult Error() { return View(); } } } <file_sep><?php /** * Description of JuegoCategoria * * @author Nikolas-PC */ class JuegoCategoria { private $juego_id; private $categoria_id; function __construct($juego_id, $categoria_id) { $this->juego_id = $juego_id; $this->categoria_id = $categoria_id; } function getJuego_id() { return $this->juego_id; } function getCategoria_id() { return $this->categoria_id; } function setJuego_id($juego_id) { $this->juego_id = $juego_id; } function setCategoria_id($categoria_id) { $this->categoria_id = $categoria_id; } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Web; /// <summary> /// Descripción breve de GeneroLibroBLL /// </summary> public class GeneroLibroBLL { public GeneroLibroBLL() { } public static List<GeneroLibro> SelectByIdGenero(int id) { List<GeneroLibro> listaGenerosLibros = new List<GeneroLibro>(); GeneroLibroDSTableAdapters.SelectByIdGeneroTableAdapter adapter = new GeneroLibroDSTableAdapters.SelectByIdGeneroTableAdapter(); GeneroLibroDS.SelectByIdGeneroDataTable table = adapter.SelectByIdGenero(id); foreach (GeneroLibroDS.SelectByIdGeneroRow row in table) { listaGenerosLibros.Add(rowToDto(row)); } return listaGenerosLibros; } private static GeneroLibro rowToDto(GeneroLibroDS.SelectByIdGeneroRow row) { GeneroLibro objGeneroLibro = new GeneroLibro(); objGeneroLibro.id = row.id; objGeneroLibro.idLibro = row.idLibro; objGeneroLibro.idGenero = row.idGenero; objGeneroLibro.nombreGenero = row.nombre; objGeneroLibro.NombreLibro = row.titulo; return objGeneroLibro; } }<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace CarteleraMVC.Models { public class Pelicula { public int PeliculaID { get; set; } public string titulo { get; set; } //public int director_id { get; set; } public string horarios { get; set; } public int puntaje { get; set; } public ICollection<CategoriasPelicula> categoriasPelicula { get; set; } } } <file_sep><?php /* |-------------------------------------------------------------------------- | Web Routes |-------------------------------------------------------------------------- | | Here is where you can register web routes for your application. These | routes are loaded by the RouteServiceProvider within a group which | contains the "web" middleware group. Now create something great! | */ Route::get('/', function () { return view('welcome'); }); Auth::routes(); Route::get('/home', 'HomeController@index')->name('home'); Route::get('/notas/{id}', 'NotasController@destroy'); Route::post('/notas/', 'NotasController@store'); Route::get('/notas/', 'NotasController@index'); Route::get('/notas/edit/{id}', 'NotasController@edit');<file_sep><?php include_once './DAO/DAL/Connection.php'; include_once './DAO/DTO/Categoria.php'; include_once './DAO/BLL/CategoriaBLL.php'; $categoriaBLL = new CategoriaBLL(); $id = 0; $objCategoria = null; if (isset($_REQUEST["id"])) { $id = $_REQUEST["id"]; $objCategoria = $categoriaBLL->select($id); } ?> <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Categoria</title> <link href="css/bootstrap.min.css" rel="stylesheet" type="text/css"/> <link href="css/bootstrap-theme.min.css" rel="stylesheet" type="text/css"/> <script src="js/bootstrap.min.js" type="text/javascript"></script> </head> <body> <div class="container"> <div class="row"> <div class="col-md-6"> <h2>Datos de Categoria</h2> <form action="abmCategoria.php" method="post"> <input type="hidden" value="<?php if ($objCategoria != null) { echo "actualizar"; } else { echo "insertar"; } ?>" name="tarea"/> <input type="hidden" value="<?php echo $id; ?>" name="id"/> <div class="form-group"> <label> Nombre: </label> <input class="form-control" type="text" name="nombre" value="<?php if ($objCategoria != null) { echo $objCategoria->getNombre(); } ?>" required="required" /> </div> <div class="form-group"> <label> Categoria Padre: </label> <input class="form-control" type="text" name="idCategoriaPadre" value="<?php if ($objCategoria != null) { echo $objCategoria->getIdCategoriaPadre(); } ?>" required="required" /> </div> <div> <input type="submit" value="Guardar Datos"> <a href="AgregarCategoria.php" class="btn btn-danger" >Cancelar</a> </div> </form> </div> </div> </div> </body> </html> <file_sep><?php /** * Description of Categoria * * @author Nikolas-PC */ class Categoria { private $codigo_id; private $nombre; private $id_categoriaPadre; function __construct($codigo_id, $nombre, $id_categoriaPadre) { $this->codigo_id = $codigo_id; $this->nombre = $nombre; $this->id_categoriaPadre = $id_categoriaPadre; } function getCodigo_id() { return $this->codigo_id; } function getNombre() { return $this->nombre; } function getId_categoriaPadre() { return $this->id_categoriaPadre; } function setCodigo_id($codigo_id) { $this->codigo_id = $codigo_id; } function setNombre($nombre) { $this->nombre = $nombre; } function setId_categoriaPadre($id_categoriaPadre) { $this->id_categoriaPadre = $id_categoriaPadre; } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; public partial class LibroPagina : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { if (IsPostBack) return; String id = Request.QueryString["id"]; if (id != null) { libroBll.borrar(id); } Response.Redirect("VerLibros.aspx"); } protected void btnAceptar_Click(object sender, EventArgs e) { String id = Request.QueryString["id"]; if (id != null) { // editar // titulo autor ISBN Año Editorial // h3ISBN.Value = libro.ISBN; // Anho.Value = libro.anho + ""; // Editorial.Value = libro.editorial; libroBll.Editar(H1titulo.Value, lista.SelectedItem.Value, h3ISBN.Value, Anho.Value, Editorial.Value, id); // H1titulo.Value = lista.SelectedItem.Value; // elim if(FileUpload1.FileName != null) { string DeleteThis = id +".jpg"; String Files = @"C:/Users/L855/Documents/Visual Studio 2017/WebSites/Biblioteca/fotos/" + DeleteThis; if ((System.IO.File.Exists(Files))) { System.IO.File.Delete(Files); // borroo } FileUpload1.SaveAs("C:/Users/L855/Documents/Visual Studio 2017/WebSites/Biblioteca/fotos/" + id + ".jpg"); Response.Redirect("VerLibros.aspx"); } // Response.Redirect("VerLibros.aspx"); // C: \Users\L855\Documents\Visual Studio 2017\WebSites\Biblioteca\fotos // StatusLabel.Text = "Upload status: File uploaded!"; } else { // nuevo // libroBll.Editar(H1titulo.Value, lista.SelectedItem.Value, h3ISBN.Value, Anho.Value, Editorial.Value, id); libroBll.insert(H1titulo.Value, lista.SelectedItem.Value, h3ISBN.Value, Anho.Value, Editorial.Value, "nu"); Response.Redirect("VerLibros.aspx"); int idd = libroBll.selectUltimo(); if (FileUpload1.FileName != null) { FileUpload1.SaveAs("C:/Users/L855/Documents/Visual Studio 2017/WebSites/Biblioteca/fotos/" + idd + ".jpg"); } Response.Redirect("VerLibros.aspx"); } } protected void btnEditar_Click(object sender, EventArgs e) { Response.Redirect("VerLibros.aspx"); } } <file_sep><?php /** * Description of Juego * * @author Nikolas-PC */ class Juego { private $codigo_id; private $nombre; private $precio; private $descripcion; // function __construct($codigo_id, $nombre, $precio, $descripcion) { // $this->codigo_id = $codigo_id; // $this->nombre = $nombre; // $this->precio = $precio; // $this->descripcion = $descripcion; // } function getCodigo_id() { return $this->codigo_id; } function getNombre() { return $this->nombre; } function getPrecio() { return $this->precio; } function getDescripcion() { return $this->descripcion; } function setCodigo_id($codigo_id) { $this->codigo_id = $codigo_id; } function setNombre($nombre) { $this->nombre = $nombre; } function setPrecio($precio) { $this->precio = $precio; } function setDescripcion($descripcion) { $this->descripcion = $descripcion; } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Web; /// <summary> /// Descripción breve de LibroBRL /// </summary> public class LibroBRL { public LibroBRL() { // // TODO: Agregar aquí la lógica del constructor // } public static List<Libro> GetLibros(int id) { List<Libro> listaLibros = new List<Libro>(); LibroDSTableAdapters.LibroTableAdapter adapter = new LibroDSTableAdapters.LibroTableAdapter(); LibroDS.LibroDataTable table = adapter.getLibrosByGenero(id); foreach (LibroDS.LibroRow row in table) { listaLibros.Add(rowToDto(row)); } return listaLibros; } private static Libro rowToDto(LibroDS.LibroRow row) { Libro objLibro = new Libro(); objLibro.titulo = row.titulo; objLibro.id = row.id; objLibro.imagen = row.imagen; return objLibro; } public static List<Libro> GetLibrosByAutor(int id) { List<Libro> listaLibros = new List<Libro>(); LibroDSTableAdapters.LibroTableAdapter adapter = new LibroDSTableAdapters.LibroTableAdapter(); LibroDS.LibroDataTable table = adapter.GetLibroByAutor(id); foreach (LibroDS.LibroRow row in table) { listaLibros.Add(rowToDto(row)); } return listaLibros; } private static Libro rowToDtoAutor(LibroDS.LibroRow row) { Libro objLibro = new Libro(); objLibro.titulo = row.titulo; objLibro.id = row.id; objLibro.imagen = row.imagen; return objLibro; } public static void insert(string isbn, string titulo, int autor, string editorial, int anho,string imagen) { LibroDSTableAdapters.LibroTableAdapter adapter = new LibroDSTableAdapters.LibroTableAdapter(); adapter.Insert(isbn, titulo, autor, editorial, anho,imagen); } }<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace MVCPeliculas.Models { public class Director { public int ID { get; set; } public string Nombres { get; set; } public string Apellidos { get; set; } public ICollection<Pelicula> Peliculas { get; set; } public Director() { } } } <file_sep>using System; using System.Collections.Generic; using System.Data; using System.Data.SqlClient; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; public partial class _Default : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { var genero = Request.QueryString["idGenero"]; var autor = Request.QueryString["idAutor"]; if (autor != null) { List<Libro> Libro = LibroBLL.SelectAll_IdAutor(Convert.ToInt32(autor)); rptCustomers.DataSource = Libro; rptCustomers.DataBind(); }else if (genero != null) { List<Libro> Libro = LibroBLL.SelectAll_IdGenero(Convert.ToInt32(genero)); rptCustomers.DataSource = Libro; rptCustomers.DataBind(); } else { List<Libro> Libros = LibroBLL.lectAll(); rptCustomers.DataSource = Libros; rptCustomers.DataBind(); } } } protected void ImageButton1sss_Click1(object sender, CommandEventArgs e) { int StockId = Convert.ToInt32((e.CommandArgument).ToString()); Response.Redirect("Default2.aspx?idLibro=" +StockId); } }<file_sep> using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Threading.Tasks; namespace Cartelera.Models { public class Categoria { public int CategoriaID { get; set; } public string nombre { get; set; } [Display(Name = "Pelicula")] public int PeliculaID { get; set; } public Pelicula Pelicula { get; set; } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Web; /// <summary> /// Descripción breve de Libro /// </summary> public class Libro { public int id { get; set; } public string isbn { get; set; } public string titulo { get; set; } public int idAutor { get; set; } public string editorial { get; set; } public int anho { get; set; } public string imagen { get; set; } public Libro() { // // TODO: Agregar aquí la lógica del constructor // } }<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Web; /// <summary> /// Descripción breve de AutorBLL /// </summary> public class AutorBLL { public AutorBLL() { } public static List<Autor> SelectAll() { List<Autor> listadoAut = new List<Autor>(); DTAutorTableAdapters.tblautoresTableAdapter adapter = new DTAutorTableAdapters.tblautoresTableAdapter(); DTAutor.tblautoresDataTable table = adapter.SelectAll(); foreach (DTAutor.tblautoresRow row in table) { listadoAut.Add(rowToDto(row)); } return listadoAut; } public static Autor SelectById(int idautor) { DTAutorTableAdapters.tblautoresTableAdapter adapter = new DTAutorTableAdapters.tblautoresTableAdapter(); DTAutor.tblautoresDataTable table = adapter.SelectAllById(idautor); if (table.Rows.Count == 0) { return null; } return rowToDto(table[0]); } public static void insert(string nombreautor) { DTAutorTableAdapters.tblautoresTableAdapter adapter = new DTAutorTableAdapters.tblautoresTableAdapter(); adapter.Insert(nombreautor); } public static void update(string nombreautor, int idautor) { DTAutorTableAdapters.tblautoresTableAdapter adapter = new DTAutorTableAdapters.tblautoresTableAdapter(); adapter.Update(nombreautor, idautor); } public static void delete(int idautor) { DTAutorTableAdapters.tblautoresTableAdapter adapter = new DTAutorTableAdapters.tblautoresTableAdapter(); adapter.Delete(idautor); } private static Autor rowToDto(DTAutor.tblautoresRow row) { Autor objAutor = new Autor(); objAutor.AutorId = row.autorId; objAutor.NombreAutor = row.a_nombre; return objAutor; } }<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.Rendering; using Microsoft.EntityFrameworkCore; using TiendaPeliculas.Context; using TiendaPeliculas.Models; namespace TiendaPeliculas.Controllers { public class CategoriaxLibrosController : Controller { private readonly ProyectoTiendaPeliculasContext _context; public CategoriaxLibrosController(ProyectoTiendaPeliculasContext context) { _context = context; } // GET: CategoriaxLibros public async Task<IActionResult> Index() { var proyectoTiendaPeliculasContext = _context.CategoriasxLibro.Include(c => c.Categoria).Include(c => c.Pelicula); return View(await proyectoTiendaPeliculasContext.ToListAsync()); } // GET: CategoriaxLibros/Details/5 public async Task<IActionResult> Details(int? id) { if (id == null) { return NotFound(); } var categoriaxLibro = await _context.CategoriasxLibro .Include(c => c.Categoria) .Include(c => c.Pelicula) .SingleOrDefaultAsync(m => m.PeliculaID == id); if (categoriaxLibro == null) { return NotFound(); } return View(categoriaxLibro); } // GET: CategoriaxLibros/Create public IActionResult Create() { ViewData["CategoriaID"] = new SelectList(_context.Categorias, "ID", "ID"); ViewData["PeliculaID"] = new SelectList(_context.Peliculas, "ID", "ID"); return View(); } // POST: CategoriaxLibros/Create // To protect from overposting attacks, please enable the specific properties you want to bind to, for // more details see http://go.microsoft.com/fwlink/?LinkId=317598. [HttpPost] [ValidateAntiForgeryToken] public async Task<IActionResult> Create([Bind("PeliculaID,CategoriaID")] CategoriaxLibro categoriaxLibro) { if (ModelState.IsValid) { _context.Add(categoriaxLibro); await _context.SaveChangesAsync(); return RedirectToAction("Index"); } ViewData["CategoriaID"] = new SelectList(_context.Categorias, "ID", "ID", categoriaxLibro.CategoriaID); ViewData["PeliculaID"] = new SelectList(_context.Peliculas, "ID", "ID", categoriaxLibro.PeliculaID); return View(categoriaxLibro); } // GET: CategoriaxLibros/Edit/5 public async Task<IActionResult> Edit(int? id) { if (id == null) { return NotFound(); } var categoriaxLibro = await _context.CategoriasxLibro.SingleOrDefaultAsync(m => m.PeliculaID == id); if (categoriaxLibro == null) { return NotFound(); } ViewData["CategoriaID"] = new SelectList(_context.Categorias, "ID", "ID", categoriaxLibro.CategoriaID); ViewData["PeliculaID"] = new SelectList(_context.Peliculas, "ID", "ID", categoriaxLibro.PeliculaID); return View(categoriaxLibro); } // POST: CategoriaxLibros/Edit/5 // To protect from overposting attacks, please enable the specific properties you want to bind to, for // more details see http://go.microsoft.com/fwlink/?LinkId=317598. [HttpPost] [ValidateAntiForgeryToken] public async Task<IActionResult> Edit(int id, [Bind("PeliculaID,CategoriaID")] CategoriaxLibro categoriaxLibro) { if (id != categoriaxLibro.PeliculaID) { return NotFound(); } if (ModelState.IsValid) { try { _context.Update(categoriaxLibro); await _context.SaveChangesAsync(); } catch (DbUpdateConcurrencyException) { if (!CategoriaxLibroExists(categoriaxLibro.PeliculaID)) { return NotFound(); } else { throw; } } return RedirectToAction("Index"); } ViewData["CategoriaID"] = new SelectList(_context.Categorias, "ID", "ID", categoriaxLibro.CategoriaID); ViewData["PeliculaID"] = new SelectList(_context.Peliculas, "ID", "ID", categoriaxLibro.PeliculaID); return View(categoriaxLibro); } // GET: CategoriaxLibros/Delete/5 public async Task<IActionResult> Delete(int? id) { if (id == null) { return NotFound(); } var categoriaxLibro = await _context.CategoriasxLibro .Include(c => c.Categoria) .Include(c => c.Pelicula) .SingleOrDefaultAsync(m => m.PeliculaID == id); if (categoriaxLibro == null) { return NotFound(); } return View(categoriaxLibro); } // POST: CategoriaxLibros/Delete/5 [HttpPost, ActionName("Delete")] [ValidateAntiForgeryToken] public async Task<IActionResult> DeleteConfirmed(int id) { var categoriaxLibro = await _context.CategoriasxLibro.SingleOrDefaultAsync(m => m.PeliculaID == id); _context.CategoriasxLibro.Remove(categoriaxLibro); await _context.SaveChangesAsync(); return RedirectToAction("Index"); } private bool CategoriaxLibroExists(int id) { return _context.CategoriasxLibro.Any(e => e.PeliculaID == id); } } } <file_sep><?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\notas; class HomeController extends Controller { /** * Show the application dashboard. * * @return \Illuminate\Http\Response */ public function index() { return view('home'); } /** * Show the form for creating a new resource. * * @return \Illuminate\Http\Response */ public function create() { // } /** * Store a newly created resource in storage. * * @param \Illuminate\Http\Request $request * @return \Illuminate\Http\Response */ public function store(Request $request) { $data = [ 'titulo' => request['titulo'], 'nota' => request['nota'] ]; return $data; } public function NotasInsert($id, Request $request) { return $request->all(); //notas::create($request->all();); } /** * Display the specified resource. * * @param \App\notas $notas * @return \Illuminate\Http\Response */ public function show($notas) { notas::where('titulo', 'LIKE', '%notas%')->orwhere('nota', 'LIKE', '%notas%') ->get(); } public function notass($notas) { notas::where('titulo', 'LIKE', '%notas%')->orwhere('nota', 'LIKE', '%notas%') ->get(); } /** * Show the form for editing the specified resource. * * @param \App\notas $notas * @return \Illuminate\Http\Response */ public function edit(notas $notas) { // } /** * Update the specified resource in storage. * * @param \Illuminate\Http\Request $request * @param \App\notas $notas * @return \Illuminate\Http\Response */ public function update(Request $request, notas $notas) { // } /** * Remove the specified resource from storage. * * @param \App\notas $notas * @return \Illuminate\Http\Response */ public function destroy(notas $notas) { // } } <file_sep><?php namespace App\Http\Controllers; use Illuminate\Http\Request; class PruebaNotaController extends Controller { // public function traerHolamundo(){ return "hola mundo"; } public function verajax(){ return view('home'); } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Web; /// <summary> /// Descripción breve de DetalleLibroBRL /// </summary> public class DetalleLibroBRL { public DetalleLibroBRL() { // // TODO: Agregar aquí la lógica del constructor // } public static List<Libro> GetLibros(int id) { List<Libro> listaLibros = new List<Libro>(); LibroDSTableAdapters.DetalleLibroTableAdapter adapter = new LibroDSTableAdapters.DetalleLibroTableAdapter(); LibroDS.DetalleLibroDataTable table = adapter.GetLibro(id); foreach (LibroDS.DetalleLibroRow row in table) { listaLibros.Add(rowToDto(row)); } return listaLibros; } private static Libro rowToDto(LibroDS.DetalleLibroRow row) { Libro objLibro = new Libro(); objLibro.id = row.id; objLibro.isbn = row.isbn; objLibro.titulo = row.titulo; objLibro.idAutor = row.idAutor; objLibro.editorial = row.editorial; objLibro.anho = row.anho; objLibro.imagen = row.imagen; return objLibro; } }<file_sep><?php include_once './DAO/DAL/Connection.php'; include_once './DAO/DTO/Juego.php'; include_once './DAO/BLL/JuegoBLL.php'; $juegoBLL = new JuegoBLL(); $id = 0; $objJuego = null; if (isset($_REQUEST["id"])) { $id = $_REQUEST["id"]; $objJuego = $juegoBLL->select($id); } ?> <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Juego</title> <link href="css/bootstrap.min.css" rel="stylesheet" type="text/css"/> <link href="css/bootstrap-theme.min.css" rel="stylesheet" type="text/css"/> <script src="js/bootstrap.min.js" type="text/javascript"></script> </head> <body> <div class="container"> <div class="row"> <div class="col-md-6"> <h2>Datos de Categoria</h2> <form action="abmJuego.php" method="post"> <input type="hidden" value="<?php if ($objJuego != null) { echo "actualizar"; } else { echo "insertar"; } ?>" name="tarea"/> <input type="hidden" value="<?php echo $id; ?>" name="id"/> <div class="form-group"> <label> Nombre: </label> <input class="form-control" type="text" name="nombre" value="<?php if ($objJuego != null) { echo $objJuego->getNombre(); } ?>" required="required" /> </div> <div class="form-group"> <label> Precio: </label> <input class="form-control" type="text" name="precio" value="<?php if ($objJuego != null) { echo $objJuego->getPrecio(); } ?>" required="required" /> </div> <div class="form-group"> <label> Descripcion: </label> <input class="form-control" type="text" name="descripcion" value="<?php if ($objJuego != null) { echo $objJuego->getDescripcion(); } ?>" required="required" /> </div> <div> <input type="submit" value="Guardar Datos"> <a href="AgregarJuego.php" class="btn btn-danger" >Cancelar</a> </div> </form> </div> </div> </div> </body> </html> <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using System.ComponentModel.DataAnnotations; namespace TiendaPeliculas.Models { public class Pelicula { public int ID { get; set; } public string Titulo { get; set; } public string Horario { get; set; } public string Descripcion { get; set; } public int Puntuacion { get; set; } public ICollection<CategoriaxLibro> Categoria { get; set; } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Web; /// <summary> /// Summary description for LibroBLL /// </summary> public class LibroBLL { public LibroBLL() { // // TODO: Add constructor logic here // } public static List<Libro> GetAllLibros() { LibroDSTableAdapters.LibrosTableAdapter adapter = new LibroDSTableAdapters.LibrosTableAdapter(); LibroDS.LibrosDataTable table = adapter.getAllLibros(); List<Libro> libros = new List<Libro>(); foreach (var row in table) { libros.Add(new Libro { libroId = row.autorId, isbn = row.isbn, titulo = row.titulo, editorial = row.editorial, ano = row.ano, autorId = row.autorId }); } return libros; } public static List<Libro> GetAllLibrosByGenero(int generoId) { LibroDSTableAdapters.LibrosTableAdapter adapter = new LibroDSTableAdapters.LibrosTableAdapter(); LibroDS.LibrosDataTable table = adapter.getLibrosByGenero(generoId); List<Libro> libros = new List<Libro>(); foreach (var row in table) { libros.Add(new Libro { libroId = row.libroId, isbn = row.isbn, titulo = row.titulo, editorial = row.editorial, ano = row.ano, autorId = row.autorId }); } return libros; } public static List<Libro> GetAllLibrosByAutor(int autorId) { LibroDSTableAdapters.LibrosTableAdapter adapter = new LibroDSTableAdapters.LibrosTableAdapter(); LibroDS.LibrosDataTable table = adapter.getLibrosByAutor(autorId); List<Libro> libros = new List<Libro>(); foreach (var row in table) { libros.Add(new Libro { libroId = row.libroId, isbn = row.isbn, titulo = row.titulo, editorial = row.editorial, ano = row.ano, autorId = row.autorId }); } return libros; } public static int insertarLibro(string isbn, string titulo, string editorial, string ano, int autorId) { int? libroId = 0; LibroDSTableAdapters.LibrosTableAdapter adapter = new LibroDSTableAdapters.LibrosTableAdapter(); adapter.insertarLibro(isbn, titulo, editorial, ano, autorId, ref libroId); return libroId.Value; } public static void UpdateLibro(int libroId, string isbn, string titulo, string editorial, string ano, int autorId) { LibroDSTableAdapters.LibrosTableAdapter adapter = new LibroDSTableAdapters.LibrosTableAdapter(); adapter.updateLibros(libroId, isbn, titulo, editorial, ano, autorId); } public static Libro getLibroById(int libroId) { LibroDSTableAdapters.LibrosTableAdapter adapter = new LibroDSTableAdapters.LibrosTableAdapter(); LibroDS.LibrosDataTable table = adapter.GetLibroById(libroId); if (table.Rows.Count == 0) { return null; } return rowToDto(table[0]); } private static Libro rowToDto(LibroDS.LibrosRow row) { Libro objRol = new Libro(); objRol.libroId = row.libroId; objRol.isbn = row.isbn; objRol.titulo = row.titulo; objRol.editorial = row.editorial; objRol.ano = row.ano; objRol.autorId = row.autorId; return objRol; } }<file_sep>-- phpMyAdmin SQL Dump -- version 4.6.5.2 -- https://www.phpmyadmin.net/ -- -- Servidor: 127.0.0.1 -- Tiempo de generación: 02-09-2017 a las 15:53:49 -- Versión del servidor: 10.1.21-MariaDB -- Versión de PHP: 5.6.30 SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO"; SET time_zone = "+00:00"; /*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */; /*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */; /*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */; /*!40101 SET NAMES utf8mb4 */; -- -- Base de datos: `proyectovj` -- -- -------------------------------------------------------- -- -- Estructura de tabla para la tabla `tbl_categoria` -- CREATE TABLE `tbl_categoria` ( `id` int(11) NOT NULL, `nombre` varchar(200) COLLATE utf8_unicode_ci NOT NULL, `idCategoriaPadre` int(11) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -- -- Volcado de datos para la tabla `tbl_categoria` -- INSERT INTO `tbl_categoria` (`id`, `nombre`, `idCategoriaPadre`) VALUES (19, 'New on PSVR', 5), (20, 'Popular on PSVR', 5), (21, 'New on PSVR', 5), (22, 'Popular on PSVR', 5), (23, 'Free on PSVR', 5), (24, 'Made for PSVR', 5), (25, 'PSVR Mode Include', 5), (26, 'PSVR experiences', 5), (27, 'PSVR Add', 5), (28, 'PSVR Catalog', 5), (29, 'New on PS4 Games', 6), (30, 'Popular on PS4 ', 6), (31, 'Free on PS4', 6), (32, 'Made for PS4', 6), (33, 'PS4 Mode Include', 6), (34, 'PS4 experiences', 6), (35, 'PS4 Add', 6), (36, 'PS4 Catalog', 6); -- -------------------------------------------------------- -- -- Estructura de tabla para la tabla `tbl_categoriajuego` -- CREATE TABLE `tbl_categoriajuego` ( `id` int(11) NOT NULL, `idJuego` int(11) NOT NULL, `idCategoria` int(11) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -- -- Volcado de datos para la tabla `tbl_categoriajuego` -- INSERT INTO `tbl_categoriajuego` (`id`, `idJuego`, `idCategoria`) VALUES (9, 10, 21), (10, 14, 26), (11, 22, 35), (12, 20, 31), (13, 26, 25), (14, 22, 21), (15, 27, 20), (16, 14, 26), (17, 22, 35), (18, 20, 31), (19, 26, 25), (20, 22, 21), (21, 27, 20); -- -------------------------------------------------------- -- -- Estructura de tabla para la tabla `tbl_categoriapadre` -- CREATE TABLE `tbl_categoriapadre` ( `id` int(11) NOT NULL, `nombre` varchar(200) COLLATE utf8_unicode_ci NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -- -- Volcado de datos para la tabla `tbl_categoriapadre` -- INSERT INTO `tbl_categoriapadre` (`id`, `nombre`) VALUES (5, 'PS VR'), (6, 'PS4'), (7, 'PS3'), (8, 'PS Vita/PS TV/PSP'), (9, 'Discover'), (10, 'Play'), (11, 'Expand'), (12, '$ave'); -- -------------------------------------------------------- -- -- Estructura de tabla para la tabla `tbl_juego` -- CREATE TABLE `tbl_juego` ( `id` int(11) NOT NULL, `nombre` varchar(200) COLLATE utf8_unicode_ci NOT NULL, `precio` int(11) NOT NULL, `descripcion` varchar(800) COLLATE utf8_unicode_ci NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -- -- Volcado de datos para la tabla `tbl_juego` -- INSERT INTO `tbl_juego` (`id`, `nombre`, `precio`, `descripcion`) VALUES (10, 'DiRT 4', 10, 'The world’s leading off-road racing series is back! DiRT 4 puts you at the wheel of the most powerful machines ever made as you face the toughest roads and circuits on the planet in rally, rallycross & landrush.\r\n\r\nRevolutionary \'Your Stage\' technology gives you millions of rally routes at the touch of a button in Australia, Spain, Michigan, Sweden & Wales.\r\n\r\nDrive over 50 of the most iconic rally vehicles ever made from the history of the sport.\r\n\r\nThe official game of the FIA World Rallycross Championship with races in France, Portugal, UK, Sweden & Norway. Race in Supercars, RX2, Super 1600s and Group B rallycross.'), (11, 'Elite Dangerous: Commander Deluxe Edition', 20, 'The Commander Deluxe Edition is the ultimate way for new Commanders to experience what Elite Dangerous has to offer. The bundle includes the base game Elite Dangerous, Elite Dangerous: Horizons Season Pass and the Commander Pack, which grants access to a collection of items with which to customize your ship.\r\n\r\nRemote Play requires PS Vita system and sufficiently robust Wi-Fi connection.\r\n\r\nOnline features require an account and are subject to terms of service and applicable privacy policy (playstationnetwork.com/terms-of-service & playstationnetwork.com/privacy-policy).'), (14, 'GOD WARS Future Past', 25, 'GOD WARS Future Past is a tactical RPG that explores the untold history of Japan through folklore and tactical combat.\r\n\r\nRemote Play requires PS Vita system and sufficiently robust Wi-Fi connection.\r\n\r\n1 player\r\n4GB minimum save size\r\nRemote Play\r\n\r\nSoftware subject to license (us.playstation.com/softwarelicense). Online features require an account and are subject to terms of service and applicable privacy policy (playstationnetwork.com/terms-of-service & playstationnetwork.com/privacy-policy). One-time license fee for play on account’s designated primary PS4™ system and other PS4™ systems when signed in with that account.'), (15, 'Call Of Dutty', 50, 'GOD WARS Future Past is a tactical RPG that explores the untold history of Japan through folklore and tactical combat.\r\n\r\nRemote Play requires PS Vita system and sufficiently robust Wi-Fi connection.\r\n\r\n1 player\r\n4GB minimum save size\r\nRemote Play\r\n\r\nSoftware subject to license (us.playstation.com/softwarelicense). Online features require an account and are subject to terms of service and applicable privacy policy (playstationnetwork.com/terms-of-service & playstationnetwork.com/privacy-policy). One-time license fee for play on account’s designated primary PS4™ system and other PS4™ systems when signed in with that account.'), (16, 'Destiny 2 - Digital Deluxe Edition', 15, 'Pre-Order Destiny 2 and get:\r\n- Coldheart Exotic Rifle*\r\n- Kill-Tracker Ghost\r\n- Salute Emote\r\n\r\nDigital pre-orders also receive a PS4 dynamic system theme after checking out.\r\n\r\nGet the ultimate Destiny 2 experience with the Digital Deluxe Edition. Includes a copy of Destiny 2, premium digital content and the Expansion Pass to continue your Guardian’s legend.\r\n\r\nPremium digital content:\r\n- Legendary Sword\r\n- Legendary Player Emote\r\n- Cabal Empire Themed Emblem'), (17, 'EA SPORTS™ NHL® 18 Young Stars Deluxe Edition', 15, 'Digital Pre-order Details:\r\n\r\nPre-order and receive a bonus after checking out:\r\n\r\n\r\nEA SPORTS™ NHL® 18 THEME\r\n\r\n\r\n\r\n\r\nPre-Order the NHL 18 Young Stars Deluxe Edition now which includes 3 days of early access to the full game plus:'), (18, 'Destiny 2 - Game + Expansion Pass Bundle', 16, 'Pre-Order Destiny 2 and get:\r\n- Coldheart Exotic Rifle*\r\n- Kill-Tracker Ghost\r\n- Salute Emote\r\n\r\nDigital pre-orders also receive a PS4 dynamic system theme after checking out.\r\n\r\nUpgrade your Destiny 2 experience with the Expansion Pass bundle. Includes a copy of Destiny 2, and the Expansion Pass to continue your Guardian’s legend.'), (19, 'The Elder Scrolls® Online: 21000 Crowns', 18, 'Purchase 21000 crowns to be used in The Crown Store. The Crown Store can be accessed in-game to browse and purchase unique pets, mounts, costumes for your character, and other virtual goods and services.\r\n\r\nRemote Play requires PS Vita system and sufficiently robust Wi-Fi connection.'), (20, '12000 Madden NFL 18 Ultimate Team Points', 10, 'Build, play, and win with your ultimate team of todays’ NFL stars and legends in Madden Ultimate Team (MUT) is the complete NFL team-building mode. Play games, collect rewards, and upgrade your team with daily, fun and engaging content updates including legendary NFL players exclusively found in MUT. Start crafting your squad to elite status today with 12000 Ultimate Team Points on the road to building your Ultimate Team dynasty.\r\n\r\nRemote Play requires PS Vita system and sufficiently robust Wi-Fi connection.\r\n\r\nOnline features require an account and are subject to terms of service and applicable privacy policy (playstationnetwork.com/terms-of-service & playstationnetwork.com/privacy-policy)'), (21, 'Money Pack 2330 BaitCoins', 25, 'Experienced and highly skilled anglers as well as persistent learners can succeed in fishing tournaments and get the highest ranks without any financial investment in the game. However, there’s a way to ease your progress - a special in-game currency called Baitcoins! You can use them to get faster access to the most advanced fishing tackle available in the Game Store.\r\n\r\nPACKAGE INCLUDES: 2000 Baitcoins\r\nBONUS: 330 Baitcoins\r\n\r\n'), (22, 'The Elder Scrolls® Online: 14000 Crowns', 19, 'Purchase 14000 crowns to be used in The Crown Store. The Crown Store can be accessed in-game to browse and purchase unique pets, mounts, costumes for your character, and other virtual goods and services.\r\n\r\nRemote Play requires PS Vita system and sufficiently robust Wi-Fi connection.\r\n\r\nOnline features require an account and are subject to terms of service and applicable privacy policy (playstationnetwork.com/terms-of-service & playstationnetwork.com/privacy-policy).\r\n\r\n\r\nNetwork Players 2-99 - Full game requires PlayStation®Plus membership to access online multiplayer\r\nDUALSHOCK®4\r\nRemote Play\r\nOnline Play (Required)'), (23, 'Danganronpa V3: Killing Harmony', 23, 'Digital Pre-order Details:\r\nPre-order and receive a bonus after checking out:\r\n\r\nDANGANRONPA V3 - PS4 THEME\r\n\r\n\r\n\r\n\r\n\r\nPlay on 09/26/2017 11am Eastern Time\r\n\r\nCANCELLATIONS AND REFUNDS ARE NOT AVAILABLE EXCEPT WHERE REQUIRED BY LAW.\r\nWelcome to a new world of Danganronpa, and prepare yourself for the biggest, most exhilarating episode yet. Set in a “psycho-cool” environment, a new cast of 16 characters find themselves kidnapped and imprisoned in a school. Inside, some will kill, some will die, and some will be punished. Reimagine what you thought high-stakes, fast-paced investigation was as you investigate twisted murder cases and condemn your new friends to death.'), (24, 'Secret of Mana', 52, 'Digital Pre-order Details:\r\nPre-order and receive a bonus after checking out:\r\n\r\nSECRET OF MANA – RANDI AVATAR\r\n\r\nSECRET OF MANA – PRIMM AVATAR\r\n\r\nSECRET OF MANA – POPOI AVATAR'), (25, 'Battle Chasers: Nightwar', 32, 'Digital Pre-order Details:\r\nPre-order and receive a bonus after checking out:\r\n\r\nBATTLE CHASERS THEME\r\n\r\n\r\n\r\nPre-order Battle Chasers Nightwar today for 10% off and receive a Free Theme!\r\n\r\nPlay on 10/03/2017 11am Eastern Time\r\n\r\nCANCELLATIONS AND REFUNDS ARE NOT AVAILABLE EXCEPT WHERE REQUIRED BY LAW.\r\nBattle Chasers: Nightwar is an RPG inspired by the console genre-greats, featuring deep dungeon diving, turn-based combat presented in classic JRPG format, and a rich story driven by exploration of the world.'), (26, 'LEGO® NINJAGO® Movie Video Game', 24, 'Digital Pre-order Details:\r\nPre-order and receive a bonus after checking out:\r\n\r\nTHE LEGO NINJAGO MOVIE VIDEOGAME THEME\r\n\r\n\r\n\r\nDon\'t let this one sneak by you, pre-order now!\r\n\r\nPlay on 09/22/2017 12am Eastern Time\r\n\r\nCANCELLATIONS AND REFUNDS ARE NOT AVAILABLE EXCEPT WHERE REQUIRED BY LAW.\r\nFind your inner ninja with the all-new LEGO NINJAGO Movie Video Game! Play as your favorite ninjas, Lloyd, Jay, Kai, Cole, Zane, Nya and <NAME> to defend their home island of Ninjago from the evil Lord Garmadon and his Shark Army. Master the art of Ninjagility by wall-running, high-jumping and battling the foes of Ninjago to rank up and upgrade the ninja\'s combat skills. Only in the LEGO NINJAGO Movie Video Game will you experience the film across 8 action packed locations each with its own unique C'), (27, 'LEGO® NINJAGO® Movie Video Game 2', 24, 'Digital Pre-order Details:\r\nPre-order and receive a bonus after checking out:\r\n\r\nTHE LEGO NINJAGO MOVIE VIDEOGAME THEME\r\n\r\n\r\n\r\nDon\'t let this one sneak by you, pre-order now!\r\n\r\nPlay on 09/22/2017 12am Eastern Time\r\n\r\nCANCELLATIONS AND REFUNDS ARE NOT AVAILABLE EXCEPT WHERE REQUIRED BY LAW.\r\nFind your inner ninja with the all-new LEGO NINJAGO Movie Video Game! Play as your favorite ninjas, Lloyd, Jay, Kai, Cole, Zane, Nya and Master Wu to defend their home island of Ninjago from the evil Lord Garmadon and his Shark Army. Master the art of Ninjagility by wall-running, high-jumping and battling the foes of Ninjago to rank up and upgrade the ninja\'s combat skills. Only in the LEGO NINJAGO Movie Video Game will you experience the film across 8 action packed locations each with its own unique C'); -- -- Índices para tablas volcadas -- -- -- Indices de la tabla `tbl_categoria` -- ALTER TABLE `tbl_categoria` ADD PRIMARY KEY (`id`), ADD KEY `idCategoriaPadre` (`idCategoriaPadre`); -- -- Indices de la tabla `tbl_categoriajuego` -- ALTER TABLE `tbl_categoriajuego` ADD PRIMARY KEY (`id`), ADD KEY `idJuego` (`idJuego`), ADD KEY `idCategoria` (`idCategoria`); -- -- Indices de la tabla `tbl_categoriapadre` -- ALTER TABLE `tbl_categoriapadre` ADD PRIMARY KEY (`id`); -- -- Indices de la tabla `tbl_juego` -- ALTER TABLE `tbl_juego` ADD PRIMARY KEY (`id`); -- -- AUTO_INCREMENT de las tablas volcadas -- -- -- AUTO_INCREMENT de la tabla `tbl_categoria` -- ALTER TABLE `tbl_categoria` MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=37; -- -- AUTO_INCREMENT de la tabla `tbl_categoriajuego` -- ALTER TABLE `tbl_categoriajuego` MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=22; -- -- AUTO_INCREMENT de la tabla `tbl_categoriapadre` -- ALTER TABLE `tbl_categoriapadre` MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=13; -- -- AUTO_INCREMENT de la tabla `tbl_juego` -- ALTER TABLE `tbl_juego` MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=28; -- -- Restricciones para tablas volcadas -- -- -- Filtros para la tabla `tbl_categoria` -- ALTER TABLE `tbl_categoria` ADD CONSTRAINT `tbl_categoria_ibfk_1` FOREIGN KEY (`idCategoriaPadre`) REFERENCES `tbl_categoriapadre` (`id`); -- -- Filtros para la tabla `tbl_categoriajuego` -- ALTER TABLE `tbl_categoriajuego` ADD CONSTRAINT `tbl_categoriajuego_ibfk_1` FOREIGN KEY (`idCategoria`) REFERENCES `tbl_categoria` (`id`), ADD CONSTRAINT `tbl_categoriajuego_ibfk_2` FOREIGN KEY (`idJuego`) REFERENCES `tbl_juego` (`id`); /*!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 include_once './DAO/DAL/Connection.php'; include_once './DAO/DTO/Persona.php'; include_once './DAO/BLL/PersonaBLL.php'; $personaBLL = new PersonaBLL(); function mostrarMensaje($mensaje) { echo "<script type='text/javascript'>alert('$mensaje')</script>"; } if (isset($_REQUEST["tarea"])) { $tarea = $_REQUEST["tarea"]; switch ($tarea) { case "insertar": if (!isset($_REQUEST["nombre"]) || !isset($_REQUEST["apellido"]) || !isset($_REQUEST["ciudad"]) || !isset($_REQUEST["edad"])) { mostrarMensaje('Error al insertar, parámetros incompletos'); } else { $nombre = $_REQUEST["nombre"]; $apellido = $_REQUEST["apellido"]; $ciudad = $_REQUEST["ciudad"]; $edad = $_REQUEST["edad"]; $personaBLL->insert($nombre, $apellido, $ciudad, $edad); } break; case "actualizar": if (!isset($_REQUEST["nombre"]) || !isset($_REQUEST["apellido"]) || !isset($_REQUEST["ciudad"]) || !isset($_REQUEST["edad"]) || !isset($_REQUEST["id"])) { mostrarMensaje('Error al actualizar, parámetros incompletos'); } else { $id = $_REQUEST["id"]; $nombre = $_REQUEST["nombre"]; $apellido = $_REQUEST["apellido"]; $ciudad = $_REQUEST["ciudad"]; $edad = $_REQUEST["edad"]; $personaBLL->update($nombre, $apellido, $ciudad, $edad, $id); } break; case "eliminar": if (!isset($_REQUEST["id"])) { mostrarMensaje('Error al eliminar, parámetros incompletos'); } else { $id = $_REQUEST["id"]; $personaBLL->delete($id); } break; case "fotoperfil": if (!isset($_REQUEST["id"])) { mostrarMensaje('Error al agregar foto de perfil, parámetros incompletos'); } else { $id = $_REQUEST["id"]; $dir_subida = 'img/'; $fichero_subido = $dir_subida . $id . ".jpg"; if (move_uploaded_file($_FILES['archivo']['tmp_name'], $fichero_subido)) { // echo "El fichero es válido y se subió con éxito.\n"; } else { // echo "¡Posible ataque de subida de ficheros!\n"; } } break; } } ?> <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <link href="css/bootstrap.min.css" rel="stylesheet" type="text/css"/> <link href="css/bootstrap-theme.min.css" rel="stylesheet" type="text/css"/> <script src="js/bootstrap.min.js" type="text/javascript"></script> <title></title> </head> <body> <div class="container"> <div class="row"> <div class="col-md-12"> <div class="well" style="margin-top: 10px;"> <a class="btn btn-primary" href="AgregarPersona.php"><i class="glyphicon glyphicon-plus"></i> Agregar persona</a> </div> <?php // $personaBLL->insert("Juan", "Perez", "SCZ", 20); ?> <table class="table"> <thead> <tr> <th></th> <th>ID</th> <th>Nombre</th> <th>Apellido</th> <th>Ciudad</th> <th>Edad</th> </tr> </thead> <tbody> <?php $listaPersonas = $personaBLL->selectAll(); foreach ($listaPersonas as $objPersona) { ?> <tr> <td> <img alt="<?php echo $objPersona->getNombre();?>" class="img-responsive" style="max-width: 100px" src="img/<?php echo $objPersona->getId(); ?>.jpg" /> </td> <td> <?php echo $objPersona->getId(); ?> </td> <td> <?php echo $objPersona->getNombre(); ?> </td> <td> <?php echo $objPersona->getApellido(); ?> </td> <td> <?php echo $objPersona->getCiudad(); ?> </td> <td> <?php echo $objPersona->getEdad(); ?> </td> <td> <a href="FotoDePerfil.php?id=<?php echo $objPersona->getId(); ?>"><i class="glyphicon glyphicon-picture"></i> Subir Foto</a> </td> <td> <a href="AgregarPersona.php?id=<?php echo $objPersona->getId(); ?>"><i class="glyphicon glyphicon-edit"></i> Editar</a> </td> <td> <a href="index.php?tarea=eliminar&id=<?php echo $objPersona->getId(); ?>"><i class="glyphicon glyphicon-trash"></i> Eliminar</a> </td> </tr> <?php } ?> </tbody> </table> </div> </div> </div> </body> </html> <file_sep><?php /* * 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. */ /** * Description of Categoria * * @author COCCO */ class Categoria { private $id; private $nombre; private $categoriaPadre; public function getId() { return $this->id; } public function getNombre() { return $this->nombre; } public function getCategoriaPadre() { return $this->categoriaPadre; } public function setId($id) { $this->id = $id; } public function setNombre($nombre) { $this->nombre = $nombre; } public function setCategoriaPadre($categoriaPadre) { $this->categoriaPadre = $categoriaPadre; } } <file_sep>-- phpMyAdmin SQL Dump -- version 4.7.0 -- https://www.phpmyadmin.net/ -- -- Servidor: 127.0.0.1 -- Tiempo de generación: 02-09-2017 a las 05:41:05 -- Versión del servidor: 5.7.15-log -- Versión de PHP: 7.1.7 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: `dbproyectoweb1` -- CREATE DATABASE IF NOT EXISTS `dbproyectoweb1` DEFAULT CHARACTER SET utf8 COLLATE utf8_general_ci; USE `dbproyectoweb1`; DELIMITER $$ -- -- Procedimientos -- DROP PROCEDURE IF EXISTS `sp_juego_insert`$$ CREATE DEFINER=`root`@`localhost` PROCEDURE `sp_juego_insert` (IN `nombre` VARCHAR(200), IN `precio` DECIMAL(9,2), IN `descripcion` VARCHAR(500), IN `imagen` VARCHAR(200)) NO SQL INSERT INTO Juego(nombre,precio,descripcion,imagen) VALUES (p_nombre, p_precio, p_descripcion, p_imagen)$$ DROP PROCEDURE IF EXISTS `sp_juego_selectall`$$ CREATE DEFINER=`root`@`localhost` PROCEDURE `sp_juego_selectall` () NO SQL SELECT idJuego, nombre, precio, descripcion, imagen FROM juego$$ DELIMITER ; -- -------------------------------------------------------- -- -- Estructura de tabla para la tabla `categoria` -- DROP TABLE IF EXISTS `categoria`; CREATE TABLE `categoria` ( `idCategoria` int(11) NOT NULL, `nombre` varchar(200) NOT NULL, `idCategoriaPadre` int(11) DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8; -- -- Volcado de datos para la tabla `categoria` -- INSERT INTO `categoria` (`idCategoria`, `nombre`, `idCategoriaPadre`) VALUES (1, 'PS4', NULL), (2, 'PS3', NULL), (3, 'PS Vita/PSP', NULL), (4, 'otros', NULL), (5, 'Full Games', 1), (6, 'Digitales', 1), (7, 'Exclusividades', 1), (8, 'Free-to-Play', 1), (9, 'Juegos Indie', 1), (10, 'Cross-Platform', 1), (11, 'Full Games', 2), (12, 'Digitales', 2), (13, 'Exclusividades', 2), (14, 'Free-to-Play', 2), (15, 'Juegos Indie', 2), (16, 'Cross-Platform', 2), (17, 'Juegos de PS Vita', 3), (18, 'Juegos de PSP', 3), (19, 'Juegos otros', 4); -- -------------------------------------------------------- -- -- Estructura de tabla para la tabla `categoria_juego` -- DROP TABLE IF EXISTS `categoria_juego`; CREATE TABLE `categoria_juego` ( `idCategoriaJuego` int(11) NOT NULL, `idCategoria` int(11) NOT NULL, `idJuego` int(11) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8; -- -- Volcado de datos para la tabla `categoria_juego` -- INSERT INTO `categoria_juego` (`idCategoriaJuego`, `idCategoria`, `idJuego`) VALUES (1, 1, 4), (2, 1, 4), (3, 2, 6), (4, 3, 7); -- -------------------------------------------------------- -- -- Estructura de tabla para la tabla `juego` -- DROP TABLE IF EXISTS `juego`; CREATE TABLE `juego` ( `idJuego` int(11) NOT NULL, `nombre` varchar(200) NOT NULL, `precio` decimal(5,2) NOT NULL, `descripcion` varchar(250) NOT NULL, `imagen` varchar(200) DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8; -- -- Volcado de datos para la tabla `juego` -- INSERT INTO `juego` (`idJuego`, `nombre`, `precio`, `descripcion`, `imagen`) VALUES (4, 'Days Gone', '71.00', 'El software está sujeto a licencia y garantía limitada (us.playstation.com/softwarelicense/sp). Las funciones en línea requieren una cuenta y están sujetas a los términos de servicio y a la.', 'img/frantics.png'), (5, 'Detroid: Become Human', '69.20', 'DETROIT PRE-ORDER DYNAMIC THEME', 'img/frantics.png'), (6, 'Pro Evolution Soccer 2018', '35.90', 'Donde se forjan las leyendas\': PES vuelve con nuevas funciones, modos y una gran experiencia de juego.', 'img/frantics.png'), (7, 'Still Time', '22.99', 'Still Time es un juego de rompecabezas y plataformas en 2D sobre los viajes en el tiempo y la física temporal.', 'img/frantics.png'); -- -- Índices para tablas volcadas -- -- -- Indices de la tabla `categoria` -- ALTER TABLE `categoria` ADD PRIMARY KEY (`idCategoria`), ADD KEY `FKidCategoriaPadre_idx` (`idCategoriaPadre`); -- -- Indices de la tabla `categoria_juego` -- ALTER TABLE `categoria_juego` ADD PRIMARY KEY (`idCategoriaJuego`), ADD KEY `idCategoria_idx` (`idCategoria`), ADD KEY `idJuego_idx` (`idJuego`); -- -- Indices de la tabla `juego` -- ALTER TABLE `juego` ADD PRIMARY KEY (`idJuego`); -- -- AUTO_INCREMENT de las tablas volcadas -- -- -- AUTO_INCREMENT de la tabla `categoria` -- ALTER TABLE `categoria` MODIFY `idCategoria` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=20; -- -- AUTO_INCREMENT de la tabla `categoria_juego` -- ALTER TABLE `categoria_juego` MODIFY `idCategoriaJuego` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=5; -- -- AUTO_INCREMENT de la tabla `juego` -- ALTER TABLE `juego` MODIFY `idJuego` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=8; -- -- Restricciones para tablas volcadas -- -- -- Filtros para la tabla `categoria` -- ALTER TABLE `categoria` ADD CONSTRAINT `FKidCategoriaPadre` FOREIGN KEY (`idCategoriaPadre`) REFERENCES `categoria` (`idCategoria`) ON DELETE NO ACTION ON UPDATE NO ACTION; -- -- Filtros para la tabla `categoria_juego` -- ALTER TABLE `categoria_juego` ADD CONSTRAINT `idCategoria` FOREIGN KEY (`idCategoria`) REFERENCES `categoria` (`idCategoria`) ON DELETE NO ACTION ON UPDATE NO ACTION, ADD CONSTRAINT `idJuego` FOREIGN KEY (`idJuego`) REFERENCES `juego` (`idJuego`) ON DELETE NO ACTION ON UPDATE NO ACTION; 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>using System; using System.Collections.Generic; using System.Linq; using System.Web; /// <summary> /// Descripción breve de LibroGeneroBLL /// </summary> public class LibroGeneroBLL { public LibroGeneroBLL() {} public static void insert(LibroGenero objLibGen) { LibroGeneroDSTableAdapters.tblLibroGeneroTableAdapter adapter = new LibroGeneroDSTableAdapters.tblLibroGeneroTableAdapter(); adapter.Insert(objLibGen.Libro_id, objLibGen.Genero_id); } public static void update(LibroGenero objLibGen) { LibroGeneroDSTableAdapters.tblLibroGeneroTableAdapter adapter = new LibroGeneroDSTableAdapters.tblLibroGeneroTableAdapter(); adapter.Update(objLibGen.Libro_id, objLibGen.Genero_id, objLibGen.Codigo_id); } }<file_sep><?php /** * Description of CategoriaJuegoBLL * * @author ANDREA_ORTIZ */ class CategoriaJuegoBLL { public function insert($idJuego, $idCategoria) { $objConexion = new Connection(); $objConexion->queryWithParams("INSERT INTO tbl_categoriajuego(idJuego,idCategoria) VALUES (:pIdJuego, :pIdCategoria)", array( ":pIdJuego" => $idJuego, ":pIdCategoria" => $idCategoria )); } public function update($idJuego, $idCategoria, $id) { $objConexion = new Connection(); $objConexion->queryWithParams("UPDATE tbl_categoriajuego SET idJuego = :pIdJuego, idCategoria = :pIdCategoria WHERE id = :pId", array( ":pIdJuego" => $idJuego, ":pIdCategoria" => $idCategoria, ":pId" => $id )); } public function delete($id) { $objConexion = new Connection(); $objConexion->queryWithParams(" DELETE From tbl_categoriajuego WHERE id = :pId", array( ":pId" => $id )); } public function selectAll() { $listaCategoriaJuegos = array(); $objConexion = new Connection(); $res = $objConexion->query(" SELECT id,idJuego,idCategoria FROM tbl_categoriajuego"); while ($row = $res->fetch(PDO::FETCH_ASSOC)) { $objCategoriaJuego = $this->rowToDto($row); $listaCategoriaJuegos[] = $objCategoriaJuego; } return $listaCategoriaJuegos; } public function select($id) { $objConexion = new Connection(); $res = $objConexion->queryWithParams(" SELECT id,idJuego,idCategoria FROM tbl_categoriajuego WHERE id = :pId", array( ":pId" => $id )); if ($res->rowCount() == 0) { return null; } $row = $res->fetch(PDO::FETCH_ASSOC); return $this->rowToDto($row); } function rowToDto($row) { $objCategoriaJuego = new CategoriaJuego(); $objCategoriaJuego->setId($row["id"]); $objCategoriaJuego->setIdJuego($row["idJuego"]); $objCategoriaJuego->setIdCategoria($row["idCategoria"]); return $objCategoriaJuego; } } <file_sep> <?php include_once './DAO/DAL/Connection.php'; include_once './DAO/DTO/accat.php'; include_once './DAO/BLL/accatBLL.php'; ?> <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta name="description" content=""> <meta name="author" content=""> <title>Home</title> <!-- core CSS --> <link href="css/bootstrap.min.css" rel="stylesheet"> <link href="css/font-awesome.min.css" rel="stylesheet"> <link href="css/animate.min.css" rel="stylesheet"> <link href="css/prettyPhoto.css" rel="stylesheet"> <link href="css/main.css" rel="stylesheet"> <link href="css/responsive.css" rel="stylesheet"> <!--[if lt IE 9]> <script src="js/html5shiv.js"></script> <script src="js/respond.min.js"></script> <![endif]--> <link rel="shortcut icon" href="images/ico/favicon.ico"> <link rel="apple-touch-icon-precomposed" sizes="144x144" href="images/ico/apple-touch-icon-144-precomposed.png"> <link rel="apple-touch-icon-precomposed" sizes="114x114" href="images/ico/apple-touch-icon-114-precomposed.png"> <link rel="apple-touch-icon-precomposed" sizes="72x72" href="images/ico/apple-touch-icon-72-precomposed.png"> <link rel="apple-touch-icon-precomposed" href="images/ico/apple-touch-icon-57-precomposed.png"> <link rel="stylesheet" href="https://cdn.datatables.net/1.10.15/css/dataTables.bootstrap.min.css"> <?php $catGlobalBLL = new accatBLL(); if (isset($_REQUEST['editar'])) { $accatNomb = $_REQUEST['accatNomb']; $accatCcat = $_REQUEST['accatCcat']; $padre = $_REQUEST['padre']; if ($padre == 1) { $catGlobalBLL->update($accatCcat, $accatNomb, 0); } else { $accatCpad = $_REQUEST['accatCpad']; $catGlobalBLL->update($accatCcat, $accatNomb, $accatCpad); } } else if (isset($_REQUEST['nuevo'])) { $accatNomb = $_REQUEST['accatNomb']; $accatCpad = $_REQUEST['accatCpad']; $padre = $_REQUEST['padre']; if ($padre == 1) { $catGlobalBLL->insert($accatNomb, 0); } else { $accatCpad = $_REQUEST['accatCpad']; $catGlobalBLL->insert($accatNomb, $accatCpad); } } else if (isset($_REQUEST['eliminar'])) { $accatCcatedit = $_REQUEST['accatCcat']; $catGlobalresult = $catGlobalBLL->delete($accatCcatedit); } else { echo "error"; } ?> </head> <body class="homepage"> <header id="header"> <div class="top-bar"> <div class="container"> <div class="row"> <div class="col-sm-6 col-xs-4"> <a class="navbar-brand" href="index.php"><img style="max-width: 100%; height: 50px;" src="images/svgLogo.png" alt="logo"></a> </div> <div class="col-sm-6 col-xs-8"> <div class="social"> <ul class="social-share"> <li><a href="#"><i class="fa fa-desktop" title="ADMIN"></i></a></li> </ul> <div class="search"> <form role="form"> <input type="text" class="search-form" autocomplete="off" placeholder="Search"> <i class="fa fa-search"></i> </form> </div> </div> </div> </div> </div><!--/.container--> </div><!--/.top-bar--> </header><!--/header--> <section id="feature"> <div class="container"> <div class="row"> <div class="col-md-12 col-sm-12"> <div class="container"> <div class="row" style="height: 610px;" > <div style="padding-top: 20px"> <div class="col-md-12"> <a href="addcategorias.php?nuevo=nuevo" type="button" name="nuevo" id="nuevo" class="btn btn-primary btn-lg">Nueva Categoria</a> <table id="idcat" class="table table-bordered table-striped"> <thead> <tr> <th>ID</th> <th>NOMBRE</th> <th>CATEGORIA PADRE</th> <th></th> <th></th> </tr> </thead> <tbody> <?php $accatBLLTable = new accatBLL(); $ListaAccat = $accatBLLTable->selectAll(); ?> <?php foreach ($ListaAccat as $value) { ?> <tr> <td> <?php echo $value->getAccatCcat(); ?></td> <td> <?php echo $value->getAccatNomb(); ?></td> <td> <?php if ($value->getAccatCpad() == 0) { ?> <span class="label label-danger">Es padre</span> <?php } else { $SelectAccatPad = $accatBLLTable->selectaccatPadre($value->getAccatCpad()); ?> <span class="label label-success"><?php echo $SelectAccatPad->getAccatNomb(); ?></span> <?php } ?> </td> <th> <a href="addcategorias.php?accatCcat=<?php echo $value->getAccatCcat(); ?>&editar=editar" type="button" name="editar" id="" class="btn btn-warning btn-sm">Editar</a></th> <th> <a <a href="categorias.php?accatCcat=<?php echo $value->getAccatCcat(); ?>&eliminar=eliminar" type="button" name="eliminar" id="" class="btn btn-danger btn-sm">Eliminar</a></th> </tr> <?php } ?> </tbody> </table> </div> </div> </div></div> </div><!--/.col-md-3--> </div> </div> </section><!--/#bottom--> <footer id="footer" class="midnight-blue"> <div class="container"> <div class="row"> <div class="col-sm-6"> &copy; 2017 <a target="_blank" href="http://www.facebook.com/" title="Free Miguel Angel">Miguel Angel</a>. All Rights Reserved. </div> <div class="col-sm-6"> <ul class="pull-right"> <li><a href="#">Home</a></li> <li><a href="#">About Us</a></li> <li><a href="#">Faq</a></li> <li><a href="#">Contact Us</a></li> </ul> </div> </div> </div> </footer><!--/#footer--> <script src="js/jquery.js"></script> <script src="js/bootstrap.min.js"></script> <script src="js/jquery.prettyPhoto.js"></script> <script src="js/jquery.isotope.min.js"></script> <script src="js/main.js"></script> <script src="js/wow.min.js"></script> <script src="https://cdn.datatables.net/1.10.15/js/jquery.dataTables.min.js"></script> <script src="https://cdn.datatables.net/1.10.15/js/dataTables.bootstrap.min.js"></script> </body> </html> <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; public partial class EditarGenero : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { if (IsPostBack) return; String id = Request.QueryString["idGenero"]; if (id != null) { // ; Genero genero = GeneroBll.SelectById(id); txtNombre.Value = genero.Nombre; idH3.InnerText = "Id Genero: " + id; } } protected void btnEditar_Click(object sender, EventArgs e) { } protected void btnAceptar_Click(object sender, EventArgs e) { String id = Request.QueryString["idGenero"]; if (id != null) { String texto = txtNombre.Value; GeneroBll.Editar(id, texto); Response.Redirect("genero.aspx"); } else { String texto = txtNombre.Value; GeneroBll.Crear(texto); Response.Redirect("genero.aspx"); } // Editar Autor //AutorBll.EditarAutor() } }<file_sep> <?php include_once './DAO/DAL/Connection.php'; include_once './DAO/DTO/accat.php'; include_once './DAO/BLL/accatBLL.php'; ?> <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta name="description" content=""> <meta name="author" content=""> <title>Nueva Categorias</title> <!-- core CSS --> <link href="css/bootstrap.min.css" rel="stylesheet"> <link href="css/font-awesome.min.css" rel="stylesheet"> <link href="css/animate.min.css" rel="stylesheet"> <link href="css/prettyPhoto.css" rel="stylesheet"> <link href="css/main.css" rel="stylesheet"> <link href="css/responsive.css" rel="stylesheet"> <!--[if lt IE 9]> <script src="js/html5shiv.js"></script> <script src="js/respond.min.js"></script> <![endif]--> <link rel="shortcut icon" href="images/ico/favicon.ico"> <link rel="apple-touch-icon-precomposed" sizes="144x144" href="images/ico/apple-touch-icon-144-precomposed.png"> <link rel="apple-touch-icon-precomposed" sizes="114x114" href="images/ico/apple-touch-icon-114-precomposed.png"> <link rel="apple-touch-icon-precomposed" sizes="72x72" href="images/ico/apple-touch-icon-72-precomposed.png"> <link rel="apple-touch-icon-precomposed" href="images/ico/apple-touch-icon-57-precomposed.png"> <link rel="stylesheet" href="https://cdn.datatables.net/1.10.15/css/dataTables.bootstrap.min.css"> </head> <body class="homepage"> <header id="header"> <div class="top-bar"> <div class="container"> <div class="row"> <div class="col-sm-6 col-xs-4"> <a class="navbar-brand" href="index.php"><img style="max-width: 100%; height: 50px;" src="images/svgLogo.png" alt="logo"></a> </div> <div class="col-sm-6 col-xs-8"> <div class="social"> <ul class="social-share"> <li><a href="#"><i class="fa fa-desktop" title="ADMIN"></i></a></li> </ul> <div class="search"> <form role="form"> <input type="text" class="search-form" autocomplete="off" placeholder="Search"> <i class="fa fa-search"></i> </form> </div> </div> </div> </div> </div><!--/.container--> </div><!--/.top-bar--> </header><!--/header--> <section id="feature"> <div class="container"> <div class="row"> <div class="col-md-12 col-sm-12"> <div class="container"> <div class="row" style="height: 610px;" > <div style="padding-top: 20px"> <div class="col-md-12"> <form class="form-horizontal" method="POST" action="categorias.php" role="form" > <?php $catGlobalBLL = new accatBLL(); if (isset($_REQUEST["editar"])) { $global = $_REQUEST["editar"]; ?> <input type="hidden" name="<?php echo $global ?>" value="<?php echo $global ?>"> <?php } else if (isset($_REQUEST["nuevo"])) { $global = $_REQUEST["nuevo"]; ?> <input type="hidden" name="<?php echo $global ?>" value="<?php echo $global ?>"> <?php } else { echo "error"; } ?> <?php if (isset($_REQUEST['editar'])) { $catGlobalBLL = new accatBLL(); $idacjuetEdit = $_REQUEST["accatCcat"]; $objacjue = $catGlobalBLL->select($idacjuetEdit); ?> <div class="form-group"> <label for="accatCcat" class="col-lg-2 control-label">ID</label> <div class="col-lg-10"> <input type="text" class="form-control" name="accatCcat" value="<?php echo $_REQUEST["accatCcat"]; ?>" placeholder="ID" readonly="true"> </div> </div> <div class="form-group"> <label for="accatNomb" class="col-lg-2 control-label">NOMBRE</label> <div class="col-lg-10"> <input type="text" class="form-control"value="<?php echo $objacjue->getAccatNomb() ?>" name="accatNomb" placeholder="Nombre de la categoria"> </div> </div> <div class="form-group" id="categoriapadre"> <label for="accatCpad" class="col-lg-2 control-label">CATEGORIA PADRE</label> <div class="col-lg-10"> <select class="form-control" id="accatCpad" name="accatCpad" > <?php $categoriasBLL = new accatBLL(); $categoriasPadres = $categoriasBLL->selectAccatPad(); ?> <?php foreach ($categoriasPadres as $value) { ?> <option value="<?php echo $value->getAccatCcat(); ?>"><?php echo $value->getAccatNomb(); ?></option> <?php } ?> </select> </div> </div> <div class="form-group"> <label for="accatCpad" class="col-lg-2 control-label">CATEGORIA ES PADRE?</label> <div class="col-lg-10"> <label class="radio-inline"><input class="des" type="radio" name="padre" id="padre" checked value="1">Si</label> <label class="radio-inline"><input class="des" type="radio" name="padre" id="padre" value="0">No</label> </div> </div> <?php } else if (isset($_REQUEST['nuevo'])) { $global = $_REQUEST['nuevo']; ?> <div class="form-group"> <label for="accatCcat" class="col-lg-2 control-label">ID</label> <div class="col-lg-10"> <input type="text" class="form-control" id="accatCcat" value="0" placeholder="ID" readonly="true"> </div> </div> <div class="form-group"> <label for="accatNomb" class="col-lg-2 control-label">NOMBRE</label> <div class="col-lg-10"> <input type="text" class="form-control" id="accatNomb" name="accatNomb" placeholder="Contraseña"> </div> </div> <div class="form-group" id="categoriapadre"> <label for="accatCpad" class="col-lg-2 control-label">CATEGORIA PADRE</label> <div class="col-lg-10"> <select class="form-control" id="accatCpad" name="accatCpad" > <?php $categoriasBLL = new accatBLL(); $categoriasPadres = $categoriasBLL->selectAccatPad(); ?> <?php foreach ($categoriasPadres as $value) { ?> <option value="<?php echo $value->getAccatCcat(); ?>"><?php echo $value->getAccatNomb(); ?></option> <?php } ?> </select> </div> </div> <div class="form-group"> <label for="accatCpad" class="col-lg-2 control-label">CATEGORIA ES PADRE?</label> <div class="col-lg-10"> <label class="radio-inline"><input class="des" type="radio" name="padre" checked value="1">Si</label> <label class="radio-inline"><input class="des" type="radio" name="padre" value="0">No</label> </div> </div> <?php } else { echo "error"; } ?> </div> <div class="form-group"> <div class="col-lg-offset-2 col-lg-10"> <button type="submit" class="btn btn-default">Registrar</button> </div> </div> </form> </div> </div> </div></div> </div><!--/.col-md-3--> </div> </div> </section><!--/#bottom--> <footer id="footer" class="midnight-blue"> <div class="container"> <div class="row"> <div class="col-sm-6"> &copy; 2017 <a target="_blank" href="http://www.facebook.com/" title="Free Miguel Angel">M<NAME></a>. All Rights Reserved. </div> <div class="col-sm-6"> <ul class="pull-right"> <img > <li><a href="#">Home</a></li> <li><a href="#">About Us</a></li> <li><a href="#">Faq</a></li> <li><a href="#">Contact Us</a></li> </ul> </div> </div> </div> </footer><!--/#footer--> <script src="js/jquery.js"></script> <script src="js/bootstrap.min.js"></script> <script src="js/jquery.prettyPhoto.js"></script> <script src="js/jquery.isotope.min.js"></script> <script src="js/main.js"></script> <script src="js/wow.min.js"></script> <script src="js/addventares.js"></script> <script src="https://cdn.datatables.net/1.10.15/js/jquery.dataTables.min.js"></script> <script src="https://cdn.datatables.net/1.10.15/js/dataTables.bootstrap.min.js"></script> </body> </html> <file_sep><?php /* * 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. */ /** * Description of acjue * * @author Miguel */ class acjue { private $acjueJjue; private $acjuePrec; private $acjueNomb; private $acjueDesc; function getAcjueJjue() { return $this->acjueJjue; } function getAcjuePrec() { return $this->acjuePrec; } function getAcjueNomb() { return $this->acjueNomb; } function getAcjueDesc() { return $this->acjueDesc; } function setAcjueJjue($acjueJjue) { $this->acjueJjue = $acjueJjue; } function setAcjuePrec($acjuePrec) { $this->acjuePrec = $acjuePrec; } function setAcjueNomb($acjueNomb) { $this->acjueNomb = $acjueNomb; } function setAcjueDesc($acjueDesc) { $this->acjueDesc = $acjueDesc; } } <file_sep><?php /* * 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. */ /** * Description of Juego * * @author rodriguezja */ class Juego { private $idJuego; private $nombre; private $precio; private $descripcion; private $imagen; // function __construct($idJuego, $nombre, $precio, $descripcion) { // $this->idJuego = $idJuego; // $this->nombre = $nombre; // $this->precio = $precio; // $this->descripcion = $descripcion; // } function __construct() { } function getImagen() { return $this->imagen; } function setImagen($imagen) { $this->imagen = $imagen; } function getIdJuego() { return $this->idJuego; } function getNombre() { return $this->nombre; } function getPrecio() { return $this->precio; } function getDescripcion() { return $this->descripcion; } function setIdJuego($idJuego) { $this->idJuego = $idJuego; } function setNombre($nombre) { $this->nombre = $nombre; } function setPrecio($precio) { $this->precio = $precio; } function setDescripcion($descripcion) { $this->descripcion = $descripcion; } } <file_sep><?php include_once '../../DAO/DAL/Connection.php'; ?> <?php $checked = $_REQUEST["checked"]; if ($checked == 1) { $accxjCcat = $_REQUEST["accxjCcat"]; $accxjCjue = $_REQUEST["accxjCjue"]; $cas = new Inserts(); $cas->insert($accxjCjue, $accxjCcat); } else { $accxjCcat = $_REQUEST["accxjCcat"]; $accxjCjue = $_REQUEST["accxjCjue"]; $cas = new Inserts(); $cas->delete($accxjCjue, $accxjCcat); } ?> <?php class Inserts { public function insert($accxjCjue, $accxjCcat) { $objConexion = new Connection(); $objConexion->queryWithParams("INSERT INTO accxj(accxjCjue,accxjCcat) VALUES (:accxjCjue,:accxjCcat)", array( ":accxjCjue" => $accxjCjue, ":accxjCcat" => $accxjCcat )); } public function delete($accxjCjue, $accxjCcat) { $objConexion = new Connection(); $objConexion->queryWithParams(" DELETE FROM accxj WHERE accxjCjue = :accxjCjue and accxjCcat = :accxjCcat", array( ":accxjCjue" => $accxjCjue, ":accxjCcat" => $accxjCcat )); } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Web; /// <summary> /// Descripción breve de LibroBLL /// </summary> public class LibroBLL { public LibroBLL() { // // TODO: Agregar aquí la lógica del constructor // } public static List<Libro>lectAll() { List<Libro> listaRoles = new List<Libro>(); LibroDSTableAdapters.LibroTableAdapter adapter = new LibroDSTableAdapters.LibroTableAdapter (); LibroDS.LibroDataTable table = adapter.SelectAll(); foreach (LibroDS.LibroRow row in table) { listaRoles.Add(rowToDto(row)); } return listaRoles; } public static List<Libro> SelectAll_IdAutor(int idAutor) { List<Libro> listaRoles = new List<Libro>(); LibroDSTableAdapters.LibroTableAdapter adapter = new LibroDSTableAdapters.LibroTableAdapter(); LibroDS.LibroDataTable table = adapter.SelectAll_IdAutor(idAutor); foreach (LibroDS.LibroRow row in table) { listaRoles.Add(rowToDto(row)); } return listaRoles; } public static List<Libro> SelectAll_IdGenero(int idGenero) { List<Libro> listaRoles = new List<Libro>(); LibroDSTableAdapters.LibroTableAdapter adapter = new LibroDSTableAdapters.LibroTableAdapter(); LibroDS.LibroDataTable table = adapter.SelectAll_IdGenero(idGenero); foreach (LibroDS.LibroRow row in table) { listaRoles.Add(rowToDto(row)); } return listaRoles; } public static List<Libro> SelectById(int id) { List<Libro> listaRoles = new List<Libro>(); LibroDSTableAdapters.LibroTableAdapter adapter = new LibroDSTableAdapters.LibroTableAdapter (); LibroDS.LibroDataTable table = adapter.SelectById(id); foreach (LibroDS.LibroRow row in table) { listaRoles.Add(rowToDto(row)); } return listaRoles; } public static Libro SelectByIdS(int id) { Libro listaRoles = new Libro(); LibroDSTableAdapters.LibroTableAdapter adapter = new LibroDSTableAdapters.LibroTableAdapter(); LibroDS.LibroDataTable table = adapter.SelectById(id); if (table.Rows.Count == 0) { return null; }else { foreach (LibroDS.LibroRow row in table) { listaRoles = rowToDto(row); } return listaRoles; } } public static void insert(string ISBN, string titulo, int idAutor, string Editorial, int Anho, string imagen) { LibroDSTableAdapters.LibroTableAdapter adapter = new LibroDSTableAdapters.LibroTableAdapter (); adapter.Insert( ISBN, titulo, idAutor, Editorial, Anho, imagen); } public static void update(string ISBN, string titulo, int idAutor, string Editorial, int Anho, string imagen, int Original_idLibro) { LibroDSTableAdapters.LibroTableAdapter adapter = new LibroDSTableAdapters.LibroTableAdapter (); adapter.Update( ISBN, titulo, idAutor, Editorial, Anho, imagen, Original_idLibro); } public static void delete(int id) { LibroDSTableAdapters.LibroTableAdapter adapter = new LibroDSTableAdapters.LibroTableAdapter (); adapter.Delete(id); } private static Libro rowToDto(LibroDS.LibroRow row) { Libro objLibro = new Libro(); objLibro.idLibro = row.idLibro; objLibro.ISBN = row.ISBN; objLibro.Titulo = row.titulo; objLibro.idAutor = row.idAutor; objLibro.Editorial = row.Editorial; objLibro.Anho = row.Anho; objLibro.imagen = row.imagen; return objLibro; } }<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; public partial class VistaLibros : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { string id = Request.QueryString["generoID"]; if (id != null) { List<Libro> libros = new List<Libro>(); libros = LibroBLL.GetAllLibrosByGenero(Convert.ToInt32(id)); //grvLibros.DataSource = libros; rptLibros.DataSource = libros; //grvLibros.DataBind(); rptLibros.DataBind(); } else { id = Request.QueryString["autorID"]; if (id != null) { List<Libro> libros = new List<Libro>(); libros = LibroBLL.GetAllLibrosByAutor(Convert.ToInt32(id)); //grvLibros.DataSource = libros; rptLibros.DataSource = libros; //grvLibros.DataBind(); rptLibros.DataBind(); } } } } }<file_sep><?php include_once './DAO/DAL/Connection.php'; include_once './DAO/DTO/CategoriaJuego.php'; include_once './DAO/BLL/CategoriaJuegoBLL.php'; $categoriaJuegoBLL = new CategoriaJuegoBLL(); if (isset($_REQUEST["tarea"])) { $tarea = $_REQUEST["tarea"]; switch ($tarea) { case "insertar": if (!isset($_REQUEST["idJuego"]) || !isset($_REQUEST["idCategoria"])) { mostrarMensaje('Error al insertar, parametros incompletos'); } else { $idJuego = $_REQUEST["idJuego"]; $idCategoria = $_REQUEST["idCategoria"]; $categoriaJuegoBLL->insert($idJuego, $idCategoria); } break; case "actualizar": if (!isset($_REQUEST["idJuego"]) || !isset($_REQUEST["idCategoria"]) || !isset($_REQUEST["id"])) { mostrarMensaje('Error al actualizar, parametros incompletos'); } else { $id = $_REQUEST["id"]; $idJuego = $_REQUEST["idJuego"]; $idCategoria = $_REQUEST["idCategoria"]; $categoriaJuegoBLL->update($idJuego, $idCategoria, $id); } break; case "eliminar": if (!isset($_REQUEST["id"])) { mostrarMensaje('Error al actualizar, parametros incompletos'); } else { $id = $_REQUEST["id"]; $categoriaJuegoBLL->delete($id); } break; } } ?> <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Categoria - Juego</title> <link href="css/bootstrap.min.css" rel="stylesheet" type="text/css"/> <link href="css/bootstrap-theme.min.css" rel="stylesheet" type="text/css"/> <script src="js/bootstrap.min.js" type="text/javascript"></script> </head> <body> <div class="container"> <div class="row"> <div class="col-md-12"> <div > <a class="btn btn-primary" href="AgregarCategoriaJuego.php">Agregar Juegos a la categoria</a> </div> <table class="table"> <thead> <tr> <th>ID</th> <th>Juego</th> <th>Categoria</th> </tr> </thead> <tbody> <?php $listaCategoriasJuegos = $categoriaJuegoBLL->selectAll(); foreach ($listaCategoriasJuegos as $objCategoriaJuego) { ?> <tr> <td> <?php echo $objCategoriaJuego->getId(); ?> </td> <td> <?php echo $objCategoriaJuego->getIdJuego(); ?> </td> <td> <?php echo $objCategoriaJuego->getIdCategoria(); ?> </td> <td> <a href="AgregarCategoriaJuego.php?id=<?php echo $objCategoriaJuego->getId(); ?>">Editar</a> </td> <td> <a href="abmCategoriaJuego.php?tarea=eliminar&id=<?php echo $objCategoriaJuego->getId(); ?>">Eliminar</a> </td> </tr> <?php } ?> </tbody> </table> </div> </div> </div> <br> <br> <br> <a href="index.php"><i class="glyphicon glyphicon-arrow-left"></i>Volver a la Pagina Editable</a> <br/> <a href="PaginaPrincipal.php">Pagina Principal</a> </body> </html> <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Web; /// <summary> /// Descripción breve de LibroBLL /// </summary> public class LibroBLL { public LibroBLL() { } public static List<Libro> SelectAll() { List<Libro> listaLibros = new List<Libro>(); LibroDSTableAdapters.sp_Libro_SelectAllTableAdapter adapter = new LibroDSTableAdapters.sp_Libro_SelectAllTableAdapter(); LibroDS.sp_Libro_SelectAllDataTable table = adapter.SelectAll(); foreach (LibroDS.sp_Libro_SelectAllRow row in table) { listaLibros.Add(rowToDto(row)); } return listaLibros; } public static Libro SelectById(int id) { LibroDSTableAdapters.sp_Libro_SelectAllTableAdapter adapter = new LibroDSTableAdapters.sp_Libro_SelectAllTableAdapter(); LibroDS.sp_Libro_SelectAllDataTable table = adapter.SelectById(id); if (table.Rows.Count == 0) { return null; } return rowToDto(table[0]); } public static Libro SelectByIsbn(string isbn) { LibroDSTableAdapters.sp_Libro_SelectAllTableAdapter adapter = new LibroDSTableAdapters.sp_Libro_SelectAllTableAdapter(); LibroDS.sp_Libro_SelectAllDataTable table = adapter.SelectByIsbn(isbn); if (table.Rows.Count == 0) { return null; } return rowToDto(table[0]); } public static void Insert(string isbn, string titulo, string editorial, int anho ,string nombreAutor, string nombreGenero) { LibroDSTableAdapters.sp_Libro_SelectAllTableAdapter adapter = new LibroDSTableAdapters.sp_Libro_SelectAllTableAdapter(); adapter.Insert(isbn, titulo, editorial, anho,nombreAutor,nombreGenero); } public static void Update(string isbn, string titulo, string editorial, int anho, string nombreAutor, string nombreGenero , int id) { LibroDSTableAdapters.sp_Libro_SelectAllTableAdapter adapter = new LibroDSTableAdapters.sp_Libro_SelectAllTableAdapter(); adapter.Update(isbn, titulo, editorial, anho, nombreAutor, nombreGenero, id); } public static void Delete(int id) { LibroDSTableAdapters.sp_Libro_SelectAllTableAdapter adapter = new LibroDSTableAdapters.sp_Libro_SelectAllTableAdapter(); adapter.Delete(id); } private static Libro rowToDto(LibroDS.sp_Libro_SelectAllRow row) { Libro objlibro = new Libro(); objlibro.Id = row.id; objlibro.Isbn = row.isbn; objlibro.Titulo = row.titulo; objlibro.nombreAutor = row.nombre; objlibro.Editorial = row.editorial; objlibro.Anho = row.anho; return objlibro; } }<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Web; /// <summary> /// Descripción breve de AutorBLL /// </summary> public class AutorBLL { public AutorBLL() { // // TODO: Agregar aquí la lógica del constructor // } public void insertarAutor(string nombre) { AutorDSTableAdapters.AutoresTableAdapter adapter = new AutorDSTableAdapters.AutoresTableAdapter(); adapter.mkAutor(nombre); } public void update(int id, string nombre) { AutorDSTableAdapters.AutoresTableAdapter adapter = new AutorDSTableAdapters.AutoresTableAdapter(); adapter.updAutor(id, nombre); } public void eliminar(int id) { int? salida = 0; LibroDSTableAdapters.LibrosTableAdapter adap = new LibroDSTableAdapters.LibrosTableAdapter(); adap.existLibroByGenero(id, ref salida); if (salida.Value > 0) { return; } else { AutorDSTableAdapters.AutoresTableAdapter adapter = new AutorDSTableAdapters.AutoresTableAdapter(); adapter.delAutor(id); } } public List<Autor> getAutores() { List<Autor> listaAutores = new List<Autor>(); AutorDSTableAdapters.AutoresTableAdapter adapter = new AutorDSTableAdapters.AutoresTableAdapter(); AutorDS.AutoresDataTable tabla= adapter.getAutores(); foreach(AutorDS.AutoresRow row in tabla){ listaAutores.Add(new Autor(row.codigo_id,row.nombre)); } return listaAutores; } public static Autor getAutorById(int id) { Autor autor = null; AutorDSTableAdapters.AutoresTableAdapter adapter = new AutorDSTableAdapters.AutoresTableAdapter(); AutorDS.AutoresDataTable tabla = adapter.AutorById(id); foreach(AutorDS.AutoresRow row in tabla){ autor = new Autor(row.codigo_id,row.nombre); } return autor; } }<file_sep># electiva-2-2017 Repositorio de la materia de electiva de programación para el semestre 2-2017 <file_sep>using System; using System.Collections.Generic; using Microsoft.EntityFrameworkCore.Migrations; using Microsoft.EntityFrameworkCore.Metadata; namespace Cine.Migrations { public partial class InitialCreate : Migration { protected override void Up(MigrationBuilder migrationBuilder) { migrationBuilder.CreateTable( name: "tblPeliculasCategorias", columns: table => new { ID = table.Column<int>(nullable: false) .Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn), PategoriaID = table.Column<int>(nullable: false), PeliculaID = table.Column<int>(nullable: false) }, constraints: table => { table.PrimaryKey("PK_tblPeliculasCategorias", x => x.ID); }); migrationBuilder.CreateTable( name: "tblCategorias", columns: table => new { ID = table.Column<int>(nullable: false) .Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn), Nombre = table.Column<string>(nullable: true), PeliculaCategoriaID = table.Column<int>(nullable: true) }, constraints: table => { table.PrimaryKey("PK_tblCategorias", x => x.ID); table.ForeignKey( name: "FK_tblCategorias_tblPeliculasCategorias_PeliculaCategoriaID", column: x => x.PeliculaCategoriaID, principalTable: "tblPeliculasCategorias", principalColumn: "ID", onDelete: ReferentialAction.Restrict); }); migrationBuilder.CreateTable( name: "tblPeliculas", columns: table => new { ID = table.Column<int>(nullable: false) .Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn), Horarios = table.Column<string>(nullable: true), Nombre = table.Column<string>(nullable: true), PeliculaCategoriaID = table.Column<int>(nullable: true), Puntuacion = table.Column<string>(nullable: true) }, constraints: table => { table.PrimaryKey("PK_tblPeliculas", x => x.ID); table.ForeignKey( name: "FK_tblPeliculas_tblPeliculasCategorias_PeliculaCategoriaID", column: x => x.PeliculaCategoriaID, principalTable: "tblPeliculasCategorias", principalColumn: "ID", onDelete: ReferentialAction.Restrict); }); migrationBuilder.CreateIndex( name: "IX_tblCategorias_PeliculaCategoriaID", table: "tblCategorias", column: "PeliculaCategoriaID"); migrationBuilder.CreateIndex( name: "IX_tblPeliculas_PeliculaCategoriaID", table: "tblPeliculas", column: "PeliculaCategoriaID"); } protected override void Down(MigrationBuilder migrationBuilder) { migrationBuilder.DropTable( name: "tblCategorias"); migrationBuilder.DropTable( name: "tblPeliculas"); migrationBuilder.DropTable( name: "tblPeliculasCategorias"); } } } <file_sep><?php include_once './DAO/DAL/Connection.php'; include_once './DAO/DTO/CategoriaJuego.php'; include_once './DAO/BLL/CategoriaJuegoBLL.php'; $categoriaJuegoBLL = new CategoriaJuegoBLL(); $id = 0; $objCategoriaJuego = null; if (isset($_REQUEST["id"])) { $id = $_REQUEST["id"]; $objCategoriaJuego = $categoriaJuegoBLL->select($id); } ?> <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Categoria - Juego</title> <link href="css/bootstrap.min.css" rel="stylesheet" type="text/css"/> <link href="css/bootstrap-theme.min.css" rel="stylesheet" type="text/css"/> <script src="js/bootstrap.min.js" type="text/javascript"></script> </head> <body> <div class="container"> <div class="row"> <div class="col-md-6"> <h2>Datos de Categoria</h2> <form action="abmCategoriaJuego.php" method="post"> <input type="hidden" value="<?php if ($objCategoriaJuego != null) { echo "actualizar"; } else { echo "insertar"; } ?>" name="tarea"/> <input type="hidden" value="<?php echo $id; ?>" name="id"/> <div class="form-group"> <label> Id Juego: </label> <input class="form-control" type="text" name="idJuego" value="<?php if ($objCategoriaJuego != null) { echo $objCategoriaJuego->getIdJuego(); } ?>" required="required" /> </div> <div class="form-group"> <label> Id Categoria: </label> <input class="form-control" type="text" name="idCategoria" value="<?php if ($objCategoriaJuego != null) { echo $objCategoriaJuego->getIdCategoria(); } ?>" required="required" /> </div> <div> <input type="submit" value="Guardar Datos"> <a href="AgregarCategoriaJuego.php" class="btn btn-danger" >Cancelar</a> </div> </form> </div> </div> </div> </body> </html> <file_sep><?php /* * 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. */ /** * Description of accat * * @author Miguel */ class accat { private $accatCcat; private $accatNomb; private $accatCpad; function getAccatCcat() { return $this->accatCcat; } function getAccatNomb() { return $this->accatNomb; } function getAccatCpad() { return $this->accatCpad; } function setAccatCcat($accatCcat) { $this->accatCcat = $accatCcat; } function setAccatNomb($accatNomb) { $this->accatNomb = $accatNomb; } function setAccatCpad($accatCpad) { $this->accatCpad = $accatCpad; } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Web; /// <summary> /// Descripción breve de GeneroBLL /// </summary> public class GeneroBLL { public GeneroBLL() { // // TODO: Agregar aquí la lógica del constructor // } public static int InsertarGenero(Genero obj) { if (obj == null) throw new ArgumentException("El objeto a insertar no puede ser nulo"); if (string.IsNullOrEmpty(obj.nombre)) throw new ArgumentException("El nombre no puede ser nulo o vacio"); int? idGenero = 0; GeneroDSTableAdapters.GeneroTableAdapter adapter = new GeneroDSTableAdapters.GeneroTableAdapter(); adapter.Insert(obj.nombre, ref idGenero); return idGenero.Value; } public static void ModificarGenero(Genero obj) { if (obj == null) throw new ArgumentException("El objeto a modificar no puede ser nulo"); GeneroDSTableAdapters.GeneroTableAdapter adapter = new GeneroDSTableAdapters.GeneroTableAdapter(); adapter.Update(obj.nombre, obj.idGenero); } public static void EliminarGenero(int id) { GeneroDSTableAdapters.GeneroTableAdapter adapter = new GeneroDSTableAdapters.GeneroTableAdapter(); adapter.Delete(id); } public static List<Genero> GetGeneros() { GeneroDSTableAdapters.GeneroTableAdapter adapter = new GeneroDSTableAdapters.GeneroTableAdapter(); GeneroDS.GeneroDataTable table = adapter.Generos(); List<Genero> result = new List<Genero>(); foreach (var row in table) { result.Add(new Genero() { idGenero = row.idGenero, nombre = row.nombre }); } return result; } public static Genero GetGeneroById(int id) { if (id <= 0) throw new ArgumentException("El id no puede ser nulo ni vacio"); GeneroDSTableAdapters.GeneroTableAdapter adapter = new GeneroDSTableAdapters.GeneroTableAdapter(); GeneroDS.GeneroDataTable table = adapter.GetGeneroById(id); Genero result = null; if (table.Rows.Count == 1) { GeneroDS.GeneroRow row = table[0]; result = new Genero() { idGenero = row.idGenero, nombre = row.nombre }; } return result; } public static List<Genero> GetGeneroByIdToList(int id) { List<Genero> e = new List<Genero>(); e.Add(GetGeneroById(id)); return e; } }<file_sep><!DOCTYPE html> <!-- 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. --> <?php include_once './DAO/DAL/Connection.php'; include_once './DAO/DTO//Categoria.php'; include_once './DAO/BLL/CategoriaBLL.php'; $categoriaBLL = new CategoriaBLL(); $id = 0; if(isset($_REQUEST["id"])){ $id = $_REQUEST["id"]; } $objCategoria = $categoriaBLL->select($id); ?> <html> <head> <meta charset="UTF-8"> <link href="css/bootstrap.min.css" rel="stylesheet" type="text/css"/> <link href="css/bootstrap-theme.min.css" rel="stylesheet" type="text/css"/> <script src="js/bootstrap.min.js" type="text/javascript"></script> <title></title> </head> <body> <div class="container"> <div class="row"> <div class="col-md-6"> <h2>Datos de la Categoria</h2> <form action="Categorias.php" method="GET"> <input type="hidden" value="<?php if($objCategoria!=null){ echo "actualizar"; }else{ echo "insertar"; } ?>" name="tarea"/> <input type="hidden" value="<?php echo $id;?>" name="id"/> <div class="form-group"> <label>Nombre : </label> <input class="form-control" required="required" type="text" name="nombre" value="<?php if($objCategoria!=null) { echo $objCategoria->getNombre(); } ?>"/> </div> <div class="form-group"> <label>Categoria Padre : </label> <select name="padre" class="form-control"> <option></option> <?php $listaCategorias = $categoriaBLL->selectAll(); foreach ($listaCategorias as $objCategoria) { ?> <option> <?php echo $objCategoria->getId(); ?> </option> <?php } ?> </select> </div> <div> <input class="btn btn-primary" type="submit" value="Guardar"/> <a class="btn btn-danger" href="Categorias.php">Cancelar</a> </div> </form> </div> </div> </div> </body> </html> <file_sep><?php /** * Description of Persona * * @author jmacb */ class Persona { private $id; private $nombre; private $apellido; private $ciudad; private $edad; function getId() { return $this->id; } function getNombre() { return $this->nombre; } function getApellido() { return $this->apellido; } function getCiudad() { return $this->ciudad; } function getEdad() { return $this->edad; } function setId($id) { $this->id = $id; } function setNombre($nombre) { $this->nombre = $nombre; } function setApellido($apellido) { $this->apellido = $apellido; } function setCiudad($ciudad) { $this->ciudad = $ciudad; } function setEdad($edad) { $this->edad = $edad; } } <file_sep><?php /* * 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. */ /** * Description of Categoria_Juego * * @author rodriguezja */ class Categoria_Juego { private $idCategoriaJuego; private $idJuego; private $idCategoria; function __construct($idCategoriaJuego, $idJuego, $idCategoria) { $this->idCategoriaJuego = $idCategoriaJuego; $this->idJuego = $idJuego; $this->idCategoria = $idCategoria; } function getIdCategoriaJuego() { return $this->idCategoriaJuego; } function getIdJuego() { return $this->idJuego; } function getIdCategoria() { return $this->idCategoria; } function setIdCategoriaJuego($idCategoriaJuego) { $this->idCategoriaJuego = $idCategoriaJuego; } function setIdJuego($idJuego) { $this->idJuego = $idJuego; } function setIdCategoria($idCategoria) { $this->idCategoria = $idCategoria; } } <file_sep><?php /* |-------------------------------------------------------------------------- | Web Routes |-------------------------------------------------------------------------- | | Here is where you can register web routes for your application. These | routes are loaded by the RouteServiceProvider within a group which | contains the "web" middleware group. Now create something great! | */ Route::get('/', function () { //return view('nota/index'); return redirect('/nota/'); }); Route::post('/nota/', 'NotaController@store'); Route::get('/nota/edit/{id}', 'NotaController@edit'); Route::get('/nota/', 'NotaController@index'); Route::get('/nota/{id}', 'NotaController@destroy'); Auth::routes(); Route::get('/home', 'HomeController@index')->name('home'); <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Web; /// <summary> /// Descripción breve de LibroGenero /// </summary> public class LibroGenero { public LibroGenero() { } public int codigo_id { get; set; } public int codigo_libro { get; set; } public int codigo_genero { get; set; } }<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; public partial class Libros : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { /* string id = Request.QueryString["id"]; if(id != null) { List<Libro> listaLibros = LibroBRL.GetLibros(Convert.ToInt32(id)); if(listaLibros != null) { foreach (Libro libro in listaLibros) { titulo = libro.titulo; } }*/ } }<file_sep><?php /** * Description of JuegoBLL * * @author Nikolas-PC */ class JuegoBLL { public function insert($nombre, $precio, $descripcion){ $objConexion = new Connection(); $objConexion->queryWithParams("CALL mk_tblJuegos(:pNombre, :pPrecio, :pDescripcion)", array( "pNombre"=>$nombre, "pPrecio"=>$precio, "pDescripcion"=>$descripcion )); } public function update($id, $nombre, $precio, $descripcion){ $objConexion = new Connection(); $objConexion->queryWithParams("CALL up_tblJuegos(:pCodigo_id, :pNombre, :pPrecio, :pDescripcion)", array( "pCodigo_id"=>$id, "pNombre"=>$nombre, "pPrecio"=>$precio, "pDescripcion"=>$descripcion )); } public function delete($id) { $objConexion = new Connection(); $objConexion->queryWithParams("CALL del_tblJuegos(:pCodigo_id)", array( ":pCodigo_id" => $id )); } public function selectAll() { $listaJuegos = array(); $objConexion = new Connection(); $res = $objConexion->query("CALL get_tblJuegos()"); while ($row = $res->fetch(PDO::FETCH_ASSOC)) { $objJuego = $this->rowToDto($row); $listaJuegos[] = $objJuego; } return $listaJuegos; } public function select($id) { $objConexion = new Connection(); $res = $objConexion->queryWithParams("CALL get_tblJuegosById(:id)", array( ":id" => $id )); if ($res->rowCount() == 0) { return null; } $row = $res->fetch(PDO::FETCH_ASSOC); return $this->rowToDto($row); } function rowToDto($row) { $objJuego = new Juego(); $objJuego->setCodigo_id("codig_id"); $objJuego->setNombre("nombre"); $objJuego->setPrecio("precio"); $objJuego->setDescripcion("descripcion"); return $objJuego; } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Web; /// <summary> /// Descripción breve de LibroBLL /// </summary> public class GeneroBLL { public GeneroBLL() { // // TODO: Agregar aquí la lógica del constructor // } public static List<Genero>SelectAll() { List<Genero> listaRoles = new List<Genero>(); GeneroDSTableAdapters.GeneroTableAdapter adapter = new GeneroDSTableAdapters.GeneroTableAdapter(); GeneroDS.GeneroDataTable table = adapter.SelectAll(); foreach (GeneroDS.GeneroRow row in table) { listaRoles.Add(rowToDto(row)); } return listaRoles; } public static Genero SelectById(int id) { GeneroDSTableAdapters.GeneroTableAdapter adapter = new GeneroDSTableAdapters.GeneroTableAdapter(); GeneroDS.GeneroDataTable table = adapter.SelectById(id); if (table.Rows.Count == 0) { return null; } return rowToDto(table[0]); } public static Genero SelectByIdS(int id) { Genero listaRoles = new Genero(); GeneroDSTableAdapters.GeneroTableAdapter adapter = new GeneroDSTableAdapters.GeneroTableAdapter(); GeneroDS.GeneroDataTable table = adapter.SelectById(id); if (table.Rows.Count == 0) { return null; } else { foreach (GeneroDS.GeneroRow row in table) { listaRoles = rowToDto(row); } return listaRoles; } } public static void insert(string nombre) { GeneroDSTableAdapters.GeneroTableAdapter adapter = new GeneroDSTableAdapters.GeneroTableAdapter(); adapter.Insert( nombre); } public static void update(string nombre ,int Original_idLibro) { GeneroDSTableAdapters.GeneroTableAdapter adapter = new GeneroDSTableAdapters.GeneroTableAdapter(); adapter.Update( nombre, Original_idLibro); } public static void delete(int id) { GeneroDSTableAdapters.GeneroTableAdapter adapter = new GeneroDSTableAdapters.GeneroTableAdapter(); adapter.Delete(id); } private static Genero rowToDto(GeneroDS.GeneroRow row) { Genero objLibro = new Genero(); objLibro.idGenero = row.idGenero; objLibro.Nombre = row.Nombre; return objLibro; } }<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Web; /// <summary> /// Descripción breve de Libro /// </summary> public class Libro { public int id { get; set; } public string isbn { get; set; } public string titulo { get; set; } public int autor_id { get; set; } public string editorial { get; set; } public int año { get; set; } public Libro() { // // TODO: Agregar aquí la lógica del constructor // } public Libro(string isbn, string titulo,int autor_id, string editorial, int año) { this.isbn = isbn; this.titulo = titulo; this.autor_id = autor_id; this.editorial = editorial; this.año = año; } public Libro(int id, string isbn, string titulo, int autor_id, string editorial, int año) { this.id = id; this.isbn = isbn; this.titulo = titulo; this.autor_id = autor_id; this.editorial = editorial; this.año = año; } }<file_sep>/// <reference path="jquery-2.0.3.min.js" /> /// <reference path="knockout-3.0.0.js" /> function Student(data) { this.StudentId = ko.observable(data.StudentId); this.FirstName = ko.observable(data.FirstName); this.LastName = ko.observable(data.LastName); this.Age = ko.observable(data.Age); this.Gender = ko.observable(data.Gender); this.Batch = ko.observable(data.Batch); this.Address = ko.observable(data.Address); this.Class = ko.observable(data.Class); this.School = ko.observable(data.School); this.Domicile = ko.observable(data.Domicile); } function StudentViewModel() { var self = this; self.Domiciles = ko.observableArray(['Delhi', 'Outside Delhi']); self.Genders = ko.observableArray(['Male', 'Female']); self.Students = ko.observableArray([]); self.StudentId = ko.observable(); self.FirstName = ko.observable(); self.LastName = ko.observable(); self.Age = ko.observable(); self.Batch = ko.observable(); self.Address = ko.observable(); self.Class = ko.observable(); self.School = ko.observable(); self.Domicile = ko.observable(); self.Gender = ko.observable(); self.AddStudent = function () { self.Students.push(new Student({ StudentId: self.StudentId(), FirstName: self.FirstName(), LastName: self.LastName(), Domicile: self.Domicile(), Age: self.Age(), Batch: self.Batch(), Address: self.Address(), Class: self.Class(), School: self.School(), Gender: self.Gender() })); self.StudentId(""), self.FirstName(""), self.LastName(""), self.Domicile(""), self.Age(""), self.Batch(""), self.Address(""), self.Class(""), self.School(""), self.Gender("") }; self.DeleteStudent = function (student) { $.ajax({ type: "POST", url: 'LearnKO.aspx/DeleteStudent', data: ko.toJSON({ data: student }), contentType: "application/json; charset=utf-8", success: function (result) { alert(result.d); self.Students.remove(student) }, error: function (err) { alert(err.status + " - " + err.statusText); } }); }; self.SaveStudent = function () { $.ajax({ type: "POST", url: 'LearnKO.aspx/SaveStudent', data: ko.toJSON({ data: self.Students }), contentType: "application/json; charset=utf-8", success: function (result) { alert(result.d); }, error: function (err) { alert(err.status + " - " + err.statusText); } }); }; $.ajax({ type: "POST", url: 'LearnKO.aspx/FetchStudents', contentType: "application/json; charset=utf-8", dataType: "json", success: function (results) { var students = $.map(results.d, function (item) { return new Student(item) }); self.Students(students); }, error: function (err) { alert(err.status + " - " + err.statusText); } }) } $(document).ready(function () { ko.applyBindings(new StudentViewModel()); }); <file_sep><?php /* * 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. */ /** * Description of CategoriaBLL * * @author COCCO */ class CategoriaBLL { public function insert($nombre, $categoriaPadre) { $objConexion = new Connection(); $objConexion->queryWithParams("INSERT INTO tblCategorias(nombre, idCategoriaPadre)VALUES(" . ":pNombre, :pCategoriaPadre);", array( ":pNombre"=>$nombre, ":pCategoriaPadre"=>$categoriaPadre )); } public function update($nombre, $categoriaPadre, $id) { $objConexion = new Connection(); $objConexion->queryWithParams("UPDATE tblCategorias SET nombre = :pNombre, idCategoriaPadre = :pCategoriaPadre WHERE id = :pId", array( ":pNombre"=>$nombre, ":pCategoriaPadre"=>$categoriaPadre, ":pId"=>$id )); } public function delete($id) { $objConexion = new Connection(); $objConexion->queryWithParams( "DELETE FROM tblCategorias WHERE id = :pId", array( ":pId"=>$id )); } public function selectAll() { $listaCategorias = array(); $objConexion = new Connection(); $res = $objConexion->query( "SELECT id , nombre , idCategoriaPadre FROM tblCategorias"); while($row = $res->fetch(PDO::FETCH_ASSOC)){ $objCategoria = $this->rowToDto($row); $listaCategorias[] = $objCategoria; } return $listaCategorias; } public function select($id) { $objConexion = new Connection(); $res = $objConexion->queryWithParams( "SELECT id , nombre , idCategoriaPadre FROM tblCategorias WHERE id = :pId", array( ":pId"=>$id )); if($res->rowCount()==0){ return null; } $row = $res->fetch(PDO::FETCH_ASSOC); return $this->rowToDto($row); } public function selectName($id) { $objConexion = new Connection(); $res = $objConexion->queryWithParams( "SELECT CJ.id, CJ.idJuego, idCategoria FROM tblCategorias C , tblCategoriaDeJuego CJ WHERE C.id = :pId and C.id = CJ.idCategoria", array( ":pId"=>$id )); if($res->rowCount()==0){ return null; } $row = $res->fetch(PDO::FETCH_ASSOC); return $this->rowToDto2($row); } function rowToDto($row) { $objCategoria = new Categoria(); $objCategoria->setId($row["id"]); $objCategoria->setNombre($row["nombre"]); $objCategoria->setCategoriaPadre($row["idCategoriaPadre"]); return $objCategoria; } function rowToDto2($row) { $objCategoriaJuego = new CategoriaJuego(); $objCategoriaJuego->setId($row["id"]); $objCategoriaJuego->setIdJuego($row["idJuego"]); $objCategoriaJuego->setIdCategoria($row["idCategoria"]); return $objCategoriaJuego; } } <file_sep>using System; using System.Collections.Generic; using Microsoft.EntityFrameworkCore.Migrations; namespace PracticaMVC1.Migrations { public partial class Agregada_foranea_comida : Migration { protected override void Up(MigrationBuilder migrationBuilder) { migrationBuilder.AddColumn<int>( name: "PersonaID", table: "Comida", nullable: false, defaultValue: 0); migrationBuilder.CreateIndex( name: "IX_Comida_PersonaID", table: "Comida", column: "PersonaID"); migrationBuilder.AddForeignKey( name: "FK_Comida_Persona_PersonaID", table: "Comida", column: "PersonaID", principalTable: "Persona", principalColumn: "ID", onDelete: ReferentialAction.Cascade); } protected override void Down(MigrationBuilder migrationBuilder) { migrationBuilder.DropForeignKey( name: "FK_Comida_Persona_PersonaID", table: "Comida"); migrationBuilder.DropIndex( name: "IX_Comida_PersonaID", table: "Comida"); migrationBuilder.DropColumn( name: "PersonaID", table: "Comida"); } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; public partial class LibroPagina : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { String id = Request.QueryString["id"]; if(id != null) { Libro libro = libroBll.SelectById(id); H1titulo.Text = libro.titulo; Autor autor = AutorBll.SelectById(libro.idAutor+""); String imagen = "fotos/" + libro.id + ".jpg"; imagenLibro.Src = imagen; // imagenLibro. //// imagenli // fotoId.Text h1Autor.Text = autor.Nombre; h3ISBN.Text = libro.ISBN; } } }<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace MVCPeliculas.Models { public class Genero { public int Id { get; set; } public string Nombre { get; set; } public ICollection<GeneroPelicula> GeneroPeliculas { get; set; } public Genero() { } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace PeliculasMVC.Models { public class CategoriaPelicula { public int ID { get; set; } public int PeliculaID { get; set; } public int CategoriaID { get; set; } public Pelicula Pelicula { get; set; } public Categoria Categoria { get; set; } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Web; /// <summary> /// Descripción breve de LibroGeneroBRL /// </summary> public class LibroGeneroBRL { public LibroGeneroBRL() { } public static List<LibroGenero> selectAll() { LibroGeneroDSTableAdapters.LibroGeneroTableAdapter adapter = new LibroGeneroDSTableAdapters.LibroGeneroTableAdapter(); LibroGeneroDS.tblLibroGeneroDataTable table = adapter.GetLibroGenero(); List<LibroGenero> lista = new List<LibroGenero>(); foreach (LibroGeneroDS.tblLibroGeneroRow row in table) { lista.Add(rowToDto(row)); } return lista; } private static LibroGenero rowToDto(LibroGeneroDS.tblLibroGeneroRow row) { LibroGenero obj = new LibroGenero { codigo_id = row.codigo_id, codigo_libro = row.libro_id, codigo_genero = row.genero_id }; return obj; } public static void add(LibroGenero libroGenero) { LibroGeneroDSTableAdapters.LibroGeneroTableAdapter adapter = new LibroGeneroDSTableAdapters.LibroGeneroTableAdapter(); adapter.Insert(libroGenero.codigo_libro, libroGenero.codigo_genero); } public static void delete(int id) { LibroGeneroDSTableAdapters.LibroGeneroTableAdapter adapter = new LibroGeneroDSTableAdapters.LibroGeneroTableAdapter(); adapter.Delete(id); } public static void update(LibroGenero libroGenero) { LibroGeneroDSTableAdapters.LibroGeneroTableAdapter adapter = new LibroGeneroDSTableAdapters.LibroGeneroTableAdapter(); adapter.Update(libroGenero.codigo_genero, libroGenero.codigo_id); } }<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.EntityFrameworkCore; using PeliculasMVC.Models; namespace PeliculasMVC.Context { public class ProyectoContext : DbContext { public DbSet<Pelicula> Peliculas { get; set; } public DbSet<Categoria> Categorias { get; set; } public DbSet<CategoriaPelicula> CategoriasPeliculas { get; set; } public ProyectoContext(DbContextOptions options) : base(options) { } protected override void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder.Entity<Pelicula>().ToTable("Pelicula"); modelBuilder.Entity<Categoria>().ToTable("Categoria"); modelBuilder.Entity<CategoriaPelicula>().ToTable("CategoriaPelicula"); } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Web; /// <summary> /// Descripción breve de CategoriaBLL /// </summary> public class CategoriaBLL { public CategoriaBLL() { // // TODO: Agregar aquí la lógica del constructor // } public void insertarCategoria(string nombre) { CategoriaDSTableAdapters.GenerosTableAdapter adapter = new CategoriaDSTableAdapters.GenerosTableAdapter(); adapter.mkGenero(nombre); } public void update(int id, string nombre) { CategoriaDSTableAdapters.GenerosTableAdapter adapter = new CategoriaDSTableAdapters.GenerosTableAdapter(); adapter.updGenero(id, nombre); } public void eliminar(int id) { int? salida = 0; LibroDSTableAdapters.LibrosTableAdapter adap = new LibroDSTableAdapters.LibrosTableAdapter(); adap.existLibroByGenero(id, ref salida); if(salida.Value > 0){ return; } else { CategoriaDSTableAdapters.GenerosTableAdapter adapter = new CategoriaDSTableAdapters.GenerosTableAdapter(); adapter.delGenero(id); } } public List<Categoria> getCategorias() { List<Categoria> listaGeneros = new List<Categoria>(); CategoriaDSTableAdapters.GenerosTableAdapter adapter = new CategoriaDSTableAdapters.GenerosTableAdapter(); CategoriaDS.GenerosDataTable tabla = adapter.GetGeneros(); foreach(CategoriaDS.GenerosRow row in tabla){ listaGeneros.Add(new Categoria(row.codigo_id,row.nombre)); } return listaGeneros; } }<file_sep>using System; using System.Web; using System.IO; public partial class insLibros : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { } private void MensajeError(string v) { throw new NotImplementedException(); } string ruta; private void GuardarArchivo(HttpPostedFile file) { // Se carga la ruta física de la carpeta temp del sitio ruta = Server.MapPath("~/img"); // Si el directorio no existe, crearlo if (!Directory.Exists(ruta)) Directory.CreateDirectory(ruta); string archivo = String.Format("{0}\\{1}", ruta, file.FileName); // Verificar que el archivo no exista if (File.Exists(archivo)) { MensajeError(String.Format( "Ya existe una imagen con nombre\"{0}\".", file.FileName)); } else { file.SaveAs(archivo); } } protected void cargarImagen_Click( object sender, EventArgs e) { try { if (fileUploader1.HasFile) { // Se verifica que la extensión sea de un formato válido string ext = fileUploader1.PostedFile.FileName; ext = ext.Substring(ext.LastIndexOf(".") + 1).ToLower(); string[] formatos = new string[] { "jpg", "jpeg", "bmp", "png", "gif" }; if (Array.IndexOf(formatos, ext) < 0) { MensajeError("Formato de imagen inválido."); msgError.Text = "Formato de imagen inválido."; msgError.Visible = true; } else if (disco.Checked) { GuardarArchivo(fileUploader1.PostedFile); } } else { msgError.Text = "Seleccione un archivo del disco duro."; msgError.Visible = true; MensajeError("Seleccione un archivo del disco duro."); } } catch (Exception ex) { MensajeError(ex.Message); } } protected void btnGuardar_Click(object sender, EventArgs e) { string isbn = txtIsbn.Text; string titulo = txtTitulo.Text; int idAutor = Convert.ToInt32(cbIdAutor.SelectedValue); string editorial = txtEditorial.Text; int anho = Convert.ToInt32(txtAnho.Text); int idLibro = GeneroLibroBRL.getLibroId(); int idGenero = Convert.ToInt32(dpGenero.SelectedValue); string imagen = "imagen"; try { LibroBRL.insert(isbn, titulo, idAutor, editorial, anho, imagen); GeneroLibroBRL.insert(idLibro, idGenero); } catch (Exception ex) { } } }<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Cartelera.Context; using Cartelera.Models; namespace Cartelera.Controllers { public class HomeController : Controller { private readonly ProyectoPruebaContext db; public HomeController(ProyectoPruebaContext context) { db = context; } public IActionResult Index() { db.Database.EnsureCreated(); var pelicula = new Pelicula { nombrePelicula = "El dia despues de mañana", fecha = "24/11/2017", horario = "19:15 / 21:30", puntuacion = 6 }; db.Peliculas.Add(pelicula); var categorias = new Categoria { nombre = "Drama", Pelicula = pelicula, PeliculaID = pelicula.PeliculaID}; db.Categorias.Add(categorias); db.SaveChanges(); return View(); } public IActionResult About() { ViewData["Message"] = "Your application description page."; return View(); } public IActionResult Contact() { ViewData["Message"] = "Your contact page."; return View(); } public IActionResult Error() { return View(); } } } <file_sep><!DOCTYPE html> <!-- 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. --> <?php include_once './DAO/DAL/Connection.php'; include_once './DAO/Model/Juego.php'; include_once './DAO/BLL/JuegoBLL.php'; $juegoBLL = new JuegoBLL(); function mostrarMensaje($mensaje) { echo "<script>alert('$mensaje')</script>"; } if (isset($_REQUEST["tarea"])) { $tarea = $_REQUEST["tarea"]; switch ($tarea) { case "insertar" : if (!isset($_REQUEST["nombre"]) || !isset($_REQUEST["precio"]) || !isset($_REQUEST["descripcion"])) { mostrarMensaje("Error al insertar, faltan parametros."); return; } else { $nombre = $_REQUEST["nombre"]; $padre = $_REQUEST["padre"]; $precio = $_REQUEST["precio"]; $descripcion = $_REQUEST["descripcion"]; $juegoBLL->insert($nombre, $precio, $padre, $descripcion); } break; case "actualizar": if (!isset($_REQUEST["nombre"]) || !isset($_REQUEST["padre"]) || !isset($_REQUEST["precio"]) || !isset($_REQUEST["descripcion"]) || !isset($_REQUEST["id"])) { mostrarMensaje("Error al actualizar, faltan parametros."); return; } else { $id = $_REQUEST["id"]; $nombre = $_REQUEST["nombre"]; $padre = $_REQUEST["padre"]; $precio = $_REQUEST["precio"]; $descripcion = $_REQUEST["descripcion"]; $categoria = $_REQUEST["padre"]; $juegoBLL->update($nombre, $precio, $categoria, $descripcion, $id); } break; case "eliminar": if (!isset($_REQUEST["id"])) { mostrarMensaje("Error al eliminar, faltan parametros."); return; } else { $id = $_REQUEST["id"]; $juegoBLL->delete($id); } break; case "foto": if (!isset($_REQUEST["id"])) { mostrarMensaje("Error al cargar foto, faltan parametros."); return; } else { $id = $_REQUEST["id"]; $dir_subida = 'img/'; $fichero_subido = $dir_subida . $id . ".jpg"; if (move_uploaded_file($_FILES['archivo']['tmp_name'], $fichero_subido)) { } else { } } break; } } ?> <html> <head> <meta charset="UTF-8"> <link href="css/bootstrap.min.css" rel="stylesheet" type="text/css"/> <link href="css/bootstrap-theme.min.css" rel="stylesheet" type="text/css"/> <script src="js/bootstrap.min.js" type="text/javascript"></script> <link rel="stylesheet" type="text/css" href="css/style.css"> <title>JUEGOS</title> </head> <header> <div class="titulo center-block"> </div> <h1>Playstation</h1> <nav> <ul> <?php $listaJuegos = $juegoBLL->selectAll(); foreach ($listaJuegos as $objJuego) { ?> <li><?php echo $objJuego->getNombre()?></li> <?php } ?> </ul> </nav> <h2>Juegos</h2> </header> <body> <div class="container"> <div class="row"> <div class="col-md-12"> <div class="well"> <a href="AgregarJuego.php">Agregar</a> <a href="Categorias.php">Categorias</a> </div> <div class="categorias col-md-2"> <nav> <ul> <?php $listaJuegos = $juegoBLL->selectAll(); foreach ($listaJuegos as $objJuego) { ?> <li><?php echo $objJuego->getNombre()?></li> <?php } ?> </ul> </nav> </div> <div class="filtros"> </div> <div class="filtros2 col-md-10"> <?php $listaJuegos = $juegoBLL->selectAll(); foreach ($listaJuegos as $objJuego) { ?> <div class="col-md-3 item center-block"> <img src="img/<?php echo $objJuego->getId() ?>.jpg" alt="" class="center-block img-responsive" id="img"/> <h2><?php echo $objJuego->getNombre() ?></h2> <label id="precio">Precio : <?php echo $objJuego->getPrecio() ?></label> <a href="detalle.php?id=<?php echo $objJuego->getId(); ?>"><i class="glyphicon glyphicon-resize-full"></i></a> <a href="AgregarJuego.php?id=<?php echo $objJuego->getId(); ?>"><i class="glyphicon glyphicon-edit"></i></a> <a href="Foto.php?id=<?php echo $objJuego->getId(); ?>"><i class="glyphicon glyphicon-picture"></i></a> <a href="index.php?tarea=eliminar&id=<?php echo $objJuego->getId(); ?>"><i class="glyphicon glyphicon-trash"></i></a> </div> <?php } ?> </div> </div> </div> </div> </body> </html> <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Web; /// <summary> /// Descripción breve de GeneroLibroEdicionesBLL /// </summary> public class GeneroLibroEdicionesBLL { public GeneroLibroEdicionesBLL() { } public static List<GeneroLibroEdiciones> SelectAll() { List<GeneroLibroEdiciones> listaGenerosLibros = new List<GeneroLibroEdiciones>(); GeneroLibroEdicionesDSTableAdapters.sp_GeneroLibroEdiciones_SelectAllTableAdapter adapter = new GeneroLibroEdicionesDSTableAdapters.sp_GeneroLibroEdiciones_SelectAllTableAdapter(); GeneroLibroEdicionesDS.sp_GeneroLibroEdiciones_SelectAllDataTable table = adapter.SelectAll(); foreach (GeneroLibroEdicionesDS.sp_GeneroLibroEdiciones_SelectAllRow row in table) { listaGenerosLibros.Add(rowToDto2(row)); } return listaGenerosLibros; } public static GeneroLibroEdiciones SelectByIdGeneroLibro(int id) { GeneroLibroEdicionesDSTableAdapters.sp_GeneroLibroEdiciones_SelectAllTableAdapter adapter = new GeneroLibroEdicionesDSTableAdapters.sp_GeneroLibroEdiciones_SelectAllTableAdapter(); GeneroLibroEdicionesDS.sp_GeneroLibroEdiciones_SelectAllDataTable table = adapter.selectbyidgenerolibro(id); if (table.Rows.Count == 0) { return null; } return rowToDto2(table[0]); } public static void Insert(int idLibro,int idGenero) { GeneroLibroEdicionesDSTableAdapters.sp_GeneroLibroEdiciones_SelectAllTableAdapter adapter = new GeneroLibroEdicionesDSTableAdapters.sp_GeneroLibroEdiciones_SelectAllTableAdapter(); adapter.Insert(idLibro,idGenero); } public static void Update(int idLibro, int idGenero, int id) { GeneroLibroEdicionesDSTableAdapters.sp_GeneroLibroEdiciones_SelectAllTableAdapter adapter = new GeneroLibroEdicionesDSTableAdapters.sp_GeneroLibroEdiciones_SelectAllTableAdapter(); adapter.Update(idLibro,idGenero,id); } public static void Delete(int id) { GeneroLibroEdicionesDSTableAdapters.sp_GeneroLibroEdiciones_SelectAllTableAdapter adapter = new GeneroLibroEdicionesDSTableAdapters.sp_GeneroLibroEdiciones_SelectAllTableAdapter(); adapter.Delete(id); } private static GeneroLibroEdiciones rowToDto2(GeneroLibroEdicionesDS.sp_GeneroLibroEdiciones_SelectAllRow row) { GeneroLibroEdiciones objGeneroLibro = new GeneroLibroEdiciones(); objGeneroLibro.Id = row.id; objGeneroLibro.Nombre = row.nombre; objGeneroLibro.Titulo = row.titulo; return objGeneroLibro; } }<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Web; using Biblioteca.App_Code.DAL; public class libroBll { public libroBll() { } public static List<Libro> SelectAll() { List<Libro> listaLibros = new List<Libro>(); DataSet1TableAdapters.LibroTableAdapter adapter = new DataSet1TableAdapters.LibroTableAdapter(); DataSet1.LibroDataTable table = adapter.SelectAll(); foreach (DataSet1.LibroRow item in table) { listaLibros.Add(rowtoDto(item)); } return listaLibros; } public static void borrar(string id) { DataSet1TableAdapters.LibroTableAdapter adapter = new DataSet1TableAdapters.LibroTableAdapter(); adapter.Delete(Int32.Parse(id)); } public static int selectUltimo() { List<Libro> listaLibros = new List<Libro>(); DataSet1TableAdapters.LibroTableAdapter adapter = new DataSet1TableAdapters.LibroTableAdapter(); DataSet1.LibroDataTable table = adapter.SelectAll(); int mayor = 0; foreach (DataSet1.LibroRow item in table) { if (item.Id > mayor) mayor = item.Id; } return mayor; } public static Libro SelectById(String id) { int id2 = Int32.Parse(id); List<Libro> listaLibros = new List<Libro>(); DataSet1TableAdapters.LibroTableAdapter adapter = new DataSet1TableAdapters.LibroTableAdapter(); DataSet1.LibroDataTable table = adapter.SelectById(id2); //DAL.LibroDS.LibroDataTable table = adapter.SelectAll(); Libro libro = null; foreach (DataSet1.LibroRow item in table) { libro = rowtoDto(item); } return libro; } public static List<Libro> SelectByIdS(String idAutor,String idGenero) { if (idAutor.Equals("0") && !idGenero.Equals("0")) // es por genero { int id2 = Int32.Parse(idGenero); List<Libro> listaLibros = new List<Libro>(); DataSet1TableAdapters.LibroTableAdapter adapter = new DataSet1TableAdapters.LibroTableAdapter(); DataSet1.LibroDataTable table = adapter.SelectByIdGenero(id2); //DAL.LibroDS.LibroDataTable table = adapter.SelectAll(); foreach (DataSet1.LibroRow item in table) { listaLibros.Add(rowtoDto(item)); } return listaLibros; } else if (idGenero.Equals("0") && idAutor.Equals("0")) // es sin parametros { return SelectAll(); } else { int id2 = Int32.Parse(idAutor); // es por autor List<Libro> listaLibros = new List<Libro>(); DataSet1TableAdapters.LibroTableAdapter adapter = new DataSet1TableAdapters.LibroTableAdapter(); DataSet1.LibroDataTable table = adapter.SelectByIDAutor(id2); //DAL.LibroDS.LibroDataTable table = adapter.SelectAll(); foreach (DataSet1.LibroRow item in table) { listaLibros.Add(rowtoDto(item)); } return listaLibros; } } public static void insert(string titulo, string autor, string isbn, string anho, string editorial, String id) { DataSet1TableAdapters.LibroTableAdapter adapter = new DataSet1TableAdapters.LibroTableAdapter(); adapter.Insert(isbn,titulo,Int32.Parse(autor),editorial,Int32.Parse(anho), " "); } public static void Editar(string titulo, string autor, string isbn, string anho, string editorial,String id) { Libro libro = libroBll.SelectById(id); DataSet1TableAdapters.LibroTableAdapter adapter = new DataSet1TableAdapters.LibroTableAdapter(); adapter.Update(isbn,titulo, Int32.Parse(autor), editorial, Int32.Parse(anho), " ",libro.id); } // titulo autor ISBN Año Editorial public static void Editar(string titulo, string autor, string isbn, string value4) { } private static Libro rowtoDto(DataSet1.LibroRow item) { Libro objlibro = new Libro(); objlibro.id = item.Id; objlibro.idAutor = item.IdAutor; objlibro.ISBN = item.ISBN; objlibro.titulo = item.Titulo; objlibro.editorial = item.Editorial; objlibro.anho = item.Anho; return objlibro; } }<file_sep><?php include_once './DAO/DAL/Connection.php'; include_once './DAO/DTO/Juego.php'; include_once './DAO/BLL/JuegoBLL.php'; include_once './DAO/DTO/Categoria.php'; include_once './DAO/BLL/CategoriaBLL.php'; $juegoBLL = new JuegoBLL(); $categoriaBLL = new CategoriaBLL(); $id = 0; if(isset($_REQUEST["id"])){ $id = $_REQUEST["id"]; } ?> <!DOCTYPE html> <!-- 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. --> <html> <head> <meta charset="UTF-8"> <link href="css/bootstrap.min.css" rel="stylesheet" type="text/css"/> <link href="css/bootstrap-theme.min.css" rel="stylesheet" type="text/css"/> <script src="js/bootstrap.min.js" type="text/javascript"></script> <link href="css/style.css" rel="stylesheet" type="text/css"/> <title></title> </head> <body> <div class="container"> <div class="row"> <div class="col-md-6"> <form enctype="multipart/form-data" method="POST" action="index.php"> <input class="form-group" type="file" name="archivo" required="required"/> <img src="img/<?php echo $id?>.jpg" alt="" class="img-responsive" id="img"/> <input type="hidden" value="foto" name="tarea"/> <input type="hidden" value="<?php echo $id;?>" name="id"/> <input class="btn btn-primary"type="submit" value="Subir Foto"/> <a class="btn btn-danger" href="index.php">Cancelar</a> </form> </div> </div> </div> </body> </html> <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; public partial class DetalleLibro : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { //string id = Request.QueryString["id"]; //if (id != null) //{ // Libro objLibro = LibroBLL.SelectById(Convert.ToInt32(id)); // if (objLibro != null) // { // txtIsbn.Text = objLibro.Isbn; // txtTitulo.Text = objLibro.Titulo; // txtEditorial.Text = objLibro.Editorial; // txtanho.Text = Convert.ToString(objLibro.Anho); // hdnId.Value = objLibro.Id.ToString(); // } //} } } }<file_sep><?php include_once './DAO/DAL/Connection.php'; include_once './DAO/DTO/Persona.php'; include_once './DAO/BLL/PersonaBLL.php'; ?> <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title></title> </head> <body> <?php $personaBLL = new PersonaBLL(); // $personaBLL->insert("Juan", "Perez", "SCZ", 20); ?> <table> <thead> <tr> <th>ID</th> <th>Nombre</th> <th>Apellido</th> <th>Ciudad</th> <th>Edad</th> </tr> </thead> <tbody> <?php $listaPersonas = $personaBLL->selectAll(); foreach ($listaPersonas as $objPersona) { ?> <tr> <td> <?php echo $objPersona->getId(); ?> </td> <td> <?php echo $objPersona->getNombre(); ?> </td> <td> <?php echo $objPersona->getApellido(); ?> </td> <td> <?php echo $objPersona->getCiudad(); ?> </td> <td> <?php echo $objPersona->getEdad(); ?> </td> </tr> <?php } ?> </tbody> </table> </body> </html> <file_sep>using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Threading.Tasks; namespace TiendaPeliculas.Models { public class Categoria { public int ID { get; set; } public string Nombre { get; set; } public ICollection<CategoriaxLibro> Pelicula { get; set; } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; public partial class Libros : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { } protected void Eliminar_Click(object sender, EventArgs e) { LinkButton elimiar = (LinkButton)sender; int idLibro = Convert.ToInt32(elimiar.CommandArgument); LibroBLL.delete(idLibro); GeneroLibroBLL.delete(idLibro); GridViewLibros.DataBind(); } }<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Web; /// <summary> /// Descripción breve de Libro /// </summary> /// [Serializable] public class Libro { public int idLibro { get; set; } public string isbn { get; set; } public string titulo { get; set; } public string editorial { get; set; } public int edicion { get; set; } //año de edicion public string cubierta { get; set; } //imagen public int idAutor { get; set; } public int idGenero { get; set; } public Libro() { } }<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace MVCPeliculas.Models { public class Pelicula { public int ID { get; set; } public int DirectorID { get; set; } public string CodigoImagen { get; set; } public string Nombre { get; set; } public string FechaEstreno { get; set; } public string Descripcion { get; set; } public string Duraccion { get; set; } public string Idioma { get; set; } public string Pais { get; set; } public Director Director { get; set; } public ICollection<GeneroPelicula> GeneroPeliculas { get; set; } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Web; /// <summary> /// Descripción breve de Genero /// </summary> public class Genero { public Genero() { } public int GeneroId { get; set; } public string NombreGenero { get; set; } }<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.Data; using System.IO; public partial class EditarLibro : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { var idLibro = Request.QueryString["idLibro"]; if (idLibro != null) { Libro Libros = LibroBLL.SelectByIdS(Convert.ToInt32(idLibro)); HiddenId.Value = idLibro; titulo.Text = Libros.Titulo; ISBN.Text = Libros.ISBN; DropDownList1.SelectedValue = Convert.ToString(Libros.idAutor); Editorial.Text = Libros.Editorial; anho.Text = Convert.ToString(Libros.Anho); } } } protected void Button1_Click(object sender, EventArgs e) { try { Libro nuevoLibro = new Libro(); nuevoLibro.idAutor = Convert.ToInt32(DropDownList1.SelectedValue.ToString()); nuevoLibro.ISBN = ISBN.Text; nuevoLibro.idLibro = Convert.ToInt32(HiddenId.Value); nuevoLibro.Editorial = Editorial.Text; nuevoLibro.Anho = Convert.ToInt32(anho.Text); nuevoLibro.Titulo = titulo.Text; GuardarArchivo(fileUploader1.PostedFile, nuevoLibro); } catch (Exception ex) { } } protected void Agregar_Click(object sender, EventArgs e) { } protected void CheckBox1_CheckedChanged(object sender, EventArgs e) { CheckBox elimiar = (CheckBox)sender; var Ceheck = elimiar.Checked; if (Ceheck == true) { int idLibro = Convert.ToInt32(elimiar.Text); GeneroLibroBLL.insert(Convert.ToInt32(HiddenId.Value), Convert.ToInt32(elimiar.Text)); }else { int idLibro = Convert.ToInt32(elimiar.Text); GeneroLibroBLL.deleteGeneral(Convert.ToInt32(HiddenId.Value), Convert.ToInt32(elimiar.Text)); } } private void GuardarArchivo(HttpPostedFile file, Libro nuevoLibro) { string archivo=""; if (file.FileName !="") { archivo = (DateTime.Now.ToString("yyyyMMddHHmmss") + "-" + nuevoLibro.idLibro + "-" + file.FileName).ToLower(); file.SaveAs(Server.MapPath("~/temp/" + archivo)); } LibroBLL.update(nuevoLibro.ISBN, nuevoLibro.Titulo, nuevoLibro.idAutor, nuevoLibro.Editorial, nuevoLibro.Anho, archivo, nuevoLibro.idLibro); Response.Redirect("Libros.aspx",false); } }<file_sep><?php /* |-------------------------------------------------------------------------- | Web Routes |-------------------------------------------------------------------------- | | Here is where you can register web routes for your application. These | routes are loaded by the RouteServiceProvider within a group which | contains the "web" middleware group. Now create something great! | */ Route::get('/', function () { // return Route::resource('/Nota', 'NotaController'); return view('home'); }); Auth::routes(); Route::resource('/nota', 'NotaController'); Route::get('/buscar/{id}','NotaController@buscar'); Route::get('/buscar/','NotaController@buscartodos'); Route::get('/borrar/{id}','NotaController@destroy'); Route::get('/agregar/{titulo}/{desc}','NotaController@agregar'); Route::get('/agregar/{titulo}/{desc}/{id}','NotaController@editar'); <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Web; /// <summary> /// Descripción breve de GeneroBRL /// </summary> public class GeneroBRL { public GeneroBRL() { // // TODO: Agregar aquí la lógica del constructor // } public static List<Genero> GetGeneros() { List<Genero> listaGeneros = new List<Genero>(); GeneroDSTableAdapters.GenerosTableAdapter adapter = new GeneroDSTableAdapters.GenerosTableAdapter(); GeneroDS.GenerosDataTable table = adapter.GetGeneros(); foreach(GeneroDS.GenerosRow row in table) { listaGeneros.Add(rowToDto(row)); } return listaGeneros; } private static Genero rowToDto(GeneroDS.GenerosRow row) { Genero objGeneros = new Genero(); objGeneros.id = row.id; objGeneros.nombre = row.nombre; return objGeneros; } public static void insert(string nombreGenero) { GeneroDSTableAdapters.GenerosTableAdapter adapter = new GeneroDSTableAdapters.GenerosTableAdapter(); adapter.Insert(nombreGenero); } public static void delete(int id) { GeneroDSTableAdapters.GenerosTableAdapter adapter = new GeneroDSTableAdapters.GenerosTableAdapter(); adapter.Delete(id); } public static void update(string nombreGenero, int id) { GeneroDSTableAdapters.GenerosTableAdapter adapter = new GeneroDSTableAdapters.GenerosTableAdapter(); adapter.Update(id,nombreGenero); } public static Genero getGeneroById( int id) { GeneroDSTableAdapters.GenerosTableAdapter adapter = new GeneroDSTableAdapters.GenerosTableAdapter(); GeneroDS.GenerosDataTable table = adapter.GetGeneroById(id); if(table.Rows.Count == 0) { return null; } return rowToDto(table[0]); } public static int getLibroId() { int? id = 0; GeneroLibroDSTableAdapters.GeneroLibroTableAdapter adapter = new GeneroLibroDSTableAdapters.GeneroLibroTableAdapter(); adapter.getIdLibro(ref id); return id.Value; } }<file_sep> <?php include_once './DAO/DAL/Connection.php'; include_once './DAO/DTO/accat.php'; include_once './DAO/BLL/accatBLL.php'; include_once './DAO/DTO/acjue.php'; include_once './DAO/BLL/acjueBLL.php'; ?> <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta name="description" content=""> <meta name="author" content=""> <title>Home</title> <!-- core CSS --> <link href="css/bootstrap.min.css" rel="stylesheet"> <link href="css/font-awesome.min.css" rel="stylesheet"> <link href="css/animate.min.css" rel="stylesheet"> <link href="css/prettyPhoto.css" rel="stylesheet"> <link href="css/main.css" rel="stylesheet"> <link href="css/responsive.css" rel="stylesheet"> <!--[if lt IE 9]> <script src="js/html5shiv.js"></script> <script src="js/respond.min.js"></script> <![endif]--> <link rel="shortcut icon" href="images/ico/favicon.ico"> <link rel="apple-touch-icon-precomposed" sizes="144x144" href="images/ico/apple-touch-icon-144-precomposed.png"> <link rel="apple-touch-icon-precomposed" sizes="114x114" href="images/ico/apple-touch-icon-114-precomposed.png"> <link rel="apple-touch-icon-precomposed" sizes="72x72" href="images/ico/apple-touch-icon-72-precomposed.png"> <link rel="apple-touch-icon-precomposed" href="images/ico/apple-touch-icon-57-precomposed.png"> </head> <body class="homepage"> <header id="header"> <div class="top-bar"> <div class="container"> <div class="row"> <div class="col-sm-6 col-xs-4"> <a class="navbar-brand" href="index.php"><img style="max-width: 100%; height: 50px;" src="images/svgLogo.png" alt="logo"></a> </div> <div class="col-sm-6 col-xs-8"> <div class="social"> <ul class="social-share"> <li><a href="#"><i class="fa fa-desktop" title="ADMIN"></i></a></li> </ul> <div class="search"> <form role="form"> <input type="text" class="search-form" autocomplete="off" placeholder="Search"> <i class="fa fa-search"></i> </form> </div> </div> </div> </div> </div><!--/.container--> </div><!--/.top-bar--> </header><!--/header--> <section id="services"> <div class="container"> <div class="row"> <div class="col-md-12 col-sm-12"> <div class="container"> <div class="row" style="height: 610px; text-align: center" > <div style="padding-top: 200px"> <div class="col-md-6"> <a href="categorias.php"style="padding: 0; padding: 20px 20px; " type="button" class="btn btn-primary btn-lg">GESTIONAR CATEGORIAS</a> </div> <div class="col-md-6"> <a href="juegos.php" style="padding: 0; padding: 20px 20px;" type="button" class="btn btn-primary btn-lg">GESTIONAR JUEGOS</a> </div> </div> </div></div> </div><!--/.col-md-3--> </div> </div> </section><!--/#bottom--> <footer id="footer" class="midnight-blue"> <div class="container"> <div class="row"> <div class="col-sm-6"> &copy; 2017 <a target="_blank" href="http://www.facebook.com/" title="Free Miguel Angel"><NAME></a>. All Rights Reserved. </div> <div class="col-sm-6"> <ul class="pull-right"> <li><a href="#">Home</a></li> <li><a href="#">About Us</a></li> <li><a href="#">Faq</a></li> <li><a href="#">Contact Us</a></li> </ul> </div> </div> </div> </footer><!--/#footer--> <script src="js/jquery.js"></script> <script src="js/bootstrap.min.js"></script> <script src="js/jquery.prettyPhoto.js"></script> <script src="js/jquery.isotope.min.js"></script> <script src="js/main.js"></script> <script src="js/wow.min.js"></script> </body> </html> <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Web; /// <summary> /// Summary description for Libro /// </summary> public class Libro { public Libro() { } public int libroId { get; set; } public string isbn { get; set; } public string titulo { get; set; } public string editorial { get; set; } public string ano { get; set; } public int autorId { get; set; } }<file_sep>using System; using System.Collections.Generic; using Microsoft.EntityFrameworkCore.Migrations; using Microsoft.EntityFrameworkCore.Metadata; namespace TiendaPeliculas.Migrations { public partial class addInitialCreate : Migration { protected override void Up(MigrationBuilder migrationBuilder) { migrationBuilder.CreateTable( name: "Categoria", columns: table => new { ID = table.Column<int>(nullable: false) .Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn), Nombre = table.Column<string>(nullable: true) }, constraints: table => { table.PrimaryKey("PK_Categoria", x => x.ID); }); migrationBuilder.CreateTable( name: "Pelicula", columns: table => new { ID = table.Column<int>(nullable: false) .Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn), Descripcion = table.Column<string>(nullable: true), Horario = table.Column<string>(nullable: true), Puntuacion = table.Column<int>(nullable: false), Titulo = table.Column<string>(nullable: true) }, constraints: table => { table.PrimaryKey("PK_Pelicula", x => x.ID); }); migrationBuilder.CreateTable( name: "CategoriaxLibro", columns: table => new { PeliculaID = table.Column<int>(nullable: false), CategoriaID = table.Column<int>(nullable: false) }, constraints: table => { table.PrimaryKey("PK_CategoriaxLibro", x => new { x.PeliculaID, x.CategoriaID }); table.ForeignKey( name: "FK_CategoriaxLibro_Categoria_CategoriaID", column: x => x.CategoriaID, principalTable: "Categoria", principalColumn: "ID", onDelete: ReferentialAction.Cascade); table.ForeignKey( name: "FK_CategoriaxLibro_Pelicula_PeliculaID", column: x => x.PeliculaID, principalTable: "Pelicula", principalColumn: "ID", onDelete: ReferentialAction.Cascade); }); migrationBuilder.CreateIndex( name: "IX_CategoriaxLibro_CategoriaID", table: "CategoriaxLibro", column: "CategoriaID"); } protected override void Down(MigrationBuilder migrationBuilder) { migrationBuilder.DropTable( name: "CategoriaxLibro"); migrationBuilder.DropTable( name: "Categoria"); migrationBuilder.DropTable( name: "Pelicula"); } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; public partial class FormularioAutor : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { string id = Request.QueryString["id"]; if (id != null) { Autor objautor = AutorBLL.SelectById(Convert.ToInt32(id)); if (objautor != null) { txtautor.Text = objautor.NombreAutor; hdnId.Value = objautor.AutorId.ToString(); } } } } protected void btnGuardar_Click(object sender, EventArgs e) { string autor = txtautor.Text; try { if (string.IsNullOrEmpty(hdnId.Value)) { AutorBLL.insert(autor); } else { AutorBLL.update(autor, Convert.ToInt32(hdnId.Value)); } Response.Redirect("~/ListadoAutor.aspx"); } catch (Exception ex) { } } }<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Web; using Biblioteca.App_Code.DAL; public class AutorBll { public AutorBll() { } public static List<Autor> SelectAllAutor() { List<Autor> listaAutors = new List<Autor>(); DataSet1TableAdapters.AutorTableAdapter adapter = new DataSet1TableAdapters.AutorTableAdapter(); DataSet1.AutorDataTable table = adapter.SelectAllAutor(); //DAL.AutorDS.AutorDataTable table = adapter.SelectAll(); foreach (DataSet1.AutorRow item in table) { listaAutors.Add(rowtoDto(item)); } return listaAutors; } private static Autor rowtoDto(DataSet1.AutorRow item) { Autor objAutor = new Autor(); objAutor.id = item.Id; objAutor.Nombre = item.Nombre; return objAutor; } public static void Editar(string id, string texto) { DataSet1TableAdapters.AutorTableAdapter adapter = new DataSet1TableAdapters.AutorTableAdapter(); adapter.Update(texto, Int32.Parse(id)); } public static void Insert(string texto) { DataSet1TableAdapters.AutorTableAdapter adapter = new DataSet1TableAdapters.AutorTableAdapter(); adapter.Insert(texto); } public static void eliminar(int id) { DataSet1TableAdapters.AutorTableAdapter adapter = new DataSet1TableAdapters.AutorTableAdapter(); adapter.Delete(id); } public static Autor SelectById(String id) { int id2 = Int32.Parse(id); List<Autor> listaAutors = new List<Autor>(); DataSet1TableAdapters.AutorTableAdapter adapter = new DataSet1TableAdapters.AutorTableAdapter(); DataSet1.AutorDataTable table = adapter.selectById(id2); //DAL.AutorDS.AutorDataTable table = adapter.SelectAll(); Autor Autor = null; foreach (DataSet1.AutorRow item in table) { Autor = rowtoDto(item); } return Autor; } }<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; public partial class formularioLibro : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { string id = Request.QueryString["id"]; if (id != null) { Libro objLibro = LibroBLL.SelectById(Convert.ToInt32(id)); if (objLibro != null) { txtIsbn.Text = objLibro.Isbn; txtTitulo.Text = objLibro.Titulo; txtEditorial.Text = objLibro.Editorial; txtanho.Text = Convert.ToString(objLibro.Anho); hdnId.Value = objLibro.Id.ToString(); } } } } protected void btnGuardar_Click(object sender, EventArgs e) { string isbn = txtIsbn.Text; string titulo = txtTitulo.Text; string editorial = txtEditorial.Text; string nombreAutor = cbautor.SelectedValue.ToString(); string nombreGenero = cbgenero.SelectedValue.ToString(); int anho = Convert.ToInt32(txtanho.Text); SubirImagen.SaveAs(Server.MapPath("~/image/libros/") + isbn + ".jpg"); try { if (string.IsNullOrEmpty(hdnId.Value)) { LibroBLL.Insert(isbn, titulo, editorial, anho, nombreAutor, nombreGenero); } else { LibroBLL.Update(isbn, titulo, editorial, anho, nombreAutor, nombreGenero, Convert.ToInt32(hdnId.Value)); } Response.Redirect("~/abmLibro.aspx"); } catch (Exception) { throw; } } }<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.Windows.Forms; public partial class frmGenero : System.Web.UI.Page { public Genero GeneroActual { set { ViewState["GeneroActual"] = value; } get { return (Genero)ViewState["GeneroActual"]; } } protected void Page_Load(object sender, EventArgs e) { if (IsPostBack) return; int ValorRecibido = Convert.ToInt16(Request.QueryString["id"]); if (ValorRecibido > 0) { CargarDatos(ValorRecibido); } if (GeneroActual == null) { GeneroActual = new Genero(); } } //Cargar los datos para modificarlos protected void CargarDatos(int valor) { GeneroActual = GeneroBLL.GetGeneroById(valor); //titulo.InnerText = "MODIFICACION DE DATOS EVENTO: " + EventoActual.nombre; nombre.Text = GeneroActual.nombre; btnGuardar.Text = "MODIFICAR GENERO"; } //fin de cargar DAtos para modificar //Modificar protected void ModificarGenero(int valor) { GeneroActual.nombre = nombre.Text; try { GeneroBLL.ModificarGenero(GeneroActual); //Response.Write("<script>window.confirm('Mensaje de confirmacion');</script>"); } catch (Exception ex) { MessageBox.Show("Error al guardar los datos: " + ex); return; } MessageBox.Show("Los datos fueron modificados con Exito!"); Response.Redirect("AdministracionGeneros.aspx"); } //fin modificar protected void btnBorrar_Click(object sender, EventArgs e) { } protected void btnGuardar_Click(object sender, EventArgs e) { int ValorRecibido = Convert.ToInt16(Request.QueryString["id"]); if (ValorRecibido > 0) { ModificarGenero(ValorRecibido); } else { GeneroActual.nombre = nombre.Text; try { GeneroBLL.InsertarGenero(GeneroActual); } catch (Exception ex) { return; } Response.Redirect("~/Default.aspx"); } } } <file_sep> //$("#rbAtivoInativo input").click(function () { // var select = $(this).val(); // if (select == "INATIVO") { // $("#cphConteudo_divMotivoInativacao").show(); // } else { // $('#cphConteudo_divMotivoInativacao').hide(); // } //}); $("#prueba").click(function () { if ($("#selectGratis").click()) { //$("#formulariomayores").css("display", "block"); $("#gratis").show(); $("#continuar").hide(); } if ($("#selectPago").click()) { //$("#formulariomayores").css("display", "none"); $("#continuar").show(); $("#gratis").hide(); } }); <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Web; public class AutorBLL { public AutorBLL() { } public static List<Autor> SelectAll() { List<Autor> listaAutores = new List<Autor>(); AutorDSTableAdapters.tblAutorTableAdapter adapter = new AutorDSTableAdapters.tblAutorTableAdapter(); AutorDS.tblAutorDataTable table = adapter.SelectAll(); foreach (AutorDS.tblAutorRow row in table) { listaAutores.Add(rowToDto(row)); } return listaAutores; } public static Autor SelectById(int id) { AutorDSTableAdapters.tblAutorTableAdapter adapter = new AutorDSTableAdapters.tblAutorTableAdapter(); AutorDS.tblAutorDataTable table = adapter.SelectById(id); if (table.Rows.Count == 0) { return null; } return rowToDto(table[0]); } public static void Insert(string nombre) { AutorDSTableAdapters.tblAutorTableAdapter adapter = new AutorDSTableAdapters.tblAutorTableAdapter(); adapter.Insert(nombre); } public static void Update(string nombre, int id) { AutorDSTableAdapters.tblAutorTableAdapter adapter = new AutorDSTableAdapters.tblAutorTableAdapter(); adapter.Update(nombre, id); } public static void Delete(int id) { AutorDSTableAdapters.tblAutorTableAdapter adapter = new AutorDSTableAdapters.tblAutorTableAdapter(); adapter.Delete(id); } private static Autor rowToDto(AutorDS.tblAutorRow row) { Autor objAutor = new Autor(); objAutor.Id = row.id; objAutor.Nombre = row.nombre; return objAutor; } }<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Web; /// <summary> /// Descripción breve de GeneroLibroBRL /// </summary> public class GeneroLibroBRL { public GeneroLibroBRL() { // // TODO: Agregar aquí la lógica del constructor // } public static int getLibroId() { int? id = 0; GeneroLibroDSTableAdapters.GeneroLibroTableAdapter adapter = new GeneroLibroDSTableAdapters.GeneroLibroTableAdapter(); adapter.getIdLibro(ref id); return id.Value; } public static void insert(int idLibro, int idGenero) { GeneroLibroDSTableAdapters.GeneroLibroTableAdapter adapter = new GeneroLibroDSTableAdapters.GeneroLibroTableAdapter(); adapter.Insert(idLibro, idGenero); } public static void eliminar(int idGenero) { GeneroLibroDSTableAdapters.GeneroLibroTableAdapter adapter = new GeneroLibroDSTableAdapters.GeneroLibroTableAdapter(); adapter.Delete(idGenero); } }<file_sep>copy.src.files=false copy.src.on.open=false copy.src.target=C:\\xampp\\htdocs\\PracticoJuego index.file= run.as=LOCAL url=http://localhost:8080/PracticoElectiva/ <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Web; /// <summary> /// Summary description for AutorBLL /// </summary> public class AutorBLL { public AutorBLL() { // // TODO: Add constructor logic here // } public static List<Autor> getListadoAutores() { AutorDSTableAdapters.AutoresTableAdapter adapter = new AutorDSTableAdapters.AutoresTableAdapter(); AutorDS.AutoresDataTable table = adapter.getAllAutores(); List<Autor> autores = new List<Autor>(); foreach (var row in table) { autores.Add(new Autor { autorId = row.autorId, nombre = row.nombre }); } return autores; } public static void InsertarAutor(string nombre) { AutorDSTableAdapters.AutoresTableAdapter adapter = new AutorDSTableAdapters.AutoresTableAdapter(); adapter.insertarAutor(nombre); } public static void EliminarAutor(int autorId) { AutorDSTableAdapters.AutoresTableAdapter adapter = new AutorDSTableAdapters.AutoresTableAdapter(); adapter.deleteAutor(autorId); } public static void UpdateAutor(int autorId, string nombre) { AutorDSTableAdapters.AutoresTableAdapter adapter = new AutorDSTableAdapters.AutoresTableAdapter(); adapter.updateAutores(autorId, nombre); } public static Autor getAutorById(int autorId) { AutorDSTableAdapters.AutoresTableAdapter adapter = new AutorDSTableAdapters.AutoresTableAdapter(); AutorDS.AutoresDataTable table = adapter.getAutorById(autorId); if (table.Rows.Count == 0) { return null; } return rowToDto(table[0]); } private static Autor rowToDto(AutorDS.AutoresRow row) { Autor objRol = new Autor(); objRol.autorId = row.autorId; objRol.nombre = row.nombre; return objRol; } }<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; public partial class RegistroLibros : System.Web.UI.Page { string isbn = ""; string nombreLibro = ""; string editorial = ""; string ano = ""; int autorId = 0; int idLibro = 0; protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { string id = Request.QueryString["id"]; if (id != null) { Libro obj = LibroBLL.getLibroById(Convert.ToInt32(id)); if (obj != null) { txtIsbn.Text = obj.isbn; txtNombreLibro.Text = obj.titulo; txtEditorial.Text = obj.editorial; txtAno.Text = obj.ano; AutoresDropDownList.SelectedIndex = obj.autorId; hdnId.Value = obj.libroId.ToString(); } } } } protected void btnRegistrar_Click(object sender, EventArgs e) { CapturarInformacion(); try { if (string.IsNullOrEmpty(hdnId.Value)) { if (!string.IsNullOrEmpty(isbn) && !string.IsNullOrEmpty(nombreLibro) && !string.IsNullOrEmpty(editorial) && !string.IsNullOrEmpty(ano) && autorId > 0) { int libroId = LibroBLL.insertarLibro(isbn, nombreLibro, editorial, ano, autorId); List<int> ids = new List<int>(); foreach (GridViewRow row in GenerosGridView.Rows) { if (row.RowType == DataControlRowType.DataRow) { CheckBox chk = (CheckBox)row.FindControl("ChkGenero"); if (chk.Checked) { string id = chk.Attributes["data-roleid"]; //labelPermisos.Text += id + ","; ids.Add(Convert.ToInt32(id)); GeneroBLL.insertarGeneroLibro(libroId, Convert.ToInt32(id)); } chk.Checked = false; } } } } else { idLibro = valor(Request.QueryString["id"]); LibroBLL.UpdateLibro(idLibro, isbn, nombreLibro, editorial, ano, autorId); List<int> ids = new List<int>(); foreach (GridViewRow row in GenerosGridView.Rows) { if (row.RowType == DataControlRowType.DataRow) { CheckBox chk = (CheckBox)row.FindControl("ChkGenero"); if (chk.Checked) { string id = chk.Attributes["data-roleid"]; //labelPermisos.Text += id + ","; ids.Add(Convert.ToInt32(id)); GeneroBLL.UpdateGeneroxLibro(idLibro); GeneroBLL.insertarGeneroLibro(idLibro, Convert.ToInt32(id)); } chk.Checked = false; } } } BorrarCampos(); Response.Redirect("~/AdministracionLibros.aspx"); } catch (Exception) { Response.Write("<script>window.alert('AVISO: Uno o más campos de texto no han sido llenados.')</script>"); } } public void CapturarInformacion() { isbn = txtIsbn.Text.Trim(); nombreLibro = txtNombreLibro.Text.Trim(); editorial = txtEditorial.Text.Trim(); ano = txtAno.Text.Trim(); autorId = Convert.ToInt32(AutoresDropDownList.SelectedValue); } public void BorrarCampos() { txtIsbn.Text = ""; txtNombreLibro.Text = ""; txtEditorial.Text = ""; txtAno.Text = ""; isbn = ""; nombreLibro = ""; editorial = ""; ano = ""; autorId = 0; } public int valor(string texto) { return Convert.ToInt32(texto); } }<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Web; /// <summary> /// Descripción breve de LibroBLL /// </summary> public class LibroBLL { public LibroBLL() { // // TODO: Agregar aquí la lógica del constructor // } public static int InsertarLibro(Libro obj) { if (obj == null) throw new ArgumentException("El objeto a insertar no puede ser nulo"); if (string.IsNullOrEmpty(obj.titulo)) throw new ArgumentException("El nombre no puede ser nulo o vacio"); if (string.IsNullOrEmpty(obj.editorial)) throw new ArgumentException("La descripcion no puede ser nula o vacio"); //if (string.IsNullOrEmpty(obj.edicion)) // throw new ArgumentException("La descripcion no puede ser nula o vacio"); //if (obj. < 0) // throw new ArgumentException("El celular no puede ser nulo o vacio"); int? idLibro = 0; LibroDSTableAdapters.LibroTableAdapter adapter = new LibroDSTableAdapters.LibroTableAdapter(); adapter.Insert(obj.titulo, obj.isbn, obj.editorial, obj.edicion, obj.cubierta, obj.idAutor, obj.idGenero, ref idLibro); return idLibro.Value; } public static void ModificarLibro(Libro obj) { if (obj == null) throw new ArgumentException("El objeto a modificar no puede ser nulo"); // int? personaId = obj.personaId; LibroDSTableAdapters.LibroTableAdapter adapter = new LibroDSTableAdapters.LibroTableAdapter(); adapter.Update(obj.isbn, obj.titulo, obj.editorial, obj.edicion, obj.cubierta, obj.idAutor, obj.idGenero, obj.idLibro); } public static void EliminarLibro(int id) { LibroDSTableAdapters.LibroTableAdapter adapter = new LibroDSTableAdapters.LibroTableAdapter(); adapter.Delete(id); } public static List<Libro> GetLibros() { LibroDSTableAdapters.LibroTableAdapter adapter = new LibroDSTableAdapters.LibroTableAdapter(); LibroDS.LibroDataTable table = adapter.Libros(); List<Libro> result = new List<Libro>(); foreach (var row in table) { result.Add(new Libro() { idLibro = row.idLibro, isbn = row.isbn, titulo = row.titulo, editorial = row.editorial, edicion = row.edicion, cubierta = row.cubierta, idAutor = row.idAutor, idGenero = row.idGenero }); } return result; } public static Libro GetLibroById(int idLibro) { if (idLibro <= 0) throw new ArgumentException("El id de evento no puede ser nulo ni vacio"); LibroDSTableAdapters.LibroTableAdapter adapter = new LibroDSTableAdapters.LibroTableAdapter(); LibroDS.LibroDataTable table = adapter.GetLibroById(idLibro); Libro result = null; if (table.Rows.Count == 1) { LibroDS.LibroRow row = table[0]; result = new Libro() { idLibro = row.idLibro, isbn = row.isbn, titulo = row.titulo, editorial = row.editorial, edicion = row.edicion, cubierta = row.cubierta, idAutor = row.idAutor, idGenero = row.idGenero }; } return result; } public static Libro GetLibroByAutor(int idautor) { if (idautor <= 0) throw new ArgumentException("El id de evento no puede ser nulo ni vacio"); LibroDSTableAdapters.LibroTableAdapter adapter = new LibroDSTableAdapters.LibroTableAdapter(); LibroDS.LibroDataTable table = adapter.GetLibrosByAutor(idautor); Libro result = null; if (table.Rows.Count == 1) { LibroDS.LibroRow row = table[0]; result = new Libro() { idLibro = row.idLibro, isbn = row.isbn, titulo = row.titulo, editorial = row.editorial, edicion = row.edicion, cubierta = row.cubierta, idAutor = row.idAutor, idGenero = row.idGenero }; } return result; } public static Libro GetLibroByGenero(int idgenero) { if (idgenero <= 0) throw new ArgumentException("El id de evento no puede ser nulo ni vacio"); LibroDSTableAdapters.LibroTableAdapter adapter = new LibroDSTableAdapters.LibroTableAdapter(); LibroDS.LibroDataTable table = adapter.GetLibrosByGenero(idgenero); Libro result = null; if (table.Rows.Count == 1) { LibroDS.LibroRow row = table[0]; result = new Libro() { idLibro = row.idLibro, isbn = row.isbn, titulo = row.titulo, editorial = row.editorial, edicion = row.edicion, cubierta = row.cubierta, idAutor = row.idAutor, idGenero = row.idGenero }; } return result; } public static List<Libro> GetEventoByIdToList(int idlibro) { List<Libro> e = new List<Libro>(); e.Add(GetLibroById(idlibro)); return e; } public static List<Libro> GetLibroByAutorIdToList(int idAutor) { LibroDSTableAdapters.LibroTableAdapter adapter = new LibroDSTableAdapters.LibroTableAdapter(); LibroDS.LibroDataTable table = adapter.Libros(); List<Libro> result = new List<Libro>(); foreach (var row in table) { if (row.idAutor == idAutor) { result.Add(new Libro() { idLibro = row.idLibro, isbn = row.isbn, titulo = row.titulo, editorial = row.editorial, edicion = row.edicion, cubierta = row.cubierta, idAutor = row.idAutor, idGenero = row.idGenero }); } } return result; } public static List<Libro> GetLibroByGeneroIdToList(int idGenero) { LibroDSTableAdapters.LibroTableAdapter adapter = new LibroDSTableAdapters.LibroTableAdapter(); LibroDS.LibroDataTable table = adapter.Libros(); List<Libro> result = new List<Libro>(); foreach (var row in table) { if (row.idGenero == idGenero) { result.Add(new Libro() { idLibro = row.idLibro, isbn = row.isbn, titulo = row.titulo, editorial = row.editorial, edicion = row.edicion, cubierta = row.cubierta, idAutor = row.idAutor, idGenero = row.idGenero }); } } return result; } }<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using PracticaMVC1.Context; using PracticaMVC1.Models; namespace PracticaMVC1.Controllers { public class HomeController : Controller { private readonly ProyectoPruebaContext db; public HomeController(ProyectoPruebaContext context) { db = context; } public IActionResult Index() { db.Database.EnsureCreated(); var persona = new Persona { Nombres = "Juan", Apellidos = "Perez", Ciudad = "Santa Cruz", Edad = 20 }; db.Personas.Add(persona); var telefono = new Telefono { Numero = "123456", Persona = persona, PersonaID = persona.ID }; db.Telefonos.Add(telefono); persona.Telefonos.Add(telefono); db.SaveChanges(); return View(); } public IActionResult About() { ViewData["Message"] = "Your application description page."; return View(); } public IActionResult Contact() { ViewData["Message"] = "Your contact page."; return View(); } public IActionResult Error() { return View(); } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Web; /// <summary> /// Descripción breve de GeneroBLL /// </summary> public class GeneroBLL { public GeneroBLL() { // // TODO: Agregar aquí la lógica del constructor // } public static List<Genero> SelectAll() { List<Genero> listaGeneros = new List<Genero>(); GeneroDSTableAdapters.GeneroTableAdapter adapter = new GeneroDSTableAdapters.GeneroTableAdapter(); GeneroDS.GeneroDataTable table = adapter.sp_genero_selectall(); foreach (GeneroDS.GeneroRow row in table) { listaGeneros.Add(rowToDto(row)); } return listaGeneros; } public static Genero SelectById(int id) { GeneroDSTableAdapters.GeneroTableAdapter adapter = new GeneroDSTableAdapters.GeneroTableAdapter(); GeneroDS.GeneroDataTable table = adapter.sp_genero_selectbyid(id); if (table.Rows.Count == 0) { return null; } return rowToDto(table[0]); } public static void Insert(string nombre) { GeneroDSTableAdapters.GeneroTableAdapter adapter = new GeneroDSTableAdapters.GeneroTableAdapter(); adapter.Insert(nombre); } public static void Update(string nombre, int id) { GeneroDSTableAdapters.GeneroTableAdapter adapter = new GeneroDSTableAdapters.GeneroTableAdapter(); adapter.Update(nombre, id); } public static void Delete(int id) { GeneroDSTableAdapters.GeneroTableAdapter adapter = new GeneroDSTableAdapters.GeneroTableAdapter(); adapter.Delete(id); } private static Genero rowToDto(GeneroDS.GeneroRow row) { Genero objGenero = new Genero(); objGenero.id_Genero = row.id_Genero; objGenero.nombregenero = row.nombregenero; return objGenero; } }<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; public partial class DefaultAutores : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { cargarDatos(); } protected void cargarDatos() { AutoresRepeater.DataSource = AutorBLL.GetAutores(); AutoresRepeater.DataBind(); } protected void AutoresRepeater_ItemCommand(object source, RepeaterCommandEventArgs e) { if (e.CommandName == "ComandoAutor") { string id = e.CommandArgument == null ? "0" : e.CommandArgument.ToString(); Response.Redirect("Libros.aspx?idAutor=" + id); } } }<file_sep> $(function(){ var token = $('#csrf-token').val(); $.ajaxSetup({ headers: { 'X-CSRF-Token' : token } }); $('#insertar').click(function(event) { event.preventDefault(); debugger; $.ajax({ url: $('#create').attr('action'), method: $('#create').attr('method'), data: $('#create').serialize(), dataType: 'JSON', success: function(response){ debugger; $(response).each(function (key, value) { $( "#NotasGeneral" ).append( "<div id='section-" + value.id + "' class='sections level3'> <h3> " + value.titulo + "</h3><p>" + value.nota + "</p></div>" ); }); }, error: function(){ console.log('Error'); } }); }); }); $("#search").keyup(function (event) { debugger; var value = $(this).val(); event.preventDefault(); debugger; $.ajax({ url: $('#searchs').attr('action'), method: $('#searchs').attr('method'), data: {value : value}, dataType: 'JSON', success: function(response){ $('#NotasGeneral').empty(); if(response==""){ $('#NotasGeneral').empty(); }else{ $(response).each(function (key, values) { $( "#NotasGeneral" ).append( "<div id='section-" + values.id + "' class='sections level3'> <h3> " + values.titulo + "</h3><p>" + values.nota + "</p></div>" ); }); } }, error: function(){ console.log('Error'); } }); });<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; public partial class Pages_LibroABM : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { } protected void btnImagen_Click(object sender, EventArgs e) { } protected void btnGuardar_Click(object sender, EventArgs e) { Libro libro = new Libro { Titulo = txtTitulo.Text, Editorial = txtEditorial.Text, ISBN = txtIsbn.Text, año = Convert.ToInt32(txtAño.Text), Autor_id = Convert.ToInt32(cmbAutores.SelectedValue), Genero_id = Convert.ToInt32(cmbGenero.SelectedValue) }; try { LibroBLL.insert(libro); Imagen.SaveAs(Server.MapPath("~/img/") + libro.ISBN + ".jpg"); Response.Redirect("~/pages/Principal.aspx"); } catch (Exception Ex) { } } }<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.Rendering; using Microsoft.EntityFrameworkCore; using VentaDePeliculas.Context; using VentaDePeliculas.Models; namespace VentaDePeliculas.Controllers { public class GeneroPeliculasController : Controller { private readonly ProyectoPruebaContext _context; public GeneroPeliculasController(ProyectoPruebaContext context) { _context = context; } // GET: GeneroPeliculas public async Task<IActionResult> Index() { var proyectoPruebaContext = _context.GeneroPeliculas.Include(g => g.Genero).Include(g => g.Pelicula); return View(await proyectoPruebaContext.ToListAsync()); } // GET: GeneroPeliculas/Details/5 public async Task<IActionResult> Details(int? id) { if (id == null) { return NotFound(); } var generoPelicula = await _context.GeneroPeliculas .Include(g => g.Genero) .Include(g => g.Pelicula) .SingleOrDefaultAsync(m => m.ID == id); if (generoPelicula == null) { return NotFound(); } return View(generoPelicula); } // GET: GeneroPeliculas/Create public IActionResult Create() { ViewData["GeneroID"] = new SelectList(_context.Generos, "ID", "Nombre"); ViewData["PeliculaID"] = new SelectList(_context.Peliculas, "ID", "Nombre"); return View(); } // POST: GeneroPeliculas/Create // To protect from overposting attacks, please enable the specific properties you want to bind to, for // more details see http://go.microsoft.com/fwlink/?LinkId=317598. [HttpPost] [ValidateAntiForgeryToken] public async Task<IActionResult> Create([Bind("ID,GeneroID,PeliculaID")] GeneroPelicula generoPelicula) { if (ModelState.IsValid) { _context.Add(generoPelicula); await _context.SaveChangesAsync(); return RedirectToAction("Index"); } ViewData["GeneroID"] = new SelectList(_context.Generos, "ID", "ID", generoPelicula.GeneroID); ViewData["PeliculaID"] = new SelectList(_context.Peliculas, "ID", "ID", generoPelicula.PeliculaID); return View(generoPelicula); } // GET: GeneroPeliculas/Edit/5 public async Task<IActionResult> Edit(int? id) { if (id == null) { return NotFound(); } var generoPelicula = await _context.GeneroPeliculas.SingleOrDefaultAsync(m => m.ID == id); if (generoPelicula == null) { return NotFound(); } ViewData["GeneroID"] = new SelectList(_context.Generos, "ID", "Nombre", generoPelicula.GeneroID); ViewData["PeliculaID"] = new SelectList(_context.Peliculas, "ID", "Nombre", generoPelicula.PeliculaID); return View(generoPelicula); } // POST: GeneroPeliculas/Edit/5 // To protect from overposting attacks, please enable the specific properties you want to bind to, for // more details see http://go.microsoft.com/fwlink/?LinkId=317598. [HttpPost] [ValidateAntiForgeryToken] public async Task<IActionResult> Edit(int id, [Bind("ID,GeneroID,PeliculaID")] GeneroPelicula generoPelicula) { if (id != generoPelicula.ID) { return NotFound(); } if (ModelState.IsValid) { try { _context.Update(generoPelicula); await _context.SaveChangesAsync(); } catch (DbUpdateConcurrencyException) { if (!GeneroPeliculaExists(generoPelicula.ID)) { return NotFound(); } else { throw; } } return RedirectToAction("Index"); } ViewData["GeneroID"] = new SelectList(_context.Generos, "ID", "ID", generoPelicula.GeneroID); ViewData["PeliculaID"] = new SelectList(_context.Peliculas, "ID", "ID", generoPelicula.PeliculaID); return View(generoPelicula); } // GET: GeneroPeliculas/Delete/5 public async Task<IActionResult> Delete(int? id) { if (id == null) { return NotFound(); } var generoPelicula = await _context.GeneroPeliculas .Include(g => g.Genero) .Include(g => g.Pelicula) .SingleOrDefaultAsync(m => m.ID == id); if (generoPelicula == null) { return NotFound(); } return View(generoPelicula); } // POST: GeneroPeliculas/Delete/5 [HttpPost, ActionName("Delete")] [ValidateAntiForgeryToken] public async Task<IActionResult> DeleteConfirmed(int id) { var generoPelicula = await _context.GeneroPeliculas.SingleOrDefaultAsync(m => m.ID == id); _context.GeneroPeliculas.Remove(generoPelicula); await _context.SaveChangesAsync(); return RedirectToAction("Index"); } private bool GeneroPeliculaExists(int id) { return _context.GeneroPeliculas.Any(e => e.ID == id); } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; public partial class AdministracionLibros : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { Repeater1.DataSource = LibroBLL.GetLibros(); Repeater1.DataBind(); } protected void Repeater1_ItemCommand(object source, RepeaterCommandEventArgs e) { if (e.CommandName == "Eliminar") { int id = e.CommandArgument == null ? 0 : Convert.ToInt32(e.CommandArgument); LibroBLL.EliminarLibro(id); Repeater1.DataSource = LibroBLL.GetLibros(); Repeater1.DataBind(); } if (e.CommandName == "Editar") { string id = e.CommandArgument == null ? "0" : e.CommandArgument.ToString(); Response.Redirect("frmRegistroLibro.aspx?id=" + id); } } }<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace PracticaMVC1.Models { public class Comida { public int ID { get; set; } public string Nombre { get; set; } public decimal Precio { get; set; } public DateTime FechaVencimiento { get; set; } public int PersonaID { get; set; } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; public partial class Login : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { } protected void btnLogin_Click(object sender, EventArgs e) { string usuario = txtUsuario.Text; string password = TextUtilities.Hash(txtPassword.Text); Usuario objUsuarioAutenticado = UsuarioBLL.SelectByLogin(usuario, password); if (objUsuarioAutenticado == null) { //TODO: Mostrar error return; } Session["varUsuario"] = objUsuarioAutenticado.ID; Response.Redirect("~/Default.aspx"); } }<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Web; /// <summary> /// Descripción breve de AutorBLL /// </summary> public class AutorBLL { public AutorBLL() {} public static List<Autor> getAutores() { List<Autor> lista = new List<Autor>(); AutorDSTableAdapters.AutorTableAdapter adapter = new AutorDSTableAdapters.AutorTableAdapter(); AutorDS.AutorDataTable table = adapter.GetAutores(); foreach (AutorDS.AutorRow row in table) { lista.Add(rowToDto(row)); } return lista; } public static Autor getAutorById(int id) { AutorDSTableAdapters.AutorTableAdapter adapter = new AutorDSTableAdapters.AutorTableAdapter(); AutorDS.AutorDataTable table = adapter.GetAutoresById(id); if (table.Rows.Count == 0) return null; return rowToDto(table[0]); } public static void insert(Autor objAutor) { AutorDSTableAdapters.AutorTableAdapter adapter = new AutorDSTableAdapters.AutorTableAdapter(); adapter.Insert(objAutor.nombre); } public static void delete(int id) { AutorDSTableAdapters.AutorTableAdapter adapter = new AutorDSTableAdapters.AutorTableAdapter(); adapter.Delete(id); } public static void update(Autor objAutor) { AutorDSTableAdapters.AutorTableAdapter adapter = new AutorDSTableAdapters.AutorTableAdapter(); adapter.Update(objAutor.nombre, objAutor.Codigo_id); } public static Autor getIdByAutor(string nombre) { AutorDSTableAdapters.AutorTableAdapter adapter = new AutorDSTableAdapters.AutorTableAdapter(); AutorDS.AutorDataTable table = adapter.GetIdAutorByNombre(nombre); if (table.Rows.Count == 0) return null; return rowToDto(table[0]); } private static Autor rowToDto(AutorDS.AutorRow row) { Autor objAautor = new Autor { Codigo_id = row.codigo_id, nombre = row.nombre }; return objAautor; } }<file_sep><?php namespace App\Http\Controllers; use Illuminate\Http\Request; class PruebaController extends Controller { public function traerHolaMundo(){ return "Hola Mundo"; } public function verPrueba(){ return view('pruebaajax'); } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; public partial class _Default : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { cargarDatos(); } protected void cargarDatos() { GenerosRepeater.DataSource = GeneroBLL.GetGeneros(); GenerosRepeater.DataBind(); } protected void GenerosRepeater_ItemCommand(object source, RepeaterCommandEventArgs e) { if (e.CommandName == "ComandoGenero") { string id = e.CommandArgument == null ? "0" : e.CommandArgument.ToString(); Response.Redirect("Libros.aspx?idGenero=" + id); } } }<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Web; /// <summary> /// Descripción breve de GeneroLibroBLL /// </summary> public class GeneroLibroBLL { public GeneroLibroBLL() { // // TODO: Agregar aquí la lógica del constructor // } public static void insert(int idLibro, int idGnero) { GeneroLibroTableAdapters.GeneroLibroTableAdapter adapter = new GeneroLibroTableAdapters.GeneroLibroTableAdapter(); adapter.Insert(idLibro, idGnero); } public static void delete(int idLibro) { GeneroLibroTableAdapters.GeneroLibroTableAdapter adapter = new GeneroLibroTableAdapters.GeneroLibroTableAdapter(); adapter.SP_GENEROLIBRO_DELETE (idLibro); } public static void deleteGeneral(int idLibro, int idGnero) { GeneroLibroTableAdapters.GeneroLibroTableAdapter adapter = new GeneroLibroTableAdapters.GeneroLibroTableAdapter(); adapter.SP_GENEROLIGRO_DELETEGENERAL(idLibro, idGnero); } }<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Web; /// <summary> /// Descripción breve de AutorBRL /// </summary> public class AutorBRL { public AutorBRL() { // // TODO: Agregar aquí la lógica del constructor // } public static List<Autor> GetAutor() { List<Autor> listaAutor = new List<Autor>(); AutorDSTableAdapters.AutorTableAdapter adapter = new AutorDSTableAdapters.AutorTableAdapter(); AutorDS.AutorDataTable table = adapter.GetAutor(); foreach (AutorDS.AutorRow row in table) { listaAutor.Add(rowToDto(row)); } return listaAutor; } private static Autor rowToDto(AutorDS.AutorRow row) { Autor objAutor = new Autor(); objAutor.id = row.id; objAutor.nombre = row.nombre; return objAutor; } public static void insert(string nombreAutor) { AutorDSTableAdapters.AutorTableAdapter adapter = new AutorDSTableAdapters.AutorTableAdapter(); adapter.Insert(nombreAutor); } public static void delete(int idAutor) { AutorDSTableAdapters.AutorTableAdapter adapter = new AutorDSTableAdapters.AutorTableAdapter(); adapter.Delete(idAutor); } public static string GetNombreAutor(int id) { string nombre = "nombre"; AutorDSTableAdapters.AutorTableAdapter adapter = new AutorDSTableAdapters.AutorTableAdapter(); nombre = adapter.GetNombreAutor(id).ToString(); return nombre; } public static int getLibroId() { int? id = 0; GeneroLibroDSTableAdapters.GeneroLibroTableAdapter adapter = new GeneroLibroDSTableAdapters.GeneroLibroTableAdapter(); adapter.getIdLibro(ref id); return id.Value; } }<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; public partial class EditarAutor : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { if (IsPostBack) return; String id = Request.QueryString["idAutor"]; if (id != null) { // ; Autor autor = AutorBll.SelectById(id); txtNombre.Value = autor.Nombre; idH3.InnerText = "Id Autor: " + id; } } protected void btnEditar_Click(object sender, EventArgs e) { } protected void btnAceptar_Click(object sender, EventArgs e) { String id = Request.QueryString["idAutor"]; if (id != null) { String texto = txtNombre.Value; AutorBll.Editar(id, texto); Response.Redirect("home.aspx"); } else { String texto = txtNombre.Value; AutorBll.Insert(texto); Response.Redirect("home.aspx"); } // Editar Autor //AutorBll.EditarAutor() } }<file_sep><?php include_once './DAO/DAL/Connection.php'; include_once './DAO/DTO/Juego.php'; include_once './DAO/BLL/JuegoBLL.php'; $JuegoBLL = new JuegoBLL(); ?> <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <meta name="description" content=""> <meta name="author" content=""> <title>Segundo Practico - <NAME></title> <!-- Bootstrap core CSS --> <link href="vendor/bootstrap/css/bootstrap.min.css" rel="stylesheet"> <link href="vendor/bootstrap/css/personalizado.css" rel="stylesheet"> <!-- Custom styles for this template --> <link href="css/shop-homepage.css" rel="stylesheet"> </head> <body class='bg-fondo123'> <!-- Navigation --> <div class="navbar navbar-expand-lg navbar-dark bg-dark fixed-top"> <div class="container logo"> <p> <img src="img/sony.png"/> </p> </div> </div> <hr> <div class="navbar navbar-expand-lg navbar-dark bg-play"> <div class="container"> <img src="img/logo.png"/> </div> </div> <hr> <nav class="navbar navbar-expand-lg navbar-dark bg-play2"> <div class="container"> <div class="collapse navbar-collapse" id="navbarResponsive"> <ul class="nav nav-pills"> <li role="presentacion" style="margin-right: 25px;"> <span style="color: white">Exclusivamente para tí </span> </li> <li role="presentation" class="dropdown"> <a style="color:whitesmoke" class="dropdown-toggle" data-toggle="dropdown" href="#" role="button" aria-haspopup="true" aria-expanded="false"> Categoria 1 <span class="caret"></span> </a> <ul class="dropdown-menu "> <li><a href="#">Clase1</a></li> </ul> </li> <li role="presentation" class="dropdown"> <a style="color:whitesmoke" class="dropdown-toggle" data-toggle="dropdown" href="#" role="button" aria-haspopup="true" aria-expanded="false"> Categoria 2 <span class="caret"></span> </a> <ul class="dropdown-menu"> <li><a href="#">Clase1</a></li> </ul> </li> <li role="presentation" class="dropdown"> <a style="color:whitesmoke" class="dropdown-toggle" data-toggle="dropdown" href="#" role="button" aria-haspopup="true" aria-expanded="false"> Categoria 3 <span class="caret"></span> </a> <ul class="dropdown-menu"> <li><a href="#">Clase1</a></li> </ul> </li> <li role="presentation" class="dropdown"> <a style="color:whitesmoke" class="dropdown-toggle" data-toggle="dropdown" href="#" role="button" aria-haspopup="true" aria-expanded="false"> Categoria 4 <span class="caret"></span> </a> <ul class="dropdown-menu"> <li><a href="#">Clase1</a></li> </ul> </li> </ul> </div> </div> </nav> <!-- Page Content --> <div class="container bg-contenido"> <div class='panel-heading' style="padding-bottom: 25px; padding-top: 25px; background-color: #001740; margin-top: 20px; "> <h1 style="color: #ffffff; margin-left: 20px">Juegos</h1> </div> <div class="row"> <div class="col-lg-3"> <div class="list-group"> <a href="#" class="list-group-item" style="color: white">Category 1</a> <a href="#" class="list-group-item" style="color: white">Category 2</a> <a href="#" class="list-group-item" style="color: white">Category 3</a> <a href="#" class="list-group-item" style="color: white">Category 4</a> </div> </div> <!-- /.col-lg-3 --> <div class="col-lg-9"> <div class="row"> <?php $listaJuegos = $JuegoBLL->selectAll(); foreach ($listaJuegos as $objJuegos) { ?> <div class="col-lg-4 col-md-6 mb-4"> <div class="card h-100"> <a href="#"><img class="card-img-top" src="<?php echo $objJuegos->getImagen(); ?>" alt=""></a> <div class="card-body"> <h4 class="card-title"> <a href="#"><?php echo $objJuegos->getNombre(); ?></a> </h4> <h5>.$<?php echo $objJuegos->getPrecio(); ?></h5> <p class="card-text" style="overflow:hidden;white-space:nowrap;text-overflow:ellipsis;"><?php echo $objJuegos->getDescripcion(); ?></p> </div> <div class="card-footer"> <small class="text-muted">&#9733; &#9733; &#9733; &#9733; &#9734;</small> </div> </div> </div> <?php } ?> <div class="col-lg-4 col-md-6 mb-4"> <div class="card h-100"> <a href="#"><img class="card-img-top" src="http://placehold.it/700x400" alt=""></a> <div class="card-body"> <h4 class="card-title"> <a href="#">Item Two</a> </h4> <h5>$24.99</h5> <p class="card-text">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Amet numquam aspernatur! Lorem ipsum dolor sit amet.</p> </div> <div class="card-footer"> <small class="text-muted">&#9733; &#9733; &#9733; &#9733; &#9734;</small> </div> </div> </div> <div class="col-lg-4 col-md-6 mb-4"> <div class="card h-100"> <a href="#"><img class="card-img-top" src="http://placehold.it/700x400" alt=""></a> <div class="card-body"> <h4 class="card-title"> <a href="#">Item Three</a> </h4> <h5>$24.99</h5> <p class="card-text">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Amet numquam aspernatur!</p> </div> <div class="card-footer"> <small class="text-muted">&#9733; &#9733; &#9733; &#9733; &#9734;</small> </div> </div> </div> <div class="col-lg-4 col-md-6 mb-4"> <div class="card h-100"> <a href="#"><img class="card-img-top" src="http://placehold.it/700x400" alt=""></a> <div class="card-body"> <h4 class="card-title"> <a href="#">Item Four</a> </h4> <h5>$24.99</h5> <p class="card-text">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Amet numquam aspernatur!</p> </div> <div class="card-footer"> <small class="text-muted">&#9733; &#9733; &#9733; &#9733; &#9734;</small> </div> </div> </div> <div class="col-lg-4 col-md-6 mb-4"> <div class="card h-100"> <a href="#"><img class="card-img-top" src="http://placehold.it/700x400" alt=""></a> <div class="card-body"> <h4 class="card-title"> <a href="#">Item Five</a> </h4> <h5>$24.99</h5> <p class="card-text">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Amet numquam aspernatur! Lorem ipsum dolor sit amet.</p> </div> <div class="card-footer"> <small class="text-muted">&#9733; &#9733; &#9733; &#9733; &#9734;</small> </div> </div> </div> <div class="col-lg-4 col-md-6 mb-4"> <div class="card h-100"> <a href="#"><img class="card-img-top" src="http://placehold.it/700x400" alt=""></a> <div class="card-body"> <h4 class="card-title"> <a href="#">Item Six</a> </h4> <h5>$24.99</h5> <p class="card-text">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Amet numquam aspernatur!</p> </div> <div class="card-footer"> <small class="text-muted">&#9733; &#9733; &#9733; &#9733; &#9734;</small> </div> </div> </div> </div> <!-- /.row --> </div> <!-- /.col-lg-9 --> </div> <!-- /.row --> </div> <!-- /.container --> <!-- Footer --> <footer class="py-5 bg-dark"> <div class="container"> <p class="m-0 text-center text-white">Copyright &copy; Your Website 2017</p> </div> <!-- /.container --> </footer> <!-- Bootstrap core JavaScript --> <script src="vendor/jquery/jquery.min.js"></script> <script src="vendor/popper/popper.min.js"></script> <script src="vendor/bootstrap/js/bootstrap.min.js"></script> </body> </html> <file_sep>-- phpMyAdmin SQL Dump -- version 4.5.1 -- http://www.phpmyadmin.net -- -- Servidor: 127.0.0.1 -- Tiempo de generación: 30-08-2017 a las 15:29:41 -- Versión del servidor: 10.1.9-MariaDB -- Versión de PHP: 5.6.15 SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO"; SET time_zone = "+00:00"; /*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */; /*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */; /*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */; /*!40101 SET NAMES utf8mb4 */; -- -- Base de datos: `practicadao1` -- DELIMITER $$ -- -- Procedimientos -- CREATE DEFINER=`root`@`localhost` PROCEDURE `sp_Persona_Delete` (IN `p_id` INT) NO SQL DELETE FROM Persona WHERE id = p_id$$ CREATE DEFINER=`root`@`localhost` PROCEDURE `sp_Persona_Insert` (IN `p_nombre` VARCHAR(200), IN `p_apellido` VARCHAR(200), IN `p_ciudad` VARCHAR(200), IN `p_edad` INT) NO SQL INSERT INTO Persona(nombre,apellido,ciudad,edad) VALUES (p_nombre, p_apellido, p_ciudad, p_edad)$$ CREATE DEFINER=`root`@`localhost` PROCEDURE `sp_Persona_SelectAll` () NO SQL SELECT id, nombre, apellido, ciudad, edad FROM Persona$$ CREATE DEFINER=`root`@`localhost` PROCEDURE `sp_Persona_SelectById` (IN `p_id` INT) NO SQL SELECT id, nombre, apellido, ciudad, edad FROM Persona WHERE id = p_id$$ CREATE DEFINER=`root`@`localhost` PROCEDURE `sp_Persona_Update` (IN `p_nombre` VARCHAR(200), IN `p_apellido` VARCHAR(200), IN `p_ciudad` VARCHAR(200), IN `p_edad` INT, IN `p_id` INT) NO SQL UPDATE Persona SET nombre = p_nombre, apellido = p_apellido, ciudad = p_ciudad, edad = p_edad WHERE id = p_id$$ DELIMITER ; -- -------------------------------------------------------- -- -- Estructura de tabla para la tabla `Persona` -- CREATE TABLE `Persona` ( `id` int(11) NOT NULL, `nombre` varchar(200) NOT NULL, `apellido` varchar(200) NOT NULL, `ciudad` varchar(200) NOT NULL, `edad` int(11) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Volcado de datos para la tabla `Persona` -- INSERT INTO `Persona` (`id`, `nombre`, `apellido`, `ciudad`, `edad`) VALUES (3, 'Juan', 'Perez', 'SCZ', 20), (5, 'Jose', 'Alvarez', 'Santa Cruz', 27), (6, 'Ulises', 'Macedo', 'Santa Cruz', 22), (7, 'Ulises', 'Macedo', 'Santa Cruz', 28), (12, 'Juan', 'asd', 'asdas', 12), (13, 'Juanito', 'Perezito', 'Santacruzito', 23); -- -- Índices para tablas volcadas -- -- -- Indices de la tabla `Persona` -- ALTER TABLE `Persona` ADD PRIMARY KEY (`id`); -- -- AUTO_INCREMENT de las tablas volcadas -- -- -- AUTO_INCREMENT de la tabla `Persona` -- ALTER TABLE `Persona` MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=15; /*!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>using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; public partial class formularioGenero : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { if (!IsPostBack) { string id = Request.QueryString["id"]; if (id != null) { Genero objgenero = GeneroBLL.SelectById(Convert.ToInt32(id)); if (objgenero != null) { generotxt.Text = objgenero.nombregenero; hdnId.Value = objgenero.id_Genero.ToString(); } } } } } protected void btnGuardar_Click(object sender, EventArgs e) { string genero = generotxt.Text; try { if (string.IsNullOrEmpty(hdnId.Value)) { GeneroBLL.Insert(genero); } else { GeneroBLL.Update(genero, Convert.ToInt32(hdnId.Value)); } Response.Redirect("~/listaGenero.aspx"); } catch (Exception ex) { } } }<file_sep><?php include_once './DAO/DAL/Connection.php'; include_once './DAO/DTO/Persona.php'; include_once './DAO/BLL/PersonaBLL.php'; $personaBLL = new PersonaBLL(); $id = 0; $objPersona = null; if (isset($_REQUEST["id"])) { $id = $_REQUEST["id"]; $objPersona = $personaBLL->select($id); } ?> <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Datos de Persona</title> <link href="css/bootstrap.min.css" rel="stylesheet" type="text/css"/> <link href="css/bootstrap-theme.min.css" rel="stylesheet" type="text/css"/> <script src="js/bootstrap.min.js" type="text/javascript"></script> </head> <body> <div class="container"> <div class="row"> <div class="col-md-6"> <h2> Datos de Persona </h2> <form action="index.php" method="POST"> <input type="hidden" value="<?php if ($objPersona != null) { echo "actualizar"; } else { echo "insertar"; } ?>" name="tarea"/> <input type="hidden" value="<?php echo $id; ?>" name="id"/> <div class="form-group"> <label> Nombre: </label> <input class="form-control" required="required" type="text" name="nombre" value="<?php if ($objPersona != null) { echo $objPersona->getNombre(); } ?>"/> </div> <div class="form-group"> <label> Apellido: </label> <input class="form-control" required="required" type="text" name="apellido" value="<?php if ($objPersona != null) { echo $objPersona->getApellido(); } ?>"/> </div> <div class="form-group"> <label> Ciudad: </label> <input class="form-control" type="text" name="ciudad" required="required" value="<?php if ($objPersona != null) { echo $objPersona->getCiudad(); } ?>"/> </div> <div class="form-group"> <label> Edad: </label> <input class="form-control" type="number" name="edad" value="<?php if ($objPersona != null) { echo $objPersona->getEdad(); } ?>" required="required"/> </div> <div class="form-group"> <input class="btn btn-primary" type="submit" value="Guardar datos" /> <a href="index.php" class="btn btn-link">Cancelar</a> </div> </form> </div> </div> </div> </body> </html> <file_sep><?php /** * Description of CategoriaJuego * * @author ANDREA_ORTIZ */ class CategoriaJuego { private $id; private $idJuego; private $idCategoria; function getId() { return $this->id; } function getIdJuego() { return $this->idJuego; } function getIdCategoria() { return $this->idCategoria; } function setId($id) { $this->id = $id; } function setIdJuego($idJuego) { $this->idJuego = $idJuego; } function setIdCategoria($idCategoria) { $this->idCategoria = $idCategoria; } } <file_sep><?php namespace App\Http\Controllers; use App\Nota; use Illuminate\Http\Request; class NotaController extends Controller { /** * Display a listing of the resource. * * @return \Illuminate\Http\Response */ function __construct(array $attributes = []) { } public function index() { $listaNotas = Nota::all()->toArray(); return view('Notas.principal', compact('listaNotas')); } /** * Show the form for creating a new resource. * * @return \Illuminate\Http\Response */ public function create() { // } /** * Store a newly created resource in storage. * * @param \Illuminate\Http\Request $request * @return \Illuminate\Http\Response */ public function store(Request $request) { $objNota = new Nota(); $objNota->titulo = $request->post('titulo'); $objNota->contenido = $request->post('contenido'); $objNota->save(); return redirect('/Notas/principal'); } /** * Display the specified resource. * * @param \App\Nota $nota * @return \Illuminate\Http\Response */ public function show(Nota $nota) { // } /** * Show the form for editing the specified resource. * * @param \App\Nota $nota * @return \Illuminate\Http\Response */ public function edit($id) { $objNotaEditar = Nota::find($id); return view('Notas.principal', compact('objNotaEditar', 'id')); } /** * Update the specified resource in storage. * * @param \Illuminate\Http\Request $request * @param \App\Nota $nota * @return \Illuminate\Http\Response */ public function update(Request $request) { $objNota = new Nota(); $idNota = $request->post('id_nota'); $objNota = Nota::find($idNota); $objNota->titulo = $request->post('titulo'); $objNota->contenido = $request->post('contenido'); $objNota->save(); return redirect('/Notas/principal'); } /** * Remove the specified resource from storage. * * @param \App\Nota $nota * @return \Illuminate\Http\Response */ public function destroy($id) { $objNota = Nota::find($id); $objNota->delete(); return redirect('/Notas/principal'); } public function traerNotasAjax(){ $listaNotas = Nota::all()->toArray(); return $listaNotas; } public function traerNotaById($id) { $objNota = Nota::find($id); return $objNota; } public function traerNotasByParameter($parametro){ $listaNotas = Nota::where('contenido','like', '%' . $parametro. '%' )->get()->toArray(); return $listaNotas; } } <file_sep> <?php include_once './DAO/DAL/Connection.php'; include_once './DAO/DTO/accat.php'; include_once './DAO/BLL/accatBLL.php'; include_once './DAO/DTO/acjue.php'; include_once './DAO/BLL/acjueBLL.php'; ?> <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta name="description" content=""> <meta name="author" content=""> <title>Home</title> <!-- core CSS --> <link href="css/bootstrap.min.css" rel="stylesheet"> <link href="css/font-awesome.min.css" rel="stylesheet"> <link href="css/animate.min.css" rel="stylesheet"> <link href="css/prettyPhoto.css" rel="stylesheet"> <link href="css/main.css" rel="stylesheet"> <link href="css/responsive.css" rel="stylesheet"> <!--[if lt IE 9]> <script src="js/html5shiv.js"></script> <script src="js/respond.min.js"></script> <![endif]--> <link rel="shortcut icon" href="images/ico/favicon.ico"> <link rel="apple-touch-icon-precomposed" sizes="144x144" href="images/ico/apple-touch-icon-144-precomposed.png"> <link rel="apple-touch-icon-precomposed" sizes="114x114" href="images/ico/apple-touch-icon-114-precomposed.png"> <link rel="apple-touch-icon-precomposed" sizes="72x72" href="images/ico/apple-touch-icon-72-precomposed.png"> <link rel="apple-touch-icon-precomposed" href="images/ico/apple-touch-icon-57-precomposed.png"> <style> .menuTitle{ border-bottom: 1px solid rgba(255,255,255,255.5); } .menuTitle{ display: block; float: none; font-size: 16px; line-height: 18px; font-family: OpenSansMedium !important; padding-bottom: 6px; margin-bottom: 10px; } .row-flex, .row-flex > a{ display: -webkit-box; display: -moz-box; display: -ms-flexbox; display: -webkit-flex; display: flex; } .row-flex, .row-flex > a > div[class*='col-'] { display: -webkit-box; display: -moz-box; display: -ms-flexbox; display: -webkit-flex; display: flex; } .row-flex-wrap { -webkit-flex-flow: row wrap; align-content: flex-start; flex:0; } .info2:hover { -webkit-transition: border-color .2s linear; -moz-transition: border-color .2s linear; -o-transition: border-color .2s linear; -ms-transition: border-color .2s linear; transition: border-color .2s linear; border-color: white; } .info2 { -moz-border-radius: 2px; -webkit-border-radius: 2px; border-radius: 2px; border: 4px solid #000; border: 4px solid transparent; -webkit-transition: border-color .2s linear; -moz-transition: border-color .2s linear; -o-transition: border-color .2s linear; -ms-transition: border-color .2s linear; transition: border-color .2s linear; } .info h4{ color:#bfbfbf; text-align: center; } .info img{ width: 100%; } .gameStore{ width: 100%; margin: 20px 0 10px 0; } .price { background-color: rgba(255,255,255,0.07); color:#bfbfbf; text-align: center; } .services > container-flex > a > div[class*='col-'] div,.row-flex > div[class*='col-'] div { width:100%; } .flex-col { display: flex; display: -webkit-flex; flex: 1 100%; flex-flow: column nowrap; } .flex-grow { display: flex; -webkit-flex: 2; flex: 2; } </style> </head> <body class="homepage"> <header id="header"> <div class="top-bar"> <div class="container"> <div class="row"> <div class="col-sm-6 col-xs-4"> <a class="navbar-brand" href="index.php"><img style="max-width: 100%; height: 50px;" src="images/svgLogo.png" alt="logo"></a> </div> <div class="col-sm-6 col-xs-8"> <div class="social"> <ul class="social-share"> <li><a href="admin.php"><i class="fa fa-desktop" title="ADMIN"></i></a></li> </ul> <div class="search"> <form role="form"> <input type="text" class="search-form" autocomplete="off" placeholder="Search"> <i class="fa fa-search"></i> </form> </div> </div> </div> </div> </div><!--/.container--> </div><!--/.top-bar--> <nav class="navbar navbar-inverse" role="banner"> <div class="container"> <div class="navbar-header"> <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse"> <span class="sr-only">Toggle navigation</span> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> </div> <div class="collapse navbar-collapse"> <ul class="nav navbar-nav"> <?php $personaBLL = new accatBLL(); ?> <?php $res = $personaBLL->selectAccatPad(); foreach ($res as $r) { ?> <?php $ress = $personaBLL->selectAccatPads($r->getAccatCcat()); ?> <?php $cont = 0; foreach ($ress as $rrr) { $cont++; } ?> <?php if ($cont <= 0) { ?><li><a href=""><?php echo $r->getAccatNomb(); ?></a></li> <?php } else { ?> <li class="dropdown"> <a href="" class="dropdown-toggle" data-toggle="dropdown"><?php echo $r->getAccatNomb(); ?> <i class="fa fa-angle-down"></i></a> <ul class="dropdown-menu"> <?php foreach ($ress as $rr) { ?><li><a href="index.php?accatCcat=<?php echo $rr->getAccatCcat()?>"><?php echo $rr->getAccatNomb(); ?></a></li> <?php } ?> </ul> </li> <?php } } ?></ul> </div> </div><!--/.container--> </nav><!--/nav--> </header><!--/header--> <section id="services"> <div class="container"> <div class="row"> <div class="col-md-2 col-sm-4"> <div class="widget"> <?php foreach ($res as $r) { ?> <h2 class="menuTitle"><?php echo $r->getAccatNomb(); ?></h2> <ul > <?php $ressss = $personaBLL->selectAccatPads($r->getAccatCcat()); // echo $responce = json_encode($ress, TRUE); // $rows = json_decode($responce, TRUE); foreach ($ressss as $output) { ?> <li><a href="index.php?accatCcat=<?php echo $output->getAccatCcat() ?>"><?php echo $output->getAccatNomb() ?></a></li> <?php } ?> </ul> <?php } ?> </div> </div><!--/.col-md-3--> <div class="col-md-10 col-sm-8"> <div class="container"> <div class="row-flex row-flex-wrap"> <?php $juegosBLL = new acjueBLL(); if (!isset($_REQUEST['accatCcat'])) { $resJuegos = $juegosBLL->selectAll(); } else { $accatCcat = $_REQUEST['accatCcat']; $resJuegos = $juegosBLL->selectAllbyCat($accatCcat); } ?> <?php foreach ($resJuegos as $key) { ?> <a href="juego.php?acjueCjue=<?php echo $key->getAcjueJjue()?>"> <div class="col-md-2 gameStore"> <div class="info"> <div class="info2" > <img src="images/image2.jpg" > <h4><?php echo $key->getAcjueNomb(); ?></h4> <div class="price"> <label><?php echo $key->getAcjuePrec() . " BS"; ?> </label> </div> </div> </div> </div> </a> <?php } ?> </div></div> </div><!--/.col-md-3--> </div> </div> </section><!--/#bottom--> <footer id="footer" class="midnight-blue"> <div class="container"> <div class="row"> <div class="col-sm-6"> &copy; 2017 <a target="_blank" href="http://www.facebook.com/" title="Free Miguel Angel">Miguel Angel</a>. All Rights Reserved. </div> </div> </div> </footer><!--/#footer--> <script src="js/jquery.js"></script> <script src="js/bootstrap.min.js"></script> <script src="js/jquery.prettyPhoto.js"></script> <script src="js/jquery.isotope.min.js"></script> <script src="js/main.js"></script> <script src="js/wow.min.js"></script> </body> </html> <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace Cine.Model { public class PeliculaCategoria { public int ID { get; set; } public int PeliculaID { get; set; } public int PategoriaID { get; set; } public ICollection<Pelicula> Peliculas { get; set; } public ICollection<Categoria> Categorias { get; set; } } } <file_sep>'use strict'; (function () { var app = angular.module('appAngular', []); // app.config(function ($routeProvider) { $routeProvider.when('/view1', { controller: 'controller1', templateUrl:'views/view1.html' }); }); })();<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; public partial class formularioAutor : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { string id = Request.QueryString["id"]; if (id != null) { Autor objAutor = AutorBLL.SelectById(Convert.ToInt32(id)); if (objAutor != null) { txtNombre.Text = objAutor.Nombre; hdnId.Value = objAutor.Id.ToString(); } } } } protected void btnGuardar_Click(object sender, EventArgs e) { string nombre = txtNombre.Text; try { if (string.IsNullOrEmpty(hdnId.Value)) { AutorBLL.Insert(nombre); } else { AutorBLL.Update(nombre, Convert.ToInt32(hdnId.Value)); } Response.Redirect("~/abmAutor.aspx"); } catch (Exception) { } } }<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; public partial class DetalleLibro : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { //string id = Request.QueryString["id"]; //if (id != null) //{ // Libro objLibro = LibroBLL.SelectById(Convert.ToInt32(id)); // if (objLibro != null) // { // txtIsbn.Text = objLibro.Isbn; // txtTitulo.Text = objLibro.Titulo; // txtEditorial.Text = objLibro.Editorial; // txtanho.Text = Convert.ToString(objLibro.Anho); // hdnId.Value = objLibro.Id.ToString(); // } //} } } }<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace VentaDePeliculas.Models { public class Pelicula { public int ID { get; set; } public int DirectorID { get; set; } public string Codigo { get; set; } public string Nombre { get; set; } public string Productora { get; set; } public string anho { get; set; } public string Descripcion { get; set; } public string Idioma { get; set; } public string Duracion { get; set; } public string Pais { get; set; } public Director Director { get; set; } public ICollection<GeneroPelicula> GeneroPelicula { get; set; } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; public partial class EditarAutor : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { var idGenero = Request.QueryString["idAutor"]; if (idGenero != null) { Autor Libros = AutorBLL.SelectByIdS(Convert.ToInt32(idGenero)); HiddenId.Value = idGenero; nombre.Text = Libros.Nombre; } } } protected void Button1_Click(object sender, EventArgs e) { AutorBLL.update(nombre.Text, Convert.ToInt32(HiddenId.Value)); Response.Redirect("Autores.aspx", false); } }<file_sep><?php include_once './DAO/DAL/Connection.php'; include_once './DAO/DTO/Juego.php'; include_once './DAO/BLL/JuegoBLL.php'; include_once './DAO/DAL/Connection.php'; include_once './DAO/DTO/CategoriaPadre.php'; include_once './DAO/BLL/CategoriaPadreBLL.php'; include_once './DAO/DTO/Categoria.php'; include_once './DAO/BLL/CategoriaBLL.php'; $categoriaPadreBLL = new CategoriaPadreBLL(); $categoriaBLL = new CategoriaBLL(); $categoriaIdPadre = 0; $juegoBLL = new JuegoBLL(); $id = 0; $objJuego = null; if (isset($_REQUEST["id"])) { $id = $_REQUEST["id"]; $objJuego = $juegoBLL->select($id); } ?> <!DOCTYPE html> <!-- 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. --> <html> <head> <meta charset="UTF-8"> <title>Juego</title> <meta charset="utf-8"> <meta name="description" content="Plus E-Commerce Template"> <meta name="author" content="<NAME>" /> <meta name="keywords" content="plus, html5, css3, template, ecommerce, e-commerce, bootstrap, responsive, creative" /> <meta name="viewport" content="width=device-width; initial-scale=1.0; maximum-scale=1.0; user-scalable=0;"> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <!--Favicon--> <link rel="shortcut icon" href="img/favicon.ico" type="image/x-icon"> <link rel="icon" href="img/favicon.ico" type="image/x-icon"> <!-- css files --> <link href="css/estilo.css" rel="stylesheet" type="text/css"/> <link rel="stylesheet" type="text/css" href="css/bootstrap.min.css" /> <link rel="stylesheet" type="text/css" href="css/font-awesome.min.css" /> <link rel="stylesheet" type="text/css" href="css/owl.carousel.min.css" /> <link rel="stylesheet" type="text/css" href="css/owl.theme.default.min.css" /> <link rel="stylesheet" type="text/css" href="css/animate.css" /> <link rel="stylesheet" type="text/css" href="css/swiper.css" /> <!-- this is default skin you can replace that with: dark.css, yellow.css, red.css ect --> <link id="pagestyle" rel="stylesheet" type="text/css" href="css/default.css" /> <!-- Google fonts --> <link href="https://fonts.googleapis.com/css?family=Roboto:300,300i,400,400i,500,500i,700,700i,900,900i&subset=cyrillic,cyrillic-ext,latin-ext" rel="stylesheet"> <link href="https://fonts.googleapis.com/css?family=Roboto+Slab:100,300,400,700" rel="stylesheet"> <link href="https://fonts.googleapis.com/css?family=Dosis:200,300,400,500,600,700,800&amp;subset=latin-ext" rel="stylesheet"> <link href="css/estilo.css" rel="stylesheet" type="text/css"/> </head> <body> <!-- start topBar --> <div class="topBar" id="solonegro"> <div class="container" > <ul class="topBarNav pull-right" id="espacio1"> <img src="img/iconosony.png" alt="icono sony"/> </ul> </div><!-- end container --> </div> <!-- end topBar --> <div class="middleBar" id="fondoazul"> <div class="container" id="tamaniologo"> <!-- <img src="img/logocabecera2.png" width="163" height="17" alt="logo Principal"/>--> <img src="img/iconoplaystorenegro.png" alt=""/> <a href="index.php" id="espacio5">Editar<i class="glyphicon glyphicon-edit"></i></a> </div><!-- end container --> </div><!-- end middleBar --> <!-- start navbar --> <div class="navbar yamm navbar-default" id="fondoazul"> <div class="container" style="margin-left: 80px;" > <div id="navbar-collapse-3" class="navbar-collapse collapse"> <?php $listaCategoriasPadre = $categoriaPadreBLL->selectAll(); foreach ($listaCategoriasPadre as $objCategoriaPadre) { $categoriaIdPadre = $objCategoriaPadre->getId(); ?> <ul class="nav navbar-nav" id="espacio2" > <li class="dropdown active" ><a href="#" data-toggle="dropdown" class="dropdown-toggle"> <?php echo $objCategoriaPadre->getNombre(); ?> <i class="glyphicon glyphicon-chevron-right"></i> </a> <ul role="menu" class="dropdown-menu"> <li><a href="home-v1.html"></a></li> </ul><!-- end ul dropdown-menu --> </li><!-- end li dropdown --> </ul> <?php } ?> <!-- end navbar-nav --> </div><!-- end navbar collapse --> </div><!-- end container --> </div><!-- end navbar --> <div class="container"> <div class="row"> <div class="col-md-4"> <h2>Juego</h2> <form action="abmJuego.php" method="post"> <div class="form-group"> <image class="tamanoImagen" src="img/<?php echo $id; ?>.jpg" /> </div> <div class="form-group"> <label> Descripcion: </label> <label> <?php if ($objJuego != null) { echo $objJuego->getDescripcion(); } ?> </label> </div> <div class="form-group"> <label> Precio: </label> <label> <?php if ($objJuego != null) { echo $objJuego->getPrecio(); } ?> </label> </div> </form> </div> </div> </div> <!-- Swiper slider--> </body> </html> <file_sep><?php include_once '../DAO/DAL/Connection.php'; include_once '../DAO/DTO/Juego.php'; include_once '../DAO/DTO/Categoria.php'; include_once '../DAO/BLL/JuegoBLL.php'; include_once '../DAO/BLL/CategoriaBLL.php'; $juegoBLL = new JuegoBLL(); $id = 0; $objjuego = null; if (isset($_REQUEST["id"])) { $id = $_REQUEST["id"]; $objjuego = $juegoBLL->select($id); } ?> <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Datos del Juego</title> <link href="../bootstrap-3.3.7-dist/css/bootstrap.min.css" rel="stylesheet" type="text/css"/> <link href="../bootstrap-3.3.7-dist/css/bootstrap-theme.min.css" rel="stylesheet" type="text/css"/> <script src="../bootstrap-3.3.7-dist/js/bootstrap.min.js" type="text/javascript"></script> </head> <body> <div class="container"> <div class="row"> <div class="col-md-6"> <h2> Datos del juego </h2> <form action="index.php" method="POST" id="usrform"> <input type="hidden" value="<?php if ($objjuego != null) { echo "actualizar"; } else { echo "insertar"; } ?>" name="tarea"/> <input type="hidden" value="<?php echo $id; ?>" name="id"/> <div class="form-group"> <label> Nombre: </label> <input class="form-control" required="required" type="text" name="nombre" value="<?php if ($objjuego != null) { echo $objjuego->getNombre(); } ?>"/> </div> <div class="form-group"> <label> Precio: </label> <input class="form-control" required="required" type="text" name="precio" value="<?php if ($objjuego != null) { echo $objjuego->getPrecio(); } ?>"/> </div> <div class="form-group"> <label> Descripcion: </label> <textarea form="usrform" class="form-control" name="descripcion" required="required" style="width: 700px; height: 242px;"><?php if ($objjuego != null) { echo $objjuego->getDescripcion(); } ?></textarea> <!--<input class="form-control" required="required" type="text" name="apellido" value=""/>--> </div> <div class="form-group"> <input class="btn btn-primary" type="submit" value="Guardar datos" /> <a href="index.php" class="btn btn-link">Cancelar</a> </div> </form> </div> </div> </div> </body> </html> <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.EntityFrameworkCore; using Cartelera.Models; namespace Cartelera.Context { public class ProyectoPruebaContext : DbContext { public ProyectoPruebaContext(DbContextOptions options) : base(options) { } public DbSet<Pelicula> Peliculas { get; set; } public DbSet<Categoria> Categorias { get; set; } //public DbSet<CategoriaPelicula> CategoriasPeliculas { get; set; } protected override void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder.Entity<Pelicula>().ToTable("Pelicula"); modelBuilder.Entity<Categoria>().ToTable("Categoria"); } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Web; /// <summary> /// Descripción breve de GeneroBL /// </summary> public class GeneroBLL { public GeneroBLL() {} public static List<Genero> getGeneros() { List<Genero> lista = new List<Genero>(); GeneroDSTableAdapters.GenerosTableAdapter adapter = new GeneroDSTableAdapters.GenerosTableAdapter(); GeneroDS.GenerosDataTable table = adapter.GetGeneros(); foreach (GeneroDS.GenerosRow row in table) { lista.Add(rowToDto(row)); } return lista; } public static Genero getGeneroById(int id) { GeneroDSTableAdapters.GenerosTableAdapter adapter = new GeneroDSTableAdapters.GenerosTableAdapter(); GeneroDS.GenerosDataTable table = adapter.GetGenerosById(id); if (table.Rows.Count == 0) return null; return rowToDto(table[0]); } public static void insert (Genero objGenero) { GeneroDSTableAdapters.GenerosTableAdapter adapter = new GeneroDSTableAdapters.GenerosTableAdapter(); adapter.Insert(objGenero.Nombre); } public static void update(Genero objGenero) { GeneroDSTableAdapters.GenerosTableAdapter adapter = new GeneroDSTableAdapters.GenerosTableAdapter(); adapter.Update(objGenero.Nombre, objGenero.Codigo_id); } public static void delete(int id) { GeneroDSTableAdapters.GenerosTableAdapter adapter = new GeneroDSTableAdapters.GenerosTableAdapter(); adapter.Delete(id); } private static Genero rowToDto(GeneroDS.GenerosRow row) { Genero objGenero = new Genero { Codigo_id = row.codigo_id, Nombre = row.nombre }; return objGenero; } }<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; public partial class insAutor : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { } protected void btnGuardar_Click(object sender, EventArgs e) { string nombre = txtNombre.Text; try { AutorBRL.insert(nombre); }catch(Exception ex) { } } }<file_sep>CREATE DATABASE juegos; USE juegos; CREATE TABLE tblCategorias(id int PRIMARY KEY AUTO_INCREMENT, nombre varchar(50), idCategoriaPadre int); CREATE TABLE tblJuegos(id int PRIMARY KEY AUTO_INCREMENT, nombre varchar(50), precio decimal, descripcion varchar(500)); CREATE TABLE tblCategoriaDeJuego(id int PRIMARY KEY AUTO_INCREMENT, idJuego int, idCategoria int); ALTER TABLE tblCategoriaDeJuego ADD FOREIGN KEY (idJuego) REFERENCES tblJuegos(id); ALTER TABLE tblCategoriaDeJuego ADD FOREIGN KEY (idCategoria) REFERENCES tblCategorias(id); <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; public partial class Pages_Autor : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { } protected void btnAutor_Click(object sender, EventArgs e) { AutorBLL autor = new AutorBLL(); autor.insertarAutor(txtAutor.Text.Trim()); txtAutor.Text = ""; } }<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Web; /// <summary> /// Descripción breve de GenerosBRL /// </summary> public class GenerosBRL { public GenerosBRL() { } public static List<Generos> selectAll() { GenerosDSTableAdapters.GenerosTableAdapter adapter = new GenerosDSTableAdapters.GenerosTableAdapter(); GenerosDS.tblGenerosDataTable table = adapter.GetGeneros(); List<Generos> lista = new List<Generos>(); foreach (GenerosDS.tblGenerosRow row in table) { lista.Add(rowToDto(row)); } return lista; } private static Generos rowToDto(GenerosDS.tblGenerosRow row) { Generos obj = new Generos { codigo_id = row.codigo_id, nombre = row.nombre }; return obj; } public static void add(Generos genero) { GenerosDSTableAdapters.GenerosTableAdapter adapter = new GenerosDSTableAdapters.GenerosTableAdapter(); adapter.Insert(genero.nombre); } public static void selectByID(int id) { GenerosDSTableAdapters.GenerosTableAdapter adapter = new GenerosDSTableAdapters.GenerosTableAdapter(); adapter.GetGenerosByID(id); } public static void delete(int id) { GenerosDSTableAdapters.GenerosTableAdapter adapter = new GenerosDSTableAdapters.GenerosTableAdapter(); adapter.Delete(id); } public static void update(Generos genero) { GenerosDSTableAdapters.GenerosTableAdapter adapter = new GenerosDSTableAdapters.GenerosTableAdapter(); adapter.Update(genero.nombre, genero.codigo_id); } }<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Web; /// <summary> /// Descripción breve de LibroBLL /// </summary> public class LibroBLL { public LibroBLL() { // // TODO: Agregar aquí la lógica del constructor // } public int insertarLibro(string isbn, string titulo, int autor_id, string editorial, int año) { int? salida = 0; LibroDSTableAdapters.getLibrosTableAdapter adapter = new LibroDSTableAdapters.getLibrosTableAdapter(); adapter.mkLibro(isbn, titulo, autor_id, editorial, año, ref salida); return salida.Value; } public void insertarGeneroLibro(int libro, int genero) { LibroDSTableAdapters.LibrosTableAdapter adapter = new LibroDSTableAdapters.LibrosTableAdapter(); adapter.mkGeneroByLibro(libro, genero); } public void update(int id, string isbn, string titulo, int autor_id,string editorial, int año) { LibroDSTableAdapters.getLibrosTableAdapter adapter = new LibroDSTableAdapters.getLibrosTableAdapter(); adapter.updLibro(id, isbn, titulo, autor_id, editorial, año); } public void eliminar(int id) { LibroDSTableAdapters.getLibrosTableAdapter adapter = new LibroDSTableAdapters.getLibrosTableAdapter(); adapter.delLibro(id); } public List<Categoria> getGenerosByLibro(int id) { List<Categoria> listaGeneros = new List<Categoria>(); LibroDSTableAdapters.LibrosTableAdapter adapter = new LibroDSTableAdapters.LibrosTableAdapter(); LibroDS.LibrosDataTable tabla = adapter.GetGenerosLibro(id); foreach (LibroDS.LibrosRow row in tabla) { listaGeneros.Add(new Categoria(row.codigo_id, row.nombre)); } return listaGeneros; } public List<Libro> getLibros() { List<Libro> listaLibros = new List<Libro>(); LibroDSTableAdapters.getLibrosTableAdapter adapter = new LibroDSTableAdapters.getLibrosTableAdapter(); LibroDS.getLibrosDataTable tabla = adapter.GetLibros(); foreach (LibroDS.getLibrosRow row in tabla) { listaLibros.Add(new Libro(row.codigo_id, row.isbn, row.titulo, row.autor_id, row.editorial, row.año)); } return listaLibros; } public Libro getLibroById(int id) { Libro libro = null; LibroDSTableAdapters.getLibrosTableAdapter adapter = new LibroDSTableAdapters.getLibrosTableAdapter(); LibroDS.getLibrosDataTable tabla = adapter.GetLibrosById(id); foreach (LibroDS.getLibrosRow row in tabla) { libro = new Libro(row.codigo_id, row.isbn, row.titulo, row.autor_id, row.editorial, row.año); } return libro; } }<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.Windows.Forms; public partial class frmAutor : System.Web.UI.Page { public Autor AutorActual { set { ViewState["AutorActual"] = value; } get { return (Autor)ViewState["AutorActual"]; } } protected void Page_Load(object sender, EventArgs e) { if (IsPostBack) return; int ValorRecibido = Convert.ToInt16(Request.QueryString["id"]); if (ValorRecibido > 0) { CargarDatos(ValorRecibido); } if (AutorActual == null) { AutorActual = new Autor(); } } //Cargar los datos para modificarlos protected void CargarDatos(int valor) { AutorActual = AutorBLL.GetAutorById(valor); //titulo.InnerText = "MODIFICACION DE DATOS EVENTO: " + EventoActual.nombre; nombre.Text = AutorActual.nombre; label1.Visible = true; imagenAutor.Visible = true; btnGuardar.Text = "MODIFICAR AUTOR"; } //fin de cargar DAtos para modificar //Modificar protected void ModificarAutor(int valor) { AutorActual.nombre = nombre.Text; //Fileupload codigo Boolean fileOK = false; String path = Server.MapPath("~/uploadsPerfiles/"); if (imagenAutor.HasFile) { String fileExtension = System.IO.Path.GetExtension(imagenAutor.FileName).ToLower(); String[] allowedExtensions = {".gif", ".png", ".jpeg", ".jpg"}; for (int i = 0; i < allowedExtensions.Length; i++) { if (fileExtension == allowedExtensions[i]) { fileOK = true; } } } if (fileOK) { try { imagenAutor.PostedFile.SaveAs(path + imagenAutor.FileName); label1.Visible = true; label1.Text = "File uploaded!"; AutorActual.foto = imagenAutor.FileName; } catch (Exception ex) { label1.Text = "File could not be uploaded."; } } else { label1.Text = "Cannot accept files of this type."; } try { AutorBLL.ModificarAutor(AutorActual); //Response.Write("<script>window.confirm('Mensaje de confirmacion');</script>"); } catch (Exception ex) { MessageBox.Show("Error al guardar los datos: " + ex); return; } MessageBox.Show("Los datos fueron modificados con Exito!"); Response.Redirect("AdministracionAutores.aspx"); } //fin modificar protected void btnBorrar_Click(object sender, EventArgs e) { } protected void btnGuardar_Click(object sender, EventArgs e) { int ValorRecibido = Convert.ToInt16(Request.QueryString["id"]); if (ValorRecibido > 0) { ModificarAutor(ValorRecibido); } else { AutorActual.nombre = nombre.Text; //Fileupload codigo Boolean fileOK = false; String path = Server.MapPath("~/uploadsPerfiles/"); if (imagenAutor.HasFile) { String fileExtension = System.IO.Path.GetExtension(imagenAutor.FileName).ToLower(); String[] allowedExtensions = {".gif", ".png", ".jpeg", ".jpg"}; for (int i = 0; i < allowedExtensions.Length; i++) { if (fileExtension == allowedExtensions[i]) { fileOK = true; } } } if (fileOK) { try { imagenAutor.PostedFile.SaveAs(path + imagenAutor.FileName); label1.Visible = true; label1.Text = "File uploaded!"; AutorActual.foto = imagenAutor.FileName; } catch (Exception ex) { label1.Text = "File could not be uploaded."; } } else { if (!imagenAutor.HasFile) { AutorActual.foto = ""; } else { label1.Text = "Cannot accept files of this type."; } } //Fin de FileUpload try { // Persona obj = SeguridadUtils.GetUserInSession(); // AutorActual.idAutor = obj; AutorBLL.InsertarAutor(AutorActual); } catch (Exception ex) { return; } Response.Redirect("~/AdministracionAutores.aspx"); } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using MVCPeliculas.Context; using MVCPeliculas.Models; namespace MVCPeliculas.Controllers { public class HomeController : Controller { private readonly ProyectoPeliculaContext db,db2; public HomeController(ProyectoPeliculaContext context) { db = context; } public IActionResult Index() { db.Database.EnsureCreated(); //var genero = new Genero { Nombre = "Accion" }; //db.Add(genero); //var director = new Director { Nombres = "Alejandro", Apellidos = "<NAME>" }; //db.Add(director); //var peliculas = new Pelicula { Nombre = "Titanic", DirectorID = 1, CodigoImagen = "TT1", FechaEstreno = "17 de Abril de 2018", Duraccion = "2 horas", Idioma = "Español", Pais = "Bolivia", Director = director}; //db.Add(peliculas); //var generopelicula = new GeneroPelicula {PeliculaID = 1,GeneroID= 1,Pelicula = peliculas,Genero = genero}; //db.Add(generopelicula); db.SaveChanges(); return View(); } public IActionResult About() { ViewData["Message"] = "Your application description page."; return View(); } public IActionResult Contact() { ViewData["Message"] = "Your contact page."; return View(); } public IActionResult Error() { return View(); } } } <file_sep><?php namespace App\Http\Controllers; use App\notas; use Illuminate\Http\Request; class notasController extends Controller { /** * Display a listing of the resource. * * @return \Illuminate\Http\Response */ public function index() { $listaNotas = notas::all()->toArray(); return view('home', compact('listaNotas')); } /** * Show the form for creating a new resource. * * @return \Illuminate\Http\Response */ public function create() { // } /** * Store a newly created resource in storage. * * @param \Illuminate\Http\Request $request * @return \Illuminate\Http\Response */ public function store(Request $request) { $notas = notas::create($request->all()); // $listaNotas = notas::all()->toArray(); return response()->json($notas); } public function notas(Request $request) { $tasks = notas::all(); return $tasks; } /** * Display the specified resource. * * @param \App\notas $notas * @return \Illuminate\Http\Response */ public function show(notas $notas) { // } public function notass(Request $request) { $valor = $request->input('value'); if($valor == ""){ $tasks = notas::all(); return response()->json($tasks); }else{ $notas = notas::where('titulo','like', '%' . $request->input('value'). '%' )->orWhere('nota', 'like', '%' . $request->input('value'). '%')->get(); return response()->json($notas); } } /** * Show the form for editing the specified resource. * * @param \App\notas $notas * @return \Illuminate\Http\Response */ public function edit(notas $notas) { // } /** * Update the specified resource in storage. * * @param \Illuminate\Http\Request $request * @param \App\notas $notas * @return \Illuminate\Http\Response */ public function update(Request $request, notas $notas) { // } /** * Remove the specified resource from storage. * * @param \App\notas $notas * @return \Illuminate\Http\Response */ public function destroy(notas $notas) { // } }<file_sep><?php /* |-------------------------------------------------------------------------- | Web Routes |-------------------------------------------------------------------------- | | Here is where you can register web routes for your application. These | routes are loaded by the RouteServiceProvider within a group which | contains the "web" middleware group. Now create something great! | */ Route::resource('notas','notasController'); Route::get('/', 'notasController@index'); Route::get('/notasget',[ 'uses' => 'notasController@notass', 'as' => 'notasget.notass' ]);<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Web; /// <summary> /// Descripción breve de LibroBLL /// </summary> public class LibroBLL { public LibroBLL() { // // TODO: Agregar aquí la lógica del constructor // } public static List<Libro> SelectAll() { List<Libro> listaLibro = new List<Libro>(); LibroDSTableAdapters.LibroTableAdapter adapter = new LibroDSTableAdapters.LibroTableAdapter(); LibroDS.LibroDataTable table = adapter.sp_libro_selectall(); foreach (LibroDS.LibroRow row in table) { listaLibro.Add(rowToDto(row)); } return listaLibro; } public static List<Libro> GenerarLibroSelectAll(int idgenero) { List<Libro> listaLibrogenero = new List<Libro>(); LibroDSTableAdapters.sp_generarlibro_selectallTableAdapter adapter = new LibroDSTableAdapters.sp_generarlibro_selectallTableAdapter(); LibroDS.sp_generarlibro_selectallDataTable table = adapter.sp_generarlibro_selectall(idgenero); foreach (LibroDS.sp_generarlibro_selectallRow row in table) { listaLibrogenero.Add(rowToDto2(row)); } return listaLibrogenero; } private static Libro rowToDto2(LibroDS.sp_generarlibro_selectallRow row) { Libro objLibrogenero = new Libro(); objLibrogenero.id_GenerarLibro = row.id_GenerarLibro; objLibrogenero.id_Libro = row.id_Libro; objLibrogenero.id_Genero = row.id_Genero; return objLibrogenero; } public static Libro SelectById(int id) { LibroDSTableAdapters.LibroTableAdapter adapter = new LibroDSTableAdapters.LibroTableAdapter(); LibroDS.LibroDataTable table = adapter.sp_libro_selectbyid(id); if (table.Rows.Count == 0) { return null; } return rowToDto(table[0]); } public static void Insert(string isbn, string titulo, string editorial,int ano, int id_Autor ) { LibroDSTableAdapters.LibroTableAdapter adapter = new LibroDSTableAdapters.LibroTableAdapter(); adapter.Insert(isbn, titulo, editorial, ano, id_Autor); } public static void Update(string isbn, string titulo, string editorial, int ano, int id_Autor, int id_Libro) { LibroDSTableAdapters.LibroTableAdapter adapter = new LibroDSTableAdapters.LibroTableAdapter(); adapter.Update(isbn, titulo, editorial, ano, id_Autor,id_Libro); } public static void Delete(int id) { LibroDSTableAdapters.LibroTableAdapter adapter = new LibroDSTableAdapters.LibroTableAdapter(); adapter.Delete(id); } private static Libro rowToDto(LibroDS.LibroRow row) { Libro objLibro = new Libro(); objLibro.id_Libro = row.id_Libro; objLibro.isbn = row.isbn; objLibro.titulo = row.titulo; objLibro.editorial = row.editorial; objLibro.ano = row.ano; objLibro.id_Autor = row.id_Autor; return objLibro; } }<file_sep><?php namespace App\Http\Controllers; use App\Nota; use Illuminate\Http\Request; class NotaController extends Controller { /** * Display a listing of the resource. * * @return \Illuminate\Http\Response */ public function index() { $notas = Nota::all()->toArray(); return view('nota.index', compact('notas')); } /** * Show the form for creating a new resource. * * @return \Illuminate\Http\Response */ public function create() { return view('nota.create'); } /** * Store a newly created resource in storage. * * @param \Illuminate\Http\Request $request * @return \Illuminate\Http\Response */ public function store(Request $request) { $objNota = new Nota(); $objNota->titulo = $request->post('titulo'); $objNota->descripcion = $request->post('descripcion'); $objNota->save(); return redirect('/nota/index'); } /** * Display the specified resource. * * @param \App\Nota $nota * @return \Illuminate\Http\Response */ public function show(Nota $nota) { // } /** * Show the form for editing the specified resource. * * @param \App\Nota $nota * @return \Illuminate\Http\Response */ //agregue el edit public function edit($id) { $objNota = Nota::find($id); return view('nota.edit', compact('objNota', 'id')); } /** * Update the specified resource in storage. * * @param \Illuminate\Http\Request $request * @param \App\Nota $nota * @return \Illuminate\Http\Response */ //agregue el update public function update(Request $request, $id) { $objNota = Nota::find($id); $objNota->titulo = $request->post('titulo'); $objNota->descripcion = $request->post('descripcion'); $objNota->save(); return redirect('/nota/index'); } /** * Remove the specified resource from storage. * * @param \App\Nota $nota * @return \Illuminate\Http\Response */ //agregue el eliminar public function destroy($id) { $objNota = Nota::find($id); $objNota->delete(); return redirect('/nota/index'); } /*PHP Route::delete('user/{id}', function ($id) { $user = App\User::find($id)->delete(); return Redirect::back(); });*/ } <file_sep>$(document).ready(function () { var myViewModel = { nombre: ko.observable(''), email: ko.observable(''), web: ko.observable(''), comments: ko.observable(''), nombre2: ko.observable(''), email2: ko.observable(''), web2: ko.observable(''), comments2: ko.observable(''), click_enviar: function () { var nom = this.nombre(); var ema = this.email(); var wb = this.web(); var com = this.comments(); this.nombre2(nom); this.email2(ema); this.web2(wb); this.comments2(com); //alert('datos enviados correctamente') }, click_eliminar: function () { this.nombre(''); this.email(''); this.web(''); this.comments(''); this.nombre2(''); this.email2(''); this.web2(''); this.comments2(''); }, }; ko.applyBindings(myViewModel); });<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; public partial class MasterPage : System.Web.UI.MasterPage { protected void Page_Load(object sender, EventArgs e) { if (IsPostBack) return; LoadResources(); } private void LoadResources() { StringBuilder str = new StringBuilder(); str.Append("<script type='text/javascript' "); str.Append("src='" + ResolveClientUrl("~/js/jquery.dataTables.min.js") + "'></script>"); str.Append("<script type='text/javascript' "); str.Append("src='" + ResolveClientUrl("~/js/modernizr-2.6.2-respond-1.1.0.min.js") + "'></script>"); str.Append("<script type='text/javascript' "); str.Append("src='" + ResolveClientUrl("~/js/jquery-1.12.4.js") + "'></script>"); str.Append("<script type='text/javascript' "); str.Append("src='" + ResolveClientUrl("~/js/bootstrap.min.js") + "'></script>"); str.Append("<script type='text/javascript' "); str.Append("src='" + ResolveClientUrl("~/js/jquery.easing.min.js") + "'></script>"); str.Append("<script type='text/javascript' "); str.Append("src='" + ResolveClientUrl("~/js/cambioBotones.js") + "'></script>"); str.Append("<script type='text/javascript' "); str.Append("src='" + ResolveClientUrl("~/js/ga.js") + "'></script>"); str.Append("<script type='text/javascript' "); str.Append("src='" + ResolveClientUrl("~/js/scrolling-nav.js") + "'></script>"); str.Append("<script type='text/javascript' "); str.Append("src='" + ResolveClientUrl("http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js") + "'></script>"); str.Append("<script type='text/javascript' "); str.Append("src='" + ResolveClientUrl("http://code.jquery.com/ui/1.10.3/jquery-ui.js") + "'></script>"); ResourcesLiteral.Text = str.ToString(); } protected void BtnLogout_Click(object sender, EventArgs e) { } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; public partial class MasterPage : System.Web.UI.MasterPage { protected void Page_Load(object sender, EventArgs e) { List<Autor> Libro = AutorBLL.SelectAll(); rptCustomersAutor.DataSource = Libro; rptCustomersAutor.DataBind(); List<Genero> genero = GeneroBLL.SelectAll(); rptCustomersGenero.DataSource = genero; rptCustomersGenero.DataBind(); } } <file_sep><?php /** * Description of CategoriaBLL * * @author Nikolas-PC */ class CategoriaBLL { public function insert($nombre, $catPadre){ $objConexion = new Connection(); $objConexion->queryWithParams("CALL mk_tblCategorias(:pNombre, :pCatPadre)", array( "pNombre"=>$nombre, "pCatPadre"=>$catPadre )); } public function update($id, $nombre, $catPadre){ $objConexion = new Connection(); $objConexion->queryWithParams("CALL up_tblCategorias(:pCodigo_id, :pNombre, :pCatPadre)", array( "pCodigo_id"=>$id, "pNombre"=>$nombre, "pCatPadre"=>$catPadre )); } public function delete($id) { $objConexion = new Connection(); $objConexion->queryWithParams("CALL del_tblCategorias(:pCodigo_id)", array( ":pCodigo_id" => $id )); } public function selectAll() { $listaCategorias = array(); $objConexion = new Connection(); $res = $objConexion->query("CALL get_tblCategorias"); while ($row = $res->fetch(PDO::FETCH_ASSOC)) { $objJuego = $this->rowToDto($row); $listaCategorias[] = $objJuego; } return $listaCategorias; } public function select($id) { $objConexion = new Connection(); $res = $objConexion->queryWithParams("CALL get_tblCategoriasById(:id)", array( ":id" => $id )); if ($res->rowCount() == 0) { return null; } $row = $res->fetch(PDO::FETCH_ASSOC); return $this->rowToDto($row); } function rowToDto($row) { $objJuego = new Juego(); $objJuego->setCodigo_id("codig_id"); $objJuego->setNombre("nombre"); $objJuego->setPrecio("id_categoriaPadre"); } } <file_sep><?php include_once './DAO/DAL/Connection.php'; include_once './DAO/DTO/Persona.php'; include_once './DAO/BLL/PersonaBLL.php'; $personaBLL = new PersonaBLL(); function mostrarMensaje($mensaje) { echo "<script type='text/javascript'>alert('$mensaje')</script>"; } if (isset($_REQUEST["tarea"])) { $tarea = $_REQUEST["tarea"]; switch ($tarea) { case "insertar": if (!isset($_REQUEST["nombre"]) || !isset($_REQUEST["apellido"]) || !isset($_REQUEST["ciudad"]) || !isset($_REQUEST["edad"])) { mostrarMensaje('Error al insertar, parámetros incompletos'); } else { $nombre = $_REQUEST["nombre"]; $apellido = $_REQUEST["apellido"]; $ciudad = $_REQUEST["ciudad"]; $edad = $_REQUEST["edad"]; $personaBLL->insert($nombre, $apellido, $ciudad, $edad); } break; case "actualizar": if (!isset($_REQUEST["nombre"]) || !isset($_REQUEST["apellido"]) || !isset($_REQUEST["ciudad"]) || !isset($_REQUEST["edad"]) || !isset($_REQUEST["id"])) { mostrarMensaje('Error al actualizar, parámetros incompletos'); } else { $id = $_REQUEST["id"]; $nombre = $_REQUEST["nombre"]; $apellido = $_REQUEST["apellido"]; $ciudad = $_REQUEST["ciudad"]; $edad = $_REQUEST["edad"]; $personaBLL->update($nombre, $apellido, $ciudad, $edad, $id); } break; case "eliminar": if (!isset($_REQUEST["id"])) { mostrarMensaje('Error al actualizar, parámetros incompletos'); } else { $id = $_REQUEST["id"]; $personaBLL->delete($id); } break; } } ?> <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <link href="css/bootstrap.min.css" rel="stylesheet" type="text/css"/> <link href="css/bootstrap-theme.min.css" rel="stylesheet" type="text/css"/> <script src="js/bootstrap.min.js" type="text/javascript"></script> <title></title> </head> <body> <div class="container"> <div class="row"> <div class="col-md-12"> <div class="well" style="margin-top: 10px;"> <a class="btn btn-primary" href="AgregarPersona.php">Agregar persona</a> </div> <?php // $personaBLL->insert("Juan", "Perez", "SCZ", 20); ?> <table class="table"> <thead> <tr> <th>ID</th> <th>Nombre</th> <th>Apellido</th> <th>Ciudad</th> <th>Edad</th> </tr> </thead> <tbody> <?php $listaPersonas = $personaBLL->selectAll(); foreach ($listaPersonas as $objPersona) { ?> <tr> <td> <?php echo $objPersona->getId(); ?> </td> <td> <?php echo $objPersona->getNombre(); ?> </td> <td> <?php echo $objPersona->getApellido(); ?> </td> <td> <?php echo $objPersona->getCiudad(); ?> </td> <td> <?php echo $objPersona->getEdad(); ?> </td> <td> <a href="AgregarPersona.php?id=<?php echo $objPersona->getId(); ?>">Editar</a> </td> <td> <a href="index.php?tarea=eliminar&id=<?php echo $objPersona->getId(); ?>">Eliminar</a> </td> </tr> <?php } ?> </tbody> </table> </div> </div> </div> </body> </html> <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Web; /// <summary> /// Descripción breve de GeneroBLL /// </summary> public class GeneroBLL { public GeneroBLL() { } public static List<Genero> SelectAll() { List<Genero> listadoGen = new List<Genero>(); DTGeneroTableAdapters.tblgenerosTableAdapter adapter = new DTGeneroTableAdapters.tblgenerosTableAdapter(); DTGenero.tblgenerosDataTable table = adapter.SelectAll(); foreach (DTGenero.tblgenerosRow row in table) { listadoGen.Add(rowToDto(row)); } return listadoGen; } public static Genero SelectById(int idgenero) { DTGeneroTableAdapters.tblgenerosTableAdapter adapter = new DTGeneroTableAdapters.tblgenerosTableAdapter(); DTGenero.tblgenerosDataTable table = adapter.SelectAllById(idgenero); if (table.Rows.Count == 0) { return null; } return rowToDto(table[0]); } public static void insert(string nombregenero) { DTGeneroTableAdapters.tblgenerosTableAdapter adapter = new DTGeneroTableAdapters.tblgenerosTableAdapter(); adapter.Insert(nombregenero); } public static void update(string nombregenero, int idgenero) { DTGeneroTableAdapters.tblgenerosTableAdapter adapter = new DTGeneroTableAdapters.tblgenerosTableAdapter(); adapter.Update(nombregenero, idgenero); } public static void delete(int idgenero) { DTGeneroTableAdapters.tblgenerosTableAdapter adapter = new DTGeneroTableAdapters.tblgenerosTableAdapter(); adapter.Delete(idgenero); } private static Genero rowToDto(DTGenero.tblgenerosRow row) { Genero objgenero = new Genero(); objgenero.GeneroId = row.generoId; objgenero.NombreGenero = row.g_nombre; return objgenero; } }<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; public partial class Pages_Libro : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { AutorBLL autor = new AutorBLL(); List<Autor> lista = autor.getAutores(); for (int i = 0; i < lista.Count; i++) { cmbAutores.Items.Add(lista.ElementAt(i).cadena()); } } protected void Unnamed5_Click(object sender, EventArgs e) { LibroBLL libro = new LibroBLL(); int llave = libro.insertarLibro(txtIsbn.Text, txtTitulo.Text, cmbAutores.SelectedIndex+1, txtEditorial.Text, Int32.Parse(txtAño.Text)); libro.insertarGeneroLibro(llave, 1); } }<file_sep><?php /* * 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. */ /** * Description of accatBLL * * @author Miguel */ class accatBLL { public function insert($accatNomb, $accatCpad) { $objConexion = new Connection(); $objConexion->queryWithParams("INSERT INTO accat(accatNomb,accatCpad) VALUES (:accatNomb,:accatCpad)", array( ":accatNomb" => $accatNomb, ":accatCpad" => $accatCpad )); } public function update($accatCcat, $accatNomb, $accatCpad) { $objConexion = new Connection(); $objConexion->queryWithParams(" UPDATE accat SET accatNomb = :accatNomb, accatCpad = :accatCpad WHERE accatCcat = :accatCcat", array( ":accatNomb" => $accatNomb , ":accatCpad" => $accatCpad, ":accatCcat" => $accatCcat )); } public function delete($id) { $objConexion = new Connection(); $objConexion->queryWithParams(" DELETE FROM accat WHERE accatCcat = :pId", array( ":pId" => $id )); } public function selectAll() { $ListaAccat = array(); $objConexion = new Connection(); $res = $objConexion->query(" SELECT `accatCcat`, `accatNomb`, `accatCpad` FROM `accat`"); while ($row = $res->fetch(PDO::FETCH_ASSOC)) { $objaccat = $this->rowToDto($row); $ListaAccat[] = $objaccat; } return $ListaAccat; } public function selectAccatPad() { $objConexion = new Connection(); $listaAccat = array(); $res = $objConexion->queryWithParams(" SELECT `accatCcat`, `accatNomb`, `accatCpad` FROM `accat` WHERE 1 and `accatCpad` = :accatCpad", array( ":accatCpad" => 0 )); while ($row = $res->fetch(PDO::FETCH_ASSOC)) { $accat = $this->rowToDto($row); $listaAccat[] = $accat; } return $listaAccat; } public function selectAccatPads($accatCcat) { $objConexion = new Connection(); $listaAccats = array(); $ress = $objConexion->queryWithParams(" SELECT `accatCcat`, `accatNomb`, `accatCpad` FROM `accat` WHERE 1 and `accatCpad` = :accatCpad", array( ":accatCpad" => $accatCcat )); while ($rows = $ress->fetch(PDO::FETCH_ASSOC)) { $accats = $this->rowToDto($rows); $listaAccats[] = $accats; } return $listaAccats; } public function selectaccatPadre($accatCcat) { $objConexion = new Connection(); $res = $objConexion->queryWithParams(" SELECT `accatCcat`, `accatNomb`, `accatCpad` FROM `accat` WHERE `accatCcat`= :accatCcat", array( ":accatCcat" => $accatCcat )); if ($res->rowCount() == 0) { return null; } $row = $res->fetch(PDO::FETCH_ASSOC); return $this->rowToDto($row); } public function selectAccatByID($accatCcat) { $objConexion = new Connection(); $listaAccats; $ress = $objConexion->queryWithParams(" SELECT `accatCcat`, `accatNomb`, `accatCpad` FROM `accat` WHERE 1 and `accatCpad` = :accatCpad", array( ":accatCpad" => $accatCcat )); $total = $ress->rowCount(); if ($total > 0) { while ($row = $ress->fetch(PDO::FETCH_OBJ)) { $listaAccats = array("accatCcat" => $row->accatCcat, "accatNomb" => $row->accatNomb); } } return $listaAccats; } public function select($id) { $objConexion = new Connection(); $res = $objConexion->queryWithParams(" SELECT `accatCcat`, `accatNomb`, `accatCpad` FROM `accat` WHERE accatCcat = :accatCcat", array( ":accatCcat" => $id )); if ($res->rowCount() == 0) { return null; } $row = $res->fetch(PDO::FETCH_ASSOC); return $this->rowToDto($row); } function rowToDto($row) { $obj = new accat(); $obj->setAccatCcat($row["accatCcat"]); $obj->setAccatNomb($row["accatNomb"]); $obj->setAccatCpad($row["accatCpad"]); return $obj; } } <file_sep><?php namespace App\Http\Controllers; use App\Nota; use Illuminate\Http\Request; class NotaController extends Controller { // public function index(){ $lista = Nota::all()->toArray(); return view('nota.index', compact('lista')); } public function create(){ } public function store(Request $request){ $nota = new Nota; $nota->titulo = $request->input('titulo'); $nota->cuerpo = $request->input('cuerpo'); $nota->save(); /*Nota::created($request->all());*/ return redirect('/nota/'); } public function show($id){ } public function edit($id){ return view('/nota/edit'); } public function update(Request $request, $id){ } public function destroy($id){ $objNota = Nota::find($id); $objNota->delete(); return redirect('/nota/'); //return "Funciona"; } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Web; /// <summary> /// Descripción breve de Libro /// </summary> public class Libro { public Libro() { } public string LibroIsbn { get; set; } public string LibroEditorial { get; set; } public int LibroAño { get; set; } public string AutorNombre { get; set; } public int idlibroGenero { get; set; } public int LibroId { get; set; } public int idGenero { get; set; } public string GeneroNombre { get; set; } public string LibroTitulo { get; set; } public Libro SeleccionarLibro { get { return LibroBLL.SelectById(LibroId); } } }<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using CarteleraMVC.Models; namespace CarteleraMVC.Models { public class CategoriasPelicula { public int CategoriaID { get; set; } public int PeliculaID { get; set; } public Pelicula Pelicula { get; set; } public Categoria Categoria { get; set; } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Web; /// <summary> /// Descripción breve de Autor /// </summary> public class Autor { public int id{set; get;} public string nombre{get; set;} public Autor() { // // TODO: Agregar aquí la lógica del constructor // } public Autor(int id, string nombre) { this.id=id; this.nombre=nombre; } public Autor(string nombre) { this.nombre = nombre; } public String cadena() { return nombre; } }<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; public partial class formularioAutor : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { string id = Request.QueryString["id"]; if (id != null) { Autor objautor = AutorBLL.SelectById(Convert.ToInt32(id)); if (objautor != null) { autortxt.Text = objautor.Nombreautor; hdnId.Value = objautor.Id_Autor.ToString(); } } } } protected void btnGuardar_Click(object sender, EventArgs e) { string autor = autortxt.Text; try { if (string.IsNullOrEmpty(hdnId.Value)) { AutorBLL.Insert(autor); } else { AutorBLL.Update(autor, Convert.ToInt32(hdnId.Value)); } Response.Redirect("~/listaAutor.aspx"); } catch (Exception ex) { } } }<file_sep><?php namespace App\Http\Controllers; use App\Persona; use Illuminate\Http\Request; class PersonaController extends Controller { /** * Display a listing of the resource. * * @return \Illuminate\Http\Response */ public function index() { $listaPersonas = Persona::all()->toArray(); return view('persona.index', compact('listaPersonas')); } /** * Show the form for creating a new resource. * * @return \Illuminate\Http\Response */ public function create() { return view('persona.create'); } /** * Store a newly created resource in storage. * * @param \Illuminate\Http\Request $request * @return \Illuminate\Http\Response */ public function store(Request $request) { $objPersona = new Persona(); $objPersona->nombre = $request->post('nombre'); $objPersona->apellido = $request->post('apellido'); $objPersona->ciudad = $request->post('ciudad'); $objPersona->edad = $request->post('edad'); $objPersona->save(); return redirect('/persona'); } /** * Display the specified resource. * * @param \App\Persona $persona * @return \Illuminate\Http\Response */ public function show(Persona $persona) { // } /** * Show the form for editing the specified resource. * * @param \App\Persona $persona * @return \Illuminate\Http\Response */ public function edit($id) { $objPersona = Persona::find($id); return view('persona.edit', compact('objPersona', 'id')); } /** * Update the specified resource in storage. * * @param \Illuminate\Http\Request $request * @param \App\Persona $persona * @return \Illuminate\Http\Response */ public function update(Request $request, $id) { $objPersona = Persona::find($id); $objPersona->nombre = $request->post('nombre'); $objPersona->apellido = $request->post('apellido'); $objPersona->ciudad = $request->post('ciudad'); $objPersona->edad = $request->post('edad'); $objPersona->save(); return redirect('/persona'); } /** * Remove the specified resource from storage. * * @param \App\Persona $persona * @return \Illuminate\Http\Response */ public function destroy($id) { $objPersona = Persona::find($id); $objPersona->delete(); return redirect('/persona'); } } <file_sep>using Microsoft.EntityFrameworkCore; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using VentaDePeliculas.Models; namespace VentaDePeliculas.Context { public class ProyectoPruebaContext : DbContext { //este hace reconocer los comandos del home CONTROLER public ProyectoPruebaContext(DbContextOptions options) : base(options) { } public DbSet<Genero> Generos { get; set; } public DbSet<Pelicula> Peliculas { get; set; } public DbSet<Director> Directores { get; set; } public DbSet<GeneroPelicula> GeneroPeliculas { get; set; } //este modelo se va a disparar cuando las tablas no existan en la DB protected override void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder.Entity<Genero>().ToTable("Genero"); // esto es lo q se encarga de hacer q el codigo se vuelva BD modelBuilder.Entity<Pelicula>().ToTable("Pelicula"); modelBuilder.Entity<Director>().ToTable("Director"); modelBuilder.Entity<GeneroPelicula>().ToTable("GeneroPelicula"); } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace Seguridad.App_Code.BLL { public class RolBLL { public RolBLL() { } public static List<Rol> SelectAll() { RolDSTableAdapters.RolesTableAdapter = } } }<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using VentaDePeliculas.Context; using VentaDePeliculas.Models; namespace VentaDePeliculas.Controllers { public class HomeController : Controller { //READONLY private readonly ProyectoPruebaContext db; public HomeController(ProyectoPruebaContext contex) { //se va a encargar de conectar todas nuestras cosas db = contex; } public IActionResult Index() { db.Database.EnsureCreated(); // este se asegura de que la bd este creada //var genero = new Genero { Nombre = "Terror" }; //el enshure nos dice q esta creado todo //db.Add(genero); //var director = new Director { Nombre = "Condorito" }; //db.Add(director); //var pelicula = new Pelicula { Codigo = "nnji1", Nombre = "la b<NAME>dida", Duracion = "100 mins", Productora = "wd", anho = "2017", Descripcion = "todo", Idioma = "spanish", Pais = "por ahi", Director = director }; //db.Add(pelicula); //var generopelicula = new GeneroPelicula { GeneroID = 1, PeliculaID = 1, Genero = genero, Pelicula = pelicula }; //db.Add(generopelicula); db.SaveChanges(); return View(); } public IActionResult About() { ViewData["Message"] = "Your application description page."; return View(); } public IActionResult Contact() { ViewData["Message"] = "Your contact page."; return View(); } public IActionResult Error() { return View(); } } } <file_sep>var app = require('express')(); var http = require('http').Server(app); var io = require('socket.io')(http); var Port = 8080; app.get('/',function(req,res){ res.sendFile(__dirname + '/index.html'); }); io.on('connection', function (socket) { console.log("Usuario Id: %s", socket.id); io.emit('message', 'El Usuario' + socket.id + ' se ha Conectado', 'System'); socket.on('message', function (msg) { io.emit('message', msg, socket.id); }); socket.on('disconnect', function (e) { console.log("Desconectado : %s", socket.id); }); }); http.listen(Port,function(){ console.log('El Servidor Se inicio',Port); });<file_sep><?php /* |-------------------------------------------------------------------------- | Web Routes |-------------------------------------------------------------------------- | | Here is where you can register web routes for your application. These | routes are loaded by the RouteServiceProvider within a group which | contains the "web" middleware group. Now create something great! | */ Route::get('/', function () { return view('/nota'); }); Auth::routes(); Route::resource('nota/','NotaController'); Route::get('/nota/index','NotaController@index'); Route::get('/nota/','NotaController@create'); Route::post('/nota/','NotaController@store'); Route::delete('/nota/{id}','NotaController@destroy'); /* Route::delete('user/{id}', function ($id) { $user = App\User::find($id)->delete(); return Redirect::back(); });*/ Route::put('/nota/edit/{id}','NotaController@edit'); Route::get('/home', 'HomeController@index')->name('home'); <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Web; /// <summary> /// Descripción breve de Libro /// </summary> public class Libro { public Libro() {} public int Codigo_id { get; set; } public string Titulo { get; set; } public string ISBN { get; set; } public string Editorial { get; set; } public int año { get; set; } public int Autor_id { get; set; } public int Genero_id { get; set; } }<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace Cartelera.Models { public class Pelicula { public int PeliculaID { get; set; } public string nombrePelicula { get; set; } public string fecha { get; set; } public string horario { get; set; } public int puntuacion { get; set; } public ICollection<Categoria> Categorias { get; set; } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Web; /// <summary> /// Descripción breve de Autor /// </summary> public class Categoria { public int id { get; set; } public string nombre { get; set; } public Categoria() { // // TODO: Agregar aquí la lógica del constructor // } public Categoria(int id, string nombre) { this.id=id; this.nombre=nombre; } public Categoria(string nombre) { this.nombre = nombre; } }<file_sep>var app = require('express')(); var http = require('http').Server(app); var Port = 8080; app.get('/', function (req, res) { res.send('<h1>Hola Mundo</h1>'); }); http.listen(Port, function () { console.log('El Servidor Se inicio', Port); });<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Web; /// <summary> /// Summary description for GeneroBLL /// </summary> public class GeneroBLL { public GeneroBLL() { } public static List<Genero> getListadoGeneros() { GeneroDSTableAdapters.GenerosTableAdapter adapter = new GeneroDSTableAdapters.GenerosTableAdapter(); GeneroDS.GenerosDataTable table = adapter.getAllGeneros(); List<Genero> generos = new List<Genero>(); foreach (var row in table) { generos.Add(new Genero { generoId = row.generoId, nombre = row.nombre }); } return generos; } public static void insertarGenero(string nombre) { GeneroDSTableAdapters.GenerosTableAdapter adapter = new GeneroDSTableAdapters.GenerosTableAdapter(); adapter.insertarGenero(nombre); } public static void insertarGeneroLibro(int libroId, int generoId) { GeneroDSTableAdapters.GenerosTableAdapter adapter = new GeneroDSTableAdapters.GenerosTableAdapter(); adapter.insertarGeneroLibro(libroId, generoId); } public static void EliminarGenero(int generoId) { GeneroDSTableAdapters.GenerosTableAdapter adapter = new GeneroDSTableAdapters.GenerosTableAdapter(); adapter.deleteGenero(generoId); } public static void UpdateGenero(int generoId, string nombre) { GeneroDSTableAdapters.GenerosTableAdapter adapter = new GeneroDSTableAdapters.GenerosTableAdapter(); adapter.updateGeneros(generoId, nombre); } public static void UpdateGeneroxLibro(int libroId) { GeneroDSTableAdapters.GenerosTableAdapter adapter = new GeneroDSTableAdapters.GenerosTableAdapter(); adapter.updateGeneroxLibro(libroId); } public static Genero getGeneroById(int generoId) { GeneroDSTableAdapters.GenerosTableAdapter adapter = new GeneroDSTableAdapters.GenerosTableAdapter(); GeneroDS.GenerosDataTable table = adapter.getGeneroById(generoId); if (table.Rows.Count == 0) { return null; } return rowToDto(table[0]); } private static Genero rowToDto(GeneroDS.GenerosRow row) { Genero objRol = new Genero(); objRol.generoId = row.generoId; objRol.nombre = row.nombre; return objRol; } }<file_sep><?php include_once './DAO/DAL/Connection.php'; include_once './DAO/DTO/Juego.php'; include_once './DAO/BLL/JuegoBLL.php'; $juegoBLL = new JuegoBLL(); if (isset($_REQUEST["tarea"])) { $tarea = $_REQUEST["tarea"]; switch ($tarea) { case "insertar": if (!isset($_REQUEST["nombre"]) || !isset($_REQUEST["precio"]) || !isset($_REQUEST["descripcion"])) { mostrarMensaje('Error al insertar, parametros incompletos'); } else { $nombre = $_REQUEST["nombre"]; $precio = $_REQUEST["precio"]; $descripcion = $_REQUEST["descripcion"]; $juegoBLL->insert($nombre, $precio, $descripcion); } break; case "actualizar": if (!isset($_REQUEST["nombre"]) || !isset($_REQUEST["precio"]) || !isset($_REQUEST["descripcion"]) || !isset($_REQUEST["id"])) { mostrarMensaje('Error al actualizar, parametros incompletos'); } else { $id = $_REQUEST["id"]; $nombre = $_REQUEST["nombre"]; $precio = $_REQUEST["precio"]; $descripcion = $_REQUEST["descripcion"]; $juegoBLL->update($nombre, $precio, $descripcion, $id); } break; case "eliminar": if (!isset($_REQUEST["id"])) { mostrarMensaje('Error al eliminar, parametros incompletos'); } else { $id = $_REQUEST["id"]; $juegoBLL->delete($id); } break; case "fotoperfil": if (!isset($_REQUEST["id"])) { mostrarMensaje('Error al subir foto, parametros incompletos'); } else { $id = $_REQUEST["id"]; $dir_subida = 'img/'; $fichero_subido = $dir_subida . $id . ".jpg"; if (move_uploaded_file($_FILES['archivo']['tmp_name'], $fichero_subido)) { // echo "El fichero es válido y se subió con éxito.\n"; } else { // echo "¡Posible ataque de subida de ficheros!\n"; } } break; } } ?> <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Juego</title> <link href="css/bootstrap.min.css" rel="stylesheet" type="text/css"/> <link href="css/bootstrap-theme.min.css" rel="stylesheet" type="text/css"/> <script src="js/bootstrap.min.js" type="text/javascript"></script> <link href="css/estilo.css" rel="stylesheet" type="text/css"/> </head> <body class="letrablanca"> <div class="container"> <div class="row"> <div class="col-md-12"> <div > <a class="btn btn-primary" href="AgregarJuego.php">Agregar Juego</a> </div> <table class="table"> <thead> <tr> <th></th> <th>ID</th> <th>Nombre</th> <th>Precio</th> <th>Descripcion</th> </tr> </thead> <tbody> <?php $listaJuegos = $juegoBLL->selectAll(); foreach ($listaJuegos as $objJuego) { ?> <tr> <td> <image class="tamanioimg" src="img/<?php echo $objJuego->getId(); ?>.jpg" /> </td> <td> <?php echo $objJuego->getId(); ?> </td> <td> <?php echo $objJuego->getNombre(); ?> </td> <td> <?php echo $objJuego->getPrecio(); ?> </td> <td> <?php echo $objJuego->getDescripcion(); ?> </td> <td> <a href="fotoJuego.php?id=<?php echo $objJuego->getId(); ?>"><i class="glyphicon glyphicon-picture"></i>Subir Foto</a> </td> <td> <a href="AgregarJuego.php?id=<?php echo $objJuego->getId(); ?>"><i class="glyphicon glyphicon-edit"></i>Editar</a> </td> <td> <a href="abmJuego.php?tarea=eliminar&id=<?php echo $objJuego->getId(); ?>"><i class="glyphicon glyphicon-trash"></i>Eliminar</a> </td> </tr> <?php } ?> </tbody> </table> </div> </div> </div> <br> <br> <a href="index.php"><i class="glyphicon glyphicon-arrow-left"></i>Volver a la Pagina Editable</a> <br/> <a href="PaginaPrincipal.php">Pagina Principal</a> </body> </html> <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; public partial class DetalleLibro : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { string id = Request.QueryString["id"]; if (id != null) { Libro obj = LibroBLL.getLibroById(Convert.ToInt32(id)); Autor autor = AutorBLL.getAutorById(obj.autorId); if (obj != null) { imgLibro.ImageUrl = "~/images/" + id + ".jpg"; lbTitulo.Text = obj.titulo; lbIsbnValor.Text = obj.isbn; lbAutorValor.Text = autor.nombre; lbEditorialValor.Text = obj.editorial; lbAnoValor.Text = obj.ano; } } } } }<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Web; /// <summary> /// Descripción breve de LibroBLL /// </summary> public class AutorBLL { public AutorBLL() { // // TODO: Agregar aquí la lógica del constructor // } public static List<Autor>SelectAll() { List<Autor> listaRoles = new List<Autor>(); AutorDSTableAdapters.AutorTableAdapter adapter = new AutorDSTableAdapters.AutorTableAdapter(); AutorDS.AutorDataTable table = adapter.SelectAll(); foreach (AutorDS.AutorRow row in table) { listaRoles.Add(rowToDto(row)); } return listaRoles; } public static Autor SelectByIdS(int id) { Autor listaRoles = new Autor(); AutorDSTableAdapters.AutorTableAdapter adapter = new AutorDSTableAdapters.AutorTableAdapter(); AutorDS.AutorDataTable table = adapter.SelectById(id); if (table.Rows.Count == 0) { return null; } else { foreach (AutorDS.AutorRow row in table) { listaRoles = rowToDto(row); } return listaRoles; } } public static Autor SelectById(int id) { AutorDSTableAdapters.AutorTableAdapter adapter = new AutorDSTableAdapters.AutorTableAdapter(); AutorDS.AutorDataTable table = adapter.SelectById(id); if (table.Rows.Count == 0) { return null; } return rowToDto(table[0]); } public static void insert(string nombre) { AutorDSTableAdapters.AutorTableAdapter adapter = new AutorDSTableAdapters.AutorTableAdapter(); adapter.Insert( nombre); } public static void update(string nombre ,int Original_idLibro) { AutorDSTableAdapters.AutorTableAdapter adapter = new AutorDSTableAdapters.AutorTableAdapter(); adapter.Update( nombre, Original_idLibro); } public static void delete(int id) { AutorDSTableAdapters.AutorTableAdapter adapter = new AutorDSTableAdapters.AutorTableAdapter(); adapter.Delete(id); } private static Autor rowToDto(AutorDS.AutorRow row) { Autor objLibro = new Autor(); objLibro.idAutor = row.idAutor; objLibro.Nombre = row.Nombre; return objLibro; } }<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Web; /// <summary> /// Descripción breve de AutoresBRL /// </summary> public class AutoresBRL { public AutoresBRL() { } public static List<Autores> selectAll() { AutorDSTableAdapters.AutoresTableAdapter adapter = new AutorDSTableAdapters.AutoresTableAdapter(); AutorDS.tblAutoresDataTable table = adapter.GetAutores(); List<Autores> lista = new List<Autores>(); foreach (AutorDS.tblAutoresRow row in table) { lista.Add(rowToDto(row)); } return lista; } private static Autores rowToDto(AutorDS.tblAutoresRow row) { Autores obj = new Autores { codigo_id = row.codigo_id, nombre = row.nombre }; return obj; } public static void add(Autores autor) { AutorDSTableAdapters.AutoresTableAdapter adapter = new AutorDSTableAdapters.AutoresTableAdapter(); adapter.Insert(autor.nombre); } public static void selectByID(int id) { AutorDSTableAdapters.AutoresTableAdapter adapter = new AutorDSTableAdapters.AutoresTableAdapter(); adapter.GetAutorByID(id); } public static void delete(int id) { AutorDSTableAdapters.AutoresTableAdapter adapter = new AutorDSTableAdapters.AutoresTableAdapter(); adapter.Delete(id); } public static void update(Autores autor) { AutorDSTableAdapters.AutoresTableAdapter adapter = new AutorDSTableAdapters.AutoresTableAdapter(); adapter.Update(autor.nombre, autor.codigo_id); } }<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Web; /// <summary> /// Descripción breve de LibroBLL /// </summary> public class LibroBLL { public LibroBLL() {} public static List<Libro> GetLibros() { LibroDSTableAdapters.LibrosTableAdapter adapter = new LibroDSTableAdapters.LibrosTableAdapter(); LibroDS.LibrosDataTable table = adapter.GetLibros(); List<Libro> lista = new List<Libro>(); foreach (LibroDS.LibrosRow row in table) { lista.Add(RowToDto(row)); } return lista; } public static Libro GetLibrosById(int id) { LibroDSTableAdapters.LibrosTableAdapter adapter = new LibroDSTableAdapters.LibrosTableAdapter(); LibroDS.LibrosDataTable table = adapter.GetLibroById(id); if (table.Rows.Count == 0) return null; return RowToDto(table[0]); } public static List<Libro> GetLibrosByGenero(int id) { LibroDSTableAdapters.LibrosTableAdapter adapter = new LibroDSTableAdapters.LibrosTableAdapter(); LibroDS.LibrosDataTable table = adapter.GetLibroByGenero(id); List<Libro> lista = new List<Libro>(); foreach (LibroDS.LibrosRow row in table) { lista.Add(RowToDto(row)); } return lista; } public static List<Libro> GetLibrosByAutor(int id) { LibroDSTableAdapters.LibrosTableAdapter adapter = new LibroDSTableAdapters.LibrosTableAdapter(); LibroDS.LibrosDataTable table = adapter.GetLibrosByAutor(id); List<Libro> lista = new List<Libro>(); foreach (LibroDS.LibrosRow row in table) { lista.Add(RowToDto(row)); } return lista; } public static void insert (Libro objLibro) { LibroDSTableAdapters.LibrosTableAdapter adapter = new LibroDSTableAdapters.LibrosTableAdapter(); adapter.Insert(objLibro.ISBN, objLibro.Titulo, objLibro.Autor_id, objLibro.Editorial, objLibro.año, objLibro.Genero_id); } public static void update(Libro objLibro) { LibroDSTableAdapters.LibrosTableAdapter adapter = new LibroDSTableAdapters.LibrosTableAdapter(); adapter.Update(objLibro.ISBN, objLibro.Titulo, objLibro.Autor_id, objLibro.Editorial, objLibro.año, objLibro.Codigo_id); } public static void delete(int codigo_id) { LibroDSTableAdapters.LibrosTableAdapter adapter = new LibroDSTableAdapters.LibrosTableAdapter(); adapter.Delete(codigo_id); } private static Libro RowToDto(LibroDS.LibrosRow row) { Libro objLibro = new Libro { Codigo_id = row.codigo_id, Titulo = row.titulo, Editorial = row.editorial, año = row.año, ISBN = row.ISBN, Autor_id = row.autor_id }; return objLibro; } }<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; public partial class Registro : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { } protected void btnRegistro_Click(object sender, EventArgs e) { string usuario = txtUsuario.Text.Trim(); if (string.IsNullOrWhiteSpace(usuario)) { //TODO: mostrar error return; } string password = txtPassword.Text.Trim(); if (string.IsNullOrWhiteSpace(password)) { //TODO: mostrar error return; } string confirmar = txtConfirmarPassword.Text.Trim(); if (string.IsNullOrWhiteSpace(confirmar)) { //TODO: mostrar error return; } if (password != confirmar) { //TODO: mostrar error contraseñas diferentes return; } Usuario objUsuario = UsuarioBLL.SelectByUserName(usuario); if (objUsuario != null) { //TODO: mostrar error usuario con ese nombre ya existe return; } try { UsuarioBLL.insert(usuario, TextUtilities.Hash(password)); Response.Redirect("~/Login.aspx"); } catch (Exception ex) { //TODO: mostrar error return; } } }<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Web; /// <summary> /// Descripción breve de Libros /// </summary> public class Libros { public Libros() { // // TODO: Agregar aquí la lógica del constructor // } public int codigo_id { get; set; } public string titulo { get; set; } public string isbn { get; set; } public int año { get; set; } public string editorial { get; set; } public int autor_id { get; set; } }<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; public partial class RegistroGeneros : System.Web.UI.Page { string nombre = ""; protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { string id = Request.QueryString["id"]; if (id != null) { Genero obj = GeneroBLL.getGeneroById(Convert.ToInt32(id)); if (obj != null) { txtNombreGenero.Text = obj.nombre; hdnId.Value = obj.generoId.ToString(); } } } } protected void btnRegistrarGenero_Click(object sender, EventArgs e) { ObtenerInformacion(); try { if (string.IsNullOrEmpty(hdnId.Value)) { GeneroBLL.insertarGenero(nombre); } else { GeneroBLL.UpdateGenero(Convert.ToInt32(hdnId.Value), nombre); } BorrarInformacion(); Response.Redirect("~/AdministracionGeneros.aspx"); } catch (Exception) { Response.Write("<script>window.alert('AVISO: El campo de texto no ha sido llenado.')</script>"); } } public void ObtenerInformacion() { nombre = txtNombreGenero.Text.Trim(); } public void BorrarInformacion() { txtNombreGenero.Text = ""; } }<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Web; /// <summary> /// Descripción breve de Genero /// </summary> public class Genero { public Genero(){ } public int Id { get; set; } public string Nombre { get; set; } public Genero UnGeneroSeleccionado { get { return GeneroBLL.SelectById(Id); } } }<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; public partial class Default2 : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { var g = Request.QueryString["idLibro"]; if (g == null) { } else { int idLibro = Convert.ToInt32(Request.QueryString["idLibro"]); List<Libro> Libro = LibroBLL.SelectById(idLibro); rptCustomersLibro.DataSource = Libro; rptCustomersLibro.DataBind(); } } } }<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Web; /// <summary> /// Descripción breve de AutorBLL /// </summary> public class AutorBLL { public AutorBLL() { // // TODO: Agregar aquí la lógica del constructor // } public static List<Autor> SelectAll() { List<Autor> listaAutores = new List<Autor>(); AutorDSTableAdapters.sp_autor_selectallTableAdapter adapter = new AutorDSTableAdapters.sp_autor_selectallTableAdapter(); AutorDS.sp_autor_selectallDataTable table = adapter.SelectAll(); foreach (AutorDS.sp_autor_selectallRow row in table) { listaAutores.Add(rowToDto(row)); } return listaAutores; } public static Autor SelectById(int id) { AutorDSTableAdapters.sp_autor_selectallTableAdapter adapter = new AutorDSTableAdapters.sp_autor_selectallTableAdapter(); AutorDS.sp_autor_selectallDataTable table = adapter.SelectByid(id); if (table.Rows.Count == 0) { return null; } return rowToDto(table[0]); } public static void Insert(string nombre) { AutorDSTableAdapters.sp_autor_selectallTableAdapter adapter = new AutorDSTableAdapters.sp_autor_selectallTableAdapter(); adapter.Insert(nombre); } public static void Update(string nombre, int id) { AutorDSTableAdapters.sp_autor_selectallTableAdapter adapter = new AutorDSTableAdapters.sp_autor_selectallTableAdapter(); adapter.Update(nombre, id); } public static void Delete(int id) { AutorDSTableAdapters.sp_autor_selectallTableAdapter adapter = new AutorDSTableAdapters.sp_autor_selectallTableAdapter(); adapter.Delete(id); } private static Autor rowToDto(AutorDS.sp_autor_selectallRow row) { Autor objAutor = new Autor(); objAutor.Id_Autor = row.id_Autor; objAutor.Nombreautor = row.nombreautor; return objAutor; } }<file_sep><?php /* * 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. */ /** * Description of CategoriaBLL * * @author rodriguezja */ class CategoriaBLL { public function insert($nombre, $idCategoriaPadre) { $objConexion = new Connection(); $objConexion->queryWithParams("INSERT INTO Categoria(nombre,idCategoriaPadre) VALUES (:pNombre,:pIdCategoriaPadre)", array( ":pNombre" => $nombre, ":pIdCategoriaPadre" => $idCategoriaPadre )); } public function update($nombre, $idCategoriaPadre, $idCategoria) { $objConexion = new Connection(); $objConexion->queryWithParams(" UPDATE Categoria SET nombre = :pNombre, idCategoriaPadre = :pIdCategoriaPadre, WHERE idCategoria = :pIdCategoria", array( ":pNombre" => $nombre, ":pIdCategoriaPadre" => $idCategoriaPadre, ":pIdCategoria" => $idCategoria )); } public function delete($id) { $objConexion = new Connection(); $objConexion->queryWithParams("CALL sp_Persona_Delete(:pId)", array( ":pId" => $id )); } public function selectAll() { $listaPersonas = array(); $objConexion = new Connection(); $res = $objConexion->query("CALL sp_Persona_SelectAll()"); while ($row = $res->fetch(PDO::FETCH_ASSOC)) { $objPersona = $this->rowToDto($row); $listaPersonas[] = $objPersona; } return $listaPersonas; } public function select($id) { $objConexion = new Connection(); $res = $objConexion->queryWithParams("CALL sp_Persona_SelectById(:pId)", array( ":pId" => $id )); if ($res->rowCount() == 0) { return null; } $row = $res->fetch(PDO::FETCH_ASSOC); return $this->rowToDto($row); } function rowToDto($row) { $objPersona = new Persona(); $objPersona->setId($row["id"]); $objPersona->setNombre($row["nombre"]); $objPersona->setApellido($row["apellido"]); $objPersona->setCiudad($row["ciudad"]); $objPersona->setEdad($row["edad"]); return $objPersona; } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; public partial class DetalleLibro : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { string id = Request.QueryString["id"]; if (id != null) { Libro objlibro = LibroBLL.SelectById(Convert.ToInt32(id)); if (objlibro != null) { txtisbn.Text = objlibro.LibroIsbn; txttitulo.Text = objlibro.LibroTitulo; txteditorial.Text = objlibro.LibroEditorial; txtaño.Text = objlibro.LibroAño.ToString(); txtAutor.Text = objlibro.AutorNombre; txtGenero.Text = objlibro.GeneroNombre; hdnId.Value = objlibro.LibroId.ToString(); } } } } }<file_sep>using Cine.Model; using Microsoft.EntityFrameworkCore; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace Cine.Context { public class Cine_DBContext : DbContext { public Cine_DBContext(DbContextOptions options) : base(options) { } public DbSet<Pelicula> Peliculas { get; set; } public DbSet<Categoria> Categorias { get; set; } public DbSet<PeliculaCategoria> PeliculasCategorias { get; set; } protected override void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder.Entity<Pelicula>().ToTable("tblPeliculas"); modelBuilder.Entity<Categoria>().ToTable("tblCategorias"); modelBuilder.Entity<PeliculaCategoria>().ToTable("tblPeliculasCategorias"); } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Web; /// <summary> /// Descripción breve de LibroBLL /// </summary> public class LibroBLL { public LibroBLL() { } public static List<Libro> SelectAll() { List<Libro> listadoLib = new List<Libro>(); DTLibroTableAdapters.sp_Libro_SelectAllTableAdapter adapter = new DTLibroTableAdapters.sp_Libro_SelectAllTableAdapter(); DTLibro.sp_Libro_SelectAllDataTable table = adapter.SelectAll(); foreach (DTLibro.sp_Libro_SelectAllRow row in table) { listadoLib.Add(rowToDto(row)); } return listadoLib; } public static Libro SelectById(int idlibro) { DTLibroTableAdapters.sp_Libro_SelectAllTableAdapter adapter = new DTLibroTableAdapters.sp_Libro_SelectAllTableAdapter(); DTLibro.sp_Libro_SelectAllDataTable table = adapter.SelectAllById(idlibro); if (table.Rows.Count == 0) { return null; } return rowToDto(table[0]); } public static List<Libro> SelectGeneroLibroId(int id) { List<Libro> listadoLib = new List<Libro>(); pruebaLibroGeneroDSTableAdapters.SelectGeneroLibroIdTableAdapter adapter = new pruebaLibroGeneroDSTableAdapters.SelectGeneroLibroIdTableAdapter(); pruebaLibroGeneroDS.SelectGeneroLibroIdDataTable table = adapter.SelectGeneroLibroId(id); foreach (pruebaLibroGeneroDS.SelectGeneroLibroIdRow row in table) { listadoLib.Add(GenerorowToDto2(row)); } return listadoLib; } public static Libro GeneroSelectById(string nombre) { DTLibroTableAdapters.sp_GeneroLibro_SelectByNameTableAdapter adapter = new DTLibroTableAdapters.sp_GeneroLibro_SelectByNameTableAdapter(); DTLibro.sp_GeneroLibro_SelectByNameDataTable table = adapter.GeneroSelectByName(nombre); if (table.Rows.Count == 0) { return null; } return GenerorowToDto(table[0]); } public static void insert(string isbn, string titulo, string editorial, int anho, string nombreautor, string nombregenero) { DTLibroTableAdapters.sp_Libro_SelectAllTableAdapter adapter = new DTLibroTableAdapters.sp_Libro_SelectAllTableAdapter(); adapter.Insert(isbn,titulo,editorial,anho,nombreautor,nombregenero); } public static void update(string isbn, string titulo, string editorial, int anho, string nombreautor, string nombregenero,int idlibro) { DTLibroTableAdapters.sp_Libro_SelectAllTableAdapter adapter = new DTLibroTableAdapters.sp_Libro_SelectAllTableAdapter(); adapter.Update(isbn, titulo, editorial, anho, nombreautor, nombregenero,idlibro); } public static void delete(int idlibro) { DTLibroTableAdapters.sp_Libro_SelectAllTableAdapter adapter = new DTLibroTableAdapters.sp_Libro_SelectAllTableAdapter(); adapter.Delete(idlibro); } private static Libro rowToDto(DTLibro.sp_Libro_SelectAllRow row) { Libro objlibro = new Libro(); objlibro.LibroId = row.libroId; objlibro.LibroIsbn = row.l_isbn; objlibro.LibroTitulo = row.l_titulo; objlibro.LibroEditorial = row.l_editorial; objlibro.LibroAño = row.l_anho; objlibro.AutorNombre = row.a_nombre; objlibro.GeneroNombre = row.g_nombre; return objlibro; } private static Libro GenerorowToDto(DTLibro.sp_GeneroLibro_SelectByNameRow row) { Libro objlibro = new Libro(); objlibro.LibroId = row.libroId; objlibro.LibroTitulo = row.l_titulo; return objlibro; } private static Libro GenerorowToDto2(pruebaLibroGeneroDS.SelectGeneroLibroIdRow row) { Libro objlibro = new Libro(); objlibro.idlibroGenero = row.generolibroId; objlibro.LibroId = row.libroId; objlibro.idGenero = row.generoId; objlibro.GeneroNombre = row.g_nombre; objlibro.LibroTitulo = row.l_titulo; return objlibro; } }<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Web; public class Autor { public Autor() { } public int id { get; set; } public String Nombre { get; set; } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace PracticaMVC1.Models { public class Persona { public int ID { get; set; } public string Nombres { get; set; } public string Apellidos { get; set; } public string Ciudad { get; set; } public int Edad { get; set; } public string NombreCompleto { get { return Nombres + " " + Apellidos; } } public ICollection<Telefono> Telefonos { get; set; } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Web; public class Libro { public Libro() { } public int id { get; set; } public String ISBN { get; set; } public String titulo { get; set; } public int idAutor { get; set; } public string editorial { get; set; } public int anho { get; set; } }<file_sep><?php namespace App\Http\Controllers; use App\Bloque; use Illuminate\Http\Request; class BloqueController extends Controller { /** * Display a listing of the resource. * * @return \Illuminate\Http\Response */ public function index() { $listaBloques = Bloque::all()->toArray(); //esto es como un selec por q me va a mostrar todo return view('bloque.index', compact('listaBloques')); //vamos a la carpeta de view y le vamos a pasar una lista de personas //nombre capera, archivo } /** * Show the form for creating a new resource. * * @return \Illuminate\Http\Response */ public function create() { return view('bloque.create'); } /** * Store a newly created resource in storage. * * @param \Illuminate\Http\Request $request * @return \Illuminate\Http\Response */ public function store(Request $request) { $objBloque = new Bloque(); $objBloque->titulo = $request->get('titulo'); $objBloque->descripcion = $request->get('descripcion'); $objBloque->save(); return redirect('/bloque'); } /** * Display the specified resource. * * @param \App\Bloque $bloque * @return \Illuminate\Http\Response */ public function show(Bloque $bloque) { // } /** * Show the form for editing the specified resource. * * @param \App\Bloque $bloque * @return \Illuminate\Http\Response */ public function edit($id) { $objBloque = Bloque::find($id); return view('bloque.edit', compact('objBloque', 'id')); } /** * Update the specified resource in storage. * * @param \Illuminate\Http\Request $request * @param \App\Bloque $bloque * @return \Illuminate\Http\Response */ public function update(Request $request, $id) { $objBloque = Bloque::find($id); // print_r($request->post()); $objBloque->titulo = $request->get('titulo'); $objBloque->descripcion = $request->get('descripcion'); $objBloque->save(); return redirect('/bloque'); } /** * Remove the specified resource from storage. * * @param \App\Bloque $bloque * @return \Illuminate\Http\Response */ public function destroy($id) { $objBloque = Bloque::find($id); $objBloque->delete(); return redirect('/bloque'); } public function buscar(Request $request) { $valor = $request->input('value'); if($valor == ""){ $tasks = bloque::all(); return response()->json($tasks); }else{ $bloques = bloque::where('titulo','like', '%' . $request->input('value'). '%' )->orWhere('descripcion', 'like', '%' . $request->input('value'). '%')->get(); return response()->json($bloques); } } } <file_sep><?php /* * 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. */ /** * Description of JuegoBLL * * @author COCCO */ class JuegoBLL { public function insert($nombre, $precio, $padre, $descripcion) { $objConexion = new Connection(); $objConexion->queryWithParams("INSERT INTO tblJuegos(nombre, precio, descripcion)VALUES(" . ":pNombre, :pPrecio, :pDescripcion);", array( ":pNombre"=>$nombre, ":pPrecio"=>$precio, ":pDescripcion"=>$descripcion )); $objSentencia=$objConexion->getLastInsertedId(); $objConexion->queryWithParams("INSERT INTO tblCategoriaDeJuego(idJuego, idCategoria)VALUES(" . ":pJuego, :pCategoria);", array( ":pJuego"=>$objSentencia, ":pCategoria"=>$padre )); } public function update($nombre, $precio, $categoria, $descripcion, $id) { $objConexion = new Connection(); $objConexion->queryWithParams("UPDATE tblJuegos SET nombre = :pNombre, precio = :pPrecio, descripcion = :pDescripcion WHERE id = :pId", array( ":pNombre"=>$nombre, ":pPrecio"=>$precio, ":pDescripcion"=>$descripcion, ":pId"=>$id )); $objConexion->queryWithParams("UPDATE tblCategoriaDeJuego SET idCategoria = :pCategoria WHERE id = :pId", array( ":pCategoria"=>$categoria, ":pId"=>$id )); } public function delete($id) { $objConexion = new Connection(); $objConexion->queryWithParams( "DELETE FROM tblCategoriaDeJuego WHERE id = :pId", array( ":pId"=>$id )); $objConexion->queryWithParams( "DELETE FROM tblJuegos WHERE id = :pId", array( ":pId"=>$id )); } public function selectAll() { $listaJuegos = array(); $objConexion = new Connection(); $res = $objConexion->query( "SELECT id , nombre , precio , descripcion FROM tblJuegos"); while($row = $res->fetch(PDO::FETCH_ASSOC)){ $objJuego = $this->rowToDto($row); $listaJuegos[] = $objJuego; } return $listaJuegos; } public function select($id) { $objConexion = new Connection(); $res = $objConexion->queryWithParams( "SELECT J.id , J.nombre , J.precio , J.descripcion, CJ.idJuego FROM tblJuegos J, tblCategoriaDeJuego CJ WHERE J.id = :pId", array( ":pId"=>$id )); if($res->rowCount()==0){ return null; } $row = $res->fetch(PDO::FETCH_ASSOC); return $this->rowToDto($row); } function rowToDto($row) { $objJuego = new Juego(); $objJuego->setId($row["id"]); $objJuego->setNombre($row["nombre"]); $objJuego->setPrecio($row["precio"]); $objJuego->setDescripcion($row["descripcion"]); return $objJuego; } } <file_sep><?php /* |-------------------------------------------------------------------------- | Web Routes |-------------------------------------------------------------------------- | | Here is where you can register web routes for your application. These | routes are loaded by the RouteServiceProvider within a group which | contains the "web" middleware group. Now create something great! | */ Route::get('/', function () { return view('welcome'); }); Route::get('Notas/principal', function () { return view('Notas/principal'); }); Auth::routes(); Route::get('/Notas/principal/{id}/edit','NotaController@traerNotaById'); Route::get('/Notas/principal','NotaController@update'); Route::get('/home', 'HomeController@index')->name('home'); //Route::get('/Notas/principal', 'NotaController@index'); //Route::get('/Notas/principal/{id}','NotaController@update'); Route::resource('/Notas/principal', 'NotaController');<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using System.ComponentModel.DataAnnotations; namespace TiendaPeliculas.Models { public class CategoriaxLibro { [Display(Name = "Película")] public int PeliculaID { get; set; } public Pelicula Pelicula { get; set; } [Display(Name = "Categoría")] public int CategoriaID { get; set; } public Categoria Categoria { get; set; } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; public partial class MasterPage : System.Web.UI.MasterPage { protected void Page_Load(object sender, EventArgs e) { if (IsPostBack) { return; } cargarMenu(); } private void cargarMenu() { object varUsuarioObj = Session["varUsuario"]; if (varUsuarioObj == null) { //No hay usuario autenticado liRolesMenu.Visible = false; liLogin.Visible = true; liRegistro.Visible = true; liCerrarSesion.Visible = false; } else { //hay usuario autenticado liRolesMenu.Visible = true; liLogin.Visible = false; liRegistro.Visible = false; liCerrarSesion.Visible = true; } } protected void btnCerrarSesion_Click(object sender, EventArgs e) { Session.Remove("varUsuario"); Response.Redirect("~/Default.aspx"); } } <file_sep><?php /* * 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. */ /** * Description of accatBLL * * @author Miguel */ class acjueBLL { public function insert($acjueJjue, $acjueNomb, $acjuePrec, $acjueDesc) { $objConexion = new Connection(); $objConexion->queryWithParams("INSERT INTO acjue(acjueJjue,acjueNomb,acjuePrec,acjueDesc) VALUES (:acjueJjue,:acjueNomb,:acjuePrec,:acjueDesc)", array( ":acjueJjue" => $acjueJjue, ":acjueNomb" => $acjueNomb, ":acjuePrec" => $acjuePrec, ":acjueDesc" => $acjueDesc )); } public function update($acjueJjue, $acjueNomb, $acjuePrec, $acjueDesc) { $objConexion = new Connection(); $objConexion->queryWithParams(" UPDATE acjue SET acjueJjue = :acjueJjue, acjueNomb = :acjueNomb, acjuePrec = :acjuePrec, acjueDesc = :acjueDesc WHERE acjueJjue = :pId", array( ":acjueJjue" => $acjueJjue, ":acjueNomb" => $acjueNomb, ":acjuePrec" => $acjuePrec, ":acjueDesc" => $acjueDesc, ":pId" => $acjueJjue )); } public function delete($id) { $objConexion = new Connection(); $objConexion->queryWithParams(" DELETE FROM accxj WHERE accxjCjue = :pId", array( ":pId" => $id )); } public function deleteJxC($accxjCjue) { $objConexion = new Connection(); $objConexion->queryWithParams(" DELETE FROM accxj WHERE accxjCjue = :accxjCjue ", array( ":accxjCjue" => $accxjCjue )); } public function selectAll() { $listaJuegos = array(); $objConexion = new Connection(); $res = $objConexion->query(" SELECT acjueJjue ,acjueNomb, acjuePrec, acjueDesc FROM acjue"); while ($row = $res->fetch(PDO::FETCH_ASSOC)) { $objJuegos = $this->rowToDto($row); $listaJuegos[] = $objJuegos; } return $listaJuegos; } public function selectAllbyCat($accatCcat) { $objConexion = new Connection(); $listaJuegosbyCat = array(); $ress = $objConexion->queryWithParams(" SELECT acjue.* FROM acjue, accat , accxj WHERE accat.`accatCpad` > 0 AND acjue.`acjueJjue` = accxj.`accxjCjue` AND accat.`accatCcat` = accxj.`accxjCcat` AND accat.`accatCcat` = :accatCpad", array( ":accatCpad" => $accatCcat )); $total = $ress->rowCount(); if ($total > 0) { while ($row = $ress->fetch(PDO::FETCH_ASSOC)) { $objJuegos = $this->rowToDto($row); $listaJuegosbyCat[] = $objJuegos; } } return $listaJuegosbyCat; } public function selectMaxAcjueJjue() { $objConexion = new Connection(); $res = $objConexion->query("SELECT MAX(acjueJjue)+1 AS acjueJjue,acjueNomb, acjuePrec, acjueDesc FROM acjue" ); if ($res->rowCount() == 0) { return null; } $row = $res->fetch(PDO::FETCH_ASSOC); return $this->rowToDto($row); } public function select($id) { $objConexion = new Connection(); $res = $objConexion->queryWithParams(" SELECT acjueJjue, acjueNomb, acjuePrec, acjueDesc FROM acjue WHERE acjueJjue = :pId", array( ":pId" => $id )); if ($res->rowCount() == 0) { return null; } $row = $res->fetch(PDO::FETCH_ASSOC); return $this->rowToDto($row); } function rowToDto($row) { $obj = new acjue(); $obj->setAcjueJjue($row["acjueJjue"]); $obj->setAcjueNomb($row["acjueNomb"]); $obj->setAcjuePrec($row["acjuePrec"]); $obj->setAcjueDesc($row["acjueDesc"]); return $obj; } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; public partial class FormularioLibro : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { string id = Request.QueryString["id"]; if (id != null) { Libro objlibro = LibroBLL.SelectById(Convert.ToInt32(id)); if (objlibro != null) { txtisbn.Text = objlibro.LibroIsbn; txttitulo.Text = objlibro.LibroTitulo; txteditorial.Text = objlibro.LibroEditorial; txtaño.Text = objlibro.LibroAño.ToString(); hdnId.Value = objlibro.LibroId.ToString(); } } } } protected void btnGuardar_Click(object sender, EventArgs e) { string isbn = txtisbn.Text; string titulo = txttitulo.Text; string editorial = txteditorial.Text; int anho = Convert.ToInt32(txtaño.Text); string autor = cbautor.SelectedValue.ToString(); string genero = cbgenero.SelectedValue.ToString(); imagen.SaveAs(Server.MapPath("~/Imagenes/" + isbn + ".jpg")); try { if (string.IsNullOrEmpty(hdnId.Value)) { LibroBLL.insert(isbn,titulo,editorial,anho,autor,genero); } else { LibroBLL.update(isbn, titulo, editorial, anho, autor, genero, Convert.ToInt32(hdnId.Value)); } Response.Redirect("~/ListadoLibros.aspx"); } catch (Exception ex) { } } }<file_sep><?php include_once '../DAO/DAL/Connection.php'; include_once '../DAO/DTO/Juego.php'; include_once '../DAO/DTO/Categoria.php'; include_once '../DAO/BLL/JuegoBLL.php'; include_once '../DAO/BLL/CategoriaBLL.php'; $juegoBLL = new JuegoBLL(); $CategoriaBLL = new CategoriaBLL(); $id = 0; $objjuego = null; if (isset($_REQUEST["id"])) { $id = $_REQUEST["id"]; $objjuego = $juegoBLL->select($id); } ?> <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Datos del Juego</title> <link href="../bootstrap-3.3.7-dist/css/bootstrap.min.css" rel="stylesheet" type="text/css"/> <link href="../bootstrap-3.3.7-dist/css/bootstrap-theme.min.css" rel="stylesheet" type="text/css"/> <script src="../bootstrap-3.3.7-dist/js/bootstrap.min.js" type="text/javascript"></script> </head> <body> <div class="container"> <div class="row"> <div class="col-md-6"> <h2> Detalles del Juego </h2> <form action="index.php" method="POST" id="usrform"> <input type="hidden" value="<?php echo "agregarCategoria"; // echo "insertar"; ?>" name="tarea"/> <input type="hidden" value="<?php echo $id; ?>" name="id"/> <div class="form-group"> <label> Nombre: </label> <input class="form-control" required="required" type="text" name="nombre" readonly value="<?php if ($objjuego != null) { echo $objjuego->getNombre(); } ?>"/> </div> <div class="form-group"> <label> Precio: </label> <input class="form-control" required="required" type="text" readonly name="precio" value="<?php if ($objjuego != null) { echo $objjuego->getPrecio(); } ?>"/> </div> <div class="form-group"> <label> Categorias Del Juego: </label> <input class="form-control" required="required" readonly type="text" name="precio" value="<?php // For de categorias $listaCategorias = $CategoriaBLL->selectCategoriasDeJuego($id); foreach ($listaCategorias as $objCategoria) { echo $objCategoria->getNombre() . ", "; } // $objCategoria ?>" /> </div> <BR> <BR> <BR> ` <div class="form-group"> <label> Agregar Categoria: </label> <select class="form-control" required="required" name="categoria"> <?php $listaCat = $CategoriaBLL->selectCategoriasNoEnJuego($id); foreach ($listaCat as $objCategoria) { ?> <option value="<?php // For de categorias echo $objCategoria->getId(); ?>" ><?php echo $objCategoria->getNombre(); ?></option> <?php } ?> </select> </div> <div class="form-group"> <input class="btn btn-primary" type="submit" value="Agregar" /> <a href="index.php" class="btn btn-link">Cancelar</a> </div> </form> </div> </div> </div> </body> </html> <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Web; /// <summary> /// Descripción breve de Libro /// </summary> public class Libro { public Libro() { // // TODO: Agregar aquí la lógica del constructor // } public int id_Libro { get; set; } public string isbn { get; set; } public string titulo { get; set; } public string editorial { get; set; } public int ano { get; set; } public int id_Autor { get; set; } public int id_Genero { get; set; } public int id_GenerarLibro { get; set; } public Libro librito { get { return LibroBLL.SelectById(id_Libro); } } } <file_sep><?php namespace App\Http\Controllers; use App\Nota; use Illuminate\Http\Request; class NotaController extends Controller { /** * Display a listing of the resource. * * @return \Illuminate\Http\Response */ public function index() { $listaNotas = Nota::all()->toArray(); //esto es como un selec por q me va a mostrar todo return view('nota.index', compact('listaNotas')); //vamos a la carpeta de view y le vamos a pasar una lista de personas //nombre capera, archivo } /** * Show the form for creating a new resource. * * @return \Illuminate\Http\Response */ public function create() { return view('nota.create'); } /** * Store a newly created resource in storage. * * @param \Illuminate\Http\Request $request * @return \Illuminate\Http\Response */ public function store(Request $request) { $objNota = new Nota(); $objNota->titulo = $request->get('titulo'); $objNota->descripcion = $request->get('descripcion'); $objNota->save(); return redirect('/nota'); } /** * Display the specified resource. * * @param \App\Bloque $bloque * @return \Illuminate\Http\Response */ public function show(Nota $nota) { // } /** * Show the form for editing the specified resource. * * @param \App\Bloque $bloque * @return \Illuminate\Http\Response */ public function edit($id) { $objNota = Nota::find($id); return view('nota.edit', compact('objNota', 'id')); } /** * Update the specified resource in storage. * * @param \Illuminate\Http\Request $request * @param \App\Bloque $bloque * @return \Illuminate\Http\Response */ public function update(Request $request, $id) { $objNota = Nota::find($id); // print_r($request->post()); $objNota->titulo = $request->get('titulo'); $objNota->descripcion = $request->get('descripcion'); $objNota->save(); return redirect('/nota'); } /** * Remove the specified resource from storage. * * @param \App\Bloque $bloque * @return \Illuminate\Http\Response */ public function destroy($id) { $objNota = Nota::find($id); $objNota->delete(); return redirect('/nota'); } public function vermundo($id){ $objNota = Nota::find($id); return "Su titulo es: " . $objNota->descripcion; } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; public partial class Pages_Libros : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { } protected void btnEliminar_Click(object sender, EventArgs e) { LinkButton btnEliminar = (LinkButton)sender; int id = Convert.ToInt32(btnEliminar.CommandArgument); GeneroBLL.delete(id); gridGeneros.DataBind(); } protected void btnVerLibros_Click(object sender, EventArgs e) { LinkButton btnVerLibros = (LinkButton)sender; int id = Convert.ToInt32(btnVerLibros.CommandArgument); Response.Redirect("~/Pages/ListaLibros.aspx"); } protected void btnEliminarAutor_Click(object sender, EventArgs e) { LinkButton btnEliminar = (LinkButton)sender; int id = Convert.ToInt32(btnEliminar.CommandArgument); AutorBLL.delete(id); gridAutores.DataBind(); } }<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Web; /// <summary> /// Descripción breve de Libro /// </summary> public class Libro { public Libro() { } public int Id { get; set; } public string Isbn { get; set; } public string Titulo { get; set; } public string nombreAutor { get; set; } public int idAutor { get; set; } public string nombreGenero { get; set; } public string Editorial { get; set; } public int Anho { get; set; } public Libro UnLibroSeleccionado { get { return LibroBLL.SelectById(Id); } } }<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Web; /// <summary> /// Descripción breve de GeneroLibro /// </summary> public class GeneroLibro { //public int idGenero { get { return Genero.id; } } public GeneroLibro() { // // TODO: Agregar aquí la lógica del constructor // } }<file_sep><?php include_once './DAO/DAL/Connection.php'; include_once './DAO/DTO/Juego.php'; include_once './DAO/BLL/JuegoBLL.php'; include_once './DAO/DTO/Categoria.php'; include_once './DAO/BLL/CategoriaBLL.php'; $juegoBLL = new JuegoBLL(); $categoriaBLL = new CategoriaBLL(); $id = 0; if (isset($_REQUEST["id"])) { $id = $_REQUEST["id"]; } ?> <!DOCTYPE html> <html lang="es"> <head> <link href="css/bootstrap.min.css" rel="stylesheet" type="text/css"/> <link href="css/bootstrap-theme.min.css" rel="stylesheet" type="text/css"/> <script src="js/bootstrap.min.js" type="text/javascript"></script> <link href="css/style.css" rel="stylesheet" type="text/css"/> <meta charset="utf-8"> <title></title> </head> <body> <div class="container"> <div class="row "> <input type="hidden" value="foto" name="tarea"/> <input type="hidden" value="<?php echo $id; ?>" name="id"/> <div class="imagen" style=" background-image: url('img/<?php echo $id ?>.jpg');"> </div> <img src="img/<?php echo $id ?>.jpg" alt="" class="img-responsive" id="img2" > <div class="detalle col-lg-12 form-group"> <label><?php echo $juegoBLL->select($id)->getNombre(); ?></label> <label contenteditable="false" class="col-md-12"><?php echo $juegoBLL->select($id)->getDescripcion(); ?></label> </div> </div> </body> </html><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.Windows.Forms; public partial class frmRegistroLibro : System.Web.UI.Page { public Libro LibroActual { set { ViewState["LibroActual"] = value; } get { return (Libro)ViewState["LibroActual"]; } } protected void Page_Load(object sender, EventArgs e) { if (IsPostBack) return; if (LibroActual == null) { LibroActual = new Libro(); } int ValorRecibido = Convert.ToInt16(Request.QueryString["id"]); if (ValorRecibido > 0) { CargarDatos(ValorRecibido); } try { if (ValorRecibido <= 0) { AutorComboBox.DataSource = AutorBLL.GetAutores(); AutorComboBox.DataBind(); GeneroComboBox.DataSource = GeneroBLL.GetGeneros(); GeneroComboBox.DataBind(); } } catch (Exception ex) { } } protected void btnGuardar_Click(object sender, EventArgs e) { int ValorRecibido = Convert.ToInt16(Request.QueryString["id"]); if (ValorRecibido > 0) { ModificarLibro(ValorRecibido); } else { LibroActual.isbn = isbn.Text; LibroActual.titulo = titulo.Text; LibroActual.editorial = editorial.Text; LibroActual.edicion = Convert.ToInt32(edicion.Text); //LibroActual.cubierta = imagenAutor.Text; LibroActual.idAutor = Convert.ToInt32(AutorComboBox.SelectedValue); LibroActual.idGenero = Convert.ToInt32(GeneroComboBox.SelectedValue); //Fileupload codigo Boolean fileOK = false; String path = Server.MapPath("~/Uploads/"); if (imagenLibro.HasFile) { String fileExtension = System.IO.Path.GetExtension(imagenLibro.FileName).ToLower(); String[] allowedExtensions = {".gif", ".png", ".jpeg", ".jpg"}; for (int i = 0; i < allowedExtensions.Length; i++) { if (fileExtension == allowedExtensions[i]) { fileOK = true; } } } if (fileOK) { try { imagenLibro.PostedFile.SaveAs(path + imagenLibro.FileName); label1.Visible = true; label1.Text = "File uploaded!"; LibroActual.cubierta = imagenLibro.FileName; } catch (Exception ex) { label1.Text = "File could not be uploaded."; } } else { if (!imagenLibro.HasFile) { LibroActual.cubierta = ""; } else { label1.Text = "Cannot accept files of this type."; } } try { //Persona obj = SeguridadUtils.GetUserInSession(); //PersonaActual.personaId = obj.personaId; int LibroIdActual = LibroBLL.InsertarLibro(LibroActual); } catch (Exception ex) { MessageBox.Show("Error al guardar los datos: " + ex); return; } MessageBox.Show("Los datos fueron guardados con Exito!"); Response.Redirect("Default.aspx"); } } //Cargar Datos protected void CargarDatos(int valor) { AutorComboBox.DataSource = AutorBLL.GetAutores(); AutorComboBox.DataBind(); GeneroComboBox.DataSource = GeneroBLL.GetGeneros(); GeneroComboBox.DataBind(); LibroActual = LibroBLL.GetLibroById(valor); // titulo.InnerText = "MODIFICACION DE DATOS EVENTO: " + EventoActual.nombre; isbn.Text = LibroActual.isbn; titulo.Text = LibroActual.titulo; editorial.Text = LibroActual.editorial; edicion.Text = Convert.ToString(LibroActual.edicion); Autor autorActual = new Autor(); autorActual = AutorBLL.GetAutorById(LibroActual.idAutor); AutorComboBox.Items.Insert(0, new ListItem(autorActual.nombre, Convert.ToString(autorActual.idAutor))); Genero GeneroActual = new Genero(); GeneroActual = GeneroBLL.GetGeneroById(LibroActual.idGenero); GeneroComboBox.Items.Insert(0, new ListItem(GeneroActual.nombre, Convert.ToString(GeneroActual.idGenero))); imagenLibro.Visible = true; btnGuardar.Text = "MODIFICAR EVENTO"; } //Fin Cargar datos //modificar Datos protected void ModificarLibro(int valor) { LibroActual.isbn = isbn.Text; LibroActual.titulo = titulo.Text; LibroActual.editorial = editorial.Text; LibroActual.edicion = Convert.ToInt32(edicion.Text); LibroActual.idAutor = Convert.ToInt32(AutorComboBox.SelectedValue); LibroActual.idGenero = Convert.ToInt32(GeneroComboBox.SelectedValue); //Fileupload codigo Boolean fileOK = false; String path = Server.MapPath("~/Uploads/"); if (imagenLibro.HasFile) { String fileExtension = System.IO.Path.GetExtension(imagenLibro.FileName).ToLower(); String[] allowedExtensions = {".gif", ".png", ".jpeg", ".jpg"}; for (int i = 0; i < allowedExtensions.Length; i++) { if (fileExtension == allowedExtensions[i]) { fileOK = true; } } } if (fileOK) { try { imagenLibro.PostedFile.SaveAs(path + imagenLibro.FileName); label1.Visible = true; label1.Text = "File uploaded!"; LibroActual.cubierta = imagenLibro.FileName; } catch (Exception ex) { label1.Text = "File could not be uploaded."; } } else { label1.Text = "Cannot accept files of this type."; } try { LibroBLL.ModificarLibro(LibroActual); } catch (Exception ex) { MessageBox.Show("Error al guardar los datos: " + ex); return; } MessageBox.Show("Los datos fueron modificados con Exito!"); Response.Redirect("AdministracionLibros.aspx"); } //fin modificar protected void btnBorrar_Click(object sender, EventArgs e) { } protected void AutorComboBox_DataBound(object sender, EventArgs e) { AutorComboBox.Items.Insert(0, new ListItem("Seleccione un Autor", "90")); } protected void GeneroComboBox_DataBound(object sender, EventArgs e) { GeneroComboBox.Items.Insert(0, new ListItem("Seleccione un Genero", "")); } protected void nuevoAutor_Click(object sender, EventArgs e) { } }<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Web; /// <summary> /// Summary description for RolBLL /// </summary> public class RolBLL { public RolBLL() { } public static List<Rol> SelectAll() { List<Rol> listaRoles = new List<Rol>(); RolDSTableAdapters.RolesTableAdapter adapter = new RolDSTableAdapters.RolesTableAdapter(); RolDS.RolesDataTable table = adapter.SelectAll(); foreach (RolDS.RolesRow row in table) { listaRoles.Add(rowToDto(row)); } return listaRoles; } public static Rol SelectById(int id) { RolDSTableAdapters.RolesTableAdapter adapter = new RolDSTableAdapters.RolesTableAdapter(); RolDS.RolesDataTable table = adapter.SelectAll(); if (table.Rows.Count == 0) { return null; } return rowToDto(table[0]); } public static void insert(string nombreRol) { RolDSTableAdapters.RolesTableAdapter adapter = new RolDSTableAdapters.RolesTableAdapter(); adapter.Insert(nombreRol); } public static void update(string nombreRol, int id) { RolDSTableAdapters.RolesTableAdapter adapter = new RolDSTableAdapters.RolesTableAdapter(); adapter.Update(nombreRol, id); } public static void delete(int id) { RolDSTableAdapters.RolesTableAdapter adapter = new RolDSTableAdapters.RolesTableAdapter(); adapter.Delete(id); } private static Rol rowToDto(RolDS.RolesRow row) { Rol objRol = new Rol(); objRol.ID = row.id; objRol.NombreRol = row.nombreRol; return objRol; } }<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Web; /// <summary> /// Descripción breve de GeneroBLL /// </summary> public class GeneroBLL { public GeneroBLL() { } public static List<Genero> SelectAll() { List<Genero> listaGeneros = new List<Genero>(); GeneroDSTableAdapters.tblGeneroTableAdapter adapter = new GeneroDSTableAdapters.tblGeneroTableAdapter(); GeneroDS.tblGeneroDataTable table = adapter.SelectAll(); foreach (GeneroDS.tblGeneroRow row in table) { listaGeneros.Add(rowToDto(row)); } return listaGeneros; } public static Genero SelectById(int id) { GeneroDSTableAdapters.tblGeneroTableAdapter adapter = new GeneroDSTableAdapters.tblGeneroTableAdapter(); GeneroDS.tblGeneroDataTable table = adapter.SelectById(id); if (table.Rows.Count == 0) { return null; } return rowToDto(table[0]); } public static Genero SelectByIdGenero(int id) { GeneroDSTableAdapters.tblGeneroTableAdapter adapter = new GeneroDSTableAdapters.tblGeneroTableAdapter(); GeneroDS.tblGeneroDataTable table = adapter.SelectByIdGenero(id); if (table.Rows.Count == 0) { return null; } return rowToDto(table[0]); } public static void Insert(string nombre) { GeneroDSTableAdapters.tblGeneroTableAdapter adapter = new GeneroDSTableAdapters.tblGeneroTableAdapter(); adapter.Insert(nombre); } public static void Update(string nombre, int id) { GeneroDSTableAdapters.tblGeneroTableAdapter adapter = new GeneroDSTableAdapters.tblGeneroTableAdapter(); adapter.Update(nombre, id); } public static void Delete(int id) { GeneroDSTableAdapters.tblGeneroTableAdapter adapter = new GeneroDSTableAdapters.tblGeneroTableAdapter(); adapter.Delete(id); } private static Genero rowToDto(GeneroDS.tblGeneroRow row) { Genero objGenero = new Genero(); objGenero.Id = row.id; objGenero.Nombre = row.nombre; return objGenero; } }<file_sep><?php namespace App\Http\Controllers; use App\Notas; use Illuminate\Http\Request; class NotasController extends Controller { /** * Display a listing of the resource. * * @return \Illuminate\Http\Response */ public function index() { $lista = Notas::all()->toArray(); return view('notas.index', compact('lista')); } /** * Show the form for creating a new resource. * * @return \Illuminate\Http\Response */ public function create() { // } /** * Store a newly created resource in storage. * * @param \Illuminate\Http\Request $request * @return \Illuminate\Http\Response */ public function store(Request $request) { $nuevaNota = new Notas; $nuevaNota->titulo = $request->input('titulo'); $nuevaNota->texto = $request->input('nota'); $nuevaNota->save(); return redirect('/notas'); } /** * Display the specified resource. * * @param \App\Notas $notas * @return \Illuminate\Http\Response */ public function show(Notas $notas) { // } /** * Show the form for editing the specified resource. * * @param \App\Notas $notas * @return \Illuminate\Http\Response */ public function edit($nota_id) { return view('notas.editar'); } /** * Update the specified resource in storage. * * @param \Illuminate\Http\Request $request * @param \App\Notas $notas * @return \Illuminate\Http\Response */ public function update(Request $request, Notas $notas) { // } /** * Remove the specified resource from storage. * * @param \App\Notas $notas * @return \Illuminate\Http\Response */ public function destroy($ntoa_id) { $notaEliminar = Notas::find($ntoa_id); $notaEliminar->delete(); return redirect('/notas'); } } <file_sep>using Microsoft.EntityFrameworkCore; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using TiendaPeliculas.Models; namespace TiendaPeliculas.Context { public class ProyectoTiendaPeliculasContext : DbContext { public DbSet<Pelicula> Peliculas { get; set; } public DbSet<Categoria> Categorias { get; set; } public DbSet<CategoriaxLibro> CategoriasxLibro { get; set; } public ProyectoTiendaPeliculasContext(DbContextOptions options) : base(options) { } protected override void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder.Entity<CategoriaxLibro>().ToTable("CategoriaxLibro"); modelBuilder.Entity<CategoriaxLibro>().HasKey(t => new { t.PeliculaID, t.CategoriaID }); modelBuilder.Entity<CategoriaxLibro>() .HasOne(p => p.Pelicula) .WithMany(x => x.Categoria) .HasForeignKey(y => y.PeliculaID); modelBuilder.Entity<CategoriaxLibro>() .HasOne(p => p.Categoria) .WithMany(x => x.Pelicula) .HasForeignKey(y => y.CategoriaID); modelBuilder.Entity<Pelicula>().ToTable("Pelicula"); modelBuilder.Entity<Categoria>().ToTable("Categoria"); } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace PracticaMVC1.Models { public class Persona { public int ID { get; set; } public string Nombres { get; set; } public string Apellidos { get; set; } public string Ciudad { get; set; } public int Edad { get; set; } } } <file_sep>using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Threading.Tasks; namespace PracticaMVC1.Models { public class Telefono { public int ID { get; set; } [Display(Name = "Persona")] public int PersonaID { get; set; } public string Numero { get; set; } [Display(Name = "Personita")] public Persona Persona { get; set; } } } <file_sep><?php include_once './DAO/DAL/Connection.php'; include_once './DAO/DTO/Persona.php'; include_once './DAO/BLL/PersonaBLL.php'; $personaBLL = new PersonaBLL(); $id = 0; $objPersona = null; if (isset($_REQUEST["id"])) { $id = $_REQUEST["id"]; } ?> <!DOCTYPE html> <!-- 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. --> <html> <head> <meta charset="UTF-8"> <title>Foto de Perfil</title> <link href="css/bootstrap.min.css" rel="stylesheet" type="text/css"/> <link href="css/bootstrap-theme.min.css" rel="stylesheet" type="text/css"/> <script src="js/bootstrap.min.js" type="text/javascript"></script> </head> <body> <div class="container" style="margin-top:10px;"> <div class="row"> <div class="col-md-6"> <div class="panel panel-primary"> <div class="panel-heading"> Agregar foto de perfil </div> <div class="panel-body"> <form action="index.php" enctype="multipart/form-data" method="POST"> <input type="hidden" value="fotoperfil" name="tarea"/> <input type="hidden" value="<?php echo $id; ?>" name="id"/> <div class="form-group"> <input type="file" name="archivo" required="required"/> <img class="img-responsive" style="max-width: 100px" src="img/<?php echo $id ?>.jpg" /> </div> <div class="form-group"> <input class="btn btn-primary" type="submit" value="Subir Foto"/> <a href="index.php" class="btn btn-link">Cancelar</a> </div> </form> </div> </div> </div> </div> </div> </body> </html> <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; public partial class ListadoLibros : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { //if (!IsPostBack) //{ // string nombre = Request.QueryString["id"]; // if (nombre != null) // { // Libro objgenero = LibroBLL.GeneroSelectById(nombre); // if (objgenero != null) // { // hdnId.Value = objgenero.GeneroNombre.ToString(); // grvLibroGenero.DataBind(); // } // } //} } }<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.Data; using System.IO; public partial class NuevoLibro : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { } protected void Button1_Click(object sender, EventArgs e) { try { if (fileUploader1.HasFile) { // Se verifica que la extensión sea de un formato válido string ext = fileUploader1.FileName; Libro nuevoLibro = new Libro(); nuevoLibro.idAutor = Convert.ToInt32(DropDownList1.SelectedValue.ToString()); nuevoLibro.ISBN = ISBN.Text; nuevoLibro.Editorial = Editorial.Text; nuevoLibro.Anho = Convert.ToInt32(anho.Text); nuevoLibro.Titulo = titulo.Text; GuardarArchivo(fileUploader1.PostedFile, nuevoLibro); } else { } } catch (Exception ex) { } } private void GuardarArchivo(HttpPostedFile file, Libro nuevoLibro) { if (file !=null) { string archivo = (DateTime.Now.ToString("yyyyMMddHHmmss") + "-" + nuevoLibro.idLibro + "-" + file.FileName).ToLower(); file.SaveAs(Server.MapPath("~/temp/" + archivo)); LibroBLL.insert(nuevoLibro.ISBN,nuevoLibro.Titulo,nuevoLibro.idAutor,nuevoLibro.Editorial,nuevoLibro.Anho, archivo); } Response.Redirect("libros.aspx"); } }<file_sep><!DOCTYPE html> <!-- 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. --> <?php include_once './DAO/DAL/Connection.php'; include_once './DAO/DTO//Categoria.php'; include_once './DAO/DTO//CategoriaJuego.php'; include_once './DAO/BLL/CategoriaBLL.php'; $categoriaBLL = new CategoriaBLL(); function mostrarMensaje($mensaje) { echo "<script>alert('$mensaje')</script>"; } if(isset($_REQUEST["tarea"])){ $tarea = $_REQUEST["tarea"]; switch ($tarea){ case "insertar" : if(!isset($_REQUEST["nombre"])){ mostrarMensaje("Error al insertar, faltan parametros."); return; }else{ $nombre = $_REQUEST["nombre"]; $padre = $_REQUEST["padre"]; if($padre == NULL){ $categoriaBLL->insert($nombre, NULL); }else{ $categoriaBLL->insert($nombre, $padre); } } break; case "actualizar": if(!isset($_REQUEST["nombre"]) || !isset($_REQUEST["padre"]) || !isset($_REQUEST["id"])){ mostrarMensaje("Error al actualizar, faltan parametros."); return; }else{ $id = $_REQUEST["id"]; $nombre = $_REQUEST["nombre"]; $padre = $_REQUEST["padre"]; if($padre == null){ $categoriaBLL->update($nombre, NULL, $id); }else{ $categoriaBLL->update($nombre, $padre, $id); }} break; case "eliminar": if(!isset($_REQUEST["id"])){ mostrarMensaje("Error al eliminar, faltan parametros."); return; }else{ $id = $_REQUEST["id"]; if($categoriaBLL->selectName($id) == NULL){ $categoriaBLL->delete($id);}else{ echo "<script href='Categorias.php'>alert('No se puede eliminar')</script>"; } } break; } } ?> <html> <head> <meta charset="UTF-8"> <link href="css/bootstrap.min.css" rel="stylesheet" type="text/css"/> <link href="css/bootstrap-theme.min.css" rel="stylesheet" type="text/css"/> <script src="js/bootstrap.min.js" type="text/javascript"></script> <title></title> </head> <body> <div class="container"> <div class="row"> <div class="col-md-12"> <div class="well"> <a href="AgregarCategoria.php">Agregar</a> <a href="index.php">Inicio</a> </div> <table> <thead> <tr> <th>ID</th> <th>NOMBRE</th> <th>C. PADRE</th> </tr> </thead> <tbody> </tbody> <?php $listaCategorias = $categoriaBLL->selectAll(); foreach ($listaCategorias as $objCategoria) { ?> <tr> <td> <?php echo $objCategoria->getId() ?> </td> <td> <?php echo $objCategoria->getNombre() ?> </td> <td> <?php echo $objCategoria->getCategoriaPadre() ?> </td> <td> <a href="AgregarCategoria.php?id=<?php echo $objCategoria->getId();?>">Editar</a> </td> <td> <a href="Categorias.php?tarea=eliminar&id=<?php echo $objCategoria->getId();?>">Eliminar</a> </td> </tr> <?php } ?> </table> </div> </div> </div> </body> </html> <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; public partial class FormularioGenero : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { string id = Request.QueryString["id"]; if (id != null) { Genero objgenero = GeneroBLL.SelectById(Convert.ToInt32(id)); if (objgenero != null) { txtgenero.Text = objgenero.NombreGenero; hdnId.Value = objgenero.GeneroId.ToString(); } } } } protected void btnGuardar_Click(object sender, EventArgs e) { string genero = txtgenero.Text; try { if (string.IsNullOrEmpty(hdnId.Value)) { GeneroBLL.insert(genero); } else { GeneroBLL.update(genero, Convert.ToInt32(hdnId.Value)); } Response.Redirect("~/ListadoGenero.aspx"); } catch (Exception ex) { } } }<file_sep><?php /* * 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. */ /** * Description of Juego * * @author COCCO */ class Juego { private $id; private $nombre; private $precio; private $descripcion; public function getId() { return $this->id; } public function getNombre() { return $this->nombre; } public function getPrecio() { return $this->precio; } public function getDescripcion() { return $this->descripcion; } public function setId($id) { $this->id = $id; } public function setNombre($nombre) { $this->nombre = $nombre; } public function setPrecio($precio) { $this->precio = $precio; } public function setDescripcion($descripcion) { $this->descripcion = $descripcion; } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; public partial class RegistroAutores : System.Web.UI.Page { string nombre = ""; protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { string id = Request.QueryString["id"]; if (id != null) { Autor obj = AutorBLL.getAutorById(Convert.ToInt32(id)); if (obj != null) { txtNombreAutor.Text = obj.nombre; hdnId.Value = obj.autorId.ToString(); } } } } protected void btnRegistrarAutor_Click(object sender, EventArgs e) { ObtenerInformacion(); try { if (string.IsNullOrEmpty(hdnId.Value)) { AutorBLL.InsertarAutor(nombre); } else { AutorBLL.UpdateAutor(Convert.ToInt32(hdnId.Value), nombre); } txtNombreAutor.Text = ""; Response.Redirect("~/AdministracionAutores.aspx"); } catch (Exception) { Response.Write("<script>window.alert('AVISO: El campo de texto no ha sido llenado.')</script>"); } } public void ObtenerInformacion() { nombre = txtNombreAutor.Text.Trim(); } }<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; public partial class Libros : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { cargarDatos(); } protected void cargarDatos() { int ValorAutor = Convert.ToInt16(Request.QueryString["idAutor"]); int ValorGenero = Convert.ToInt16(Request.QueryString["idGenero"]); if (ValorAutor > 0) { LibrosRepeater.DataSource = LibroBLL.GetLibroByAutorIdToList(ValorAutor); LibrosRepeater.DataBind(); } if (ValorGenero > 0) { try { LibrosRepeater.DataSource = LibroBLL.GetLibroByGeneroIdToList(ValorGenero); LibrosRepeater.DataBind(); } catch (Exception) { throw; } } if (ValorAutor <= 0 && ValorGenero <= 0) { try { LibrosRepeater.DataSource = LibroBLL.GetLibros(); LibrosRepeater.DataBind(); } catch (Exception) { throw; } } } protected void LibrosRepeater_ItemCommand(object source, RepeaterCommandEventArgs e) { if (e.CommandName == "Comando") { string id = e.CommandArgument == null ? "0" : e.CommandArgument.ToString(); Response.Redirect("Item-Libro.aspx?id=" + id); } } }<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using TiendaPeliculas.Context; using TiendaPeliculas.Models; namespace TiendaPeliculas.Controllers { public class HomeController : Controller { private readonly ProyectoTiendaPeliculasContext db; public HomeController(ProyectoTiendaPeliculasContext context) { db = context; } public IActionResult Index() { /*db.Database.EnsureCreated(); var pelicula = new Pelicula {Titulo = "Recuerdame", Descripcion = "Cuenta el trágico drama de una familia que empieza a descomponerse tras el suicidio de uno de sus hijos. A pesar de ello, el otro hijo, Tyler, no pierde la esperanza de llegar a enamorarse y ser feliz. Es entonces cuando conoce a una joven que ha presenciado el suicidio de su propia madre. A pesar de todas las desgracias familiares, ambos lucharán para que su historia de amor funcione.", Horario = "18:00", Puntuacion = 5 }; db.Peliculas.Add(pelicula); var categoria = new Categoria { Nombre = "Suspenso" }; db.Categorias.Add(categoria); var categoriaxLibro = new CategoriaxLibro { PeliculaID = pelicula.ID, CategoriaID = categoria.ID, Pelicula = pelicula, Categoria = categoria}; db.CategoriasxLibro.Add(categoriaxLibro); pelicula.Categoria.Add(categoriaxLibro); categoria.Pelicula.Add(categoriaxLibro); db.SaveChanges();*/ return View(); } public IActionResult About() { ViewData["Message"] = "Your application description page."; return View(); } public IActionResult Contact() { ViewData["Message"] = "Your contact page."; return View(); } public IActionResult Error() { return View(); } } } <file_sep><?php include_once './DAO/DAL/Connection.php'; include_once './DAO/DTO/Persona.php'; include_once './DAO/BLL/PersonaBLL.php'; $personaBLL = new PersonaBLL(); ?> <!DOCTYPE html> <!-- 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. --> <html> <head> <meta charset="UTF-8"> <title></title> </head> <body> <?php $listaPersonas = $personaBLL->selectAll(); ?> <select> <option>Categoria 1</option> </select> <select> <?php foreach ($listaPersonas as $objPersona) { ?> <option value="<?php echo $objPersona->getId();?>"><?php echo $objPersona->getNombre() . " " . $objPersona->getApellido(); ?></option> <?php } ?> </select> <div class="form-group"> <input class="btn btn-primary" type="submit" value="Subir Foto"/> <a href="index.php" class="btn btn-link">Cancelar</a> </div> </body> </html> <file_sep><?php include_once './DAO/DAL/Connection.php'; include_once './DAO/DTO/Categoria.php'; include_once './DAO/BLL/CategoriaBLL.php'; $categoriaBLL = new CategoriaBLL(); if (isset($_REQUEST["tarea"])) { $tarea = $_REQUEST["tarea"]; switch ($tarea) { case "insertar": if (!isset($_REQUEST["nombre"]) || !isset($_REQUEST["idCategoriaPadre"])) { mostrarMensaje('Error al insertar, parametros incompletos'); } else { $nombre = $_REQUEST["nombre"]; $idCategoriaPadre = $_REQUEST["idCategoriaPadre"]; $categoriaBLL->insert($nombre, $idCategoriaPadre); } break; case "actualizar": if (!isset($_REQUEST["nombre"]) || !isset($_REQUEST["idCategoriaPadre"]) || !isset($_REQUEST["id"])) { mostrarMensaje('Error al actualizar, parametros incompletos'); } else { $id = $_REQUEST["id"]; $nombre = $_REQUEST["nombre"]; $idCategoriaPadre = $_REQUEST["idCategoriaPadre"]; $categoriaBLL->update($nombre, $idCategoriaPadre, $id); } break; case "eliminar": if (!isset($_REQUEST["id"])) { mostrarMensaje('Error al actualizar, parametros incompletos'); } else { $id = $_REQUEST["id"]; $categoriaBLL->delete($id); } break; } } ?> <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Categoria</title> <link href="css/bootstrap.min.css" rel="stylesheet" type="text/css"/> <link href="css/bootstrap-theme.min.css" rel="stylesheet" type="text/css"/> <script src="js/bootstrap.min.js" type="text/javascript"></script> </head> <body> <div class="container"> <div class="row"> <div class="col-md-12"> <div > <a class="btn btn-primary" href="AgregarCategoria.php">Agregar Categoria</a> </div> <table class="table"> <thead> <tr> <th>ID</th> <th>Nombre</th> <th>ID Padre</th> <th>Editar</th> <th>Eliminar</th> </tr> </thead> <tbody> <?php $listaCategorias = $categoriaBLL->selectAll(); foreach ($listaCategorias as $objCategoria) { ?> <tr> <td> <?php echo $objCategoria->getId(); ?> </td> <td> <?php echo $objCategoria->getNombre(); ?> </td> <td> <?php echo $objCategoria->getIdCategoriaPadre(); ?> </td> <td> <a href="AgregarCategoria.php?id=<?php echo $objCategoria->getId(); ?>">Editar</a> </td> <td> <a href="abmCategoria.php?tarea=eliminar&id=<?php echo $objCategoria->getId(); ?>">Eliminar</a> </td> </tr> <?php } ?> </tbody> </table> </div> </div> </div> <br> <br> <a href="index.php"><i class="glyphicon glyphicon-arrow-left"></i>Volver a la Pagina Editable</a> <br/> <a href="PaginaPrincipal.php">Pagina Principal</a> </body> </html> <file_sep>using CarteleraMVC.Models; using Microsoft.EntityFrameworkCore; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace CarteleraMVC.Context { public class CarteleraContextMVC : DbContext { public CarteleraContextMVC(DbContextOptions options) : base(options) { } public CarteleraContextMVC() { } public DbSet<Pelicula> Peliculas { get; set; } public DbSet<Categoria> Categorias { get; set; } public DbSet<CategoriasPelicula> CategoriasPeliculas { get; set; } protected override void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder.Entity<Pelicula>().ToTable("Pelicula"); modelBuilder.Entity<Categoria>().ToTable("Categoria"); modelBuilder.Entity<CategoriasPelicula>().HasKey(t => new { t.PeliculaID, t.CategoriaID }); modelBuilder.Entity<CategoriasPelicula>() .HasOne(pt => pt.Pelicula) .WithMany(p => p.categoriasPelicula) .HasForeignKey(pt => pt.PeliculaID); modelBuilder.Entity<CategoriasPelicula>() .HasOne(pt => pt.Categoria) .WithMany(p => p.categoriasPelicula) .HasForeignKey(pt => pt.CategoriaID); } } } <file_sep>sameCol = function(div1, div2){ var check = $(div1).offset().left - $(div2).offset().left; return check < 320 & check > -320; } spacing = function(divup, divdown){ return $(divup).offset().top + $(divup).height() - $(divdown).offset().top; } moveIt = function(div, amt){ if(-amt > 20 + 14*2){ $(div).css("transform", "translate(0px, " + (amt+14*2+20) + "px)"); } } colMat = function(divs){ var divids = []; divs.each(function(){ $(this).css("transform", "translate(0px, 0px)"); divids.push("#" + $(this).attr("id")); }); // find divs in top row var heights = []; divs.each(function(){ heights.push($(this).offset().top); }) var topdivs = divids.filter(function(value, index){ return heights[index] <= Math.min.apply(null, heights); }) console.log(topdivs); // for each column, find other divs in that column, // and move up in order of distance from top for(var i = 0; i < topdivs.length; i++){ var coldivs = []; var dists = []; // identify and compute distance for(var j = 0; j < divids.length; j++){ if(topdivs[i] != divids[j] & sameCol(topdivs[i], divids[j])){ coldivs.push(divids[j]); dists.push(spacing(topdivs[i], divids[j])); } } var sdist = dists.sort(function(a, b){ return -a+b; }); var dexof = []; $.each(sdist, function(dex, sorted){ dexof.push($.inArray(sorted, dists)); }); for(j = 0; j < dexof.length; j++){ if(j == 0){ moveIt(coldivs[dexof[j]], dists[dexof[j]]); } else { moveIt(coldivs[dexof[j]], spacing(coldivs[dexof[j - 1]], coldivs[dexof[j]])); } } } } var resizeTimer; $(window).resize(function(){ clearTimeout(resizeTimer); resizeTimer = setTimeout(function(){ colMat($(".sections")); }, 50); }) <file_sep>(function (app) { 'use strict'; var arreglo = [{ id : 1, nombre : '<NAME>', cargo : 'Gerente General' }, { id : 2, nombre : '<NAME>', cargo : 'Jefe de proyecto' }, { id : 3, nombre : '<NAME>', cargo : 'Analista' }, { id : 4, nombre : '<NAME>', cargo : 'Programador Senior' }, { id : 5, nombre : '<NAME>', cargo : 'Programador Junior' }] app.arreglo = arreglo; }(window.app));<file_sep><?php /** * Description of Persona * * @author <NAME> */ class Categoria { private $idCategoria; private $nombre; private $idCategoriaPadre; function __construct($idCategoria, $nombre, $idCategoriaPadre) { $this->idCategoria = $idCategoria; $this->nombre = $nombre; $this->idCategoriaPadre = $idCategoriaPadre; } function getIdCategoria() { return $this->idCategoria; } function getNombre() { return $this->nombre; } function getIdCategoriaPadre() { return $this->idCategoriaPadre; } function setIdCategoria($idCategoria) { $this->idCategoria = $idCategoria; } function setNombre($nombre) { $this->nombre = $nombre; } function setIdCategoriaPadre($idCategoriaPadre) { $this->idCategoriaPadre = $idCategoriaPadre; } } <file_sep> <?php include_once './DAO/DAL/Connection.php'; include_once './DAO/DTO/acjue.php'; include_once './DAO/BLL/acjueBLL.php'; include_once './DAO/DTO/accat.php'; include_once './DAO/BLL/accatBLL.php'; ?> <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta name="description" content=""> <meta name="author" content=""> <title>Nueva Categorias</title> <!-- core CSS --> <link href="css/bootstrap.min.css" rel="stylesheet"> <link href="css/font-awesome.min.css" rel="stylesheet"> <link href="css/animate.min.css" rel="stylesheet"> <link href="css/prettyPhoto.css" rel="stylesheet"> <link href="css/main.css" rel="stylesheet"> <link href="css/responsive.css" rel="stylesheet"> <!--[if lt IE 9]> <script src="js/html5shiv.js"></script> <script src="js/respond.min.js"></script> <![endif]--> <link rel="shortcut icon" href="images/ico/favicon.ico"> <link rel="apple-touch-icon-precomposed" sizes="144x144" href="images/ico/apple-touch-icon-144-precomposed.png"> <link rel="apple-touch-icon-precomposed" sizes="114x114" href="images/ico/apple-touch-icon-114-precomposed.png"> <link rel="apple-touch-icon-precomposed" sizes="72x72" href="images/ico/apple-touch-icon-72-precomposed.png"> <link rel="apple-touch-icon-precomposed" href="images/ico/apple-touch-icon-57-precomposed.png"> <link rel="stylesheet" href="https://cdn.datatables.net/1.10.15/css/dataTables.bootstrap.min.css"> </head> <body class="homepage"> <header id="header"> <div class="top-bar"> <div class="container"> <div class="row"> <div class="col-sm-6 col-xs-4"> <a class="navbar-brand" href="index.php"><img style="max-width: 100%; height: 50px;" src="images/svgLogo.png" alt="logo"></a> </div> <div class="col-sm-6 col-xs-8"> <div class="social"> <ul class="social-share"> <li><a href="#"><i class="fa fa-desktop" title="ADMIN"></i></a></li> </ul> <div class="search"> <form role="form"> <input type="text" class="search-form" autocomplete="off" placeholder="Search"> <i class="fa fa-search"></i> </form> </div> </div> </div> </div> </div><!--/.container--> </div><!--/.top-bar--> </header><!--/header--> <section id="feature"> <div class="container"> <div class="row"> <div class="col-md-12 col-sm-12"> <div class="container"> <div class="row" style="height: 610px;" > <div style="padding-top: 20px"> <div class="col-md-12"> <form class="form-horizontal" method="POST" action="juegos.php" role="form" > <?php $catGlobalBLL = new acjueBLL(); if (isset($_REQUEST["editar"])) { $global = $_REQUEST["editar"]; ?> <input type="hidden" name="<?php echo $global ?>" value="<?php echo $global ?>"> <?php } else if (isset($_REQUEST["nuevo"])) { $global = $_REQUEST["nuevo"]; $idacjueUltimo = $catGlobalBLL->selectMaxAcjueJjue(); ?> <input type="hidden" name="<?php echo $global ?>" value="<?php echo $global ?>"> <?php } else { echo "error"; } ?> <?php if (isset($_REQUEST['editar'])) { $catGlobalBLL = new acjueBLL(); $idacjuetEdit = $_REQUEST["accatJjue"]; $objacjue = $catGlobalBLL->select($idacjuetEdit); ?> <div class="form-group"> <label for="accatCcat" class="col-lg-2 control-label">ID</label> <div class="col-lg-10"> <input type="text" class="form-control" name="accatJjue" value="<?php echo $_REQUEST["accatJjue"]; ?>" placeholder="ID" readonly="true"> </div> </div> <div class="form-group"> <label for="accatNomb" class="col-lg-2 control-label">NOMBRE</label> <div class="col-lg-10"> <input type="text" class="form-control"value="<?php echo $objacjue->getAcjueNomb() ?>" name="acjueNomb" placeholder="Nombre del juego"> </div> </div> </div> <div class="form-group"> <label for="acjuePrec" class="col-lg-2 control-label">PRECIO</label> <div class="col-lg-10"> <input type="number" class="form-control" id="acjuePrec" name="acjuePrec" placeholder="Precio" value="<?php echo $objacjue->getAcjuePrec() ?>"> </div> </div> <div class="form-group"> <label for="acjueDesc" class="col-lg-2 control-label">DESCRIPCION</label> <div class="col-lg-10"> <textarea type="tex" class="form-control" id="acjueDesc" name="acjueDesc" placeholder="Descripcion"><?php echo $objacjue->getAcjueDesc() ?></textarea> </div> </div> <?php } else if (isset($_REQUEST['nuevo'])) { $global = $_REQUEST['nuevo']; ?> <div class="form-group"> <label for="acjueJjue" class="col-lg-2 control-label">ID</label> <div class="col-lg-10"> <input type="text" class="form-control" id="acjueJjue" name="acjueJjue" value ="<?php echo $idacjueUltimo->getAcjueJjue() ?>" placeholder="ID" readonly="true"> </div> </div> <div class="form-group"> <label for="acjueNomb" class="col-lg-2 control-label">NOMBRE</label> <div class="col-lg-10"> <input type="text" class="form-control" id="accatNomb" name="acjueNomb" placeholder="NOMBRE"> </div> </div> <div class="form-group"> <label for="acjuePrec" class="col-lg-2 control-label">PRECIO</label> <div class="col-lg-10"> <input type="number" class="form-control" id="acjuePrec" name="acjuePrec" placeholder="Precio"> </div> </div> <div class="form-group"> <label for="acjueDesc" class="col-lg-2 control-label">DESCRIPCION</label> <div class="col-lg-10"> <textarea type="tex" class="form-control" rows="9" id="acjueDesc" name="acjueDesc"placeholder="Descripcion"></textarea> </div> </div> <?php } else { echo "error"; } ?> </div> <div class="form-group"> <div class="col-lg-offset-2 col-lg-10"> <button type="submit" class="btn btn-default">Registrar</button> <a href="juegos.php?cancelar=cancelar&acjueJjue=<?php echo $idacjueUltimo->getAcjueJjue() ?>" class="btn btn-danger">Cancelar</a> </div> </div> </form> <div class="col-md-12"> <table id="idcat" class="table table-bordered table-striped"> <thead> <tr> <th>ID</th> <th>NOMBRE</th> <th>CATEGORIA PADRE</th> <th></th> </tr> </thead> <tbody> <?php $accatBLLTable = new accatBLL(); $ListaAccat = $accatBLLTable->selectAll(); ?> <?php foreach ($ListaAccat as $value) { ?> <tr> <td> <?php echo $value->getAccatCcat(); ?></td> <td> <?php echo $value->getAccatNomb(); ?></td> <td> <?php if ($value->getAccatCpad() == 0) { ?> <span class="label label-danger">Es padre</span> <?php } else { $SelectAccatPad = $accatBLLTable->selectaccatPadre($value->getAccatCpad()); ?> <span class="label label-success"><?php echo $SelectAccatPad->getAccatNomb(); ?></span> <?php } ?> </td> <th> <input id="checCat<?php echo $value->getAccatCcat(); ?>" type="checkbox" class="form-control" OnClick="Agregar(<?php echo $value->getAccatCcat(); ?>,<?php echo $idacjueUltimo->getAcjueJjue() ?>);"> </th> </tr> <?php } ?> </tbody> </table> </div> </div> </div> </div></div> </div><!--/.col-md-3--> </div> </div> </section><!--/#bottom--> <footer id="footer" class="midnight-blue"> <div class="container"> <div class="row"> <div class="col-sm-6"> &copy; 2017 <a target="_blank" href="http://www.facebook.com/" title="Free Miguel Angel"><NAME></a>. All Rights Reserved. </div> <div class="col-sm-6"> <ul class="pull-right"> <li><a href="#">Home</a></li> <li><a href="#">About Us</a></li> <li><a href="#">Faq</a></li> <li><a href="#">Contact Us</a></li> </ul> </div> </div> </div> </footer><!--/#footer--> <script src="js/jquery.js"></script> <script src="js/bootstrap.min.js"></script> <script src="js/jquery.prettyPhoto.js"></script> <script src="js/jquery.isotope.min.js"></script> <script src="js/main.js"></script> <script src="js/wow.min.js"></script> <script src="js/addventares.js"></script> <script src="https://cdn.datatables.net/1.10.15/js/jquery.dataTables.min.js"></script> <script src="https://cdn.datatables.net/1.10.15/js/dataTables.bootstrap.min.js"></script> </body> </html> <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using PeliculasMVC.Context; using PeliculasMVC.Models; using Microsoft.EntityFrameworkCore; namespace PeliculasMVC.Controllers { public class HomeController : Controller { private readonly ProyectoContext db; public HomeController (ProyectoContext context) { db = context; } public async Task<IActionResult> Index() { //db.Database.EnsureCreated(); //db.SaveChanges(); return View(await db.Categorias.ToListAsync()); } public IActionResult About() { ViewData["Message"] = "Your application description page."; return View(); } public IActionResult Contact() { ViewData["Message"] = "Your contact page."; return View(); } public IActionResult Error() { return View(); } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Web; /// <summary> /// Descripción breve de Libros /// </summary> public class LibrosBRL { public LibrosBRL() { } public static List<Libros> selectAll() { LibrosDSTableAdapters.LibrosTableAdapter adapter = new LibrosDSTableAdapters.LibrosTableAdapter(); LibrosDS.tblLibrosDataTable table = adapter.GetLibros(); List<Libros> lista = new List<Libros>(); foreach (LibrosDS.tblLibrosRow row in table) { lista.Add(rowToDto(row)); } return lista; } private static Libros rowToDto(LibrosDS.tblLibrosRow row) { Libros obj = new Libros { titulo = row.titulo, año = row.año, editorial = row.editorial, autor_id = row.autor_id, codigo_id = row.codigo_id, isbn = row.ISBN }; return obj; } public static void add(Libros libro) { LibrosDSTableAdapters.LibrosTableAdapter adapter = new LibrosDSTableAdapters.LibrosTableAdapter(); adapter.Insert(libro.isbn, libro.titulo, libro.autor_id, libro.editorial, libro.año); } public static void selectByID(int id) { LibrosDSTableAdapters.LibrosTableAdapter adapter = new LibrosDSTableAdapters.LibrosTableAdapter(); adapter.GetLibroByID(id); } public static void delete(int id) { LibrosDSTableAdapters.LibrosTableAdapter adapter = new LibrosDSTableAdapters.LibrosTableAdapter(); adapter.Delete(id); } public static void update(Libros libro) { LibrosDSTableAdapters.LibrosTableAdapter adapter = new LibrosDSTableAdapters.LibrosTableAdapter(); adapter.Update(libro.isbn, libro.titulo, libro.autor_id, libro.editorial, libro.año, libro.codigo_id); } }<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Web; /// <summary> /// Summary description for UsuarioBLL /// </summary> public class UsuarioBLL { public UsuarioBLL() { } public static List<Usuario> SelectAll() { List<Usuario> listaUsuarios = new List<Usuario>(); UsuarioDSTableAdapters.UsuariosTableAdapter adapter = new UsuarioDSTableAdapters.UsuariosTableAdapter(); UsuarioDS.UsuariosDataTable table = adapter.SelectAll(); foreach (UsuarioDS.UsuariosRow row in table) { listaUsuarios.Add(rowToDto(row)); } return listaUsuarios; } public static Usuario SelectByLogin(string usuario, string hashedPassword) { UsuarioDSTableAdapters.UsuariosTableAdapter adapter = new UsuarioDSTableAdapters.UsuariosTableAdapter(); UsuarioDS.UsuariosDataTable table = adapter.SelectByLogin(usuario, hashedPassword); if (table.Rows.Count == 0) { return null; } return rowToDto(table[0]); } public static Usuario SelectByUserName(string usuario) { UsuarioDSTableAdapters.UsuariosTableAdapter adapter = new UsuarioDSTableAdapters.UsuariosTableAdapter(); UsuarioDS.UsuariosDataTable table = adapter.SelectByUserName(usuario); if (table.Rows.Count == 0) { return null; } return rowToDto(table[0]); } public static Usuario SelectById(int id) { UsuarioDSTableAdapters.UsuariosTableAdapter adapter = new UsuarioDSTableAdapters.UsuariosTableAdapter(); UsuarioDS.UsuariosDataTable table = adapter.SelectById(id); if (table.Rows.Count == 0) { return null; } return rowToDto(table[0]); } public static void insert(string nombreUsuario, string password) { UsuarioDSTableAdapters.UsuariosTableAdapter adapter = new UsuarioDSTableAdapters.UsuariosTableAdapter(); adapter.Insert(nombreUsuario, password); } public static void update(string nombreUsuario, string password, int id) { UsuarioDSTableAdapters.UsuariosTableAdapter adapter = new UsuarioDSTableAdapters.UsuariosTableAdapter(); adapter.Update(nombreUsuario, password, id); } public static void delete(int id) { UsuarioDSTableAdapters.UsuariosTableAdapter adapter = new UsuarioDSTableAdapters.UsuariosTableAdapter(); adapter.Delete(id); } private static Usuario rowToDto(UsuarioDS.UsuariosRow row) { Usuario objUsuario = new Usuario(); objUsuario.ID = row.id; objUsuario.Username = row.username; objUsuario.Password = <PASSWORD>; return objUsuario; } }<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Web; using Biblioteca.App_Code.DAL; public class GeneroBll { public GeneroBll() { } public static List<Genero> SelectAllGenero() { List<Genero> listaGeneros = new List<Genero>(); DataSet1TableAdapters.GeneroTableAdapter adapter = new DataSet1TableAdapters.GeneroTableAdapter(); DataSet1.GeneroDataTable table = adapter.SelectAllGenero(); //DAL.GeneroDS.GeneroDataTable table = adapter.SelectAll(); foreach (DataSet1.GeneroRow item in table) { listaGeneros.Add(rowtoDto(item)); } return listaGeneros; } private static Genero rowtoDto(DataSet1.GeneroRow item) { Genero objGenero = new Genero(); objGenero.id = item.Id; objGenero.Nombre = item.Nombre; return objGenero; } public static void Editar(string id, string texto) { DataSet1TableAdapters.GeneroTableAdapter adapter = new DataSet1TableAdapters.GeneroTableAdapter(); adapter.Update(texto, Int32.Parse(id)); } public static void Crear(string texto) { DataSet1TableAdapters.GeneroTableAdapter adapter = new DataSet1TableAdapters.GeneroTableAdapter(); adapter.Insert(texto); } public static void eliminar(int id) { DataSet1TableAdapters.GeneroTableAdapter adapter = new DataSet1TableAdapters.GeneroTableAdapter(); adapter.Delete(id); } public static Genero SelectById(String id) { int id2 = Int32.Parse(id); List<Autor> listaAutors = new List<Autor>(); DataSet1TableAdapters.GeneroTableAdapter adapter = new DataSet1TableAdapters.GeneroTableAdapter(); DataSet1.GeneroDataTable table = adapter.GeneroById(id2); //DAL.AutorDS.AutorDataTable table = adapter.SelectAll(); Genero genero = null; foreach (DataSet1.GeneroRow item in table) { genero = rowtoDto(item); } return genero; } }<file_sep><?php /** * Description of PersonaBLL * * @author jmacb */ class PersonaBLL { public function insert($nombre, $apellido, $ciudad, $edad) { $objConexion = new Connection(); $objConexion->queryWithParams("INSERT INTO Persona(nombre,apellido,ciudad,edad) VALUES (:pNombre,:pApellido,:pCiudad,:pEdad)", array( ":pNombre" => $nombre, ":pApellido" => $apellido, ":pCiudad" => $ciudad, ":pEdad" => $edad )); } public function update($nombre, $apellido, $ciudad, $edad, $id) { $objConexion = new Connection(); $objConexion->queryWithParams(" UPDATE Persona SET nombre = :pNombre, apellido = :pApellido, ciudad = :pCiudad, edad = :pEdad WHERE id = :pId", array( ":pNombre" => $nombre, ":pApellido" => $apellido, ":pCiudad" => $ciudad, ":pEdad" => $edad, ":pId" => $id )); } public function delete($id) { $objConexion = new Connection(); $objConexion->queryWithParams(" DELETE FROM Persona WHERE id = :pId", array( ":pId" => $id )); } public function selectAll() { $listaPersonas = array(); $objConexion = new Connection(); $res = $objConexion->query(" SELECT id, nombre, apellido, ciudad, edad FROM Persona"); while ($row = $res->fetch(PDO::FETCH_ASSOC)) { $objPersona = $this->rowToDto($row); $listaPersonas[] = $objPersona; } return $listaPersonas; } public function select($id) { $objConexion = new Connection(); $res = $objConexion->queryWithParams(" SELECT id, nombre, apellido, ciudad, edad FROM Persona WHERE id = :pId", array( ":pId" => $id )); if ($res->rowCount() == 0) { return null; } $row = $res->fetch(PDO::FETCH_ASSOC); return $this->rowToDto($row); } function rowToDto($row) { $objPersona = new Persona(); $objPersona->setId($row["id"]); $objPersona->setNombre($row["nombre"]); $objPersona->setApellido($row["apellido"]); $objPersona->setCiudad($row["ciudad"]); $objPersona->setEdad($row["edad"]); return $objPersona; } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; public partial class formularioGenero : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { string id = Request.QueryString["id"]; if (id != null) { Genero objGenero = GeneroBLL.SelectById(Convert.ToInt32(id)); if (objGenero != null) { txtNombre.Text = objGenero.Nombre; hdnId.Value = objGenero.Id.ToString(); } } } } protected void btnGuardar_Click(object sender, EventArgs e) { string nombre = txtNombre.Text; SubirImagen.SaveAs(Server.MapPath("~/image/libros/") + nombre + ".jpg"); try { if (string.IsNullOrEmpty(hdnId.Value)) { GeneroBLL.Insert(nombre); } else { GeneroBLL.Update(nombre, Convert.ToInt32(hdnId.Value)); } Response.Redirect("~/abmGenero.aspx"); } catch (Exception) { } } }<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; public partial class Pages_GenereoABM : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { } protected void btnGuardar_Click(object sender, EventArgs e) { Genero nuevo = new Genero { Nombre = txtNombre.Text }; try { GeneroBLL.insert(nuevo); Response.Redirect("~/pages/Principal.aspx"); } catch (Exception Ex) { } } }<file_sep><?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Nota; class NotaController extends Controller { // public function index() { $listaNotas = Nota::all()->toArray(); return view('home', compact('listaNotas')); } public function buscar($id) { // return "hola"; // $resultado = Nota:: if ($id == null) { $listaNotas = Nota::all()->toArray(); // return $listaNotas; return 'hola'; } // $listaNotas = Nota::Where([['titulo', 'LIKE', '%'.$id.'%'], // ['descripcion', 'LIKE', '%'.$id.'%']] // )->get(); $listaNotas = Nota::Where('titulo', 'LIKE', '%' . $id . '%' )->orWhere('descripcion', 'LIKE', '%' . $id . '%')->get(); // $listaNotas = Nota::where('descripcion', 'LIKE', '%'.$id.'%' // )->get(); // $listaNotas = $listaNota return $listaNotas; // return "hola"; } public function buscartodos() { $listaNotas = Nota::all()->toArray(); return $listaNotas; } public function agregar($titulo,$desc) { $nota = new Nota(); $nota->titulo = $titulo ; $nota->descripcion = $desc ; $nota->save(); $listaNotas = Nota::all()->toArray(); return $listaNotas; } public function editar($titulo,$desc,$id) { $nota = Nota::where('id',$id) -> first(); $nota->titulo = $titulo ; $nota->descripcion = $desc ; $nota->save(); $listaNotas = Nota::all()->toArray(); return $listaNotas; } public function destroy($id) { Nota::destroy($id); $listaNotas = Nota::all()->toArray(); return $listaNotas; // } } <file_sep><?php namespace App; use Illuminate\Database\Eloquent\Model; class Persona extends Model { function index(){ return view('welcome'); } }
7353f04806ad3bffd1264873b84c22daab260a0e
[ "SQL", "Markdown", "JavaScript", "INI", "C#", "PHP" ]
233
C#
jmacboy/electiva-2-2017
62ae0926270f57b0c207ecd7aa3494a0200a60f7
f9a6b4e645c972272ac6ebc720e437fc607c231f
refs/heads/master
<repo_name>wdrougas/rack-dynamic-web-apps-dc-web-102819<file_sep>/app/application.rb class Application @@items = ["apples","Carrots","Pears"] @@cart = ["Soap", "Shampoo", "Face Cleanser"] def call(env) resp = Rack::Response.new req = Rack::Request.new(env) if req.path.match(/cart/) @@cart.each do |cart| resp.write "#{cart}\n" end elsif req.path.match(/add/) search_term = req.params["q"] if @@items.include?(search_term) @@cart << search_term resp.write "#{search_term} added to cart" else resp.write "Couldn't find #{search_term}" end else resp.write "Path Not Found" end resp.finish end end
4ccdef7660fea83b920369848e3457479f3659dc
[ "Ruby" ]
1
Ruby
wdrougas/rack-dynamic-web-apps-dc-web-102819
3f7a127d724b42ff0ae45c9ddb9146b2dc267cf6
cc7be77d8fc729db8e576586049a37100b9da056
refs/heads/main
<repo_name>dk-frontend-dev/webos-backend<file_sep>/src/user/user.controller.ts import {Body, Controller, Post} from '@nestjs/common' import {UserCreateInterface} from '@/user/types/user-create.interface' import {UserResponseType} from '@/user/types/user-response.type' @Controller('user') export class UserController { @Post('create') createUser(@Body('user') payload: UserCreateInterface): UserResponseType { return payload } } <file_sep>/src/user/types/user-response.type.ts import {UserCreateInterface} from '@/user/types/user-create.interface' export type UserResponseType = Omit<UserCreateInterface, 'password'>
5cad1e106854acffa7b96bec532523b952291b1d
[ "TypeScript" ]
2
TypeScript
dk-frontend-dev/webos-backend
ae018b5302e4e14c5d0b6e6ae05a37d21471b085
050fddc3cd5d4f7493fe47f875f8988e019a50fd
refs/heads/master
<file_sep># Frank-s-Server-plugins Spigot plugins development for my minecraft server. <file_sep>package primero; import java.util.ArrayList; import org.bukkit.Material; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.Listener; import org.bukkit.event.inventory.InventoryClickEvent; import org.bukkit.event.inventory.InventoryDragEvent; import org.bukkit.event.inventory.InventoryType; import org.bukkit.event.player.PlayerInteractEvent; import org.bukkit.inventory.Inventory; import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.meta.ItemMeta; import org.bukkit.plugin.Plugin; @SuppressWarnings("unused") public class CustomInventory implements Listener { private Plugin plugin = PrimerPlugin.getPlugin(PrimerPlugin.class); public Inventory market; public CustomInventory() { market = plugin.getServer().createInventory(null, 9, "Market Menu"); createDisplay(Material.STORAGE_MINECART, market, 0, "SEND ITEM", "Send Item to the Market."); createDisplay(Material.COMPASS, market, 1, "EXPLORE MARKET", "Explore the market "); createDisplay(Material.CHEST, market, 2, "MY ITEMS", "Check items in the market"); } public Inventory getInventory(){ return market; } public static void createDisplay(Material material, Inventory inv, int Slot, String name, String lore) { //Creates an item to put in the inventory interface ItemStack item = new ItemStack(material); ItemMeta meta = item.getItemMeta(); meta.setDisplayName(name); ArrayList<String> Lore = new ArrayList<String>(); Lore.add(lore); meta.setLore(Lore); item.setItemMeta(meta); inv.setItem(Slot, item); } public void openMarket(Player player) { player.openInventory(market); } }
63636c0c7c5be602d339ac63117175a3e3e934c6
[ "Markdown", "Java" ]
2
Markdown
unpluggedLink/Frank-s-Server-plugins
7a5cc13bd5dc58a34c7a3f5228e11a8ea9599bce
73b7a3ac5a6294f562b853919b4f28a47a6942ce
refs/heads/master
<repo_name>Sasson22/source<file_sep>/ida/idaapi.py #idaapi.py adapter #@category Daenerys.Framework.IDAPython """ Daenerys IDA/Ghidra interop library by <NAME> <<EMAIL>> """ import sys import inspect import daenerys_utils as utils from ghidra.program.model.address import GenericAddress from ghidra.program.model.address import Address # ------------------------------------------------------------------- class ea_t(long): """Effective address class. It can also store the Ghidra Address object in it. An effective address in IDA Pro is a 32-bits or 64-bits number. """ @staticmethod def init(ea, addr): ea = ea_t(ea) ea.address = addr return ea # ------------------------------------------------------------------- # Ghidra initialization def ghidra_state(): """Current Ghidra script state""" return _state def _deduce_state_variables(): """Deduce the needed invocation context""" var_names = ('currentAddress', 'currentHighlight', 'currentLocation', 'currentProgram', 'currentSelection', 'state') """Sentinel variables that we can use to detect the invocation context""" for s in inspect.stack(): if isinstance(s, tuple): s = s[0] if all(x in s.f_locals for x in var_names): # Bring all the state variables to this module's global scope for x in var_names: globals()['_' + x] = s.f_locals[x] return raise Exception('Failed to initialize Daenerys idaapi module!') _deduce_state_variables() # Store the state for use from other modules (w/o requiring to import this module) sys.__ghidra_state__ = _state # Assume program bitness based on the first memory block pointer size BADADDR = ea_t.init( 0xFFFFFFFFFFFFFFFF if _currentProgram.getMinAddress().getPointerSize() == 8 else 0xFFFFFFFF, Address.NO_ADDRESS) _memory = _currentProgram.getMemory() # ------------------------------------------------------------------- # Ghidra helper functions def AddressToEA(addr): """Converts a Ghidra Address object to an ea""" return ea_t.init(addr.getOffset(), addr) def eaToAddress(ea): """Converts an effective address to a Ghidra Address object""" if isinstance(ea, GenericAddress): # No conversion needed return ea elif isinstance(ea, ea_t): return ea.address elif utils.is_number(ea): addrs = _currentProgram.parseAddress("0x%x" % ea) # Return the first memory address for addr in addrs: if addr.isMemoryAddress(): return addr return Address.NO_ADDRESS def ghidra_program_getMinAddress(): return _currentProgram.getMinAddress() def ghidra_program_getMaxAddress(): return _currentProgram.getMaxAddress() # ------------------------------------------------------------------------ def get_wide_byte(ea): """Reads a byte (ida_bytes.get_wide_byte()""" return _memory.getByte(eaToAddress(ea)) & 0xff # ------------------------------------------------------------------------ def get_screen_ea(): """ida_kernwin.get_screen_ea()""" return AddressToEA(_state.getCurrentAddress()) # ------------------------------------------------------------------------ # IDA inf global variable emulator class _inf(object): @property def min_ea(self): return AddressToEA(ghidra_program_getMinAddress()) @property def max_ea(self): return AddressToEA(ghidra_program_getMaxAddress()) class _cvar(object): inf = _inf() cvar = _cvar() <file_sep>/ida/idc.py #idc.py adapter #@category Daenerys.Framework.IDAPython """ Daenerys IDA/Ghidra interop library by <NAME> <<EMAIL>> """ import idaapi INF_MIN_EA = 76 # ea_t; The lowest address used in the program INF_MAX_EA = 80 # ea_t; The highest address used in the program BADADDR = idaapi.BADADDR def ScreenEA(): return idaapi.get_screen_ea() def here(): return idaapi.get_screen_ea() def MinEA(): return get_inf_attr(INF_MIN_EA) def MaxEA(): return get_inf_attr(INF_MAX_EA) def get_inf_attr(offset): if offset == INF_MIN_EA: return idaapi.cvar.inf.min_ea elif offset == INF_MAX_EA: return idaapi.cvar.inf.max_ea def Byte(ea): return idaapi.get_wide_byte(ea) <file_sep>/scripts/IDAPython/hello.py # Daenerys IDAPython "hello world" example script #@category Daenerys.IDAPython.Examples import idc print("Hello world from Ghidra...") print("Current address is: %x" % idc.here()) print("Min address: %x - Max address: %x" % (idc.MinEA(), idc.MaxEA())) print("Byte at current address is: %02x" % idc.Byte(idc.here())) print("BADADDR=%x" % idc.BADADDR) <file_sep>/ida/daenerys_utils.py # Daenerys IDA/Ghidra interop framework # by <NAME> <<EMAIL>> # # Python utility functions import numbers def is_number(n): return isinstance(n, numbers.Number)
e6a423763f9eb3e961c5cdc704d96ce03788c1a7
[ "Python" ]
4
Python
Sasson22/source
e9175407d4f43b33e20a5d7060480a7659535874
6dbf6c2cbf8c417f0f52b548e7cbc57d8413abc6
refs/heads/master
<repo_name>IEturbo/webapp<file_sep>/src/app/home/home.component.ts import { Component, OnInit, Input, Output, EventEmitter, OnChanges, SimpleChanges } from '@angular/core'; @Component({ selector: 'app-home', templateUrl: './home.component.html', styleUrls: ['./home.component.less'] }) export class HomeComponent implements OnInit , OnChanges { @Input() valueParam = 'value'; // value对应的字段名 @Input() textParam = 'text'; // text对应的字段名 itemsOpen = ''; selectedItem: any = {}; // [{'name':'主机名称',value:'jiangtao-PC[172.20.10.10]'},{'name':'系统版本',value:'Microsoft Windows 7 x64'},{'name':'服务数',value:'2'}] @Input() data: any[] = [ { value: 1, 'text': 'qwe1' }, { value: 3, 'text': 'qwe2' }, { value: 4, 'text': 'qwe3' } ]; toggleCaret: boolean; @Output() change: EventEmitter<string> = new EventEmitter<string>(); @Input() placeholder = ''; constructor() { } ngOnInit() { this.toggleCaret = true; this.selectedItem[this.valueParam] = ''; this.selectedItem[this.textParam] = '请选择'; } ngOnChanges(changes: SimpleChanges) { } setBtnIClasses() { const btnIClass: any = { 'fa': true, 'fa-caret-down': this.toggleCaret, 'fa-caret-up': !this.toggleCaret } return btnIClass; } toggleCaretClass() { this.toggleCaret = !this.toggleCaret; } toggle(item: any) { this.selectedItem = item; this.toggleCaretClass(); this.change.emit(item); } } interface DataItem { value: string, text: string } <file_sep>/src/app/about/about.component.html <div class="about"> <div class="container"> <h1 class="title">ABOUT SOCIAL FRONTIER</h1> <p> Social frontier is a Digital Marketing Agency that specializes in 360-degree marketing integration. We believe that a good marketing initiative will fetch results not only in the short term but also the results will multifold in years to come. In order to meet the objective with the result, Social Frontier backs every marketing initiative with technology. </p> <p>We ensure the customer finds value throughout the buyer's journey. Our 360-degree marketing approach enables us to have a well thought and integrated cross- channel promotion. At every touch point whether it is social media, paid advertising, email, mobile or search, customer experiences a rich integrated content. Social Frontier ensures that the marketing message holds its essence across the channels of promotion. The brand message is optimized keeping in mind the platform used and customer behavior. </p> </div> </div>
e221046c519b4523b3618d7465526844714048cc
[ "TypeScript", "HTML" ]
2
TypeScript
IEturbo/webapp
ec9ececff392144308a629202188419783eec827
1869b7942bc2a653c0269a1b5a555414454b63e4
refs/heads/master
<file_sep>2014 project using android and ardunio to build the project-"I-hamlet" team member: MarkVen SiaoHui HaoHsun pk356142 Avon Yixue beafajita Provide slide to introduce: http://www.slideshare.net/MarkVen/20140108-32023480 change by sublime <file_sep>/* This is for the moto navigation. At first, we use the blabla pin as input(bluetooth),then have the pins: blablabla as output. Smart phone send some text to arduino by bluetooth e.g, : 6 Q numbers mean the time counting down, 6 means we need 6 pins fot led Q */ boolean dirCheckForA = false; boolean dirCheckForB2I = false; boolean dirCheckForJ2P = false; boolean countingTimeEvent =true; int countingTime =6; char chr = 'Z'; int i = 0; void setup(){ Serial.begin(9600); // 開啟 Serial port, 通訊速率為 9600 bps for (int pin1 = 2 ; pin1 <=13;pin1++){ // 定義digital 2~13 為輸出 pinMode(pin1, OUTPUT); digitalWrite(pin1,HIGH); //確認每個LED燈 // delay(50); digitalWrite(pin1,LOW); // delay(50); } //Serial.println("OK"); // 回傳"OK" } void serialEvent() { while (Serial.available()){ chr = Serial.read(); char inputcheck = Serial.read(); if (inputcheck == '7'){ countingTime = 7; } if (inputcheck == '6'){ countingTimeEvent =true; countingTime = 6; } else if (inputcheck == '5'){ countingTimeEvent =true; countingTime = 5; } else if (inputcheck == '4'){ countingTimeEvent =true; countingTime = 4; } else if (inputcheck == '3'){ countingTimeEvent =true; countingTime = 3; } else if (inputcheck == '2'){ countingTimeEvent =true; countingTime = 2; } else if (inputcheck == '1'){ countingTimeEvent =true; countingTime = 1; } else if (inputcheck == '0'){ countingTimeEvent =true; countingTime = 0; } // Serial.println(inputcheck); // 回傳"inputcheck" } } void loop(){ if(chr != 'Z'){ for (int dir = 2; dir <= 5; dir++) { digitalWrite(dir, LOW); } if(chr == 'J') digitalWrite(5, HIGH); else if(chr == 'K') digitalWrite(2, HIGH); else if(chr == 'L') digitalWrite(4, HIGH); else if(chr == 'M') digitalWrite(3, HIGH); else if(chr == 'N'){ digitalWrite(5, HIGH); digitalWrite(4, HIGH); } else if(chr == 'O'){ digitalWrite(2, HIGH); digitalWrite(3, HIGH); } else if(chr == 'P' || chr == 'F'){ digitalWrite(3, HIGH); digitalWrite(4, HIGH); } } /* //mark ven change 20140112 if(chr == 'B'||chr == 'C'||chr == 'D'||chr == 'E'||chr == 'F'||chr == 'G'||chr == 'H'||chr == 'I' ){ // 當B~I時 全方向燈號亮 for (int dir = 2; dir <= 5; dir++) { digitalWrite(dir, HIGH); } } */ //mark ven change 20140112 if (chr == 'C'|| chr == 'D' || chr == 'E') { digitalWrite(2, HIGH); } if (chr == 'G'|| chr == 'H' || chr == 'I') { digitalWrite(5, HIGH); } //mark ven change 20140112 if(chr == 'Q'&&countingTime == 7) { digitalWrite(4, HIGH); digitalWrite(10, HIGH); } if(countingTimeEvent){ for (int ct=8;ct<=13;ct++){ digitalWrite(ct, LOW); } // Serial.print(countingTime); // for(int i = 0 ;i < 2500;i++){ for (int ct=0;ct<=(6-countingTime);ct++){ digitalWrite(ct+7, HIGH); } } if(countingTime == 0) for(int i = 0 ;i < 2500;i++){ for (int ct=8;ct<=13;ct++){ digitalWrite(ct, LOW); } } //countingTimeEvent = false; } }
6eaf34c058b971602c6e4182b7607fa4aa583e5e
[ "Markdown", "C++" ]
2
Markdown
markven/ubi_project_ihamlet
306d8849f97f572eac69351347c9bc7567bf4fc7
e13588fd0fab7bb81901963758444237ec8c4a37
refs/heads/main
<repo_name>RafliTelyuu/raflitelyuu.github.io<file_sep>/js/script.js var countDate = new Date ("May 16, 2021 03:06:00").getTime(); var x = setInterval(function() { var now = new Date().getTime(); var distance = now - countDate; var days = Math.floor(distance / (1000 * 60 * 60 * 24)); var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60)); var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60)); var seconds = Math.floor((distance % (1000 * 60)) / 1000); // Display the result in the element with id="demo" document.getElementById("day-count").innerHTML = days + "d " + hours + "h " + minutes + "m " + seconds + "s "; }, 1000) //Random Name and Age var birthDate = new Date ("Dec 24, 2001 00:00:01").getTime(); const nameRafli = ["Rafli", "सिफ़ा मीडियाना", "<NAME>", "ラフィ", "拉夫利迈西亚迪瓦", "رافلي مايزياديفا", "рафли", "ราฟลี", "ରାଫଲି"]; var y = setInterval(function() { var now = new Date().getTime(); var days = now - birthDate; var Age = Math.floor(days / (1000 * 60 * 60 * 24 * 365)); const random = Math.floor(Math.random() * nameRafli.length); document.getElementById("name").innerHTML = nameRafli[random] + ", " + Age; },1000) //alert function FewAlert() { alert("Hello"); alert("Thank You for visiting my website"); alert("bagi tp"); } //color change function colorChange(clr) { var root = document.querySelector(':root'); var className = '.' + clr.classList[1]; var classStyles = document.querySelector(className) var rootColor = getComputedStyle(root); var classColor = getComputedStyle(classStyles); var c1 = ' rgb(162, 219, 250)'; var c1_0 = 'rgb(162, 219, 250)'; var c2 = ' rgb(229, 228, 204)'; var c2_0 = 'rgb(229, 228, 204)'; var c3 = ' rgb(248, 237, 227)'; var c3_0 = 'rgb(248, 237, 227)'; var c4 = ' rgb(212, 236, 221)'; var c4_0 = 'rgb(212, 236, 221)'; var c5_0 = 'rgb(198, 180, 206)'; var c6_0 = 'rgb(161, 155, 150)'; // console.log(clr.classList); // console.log(classColor.getPropertyValue('background-color')); // console.log(c1_0 == classColor.getPropertyValue('background-color')); // console.log(rootColor.getPropertyValue('--color-1')); if (classColor.getPropertyValue('background-color') == c1 || classColor.getPropertyValue('background-color') == c1_0) { root.style.setProperty('--color-1', 'rgb(232, 240, 242)'); root.style.setProperty('--color-2', 'rgb(162, 219, 250)'); root.style.setProperty('--color-3', 'rgb(57, 162, 219)'); root.style.setProperty('--color-4', 'rgb(5, 55, 66)'); root.style.setProperty('--color-font', 'white'); root.style.setProperty('--color-con', 'rgb(255, 81, 81)'); } else if (classColor.getPropertyValue('background-color') == c2 || classColor.getPropertyValue('background-color') == c2_0) { root.style.setProperty('--color-1', 'rgb(229, 228, 204)'); root.style.setProperty('--color-2', 'rgb(186, 199, 167)'); root.style.setProperty('--color-3', 'rgb(136, 158, 129)'); root.style.setProperty('--color-4', 'rgb(105, 132, 116)'); root.style.setProperty('--color-font', 'black'); root.style.setProperty('--color-con', 'rgb(251, 209, 72)'); } else if (classColor.getPropertyValue('background-color') == c3 || classColor.getPropertyValue('background-color') == c3_0) { root.style.setProperty('--color-1', 'rgb(248, 237, 227)'); root.style.setProperty('--color-2', 'rgb(189, 210, 182)'); root.style.setProperty('--color-3', 'rgb(162, 178, 159)'); root.style.setProperty('--color-4', 'rgb(121, 135, 119)'); root.style.setProperty('--color-font', 'black'); root.style.setProperty('--color-con', 'rgb(251, 209, 72)'); } else if (classColor.getPropertyValue('background-color') == c4 || classColor.getPropertyValue('background-color') == c4_0) { root.style.setProperty('--color-1', 'rgb(212, 236, 221)'); root.style.setProperty('--color-2', 'rgb(52, 91, 99)'); root.style.setProperty('--color-3', 'rgb(21, 45, 53)'); root.style.setProperty('--color-4', 'rgb(17, 32, 49)'); root.style.setProperty('--color-font', 'white'); root.style.setProperty('--color-con', 'rgb(200, 92, 92)'); } else if (classColor.getPropertyValue('background-color') == c5_0) { root.style.setProperty('--color-1', 'rgb(241, 241, 246)'); root.style.setProperty('--color-2', 'rgb(198, 180, 206)'); root.style.setProperty('--color-3', 'rgb(155, 114, 170)'); root.style.setProperty('--color-4', 'rgb(60, 81, 134)'); root.style.setProperty('--color-font', 'white'); root.style.setProperty('--color-con', 'rgb(23, 215, 160)'); } else if (classColor.getPropertyValue('background-color') == c6_0) { root.style.setProperty('--color-1', 'rgb(161,155,150)'); root.style.setProperty('--color-2', 'rgb(133,119,100)'); root.style.setProperty('--color-3', 'rgba(39,42,31,255)'); root.style.setProperty('--color-4', 'rgb(40,61,56)'); root.style.setProperty('--color-font', 'white'); root.style.setProperty('--color-con', 'rgb(247, 208, 138)'); } } //button let button = document.getElementById("btn1"); function buttonChangeOver() { button.innerHTML = "Click Here"; } function buttonChangeOut() { button.innerHTML = "Hover Here"; } //images function expandImg(imgs) { var expImg = document.getElementById("expandedImg"); var source = String(imgs.src).replace("/thumbnail", ""); expImg.src = source; expImg.parentElement.style.display = "block"; } function expandImg2(imgs) { var expImg = document.getElementById("expandedImg2"); var source = String(imgs.src).replace("/thumbnail", ""); expImg.src = source; expImg.parentElement.style.display = "block"; } //Card let iconCard = document.querySelectorAll(".icon-container"); let icon = document.querySelectorAll(".material-icons"); let title = document.querySelectorAll(".card-title"); let cardContent = document.querySelectorAll(".card-content"); let card = document.querySelectorAll(".card"); let iconName = []; for (let i = 0; i<iconCard.length; i++) { iconCard[i].onclick = function() { if (icon[i].innerHTML != "close") { iconName[i] = icon[i].innerHTML; icon[i].innerHTML = "close"; } else { icon[i].innerHTML = iconName[i]; } iconCard[i].classList.toggle('active'); icon[i].classList.toggle('active'); title[i].classList.toggle('active'); cardContent[i].classList.toggle('active'); card[i].classList.toggle('active'); } }
00906c2222f0a24e7712662f0de6d9df31124410
[ "JavaScript" ]
1
JavaScript
RafliTelyuu/raflitelyuu.github.io
873a64ffab37a19723639bd1aefdd227d3286d2d
8eed11ec6977e8f31d542ec15730db45b5fd1e0a
refs/heads/master
<repo_name>ZhangHector/ANNHandwritingRecognition<file_sep>/Neural Network/src/GUI/Plotter.java package GUI; import ptolemy.plot.PlotLive; import Utils.Utils; /* Plotter * The plot is an instance of the PTPlot Java Plotter * http://ptolemy.eecs.berkeley.edu/java/ptplot5.7/ptolemy/plot/doc/index.htm * The plot will auto adjust to the domain of the current values, and the user can zoom by click-drag-releasing * on the plot. */ public class Plotter extends PlotLive { private static final long serialVersionUID = 1L; /* variable to determine how many examples (x-axis) we've had already */ private int counter; /* how much the x-axis should increase at every step */ private int stepSize; public Plotter(int stepSize) { this.resetAll(); this.setTitle(Utils.PLOTTER_TITLE); this.setTitleFont(Utils.PLOTTER_TITLEFONT); this.setXLabel(Utils.PLOTTER_XLABEL); this.setYLabel(Utils.PLOTTER_YLABEL); this.setXRange(0, 300); this.stepSize = stepSize; this.addLegend(0, Utils.PLOTTER_LEGEND_TRAIN); this.addLegend(1, Utils.PLOTTER_LEGEND_TEST); } public void addToPlot(double value, int dataset) { /* automatically zoom out 200% when the x-axis reaches its maximum */ if (counter >= this.getXRange()[1]) this.zoom(0, 0, counter*2, 1); this.addPoint(dataset, counter, value, true); counter += stepSize; } public void addPoints() { } public void resetCounter() { counter = 0; } public void resetAll() { this.resetCounter(); this.setYRange(0, 1); this.clear(0); this.clear(1); } }<file_sep>/Neural Network/src/GUI/Runner.java package GUI; import java.io.IOException; import NeuralNetwork.BackPropagation; import mnist.tools.MnistManager; import Utils.Utils; /* Runner * Thread object that will work the neural network. * Is capable of both training and testing and does image processing as well. * It reports results back to its parent, which is a GUI. * Gets all the required settings for the network from the parent. * The thread dies when finished, or when interrupted. */ /* THE MNIST DATABASE of handwritten digits * The MNIST database of handwritten digits, available from this page, has a training set of 60,000 examples, and a test set of 10,000 examples. * It is a subset of a larger set available from NIST. The digits have been size-normalized and centered in a fixed-size image. * It is a good database for people who want to try learning techniques and pattern recognition methods on real-world data while spending minimal efforts on preprocessing and formatting. * train-images-idx3-ubyte.gz: training set images (9912422 bytes) * train-labels-idx1-ubyte.gz: training set labels (28881 bytes) * t10k-images-idx3-ubyte.gz: test set images (1648877 bytes) * t10k-labels-idx1-ubyte.gz: test set labels (4542 bytes) * The original black and white (bilevel) images from NIST were size normalized to fit in a 20x20 pixel box while preserving their aspect ratio. * The resulting images contain grey levels as a result of the anti-aliasing technique used by the normalization algorithm. * The images were centered in a 28x28 image by computing the center of mass of the pixels, and translating the image so as to position this point at the center of the 28x28 field. * [LeCun et al., 1998a] * <NAME>, <NAME>, <NAME>, and <NAME>. "Gradient-based learning applied to document recognition." Proceedings of the IEEE, 86(11):2278-2324, November 1998. */ public class Runner extends Thread { private GUI parent; private MnistManager m; private boolean train; BackPropagation network; public Runner(GUI parent, BackPropagation network) { this.parent = parent; this.network = network; } public void run() { try { m = new MnistManager(parent.getImageFile(), parent.getLabelFile()); } catch (IOException e) { e.printStackTrace(); } parent.Log(String.format(Utils.LOG_RUN, Utils.getMode(train), network.printTopology())); if (!train) network.loadOptimalWeights(); for (int run=0; run<parent.getNumRuns(); run++) { for (int example=1; example<parent.getNumExamples(); example++) { m.setCurrent(example); /* load image */ /* pre-process image according to setting defined by user* /* the correct answers (what the network should answer) */ try { if (train) network.train(processImage(m.readImage(), parent.getCanvasProcessor(), parent.getScaleProcessor()), m.readLabel()); else network.test(processImage(m.readImage(), parent.getCanvasProcessor(), parent.getScaleProcessor()), m.readLabel()); if (example % parent.getStepSize() == 0) { parent.Log(String.format(Utils.LOG_AVERAGE_ERROR_VALUE, m.readLabel(), example, parent.getStepSize(), network.getCurStepError())); parent.addValue(network.getCurStepError(), train); } } catch (IOException e) { e.printStackTrace(); } if (interrupted()) { parent.Log(Utils.LOG_INTERRUPTED); return; } } } parent.enableAll(true); } /* preprocess the image according to the values of the preProcessor, see GUI.java for explanation about this technique */ private double[] processImage(int image[][], boolean canvas, boolean scaled) { int imgScaled[][] = scaled ? scaleImage(image) : image; int imgCanvas = canvas ? 4 : 0; imgCanvas = scaled ? imgCanvas/2 : imgCanvas; int dim1 = imgScaled.length-(imgCanvas*2); int dim2 = imgScaled[0].length-(imgCanvas*2); double ret[] = new double[(dim1*dim2)]; for (int i=0; i<dim1; i++) for (int j=0; j<dim2; j++) /* first scale values to [0,1], enter values in the input nodes */ ret[j + dim2*i] = scale(imgScaled[i+imgCanvas][j+imgCanvas]); return ret; } private int[][] scaleImage(int image[][]) { int img[][] = new int[image.length/2][image[0].length/2]; for (int i=0; i<img.length; i+=2) for (int j=0; j<img[0].length; j+=2) img[i][j] = (image[i][j] + image[i+1][j] + image[i][j+1] + image[i+1][j+1])/4; return img; } /* use this to scale the inputs to [0,1] */ private double scale(double num) { return num / 255; } public void setTrain(boolean train) { this.train = train; } }<file_sep>/README.md ANN Handwriting Recognition =================================== Handwriting Digit Recognition is most popular problem to the area of machine learning in AI Introduction ------------ For this project, the goal is to complete electronic conversion of images, hand written or printed text by over thousands unique authors, into machine-encoded text, whether from a scanned document, a photo of a document or from subtitle text superimposed on an image. Depended on the scope of the field, it will be only considered a subset of characters, digits 0 to 9 in this project. This narrowed down domain can be applied to the identification of US postal codes, bank check identification processing, and any task that follows numeric data processing. In order to get formally state the problem domain, AI project will be a handwriting recognition program specifically targeting digits zero to nine, on top of a machine learning algorithm accomplished by artificial neural networks. Screenshots ----------- <img src="Neural Network/Screeen Shot/Testing.png" height="600" alt="Screenshot"/> <file_sep>/Neural Network/src/GUI/Drawer.java package GUI; /* Drawer * Thread object that will work the neural network. * Is capable of both training and testing and does image processing as well. * It reports results back to its parent, which is a GUI. * Gets all the required settings for the network from the parent. * The thread dies when finished, or when interrupted. */ import java.awt.geom.Line2D; import java.awt.geom.Point2D; import java.util.Vector; import Utils.Utils; public class Drawer extends Thread { private NetworkDrawing drawPanel; private double weights[][]; private int layers[]; private Point2D nodes[][]; private Vector<Line2D> lines = new Vector<Line2D>(); private Vector<Integer> lineWeights = new Vector<Integer>(); public Drawer(int layers[], double weights[][], NetworkDrawing drawPanel) { this.drawPanel = drawPanel; this.layers = layers; this.weights = weights; } public void run() { int maxNodeLayer = 0; for (int i=0; i<layers.length; i++) maxNodeLayer = (layers[i] > maxNodeLayer) ? layers[i] : maxNodeLayer; nodes = drawPanel.getNodes(); for (int i=1; i<layers.length; i++) { /* find maximum weight of this layer */ double bestWeight = 0; for (int j=0; j<weights[i-1].length; j++) if (weights[i-1][j] > bestWeight) bestWeight = weights[i-1][j]; for (int j=0; j<layers[i]; j++) { for (int k=0; k<layers[i-1]; k++) { if (weights[i-1][j*k+k] >= bestWeight*0.5) { double curWeight = weights[i-1][j*k+k]; double min = bestWeight*0.5; double max = bestWeight; curWeight = (curWeight-min)/(max-min) * 255; int alpha = (int)curWeight; if (alpha > 255) alpha = 255; if (alpha < 0) alpha = 0; lines.add(new Line2D.Double(nodes[i][j].getX(), nodes[i][j].getY(), nodes[i-1][k].getX(), nodes[i-1][k].getY())); lineWeights.add(alpha); } } } } while (lines.size() > 1000) { int r = Utils.random().nextInt(lines.size()-1); lines.remove(r); lineWeights.remove(r); } drawPanel.addLines(lines, lineWeights); } }<file_sep>/Neural Network/src/NeuralNetwork/BackPropagation.java package NeuralNetwork; import Acvtivation.Function; import Element.Line; import Element.LineLayer; import Element.Node; import Element.NodeLayer; import Element.OutputNode; import Utils.Utils; /* BackPropagation * BackPropagation is an implementation of the FeedForward Neural Network that * propagates the input through the network, depending on the weights of the * Lines that connect the Nodes. Then it determines an error term at the output * and propagates this error term back through the network. From these error terms, * the weights of the Lines are being updated. This process iterates until an optimal * values has been found. * As you can see, this implementation has a lot more functionality that the FeedForward * algorithm. I want to make clear that all these functionalities are not a property of the * Neural Network, but a property of Back propagation. That is why I have not implemented * this method in the Node and Line classes. They only have very simple values, and all * the calculations are done in this class. * I did use additional classes for the error, sigmoid and weight functions. This allows * one to easily change them without having to dig in this class. */ public class BackPropagation extends FeedForward { /* algorithm variables - are being initialized by the GUI */ protected double LEARNING_RATE = 0.5; protected double MOMENTUM = 0.3; protected double MIN_WEIGHT = -0.05; protected double MAX_WEIGHT = 0.05; /* error feedback variables */ protected int rounds = 0, stepSize = 100; protected double[][] previousDeltaWeight; protected double[][] averageWeight; protected double[][] minErrorWeight; protected double minError; protected double curStepError; /* create network topology based on networkLayers, initialize the momentum and the counters for error feedback */ public BackPropagation(int[] networkLayers) { super(networkLayers); initMomentum(); initCounters(); initWeights(); } public void train(double[] image, int answer) { inputExample(image); // set target of all output values setOutputTargets(answer); // now computer output of every unit // first reset all the netto values and errors in the nodes to 0 resetNodes(); // propagate input forward through the network propagateInput(); // propagate errors backward through the network propagateError(); // process these error for error feedback updateStepError(); } public void test(double[] image, int answer) { // very similar to train() method, except that we don't // propagate the error back since we are only interested in // the error values at the output Nodes. inputExample(image); setOutputTargets(answer); propagateInput(); // different update step because we don't keep track of anything updateTestStep(); } /* propagate the output value of the input Nodes all the way to the output Nodes using the Sigmoid function */ private void propagateInput() { for (int i=0; i<lineLayers.length; i++) { for (int j=0; j<lineLayers[i].size(); j++) { Line curLine = lineLayers[i].get(j); // propagate the output of the fromNode to the toNode // the output depends on the weight of this line. // toNode(output) += fromNode(output) * weight // NOTE: the values are being added for all lines in this Line Layer, // only after all the lines have done this, the sigmoid function // is being used. this has to advantage that the sum of the inputs // of the Nodes and the output can be stored in one variable. Node toNode = curLine.getToNode(); Node fromNode = curLine.getFromNode(); toNode.incOutput(fromNode.getOutput() * curLine.getWeight()); } // now use the sigmoid function to calculate output values of the Nodes in this Layer // if there are no more hidden layers, we are connecting it to the output layer. NodeLayer curLayer = (i < hiddenLayers.length) ? hiddenLayers[i] : outputLayer; for (int j=0; j<curLayer.size(); j++) curLayer.get(j).setOutput(Function.Sigmoid.compute(curLayer.get(j).getOutput())); } } /* propagate the errors back through the network, starting at the output nodes */ private void propagateError() { // for each network output unit, calculate its error term for (int i=0; i<outputLayer.size(); i++) { OutputNode curNode = ((OutputNode) outputLayer.get(i)); double curOutput = curNode.getOutput(); double errorValue = Function.Error.computeOutput(curOutput, curNode.getTarget()); curNode.setError(errorValue); } LineLayer curLineLayer; for (int i=(lineLayers.length-1); i>=0; i--) { // calculate error values of the nodes by propagating previous error using the lines curLineLayer = lineLayers[i]; for (int j=0; j<curLineLayer.size(); j++) { Line curLine = curLineLayer.get(j); Node toNode = curLine.getToNode(); Node fromNode = curLine.getFromNode(); fromNode.incError(toNode.getError() * curLine.getWeight()); // and update the weight of this line // NOTE: the line update function was previously in a separated method. // I have put it here because a network can consist of many Lines, and // it is a big bottleneck if I would use another method to iterate over // all the lines again, while I can also do it here and catch two flies // in once (is that an English expression?) double deltaWeight = LEARNING_RATE * toNode.getError() * fromNode.getOutput(); curLine.setWeight(Function.Weight.compute(LEARNING_RATE, MOMENTUM, toNode.getError(), fromNode.getOutput(), curLine.getWeight(), previousDeltaWeight[i][j])); previousDeltaWeight[i][j] = deltaWeight; } // use error function to calculate error values of the nodes of this layer // if we are at the last lineLayer, then use the inputLayer. else, if there // are more than one lineLayers, we must have hiddenLayers. NodeLayer curLayer = (i > 0) ? hiddenLayers[i - 1] : inputLayer; for (int j=0; j<curLayer.size(); j++) { Node curNode = curLayer.get(j); curNode.setError(Function.Error.compute(curNode.getOutput(), curNode.getError())); } } } private void initMomentum() { int maxLines = 0; // find the maximal amount of Lines in a Line Layer for (int i=0; i<lineLayers.length; i++) maxLines = (lineLayers[i].size() > maxLines) ? lineLayers[i].size() : maxLines; // initialize the array to this value // NOTE: this leads to empty calls in the array, but still it is much faster than using a VectorList previousDeltaWeight = new double[lineLayers.length][maxLines]; // initialize all previous weights to 0 for (int i=0; i<lineLayers.length; i++) for (int j=0; j<lineLayers[i].size(); j++) previousDeltaWeight[i][j] = 0.0; } /* initialize counter for error feedback */ private void initCounters() { curStepError = 0; rounds = 0; stepSize = 100; minError = 1; averageWeight = new double[lineLayers.length][lineLayers[0].size()]; minErrorWeight = new double[lineLayers.length][lineLayers[0].size()]; } public void initWeights() { for (int i=0; i<lineLayers.length; i++) for (int j=0; j<lineLayers[i].size(); j++) lineLayers[i].get(j).setWeight(MIN_WEIGHT + Utils.random().nextDouble() * (Math.abs(MIN_WEIGHT) + Math.abs(MAX_WEIGHT))); } private void saveCurrentWeight() { for (int i=0; i<lineLayers.length; i++) for (int j=0; j<lineLayers[i].size(); j++) minErrorWeight[i][j] = averageWeight[i][j] / stepSize; } public void increaseAverageWeight() { for (int i=0; i<lineLayers.length; i++) for (int j=0; j<lineLayers[i].size(); j++) averageWeight[i][j] += lineLayers[i].get(j).getWeight(); } public void loadOptimalWeights() { for (int i=0; i<lineLayers.length; i++) for (int j=0; j<lineLayers[i].size(); j++) lineLayers[i].get(j).setWeight(minErrorWeight[i][j]); } private void updateStepError() { // update only if we have run for <stepSize> times // rounds > 0, because 0 % x = 0 if ((rounds % stepSize == 0) && (rounds > 0)) { if (curStepError < minError) { saveCurrentWeight(); minError = curStepError; } curStepError = getCurrentError(); rounds = 0; } else { double curError = getCurrentError(); // update the average error by multiplying the previous error level // with the amount of runs, adding the current error level to it // and dividing this by the number of rounds+1 curStepError = (curError + curStepError * rounds) / (rounds + 1); increaseAverageWeight(); } rounds++; } private void updateTestStep() { if (rounds % stepSize == 0) { curStepError = getCurrentError(); rounds = 0; } else { curStepError = (getCurrentError() + curStepError * rounds) / (rounds + 1); increaseAverageWeight(); } rounds++; } private void setOutputTargets(int answer) { for (int i=0; i<outputLayer.size(); i++) ((OutputNode) outputLayer.get(i)).setTarget((i==answer)?1:0); } public double getCurrentError() { /* get the overall error of this network by applying the standard error function: 0.5 * (target - output) ^ 2 */ double sum = 0; for (int i=0; i<outputLayer.size(); i++) sum += Math.pow(((OutputNode) outputLayer.get(i)).getTarget() - ((OutputNode) outputLayer.get(i)).getOutput(), 2); return sum * 0.5; } public void setInitMinWeight(double MIN_WEIGHT) { this.MIN_WEIGHT = MIN_WEIGHT; } public void setInitMaxWeight(double MAX_WEIGHT) { this.MAX_WEIGHT = MAX_WEIGHT; } public void setStepSize(int stepSize) { this.stepSize = stepSize; } public void setMomentum(double momentum) { this.MOMENTUM = momentum; } public double getCurStepError() { return curStepError; } public double[][] getOptimalWeights() { return minErrorWeight; } public String printTopology() { return String.format(Utils.TOPOLOGY_MOMENTUM, super.printTopology(), MOMENTUM); } }<file_sep>/Neural Network/src/Acvtivation/Function.java package Acvtivation; public final class Function { /* Standard Sigmoid Function */ public final static class Sigmoid { public static final double compute(double val) { return 1 / (1 + Math.pow(Math.E, -val)); } } /* Standard Error Function */ public final static class Error { /* Calculate the error values of the nodes */ public static double compute(double output, double error) { return output * (1 - output) * error; } /* Notice that the output nodes primarily define the error values as the difference * between the target value and the actual output * All the other nodes simply propagate these errors base on their own output. */ public static double computeOutput(double output, double target) { return output * (1 - output) * (target - output); } } /* Standard Weight Function */ public final static class Weight { /* Calculate the new weight values of the lines; Momentum can be ignored by entering 0 for it. All other values (except previousWeight) are required. */ public static final double compute(double learningRate, double momentum, double toError, double fromOutput, double lineWeight, double previousWeight) { double deltaWeight = learningRate * toError * fromOutput; return lineWeight + deltaWeight + momentum * previousWeight; } } } <file_sep>/Neural Network/MNIST/Readme.txt Please open the web achive "MNIST handwritten digit database, <NAME>, <NAME> and <NAME>" And download the following trainning and testing data to current directory train-images-idx3-ubyte.gz train-labels-idx1-ubyte.gz t10k-images-idx3-ubyte.gz t10k-labels-idx1-ubyte.gz<file_sep>/Neural Network/src/Utils/Utils.java package Utils; import java.util.Random; public class Utils { public final static String ANN = "Artificial Neural Network"; /* Database Path */ public final static String FILE_TRAIN_IMAGES = "../MNIST/train-images.idx3-ubyte"; public final static String FILE_TRAIN_LABELS = "../MNIST/train-labels.idx1-ubyte"; public final static String FILE_TEST_IMAGES = "../MNIST/t10k-images.idx3-ubyte"; public final static String FILE_TEST_LABELS = "../MNIST/t10k-labels.idx1-ubyte"; /* the initial values of the setting of the neural network. */ public final static int INPUT_LAYER_NODES = 400; public final static int HIDDEN_LAYER_NODES = 100; public final static int OUTPUT_LAYER_NODES = 10; public final static double MOMENTUM = 0.3; public final static double LEARNING_RATE = 0.05; public final static double INIT_WEIGHT_BOUNDARIES[] = { -0.05, 0.05 }; public final static int NUM_EXAMPLES = 60000; public final static int NUM_TEST_EXAMPLES = 10000; public final static int NUM_ROUNDS = 3; /* Plotter - String*/ public final static String PLOTTER_TITLE = "Error-Correction Learning"; public final static String PLOTTER_TITLEFONT = "Arial Rounded MT Bold"; public final static String PLOTTER_XLABEL = "Number of Examples"; public final static String PLOTTER_YLABEL = "Error Rate"; public final static String PLOTTER_LEGEND_TRAIN = "Training"; public final static String PLOTTER_LEGEND_TEST = " Test "; /* GUI - Check boxes' String */ public final static String STRING_DECREASE_CANVAS = "Decrease canvas to 20x20"; public final static String STRING_SCALE_DOWN = "Scale down pixels"; /* GUI - Buttons' String */ public final static String STRING_TRAIN = "TRAIN"; public final static String STRING_TEST = "TEST"; public final static String STRING_START = "START"; public final static String STRING_STOP = "STOP"; public final static String STRING_RESET = "RESET"; /* GUI - Labels' String */ public final static String STRING_NETWORK_TOPOLOGY = "Neural Network Specifications"; public final static String STRING_INPUT_NODES = "Input nodes: "; public final static String STRING_HIDDEN_NODES = "Hidden nodes: "; public final static String STRING_OUTPUT_NODES = "Output nodes: "; public final static String STRING_MOMENTUM = "Momentum (0 = off): "; public final static String STRING_LEARNING_RATE = "Learning Rate: "; public final static String STRING_INIT_WEIGHT = "Init Weight (w1,w2): "; public final static String STRING_DATABASE_SPECS = "Databse Details"; public final static String STRING_TRAIN_DATABASE = "Train Database: "; public final static String STRING_TEST_DATABASE = "Test Database: "; public final static String STRING_SIMULATION_MODE = "Simulation Mode: "; public final static String STRING_NUM_EXAMPLES = "Number of examples: "; public final static String STRING_NUM_RUNS = "Number of runs: "; /* Log Message */ public final static String LOG_INITIAL = ">> Choose your settings and Train or Test the network.\n>> First Train and then Test."; public final static String LOG_RUN = "\n>> %s Mode %s\n>> printing error rate. Graph is updated after training."; public final static String LOG_INTERRUPTED = "\n>> run halted by user."; public final static String LOG_AVERAGE_ERROR_VALUE = "[Digit: %d, Image: %6d] Average Error Value of the Network (Every %3d times): %.8f"; /* Topology Message*/ public final static String TOPOLOGY_INPUT_NODES = "input layer: %d"; public final static String TOPOLOGY_HIDDEN_NODES = "\n\thidden layer (%d): %d"; public final static String TOPOLOGY_OUTPUT_NODES = "\n\toutput nodes: %d\n"; public final static String TOPOLOGY_CONNECTIONS = "\n\t\tconnections: %d"; public final static String TOPOLOGY_MOMENTUM = "\n\t%s\tmomentum: %s"; /* Warning Message */ public final static String WARNING_TRAINING_FIRST = "Cannot test without training first!"; /* Symbol */ public final static String COMMA = ","; public final static String NEW_LINE = "\n"; public final static String EMPTY = ""; public final static String SEMICOLON = ":"; public final static String SPACE = " "; static Random random = new Random(); public static Random random() { return random; } public final static String getMode(boolean train) { return (train ? "Training" : "Testing"); } } <file_sep>/Neural Network/src/Element/Line.java package Element; /* Line.java * A line in the network. * A line is simply a connection between two nodes, and contains a weight. * This weight can be requested and altered. The two nodes that it connects are also * saved as pointers. */ public class Line { private double weight = 0; private Node fromNode; private Node toNode; public Line(Node fromNode, Node toNode) { this(fromNode, toNode, 0); } public Line(Node fromNode, Node toNode, double weight) { this.fromNode = fromNode; this.toNode = toNode; this.weight = weight; } public void setWeight(double weight) { this.weight = weight; } public double getWeight() { return this.weight; } public Node getFromNode() { return this.fromNode; } public Node getToNode() { return this.toNode; } } <file_sep>/Neural Network/src/GUI/GUI.java package GUI; /********************************* * GUI.java - RUN THIS METHOD * ********************************* * * The start method of the application. * Contains the GUI, where the user can set the properties of the neural network. * * ---------- FUNCTIONS OF THE GUI EXPLAINED * * [1] NETWORK TOPOLOGY * * Input nodes: not editable by the user. the number of nodes depend on the input image. * can be changed by preprocessing the image (enabling the checkboxes will * change the input node value); * * Hidden nodes: the number of hidden nodes per layer, examples: * 3 creates 1 hidden layer of 3 nodes. * [] not entering a value will create a network without any hidden layers. * this will lead to underfitting; the nodes cannot hold all the information. * 2 4 1 creates 3 hidden layers of respectively 2, 4 and 1 nodes, where the first * layer will connect to the input layer and the last to the output * * Output nodes: the number of output nodes, is always 10. * every number from the input file is represented in 10 output nodes, where for every * number a different output node will have a target value of 1 and all the others a * target value of 0. * * [2] ALGORTIHM SPECIFICATIONS * * Algorithm: backprop & other * * Momentum: Making the weight update on the nth iteration depend partially on the update that * occured during the (n-1)th iteration. * Set to 0 for no momentum. Values between 0.1 and 0.3 are suggested. * * Learning rate: values between 0.05 and 0.1 are suggested * a lower values makes the simulation slower, but more stable. * * Initial Weight:the boundaries of the initial values of the weights of the lines. * values separated by a , * [0,5] * [-1,1] * [13,24.1] * * Learning method: x * * [3] SIMULATION SPECIFICATIONS * * Simulation method: Training or test. first perform a training before doing any test. * the correct files for the simulation method are selected automatically, but can * be changed by choosing another file. * * Nr of Examples: number of examples that the network should traing/test. * Nr of Runs: how often these examples should be inserted into the network. * * Decrease canvas: crop the canvas from 28x28 pixels to 20x20 pixels. * " the original black and white (bilevel) images from NIST were size normalized to fit in a * 20x20 pixel box while preserving their aspect ratio. the images were centered in a 28x28 * image by computing the center of mass of the pixels, and translating the image so as to * position this point at the center of the 28x28 field." * * --- source [http://yann.lecun.com/exdb/mnist/] * * Scale image: take a square of four pixels and reduce it to one pixel. * this was actually an experiment to speed up the training process, * it turns out that the results are very poor though. * * Start: start simulation * when started, press again to stop. * when stopped, press again to resume. * * Reset: erase all the values of the current network, aswell as the plot. * * [4] PLOT * * The plot is an instance of the PTPlot Java Plotter * http://ptolemy.eecs.berkeley.edu/java/ptplot5.7/ptolemy/plot/doc/index.htm * * The plot will auto adjust to the domain of the current values, and the user can zoom by click-drag-releasing * on the plot. * * [5] DEBUG WINDOW * * Will print the error values every [x] steps. These values are also being plotted. * It is suggested to set this to a value around 100, since a value of 1 will plot every individual result. * This will create a very messy plot. When a step size of 100 is entered, the average error term over 100 * examples will be printed and will thus be much more constant. * * Also, additional messages are printed in this window. * * stepSize can be set in the variables below (global int stepSize) * */ import java.applet.*; import java.awt.*; import java.awt.event.*; import NeuralNetwork.BackPropagation; import Utils.Utils; public class GUI extends Applet implements ActionListener, ItemListener { private static final long serialVersionUID = 1L; /* interface variables */ private Plotter plot; private NetworkDrawing drawingPanel; private Button startButton, resetButton; private TextField trainImagesFile, trainLabelsFile, testImagesFile, testLabelsFile; private TextField inputNodes, hiddenNodes, outputNodes; private TextField momentumTxt, learningRateTxt, weightBoundaries; private TextField numExamples, numRuns; private TextArea logPanel; private Panel databasePanel, plotPanel, actionContainer, specificationPanel; private Panel displayPanel, networkPanel, algorithmPanel, simulationPanel; private Panel computationPanel, demonstrationPanel; private Choice simulationModeCombo; private Checkbox decreaseCanvas, scaleDownPixels; /* neural network variables */ private BackPropagation network; private int networkLayers[]; private boolean training = true; private int stepSize = 100; private String imageFile = Utils.FILE_TRAIN_IMAGES; private String labelFile = Utils.FILE_TRAIN_LABELS; /* run in the background and communicate with the [network] object but send results to this class */ private Runner runThread; private Drawer drawThread; public void init() { setLayout(new BorderLayout()); ((Frame)getParent().getParent()).setTitle(Utils.ANN); initComponents(); initListener(); initPanels(); addDatabase(); addAction(); addNetworkSpecs(); add(demonstrationPanel, BorderLayout.CENTER); add(computationPanel, BorderLayout.SOUTH); resize(1280,640); } private void initComponents(){ drawingPanel = new NetworkDrawing(); plot = new Plotter(stepSize); logPanel = new TextArea(Utils.LOG_INITIAL, 5, 20, TextArea.SCROLLBARS_VERTICAL_ONLY); trainImagesFile = new TextField(Utils.FILE_TRAIN_IMAGES, 30); trainLabelsFile = new TextField(Utils.FILE_TRAIN_LABELS, 30); testImagesFile = new TextField(Utils.FILE_TEST_IMAGES, 30); testLabelsFile = new TextField(Utils.FILE_TEST_LABELS, 30); trainImagesFile.setEnabled(false); trainLabelsFile.setEnabled(false); testImagesFile.setEnabled(false); testLabelsFile.setEnabled(false); decreaseCanvas = new Checkbox(Utils.STRING_DECREASE_CANVAS); scaleDownPixels = new Checkbox(Utils.STRING_SCALE_DOWN); inputNodes = new TextField(Integer.toString(Utils.INPUT_LAYER_NODES), 5); hiddenNodes = new TextField(Integer.toString(Utils.HIDDEN_LAYER_NODES), 15); outputNodes = new TextField(Integer.toString(Utils.OUTPUT_LAYER_NODES), 5); inputNodes.setEnabled(false); outputNodes.setEnabled(false); momentumTxt = new TextField(Double.toString(Utils.MOMENTUM), 5); learningRateTxt = new TextField(Double.toString(Utils.LEARNING_RATE), 5); weightBoundaries = new TextField(Utils.INIT_WEIGHT_BOUNDARIES[0] + Utils.COMMA + Utils.INIT_WEIGHT_BOUNDARIES[1], 5); startButton = new Button(Utils.STRING_START); resetButton = new Button(Utils.STRING_RESET); decreaseCanvas.setState(true); scaleDownPixels.setState(false); simulationModeCombo = new Choice(); simulationModeCombo.addItem(Utils.STRING_TRAIN); simulationModeCombo.addItem(Utils.STRING_TEST); numExamples = new TextField(Integer.toString(Utils.NUM_EXAMPLES)); numRuns = new TextField(Integer.toString(Utils.NUM_ROUNDS)); } private void initListener(){ startButton.addActionListener(this); resetButton.addActionListener(this); decreaseCanvas.addItemListener(this); scaleDownPixels.addItemListener(this); simulationModeCombo.addItemListener(this); } private void initPanels(){ plotPanel = new Panel(new GridLayout(0, 1)); databasePanel = new Panel(new GridLayout(0, 1)); displayPanel = new Panel(new BorderLayout()); demonstrationPanel = new Panel(new GridLayout(0, 2)); actionContainer = new Panel(new GridLayout(1, 0)); networkPanel = new Panel(new GridLayout(0, 3)); algorithmPanel = new Panel(new GridLayout(0, 3)); simulationPanel = new Panel(new GridLayout(0, 3)); specificationPanel = new Panel(new GridLayout(1, 0)); computationPanel = new Panel(new BorderLayout()); displayPanel.add(databasePanel, BorderLayout.NORTH); displayPanel.add(plotPanel, BorderLayout.CENTER); displayPanel.add(logPanel, BorderLayout.SOUTH); demonstrationPanel.add(drawingPanel); demonstrationPanel.add(displayPanel); specificationPanel.add(networkPanel); specificationPanel.add(algorithmPanel); specificationPanel.add(simulationPanel); computationPanel.add(new Label(Utils.STRING_NETWORK_TOPOLOGY), BorderLayout.NORTH); computationPanel.add(specificationPanel, BorderLayout.CENTER); computationPanel.add(actionContainer, BorderLayout.SOUTH); } private void addDatabase(){ plotPanel.add(plot); databasePanel.add(new Label(Utils.STRING_DATABASE_SPECS)); databasePanel.add(trainImagesFile); databasePanel.add(testImagesFile); databasePanel.add(trainLabelsFile); databasePanel.add(testLabelsFile); } private void addAction(){ actionContainer.add(decreaseCanvas); actionContainer.add(scaleDownPixels); actionContainer.add(startButton); actionContainer.add(resetButton); } private void addNetworkSpecs() { networkPanel.add(new Label(Utils.STRING_INPUT_NODES)); networkPanel.add(new Label(Utils.STRING_HIDDEN_NODES)); networkPanel.add(new Label(Utils.STRING_OUTPUT_NODES)); networkPanel.add(inputNodes); networkPanel.add(hiddenNodes); networkPanel.add(outputNodes); algorithmPanel.add(new Label(Utils.STRING_MOMENTUM)); algorithmPanel.add(new Label(Utils.STRING_LEARNING_RATE)); algorithmPanel.add(new Label(Utils.STRING_INIT_WEIGHT)); algorithmPanel.add(momentumTxt); algorithmPanel.add(learningRateTxt); algorithmPanel.add(weightBoundaries); simulationPanel.add(new Label(Utils.STRING_NUM_EXAMPLES)); simulationPanel.add(new Label(Utils.STRING_NUM_RUNS)); simulationPanel.add(new Label(Utils.STRING_SIMULATION_MODE)); simulationPanel.add(numExamples); simulationPanel.add(numRuns); simulationPanel.add(simulationModeCombo); } public void addValue(double value, boolean train) { /* red plot for train and blue plot for test */ plot.addToPlot(value, (train) ? 0 : 1); drawThread = new Drawer(networkLayers, network.getOptimalWeights(), drawingPanel); drawThread.start(); } private void startTraining() { networkLayers = getNetworkLayers(); if (network == null) { network = new BackPropagation(networkLayers); network.setStepSize(getStepSize()); network.setInitMinWeight(getInitMinWeight()); network.setInitMaxWeight(getInitMaxWeight()); network.setMomentum(getMomentum()); network.printTopology(); drawingPanel.addNodes(networkLayers); } if (!training) { plot.resetCounter(); training = true; } runThread = new Runner(this, network); runThread.setTrain(true); runThread.start(); } private void startTest() { if (network == null) { Log(Utils.WARNING_TRAINING_FIRST); } else { if (training) { plot.resetCounter(); training = false; } runThread = new Runner(this, network); runThread.setTrain(false); runThread.start(); } } public void enableAll(boolean enable) { hiddenNodes.setEnabled(enable); momentumTxt.setEnabled(enable); learningRateTxt.setEnabled(enable); weightBoundaries.setEnabled(enable); numExamples.setEnabled(enable); numRuns.setEnabled(enable); simulationModeCombo.setEnabled(enable); decreaseCanvas.setEnabled(enable); scaleDownPixels.setEnabled(enable); resetButton.setEnabled(enable); startButton.setLabel( enable ? Utils.STRING_START : Utils.STRING_STOP); } public void actionPerformed(ActionEvent evt) { if (evt.getSource() == startButton) { if (startButton.getLabel() == Utils.STRING_START) { enableAll(false); if (simulationModeCombo.getSelectedItem() == Utils.STRING_TRAIN) startTraining(); else startTest(); } else { enableAll(true); runThread.interrupt(); } } else if (evt.getSource() == resetButton) { network = null; plot.resetAll(); logPanel.setText(Utils.EMPTY); drawingPanel.reset(); } } public void itemStateChanged(ItemEvent e) { if ((e.getSource() == decreaseCanvas) || (e.getSource() == scaleDownPixels)) { int inputs = (decreaseCanvas.getState()) ? 400 : 784; inputs = (scaleDownPixels.getState()) ? inputs/2 : inputs; inputNodes.setText(Integer.toString(inputs)); } else if (e.getSource() == simulationModeCombo) { if (simulationModeCombo.getSelectedItem().equals(Utils.STRING_TRAIN)) { imageFile = Utils.FILE_TRAIN_IMAGES; labelFile = Utils.FILE_TRAIN_LABELS; numExamples.setText(Integer.toString(Utils.NUM_EXAMPLES)); } else if (simulationModeCombo.getSelectedItem().equals(Utils.STRING_TEST)) { imageFile = Utils.FILE_TEST_IMAGES; labelFile = Utils.FILE_TEST_LABELS; numExamples.setText(Integer.toString(Utils.NUM_TEST_EXAMPLES)); } else { plotPanel = null; repaint(); } } } /* an algorithm to translate the nodes in the GUI to an array of nodes */ public int[] getNetworkLayers() { String[] hiddens = hiddenNodes.getText().split("\\s+"); int numHiddens = (hiddens.length == 1 && hiddens[0].length() == 0) ? 0 : hiddens.length; int[] nodes = new int[numHiddens + 2]; nodes[0] = Integer.parseInt(inputNodes.getText()); for (int i=0; i<numHiddens; i++) nodes[i+1] = Integer.parseInt(hiddens[i]); nodes[nodes.length-1] = Integer.parseInt(outputNodes.getText()); return nodes; } public void paint( Graphics g ) { } public int getStepSize() { return stepSize; } public String getImageFile() { return imageFile; } public String getLabelFile() { return labelFile; } public boolean getCanvasProcessor() { return decreaseCanvas.getState(); } public boolean getScaleProcessor() { return scaleDownPixels.getState(); } public int getNumRuns() { return Integer.parseInt(numRuns.getText()); } public int getNumExamples() { return Integer.parseInt(numExamples.getText()); } public void Log(String log) { logPanel.append(log + Utils.NEW_LINE); } public double getMomentum() { return Double.parseDouble(momentumTxt.getText()); } public double getLearningRate() { return Double.parseDouble(learningRateTxt.getText()); } public double getInitMinWeight() { return Double.parseDouble(weightBoundaries.getText().split("\\s*,\\s*")[0]); } public double getInitMaxWeight() { return Double.parseDouble(weightBoundaries.getText().split("\\s*,\\s*")[1]); } }<file_sep>/Neural Network/src/Element/LineLayer.java package Element; /* LineLayer.java * The LineLayer is simply a collection of lines. * The size is static (not dynamic like a VectorList), because of efficiency consideration. * Please read FeedForward.java for more details on this subject. */ public class LineLayer { private Line[] lines; public LineLayer(int length) { this.lines = new Line[length]; } public void add(Line line, int index) { this.lines[index] = line; } public Line get(int i) { return this.lines[i]; } public int size() { return this.lines.length; } }
95a47d1a18b59daccc2473afa66c5363bd62b22e
[ "Markdown", "Java", "Text" ]
11
Java
ZhangHector/ANNHandwritingRecognition
9c9f935f0061a9f51ee2290bca9ac535d2c53e5f
aed248d7f6f04e943b55ba2670f370d14949fabb
refs/heads/master
<file_sep># !/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 2018/6/25 14:06 # @Author : zhe # @FileName : stack.py # @Project : PyCharm class StackUnderflow(ValueError): pass class SStack(): def __init__(self): self._elems = [] def is_empty(self): return self._elems == [] def top(self): if self.is_empty(): raise StackUnderflow('In SStack.top: stack is empty') return self._elems[-1] def push(self, elem): self._elems.append(elem) def pop(self): if self.is_empty(): raise StackUnderflow('In SStack.pop: stack is empty') return self._elems.pop() from chapter3_LinearList.node import * class LStack(): def __init__(self): self._top = None def is_empty(self): return self._top is None def top(self): if self.is_empty(): raise StackUnderflow('In LStack.top: stack is empty') return self._top.get_elem() def push(self, elem): self._top = LNode(elem, self._top) def pop(self): if self.is_empty(): raise StackUnderflow('In LStack.pop: stack is empty') p = self._top self._top = self._top.get_next() return p.get_elem() def check_parens(text): '''括号匹配检查函数, text为被检查的字符串''' open_parens = '([{' close_parens = ')]}' i, text_len = 0, len(text) st = SStack() result = {'match': False, 'count': 0} while i < text_len: if text[i] in open_parens: st.push((i, text[i])) elif text[i] in close_parens: if not st.is_empty() and open_parens.index( st.pop()[1]) == close_parens.index(text[i]): result['count'] += 1 else: break i += 1 if i < text_len: print('Unmatching is found at', i, 'for', text[i]) elif i == text_len and not st.is_empty(): print('Unmatching is found at', st.top()[0], 'for', st.top()[1]) elif result['count'] == 0: print('No found parens') elif i == text_len and result['count'] > 0 and st.is_empty(): print('All pass') result['match'] = True return result class ESStack(SStack): def depath(self): return len(self._elems) def suf_exp_evalustor(exp): operators = '+-*/' st = ESStack() for x in exp: if x not in operators: st.push(float(x)) continue if st.depath() < 2: raise SyntaxError('Short of operand(s).') b = st.pop() a = st.pop() if x == '+': c = a + b elif x == '-': c = a - b elif x == '*': c = a * b elif x == '/': if b == 0: raise ZeroDivisionError('division by zero') c = a / b st.push(c) if st.depath() == 1: return st.pop() raise SyntaxError('Extra operand(s).') def trans_infix_suffix(line): operators = '+-*/()' property = {'(': 1, '+': 3, '-': 3, '*': 5, '/': 5} st = SStack() exp = [] line = line.split() for x in line: if x == '(': st.push(x) elif x == ')': while st.top() != '(': exp.append(st.pop()) try: st.pop() except: raise SyntaxError("Missing '('.") elif x not in operators: exp.append(x) else: while not st.is_empty() and property[st.top()] >= property[x]: exp.append(st.pop()) st.push(x) while not st.is_empty(): if st.top() == '(': raise SyntaxError("Extra '('.") exp.append(st.pop()) return exp def norec_fact(n): res = 1 st = SStack() while n > 0: st.push(n) n -= 1 while not st.is_empty(): res *= st.pop() return res def knap_rec(weight, wlist, n): if weight == 0: return True if weight < 0 or (weight > 0 and n < 1): return False if knap_rec(weight - wlist[n-1], wlist, n-1): print('Item ' + str(n) + ':', wlist[n-1]) return True if knap_rec(weight, wlist, n-1): return True else: return False <file_sep>class Rationa10: def __init__(self, num, den=1): self.num = num self.den = den def plus(self, another): den = self.den * another.den num = self.num * another.den + self.den * another.num return Rationa10(num, den) def print(self): print(str(self.num) + '/' + str(self.den)) r1 = Rationa10(3, 5) r1.print() r2 = r1.plus(Rationa10(7, 15)) r2.print()<file_sep># !/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 2018/7/9 13:13 # @Author : zhe # @FileName : binary_tree_class.py # @Project : PyCharm class BinTNode(): def __init__(self, dat, left=None, right=None): self.data = dat self.left = left self.right = right def count_BinTNode(t): if t is None: return 0 else: return 1 + count_BinTNode(t.left) + count_BinTNode(t.right) def sum_BinTNode(t): if t is None: return 0 else: return t.data + sum_BinTNode(t.left) + sum_BinTNode(t.right) def preorder(t, proc): ''' 先根序遍历 :param t: 二叉树类BinTNode :param proc: 节点数据操作 :return: 返回None ''' if t is None: return proc(t.data) preorder(t.left, proc) preorder(t.right, proc) def print_BinTNodes(t): if t is None: print('^', end='') return print('(' + str(t.data), end='') print_BinTNodes(t.left) print_BinTNodes(t.right) print(')', end='') from chapter5_StackAndQueue.queue import * def levelorder(t, proc): ''' 宽度优先遍历 :param t: 二叉树 :param proc: 节点数据操作 :return: 返回None ''' qu = SQueue(10) qu.enqueue(t) while not qu.is_empty(): t = qu.dequeue() if t is None: continue qu.enqueue(t.left) qu.enqueue(t.right) proc(t.data) from chapter5_StackAndQueue.stack import * def preorder_nonrec(t, proc): s = SStack() while t is not None or not s.is_empty(): while t is not None: proc(t.data) s.push(t.right) t = t.left t = s.pop() def preorder_elements(t): s = SStack() while t is not None or not s.is_empty(): while t is not None: s.push(t.right) yield t.data t = t.left t = s.pop() def postorder_nonrec(t, proc): s = SStack() while t is not None or not s.is_empty(): while t is not None: s.push(t) t = t.left if t.left is not None else t.right t = s.pop() proc(t.data) if not s.is_empty() and t is s.top().left: # 左子结点遍历完成,遍历右子结点 t = s.top().right elif not s.is_empty() and t is s.top().right: # 右子结点遍历完成,下一步是弹出父结点 # 将t设为None防止子结点再次入栈再次遍历一遍下面的子结点(退栈) t = None else: # 根节点,退栈 t = None ''' 可以合并为: else: t = None ''' class BinTreeError(ValueError): pass class BinTree(): def __init__(self): self._root = None def is_empty(self): return self._root is None def root(self): return self._root def leftchild(self): if self.is_empty(): raise BinTreeError('BinTree is None') return self._root.left def rightchild(self): if self.is_empty(): raise BinTreeError('BinTree is None') return self._root.righr def set_root(self, rootnode): self._root = rootnode def set_left(self, leftnode): if self.is_empty(): raise BinTreeError() self._root.left = leftnode def set_right(self, rightnode): if self.is_empty(): raise BinTreeError() self._root.righr = rightnode def preorder_elements(self): t, s = self._root, SStack() while t is not None or not s.is_empty(): while t is not None: s.push(t.right) yield t.data t = t.left t = s.pop() <file_sep>def sqrt(x): y = 1.0 i = 1 while abs(y * y - x) > 1e-10: i += 1 y = (y + x/y)/2 print('loop count:', i) return y<file_sep># !/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 2018/7/3 18:37 # @Author : zhe # @FileName : queue.py # @Project : PyCharm class QueueUnderflow(ValueError): pass class SQueue(): ''' 队列的list实现 ''' def __init__(self, init_len=0): self._len = init_len self._eleme = [0] * init_len self._head = 0 self._num = 0 def is_empty(self): return self._num == 0 def peek(self): if self._num == 0: raise QueueUnderflow('in peek') return self._eleme[self._head] def dequeue(self): if self._num == 0: raise QueueUnderflow('in dequeue') e = self._eleme[self._head] self._head = (self._head+1) % self._len self._num -= 1 return e def enqueue(self, e): if self._num == self._len: self.__extend() self._eleme[(self._head+self._num) % self._len] = e self._num += 1 def __extend(self): old_len = self._len self._len *= 2 new_elem = [0]*self._len for i in range(old_len): new_elem[i] = self._eleme[(self._head+i) % old_len] self._eleme, self._head = new_elem, 0 <file_sep># !/usr/bin/python3 # -*- coding: utf-8 -*- # @Author : zhe # @File : test.py # @Time : 2018/07/01 20:52 # @Software : PyCharm from .stack import check_parens, trans_infix_suffix, suf_exp_evalustor def test_trans_infix_suffixs(s): print(s) check = check_parens(s) assert check['match'] is True correct_value = eval(s) tran = trans_infix_suffix(s) print(tran) value = suf_exp_evalustor(tran) print(correct_value, value) assert correct_value == value <file_sep># !/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 2018/7/9 13:50 # @Author : zhe # @FileName : simple_sorting_algorithm.py # @Project : PyCharm def insert_sort(lst): ''' 插入排序 :param lst: 待排序的list :return: 这里直接修改待排序的list,不需要返回 ''' for i in range(1, len(lst)): value = lst[i] j = i while j > 0 and lst[j - 1] > value: lst[j] = lst[j - 1] j -= 1 lst[j] = value def select_sort(lst): ''' 选择排序 不稳定举例: [5, 8, 5, 2, 9],第一个5和第二个5 改变交换的方式,比如和插入排序一后移可以使其稳定 :param lst: 同insert_sort :return: 同insert_sort ''' for i in range(len(lst) - 1): index = i for j in range(i, len(lst)): if lst[j] < lst[index]: index = j if lst[index] < lst[i]: lst[i], lst[index] = lst[index], lst[i] def hubble_sort1(lst): ''' 交换排序: 冒泡法 :param lst: 同insert_sort :return: 同insert_sort ''' count = len(lst) - 1 while count > 0: found = False for i in range(count): if lst[i + 1] < lst[i]: lst[i], lst[i + 1] = lst[i + 1], lst[i] found = True if not found: break count -= 1<file_sep># !/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 2018/6/21 15:17 # @Author : zhe # @FileName : CList.py # @Project : PyCharm from .node import LNode, DLNode, LinkedListUnderflow # 循环单链表 class LCList: def __init__(self): self._rear = None def is_empty(self): return self._rear is None def set_empty(self): self._rear = None def prepend(self, elem): if self._rear is None: self._rear = LNode(elem, self._rear) self._rear.set_next(self._rear) else: p = LNode(elem, self._rear.get_next()) self._rear.set_next(p) return self._rear.get_next() def append(self, elem): self.prepend(elem) self._rear = self._rear.get_next() return self._rear def pop(self): if self._rear is None: raise LinkedListUnderflow('in pop of LCList') p = self._rear.get_next() if self._rear is p: self._rear = None else: self._rear.set_next(p.get_next()) return p def length(self): p, n = self._rear, 0 while p is not None: n += 1 p = p.get_next() if p is self._rear: break return n def find(self, elem): elems_list = [] if self._rear is not None: p, i = self._rear.get_next(), 0 while True: if p.get_elem() == elem: elems_list.append((i, p)) p = p.get_next() if p is self._rear.get_next(): break i += 1 return elems_list def filter(self, pred): if self._rear is not None: p = self._rear.get_next() while True: elem = p.get_elem() if pred(elem): yield p p = p.get_next() if p is self._rear.get_next(): break def for_each(self, proc): p = self._rear while p is not None: p.set_elem(proc(p.get_elem())) p = p.get_next() if p is self._rear: break def elements(self): if self._rear is not None: p = self._rear.get_next() while True: yield p p = p.get_next() if p is self._rear.get_next(): break def reverse(self): length = self.length() if length > 1: for i in range(length // 2): p = self._rear.get_next() # 初始化j,因为for循环不一定会执行,否则导致j未定义错误 j = 0 for j in range(1, i+1): p = p.get_next() tmp1 = p.get_elem() for j in range(j+1, length-i): p = p.get_next() tmp2 = p.get_elem() p.set_elem(tmp1) p = self._rear.get_next() for j in range(1, i+1): p = p.get_next() p.set_elem(tmp2) def printall(self): if self._rear is None: print('empty list') else: # 单个结点 if self._rear is self._rear.get_next(): print(0, '-', self._rear.get_elem()) else: p = self._rear.get_next() i = 0 while True: print(i, '-', p.get_elem()) if p is self._rear: break p = p.get_next() i += 1 # 循环双链表 class DCList(LCList): def __init__(self): super().__init__() def prepend(self, elem=None): if self._rear is None: self._rear = DLNode(elem) self._rear.set_next(self._rear) self._rear.set_prev(self._rear) else: p = DLNode(elem, self._rear, self._rear.get_next()) self._rear.get_next().set_prev(p) self._rear.set_next(p) return self._rear.get_next() def append(self, elem=None): self.prepend(elem) self._rear = self._rear.get_next() return self._rear def pop(self): if self._rear is None: raise LinkedListUnderflow('in pop of DCList') p = self._rear.get_next() if self._rear is p: self._rear = None else: p.get_next().set_prev(self._rear) self._rear.set_next(p.get_next()) return p def pop_last(self): if self._rear is None: raise LinkedListUnderflow('in pop_list of DCList') p = self._rear if self._rear is p.get_next(): self._rear = None else: self._rear = p.get_prev() self._rear.set_next(p.get_next()) p.get_next().set_prev(self._rear) return p def reverse(self): length = self.length() if length > 1: p1 = self._rear.get_next() p2 = self._rear for i in range(length // 2): tmp = p1.get_elem() p1.set_elem(p2.get_elem()) p2.set_elem(tmp) p1 = p1.get_next() p2 = p2.get_prev() <file_sep># !/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 2018/6/21 15:21 # @Author : zhe # @FileName : LList.py # @Project : PyCharm from .node import LNode, DLNode, LinkedListUnderflow # 实现单链表 class LList: def __init__(self): self._head = None def is_empty(self): return self._head is None def set_empty(self): self._head = None def prepend(self, elem=None): self._head = LNode(elem, self._head) return self._head def pop(self): if self._head is None: raise LinkedListUnderflow('in pop of LList') e = self._head self._head = self._head.get_next() return e def append(self, elem=None): if self._head is None: self._head = LNode(elem) return self._head p = self._head while p.get_next() is not None: p = p.get_next() p.set_next(LNode(elem)) return p.get_next() def pop_last(self): if self._head is None: raise LinkedListUnderflow('in pop_last of LList') p = self._head if p.get_next() is None: self._head = None return p while p.get_next().get_next() is not None: p = p.get_next() e = p.get_next() p.set_next() return e def length(self): p, n = self._head, 0 while p is not None: p = p.get_next() n += 1 return n def find(self, pred): i = 0 p = self._head elem_list = [] while p is not None: if p.get_elem() == pred: elem_list.append((i, p)) i += 1 p = p.get_next() return elem_list def filter(self, pred): p = self._head while p is not None: elem = p.get_elem() if pred(elem): yield p p = p.get_next() def for_each(self, proc): p = self._head while p is not None: p.set_elem(proc(p.get_elem())) p = p.get_next() def elements(self): p = self._head while p is not None: yield p p = p.get_next() def printall(self): p = self._head i = 0 while p is not None: print(i, '-', p.get_elem(), end='') if p.get_next() is not None: print(', ', end='') p = p.get_next() i += 1 print('') def reverse(self): length = self.length() if length > 1: for i in range(length // 2): p = self._head # 初始化j,因为for循环不一定会执行,否则导致j未定义错误 j = 0 for j in range(1, i+1): p = p.get_next() tmp1 = p.get_elem() for j in range(j+1, length-i): p = p.get_next() tmp2 = p.get_elem() p.set_elem(tmp1) p = self._head for j in range(1, i+1): p = p.get_next() p.set_elem(tmp2) # 添加尾结点 class LList1(LList): def __init__(self): super().__init__() self._rear = None def prepend(self, elem=None): if self._head is None: self._head = LNode(elem, self._head) self._rear = self._head else: self._head = LNode(elem, self._head) return self._head def append(self, elem=None): if self._head is None: self._head = LNode(elem, self._head) self._rear = self._head else: self._rear.set_next(LNode(elem)) self._rear = self._rear.get_next() return self._rear def pop(self): if self._head is None: raise LinkedListUnderflow e = self._head self._head = self._head.get_next() if self._head is None: self._rear = self._head return e def pop_last(self): if self._head is None: raise LinkedListUnderflow('in pop-last') p = self._head if p.get_next() is None: e = p self._head = None # self._rear = self._head return e while p.get_next().get_next() is not None: # while p.get_next() != self._rear p = p.get_next() e = p.get_next() p.set_next() self._rear = p return e def is_empty(self): return self._head is None and self._rear is None def set_empty(self): super().set_empty() self._rear = None # 双链表 class DLList(LList1): def __init__(self): super().__init__() def prepend(self, elem=None): if self._head is None: self._head = DLNode(elem) self._rear = self._head else: self._head = DLNode(elem, next_=self._head) self._head.get_next().set_prev(self._head) return self._head def append(self, elem=None): if self._head is None: self._head = DLNode(elem) self._rear = self._head else: self._rear = DLNode(elem, self._rear) self._rear.get_prev().set_next(self._rear) return self._rear def pop(self): if self._head is None: raise LinkedListUnderflow e = self._head self._head = self._head.get_next() if self._head is None: self._rear = self._head else: self._head.set_prev() return e def pop_last(self): if self._head is None: raise LinkedListUnderflow e = self._rear self._rear = self._rear.get_prev() if self._rear is None: self._head = None else: self._rear.set_next() return e def reverse(self): length = self.length() if length > 1: p1 = self._head p2 = self._rear for i in range(length // 2): tmp = p1.get_elem() p1.set_elem(p2.get_elem()) p2.set_elem(tmp) p1 = p1.get_next() p2 = p2.get_prev()<file_sep># !/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 2018/6/21 15:11 # @Author : zhe # @FileName : node.py # @Project : PyCharm class LinkedListUnderflow(Exception): pass # 结点 class LNode: def __init__(self, elem=None, next_=None): self._elem = elem self._next = next_ def get_elem(self): return self._elem def get_next(self): return self._next def set_elem(self, elem=None): self._elem = elem def set_next(self, next=None): self._next = next # 添加反向引用 class DLNode(LNode): def __init__(self, elem=None, prev=None, next_=None): super().__init__(elem, next_) self.prev = prev def get_prev(self): return self.prev def set_prev(self, prev=None): self.prev = prev <file_sep># !/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 2018/6/22 14:03 # @Author : zhe # @FileName : matching.py # @Project : PyCharm def naive_matching(t, p): m, n = len(p), len(t) result = {'count': 0, 'index': []} for i in range(n - m + 1): count = 0 for j in range(m): if t[i + j] == p[j]: count += 1 else: break if count == m: result['count'] += 1 result['index'].append(i) return result def matching_KMP(t, p): n, m = len(t), len(p) i, k = 0, -1 pnext = [-1] * m # 初始数组全为-1 while i < m - 1: # 生成下一个pnext元素值 if k == -1 or p[i] == p[k]: i, k = i + 1, k + 1 pnext[i] = k # 设置pnext元素 else: k = pnext[k] # 退到更短相同前缀 i, j = 0, 0 ''' # 展开 while j < n and i < m: # i==m找到匹配 if i == -1: # 遇到-1,比较下一对字符 j, i = j + 1, i + 1 elif t[j] == p[i]: # 字符相等,比较下一对字符 j, i = j + 1, i + 1 else: i = pnext[i] # 匹配失败,从pnext取得p的下一字符位置 ''' result = {'count': 0, 'index': []} while j < n - m - 1: i = 0 while j < n and i < m: if i == -1 or t[j] == p[i]: j, i = j + 1, i + 1 else: i = pnext[i] if i == m: # 匹配成功,返回下标 result['count'] += 1 result['index'].append(j - m) j = j - m + 1 # j指向匹配成功的下一位,此方法有待改进 return result <file_sep># !/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 2018/7/9 15:43 # @Author : zhe # @FileName : quicksort.py # @Project : PyCharm def qucik_sort1(lst): def qsort_rec(lst, l, r): if l >= r: return i = l j = r pivot = lst[i] while i < j: while i < j and lst[j] >= pivot: j -= 1 if i < j: lst[i] = lst[j] i += 1 while i < j and lst[i] <= pivot: i += 1 if i < j: lst[j] = lst[i] j -= 1 lst[i] = pivot qsort_rec(lst, l, i - 1) qsort_rec(lst, i + 1, r) qsort_rec(lst, 0, len(lst) - 1) def quick_sort2(lst): def qsort(lst, begin, end): if begin >= end: return pivot = lst[begin] i = begin for index in range(begin + 1, end + 1): if lst[index] < pivot: i += 1 lst[i], lst[index] = lst[index], lst[i] lst[begin], lst[i] = lst[i], pivot qsort(lst, begin, i - 1) qsort(lst, i + 1, end) qsort(lst, 0, len(lst) - 1) def quick_sort3(lst): def qsort(lst, l, r): if l >= r: return i, j = l + 1, r pivot = lst[l] while i < j: while i < j and lst[j] >= pivot: j -= 1 while i < j and lst[i] < pivot: i += 1 if i < j: # print('change %s:%s %s:%s' % (i, lst[i], j, lst[j])) lst[i], lst[j] = lst[j], lst[i] # print('changed', lst) i += 1 j -= 1 if i == j and lst[i] < pivot: lst[l], lst[i] = lst[i], pivot # print(lst) qsort(lst, l, i - 1) qsort(lst, i + 1, r) else: lst[l], lst[i - 1] = lst[i - 1], pivot # print(lst) qsort(lst, l, i - 2) qsort(lst, i, r) qsort(lst, 0, len(lst) - 1) if __name__ == '__main__': from random import randint for i in range(10): a = [] for j in range(100, randint(1000, 10000)): a.append(randint(0, j)) b = a[:] test1 = a[:] test2 = a[:] test3 = a[:] b.sort() qucik_sort1(test1) quick_sort2(test2) quick_sort3(test3) assert test1 == b assert test2 == b assert test3 == b <file_sep>### 数据结构与算法--Python语言描述 这是《数据结构与算法--Python语言描述》的学习记录<br> 教材作者为北京大学裘宗燕,机械工业出版社<file_sep>#### 线性表 - 单链表 - 循环单链表 - 双链表 - 循环双链表 ##### 已经实现的方法 - 首尾添加删除 - 链表的长度 - 元素的寻找、过滤 - 生成器、链表map、元素倒置 - 打印 ##### 需要修改/实现的方法 - 链表的倒置,分为两种:修改结点元素和修改节点之间连结关系,采用后者 - 链表的排序,见第9章内容<file_sep>def fib1(n, a=1, b=1): if n == 1: return a elif n == 2: return b elif n >= 3: for i in range(n-2): b, a = a+b, b return b else: return 0 def fib2(n, a=1, b=1): if n == 1: return a elif n == 2: return b elif n >= 3: return fib2(n-1, a, b) + fib2(n-2, a, b) else: return 0 print(fib1(1), fib1(2), fib1(3), fib1(5), fib1(10)) print(fib2(1, 2, 2), fib2(2, 2, 2), fib2(3, 2, 2), fib2(5, 2, 2), fib2(10, 2, 2)) for i in range(20): print(fib2(i, 1, 2))<file_sep># -*- coding: utf-8 -*- # @Author : zhe # @File : person.py # @Time : 2018/04/27 21:06 # @Software: PyCharm import datetime class PersonTypeError(TypeError): pass class PersonValueError(ValueError): pass class Person: _num = 0 def __init__(self, name, sex, birthday): if not isinstance(name, str): raise PersonTypeError('name must be str', name) if sex not in ('男', '女'): raise PersonValueError('sex must in "男" or "女"',sex) try: birth = datetime.date(*birthday) except: raise PersonValueError('Wrong date', birthday) self._name = name self._sex = sex self._birthday = birth self._age = datetime.date.today().year - self._birthday.year Person._num += 1 self._id = Person._num def get_id(self): return self._id def get_name(self): return self._name def get_sex(self): return self._sex def get_birthday(self): return self._birthday def get_age(self): return datetime.date.today().year - self._birthday.year @classmethod def get_person_num(cls): return Person._num def set_birthday(self, birthday): try: birth = datetime.date(*birthday) except: raise PersonValueError('Wrong date', birthday) self._birthday = birth self._age = datetime.date.today().year - self._birthday.year def set_name(self, new_name): if not isinstance(new_name, str): raise PersonTypeError('set_name', new_name) self._name = new_name def __lt__(self, other): if not isinstance(other, Person): raise PersonTypeError('error other', other) return self.get_id() < other.get_id() def __str__(self): return ', '.join(( self.get_id(), self.get_name(), )) def details(self): return ', '.join(( 'ID: ' + str(self.get_id()), 'Name: ' + self.get_name(), 'Sex: ' + self.get_sex(), 'Birthday: ' + self.get_birthday().strftime('%Y-%m-%d'), 'Age: ' + str(self.get_age()), )) class Student(Person): _num = 0 _id_num = 0 @classmethod def _id_gen(cls): cls._id_num += 1 Student._num += 1 year = datetime.date.today().year return '1{:04}{:05}'.format(year, cls._id_num) def __init__(self, name, sex, birthday, department): super().__init__(name, sex, birthday) self._department = department self._enroll_date = datetime.date.today() self._courses = {} self._id = Student._id_gen() def set_course(self, course_name): self._courses[course_name] = None def set_soure(self, course_name, score): if course_name in self._courses: self._courses[course_name] = score else: raise PersonValueError('没有选修这门课程') def set_department(self, department): self._department = department def get_scores(self): return [(course_name, score) for course_name,score in self._courses.items()] def get_score(self, course_name): if course_name in self._courses: return self._courses[course_name] else: raise PersonValueError('没有选修这门课') @classmethod def get_student_num(cls): return cls._num def details(self): return ', '.join( ( Person.details(self), '入学日期:' + str(self._enroll_date), '院系:' + self._department, '课程记录:' + str(self.get_scores()), ) ) class Staff(Person): _id_num = 0 @classmethod def _id_gen(cls, birthday): cls._id_num += 1 birth_year = datetime.date(*birthday).year return '0{:04}{:05}'.format(birth_year, cls._id_num) def __init__(self, name, sex, birthday, department, entry_date = None, position = None): super().__init__(name, sex, birthday) if entry_date: try: self._entry_date = datetime.date(*entry_date) except: raise PersonValueError('错误的日期格式') else: self._entry_date = datetime.date.today() self._salary = 1720 self._department = department self._entry_age = datetime.date.today().year - self._entry_date.year self._position = position self._id = Staff._id_gen(birthday) def set_salary(self, salary): if type(salary) is int or type(salary) is float: if salary < 0: raise PersonValueError('工资小于0!') self._salary = salary else: raise PersonTypeError('错误,工作为整数或者小数') def set_department(self, department): self._department = department def set_position(self, position): self._position = position def get_department(self): return self._department def get_position(self): return self._position def get_salary(self): return self._salary def get_entry_date(self): return self._entry_date def get_entry_age(self): return self._entry_age def details(self): return ', '.join(( super().details(), '入职日期:' + str(self._entry_date), '院系:' + self._department, '职位:' + self._position, '工资:' + str(self._salary), '工龄:' + str(self._entry_age), ))<file_sep># !/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 2018/7/5 8:56 # @Author : zhe # @FileName : binary_tree.py # @Project : PyCharm def bin_tree(data, left=None, right=None): return [data, left, right] def is_empty_BinTree(btree): return btree is None def root(btree): return btree[0] def left(btree): return btree[1] def right(btree): return btree[2] def set_root(btree, data): btree[0] = data def set_left(btree, left): btree[1] = left def set_right(btree, right): btree[2] = right def make_sum(a, b): return ('+', a, b) def make_diff(a, b): return ('-', a, b) def make_prod(a, b): return ('*', a, b) def make_div(a, b): return ('/', a, b) def is_basic_exp(a): return not isinstance(a, tuple) def is_number(x): return isinstance(x, int) or isinstance(x, float) or isinstance(x, complex) def eval_sum(a, b): if is_number(a) and is_number(b): return a + b if is_number(a) and a == 0: return b if is_number(b) and b == 0: return a return make_sum(a, b) def eval_diff(a, b): if is_number(a) and is_number(b): return a - b if is_number(a) and a == 0: return -b if is_number(b) and b == 0: return a return make_diff(a, b) def eval_prod(a, b): if is_number(a) and is_number(b): return a * b if is_number(a) and a == 0: return 0 if is_number(b) and b == 0: return 0 return make_prod(a, b) def eval_div(a, b): if is_number(b) and b == 0: raise ZeroDivisionError if is_number(a) and is_number(b): return a / b if is_number(a) and a == 0: return 0 return make_div(a, b) def eval_exp(e): if is_basic_exp(e): return e op, a, b = e[0], eval_exp(e[1]), eval_exp(e[2]) if op == '+': return eval_sum(a, b) elif op == '-': return eval_diff(a, b) elif op == '*': return eval_prod(a, b) elif op == '/': return eval_div(a, b) else: raise ValueError('Unknown operator:', op) <file_sep># !/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 2018/6/22 8:31 # @Author : zhe # @FileName : Josephue.py # @Project : PyCharm from .CList import LCList def josephus_A(n, k, m): people = list(range(1, n + 1)) i = k - 1 for num in range(n): count = 0 while count < m: if people[i] > 0: count += 1 if count == m: print(people[i], end='') people[i] = 0 i = (i + 1) % n if num == n - 1: print('') else: print(', ', end='') def josephus_B(n, k, m): people = list(range(1, n + 1)) i = k - 1 while people: length = len(people) i = (i + m - 1) % length num = people.pop(i) print(num, end=(', ' if length != 1 else '\n')) class Josephus(LCList): def __init__(self, n, k, m): super(Josephus, self).__init__() self.n = n self.k = k self.m = m for i in range(1, self.n + 1): self.append(i) def turn(self, m): for i in range(m): self._rear = self._rear.get_next() def run(self): self.turn(self.k - 1) while not self.is_empty(): self.turn(self.m - 1) num = self.pop() print(num.get_elem(), end=(', ' if self.length() != 0 else '\n')) <file_sep># !/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 2018/7/10 9:24 # @Author : zhe # @FileName : merge_sort.py # @Project : PyCharm def merge(lfrom, lto, low, mid, high): i, j, k = low, mid, low while i < mid and j < high: if lfrom[k] <= lfrom[i]: lto[k] = lfrom[i] i += 1 else: lto[k] = lfrom[j] j += 1 k += 1 while i < mid: lto[k] = lfrom[i] i += 1 k += 1 while j < high: lto[k] = lfrom[j] j += 1 k += 1 def merge_pass(lfrom, lto, llen, slen): i = 0 while i + 2 * slen < llen: merge(lfrom, lto, i, i + slen, i + 2 * slen) i += 2 * slen if i + slen < llen: merge(lfrom, lto, i, i+slen, llen) else: for j in range(i, llen): lto[j] = lfrom[j] def merge_sort(lst): slen, llen = 1, len(lst) temp = [None] * llen while slen < llen: merge_pass(lst, temp, llen, slen) slen *= 2 merge_pass(temp, lst, llen, slen) slen *= 2
83619ca9b020d2ba3a12995cf468f64b926b2428
[ "Markdown", "Python" ]
19
Python
huazhaozhe/DSAAInPython
6b02070532e1982d016f73189e6d00fa4da32b78
afac8fdcdd326eaee329b07ca23e9466bd55c259
refs/heads/main
<file_sep>import fs from "fs"; import faceapi from "face-api.js"; import nodeCanvas from "canvas"; import util from "util"; import stream from "stream"; import { dirname } from "path"; import { fileURLToPath } from "url"; import fetch from "node-fetch"; const __dirname = dirname(fileURLToPath(import.meta.url)); const MODELS_PATH = `${__dirname}/models`; const SOURCE_FILE = "sample.json"; const EVENT_ID = "Event ID"; const peopleData = JSON.parse(fs.readFileSync(SOURCE_FILE).toString()); await faceapi.nets.ssdMobilenetv1.loadFromDisk(MODELS_PATH); await faceapi.nets.faceLandmark68Net.loadFromDisk(MODELS_PATH); await faceapi.nets.faceRecognitionNet.loadFromDisk(MODELS_PATH); const { Canvas, Image, ImageData } = nodeCanvas; faceapi.env.monkeyPatch({ Canvas, Image, ImageData }); const downloadImage = async (uri, filename) => { const streamPipeline = util.promisify(stream.pipeline); const response = await fetch(uri); if (response.ok) { return streamPipeline(response.body, fs.createWriteStream(filename)); } if (response.status === 404) { console.log(`Got a 404 for ${filename}`); return fs.copyFileSync(`${__dirname}/assets/default_profile.png`, filename); } throw new Error(`Unexpected response ${response.status} ${response.statusText}`); }; const getDescriptors = async filename => { let faceDescriptors = {}; try { const input = await nodeCanvas.loadImage(filename); const fullFaceDescription = await faceapi.detectSingleFace(input).withFaceLandmarks().withFaceDescriptor(); if (!fullFaceDescription) { console.log(`No faces detected for ${filename}`); return; } faceDescriptors = fullFaceDescription.descriptor; } catch(e) { console.log(e); } return faceDescriptors; } async function main() { let newPeopleData = peopleData.map(async personData => { let uri = personData.imgSrc; let filename = uri.split("/"); filename = filename[filename.length - 1]; let fileExtension = filename.substr(filename.lastIndexOf(".") + 1); if (filename === fileExtension) { fileExtension = "jpg"; filename = `${filename}.${fileExtension}`; } filename = `${__dirname}/tmp/${filename}`; await downloadImage(uri, filename); let descriptors = await getDescriptors(filename); personData.descriptors = descriptors; personData.eventId = EVENT_ID; try { await fs.unlinkSync(filename); } catch(e) { console.log(e); } return personData; }); Promise.all(newPeopleData).then(d => { console.log(newPeopleData); fs.writeFileSync(SOURCE_FILE.replace(".json", "-withDescriptors.json"), JSON.stringify(d)); }); } main(); <file_sep>import express from "express"; import cors from "cors"; import { dirname } from "path"; import { fileURLToPath } from "url"; import { MongoClient } from "mongodb"; import faceapi from "face-api.js"; import nodeCanvas from "canvas"; import dotenv from "dotenv"; dotenv.config(); const __dirname = dirname(fileURLToPath(import.meta.url)); const wwwPath = `${__dirname}/www`; const MODELS_PATH = `${__dirname}/models`; const PORT = process.env.PORT || 3000; // Connect to MongoDB const { MONGODB_USER, MONGODB_PASS, MONGODB_CLUSTER } = process.env; if (!MONGODB_CLUSTER) { console.error("No MongoDB cluster was specified. Exiting."); process.exit(1); } const mongoClient = await MongoClient.connect( `mongodb+srv://${MONGODB_USER}:${MONGODB_PASS}@${MONGODB_CLUSTER}.mongodb.net/edge-poc?authSource=admin&replicaSet=atlas-v6xmes-shard-0&readPreference=primary&appname=MongoDB%20Compass&ssl=true`, { useNewUrlParser: true, useUnifiedTopology: true }); // Load face recognition models await faceapi.nets.ssdMobilenetv1.loadFromDisk(MODELS_PATH); await faceapi.nets.faceLandmark68Net.loadFromDisk(MODELS_PATH); await faceapi.nets.faceRecognitionNet.loadFromDisk(MODELS_PATH); // Use Node Canvas and monkey patch FaceAPI.js const { Canvas, Image, ImageData } = nodeCanvas; faceapi.env.monkeyPatch({ Canvas, Image, ImageData }); // Initialize Server const app = express(); app.use(cors()); app.use(express.static(wwwPath)); app.use(express.json({limit: '50mb'})); app.get("/", (req, res) => { res.sendFile(`${wwwPath}/index.html`); }); app.post("/detection", async (req, res) => { console.log("Face detection requested"); //Load image in a node-canvas with a 500px height. Width is calculated to preserve ration let img = new Image(); img.src = req.body.imgData; let canvas = new Canvas(); let imageRatio = img.width / img.height; canvas.height = 500; canvas.width = 500 * imageRatio; let ctx = canvas.getContext("2d"); ctx.drawImage(img, 0, 0, img.width, img.height, 0, 0, canvas.width, canvas.height); //Find the face descriptors for each face on this image let fullFaceDescriptions = await faceapi .detectAllFaces(img) .withFaceLandmarks() .withFaceDescriptors(); let dim = new faceapi.Dimensions(canvas.width, canvas.height); fullFaceDescriptions = faceapi.resizeResults(fullFaceDescriptions, dim); //Fetch the face descriptors from MongoDB const filter = { 'descriptors': { '$exists': true }, 'eventId': 'CodePaLOUsa' }; const projection = { 'name': 1, 'descriptors': 1, '_id': 0 }; let coll = mongoClient.db('edge-poc').collection('people'); let cursor = coll.find(filter, { projection: projection }); let faceData = await cursor.toArray(); // Create an array of existing face descriptors let labeledFaceDescriptors = faceData.map(desc => { let arr = Float32Array.from(desc.descriptors); return new faceapi.LabeledFaceDescriptors(desc.name, [arr]); }); //Find the best matches using the faceMatcher const maxDescriptorDistance = 0.6; const faceMatcher = new faceapi.FaceMatcher(labeledFaceDescriptors, maxDescriptorDistance); const results = fullFaceDescriptions.map(fd => faceMatcher.findBestMatch(fd.descriptor)); // Format data to send back to the client let responseObject = []; results.forEach((bestMatch, i) => { let obj = { name: bestMatch.label, distance: bestMatch.distsance, box: fullFaceDescriptions[i].detection.box }; responseObject.push(obj); }); //Return the matching name res.send(responseObject).status(200); }); app.listen(PORT, () => console.log(`Server started on port ${PORT}`))<file_sep># Edge Computing POC Sample face recognition application for edge computing POC. The front-end (index.html) page will let you pick an image on your local machine. The image is then uploaded to the Node.js server for processing. Node.js fetched a list of existing face descriptors (mathematical representation of faces) from MongoDB each time the /detect URL is hit. ## Installation Install dependencies ``` npm install ``` Edit the file `index.js` to add your MongoDB cluster info. Start the server ``` node . ``` Point your browser to [http://localhost:3000](http://localhost:3000) ## Import data Using a JSON file with an array of images and names: ``` [ { "imgSrc": "https://example.com/speaker/face.jpg", "name": "<NAME>" }, ... ] ``` Open the file `addFaceDescriptors.js`. Change line 12 to the name of your `.json` file. You can also specify an event id on line 13. Then run the script. ``` node addFaceDescriptors ``` For each item in the array, the script will * Download the image to the `/tmp` folder (make sure it exists) * Run the analyzer and find the face descriptors * Create a new JSON object with the name, imgSrc, face descriptors and event id The new array is the written to a file named `ORIGINAL-withDescriptors.json`. Once you have this file, you can import it to MongoDB using [Compass](https://www.mongodb.com/products/compass) (or [mongoimport](https://docs.mongodb.com/guides/server/import/)).
b89b5c51a09a1f489bc86ccf5a56a9bb1350232a
[ "JavaScript", "Markdown" ]
3
JavaScript
joellord/edge-poc
4a823683982500d42c3d813e16b5cc843983d2b8
ee083b8509beb70cf36ec8d6a224fba3d7bba6cb
refs/heads/master
<repo_name>angeldar/r-notes<file_sep>/README.md r-notes ======= Notes about R programming language. <file_sep>/basics.r # This is a comment # '<-' - is the assignment operator. # c() - for Combine. Generic function, to form a vector. # vector - is a data type, that must contain entries that are all of the same type. colors <- c("red", "green", "blue") # IMPORTANT - R using 1 based indexing. colors[1] # is red # Print the vector colors # Create vector of numbers, with values from one to 10. numbers <- c(1:10) # Add values to a vector numbers <- c(numbers, 11:15) # R has some built in datasets data(mtcars) names(mtcars) # Use '?' to get more information about any commands. ?mean str(mtcars) # get the structure of dataset head(mtcars, 10) # prints first 10 rows of dataset tail(mtcars, 10) # prints last 10 rows of dataset # Use '$' to get any column mtcars$mpg ### datasets getwd() # get working directory setwd('') # set working directory (use forwar '/' slashes) statesInfo <- read.csv('data.csv', sep='\t') # read data from data.csv subset(statesInfo, state.region == 1) # get subset of data, where region == 1 subset(statesInfo, !is.na(gender)) # get subset of data, where present the value of gender row statesInfo[statesInfo$state.region = 1,] # the same table(reddit$gender) # table by(reddit$friend_count, reddit$gender, summary) ### R markdown # You can use markdown with R. The extension of the file will be .Rmd ```{r} summary(mtcars) # summary - get basic info. Min, max, median and quantiles about each column. ``` # ifelse construction cond <- mtcars$wt < 3 mtcars$weight_class <- ifelse(cond, 'light', 'average') # Libraries # ggplot2 - library to plot graphs. # gridExtra - library to plot complex grids of graphs. # installation install.packages('ggplot2') # install package library(ggplot2) # load package # plot the histogramm qplot(data = reddit, x = age.range) # plot a splitted histogram with a binwidth, breaks and scale x a axis: qplot(x = age.range, data = reddit, binwidth = 25) + scale_x_continious(limit = c(0, 1000) breaks = seq(0, 1000, 50)) + facet_wrap(~gender) # plot many graphs in a grid library(gridExtra) # Define individual plots p1 = qplot(...) p2 = qplot(...) p3 = qplot(...) p4 = qplot(...) # Arrange plots in grid grid(p1, p2, p3, p4, ncol = 2) # Independence tests # p-value is the probability of columns and rows are independent. # Chi-square test chisq.test(table) # Fisher's test fisher.test(table) # Chochran-Mantel-Haenszel test mantelhaen.test(table) # Correlations # x - data, use - specifies the handling of missing data, # method - pearson(default) | spearman | kendall cor(x, use= , method=) cor(x, y) # x and y are vectors <file_sep>/pandas_notes.py # Notes about pandas froamework for python # Pandas is a data-analisys framework for python, like R programming language. #import pandas import pandas # Read data data = pandas.read_csv('file.csv') # Get data column data['nameFirst'] # Add new column using old columns data['new_column'] = data['weight'] + data['height'] # Filter data by column. data = data[data.colour = 'green'] # Create new row with values equal difference between current and previous value of another row data['diff'] = (data['money'] - data['money'].shift(1)).fillna(1) # Save data to csv data.to_csv('new_file.csv') # You can use SQL queries in pandas import pandasql q = """ SELECT * FROM data LIMIT 30 WHERE country = "russia" """ pandasql.sqldf(q.lower(), locals()) # Describe dataframe data.describe() # Fill NA values with the mean data['weight'] = data['weight'].fillna(numpy.mean(data['weight'])) <file_sep>/gettin_and_cleaning_data.R ## Getting and cleaning data with R ## From coursera Getting and Cleaning Data course ### Reading data ## Get working directory getwd() ## Set working directory setwd('./data') ## Checking for and creating directories if (!file.exists('directoryName')) { dir.create('directoryName') } ## Getting data from the internet download.file(fileUrl, destfile = './data/cameras.csv', method = 'curl') list.files('./data') dateDownloaded <- date() ## Reading local files cameraData <- read.table('data/cameras.csv', sep = ',', header = TRUE) cameraData <- read.csv('data/cameras.csv') ## Reading Excel files library(xlsx) cameraData <- read.xlsx('data/camera.xlsx', sheetIndex=1, header = TRUE) colIndex <- 1:4 rowIndex <- 2:3 cameraData <- read.xlsx('data/camera.xlsx', sheetIndex=1, header = TRUE, colIndex = colIndex, rowIndex = rowIndex) ## Reading XML library(XML) fileUrl <- 'www.example.com/simple.xml' doc <- xmlTreeParse(fileUrl, useInternal = TRUE) rootNode <- xmlRoot(doc) xmlName(rootNode) names(rootNode) rootNode[[1]] # access 1st element rootNode[[1][[1]]] # access first subcomponent of first subcomponent xmlSApply(rootNode, xmlValue) # apply xmlValue function to all nodes in rootNode xpathSApply(rootNode, '//name', xmlValue) ## Reading JSON library(jsonlite) jsonData <- fromJSON('https://example.com/path/to/json') names(json) names(jsonData$owner) myjson <- toJSON(data, pretty = TRUE) cat(myjson) head(jsonData) ## Reading data from the web con = url('http://website.com/article') htmlCode = readLines(con) close(con) htmlCode library(httr); html2 = GET(url) content2 = content(html2, as='text') parsedHtml = htmlParse(content2, asText=TRUE) xpathSApply(parsedHtml, '//title', xmlValue) pg2 = GET('http://website.com/login', authenticate('user', 'passwd')) google = handle('http://google.com') pg3 = GET(handle=google, path='/') ## Reading data from APIs myapp = oauth_app('twitter', key='consumerKey', secret='consumerSecret') sig = sign_oauth1.0(myapp, token='token', token_secret='token_secret') homeTL = GET('https://api.twitter.com/1.1/statuses/home_timeline.json', sig) ### Working with data ## Summirizing data # Look at a bit of data head(resData, n = 3) tail(restData, n = 3) summary(resData) str(resData) # Quantiles of quantitative variables quantile(resData$councilDistrict, na.rm = TRUE) # Make table table(resData$zipCode, useNA="ifany") table(restData$councilDistrict, resData$zipCode) # Check for missing values sum(is.na(resData$councilDistrict)) any(is.na(resData$councilDistrict)) all(resData$zipCode > 0) # Rows and colums sums colSum(is.na(resData)) all(colSum(is.na(resData))==0) # Values with specific characteristics table(resData$zipCode %in% c("12345", "12543")) resData[resData$zipCode %in% c("12345")] # Cross tabs data(UCBAdmissions) df = as.data.frame(USBAdmissions) summary(df) xt <- xtabs(Freq ~ Gender + Admit, data = df) # Flat tables warpbreaks$replicate <- rep(1:9, len=54) xt = xtabs(breaks ~., data=warpbreaks) ftable(xt) # Size of dataset fakeData = rnorm(1e5) object.size(fakeData) print(object.size(fakeData), units="Mb") ## Creating new variables # Creating sequences s1 <- seq(1,10,by=2) # 1 3 5 7 9 s2 <- seq(1,10,length=3) # 1.0 5.5 10.0 x <- c(1,3,8,25,100); seq(along = x) # 1 2 3 4 5 # Subsetting variables restData$nearMe = restData$neirghborthood %in% c("Roland Park", "Homeland") table(restData$nearMe) # Creating binary variables resData$zipWrong = ifelse(resData$zipCode < 0, TRUE, FALSE) table(resData$zipWrong, resData$zipCode < 0) # Creating categorical variables resData$zipGroups = cut(resData$zipCode, breaks=quantile(resData$zipCode)) table(resData$zipGroups) # Creating factor variables resData$zcf <- factor(resData$zipCode) # Levels of factor veriables yesno <- sample(c("yes", "no"), size = 10, replace=TRUE) yesnofac = fatcor(yesno, levels=c("yes", "no")) releal(yesnofac, ref="yes") # change factor to numeric as.numeric(yesnofac) # another way to change factor to numeric ## Reshaping data # Melting data frames library(reshape2) mtcars$carname <- rownames(mtcars) carMelt <- melt(mtcars, id=c("carname", "gear", "cyl"), measure.vars=c("mpg", "hp")) # Casting data frames cylData <- dcast(carMelt, cyl ~ variable) cylData <- dcast(carMelt, cyl ~ variable, mean) # Averaging values tallpy(InsectSpray$count, InsectSpray$spray, sum) # Another way spIns = split(InsectSpray$count, InspectSpray$spray) sprCount = lapply(spIns, sum) # Another way ddply(InspectSpray, .(spray), summarize, sum=sum(count)) # require dplyr ## Managing Data Frames with dplyr # select filter arrange rename mutate summirise # The first arg is a data frame # The subsequent arguments describe what to do with it. # The result is a new dataframe. ## Managing data with dplyr - Basic Tools chicago <- readRDS("chicago.rds") # Select function head(select(chicago, city:dptp)) head(seelct(chicage, -(city:dptp))) # Filter function chic.g <- filter(chicage, pm25tmean2 > 30) # Arrange function chicago <- arrange(chicago, date) chicago <- arrange(chicago, desc(date)) # descending order. # Rename function chicago <- rename(chicago, pm25 = pm25tmean2, dewpoint = dptp) # Mutate function chicago <- mutate(chicago, pm25detrend = pm25-mean(pm25, na.rm = TRUE) ) ## Mergin data mergedData = merge(reviews, solutions, by.x="solution_id", by.y="id", all=TRUE) ## Edititng text variables # Fixin character vectors tolower(names(cameralData)) splitNames <- strsplit(names(cameraData), '\\.') sub("_", "", names(reviews),) # replace first gsub("_","") # replace all # Finding values grep("Alameda", cameraData$intersection) table(grepl("Amaleda", cameraData$intersection)) # Usefule string functions library(stringr) nchar("Jeffrey") substr("<NAME>", 1, 7) paste("Hello", "world!") str_trim("OpenData ") ## Working with datas d1 = date() d2 = Sys.Date() format(d2, "%a %b %d") z = as.Date(x, "%d%b%Y") weekdays(d2) months(d2) julian(d2) library(lubridate) ymd("20140108")
41a9f0f2ddf6bb64d9b35a4ab9c21c042cc559b5
[ "Markdown", "Python", "R" ]
4
Markdown
angeldar/r-notes
86554601f9348c075944e0b5deb34aaed356ae6b
75167c47736f66c1eb7c09843c03bb2b286fe0aa
refs/heads/master
<repo_name>lzc2719/manager<file_sep>/src/main/java/cn/lzc/bean/User.java package cn.lzc.bean; public class User { private int userId; private String userName; private String userAccount; private String userPassword; private String userIdentity; public User(){} public User(String userName, String userAccount, String userPassword, String userIdentity) { this.userName = userName; this.userAccount = userAccount; this.userPassword = <PASSWORD>; this.userIdentity = userIdentity; } public int getUserId() { return userId; } public void setUserId(int userId) { this.userId = userId; } public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public String getUserAccount() { return userAccount; } public void setUserAccount(String userAccount) { this.userAccount = userAccount; } public String getUserPassword() { return userPassword; } public void setUserPassword(String userPassword) { this.userPassword = <PASSWORD>; } public String getUserIdentity() { return userIdentity; } public void setUserIdentity(String userIdentity) { this.userIdentity = userIdentity; } } <file_sep>/src/main/java/cn/lzc/servlet/MovieScoreServlet.java package cn.lzc.servlet; import cn.lzc.dao.MovieDao; import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import java.io.IOException; import java.io.PrintWriter; @WebServlet(urlPatterns = "/MovieScoreServlet") public class MovieScoreServlet extends HttpServlet { protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request,response); } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("UTF-8"); response.setContentType("text/html;charset=UTF-8"); PrintWriter out=response.getWriter(); ServletContext servletContext = request.getServletContext(); HttpSession session = request.getSession(); //获取请求参数 String movieName=(String)request.getParameter("movieName"); String movieScore=(String)request.getParameter("movieScore"); MovieDao movieDao=new MovieDao(); try { movieDao.updateMovieScoreByMovieName(movieName,movieScore); } catch (Exception e) { e.printStackTrace(); } /*response.sendRedirect("OnloadMovieServlet");*/ out.print("打分成功!"); } } <file_sep>/src/main/java/cn/lzc/listener/UserLogoutListener.java package cn.lzc.listener; import cn.lzc.bean.User; import cn.lzc.dao.AccountDao; import javax.servlet.ServletContext; import javax.servlet.ServletContextEvent; import javax.servlet.ServletContextListener; import javax.servlet.annotation.WebListener; import javax.servlet.http.*; import java.text.SimpleDateFormat; import java.util.Date; @WebListener public class UserLogoutListener implements HttpSessionAttributeListener { // Public constructor is required by servlet spec public UserLogoutListener() { } @Override public void attributeRemoved(HttpSessionBindingEvent se) { HttpSession session = se.getSession(); ServletContext servletContext = session.getServletContext(); if(se.getName().equals("user")){ User user=(User)se.getValue(); Date date = new Date(); SimpleDateFormat sdf= new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); String ioTime = sdf.format(date); String ioUsername=user.getUserName(); String ioUserIdentity=user.getUserIdentity().equals("0")?"普通用户":"管理员"; String ioType="退出"; AccountDao accountDao=new AccountDao(); try { accountDao.recordUserLogoutMessage(ioUsername,ioTime,ioUserIdentity,ioType); } catch (Exception e) { e.printStackTrace(); } } } } <file_sep>/src/main/java/cn/lzc/utils/DBUtils.java package cn.lzc.utils; import com.alibaba.druid.pool.DruidDataSourceFactory; import javax.sql.DataSource; import java.io.InputStream; import java.sql.Connection; import java.sql.SQLException; import java.util.Properties; public class DBUtils { public static Connection getConnection() throws Exception { InputStream in=Thread.currentThread().getContextClassLoader().getResourceAsStream("db.properties"); Properties properties=new Properties(); properties.load(in); DataSource dataSource= DruidDataSourceFactory.createDataSource(properties); return dataSource.getConnection(); } public static void closeJDBC(Connection conn){ try { conn.close(); }catch (SQLException e){ e.printStackTrace(); } } } <file_sep>/src/main/java/cn/lzc/servlet/AddMovieServlet.java package cn.lzc.servlet; import cn.lzc.bean.Movie; import cn.lzc.dao.MovieDao; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.io.PrintWriter; @WebServlet(urlPatterns = "/AddMovieServlet") public class AddMovieServlet extends HttpServlet { protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("UTF-8"); response.setContentType("text/html;charset=UTF-8"); PrintWriter out=response.getWriter(); //获取请求参数 String movieName=(String)request.getParameter("movieName"); String movieYear=(String)request.getParameter("movieYear"); String movieNation=(String)request.getParameter("movieNation"); String movieDirector=(String)request.getParameter("movieDirector"); String movieActor=(String)request.getParameter("movieActor"); String movieType=(String)request.getParameter("movieType"); String movieBrief=(String)request.getParameter("movieBrief"); String movieLink=(String)request.getParameter("movieLink"); String movieTime=(String)request.getParameter("movieTime"); Movie movie=new Movie(movieName,movieYear,movieNation,movieDirector,movieActor,movieType,movieBrief,movieLink,movieTime); String[] movieTypeList=movieType.split("、"); MovieDao movieDao=new MovieDao(); try { movieDao.addMovie(movie); movieDao.increaseMovieTypeList(movieName,movieTypeList); } catch (Exception e) { e.printStackTrace(); } response.sendRedirect("pages/movieMessageManage.jsp"); } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { } } <file_sep>/src/main/java/cn/lzc/servlet/RegisterServlet.java package cn.lzc.servlet; import cn.lzc.dao.AccountDao; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.io.PrintWriter; @WebServlet(urlPatterns = "/RegisterServlet") public class RegisterServlet extends HttpServlet { protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("UTF-8"); response.setContentType("text/html;charset=UTF-8"); PrintWriter out=response.getWriter(); //获取请求参数 String account=(String)request.getParameter("account"); String password=(String)request.getParameter("password"); String userName=(String)request.getParameter("userName"); String userIdentity=(String)request.getParameter("userIdentity"); AccountDao accountDao=new AccountDao(); boolean flag=false; try { flag=accountDao.isExistAccount(account); } catch (Exception e) { e.printStackTrace(); } if(flag){//新注册的账号已经存在 out.print("<script type='text/javascript'>"); out.print("alert('注册失败!该账号已经存在');"); out.print("window.location='register.jsp';"); out.print("</script>"); }else{//新注册的账号没重复,可以继续注册 try { //保存新注册的用户信息 accountDao.saveUser(account,password,userName,userIdentity); } catch (Exception e) { e.printStackTrace(); } response.sendRedirect("login.jsp");//重定向至登录界面 } } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { } } <file_sep>/src/main/java/cn/lzc/bean/Movie.java package cn.lzc.bean; //电影JavaBean类 public class Movie { private int movieId;//电影id private String movieName;//电影名 private String movieYear;//上映时间 private String movieNation;//产自国 private String movieDirector;//导演 private String movieActor;//演员 private String movieType;//电影类型 private String movieBrief;//电影简介 private String movieScore;//电影评分 private String moviePicture;//电影图片 private String movieLink;//电影链接 private String movieTime;//电影时长 public Movie(){} public Movie(String movieName, String movieYear, String movieNation, String movieDirector, String movieActor, String movieType, String movieBrief, String movieLink, String movieTime) { this.movieName = movieName; this.movieYear = movieYear; this.movieNation = movieNation; this.movieDirector = movieDirector; this.movieActor = movieActor; this.movieType = movieType; this.movieBrief = movieBrief; this.movieLink = movieLink; this.movieTime = movieTime; } public Movie(int movieId, String movieName, String movieYear, String movieNation, String movieDirector, String movieActor, String movieType, String movieBrief, String movieScore, String moviePicture, String movieLink, String movieTime) { this.movieId = movieId; this.movieName = movieName; this.movieYear = movieYear; this.movieNation = movieNation; this.movieDirector = movieDirector; this.movieActor = movieActor; this.movieType = movieType; this.movieBrief = movieBrief; this.movieScore = movieScore; this.moviePicture = moviePicture; this.movieLink = movieLink; this.movieTime = movieTime; } public int getMovieId() { return movieId; } public void setMovieId(int movieId) { this.movieId = movieId; } public String getMovieName() { return movieName; } public void setMovieName(String movieName) { this.movieName = movieName; } public String getMovieYear() { return movieYear; } public void setMovieYear(String movieYear) { this.movieYear = movieYear; } public String getMovieNation() { return movieNation; } public void setMovieNation(String movieNation) { this.movieNation = movieNation; } public String getMovieDirector() { return movieDirector; } public void setMovieDirector(String movieDirector) { this.movieDirector = movieDirector; } public String getMovieActor() { return movieActor; } public void setMovieActor(String movieActor) { this.movieActor = movieActor; } public String getMovieType() { return movieType; } public void setMovieType(String movieType) { this.movieType = movieType; } public String getMovieBrief() { return movieBrief; } public void setMovieBrief(String movieBrief) { this.movieBrief = movieBrief; } public String getMovieScore() { return movieScore; } public void setMovieScore(String movieScore) { this.movieScore = movieScore; } public String getMoviePicture() { return moviePicture; } public void setMoviePicture(String moviePicture) { this.moviePicture = moviePicture; } public String getMovieLink() { return movieLink; } public void setMovieLink(String movieLink) { this.movieLink = movieLink; } public String getMovieTime() { return movieTime; } public void setMovieTime(String movieTime) { this.movieTime = movieTime; } } <file_sep>/src/main/java/cn/lzc/servlet/AddMovieTypeServlet.java package cn.lzc.servlet; import cn.lzc.bean.Movie; import cn.lzc.dao.MovieDao; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.io.PrintWriter; @WebServlet(urlPatterns = "/AddMovieTypeServlet") public class AddMovieTypeServlet extends HttpServlet { protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("UTF-8"); response.setContentType("text/html;charset=UTF-8"); PrintWriter out=response.getWriter(); //获取请求参数 String movieTypeName=(String)request.getParameter("movieTypeName"); MovieDao movieDao=new MovieDao(); try { movieDao.addMovieType(movieTypeName); } catch (Exception e) { e.printStackTrace(); } response.sendRedirect("pages/movieTypeManage.jsp"); } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request,response); } } <file_sep>/src/main/java/cn/lzc/dao/MovieDao.java package cn.lzc.dao; import cn.lzc.bean.Movie; import cn.lzc.bean.MovieType; import cn.lzc.utils.DBUtils; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.util.ArrayList; import java.util.List; public class MovieDao { //增加电影评论操作 public void increaseMovieComment(String movieId,String commentUser,String commentTime,String commentText) throws Exception { Connection conn = DBUtils.getConnection(); PreparedStatement pstmt = null; try { String sql = "insert into comment(movie_id,comment_user,comment_time,comment_content) value(?,?,?,?)"; pstmt=conn.prepareStatement(sql); pstmt.setString(1,movieId); pstmt.setString(2,commentUser); pstmt.setString(3,commentTime); pstmt.setString(4,commentText); pstmt.executeUpdate(); } catch (Exception e) { e.printStackTrace(); } finally { DBUtils.closeJDBC(conn); } } //更新movieName电影的评分 public void updateMovieScoreByMovieName(String movieName,String movieScore) throws Exception { Connection conn = DBUtils.getConnection(); PreparedStatement pstmt = null; try { String sql = "update movie set movie_score=? where movie_name=?"; pstmt=conn.prepareStatement(sql); pstmt.setString(1,movieScore); pstmt.setString(2,movieName); pstmt.executeUpdate(); } catch (Exception e) { e.printStackTrace(); } finally { DBUtils.closeJDBC(conn); } } //获得搜索的内容 public List<Movie> getMovieListBySearchContent(String searchContent) throws Exception { Connection conn = DBUtils.getConnection(); PreparedStatement pstmt = null; List<Movie> movieList=new ArrayList<Movie>(); try { String sql = "select * from movie"; pstmt=conn.prepareStatement(sql); ResultSet rs=pstmt.executeQuery(); while (rs.next()){ if(rs.getString("movie_name").contains(searchContent) ||rs.getString("movie_name").equals(searchContent)){ Movie movie=new Movie(); movie.setMovieId(rs.getInt(1)); movie.setMovieName(rs.getString(2)); String s1=rs.getString("movie_name"); movie.setMovieYear(rs.getString(3)); movie.setMovieNation(rs.getString(4)); movie.setMovieDirector(rs.getString(5)); movie.setMovieActor(rs.getString(6)); movie.setMovieType(rs.getString(7)); movie.setMovieBrief(rs.getString(8)); movie.setMovieScore(rs.getString(9)); movie.setMoviePicture(rs.getString(10)); movie.setMovieLink(rs.getString(11)); movie.setMovieTime(rs.getString(12)); movieList.add(movie); } } } catch (Exception e) { e.printStackTrace(); } finally { DBUtils.closeJDBC(conn); } return movieList; } //通过电影类型名字查找对应电影类型清单,并返回 public String getMovieTypeListByMovieTypeName(String movieTypeName) throws Exception { Connection conn = DBUtils.getConnection(); PreparedStatement pstmt = null; String movieTypeList=null; try { String sql = "select movie_type_list from movie_type where movie_type_name=?"; pstmt=conn.prepareStatement(sql); pstmt.setString(1,movieTypeName); ResultSet rs=pstmt.executeQuery(); while (rs.next()){ movieTypeList=rs.getString("movie_type_list"); } } catch (Exception e) { e.printStackTrace(); } finally { DBUtils.closeJDBC(conn); } String s1=movieTypeList; return movieTypeList; } //通过电影类型列表的电影字符串,获得对应的电影集合 public List<Movie> getMoviesByMovieTypeList(String[] movieTypeList) throws Exception { Connection conn = DBUtils.getConnection(); PreparedStatement pstmt = null; ResultSet rs=null; List<Movie> movieList=new ArrayList<Movie>(); try { int num=movieTypeList.length; for(int i=0;i<movieTypeList.length;i++){ String sql = "select movie_id,movie_name,movie_year,movie_nation,movie_director,\n" + "movie_actor,movie_type,movie_brief,movie_score,movie_picture,\n" + "movie_link,movie_time from movie where movie_name=?"; pstmt=conn.prepareStatement(sql); pstmt.setString(1,movieTypeList[i]); rs=pstmt.executeQuery(); while (rs.next()){ Movie movie=new Movie(); movie.setMovieId(rs.getInt(1)); movie.setMovieName(rs.getString(2)); movie.setMovieYear(rs.getString(3)); movie.setMovieNation(rs.getString(4)); movie.setMovieDirector(rs.getString(5)); movie.setMovieActor(rs.getString(6)); movie.setMovieType(rs.getString(7)); movie.setMovieBrief(rs.getString(8)); movie.setMovieScore(rs.getString(9)); movie.setMoviePicture(rs.getString(10)); movie.setMovieLink(rs.getString(11)); movie.setMovieTime(rs.getString(12)); movieList.add(movie); } } } catch (Exception e) { e.printStackTrace(); } finally { DBUtils.closeJDBC(conn); } for(Movie movie:movieList){ String s1=movie.getMovieName(); String s2=movie.getMovieActor(); String s3=movie.getMovieDirector(); } return movieList; } //根据电影名,存放它对应的电影图片名 public void addMoviePicture(String movieName,String pictureFileName) throws Exception { Connection conn = DBUtils.getConnection(); PreparedStatement pstmt = null; try { String sql = "update movie set movie_picture=? where movie_name=?"; pstmt=conn.prepareStatement(sql); pstmt.setString(1,pictureFileName); pstmt.setString(2,movieName); pstmt.executeUpdate(); } catch (Exception e) { e.printStackTrace(); } finally { DBUtils.closeJDBC(conn); } } //添加电影类型,movieTypeName:要添加的电影类型名 public void addMovieType(String movieTypeName) throws Exception { Connection conn = DBUtils.getConnection(); PreparedStatement pstmt = null; try { String sql = "insert into movie_type(movie_type_name) value(?)"; pstmt=conn.prepareStatement(sql); pstmt.setString(1,movieTypeName); pstmt.executeUpdate(); } catch (Exception e) { e.printStackTrace(); } finally { DBUtils.closeJDBC(conn); } } //获取数据库中所有的电影类型记录 public List<MovieType> getAllMovieType() throws Exception { List<MovieType> arrayList = new ArrayList<MovieType>(); Connection conn = DBUtils.getConnection(); PreparedStatement pstmt = null; ResultSet rs = null; try { String sql = "select movie_type_id,movie_type_name,movie_type_list from movie_type\n"; pstmt = conn.prepareStatement(sql); rs = pstmt.executeQuery(); while (rs.next()) { MovieType movieType = new MovieType(); movieType.setMovieTypeId(rs.getInt(1)); movieType.setMovieTypeName(rs.getString(2)); movieType.setMovieTypeList(rs.getString(3)); String str=rs.getString("movie_type_name"); arrayList.add(movieType); } } catch (Exception e) { e.printStackTrace(); } finally { DBUtils.closeJDBC(conn); } return arrayList; } //删除电影,movieName:要删除的电影名 public void deleteMovie(String movieName) throws Exception { Connection conn = DBUtils.getConnection(); PreparedStatement pstmt = null; try { String sql = "delete from movie where movie_name=?"; pstmt=conn.prepareStatement(sql); pstmt.setString(1,movieName); pstmt.executeUpdate(); } catch (Exception e) { e.printStackTrace(); } finally { DBUtils.closeJDBC(conn); } } //删除电影类型,movieTypeName:要删除的电影类型名 public void deleteMovieType(String movieTypeName) throws Exception { Connection conn = DBUtils.getConnection(); PreparedStatement pstmt = null; try { String sql = "delete from movie_type where movie_type_name=?"; pstmt=conn.prepareStatement(sql); pstmt.setString(1,movieTypeName); pstmt.executeUpdate(); } catch (Exception e) { e.printStackTrace(); } finally { DBUtils.closeJDBC(conn); } } //根据updateType,获取相应的sql语句 public String selectSql(String updateType){ String sql = null; if(updateType.equals("movie_year")){ sql = "update movie set movie_year=? where movie_name=?"; }else if(updateType.equals("movie_nation")){ sql = "update movie set movie_nation=? where movie_name=?"; }else if(updateType.equals("movie_director")){ sql = sql = "update movie set movie_director=? where movie_name=?"; }else if(updateType.equals("movie_actor")){ sql = "update movie set movie_actor=? where movie_name=?"; }else if(updateType.equals("movie_type")){ sql = "update movie set movie_type=? where movie_name=?"; }else if(updateType.equals("movie_brief")){ sql = "update movie set movie_brief=? where movie_name=?"; }else if(updateType.equals("movie_link")){ sql = "update movie set movie_link=? where movie_name=?"; }else if(updateType.equals("movie_time")){ sql = "update movie set movie_time=? where movie_name=?"; } return sql; } //更新电影信息,movieName:要修改的电影名,updateType:修改类型,updateContent:修改内容 public void updateMovie(String movieName,String updateType,String updateContent) throws Exception { Connection conn = DBUtils.getConnection(); PreparedStatement pstmt = null; try { String sql = selectSql(updateType); pstmt=conn.prepareStatement(sql); pstmt.setString(1,updateContent); pstmt.setString(2,movieName); pstmt.executeUpdate(); } catch (Exception e) { e.printStackTrace(); } finally { DBUtils.closeJDBC(conn); } } //保存电影,movie:电影对象 public void addMovie(Movie movie) throws Exception { Connection conn = DBUtils.getConnection(); PreparedStatement pstmt = null; ResultSet rs = null; try { String sql = "insert into movie(movie_name,movie_year,movie_nation,movie_director,movie_actor,movie_type,movie_brief,movie_link,movie_time) value(?,?,?,?,?,?,?,?,?)"; pstmt=conn.prepareStatement(sql); pstmt.setString(1,movie.getMovieName()); pstmt.setString(2,movie.getMovieYear()); pstmt.setString(3,movie.getMovieNation()); pstmt.setString(4,movie.getMovieDirector()); pstmt.setString(5,movie.getMovieActor()); pstmt.setString(6,movie.getMovieType()); pstmt.setString(7,movie.getMovieBrief()); pstmt.setString(8,movie.getMovieLink()); pstmt.setString(9,movie.getMovieTime()); pstmt.executeUpdate(); } catch (Exception e) { e.printStackTrace(); } finally { DBUtils.closeJDBC(conn); } } //获取数据库中所有的电影记录 public List<Movie> getAllMovies() throws Exception { List<Movie> arrayList = new ArrayList<Movie>(); Connection conn = DBUtils.getConnection(); PreparedStatement pstmt = null; ResultSet rs = null; try { String sql = "SELECT \n" + "movie_id,\n" + "movie_name,\n" + "movie_year,\n" + "movie_nation,\n" + "movie_director,\n" + "movie_actor,\n" + "movie_type,\n" + "movie_brief,\n" + "movie_score,\n" + "movie_picture,\n" + "movie_link,\n" + "movie_time \n" + "FROM \n" + "movie\n"; pstmt = conn.prepareStatement(sql); rs = pstmt.executeQuery(); while (rs.next()) { Movie movie = new Movie(); movie.setMovieId(rs.getInt(1)); movie.setMovieName(rs.getString(2)); movie.setMovieYear(rs.getString(3)); movie.setMovieNation(rs.getString(4)); movie.setMovieDirector(rs.getString(5)); movie.setMovieActor(rs.getString(6)); movie.setMovieType(rs.getString(7)); movie.setMovieBrief(rs.getString(8)); movie.setMovieScore(rs.getString(9)); movie.setMoviePicture(rs.getString(10)); movie.setMovieLink(rs.getString(11)); movie.setMovieTime(rs.getString(12)); arrayList.add(movie); } } catch (Exception e) { e.printStackTrace(); } finally { DBUtils.closeJDBC(conn); } return arrayList; } //将要添加的电影添加进对应的电影类型里面来 public void increaseMovieTypeList(String movieName,String[] movieTypeList) throws Exception { Connection conn = DBUtils.getConnection(); PreparedStatement pstmt = null; PreparedStatement pstmt2 = null; ResultSet rs = null; try { for(int i=0;i<movieTypeList.length;i++){ String sql = "select movie_type_list from movie_type where movie_type_name=?"; pstmt=conn.prepareStatement(sql); pstmt.setString(1,movieTypeList[i]); rs= pstmt.executeQuery(); String str = null; if(rs.next()){ str=(String)rs.getString("movie_type_list"); } if(str.lastIndexOf("、")==str.length()-1) str+=movieName; else str+="、"+movieName; String sql2="update movie_type set movie_type_list=? where movie_type_name=?"; pstmt2=conn.prepareStatement(sql2); pstmt2.setString(1,str); pstmt2.setString(2,movieTypeList[i]); pstmt2.executeUpdate(); } } catch (Exception e) { e.printStackTrace(); } finally { DBUtils.closeJDBC(conn); } } //将当前电影类型清单里面要删除的电影删除掉 public void reduceMovieTypeList(String movieName) throws Exception { Connection conn = DBUtils.getConnection(); String sql=null; PreparedStatement pstmt = null; PreparedStatement pstmt2 = null; PreparedStatement pstmt3 = null; ResultSet rs = null; ResultSet rs2 = null; ResultSet rs3 = null; try { //1.查找所有的电影类型,挑选出电影类型清单里面包含了要被删除的电影名的电影类型集合 int n=0; String[] str=new String[100]; sql="select * from movie_type"; pstmt = conn.prepareStatement(sql); rs = pstmt.executeQuery(); while (rs.next()) if(rs.getString(3).contains(movieName)) str[n++]=rs.getString(2); for(int i=0;i<n;i++){ //2.找出当前电影类型里面的电影类型清单 String sql2=null; sql2="select movie_type_list from movie_type where movie_type_name=?"; pstmt2=conn.prepareStatement(sql2); pstmt2.setString(1,str[i]); rs2=pstmt2.executeQuery(); //3.把当前挑选出来的电影类型清单字符串进行分离,剔除掉要被删除的电影名再重组成字符串 String[] str2=new String[100]; while(rs2.next()){ String movieTypeList=(String)rs2.getString("movie_type_list"); str2=movieTypeList.split("、"); } StringBuffer stringBuffer=new StringBuffer(); for(int j=0;j<str2.length;j++) if(!(movieName.equals(str2[j]))){ if(j==str2.length-1){ stringBuffer.append(str2[j]); break; } stringBuffer.append(str2[j]).append("、"); } //4.将剔除掉电影名的当前电影类型清单,重新插入到当前电影类型里去 String sql3=null; sql3="update movie_type set movie_type_list=? where movie_type_name=?"; pstmt3=conn.prepareStatement(sql3); pstmt3.setString(1,stringBuffer.toString()); pstmt3.setString(2,str[i]); pstmt3.executeUpdate(); } } catch (Exception e) { e.printStackTrace(); } finally { DBUtils.closeJDBC(conn); } } } <file_sep>/src/main/java/cn/lzc/bean/MovieType.java package cn.lzc.bean; public class MovieType { private int movieTypeId;//电影类型的id private String movieTypeName;//电影类型的名字 private String movieTypeList;//这种类型的电影清单 public MovieType(){} public int getMovieTypeId() { return movieTypeId; } public MovieType(String movieTypeName, String movieTypeList) { this.movieTypeName = movieTypeName; this.movieTypeList = movieTypeList; } public void setMovieTypeId(int movieTypeId) { this.movieTypeId = movieTypeId; } public String getMovieTypeName() { return movieTypeName; } public void setMovieTypeName(String movieTypeName) { this.movieTypeName = movieTypeName; } public String getMovieTypeList() { return movieTypeList; } public void setMovieTypeList(String movieTypeList) { this.movieTypeList = movieTypeList; } } <file_sep>/src/main/java/cn/lzc/servlet/MovieCommentServlet.java package cn.lzc.servlet; import cn.lzc.dao.MovieDao; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.io.PrintWriter; @WebServlet(urlPatterns = "/MovieCommentServlet") public class MovieCommentServlet extends HttpServlet { /*protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { PrintWriter out=response.getWriter(); //获取请求参数 String commentText=(String)request.getParameter("commentText"); String movieId=(String)request.getParameter("movieId"); String commentUser=(String)request.getParameter("commentUser"); String commentTime=(String)request.getParameter("commentTime"); MovieDao movieDao=new MovieDao(); try { movieDao.increaseMovieComment(movieId,commentUser,commentTime,commentText); } catch (Exception e) { e.printStackTrace(); } }*/ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("UTF-8"); response.setContentType("text/html;charset=UTF-8"); PrintWriter out=response.getWriter(); //获取请求参数 String movieId=(String)request.getParameter("movieId"); String commentUser=(String)request.getParameter("commentUser"); String commentDate=(String)request.getParameter("commentDate"); String commentText=(String)request.getParameter("commentText"); MovieDao movieDao=new MovieDao(); try { movieDao.increaseMovieComment(movieId,commentUser,commentDate,commentText); } catch (Exception e) { e.printStackTrace(); } out.print("评论成功!"); } } <file_sep>/src/main/java/cn/lzc/dao/AccountDao.java package cn.lzc.dao; import cn.lzc.bean.User; import cn.lzc.utils.DBUtils; import java.sql.*; import java.util.Date; public class AccountDao { //记录用户退出时的记录 public void recordUserLogoutMessage(String ioUsername,String ioTime,String ioUserIdentity,String ioType) throws Exception { Connection conn=DBUtils.getConnection(); PreparedStatement pstmt=null; String sql="insert into user_io_record(io_username,io_identity,io_time,io_type) value(?,?,?,?)"; try { pstmt=conn.prepareStatement(sql); pstmt.setString(1,ioUsername); pstmt.setString(2,ioUserIdentity); pstmt.setString(3,ioTime); pstmt.setString(4,ioType); pstmt.executeUpdate(); }catch (SQLException e){ e.printStackTrace(); }finally { DBUtils.closeJDBC(conn); } } //记录用户登录时的记录 public void recordUserLoginMessage(String ioUsername,String ioTime,String ioUserIdentity,String ioType) throws Exception { Connection conn=DBUtils.getConnection(); PreparedStatement pstmt=null; String sql="insert into user_io_record(io_username,io_identity,io_time,io_type) value(?,?,?,?)"; try { pstmt=conn.prepareStatement(sql); pstmt.setString(1,ioUsername); pstmt.setString(2,ioUserIdentity); pstmt.setString(3,ioTime); pstmt.setString(4,ioType); pstmt.executeUpdate(); }catch (SQLException e){ e.printStackTrace(); }finally { DBUtils.closeJDBC(conn); } } //用户登录判断 public int login(String account,String password) throws Exception { int user_id=0; Connection conn=DBUtils.getConnection(); PreparedStatement pstmt=null; ResultSet rs=null; String sql="select user_id from user where user_account=? and user_password=?"; try { pstmt=conn.prepareStatement(sql); pstmt.setString(1,account); pstmt.setString(2,password); rs=pstmt.executeQuery(); if(rs.next()) { user_id=(int)rs.getInt("user_id"); } }catch (SQLException e){ e.printStackTrace(); }finally { DBUtils.closeJDBC(conn); } return user_id; } //获得用户的id public User getUserById(int user_id) throws Exception { User user=new User(); Connection conn=DBUtils.getConnection(); PreparedStatement pstmt=null; ResultSet rs=null; String sql="select user_name,user_account,user_password,user_identity from user where user_id=?"; try { pstmt=conn.prepareStatement(sql); pstmt.setInt(1,user_id); rs=pstmt.executeQuery(); if(rs.next()) { user.setUserName(rs.getString("user_name")); user.setUserAccount(rs.getString("user_account")); user.setUserPassword(<PASSWORD>("<PASSWORD>")); user.setUserIdentity(rs.getString("user_identity")); } }catch (SQLException e){ e.printStackTrace(); }finally { DBUtils.closeJDBC(conn); } return user; } //判断新注册的账号是否已经存在,存在则返回true public boolean isExistAccount(String account) throws Exception { Connection conn = DBUtils.getConnection(); PreparedStatement pstmt = null; ResultSet rs = null; String sql="SELECT * FROM user WHERE user_account=?"; try { pstmt=conn.prepareStatement(sql); pstmt.setString(1,account); rs=pstmt.executeQuery(); if(rs.next()){ return true; } }catch(SQLException e){ e.printStackTrace(); }finally{ DBUtils.closeJDBC(conn); } return false; } //存储用户信息 public void saveUser(String account,String password,String userName,String userIdentity) throws Exception { Connection conn=DBUtils.getConnection(); PreparedStatement pstmt=null; String sql="insert into user(user_name,user_account,user_password,user_identity) value(?,?,?,?)"; try { pstmt=conn.prepareStatement(sql); pstmt.setString(1,account); pstmt.setString(2,password); pstmt.setString(3,userName); pstmt.setString(4,userIdentity); pstmt.executeUpdate(); }catch (SQLException e){ e.printStackTrace(); }finally { DBUtils.closeJDBC(conn); } } //获得所有的账户信息 public String getAllAccount() throws Exception { String str=null; Connection conn = DBUtils.getConnection(); PreparedStatement pstmt = null; ResultSet rs = null; String sql="SELECT * FROM user"; try { pstmt=conn.prepareStatement(sql); rs=pstmt.executeQuery(); if(rs.next()){ str=(String)rs.getString("user_name"); } }catch(SQLException e){ e.printStackTrace(); }finally{ DBUtils.closeJDBC(conn); } return str; } } <file_sep>/web/js/isUserExistAjax.js // 定义一个全局的XMLHttpRequest对象 var xhr = false; // 创建XMLHttpRequest对象 function createXHR() { try { // 适用于IE7+, Firefox, Chrome, Opera, Safari xhr = new XMLHttpRequest(); } catch (e) { try { // 适用于IE6, IE5 xhr = new ActiveXObject("Microsoft.XMLHTTP"); } catch (e1) { xhr = false; } } if (!xhr) alert("初始化XMLHttpRequest对象失败!"); } // 进行Ajax请求和响应结果处理 function ajaxProcess3() { // 创建XMLHttpRequest对象 createXHR(); // 获取请求数据 var account=$("#account-text").val(); var password=$("#password-text").val(); // 设定请求地址 var url = "http://localhost:8080/myproject/LoginServlet?account=" + account+"&password="+password; // 建立对服务器的调用 xhr.open("get", url, true); // 向服务器发出请求 xhr.send(null); // 指定响应事件处理函数 xhr.onreadystatechange = function() { // 当 readyState 等于 4 且状态为 200 时,表示响应已就绪 if (xhr.readyState == 4 && xhr.status == 200) { // 将响应数据更新到页面控件中显示 var responseData=xhr.responseText; if(responseData=='登录失败,账号或密码错误!'){ alert(responseData); window.location.href="login.jsp"; }else{ alert(responseData); window.location.href="homePage.jsp"; } } }; } <file_sep>/src/main/java/cn/lzc/servlet/UploadMoviePictureServlet.java package cn.lzc.servlet; import cn.lzc.dao.MovieDao; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.Part; import javax.servlet.annotation.MultipartConfig; import java.io.File; import java.io.IOException; @WebServlet(urlPatterns = "/UploadMoviePictureServlet") @MultipartConfig public class UploadMoviePictureServlet extends HttpServlet { protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("UTF-8"); response.setContentType("text/html;charset=UTF-8"); // 获取上传文件域 Part part = request.getPart("moviePicture"); String movieName=request.getParameter("movieName"); // 获取上传文件名称 String pictureFileName = part.getSubmittedFileName(); // 将上传的文件保存在服务器项目发布路径的applicant/images目录下 String filepath = getServletContext().getRealPath("/imgs"); System.out.println("头像保存路径为:" + filepath); File f = new File(filepath); if (!f.exists()) f.mkdirs(); //将上传的照片保存指定路径的文件夹下 part.write(filepath + "/" + pictureFileName); // MovieDao movieDao = new MovieDao(); try { movieDao.addMoviePicture(movieName,pictureFileName); } catch (Exception e) { e.printStackTrace(); } response.sendRedirect("pages/movieMessageManage.jsp"); } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request,response); } }
6592219d08f182487dcebbf33a1ad5df9774c2f2
[ "JavaScript", "Java" ]
14
Java
lzc2719/manager
6596e7b1d63b423c02f06fad91ec626e7c1020d2
a97861b863d0dd0daa1019676dd5e1edee1acccb
refs/heads/master
<repo_name>Yves-T/examplecode<file_sep>/src/main/java/spring/WeatherDataGenerator.java package spring; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.ObjectWriter; import org.apache.log4j.LogManager; import org.apache.log4j.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.ApplicationListener; import org.springframework.messaging.core.MessageSendingOperations; import org.springframework.messaging.simp.broker.BrokerAvailabilityEvent; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Component; import pojo.SocketMessage; import pojo.weather.Channel; import pojo.weather.Condition; import pojo.weather.Item; import pojo.weather.Query; import pojo.weather.Result; import pojo.weather.Results; import java.io.IOException; import java.net.URL; @Component public class WeatherDataGenerator implements ApplicationListener<BrokerAvailabilityEvent> { private static final Logger log = LogManager.getLogger(WeatherDataGenerator.class); private final MessageSendingOperations<String> messagingTemplate; private final ObjectMapper objectMapper; @SuppressWarnings("SpringJavaAutowiringInspection") @Autowired public WeatherDataGenerator( final MessageSendingOperations<String> messagingTemplate) { this.messagingTemplate = messagingTemplate; this.objectMapper = new ObjectMapper(); } @Override public void onApplicationEvent(final BrokerAvailabilityEvent event) { } // fetch pojo.weather json ( delay is in milliseconds ) @Scheduled(fixedDelay = 10000) public void sendDataUpdates() throws JsonProcessingException { WeatherResults weatherResults = new WeatherResults(objectMapper); Result result = weatherResults.getWeatherResults(); SocketMessage socketMessage = createSocketMessage(result); this.messagingTemplate.convertAndSend( "/topic/data", socketMessage); } private SocketMessage createSocketMessage(Result result) throws JsonProcessingException { Query query = result.getQuery(); Results results = query.getResults(); Channel channel = results.getChannel(); Item item = channel.getItem(); Condition condition = item.getCondition(); String temperature = condition.getTemp(); SocketMessage socketMessage = new SocketMessage(); socketMessage.setTemperature(temperature); return socketMessage; } static private class WeatherResults { public static final String WEATHER_URL = "http://query.yahooapis.com/v1/public/yql?q=select%20item%20from" + "%20weather.forecast%20where%20location%3D%22BEXX0003%22&format=json"; private ObjectMapper mapper; public WeatherResults(ObjectMapper mapper) { this.mapper = mapper; } public Result getWeatherResults() { Result query = null; try { URL url = new URL(WEATHER_URL); query = mapper.readValue(url, Result.class); } catch (IOException e) { log.error("Error when fetching pojo.weather"); } return query; } } }<file_sep>/src/main/java/spring/Application.java package spring; import org.apache.log4j.LogManager; import org.apache.log4j.Logger; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.scheduling.TaskScheduler; import org.springframework.scheduling.annotation.AsyncConfigurer; import org.springframework.scheduling.annotation.EnableAsync; import org.springframework.scheduling.annotation.EnableScheduling; import org.springframework.scheduling.annotation.SchedulingConfigurer; import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler; import org.springframework.scheduling.config.ScheduledTaskRegistrar; import org.springframework.util.ErrorHandler; import java.util.concurrent.Executor; import java.util.concurrent.RejectedExecutionHandler; import java.util.concurrent.ThreadPoolExecutor; @Configuration @EnableAsync(proxyTargetClass = true) @EnableScheduling @ComponentScan @EnableAutoConfiguration public class Application implements AsyncConfigurer, SchedulingConfigurer { private static final Logger log = LogManager.getLogger(Application.class); private static final Logger schedulingLogger = LogManager.getLogger(log.getName() + ".[scheduling]"); public static void main(String[] args) { SpringApplication.run(Application.class, args); } @Bean public ThreadPoolTaskScheduler taskScheduler() { log.info("Setting up thread pool task scheduler with 20 threads."); ThreadPoolTaskScheduler scheduler = new ThreadPoolTaskScheduler(); scheduler.setPoolSize(20); scheduler.setThreadNamePrefix("task-"); scheduler.setAwaitTerminationSeconds(60); scheduler.setWaitForTasksToCompleteOnShutdown(true); scheduler.setErrorHandler(new MyErrorHandler()); scheduler.setRejectedExecutionHandler(new MyRejectedExecutionHandler()); return scheduler; } @Override public Executor getAsyncExecutor() { return this.taskScheduler(); } @Override public void configureTasks(ScheduledTaskRegistrar registrar) { TaskScheduler scheduler = this.taskScheduler(); registrar.setTaskScheduler(scheduler); } private static class MyErrorHandler implements ErrorHandler { @Override public void handleError(Throwable throwable) { schedulingLogger.error("Unknown error occurred while executing task.", throwable); } } private static class MyRejectedExecutionHandler implements RejectedExecutionHandler { @Override public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) { schedulingLogger.error("Execution of task {} was rejected for unknown reasons."); } } } <file_sep>/src/main/resources/static/js/app/controllers.js angular.module("myApp.controllers", []).controller("weatherController", function ($scope) { $scope.initiator = false; $scope.temperature = 0; $scope.socket = { client: null, stomp: null }; $scope.notify = function (/** Message */ message) { var jsonObject = JSON.parse(message.body); console.log(jsonObject); console.log(jsonObject.temperature); $scope.temperature = jsonObject.temperature; $scope.$apply() }; $scope.reconnect = function () { setTimeout($scope.initSockets, 10000); }; $scope.initSockets = function () { $scope.socket.client = new SockJS('/hello'); $scope.socket.stomp = Stomp.over($scope.socket.client); $scope.socket.stomp.connect({}, function () { $scope.socket.stomp.subscribe("/topic/notify", $scope.notify); $scope.socket.stomp.subscribe("/topic/data", $scope.notify); }); $scope.socket.client.onclose = $scope.reconnect; console.log("init sockets...."); }; $scope.initSockets(); });<file_sep>/src/main/java/pojo/SocketMessage.java package pojo; import java.text.DecimalFormat; public class SocketMessage { private String temperature; public String getTemperature() { return convertTemperatureFromFahrenheitToCelsius(); } public void setTemperature(String temperature) { this.temperature = temperature; } private String convertTemperatureFromFahrenheitToCelsius() { Float temperatureAsInteger = Float.parseFloat(temperature); Float temperatureCelsius = ((temperatureAsInteger - 32) * 5.0F / 9); DecimalFormat decimalFormat = new DecimalFormat("#.#"); return decimalFormat.format(temperatureCelsius); } } <file_sep>/src/main/java/spring/HelloWorld.java package spring; import org.springframework.messaging.handler.annotation.MessageMapping; import org.springframework.messaging.handler.annotation.SendTo; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import pojo.Greeting; import pojo.HelloMessage; @Controller public class HelloWorld { @MessageMapping("/hello") @SendTo("/topic/greetings") public Greeting hello(HelloMessage message) { System.out.println("called with message" + message); return new Greeting("Hello, " + message.getName()); } @RequestMapping("/") public String showSocketStartPage() { return "index"; } @RequestMapping("/test") public String test() { return "test"; } }
0e60fdd7a24b7d9c7161ecbcc1abb8b5dc2bea35
[ "JavaScript", "Java" ]
5
Java
Yves-T/examplecode
989a4426474600aa8187d5db7ba67440e634f14e
9a67fb7a42c2e408a97bb8e2cfcd541c56e17fd4
refs/heads/master
<repo_name>taylormck/ExampleRepository<file_sep>/readmes/TravisCI.md Travis CI ========= <!-- TODO --> Coming soon <file_sep>/readmes/GoogleTest.md Google Test =========== Google Test is a C++ testing suite. I find it very well designed and it is my preferred way to test C/C++ code. Take a look at the [project home page](https://code.google.com/p/googletest/). If you need help setting it up or creating test programs, take a look at the [Google Test Example repository](https://github.com/taylormck/GoogleTestExample). <file_sep>/test.cpp /** * Just a very simple test program. * Really just here to show off how Travis CI works. * * These tests are not indicitave of how real unit tests should be written * or how many should be written. It'd be better to have tests for every * known "corner" or "edge" case, then a bunch of tests for the general case. * * @author <NAME>, <EMAIL> */ #include <iostream> #include "gtest/gtest.h" #include "run.cpp" // --- plus --- TEST (Plus, PlusTest0) { ASSERT_EQ(0, example::plus(0, 0)); } TEST (Plus, PlusTest1) { ASSERT_EQ(1, example::plus(1, 0)); } TEST (Plus, PlusTest2) { ASSERT_EQ(10, example::plus(4, 6)); } // --- minus --- TEST (Minus, MinusTest0) { ASSERT_EQ(0, example::minus(0, 0)); } TEST(Minus, MinusTest1) { ASSERT_EQ(1, example::minus(1, 0)); } TEST(Minus, MinusTest2) { ASSERT_EQ(5, example::minus(10, 5)); } // --- multiply --- TEST (Multiply, MultiplyTest0) { ASSERT_EQ(0, example::multiply(0, 0)); } TEST (Multiply, MultiplyTest1) { ASSERT_EQ(0, example::multiply(1, 0)); } TEST (Multiply, MultiplyTest2) { ASSERT_EQ(20, example::multiply(4, 5)); } // --- divide --- TEST (Divide, DivideTest0) { ASSERT_EQ(0, example::divide(0, 1)); } TEST (Divide, DivideTest1) { ASSERT_EQ(1, example::divide(1, 1)); } TEST (Divide, DivideTest2) { ASSERT_EQ(5, example::divide(20, 4)); } // --- pow --- TEST(Pow, PowTest0) { ASSERT_EQ(0, example::pow(0, 1)); } TEST(Pow, PowTest1) { ASSERT_EQ(4, example::pow(4, 1)); } TEST(Pow, PowTest2) { ASSERT_EQ(32, example::pow(2, 5)); } <file_sep>/readmes/GitUsage.md Git/Github Usage ================ ######Forking a repository Unless you're the owner or a collaborator of a repository, you won't be able to modify it directly. In order to add your own changes, you'll need to make a *fork*. With your own fork, you'll be able to read, write, and push changes. To fork a repository on Github, go to any of the project's pages and click the Fork button on the top right. This will create your own copy of the repository. ![Fork Button](../img/forkButton.png) <sup>The Fork button</sup> Now you can clone your new fork and get to work. You can create branches, make changes, make commits, and push the changes back to Github. For now, your changes will only affect your repository, not the original. ######Getting the latest code from the original Once you've done some work with a fork, you may want to have the owner of the original repository take a look at it, maybe even integrate it. We do this using a Pull Request. First thing's first, you'll need to add the original repository as a remote. This can be done using the following command. `git remote add upstream [original repository's url]` From there, we need to pull down any work that's been done since you last synced with the original. This can be done with a simple fetch. `git fetch` Next, we need to merge in the changes. We'll do this using the rebase command instead of merge. This will often help us avoid merge conflicts and will keep our history cleaner. You can read more about rebase in [The Magical and Not Harmful Rebase](http://jeffkreeftmeijer.com/2010/the-magical-and-not-harmful-rebase/). You'll want to rebase from the latest stable code, which is usually the `develop` branch. If the original doesn't have a `develop` branch, you may have to use `master`. When in doubt, check the original repository's readme or ask the owners what branch to use. The command will look like this. `git rebase develop` <sup>Remember that you may need to rebase from a branch other than develop</sup> The rebase command will go one commit at a time. If there are any merge conflicts along the way, the rebase will stop until you've resolved them. Once resolved, you can continue the rebase using `git rebase --continue` ######Creating a Pull Request Now that you've got the latest code from the original, test to make sure that you're changes are still working correctly. Commit and push when you're ready, then go on back to your fork's page on Github. Select the branch whose changes you want to upload, then click the Compare and Review button. ![Compare and Review](../img/compareAndReviewButton.png) <sup>The Compare and Review button</sup> This will bring up a page where you can review your changes and create a pull request. You may view the diff of every file changed and a list of commits. Click the Create Pull Request area and you will given some text areas where you may fill in a title and summary of the pull request. Click the Send Pull Request button to the this pull request to the original repository. <!-- TODO add createPullRequest and sendPullRequest images --> ![Create Pull Request](../img/createPullRequest.png) <sup>The Create Pull Request button</sup> ![Send Pull Request](../img/sendPullRequest.png) <sup>The Send Pull Request button</sup> In the original repository, you will find that your pull request has been added as an issue. The owner of the original repository may now review your changes. The pull request also acts as a thread, and they may comment on it and discuss your changes with you. Once they are satisfied, they may merge your pull request into the original. Remember, whether they accept your code or not is up to them. ######Tagging Issues and Other Users On Github, in pretty much any text area you can type in, you can link to issues of the current directory. This makes histories easier to read, and can keep the status of issues up to date. You simply put a pound sign and the number of the issue. If the message includes one of the words fixes, fixed, close, closes, or closed, then the numbered issue will be closed automatically. If automatically closing more than one issue, you must say one of the magic words again before each issue number. The issue's thread will be updated to show that it was referenced. You can also tag other Github users by using the at sign followed by their name. This will send them a notificaton and a link to the thread. This can be done in an other issues, pull requests, and commit messages. Informally, the process may look something like this `git commit -am "Fixed #14"` <sup>This will automatically close issue 14 when pushed to Github</sup> ![Tagging Users](../img/userTag.png) <sup>Tagging a user will send them a notification in Github, which may email them</sup> <!-- TODO --> Here's an example of a commit referencing an issue in this very repository. ![Commit Issue Tag](../img/commitIssueTag.png) <sup>The commit message references an issue.</sup> ![Issue Referenced](../img/issueReferenced.png) <sup>The issue thread now contains a notification that is was referenced.</sup> Feel free to look at the actual [commit message](https://github.com/taylormck/ExampleRepository/commit/569929599ac821a90504e41c18c03d9fe17c4792) and [issue thread](https://github.com/taylormck/ExampleRepository/issues/16). <file_sep>/readmes/PivotalTracker.md Pivotal Tracker =============== The repository now has a [Pivotal Tracker project] (https://www.pivotaltracker.com/s/projects/894000). It is public and you may view it all you like. ######Setting Up Pivotal Tracker Create and verify an account on Pivotal Tracker. Go to your profile page and scroll to the bottom. Click the CREATE NEW TOKEN button. We will need this token later. ![API Token Area](../img/apiToken.png) <sup>Create a new token here</sup> Create a new project and add a new story. Use whatever settings you like. Once created, view the settings to find the id. ![Story Settings](../img/story.png) <sup>The id can be found here</sup> Go to your repositories page. In settings, look up service hooks. ![Navigation List](../img/navigationList.png) <sup>The Navigation List</sup> On the Service Hooks page, scroll down and click Pivotal Tracker. Paste the token you created earlier into the text field labeled token. If you like, give the hook a branch to track as well. Now, make some change to the code base and commit. Make sure the commit message contains the text `delivers #[story id]`. The story id can be found in the stories details on Pivotal Tracker. The story will update when the commit is pushed. It will contain the commit message and a link to the commit page on Github. <file_sep>/readmes/Trello.md Trello ====== This repository now has a Trello board. [Example Repository board on Trello](https://trello.com/b/m6rhwkg2/example-repository) All commits and pull requests will automatically create cards on the Trello board. This is particularly useful implementation of a Kanban board. All work done is added to the board for quick review. ######Setting up Trello First, you will need to create an account on Trello. Second, create the board you want to use. Third, create the lists you want to push cards on for commits and pull requests. Lastly, you will need to set up the service hook for your repository. Go to your repository's settings page. On the navigation list to the left, click Service Hooks. On the service hooks page, scroll down the list and click Trello. You will now see a few text fields, some check fields, and an install notes section. ![Navigation List](../img/navigationList.png) <sup>The navigation list</sup> ![Trello Install Notes](../img/trelloInstallNotes.png) <sup>Trello Install Notes</sup> Under install note 1, you will see a link that says "create a consumer token". Open this link in a new tab, accept, and copy the token it gives you. Under install note 2, you will see an incomplete url. You will need to copy and paste this url. You must replace TOKEN with the token we got from install note 1. Replace BOARDID with the board id from the board's url. Upon opening the new url, you will have a json file with all the board's lists and their id's. Copy the desired id's into the corresponding text fields. ![Board ID](../img/boardid.png) <sup>The Board ID in the URL</sup> Apply the settings, and you're done. Now all commits and pull requests will create cards on Trello. <file_sep>/run.cpp /** * This is a simple program that defines a few basic functions. * These functions aren't particularly exciting, they're just placeholders * to show of some of the technology in this repository. * * @author <NAME>, <EMAIL> */ namespace example { int plus (int i, int j) { return i + j; } int minus (int i, int j) { return i - j; } int multiply (int i, int j) { return i * j; } int divide (int i, int j) { return i / j; } int pow (int i, int j) { // Will be refactored later int v = 1; while (j-- != 0) v *= i; return v; } } <file_sep>/README.md <!-- Travis CI build and test status --> [![Build Status](https://travis-ci.org/taylormck/ExampleRepository.png)] (https://travis-ci.org/taylormck/ExampleRepository) Example Repository ================== This repository, as its name implies, is a simple repository created to show off a handful of Github's features and several of the tools that integrate with it. As a start, the features and tools presented in [Team Collaboration with Github](http://net.tutsplus.com/articles/general/team-collaboration-with-github/) will be put to use. I'll try to make sure that there are clear instructions explaining how to use all the tools associated with this repository. If you find anything to be unclear, open up an issue and I'll get around to it. If you know a cool new tool or feature that I'm not using, feel free to open an issue or make a pull request. Details ------- Explanations of tools and features used in this repository - [Git Usage](/readmes/GitUsage.md) - [Google Test](/readmes/GoogleTest.md) - [Trello](/readmes/Trello.md) - [Pivotal Tracker](/readmes/PivotalTracker.md) - [Hubot](/readmes/Hubot.md) - [Travis CI](/readmes/TravisCI.md) Reading/Links ------------- Some literature associated with git, Github, and some of the tools seen in this repository. - [Team Collaboration with Github](http://net.tutsplus.com/articles/general/team-collaboration-with-github/) - [The Magical and Not Harmful Rebase](http://jeffkreeftmeijer.com/2010/the-magical-and-not-harmful-rebase/) - [Git Flow (nvie)](http://nvie.com/posts/a-successful-git-branching-model/) - [Github Flow](http://scottchacon.com/2011/08/31/github-flow.html) <file_sep>/makefile # Simple makefile for this project # I have a tendency to use makefiles and make commands like scripts, # and this repo is no exception # # @author <NAME>, <EMAIL> Test: run.cpp test.cpp g++ -pedantic -Wall test.cpp -o Test -lgtest -lpthread -lgtest_main # The slash dot before the binary name is important # The Travis CI environment DOES NOT export the current working directory # to the PATH, so the directory must explicitly name the directory # where the binary is found test: Test ./Test clean: rm -f *.o rm -f *.zip rm -f Test
98c0c1d1421f84998b3fbed7bcdb3efe3b271d26
[ "Markdown", "Makefile", "C++" ]
9
Markdown
taylormck/ExampleRepository
4592027e30011efeabe2cf678fff7fe27b1d1409
5c0338700c8dd1ceff95a7f4f2f8af138ecacc4b
refs/heads/master
<file_sep>import numpy import scipy.special import re class predict: def __init__(self, inputNodes, hiddenNodes, outputNodes, learningRate, rnnSize): self.iNodes = inputNodes self.hNodes = hiddenNodes self.oNodes = outputNodes self.lr = learningRate self.rs = rnnSize self.w = [] for i in range(self.rs + 1): if i == 0: self.w.append(numpy.random.normal(0.0, pow(self.hNodes, -0.5), (self.hNodes, self.oNodes))) continue if i == self.rs: self.w.append(numpy.random.normal(0.0, pow(self.oNodes, -0.5), (self.oNodes, self.hNodes))) continue # 정규 분포의 (중심은 0.0, 표준 편차 연결 노드에 들어오는 개수 루트 역수, numpy 행렬) self.w.append(numpy.random.normal(0.0, pow(self.hNodes, -0.5), (self.hNodes, self.hNodes))) # 활성화 함수 self.af = lambda x: scipy.special.expit(x) def train(self, source, target): source = numpy.array(source, ndmin=2).T target = numpy.array(target, ndmin=2).T outputs = [] # 정방향 for i in range(self.rs +1): if i == 0: inputs = numpy.dot(self.w[i],source) outputs.append(self.af(inputs)) continue inputs = numpy.dot(self.w[i], outputs[i-1]) outputs.append(self.af(inputs)) # print(outputs) # print(target) # 역전파 오차 errors = [] for i in range(self.rs +1): errors.append('') for i in range(self.rs +1): i = self.rs - i if i == self.rs: errors[i] = target - outputs[i] continue errors[i] = numpy.dot(self.w[i+1].T, errors[i+1]) # print(errors) # 갱신 for i in range(self.rs +1): if i ==0: self.w[i] += self.lr * numpy.dot(errors[i] * outputs[i] * (1.0 - outputs[i]), numpy.transpose(source)) continue self.w[i] += self.lr * numpy.dot(errors[i] * outputs[i] * (1.0 - outputs[i]), numpy.transpose(outputs[i-1])) def test(self, inputs): inputs = numpy.array(inputs, ndmin=2).T output = [] for i in range(self.rs + 1): if i == 0: input = numpy.dot(self.w[i], inputs) output = self.af(input) continue input = numpy.dot(self.w[i], output) output = self.af(input) # print(output.flatten().argsort()) return output.flatten().argsort() if __name__ == "__main__": inputNodes = 45 hiddenNodes = 45 outputNodes = 45 learningRate = 0.3 rnnSize = 2 p = predict(inputNodes, hiddenNodes, outputNodes, learningRate, rnnSize) # 트레이닝 f = open('train_data.txt', 'r') lines = f.readlines() epochs = 100 for e in range(epochs): for line in lines: line= re.sub('\n','', line) line = line.split(',') inputs = numpy.zeros(inputNodes) + 0.01 outputs = numpy.zeros(outputNodes) + 0.01 for i in range(7,13): outputs[int(line[i])-1] = 0.99 for i in range(6): inputs[int(line[i])-1] = 0.99 p.train(inputs, outputs) # 예측률 f = open('test_data.txt', 'r') lines = f.readlines() lineLen = len(lines) prob = [] for i in range(7): prob.append(0) for line in lines: line = re.sub('\n', '', line) line = line.split(',') inputs = numpy.zeros(inputNodes) + 0.01 outputs = [] for i in range(7, 13): outputs.append(line[i]) for i in range(6): inputs[int(line[i]) - 1] = 0.99 result = p.test(inputs) score = 0 for i in range(1,7): if(str(int(result[-i]) + 1)) in outputs: score += 1 prob[score] += 1/lineLen for i in range(7): print(str(i) + '개 맞을 확률 : ' + str(prob[i])) # value = [4,7,13,29,31,39] value = [5,11,12,29,33,44] for i in range(6): inputs[value[i]] = 0.99 result = p.test(inputs) print(result) for i in range(45): result[i] +=1 print(result) # for i in range(1,7): # a = int(result[-i]) + 1 # print(a)
83d018f4cff446c5e25dc510da48e38e24aaee8a
[ "Python" ]
1
Python
wotres/RNN
96c642b08bed758efd3e96ab5958fc4fb3da1a8e
69f1ecc8bd9292dd0f0ab74c6653d3dce12c4817
refs/heads/master
<file_sep>package com.example.android.fragmentcalss; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.EditText; public class jingActivity extends AppCompatActivity { private EditText mEditText; private Button mButton; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_jing); mEditText= (EditText) findViewById(R.id.view_one); mButton= (Button) findViewById(R.id.butt); mButton.setOnClickListener(new ok()); } private class ok implements View.OnClickListener { @Override public void onClick(View v) { mEditText.setText("222222222222"); } } }
e801c70f1e59af7c569655cd9cba4bf899d995b2
[ "Java" ]
1
Java
IntelAndroid/FragmentCalss
32bbe4c20c675ca4723bb9856947edfa846c76e1
e4384106ad69c0124b52b0d15055837d7d2e418a
refs/heads/master
<repo_name>mfernandesp/TrabalhoKotlinRastreio<file_sep>/RastreioPacienteOficial/app/src/main/java/com/example/rastreiopacienteoficial/PacienteAdapter.kt package com.example.rastreiopacienteoficial import android.app.Activity import android.arch.persistence.room.Room import android.content.Context import android.view.View import android.view.ViewGroup import android.widget.BaseAdapter import android.widget.TextView import com.example.rastreiopaciente.Banco.Banco import com.example.rastreiopaciente.Banco.Paciente class PacienteAdapter(var context: Context, var act: Activity) : BaseAdapter() { var banco = Room.databaseBuilder(context, Banco::class.java, "RastreioPaciente").allowMainThreadQueries().build() var listaPaciente = banco.pacienteCrud().listarPacientes() override fun getView(position: Int, convertView: View?, parent: ViewGroup?): View { var view = act.getLayoutInflater().inflate(R.layout.lista_paciente_personalizada, parent, false) var paciente = listaPaciente.get(position) //pegando as referências das Views var nome = view.findViewById<TextView>(R.id.lista_nome_paciente) var nascimento = view.findViewById<TextView>(R.id.lista_nascimento) var id_paciente = view.findViewById<TextView>(R.id.lista_id_paciente) //populando as views nome.text = paciente.nome nascimento.text = paciente.dataNascimento id_paciente.text = paciente.id_paciente.toString() return view } override fun getItem(position: Int): Any { return listaPaciente.get(position) } override fun getItemId(position: Int): Long { // var paciente = listaPaciente.get(position) // return paciente.id_paciente?.toLong()!! return 0 } override fun getCount(): Int { return listaPaciente.size } }<file_sep>/RastreioPacienteOficial/app/src/main/java/com/example/rastreiopacienteoficial/Banco/Banco.kt package com.example.rastreiopaciente.Banco import android.arch.persistence.room.Database import android.arch.persistence.room.RoomDatabase @Database(entities = [Usuario::class, Paciente::class, Doenca::class, Atendimento::class, PacienteDoenca::class], version = 1, exportSchema = false) public abstract class Banco: RoomDatabase(){ abstract fun usuarioCrud(): UsuarioCRUD abstract fun pacienteCrud(): PacienteCRUD abstract fun doencaCrud():DoencaCRUD abstract fun pacienteDoencaCrud():PacienteDoencaCRUD abstract fun atendimentoCrud(): AtendimentoCRUD }<file_sep>/RastreioPacienteOficial/app/src/main/java/com/example/rastreiopacienteoficial/Cadastro_atendimento.kt package com.example.rastreiopacienteoficial import android.arch.persistence.room.Room import android.content.Context import android.content.SharedPreferences import android.support.v7.app.AppCompatActivity import android.os.Bundle import android.widget.Toast import com.example.rastreiopaciente.Banco.Atendimento import com.example.rastreiopaciente.Banco.Banco import com.example.rastreiopaciente.Banco.Paciente import kotlinx.android.synthetic.main.activity_cadastro_atendimento.* import java.lang.Exception class Cadastro_atendimento : AppCompatActivity() { lateinit var banco: Banco override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_cadastro_atendimento) banco = Room.databaseBuilder(applicationContext, Banco::class.java, "RastreioPaciente").allowMainThreadQueries().build() buttonCriarAtendimento.setOnClickListener { cadastrarAtendimento() } } fun cadastrarAtendimento(){ val sharedPreferences: SharedPreferences = getSharedPreferences("rastreiopacienteoficial", Context.MODE_PRIVATE) val atendimento = Atendimento() atendimento.id_atendimento = lastIdAtendimento() atendimento.id_paciente= sharedPreferences.getString("paciente_id", "").toInt() atendimento.data = dataChegadaAtendimento.text.toString() atendimento.doenca = doencaNomeAtendimento.text.toString() atendimento.medicacao = medicacaoAtendimento.text.toString() atendimento.custo = custoTextAtedimento1.text.toString().toFloat() atendimento.observacoes = obstextAtendimento.text.toString() try{ banco?.atendimentoCrud()?.inserirAtendimento(atendimento) Toast.makeText(this, "Atendimento registrado com sucesso!.", Toast.LENGTH_LONG).show() finish() }catch (e: Exception){ Toast.makeText(this, "Erro ao cadastrar.", Toast.LENGTH_LONG).show() } } fun lastIdAtendimento(): Int { var lastId: Int try { lastId = banco?.atendimentoCrud()?.lastId()?.get(0)?.id_atendimento.toString().toInt() + 1 }catch (e: Exception) { lastId = 1 } return lastId } } <file_sep>/RastreioPacienteOficial/app/src/main/java/com/example/rastreiopacienteoficial/Cadastro_paciente.kt package com.example.rastreiopacienteoficial import android.arch.persistence.room.Room import android.support.v7.app.AppCompatActivity import android.os.Bundle import android.widget.Toast import com.example.rastreiopaciente.Banco.Banco import com.example.rastreiopaciente.Banco.Paciente import com.example.rastreiopaciente.Banco.Usuario import kotlinx.android.synthetic.main.activity_cadastrar_usuario.* import kotlinx.android.synthetic.main.activity_cadastro_paciente.* import java.lang.Exception class Cadastro_paciente : AppCompatActivity() { lateinit var banco: Banco override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_cadastro_paciente) banco = Room.databaseBuilder(applicationContext, Banco::class.java, "RastreioPaciente").allowMainThreadQueries().build() cadastrarPaciente.setOnClickListener { cadastrarPaciente() } } fun cadastrarPaciente(){ val paciente = Paciente() paciente.id_paciente = lastIdPaciente() paciente.nome = nomeTextCardastrarPaciente.text.toString() paciente.email = emailTextCardastrarPaciente.text.toString() paciente.dataNascimento = dataTextCardastrarPaciente.text.toString() paciente.telefone = telTextCardastrarPaciente.text.toString() paciente.planoSaude = planoSaudeTextCardastrarPaciente.text.toString() paciente.cpf = cpfTextCardastrarPaciente.text.toString() try{ banco?.pacienteCrud()?.inserirPaciente(paciente) Toast.makeText(this, "Paciente ${paciente.nome} criado com sucesso!.", Toast.LENGTH_LONG).show() finish() }catch (e: Exception){ Toast.makeText(this, "Erro ao cadastrar. ${e} ${lastIdPaciente()} ", Toast.LENGTH_LONG).show() } } fun lastIdPaciente(): Int { var lastId: Int try { lastId = banco?.pacienteCrud()?.lastId()?.get(0)?.id_paciente.toString().toInt() + 1 }catch (e: Exception) { lastId = 1 } return lastId } } <file_sep>/RastreioPacienteOficial/app/src/main/java/com/example/rastreiopacienteoficial/CadastrarUsuario.kt package com.example.rastreiopacienteoficial import android.arch.persistence.room.Room import android.content.Context import android.content.Intent import android.content.SharedPreferences import android.support.v7.app.AppCompatActivity import android.os.Bundle import android.widget.Toast import com.example.rastreiopaciente.Banco.Banco import com.example.rastreiopaciente.Banco.Usuario import kotlinx.android.synthetic.main.activity_cadastrar_usuario.* import java.lang.Exception class CadastrarUsuario : AppCompatActivity() { lateinit var banco: Banco override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_cadastrar_usuario) title = "Cadastrar Novo Usuário" banco = Room.databaseBuilder(applicationContext, Banco::class.java, "RastreioPaciente").allowMainThreadQueries().build() cadastrarUsuario.setOnClickListener { cadastrar() } } fun cadastrar(){ //Cria um novo usuario val usuario = Usuario() usuario.idUsuario = lastIdUsuario() usuario.nome = nome.text.toString() usuario.login = login_usuario.text.toString() usuario.senha = <PASSWORD>.text.toString() usuario.email = email.text.toString() usuario.credencial = credencial.text.toString() try{ banco?.usuarioCrud()?.inserirUsuario(usuario) login() Toast.makeText(this, "Usuário ${usuario.nome} criado com sucesso!.", Toast.LENGTH_LONG).show() }catch (e: Exception){ Toast.makeText(this, "Erro ao cadastrar.", Toast.LENGTH_LONG).show() } } fun lastIdUsuario(): Int { var lastId: Int try { lastId = banco?.usuarioCrud()?.lastId()?.get(0)?.idUsuario.toString().toInt() + 1 }catch (e: Exception) { lastId = 1 } return lastId } fun login() { val login = login_usuario.text.toString() val senha = senha.text.toString() val sharedPreferences: SharedPreferences = getSharedPreferences("rastreiopacienteoficial", Context.MODE_PRIVATE) val editor = sharedPreferences.edit() editor.putBoolean("isLogged", true) editor.putString("username", login) editor.putString("password", <PASSWORD>) editor.putString("name", nome.text.toString()) editor.apply() startActivity(Intent(this, MainActivity::class.java)) finish() } } <file_sep>/RastreioPacienteOficial/app/src/main/java/com/example/rastreiopacienteoficial/Banco/UsuarioCRUD.kt package com.example.rastreiopaciente.Banco import android.arch.persistence.room.* @Dao interface UsuarioCRUD { @Insert // or OnConflictStrategy.IGNORE fun inserirUsuario(usuario: Usuario) @Delete fun deleteUsuario(usuario: Usuario) @Update fun updateUsuario(usuario: Usuario) @Query("select * from Usuario") fun listarUsuarios(): List<Usuario> @Query("select * from Usuario where idUsuario=:id") fun getUsuario(id:Int): Usuario @Query("select * from Usuario where login=:login1 and senha=:senha1") fun verifyUruario(login1:String, senha1:String): Usuario @Query("select * from Usuario order by idUsuario desc") fun lastId(): List<Usuario> }<file_sep>/RastreioPacienteOficial/app/src/main/java/com/example/rastreiopacienteoficial/Edita_paciente.kt package com.example.rastreiopacienteoficial import android.arch.persistence.room.Room import android.content.Context import android.content.SharedPreferences import android.support.v7.app.AppCompatActivity import android.os.Bundle import android.text.Editable import android.widget.Toast import com.example.rastreiopaciente.Banco.Banco import com.example.rastreiopaciente.Banco.Paciente import com.example.rastreiopaciente.Banco.Usuario import kotlinx.android.synthetic.main.activity_cadastrar_usuario.* import kotlinx.android.synthetic.main.activity_cadastro_paciente.* import kotlinx.android.synthetic.main.activity_edita_paciente.* import java.lang.Exception class Edita_paciente : AppCompatActivity() { lateinit var banco: Banco lateinit var paciente: Paciente override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_edita_paciente) val sharedPreferences: SharedPreferences = getSharedPreferences("rastreiopacienteoficial", Context.MODE_PRIVATE) banco = Room.databaseBuilder(applicationContext, Banco::class.java, "RastreioPaciente").allowMainThreadQueries().build() paciente = banco.pacienteCrud().getPaciente(sharedPreferences.getString("paciente_id", "").toInt()) nomeTextCardastrarPaciente2.text = Editable.Factory.getInstance().newEditable(paciente.nome) emailTextCardastrarPaciente2.text = Editable.Factory.getInstance().newEditable(paciente.email) dataTextCardastrarPaciente2.text = Editable.Factory.getInstance().newEditable(paciente.dataNascimento) telTextCardastrarPaciente2.text = Editable.Factory.getInstance().newEditable(paciente.telefone) planoSaudeTextCardastrarPaciente2.text = Editable.Factory.getInstance().newEditable(paciente.planoSaude) cpfTextCardastrarPaciente2.text = Editable.Factory.getInstance().newEditable(paciente.cpf.toString()) alterarPaciente.setOnClickListener { alterarPaciente(sharedPreferences) } } fun alterarPaciente(sharedPreferences: SharedPreferences){ paciente.nome = nomeTextCardastrarPaciente2.text.toString() paciente.email = emailTextCardastrarPaciente2.text.toString() paciente.dataNascimento = dataTextCardastrarPaciente2.text.toString() paciente.telefone = telTextCardastrarPaciente2.text.toString() paciente.planoSaude = planoSaudeTextCardastrarPaciente2.text.toString() paciente.cpf = cpfTextCardastrarPaciente2.text.toString() try{ banco?.pacienteCrud()?.updatePaciente(paciente) Toast.makeText(this, "Paciente ${paciente.nome} alterado com sucesso!.", Toast.LENGTH_LONG).show() val editor = sharedPreferences.edit() editor.putString("paciente_nome", paciente.nome) finish() }catch (e: Exception){ Toast.makeText(this, "Erro ao cadastrar. ${e} ", Toast.LENGTH_LONG).show() } } } <file_sep>/RastreioPacienteOficial/app/src/main/java/com/example/rastreiopacienteoficial/ProcurarPaciente.kt package com.example.rastreiopacienteoficial import android.arch.persistence.room.Room import android.content.Context import android.content.Intent import android.content.SharedPreferences import android.support.v7.app.AppCompatActivity import android.os.Bundle import android.view.View import android.widget.* import com.example.rastreiopaciente.Banco.Banco import com.example.rastreiopaciente.Banco.Paciente class ProcurarPaciente : AppCompatActivity() { lateinit var banco: Banco lateinit var listaPaciente: ListView override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_procurar_paciente) banco = Room.databaseBuilder(applicationContext, Banco::class.java, "RastreioPaciente").allowMainThreadQueries().build() listaPaciente = findViewById<ListView>(R.id.listViewPesquisa) var adapterPaciente = PacienteAdapter(context = this.applicationContext, act = this) listaPaciente.adapter = adapterPaciente listaPaciente.setOnItemClickListener{parent: AdapterView<*>?, view: View?, position: Int, id: Long -> var id_paciente = view?.findViewById<TextView>(R.id.lista_id_paciente)?.text.toString() var nome = view?.findViewById<TextView>(R.id.lista_nome_paciente)?.text.toString() val sharedPreferences: SharedPreferences = getSharedPreferences("rastreiopacienteoficial", Context.MODE_PRIVATE) val editor = sharedPreferences.edit() editor.putString("paciente_nome", nome) editor.putString("paciente_id",id_paciente) editor.apply() Toast.makeText(this, "Paciente ${nome} escolhido.", Toast.LENGTH_LONG).show() startActivity(Intent(this, TelaSelecaoOpccao::class.java)) finish() } } } <file_sep>/RastreioPacienteOficial/app/src/main/java/com/example/rastreiopacienteoficial/Banco/PacienteDoencaCRUD.kt package com.example.rastreiopaciente.Banco import android.arch.persistence.room.* @Dao interface PacienteDoencaCRUD { @Insert // or OnConflictStrategy.IGNORE fun inserirPacienteDoenca(pacienteDoenca: PacienteDoenca) @Delete fun deletePacienteDoenca(pacienteDoenca: PacienteDoenca) @Update fun updatePacienteDoenca(pacienteDoenca: PacienteDoenca) @Query("select * from PacienteDoenca") fun listarPacienteDoencas(): List<PacienteDoenca> @Query("select * from PacienteDoenca where id_pacienteDoenca=:id") fun getPacienteDoenca(id:Int): PacienteDoenca }<file_sep>/RastreioPacienteOficial/app/src/main/java/com/example/rastreiopacienteoficial/ProcurarAtendimento.kt package com.example.rastreiopacienteoficial import android.arch.persistence.room.Room import android.content.Context import android.content.Intent import android.content.SharedPreferences import android.support.v7.app.AppCompatActivity import android.os.Bundle import android.view.View import android.widget.* import com.example.rastreiopaciente.Banco.Banco class ProcurarAtendimento : AppCompatActivity() { lateinit var banco: Banco lateinit var listaAtendimento: ListView override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_procurar_atendimento) banco = Room.databaseBuilder(applicationContext, Banco::class.java, "RastreioPaciente").allowMainThreadQueries().build() listaAtendimento = findViewById<ListView>(R.id.listViewPesquisaAtendimento) var adapterAtendimento = AtendimentoAdapter(context = this.applicationContext, act = this) listaAtendimento.adapter = adapterAtendimento listaAtendimento.setOnItemClickListener{ parent: AdapterView<*>?, view: View?, position: Int, id: Long -> var id_atendimento = view?.findViewById<TextView>(R.id.lista_id_atendimento)?.text.toString() var doenca = view?.findViewById<TextView>(R.id.lista_doenca_paciente)?.text.toString() val sharedPreferences: SharedPreferences = getSharedPreferences("rastreiopacienteoficial", Context.MODE_PRIVATE) val editor = sharedPreferences.edit() editor.putString("atendimento_id", id_atendimento) editor.apply() Toast.makeText(this, "Atendimento do dença ${doenca} escolhido.", Toast.LENGTH_LONG).show() startActivity(Intent(this, Editar_Atendimento::class.java)) finish() } } } <file_sep>/RastreioPacienteOficial/app/src/main/java/com/example/rastreiopacienteoficial/TelaSelecaoOpccao.kt package com.example.rastreiopacienteoficial import android.arch.persistence.room.Room import android.content.Context import android.content.Intent import android.content.SharedPreferences import android.support.v7.app.AppCompatActivity import android.os.Bundle import android.widget.TextView import com.example.rastreiopaciente.Banco.Banco import kotlinx.android.synthetic.main.activity_tela_selecao_opccao.* class TelaSelecaoOpccao : AppCompatActivity() { lateinit var banco: Banco override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_tela_selecao_opccao) val sharedPreferences: SharedPreferences = getSharedPreferences("rastreiopacienteoficial", Context.MODE_PRIVATE) banco = Room.databaseBuilder(applicationContext, Banco::class.java, "RastreioPaciente").allowMainThreadQueries().build() var viewNome = findViewById<TextView>(R.id.textView10) viewNome.text = sharedPreferences.getString("paciente_nome", "") buttonAdiconarAtendimento.setOnClickListener { adicionarAtendimento() } buttonEditarAtendimento.setOnClickListener { editarAtendimento() } editarPaciente.setOnClickListener { editarPaciente() } } fun adicionarAtendimento(){ startActivity(Intent(this, Cadastro_atendimento::class.java)) } fun editarAtendimento(){ startActivity(Intent(this, ProcurarAtendimento::class.java)) } fun editarPaciente(){ startActivity(Intent(this, Edita_paciente::class.java)) } } <file_sep>/RastreioPacienteOficial/app/src/main/java/com/example/rastreiopacienteoficial/Banco/AtendimentoCRUD.kt package com.example.rastreiopaciente.Banco import android.arch.persistence.room.* @Dao interface AtendimentoCRUD { @Insert // or OnConflictStrategy.IGNORE fun inserirAtendimento(atendimento: Atendimento) @Delete fun deleteAtendimento(atendimento: Atendimento) @Update fun updateAtendimento(atendimento: Atendimento) @Query("select * from Atendimento") fun listarAtendimentos(): List<Atendimento> @Query("select * from Atendimento where id_atendimento=:id") fun getAtendimento(id:Int): Atendimento @Query("select * from Atendimento where id_paciente=:id") fun getAtendimentoPaciente(id:Int): List<Atendimento> @Query("select * from Atendimento order by id_atendimento desc") fun lastId(): List<Atendimento> @Query("select * from Atendimento where data=:obs") fun getIdAtendimento(obs:String): Atendimento }<file_sep>/RastreioPacienteOficial/app/src/main/java/com/example/rastreiopacienteoficial/Banco/Atendimento.kt package com.example.rastreiopaciente.Banco import android.arch.persistence.room.ColumnInfo import android.arch.persistence.room.Entity import android.arch.persistence.room.PrimaryKey import java.time.Instant import java.time.Instant.now import java.util.* @Entity class Atendimento { @PrimaryKey var id_atendimento:Int?=0 @ColumnInfo(name = "doenca") var doenca:String?=null @ColumnInfo(name = "medicacao") var medicacao:String?=null @ColumnInfo(name = "data") var data: String? = null @ColumnInfo(name = "custo") var custo: Float = 0.0F @ColumnInfo(name = "observacoes") var observacoes:String?=null @ColumnInfo(name = "id_paciente") var id_paciente:Int?=0 } <file_sep>/RastreioPacienteOficial/app/src/main/java/com/example/rastreiopacienteoficial/Banco/Usuario.kt package com.example.rastreiopaciente.Banco import android.arch.persistence.room.ColumnInfo import android.arch.persistence.room.Entity import android.arch.persistence.room.PrimaryKey @Entity class Usuario { @PrimaryKey var idUsuario:Int?=0 @ColumnInfo(name = "login") var login:String?=null @ColumnInfo(name = "senha") var senha:String?=null @ColumnInfo(name = "email") var email:String?=null @ColumnInfo(name = "nome") var nome:String?=null @ColumnInfo(name = "credencial") var credencial:String?=null } <file_sep>/RastreioPacienteOficial/app/src/main/java/com/example/rastreiopacienteoficial/MyApplication.kt package com.example.rastreiopacienteoficial import android.arch.persistence.room.Room import android.app.Application import com.example.rastreiopaciente.Banco.Banco open class MyApplication : Application() { companion object { var banco: Banco? = null } override fun onCreate() { super.onCreate() //Room banco = Room.databaseBuilder(this, Banco::class.java, "my-db").allowMainThreadQueries().build() } }<file_sep>/RastreioPacienteOficial/app/src/main/java/com/example/rastreiopacienteoficial/MainActivity.kt package com.example.rastreiopacienteoficial import android.arch.persistence.room.Room import android.support.v7.app.AppCompatActivity import android.os.Bundle import android.content.Context import android.content.Intent import android.content.SharedPreferences import com.example.rastreiopaciente.Banco.Banco import kotlinx.android.synthetic.main.activity_main.* class MainActivity : AppCompatActivity() { lateinit var banco: Banco override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) //instancia o banco banco = Room.databaseBuilder(applicationContext, Banco::class.java, "RastreioPaciente").allowMainThreadQueries().build() val sharedPreferences: SharedPreferences = getSharedPreferences("rastreiopacienteoficial", Context.MODE_PRIVATE) val isLogged = sharedPreferences.getBoolean("isLogged", false) //verifica se o usuario já está logado if (isLogged) { buttonSair.setOnClickListener { logout(sharedPreferences) } buttonVisualizarAtendimento.setOnClickListener {visualizarHistorico ()} buttonCriarPaciente.setOnClickListener {criarPaciente ()} } else { startActivity(Intent(this, Login::class.java)) finish() } } fun logout(sharedPreferences: SharedPreferences) { val editor = sharedPreferences.edit() editor.putBoolean("isLogged", false) editor.putString("username", "") editor.putString("password", "") editor.putString("paciente_nome","" ) editor.putString("paciente_id","" ) editor.apply() startActivity(Intent(this, Login::class.java)) finish() } fun visualizarHistorico() { startActivity(Intent(this, ProcurarPaciente::class.java)) } fun criarPaciente() { startActivity(Intent(this, Cadastro_paciente::class.java)) } } <file_sep>/RastreioPacienteOficial/app/src/main/java/com/example/rastreiopacienteoficial/Login.kt package com.example.rastreiopacienteoficial import android.arch.persistence.room.Room import android.content.Context import android.content.Intent import android.content.SharedPreferences import android.support.v7.app.AppCompatActivity import android.os.Bundle import kotlinx.android.synthetic.main.activity_login.* import android.widget.Toast import com.example.rastreiopaciente.Banco.Banco import com.example.rastreiopaciente.Banco.Usuario import kotlinx.android.synthetic.main.activity_cadastrar_usuario.* import org.json.JSONException import org.json.JSONObject import java.lang.Exception import java.util.* class Login : AppCompatActivity() { lateinit var banco: Banco override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_login) title = "Login" banco = Room.databaseBuilder(applicationContext, Banco::class.java, "RastreioPaciente").allowMainThreadQueries().build() entrar.setOnClickListener { login() } cadastraruser.setOnClickListener { cadastro() } } fun login() { try { val login = username.text.toString() val senha = password.text.toString() var usr = banco?.usuarioCrud()?.verifyUruario(username.text.toString(), password.text.toString()) if(usr?.login.equals(login) && usr?.senha.equals(senha)) { val sharedPreferences: SharedPreferences = getSharedPreferences("rastreiopacienteoficial", Context.MODE_PRIVATE) val editor = sharedPreferences.edit() editor.putBoolean("isLogged", true) editor.putString("username", usr?.nome) editor.putString("password", usr?.senha) editor.putString("name", usr?.nome) editor.putString("paciente_nome","" ) editor.putString("paciente_id","" ) editor.apply() startActivity(Intent(this, MainActivity::class.java)) finish() }else{ Toast.makeText(this, "Login ou senha incorreta.", Toast.LENGTH_LONG).show() } } catch (e: JSONException) { Toast.makeText(this, "Erro ao logar.", Toast.LENGTH_LONG).show() } } fun cadastro(){ startActivity(Intent(this, CadastrarUsuario::class.java)) finish() } } <file_sep>/RastreioPacienteOficial/app/src/main/java/com/example/rastreiopacienteoficial/Banco/Doenca.kt package com.example.rastreiopaciente.Banco import android.arch.persistence.room.ColumnInfo import android.arch.persistence.room.Entity import android.arch.persistence.room.PrimaryKey @Entity class Doenca { @PrimaryKey(autoGenerate = true) var id_doenca:Long?=0 @ColumnInfo(name = "nome") var nome:String?=null @ColumnInfo(name = "tipo") var tipo:Int?=0 } <file_sep>/RastreioPacienteOficial/app/src/main/java/com/example/rastreiopacienteoficial/Banco/PacienteCRUD.kt package com.example.rastreiopaciente.Banco import android.arch.persistence.room.* @Dao interface PacienteCRUD { @Insert // or OnConflictStrategy.IGNORE fun inserirPaciente(paciente: Paciente) @Delete fun deletePaciente(paciente: Paciente) @Update fun updatePaciente(paciente: Paciente) @Query("select * from Paciente") fun listarPacientes(): List<Paciente> @Query("select * from Paciente where id_paciente=:id") fun getPaciente(id:Int): Paciente @Query("select * from Paciente order by id_paciente desc") fun lastId(): List<Paciente> @Query("select * from Paciente where nome=:nome") fun getIdPaciente(nome:String): Paciente }<file_sep>/RastreioPacienteOficial/app/src/main/java/com/example/rastreiopacienteoficial/AtendimentoAdapter.kt package com.example.rastreiopacienteoficial import android.app.Activity import android.arch.persistence.room.Room import android.content.Context import android.view.View import android.view.ViewGroup import android.content.SharedPreferences import android.widget.BaseAdapter import android.widget.TextView import com.example.rastreiopaciente.Banco.Banco class AtendimentoAdapter(var context: Context, var act: Activity) : BaseAdapter() { var banco = Room.databaseBuilder(context, Banco::class.java, "RastreioPaciente").allowMainThreadQueries().build() val sharedPreferences: SharedPreferences = context.getSharedPreferences("rastreiopacienteoficial", Context.MODE_PRIVATE) var listaAtendimento = banco.atendimentoCrud().getAtendimentoPaciente(sharedPreferences.getString("paciente_id", "").toInt()) override fun getView(position: Int, convertView: View?, parent: ViewGroup?): View { var view = act.getLayoutInflater().inflate(R.layout.lista_atendimento_personalizada, parent, false) var atendimento = listaAtendimento.get(position) //pegando as referências das Views var doenca = view.findViewById<TextView>(R.id.lista_doenca_paciente) var data_atendimento = view.findViewById<TextView>(R.id.lista_data_atendimento) var id_atendimento = view.findViewById<TextView>(R.id.lista_id_atendimento) //populando as views doenca.text = atendimento.doenca data_atendimento.text = atendimento.data id_atendimento.text = atendimento.id_atendimento.toString() return view } override fun getItem(position: Int): Any { return listaAtendimento.get(position) } override fun getItemId(position: Int): Long { // var paciente = listaPaciente.get(position) // return paciente.id_paciente?.toLong()!! return 0 } override fun getCount(): Int { return listaAtendimento.size } }<file_sep>/RastreioPacienteOficial/app/src/main/java/com/example/rastreiopacienteoficial/Banco/PacienteDoenca.kt package com.example.rastreiopaciente.Banco import android.arch.persistence.room.ColumnInfo import android.arch.persistence.room.Entity import android.arch.persistence.room.PrimaryKey @Entity class PacienteDoenca { @PrimaryKey(autoGenerate = true) var id_pacienteDoenca:Long?=0 @ColumnInfo(name = "id_paciente") var id_paciente:Long?=0 @ColumnInfo(name = "id_doenca") var id_doenca:Long?=0 } <file_sep>/RastreioPacienteOficial/app/src/main/java/com/example/rastreiopacienteoficial/Editar_Atendimento.kt package com.example.rastreiopacienteoficial import android.arch.persistence.room.Room import android.content.Context import android.content.SharedPreferences import android.support.v7.app.AppCompatActivity import android.os.Bundle import android.text.Editable import android.widget.Toast import com.example.rastreiopaciente.Banco.Atendimento import com.example.rastreiopaciente.Banco.Banco import com.example.rastreiopaciente.Banco.Paciente import com.example.rastreiopacienteoficial.R import kotlinx.android.synthetic.main.activity_editar__atendimento.* import java.lang.Exception class Editar_Atendimento : AppCompatActivity() { lateinit var banco: Banco lateinit var atendimento: Atendimento override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_editar__atendimento) val sharedPreferences: SharedPreferences = getSharedPreferences("rastreiopacienteoficial", Context.MODE_PRIVATE) banco = Room.databaseBuilder(applicationContext, Banco::class.java, "RastreioPaciente").allowMainThreadQueries().build() atendimento = banco.atendimentoCrud().getAtendimento(sharedPreferences.getString("atendimento_id", "").toInt()) dataChegadaAtendimento1.text = Editable.Factory.getInstance().newEditable(atendimento.data) doencaNomeAtendimento1.text = Editable.Factory.getInstance().newEditable(atendimento.doenca) medicacaoAtendimento1.text = Editable.Factory.getInstance().newEditable(atendimento.medicacao) custoTextAtedimento11.text = Editable.Factory.getInstance().newEditable(atendimento.custo.toString()) obstextAtendimento1.text = Editable.Factory.getInstance().newEditable(atendimento.observacoes) buttonCriarAtendimento1.setOnClickListener { alterarAtendimento(sharedPreferences) } } fun alterarAtendimento(sharedPreferences: SharedPreferences){ atendimento.data = dataChegadaAtendimento1.text.toString() atendimento.doenca = doencaNomeAtendimento1.text.toString() atendimento.medicacao = medicacaoAtendimento1.text.toString() atendimento.custo = custoTextAtedimento11.text.toString().toFloat() atendimento.observacoes = obstextAtendimento1.text.toString() try{ banco?.atendimentoCrud()?.updateAtendimento(atendimento) Toast.makeText(this, "Atendimento ${atendimento.observacoes} alterado com sucesso!.", Toast.LENGTH_LONG).show() finish() }catch (e: Exception){ Toast.makeText(this, "Erro ao cadastrar. ${e} ", Toast.LENGTH_LONG).show() } } } <file_sep>/RastreioPacienteOficial/app/src/main/java/com/example/rastreiopacienteoficial/Banco/DoencaCRUD.kt package com.example.rastreiopaciente.Banco import android.arch.persistence.room.* @Dao interface DoencaCRUD { @Insert // or OnConflictStrategy.IGNORE fun inserirDoenca(doenca: Doenca) @Delete fun deleteDoenca(doenca: Doenca) @Update fun updateDoenca(doenca: Doenca) @Query("select * from Doenca") fun listarDoencas(): List<Doenca> @Query("select * from Doenca where id_doenca=:id") fun getDoenca(id:Int): Doenca }<file_sep>/RastreioPacienteOficial/app/src/main/java/com/example/rastreiopacienteoficial/Banco/Paciente.kt package com.example.rastreiopaciente.Banco import android.arch.persistence.room.ColumnInfo import android.arch.persistence.room.Entity import android.arch.persistence.room.PrimaryKey @Entity class Paciente { @PrimaryKey var id_paciente:Int?=0 @ColumnInfo(name = "nome") var nome:String?=null @ColumnInfo(name = "email") var email:String?=null @ColumnInfo(name = "dataNascimento") var dataNascimento:String?=null @ColumnInfo(name = "telefone") var telefone:String?=null @ColumnInfo(name = "planoSaude") var planoSaude:String?=null @ColumnInfo(name = "cpf") var cpf:String?=null }
319209d087ece4b99d424e579e9f2fd352bb6543
[ "Kotlin" ]
24
Kotlin
mfernandesp/TrabalhoKotlinRastreio
d048d32525489a383b7cd3a755a4f1b0f5e1244b
b072c830f4b1c2621a8693df22526078f8c68a0a
refs/heads/master
<repo_name>martinfdev/-OLC1-Practica1_201700656<file_sep>/src/clases/Token.java /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package clases; /** * * @author jblack */ public class Token { public enum Tipo { LLAVE_IZQUIERDO, LLAVE_DERECHO, DOS_PUNTOS, PUNTO_COMA, ID, CADENA, OR, CONCATENACION, DISYUNCION, CERO_UNA_VEZ, CERO_MAS_VECES, UNA_MAS_VECES, OPERADOR, COMENTARIO_SIMPLE, COMENTARIO_MULTILINEA, ASIGNACION, //-> CONJUNTO, CONJ, EXPRESION_REGULAR, SEPARADOR, ERRORLEXICO } private final Tipo tipoToken; private final String lexema; private final int fila, columna; // private String valor; public Token(Tipo tipo, String lexema, int fila, int columna) { this.tipoToken = tipo; this.lexema = lexema; this.fila = fila; this.columna = columna; } public Tipo getTipoToken() { return tipoToken; } public int getFila() { return fila; } public int getColumna() { return columna; } public String getLexema() { return lexema; } public String getEndString() { switch (tipoToken) { case ERRORLEXICO: return "Elemento lexico desconocido"; } return "Elemento lexico desconocido"; } } <file_sep>/README.md # [OLC1]Practica1_201700656
42fa2c3d02324cbf8fb35d9c659837c1db6a5b85
[ "Markdown", "Java" ]
2
Java
martinfdev/-OLC1-Practica1_201700656
85fb44b1eab5c996e026cf2466b393453adba9c3
d6f89b9cff0c9de909f6ee411f1d8fb07f0f5d6b
refs/heads/main
<repo_name>SulakshaPowar/node-and-mysql-CRUD<file_sep>/router.js const express = require("express"); const router = express.Router(); const bcrypt = require("bcryptjs"); const jwt = require("jsonwebtoken"); const uuid = require("uuid"); const index = require("../index"); const db = require("../lib/db.js"); const userMiddleware = require("../middleware/user.js"); const { validateRegister } = require("../middleware/user.js"); var app = express(); const bodyparser = require('body-parser'); // app.use(bodyParser.urlencoded({ extended: true })); app.use(bodyparser.json()); //http://localhost:3000/api/sign-up router.post("/sign-up", userMiddleware.validateRegister, (req, res, next) => { db.query( `SELECT id FROM users WHERE LOWER(username) = LOWER(${req.body.username})` , (err, result) => { if(result && result.length){ //error return res.status(409).send({ message:"This username is already in use!", }); } else { //username not in use bcrypt.hash(req.body.password,10 ,(err, hash) => { if(err){ throw err; return res.status(500).send({ message: err, }); } else { db.query( `INSERT INTO users(id, username, password, registered) VALUES('${uuid.v4()}', ${db.escape(req.body.username)}, '${hash}',now());`, (err, result) => { if(err){ throw err; return res.status(400).send({ message: err, }); } return res.status(201).send({ message: "Registered!", }); }) } }); } }) }); //http://localhost:3000/api/login router.post("/login", (req, res, next) => { console.log(req.body); db.query( `SELECT * FROM users WHERE username = ${db.escape(req.body.username)};`, (err, result) => { console.log(result); if(err) { throw err; return res.status(400).send({ message:"err" , }); } if(!result.length){ return res.status(401).send({ message: "Username or password incorrect", }); } //check password bcrypt.compare(req.body.password, result[0]["password"], (bErr, bResult) => { //wrong password if (bErr) { throw bErr; return res.status(401).send({ message: "Username or password incorrect!", }); } if(bResult){ //password match const token = jwt.sign( { username: result[0].username, userId: result[0].id }, "SECRETKEY", {expiresIn: "7d"} ); db.query(`UPDATE users SET last_login = now() WHERE id = '${result[0].id}'` ); return res.status(200).send({ message: 'Logged in!', token, user: result[0] }); } return res.status(400).send({ message: "Username or password incorrect" }); } ); }); }); //http://localhost:3000/api/secret-route router.get("/secret-route", userMiddleware.isLoggedIn,(req, res, next) => { console.log(req.userData); console.log(result); res.send("This is the secret content. Only Logged In users can see that!"); }); //-------------------------------------Products section-----------------------------------------------// //Get all products //http://localhost:3000/api/product-details router.get('/product-details', (req, res) => { db.query('SELECT * FROM Products', (err, rows, fields) => { if (!err) res.send(rows); else console.log(err); }) }); //Get a product based on id //http://localhost:3000/api/product-details/:id router.get('/product-details/:id', (req, res) => { db.query('SELECT * FROM Products WHERE id = ?', [req.params.id], (err, rows, fields) => { if (!err) res.send(rows); else console.log(err); }) }); //Delete a product //http://localhost:3000/api/delete-product/:id router.delete('/delete-product/:id', (req, res) => { db.query('DELETE FROM Products WHERE id = ?', [req.params.id], (err, rows, fields) => { if (!err) res.send('Deleted successfully.'); else console.log(err); }) }); //Insert a product //http://localhost:3000/api/add-product router.post('/add-product', (req, res, next) => { db.query('INSERT INTO Products SET ?', { product_name: req.body.product_name, description: req.body.description, slug: req.body.slug, image: req.body.image, status: req.body.status}, (err, res)=>{ if(err) throw err; else console.log('product has been added successfully'); }); }); //Update a product //http://localhost:3000/api/update-product router.put('/update-product', (req, res) => { var param = req.body; var id= param.id; var product_name = param.product_name; var description = param.description; var slug = param.slug; var image = param.image; var status = param.status; db.query("UPDATE Products SET product_name = ?, description = ?, slug= ?, image = ?, status= ? WHERE id = ?", [product_name, description, slug, image, status, id ] ,(err, rows, fields) => { if (err){ throw err; } else { res.json({ status: 1, message: "Product has been updated successfully" }); } }) }); module.exports = router;
770d370241c01dbaa5780f15012cbbd80e93b26f
[ "JavaScript" ]
1
JavaScript
SulakshaPowar/node-and-mysql-CRUD
0d44f842c27a0dae188e1a0261de515966a4cfa6
2bd288ffeda2634832bdff959e18fce325d3b9b1
refs/heads/main
<repo_name>dleorud111/population-chicken_nums-graph<file_sep>/매장1개당 유동인구 그래프그리기.py #!/usr/bin/env python # coding: utf-8 # In[2]: import pandas as pd commercial = pd.read_csv('./commercial.csv') commercial commercial.groupby('상가업소번호')['상권업종소분류명'].count().sort_values(ascending=False) commercial['도로명주소'] # 서울시 데이터만 가져오기 # 3덩어리로 쪼갠 후 새로운 칼럼 추가 commercial[['시','구','상세주소']] = commercial['도로명주소'].str.split(' ',n=2, expand=True) # 서울특별시의 데이터만 추출 seoul_data = commercial[ commercial['시'] == '서울특별시'] seoul_data.tail(5) # 서울만 있는지 확인하기(집합연산) city_type = set(seoul_data['시']) city_type # 서울 치킨집만 추출 seoul_chicken_data = seoul_data[ seoul_data['상권업종소분류명'] == '후라이드/양념치킨' ] seoul_chicken_data chicken_count_by_gu = seoul_chicken_data.groupby('구')['상권업종소분류명'].count() chicken_count_by_gu # In[4]: new_chicken_count_gu = pd.DataFrame(chicken_count_by_gu).reset_index() new_chicken_count_gu # In[5]: population = pd.read_csv('./population07.csv') sum_populationo_by_gu = population.groupby('군구')['유동인구수'].sum() # In[6]: new_sum_populationo_by_gu = pd.DataFrame(sum_populationo_by_gu).reset_index() new_sum_populationo_by_gu # In[7]: # 두 데이터 합치기 gu_chicken = new_chicken_count_gu.join(new_sum_populationo_by_gu.set_index('군구'), on = '구') gu_chicken # In[8]: gu_chicken['유동인구수/치킨집수'] = gu_chicken['유동인구수'] / gu_chicken['상권업종소분류명'] gu_chicken = gu_chicken.sort_values(by='유동인구수/치킨집수') gu_chicken # In[14]: import matplotlib.pyplot as plt plt.rcParams['font.family'] = 'Malgun Gothic' plt.figure(figsize=(10,5)) plt.bar(gu_chicken['구'], gu_chicken['유동인구수/치킨집수']) plt.title('치킨집당 유동인구수') plt.xlabel('구') plt.ylabel('유동인구수/치킨집수') plt.xticks(rotation=90) plt.show() # In[ ]:
593ff1283e1fda609d4c98a80525c62e28185caa
[ "Python" ]
1
Python
dleorud111/population-chicken_nums-graph
2cad09c74a3dfac1289b0b6e56eb971741f353e7
69200a4590c78b263002fa0d6552d22e904c65f7
refs/heads/master
<repo_name>nikitadurasov/EAST_pytorch<file_sep>/datasets/dataset_utils.py from cv2 import minAreaRect, boxPoints import numpy as np import matplotlib.pyplot as plt import skimage.draw def generate_minimum_quad_orthogon(quad_bbox): """Generate rectangle with minimal square that surrounds given polygon. Args: quad_bbox (numpy.array): float numpy array with shape (8,) that contains coordinates of polygon vertexes. Returns: numpy.array: float numpy array with shape (8,) that contains coordinates of minimal square rectangle. """ points_pairs = quad_bbox.reshape(-2, 2) rect = minAreaRect(points_pairs) box = boxPoints(rect).ravel() return box def read_gt(filename): lines = open(filename).readlines() bboxes = np.array(list(map(lambda x: x.split(',')[:-1], lines))) return bboxes.astype('float32') def draw_bbox(bbox, c='r'): """Drawing given bbox borders. Args: bbox (numpy.array): float numpy array with shape (8,) that contains coordinates of polygon vertexes. """ plt.plot(bbox[::2], bbox[1::2], c=c) plt.plot([bbox[-2], bbox[0]], [bbox[-1], bbox[1]], c=c) def draw_bboxes(img, bboxes, c='r'): """Drawing given image and bboxes borders Args: img (numpy.array): float numpy array of image with shape (*, *, 3). bboxes (numpy.array): float numpy array with shape (*, 8) that contains coordinates of polygons vertexes. """ plt.imshow(img) for bbox in bboxes: draw_bbox(bbox, c) def normalize(vector): return vector / np.linalg.norm(vector) def shrink_bbox(bbox, scale=0.2): """Clip original rectangle from both size with scale * current_side_length. Result of this operation is rectangle with smaller square nested in original bbox. Examples: >>> bbox = np.array([-2, -2, -2, 2, 2, 2, 2, -2]) >>> clipped_bbox = shrink_bbox(bbox, 0.25) >>> print(clipped_bbox) array([-1, -1, -1, 1, 1, 1, 1, -1]) Args: bbox (numpy.array): float numpy array with shape (8,) that contains coordinates of polygon vertexes. scale (float): reduction measure of rectangle sides, e.g. scale=0.25 rectangle sides will be reduced twice, scale=0.5 - all vertices are tightened to one point. Returns: numpy.array: float numpy array with shape (8,) that contains coordinates of reduced bbox """ bbox_points = bbox.reshape(4, 2) first_direction = scale * (bbox_points[1] - bbox_points[0]) second_direction = scale * (bbox_points[2] - bbox_points[1]) new_points = bbox_points.copy() new_points[0] = new_points[0] + first_direction new_points[3] = new_points[3] + first_direction new_points[2] = new_points[2] - first_direction new_points[1] = new_points[1] - first_direction new_points[0] = new_points[0] + second_direction new_points[3] = new_points[3] - second_direction new_points[2] = new_points[2] - second_direction new_points[1] = new_points[1] + second_direction return bbox_order(new_points.ravel()) def rectangle_borders_distances(bbox, points): """Calculate distances from points to borders of bbox. This function assumes that first point in bbox is upper left one and other point follows in clockwise order. Args: bbox (numpy.array): float numpy array with shape (8,) that contains coordinates of polygon vertexes. points (numpy.array): float numpy array with shape (*, 8) that contains coordinates of considered points. Returns: numpy.array: float numpy array with shape (*, 2) that contains distances from corresponding point to bbox borders. """ bbox_points = bbox.reshape(4, 2) a, b = bbox_points[0], bbox_points[2] a_p = a - points b_p = b - points first_direction = normalize(bbox_points[1] - bbox_points[0]) second_direction = normalize(bbox_points[2] - bbox_points[1]) h_dist = np.vstack([np.abs(np.dot(a_p, first_direction)), np.abs(np.dot(b_p, first_direction))]) v_dist = np.vstack([np.abs(np.dot(a_p, second_direction)), np.abs(np.dot(b_p, second_direction))]) return np.vstack([np.min(h_dist, axis=0), np.min(v_dist, axis=0)]) def generate_bbox_interion(bbox, shape): """Generates coordinates of bbox interior points Args: bbox (numpy.array): float numpy array with shape (8,) that contains coordinates of polygon vertexes. shape (tuple): two elements tuple with height and width of image Returns: numpy.array: float numpy array with shape (*, 2) that contains coordinates of bbox interior points """ shape = shape[1::-1] points = skimage.draw.polygon(bbox[::2], bbox[1::2], shape=shape) return np.vstack([points[0], points[1]]).T def quad_shifts(bbox, points): """Calculates vector shift for points to bbox vertexes Args: bbox (numpy.array): float numpy array with shape (8,) that contains coordinates of polygon vertexes. points (numpy.array): float numpy array with shape (*, 8) that contains coordinates of considered points. Returns: numpy.array: float numpy array with shape (*, 8) that contains shifts vectors from points to bbox vertexes, e.g. bbox = (v1, v2, v3, v4) and point in z = (x, y), then result is (v1 - x, v2 - x, v3 - x, v4 - x) """ upper_left_diff = bbox.reshape(4, 2)[0] - points upper_right_diff = bbox.reshape(4, 2)[1] - points lower_right_diff = bbox.reshape(4, 2)[2] - points lower_left_diff = bbox.reshape(4, 2)[3] - points return np.hstack([upper_left_diff, upper_right_diff, lower_right_diff, lower_left_diff]) def bbox_order(bbox): """Fixing bbox vertexes order: upper-left points is the first, other follows in clockwise manner. Args: bbox (numpy.array): float numpy array with shape (8,) that contains coordinates of polygon vertexes. Returns: numpy.array: float numpy array with shape (8,) that contains coordinates of fixed order polygon vertexes. """ def mapping(x): if x == 0: return 3 elif x == 1: return 0 elif x == 2: return 2 elif x == 3: return 1 mapping = np.vectorize(mapping) box_points = bbox.reshape(4, 2) mean_point = box_points.mean(axis=0) new_res = quad_shifts(bbox, mean_point).reshape(4,2) positive_values = new_res >= 0 new_order = mapping(positive_values.sum(axis=1) + positive_values[:, 0]) return box_points[new_order].ravel() def short_length_bbox_size(bboxes): bb_points = bboxes.reshape(-1, 4, 2) first_lengths = np.linalg.norm(bb_points[:, 1] - bb_points[:, 0], axis=1) second_lengths = np.linalg.norm(bb_points[:, 2] - bb_points[:, 1], axis=1) return np.stack([first_lengths, second_lengths]).T.min(axis=1) <file_sep>/losses.py import torch import numpy as np import datasets class BalancedXent(torch.nn.Module): def __call__(self, prediction, ground, mask): positive_pixels_sum = ground.sum(dim=[1, 2, 3]).float() beta = 1 - positive_pixels_sum / np.prod(ground.shape[2:]) beta = beta.reshape([beta.shape[0], 1, 1, 1]).type_as(prediction).float() result = beta * ground * torch.log(prediction + 1e-4) + \ (1 - beta) * (1 - ground) * torch.log(1 - prediction + 1e-4) return -result[mask].mean() class QuadGeometry(torch.nn.Module): def __call__(self, pred_geom, gt_geom, mask): eps = 1e-4 predicted_geom = pred_geom.permute(0, 2, 3, 1)[mask.squeeze(1).byte()] ground_geom = gt_geom.permute(0, 2, 3, 1)[mask.squeeze(1).byte()] # print() # print("PREDICTED GEOM FULL - min: {0}, mean: {1}, max: {2}".format(pred_geom.min(), # pred_geom.mean(), # pred_geom.max())) # print("GROUND GEOM FULL - min: {0}, mean: {1}, max: {2}".format(gt_geom.min(), # gt_geom.mean(), # gt_geom.max())) # print("GROUND GEOM - min: {0}, mean: {1}, max: {2}".format(ground_geom.min(), # ground_geom.mean(), # ground_geom.max())) # print("PREDICTED GEOM - min: {0}, mean: {1}, max: {2}".format(predicted_geom.min(), # predicted_geom.mean(), # predicted_geom.max())) smooth_loss = torch.nn.functional.smooth_l1_loss(predicted_geom, ground_geom, reduction='mean') if torch.isnan(smooth_loss): return None # predicted_bboxes = predicted_geom.permute(0, 2, 3, 1)[mask.squeeze(1).byte()] normalization = datasets.dataset_utils.short_length_bbox_size( predicted_geom.cpu().detach().numpy()) normalization = torch.from_numpy(normalization).type_as(predicted_geom) normalization = normalization.reshape(-1, 1) return (smooth_loss / (normalization + 1)).mean() class RboxGeometry(torch.nn.Module): pass <file_sep>/train.py import models import datasets import losses import numpy as np import lanms import metrics from dstorch.detection.icdar2015textloc import ICDAR2015TEXTLOC import torch import torchvision import sys dataset_path = '/srv/hd1/data/ndurasov/datasets/icdar2015/text_localization/' class Trainer(): def __init__(self, checkpoint=None): # models creation self.model = models.east.EAST() if checkpoint is not None: self.model.load_state_dict(torch.load(checkpoint)) # transform obj for dataset trans = torchvision.transforms.Compose([datasets.augmentations.QUAD(0.3), datasets.augmentations.RandomCrop((640, 704)), datasets.augmentations.Normalize()]) # datasets object self.dataset_train = ICDAR2015TEXTLOC(dataset_path, split='train', transform=trans, transform_type='dict') self.dataset_test = ICDAR2015TEXTLOC(dataset_path, split='test', transform=trans, transform_type='dict') # dataloaders objects self.train_dataloader = torch.utils.data.DataLoader(self.dataset_train, batch_size=3, shuffle=True) self.test_dataloader = torch.utils.data.DataLoader(self.dataset_test, batch_size=1) # losses self.loss_cls = losses.BalancedXent() self.loss_geom = losses.QuadGeometry() # optimizer self.optimizer = torch.optim.Adam(self.model.parameters(), lr=1e-5, amsgrad=True) def print_train_results(self, epoch, batch, mean_loss, loss, cls_loss): # print current accuracy sys.stdout.write("\r Training: epoch = {0} ".format(epoch)) sys.stdout.write("batch: {0}/{1} ".format(batch, len(self.train_dataloader))) sys.stdout.write("mean loss = %.3f " % mean_loss) sys.stdout.write("loss = %.3f " % loss) sys.stdout.write("classification loss = %.3f " % cls_loss) sys.stdout.flush() def train_one_epoch(self, epoch): self.model = self.model.cuda() mean_loss = 0 for i, batch in enumerate(self.train_dataloader): images = batch['image'].permute(0, 3, 1, 2).cuda() bbox_maps = batch['bbox_map'].unsqueeze(1).float().cuda() quad = batch['quad_formatting'].permute(0, 3, 1, 2).cuda() ignore_map = batch['ignore_map'].unsqueeze(1).cuda() prediction = self.model(images) l1 = 5e3 * self.loss_cls(prediction['score_map'], bbox_maps, ignore_map.byte()) l2 = self.loss_geom(prediction['geometry'].float(), quad.float(), bbox_maps.byte()) if l2 is None: final_loss = l1 else: final_loss = l1 + l2 mean_loss += final_loss.item() self.optimizer.zero_grad() final_loss.backward() self.optimizer.step() self.print_train_results(epoch, i, mean_loss / (i + 1), final_loss.item(), l1.item()) print() self.model = self.model.cpu() def save_model(self, filename): torch.save(self.model.state_dict(), filename) def print_valid_results(self, epoch, batch, recall, precision, iou): # print current accuracy sys.stdout.write("\r Validation: epoch = {0} ".format(epoch)) sys.stdout.write("batch: {0}/{1} ".format(batch, len(self.test_dataloader))) sys.stdout.write("recall = %.3f " % recall) sys.stdout.write("precision = %.3f " % precision) sys.stdout.write("IOU = %.3f " % iou) sys.stdout.flush() def validate_one_epoch(self, epoch): box_predictor = models.BoxesPredictor(0.9) recall_cum = 0 prec_cum = 0 iou_cum = 0 self.model = self.model.cuda() i = 0 for _, batch in enumerate(self.test_dataloader): images = batch['image'].permute(0, 3, 1, 2).cuda() bbox_maps = batch['bbox_map'].unsqueeze(1).float() quad = batch['quad_formatting'].permute(0, 3, 1, 2) ignore_map = batch['ignore_map'].unsqueeze(1) prediction = self.model(images) for key in prediction: prediction[key] = prediction[key].cpu() boxes = box_predictor(prediction)[0] boxes_p = np.hstack([boxes.detach().numpy(), np.ones([boxes.shape[0], 1])]) boxes_pr = lanms.merge_quadrangle_n9(boxes_p, 0.1) valid_boxes = boxes_pr[:, :8] ground_boxes = box_predictor({"score_map": bbox_maps, "geometry": quad.float()})[0].numpy() if ground_boxes.shape[0] != 0: ground_boxes = np.hstack([ground_boxes, np.ones([ground_boxes.shape[0], 1])]) ground_boxes = lanms.merge_quadrangle_n9(ground_boxes, 0.1) ground_boxes = ground_boxes[:, :8] recall, prec, iou = metrics.matchBoxes(ground_boxes, valid_boxes, thr=0.5) recall_cum += recall prec_cum += prec iou_cum += iou self.print_valid_results(epoch, i, recall_cum / (i + 1), prec_cum / (i + 1), iou_cum / (i + 1)) i += 1 print() self.model = self.model.cpu() if __name__ == '__main__': if sys.argv[1] == 'train': trainer = Trainer('./experiments/29_04_1_epoch_12.pth') for epoch in range(40): trainer.validate_one_epoch(epoch) trainer.train_one_epoch(epoch) if epoch % 3 == 0: trainer.save_model('experiments/30_04_2_epoch_{}.pth'.format(epoch)) elif sys.argv[1] == 'test': trainer = Trainer('./experiments/29_04_1_epoch_12.pth') trainer.validate_one_epoch(0) <file_sep>/datasets/__init__.py from . import dataset_utils from . import augmentations from . import debug_dataset<file_sep>/models/__init__.py from . import east import numpy as np import torch class BoxesPredictor: def __init__(self, thr=0.5): self.thr = thr def __call__(self, prediction): score_maps = prediction["score_map"].clone() geometries = prediction["geometry"].clone() batch_boxes = [] for i in range(len(score_maps)): score_map = score_maps[i].squeeze() geometry = geometries[i].squeeze().permute(1, 2, 0) # preprocess quad format ones = np.ones(list(geometry.shape[:2]) + [4]) x_coords = np.cumsum(ones, axis=1) y_coords = np.cumsum(ones, axis=0) geometry[:, :, ::2] += torch.from_numpy(x_coords).float() geometry[:, :, 1::2] += torch.from_numpy(y_coords).float() mask = score_map > self.thr boxes = geometry[mask] batch_boxes.append(boxes) return batch_boxes <file_sep>/README.md # EAST_pytorch Pytorch implementation of EAST detector for text -- this version is not based on original TensorFlow authors code. ## Usage First of all you need to install [pytorch](https://pytorch.org/?utm_source=Google&utm_medium=PaidSearch&utm_campaign=%2A%2ALP+-+TM+-+General+-+HV+-+RU&utm_adgroup=Install+PyTorch&utm_keyword=%2Binstall%20%2Bpytorch&utm_offering=AI&utm_Product=PyTorch&gclid=Cj0KCQjw6cHoBRDdARIsADiTTzbpH_VFIFaOoEmjySWPiLx9J5wkLwud2-SnaUIDQtpTXDNL1qEadcAaAlFREALw_wcB) and [dstorch](https://github.com/nikitadurasov/dstorch) Other required libraries: * albumentations * torchvision For training you need to download ICDAR 2015: *Note: you should change the gt text file of icdar2015's filename to img_*.txt instead of gt_img_*.txt* To start training procedure you need to run ```python python train.py ``` Please find useful function for bounding box processing in [datasets_utils](https://github.com/nikitadurasov/EAST_pytorch/blob/master/datasets/dataset_utils.py) and basic implementation of EAST in models. Lanms directory consist of original authors code for locally aware NMS algorithm from paper (requires at least gcc 6 ). <file_sep>/models/east.py import torch import torchvision class EAST(torch.nn.Module): # TODO different kinds of backbones @staticmethod def build_feature_extractor(): resnet_params = torchvision.models.resnet50(pretrained=True) # 3 -> 64, /2 block_1 = torch.nn.Sequential(resnet_params.conv1, resnet_params.bn1, resnet_params.relu) # 64 -> 256, /2 block_2 = torch.nn.Sequential(resnet_params.maxpool, resnet_params.layer1) # 256 -> 512, /2 block_3 = resnet_params.layer2 # 512 -> 1024, /2 block_4 = resnet_params.layer3 # 1024 -> 2048, /2 block_5 = resnet_params.layer4 return torch.nn.Sequential(block_1, block_2, block_3, block_4, block_5) @staticmethod def build_feature_merging_branch(): # 2048 -> 1024, 2/ block_1 = torch.nn.Sequential(torch.nn.Conv2d(2048, 1024, 1), torch.nn.Conv2d(1024, 1024, 3, padding=1)) # 1024 -> 512, 2/ block_2 = torch.nn.Sequential(torch.nn.Conv2d(2*1024, 512, 1), torch.nn.Conv2d(512, 512, 3, padding=1)) # 512 -> 256, 2/ block_3 = torch.nn.Sequential(torch.nn.Conv2d(2*512, 256, 1), torch.nn.Conv2d(256, 256, 3, padding=1)) # 256 -> 64, 2/ block_4 = torch.nn.Sequential(torch.nn.Conv2d(2*256, 64, 1), torch.nn.Conv2d(64, 64, 3, padding=1)) # 64 -> 1, 2/ block_5 = torch.nn.Conv2d(2*64, 32, 3, padding=1) return torch.nn.Sequential(block_1, block_2, block_3, block_4, block_5) def __init__(self, kind="quad"): super(EAST, self).__init__() self.resnet_blocks = self.build_feature_extractor() self.feature_merging_branch = self.build_feature_merging_branch() self.score_map_conv = torch.nn.Conv2d(32, 1, 1) self.quad_conv = torch.nn.Conv2d(32, 8, 1) self.kind = kind def forward(self, x): # interpolation block unpooling = torch.nn.Upsample(scale_factor=2, mode='bilinear', align_corners=True) # feature extraction fte1 = self.resnet_blocks[0](x) fte2 = self.resnet_blocks[1](fte1) fte3 = self.resnet_blocks[2](fte2) fte4 = self.resnet_blocks[3](fte3) fte5 = self.resnet_blocks[4](fte4) # features merging ftm5 = fte5 ftm5 = unpooling(ftm5) ftm4 = torch.cat([self.feature_merging_branch[0](ftm5), fte4], dim=1) ftm4 = unpooling(ftm4) ftm3 = torch.cat([self.feature_merging_branch[1](ftm4), fte3], dim=1) ftm3 = unpooling(ftm3) ftm2 = torch.cat([self.feature_merging_branch[2](ftm3), fte2], dim=1) ftm2 = unpooling(ftm2) ftm1 = torch.cat([self.feature_merging_branch[3](ftm2), fte1], dim=1) ftm1 = unpooling(ftm1) merged_features = self.feature_merging_branch[4](ftm1) score_map = torch.nn.functional.sigmoid(self.score_map_conv(merged_features)) if self.kind == 'quad': geometry = self.quad_conv(merged_features) return {'score_map': score_map, 'geometry': geometry} <file_sep>/datasets/debug_dataset.py from torch.utils.data import Dataset from . import dataset_utils from PIL import Image import numpy as np import os class DebugDataset(Dataset): def __init__(self, data_path, split='train', transform=None): self.data_path = data_path self.split = split self.transform = transform self.datafiles = self.generate_files() def generate_files(self): gt_path = os.path.join(self.data_path, self.split, 'gt') img_path = os.path.join(self.data_path, self.split, 'img') id_range = range(1, len(os.listdir(img_path)) + 1) img_files = ["img_{}.jpg".format(idx) for idx in id_range] gt_files = ["gt_{}.txt".format(idx) for idx in id_range] img_files = [os.path.join(img_path, img) for img in img_files] gt_files = [os.path.join(gt_path, gt) for gt in gt_files] return list(zip(img_files, gt_files)) def __len__(self): return len(self.datafiles) def __getitem__(self, index): img_file, gt_file = self.datafiles[index] img = np.array(Image.open(img_file)) bboxes = dataset_utils.read_gt(gt_file) # TODO vectorize me for i in range(len(bboxes)): bboxes[i] = dataset_utils.bbox_order(bboxes[i]) sample = {"image": img, "bbox": bboxes} if self.transform: sample = self.transform(sample) return sample <file_sep>/datasets/augmentations.py from . import dataset_utils import numpy as np class RBOX: def __init__(self, scale=0.15): self.scale = scale def __call__(self, sample): image, bboxes = sample['image'], sample['bbox'] bbox_map = np.zeros(image.shape[:2]) dist_map = np.zeros(list(image.shape[:2]) + [2]) for bbox in bboxes: rectangle_bbox = dataset_utils.generate_minimum_quad_orthogon(bbox) croped_bbox = dataset_utils.shrink_bbox(rectangle_bbox, scale=self.scale) bb_interior = dataset_utils.generate_bbox_interion(croped_bbox, image.shape[:2]) distances = dataset_utils.rectangle_borders_distances(croped_bbox, bb_interior) bbox_map[bb_interior[:, 1], bb_interior[:, 0]] = 1 dist_map[bb_interior[:, 1], bb_interior[:, 0]] = distances.T return {"image": image, "bbox_map": bbox_map, "distances_map": dist_map} class QUAD: def __init__(self, scale=0.15): self.scale = scale def __call__(self, sample): image, bboxes = sample['image'], sample['bbox'] bbox_map = np.zeros(image.shape[:2]) quad_formatting = np.zeros(list(image.shape[:2]) + [8]) ignore_map = np.ones(image.shape[:2]) for bbox in bboxes: rectangle_bbox = dataset_utils.generate_minimum_quad_orthogon(bbox) crop_bbox = dataset_utils.shrink_bbox(rectangle_bbox, self.scale) bb_interior = dataset_utils.generate_bbox_interion(crop_bbox, image.shape[:2]) full_interior = dataset_utils.generate_bbox_interion(rectangle_bbox, image.shape[:2]) ignore_map[full_interior[:, 1], full_interior[:, 0]] = 0 ignore_map[bb_interior[:, 1], bb_interior[:, 0]] = 1 bbox_map[bb_interior[:, 1], bb_interior[:, 0]] = 1 quad = dataset_utils.quad_shifts(bbox, bb_interior) quad_formatting[bb_interior[:, 1], bb_interior[:, 0]] = quad return {"image": image, "bbox_map": bbox_map, "quad_formatting": quad_formatting, "ignore_map": ignore_map} class RandomCrop: def __init__(self, crop_size=(512, 512)): self.crop_size = crop_size def __call__(self, sample): image = sample['image'] bbox_map = sample['bbox_map'] quad_formatting = sample['quad_formatting'] ignore_map = sample['ignore_map'] new_x_b = np.random.randint(0, image.shape[1] - self.crop_size[1]) new_y_b = np.random.randint(0, image.shape[0] - self.crop_size[0]) new_x_e = new_x_b + self.crop_size[1] new_y_e = new_y_b + self.crop_size[0] new_sample = {"image": image[new_y_b:new_y_e, new_x_b:new_x_e, :], "bbox_map": bbox_map[new_y_b:new_y_e, new_x_b:new_x_e], "quad_formatting": quad_formatting[new_y_b:new_y_e, new_x_b:new_x_e, :], "ignore_map": ignore_map[new_y_b:new_y_e, new_x_b:new_x_e]} return new_sample class Normalize: def __init__(self): self.imagenet_stats = {'mean': np.array([0.485, 0.456, 0.406]), 'std': np.array([0.229, 0.224, 0.225])} def __call__(self, sample): image = sample['image'].astype('float32') / 255 bbox_map = sample['bbox_map'] quad_formatting = sample['quad_formatting'] ignore_map = sample['ignore_map'] image -= self.imagenet_stats['mean'].reshape(1, 1, 3) image /= self.imagenet_stats['std'].reshape(1, 1, 3) new_sample = {"image": image, "bbox_map": bbox_map, "quad_formatting": quad_formatting, "ignore_map": ignore_map} return new_sample
057eefc8b0190dd55b57dce2959ebf4bf7b8f60e
[ "Markdown", "Python" ]
9
Python
nikitadurasov/EAST_pytorch
52a8203064218c91ee7f5e1d14b55a3d01f0b122
4597714289a32f0c1af0cfb64e71ae0fbed8fc27
refs/heads/main
<file_sep>package ecftech.constructor; public class Item { // 名前 String name; // 値段 int price; public Item(String name, int price) { this.name = name; this.price = price; } public void display () { System.out.println(name + ":" + price + "円"); } }
aa83aba648b673c1d2c09e7d354159aeeac8794d
[ "Java" ]
1
Java
KanonShinoda/java_practice
622c8b751ad35c12a7c40a34fe33fa464a060fe4
aeedfed772870d1b795025c972d0fb69cbad7171
refs/heads/master
<file_sep>FROM golang:1.8.3-alpine as builder WORKDIR /go/src/packagetree COPY . . RUN go test -cover ./... \ && go build -o reposerver cmd/reposerver/reposerver.go FROM alpine:3.6 EXPOSE 8080 WORKDIR /run/ COPY --from=builder /go/src/packagetree/reposerver . RUN apk --no-cache add ca-certificates USER nobody ENTRYPOINT ["./reposerver"]<file_sep>package graph import ( "testing" ) func newGraph(t *testing.T) *TreeGraph { g, err := NewGraph() if err != nil { t.Error("Failed to create new graph") } return g } func TestExists(t *testing.T) { g := newGraph(t) g.Add("boo") if exists := g.Exists("boo"); !exists { t.Errorf("Node does not exist after adding to graph") } if exists := g.Exists("bar"); exists { t.Errorf("Node should not exist in graph") } } func TestAdd(t *testing.T) { g := newGraph(t) var errResult bool var tests = []struct { name string edges []string errShouldBeNil bool }{ {name: "boo", errShouldBeNil: true}, {name: "boo", edges: []string{"foo,bar"}, errShouldBeNil: false}, {name: "foo", errShouldBeNil: true}, {name: "bar", errShouldBeNil: true}, {name: "boo", edges: []string{"foo"}, errShouldBeNil: true}, {name: "boo", edges: []string{"foo", "bar"}, errShouldBeNil: true}, } for _, test := range tests { err := g.Add(test.name, test.edges...) if err == nil { errResult = true } else { errResult = false } if errResult != test.errShouldBeNil { t.Errorf("Add(%q, %q) = %v", test.name, test.edges, err) } } } func TestRemoveEmpty(t *testing.T) { g := newGraph(t) var errResult bool var tests = []struct { name string shouldBeNil bool }{ {name: "boo", shouldBeNil: true}, {name: "foo", shouldBeNil: true}, {name: "bar", shouldBeNil: true}, } for _, test := range tests { err := g.Remove(test.name) if err == nil { errResult = true } else { errResult = false } if errResult != test.shouldBeNil { t.Errorf("Remove(%q) = %v", test.name, err) } } } func TestRemove(t *testing.T) { g := newGraph(t) var errResult bool var addPackages = []struct { name string edges []string }{ {name: "boo"}, {name: "foo"}, {name: "bar"}, {name: "bar2"}, {name: "zap", edges: []string{"bar", "bar2"}}, } var removePackages = []struct { name string errShouldBeNil bool }{ {name: "boo", errShouldBeNil: true}, {name: "foo", errShouldBeNil: true}, {name: "zap", errShouldBeNil: false}, {name: "bar", errShouldBeNil: true}, {name: "bar2", errShouldBeNil: true}, {name: "zap", errShouldBeNil: true}, } for _, p := range addPackages { g.Add(p.name, p.edges...) } for _, test := range removePackages { err := g.Remove(test.name) if err == nil { errResult = true } else { errResult = false } if errResult != test.errShouldBeNil { t.Errorf("Remove(%q) = %v", test.name, err) } } } <file_sep># Coding Assignment # Requirements - Not to use any library apart from your chosen runtime's standard library - Code must pass the supplied test harness using different random seeds and concurrency factor up to 100 The system you are going to write keeps track of package dependencies. Clients will connect to your server and inform which packages should be indexed, and which dependencies they might have on other packages. We want to keep our index consistent, so your server must not index any package until all of its dependencies have been indexed first. The server should also not remove a package if any other packages depend on it. The server will open a TCP socket on port 8080. It must accept connections from multiple clients at the same time, all trying to add and remove items to the index concurrently. Clients are independent of each other, and it is expected that they will send repeated or contradicting messages. New clients can connect and disconnect at any moment, and sometimes clients can behave badly and try to send broken messages. Messages from clients follow this pattern: ``` <command>|<package>|<dependencies>\n ``` Where: * `<command>` is mandatory, and is either `INDEX`, `REMOVE`, or `QUERY` * `<package>` is mandatory, the name of the package referred to by the command, e.g. `mysql`, `openssl`, `pkg-config`, `postgresql`, etc. * `<dependencies>` is optional, and if present it will be a comma-delimited list of packages that need to be present before `<package>` is installed. e.g. `cmake,sphinx-doc,xz` * The message always ends with the character `\n` Here are some sample messages: ``` INDEX|cloog|gmp,isl,pkg-config\n INDEX|ceylon|\n REMOVE|cloog|\n QUERY|cloog|\n ``` For each message sent, the client will wait for a response code from the server. Possible response codes are `OK\n`, `FAIL\n`, or `ERROR\n`. After receiving the response code, the client can send more messages. The response code returned should be as follows: * For `INDEX` commands, the server returns `OK\n` if the package can be indexed. It returns `FAIL\n` if the package cannot be indexed because some of its dependencies aren't indexed yet and need to be installed first. If a package already exists, then its list of dependencies is updated to the one provided with the latest command. * For `REMOVE` commands, the server returns `OK\n` if the package could be removed from the index. It returns `FAIL\n` if the package could not be removed from the index because some other indexed package depends on it. It returns `OK\n` if the package wasn't indexed. * For `QUERY` commands, the server returns `OK\n` if the package is indexed. It returns `FAIL\n` if the package isn't indexed. * If the server doesn't recognize the command or if there's any problem with the message sent by the client it should return `ERROR\n`. # Package Server Utilizes a simple graph to index packages. TCP Server can be configured using the ENV_VAR `PACKAGE_PORT` to listen for connections, defaults to 8080. Utilizes channels and go-routines to handle long living connections. Connections that do not write will be closed by the default amount of time (10seconds), can be configured using ENV_VAR `PACKAGE_CONNECTION_TIMEOUT`. The TCP Server will attempt to exit cleanly upon receiving SIGINT or SIGTERM. To use a different backend you must have a type that adheres to: ```go type Backend interface { Exists(name string) bool Add(name string, edges ...string) error Remove(name string) error } ``` The repository manager will handle read/write locking of the backend so you do not to directly make it go routine safe. The backend must be supplied to the server as part of a configuration. ##Add additional commands To add additional commands you must adhere to the the interface in repomanager.go: ```go type Operation interface { Run() (string, error) GetCommand() string } ``` And update: `func validateAndCreateOperator(instruction *instruction, repo *Repo) Operation {}` which returns an Operator type to perform the corresponding action. Read and write locks should be use whenever interacting with the backend type. Example with Query: ```go const QUERY string = "QUERY" type QueryOperator struct { instruction *instruction repo *Repo } func NewQueryOperator(instruction *instruction, repo *Repo) *QueryOperator { return &QueryOperator{ instruction: instruction, repo: repo, } } func (o QueryOperator) Run() (string, error) { o.repo.mu.RLock() exists := o.repo.backend.Exists(o.instruction.packageName) o.repo.mu.RUnlock() if exists { return OK, nil } return FAIL, nil } func (o QueryOperator) GetCommand() string { return o.instruction.cmd } ``` ## Build ``` make ``` ## Test Unit + Integration ``` make test ``` ## Docker ``` make build.docker ``` ## Built with - Golang 1.8.3 - Docker 17.06.0-ce - golang:1.8.3-alpine (Docker build step) - alpine:3.6 (Docker artifact step)<file_sep>package server import ( "fmt" "math/rand" "net" "syscall" "testing" "time" ) type MockConnectionHandler struct { } func (mch *MockConnectionHandler) Handle(conn net.Conn) { conn.Close() } func random(min, max int) int { rand.Seed(time.Now().Unix() + 1) return rand.Intn(max-min) + min } func serverSetup(port int, t *testing.T) *Configuration { mch := &MockConnectionHandler{} configuration := NewServerConfiguration(mch, port+1, 1, 10) go func() { err := Listen(configuration) if err != nil { t.Fatal(err) } }() time.Sleep(1 * time.Second) return configuration } func TestListenSignal(t *testing.T) { port := random(1025, 9999) configuration := serverSetup(port, t) configuration.SignalChannel <- syscall.SIGINT } func TestListenClose(t *testing.T) { port := random(1025, 9999) configuration := serverSetup(port, t) close(configuration.ConnectionChannel) } func TestListenPortTaken(t *testing.T) { port := random(1025, 9999) configuration := serverSetup(port, t) err := Listen(configuration) if err == nil { t.Fatal("Port should be in use and server retuning error") } } func TestListenMessagesClose(t *testing.T) { port := random(1025, 9999) serverSetup(port, t) var connections = []struct { rawCommand string }{ {"QUERY|boo|"}, } c, err := net.Dial("tcp", fmt.Sprintf(":%v", port+1)) if err != nil { t.Fatalf("Failed to establish connection to repo server") } defer c.Close() for _, connection := range connections { _, err = fmt.Fprintln(c, connection.rawCommand) } } <file_sep>package graph import ( "errors" "fmt" ) const ( NODE_NOT_FOUND string = "Node not found" ) type Node struct { name string edges []*Node } type TreeGraph struct { tree map[string]*Node } //Creates an empty TreeGraph type func NewGraph() (*TreeGraph, error) { return &TreeGraph{ tree: make(map[string]*Node), }, nil } //If the name exists return the Node, other wise return empty Node struct with error func (g *TreeGraph) Get(name string) (Node, error) { if g.Exists(name) { return *g.tree[name], nil } else { return Node{}, errors.New(fmt.Sprintf("%s:%s", NODE_NOT_FOUND, name)) } } //Return true or false if name exists in graph func (g *TreeGraph) Exists(name string) bool { _, exists := g.tree[name] return exists } //Performs actual insert/update against graph func (g *TreeGraph) addNode(node *Node) { g.tree[node.name] = node g.addEdge(node) } //Attempts to add new name, will check that dependencies exist if all exist node will be added, //otherwise and error is returned func (g *TreeGraph) Add(name string, edges ...string) error { var edgeNodes []*Node if len(edges) >= 1 { for _, edge := range edges { n, err := g.Get(edge) if err == nil { edgeNodes = append(edgeNodes, &n) } else { return errors.New(fmt.Sprintf("%s:%s", NODE_NOT_FOUND, edge)) } } } tempNode := &Node{ name: name, edges: edgeNodes, } g.addNode(tempNode) return nil } //Performs removal of node func (g *TreeGraph) removeNode(name string) { delete(g.tree, name) } //Attempts to remove name from graph as long as no dependencies require it func (g *TreeGraph) Remove(name string) error { if g.Exists(name) { for _, edge := range g.tree[name].edges { if g.Exists(edge.name) { for _, e := range edge.edges { if e.name == name { return errors.New(fmt.Sprintf("Dependency with:%s exists cannot remove:%s", edge.name, name)) } } } else { continue } } g.removeNode(name) return nil } else { return nil } } //Links nodes together as edges func (g *TreeGraph) addEdge(node *Node) { var temp []*Node for _, edgeNode := range node.edges { edgeNode.edges = temp edgeNode.edges = append(edgeNode.edges, node) } } <file_sep>package repomanager const INDEX string = "INDEX" type IndexOperator struct { instruction *instruction repo *Repo } func NewIndexOperator(instruction *instruction, repo *Repo) *IndexOperator { return &IndexOperator{ instruction: instruction, repo: repo, } } func (o IndexOperator) Run() (string, error) { o.repo.mu.Lock() err := o.repo.backend.Add(o.instruction.packageName, o.instruction.packageDependencies...) o.repo.mu.Unlock() if err != nil { return FAIL, nil } return OK, nil } func (o IndexOperator) GetCommand() string { return o.instruction.cmd } <file_sep>package server import ( "fmt" "github.com/jrxfive/packagetree/pkg/logging" "net" "os" "os/signal" "sync" "syscall" "time" ) var logger = logging.GetLogger() type ConnectionHandler interface { Handle(conn net.Conn) } type Configuration struct { Handler ConnectionHandler Port int MaxHerd int Timeout time.Duration ConnectionChannel chan net.Conn SignalChannel chan os.Signal mu sync.RWMutex } //Creates and returns a new configuration that can has a net.Conn Handler. The //port to bind the TCP server to, how large the buffer should be for simultaneous connections //to the connection channel. func NewServerConfiguration(handler ConnectionHandler, port, maxHerd, timeout int) *Configuration { signalChannel := make(chan os.Signal, 1) connChannel := make(chan net.Conn, maxHerd) return &Configuration{ Handler: handler, Port: port, Timeout: time.Duration(timeout), MaxHerd: maxHerd, ConnectionChannel: connChannel, SignalChannel: signalChannel, mu: sync.RWMutex{}, } } //Binds a TCP server to handle connections for anything that use the interface ConnectionHandler. Will //close the server and channel on SIGINT or SIGTERM. func Listen(sc *Configuration) error { signal.Notify(sc.SignalChannel, syscall.SIGINT, syscall.SIGTERM) channelBreaker := false listener, err := net.Listen("tcp", fmt.Sprintf(":%v", sc.Port)) if err != nil { return err } go func(listener net.Listener, connChannel chan net.Conn, signalChannel chan os.Signal) { for { select { case s := <-signalChannel: logger.Printf("Signal:%v received closing channel and listener\n", s) close(connChannel) listener.Close() case conn, ok := <-connChannel: if ok { err = conn.SetDeadline(time.Now().Add(time.Second * sc.Timeout)) if err != nil { conn.Close() } else { go sc.Handler.Handle(conn) } } else { sc.mu.Lock() channelBreaker = true sc.mu.Unlock() } } } }(listener, sc.ConnectionChannel, sc.SignalChannel) for { conn, err := listener.Accept() if err != nil { sc.mu.RLock() if channelBreaker { sc.mu.RUnlock() break } sc.mu.RUnlock() } sc.mu.RLock() if !channelBreaker { sc.ConnectionChannel <- conn } sc.mu.RUnlock() } return nil } <file_sep>package repomanager const REMOVE string = "REMOVE" type RemoveOperator struct { instruction *instruction repo *Repo } func NewRemoveOperator(instruction *instruction, repo *Repo) *RemoveOperator { return &RemoveOperator{ instruction: instruction, repo: repo, } } func (o RemoveOperator) Run() (string, error) { o.repo.mu.Lock() err := o.repo.backend.Remove(o.instruction.packageName) o.repo.mu.Unlock() if err != nil { return FAIL, nil } return OK, nil } func (o RemoveOperator) GetCommand() string { return o.instruction.cmd } <file_sep>CONTAINER_NAME=package-server SERVER_DIR_NAME=reposerver .PHONY: build .PHONY: fmt .PHONY: vet .PHONY: docker.build .PHONY: test.unit .PHONY: test .PHONY: clean build: fmt vet reposerver fmt: go $@ ./... vet: go $@ ./... reposerver: go build -o $(SERVER_DIR_NAME) cmd/$(SERVER_DIR_NAME)/reposerver.go client: cd cmd/$(CLIENT_DIR_NAME); go build -o client && cp client ../.. build.docker: docker build -t $(CONTAINER_NAME) . test: test.unit test.unit: fmt vet go test -cover ./... clean: -rm reposerver -rm client -rm packagetree.zip <file_sep>package repomanager const QUERY string = "QUERY" type QueryOperator struct { instruction *instruction repo *Repo } func NewQueryOperator(instruction *instruction, repo *Repo) *QueryOperator { return &QueryOperator{ instruction: instruction, repo: repo, } } func (o QueryOperator) Run() (string, error) { o.repo.mu.RLock() exists := o.repo.backend.Exists(o.instruction.packageName) o.repo.mu.RUnlock() if exists { return OK, nil } return FAIL, nil } func (o QueryOperator) GetCommand() string { return o.instruction.cmd } <file_sep>package logging import ( "log" "os" ) var logger = &log.Logger{} var instantiatedCheck bool = false func GetLogger() *log.Logger { if instantiatedCheck == false { instantiatedCheck = true logger = log.New(os.Stdout, "", log.Ldate|log.Ltime|log.Llongfile) return logger } else { return logger } } <file_sep>package repomanager import ( "bytes" "errors" "fmt" "net" "regexp" "strings" "sync" "unicode" ) const ( plusSignCharacterValue = 43 OK = "OK" FAIL = "FAIL" ERROR = "ERROR" ) var allowedCharacters = regexp.MustCompile(`([a-zA-z\_\-\+\.\d]+)`) type Backend interface { Exists(name string) bool Add(name string, edges ...string) error Remove(name string) error } type Repo struct { backend Backend mu *sync.RWMutex } type Operation interface { Run() (string, error) GetCommand() string } type instruction struct { cmd string packageName string packageDependencies []string } func NewRepo(graph Backend) *Repo { return &Repo{ backend: graph, mu: &sync.RWMutex{}, } } func createInstructionSet(input []byte) (*instruction, error) { var CMD_INDEX int = 0 var PACKAGE_NAME_INDEX int = 1 var DEPENDENCY_INDEX int = 2 trimmedInput := bytes.Trim(input, "\n") delimit := bytes.Split(trimmedInput, []byte{'|'}) if len(delimit) == 3 { return &instruction{ cmd: string(delimit[CMD_INDEX]), packageName: string(delimit[PACKAGE_NAME_INDEX]), packageDependencies: getDependencyPackages(delimit[DEPENDENCY_INDEX]), }, nil } else { return &instruction{}, errors.New(fmt.Sprintf("Invalid Protocol Specification")) } } func getDependencyPackages(dependencies []byte) []string { var dep []string if len(dependencies) > 0 { r := strings.SplitN(string(dependencies), ",", -1) dep = r } return dep } func validatePackage(packageName string) error { packageNameLength := len(packageName) allowedCharactersMatches := allowedCharacters.FindAllString(packageName, -1) if len(allowedCharactersMatches) != 1 { return errors.New("Package can only contain a-zA-Z9+-_.") } if check := strings.Contains(packageName, "+"); check { for idx, char := range packageName { if unicode.IsSymbol(char) { if char == plusSignCharacterValue { if idx == packageNameLength-1 { break } if idx < packageNameLength-1 { nextChar := packageName[idx+1] if unicode.IsLetter(int32(nextChar)) { if !strings.Contains(packageName, "-") { return errors.New("Package name should be split by '-'") } else { return nil } } } } } } } return nil } func validateDependencies(dependencies []string) error { for _, dependency := range dependencies { return validatePackage(dependency) } return nil } func validateAndCreateOperator(instruction *instruction, repo *Repo) Operation { err := validatePackage(instruction.packageName) if err != nil { return NewUnknownOperator() } err = validateDependencies(instruction.packageDependencies) if err != nil { return NewUnknownOperator() } switch instruction.cmd { case INDEX: return NewIndexOperator(instruction, repo) case REMOVE: return NewRemoveOperator(instruction, repo) case QUERY: return NewQueryOperator(instruction, repo) default: return NewUnknownOperator() } } //Handles TCP connections for the repo manager. Will set a read dead line before //serving the connection to avoid stale connections. The buffer is set to 1024 bytes //this could have been more dynamic by using bufio instead of a static limit. After //receiving and creating an instruction set it will run the corresponding command and //return the value based on the backend. func (r *Repo) Handle(conn net.Conn) { for { //err := conn.SetReadDeadline(time.Now().Add(time.Second * time.Duration(r.readTimeout))) //if err != nil { // conn.Close() // break //} buffer := make([]byte, 1024) bufferLength, err := conn.Read(buffer) if err != nil { conn.Close() break } instruction, err := createInstructionSet(buffer[:bufferLength]) if err != nil { fmt.Fprintln(conn, ERROR) continue } operator := validateAndCreateOperator(instruction, r) output, err := operator.Run() _, err = fmt.Fprintln(conn, output) if err != nil { conn.Close() } } } <file_sep>package repomanager type UnknownOperator struct { instruction *instruction } func NewUnknownOperator() *UnknownOperator { return &UnknownOperator{ instruction: &instruction{ cmd: ERROR, }, } } func (o UnknownOperator) Run() (string, error) { return ERROR, nil } func (o UnknownOperator) GetCommand() string { return o.instruction.cmd } <file_sep>package main import ( "github.com/jrxfive/packagetree/pkg/graph" "github.com/jrxfive/packagetree/pkg/logging" "github.com/jrxfive/packagetree/pkg/repomanager" "github.com/jrxfive/packagetree/pkg/server" "os" "strconv" ) var PORT int = 8080 var MAX_HERD int = 10 var CONNECTION_TIMEOUT = 10 var logger = logging.GetLogger() func init() { if envPort, ok := os.LookupEnv("PACKAGE_PORT"); ok { value, err := strconv.Atoi(envPort) if err != nil { } else { PORT = value } } if envMaxHerd, ok := os.LookupEnv("PACKAGE_MAX_HERD"); ok { value, err := strconv.Atoi(envMaxHerd) if err != nil { } else { MAX_HERD = value } } if envConnTimeout, ok := os.LookupEnv("PACKAGE_CONNECTION_TIMEOUT"); ok { value, err := strconv.Atoi(envConnTimeout) if err != nil { } else { CONNECTION_TIMEOUT = value } } logger.Printf("Starting new server on port:%v\n", PORT) logger.Printf("MAX_HERD set to:%v\n", MAX_HERD) logger.Printf("Connection timeout set to:%v\n", CONNECTION_TIMEOUT) } func main() { g, err := graph.NewGraph() if err != nil { os.Exit(1) } repo := repomanager.NewRepo(g) serverConfiguration := server.NewServerConfiguration(repo, PORT, MAX_HERD, CONNECTION_TIMEOUT) err = server.Listen(serverConfiguration) if err != nil { os.Exit(1) } os.Exit(0) } <file_sep>package repomanager import ( "errors" "fmt" "github.com/jrxfive/packagetree/pkg/server" "math/rand" "net" "testing" "time" ) type MockBackend struct { } func (mb *MockBackend) Exists(name string) bool { if name == "generate-error" { return false } return true } func (mb *MockBackend) Add(name string, edges ...string) error { if name == "generate-error" { return errors.New("error") } return nil } func (mb *MockBackend) Remove(name string) error { if name == "generate-error" { return errors.New("error") } return nil } func random(min, max int) int { rand.Seed(time.Now().Unix()) return rand.Intn(max-min) + min } func TestValidatePackage(t *testing.T) { var tests = []struct { input string expected bool }{ {"cless", false}, {"clang-omp", false}, {"gnome-doc-utils", false}, {"emacs=elisp", true}, {"emacs-elisp++", false}, {"emacs+elisp", true}, {"emacs elisp", true}, {"dvd+rw-tools", false}, {"g++", false}, } for _, test := range tests { err := validatePackage(test.input) var errResult bool if err == nil { errResult = false } else { errResult = true } if errResult != test.expected { t.Errorf("validatePackage(%q) = %v", test.input, err) } } } func TestValidateAndCreateOperator(t *testing.T) { r := NewRepo(&MockBackend{}) var tests = []struct { instruction *instruction repo *Repo expectedCommand string }{ {&instruction{"INDEX", "emacs=elisp", []string{}}, r, "ERROR"}, {&instruction{"INDEX", "g++", []string{}}, r, "INDEX"}, {&instruction{"INDEX", "g++", []string{"ba+r"}}, r, "ERROR"}, {&instruction{"INDE", "g++", []string{}}, r, "ERROR"}, {&instruction{"QUERY", "g++", []string{}}, r, "QUERY"}, {&instruction{"QUERY", "g++", []string{"bar"}}, r, "QUERY"}, {&instruction{"QUERY", "emacs=elisp", []string{}}, r, "ERROR"}, {&instruction{"QRY", "g++", []string{}}, r, "ERROR"}, {&instruction{"REMOVE", "g++", []string{}}, r, "REMOVE"}, {&instruction{"REMOVE", "g++", []string{"bar"}}, r, "REMOVE"}, {&instruction{"REMOV", "emacs=elisp", []string{}}, r, "ERROR"}, {&instruction{"REM", "g++", []string{}}, r, "ERROR"}, } for _, test := range tests { if output := validateAndCreateOperator(test.instruction, test.repo); output.GetCommand() != test.expectedCommand { t.Errorf("validateAndCreateOperator(%#v) = %s, expected:%s", test.instruction, output.GetCommand(), test.expectedCommand) } } } func TestCreateInstructionSet(t *testing.T) { var instructions = []struct { rawInstruction []byte expectedCMD string expectedPackageName string expectedDependencyLength int expectedErrResult bool }{ {[]byte("INDEX|boo|\n"), "INDEX", "boo", 0, false}, {[]byte("INDEX|boo|foo\n"), "INDEX", "boo", 1, false}, {[]byte("INDEX|boo|foo,bar\n"), "INDEX", "boo", 2, false}, {[]byte("QUERY"), "", "", 0, true}, } for _, instruct := range instructions { var errResult bool i, err := createInstructionSet(instruct.rawInstruction) if err == nil { errResult = false } else { errResult = true } if errResult != instruct.expectedErrResult { t.Errorf("createInstructionSet(%q) = %q, expected:%v", i, err, instruct.expectedErrResult) } if i.cmd != instruct.expectedCMD { t.Errorf("createInstructionSet(%q) = %v, expected:%v", i, string(i.cmd), instruct.expectedCMD) } if i.packageName != instruct.expectedPackageName { t.Errorf("createInstructionSet(%q) = %v, expected:%v", i, string(i.packageName), instruct.expectedPackageName) } if len(i.packageDependencies) != instruct.expectedDependencyLength { t.Errorf("createInstructionSet(%q) = %v, expected:%v", i, len(i.packageDependencies), instruct.expectedDependencyLength) } } } func TestHandle(t *testing.T) { port := random(1025, 9999) go func() { r := NewRepo(&MockBackend{}) configuration := server.NewServerConfiguration(r, port, 1, 10) err := server.Listen(configuration) if err != nil { fmt.Println(err) t.Fatal(err) } }() time.Sleep(1 * time.Second) var connections = []struct { rawCommand string expectedReturnValue string shouldCloseBeforeReturn bool }{ {"INDEX|boo|", OK, false}, {"QUERY|boo|", OK, false}, {"REMOVE|boo|", OK, false}, {"REMOVE|boo|extra|", ERROR, false}, {"INDEX|generate-error|", FAIL, false}, {"QUERY|generate-error|", FAIL, false}, {"REMOVE|generate-error|", FAIL, false}, {"REMOVE|boo|", "", true}, } c, err := net.Dial("tcp", fmt.Sprintf(":%v", port)) if err != nil { t.Fatalf("Failed to establish connection to repo server") } defer c.Close() for _, connection := range connections { _, err = fmt.Fprintln(c, connection.rawCommand) if err != nil { t.Error(err) } if connection.shouldCloseBeforeReturn { c.Close() continue } c.SetReadDeadline(time.Now().Add(time.Second * 3)) buffer := make([]byte, 1024) bufferLength, err := c.Read(buffer) if err != nil { c.Close() t.Error(err) } if string(buffer[:bufferLength]) != fmt.Sprintf("%s\n", connection.expectedReturnValue) { t.Errorf("Command:%s Expected:%s Got:%s", connection.rawCommand, connection.expectedReturnValue, string(buffer[:bufferLength])) } } c.Close() }
e527b21d3e217bcd7cbeb788c054e133daa5b064
[ "Markdown", "Go", "Dockerfile", "Makefile" ]
15
Dockerfile
michalskiluc/packagetree
752f177e5981fcbcfda439a65603ecbb1174e8f2
028823e02d111820028dccbb166f497386aebb54
refs/heads/master
<file_sep><?php namespace Tests\Roku; use \Roku\Commands\Sensor; use PHPUnit\Framework\TestCase; class SensorTest extends TestCase { public function setUp() { parent::setUp(); } public function testEmpty() { $this->assertTrue(Sensor::hasName("rotation")); $this->assertFalse(Sensor::hasName("nosensor")); } } <file_sep><?php namespace Roku\Console; /** * Console * */ class Console { /** * Roku Instance * @var \Roku\Roku */ private $roku; public function start() { $options = getopt("h:p:d:c:it", array("help")); $host = isset($options["h"]) ? $options["h"] : "127.0.0.1"; $port = isset($options["p"]) ? $options["p"] : 8060; $delay = isset($options["d"]) ? $options["d"] : 1.3; if(isset($options["help"])) { $this->help(); } else { $this->roku = new \Roku\Roku($host, $port, $delay); if(isset($options["t"])) { $this->roku->setClient(new \Roku\Utils\HttpConsole()); } if(isset($options["i"])) { try { $this->interactive(); } catch(\Exception $e) { echo "Error " . $e->getMessage(); echo "\n"; } } elseif(isset($options["c"])) { try { $this->commands($options["c"]); } catch(\Exception $e) { echo "Error " . $e->getMessage(); echo "\n"; } } else { $this->help(); } } } public function commands($commands) { $commands = explode(" ", $commands); foreach($commands as $command) { if(\Roku\Commands\Command::hasName($command)) { $this->roku->$command(); } else { $this->roku->literals($command); } } } public function interactive() { system("stty -icanon"); while ($c = (fread(STDIN, 4))) { $key = $c; echo "\n"; echo ord($c); try { //Special Keys if(ord($c) == 27) { if(strpos($c, '[')) { if(strpos($c, 'B')) { $this->roku->down(); } else if(strpos($c, 'A')) { $this->roku->up(); } else if(strpos($c, 'D')) { $this->roku->left(); } else if(strpos($c, 'C')) { $this->roku->right(); } else { } } if(strpos($c, 'O')) { if(strpos($c, 'H')) { $this->roku->home(); } elseif(strpos($c, 'F')) { $this->roku->back(); } } if(strpos($c, '5')) { $this->roku->fwd(); } if(strpos($c, '6')) { $this->roku->info(); } } elseif(ord($c) == 10) { $this->roku->select(); } else { $this->roku->lit($key); } } catch(\Exception $e) { echo "Not registered keystroke - " . $key; } } } private function help() { echo <<<EOT PHP Roku Console Usage: roku [OPTION] .. -h <host> Host -p <port> Port -d <delay> Delay between each command -i Interactive mode (Listens for keyboard keystrokes) -c <commands> Command mode (Specify commands to be executed, Example -c "up down <EMAIL> down select home") -t Test Mode (Does not send commands.Just simulates them.) --help Shows this help EOT; } }<file_sep><?php namespace Roku\Utils; /** * Abstract Enum Class * */ abstract class AbstractEnum { /** * Constants cache * @var array */ private static $constCache = null; /** * Get All constants * * @return array */ private static function getConstants() { $class = get_called_class(); if (!isset(self::$constCache[$class])) { $reflect = new \ReflectionClass(get_called_class()); self::$constCache[$class] = $reflect->getConstants(); } return self::$constCache[$class]; } /** * Check if constant name exists * * @param string $name * @param string $strict * @return boolean */ public static function hasName($name, $strict = false) { $constants = self::getConstants(); if ($strict) { return array_key_exists($name, $constants); } $keys = array_map('strtolower', array_keys($constants)); return in_array(strtolower($name), $keys); } /** * Check if constant value exists * * @param string $name * @param string $strict * @return boolean */ public static function hasValue($value) { $values = array_values(self::getConstants()); return in_array($value, $values, $strict = true); } }<file_sep><?php namespace Tests\Roku; use \Roku\Commands\Command; use PHPUnit\Framework\TestCase; class CommandTest extends TestCase { public function setUp() { parent::setUp(); } public function testEmpty() { $this->assertTrue(Command::hasName("PLAY")); $this->assertTrue(Command::hasValue("Play")); $this->assertFalse(Command::hasName("nosuch")); $this->assertTrue(Command::hasName("PLAY")); } } <file_sep><?php namespace Roku\Commands; /** * * Orientation Options */ class Orientation extends \Roku\Utils\AbstractEnum { const ORIENTATION_X = "orientation.x"; const ORIENTATION_Y = "orientation.y"; const ORIENTATION_Z = "orientation.z"; } <file_sep><?php namespace Roku\Commands; /** * Magnetic Options */ class Magnetic extends \Roku\Utils\AbstractEnum { const MAGNETIC_X = "magnetic.x"; const MAGNETIC_Y = "magnetic.y"; const MAGNETIC_Z = "magnetic.z"; } <file_sep><?php namespace Roku\Commands; /** * Command * */ class Command extends \Roku\Utils\AbstractEnum { const PLAY = "Play"; const UP = "Up"; const DOWN = "Down"; const LEFT = "Left"; const RIGHT = "Right"; const HOME = "Home"; const SELECT = "Select"; const REV = "Rev"; const FWD = "Fwd"; const REPLAY = "InstantReplay"; const INFO = "Info"; const LIT = "Lit"; const BACK = "Back"; const BACKSPACE = "Backspace"; const SEARCH = "Search"; const ENTER = "Enter"; }<file_sep><?php namespace Roku; /** * Application */ class Application { /** * Id * @var string */ private $id; /** * Version * @var string */ private $version; /** * Name * @var string */ private $name; /** * Init * * @param string $id Id * @param string $version Version * @param string $name Name */ public function __construct($id, $version = "", $name = "") { $this->id = $id; $this->version = $version; $this->name = $name; } /** * Get Id * @return string */ public function getId() { return $this->id; } /** * Get Version * @return string */ public function getVersion() { return $this->version; } /** * Get Name * @return string */ public function getName() { return $this->name; } /** * Set Application Id * * @param string $id * @return \Roku\Application */ public function setId($id) { $this->id = $id; return $this; } /** * Set Version * @param string $version * @return \Roku\Application */ public function setVersion($version) { $this->version = $version; return $this; } /** * Set Application Name * @param string $name * @return \Roku\Application */ public function setName($name) { $this->name = $name; return $this; } }<file_sep><?php namespace Roku\Commands; /** * Touch Options */ class Touch extends \Roku\Utils\AbstractEnum { const UP = "up"; const DOWN = "down"; const PRESS = "press"; const MOVE = "move"; const CANCEL = "cancel"; }<file_sep><?php namespace Roku\Commands; /** * Acceleration Options */ class Acceleration extends \Roku\Utils\AbstractEnum { const ACCELERATION_X = "acceleration.x"; const ACCELERATION_Y = "acceleration.y"; const ACCELERATION_Z = "acceleration.z"; }<file_sep>Roku PHP Library ================================================ [![Build Status](https://api.travis-ci.org/svilborg/php-roku.png?branch=master)](https://travis-ci.org/svilborg/php-roku) [![Latest Stable Version](https://poser.pugx.org/svilborg/php-roku/v/stable.png)](https://packagist.org/packages/svilborg/php-roku) [![Latest Unstable Version](https://poser.pugx.org/svilborg/php-roku/v/unstable.png)](https://packagist.org/packages/svilborg/php-roku) PHP Library for communication with Roku External Control Protocol Installation ================ Installing via Composer ----------------------- Install composer in a common location or in your project: ```bash curl -s http://getcomposer.org/installer | php ``` Create the composer.json file as follows: ```json { "require": { "svilborg/php-roku": "dev-master" } } ``` Run the composer installer: ```bash php composer.phar install ``` Requirements ============ * PHP Version >=5.3.2. * PHP Httpful Library Usage ===== Execute commands : ```php $roku = new \Roku\Roku("192.168.72.10", 8060, 0.2); $roku->up(); $roku->select(); $roku->literals("<EMAIL>"); $roku->down(); $roku->down(); $roku->select(); ``` List the applicatioin installed on the device : ```php $roku = new \Roku\Roku("192.168.72.10", 8060, 0.2); $applications = $roku->apps(); foreach ($applications as $application) { echo $application->getId(); echo $application->getVersion(); echo $application->getName(); echo "\n"; } ``` Get device information : ```php $roku = new \Roku\Roku("192.168.72.10", 8060, 0.2); $device = $roku->device(); echo $device->getSerialNumber(); echo $device->getModelName(); echo $device->getModelDescription(); // etc.. ``` Usage Commandline ================= For the list of commands execute : ```bash $ vendor/bin/roku --help ``` It displays : ```bash PHP Roku Console Usage: roku [OPTION] .. -h <host> Host -p <port> Port -d <delay> Delay between each command -i Interactive mode (Listens for keyboard keystrokes) -c <commands> Command mode (Specify commands to be executed, Example -c "up down <EMAIL> down select home") -t Test Mode (Does not send commands.Just simulates them.) --help Shows this help ``` Example usage of command and interactive modes : ```bash $ vendor/bin/roku -h 192.168.72.10 -p 8060 -d 1 -c "up <EMAIL> down down select home" $ vendor/bin/roku -h 192.168.72.10 -d 1 -i ``` Running the tests ================= First, install PHPUnit with `composer.phar install --dev`, then run `./vendor/bin/phpunit`. <file_sep><?php namespace Roku\Utils; class HttpConsole { /** * Get Request * * @param string $uri * @return \Httpful\Response */ public function get($uri, $params = array()) { if($params) { $uri .= "?" . http_build_query($params); } $this->output("GET : " . $uri); return new \Httpful\Response("", "HTTP/1.1 200 OK\r\n", \Httpful\Request::init()); } /** * Post Request * * @param string $uri * @return \Httpful\Response */ public function post($uri, $params = array()) { if($params) { $uri .= "?" . http_build_query($params); } $this->output("POST : " . $uri); return new \Httpful\Response("", "HTTP/1.1 200 OK\r\n", \Httpful\Request::init()); } private function output($string) { echo $string; echo "\n"; } }<file_sep><?php namespace Roku\Commands; /** * Rotation Options */ class Rotation extends \Roku\Utils\AbstractEnum { const ROTATION_X = "rotation.x"; const ROTATION_Y = "rotation.y"; const ROTATION_Z = "rotation.z"; }<file_sep><?php namespace Roku; use \Roku\Commands\Command; use \Roku\Commands\Sensor; use \Roku\Commands\Touch; /** * Roku Client */ class Roku { /** * Host * * @var string */ private $host; /** * Port * * @var integer */ private $port; /** * Roku Http Client * * @var \Roku\Utils\Http */ private $client; /** * Delay * * @var float */ private $delay; /** * Init * * @param string $host Host * @param number $port Port Number */ public function __construct($host, $port = null, $delay = 0) { $this->host = $host; $this->port = $port ? $port : 8060; $this->delay = $delay; $this->client = new \Roku\Utils\Http(); } /** * Set Client Instance * * @param \Roku\Utils\Http $client */ public function setClient($client) { $this->client = $client; } /** * Catchase all function calls * * @param string $name Function name * @param array $fargs Arguments */ public function __call($name, $fargs) { if (Command::hasName($name)) { if (strtoupper(Command::LIT) == strtoupper($name)) { $command = Command::LIT . "_" . ($fargs[0] ? urlencode($fargs[0]) : ""); return $this->keypress($command); } else { return $this->keypress($name); } } elseif (Sensor::hasName($name)) { $params = array(); $axis = array("x", "y", "z"); foreach($fargs as $i => $value) { $params[strtolower($name) . "." . $axis[$i]] = $value; } return $this->input($params); } else { throw new Exception("Command Not Found"); } } /** * Send text as multiple literal calls * * @param string $text Text * @throws Exception * @return void */ public function literals($text) { $chars = str_split($text); foreach ($chars as $char) { $this->lit($char); } } /** * Keypress * * @param string $command Command name * @throws Exception */ public function keypress($command) { $response = $this->client->post($this->getUri("keypress", $command)); $this->delay(); if ($response->code !== 200) { throw new Exception("Command Error - " . $command, $response->code); } return $response->raw_body; } /** * Keydown * * @param string $command Command name * @throws Exception */ public function keydown($command) { $response = $this->client->post($this->getUri("keydown", $command)); $this->delay(); if ($response->code !== 200) { throw new Exception("Command Error - " . $command, $response->code); } return $response->raw_body; } /** * Keyup * * @param string $command Command name * @throws Exception */ public function keyup($command) { $response = $this->client->post($this->getUri("keyup", $command)); $this->delay(); if ($response->code !== 200) { throw new Exception("Command Error - " . $command, $response->code); } return $response->raw_body; } /** * Get Device Information * * @throws Exception * @return \Roku\Device */ public function device() { $response = $this->client->get($this->getUri()); if ($response->code !== 200) { throw new Exception("Command Error - device", $response->code); } $deviceElement = simplexml_load_string($response->body); if ($deviceElement === false) { throw new Exception("Parse Error"); } $device = new Device(); $device->init($deviceElement->device); return $device; } /** * Get Applications * * @throws Exception * @return array:\Roku\Application */ public function apps() { $response = $this->client->get($this->getUri("query", "apps")); if ($response->code !== 200) { throw new Exception("Command Error - apps", $response->code); } $apps = simplexml_load_string($response->body); if ($apps === false) { throw new Exception("Parse Error"); } $result = array(); foreach ($apps as $app) { $id = (string) $app->attributes()->id; $version = (string) $app->attributes()->version; $name = (string) $app; $result[] = new Application($id, $version, $name); } return $result; } /** * Get Application Icon * * @param Application $app * @throws Exception */ public function icon(Application $app) { $response = $this->client->get($this->getUri("query", "icon", $app->getId())); if ($response->code !== 200) { throw new Exception("Command Error - icon"); } return $response->raw_body; } /** * Launch Application * * @param Application $app * Application * @param array $params * Params * @throws Exception * * @return string */ public function launch(Application $app, $params = array()) { $response = $this->client->post($this->getUri("launch", $app->getId()), $params); if ($response->code !== 200) { if ($response->code == 204) { throw new Exception("Application already launched"); } elseif ($response->code == 204) { throw new Exception("Application Not Found"); } else { throw new Exception("Command Error - launch"); } } return $response->raw_body; } /** * Send raw input command * * @param array $params * @throws Exception * @return string */ public function input($params = array()) { $response = $this->client->post($this->getUri("input"), $params); if ($response->code !== 200) { throw new Exception("Command Error - input"); } return $response->raw_body; } /** * Touch * * @param string $x * @param string $y * @param string $op * * @throws Exception * @return string */ public function touch($x =0, $y = 0, $op = Touch::DOWN) { $params = array(); if (!Touch::hasName($op)) { throw new Exception("Touch Option Not Found - " . $op); } $params = array( "touch.0.x" => $x, "touch.0.y" => $y, "touch.0.op" => $op ); return $this->input($params); } /** * Build uri from input args * * @return string */ private function getUri() { $uri = $this->host . ":" . $this->port; foreach (func_get_args() as $part) { $uri .= '/' . $part; } return $uri; } /** * Execute sleep * @return void */ private function delay() { if($this->delay > 0) { sleep($this->delay); } } /** * toString * @return string */ public function __toString() { return "Roku [" . $this->host . ":" . $this->port ."]"; } }<file_sep><?php namespace Roku\Commands; /** * Sensor * There are four sensor values to report, accelerometer, orientation, gyroscope (rotation), and magnetometer (magnetic). */ class Sensor extends \Roku\Utils\AbstractEnum { const ACCELERATION = "acceleration"; const MAGNETIC = "magnetic"; const ORIENTATION = "orientation"; const ROTATION = "rotation"; }<file_sep><?php namespace Tests\Roku; use Roku; use \Httpful\Request; use PHPUnit\Framework\TestCase; class RokuTest extends TestCase { public function setUp() { $host = "http://127.0.0.1"; $http = $this->getHttpInstance(); $this->roku = new \Roku\Roku($host, 8060, 0.1); $this->roku->setClient($http); parent::setUp(); } public function testCommands() { $this->assertNotNull($this->roku->home()); $this->assertNotNull($this->roku->up()); $this->assertNotNull($this->roku->down()); $this->assertNotNull($this->roku->rev()); $this->assertNotNull($this->roku->select()); $this->assertNotNull($this->roku->keydown("home")); $this->assertNotNull($this->roku->keyup("home")); } public function testSensors() { $this->assertNotNull($this->roku->acceleration(0.1,0.2,0.3)); $this->assertNotNull($this->roku->rotation(1,2,3)); $this->assertNotNull($this->roku->orientation(0.1,0.2,0.3)); $this->assertNotNull($this->roku->magnetic(0.1,0.2,0.3)); } public function testTouches() { $this->assertNotNull($this->roku->touch(0.1,0.2)); $this->assertNotNull($this->roku->touch(0.1,0.2, "down")); $this->assertNotNull($this->roku->touch(0.1,0.2, "up")); $this->assertNotNull($this->roku->touch(0.1,0.2, "move")); } public function testIcon() { $app = new \Roku\Application("dev", "0.1.0", "Test App"); $this->assertNotNull($this->roku->icon($app)); } public function testLaunch() { $app = new \Roku\Application("dev", "0.1.0", "Test App"); $this->assertNotNull($this->roku->launch($app, array("contentID" => 120))); } public function testApplication() { $app = new \Roku\Application("dev"); $app->setId("dev"); $app->setName("<NAME>"); $app->setVersion("0.1.0"); $this->assertEquals(new \Roku\Application("dev", "0.1.0", "Test App"), $app); } /** * @expectedException \Roku\Exception * @expectedExceptionCode 0 */ public function testErrors() { $this->assertNotNull($this->roku->rotate()); } /** * @expectedException \Roku\Exception * @expectedExceptionCode 0 */ public function testErrorsTouch() { $this->assertNotNull($this->roku->touch(1,1,"nosuchtouch")); } public function testApps() { $host = "http://127.0.0.1"; $http = $this->getHttpXmlInstance(); $this->roku = new \Roku\Roku($host); $this->roku->setClient($http); $apps = $this->roku->apps(); $this->assertEquals(31012, $apps[0]->getId()); $this->assertEquals("1.4.14", $apps[0]->getVersion()); $this->assertEquals("Movies and TV Shows", $apps[0]->getName()); $this->assertCount(43, $apps); } public function testDevice() { $host = "http://127.0.0.1"; $http = $this->getHttpXmlInstance("roku.xml"); $this->roku = new \Roku\Roku($host); $this->roku->setClient($http); $device = $this->roku->device(); $this->assertEquals("urn:roku-com:device:player:1-0", $device->getDeviceType()); $this->assertEquals("Roku Streaming Player", $device->getFriendlyName()); $this->assertEquals("Roku", $device->getManufacturer()); $this->assertEquals("http://www.roku.com/", $device->getManufacturerURL()); $this->assertEquals("Roku Streaming Player Network Media", $device->getModelDescription()); $this->assertEquals("Roku Streaming Player 4200X", $device->getModelName()); $this->assertEquals("4200X", $device->getModelNumber()); $this->assertEquals("http://www.roku.com/", $device->getModelURL()); $this->assertEquals("uuid:8888888-8888-888-8888-b83e59cfd25f", $device->getUDN()); $this->assertEquals("1GN111111111", $device->getSerialNumber()); } public function getHttpInstance () { $headers = "HTTP/1.1 200 OK Content-Length: 0 Server: Roku UPnP/1.0 MiniUPnPd/1.4\r\n"; $response = new \Httpful\Response("", $headers, \Httpful\Request::init()); $http = $this->createMock('\Roku\Utils\Http'); // Configure the stub. $http->expects($this->any()) ->method('get') ->will($this->returnValue($response)); $http->expects($this->any()) ->method('post') ->will($this->returnValue($response)); return $http; } public function getHttpXmlInstance ($file = "apps.xml") { $headers = "HTTP/1.1 200 OK Content-Length: 0 Server: Roku UPnP/1.0 MiniUPnPd/1.4\r\n"; $response = new \Httpful\Response( file_get_contents(__DIR__."/../data/" . $file), $headers, \Httpful\Request::init()); $http = $this->createMock('\Roku\Utils\Http'); // Configure the stub. $http->expects($this->any()) ->method('get') ->will($this->returnValue($response)); $http->expects($this->any()) ->method('post') ->will($this->returnValue($response)); return $http; } } <file_sep><?php namespace Roku; /** * Device */ class Device { private $deviceType; private $friendlyName; private $manufacturer; private $manufacturerURL; private $modelDescription; private $modelName; private $modelNumber; private $modelURL; private $serialNumber; private $udn; private $serviceList; /** * Get manufacturerURL */ public function getManufacturerURL() { return $this->manufacturerURL; } /** * Set manufacturerURL * * @param string $manufacturerURL * @return \Roku\Device */ public function setManufacturerURL($manufacturerURL) { $this->manufacturerURL = $manufacturerURL; return $this; } /** * Get manufacturerURL */ public function getModelDescription() { return $this->modelDescription; } /** * Set modelDescription * * @param string $modelDescription * @return \Roku\Device */ public function setModelDescription($modelDescription) { $this->modelDescription = $modelDescription; return $this; } /** * Set modelName */ public function getModelName() { return $this->modelName; } /** * Set modelName * * @param string $modelName * @return \Roku\Device */ public function setModelName($modelName) { $this->modelName = $modelName; return $this; } /** * Get modelNumber */ public function getModelNumber() { return $this->modelNumber; } /** * Set modelNumber * * @param string $modelNumber * @return \Roku\Device */ public function setModelNumber($modelNumber) { $this->modelNumber = $modelNumber; return $this; } /** * Get modelURL */ public function getModelURL() { return $this->modelURL; } /** * Set modelURL * * @param string $modelURL * @return \Roku\Device */ public function setModelURL($modelURL) { $this->modelURL = $modelURL; return $this; } /** * Get setModelURL * * @return string */ public function getSerialNumber() { return $this->serialNumber; } /** * Set serialNumber * * @param string $serialNumber * @return \Roku\Device */ public function setSerialNumber($serialNumber) { $this->serialNumber = $serialNumber; return $this; } /** * Get UDN * * @return string */ public function getUDN() { return $this->udn; } /** * Set udn * * @param string $udn * @return \Roku\Device */ public function setUDN($udn) { $this->udn = $udn; return $this; } /** * Get Device Type * * @return string */ public function getDeviceType() { return $this->deviceType; } /** * Set deviceType * * @param string $deviceType * @return \Roku\Device */ public function setDeviceType($deviceType) { $this->deviceType = $deviceType; return $this; } public function getFriendlyName() { return $this->friendlyName; } /** * Set friendlyName * * @param string $friendlyName * @return \Roku\Device */ public function setFriendlyName($friendlyName) { $this->friendlyName = $friendlyName; return $this; } /** * Get Manufacturer * * @return string */ public function getManufacturer() { return $this->manufacturer; } /** * Set Manufacturer * * @param string $manufacturer * @return \Roku\Device */ public function setManufacturer($manufacturer) { $this->manufacturer = $manufacturer; return $this; } /** * Get serviceList * * @return string */ public function getServiceList() { return $this->serviceList; } /** * Init from Xml * * @param \SimpleXMLElement $xml * @return \Roku\Device */ public function init(\SimpleXMLElement $xml) { $xml = $this->xml2Array($xml); foreach ($xml as $name => $value) { if ($name == "UDN") { $name = strtolower($name); } $this->$name = $value; } return $this; } /** * XML To Array * * @param \SimpleXMLElement $xml * @return array */ function xml2Array(\SimpleXMLElement $xml) { // $xml = simplexml_load_string($string, 'SimpleXMLElement', LIBXML_NOCDATA); $array = json_decode(json_encode($xml), TRUE); return $array; } }<file_sep><?php namespace Roku; /** * Roku Exception Class */ class Exception extends \Exception{ }<file_sep><?php namespace Roku\Utils; class Http { /** * Get Request * * @param string $uri * @return \Httpful\Response */ public function get($uri, $params = array()) { $uri = $this->buildUri($uri, $params); return \Httpful\Request::get($uri)->send(); } /** * Post Request * * @param string $uri * @return \Httpful\Response */ public function post($uri, $params = array()) { $uri = $this->buildUri($uri, $params); return \Httpful\Request::post($uri)->send(); } private function buildUri ($uri, $params = array()) { if($params) { return $uri . "?" . http_build_query($params); } return $uri; } }
1b277529a5d9a4e73fc3d6ba0b4a02e9901ba1ad
[ "Markdown", "PHP" ]
19
PHP
svilborg/php-roku
da95262f2ab56336a299406b0116702293546551
1e2852e5642ca51bf0720499730305f25b326a30
refs/heads/master
<file_sep> #ifndef LUT_UTILS #define LUT_UTILS namespace{ // Avoid integer conversion problems by using these const std::uint64_t allZero = 0; const std::uint64_t allOne = -1; const std::uint64_t one = 1; // Output positions for positive values of this input const std::uint64_t lutInputMask[7] = { 0xaaaaaaaaaaaaaaaa, 0xcccccccccccccccc, 0xf0f0f0f0f0f0f0f0, 0xff00ff00ff00ff00, 0xffff0000ffff0000, 0xffffffff00000000, allOne }; // Masks when the Lut has less than 6 inputs const std::uint64_t lutSizeMask[7] = { 0x01, 0x03, 0x0f, 0xff, 0xffff, 0xffffffff, 0xffffffffffffffff }; // The 64-bit Lut for Xor const std::uint64_t xorMask = 0x6996966996696996; } #endif <file_sep> # Fast lut manipulation ## Goals Most of the time, logic optimization is done with advanced algorithmic constructs, like SOPs, BDDs, and AIGs. This library is a try at the brute-force approach: lookup tables are relatively small for few inputs - actually smaller than any of the clever approaches - and they can be manipulated using shifts and bitwise operations. The library provide Lut manipulation and construction primitives. Its goal is to allow brute-force based logic optimization, with only a few cycles per operation, something that would be slower with another approach. ## Implementation The Luts are represented as vectors of 64-bit integers. Luts of 6 inputs or less have only one, but the vector's size doubles with each new input. Depending on the memory requirements, it may be a bad idea to represent (let alone process) Luts with more than 10 inputs - a 13-input Lut will need 1kB of memory. <file_sep> #ifndef LUTIN_LUTPRINT #define LUTIN_LUTPRINT #include "Lut.h" #include <iosfwd> std::ostream& operator<<(std::ostream& stream, Lut const & lut); #endif <file_sep> #include "LutPrint.h" #include <ostream> std::ostream& operator<<(std::ostream& os, Lut const & lut){ os << lut.str(); return os; } <file_sep> #include "Lut.h" #include "LutPrint.h" #include <cassert> #include <cstdlib> #include <iostream> using namespace std; void testCofactors(Lut const & lut){ for(unsigned in=0; in<lut.inputCount(); ++in){ if(!lut.getCofactor(in, true).isDC(in) || !lut.getCofactor(in, false).isDC(in)){ cerr << lut.inputCount() << " inputs lut failed DC test" << in << std::endl; abort(); } } } void testSaveReload(Lut const & lut){ if(lut.inputCount() >= 2){ string strRepr = lut.str(); Lut rebuilt(strRepr); if(rebuilt != lut){ cerr << "Luts <" << lut << "> and <" << rebuilt << "> should be equal but are not" << endl; abort(); } } } void testSwapInputs(Lut const & lut){ Lut dup = lut; if(lut.inputCount() <= 1) return; for(unsigned i=0; i<lut.inputCount()-1; ++i){ for(unsigned j=i+1; j<lut.inputCount(); ++j){ dup.swapInputs(i,j); dup.swapInputs(i,j); if(dup != lut){ cerr << "Input swapping error: <" << dup << "> vs <" << lut << ">" << endl; abort(); } } } } void testInvertInput(Lut const & lut){ Lut dup = lut; for(unsigned i=0; i<lut.inputCount()-1; ++i){ dup.invertInput(i); dup.invertInput(i); if(dup != lut){ cerr << "Input inversion error: <" << dup << "> vs <" << lut << ">" << endl; abort(); } } } Lut getGeneralizedAnd(unsigned inputCnt, unsigned inputValues, bool inverted){ Lut ret = Lut::Gnd(inputCnt); ret.setVal(inputValues & ((1u << inputCnt)-1), true); if(inverted) ret.invert(); return ret; } void testGeneralizedAnd(unsigned inputCnt, unsigned inputValues, bool inverted){ Lut lut = getGeneralizedAnd(inputCnt, inputValues, inverted); if(lut.inputCount() != inputCnt){ cerr << "Input counts don't match" << std::endl; } testSaveReload(lut); testInvertInput(lut); if(inputCnt <= 10) testSwapInputs(lut); for(unsigned in=0; in<inputCnt; ++in){ bool forcingIn = ((inputValues >> in) & 0x1) == 0, forcedVal = inverted; if(!lut.forcesValue(in, forcingIn, forcedVal)){ cerr << inputCnt << " inputs generalized And gate forcing failed on input " << in << std::endl; abort(); } if(lut.forcesValue(in, forcingIn, !forcedVal) || lut.forcesValue(in, !forcingIn, true) || lut.forcesValue(in, !forcingIn, false)){ cerr << inputCnt << " inputs generalized And gate false positive on input " << in << std::endl; abort(); } } testCofactors(lut); if(!lut.isGeneralizedAnd()){ cerr << "Generalized And check failed for " << inputCnt << " input" << std::endl; abort(); } Lut pseudoRepr = lut.getPseudoRepresentant(); if(lut.isPseudoRepresentant() && lut != pseudoRepr){ cerr << "Failed pseudo-representant stability check" << endl; } if(pseudoRepr != getGeneralizedAnd(inputCnt, 0u, true)){ cerr << "Unexpected pseudo-representant of generalized and" << endl; } } void testGeneralizedAnds(){ for(unsigned inCnt=1; inCnt<15u; ++inCnt){ for(unsigned inMask=0; inMask < (1u<<inCnt); ++inMask){ testGeneralizedAnd(inCnt, inMask, false); testGeneralizedAnd(inCnt, inMask, true); } } cout << "Generalized And test OK" << std::endl; } void testAnd(){ for(unsigned i=0; i<15u; ++i){ Lut lut = Lut::And(i); Lut reference = getGeneralizedAnd(i, -1, false); if(reference != lut){ cerr << "And check failed for " << lut << std::endl; abort(); } } cout << "And test OK" << std::endl; } void testOr(){ for(unsigned i=0; i<15u; ++i){ Lut lut = Lut::Or(i); Lut reference = getGeneralizedAnd(i, 0, true); if(reference != lut){ cerr << "Or check failed for " << lut << std::endl; abort(); } } cout << "Or test OK" << std::endl; } void testNor(){ for(unsigned i=0; i<15u; ++i){ Lut lut = Lut::Nor(i); Lut reference = getGeneralizedAnd(i, 0, false); if(reference != lut){ cerr << "Nor check failed for " << lut << std::endl; abort(); } } cout << "Nor test OK" << std::endl; } void testNand(){ for(unsigned i=0; i<15u; ++i){ Lut lut = Lut::Nand(i); Lut reference = getGeneralizedAnd(i, -1, true); if(reference != lut){ cerr << "Nand check failed for " << lut << std::endl; abort(); } } cout << "Nand test OK" << std::endl; } void testXor(){ for(unsigned i=0; i<15; ++i){ Lut lut = Lut::Xor(i); Lut reference = Lut::Exor(i); if(Lut::Not(reference) != lut){ cerr << "Xor check failed for " << lut << std::endl; abort(); } testSaveReload(lut); for(unsigned in=0; in<i; ++in){ if(!lut.toggles(in)){ cerr << i << " inputs Xor gate failed for input " << in << std::endl; abort(); } } testCofactors(lut); if(!lut.isGeneralizedXor()){ cerr << "Generalized And check failed" << std::endl; abort(); } } cout << "Xor test OK" << std::endl; } void testBufCofactors(Lut const & wire, unsigned j){ for(unsigned k=0; k<wire.inputCount(); ++k){ if(k != j){ if(wire.getCofactor(k, false) != wire.getCofactor(k, true)){ cerr << "Buffer cofactor test failed" << endl; abort(); } if(!wire.isDC(k)){ cerr << "Buffer DC check failed" << endl; abort(); } } } if(wire.isDC(j)){ cerr << "Buffer sensitivity check failed" << endl; abort(); } } void testBuf(){ for(unsigned i=1; i<15; ++i){ for(unsigned j=0; j<i; ++j){ Lut buf = Lut::Buf(j, i); Lut inv = Lut::Inv(j, i); if(buf != Lut::Not(inv)){ cerr << "Buffer test failed" << endl; abort(); } testBufCofactors(buf, j); testBufCofactors(inv, j); } } } int main(){ testBuf(); testAnd(); testOr(); testNand(); testNor(); testXor(); testGeneralizedAnds(); return 0; } <file_sep> /* * Basic Lut manipulation and construction functions * * * */ #include "Lut.h" #include "LutUtils.h" #include <cassert> #include <sstream> #include <stdexcept> #include <iomanip> using namespace std; namespace{ size_t mapSize(unsigned inputCnt) { return inputCnt >= 6 ? 1ul << (inputCnt-6) : 1ul; } void checkInputCounts(Lut const & a, Lut const & b){ if(a.inputCount() != b.inputCount()){ throw std::logic_error("Luts have different input counts"); } } } // Quick and dirty for now bool Lut::isConstant() const{ return isGnd() || isVcc(); } bool Lut::isGnd() const{ return equal(Gnd(inputCount())); } bool Lut::isVcc() const{ return equal(Vcc(inputCount())); } bool Lut::isAnd() const{ return equal(And(inputCount())); } bool Lut::isOr() const{ return equal(Or(inputCount())); } bool Lut::isNand() const{ return equal(Nand(inputCount())); } bool Lut::isNor() const{ return equal(Nor(inputCount())); } bool Lut::isXor() const{ return equal(Xor(inputCount())); } bool Lut::isExor() const{ return equal(Exor(inputCount())); } Lut::Lut(unsigned inputs) : _inputCnt(inputs) , _lut(mapSize(inputs), allZero) { } Lut Lut::Gnd(unsigned inputs){ Lut ret(inputs); return ret; } Lut Lut::Vcc(unsigned inputs){ Lut ret(inputs); for(LutMask & cur : ret._lut) cur = allOne; return ret; } Lut Lut::And(unsigned inputs){ Lut ret = Gnd(inputs); if(inputs < 6){ ret._lut[0] = one << ((1<<inputs)-1); } else{ ret._lut.back() = one<<63; } return ret; } Lut Lut::Or(unsigned inputs){ Lut ret = Vcc(inputs); ret._lut[0] = ~one; return ret; } Lut Lut::Nand(unsigned inputs){ Lut ret = And(inputs); ret.invert(); return ret; } Lut Lut::Nor(unsigned inputs){ Lut ret = Or(inputs); ret.invert(); return ret; } Lut Lut::Xor(unsigned inputs){ Lut ret(inputs); ret._lut[0] = xorMask; if(inputs>6){ for(size_t i=0; i<inputs-6; ++i){ size_t curMaskSize = 1<<i; for(size_t j=0; j<curMaskSize; ++j){ ret._lut[curMaskSize+j] = ~ret._lut[j]; } } } return ret; } Lut Lut::Exor(unsigned inputs){ Lut ret = Xor(inputs); ret.invert(); return ret; } Lut Lut::Wire(unsigned wireInput, unsigned inputs, bool invert){ if(wireInput >= inputs){ throw std::logic_error("The specified wire input is not in the Lut's input range"); } Lut ret(inputs); if(wireInput < 6){ uint64_t szMask = inputs >= 6 ? lutSizeMask[6] : lutSizeMask[inputs]; uint64_t msk = invert ? ~lutInputMask[wireInput] : lutInputMask[wireInput]; for(uint64_t & cur : ret._lut){ cur = msk & szMask; } } else{ size_t const stride = 1<<(wireInput-6); for(size_t i= invert ? 0 : stride; i<ret._lut.size(); i += 2*stride){ for(size_t j=i; j<i+stride; ++j){ ret._lut[j] = allOne; } } } return ret; } Lut Lut::Buf(unsigned wireInput, unsigned inputs){ return Wire(wireInput, inputs, false); } Lut Lut::Inv(unsigned wireInput, unsigned inputs){ return Wire(wireInput, inputs, true ); } Lut Lut::Not(Lut const & a){ Lut ret = a; ret.invert(); return ret; } Lut Lut::And(Lut const & a, Lut const & b){ checkInputCounts(a, b); Lut ret(a.inputCount()); assert(ret._lut.size() == a._lut.size() && ret._lut.size() == b._lut.size()); for(size_t i=0; i<a._lut.size(); ++i){ ret._lut[i] = a._lut[i] & b._lut[i]; } return ret; } Lut Lut::Or(Lut const & a, Lut const & b){ checkInputCounts(a, b); Lut ret(a.inputCount()); assert(ret._lut.size() == a._lut.size() && ret._lut.size() == b._lut.size()); for(size_t i=0; i<a._lut.size(); ++i){ ret._lut[i] = a._lut[i] | b._lut[i]; } return ret; } Lut Lut::Nor(Lut const & a, Lut const & b){ checkInputCounts(a, b); Lut ret(a.inputCount()); assert(ret._lut.size() == a._lut.size() && ret._lut.size() == b._lut.size()); for(size_t i=0; i<a._lut.size(); ++i){ ret._lut[i] = ~(a._lut[i] | b._lut[i]); } return ret; } Lut Lut::Nand(Lut const & a, Lut const & b){ checkInputCounts(a, b); Lut ret(a.inputCount()); assert(ret._lut.size() == a._lut.size() && ret._lut.size() == b._lut.size()); for(size_t i=0; i<a._lut.size(); ++i){ ret._lut[i] = ~(a._lut[i] & b._lut[i]); } return ret; } Lut Lut::Xor(Lut const & a, Lut const & b){ checkInputCounts(a, b); Lut ret(a.inputCount()); assert(ret._lut.size() == a._lut.size() && ret._lut.size() == b._lut.size()); for(size_t i=0; i<a._lut.size(); ++i){ ret._lut[i] = a._lut[i] ^ b._lut[i]; } return ret; } Lut Lut::Exor(Lut const & a, Lut const & b){ checkInputCounts(a, b); Lut ret(a.inputCount()); assert(ret._lut.size() == a._lut.size() && ret._lut.size() == b._lut.size()); for(size_t i=0; i<a._lut.size(); ++i){ ret._lut[i] = ~(a._lut[i] ^ b._lut[i]); } return ret; } Lut::Lut(string const & init){ unsigned s = 2; while( (1lu << (s-2)) < init.size()) ++s; if(init.size() != (1lu << (s-2))) throw std::logic_error("Bad string size as init of the Lut"); _inputCnt = s; _lut.resize(mapSize(_inputCnt)); for(size_t i=0; i<_lut.size(); ++i){ uint64_t val = 0ul; for(size_t j=i*16; j<i*16+16 && j<init.size(); ++j){ uint64_t cur = 0ul; char c = init[j]; if(c >= '0' && c <= '9'){ cur = c-'0'; } else if(c >= 'a' && c <= 'f'){ cur = c-'a'+10; } else if(c >= 'A' && c <= 'F'){ cur = c-'A'+10; } else throw std::logic_error("Invalid character in init of the Lut"); val = val << 4 | cur; } _lut[_lut.size()-1-i] = val; } } string Lut::str() const{ if(inputCount() == 0) return string(); stringstream ret; ret << std::hex; int fillWidth; if(inputCount() >= 6) fillWidth = 16; else if(inputCount() <= 2) fillWidth = 1; else fillWidth = (1 << (inputCount()-2)); uint64_t mask = inputCount() >= 6 ? lutSizeMask[6] : lutSizeMask[inputCount()]; for(auto it=_lut.rbegin(); it!=_lut.rend(); ++it){ ret << setfill('0') << setw(fillWidth); ret << (mask & *it); } return ret.str(); } <file_sep> cmake_minimum_required(VERSION 2.6) project(LUTIN) set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -g -Wall -Werror -std=c++11") set(CMAKE_CXX_FLAGS_DEBUG "${CMAKE_CXX_FLAGS_DEBUG} -Og") set(CMAKE_CXX_FLAGS_RELEASE "${CMAKE_CXX_FLAGS_RELEASE} -O2") include_directories(${LUT_SOURCE_DIR}/include/public) include_directories(${LUT_SOURCE_DIR}/include/private) set(CPPS src/LutConstruction.cc src/LutManipulation.cc src/LutPrint.cc ) set(TESTCPPS tests/BasicTest.cc ) add_library(Lutin ${CPPS}) enable_testing() add_executable(tests.bin ${TESTCPPS}) target_link_libraries(tests.bin Lutin) add_test(basictests tests.bin) <file_sep> #include "Lut.h" #include "LutUtils.h" #include <cassert> #include <stdexcept> #include <bitset> using namespace std; bool Lut::equal(Lut const & b) const{ if(inputCount() != b.inputCount()) return false; if(inputCount() < 6){ // Safe while I don't force the unused bits to 0 return ((_lut[0] ^ b._lut[0]) & lutSizeMask[inputCount()]) == 0; } else{ return _lut == b._lut; } } bool Lut::evaluate(unsigned inputValues) const{ unsigned lutChunk = inputValues >> 6; assert(lutChunk < _lut.size()); unsigned chunkInd = inputValues & 0x003f; return ((_lut[lutChunk] >> chunkInd) & 0x01) != 0; } void Lut::invert(){ for(LutMask & cur : _lut){ cur = ~cur; } } void Lut::setVal(unsigned inputValues, bool val){ unsigned lutChunk = inputValues >> 6; assert(lutChunk < _lut.size()); unsigned chunkInd = inputValues & 0x003f; if(val) _lut[lutChunk] |= (one << chunkInd); else _lut[lutChunk] &= ~(one << chunkInd); } bool Lut::isGeneralizedAnd() const{ // Check if either only one bit is set or only one bit is unset if(inputCount() == 0){ return true; } else if(inputCount() <= 6){ uint64_t pv = _lut[0] & lutSizeMask[inputCount()]; uint64_t nv = ~_lut[0] & lutSizeMask[inputCount()]; bool pand = pv != allZero && (pv & (pv-1)) == allZero; bool nand = nv != allZero && (nv & (nv-1)) == allZero; return pand || nand; } else{ size_t zeros=0, ones=0, pands=0, nands=0; for(uint64_t cur : _lut){ if(cur == allOne) ++ones; else if((~cur & (~cur-1)) == allZero) ++nands; if(cur == allZero) ++zeros; else if((cur & (cur-1)) == allZero) ++pands; } return (ones == 0 && nands == 0 && pands == 1) || (zeros == 0 && pands == 0 && nands == 1); } } bool Lut::isGeneralizedXor() const{ return equal(Xor(inputCount())) || equal(Exor(inputCount())); } void Lut::invertInput(unsigned input){ if(input < 6){ for(LutMask & cur : _lut){ LutMask lowerPart = cur & ~lutInputMask[input]; LutMask upperPart = cur & lutInputMask[input]; int shiftAmount = 1<<input; cur = lowerPart << shiftAmount | upperPart >> shiftAmount; } } else{ size_t const stride = 1<<(input-6); for(size_t i=0; i<_lut.size(); i += 2*stride){ for(size_t j=i; j<i+stride; ++j){ std::swap(_lut[j], _lut[j+stride]); } } } } void Lut::swapInputs(unsigned i1, unsigned i2){ if(i1 == i2) return; if(i1 >= inputCount() && i2 >= inputCount()) throw std::logic_error("Inputs to swap must be valid inputs"); Lut ret(inputCount()); for(unsigned inMask=0; inMask < 1u<<inputCount(); ++inMask){ unsigned bit1Sel = 1u << i1; unsigned bit2Sel = 1u << i2; unsigned swappedMask = inMask & ~bit1Sel & ~bit2Sel; if((bit1Sel & inMask) != 0u) swappedMask |= bit2Sel; if((bit2Sel & inMask) != 0u) swappedMask |= bit1Sel; ret.setVal(swappedMask, evaluate(inMask)); } std::swap(ret._lut, _lut); } void Lut::swapToEnd(unsigned input){ swapInputs(inputCount()-1, input); } Lut Lut::getCofactor(unsigned input, bool value) const{ assert(input < inputCount()); Lut ret = *this; if(input < 6){ unsigned shiftAmount = 1 << input; LutMask inputMask = value? lutInputMask[input] : ~lutInputMask[input]; for(LutMask & cur : ret._lut){ LutMask maskedVal = cur & inputMask; // The shift is different depending on the input mask if(value) cur = maskedVal | (maskedVal >> shiftAmount); else cur = maskedVal | (maskedVal << shiftAmount); } } else{ size_t const stride = 1<<(input-6); for(size_t i=0; i<_lut.size(); i += 2*stride){ for(size_t j=i; j<i+stride; ++j){ if(value) ret._lut[j] = _lut[j+stride]; else ret._lut[j+stride] = _lut[j]; } } } return ret; } // The 3 following algorithms use a bitmask accumulator rather than an early exit: it is believed - but not tested - to be faster, with fewer instructions and better branch prediction bool Lut::isDC(unsigned input) const{ assert(input < inputCount()); if(input < 6){ LutMask acc = allZero; for(LutMask cur : _lut){ acc |= (cur << (1<<input)) ^ cur; } return (acc & lutInputMask[input]) == allZero; } else{ LutMask acc = allZero; size_t const stride = 1<<(input-6); for(size_t i=0; i<_lut.size(); i += 2*stride){ for(size_t j=i; j<i+stride; ++j){ acc |= (_lut[j] ^ _lut[j+stride]); } } return acc == allZero; } } bool Lut::toggles(unsigned input) const{ assert(input < inputCount()); if(input < 6){ LutMask acc = allOne; for(LutMask cur : _lut){ acc &= (cur << (1<<input)) ^ cur; } return (acc | ~lutInputMask[input]) == allOne; } else{ LutMask acc = allOne; size_t const stride = 1<<(input-6); for(size_t i=0; i<_lut.size(); i += 2*stride){ for(size_t j=i; j<i+stride; ++j){ acc &= (_lut[j] ^ _lut[j+stride]); } } return acc == allOne; } } bool Lut::forcesValue(unsigned input, bool inVal, bool outVal) const{ assert(input < inputCount()); LutMask comp = outVal? allOne : allZero; if(input<6){ LutMask inputMask = inVal? lutInputMask[input] : ~lutInputMask[input]; LutMask acc = allZero; for(LutMask cur : _lut){ acc |= (cur ^ comp); } return (acc & inputMask) == allZero; } else{ LutMask acc = allZero; size_t const stride = 1<<(input-6); for(size_t i=inVal? stride : 0; i<_lut.size(); i += 2*stride){ for(size_t j=i; j<i+stride; ++j){ acc |= (_lut[j] ^ comp); } } return acc == allZero; } } bool Lut::isPseudoRepresentant() const{ // A pseudo-representant has half the bits or more set if(countSetBits() < (1u << (inputCount()-1))){ return false; } // For each input, the 1 cofactor has at least as many bit sets than the 0 cofactor for(unsigned input=0; input<inputCount(); ++input){ if(getCofactor(input, false).countSetBits() > getCofactor(input, true).countSetBits()){ return false; } } // The inputs are sorted in increasing order of set bits in the 1 cofactor for(unsigned input=0; input+1<inputCount(); ++input){ if(getCofactor(input, true).countSetBits() > getCofactor(input+1, true).countSetBits()){ return false; } } return true; } Lut Lut::getPseudoRepresentant() const{ Lut ret = *this; // Invert the output if necessary to obtain majority of bit sets if(ret.countSetBits() < (1u << (inputCount()-1))){ ret.invert(); } // Invert the inputs to obtain majority of bit sets on each input for(unsigned input=0; input<inputCount(); ++input){ if(ret.getCofactor(input, false).countSetBits() > ret.getCofactor(input, true).countSetBits()){ ret.invertInput(input); } } // Quadratic sort of the inputs in increasing order of set bits for(unsigned end=inputCount(); end>=2; --end){ for(unsigned in=0; in+1<end; ++in){ if(ret.getCofactor(in, true).countSetBits() > ret.getCofactor(in+1, true).countSetBits()){ ret.swapInputs(in, in+1); } } } assert(ret.isPseudoRepresentant()); return ret; } unsigned Lut::countSetBits() const{ unsigned ret = 0; uint64_t szMask = inputCount() >= 6 ? lutSizeMask[6] : lutSizeMask[inputCount()]; for(uint64_t cur : _lut){ bitset<64> bs(cur & szMask); ret += bs.count(); } return ret; } <file_sep> #ifndef LUTIN_LUT #define LUTIN_LUT #include <cstdint> #include <vector> #include <string> class Lut{ public: typedef std::uint64_t LutMask; public: // Contructors (default is the ground lut) Lut(unsigned inputs); static Lut Gnd (unsigned inputs); static Lut Vcc (unsigned inputs); static Lut And (unsigned inputs); static Lut Or (unsigned inputs); static Lut Nand (unsigned inputs); static Lut Nor (unsigned inputs); static Lut Xor (unsigned inputs); static Lut Exor (unsigned inputs); static Lut Wire (unsigned wireInput, unsigned inputs, bool invert); static Lut Buf (unsigned wireInput, unsigned inputs); static Lut Inv (unsigned wireInput, unsigned inputs); // Operations on same-size Luts with a common input set static Lut Not (Lut const & a); static Lut And (Lut const & a, Lut const & b); static Lut Or (Lut const & a, Lut const & b); static Lut Nand (Lut const & a, Lut const & b); static Lut Nor (Lut const & a, Lut const & b); static Lut Xor (Lut const & a, Lut const & b); static Lut Exor (Lut const & a, Lut const & b); // Basic modifiers: invert one input or the output void invertInput(unsigned input); void invert(); void setVal(unsigned inputValues, bool val); void swapInputs(unsigned i1, unsigned i2); // Basic queries unsigned inputCount() const { return _inputCnt; } bool evaluate(unsigned inputValues) const; bool isConstant() const; bool isGnd () const; bool isVcc () const; bool isAnd () const; bool isOr () const; bool isNand () const; bool isNor () const; bool isXor () const; bool isExor () const; // And/Xor with some input and output inversions bool isGeneralizedAnd() const; bool isGeneralizedXor() const; // Logic comparison bool operator==(Lut const & b){ return equal(b); } bool operator!=(Lut const & b){ return !equal(b); } // To/from string represented as an hexadecimal init; the init is ordered high-bit first, contrary to internal storage std::string str() const; Lut(std::string const & init); /* * Logic queries * * Is an input a don't care (no influence on the output result)? * * Does the input toggle the output value? * * Does a particular value at one input force the output value? * * Test if the Lut can be simplified in smaller disjoint Luts */ bool isDC(unsigned input) const; bool toggles(unsigned input) const; bool forcesValue(unsigned input, bool inVal, bool outVal) const; bool hasFactors() const; // Get the cofactors, but keep the inputs in position (make the corresponding input DC) Lut getCofactor (unsigned input, bool value) const; // Get a pseudo representant with some input/output inversions and input permutations; it is not unique but is a good approximation for a unique representant bool isPseudoRepresentant() const; Lut getPseudoRepresentant() const; private: // Helper functions bool equal(Lut const & b) const; // Defines equality operators void swapToEnd(unsigned input); // Used in optimized swapInputs implementations unsigned countSetBits() const; // Used to compute a pseudorepresentant private: unsigned _inputCnt; std::vector<LutMask> _lut; }; #endif
7627629537892e9690d3af1083d6ef56ec6cd427
[ "Markdown", "CMake", "C++" ]
9
C++
Coloquinte/Lutin
e6f23d99516199330411b16f2c7ca110e110bb6d
0206fd878b8c44344170f20f0d31ac493a5ce396
refs/heads/master
<repo_name>JaakkoTulkki/reactapi<file_sep>/src/middleware/api/index.js function makeRequest() { console.log('making a request'); return fetch('https://api.github.com').then(response => { return response.json().then(json => { console.log('i have the json', json) return Promise.resolve(json); }) } ) } function wait() { return new Promise(resolve => setTimeout(resolve, 2000)); } export default store => next => action => { if (action.type !== 'API_CALL') { return next(action) } return wait().then(() => makeRequest().then(response => { console.log('and the response is here', response) return store.dispatch({ type: 'RESPONSE', payload: response }); }, error => { console.log('shit i got error', error) })) }<file_sep>/src/App.js import React, { Component } from 'react'; import { connect } from 'react-redux' import logo from './logo.svg'; import './App.css'; import { Provider } from 'react-redux' function wait() { return new Promise(resolve => setTimeout(resolve, 2000)); } class App extends Component { async componentWillMount() { // console.log('my props are ', this.props.apiCall); console.log('starting to wait for apiCall') await this.props.apiCall(); console.log('api call finished') // console.log('wait for some time') // await wait(); // console.log('wait ended') this.props.toggleShow(); } render() { return ( <div className="App"> <div className="App-header"> <img src={logo} className="App-logo" alt="logo" /> <h2>Welcome to React</h2> {!this.props.show && <h3>Loading...........................</h3> } {this.props.show && <h3>WOW EVERYTHING IS HERE NOW</h3> } </div> <p className="App-intro"> To get started, edit <code>src/App.js</code> and save to reload. </p> </div> ); } } function mapStateToProps(state, ownProps) { return { show: state.show, }; } function mapDispatchToProps(dispatch) { return { apiCall: async () => {await dispatch({ type: 'API_CALL', })}, toggleShow: () => dispatch({type: 'TOGGLE_SHOW'}) } } const AppContainer = connect( mapStateToProps, mapDispatchToProps, )(App); const Root = ({ store }) => { return <Provider store={store}> <AppContainer /> </Provider> } export default Root;
75463e41ff37421544d4f00cbb0d51c766b645fd
[ "JavaScript" ]
2
JavaScript
JaakkoTulkki/reactapi
646e5fd8aee531db7347bc591140b729d78c2c91
0d866bad6b84d2a5a6924e5c47028c25182193a2
refs/heads/master
<file_sep><?php namespace larvelcode\tagcategories; use Illuminate\Support\ServiceProvider; use larvelcode\tagcategories\Categoriestag; /* man */ class CattagServiceProvider extends ServiceProvider { public function boot() { $this->app->singleton('Categoriestag', function ($app) { return new Categoriestag(); }); } /** * Register bindings in the container. * * @return void */ public function register() { } } <file_sep><?php namespace larvelcode\tagcategories\Categoriestags; use Illuminate\Support\Facades\DB; use larvelcode\tagcategories\Categoriestags\otherhelperfunction; class otherhelperfunction { public static function linked_category_tag($data_array) { extract($data_array); $insert_data_list = DB::table($linked_table) ->insert([$in_linked_table_column_name => $second_table, $in_link_other_column_name => $classified_table_id, 'created_at' => date('Y-m-d h-i-s'), 'updated_at' => date('Y-m-d h-i-s')]); } public static function no_link_category_tag($data_array) { extract($data_array); $create_category = DB::table($classification_table_name) ->insert([ 'slug' => otherhelperfunction::slug($classification_table_name,$value_list), $column_name => $value_list, 'created_at' => date('Y-m-d h-i-s'), 'updated_at' => date('Y-m-d h-i-s')]); $linked_table_insert = DB::table($classification_table_name)->where($column_name,'=',$value_list)->first(); $insert_data_list = DB::table($linked_table) ->insert([$in_linked_table_column_name => $linked_table_insert->id, $in_link_other_column_name => $classified_table_id, 'created_at' => date('Y-m-d h-i-s'), 'updated_at' => date('Y-m-d h-i-s')]); } public static function detach($data_detach) { extract($data_detach); $detach = DB::table($linked_table)->where($in_link_other_column_name,$classified_table_id) ->where($in_linked_table_column_name,$valuedetach_id)->delete(); } public static function slug($table_name,$request_slug) { $search_slug = DB::table($table_name)->where('slug', str_slug($request_slug))->count(); if ($search_slug == 0) { $new_product_slug = str_slug($request_slug); } elseif($search_slug > 0){ $rand_slug = str_slug($request_slug).'-'.rand(1,10); $search_slug_again = DB::table($table_name)->where('slug', $rand_slug)->count(); if ($search_slug_again == 0) { $new_product_slug = $rand_slug; } elseif ($search_slug_again > 0) { $new_product_slug = uniqid(str_slug($rand_slug), true); } } return $new_product_slug; } }<file_sep><?php namespace larvelcode\tagcategories; use Illuminate\Support\Facades\DB; use larvelcode\tagcategories\Categoriestags\createcategories; use larvelcode\tagcategories\Categoriestags\updatecategories; class Categoriestag { public static function creation($data_array) { createcategories::create_category_tag($data_array); } public static function update($data_array) { updatecategories::update_category_tag($data_array); } }<file_sep><?php namespace larvelcode\tagcategories\Categoriestags; use Illuminate\Support\Facades\DB; use larvelcode\tagcategories\Categoriestags\otherhelperfunction; class updatecategories { public static function update_category_tag($data_array) { /* *list :- this is the list of category or Tag. *linked_list :- the list of categories or tags that associated with classified_table (product). *classified_table_id:- the table that category make to splite it in this situation product table id. *classification_table_name:- the table of category or tag. *column_name:-the column that contain category or tag name. *linked_table:- the Intermediate table category_product or product_tag. *in_linked_table_column_name:- column in Intermediate table (category_product or product_tag) category_id or tag_id. *in_link_other_column_name:- column in the Intermediate table (product_id). */ extract($data_array); foreach ($linked_list as $keydetach => $valuedetach) { $data_detach = array('linked_table' => $linked_table, 'in_link_other_column_name' => $in_link_other_column_name, 'classified_table_id' => $classified_table_id, 'in_linked_table_column_name' => $in_linked_table_column_name, 'valuedetach_id' => $valuedetach['id']); otherhelperfunction::detach($data_detach); } if (count($list) != 0) { foreach ($list as $key_list => $value_list) { $second_table = DB::table($classification_table_name)->where($column_name,'=',$value_list)->first(); if ($second_table == true) { $data_array = array('linked_table' => $linked_table, 'in_linked_table_column_name' => $in_linked_table_column_name, 'second_table' => $second_table->id, 'in_link_other_column_name' => $in_link_other_column_name, 'classified_table_id' => $classified_table_id); otherhelperfunction::linked_category_tag($data_array); } else{ $data_array = array('classification_table_name' => $classification_table_name, 'value_list' => $value_list, 'column_name' => $column_name, 'linked_table' => $linked_table, 'in_linked_table_column_name' => $in_linked_table_column_name, 'in_link_other_column_name' => $in_link_other_column_name, 'classified_table_id' => $classified_table_id); otherhelperfunction::no_link_category_tag($data_array); } } } } }
e72d016f485ccad6d239460937ee68246078d804
[ "PHP" ]
4
PHP
Uchiha-AhmedSaad/laravelcode-tagcategories
f44651c87b70da8e4acd6119ff6de2d784d9fd19
5e581c17a0260ad6c2a57b517f7ce78491c9cb7b
refs/heads/master
<repo_name>iloveujing/R_Day_1<file_sep>/员工离职预测.R ################### ============== 加载包 =================== ################# library(plyr) # Rmisc的关联包,若同时需要加载dplyr包,必须先加载plyr包 library(dplyr) # filter() library(ggplot2) # ggplot() library(DT) # datatable() 建立交互式数据表 library(caret) # createDataPartition() 分层抽样函数 library(rpart) # rpart() library(e1071) # naiveBayes() library(pROC) # roc() library(Rmisc) # multiplot() 分割绘图区域 ################### ============= 导入数据 ================== ################# hr <- read.csv("D:/R/天善智能/书豪十大案例/员工离职预测\\HR_comma_sep.csv") ################### ============= 描述性分析 ================== ############### str(hr) # 查看数据的基本数据结构 summary(hr) # 计算数据的主要描述统计量 # 后续的个别模型需要目标变量必须为因子型,我们将其转换为因子型 hr$left <- factor(hr$left, levels = c('0', '1')) ## 探索员工对公司满意度、绩效评估和月均工作时长与是否离职的关系 # 绘制对公司满意度与是否离职的箱线图 box_sat <- ggplot(hr, aes(x = left, y = satisfaction_level, fill = left)) + geom_boxplot() + theme_bw() + # 一种ggplot的主题 labs(x = 'left', y = 'satisfaction_level') # 设置横纵坐标标签 box_sat # 绘制绩效评估与是否离职的箱线图 box_eva <- ggplot(hr, aes(x = left, y = last_evaluation, fill = left)) + geom_boxplot() + theme_bw() + labs(x = 'left', y = 'last_evaluation') box_eva # 绘制平均月工作时长与是否离职的箱线图 box_mon <- ggplot(hr, aes(x = left, y = average_montly_hours, fill = left)) + geom_boxplot() + theme_bw() + labs(x = 'left', y = 'average_montly_hours') box_mon # 绘制员工在公司工作年限与是否离职的箱线图 box_time <- ggplot(hr, aes(x = left, y = time_spend_company, fill = left)) + geom_boxplot() + theme_bw() + labs(x = 'left', y = 'time_spend_company') box_time # 合并这些图形在一个绘图区域,cols = 2的意思就是排版为一行二列 multiplot(box_sat, box_eva, box_mon, box_time, cols = 2) ## 探索参与项目个数、五年内有没有升职和薪资与离职的关系 # 绘制参与项目个数条形图时需要把此变量转换为因子型 hr$number_project <- factor(hr$number_project, levels = c('2', '3', '4', '5', '6', '7')) # 绘制参与项目个数与是否离职的百分比堆积条形图 bar_pro <- ggplot(hr, aes(x = number_project, fill = left)) + geom_bar(position = 'fill') + # position = 'fill'即绘制百分比堆积条形图 theme_bw() + labs(x = 'left', y = 'number_project') bar_pro # 绘制5年内是否升职与是否离职的百分比堆积条形图 bar_5years <- ggplot(hr, aes(x = as.factor(promotion_last_5years), fill = left)) + geom_bar(position = 'fill') + theme_bw() + labs(x = 'left', y = 'promotion_last_5years') bar_5years # 绘制薪资与是否离职的百分比堆积条形图 bar_salary <- ggplot(hr, aes(x = salary, fill = left)) + geom_bar(position = 'fill') + theme_bw() + labs(x = 'left', y = 'salary') bar_salary # 合并这些图形在一个绘图区域,cols = 3的意思就是排版为一行三列 multiplot(bar_pro, bar_5years, bar_salary, cols = 3) ############## =============== 提取优秀员工 =========== ################### # filter()用来筛选符合条件的样本 hr_model <- filter(hr, last_evaluation >= 0.70 | time_spend_company >= 4 | number_project > 5) ############### ============ 自定义交叉验证方法 ========== ################## # 设置5折交叉验证 method = ‘cv’是设置交叉验证方法,number = 5意味着是5折交叉验证 train_control <- trainControl(method = 'cv', number = 5) ################ =========== 分成抽样 ============== ########################## set.seed(1234) # 设置随机种子,为了使每次抽样结果一致 # 根据数据的因变量进行7:3的分层抽样,返回行索引向量 p = 0.7就意味着按照7:3进行抽样, # list=F即不返回列表,返回向量 index <- createDataPartition(hr_model$left, p = 0.7, list = F) traindata <- hr_model[index, ] # 提取数据中的index所对应行索引的数据作为训练集 testdata <- hr_model[-index, ] # 其余的作为测试集 ##################### ============= 回归树 ============= ##################### # 使用caret包中的trian函数对训练集使用5折交叉的方法建立决策树模型 # left ~.的意思是根据因变量与所有自变量建模;trCintrol是控制使用那种方法进行建模 # methon就是设置使用哪种算法 rpartmodel <- train(left ~ ., data = traindata, trControl = train_control, method = 'rpart') # 利用rpartmodel模型对测试集进行预测,([-7]的意思就是剔除测试集的因变量这一列) pred_rpart <- predict(rpartmodel, testdata[-7]) # 建立混淆矩阵,positive=‘1’设定我们的正例为“1” con_rpart <- table(pred_rpart, testdata$left) con_rpart ################### ============ Naives Bayes =============== ################# nbmodel <- train(left ~ ., data = traindata, trControl = train_control, method = 'nb') pred_nb <- predict(nbmodel, testdata[-7]) con_nb <- table(pred_nb, testdata$left) con_nb ################### ================ ROC ==================== ################# # 使用roc函数时,预测的值必须是数值型 pred_rpart <- as.numeric(as.character(pred_rpart)) pred_nb <- as.numeric(as.character(pred_nb)) roc_rpart <- roc(testdata$left, pred_rpart) # 获取后续画图时使用的信息 #假正例率:(1-Specififity[真反例率]) Specificity <- roc_rpart$specificities # 为后续的横纵坐标轴奠基,真反例率 Sensitivity <- roc_rpart$sensitivities # 查全率 : sensitivities,也是真正例率 # 绘制ROC曲线 #我们只需要横纵坐标 NULL是为了声明我们没有用任何数据 p_rpart <- ggplot(data = NULL, aes(x = 1- Specificity, y = Sensitivity)) + geom_line(colour = 'red') + # 绘制ROC曲线 geom_abline() + # 绘制对角线 annotate('text', x = 0.4, y = 0.5, label = paste('AUC=', #text是声明图层上添加文本注释 #‘3’是round函数里面的参数,保留三位小数 round(roc_rpart$auc, 3))) + theme_bw() + # 在图中(0.4,0.5)处添加AUC值 labs(x = '1 - Specificity', y = 'Sensitivities') # 设置横纵坐标轴标签 p_rpart roc_nb <- roc(testdata$left, pred_nb) Specificity <- roc_nb$specificities Sensitivity <- roc_nb$sensitivities p_nb <- ggplot(data = NULL, aes(x = 1- Specificity, y = Sensitivity)) + geom_line(colour = 'red') + geom_abline() + annotate('text', x = 0.4, y = 0.5, label = paste('AUC=', round(roc_nb$auc, 3))) + theme_bw() + labs(x = '1 - Specificity', y = 'Sensitivities') p_nb ######################### ============= 应用 =============#################### # 使用回归树模型预测分类的概率,type=‘prob’设置预测结果为离职的概率和不离职的概率 pred_end <- predict(rpartmodel, testdata[-7], type = 'prob') # 合并预测结果和预测概率结果 data_end <- cbind(round(pred_end, 3), pred_rpart) # 为预测结果表重命名 names(data_end) <- c('pred.0', 'pred.1', 'pred') # 生成一个交互式数据表 datatable(data_end) <file_sep>/README.md # R_Day_1 R <file_sep>/数据科学调查.R ################# =========== 导入数据+简单清洗 ============== ################# library(data.table) # fread() library(dplyr) # group_by() / %>% / summaries() library(ggplot2) # ggplot() responses = fread("D:/R/天善智能/书豪十大案例/数据科学调查\\multipleChoiceResponses.csv") ## 把Country列中的表示中国的特征值改为中国 responses$Country <- ifelse(responses$Country == "Republic of China" | responses$Country == "People 's Republic of China", "China", responses$Country) ################# =========== 国家+年龄统计 ================ ################## ## 探索数据科学从业者的年龄中位数最大的十个国家 # 创建绘图所需的数据源(按照Country进行统计Age的中位数,并且按照Age进行降序排列) df_country_age <- responses %>% group_by(Country) %>% # 按照Country进行统计 summarise(AgeMedian = median(Age, na.rm = T)) %>% # 统计Age的中位数 arrange(desc(AgeMedian)) # 按照Age进行降序排列 # reorder(Country, AgeMedian)--按照AgeMedian的升序排列其对应的Country # head(df_country, 10)--选取数据源的前10行 # x参数中传入图中的x轴所需数据,y参数同理 # geom_bar()--绘制条形图的子函数 # fill = Country--按照Country填充条形图颜色 # stat(统计转换)参数设置为'identity',即对原始数据集不作任何统计变换 # geom_text()--添加文本注释的子函数 # label = AgeMedian--添加AgeMedian中的内容 # hjust--控制横向对齐(0:底部对齐, 0.5:居中, 1:顶部对齐) # colour--控制注释颜色 # theme_minimal()--是ggplot的一种主背景主题 ggplot(head(df_country_age, 10), aes(x = reorder(Country, AgeMedian), y = AgeMedian)) + geom_bar(aes(fill = Country), stat = 'identity') + labs(x = 'Country', y = 'AgeMedian') + geom_text(aes(label = AgeMedian), hjust = 1.5, colour = 'white') + coord_flip() + theme_minimal() + theme(legend.position = 'none') # 移除图例 # 封装绘图函数 fun1 <- function(data, xlab, ylab, xname, yname) { ggplot(data, aes(xlab, ylab)) + geom_bar(aes(fill = xlab), stat = 'identity') + labs(x = xname, y = yname) + geom_text(aes(label = ylab), hjust = 1.5, colour = 'white') + coord_flip() + theme_minimal() + theme(legend.position = 'none') } data <- head(df_country_age, 10) xname <- 'Country' yname <- 'AgeMedian' fun1(data, reorder(data$Country, data$AgeMedian), data$AgeMedian, xname, yname) ## 探索数据科学从业者的年龄中位数最小的十个国家 ################# =========== 职位统计 ==================== #################### ## 探索kaggler的当前职位 # 创建绘图所需的数据源(按照CurrentJobTitleSelect统计其个数,并按照个数进行降序排列) df_CJT <- responses %>% filter(CurrentJobTitleSelect != '') %>% # 筛选CurrentJobTitleSelect不为空的观测 group_by(CurrentJobTitleSelect) %>% # 按照CurrentJobTitleSelect统计 summarise(Count = n()) %>% # 统计其特征值的个数(Count) arrange(desc(Count)) # 按照个数(Count)进行降序排列 data <- head(df_CJT, 10) xname <- 'Country' yname <- 'Count' fun1(data, reorder(data$CurrentJobTitleSelect, data$Count), data$Count, xname, yname) # ggplot(head(df_CJT, 10), aes(x = reorder(CurrentJobTitleSelect, Count), y = Count)) + # geom_bar(aes(fill = CurrentJobTitleSelect), stat = 'identity') + # geom_text(aes(label = Count), hjust = 1.5, colour = 'white') + # labs(x = 'Country') + # coord_flip() + # theme_minimal() + # theme(legend.position = 'none') ## 探索美国kaggler的当前职位 # 创建绘图所需的数据源(按照CurrentJobTitleSelect统计其个数,并按照个数进行降序排列) df_CJT_USA <- responses %>% # 筛选CurrentJobTitleSelect不为空且美国kaggler的观测 filter(CurrentJobTitleSelect != '' & Country == 'United States') %>% group_by(CurrentJobTitleSelect) %>% summarise(Count = n()) %>% arrange(desc(Count)) data <- head(df_CJT_USA, 10) xname <- 'CurrentJobTitleSelect' yname <- 'Count' fun1(data, reorder(data$CurrentJobTitleSelect, data$Count), data$Count, xname, yname) ## 探索中国kaggler的当前职位 df_CJT_China <- responses %>% filter(CurrentJobTitleSelect != '' & Country == 'China') %>% group_by(CurrentJobTitleSelect) %>% summarise(Count = n()) %>% arrange(desc(Count)) data <- head(df_CJT_China, 10) xname <- 'CurrentJobTitleSelect' yname <- 'Count' fun1(data, reorder(data$CurrentJobTitleSelect, data$Count), data$Count, xname, yname) ################# =========== 明年将学习的机器学习工具 ============== ########## ## 探索kaggler明年将学习的机器学习工具 # 创建绘图所需数据源(按照MLToolNextYearSelect统计其个数,比按照其个数降序排列) df_MLT <- responses %>% filter(MLToolNextYearSelect != '') %>% # 筛选出MLToolNextYearSelect不为空的观测 group_by(MLToolNextYearSelect) %>% summarise(Count = n()) %>% arrange(desc(Count)) data <- head(df_MLT, 10) xname <- 'ML Tool' yname <- 'Count' fun1(data, reorder(data$MLToolNextYearSelect, data$Count), data$Count, xname, yname) ## 探索美国kaggler明年将学习的机器学习工具 # 创建绘图所需数据源(按照MLToolNextYearSelect统计其个数,比按照其个数降序排列) df_MLT_USA <- responses %>% # 筛选出MLToolNextYearSelect不为空且美国kaggler的观测 filter(MLToolNextYearSelect != '' & Country == 'United States') %>% group_by(MLToolNextYearSelect) %>% summarise(Count = n()) %>% arrange(desc(Count)) data <- head(df_MLT_USA, 10) xname <- 'ML Tool' yname <- 'Count' fun1(data, reorder(data$MLToolNextYearSelect, data$Count), data$Count, xname, yname) ## 探索中国kaggler明年将学习的机器学习工具 # 创建绘图所需数据源(按照MLToolNextYearSelect统计其个数,比按照其个数降序排列) df_MLT_China <- responses %>% # 筛选出MLToolNextYearSelect不为空且中国kaggler的观测 filter(MLToolNextYearSelect != '' & Country == 'China') %>% group_by(MLToolNextYearSelect) %>% summarise(Count = n()) %>% arrange(desc(Count)) data <- head(df_MLT_China, 10) xname <- 'ML Tool' yname <- 'Count' fun1(data, reorder(data$MLToolNextYearSelect, data$Count), data$Count, xname, yname) ################# =========== 明年将学习的机器学习方法 ============= ########### ## 探索kaggler明年将学习的机器学习方法 # 创建绘图所需数据源(按照MLMethodNextYearSelect统计其个数,比按照其个数降序排列) df_MLM <- responses %>% filter(MLMethodNextYearSelect != '') %>% # 筛选MLMethodNextYearSelect不为空的观测 group_by(MLMethodNextYearSelect) %>% summarise(Count = n()) %>% arrange(desc(Count)) data <- head(df_MLM, 10) xname <- 'ML Method' yname <- 'Count' fun1(data, reorder(data$MLMethodNextYearSelect, data$Count), data$Count, xname, yname) ## 探索美国kaggler明年将学习的机器学习方法 # 创建绘图所需数据源(按照MLMethodNextYearSelect统计其个数,比按照其个数降序排列) df_MLM_USA <- responses %>% # 筛选MLMethodNextYearSelect不为空且美国kaggler的观测 filter(MLMethodNextYearSelect != '' & Country == 'United States') %>% group_by(MLMethodNextYearSelect) %>% summarise(Count = n()) %>% arrange(desc(Count)) data <- head(df_MLM_USA, 10) xname <- 'ML Method' yname <- 'Count' fun1(data, reorder(data$MLMethodNextYearSelect, data$Count), data$Count, xname, yname) ## 探索中国kaggler明年将学习的机器学习方法 # 创建绘图所需数据源(按照MLMethodNextYearSelect统计其个数,比按照其个数降序排列) df_MLM_China <- responses %>% # 筛选MLMethodNextYearSelect不为空且中国kaggler的观测 filter(MLMethodNextYearSelect != '' & Country == 'China') %>% group_by(MLMethodNextYearSelect) %>% summarise(Count = n()) %>% arrange(desc(Count)) data <- head(df_MLM_China, 10) xname <- 'ML Method' yname <- 'Count' fun1(data, reorder(data$MLMethodNextYearSelect, data$Count), data$Count, xname, yname) ################# =========== 受访者来自的国家 ============= ################# ## 探索kaggler都来自哪些国家 # 创建绘图所需数据源(按照Country统计其个数,比按照其个数降序排列) df_Country <- responses %>% filter(Country != '' & Country != 'Other') %>% group_by(Country) %>% summarise(Count = n()) %>% arrange(desc(Count)) data <- head(df_Country, 10) xname <- 'Country' yname <- 'Count' fun1(data, reorder(data$Country, data$Count), data$Count, xname, yname) ################# =========== 受访者的就业状况 ================ ################ ## 探索kaggler的就业状况 # 创建绘图所需数据源(按照EmploymentStatus统计其个数,比按照其个数降序排列) df_Employment <- responses %>% group_by(EmploymentStatus) %>% summarise(Count = n()) %>% arrange(desc(Count)) data <- head(df_Employment, 10) xname <- 'EmploymentStatus' yname <- 'Count' fun1(data, reorder(data$EmploymentStatus, data$Count), data$Count, xname, yname) ################# =========== 受访者的学历水平 ===================== ########### ## 探索kaggler的学历水平 # 创建绘图所需数据源(按照FormalEducation统计其个数,比按照其个数降序排列) df_Education <- responses %>% filter(FormalEducation != '') %>% group_by(FormalEducation) %>% summarise(Count = n()) %>% arrange(desc(Count)) data <- head(df_Education, 10) xname <- 'FormalEducation' yname <- 'Count' fun1(data, reorder(data$FormalEducation, data$Count), data$Count, xname, yname) ################# =========== 开始学习数据科学的时间 ================ ########## ## 探索kaggler什么时候开始学习数据科学的 # 创建绘图所需数据源(按照FirstTrainingSelect统计其个数,比按照其个数降序排列 df_FT <- responses %>% filter(FirstTrainingSelect != '') %>% group_by(FirstTrainingSelect) %>% summarise(Count = n()) %>% arrange(desc(Count)) data <- df_FT xname <- 'FirstTrainingSelect' yname <- 'Count' fun1(data, reorder(data$FirstTrainingSelect, data$Count), data$Count, xname, yname) ################# =========== 受访者的学习平台 =============== ################# ## 探索kaggler在什么平台学习数据科学 # 按照‘,’拆分字符串---把CoursePlatformSelect列的字符依据‘,’拆分 platform <- unlist(strsplit(responses$CoursePlatformSelect, ',')) # 统计不同字符串(平台)的频次并转换成数据框 platform <- as.data.frame(table(platform)) data <- platform xname <- 'platform' yname <- 'Count' fun1(data, reorder(data$platform, data$Freq), data$Freq, xname, yname) ################# =========== 任职数据科学的时间 =============== ############### ## 探索kaggler任职数据科学的时间 # 创建绘图所需数据源(按照Tenure统计其个数,比按照其个数降序排列 df_Tenure <- responses %>% filter(Tenure != '') %>% group_by(Tenure) %>% summarise(Count = n()) %>% arrange(desc(Count)) data <- df_Tenure xname <- 'Tenure' yname <- 'Count' fun1(data, reorder(data$Tenure, data$Count), data$Count, xname, yname) ################# =========== 现任职的满意度 ======= ########################### ## 探索kaggler对现职位的满意度 # 创建绘图所需数据源(按照JobSatisfaction统计其个数,比按照其个数降序排列 df_JS <- responses %>% filter(JobSatisfaction != '') %>% group_by(JobSatisfaction) %>% summarise(Count = n()) %>% arrange(desc(Count)) data <- df_JS xname <- 'JobSatisfaction' yname <- 'Count' fun1(data, reorder(data$JobSatisfaction, data$Count), data$Count, xname, yname) ################# =========== 首推的数据科学语言 ========== #################### ## 探索kaggler的首选语言 # 创建绘图所需数据源(按照LanguageRecommendationSelect统计其个数,并按照其个数降序排列 df_LR <- responses %>% filter(LanguageRecommendationSelect != '') %>% group_by(LanguageRecommendationSelect) %>% summarise(Count = n()) %>% arrange(desc(Count)) data <- df_LR xname <- 'LanguageRecommendationSelect' yname <- 'Count' fun1(data, reorder(data$LanguageRecommendationSelect, data$Count), data$Count, xname, yname) ################# =========== 大数据、R、Python、SQL的重要程度 ====== ########## ## 创建新数据框(按照JobSkillImportanceR统计其个数,并按照Count降序排列) df_r <- responses %>% filter(JobSkillImportanceR != '') %>% group_by(JobSkillImportanceR) %>% summarise(Count = n()) %>% arrange(desc(Count)) df_r$Tool <- 'R' # 创建新列,并赋值为‘R’ names(df_r) <- c("Importance", "Count", "Tool") # 对数据框重命名 df_python <- responses %>% filter(JobSkillImportancePython != '') %>% group_by(JobSkillImportancePython) %>% summarise(Count = n()) %>% arrange(desc(Count)) df_python$Tool <- 'python' names(df_python) = c("Importance", "Count", "Tool") df_BigData <- responses %>% filter(JobSkillImportanceBigData != '') %>% group_by(JobSkillImportanceBigData) %>% summarise(Count = n()) %>% arrange(desc(Count)) df_BigData$Tool <- 'BigData' names(df_BigData) = c("Importance", "Count", "Tool") df_SQL <- responses %>% filter(JobSkillImportanceSQL != '') %>% group_by(JobSkillImportanceSQL) %>% summarise(Count = n()) %>% arrange(desc(Count)) df_SQL$Tool <- 'SQL' names(df_SQL) = c("Importance", "Count", "Tool") df_end <- rbind(df_python, df_r, df_BigData, df_SQL) # 对四个数据框进行行合并 ## 绘制百分比堆积柱状图 # position = 'fill'意味着绘制百分比堆积柱状图 ggplot(df_end, aes(x = Tool, y = Count, fill = Importance)) + geom_bar(position = 'fill', stat = 'identity') + labs(y = 'Percent') + theme_minimal() ################# =========== 5个不同国家对SQL、R和Python的推荐 ======== ####### ## 创建数据源(以下5个国家+以下3个语言的观测) df_country_language <- responses[responses$Country %in% c("United States", "India", "Russia", "Japan", "China") & responses$LanguageRecommendationSelect %in% c("R", "Python", "SQL"), ] # 创建绘图所需数据源(按照Country+LanguageRecommendationSelect的组合统计其个数 df_cl <- df_country_language %>% group_by(Country, LanguageRecommendationSelect) %>% summarise(Count = n()) # 绘制百分比堆积柱状图(5个国家首推3个语言对比) ggplot(df_cl, aes(x = Country, y = Count, fill = LanguageRecommendationSelect)) + geom_bar(stat = 'identity') + labs(y = 'Percent') + theme_minimal() <file_sep>/用管道绘制R语言.R library(data.table) library(dplyr) library(ggplot2) responses = fread('multipleChoiceResponses.csv') df_country_age = responses %>% group_by(Country) %>% summarise(AgeMedian = median(Age, na.rm = T)) %>% arrange(desc(AgeMedian)) ggplot(head(df_country_age), aes(x = reorder(Country, AgeMedian), y = AgeMedian))+ geom_bar(aes(fill=Country), stat = 'identity') + labs(x = 'Country', y = 'AgeMedian')+ geom_text(aes(label = AgeMedian), hjust = 1.5, color = 'white') +coord_flip()+ theme_minimal()+ theme(legend.position = 'none') fun1 <- function(data, xlab, ylab, xname, yname){ ggplot(data, aes(xlab, ylab))+ geom_bar(aes(fill=xlab), stat = 'identity')+ labs(x = xname, y = yname)+ geom_text(aes(label = ylab), hjust = 1.5, colour = 'white')+ coord_flip()+ theme_minimal()+ theme(legend.position = 'none') } df_CJT = responses %>% filter(CurrentJobTitleSelect != '') %>% group_by(CurrentJobTitleSelect) %>% summarise(Count = n()) %>% arrange(desc(Count)) data = head(df_CJT, 10) xname = 'Job' yname = 'Count' fun1(data, reorder(data$CurrentJobTitleSelect, data$Count), data$Count, xname, yname)
561af89d8cb7be97c0635a346eeceb5605c18cd4
[ "Markdown", "R" ]
4
R
iloveujing/R_Day_1
8b2908151529d2c5bbf18cad8199cba8fe3647af
5531844eb2051b3f17665a3497a4f143d2a45802
refs/heads/master
<repo_name>Lordtitan001/reseau<file_sep>/ImageFilter/src/Client/Verification.java package Client; import java.io.IOException; import java.util.Scanner; public class Verification { private static int port = 0; private static String ip = ""; public Verification(){} public static boolean validate(final String ip) { String PATTERN = "^((0|1\\d?\\d?|2[0-4]?\\d?|25[0-5]?|[3-9]\\d?)\\.){3}(0|1\\d?\\d?|2[0-4]?\\d?|25[0-5]?|[3-9]\\d?)$"; return ip.matches(PATTERN); } @SuppressWarnings("resource") public Verification initialisation() throws IOException { Scanner in = new Scanner(System.in); boolean ipVerification = true; while (ipVerification) { System.out.println("Entrer l'IP du poste"); ip = in.next(); if (validate(ip)) { ipVerification = false; } } boolean portTest = true; System.out.println("Entrer le port d'ecoute"); while (portTest) { port = in.nextInt(); if (port < 5000 || port > 5050) { System.out.println("La valeur doit etre comprise entre 5000 et 5050"); } else { portTest = false; } } return this; } public int getPort(){ return port; } public String getIp(){ return ip; } }<file_sep>/ImageFilter/src/Server/ClientHandler.java package Server; import java.awt.image.BufferedImage; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.net.Socket; import java.time.LocalDate; import java.time.LocalTime; import java.util.Iterator; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import javax.imageio.ImageIO; import org.json.simple.JSONObject; import org.json.simple.parser.JSONParser; import org.json.simple.parser.ParseException; public class ClientHandler extends Thread { private Socket socket; private int clientNumber; private String jsonFilePath = "./jsonFile.json"; public ClientHandler(Socket socket, int clientNumber) { this.socket = socket; this.clientNumber = clientNumber; System.out.println("Connection with client #" + clientNumber + " at " + socket); } @SuppressWarnings("unchecked") public boolean testUser(User user) throws FileNotFoundException, IOException, ParseException { JSONParser parser = new JSONParser(); Object obj = parser.parse(new FileReader(jsonFilePath)); JSONObject users = (JSONObject) obj; Set<Map.Entry<String,Object>> us = (Set<Map.Entry<String,Object>>) users.entrySet(); if(us.isEmpty()) { writeUser(user); return true; } else { Iterator<Entry<String, Object>> it = us.iterator(); while(it.hasNext()) { JSONObject u = (JSONObject)it.next().getValue(); String username = u.get("username").toString(); String password = u.get("password").toString(); if(username.equals(user.getUsername()) && password.equals(user.getPassword())) { System.out.println("User found.... establishing connexion...."); return true; } else if(password.equals(user.getPassword()) && !username.equals(user.getUsername())) { writeUser(user); return true; } else if(username.equals(user.getUsername())){ return false; } } writeUser(user); return true; } } @SuppressWarnings("unchecked") public void writeUser(User user) throws FileNotFoundException, IOException, ParseException{ System.out.println("Creation of a new User"); JSONParser parser = new JSONParser(); Object obj = parser.parse(new FileReader(jsonFilePath)); JSONObject users = (JSONObject) obj; JSONObject newUser = new JSONObject(); newUser.put("password", <PASSWORD>()); newUser.put("username", user.getUsername()); users.put("user" + users.entrySet().size(), newUser); try { FileWriter jsonFileWriter = new FileWriter(jsonFilePath); jsonFileWriter.write(users.toJSONString()); jsonFileWriter.flush(); jsonFileWriter.close(); } catch (IOException e) { e.printStackTrace(); } } public void run() { try { DataOutputStream out = new DataOutputStream(socket.getOutputStream()); DataInputStream in = new DataInputStream(socket.getInputStream()); User user = new User(in.readUTF(), in.readUTF()); try { if(testUser(user)) { out.writeUTF("Correct password"); out.writeUTF("Welcome from server " + user.getUsername() + " \n" + "Please enter the image name"); System.out.println("Connexion with " + user.getUsername() + " established"); String imagePath = ""; imagePath += in.readUTF(); System.out.println("[ "+ user.getUsername() + " - "+ socket.getInetAddress().toString() + ":" + socket.getLocalPort() + " - " + LocalDate.now() +"@"+ LocalTime.now() + " ] : " + "Image " + imagePath ); int size = in.readInt(); if(size != -1) { int sizeLeft = size; byte[] fileBytes = new byte[size]; int nRead = 0; int off = 0; try { while ((nRead = in.read(fileBytes, off, 5000)) > 0) { sizeLeft -= nRead; off += nRead; if(sizeLeft <= 5000) { break; } } in.read(fileBytes, off, sizeLeft); System.out.println("Image recieved"); } catch(Exception e) { System.out.println("Not able to recieved Image for some reason"); } ByteArrayInputStream bis = new ByteArrayInputStream(fileBytes); BufferedImage bImage2 = ImageIO.read(bis); bImage2 = Sobel.process(bImage2); ByteArrayOutputStream baos = new ByteArrayOutputStream(); ImageIO.write( bImage2, "jpg", baos ); baos.flush(); fileBytes = baos.toByteArray(); size = fileBytes.length; try { out.writeInt(size); out.write(fileBytes, 0, size); } catch(Exception e) { System.out.println("Not able to send Image for some reason"); } } else { System.out.println("Not able to recieve Image for some reason"); } } else { System.out.println("wrong password"); out.writeUTF("Wrong password"); } } catch (Exception e) { e.printStackTrace(); } } catch (IOException e) { System.out.println("Error handlind client #" + clientNumber + " : " + e); } finally{ try { socket.close(); } catch (Exception e) { System.out.println("Not able to close the socket"); } System.out.println("Connexion with client #" + clientNumber + " closed"); } } }
b09dffc8df7666010f63d4328080abaf5d6f6895
[ "Java" ]
2
Java
Lordtitan001/reseau
71f5f290728818c445d90e5a2772fa1040694958
bee20558d575840f24b1ce624a0e3bf4c299c7f4
refs/heads/master
<file_sep>import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.math.BigInteger; /** * Created by jakub on 22/12/2018 */ public class SchoolProgram implements ActionListener { ElementsCreator em ; public SchoolProgram(ElementsCreator em){ this.em=em; em.setActionListeners(this); } @Override public void actionPerformed(ActionEvent event) { switch (event.getActionCommand().toLowerCase()) { case "generate username": em.setUsernameTextBox(em.calculateUsername()); break; case "calculate": // if(em.getFactorial() instanceof Integer){ BigInteger i = em.calculateFactorial(em.getFactorial()); // } em.setValueLabel(i); //calculate the factorial and set the view accordingly. break; case "a)": //go to username page em.openUsernameScreen(); break; case "b)": //go to factorial page em.openFactorialScreen(); break; case "main menu": //go home // em.openMainMenu(); break; case "quit": // em.exit(); break; } } public static final void main(String[] args) { ElementsCreator em = new ElementsCreator(); SchoolProgram sch = new SchoolProgram(em); // SchoolProgram schoolProgram = new SchoolProgram(); // // JFrame frame = new JFrame(); // JPanel jpanel1 = new JPanel(); // //// jpanel1.setLayout(); // //frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //frame.setTitle("XXX"); //frame.setSize(400,400); //frame.setVisible(true); // // // // TextField x = new TextField(); // x.setEditable(false); // x.setSize(100,100); // x.setVisible(true); // x.setText("First Name"); // TextField tf= new TextField(); // tf.setText("huashduashuusahdhasu"); // tf.setVisible(true); // tf.setSize(100,100); // jpanel1.add(x); // jpanel1.add(tf); // frame.add(jpanel1, BorderLayout.NORTH); // jpanel1.updateUI(); // //// TextField tf= new TextField(); // // } } <file_sep>import com.sun.deploy.util.StringUtils; import javax.swing.*; import javax.swing.border.LineBorder; import java.awt.*; import java.awt.event.ActionListener; import java.math.BigDecimal; import java.math.BigInteger; import java.text.NumberFormat; /** * Created by jakub on 27/12/2018 */ public class ElementsCreator extends JSplitPane { private static Font FONT = new Font("Arial", 1, 16); private static final Dimension LABEL_DIM = new Dimension(100, 20); private static final Dimension DIM = new Dimension(120, 20); private static final LineBorder blueBorder = new LineBorder(Color.blue); private JTextArea usernameTextBox; private JPanel addingTool; private JSplitPane splitMenuPanel; public Container frameContainer; public JFrame frame; JTextArea lastNameTextBox; JTextArea firstNameTextBox; JFormattedTextField factorialTextBox; public JPanel optionAPanel; public JPanel optionBPanel; public JPanel optionBPanel2; JLabel resultLabel; JButton optionA = new JButton("A)"); JButton optionB = new JButton("B)"); JButton mainMenu = new JButton("Main Menu"); JButton quit = new JButton("Quit"); JButton generateUsernameButton ; JButton calculateButton; public ElementsCreator (){ panel(); mainMenu(); createElements(); } public void setActionListeners(ActionListener act){ generateUsernameButton.addActionListener(act); optionA.addActionListener(act); optionB.addActionListener(act); mainMenu.addActionListener(act); quit.addActionListener(act); calculateButton.addActionListener(act); } public void mainMenu(){ JPanel mainPanel = new JPanel(); optionA = new JButton("A)"); optionA.setToolTipText("Go to username generation screen."); optionA.setBackground(Color.white); optionB = new JButton("B)"); optionB.setToolTipText("Go to factorial nummber calculation screen."); optionB.setBackground(Color.white); mainMenu = new JButton("Main Menu"); mainMenu.setToolTipText("Go back to the main menu."); mainMenu.setBackground(Color.white); quit = new JButton("Quit"); quit.setToolTipText("Exit the program."); quit.setBackground(Color.white); mainPanel.add(optionA); mainPanel.add(optionB); mainPanel.add(quit); frame.add(mainPanel); // frame.pack(); // frame.setVisible(true); } public void createElements() { GridBagConstraints gbc = new GridBagConstraints(); JPanel addingPanel = new JPanel(); addingPanel.setLayout(new GridLayout(0, 1)); //first name JPanel firstName = new JPanel(); JLabel firstNameLabel = new JLabel("First Name:"); firstNameTextBox = new JTextArea(""); firstNameTextBox.setPreferredSize(DIM); firstNameTextBox.setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT); firstNameTextBox.getDocument().putProperty("filterNewlines", Boolean.TRUE); firstNameTextBox.setBorder(blueBorder); firstName.add(firstNameLabel); firstName.add(firstNameTextBox); //last name JPanel lastName = new JPanel(); JLabel lastNameLabel = new JLabel("First Name:"); lastNameTextBox = new JTextArea(""); lastNameTextBox.setPreferredSize(DIM); lastNameTextBox.setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT); lastNameTextBox.getDocument().putProperty("filterNewlines", Boolean.TRUE); lastNameTextBox.setBorder(blueBorder); lastName.add(lastNameLabel); lastName.add(lastNameTextBox); JLabel usernameLabel = new JLabel("username:"); usernameLabel.setToolTipText("Please enter minimum username"); usernameLabel.setFont(FONT); usernameLabel.setPreferredSize(LABEL_DIM); usernameTextBox = new JTextArea(""); usernameTextBox.setPreferredSize(DIM); usernameTextBox.setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT); usernameTextBox.setToolTipText(""); usernameTextBox.getDocument().putProperty("filterNewlines", Boolean.TRUE); usernameTextBox.setBorder(blueBorder); JPanel usernamePanel = new JPanel(); usernamePanel.add(usernameLabel); usernamePanel.add(usernameTextBox); addingPanel.add(usernamePanel); // addingTool = new JPanel(); // addingTool.setLayout(new GridBagLayout()); // addingTool.setMinimumSize(new Dimension(300, 375)); // addingTool.setPreferredSize(new Dimension(300, 375)); // addingTool.setBorder(blueBorder); JPanel generateUsernamePanel = new JPanel(); generateUsernameButton = new JButton("Generate Username"); generateUsernameButton.setToolTipText("Press Add to store data"); generateUsernameButton.setBackground(Color.white); generateUsernamePanel.add(generateUsernameButton); optionAPanel = new JPanel(); optionAPanel.add(firstName); optionAPanel.add(lastName); optionAPanel.add(addingPanel); optionAPanel.add(generateUsernamePanel); optionAPanel.setVisible(false); //option 2 optionBPanel = new JPanel(); JLabel valueLabel = new JLabel("Factorial number of:"); factorialTextBox = new JFormattedTextField(NumberFormat.getInstance()); factorialTextBox.setPreferredSize(DIM); factorialTextBox.setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT); factorialTextBox.getDocument().putProperty("filterNewlines", Boolean.TRUE); factorialTextBox.setBorder(blueBorder); JLabel label = new JLabel(" = "); resultLabel = new JLabel(""); // usernameLabel.setToolTipText("Please enter minimum username"); usernameLabel.setFont(FONT); usernameLabel.setPreferredSize(LABEL_DIM); calculateButton = new JButton("calculate"); calculateButton.setToolTipText("Press Add to store data"); calculateButton.setBackground(Color.white); optionBPanel.add(valueLabel); optionBPanel.add(factorialTextBox); optionBPanel.add(label); optionBPanel.add(calculateButton); // optionBPanel.add(resultLabel); optionBPanel2 = new JPanel(); optionBPanel2.add(resultLabel); optionBPanel.setVisible(false); frame.add(optionAPanel); frame.add(optionBPanel); frame.add(optionBPanel2); frame.pack(); frame.setVisible(true); } public void panel(){ frame = new JFrame(); frame.setTitle("TITLE"); frame.setLocation(500, 100); frame.setMinimumSize(new Dimension(1024, 750)); frameContainer = frame.getContentPane(); frameContainer.setLayout(new FlowLayout()); // frameContainer.setBackground(Color.WHITE); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } public void setUsernameTextBox(String text){ usernameTextBox.setText(text); } public String calculateUsername(){ if(firstNameTextBox != null && firstNameTextBox.getText().length() > 0){ if(lastNameTextBox != null && lastNameTextBox.getText().length() > 0){ String firstName = firstNameTextBox.getText().toLowerCase().substring(0,1); String lastName = lastNameTextBox.getText().toUpperCase(); return firstName+lastName; }else{ //error no last name } }else{ //error no first name... } return ""; } // public BigInteger calculateFactorial(BigInteger n){ // // if (n.g // return 1; // else // return(n * calculateFactorial(n-1)); // } public static BigInteger calculateFactorial(BigInteger number) { BigInteger result = BigInteger.valueOf(1); for (long factor = 2; factor <= number.longValue(); factor++) { result = result.multiply(BigInteger.valueOf(factor)); } return result; } public void openUsernameScreen(){ optionAPanel.setVisible(true); optionBPanel.setVisible(false); } public void openFactorialScreen(){ optionAPanel.setVisible(false); optionBPanel.setVisible(true); } public void setValueLabel(BigInteger x){ resultLabel.setText(String.valueOf(x)); } public BigInteger getFactorial(){ return BigInteger.valueOf(Long.valueOf(factorialTextBox.getText())); } }
729fe7c7631ba145950b00c9e8c740c4addc59c6
[ "Java" ]
2
Java
jakub-wojcik/school-program
5e61983490da13f5a56980049515b419337b1238
6a05b7523f60c63b3bb8c3f1e0a0728f13743885
refs/heads/master
<file_sep># Keep track of lots of history HISTFILE=~/.histfile HISTSIZE=10000 SAVEHIST=10000 setopt APPEND_HISTORY # Allow use of ** globbing setopt EXTENDED_GLOB # Fail with an error if glob fails to match any files setopt NO_MATCH # Allow writing **.x instead of **/*.x (requires zsh 5.1+) setopt GLOB_STAR_SHORT 2>/dev/null # Allow writing comments in interactive mode (why not?) setopt INTERACTIVE_COMMENTS # Simple prompt that doesn't change size PROMPT="%B%F{cyan}zsh:%f%b " PROMPT2="$PROMPT" # asdf nodejs defaults are not great export NODEJS_CHECK_SIGNATURES=no export ASDF_SKIP_RESHIM=1 # Load plugins that might exist on this device __source ~/.zsh-autosuggestions/zsh-autosuggestions.zsh __source ~/.asdf/asdf.sh # Change the zsh-autosuggestion colors (must be set after loading the plugin...) ZSH_AUTOSUGGEST_HIGHLIGHT_STYLE="fg=cyan" # Load autocomplete data for asdf fpath=(${ASDF_DIR}/completions $fpath) autoload -Uz compinit compinit # Use tab completion to install missing plugins on the current system __install.autosuggestions() { git clone --depth 1 \ https://github.com/zsh-users/zsh-autosuggestions \ ~/.zsh-autosuggestions } __install.asdf() { git clone https://github.com/asdf-vm/asdf.git ~/.asdf } __install.asdf.nodejs() { asdf plugin-add nodejs https://github.com/asdf-vm/asdf-nodejs.git } # Print a blank line between prompts to make it easier to read precmd() { echo } # zsh (and bash) have a strange feature where the shell exits with the status # code of the last command you ran. This means that if you Control-C to SIGINT a # command, then exit the shell, your terminal emulator might warn you about the # command (zsh) failing. This fixes the issue by always exiting interactive zsh # sessions with status code 0. zshexit() { true exit 0 } # Easy open files if [[ $(uname -r) = *Microsoft ]]; then alias o='explorer.exe' else alias o='open' fi # Use color with ls if [[ $(uname) = Darwin ]]; then alias ls="ls -G" else alias ls="ls --color=auto" fi # Allow pasting commands with "$" from the internet alias '$'="" # Time saving shortcuts alias g="git status" alias g="git log" alias l="ls" alias ll="ls -hl" alias la="ll -a" # Weird tmux shortcuts I like alias t="tmux" alias T="tmux attach -d" # Faster directory movement alias d='pwd' alias s="cd ..; pwd" alias ..="s" # Show a cute little graphic in the terminal if [[ ! $__already_welcome && -f ~/.welcome ]]; then cat ~/.welcome fi export __already_welcome="true" # Load device specific customizations __source ~/.after.zshrc.zsh <file_sep># Python virtualenv assumes you want your shell prompt mangled without this export VIRTUAL_ENV_DISABLE_PROMPT="true" # English and Unicode, please export LANG="en_US.UTF-8" # Make folders bold using ls on macOS export LSCOLORS="ExfxcxdxBxegedabagacad" # Edit using VSCode for git command line stuff export EDITOR="code --wait" export GIT_EDITOR="$EDITOR" export VISUAL="$EDITOR" # less is better than more export PAGER="less" path=( # Load user installed commands "$HOME/.local/bin" # Load Rust Cargo commands "$HOME/.cargo/bin" # Load "restricted" commands for use with sudo "/sbin" "/usr/sbin" # Load commands from Homebrew or other package managers "/usr/local/bin" "/usr/local/sbin" $path ) # Load file if it exists, else fail silently __source() { local file="$1" test -f "$file" && source "$file" } # Load device specific customizations __source ~/.after.zshenv.zsh <file_sep>export PS1="bash: " export PS2="$PS1" export LANG="en_US.UTF-8" export PATH="~/.local/bin:$PATH"
fe3c5c47c490382312efd0348198a08b9b40e872
[ "Shell" ]
3
Shell
saikobee/dotfiles
45c838b5a06699480f83e7b74917b3c07244d2ff
473135ee80df8a6ec161fd6636e74982438bb7e8
refs/heads/master
<file_sep># tattoo-website sitio we de tatuajes <file_sep>//INICIO Deslizar imagenes let animado = document.querySelectorAll('.animado'); function mostrarScroll() { let scrollTop = document.documentElement.scrollTop; let ancho = screen.width; for (let i = 0; i < animado.length; i++) { let alturaAnimado = animado[i].offsetTop; //offsetTop= altura de el inicio del elemento al inicio de la pagina if (alturaAnimado - 600 < scrollTop) { animado[i].style.opacity = 1; animado[i].classList.add("mostrarArriba"); } } } window.addEventListener('scroll', mostrarScroll); //FIN Deslizar imagenes //INICIO ANIMACION MENU window.addEventListener("scroll", function() { let header = document.querySelector("#header"); let img = document.querySelector("img"); let left = document.querySelectorAll("a"); header.classList.toggle("sticky", window.scrollY > 0); img.classList.toggle("logo-invertido", window.scrollY > 0); for (let i = 0; i < left.length; i++) { left[i].classList.toggle("underline-invertido", window.scrollY > 0); } }); //FIN ANIMACION MENU // INICIO DEL LIGHT BOX const images = document.querySelectorAll('.img'); const containerImage = document.querySelector('.container-img'); const imagesContainer = document.querySelector('.img-show'); const menu = document.querySelector('#header'); const lightBox = document.querySelector('#lightBox'); images.forEach(image => { image.addEventListener('click', () => { addImage(image.getAttribute('src'), image.getAttribute('alt')); }); }); const addImage = (srcImage, altImage) => { containerImage.classList.toggle('move'); imagesContainer.classList.toggle('show'); imagesContainer.src = srcImage; } // window.addEventListener('scroll', () => { // let scrollTop = document.documentElement.scrollTop; containerImage.addEventListener('click', () => { containerImage.classList.toggle('move'); imagesContainer.classList.toggle('show'); }); // if (scrollTop == 0) { // console.log('entro a la condicion'); // imagesContainer.classList.remove('show'); // containerImage.classList.remove('move'); // } // }); //FIN DEL LIGHT BOX<file_sep>let indice = 1; muestraSlider(indice); function avanzaSlider(n){ muestraSlider(indice += n); } setInterval(function tiempo(){ muestraSlider(indice+=1); }, 60000); function muestraSlider(n){ let i; let slider = document.querySelectorAll(".miSlider"); if(n > slider.length){ indice = 1; } if(n < 1){ indice = slider.length; } for(i = 0; i < slider.length; i++){ slider[i].style.display = 'none'; } slider[indice-1].style.display = 'block'; }
36144ae57bbf34782230641c56a351dfc1ba1401
[ "Markdown", "JavaScript" ]
3
Markdown
Zaleck-a/tattoo-website
c0a7919ca62dba3271d612f05c4a090e8c614e08
c863b4a65cb19d672a44bb798285e746ae13e502
refs/heads/main
<file_sep>/* 路由 */ import App from '../App.vue' // 由于懒加载页面太多的话会造成webpack热更新太慢,所以开发环境不使用懒加载,只有生产环境使用懒加载 const _import = require('@/plugins/import.' + process.env.NODE_ENV) const Home = _import('home.vue') const UserLogin = _import('userLogin.vue') const ExamCenter = _import('examCenter.vue') const EBook = _import('eBook.vue') const EBookDetail = _import('eBookDetail.vue') const CourseCenter = _import('courseCenter.vue') const CourseDetail = _import('courseDetail.vue') const ArticleCenter = _import('articleCenter.vue') const ArticleDetail = _import('articleDetail.vue') const NoticeCenter = _import('noticeCenter.vue') const NoticeDetail = _import('noticeDetail.vue') const Register = _import('register.vue') const PersonalCenter = _import('personalCenter.vue') const BookChapterContent = _import('bookChapterContent.vue') const PlaySC = _import('playSC.vue') const ClueReport = _import('clueReport.vue') const NnDoClue = _import('unDoneClue.vue') const AssessClue = _import('assessClue.vue') const MartCenter = _import('martCenter.vue') const MartResult = _import('martResult.vue') const MartRecord = _import('martRecord.vue') const MartProductInfor = _import('martProductInfor.vue') const ExamInfor = _import('examInfor.vue') const ExamResult = _import('examResult.vue') const StudyCircleCenter = _import('studyCircleCenter.vue') const StudyCircleDetail = _import('studyCircleDetail.vue') const StudyCircleStage = _import('studyCircleStage.vue') const TrainClass = _import('trainClass.vue') const TrainClass2 = _import('trainClass2.vue') const TrainClassDetail = _import('trainClassDetail.vue') const Error = _import('error.vue') const UserAgreement = _import('userAgreement') const TryPlay = _import('tryplay.vue') const ForgetPassword = _import('forgetPassword.vue') const ClueResult = _import('clueResult.vue') const routes = [ { path: '/', component: App, children: [ { path: '', redirect: '/home', meta: { title: '首页', isSkip: true }// isSkip配置为不检查登录状态 }, // 首页 { name: 'home', path: '/home', component: Home, meta: { title: '首页', isSkip: true } }, { name: 'userLogin', path: '/userLogin', component: UserLogin, meta: { title: '登陆', isSkip: true } }, { name: 'examCenter', path: '/examCenter', component: ExamCenter, meta: { title: '考试中心' } }, { name: 'eBook', path: '/eBook', component: EBook, meta: { title: '电子书' } }, { name: 'eBookDetail', path: '/eBookDetail', component: EBookDetail, meta: { title: '电子书详情' } }, { name: 'courseCenter', path: '/courseCenter', component: CourseCenter, meta: { title: '课程中心' } }, { name: 'courseDetail', path: '/courseDetail', component: CourseDetail, meta: { title: '课程详情' } }, { name: 'articleCenter', path: '/articleCenter', component: ArticleCenter, meta: { title: '文章中心' } }, { name: 'articleDetail', path: '/articleDetail', component: ArticleDetail, meta: { title: '文章详情' } }, { name: 'noticeCenter', path: '/noticeCenter', component: NoticeCenter, meta: { title: '通知公告中心' } }, { name: 'noticeDetail', path: '/noticeDetail', component: NoticeDetail, meta: { title: '通知公告详情' } }, { name: 'register', path: '/register', component: Register, meta: { title: '注册', isSkip: true } }, { name: 'assessClue', path: '/assessClue', component: AssessClue, meta: { title: '线索评估', isSkip: true } }, { name: 'personalCenter', path: '/personalCenter', component: PersonalCenter, redirect: '/personalCenter/clueReport', meta: { title: '个人中心' }, children: [ { name: 'clueReport', path: 'clueReport', meta: { title: '线索提报' }, component: ClueReport }, { name: 'unDoneClue', path: 'unDoneClue', meta: { title: '待评估线索' }, component: NnDoClue } ] }, { name: 'bookChapterContent', path: '/bookChapterContent', component: BookChapterContent, meta: { title: '电子书阅读页面' } }, { name: 'playSC', path: '/playSC', component: PlaySC, meta: { title: '单视频课程播放页面' } }, { name: 'martCenter', path: '/martcenter', meta: { title: '积分商城' }, component: MartCenter }, { name: 'martResult', path: '/martresult', meta: { title: '商城结果' }, component: MartResult }, { name: 'martProductInfor', path: '/martproductinfor', meta: { title: '商城信息' }, component: MartProductInfor }, { name: 'martRecord', path: '/martRecord', meta: { title: '兑换记录' }, component: MartRecord }, { name: 'examInfor', meta: { title: '考试信息' }, path: '/examInfor', component: ExamInfor }, { name: 'examResult', meta: { title: '考试结果' }, path: '/examResult', component: ExamResult }, { name: 'studyCircleCenter', meta: { title: '学习圈中心' }, path: '/studyCircleCenter', component: StudyCircleCenter }, { name: 'studyCircleDetail', meta: { title: '学习圈详情' }, path: '/studyCircleDetail', component: StudyCircleDetail }, { name: 'studyCircleStage', meta: { title: '学习圈分类' }, path: '/studyCircleStage', component: StudyCircleStage }, { name: 'trainClass', meta: { title: '培训班' }, path: '/trainClass', component: TrainClass }, { name: 'trainClass2', meta: { title: '培训班' }, path: '/trainClass2', component: TrainClass2 }, { name: 'trainClassDetail', meta: { title: '培训班详情' }, path: '/trainClassDetail', component: TrainClassDetail }, { name: 'userAgreement', meta: { title: '用户协议', isSkip: true }, path: '/userAgreement', component: UserAgreement }, { name: 'play', path: '/play/tryplay', component: TryPlay }, { name: 'forgetPassword', meta: { title: '找回密码', isSkip: true }, path: '/forgetPassword', component: ForgetPassword }, { name: 'clueResult', meta: { title: '评估结果', isSkip: true }, path: '/clueResult', component: ClueResult }, // error { name: 'error', path: '/error', component: Error, meta: { title: 'error' } } ] }, { path: '*', redirect: '/error' } ] export default routes <file_sep>// 发布路径 // const publicPath = process.env.VUE_APP_ PATHNAME const publicPath = '' // 代理路径 const target = 'http://gysszyzpt.jy365.net/' // 'http://www.tcsmxx.com/' // 'http://test82.jy365.net' // 'http://192.168.1.96:8005' // '' const webpack = require('webpack') module.exports = { publicPath, runtimeCompiler: true, // webpack-dev-server 配置 devServer: { publicPath, proxy: { '/api': { target, changeOrigin: true }, '/lessionnew': { target, changeOrigin: true }, '/Content': { target, changeOrigin: true } } }, configureWebpack: config => { if (process.env.NODE_ENV === 'development') { config.devtool = '#source-map' // config.devtool = 'cheap-source-map' } config.plugins.push( new webpack.ProvidePlugin({ $: 'jquery', jQuery: 'jquery', "windows.jQuery": 'jquery' }) ) } } <file_sep>/* components */ export { default as headerFix } from './headerFix.vue' export { default as footerFix } from './footerFix.vue' export { default as menuList } from './menuList.vue' export { default as searchKey } from './searchKey.vue' export { default as courseVideoList } from './courseVideoList.vue' export { default as courseTableList } from './courseTableList.vue' export { default as articleTableList } from './articleTableList.vue' export { default as noticeTableList } from './noticeTableList.vue' export { default as courseChart } from './courseChart.vue' export { default as articleChart } from './articleChart.vue' export { default as errorImg } from './errorImg' export { default as errorImg2 } from './errorImg2' export { default as errorBookImg } from './errorBookImg' export { default as errorCourseImg } from './errorCourseImg' export { default as noDataImg } from './noDataImg' export { default as jyUpload } from './jyUpload' <file_sep>import Api from './api' import fetch from './fetch' /** * 判断用户是否存在KeepOnline */ export const CheckUserIsExit = (data) => fetch.get(Api.CheckAccountExit.url, { ...Api.CheckAccountExit.data, ...data }) /** * 检查用户登录 */ export const Authorization = (data) => fetch.post(Api.Authorization.url, { ...Api.Authorization.data, ...data }) /** * 保持用户在线 */ export const KeepOnline = (data) => fetch.post(Api.KeepOnline.url, { ...Api.KeepOnline.data, ...data }) /** * 获取用户信息 */ export const GetUserInfo = (data) => fetch.post(Api.GetUerInfo.url, { ...Api.GetUerInfo.data, ...data }) /** * 获取用户信息 */ export const LoginShort = (data) => fetch.post(Api.LoginShort.url, { ...Api.LoginShort.data, ...data }) /** * 登录获取去手机验证码 */ export const SendMsg = (data) => fetch.post(Api.SendMsg.url, { ...Api.SendMsg.data, ...data }) /** * 首页志愿者风采 */ export const StudentStyle = (data) => fetch.post(Api.StudentStyle.url, { ...Api.StudentStyle.data, ...data }) /** * 获取文章频道列表信息 parentId */ export const GetArticleChannelInfoList = (data) => fetch.post(Api.GetArticleChannelInfoList.url, { ...Api.GetArticleChannelInfoList.data, ...data }) /** * 添加评论 */ export const AddComment = (data) => fetch.post(Api.AddComment.url, { ...Api.AddComment.data, ...data }) /** *文章内容 */ export const ArticleContent = (data) => fetch.post(Api.ArticleContent.url, { ...Api.ArticleContent.data, ...data }) /** *生成验证码 */ export const GenerateCode = (data) => fetch.post(Api.GenerateCode.url, { ...Api.GenerateCode.data, ...data }) /** *首页新闻推荐 */ export const ArticleList = (data) => fetch.post(Api.ArticleList.url, { ...Api.ArticleList.data, ...data }) /** *验证验证码 */ export const CheckValidateCode = (data) => fetch.post(Api.CheckValidateCode.url, { ...Api.CheckValidateCode.data, ...data }) /** *验证码登录 */ export const LoginCode = (data) => fetch.post(Api.LoginCode.url, { ...Api.LoginCode.data, ...data }) /** *退出登录 */ export const LoginOut = (data) => fetch.post(Api.LoginOut.url, { ...Api.LoginOut.data, ...data }) /** *踢出其他地方登录 */ export const KickOut = (data) => fetch.post(Api.KickOut.url, { ...Api.KickOut.data, ...data }) /** *修改密码 */ export const UpdatePwd = (data) => fetch.post(Api.UpdatePwd.url, { ...Api.UpdatePwd.data, ...data }) /** *首页轮播 */ export const GetLink = (data) => fetch.post(Api.GetLink.url, { ...Api.GetLink.data, ...data }) /** *首页通知公告 */ export const NoticeList = (data) => fetch.post(Api.NoticeList.url, { ...Api.NoticeList.data, ...data }) /** *首页通知公告 */ export const GetArticleInfoList = (data) => fetch.post(Api.GetArticleInfoList.url, { ...Api.GetArticleInfoList.data, ...data }) /** *首页课程中心ProductionInfoList */ export const CourseList = (data) => fetch.post(Api.CourseList.url, { ...Api.CourseList.data, ...data }) /** *首页社区风采-学员风采 */ export const ProductionInfoList = (data) => fetch.post(Api.ProductionInfoList.url, { ...Api.ProductionInfoList.data, ...data }, { timeout: 10000 }) /** *未读消息 */ export const UnReadNotice = (data) => fetch.post(Api.UnReadNotice.url, { ...Api.UnReadNotice.data, ...data }) /** *电子书频道 */ export const BookCategory = (data) => fetch.post(Api.BookCategory.url, { ...Api.BookCategory.data, ...data }) /** *电子书列表 */ export const BookList = (data) => fetch.post(Api.BookList.url, { ...Api.BookList.data, ...data }) /** *首页学员排行 */ export const RankUserList = (data) => fetch.post(Api.RankUserList.url, { ...Api.RankUserList.data, ...data }) /** *首页街道排行 */ export const RankGroupList = (data) => fetch.post(Api.RankGroupList.url, { ...Api.RankGroupList.data, ...data }) /** *课程点击排行 */ export const CourseClickRank = (data) => fetch.post(Api.CourseClickRank.url, { ...Api.CourseClickRank.data, ...data }) /** *首页文章排行 */ export const GetArticleRank = (data) => fetch.post(Api.GetArticleRank.url, { ...Api.GetArticleRank.data, ...data }) /** *首页实时数据 */ export const LeftRealTimeData = (data) => fetch.post(Api.LeftRealTimeData.url, { ...Api.LeftRealTimeData.data, ...data }) /** *电子书内容 */ export const BookContent = (data) => fetch.post(Api.BookContent.url, { ...Api.BookContent.data, ...data }) /** *章节列表 */ export const BookChapterList = (data) => fetch.post(Api.BookChapterList.url, { ...Api.BookChapterList.data, ...data }) /** *章节详情 */ export const BookChapterContent = (data) => fetch.post(Api.BookChapterContent.url, { ...Api.BookChapterContent.data, ...data }) /** *我的收藏课程 */ export const CourseCollect = (data) => fetch.post(Api.MyCourseCollect.url, { ...Api.MyCourseCollect.data, ...data }) /** * 我的收藏文章 */ export const EssayCollect = (data) => fetch.post(Api.MyEssayCollect.url, { ...Api.MyEssayCollect.data, ...data }) /** * 我的收藏作品 */ export const ProductCollect = (data) => fetch.post(Api.MyProductCollect.url, { ...Api.MyProductCollect.data, ...data }) /** * 我的收藏电子书 */ export const MyBookFavorite = (data) => fetch.post(Api.MyBookFavorite.url, { ...Api.MyBookFavorite.data, ...data }) /** * 我的收藏删除 */ export const CollectDelete = (data) => fetch.post(Api.CollectDelete.url, { ...Api.CollectDelete.data, ...data }) /** * 添加收藏 */ export const FavoriteAdd = (data) => fetch.post(Api.FavoriteAdd.url, { ...Api.FavoriteAdd.data, ...data }) /** * 查看收藏 */ export const FavoriteExist = (data) => fetch.post(Api.FavoriteExist.url, { ...Api.FavoriteExist.data, ...data }) /** * 删除收藏 */ export const FavoriteDelete = (data) => fetch.post(Api.FavoriteDelete.url, { ...Api.FavoriteDelete.data, ...data }) /** * 记录已读 */ export const SetArticleRed = (data) => fetch.post(Api.SetArticleRed.url, { ...Api.SetArticleRed.data, ...data }) /** * 个人学习文档 */ export const StudyStatistics = (data) => fetch.post(Api.StudyStatistics.url, { ...Api.StudyStatistics.data, ...data }) /** * 考试中心 */ export const ExamCenter = (data) => fetch.post(Api.ExamCenter.url, { ...Api.ExamCenter.data, ...data }) /** * 考试详细信息 */ export const GetExamInfo = (data) => fetch.post(Api.GetExamInfo.url, { ...Api.GetExamInfo.data, ...data }) /** * 考试种类列表 */ export const GetExamType = (data) => fetch.post(Api.GetExamType.url, { ...Api.GetExamType.data, ...data }) /** * 考试列表页 */ export const ExamListItem = (data) => fetch.post(Api.ExamListItem.url, { ...Api.ExamListItem.data, ...data }) /** * 考试答案提交 */ export const GetExamReviewInfo = (data) => fetch.post(Api.GetExamReviewInfo.url, { ...Api.GetExamReviewInfo.data, ...data }) /** * 考试结果获取 */ export const PostExam = (data) => fetch.post(Api.PostExam.url, { ...Api.PostExam.data, ...data }) /** * 注册页面获取镇区列表 */ export const GetAllGroupList = (data) => fetch.post(Api.GetAllGroupList.url, { ...Api.GetAllGroupList.data, ...data }) /** * 获取登录注册验证码 */ export const GetLoginVC = (data) => fetch.post(Api.GetLoginVC.url, { ...Api.GetLoginVC.data, ...data }) /** * 注册 */ export const Register = (data) => fetch.post(Api.Register.url, { ...Api.Register.data, ...data }) /** * 注册 */ export const FindPasswordEmail = (data) => fetch.post(Api.FindPasswordEmail.url, { ...Api.FindPasswordEmail.data, ...data }) /** * 添加点赞 */ export const AddUserAssist = (data) => fetch.post(Api.AddUserAssist.url, { ...Api.AddUserAssist.data, ...data }) /** * 文章页面公告列表 */ export const NoticeCategory = (data) => fetch.post(Api.NoticeCategory.url, { ...Api.NoticeCategory.data, ...data }) /** * 删除点赞 */ export const DelUserAssist = (data) => fetch.post(Api.DelUserAssist.url, { ...Api.DelUserAssist.data, ...data }) /** * 更新用户信息 */ export const UpdateUserInfo = (data) => fetch.post(Api.UpdateUserInfo.url, { ...Api.UpdateUserInfo.data, ...data }) /** * 获取评论 */ export const CommentList = (data) => fetch.post(Api.CommentList.url, { ...Api.CommentList.data, ...data }) /** * 网上展厅分类列表 */ export const OnlineShowList = (data) => fetch.post(Api.ProductionCategoryInfoList.url, { ...Api.ProductionCategoryInfoList.data, ...data }) /** * 网上展厅列表内容 */ export const OnlineShowInfor = (data) => fetch.post(Api.ProductionInfoList.url, { ...Api.ProductionInfoList.data, ...data }, { timeout: 40000 }) /** * 网上展厅详细内容 */ export const ProductionDetail = (data) => fetch.post(Api.ProductionDetail.url, { ...Api.ProductionDetail.data, ...data }) /** * 网上展厅获取随机内容 */ export const ProductionListTask = (data) => fetch.post(Api.ProductionListTask.url, { ...Api.ProductionListTask.data, ...data }) /** * 下载网上展厅资料 */ export const DownLoadImages = (data) => fetch.post(Api.DownLoadImages.url + '?id=' + data.id, {}) /** * 课程分类-左侧导航 */ export const CourseCategory = (data) => fetch.post(Api.CourseCategory.url, { ...Api.CourseCategory.data, ...data }) /** * 我的课程 */ export const MyCenter = (data) => fetch.post(Api.MyCenter.url, { ...Api.MyCenter.data, ...data }) /** * 我的课程删除学习中的课程 */ export const DelUserCourseReg = (data) => fetch.post(Api.DelUserCourseReg.url, { ...Api.DelUserCourseReg.url, ...data }) /** * 获取课程类型 */ export const GetCourseType = (data) => fetch.post(Api.GetCourseType.url, { ...Api.GetCourseType.data, ...data }) /** * 获取课程类型 */ export const CourseList2 = (data) => fetch.post(Api.CourseList2.url, { ...Api.CourseList2.data, ...data }) /** * 课程内容 */ export const CourseContent = (data) => fetch.post(Api.CourseContent.url, { ...Api.CourseContent.data, ...data }) /** * 课程内容 */ export const CourseComment = (data) => fetch.post(Api.CourseComment.url, { ...Api.CourseComment.data, ...data }) /** * 获取视频内容 */ export const Play = (data) => fetch.post(Api.Play.url, { ...Api.Play.data, ...data }) /** * Refresh接口 */ export const Refresh = (data) => fetch.post(Api.Refresh.url, { ...Api.Refresh.data, ...data }) /** * 防止播放多个视频 */ export const ClearPlayingCourse = (data) => fetch.post(Api.ClearPlayingCourse.url, { ...Api.ClearPlayingCourse.data, ...data }) /** * 获取mp4视频内容 */ export const PlayJwplay = (data) => fetch.post(Api.PlayJwplay.url, { ...Api.PlayJwplay.data, ...data }) /** * 获取所有商品父级种类 */ export const ProductTypeList = (data) => fetch.post(Api.ShopCenter.url, { ...data }) /** * 获取所有商品父级种类 */ export const MyProductRecordList = (data) => fetch.post(Api.MyProductRecordList.url, { ...Api.MyProductRecordList.data, ...data }) // , { headers: { 'Content-Type': 'application/json' } } /** * 根据条件查询符合条件商品列表 */ export const ProductList = (data) => fetch.post(Api.ProductList.url, { ...Api.ProductList.data, ...data }) /** * 获取商品详细信息 */ export const ProductDetail = (data) => fetch.post(Api.ProductDetail.url, { ...Api.ProductDetail.data, ...data }) /** * 积分商城商品兑换 */ export const SendRecord = (data) => fetch.post(Api.SendRecord.url, { ...Api.SendRecord.data, ...data }) /** * 积分商城热门商品兑换 */ export const ProductHotList = (data) => fetch.post(Api.ProductHotList.url, { ...Api.ProductHotList.data, ...data }) /** * 记录mp4视频进度 */ export const SingleProcess = (data) => fetch.post(Api.SingleProcess.url, { ...Api.SingleProcess.data, ...data }) /** * 记录mp4视频进度 */ export const CourseComment2 = (data) => fetch.post(Api.CourseComment2.url, { ...Api.CourseComment2.data, ...data }) /** * 课程添加笔记 */ export const AddNote = (data) => fetch.post(Api.AddNote.url, { ...Api.AddNote.data, ...data }) /** * 课程删除笔记 */ export const DelNote = (data) => fetch.post(Api.DelNote.url, { ...Api.DelNote.data, ...data }) /** * 课程播放页添加评论 */ export const CourseCommentAdd = (data) => fetch.post(Api.CourseCommentAdd.url, { ...Api.CourseCommentAdd.data, ...data }) /** * 获取jy精英-三分屏课程信息PlayJY */ export const PlayJY = (data) => fetch.post(Api.PlayJY.url, { ...Api.PlayJY.data, ...data }) /** * 防伪造请求 */ export const AntiForgeryToken = (data) => fetch.post(Api.AntiForgeryToken.url, { ...Api.AntiForgeryToken.data, ...data }) /** * 上传学习圈文章 */ export const CircleArticleCreate = (data) => fetch.post(Api.CircleArticleCreate.url, { ...Api.CircleArticleCreate.data, ...data }) /** * 学习圈详情 */ export const CircleDetail = (data) => fetch.post(Api.CircleDetail.url, { ...Api.CircleDetail.data, ...data }) /** * 圈内达人 */ export const CircleArticleHotModel = (data) => fetch.post(Api.CircleArticleHotModel.url, { ...Api.CircleArticleHotModel.data, ...data }) /** * 上传学习圈 */ export const CircleCreate = (data) => fetch.post(Api.CircleCreate.url, { ...Api.CircleCreate.data, ...data }) /** * 学习圈文章列表 */ export const CircleArticleList = (data) => fetch.post(Api.CircleArticleList.url, { ...Api.CircleArticleList.data, ...data }) /** * 热门学习圈 */ export const CircleHotInfoList = (data) => fetch.post(Api.CircleHotInfoList.url, { ...Api.CircleHotInfoList.data, ...data }) /** * 学习圈列表 */ export const CircleInfoList = (data) => fetch.post(Api.CircleInfoList.url, { ...Api.CircleInfoList.data, ...data }) /** * 学习圈类型 */ export const CircleTypeInfoList = (data) => fetch.post(Api.CircleTypeInfoList.url, { ...Api.CircleTypeInfoList.data, ...data }) /** * 获取课程计划 */ export const StudyPlanGet = (data) => fetch.post(Api.StudyPlanGet.url, { ...Api.StudyPlanGet.data, ...data }) /** * 上传课程计划 */ export const StudyPlanUpdate = (data) => fetch.post(Api.StudyPlanUpdate.url, { ...Api.StudyPlanUpdate.data, ...data }) /** * 添加课程计划 */ export const StudyPlanAdd = (data) => fetch.post(Api.StudyPlanAdd.url, { ...Api.StudyPlanAdd.data, ...data }) /** * 获取课程计划 */ export const MyStudyPlan = (data) => fetch.post(Api.MyStudyPlan.url, { ...Api.MyStudyPlan.data, ...data }) /** * 删除课程计划 */ export const DelStudyPlan = (data) => fetch.post(Api.DelStudyPlan.url, { ...Api.DelStudyPlan.data, ...data }) /** * 附件上传 */ export const UploadAttachment = (data, config) => fetch.postFormData(Api.UploadAttachment.url, data, config) /** * 培训班 */ export const TrainingClass = (data) => fetch.post(Api.TrainingClass.url, { ...Api.TrainingClass.data, ...data }) /** * 培训班类型列表 */ export const GetTrainingClassTypeList = (data) => fetch.post(Api.GetTrainingClassTypeList.url, { ...Api.GetTrainingClassTypeList.data, ...data }) /** * 学校列表 */ export const GetTrainingSchoolList = (data) => fetch.post(Api.GetTrainingSchoolList.url, { ...Api.GetTrainingSchoolList.data, ...data }) /** * 培训班详情页 */ export const GetTrainingById = (data) => fetch.post(Api.GetTrainingById.url, { ...Api.GetTrainingById.data, ...data }) /** * 培训班报名(带批量) */ export const TrainingSign = (data) => fetch.post(Api.TrainingSign.url, { ...Api.TrainingSign.data, ...data }) /** * 获取课程笔记列表 */ export const CourseNoteList = (data) => fetch.post(Api.CourseNoteList.url, { ...Api.CourseNoteList.data, ...data }) /** * 获取笔记信息信息 */ export const NoteUpdate = (data) => fetch.get(Api.NoteUpdate.url, { ...Api.NoteUpdate.data, ...data }) /** * 修改笔记信息 */ export const NoteUpdatePost = (data) => fetch.post(Api.NoteUpdate.url, { ...Api.NoteUpdate.data, ...data }) /** * 获取评论类型 */ export const GetCommentType = (data) => fetch.get(Api.GetCommentType.url, { ...Api.NoteUpdate.data, ...data }) /** * 获取我的评论 */ export const MyCommentList = (data) => fetch.post(Api.MyCommentList.url, { ...Api.MyCommentList.data, ...data }) /** * 获取我的考试信息 */ export const MyExamStat = (data) => fetch.post(Api.MyExamStat.url, { ...Api.MyExamStat.data, ...data }) /** * 获取我的考试信息 */ export const NoticeContent = (data) => fetch.post(Api.NoticeContent.url, { ...Api.NoticeContent.data, ...data }) /** * 课程推荐 */ export const RecommendCourse = (data) => fetch.post(Api.RecommendCourse.url, { ...Api.RecommendCourse.data, ...data }) /** * 首页分享资源 */ export const AddQualityResources = (data) => fetch.post(Api.AddQualityResources.url, { ...Api.AddQualityResources.data, ...data }) /** * 提交线索 */ export const AddClub = (data) => fetch.post(Api.AddClub.url, { ...Api.AddClub.data, ...data }, { headers: { 'Content-Type': 'application/json' } }) /** * 提交线索上传图片 */ export const ToLead = (data) => fetch.postFormData(Api.ToLead.url, data) /** * 获取领域信息 */ export const GetIndustryList = (data) => fetch.post(Api.GetIndustryList.url, { ...Api.GetIndustryList.data, ...data }, { headers: { 'Content-Type': 'application/json' } }) /** * 获取领域信息 */ export const GetUnfinshClubList = (data) => fetch.post(Api.GetUnfinshClubList.url, { ...Api.GetIndustryList.data, ...data }, { headers: { 'Content-Type': 'application/json' } }) /** * 获取领域信息 */ export const GetClubDetail = (data) => fetch.post(Api.GetClubDetail.url, { ...Api.GetClubDetail.data, ...data }, { headers: { 'Content-Type': 'application/json' } }) /** * 上传用户头像 */ export const SetUserPhoto = (data) => fetch.post(Api.SetUserPhoto.url, { ...Api.SetUserPhoto.data, ...data }) /* 将所有的API封装起来 */ const allApi = {} for (let key in Api) { if (Api[key].method === 'get') { if (key === 'GetNoticeInfoContent') { allApi[key] = (data) => fetch.get(Api[key].url + '/' + data.Id, { ...Api[key].data, ...data }) } else { allApi[key] = (data) => fetch.get(Api[key].url, { ...Api[key].data, ...data }) } } else if (Api[key].method === 'formData') { allApi[key] = (data, config) => fetch.postFormData(Api[key].url, data, config) } else { allApi[key] = (data) => fetch.post(Api[key].url, { ...Api[key].data, ...data }) } } export default allApi <file_sep>import Vue from 'vue' import App from './App.vue' import VueRouter from 'vue-router' import routes from './router' import store from './store/' import './registerServiceWorker' import ElementUI, { MessageBox } from 'element-ui' import VueComponents from './components/global' import VueAwesomeSwiper from 'vue-awesome-swiper' import { Authorization } from './service/getData' import 'element-ui/lib/theme-chalk/index.css' import 'swiper/dist/css/swiper.css' import VueFilter from './filters' import './style/base.scss' import JsEncrypt from 'jsencrypt' // import { setStore } from './plugins/utils' import Api from './service/api' import Axios from 'axios' import $ from 'jquery' import JyVue from '../public/scripts/js/jyvue' // ./scripts/js/jyvue Vue.use(ElementUI) Vue.use(VueFilter) Vue.use(VueRouter) Vue.use(VueComponents) Vue.use(VueAwesomeSwiper) Vue.config.productionTip = false Vue.prototype.jsEncrypt = JsEncrypt Vue.prototype.$ = $ Vue.use(JyVue) // 检查用户登录状态 const getLoginStatus = (currentUrl) => { // let userInfo = store.state.userInfo // console.log(currentUrl, 55) Authorization({ Controller: 'Do', action: currentUrl }).then(res => { // console.log(res) if (res.Data && res.Data.isauth) { // 清除定时器 let timer = null clearInterval(timer) // 每60s请求一次后台 保持用户登录状态 timer = setInterval(function () { Axios.post(Api.KeepOnline.url + '?_=' + +new Date()).then({ function (response) { } }) }, 60000) } else { if (res.Type == 3) { MessageBox.confirm('在其他设备上已经登录', '', { confirmButtonText: '确定', callback: router.push({ name: 'userLogin', query: { currentUrl: currentUrl } }) }) } else if (res.Type == 1) { router.push({ name: 'userLogin', query: { currentUrl: currentUrl } }) } else if (res.Type == 9) { MessageBox.confirm('在其他平台登录或被其他人登录', '', { confirmButtonText: '确定', callback: router.push({ name: 'userLogin', query: { currentUrl: currentUrl } }) }) } else if (res.Type == 10) { MessageBox.confirm('您还不是本平台会员,将前往您所在的平台' + ':' + res.Message, '', { confirmButtonText: '确定', callback: window.open('http://' + res.Message, '_blank') }) } else if (res.Type == 11) { MessageBox.confirm('请登录', '', { confirmButtonText: '确定', callback: router.push({ name: 'userLogin', query: { currentUrl: currentUrl } }) }) } else if (res.Type == 13) { MessageBox.confirm(res.Message, '', { confirmButtonText: '确定', callback: router.push({ name: 'userLogin', query: { currentUrl: currentUrl } }) }) } else if (res.Type == 15) { MessageBox.confirm(res.Type + ':' + res.Message, '', { confirmButtonText: '确定' }).then(() => { }) } else if (res.Type == 20) { // 登陆之后,跳转问卷调查 } else { // MessageBox.confirm('请登录', '', { // confirmButtonText: '确定', // cancelButtonText: '' // }).then(() => { // router.push({ name: 'userLogin', query: { currentUrl: currentUrl } }) // }) } } }) } const router = new VueRouter({ routes }) router.beforeEach((to, from, next) => { store.dispatch('getUserAgent') let fromUrl = from.fullPath let href = window.location.href if (!/\/favicon\.ico/.test(href)) { localStorage.setItem('fromUrl', fromUrl) } if (!to.meta.isSkip) { if (JSON.stringify(store.state.userInfo) === '{}') { next({ path: '/userLogin' }) } } next() }) router.afterEach((to, from) => { // 存入当前url let currentUrl = to.fullPath let href = window.location.href if (!/\/favicon\.ico/.test(href)) { localStorage.setItem('currentUrl', currentUrl) } if (!to.meta.isSkip) { getLoginStatus(currentUrl) } }) new Vue({ router, store, render: h => h(App) }).$mount('#app') <file_sep>export const toPlay = { // 富媒体课程 RichCourse // 单视频课程 SingleCourse // 图文课程 H5Course // 三分屏课程 ThreeScreenCourse // 音频视频 AudioCourse // 微课课程 MicroCourse // 电子书课程 OfficeCourse // 实景课程 VRCourse methods: { toPlay: function (type, id) { if (type == 'RichCourse' || type == '富媒体课程') { let jumpUrl = this.$router.resolve({ path: '/playRC', query: { id } }) window.open(jumpUrl.href, '_blank') } else if (type == 'SingleCourse' || type == '单视频课程') { // 政府基准的单视频是MP4和flv的 也使用jwplayer播放 let jumpUrl = this.$router.resolve({ path: '/playSC', query: { id } }) window.open(jumpUrl.href, '_blank') } else if (type == 'H5Course' || type == '图文课程') { let jumpUrl = this.$router.resolve({ path: '/playH5C', query: { id } }) window.open(jumpUrl.href, '_blank') } else if (type == 'ThreeScreenCourse' || type == '三分屏课程') { // 三分屏课程就是精英课程 let jumpUrl = this.$router.resolve({ path: '/playTSC', query: { id } }) window.open(jumpUrl.href, '_blank') } else if (type == 'AudioCourse' || type == '音频课程') { let jumpUrl = this.$router.resolve({ path: '/playAC', query: { id } }) window.open(jumpUrl.href, '_blank') } else if (type == 'MicroCourse' || type == '微课课程') { let jumpUrl = this.$router.resolve({ path: '/playMC', query: { id } }) window.open(jumpUrl.href, '_blank') } else if (type == 'VRCourse' || type == '实景课程') { let jumpUrl = this.$router.resolve({ path: '/playVRC', query: { id } }) window.open(jumpUrl.href, '_blank') } else if (type == 'OfficeCourse' || type == '电子书课程') { let jumpUrl = this.$router.resolve({ path: '/playOC', query: { id } }) window.open(jumpUrl.href, '_blank') } } } } <file_sep>/** * 防抖函数 * fn 延时调用的函数 * delay 延时时间 */ export const debounce = (fn, delay) => { let time = delay || 500 let timer return function () { let args = arguments if (timer) { clearTimeout(timer) } timer = setTimeout(() => { fn.apply(this, args) timer = null }, time) } } /** * 节流函数 * fn 延时调用的函数 * wait 延时时间 */ export const throttle = (fn, wait) => { var lastTime = 0 return function (...args) { var now = Date.now() var coolingDown = now - lastTime < wait // ↑ 距离上次执行的间隔,小于设定的间隔时间 => 则处于冷却时间 // 冷却时间,禁止放大招 if (coolingDown) { return } // 记录本次执行的时刻 lastTime = Date.now() // 冷却好了就要放大招 fn.apply(this, args) } } <file_sep>import { GET_USERINFO, GET_USERAGENT, GET_NETWORKTYPE, SAVE_USERINFO, SET_PERSONWINDOW_DISAPPEAR, SET_NOTECHANGE_APPEAR, SET_PLANCHANGE_APPEARCREATE, SET_PLANCHANGE_APPEARFIX, SET_PLANSTARTTIME, SET_PLANFINISHTIME, SET_PLANAWAKEPERIOD, GET_EXAMID, GET_EXAMRESULT, SET_NOTELABEL, SET_NOTEINFOR, SET_HEADCHANGE_APPEAR } from './mutation-types.js' export default { // 获取用户信息 [GET_USERINFO] (state, userInfo) { state.userInfo = userInfo }, // 获取userAgent [GET_USERAGENT] (state, userAgent) { state.userAgent = userAgent }, // 获取网络类型 [GET_NETWORKTYPE] (state, netWorkType) { state.netWorkType = netWorkType }, // 保存用户信息 [SAVE_USERINFO] (state, userInfo) { state.userInfo = userInfo }, // 获取考试ID [GET_EXAMID] (state, examId) { state.examId = examId }, // 获取考试结果信息 [GET_EXAMRESULT] (state, result) { state.examResultValue = result }, // 隐藏所有个人中心弹窗 [SET_PERSONWINDOW_DISAPPEAR] (state) { state.perNoteBox = false state.perPlanBox = false state.perWindow = false state.perHeadBox = false }, [SET_HEADCHANGE_APPEAR] (state) { state.perHeadBox = true state.perWindow = true }, // 显示笔记修改弹窗 [SET_NOTECHANGE_APPEAR] (state, arr) { state.pernoteLabel = arr[0] state.pernoteInfor = arr[1] state.pernoteId = arr[4] state.perNoteForLesson = arr[2] state.perNoteIndex = arr[3] state.perWindow = true state.perNoteBox = true }, [SET_NOTELABEL] (state, value) { state.pernoteLabel = value }, [SET_NOTEINFOR] (state, value) { state.pernoteInfor = value }, // 显示计划添加窗口 [SET_PLANCHANGE_APPEARCREATE] (state, arr) { state.perWindow = true state.perPlanBox = true state.planAddOrChange = '添加' state.planCourseID = arr[0] state.planCourseName = arr[1] state.planCredit = arr[2] state.planStartTime = new Date() state.planFinishTime = new Date() state.planAwakePeriod = 0 }, [SET_PLANCHANGE_APPEARFIX] (state, arr) { state.perWindow = true state.perPlanBox = true state.planAddOrChange = '修改' state.planID = arr[0] state.planCourseID = arr[1] state.planCourseName = arr[2] state.planCredit = arr[3] state.planStartTime = arr[4] state.planFinishTime = arr[5] if (arr[6] == '每天一次') { state.planAwakePeriod = 0 } else if (arr[6] == '每周一次') { state.planAwakePeriod = 1 } else { state.planAwakePeriod = 0 } }, // 设置计划开始时间 [SET_PLANSTARTTIME] (state, value) { state.planStartTime = value }, // 设置计划结束时间 [SET_PLANFINISHTIME] (state, value) { state.planFinishTime = value }, [SET_PLANAWAKEPERIOD] (state, value) { state.planAwakePeriod = value } } <file_sep>import dateFilters from './dateFilter' import filters from './filter' const vueFiltersDate = { install: function (Vue, options) { Object.keys(dateFilters).forEach(name => { Vue.filter(name, dateFilters[name]) }) Object.keys(filters).forEach(name => { Vue.filter(name, filters[name]) }) } } if (typeof window !== 'undefined' && window.Vue) { window.Vue.use(vueFiltersDate) } export default vueFiltersDate <file_sep>import Vue from 'vue' import Vuex from 'vuex' import { getStore, getPCUrl } from '../plugins/utils' import actions from './action' import getters from './getters' import mutations from './mutations' Vue.use(Vuex) const state = { userInfo: getStore('userInfo') || {}, // 用户信息 userAgent: getStore('userAgent') || {}, // 浏览器设备信息 wxIndexUrl: getPCUrl('#/home'), wxLoginUrl: getPCUrl('#/userLogin'), netWorkType: '', // 网络类型 perWindow: false, // 窗口背部阴影打开情况true为打开,false关闭(要打开笔记或者计划窗口比继续先打开背部阴影) perNoteBox: false, // 笔记修改窗口打开情况true为打开,false关闭 perPlanBox: false, // 课程计划窗口打开情况true为打开,false关闭 perHeadBox: false, pernoteLabel: '', // 课程标题 pernoteInfor: '', // 课程内容 perNoteForLesson: '', // 笔记关于哪门课程 perNoteIndex: '', // 笔记ID examId: 0, // 试卷Id存储 examResultValue: 0, // 后台返回试卷结果码 examValue: 0, // 试卷状态码(可能无用) planAddOrChange: '', planID: 0, planCourseID: 0, planCourseName: '', planCredit: 0, planStartTime: '', planFinishTime: '', planAwakePeriod: 0 } export default new Vuex.Store({ state, getters, actions, mutations }) <file_sep>import { setStore, userAgent } from '../plugins/utils' import { GetUserInfo, StudyPlanGet } from '../service/getData' import { GET_USERAGENT, GET_USERINFO, SAVE_USERINFO, SET_PLANCHANGE_APPEARCREATE, SET_PLANCHANGE_APPEARFIX } from './mutation-types.js' export default { async getUserInformation ({ state, commit }, payload) { let data = await GetUserInfo(payload) setStore('userInfo', data.Data || {}) commit(GET_USERINFO, data.Data || {}) }, saveUserInfo ({ state, commit }, payload) { setStore('userInfo', payload || {}) commit(SAVE_USERINFO, payload || {}) }, getUserAgent ({ state, commit }, payload) { let data = userAgent() commit(GET_USERAGENT, data) }, async setplanchangesappear ({ state, commit }, payload) { if (payload[0] == 0) { payload.splice(0, 2) commit(SET_PLANCHANGE_APPEARCREATE, payload) } else { console.log(payload) let msg = await StudyPlanGet({ planId: payload[1] }) let start = new Date(msg.RemindDate) let end = new Date(msg.PlanFinishDate) let arr = [payload[1], payload[2], payload[3], payload[4], start, end, msg.RemindCycle] commit(SET_PLANCHANGE_APPEARFIX, arr) } } }
593f5f9caa4c434232928d27cb0d8c94c298fdf5
[ "JavaScript" ]
11
JavaScript
tingfeng00/gyss-pc
17af4c082c1203f45e2276d92cc29ba7974643cc
d616a5c54def7ef1390b8bcc41463eb3af9dad45
refs/heads/master
<file_sep>""" This is the main entry of sbrpy tool, which purpose is to help people recover their specific type of files from the broken filesystem based on the file signature """ import binascii import struct from collections import defaultdict from BFS import Ext2 def main(): bfs = Ext2('sdb_full') ''' signature_index = [] # scan the whole disk for x in bfs.search(target=Ext2.SIGNATURES['cap'], granu=bfs.block_size): print(x) signature_index.append(x) print('indexes of signature found at: %s ' % signature_index) data_blocks = [] for x in signature_index: target = struct.pack('<i', x) for itable_obj in bfs.get_inode_tables(): for p in itable_obj.search(target): print(p) continue file_data = [] ''' file_iter = bfs.recover_file_by_inode(28669) with open('recovered.cap', 'ab') as f: for d in file_iter: f.write(d) if __name__ == '__main__': main() <file_sep>from collections import defaultdict def log_missing(): print('key added') return 0 def sub_gen(i=10): for x in range(i): yield x print('done') return 'finished' ev = None def deleg(): global ev ev = yield from sub_gen(5) def test2(): d = deleg() for i in d: print(i) print(ev) def test(): current = {'green' : 12, 'red' :3} increcement = [('blue', 2), ('black', 6), ('red', 66)] res = defaultdict(log_missing, current) print(current) for k, v in increcement: res[k] += v print(res) if __name__ == '__main__': test2() <file_sep># sbrpy readme a tool for recovery of specific type of files **Abstract** Signature Based File Recovery is a new strategy of EXT2 files recovery, which leverages the file’s signature to locate target files and then recovery them. By implementing this new strategy, we could recover the files in file system which have broken superblock or/and broken group descriptors even broken inode metadata. **EXT2 File System** Before elaborating the strategy, the knowledge of EXT2 file system will contribute to helping us to have the better understanding of the advantage and basis of this technology. **EXT2 Structure** The EXT2 was devised by <NAME> as an extensible and powerful file system for Linux. It is also the most successful file system so far in the Linux community and is the basis for all of the currently shipping Linux distributions **EXT2 File** Inode is the significant concept of EXT file system, which represents the data structure of an EXT file. All of the inodes are stored in inode table area of each Block Group. A inode is composing of meta-data and data indexes, for data indexes portion, where got split into 4 parts, which are: 1) direct index blocks 2) indirect index block 3) doubled indirect index block and triple indirect index block all of these area store the direct data indexes or indirect data indexes that are point to the data blocks area eventually. **Signature Based File Recovery** A reaction to the disadvantage of common file recovery methods, we created a new strategy of EXT2 file recovery, which leverages the signature of different file types. Before we talk about the details of the strategy, let’s look into the file’s signature. **3.1 File Signature** As we know, different file type has a different type name, that’s how we’re able to distinguish the file types visually; similarly computer could recognize the file type by means of file signature, which is always stored in the first 4 bytes of the file’s data blocks. Locate the index of first data block As we discussed above, the location of the first direct index is the key to find out all data blocks of an EXT2 file, and it is also the significant step to apply our recovery strategy, which could be implemented by locating the index of file’s signature 1) Seek for the address of the PDF signature “25504446” in data blocks area, data block area can be defined by the info in each disk group descriptors. 2) Seek for the “0xF3d2” which is address of 2550 4446 in inode able area, inode table area can be defined by the info in each disk group descriptor, therefore we don’t have to scan the whole disk. 3) Assume “0x082d” is the address of address “0xF3d2”, which is the first direct index of the inode. As long as we found the location of the first direct index of inode, we are able to find all data blocks according to the data structure we discussed in section 2.2, steps shown as below: 1) Foreach read the first 12 direct indexes (12 * 4 bytes direct indexes), and then read the corresponding data blocks. 2) Find the 13th indexes (A 4 bytes indirect index), where stores totally (block_size)/4 data block addresses indirectly, and then copy the corresponding data blocks. 3) Find the 14th index (A 4 bytes double-indirect index), where stores totally 〖((block_size)/4)〗^2 data block addresses indirectly, and then copy the corresponding data blocks. 4) Find the 15th index (A 4 bytes triple-indirect index), where stores totally 〖((block_size)/4)〗^3 data block addresses indirectly, and then copy the corresponding data blocks. 5) Write all copied data blocks in above 4 steps into a new file. Therefore we could easily recover all data of PDF file by above steps. **Summaries** As the strategy of Signature Based File Recovery is trying to find out the first index directly, so it’s more powerful compare to regular methods, which highly relies on the data integrity of super blocks, disk group info and even file inode’s metadata. The algorithms we mentioned above are also applicable to other similar file-systems like EXT3 and EXT4, even UFS32/UFS64 as which is also an inode based file-system. <file_sep>""" This file defines the target filesystem class where the target files imprisoned """ import os import re import mmap import binascii import struct from collections import defaultdict class Ext2: """ Ext2 file-system """ DUMP2FS = 'sudo dump2fs ' RE_GROUP = re.compile( 'Group (\d+): \(Blocks (\d+)-(\d+)\)', re.IGNORECASE) RE_ITABLE = re.compile( '\s{2}Inode table at (\d+)-(\d+)', re.IGNORECASE) # signatures of common file types SIGNATURES = { 'cap': 'd4c3b2a1', 'jpg': 'ffd8ffe1', 'png': '89504e47', 'pdf': '25504446', 'exe': '4d5a9000', 'tar.gz': '1f8b08', 'mp4': '00000014', 'mp3': '49443303', 'rmvb': '2e524d46', 'txt': '23696e63', } @classmethod def get_signature(cls, file_type=None): """ get the signature code by given name of file_type :param file_type: name of file type expected got its signature :return: signature of specify file_type or all whole signature dict :exception: KeyError if given file_type not found """ try: if file_type is None: return cls.SIGNATURES else: return cls.SIGNATURES[file_type] except KeyError: raise KeyError('error: passed key %s was not found' % file_type) @classmethod def add_signature(cls, file_type=None, signature_code=None): """ add the signature dict item to SIGNATURE dict :param file_type: name of file_type :param signature_code: signature code associated with the file_type :return: True :exception: KeError will be raised if any parameters missing """ if file_type or signature_code is None: raise KeyError('error: both parameter file_type and signature_code are required') cls.SIGNATURES[file_type] = signature_code return True @classmethod def delete_signature(cls, file_type=None): """ delete the signature record from SIGNATURE dict :param file_type: name of file_type to be deleted :return: True :exception: ValueError will be raised if any parameters missing """ if file_type is None: raise ValueError('error: parameter file_type is required') del cls.SIGNATURES[file_type] def __init__(self, disk=None, block_size=4096): """ init func while initialize a BFS object :param disk: disk path of target broken file-system :param block_size: block size of the file-system, default is 4K """ if os.path.exists(disk): self.disk = disk self.block_size = block_size # should be multiple of 1024 always else: raise FileNotFoundError def _dump_fs(self): import subprocess command = self.DUMP2FS + self.disk res = subprocess.check_output(command) print(res) return res def _dump_fs_fake(self): with open('C:\\Work\\tmp\\sdb_dumpe.txt', 'r') as f: return f.read() def open(self): """ open target file-system :return: file handle """ return open(self.disk, mode='rb') def get_inode_tables(self): """ get all the inode table objects of the current Ext2 filesystem object :return: all the inode table objects """ output = self._dump_fs_fake() for line in output.splitlines(): mi = self.RE_ITABLE.match(line) if mi: # initialize a inode table object yield InodeTable(self.disk, int(mi.group(1)), int(mi.group(2))) @classmethod def combined_iter(cls, iters): for it in iters: yield from it def get_itable_data(self, granu=4): """ get the data stored in inode tables area, this is a generator function :param granu: granularity of size to be compared during searching, default is block size :return: yield data blocks with format: (index, block_data) """ with open(self.disk, mode='rb') as f: for data in self.combined_iter(self.get_inode_tables()): if granu == len(data[1]): yield (data[0]*self.block_size, data) else: for _ in range(int(len(data[1])/granu)): yield (data[0]*self.block_size+granu, f.read(granu)) def get_disk_groups(self): """ get all disk group info :return: all disk groups info """ groups = [] # disk groups output = self._dump_fs_fake() i = 0 for line in output.splitlines(): mg = self.RE_GROUP.match(line) if mg: groups.append((int(mg.group(1)), int(mg.group(2)), int(mg.group(3)))) return groups def search(self, target=None, granu=4): """ search target string in the whole filesystem, yield its index if found :param target: target string to be searched :param granu: granularity of each step to go during searching :return: yield the first index of first byte of match """ if target is None: raise ValueError('error: mandatory parameter tareget was missing') target = binascii.unhexlify(target) if len(target) > granu: return -1 with open(self.disk, 'rb') as f: for index, block in self: # searching in each block for x in range(int(len(block)/granu)): pos = index * len(block) + granu * x f.seek(pos) data = f.read(granu) if data.find(target) == 0: yield pos def get_size(self): return os.path.getsize(self.disk) def recover_file_by_inode(self, first_block_index): """ recover a file by given first block index :param first_block_index: the index of the first block in inode data structure :return: yield data blocks """ fd = os.open(self.disk, os.O_RDONLY) size = os.path.getsize(self.disk) file_mmap = mmap.mmap(fd, size, access=mmap.ACCESS_READ) file_mview = memoryview(file_mmap).cast('I') # first 12 4B stores the addresses of data blocks for i in range(12): start = first_block_index + 4 * i if file_mview[start::self.block_size] != 0: yield file_mmap[start::self.block_size] else: file_mmap.close() pass # address of indirect block is at 13th indirect_block_addr = file_mmap[first_block_index + 12 * 4::4] indirect_block = file_mmap[indirect_block_addr::self.block_size] for x in range(len(indirect_block)/4): if memoryview(indirect_block).cast('I')[x] != 0: yield indirect_block[x] else: file_mmap.close() pass # address of double indirect blocks is at 14th d_indirect_block_addr = file_mmap[first_block_index + 13 * 4::4] indirect_addr_block = file_mmap[d_indirect_block_addr::self.block_size] for x in range(len(indirect_addr_block)/4): data_addr = memoryview(indirect_addr_block).cast('I')[x] if data_addr != 0: for y in range(data_addr/4): if memoryview(indirect_addr_block).cast('I') != 0: yield indirect_addr_block[y] else: file_mmap.close() pass file_mmap.close() # temporarily ignore triple indirect blocks def __iter__(self): """ to make file-system be iterable :return: (index, data) """ with open(self.disk, mode='rb') as f: for index in range(int(os.path.getsize(self.disk)/self.block_size)): data = f.read(self.block_size) yield (index, data) def __repr__(self): return self.disk class InodeTable: """ a class which represent the inode table data structure of a filesystem """ __slot__ = ['start', 'end', 'size', 'filesystem'] # saving memory def __init__(self, filesystem = None, start_block=None, end_block=None): if filesystem and start_block and end_block is not None: self.filesystem = filesystem self.start = start_block self.end = end_block self.size = end_block - start_block + 1 else: raise ValueError('error: mandatory parameter(s) was missing') def search(self, target=None, granu=4): """ search for given target :param target: target string to be search in inode table :param granu: granularity to steps during searching :return: target string and its index """ if target is None: raise ValueError('error: mandatory parameter target was missing') if target is isinstance(target, bytes): target = binascii.unhexlify(target) if len(target) > granu: raise ValueError('error: parameter target should not larger than parameter granu') with open(self.filesystem, 'rb') as f: for index, block in self: # searching in each block for x in range(int(len(block)/granu)): pos = index * len(block) + granu * x f.seek(pos) data = f.read(granu) if data.find(target) == 0: yield pos def __iter__(self): """ to make inode table object be iterable :return: each block and its index of inode table """ with open(self.filesystem, 'rb') as f: for index in range(self.start, self.end): yield (index, f.read(index)) def __repr__(self): return self.start, self.end, self.size <file_sep>""" This file defines the target filesystem class where the target files to nested """ class BFS: """ Base class of Broken File System """ def __init__(self, disk_path): """ init method :param disk_path: path to the target disk :return None """ self.disk = disk_path self.fd = None self.f_size = None @property def fs_size(self): """ get the size info of file-system :return: size of file-system """ return
696216a7b607e9d3251c9c25046b3851e53836b2
[ "Markdown", "Python" ]
5
Python
hynoor/sbrpy
02156b15605f51b6c09f12aaad6ebf16cbe7085b
e6698e5118c08643e450aa588536ada0a9c4bb69
refs/heads/master
<file_sep>import java.util.Random; public class EthernetSimulation { private static int BackOff = 200; private static int IFS = 50; private static int Wait = 200; private static int limit = 16; public static void main(String[] args) { Random random = new Random(); //print the title System.out.printf("%s %10s %11s %12s %6s\n %28s %11s %8s\n", "Index", "Re-Trys", "RTS|CTS", "ACK|Data", "Max", "Failures", "Failures", "Slots"); for(int i = 0; i < 25; i++) { //station has frame to send boolean tryagain = true; //while this is true the loop will loop through again int K = 0; int slots = 0; int ACKfail = 0; int RTSfail = 0; while(tryagain) { //channel is free long s = System.currentTimeMillis(); while(System.currentTimeMillis() - s < IFS) { //do nothing } slots = (int)Math.pow(2, K) - 1; //send rts s = System.currentTimeMillis(); while(System.currentTimeMillis() - s < Wait) { //do nothing } if(random.nextBoolean()) //CTS received before timeout? { s = System.currentTimeMillis(); while(System.currentTimeMillis() - s < IFS) { //do nothing } //send frame s = System.currentTimeMillis(); while(System.currentTimeMillis() - s < Wait) { //do nothing } if(random.nextBoolean()) //ACK received before timeout { //transmission was a success break;//this breaks the try again while loop } else { ACKfail++; } }//end if else { RTSfail++; } K++; if(K > limit) { break;//this breaks the try again while loop }//end if s = System.currentTimeMillis(); while(System.currentTimeMillis() - s < BackOff) { //do nothing } }//end try again System.out.printf("%4d %8d %11d %12d %10d\n", i+1, K, RTSfail, ACKfail, slots); }//end number of frames }//end main }//end class <file_sep># <NAME> and <NAME> # 09/22/2016 # HW3 Q1 Starter Code # Implementation of interval partitioning algorithm import datetime from heapq import heappush , heappop def scheduleRooms(rooms,cls): """ Input: rooms - list of available rooms cls - dictionary mapping class names to pair of (start,end) times Output: Return a dictionary mapping the room name to a list of non-conflicting scheduled classes. If there are not enough rooms to hold the classes, return 'Not enough rooms'. """ rmassign = {} PQ = [] for i in cls: x = cls[i] #grab dictionary tuple y = x[0] #first value z = x[1] #second value if y < z: #compare to get start time heappush(PQ, (y, cls[i], i)) else: heappush(PQ, (z, cls[i], i)) counter = 0 while PQ: temp = heappop(PQ) start = temp[0] key = temp[1] #not actually key. its the value in the key name = (temp[2]) #this is the real key namtup = (name,) key = namtup + key for j in rooms: if j in rmassign: assigned = list(rmassign.get(j)) lengths = len(assigned) assend = assigned[lengths-1] if assend <= start: del assigned[lengths-1] del assigned[lengths -2] assigned = tuple(assigned) rmassign[j] = assigned + (key) #adds class and times counter += 1 break elif not (rmassign.has_key(j)): #if the room doesn't have anything store rmassign[j] = (key) counter += 1 break #deletes last two remaining times in rmassign for k in rmassign: dell = list(rmassign[k]) length = len(dell) del dell[length-1] del dell[length-2] dell = tuple(dell) rmassign[k] = dell if counter < len(cls): return "There are not enough rooms!" return rmassign if __name__=="__main__": cl1 = {"a": (datetime.time(9),datetime.time(10,30)), "b": (datetime.time(9),datetime.time(12,30)), "c": (datetime.time(9),datetime.time(10,30)), "d": (datetime.time(11),datetime.time(12,30)), "e": (datetime.time(11),datetime.time(14)), "f": (datetime.time(13),datetime.time(14,30)), "g": (datetime.time(13),datetime.time(14,30)), "h": (datetime.time(14),datetime.time(16,30)), "i": (datetime.time(15),datetime.time(16,30)), "j": (datetime.time(15),datetime.time(16,30))} rm1 = [1,2,3] print cl1 print scheduleRooms(rm1,cl1) print scheduleRooms([1,2],cl1) ensrooms = ['KEH U1','KEH M1','KEH M2','KEH M3','KEH U2','KEH U3','KEH U4','KEH M4','KEH U8','KEH U9'] csclasses = {'CS 1043': (datetime.time(9,30),datetime.time(11)), 'CS 2003': (datetime.time(10,30),datetime.time(12)), 'CS 2123': (datetime.time(11,15),datetime.time(12,45)), 'CS 3003': (datetime.time(8,15),datetime.time(11,30)), 'CS 3353': (datetime.time(11),datetime.time(12)), 'CS 4013': (datetime.time(13),datetime.time(14,45)), 'CS 4063': (datetime.time(12,30),datetime.time(14,30)), 'CS 4123': (datetime.time(14),datetime.time(15)), 'CS 4163': (datetime.time(14),datetime.time(16,30)), 'CS 4253': (datetime.time(12),datetime.time(16)), } print csclasses print scheduleRooms(ensrooms,csclasses) print scheduleRooms(ensrooms[:4],csclasses)<file_sep># Various-Programs Here are some various programs and assignments that I've made over the past four years. <file_sep>#<NAME> # Starter Code for Counting Inversions, Q1 HW4 # CS 2123, The University of Tulsa from collections import deque #i treated the sequence like a list and didn't see the need to use these import itertools def mergeandcount(lft, rgt): """ Glue procedure to count inversions between lft and rgt. Input: two ordered sequences lft and rgt Output: tuple (number inversions, sorted combined sequence) """ curr1 = 0 #lft pointer curr2 = 0 #rgt pointer count = 0 #counter for inversions seq = [] #sorted combined sequence while curr1<len(lft) and curr2<len(rgt): a = lft[curr1] b = rgt[curr2] if a < b: #element in a is smaller seq.append(a) #add a to the result curr1 += 1 #increment through lft by 1 else: #element in b is smaller seq.append(b) #add b to result print b, " conflicts with ", a count = count + (len(lft) - curr1) #adding the length of whats left in the list to the counter curr2 += 1 #increment through rgt by 1 if len(rgt) == curr2:#if the right side ran out of values first seq.extend(lft[curr1:]) #add the remainder of the list if len(lft) == curr1: #if the left side ran out of values first seq.extend(rgt[curr2:]) #add the remainder of the list return (count, seq) def sortandcount(seq): """ Divide-conquer-glue method for counting inversions. Function should invoke mergeandcount() to complete glue step. Input: ordered sequence seq Output: tuple (number inversions, sequence) """ if len(seq) == 1: #if the length of the sequence is 1 return (0, seq) #there are no inversions and it is sorted mid = len(seq)/2 #middle index left = seq[:mid] #left half of the list right = seq[mid:] #right half of the list ltup = sortandcount(left) #sort left rtup = sortandcount(right) #sort right mtup = mergeandcount(ltup[1], rtup[1]) #merge left and right sides count = ltup[0] + rtup[0] + mtup[0] #get the inversion counts from left right and merge return (count ,mtup[1]) if __name__ == "__main__": seq1 = [7, 10, 18, 3, 14, 17, 23, 2, 11, 16] seq2 = [2, 1, 3, 6, 7, 8, 5, 4, 9, 10] seq3 = [1, 3, 2, 6, 4, 5, 7, 10, 8, 9] songs1 = [(1, "<NAME>: Couldn't Stand the Weather"), (2, "<NAME>: Voodoo Chile"), (3, "The Lumineers: Ho Hey"), (4, "Adele: Chasing Pavements"), (5, "Cake: I Will Survive"), (6, "<NAME>: I Will Survive"), (7, "Beyonce: All the Single Ladies"), (8, "Coldplay: Clocks"), (9, "Nickelback: Gotta be Somebody"), (10, "G<NAME>: Friends in Low Places")] songs2 = [(3, "The Lumineers: Ho Hey"), (4, "Adele: Chasing Pavements"), (2, "<NAME>: Voodoo Chile"), (1, "<NAME>: Couldn't Stand the Weather"), (8, "Coldplay: Clocks"), (6, "<NAME>: I Will Survive"), (5, "Cake: I Will Survive"), (7, "Beyonce: All the Single Ladies"), (9, "Nickelback: Gotta be Somebody"), (10, "Garth Brooks: Friends in Low Places")] songs3 = [(1, "<NAME>: Couldn't Stand the Weather"), (2, "<NAME>: Voodoo Chile"), (3, "The Lumineers: Ho Hey"), (4, "Adele: Chasing Pavements"), (6, "<NAME>: I Will Survive"), (5, "Cake: I Will Survive"), (7, "Beyonce: All the Single Ladies"), (8, "Coldplay: Clocks"), (10, "Garth Brooks: Friends in Low Places"), (9, "Nickelback: Gotta be Somebody")] print seq1 print "# Inversions: %i\n" % sortandcount(seq1)[0] print seq2 print "# Inversions: %i\n" % sortandcount(seq2)[0] print seq3 print "# Inversions: %i\n" % sortandcount(seq3)[0] print songs1 print "# Inversions: %i\n" % sortandcount(songs1)[0] print songs2 print "# Inversions: %i\n" % sortandcount(songs2)[0] print songs3 print "# Inversions: %i\n" % sortandcount(songs3)[0] <file_sep># <NAME> # Starter code to HW3 Q1. import urllib from collections import deque def getLinks(url, baseurl="http://secon.utulsa.edu/cs2123/webtraverse/"): """ Input: url to visit, Boolean absolute indicates whether URLs should include absolute path (default) or not Output: list of pairs of URLs and associated text """ # import the HTML parser package try: from BeautifulSoup import BeautifulSoup except: print 'You must first install the BeautifulSoup package for this code to work' raise # fetch the URL and load it into the HTML parser soup = BeautifulSoup(urllib.urlopen(url).read()) # pull out the links from the HTML and return return [baseurl + a["href"].encode('ascii', 'ignore') for a in soup.findAll('a')] def print_dfs(url): """ Print all links reachable from a starting **url** in depth-first order """ # g = {} hist, stack = set(), [] stack.append(url) i = 1 while stack: temp = stack.pop() if temp in hist: continue hist.add(temp) list = getLinks(temp) while list: tmp = list.pop() stack.append(tmp) g[i] = temp i += 1 print g #I used the code from the slides. Not sure if I need to cite it or not def print_bfs(url): """ Print all links reachable from a starting **url** in breadth-first order """ # g = {} visited, stack = set(), deque() stack.append(url) i = 1 while stack: temp = stack.popleft() if temp not in visited: visited.add(temp) list = getLinks(temp) stack.extend(list) g[i] = temp i += 1 print g #the code from the slides helped. Not sure if I need to cite it or not def find_shortest_path(url1, url2): """ Find and return the shortest path from **url1** to **url2** if one exists. If no such path exists, say so. """ check = deque() path = [] list = getLinks(url1) path.append(url1) while list: check.append(list.pop()) tmp = check.pop() while tmp != url2: if tmp in path: print "Path not available" break else: templist = getLinks(tmp) if url2 in templist: path.append(tmp) path.append(url2) print path break check.extend(templist) path.append(tmp) tmp = check.popleft() def find_max_depth(start_url): """ Find and return the URL that is the greatest distance from start_url, along with the sequence of links that must be followed to reach the page. For this problem, distance is defined as the minimum number of links that must be followed from start_url to reach the page. """ # path = [] check = deque() path.append(start_url) list = getLinks(start_url) while list: check.append(list.pop()) while check: tmp = check.pop() if tmp in path: break else: path.append(tmp) loader = getLinks(tmp) while loader: check.append(loader.pop()) print len(path) print path if __name__ == "__main__": starturl = "http://secon.utulsa.edu/cs2123/webtraverse/index.html" print "*********** (a) Depth-first search **********" print_dfs(starturl) print "*********** (b) Breadth-first search **********" print_bfs(starturl) print "*********** (c) Find shortest path between two URLs ********" find_shortest_path("http://secon.utulsa.edu/cs2123/webtraverse/index.html", "http://secon.utulsa.edu/cs2123/webtraverse/wainwright.html") find_shortest_path("http://secon.utulsa.edu/cs2123/webtraverse/turing.html", "http://secon.utulsa.edu/cs2123/webtraverse/dijkstra.html") print "*********** (d) Find the longest shortest path from a starting URL *****" find_max_depth(starturl)
0d3620c4f3087621d6ce790ab9289905e7ed29ac
[ "Markdown", "Java", "Python" ]
5
Java
elihjones7/Various-Programs
18c10dce2ae599c9130ea0a7331887bc1f05d822
990482bc4b8b5591811e5ba36eac77a9800b1a8d
refs/heads/master
<file_sep><?php phpinfo(); ?> CALL 一波666
c282d9e21024bf96d8c94ac74f3ca5d20e5873e3
[ "PHP" ]
1
PHP
YY-FS/test
31229535b90d0207d055455707f3f2b772b64ba3
84c58e14c37221951cd31da30bd4e35718decfd8
refs/heads/master
<repo_name>iArpanK/Realtime_Barcode_Reader<file_sep>/realtime_barcode_reader.py #!/usr/bin/env python # coding: utf-8 # In[1]: # importing required libraries from pyzbar import pyzbar import argparse import datetime import cv2 # In[2]: # defining the scan barcode function def scanBarcodes(snap, barcodeList, log): # resizing the frame from the video stream snap = cv2.resize(snap, (640, 480)) # finding & decoding barcodes in the frame barcodes = pyzbar.decode(snap) # iterating over the barcodes for b in barcodes: # storing barcode data & type # converting barcode data to string as it is a bytes object barcode_data = b.data.decode('utf-8') barcode_type = b.type # finding the rectangle locations bounding the barcode # and drawing the rectangle on the frame x, y, w, h = b.rect cv2.rectangle(snap, (x, y),(x + w, y + h), (0, 255, 0), 3) # setting the font & text, location, size, color, etc. # to be displayed on output frame font = cv2.FONT_HERSHEY_SIMPLEX text1 = "Type: {}".format(barcode_type) text2 = barcode_data cv2.putText(snap, text1, (x, y - 20), font, 0.6, (255, 0, 0), 2) cv2.putText(snap, text2, (x, y + h + 30), font, 0.6, (0, 0, 255), 2) # writing the unique barcodes in the log file & printing it if barcode_data not in barcodeList: status = "[Alert] New Barcode detected : {} ({})".format(barcode_data, barcode_type) log.write(status+'\n') print(status) barcodeList.add(barcode_data) return snap # In[3]: # defining the main function def main(): # argument parser to parse command line arguments ap = argparse.ArgumentParser() ap.add_argument("-v", "--video", required = True, help = "URL of your IP Camera (0/1 in case of primary/secondary webcam)") args = vars(ap.parse_args()) # converting to int for primary & secondary camera src if args["video"] == '0' or args["video"] == '1': args["video"] = int(args["video"]) # creating a set to contain unique barcodes barcodeList = set() # creating an object of VideoCapture with # source as the IP camera url print("[Alert] Starting Video...") cap = cv2.VideoCapture(args["video"]) # creating a text file for storing session log log = open("log.txt", mode ='w') log.write("Log created : {}\n\n".format(datetime.datetime.now())) # frame gets the next frame from video stream # ret obtains the boolean return value from getting the frame ret, frame = cap.read() # while loop keeps running the scan barcode function # till the Esc key is pressed while ret: ret, frame = cap.read() frame = scanBarcodes(frame, barcodeList, log) cv2.imshow('Real-time Barcode Reader', frame) if cv2.waitKey(1) & 0xFF == 27: log.close() break # releasing the object & closing the application window cap.release() cv2.destroyAllWindows() # calling the main function to start the program if __name__ == '__main__': main() <file_sep>/README.md # Realtime Barcode Reader --- Scans one-dimensional barcodes and QR codes in real-time from your phone's camera or computer's webcam. Can be run directly from your command-line or terminal. This application is built using Python 3.7 and uses the following libraries: - OpenCV - Pyzbar ### Dependencies --- Install OpenCV ```sh $-> pip install opencv-python ``` Install Pyzbar ```sh $-> pip install pyzbar ``` ### Running the Program --- After all the required libraries have been installed, the program can be run as ```sh $-> python realtime_barcode_reader.py --video <source> ``` In place of source, enter the URL of your IP Camera application. Format for this is ``` http://<IP_address>:<PORT>/video```. For example, I'm using an Android application called [DroidCam](https://play.google.com/store/apps/details?id=com.dev47apps.droidcam) which shows these two instances. ![1616989007121](https://user-images.githubusercontent.com/80940234/112825314-3bad0680-90a9-11eb-8389-75bc66169550.jpg) ![1617037915127](https://user-images.githubusercontent.com/80940234/112928918-182f9d80-9135-11eb-86a0-a4bb33c35d63.jpg) 1. First instance : I connected my computer to my phone's personal hotspot 2. Second instance : I connected my computer & phone to a WiFi So in the first instance, my source URL would be ```http://192.168.43.1:4747/video```. And the complete command would be ```sh $-> python realtime_barcode_reader.py --video http://192.168.43.1:4747/video ``` And in the second instance, my source URL would be ```http://192.168.43.39:4747/video```. And the complete command would be ```sh $-> python realtime_barcode_reader.py --video http://192.168.43.39:4747/video ``` > **NOTE** : In both these instances, note that your computer needs to be connected to the same network as your phone. Also, keep the IP Camera application running in your phone. If you want to use your computer’s primary or secondary webcam as the video source, use source as 0 or 1 respectively, in the command above. For example, the below command starts your computer’s primary webcam as the video source. ```sh $-> python realtime_barcode_reader.py --video 0 ``` On punching either of these commands as per your choice, the **realtime_barcode_reader.py** program will start executing displaying a startup message on the command line, and your phone/computer will start streaming video feed. At the same time, a new window will open up on your computer screen displaying the barcode reader’s output stream (as shown below). **Now we are ready to scan different barcodes!** ![Screenshot (171)](https://user-images.githubusercontent.com/80940234/112930070-444c1e00-9137-11eb-95df-a7448370d5db.png) To exit the program, press the ESC key on your computer. ### Sample Runs --- Attached below are some sample shots of the barcode reader. ![Untitled collage](https://user-images.githubusercontent.com/80940234/112828520-6bf6a400-90ad-11eb-9630-59833f24a1df.jpg) ### Log --- On every run, this program generates a log file (log.txt) which contains the exact last session timestamp and details of the unique barcodes scanned. ![Screenshot (169)](https://user-images.githubusercontent.com/80940234/112828876-ed4e3680-90ad-11eb-8651-5d19a8f29fee.png) ### Notes --- For IP Camera application, you can download either of these apps: [DroidCam](https://play.google.com/store/apps/details?id=com.dev47apps.droidcam) [IP Webcam](https://play.google.com/store/apps/details?id=com.pas.webcam) [Google Drive download link (ipynb file included) ⤓](https://drive.google.com/drive/folders/1PxKK17r4U2jFhb8HkbiN57yTIwbqJ7qy?usp=sharing) Thanks!
57d7f423844b168ca442978b48ab7545976bbf79
[ "Markdown", "Python" ]
2
Python
iArpanK/Realtime_Barcode_Reader
d1bb817497b85d862bb3e0b05bc71141824b9c6c
d77cf6d4d4a7cd8ffdd7b2d49f794d55afc67235
refs/heads/master
<repo_name>pengcunchao/data_structure<file_sep>/src/com/share/datastructure/api/Graph.java package com.share.datastructure.api; public interface Graph<T> { void addEdge(int n,int m, int weight); int getWeight(int n, int m); void DFS(); void BFS(); } <file_sep>/src/com/share/datastructure/api/impl/TreeSet.java package com.share.datastructure.api.impl; import com.share.datastructure.api.BSTree; import com.share.datastructure.api.Set; public class TreeSet<T extends Comparable<T>> implements Set<T> { private BSTree<T> data; public TreeSet(BSTree<T> data) { this.data = data; } @Override public void add(T ele) { data.add(ele); } @Override public void remove(T ele) { data.remove(ele); } @Override public boolean contains(T ele) { return data.contains(ele); } @Override public int getSize() { return data.getSize(); } @Override public boolean isEmpty() { return data.isEmpty(); } } <file_sep>/src/com/share/datastructure/api/impl/TreeSegmentTree.java package com.share.datastructure.api.impl; import com.share.datastructure.api.Merger; import com.share.datastructure.api.SegmentTree; public class TreeSegmentTree<T> implements SegmentTree<T> { private SegmentTreeNode<T> root; private T[] data; private Merger<T> merger; public TreeSegmentTree(T[] data, Merger<T> merger) { this.data = data; this.merger = merger; this.root = buildSegmentTree(data, 0, data.length - 1, merger); } private SegmentTreeNode<T> buildSegmentTree(T[] data, int start, int end, Merger<T> merger) { if (start == end) { return new SegmentTreeNode<>(start, end, data[start]); } int mid = start + (end - start) / 2; SegmentTreeNode<T> left = buildSegmentTree(data, start, mid, merger); SegmentTreeNode<T> right = buildSegmentTree(data, mid + 1, end, merger); return new SegmentTreeNode<>(start, end, merger.merge(left.getVal(), right.getVal()), left, right); } public SegmentTreeNode<T> getRoot() { return root; } public T query(int start, int end) { return query(root, start, end); } public void update(int index, T val) { data[index] = val; update(root, index, val); } private void update(SegmentTreeNode<T> node, int index, T val) { int head = node.getHead(); int tail = node.getTail(); if (index < head || index > tail) { throw new IllegalArgumentException("illegal argument"); } if (node.getHead() == node.getTail() && node.getHead() == index) { data[index] = val; node.setVal(val); return; } int mid = head + (tail - head) / 2; if (index > mid) { update(node.getRightChild(), index, val); } else { update(node.getLeftChild(), index, val); } node.setVal(merger.merge(node.getLeftChild().getVal(), node.getRightChild().getVal())); } private T query(SegmentTreeNode<T> node, int start, int end) { int head = node.getHead(); int tail = node.getTail(); if (start < head || end > tail || start > end) { throw new IllegalArgumentException("illegal argument"); } if (start == head && end == tail) { return node.getVal(); } int mid = head + (tail - head) / 2; if (end <= mid) { return query(node.getLeftChild(), start, end); } if (start > mid) { return query(node.getRightChild(), start, end); } return merger.merge(query(node.getLeftChild(), start, mid), query(node.getRightChild(), mid + 1, end)); } public T[] getData() { return data; } public void print() { print(root); } private void print(SegmentTreeNode<T> node) { if (node == null) { return; } System.out.println(node.getVal()); print(node.getLeftChild()); print(node.getRightChild()); } } <file_sep>/src/com/share/datastructure/api/impl/DynamicArray.java package com.share.datastructure.api.impl; import com.share.datastructure.api.Array; public class DynamicArray<T> implements Array<T> { private static final int DEFAULT_SIZE = 16; private T[] data; private int size; public DynamicArray(int capacity) { this.data = (T[]) new Object[capacity]; this.size = 0; } public DynamicArray() { this(DEFAULT_SIZE); } @Override public int getSize() { return this.size; } @Override public int getCapacity() { return data.length; } @Override public void add(int index, T e) { if (index < 0 || index > size) { throw new IllegalArgumentException("index is out of bound!"); } if (size == getCapacity()) { resize(this.data.length * 2); } for (int i = size; i > index; i--) { data[i] = data[i - 1]; } data[index] = e; size++; } private void resize(int capacity) { T[] newData = (T[]) new Object[capacity]; for (int i = 0; i < this.size; i++) { newData[i] = this.data[i]; } data = newData; } @Override public T get(int index) { if (index < 0 || index >= size) { throw new IllegalArgumentException("index is out of bound!"); } return data[index]; } @Override public int removeElement(T ele) { for (int i = 0; i < size; i++) { if (ele.equals(data[i])) { remove(i); return i; } } return -1; } @Override public T remove(int index) { if (isEmpty()) { throw new IllegalOperationException("Cannot remove element from empty array!"); } if (index < 0 || index >= size) { throw new IllegalArgumentException("index is out of bound!"); } T result = data[index]; for (int i = index; i < size - 1; i++) { data[i] = data[i + 1]; } size--; if (this.size == data.length / 4 && data.length / 2 != 0) { resize(data.length / 2); } return result; } @Override public T find(int index) { if (index < 0 || index >= size) { throw new IllegalArgumentException("index is out of bound!"); } return data[index]; } @Override public int findElement(T ele) { for (int i = 0; i < size; i++) { if (ele.equals(data[i])) { return i; } } return -1; } @Override public void set(int index, T ele) { if (isEmpty() || index < 0 || index >= size) { throw new IllegalArgumentException("index is out of bound!"); } data[index] = ele; } @Override public boolean isEmpty() { return this.size == 0; } @Override public boolean contains(T ele) { for (int i = 0; i < this.size; i++) { if (ele.equals(this.data[i])) { return true; } } return false; } @Override public void swap(int a, int b) { T temp = data[a]; data[a] = data[b]; data[b] = temp; } } <file_sep>/src/com/share/datastructure/api/impl/MinHeap.java package com.share.datastructure.api.impl; import com.share.datastructure.api.Array; import com.share.datastructure.api.Heap; public class MinHeap<T extends Comparable<T>> implements Heap<T> { private Array<T> tArray; public MinHeap() { this.tArray = new DynamicArray<>(); } public MinHeap(int capacity) { this.tArray = new DynamicArray<>(capacity); } public static <T extends Comparable<T>> Heap<T> heapify(T[] data) { Array<T> tArray = new DynamicArray<>(data.length); for (int i = 0; i < data.length; i++) { tArray.add(i, data[i]); } MinHeap<T> minHeap = new MinHeap<>(tArray.getCapacity()); minHeap.settArray(tArray); for (int i = minHeap.getParent(tArray.getSize() - 1); i >= 0; i--) { minHeap.siftDown(i); } return minHeap; } private void settArray(Array<T> tArray){ this.tArray = tArray; } @Override public int getSize() { return tArray.getSize(); } @Override public boolean isEmpty() { return tArray.isEmpty(); } @Override public void push(T ele) { tArray.add(getSize(), ele); siftUp(getSize() - 1); } @Override public T pop() { if (isEmpty()) { return null; } T ret = tArray.get(0); tArray.set(0, tArray.get(getSize() - 1)); tArray.remove(getSize() - 1); siftDown(0); return ret; } @Override public T peek() { return isEmpty() ? null : tArray.get(0); } @Override public T replace(T ele) { if (isEmpty()) { return null; } T ret = peek(); tArray.set(0, ele); siftDown(0); return ret; } private void siftUp(int index) { T val = tArray.get(index); for (int i = index; i > 0; i = getParent(i)) { if(val.compareTo(tArray.get(getParent(i))) < 0){ tArray.set(i,tArray.get(getParent(i))); } else { tArray.set(i, val); break; } } if (tArray.get(0).compareTo(val) > 0) { tArray.set(0, val); } } private void siftDown(int index) { int minChild = 0; for (int i = index; getLeftChild(i) < getSize() - 1; ) { minChild = getLeftChild(i); if (minChild + 1 < getSize()) { if (tArray.get(minChild).compareTo(tArray.get(minChild + 1)) > 0) { minChild = minChild + 1; } } if (tArray.get(minChild).compareTo(tArray.get(i)) >= 0) { break; } tArray.swap(minChild, i); i = minChild; } } private int getParent(int index) { if (index <= 0) { throw new IllegalArgumentException("illegal index"); } return (index - 1) / 2; } private int getLeftChild(int index) { return index * 2 + 1; } } <file_sep>/src/com/share/datastructure/api/impl/LinkedListStack.java package com.share.datastructure.api.impl; import com.share.datastructure.api.LinkedList; import com.share.datastructure.api.Stack; public class LinkedListStack<T> implements Stack<T> { private LinkedList<T> data; public LinkedListStack() { this.data = new SLinkedList<>(); } @Override public void push(T ele) { data.add(0, ele); } @Override public T pop() { return data.remove(0); } @Override public T peek() { return data.get(0); } @Override public int getSize() { return data.getSize(); } @Override public boolean isEmpty() { return data.isEmpty(); } } <file_sep>/src/com/share/datastructure/api/impl/SegmentTreeNode.java package com.share.datastructure.api.impl; public class SegmentTreeNode<T> { private int head; private int tail; private T val; private SegmentTreeNode<T> leftChild; private SegmentTreeNode<T> rightChild; public SegmentTreeNode(int head, int tail, T val) { this.head = head; this.tail = tail; this.val = val; } public SegmentTreeNode(int head, int tail, T val, SegmentTreeNode<T> leftChild, SegmentTreeNode<T> rightChild) { this.head = head; this.tail = tail; this.val = val; this.leftChild = leftChild; this.rightChild = rightChild; } public int getHead() { return head; } public void setHead(int head) { this.head = head; } public int getTail() { return tail; } public void setTail(int tail) { this.tail = tail; } public T getVal() { return val; } public void setVal(T val) { this.val = val; } public SegmentTreeNode<T> getLeftChild() { return leftChild; } public void setLeftChild(SegmentTreeNode<T> leftChild) { this.leftChild = leftChild; } public SegmentTreeNode<T> getRightChild() { return rightChild; } public void setRightChild(SegmentTreeNode<T> rightChild) { this.rightChild = rightChild; } } <file_sep>/src/com/share/datastructure/api/SegmentTree.java package com.share.datastructure.api; public interface SegmentTree<T> { } <file_sep>/src/com/share/datastructure/api/Array.java package com.share.datastructure.api; public interface Array<T> { int getSize(); int getCapacity(); void add(int index, T ele); T get(int index); int removeElement(T ele); T remove(int index); T find(int index); int findElement(T ele); void set(int index, T ele); boolean isEmpty(); boolean contains(T ele); void swap(int a, int b); } <file_sep>/src/com/share/datastructure/api/Set.java package com.share.datastructure.api; public interface Set<T> { void add(T ele); void remove(T ele); boolean contains(T ele); int getSize(); boolean isEmpty(); } <file_sep>/src/com/share/datastructure/api/impl/SimpleBSTree.java package com.share.datastructure.api.impl; import com.share.datastructure.api.BSTree; import com.share.datastructure.api.Queue; public class SimpleBSTree<T extends Comparable<T>> implements BSTree<T> { private BinaryTreeNode<T> root; private int size; public SimpleBSTree() { this.root = null; this.size = 0; } public SimpleBSTree(T val) { this.root = new BinaryTreeNode<>(val); this.size = 1; } @Override public int getSize() { return this.size; } @Override public boolean isEmpty() { return this.size == 0; } @Override public void traverse() { traverse(root); } @Override public void remove(T val) { root = remove(root,val); } private BinaryTreeNode<T> remove(BinaryTreeNode<T> node, T val){ if(node == null){ return null; } if(val.equals(node.getValue())){ if(node.getLeft() == null){ size --; return node.getRight(); } else if(node.getRight() == null){ size --; return node.getLeft(); } else{ return new BinaryTreeNode<>(max(node.getLeft()), removeMax(node.getLeft()), node.getRight()); } } else if(val.compareTo(node.getValue()) < 0){ node.setLeft(remove(node.getLeft(),val)); } else{ node.setRight(remove(node.getRight(),val)); } return node; } private T max(BinaryTreeNode<T> node) { if (node == null) { return null; } BinaryTreeNode<T> cur = node; while (cur.getRight() != null) { cur = cur.getRight(); } return cur.getValue(); } private BinaryTreeNode<T> removeMax(BinaryTreeNode<T> node) { if (node == null) { return null; } if (node.getRight() == null) { size--; return node.getLeft(); } node.setRight(removeMax(node.getRight())); return node; } private void traverse(BinaryTreeNode<T> node){ if(node == null){ return; } traverse(node.getLeft()); node.handle(); traverse(node.getRight()); } public void levelTraverse(){ Queue<BinaryTreeNode<T>> queue = new LoopQueue<>(); queue.enQueue(root); BinaryTreeNode<T> cur = null; while(!queue.isEmpty()){ cur = queue.deQueue(); cur.handle(); if(cur.getLeft() != null) queue.enQueue(cur.getLeft()); if(cur.getRight() != null) queue.enQueue(cur.getRight()); } } @Override public boolean contains(T val) { return contains(root, val); } private boolean contains(BinaryTreeNode<T> node, T val){ if(node == null){ return false; } if(val.equals(node.getValue())){ return true; } else if(val.compareTo(node.getValue()) < 0){ return contains(node.getLeft(),val); } else{ return contains(node.getRight(),val); } } @Override public void add(T val) { root = add(root,val); } private BinaryTreeNode<T> add(BinaryTreeNode<T> node, T val){ if(node == null){ size ++; return new BinaryTreeNode<>(val); } if(val.compareTo(node.getValue()) < 0){ node.setLeft(add(node.getLeft(),val)); } else if(val.compareTo(node.getValue()) > 0){ node.setRight(add(node.getRight(),val)); } return node; } } <file_sep>/src/com/share/datastructure/api/impl/LoopQueue.java package com.share.datastructure.api.impl; import com.share.datastructure.api.Queue; public class LoopQueue<T> implements Queue<T> { private static final int DEFAULT = 10; private T[] data; private int head, tail; public LoopQueue() { this(DEFAULT); } public LoopQueue(int capacity) { data = (T[]) new Object[capacity + 1]; head = 0; tail = 0; } @Override public void enQueue(T ele) { if (getSize() == getCapacity()) { resize(2 * getCapacity()); } data[tail] = ele; tail = (tail + 1) % data.length; } private int getCapacity(){ return data.length - 1; } private void resize(int capacity) { T[] newData = (T[]) new Object[capacity + 1]; for (int i = 0; i < getSize(); i++) { newData[i] = data[(head + i) % data.length]; } head = 0; tail = getSize(); data = newData; } @Override public T deQueue() { if (isEmpty()) { return null; } T result = data[head]; head = (head + 1) % data.length; if (getSize() == getCapacity() / 4 && getCapacity() / 2 != 0) { resize(getCapacity() / 2); } return result; } @Override public T getFront() { return isEmpty() ? null : data[head]; } @Override public int getSize() { return (tail - head) % data.length; } @Override public boolean isEmpty() { return head == tail; } } <file_sep>/src/com/share/datastructure/api/Heap.java package com.share.datastructure.api; public interface Heap<T extends Comparable<T>> { int getSize(); boolean isEmpty(); void push(T ele); T pop(); T peek(); T replace(T ele); } <file_sep>/src/com/share/datastructure/api/impl/Trie.java package com.share.datastructure.api.impl; import java.util.HashMap; import java.util.Map; public class Trie { private Node root; private int size; public Trie() { this.root = new Node(false, new HashMap<>()); this.size = 0; } public Node getRoot() { return root; } public void setRoot(Node root) { this.root = root; } public int getSize() { return size; } public void setSize(int size) { this.size = size; } public void add(String word) { add(root, word, 0); } private void add(Node node, String word, int index) { if (index == word.length()) { return; } Character c = word.charAt(index); if (node.getNext().get(c) == null) { node.getNext().put(c, new Node(false, new HashMap<>())); } if (index == word.length() - 1 && !node.getNext().get(c).isWord()) { node.getNext().get(c).setWord(true); size++; } add(node.getNext().get(c), word, index + 1); } public boolean contains(String word) { return contains(root, word, 0); } private boolean contains(Node node, String word, int index) { Character c = word.charAt(index); if (!node.getNext().containsKey(c)) { return false; } if (index == word.length() - 1) { return node.getNext().get(c).isWord(); } return contains(node.getNext().get(c), word, index + 1); } public boolean match(String pattern) { return match(root, pattern, 0); } private boolean match(Node node, String pattern, int index) { if (index == pattern.length()) { return true; } Character c = pattern.charAt(index); if (c.equals('.')) { for (Node child : node.getNext().values()) { if (match(child, pattern, index + 1)) { return true; } } return false; } else { if (node.getNext().get(c) == null) { return false; } return match(node.getNext().get(c), pattern, index + 1); } } private class Node { private boolean isWord; private Map<Character, Node> next; public Node(boolean isWord, Map<Character, Node> next) { this.isWord = isWord; this.next = next; } public boolean isWord() { return isWord; } public void setWord(boolean word) { isWord = word; } public Map<Character, Node> getNext() { return next; } public void setNext(Map<Character, Node> next) { this.next = next; } } }
d9fecdf5faf07a7a42f0c4a25324bbf328efa241
[ "Java" ]
14
Java
pengcunchao/data_structure
0a97fbbfb17eab72c169bc082ed53bf06e8e115f
d9df2bfc7a06a321fbc3f56f1ad40d4031522856
refs/heads/master
<repo_name>JDucktape/BatchDNSLookup<file_sep>/Batch DNS Lookup/DnsDataItem.cs using System; using System.Collections.Generic; using System.Text; namespace ClandestineDevelopment.Tools.BatchDnsLookup { public class DnsDataItem: IComparable { public int ID { get; set; } public string Domain { get; set; } public string Result { get; set; } public DnsDataItem(int id, string domain) { this.ID = id; this.Domain = domain; } public string GetResultsAsCSV(bool embedInDoubleQuotes) { if (embedInDoubleQuotes) { return String.Format("\"{0}\"", Result.Replace(Environment.NewLine, ",")); } else { return Result.Replace(Environment.NewLine, ","); } } public string GetDomainAndResultAsCSV(bool embedInDoubleQuotes, char separator) { if (embedInDoubleQuotes) { return String.Format("\"{0}\"{1}\"{2}\"", Domain, separator, Result.Replace(Environment.NewLine, ",")); } else { return String.Format("{0}{1}{2}", Domain, separator, Result.Replace(Environment.NewLine, ",")); } } public int CompareTo(object obj) { DnsDataItem target = (DnsDataItem)obj; if (this.ID < target.ID) return -1; if (this.ID == target.ID) return 0; if (this.ID > target.ID) return 1; return 0; } } } <file_sep>/Batch DNS Lookup/frmCsvExport.cs using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; namespace ClandestineDevelopment.Tools.BatchDnsLookup { public partial class frmCsvExport : Form { public bool ExportAllData { get; private set; } public char Delimiter { get; private set; } public bool IncludeHeaders { get; private set; } public bool EmbedInDoubleQuotes { get; private set; } public bool ExportToClipboard { get; private set; } public frmCsvExport() { InitializeComponent(); } private void btnExport_Click(object sender, EventArgs e) { ExportAllData = rbDomainsAndResults.Checked; IncludeHeaders = chkIncludeHeaders.Checked; EmbedInDoubleQuotes = chkEmbedInDoubleQuotes.Checked; if (rbDelimeterComma.Checked) { Delimiter = ','; } else if (rbDelimeterSemicolon.Checked) { Delimiter = ';'; } else if (rbDelimiterTab.Checked) { Delimiter = '\t'; } else if (rbDelimiterOther.Checked) { Delimiter = Convert.ToChar(txtDelimiterOtherChar.Text); } if ((sender as Button) == btnExportClipboard) { ExportToClipboard = true; } else { ExportToClipboard = false; } DialogResult = DialogResult.OK; } private void rbDelimiterOther_CheckedChanged(object sender, EventArgs e) { txtDelimiterOtherChar.Enabled = rbDelimiterOther.Checked; } } } <file_sep>/Batch DNS Lookup/DnsLookup.cs using System; using System.Net; using System.Text; using JHSoftware; namespace ClandestineDevelopment.Tools.BatchDnsLookup { public class DnsLookup { public IPAddress PrimaryDnsServer { get; set; } public IPAddress SecondaryDnsServer { get; set; } private bool EnableCustomDnsServers; private bool EnableDebugLogging; private int Timeout; private int RetryCount; public DnsLookup(bool enableCustomDnsServers, bool enableDebugLogging, int queryTimeout, int queryRetries) { this.EnableCustomDnsServers = enableCustomDnsServers; this.EnableDebugLogging = enableDebugLogging; this.Timeout = queryTimeout; this.RetryCount = queryRetries; } public string Lookup(string domain, DnsClient.RecordType recordtype, bool onlyGetOneRecord) { StringBuilder output = new StringBuilder(); if (domain.Trim().Length == 0) { output.Append(""); } else { try { DnsClient.RequestOptions options = new DnsClient.RequestOptions(); if (EnableCustomDnsServers) { options.DnsServers = new IPAddress[] { PrimaryDnsServer, SecondaryDnsServer }; } options.TimeOut = new TimeSpan(0, 0, Timeout); options.RetryCount = RetryCount; if (recordtype == DnsClient.RecordType.PTR) { string[] hostnames; IPAddress ip; if (IPAddress.TryParse(domain, out ip)) { hostnames = DnsClient.LookupReverse(ip, options); if (onlyGetOneRecord) { if (EnableDebugLogging) { output.Append(String.Format("IP: {0} Type: {1} Result: {2}", ip.ToString(), recordtype, hostnames[hostnames.Length - 1])); } else { output.Append(hostnames[hostnames.Length - 1]); } } else { for (int i = 0; i < hostnames.Length; i++) { if (i == hostnames.Length - 1) { // It's the last record, end the output without a linebreak. if (EnableDebugLogging) { output.Append(String.Format("IP: {0} Type: {1} Result: {2}", ip.ToString(), recordtype, hostnames[i])); } else { output.Append(hostnames[i]); } } else { if (EnableDebugLogging) { output.AppendLine(String.Format("IP: {0} Type: {1} Result: {2}", ip.ToString(), recordtype, hostnames[i])); } else { output.AppendLine(hostnames[i]); } } } } } else { output.Append(String.Format("Error: {0} is not a valid IP address", domain)); } } //else if (recordtype == DnsClient.RecordType.MX) //{ // // TODO: Implement this - add support for MX Priority stuff in output? // DnsClient.MXHost[] mailhosts = DnsClient.LookupMX(domain, options); // if (onlyGetOneRecord) // { // } // else // { // foreach(var m in mailhosts) // output.AppendLine(String.Format("Preference: {2} Hostname: {0} IP: ", m.HostName, m.IPAddresses, m.Preference)); // } //} else { DnsClient.Response response = DnsClient.Lookup(domain, recordtype, options); if (onlyGetOneRecord) { // We should only get one record, so we'll pick the last record looked up in the chain. // It's most likely the one needed in typical recursive A-record lookups. DnsClient.Response.Record record = response.AnswerRecords[response.AnswerRecords.Count - 1]; if (EnableDebugLogging) { output.Append(String.Format("Domain: {0} Type: {1} TTL: {2} Result: {3}", record.Name, record.Type, record.TTL, record.Data)); } else { output.Append(record.Data); } } else { for (int i = 0; i < response.AnswerRecords.Count; i++) { if (i == response.AnswerRecords.Count - 1) { // It's the last record, end the output without a linebreak. if (EnableDebugLogging) { output.Append(String.Format("Domain: {0} Type: {1} TTL: {2} Result: {3}", response.AnswerRecords[i].Name, response.AnswerRecords[i].Type, response.AnswerRecords[i].TTL, response.AnswerRecords[i].Data)); } else { output.Append(response.AnswerRecords[i].Data); } } else { if (EnableDebugLogging) { output.AppendLine(String.Format("Domain: {0} Type: {1} TTL: {2} Result: {3}", response.AnswerRecords[i].Name, response.AnswerRecords[i].Type, response.AnswerRecords[i].TTL, response.AnswerRecords[i].Data)); } else { output.AppendLine(response.AnswerRecords[i].Data); } } } } } } catch (DnsClient.NXDomainException nxd) { if (EnableDebugLogging) { output.Append(nxd.Message); } else { output.Append("The domain name does not exist."); } } catch (DnsClient.NoDefinitiveAnswerException nda) { if (EnableDebugLogging) { for (int i = 0; i < nda.ServerProblems.Count; i++) { if (i == nda.ServerProblems.Count - 1) { // It's the last record, end the output without a linebreak output.Append(String.Format("DNS Server: {0} Problem: {1} ({2})", nda.ServerProblems[i].Server, nda.ServerProblems[i].ProblemDescription, nda.ServerProblems[i].Problem)); } else { output.AppendLine(String.Format("DNS Server: {0} Problem: {1} ({2})", nda.ServerProblems[i].Server, nda.ServerProblems[i].ProblemDescription, nda.ServerProblems[i].Problem)); } } } else { output.Append("No definitive answer from server."); } } catch (Exception ex) { output.Append("Error: " + ex.Message); } } return output.ToString(); } } } <file_sep>/Batch DNS Lookup/frmAbout.cs using System; using System.Diagnostics; using System.Reflection; using System.Windows.Forms; namespace ClandestineDevelopment.Tools.BatchDnsLookup { public partial class frmAbout : Form { public frmAbout() { InitializeComponent(); Assembly a = Assembly.GetExecutingAssembly(); lblProductVersion.Text = String.Format("{0} v{1}", a.GetName().Name, a.GetName().Version.ToString()); object[] attributes = Assembly.GetExecutingAssembly().GetCustomAttributes(typeof(AssemblyCopyrightAttribute), false); lblCopyright.Text = ((AssemblyCopyrightAttribute)attributes[0]).Copyright; } private void linkJHSoftware_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e) { Process.Start("http://www.simpledns.com"); } private void linkClandestine_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e) { Process.Start("http://clandestine.dk"); } } } <file_sep>/Batch DNS Lookup/frmMain.cs using System; using System.Collections.Generic; using System.IO; using System.Net; using System.Threading; using System.Windows.Forms; using ClandestineDevelopment.Tools.BatchDnsLookup.Properties; using JHSoftware; using System.Text; namespace ClandestineDevelopment.Tools.BatchDnsLookup { public enum DnsRecordType { A, AAAA, ANY, CNAME, MX, NS, PTR, SOA, SPF, SRV, TXT } public partial class frmMain : Form { IPAddress PrimaryDnsServer; IPAddress SecondaryDnsServer; DnsLookup LookupTool; List<DnsDataItem> domains = new List<DnsDataItem>(); DnsClient.RecordType selectedRecordType; int workCounter = 0; bool useDebugLogging = false; private bool keyHandled; public frmMain() { InitializeComponent(); cmbRecordType.DataSource = Enum.GetValues(typeof(DnsRecordType)); } private bool InitializeCustomDnsServers() { bool status = true; if (Settings.Default.EnableCustomDnsServers) { Log("Initializing custom DNS servers", true); if (Settings.Default.PrimaryDnsServer.Length > 0 || Settings.Default.SecondaryDnsServer.Length > 0) { bool parseResult = IPAddress.TryParse(Settings.Default.PrimaryDnsServer, out PrimaryDnsServer); if (parseResult == false) { // Couldn't parse dns server, it must be a hostname. try { IPAddress[] servers = Dns.GetHostAddresses(Settings.Default.PrimaryDnsServer); if (servers.Length >= 1) { PrimaryDnsServer = servers[0]; } else { MessageBox.Show("Unable to lookup primary DNS server.", "Error"); Log("Unable to lookup primary DNS server", true); status = false; } } catch { MessageBox.Show("Unable to lookup primary DNS server.", "Error"); Log("Unable to lookup primary DNS server", true); status = false; } } parseResult = IPAddress.TryParse(Settings.Default.SecondaryDnsServer, out SecondaryDnsServer); if (parseResult == false) { // Couldn't parse dns server, it must be a hostname. try { IPAddress[] servers = Dns.GetHostAddresses(Settings.Default.SecondaryDnsServer); if (servers.Length >= 1) { SecondaryDnsServer = servers[0]; } else { MessageBox.Show("Unable to lookup secondary DNS server.", "Error"); Log("Unable to lookup secondary DNS server", true); status = false; } } catch { MessageBox.Show("Unable to lookup secondary DNS server.", "Error"); Log("Unable to lookup secondary DNS server", true); status = false; } } } else { status = false; MessageBox.Show("Please define both custom DNS servers", "Error"); } } if (status) { LookupTool.PrimaryDnsServer = PrimaryDnsServer; LookupTool.SecondaryDnsServer = SecondaryDnsServer; } return status; } private void Log(string text) { Log(text, false); } private void Log(string text, bool isDebugMessage) { if (txtOutput.InvokeRequired) { BeginInvoke(new MethodInvoker(delegate() { Log(text, isDebugMessage); })); } else { if ((isDebugMessage && useDebugLogging) || !isDebugMessage) { txtOutput.AppendText(text + Environment.NewLine); txtOutput.ScrollToCaret(); } } } private void IncreaseProgress() { if (prgProgress.ProgressBar.InvokeRequired) { BeginInvoke(new MethodInvoker(delegate() { IncreaseProgress(); })); } else { prgProgress.Increment(1); } } private void UpdateStatusBar() { lblStatus.Text = String.Format("Looking up domain {0} of {1}...", prgProgress.Value, txtInput.Lines.Length); } private void DoThreadedLookup(object dataitem) { DnsDataItem item = (DnsDataItem)dataitem; item.Result = LookupTool.Lookup(item.Domain, selectedRecordType, chkOnlyOneRecord.Checked); IncreaseProgress(); workCounter++; } private void btnLookup_Click(object sender, EventArgs e) { LookupTool = new DnsLookup(Settings.Default.EnableCustomDnsServers, Settings.Default.EnableDebugLogging, (int)Settings.Default.DnsQueryTimeout, (int)Settings.Default.DnsQueryRetryCount); useDebugLogging = Settings.Default.EnableDebugLogging; // Disable the GUI so we don't get interrupted btnLookup.Enabled = false; txtInput.Enabled = false; txtOutput.Enabled = false; txtOutput.Clear(); // Reset the progress bar prgProgress.Maximum = txtInput.Lines.Length; prgProgress.Minimum = 0; prgProgress.Value = prgProgress.Minimum; // Initialize custom DNS servers if they are used if (!InitializeCustomDnsServers()) { MessageBox.Show("Unable to initialize custom DNS servers." + Environment.NewLine + "Change the servers or disable the feature and try again.", "Error"); Log("Unable to initalize custom DNS servers"); } else { // Start looking up domains DateTime startTime = DateTime.Now; selectedRecordType = (DnsClient.RecordType)Enum.Parse(typeof(DnsClient.RecordType), cmbRecordType.SelectedValue.ToString()); domains.Clear(); workCounter = 0; for (int i = 0; i < txtInput.Lines.Length; i++) { domains.Add(new DnsDataItem(i, txtInput.Lines[i])); } if (Settings.Default.EnableThreading) { Log("Multithreaded queries enabled. Queing domains in ThreadPool", true); foreach (var d in domains) { ThreadPool.QueueUserWorkItem(this.DoThreadedLookup, d); } while (workCounter < domains.Count) { if (workCounter > 0) { if (workCounter % 10 == 0) { // Update GUI for every 10 domains processed UpdateStatusBar(); Application.DoEvents(); } } } } else { foreach (var d in domains) { d.Result = LookupTool.Lookup(d.Domain, selectedRecordType, chkOnlyOneRecord.Checked); IncreaseProgress(); UpdateStatusBar(); } } DateTime endTime = DateTime.Now; lblStatus.Text = String.Format("Total query time for {0} domains: {1}", txtInput.Lines.Length, (endTime - startTime)); Log(String.Format("Total query time for {0} domains: {1}", txtInput.Lines.Length, (endTime - startTime)), true); foreach (var d in domains) { Log(d.Result); } } // Enable the GUI again txtOutput.Enabled = true; txtInput.Enabled = true; btnLookup.Enabled = true; } private void settingsToolStripMenuItem_Click(object sender, EventArgs e) { frmSettings settings = new frmSettings(); settings.ShowDialog(); } private void txtInput_KeyDown(object sender, KeyEventArgs e) { if (e.Control && e.KeyCode == Keys.A) { txtInput.SelectAll(); keyHandled = true; } } private void txtInput_KeyPress(object sender, KeyPressEventArgs e) { if (keyHandled) { e.Handled = true; keyHandled = false; } } private void txtOutput_KeyDown(object sender, KeyEventArgs e) { if (e.Control && e.KeyCode == Keys.A) { txtOutput.SelectAll(); keyHandled = true; } } private void txtOutput_KeyPress(object sender, KeyPressEventArgs e) { if (keyHandled) { e.Handled = true; keyHandled = false; } } private void aboutToolStripMenuItem_Click(object sender, EventArgs e) { frmAbout about = new frmAbout(); about.ShowDialog(); } private void exportToolStripMenuItem_Click(object sender, EventArgs e) { frmCsvExport exporter = new frmCsvExport(); if (exporter.ShowDialog() == DialogResult.OK) { string data = GetCsvExportData(exporter); if (data.Length == 0) { MessageBox.Show("No data to export!", "Error"); } else { if (exporter.ExportToClipboard) { Clipboard.SetText(GetCsvExportData(exporter)); MessageBox.Show("The data is now available in the clipboard."); } else { SaveFileDialog sfd = new SaveFileDialog(); sfd.AddExtension = true; sfd.DefaultExt = ".csv"; sfd.Filter = "CSV (Comma separated) (*.csv)|*.csv|All files (*.*)|*.*"; if (sfd.ShowDialog() == DialogResult.OK) { try { using (StreamWriter sw = new StreamWriter(sfd.OpenFile())) { sw.Write(GetCsvExportData(exporter)); } } catch (Exception ex) { MessageBox.Show("Error exporting data!" + Environment.NewLine + ex.Message, "Error"); } } } } } } private string GetCsvExportData(frmCsvExport exporter) { StringBuilder sb = new StringBuilder(); if (exporter.IncludeHeaders) { string headerDomain = "Domain"; string headerResult = "Results"; if (exporter.ExportAllData) { if (exporter.EmbedInDoubleQuotes) { sb.AppendLine(String.Format("\"{0}\"{1}\"{2}\"", headerDomain, exporter.Delimiter, headerResult)); } else { sb.AppendLine(String.Format("{0}{1}{2}", headerDomain, exporter.Delimiter, headerResult)); } } else { if (exporter.EmbedInDoubleQuotes) { sb.AppendLine(String.Format("\"{0}\"", headerResult)); } else { sb.AppendLine(headerResult); } } } foreach (var d in domains) { if (exporter.ExportAllData) { sb.AppendLine(d.GetDomainAndResultAsCSV(exporter.EmbedInDoubleQuotes, exporter.Delimiter)); } else { sb.AppendLine(d.GetResultsAsCSV(exporter.EmbedInDoubleQuotes)); } } return sb.ToString(); } } } <file_sep>/Batch DNS Lookup/frmSettings.cs using System; using System.Windows.Forms; using ClandestineDevelopment.Tools.BatchDnsLookup.Properties; namespace ClandestineDevelopment.Tools.BatchDnsLookup { public partial class frmSettings : Form { public frmSettings() { InitializeComponent(); numDnsQueryTimeout.Value = Settings.Default.DnsQueryTimeout; numDnsQueryRetries.Value = Settings.Default.DnsQueryRetryCount; chkEnableThreading.Checked = Settings.Default.EnableThreading; chkEnableCustomDnsServers.Checked = Settings.Default.EnableCustomDnsServers; txtCustomDnsServer1.Text = Settings.Default.PrimaryDnsServer; txtCustomDnsServer2.Text = Settings.Default.SecondaryDnsServer; chkEnableDebugLogging.Checked = Settings.Default.EnableDebugLogging; } private void btnSaveSettings_Click(object sender, EventArgs e) { Settings.Default.DnsQueryTimeout = numDnsQueryTimeout.Value; Settings.Default.DnsQueryRetryCount = numDnsQueryRetries.Value; Settings.Default.EnableThreading = chkEnableThreading.Checked; Settings.Default.EnableCustomDnsServers = chkEnableCustomDnsServers.Checked; Settings.Default.PrimaryDnsServer = txtCustomDnsServer1.Text; Settings.Default.SecondaryDnsServer = txtCustomDnsServer2.Text; Settings.Default.EnableDebugLogging = chkEnableDebugLogging.Checked; Settings.Default.Save(); } } }
496d537d81f27ccf333fc45039d0c0966c34d1bd
[ "C#" ]
6
C#
JDucktape/BatchDNSLookup
52cd88aa13d78a1102c0aa1a20ea186e2d07d681
53f987c3b6e923e9ab831d78ec366265bf983824
refs/heads/master
<repo_name>ZacharyJeffreys/javascript-hide-and-seek-bootcamp-prep-000<file_sep>/index.js function getFirstSelector(selector){ var element = document.querySelector(selector); return(element); } function nestedTarget(){ var element = document.querySelector(`#nested .target`); return element; } function increaseRankBy(n){ var ranks = document.querySelectorAll(`ul.ranked-list li`); for(var i = 0; ranks.length>i; i++){ ranks[i].innerHTML = parseInt(ranks[i].innerHTML) + n; } } /*function deepestChild(){ var deep = document.getElementById('grand-node').querySelectorAll('div') return deep[deep.length-1] }*/ function deepestChild() { var cur = document.getElementById('grand-node') var i = 0 while (cur.firstElementChild) { i = i + 1 cur = cur.firstElementChild } return cur } function criteriaFN(criteria) { if (criteria == "target") { return true } else { return false } } function find(array,criteriaFN) { let current = array let next = [] while (current) { if (criteriaFN(current)){ return current } if (Array.isArray(current)) { for (let i = 0; i < current.length; i++) { next.push(current[i]) } } current =next.shift() } return null }
d3019776354ef1afb290e4fc9ba33c435fab52ce
[ "JavaScript" ]
1
JavaScript
ZacharyJeffreys/javascript-hide-and-seek-bootcamp-prep-000
94be8a35f08be0d4d2dffbb6a607e5c2ad992f7f
c804ea21c6c997e7aca974593c5a22430792927b
refs/heads/master
<repo_name>jiakuanghe/Intent_Detection<file_sep>/model/dl_model/model_lstm_rl/tt.py #!/usr/bin/env python # coding=utf-8 class Foo(object): instance = None def __init__(self, name): self.name = name @classmethod def get_instance(cls): if cls.instance: return cls.instance else: obj = cls('hexm') cls.instance = obj return obj obj = Foo.get_instance() obj1 = Foo.get_instance() print(obj.name) print(obj1.name) print(Foo.instance) print(obj) class FF(object): _instance=None def __init__(self): self.s=123 def __new__(cls, *args, **kw): if not cls._instance: cls._instance = super(FF, cls).__new__(cls, *args, **kw) return cls._instance f1=FF() f2=FF() print(f1==f2) f1.s=345 print(f2.s)<file_sep>/pipeline.py #-*- from model.ml_model.intent_ml import IntentMl from model.dl_model.model_lstm_wjj.pipeline_lstm import IntentDLA from model.dl_model.model_lstm_mask.pipeline_lstm_mask import IntentDLB from entity_recognition.ner import EntityRecognition from xmlrpc.client import ServerProxy from sklearn.metrics import classification_report,precision_recall_fscore_support from corpus_data.data_deal import Intent_Data_Deal import logging from collections import defaultdict from configparser import ConfigParser import re import gc import pdb from IntentConfig import Config config=Config() logging.basicConfig(level=logging.INFO, format='%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s', datefmt='%a, %d %b %Y %H:%M:%S', filemode='w') _logger=logging.getLogger("pipeline") ML = IntentMl('Classifier') if config.dl_classifiers=='DLA': DLA=IntentDLA() elif config.dl_classifiers=='DLB': DLB=IntentDLB() idd=Intent_Data_Deal() # RE=IntentRe() ER=EntityRecognition() PATTERN='\\?|?|\\.|。' # classifier_dict={'BLSTM':1.0} classifier_dict={'BLSTM':1.0,'SVM':0.5,'LR':0.5,'RF':0.5} class Pipeline(object): def __init__(self): self.faq_dict=self._get_FAQ() def _get_FAQ(self): ''' 获取人工标注的FAQ意图 :return: ''' FAQ_dict={} with open('./faq_data/FAQ.txt','r') as fr: fr=( line for line in fr.readlines()) for line in fr: line=re.subn(PATTERN,'',line.replace('\n',''))[0].replace('\t\t','\t') try: sent=line.split('\t')[0] label=line.split('\t')[1].strip().split(' ')[0] if label not in ['',' ']: FAQ_dict[sent] = label except Exception as ex: print(ex,[line]) return FAQ_dict def get_ml_intent(self,sents:list)->dict: ''' 从ml模型获取意图 :param sents: :return: ''' ss=[' '.join(e) for e in ER.get_entity(sents)] _logger.info('data_deal_finish') return ML.infer(ss,classifier_name=config.ml_classifiers) def get_dlA_intent(self,sents:list)->list: ''' 从dl模型获取意图 :param sents: :return: ''' if config.dl_classifiers == 'DLA': for ele in DLA.get_intent(sents): yield ele[0][0] elif config.dl_classifiers == 'DLB': for ele in DLB.get_intent(sents): yield ele[0][0] def pipeline(self,sents:list)->dict: ''' 获取sents的意图 :param sents:list :return: ''' res_dict=defaultdict() dl_result=list(self.get_dlA_intent(sents)) _logger.info('DL 意图识别完成') ml_result=self.get_ml_intent(sents) _logger.info('ML 意图识别完成') all_dict=ml_result all_dict['BLSTM']=dl_result print(all_dict.keys()) for sent,ele in zip(sents,self.vote(all_dict)): res_dict[sent]=[[ele,1.0]] return res_dict def vote(self, class_result): ''' 投票 :param class_result: :return: ''' ss = [] for k, v in dict(class_result).items(): ele=[(e, classifier_dict[k]) for e in v] ss.append(ele) num_=len(ss[0]) result=[] for i in range(num_): ss_i_dict={} for j in range(len(ss)): if isinstance(ss[j][i][0],str): if ss[j][i][0].lower() not in ss_i_dict: ss_i_dict[ss[j][i][0].lower()]=ss[j][i][1] else: num=ss_i_dict[ss[j][i][0].lower()] num+=ss[j][i][1] ss_i_dict[ss[j][i][0].lower()]=num else: for ele in ss[j][i][0]: if ele.lower() not in ss_i_dict: ss_i_dict[ele.lower()]=ss[j][i][1] else: num=ss_i_dict[ele.lower()] num+=ss[j][i][1] ss_i_dict[ele.lower()]=num ss_sort=[[k,v] for k,v in ss_i_dict.items() if k not in ['',' ']] ss_sort.sort(key=lambda x:x[1],reverse=True) fin_res=ss_sort[0][0] result.append(fin_res) return result if __name__ == '__main__': pipeline=Pipeline() # sents=['感冒是不是重大疾病','感冒保不保','合同生效后能退保吗','你们的总部在那个城市','保单查询','广东分公司的联系方式','你们公司在哪','患艾滋病是否赔偿','吸食毒品定义','北京有哪些营销服务部', # '盐城营销服务部的联系方式','深圳营销服务部','代理人的姓名','深圳营销服务部电话号码是多少'] # result = pipeline.pipeline(sents) data_dict={} for sent in open('./corpus_data/dn.txt','r').readlines(): sent_eles=sent.replace('\n','').split('\t\t') data_dict[sent_eles[0].strip()]=[sent_eles[1],sent_eles[2]] sents=[] labels=[] label_dict={} for dev in open('./corpus_data/dev_out_char.txt','r').readlines(): sent_eles=dev.replace('\n','').split('\t') id=sent_eles[0].strip() try: sents.append(data_dict[id][0]) labels.append(data_dict[id][1]) label_dict[data_dict[id][0]]=data_dict[id][1] except: print(id) s=pipeline.get_ml_intent(sents) result=pipeline.pipeline(sents) print(len(labels),len(result)) right_sum=0 all_sum=0 for k,v in result.items(): pred_label=v[0][0] true_label=label_dict[k] all_sum+=1 if pred_label==true_label: right_sum+=1 # for true_label,pred_label in zip(labels,result): # # all_sum+=1 # if true_label==pred_label: # right_sum+=1 print(float(right_sum)/float(all_sum)) <file_sep>/model/dl_model/model_transformer/lstm_transformer.py import tensorflow as tf import os import sys sys.path.append('./') from model.dl_model.model_transformer.data_preprocess import Intent_Slot_Data from model.dl_model.model_transformer.model_fun import embedding,sent_encoder,self_attention,loss_function,intent_acc,cosin_com,\ label_sent_attention,output_layers,get_center_loss from model.dl_model.model_transformer.modules import * from IntentConfig import Config import numpy as np import logging import pickle from sklearn.metrics import classification_report,precision_recall_fscore_support,confusion_matrix import gc path=os.path.dirname(os.path.dirname(__file__)) sys.path.insert(0,path) from basic_model import BasicModel base_path=os.path.split(os.path.split(os.path.split(os.path.split(os.path.realpath(__file__))[0])[0])[0])[0] from entity_recognition.ner import EntityRecognition from xmlrpc.server import SimpleXMLRPCServer logging.basicConfig(level=logging.INFO, format='%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s', datefmt='%a, %d %b %Y %H:%M:%S', filename='modellog.log', filemode='w') _logger = logging.getLogger("intent_bagging") intent_config=Config() gpu_id=2 os.environ["CUDA_VISIBLE_DEVICES"] = "%s"%gpu_id class Config_lstm(object): ''' 默认配置 ''' learning_rate = 0.0001 batch_size = 128 label_max_len=16 sent_len = 30 # 句子长度 embedding_dim = 100 # 词向量维度 hidden_dim = 400 train_dir = './data/train_out_%s.txt' dev_dir = './data/dev_out.txt' test_dir = './data/test.txt' model_dir = base_path+'/save_model/model_lstm_mask/%s.ckpt'%intent_config.save_model_name print('config_lstm',model_dir) if not os.path.exists(base_path+'/save_model/model_lstm_mask'): os.makedirs(base_path+'/save_model/model_lstm_mask') use_cpu_num = 16 keep_dropout = 0.001 summary_write_dir = "./tmp/r_net.log" epoch = 90 use_auto_buckets=False lambda1 = 0.01 model_mode = 'bilstm_attention_crf' # 模型选择:bilstm bilstm_crf bilstm_attention bilstm_attention_crf,cnn_crf sinusoid=False num_blocks=6 num_heads=8 config = Config_lstm() tf.app.flags.DEFINE_float("mask_lambda1", config.lambda1, "l2学习率") tf.app.flags.DEFINE_float("mask_learning_rate", config.learning_rate, "学习率") tf.app.flags.DEFINE_float("mask_keep_dropout", config.keep_dropout, "dropout") tf.app.flags.DEFINE_integer("mask_batch_size", config.batch_size, "批处理的样本数量") tf.app.flags.DEFINE_integer("mask_max_len", config.sent_len, "句子长度") tf.app.flags.DEFINE_integer("mask_max_label_len", config.label_max_len, "句子长度") tf.app.flags.DEFINE_integer("mask_embedding_dim", config.embedding_dim, "词嵌入维度.") tf.app.flags.DEFINE_integer("mask_hidden_dim", config.hidden_dim, "中间节点维度.") tf.app.flags.DEFINE_integer("mask_use_cpu_num", config.use_cpu_num, "限定使用cpu的个数") tf.app.flags.DEFINE_integer("mask_epoch", config.epoch, "epoch次数") tf.app.flags.DEFINE_string("mask_summary_write_dir", config.summary_write_dir, "训练数据过程可视化文件保存地址") tf.app.flags.DEFINE_string("mask_train_dir", config.train_dir, "训练数据的路径") tf.app.flags.DEFINE_string("mask_dev_dir", config.dev_dir, "验证数据文件路径") tf.app.flags.DEFINE_string("mask_test_dir", config.test_dir, "测试数据文件路径") tf.app.flags.DEFINE_string("mask_model_dir", config.model_dir, "模型保存路径") tf.app.flags.DEFINE_boolean('mask_use Encoder2Decoder',False,'') tf.app.flags.DEFINE_string("mask_mod", "train", "默认为训练") # true for prediction tf.app.flags.DEFINE_string('mask_model_mode', config.model_mode, '模型类型') tf.app.flags.DEFINE_boolean('mask_use_auto_buckets',config.use_auto_buckets,'是否使用自动桶') tf.app.flags.DEFINE_string('mask_only_mode','intent','执行哪种单一任务') FLAGS = tf.app.flags.FLAGS def get_sent_mask(sent_ids, entity_ids): sent_mask = np.zeros_like(sent_ids, dtype=np.float32) for i in range(sent_ids.shape[0]): for j in range(sent_ids.shape[1]): if sent_ids[i, j] > 0 and sent_ids[i, j] not in entity_ids: sent_mask[i, j] = 1.0 elif sent_ids[i, j] > 0 and sent_ids[i, j] in entity_ids: sent_mask[i, j] = 0.5 return sent_mask class LstmMask(BasicModel): def __init__(self,scope='lstm',mod='train'): self.scope=scope if mod=='train': flag='train_new' else: flag='test' with tf.device('/gpu:%s'%gpu_id): self.dd = Intent_Slot_Data(train_path=base_path+"/corpus_data/%s"%intent_config.train_name, test_path=base_path+"/corpus_data/%s"%intent_config.dev_name, dev_path=base_path+"/corpus_data/%s"%intent_config.dev_name, batch_size=FLAGS.mask_batch_size, max_length=FLAGS.mask_max_len, flag=flag, use_auto_bucket=FLAGS.mask_use_auto_buckets,save_model=self.scope) self.word_vocab = self.dd.vocab self.word_num = self.dd.vocab_num self.id2intent = self.dd.id2intent self.intent_num = len(self.id2intent) def __build_model__(self,): with tf.variable_scope(name_or_scope=self.scope): with tf.device('/device:GPU:%s'%gpu_id): self.save_model=base_path+'/save_model/model_lstm_mask/%s.ckpt'%self.scope ee=EntityRecognition() self.entity_id = [] for k, v in self.word_vocab.items(): if k in ee.entity_dict.keys(): self.entity_id.append(v) self.sent_word = tf.placeholder(shape=(None, FLAGS.mask_max_len), dtype=tf.int32,name='sent_word') self.sent_len = tf.placeholder(shape=(None,), dtype=tf.int32,name='sent_len') self.sent_mask = tf.placeholder(shape=(None, FLAGS.mask_max_len), dtype=tf.float32,name='sent_mask') self.dropout=tf.placeholder(dtype=tf.float32) self.intent_y = tf.placeholder(shape=(None, self.intent_num), dtype=tf.int32,name='intent_y') with tf.variable_scope(name_or_scope='encoder'): self.encoder_input_emb = embedding(self.sent_word, vocab_size=self.word_num, num_units=FLAGS.mask_hidden_dim, scale=True, scope="enc_embed") ## Positional Encoding if config.sinusoid: self.encoder_input_emb += positional_encoding(self.sent_word, num_units=FLAGS.mask_hidden_dim, zero_pad=False, scale=False, scope="enc_pe") else: self.encoder_input_emb += embedding( tf.tile(tf.expand_dims(tf.range(tf.shape(self.sent_word)[1]), 0), [tf.shape(self.sent_word)[0], 1]), vocab_size=FLAGS.mask_max_len, num_units=FLAGS.mask_hidden_dim, zero_pad=False, scale=False, scope="enc_pe") ## Dropout self.encoder_input_emb = tf.layers.dropout(self.encoder_input_emb, rate=config.keep_dropout, training=True) # Blocks self.enc = self.encoder_input_emb for i in range(config.num_blocks): with tf.variable_scope("num_blocks_{}".format(i)): ### Multihead Attention self.enc = multihead_attention(queries=self.enc, keys=self.enc, num_units=FLAGS.mask_hidden_dim, num_heads=config.num_heads, dropout_rate=config.keep_dropout, is_training=True, causality=False) ### Feed Forward self.enc = feedforward(self.enc, num_units=[4 * FLAGS.mask_hidden_dim, FLAGS.mask_hidden_dim]) enc_out = mean_pool(self.enc, self.sent_len) out = tf.layers.dense(enc_out, self.intent_num) self.soft_logit = tf.nn.log_softmax(out, 1) self.preds = tf.to_int32(tf.argmax(self.soft_logit, 1)) self.acc = tf.cast(tf.reduce_sum(tf.to_float(tf.equal(self.preds, tf.to_int32(tf.argmax(self.intent_y,1))))) ,tf.float32)/tf.cast(tf.reduce_sum(self.preds,0),tf.float32) # self.loss = loss(dec, self.decoder_label, self.decoder_word_num, sample_num=FLAGS.num_samples, # decoder_seq_len=self.decoder_seq_len, # decoder_len=FLAGS.decoder_len, decoder_mask=self.decoder_mask) self.y_smoothed = label_smoothing(tf.cast(self.intent_y,tf.float32)) self.loss = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=self.soft_logit, labels=self.y_smoothed)) # self.loss = tf.losses.softmax_cross_entropy(self.decoder_label,self.dec) self.optimizer = tf.train.AdamOptimizer(FLAGS.mask_learning_rate, beta1=0.9, beta2=0.98, epsilon=1e-8).minimize( self.loss) def __train__(self): config = tf.ConfigProto(allow_soft_placement=True) _logger.info("load data") # _logger.info('entity_words:%s'%(entity_dict.keys())) with tf.Session(config=config) as sess: num_batch = self.dd.num_batch init_train_acc = 0.0 init_dev_acc = 0.0 init_train_loss=9999.99 init_dev_loss=9999.99 saver = tf.train.Saver() if os.path.exists('%s.meta' % self.save_model): saver.restore(sess, self.save_model) else: sess.run(tf.global_variables_initializer()) dev_sent, dev_slot, dev_intent, dev_rel_len,_ = self.dd.get_dev() dev_sent_mask = get_sent_mask(dev_sent, self.entity_id) train_sent, train_slot, train_intent, train_rel_len,_ = self.dd.get_train() train_sent_mask = get_sent_mask(train_sent, self.entity_id) for i in range(FLAGS.mask_epoch): for _ in range(num_batch): sent, slot, intent_label, rel_len, cur_len = self.dd.next_batch() batch_sent_mask = get_sent_mask(sent, self.entity_id) soft_logit_, loss_, _ = sess.run([self.soft_logit, self.loss, self.optimizer ], feed_dict={self.sent_word: sent, self.sent_len: rel_len, self.intent_y: intent_label, self.sent_mask: batch_sent_mask, self.dropout:FLAGS.mask_keep_dropout }) train_soft_logit_, train_loss_ = sess.run([self.soft_logit, self.loss], feed_dict={self.sent_word: train_sent, self.sent_len: train_rel_len, self.intent_y: train_intent, self.sent_mask: train_sent_mask, self.dropout:1.0 }) train_acc = intent_acc(train_soft_logit_, train_intent, self.id2intent) dev_soft_logit_, dev_loss_ = sess.run([self.soft_logit, self.loss], feed_dict={self.sent_word: dev_sent, self.sent_len: dev_rel_len, self.intent_y: dev_intent, self.sent_mask: dev_sent_mask, self.dropout:1.0 }) dev_acc = intent_acc(dev_soft_logit_, dev_intent, self.id2intent) # if train_acc > init_train_acc and dev_acc > (init_dev_acc-0.05): if dev_acc>init_dev_acc: init_dev_loss=dev_loss_ init_dev_acc=dev_acc # init_train_acc = train_acc # init_dev_acc = dev_acc _logger.info('save') saver.save(sess,self.save_model) _logger.info('第 %s 次迭代 train_loss:%s train_acc:%s dev_loss:%s dev_acc:%s' % ( i, train_loss_, train_acc, dev_loss_, dev_acc)) def __infer__(self,sents,sess): sent_arr, sent_vec = self.dd.get_sent_char(sents) sent_mask = get_sent_mask(sent_arr, self.entity_id) intent_logit = sess.run(self.soft_logit, feed_dict={self.sent_word: sent_arr, self.sent_len: sent_vec, self.sent_mask:sent_mask, self.dropout:1.0}) res = [] for ele in intent_logit: ss = [[self.id2intent[index], str(e)] for index, e in enumerate(ele) if e >= 0.3] if not ss: ss = [[self.id2intent[np.argmax(ele)], str(np.max(ele))]] res.append(ss) return res def infer_dev(self): config = tf.ConfigProto( # limit to num_cpu_core CPU usage inter_op_parallelism_threads=8, intra_op_parallelism_threads=8, log_device_placement=False, allow_soft_placement=True, ) id2intent = self.dd.id2intent id2sent=self.dd.id2sent saver = tf.train.Saver() with tf.Session(config=config) as sess: if os.path.exists('%s.meta' % self.save_model): saver.restore(sess, '%s' % self.save_model) else: sess.run(tf.global_variables_initializer()) dev_sent, dev_slot, dev_intent, dev_rel_len,dev_index = self.dd.get_dev() train_sent, train_slot, train_intent, train_rel_len,train_index = self.dd.get_train() dev_sent_mask = get_sent_mask(dev_sent, self.entity_id) train_sent_mask = get_sent_mask(train_sent, self.entity_id) dev_softmax_logit, dev_loss = sess.run([self.soft_logit, self.loss], feed_dict={self.sent_word: dev_sent, self.sent_len: dev_rel_len, self.intent_y: dev_intent, self.sent_mask: dev_sent_mask, self.dropout:1.0 }) self.matirx(dev_softmax_logit, dev_intent, id2intent,id2sent,dev_sent,dev_index, 'dev') train_softmax_logit, train_loss = sess.run([self.soft_logit, self.loss], feed_dict={self.sent_word: train_sent, self.sent_len: train_rel_len, self.intent_y: train_intent, self.sent_mask: train_sent_mask, self.dropout:1.0 }) self.matirx(train_softmax_logit, train_intent, id2intent,id2sent,train_sent,train_index, 'train') def __server__(self): config = tf.ConfigProto(device_count={"CPU": FLAGS.mask_use_cpu_num}, # limit to num_cpu_core CPU usage inter_op_parallelism_threads=8, intra_op_parallelism_threads=8, log_device_placement=False, allow_soft_placement=True, ) _logger.info("load data") with tf.Session(config=config) as sess: saver = tf.train.Saver() sess = tf.Session(config=config) if os.path.exists('%s.meta' % FLAGS.mask_model_dir): saver.restore(sess, '%s' % FLAGS.mask_model_dir) else: _logger.error('lstm没有模型') def intent(sent_list): sents = [] _logger.info("%s" % len(sent_list)) sents = [] for sent in sent_list: sents.append(self.dd.get_sent_char(sent)) sent_arr, sent_vec = self.dd.get_sent_char(sents) infer_sent_mask = get_sent_mask(sent_arr, self.entity_id) intent_logit = sess.run(self.soft_logit, feed_dict={self.sent_word: sent_arr, self.sent_len: sent_vec, self.sent_mask: infer_sent_mask}) res = [] for ele in intent_logit: ss = [[self.id2intent[index], str(e)] for index, e in enumerate(ele) if e >= 0.3] if not ss: ss = [[self.id2intent[np.argmax(ele)], str(np.max(ele))]] res.append(ss) del sents gc.collect() _logger.info('process end') _logger.info('%s' % res) return res svr = SimpleXMLRPCServer((intent_config.host, 8087), allow_none=True) svr.register_function(intent) svr.serve_forever() def matirx(self,pre_label,label,id2intent,id2sent,sent,indexs,type): pre_label_prob=np.max(pre_label,1) pre_label=np.argmax(pre_label,1) label=np.argmax(label,1) pre_label=pre_label.flatten() label=label.flatten() ss = [[int(k), v] for k, v in id2intent.items()] ss.sort(key=lambda x: x[0], reverse=False) labels = [e[0] for e in ss] traget_name=[e[1] for e in ss] class_re=classification_report(label,pre_label,target_names=traget_name,labels=labels) print(class_re) # con_mat=confusion_matrix(y_true=label,y_pred=pre_label,labels=labels) sents=[] for ele in sent: s=' '.join([id2sent[e]for e in ele if e!=0]) sents.append(s) confus_dict={} for ele in traget_name: confus_dict[ele]={} for e in traget_name: confus_dict[ele][e]=[0,[]] for true,pred,sent,prob,ii in zip(label,pre_label,sents,pre_label_prob,indexs): true_name=id2intent[true] pred_name=id2intent[pred] data_list=confus_dict[true_name][pred_name] data_list[0]+=1 data_list[1].append((ii,prob,sent)) confus_dict[true_name][pred_name]=data_list # print(confus_dict) if type=='train': pickle.dump(confus_dict,open('./train.p','wb')) elif type=='dev': pickle.dump(confus_dict,open('./dev.p','wb')) def main(_): lm=LstmMask() lm.__build_model__() if FLAGS.mask_mod=='train': lm.__train__() elif FLAGS.mask_mod=='infer_dev': lm.infer_dev() elif FLAGS.mask_mod=='server': lm.__server__() if __name__ == '__main__': tf.app.run()<file_sep>/model/dl_model/model_semantic_match_new/data_preprocess.py import numpy as np import pickle import os PATH=os.path.split(os.path.split(os.path.split(os.path.split(os.path.realpath(__file__))[0])[0])[0])[0] print(PATH) import logging import random import re from IntentConfig import Config from entity_recognition.ner import EntityRecognition from collections import defaultdict import os base_path = os.path.split(os.path.split(os.path.split(os.path.split(os.path.realpath(__file__))[0])[0])[0])[0] logging.basicConfig(level=logging.INFO, format='%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s', datefmt='%a, %d %b %Y %H:%M:%S', filemode='w') _logger=logging.getLogger("data_preprocess") config=Config() er=EntityRecognition() class Intent_Slot_Data(object): ''' intent_slot 数据处理模块 ''' def __init__(self, train_path, dev_path, test_path, batch_size, flag,max_length,use_auto_bucket): #分隔符 self.split_token='\t\t' self.train_path = train_path # 训练文件路径 self.dev_path = dev_path # 验证文件路径 self.test_path = test_path # 测试文件路径 self.batch_size = batch_size # batch大小 self.max_length = max_length self.use_auto_bucket=use_auto_bucket self.bucket_len=[0,5,15,30] self.index=0 if flag == "train_new": self.vocab= self.get_vocab() pickle.dump(self.vocab, open("vocab.p", 'wb')) # 词典 elif flag == "test" or flag == "train": self.vocab = pickle.load(open("vocab.p", 'rb')) # 词典 else: pass self.vocab_num=len(self.vocab) self.train_data= self.get_train_data() self.dev_data= self.get_dev_data() self.id2sent={} for k,v in self.vocab.items(): self.id2sent[v]=k def get_vocab(self): ''' 构造字典 dict{NONE:0,word1:1,word2:2...wordn:n} NONE为未登录词 :return: ''' train_file = open(self.train_path, 'r') test_file = open(self.dev_path, 'r') dev_file = open(self.test_path, 'r') vocab = {"NONE": 0,'bos':1,'eos':2} intent_vocab = {} slot_vocab={} self.index = len(vocab) self.intent_label_index = len(intent_vocab)+1 self.slot_label_index=len(slot_vocab) intent_num_vocab={} def _vocab(file): for ele in file: ele = ele.replace("\n", "") eles=ele.split(self.split_token) sent1=eles[0].split(' ') sent2=eles[1].split(' ') label=ele[2] for word in sent1: word=word.lower() if word not in vocab and word!='': vocab[word]=self.index self.index+=1 for word in sent2: word=word.lower() if word not in vocab and word!='': vocab[word]=self.index self.index+=1 _vocab(train_file) _vocab(dev_file) _vocab(test_file) return vocab def padd_sentences_no_buckets(self, sent_list): ''' find the max length from sent_list , and standardation :param sent_list: :return: ''' # slot_labels = [' '.join(str(sent).replace('\n', '').split('\t')[1].split(' ')[:-1]) for sent in sent_list] # intent_labels=[str(sent).replace('\n', '').split('\t')[1].split(' ')[-1] for sent in sent_list] words,slot_labels,intent_labels,loss_weights=[],[],[],[] sent1,sent2,label,sent1_len,sent2_len=[],[],[],[],[] for sent in sent_list: sent=sent.replace('\n','') sents=sent.split(self.split_token) s1,s2=[],[] for e in sents[0].split(' '): if e not in self.vocab: s1.append(0) else: s1.append(self.vocab[e]) for e in sents[1].split(' '): if e not in self.vocab: s2.append(0) else: s2.append(self.vocab[e]) sent1_len.append(len(s1)) sent2_len.append(len(s2)) s1.extend([0]*self.max_length) s2.extend([0]*self.max_length) sent1.append(s1[:self.max_length]) sent2.append(s2[:self.max_length]) label.append(sents[2]) sent1,sent2,sent1_len,sent2_len,label=np.array(sent1),np.array(sent2),np.array(sent1_len),np.array(sent2_len),np.array(label) return sent1,sent2,sent1_len,sent2_len,label def get_train_data(self): ''' 对训练样本按照长度进行排序 分箱 :return: ''' train_flie = open(self.train_path, 'r') data_list = [line for line in train_flie.readlines()] data_list.sort(key=lambda x: len(x)) # sort not shuffle random.shuffle(data_list) sent1, sent2, sent1_len, sent2_len, label = self.padd_sentences_no_buckets(data_list) return [sent1,sent2,sent1_len,sent2_len,label] def get_dev_data(self): train_flie = open(self.dev_path, 'r') data_list = [line for line in train_flie.readlines()] data_list.sort(key=lambda x: len(x)) # sort not shuffle random.shuffle(data_list) sent1, sent2, sent1_len, sent2_len, label = self.padd_sentences_no_buckets(data_list) return [sent1, sent2, sent1_len, sent2_len, label] def get_sent_char(self,sent_list): pattern = '\d{1,3}(\\.|,|、|?)|《|》|?|。| ' res=[] res_vec=[] sent_list = [re.subn(pattern, '', sent)[0] for sent in sent_list] sent_list=er.get_entity(sent_list) for sent in sent_list: ss=[] ss_new=['eos'] ss_new.extend(sent) ss_new.append('bos') ss_=ss_new for word in ss_: word=word.lower() if word in self.vocab: ss.append(self.vocab[word]) else: ss.append(self.vocab['NONE']) if len(ss)>=self.max_length: res_vec.append(self.max_length) ss=ss[:self.max_length] else: res_vec.append(len(ss)) padd=[0]*(self.max_length-len(ss)) ss.extend(padd) res.append(ss) sent_arr=np.array(res) sent_vec=np.array(res_vec) return sent_arr,sent_vec def get_origin_train_data(self): ''' :return: ''' sents,sents_len,intents=[],[],[] for line in open(base_path+'/corpus_data/train_out_char.txt','r').readlines(): lines=line.replace('\n','').split('\t') sent=lines[1] s=[] for ele in sent.split(' '): if ele in self.vocab: s.append(self.vocab[ele]) else: s.append(0) sents_len.append(len(s)) s.extend([0]*self.max_length) sents.append(s[:self.max_length]) intent=lines[3] intents.append(intent) sents=np.array(sents) return sents,sents_len,intents if __name__ == '__main__': dd = Intent_Slot_Data(train_path="train_en.txt", test_path="dev_en.txt", dev_path="dev_en.txt", batch_size=20 ,max_length=30, flag="train_new",use_auto_bucket=False) sent1, sent2, sent1_len, sent2_len, label=dd.dev_data # print(sent1.shape,sent2.shape,sent1_len.shape,sent2_len.shape) print(sent1[0]) print(sent2[0]) print(sent1_len[0]) print(sent2_len[0]) # for ele in dev_data: # pos_0=''.join( id2sent[e] for e in ele['pos_0']['word_arr'] if e !=0) # pos_1=''.join( id2sent[e] for e in ele['pos_1']['word_arr'] if e !=0) # neg_0=''.join( id2sent[e] for e in ele['neg_0']['word_arr'] if e !=0) # # print(pos_0,'\t\t',pos_1,'\t\t',neg_0,'\n') # dd.next_batch() # for k,v in dd.vocab.items(): # print(k,v) # ss=dd.get_sent_char(['康爱保保什么'])[0] # print(ss) # print(sent) # print(slot) # print(intent) # print(real_len) # # # # # print(sent) # print(loss_weight) # print(sent[0]) # print(''.join([dd.id2sent[e] for e in sent[0]])) # # print() # # print(sent.shape,slot.shape,intent.shape,real_len.shape,cur_len.shape) # # print(dd.slot_vocab) # # print(cur_len) # sent='专业导医陪诊是什么服务' # sent_arr,sent_vec=dd.get_sent_char([sent]) # # print(sent_arr) # print(sent_arr,sent_vec) <file_sep>/corpus_data/read_xlsx.py import xlrd import os tab=['1宏观预测','2产品诊断','3政策规范','5理财规划','4知识方法','6时事分析'] index=0 work_sheet=xlrd.open_workbook('./意图标注_20180719.xlsx') fw = open('ww.txt', 'w') for ele in tab: sheet=work_sheet.sheet_by_name(ele) for i in range(sheet.nrows): sent=sheet.cell_value(i,0).replace('\n','') label_level_1=ele try: label_level_2=sheet.cell_value(i,1) except Exception as ex: label_level_2='None' if not label_level_2: label_level_2='None' try: label_level_3=sheet.cell_value(i,2) if not label_level_3: label_level_3='None' except Exception: label_level_3='None' fw.write(str(index)) fw.write('\t\t') fw.write(sent) fw.write('\t\t') fw.write(label_level_1) fw.write('##') fw.write(label_level_2) fw.write('##') fw.write(label_level_3) fw.write('\n') index+=1<file_sep>/pipeline_tool.py ''' 单个模型的pipeline 比如多层意图 只能对某一层意图进行infer ''' from pre_data_deal import Pre_Data_Deal from NameEntityRec import NameEntityRec import random from IntentConfig import Config from collections import OrderedDict from model.dl_model.model_lstm_mask.lstm_mask import LstmMask from model.dl_model.model_lstm_mask.pipeline_lstm_mask import IntentDLB from model.ml_model.intent_ml import IntentMl from entity_recognition.ner import EntityRecognition from collections import defaultdict import math import logging logging.basicConfig(level=logging.INFO, format='%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s', datefmt='%a, %d %b %Y %H:%M:%S', filemode='w') _logger=logging.getLogger("pipeline_tool") class PipelineTool(object): def __init__(self,config): self.config=config self.corpus_path='./corpus_data/%s'%self.config.corpus_name #数据集路径 self.pdd=Pre_Data_Deal() #数据预处理 if config.save_model_name != 'intent_all': config.entity_level='level_2' self.ner=NameEntityRec(config) # self.origin_ner=EntityRecognition(config_=config) def pre_data_deal(self,sent): ''' 数据预处理 去停用词 :return: ''' return self.pdd.main(sent=sent) def entity_rec(self,sent): ''' 命名实体识别 :param sent: :return: ''' return self.ner.main(sent=sent)[1] def train_dev_split(self,datas,split_rate=0.2): ''' 构建 训练集/测试集 :param datas: :return: ''' self.intent_indice = int(len(self.config.root_intent.keys())-1) intent_dict_ = self.config.root_intent self.intent_dict = OrderedDict() for k, v in intent_dict_.items(): v_ = [e.lower() for e in v] self.intent_dict[k] = v_ fw_train = open('./corpus_data/%s'%self.config.train_name, 'w') fw_dev = open('./corpus_data/%s'%self.config.dev_name, 'w') num_dict = {} random.shuffle(datas) split_num = int(len(datas) * split_rate) # dev write for ele in datas[:split_num]: eles = ele.split('\t') left = eles[:-1] labels = eles[-1].lower().split('##') true_label = [] if self.intent_indice == 0: if labels[self.intent_indice] in self.intent_dict[0] and labels[self.intent_indice] != 'none': left.append(labels[0]) true_label.append(labels[0]) sent = '\t'.join(left) fw_dev.write(sent) fw_dev.write('\n') else: for i in range(self.intent_indice + 1): if labels[i] == 'none': true_label = [] break elif labels[i] in self.intent_dict[i]: true_label.append(labels[i]) elif labels[i] not in self.intent_dict[i]: true_label = [] break else: true_label = [] # print(true_label,'\t\t',ele) if true_label != []: left.append('_'.join(true_label)) sent = '\t'.join(left) fw_dev.write(sent) fw_dev.write('\n') if true_label != []: true_label = '_'.join(true_label) if true_label not in num_dict: num_dict[true_label] = 1 else: s = num_dict[true_label] s += 1 num_dict[true_label] = s '''train write''' for ele in datas[split_num::]: eles = ele.split('\t') left = eles[:-1] labels = eles[-1].split('##') true_label = [] if self.intent_indice == 0: if labels[self.intent_indice] in self.intent_dict[0] and labels[self.intent_indice] != 'none': left.append(labels[0]) true_label.append(labels[0]) sent = '\t'.join(left) fw_train.write(sent) fw_train.write('\n') else: for i in range(self.intent_indice + 1): if labels[i] == 'none': true_label = [] break elif labels[i] in self.intent_dict[i]: true_label.append(labels[i]) elif labels[i] not in self.intent_dict[i]: true_label = [] break else: true_label = [] if true_label != []: left.append('_'.join(true_label)) sent = '\t'.join(left) fw_train.write(sent) fw_train.write('\n') if true_label != []: true_label = '_'.join(true_label) if true_label not in num_dict: num_dict[true_label] = 1 else: s = num_dict[true_label] s += 1 num_dict[true_label] = s _logger.info(num_dict) def train(self): ''' :return: ''' datas=[] with open(self.corpus_path,'r') as fr: for line in fr.readlines(): pre_line=self.pre_data_deal(sent=line) entity_sent=self.entity_rec(sent=pre_line) datas.append(entity_sent) fr.close() self.train_dev_split(datas,0.2) # if self.config.ml_classifiers: intent_ml=IntentMl(self.config.ml_classifiers) intent_ml.build_model() outs=intent_ml.train(self.config.ml_classifiers) for ele in outs: for e in ele: _logger.info('%s'%e) if self.config.dl_classifiers=='DLB': lstm=LstmMask(scope=self.config.save_model_name) _logger.info('构建模型') lstm.__build_model__() _logger.info('LSTM mask is train') lstm.__train__() index=0 # for ele in outs: # _logger.info('第%s次迭代: 训练准确率:%s 测试准确率:%s'%(index,round(ele[0],2),round(ele[1],2))) # index+=1 _logger.info('模型存储在%s'%'./save_model/model_lstm_mask/%s'%self.config.save_model_name) '''#############################infer#########################''' def _get_FAQ(self): ''' 获取人工标注的FAQ意图 :return: ''' FAQ_dict = {} with open('./faq_data/FAQ.txt', 'r') as fr: fr = (line for line in fr.readlines()) for line in fr: line = line.replace('\n', '').replace('\t\t', '\t') try: sent = line.split('\t')[0] label = line.split('\t')[1].strip().split(' ')[0] if label not in ['', ' ']: FAQ_dict[sent] = label except Exception as ex: print(ex, [line]) return FAQ_dict def get_ml_intent(self, sents: list) -> dict: ''' 从ml模型获取意图 :param sents: :return: ''' ml=IntentMl(class_name=self.config.ml_classifiers) datas=[' '.join(e) for e in self.origin_ner.get_entity(sents)] return ml.infer(datas, classifier_name=self.config.ml_classifiers) def get_dlA_intent(self, sents: list,config) -> list: ''' 从dl模型获取意图 :param sents: :return: ''' dlb=IntentDLB(config) if self.config.dl_classifiers == 'DLB': for ele in dlb.get_intent(sents): yield ele[0][0] def infer(self,sents,config): ''' 预测 :return: ''' print('infer save_model',self.config.save_model_name) res_dict=defaultdict() all_dict={} if self.config.dl_classifiers: dl_result = list(self.get_dlA_intent(sents,config)) _logger.info('DL 意图识别完成 %s'%dl_result) all_dict['BLSTM'] = dl_result if self.config.ml_classifiers: ml_result = self.get_ml_intent(sents) _logger.info('ML 意图识别完成 %s'%ml_result) all_dict = ml_result for sent, ele in zip(sents, self.vote(all_dict)): res_dict[sent] = ele return res_dict def intent_hgyc_level2(self,sent): ''' :param sent: :return: ''' def vote(self, class_result): ''' 投票 :param class_result: :return: ''' ss = [] for k, v in dict(class_result).items(): ele = [(e, self.config.classifier_dict[k]) for e in v] ss.append(ele) num_ = len(ss[0]) result = [] for i in range(num_): ss_i_dict = {} for j in range(len(ss)): if isinstance(ss[j][i][0], str): if ss[j][i][0].lower() not in ss_i_dict: ss_i_dict[ss[j][i][0].lower()] = ss[j][i][1] else: num = ss_i_dict[ss[j][i][0].lower()] num += ss[j][i][1] ss_i_dict[ss[j][i][0].lower()] = num else: for ele in ss[j][i][0]: if ele.lower() not in ss_i_dict: ss_i_dict[ele.lower()] = ss[j][i][1] else: num = ss_i_dict[ele.lower()] num += ss[j][i][1] ss_i_dict[ele.lower()] = num ss_sort = [[k, v] for k, v in ss_i_dict.items() if k not in ['', ' ']] ss_sort.sort(key=lambda x: x[1], reverse=True) fin_res = ss_sort[0][0] result.append(fin_res) return result if __name__ == '__main__': config=Config() pipeline=PipelineTool(config) # pipeline.train() sent=['今天天气不词'] res=pipeline.infer(sent,config) print(res) # # config.save_model_name='intent_1' # # res=pipeline.infer(sent) # print(res) <file_sep>/corpus_data/pre_data_deal.py import re sub_pattern='你好|.{0,4}老师|.{0,4}年|.{0,4}%|,|谢谢你|谢谢|。|!|?|~' replace_pattern=r'\d{6}' replace_pattern_0=r'\d.' # s='600620' # if re.search(replace_pattern,s): # print(123) # # ss=re.subn(replace_pattern,'cpzd',s)[0] # print(ss) import jieba jieba.load_userdict('./stop_word.txt') stop_words=[ele.replace('\n','') for ele in open('./stop_word.txt','r').readlines()] def data_clean(sent): sent=re.subn(sub_pattern,'',sent)[0] sent=''.join([ele for ele in jieba.cut(sent) if ele not in []]) return sent fw=open('./dn.txt','w') for line in open('意图识别数据_all.txt','r').readlines(): line=line.replace('\n','') try: index=line.split('\t\t')[0] sent=line.split('\t\t')[1] label=line.split('\t\t')[2] except: print('error',line) sent=sent.split('?')[0].replace(' ','') sent=re.subn(replace_pattern,'stock',sent)[0] sent=re.subn(replace_pattern_0,'',sent)[0] new_sent=data_clean(sent) fw.write(index) fw.write('\t\t') fw.write(new_sent) fw.write('\t\t') fw.write(label) fw.write('\n') <file_sep>/model/dl_model/model_semantic_match_new/data_deal.py import os import random from collections import defaultdict base_path = os.path.split(os.path.split(os.path.split(os.path.split(os.path.realpath(__file__))[0])[0])[0])[0] train_path=base_path+'/corpus_data/train_out_char.txt' dev_path=base_path+'/corpus_data/dev_out_char.txt' data_type='train' fw=open('%s.txt'%data_type,'w') datas_dict=defaultdict(list) for line in open(train_path,'r').readlines(): lines=line.replace('\n','').split('\t') sent=lines[1] intent=lines[3] datas_dict[intent].append(sent) pos_num=0 neg_num=0 get_pos_num=3 get_neg_num=3 keys=list(datas_dict.keys()) for k in datas_dict.keys(): keys.remove(k) other_k=keys # print(other_k) v=datas_dict[k] for i in range(len(v)-get_pos_num): for j in range(i,i+get_pos_num): # print(v[i],'\t\t',v[j],'\t\t',1) pos_num+=1 fw.write(v[i]) fw.write('\t\t') fw.write(v[j]) fw.write('\t\t') fw.write('1') fw.write('\n') # pass random.shuffle(other_k) for ok in other_k[0:get_neg_num]: ov=datas_dict[ok] random.shuffle(ov) for e in ov[:1]: neg_num += 1 # print(v[i],'\t\t',e,'\t\t',0) fw.write(v[i]) fw.write('\t\t') fw.write(ov[0]) fw.write('\t\t') fw.write('0') fw.write('\n') # pass keys.append(k) print(pos_num,neg_num) # data=[] # for ele in open('./train.txt','r').readlines(): # if ele not in data: # data.append(ele) # # fw1=open('train_1.txt','w') # for e in data: # e=e.replace('\n','') # fw1.write(e) # fw1.write('\n')<file_sep>/download_model.sh #!/bash/bin scp -r wjj@192.168.3.132:/home/wjj/work_project/zdal/Intent_Dtection/save_model<file_sep>/NameEntityRec.py from entity_recognition.ner import EntityRecognition class NameEntityRec(object): def __init__(self,config): self.ner=EntityRecognition(config_=config) def main(self,sent): line = sent.replace('\n', '').strip() sent = '' ll = '' index = '' line = line.replace('\t\t', '\t').replace('Other', 'other').lower() if '\t' in line: index = str(line).split('\t')[0].strip().replace(' ', '') sent = str(line).split('\t')[1].strip().replace(' ', '') ll = str(line).split('\t')[2].strip().replace(' ', '') else: try: index = str(line).split(' ')[0].strip().replace(' ', '') sent = str(line).split(' ')[1].strip().replace(' ', '') ll = str(line).split(' ')[2].strip().replace(' ', '') except Exception as ex: print('NameEntityRec error:{}/{}'.format(line,ex)) ss = self.ner.get_entity([sent])[0] # 实体识别功能 sent = ' '.join(ss) label = ll sent = 'bos' + ' ' + sent + ' ' + 'eos' entity = ' '.join(['o'] * len(sent.split(' '))) res = str(index) + '\t' + sent + '\t' + entity + '\t' + label return sent, res <file_sep>/model/dl_model/model_lstm_mask/lstm_mask.py import tensorflow as tf import os import sys sys.path.append('./') from model.dl_model.model_lstm_mask.data_preprocess import Intent_Slot_Data from model.dl_model.model_lstm_mask.model_fun import embedding,sent_encoder,self_attention,loss_function,intent_acc,cosin_com,label_sent_attention,output_layers from model.dl_model.model_lstm_mask.focal_loss import focal_loss from IntentConfig import Config import numpy as np import logging import pickle from sklearn.metrics import classification_report,precision_recall_fscore_support,confusion_matrix import gc path=os.path.dirname(os.path.dirname(__file__)) sys.path.insert(0,path) from basic_model import BasicModel base_path=os.path.split(os.path.split(os.path.split(os.path.split(os.path.realpath(__file__))[0])[0])[0])[0] from entity_recognition.ner import EntityRecognition from xmlrpc.server import SimpleXMLRPCServer logging.basicConfig(level=logging.INFO, format='%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s', datefmt='%a, %d %b %Y %H:%M:%S', filename='modellog.log', filemode='w') _logger = logging.getLogger("intent_bagging") intent_config=Config() gpu_id=0 os.environ["CUDA_VISIBLE_DEVICES"] = "%s"%gpu_id class Config_lstm(object): ''' 默认配置 ''' learning_rate = 0.001 batch_size = 128 label_max_len=16 sent_len = 30 # 句子长度 embedding_dim = 100 # 词向量维度 hidden_dim = 400 train_dir = './data/train_out_%s.txt' dev_dir = './data/dev_out.txt' test_dir = './data/test.txt' model_dir = base_path+'/save_model/model_lstm_mask/%s.ckpt'%intent_config.save_model_name print('config_lstm',model_dir) if not os.path.exists(base_path+'/save_model/model_lstm_mask'): os.makedirs(base_path+'/save_model/model_lstm_mask') use_cpu_num = 16 keep_dropout = 0.7 summary_write_dir = "./tmp/r_net.log" epoch = 90 use_auto_buckets=False lambda1 = 0.01 model_mode = 'bilstm_attention_crf' # 模型选择:bilstm bilstm_crf bilstm_attention bilstm_attention_crf,cnn_crf config = Config_lstm() tf.app.flags.DEFINE_float("mask_lambda1", config.lambda1, "l2学习率") tf.app.flags.DEFINE_float("mask_learning_rate", config.learning_rate, "学习率") tf.app.flags.DEFINE_float("mask_keep_dropout", config.keep_dropout, "dropout") tf.app.flags.DEFINE_integer("mask_batch_size", config.batch_size, "批处理的样本数量") tf.app.flags.DEFINE_integer("mask_max_len", config.sent_len, "句子长度") tf.app.flags.DEFINE_integer("mask_max_label_len", config.label_max_len, "句子长度") tf.app.flags.DEFINE_integer("mask_embedding_dim", config.embedding_dim, "词嵌入维度.") tf.app.flags.DEFINE_integer("mask_hidden_dim", config.hidden_dim, "中间节点维度.") tf.app.flags.DEFINE_integer("mask_use_cpu_num", config.use_cpu_num, "限定使用cpu的个数") tf.app.flags.DEFINE_integer("mask_epoch", config.epoch, "epoch次数") tf.app.flags.DEFINE_string("mask_summary_write_dir", config.summary_write_dir, "训练数据过程可视化文件保存地址") tf.app.flags.DEFINE_string("mask_train_dir", config.train_dir, "训练数据的路径") tf.app.flags.DEFINE_string("mask_dev_dir", config.dev_dir, "验证数据文件路径") tf.app.flags.DEFINE_string("mask_test_dir", config.test_dir, "测试数据文件路径") tf.app.flags.DEFINE_string("mask_model_dir", config.model_dir, "模型保存路径") tf.app.flags.DEFINE_boolean('mask_use Encoder2Decoder',False,'') tf.app.flags.DEFINE_string("mask_mod", "infer_dev", "默认为训练") # true for prediction tf.app.flags.DEFINE_string('mask_model_mode', config.model_mode, '模型类型') tf.app.flags.DEFINE_boolean('mask_use_auto_buckets',config.use_auto_buckets,'是否使用自动桶') tf.app.flags.DEFINE_string('mask_only_mode','intent','执行哪种单一任务') FLAGS = tf.app.flags.FLAGS def get_sent_mask(sent_ids, entity_ids): sent_mask = np.zeros_like(sent_ids, dtype=np.float32) for i in range(sent_ids.shape[0]): for j in range(sent_ids.shape[1]): if sent_ids[i, j] > 0 and sent_ids[i, j] not in entity_ids: sent_mask[i, j] = 1.0 elif sent_ids[i, j] > 0 and sent_ids[i, j] in entity_ids: sent_mask[i, j] = 1.0 return sent_mask class LstmMask(BasicModel): def __init__(self,scope='lstm',mod='train'): self.scope=scope if mod=='train': flag='train_new' else: flag='test' with tf.device('/gpu:%s'%gpu_id): self.dd = Intent_Slot_Data(train_path=base_path+"/corpus_data/%s"%intent_config.train_name, test_path=base_path+"/corpus_data/%s"%intent_config.dev_name, dev_path=base_path+"/corpus_data/%s"%intent_config.dev_name, batch_size=FLAGS.mask_batch_size, max_length=FLAGS.mask_max_len, flag=flag, use_auto_bucket=FLAGS.mask_use_auto_buckets,save_model=self.scope) self.word_vocab = self.dd.vocab self.word_num = self.dd.vocab_num self.id2intent = self.dd.id2intent self.intent_num = len(self.id2intent) def _decay(self): costs = [] # 遍历所有可训练变量 for var in tf.trainable_variables(): # 只计算标有“DW”的变量 costs.append(tf.nn.l2_loss(var)) # 加和,并乘以衰减因子 return tf.multiply(0.0001, tf.add_n(costs)) def batch_norm(self, name, x): with tf.variable_scope(name): # 输入通道维数 params_shape = [x.get_shape()[-1]] # offset beta = tf.get_variable('beta', params_shape, tf.float32, initializer=tf.constant_initializer(0.0, tf.float32)) # scale gamma = tf.get_variable('gamma', params_shape, tf.float32, initializer=tf.constant_initializer(1.0, tf.float32)) if FLAGS.mask_mod == 'train': # 为每个通道计算均值、标准差 mean, variance = tf.nn.moments(x, [0, 1, 2], name='moments') # 新建或建立测试阶段使用的batch均值、标准差 moving_mean = tf.get_variable('moving_mean', params_shape, tf.float32, initializer=tf.constant_initializer(0.0, tf.float32), trainable=False) moving_variance = tf.get_variable('moving_variance', params_shape, tf.float32, initializer=tf.constant_initializer(1.0, tf.float32), trainable=False) # 添加batch均值和标准差的更新操作(滑动平均) # moving_mean = moving_mean * decay + mean * (1 - decay) # moving_variance = moving_variance * decay + variance * (1 - decay) self._extra_train_ops.append(moving_averages.assign_moving_average( moving_mean, mean, 0.9)) self._extra_train_ops.append(moving_averages.assign_moving_average( moving_variance, variance, 0.9)) else: # 获取训练中积累的batch均值、标准差 mean = tf.get_variable('moving_mean', params_shape, tf.float32, initializer=tf.constant_initializer(0.0, tf.float32), trainable=False) variance = tf.get_variable('moving_variance', params_shape, tf.float32, initializer=tf.constant_initializer(1.0, tf.float32), trainable=False) # 添加到直方图总结 tf.summary.histogram(mean.op.name, mean) tf.summary.histogram(variance.op.name, variance) # BN层:((x-mean)/var)*gamma+beta y = tf.nn.batch_normalization(x, mean, variance, beta, gamma, 0.001) y.set_shape(x.get_shape()) return y def __build_model__(self,): with tf.variable_scope(name_or_scope=self.scope): with tf.device('/device:GPU:%s'%gpu_id): self.save_model=base_path+'/save_model/model_lstm_mask/%s.ckpt'%self.scope ee=EntityRecognition() self.entity_id = [] for k, v in self.word_vocab.items(): if k in ee.entity_dict.keys(): self.entity_id.append(v) self.sent_word = tf.placeholder(shape=(None, FLAGS.mask_max_len), dtype=tf.int32,name='sent_word') self.sent_len = tf.placeholder(shape=(None,), dtype=tf.int32,name='sent_len') self.sent_mask = tf.placeholder(shape=(None, FLAGS.mask_max_len), dtype=tf.float32,name='sent_mask') self.dropout=tf.placeholder(dtype=tf.float32) self.intent_y = tf.placeholder(shape=(None, self.intent_num), dtype=tf.int32,name='intent_y') sent_emb = embedding(self.sent_word, self.word_num, FLAGS.mask_embedding_dim, 'sent_emb') sent_emb=tf.nn.dropout(sent_emb,self.dropout) label_emb = tf.Variable(tf.random_uniform(shape=(self.intent_num, 300),maxval=1.0,minval=-1.0, dtype=tf.float32), trainable=True) sen_enc = sent_encoder(sent_word_emb=sent_emb, hidden_dim=FLAGS.mask_hidden_dim, num=FLAGS.mask_max_len, sequence_length=self.sent_len, name='sent_enc',dropout=self.dropout) sent_attention = self_attention(sen_enc, self.sent_mask) stack_sent_enc = tf.stack([tf.concat((ele, sent_attention), 1) for ele in sen_enc], 1,name='stack_sent_enc') stack_sent_enc=tf.nn.dropout(stack_sent_enc,self.dropout) out = label_sent_attention(stack_sent_enc, label_emb, self.sent_mask) logit = output_layers(out, self.intent_num, name='out_layers', reuse=False) self.soft_logit = tf.nn.softmax(logit, 1,name='mask_soft_logit') loss=focal_loss(self.soft_logit,tf.cast(self.intent_y,tf.float32)) class_y = tf.constant(name='class_y', shape=[self.intent_num, self.intent_num], dtype=tf.float32, value=np.identity(self.intent_num), ) logit_label = output_layers(label_emb, self.intent_num, name='out_layers', reuse=True) label_loss = tf.losses.softmax_cross_entropy(onehot_labels=class_y, logits=logit_label) # # loss = tf.losses.softmax_cross_entropy(onehot_labels=self.intent_y, logits=logit) l2_loss=self._decay() self.loss = 0.7 * loss + 0.3 * label_loss # ss=tf.concat((sent_attention,tf.stack_sent_enc),1) # cosin=cosin_com(ss,label_emb,intent_num) # loss, soft_logit=loss_function(cosin,intent_y) # loss,soft_logit=loss_function(cosin,intent_y) # ss=tf.concat((sent_attention,sen_enc[0]),1) # logit=tf.layers.dense(ss,intent_num) # soft_logit=tf.nn.softmax(logit,1) # loss=focal_loss(soft_logit,tf.cast(intent_y,tf.float32)) # # loss=tf.losses.softmax_cross_entropy(intent_y,logit) # # self.optimizer = tf.train.AdamOptimizer(FLAGS.mask_learning_rate).minimize(self.loss) # opt=tf.train.AdamOptimizer(0.3) # grad_var=opt.compute_gradients(loss) # cappd_grad_varible=[[tf.clip_by_value(g,1e-5,1.0),v] for g,v in grad_var] # optimizer=opt.apply_gradients(grads_and_vars=cappd_grad_varible) def __train__(self): config = tf.ConfigProto(allow_soft_placement=True) _logger.info("load data") # _logger.info('entity_words:%s'%(entity_dict.keys())) with tf.Session(config=config) as sess: num_batch = self.dd.num_batch init_train_acc = 0.0 init_dev_acc = 0.0 init_train_loss=9999.99 init_dev_loss=9999.99 saver = tf.train.Saver() if os.path.exists('%s.meta' % self.save_model): saver.restore(sess, self.save_model) else: sess.run(tf.global_variables_initializer()) dev_sent, dev_slot, dev_intent, dev_rel_len,_ = self.dd.get_dev() dev_sent_mask = get_sent_mask(dev_sent, self.entity_id) train_sent, train_slot, train_intent, train_rel_len,_ = self.dd.get_train() train_sent_mask = get_sent_mask(train_sent, self.entity_id) for i in range(FLAGS.mask_epoch): for _ in range(num_batch): sent, slot, intent_label, rel_len, cur_len = self.dd.next_batch() batch_sent_mask = get_sent_mask(sent, self.entity_id) soft_logit_, loss_, _ = sess.run([self.soft_logit, self.loss, self.optimizer], feed_dict={self.sent_word: sent, self.sent_len: rel_len, self.intent_y: intent_label, self.sent_mask: batch_sent_mask, self.dropout:FLAGS.mask_keep_dropout }) train_soft_logit_, train_loss_ = sess.run([self.soft_logit, self.loss], feed_dict={self.sent_word: train_sent, self.sent_len: train_rel_len, self.intent_y: train_intent, self.sent_mask: train_sent_mask, self.dropout:1.0 }) train_acc = intent_acc(train_soft_logit_, train_intent, self.id2intent) dev_soft_logit_, dev_loss_ = sess.run([self.soft_logit, self.loss], feed_dict={self.sent_word: dev_sent, self.sent_len: dev_rel_len, self.intent_y: dev_intent, self.sent_mask: dev_sent_mask, self.dropout:1.0 }) dev_acc = intent_acc(dev_soft_logit_, dev_intent, self.id2intent) # if train_acc > init_train_acc and dev_acc > (init_dev_acc-0.05): if dev_acc>init_dev_acc: init_dev_loss=dev_loss_ init_dev_acc=dev_acc # init_train_acc = train_acc # init_dev_acc = dev_acc _logger.info('save') saver.save(sess,self.save_model) _logger.info('第 %s 次迭代 train_loss:%s train_acc:%s dev_loss:%s dev_acc:%s' % ( i, train_loss_, train_acc, dev_loss_, dev_acc)) def __infer__(self,sents,sess): sent_arr, sent_vec = self.dd.get_sent_char(sents) sent_mask = get_sent_mask(sent_arr, self.entity_id) intent_logit = sess.run(self.soft_logit, feed_dict={self.sent_word: sent_arr, self.sent_len: sent_vec, self.sent_mask:sent_mask, self.dropout:1.0}) res = [] for ele in intent_logit: ss = [[self.id2intent[index], str(e)] for index, e in enumerate(ele) if e >= 0.3] if not ss: ss = [[self.id2intent[np.argmax(ele)], str(np.max(ele))]] res.append(ss) return res def infer_dev(self): config = tf.ConfigProto( # limit to num_cpu_core CPU usage inter_op_parallelism_threads=8, intra_op_parallelism_threads=8, log_device_placement=False, allow_soft_placement=True, ) id2intent = self.dd.id2intent id2sent=self.dd.id2sent saver = tf.train.Saver() with tf.Session(config=config) as sess: if os.path.exists('%s.meta' % self.save_model): saver.restore(sess, '%s' % self.save_model) else: sess.run(tf.global_variables_initializer()) dev_sent, dev_slot, dev_intent, dev_rel_len,dev_index = self.dd.get_dev() train_sent, train_slot, train_intent, train_rel_len,train_index = self.dd.get_train() dev_sent_mask = get_sent_mask(dev_sent, self.entity_id) train_sent_mask = get_sent_mask(train_sent, self.entity_id) dev_softmax_logit, dev_loss = sess.run([self.soft_logit, self.loss], feed_dict={self.sent_word: dev_sent, self.sent_len: dev_rel_len, self.intent_y: dev_intent, self.sent_mask: dev_sent_mask, self.dropout:1.0 }) self.matirx(dev_softmax_logit, dev_intent, id2intent,id2sent,dev_sent,dev_index, 'dev') train_softmax_logit, train_loss = sess.run([self.soft_logit, self.loss], feed_dict={self.sent_word: train_sent, self.sent_len: train_rel_len, self.intent_y: train_intent, self.sent_mask: train_sent_mask, self.dropout:1.0 }) self.matirx(train_softmax_logit, train_intent, id2intent,id2sent,train_sent,train_index, 'train') def __server__(self): config = tf.ConfigProto(device_count={"CPU": FLAGS.mask_use_cpu_num}, # limit to num_cpu_core CPU usage inter_op_parallelism_threads=8, intra_op_parallelism_threads=8, log_device_placement=False, allow_soft_placement=True, ) _logger.info("load data") with tf.Session(config=config) as sess: saver = tf.train.Saver() sess = tf.Session(config=config) if os.path.exists('%s.meta' % FLAGS.mask_model_dir): saver.restore(sess, '%s' % FLAGS.mask_model_dir) else: _logger.error('lstm没有模型') def intent(sent_list): sents = [] _logger.info("%s" % len(sent_list)) sents = [] for sent in sent_list: sents.append(self.dd.get_sent_char(sent)) sent_arr, sent_vec = self.dd.get_sent_char(sents) infer_sent_mask = get_sent_mask(sent_arr, self.entity_id) intent_logit = sess.run(self.soft_logit, feed_dict={self.sent_word: sent_arr, self.sent_len: sent_vec, self.sent_mask: infer_sent_mask}) res = [] for ele in intent_logit: ss = [[self.id2intent[index], str(e)] for index, e in enumerate(ele) if e >= 0.3] if not ss: ss = [[self.id2intent[np.argmax(ele)], str(np.max(ele))]] res.append(ss) del sents gc.collect() _logger.info('process end') _logger.info('%s' % res) return res svr = SimpleXMLRPCServer((config_lstm.host, 8087), allow_none=True) svr.register_function(intent) svr.serve_forever() def matirx(self,pre_label,label,id2intent,id2sent,sent,indexs,type): pre_label_prob=np.max(pre_label,1) pre_label=np.argmax(pre_label,1) label=np.argmax(label,1) pre_label=pre_label.flatten() label=label.flatten() ss = [[int(k), v] for k, v in id2intent.items()] ss.sort(key=lambda x: x[0], reverse=False) labels = [e[0] for e in ss] traget_name=[e[1] for e in ss] class_re=classification_report(label,pre_label,target_names=traget_name,labels=labels) print(class_re) # con_mat=confusion_matrix(y_true=label,y_pred=pre_label,labels=labels) sents=[] for ele in sent: s=' '.join([id2sent[e]for e in ele if e!=0]) sents.append(s) confus_dict={} for ele in traget_name: confus_dict[ele]={} for e in traget_name: confus_dict[ele][e]=[0,[]] for true,pred,sent,prob,ii in zip(label,pre_label,sents,pre_label_prob,indexs): true_name=id2intent[true] pred_name=id2intent[pred] data_list=confus_dict[true_name][pred_name] data_list[0]+=1 data_list[1].append((ii,prob,sent)) confus_dict[true_name][pred_name]=data_list # print(confus_dict) if type=='train': pickle.dump(confus_dict,open('./train.p','wb')) elif type=='dev': pickle.dump(confus_dict,open('./dev.p','wb')) def main(_): lm=LstmMask() lm.__build_model__() if FLAGS.mask_mod=='train': lm.__train__() elif FLAGS.mask_mod=='infer_dev': lm.infer_dev() elif FLAGS.mask_mod=='server': lm.__server__() if __name__ == '__main__': tf.app.run()<file_sep>/model/re_model/intent_entity_to_es.py #!/usr/bin/python3 # coding: utf-8 import requests import json import datetime ES_HOST = '192.168.3.105' # 公司内网地址 # ES_HOST = '192.168.3.11' # 外网30G内存对应的数据库 # ES_HOST = '172.16.58.3' # 外网,南迪数据管理关联的es数据库; # ES_HOST = '10.13.70.57' # 外网词向量测试服 # ES_HOST = '10.13.70.173' # 外网词向量正式服 # ES_HOST = None ES_PORT = '9200' ES_INDEX = 'intent' # 必须是小写 ES_USER = 'elastic' ES_PASSWORD = '<PASSWORD>' intent_entity_dict={'理赔_申请_保障项目' : [['Baoxianchanpin', 'Baozhangxiangmu'], []] , '询问_犹豫期' : [['Baoxianchanpin'], []] , '询问_保险责任' : [['Baoxianchanpin'], []] , '询问_合同_恢复' : [['Baoxianchanpin'], []] , '询问_保单_借款' : [['Baoxianchanpin'], []] , '询问_特别约定' : [['Baoxianchanpin'], []] , '询问_合同_终止' : [['Baoxianchanpin'], []] , '询问_合同_成立' : [['Baoxianchanpin'], []] , '询问_宣告死亡' : [['Baoxianchanpin'], []] , '询问_如实告知' : [['Baoxianchanpin'], []] , '询问_合同_解除' : [['Baoxianchanpin'], []] , '询问_保险期间' : [['Baoxianchanpin'], []] , '询问_保费_缴纳_垫缴' : [['Baoxianchanpin'], []] , '询问_受益人' : [['Baoxianchanpin'], []] , '询问_体检' : [['Baoxianchanpin'], []] , '询问_未归还款项偿还' : [['Baoxianchanpin'], []] , '介绍_合同_构成' : [['Baoxianchanpin'], []] , '询问_争议处理' : [['Baoxianchanpin'], []] , '询问_投保_年龄' : [['Baoxianchanpin'], []] , '询问_投保_适用币种' : [['Baoxianchanpin'], []] , '询问_保险金额_基本保险金额' : [['Baoxianchanpin'], []] , '询问_合同_种类' : [['Baoxianchanpin'], []] , '询问_等待期' : [['Baoxianchanpin'], []] , '询问_减额缴清' : [['Baoxianchanpin'], []] , '询问_保费_缴纳_方式' : [['Baoxianchanpin'], ['Jiaofeifangshi']] , '询问_保费_缴纳_年期' : [['Baoxianchanpin'], []] , '介绍_服务内容' : [['Fuwuxiangmu'], []] , '承保内容_产品_疾病' : [['Baoxianchanpin'], []] , '询问_公司_产品' : [['Baozhangxiangmu', 'Baoxianchanpin'], []] , '询问_宽限期_时间' : [['Baoxianchanpin'], []] , '询问_宽限期_定义' : [['Baoxianchanpin'], []] , '询问_产品_优势' : [['Baoxianchanpin'], []] , '询问_免赔_额_定义' : [['Baoxianchanpin'], []] , '询问_免赔_额_数值' : [['Baoxianchanpin'], []] , '询问_保费_缴纳' : [['Baoxianchanpin'], []] , '询问_诉讼时效' : [['Baoxianchanpin'], []] , '变更_通讯方式' : [['Baoxianchanpin'], []] , '询问_保险金_给付' : [['Baoxianchanpin'], []] , '区别' : [[], []] , '承保_投保_疾病' : [['Baoxianchanpin', 'Jibing'], []] , '询问_保单_借款_还款期限' : [['Baoxianchanpin'], []] , '承保_投保_情景' : [['Baoxianchanpin', 'Qingjing'], []] , '介绍_定义_保险种类' : [[], ['Baoxianzhonglei']] , '承保范围_情景' : [['Baoxianchanpin', 'Qingjing'], []] , '介绍_定义_疾病种类' : [['Jibingzhonglei', 'Baoxianchanpin'], []] , '介绍_定义_保障项目' : [['Baoxianchanpin', 'Baozhangxiangmu'], []] , '理赔_申请_疾病种类' : [['Baoxianchanpin', 'Jibingzhonglei'], []] , '询问_失踪处理' : [['Baoxianchanpin'], []] , '询问_疾病种类_包含_疾病' : [['Baoxianchanpin', 'Jibingzhonglei'], []] , '询问_疾病_属于_疾病种类' : [['Baoxianchanpin', 'Jibing', 'Jibingzhonglei'], []] , '询问_信息误告' : [['Baoxianchanpin'], []] , '询问_疾病种类_包含' : [['Jibingzhonglei'], []] , '询问_疾病_预防' : [['Jibing'], []] , '询问_疾病_高发疾病' : [['Baoxianchanpin'], []] , '询问_体检_异常指标分析' : [[], []] , '介绍_定义_体检异常指标' : [[], []] , '介绍_身体器官_构成' : [[], []] , '询问_疾病_发病原因' : [['Jibing'], []] , '询问_体检_体检项目_内容' : [[], []] , '询问_投保_途径_使用方法' : [[], []] , '询问_合同_领取方式' : [[], ['Baoxianchanpin']] , '询问_投保_途径' : [[], ['Baoxianchanpin']] , '询问_投保人_被保险人' : [[], []] , '区别_疾病种类' : [['Baoxianchanpin'], []] , '限制_保障项目_年龄' : [['Baoxianchanpin', 'Baozhangxiangmu'], []] , '介绍_公司_经营状况' : [['Baoxianchanpin'], []] , '限制_投保_职业' : [['Baoxianchanpin'], []] , '询问_产品_优惠' : [[], ['Baoxianchanpin']] , '询问_保费_缴纳_方式_保险种类' : [['Baoxianzhonglei'], ['Baoxianchanpin']] , '限制_体检时限' : [[], []] , '询问_投保_途径_投保流程' : [['Baoxianchanpin'], []] , '询问_保费_定价' : [['Baoxianchanpin'], []] , '理赔_申请_渠道' : [[], []] , '询问_产品_最低保额' : [['Baoxianchanpin'], []] , '理赔_缓缴保险费' : [['Baoxianchanpin'], []] , '理赔_申请_资料_保障项目' : [[], ['Baozhangxiangmu']] , '介绍_公司_股东构成' : [[], []] , '理赔_重复理赔_保障项目' : [['Baozhangxiangmu', 'Baoxianchanpin'], []] , '询问_产品_价格' : [['Baoxianchanpin'], []] , '介绍_公司' : [[], []] , '询问_产品_属于_保险种类' : [['Baoxianchanpin', 'Baoxianzhonglei'], []] , '承保_区域' : [['Baoxianchanpin'], []] , '询问_保障项目_赔付_次数' : [['Baoxianchanpin', 'Baozhangxiangmu'], []] , '询问_保费_缴纳_渠道' : [['Baoxianchanpin'], []] , '询问_财务问卷-对象' : [[], []] , '询问_疾病种类_治疗费用' : [['Jibingzhonglei'], []] , '限制_投保_特殊人群' : [['Baoxianchanpin'], []] , '询问_保险金额_推荐金额' : [['Baoxianchanpin'], []] , '询问_核保_未通过_解决办法' : [[], []] , '询问_体检_标准' : [[], []] , '询问_投保_资料' : [['Baoxianchanpin'], []] , '询问_保险条款' : [['Baoxianchanpin'], []] , '理赔_医院' : [['Baoxianchanpin'], ['Yiyuan']] , '询问_保障项目_赔付' : [['Baoxianchanpin', 'Baozhangxiangmu'], []] , '介绍_产品_推荐' : [['Baoxianchanpin'], []] , '限制_工具使用' : [[], []] , '询问_保险类型' : [['Baoxianchanpin'], []] , '询问_诊断报告_领取' : [[], []] , '介绍_产品_升级' : [['Baoxianchanpin'], []] , '询问_体检_指引' : [['Baoxianchanpin'], []] , '询问_疾病种类_生存期' : [['Jibingzhonglei', 'Baoxianchanpin'], []] , '限制_地域_理赔' : [[], []] , '限制_投保_特殊人群_保额' : [['Baoxianchanpin'], []] , '询问_权益关系' : [['Baoxianchanpin'], []] , '承保_范围_保障项目' : [['Baoxianchanpin', 'Baozhangxiangmu'], []] , '介绍_产品' : [[], []] , '询问_合同_纸质合同_申请' : [[], []] , '询问_疾病种类_赔付流程' : [['Baoxianchanpin', 'Baoxianzhonglei'], []] , '理赔_速度' : [['Baoxianchanpin'], []] , '限制_地域_产品保障' : [['Baoxianchanpin'], []] , '询问_合同_丢失' : [[], []] , '介绍_合同_电子合同' : [[], []] , '询问_保单_查询' : [[], []] , '理赔_条件' : [['Baoxianchanpin', 'Baozhangxiangmu'], []] , '理赔_方式' : [['Baoxianchanpin', 'Baozhangxiangmu'], []] , '询问_投保_指引' : [['Baoxianchanpin'], []] , '询问_业务_材料' : [[], []] , '限制_投保人' : [[], []] , '限制_红利申请' : [[], []] , '询问_合同_终止_情景' : [[], ['Qingjing']] , '理赔_报案_目的' : [[], []] , '询问_险种关联_申请资料' : [[], []] , '变更_投保人' : [['Baoxianchanpin'], []] , '询问_查询方式' : [[], []] , '理赔_申请_疾病' : [['Baoxianchanpin', 'Jibing'], []] , '赔付_疾病_保障项目' : [['Baoxianchanpin', 'Jibing', 'Baozhangxiangmu'], []] , '赔付_情景_保障项目' : [['Baoxianchanpin', 'Qingjing', 'Baozhangxiangmu'], []] , '介绍_定义_情景' : [['Qingjing'], []] , '介绍_定义_疾病' : [['Jibing', 'Baoxianchanpin'], []] , '询问_保险事故通知' : [['Baoxianchanpin'], []] , '询问_疾病_包含_疾病' : [['Jibing'], []] , '介绍_定义_释义项' : [['Shiyi'], []] , # '询问_公司_分公司_联系方式' : [[], []] , '询问_复效期' : [['Baoxianchanpin'], []] , '理赔_比例' : [['Baoxianchanpin', 'Baozhangxiangmu'], []] , '限制_投保' : [['Baoxianchanpin'], []] , '询问_投保人' : [['Baoxianchanpin'], []] , '变更_缴费方式' : [['Baoxianchanpin'], []] , '询问_现金价值' : [['Baoxianchanpin'], []] , '询问_保险种类' : [['Baoxianchanpin'], ['Baoxianzhonglei']] , '介绍_定义_产品' : [[], ['Baoxianzhonglei']] , '承保_范围_疾病' : [['Baoxianchanpin', 'Jibing'], []] , '询问_复效期_滞纳金' : [['Baoxianchanpin'], []] , '询问_减额缴清_影响' : [['Baoxianchanpin'], []] , '限制_保险种类_年龄' : [['Baoxianzhonglei'], []] , '询问_保费_缴纳_忘缴' : [[], []] , '限制_购买_产品' : [['Baoxianchanpin'], []] , '理赔_申请_特殊情况' : [[], ['Baoxianchanpin']] , '询问_现金价值_豁免保费' : [['Baoxianchanpin'], []] , '询问_投保_途径_月缴首期' : [[], []] , '询问_保障项目_赔付_赔付一半' : [['Baozhangxiangmu'], []] , '理赔_方式_特殊人群' : [['Baoxianchanpin'], []] , '限制_国外医院' : [[], []] , '介绍_投资连结保险投资账户' : [[], []] , '询问_增值服务_项目' : [['Baoxianchanpin', 'Fuwuxiangmu'], []] , '询问_增值服务_内容' : [['Baoxianchanpin', 'Fuwuxiangmu'], []] , '询问_合作单位_合作医院' : [[], []] , '询问_保险金额' : [['Baoxianchanpin'], []] , '介绍_定义_公司' : [[], []] , '询问_免赔_额_数值_保险种类' : [['Baoxianzhonglei'], []] , '询问_合同_附加险' : [['Baoxianchanpin'], []] , '询问_保险金额_保额累计' : [['Baoxianchanpin'], []] , '询问_投保书_填写' : [[], []] , '承保_范围_产品_疾病' : [['Baoxianchanpin'], []] , '变更_合同' : [['Baoxianchanpin'], []] , '询问_引导' : [[], []] , '询问_保费_支出' : [[], []] , '询问_公司_地址' : [[], []] , '询问_联系方式' : [['Didian'], []] , '询问_合作单位_合作银行' : [[], []] , '询问_商业保险与医保的关系' : [['Baoxianchanpin'], []] , '询问_保单_回溯' : [[], ['保单回溯']] , '询问_体检_意义' : [[], []] , '询问_合作单位_中信银行' : [[], []] , '询问_产品_对比' : [['Baoxianchanpin'], []] , '询问_疾病_治疗费用' : [[], []] , '询问_增值服务_使用次数' : [[], []] , '询问_增值服务_使用时间' : [['Baoxianchanpin'], []] , '询问_增值服务_亮点' : [[], []] , '变更通讯资料相关规定' : [[], []] , '银行转账授权相关规定' : [[], []] , '变更投保人相关规定' : [[], []] , '更改个人身份资料相关规定' : [[], []] , '变更签名相关规定' : [[], []] , '保费逾期未付选择相关规定' : [[], []] , '变更受益人相关规定' : [[], []] , '领取现金红利相关规定' : [[], []] , '身故保险金分期领取选择相关规定' : [[], []] , '变更红利领取方式相关规定' : [[], []] , '指定第二投保人相关规定' : [[], []] , '复效相关规定' : [[], []] , '变更职业等级相关规定' : [[], []] , '变更缴费方式相关规定' : [[], []] , '结束保险费缓缴期相关规定' : [[], []] , '降低主险保额相关规定' : [[], []] , '变更附加险相关规定' : [[], []] , '减额缴清相关规定' : [[], []] , '补充告知相关规定' : [[], []] , '取消承保条件相关规定' : [[], []] , '保单借款相关规定' : [[], []] , '保单还款相关规定' : [[], []] , '生存给付确认相关规定' : [[], []] , '变更年金领取方式相关规定' : [[], []] , '变更生存保险金领取方式相关规定' : [[], []] , '领取生存保险金相关规定' : [[], []] , '变更给付账号相关规定' : [[], []] , '满期给付生存确认相关规定' : [[], []] , '险种关联选择相关规定' : [[], []] , '部分提取相关规定' : [[], []] , '额外投资相关规定' : [[], []] , '投资账户选择相关规定' : [[], []] , '投资账户转换相关规定' : [[], []] , '终止保险合同相关规定' : [[], []] , '申请定期额外投资相关规定' : [[], []] , '变更定期额外投资相关规定' : [[], []] , '终止定期额外投资相关规定' : [[], []] , '犹豫期减保相关规定' : [[], []] , '犹豫期终止合同相关规定' : [[], []] , '犹豫期其他保全变更相关规定' : [[], []] , '补发保单相关规定' : [[], []] , '变更通讯资料申请时间' : [[], []] , '银行转账授权申请时间' : [[], []] , '变更投保人申请时间' : [[], []] , '更改个人身份资料申请时间' : [[], []] , '变更签名申请时间' : [[], []] , '保费逾期未付选择申请时间' : [[], []] , '变更受益人申请时间' : [[], []] , '领取现金红利申请时间' : [[], []] , '身故保险金分期领取选择申请时间' : [[], []] , '变更红利领取方式申请时间' : [[], []] , '指定第二投保人申请时间' : [[], []] , '复效申请时间' : [[], []] , '变更职业等级申请时间' : [[], []] , '变更缴费方式申请时间' : [[], []] , '结束保险费缓缴期申请时间' : [[], []] , '降低主险保额申请时间' : [[], []] , '变更附加险申请时间' : [[], []] , '减额缴清申请时间' : [[], []] , '补充告知申请时间' : [[], []] , '取消承保条件申请时间' : [[], []] , '保单借款申请时间' : [[], []] , '保单还款申请时间' : [[], []] , '生存给付确认申请时间' : [[], []] , '变更年金领取方式申请时间' : [[], []] , '变更生存保险金领取方式申请时间' : [[], []] , '领取生存保险金申请时间' : [[], []] , '变更给付账号申请时间' : [[], []] , '满期给付生存确认申请时间' : [[], []] , '险种关联选择申请时间' : [[], []] , '部分提取申请时间' : [[], []] , '额外投资申请时间' : [[], []] , '投资账户选择申请时间' : [[], []] , '投资账户转换申请时间' : [[], []] , '终止保险合同申请时间' : [[], []] , '申请定期额外投资申请时间' : [[], []] , '变更定期额外投资申请时间' : [[], []] , '终止定期额外投资申请时间' : [[], []] , '犹豫期减保申请时间' : [[], []] , '犹豫期终止合同申请时间' : [[], []] , '犹豫期其他保全变更申请时间' : [[], []] , '补发保单申请时间' : [[], []] , '保险产品支持保全项' : [['Baoxianchanpin'], []] , '保险产品变更通讯资料的范围' : [['Baoxianchanpin'], []] , '保险产品银行转账授权的范围' : [['Baoxianchanpin'], []] , '保险产品更改个人身份资料的范围' : [['Baoxianchanpin'], []] , '保险产品变更签名的范围' : [['Baoxianchanpin'], []] , '保险产品变更受益人的范围' : [['Baoxianchanpin'], []] , '保险产品变更投保人的范围' : [['Baoxianchanpin'], []] , '保险产品保费逾期未付选择的范围' : [['Baoxianchanpin'], []] , '保险产品补发保单的范围' : [['Baoxianchanpin'], []] , '保险产品变更职业等级的范围' : [['Baoxianchanpin'], []] , '保险产品变更缴费方式的范围' : [['Baoxianchanpin'], []] , '保险产品变更保险计划的范围' : [['Baoxianchanpin'], []] , '保险产品复效的范围' : [['Baoxianchanpin'], []] , '保险产品减额缴清的范围' : [['Baoxianchanpin'], []] , '保险产品取消承保条件的范围' : [['Baoxianchanpin'], []] , '保险产品补充告知的范围' : [['Baoxianchanpin'], []] , '保险产品保单借款的范围' : [['Baoxianchanpin'], []] , '保险产品保单还款的范围' : [['Baoxianchanpin'], []] , '保险产品终止保险合同的范围' : [['Baoxianchanpin'], []] , '保险产品附约变更的范围' : [['Baoxianchanpin'], []] , '保险产品满期生存确认的范围' : [['Baoxianchanpin'], []] , '保险产品降低主险保额的范围' : [['Baoxianchanpin'], []] , '询问_产品_续保' : [['Baoxianchanpin'], []] , '询问_产品_期满返还' : [['Baoxianchanpin'], []] , '询问_产品_费用与报销' : [['Baoxianchanpin'], []] , '变更_保险金额' : [['Baoxianchanpin'], []] , '限制_保险金额' : [['Baoxianchanpin'], []] , '理赔_情景_全残或身故' : [['Qingjing', 'Baoxianchanpin'], []] , '承保_范围_保障项目_疾病' : [['Baozhangxiangmu'], []] , '询问_责任免除_条款' : [['Baoxianchanpin'], []] , '询问_责任免除_保障项目' : [['Baoxianchanpin'], []] , '询问_疾病_属于_产品' : [['Baoxianchanpin'], []] , # '承保_范围_产品_疾病' : [['Baoxianchanpin'], []] , '承保_范围_情景' : [['Baoxianchanpin', 'Jibing'], []] , '询问_豁免_可豁免' : [['Baoxianchanpin', 'Jibing'], []] , '理赔_申请_资料' : [['Baoxianchanpin'], []] , '询问_保费_核算' : [['Baoxianchanpin'], []] , '变更_保全' : [[], []] , '询问_豁免_不可豁免' : [['Baoxianchanpin', 'Jibing'], []] , '理赔_重复理赔' : [['Baoxianchanpin', 'Jibing'], []] , '询问_补偿原则':[[],[]], '询问_产品_续保_年限':[['Baoxianchanpin'],[]], '询问_ 无保险事故_优惠':[[],[]], '询问_保费_费率_调整':[[],[]], '询问_附加险_规则':[[],[]], '询问_合同_解除_时限':[[],[]], '询问_公司_总部':[[],[]], '询问_公司_区域范围':[['Didian'],[]], '询问_服务时间':[['Didian'],[]], '询问_保全规则':[[],[]], '询问_保单_代理人信息':[[],[]], '介绍_公司_名称':[[],[]], '介绍_产品_名称':[[],[]], '区别_保险责任':[[],[]], '区别_投保年龄':[[],[]], '区别_责任免除':[[],[]], '区别_现金价值':[[],[]], '区别_重疾种类':[[],[]], '区别_重疾定义':[[],[]], '区别_缴费期限':[[],[]], '区别_保险金额_限制':[[],[]], '区别_保额累计_限制':[[],[]], '询问_地址':[['Didian'],[]], } for k in intent_entity_dict.keys(): print(k,'\t',':','\t') def download_template_intent(es_host=ES_HOST, es_port=ES_PORT, _index='templates_question', es_user=ES_USER, es_password=ES_PASSWORD, pid='all_baoxian'): """ 模板里头有必须实体,可选实体,以模板数据为准 :param es_host: :param es_port: :param _index: :param _type: :param es_user: :param es_password: :param data: :param pid: :return: """ es_index_alias = "{}_{}_alias".format(pid.lower(), _index) intent_bixuan_kexuan_dict = {} intent_list = list(intent_entity_dict.keys()) try: # 获取全部的模板数据 url = 'http://{}:{}/{}/_search?scroll=10m&size=5000'.format(es_host, es_port, es_index_alias) args_json = { "query" : { "match_all" : {} } } r = requests.get(url, json=args_json, auth=(es_user, es_password)) ret = r.json() hits = ret['hits']['hits'] datas = [h['_source'] for h in hits] except Exception as e: print("在索引`{}:{}/{}`下获取意图为`{}`的必须、可选参数出错: \n{}".format(ES_HOST, ES_PORT, es_index_alias, intent_list, e)) datas = [] for data in datas: intent = data.get('intent') pass_intent_list = [] assert intent in intent_list or intent in pass_intent_list, "模板中的意图`{}`应该在意图字典中存在".format(intent) bixuan = data.get('必选实体', []) kexuan = data.get('可选实体', []) if intent and (bixuan or kexuan): intent_bixuan_kexuan_dict.setdefault(intent, (bixuan, kexuan)) return intent_bixuan_kexuan_dict def intent_to_es(es_host=ES_HOST, es_port=ES_PORT, _index=ES_INDEX, _type='intent', es_user=ES_USER, es_password=ES_PASSWORD, data=None, pid='all_baoxian'): # 模板中存在的意图集合 templates_intent_bixuan_kexuan_dict = download_template_intent(es_host=es_host, es_port=es_port, _index='templates_question', es_user=es_user, es_password=es_password, pid=pid) es_index = "{}_{}".format(pid, _index) now = datetime.datetime.now() index_end = now.strftime('%Y%m%d_%H%M%S') current_es_index = "{}_{}".format(es_index, index_end).lower() alias_name = '{}_alias'.format(es_index) url = "http://{}:{}/{}/{}/_bulk".format(es_host, es_port, current_es_index, _type) all_data = '' # del_alias_name = {"delete": {"_index": alias_name}} # all_data += json.dumps(del_alias_name, ensure_ascii=False) + '\n' for template_id, (intent, entity_list) in enumerate(data.items()): # 若意图在模板库中存在,则以模板的意图为准 if templates_intent_bixuan_kexuan_dict.get(intent): bixuan, kexuan = templates_intent_bixuan_kexuan_dict.get(intent) else: bixuan, kexuan = entity_list doc = {"intent": intent, "必选实体": bixuan, "可选实体": kexuan, '模板id': template_id} create_data = {"create": {"_id": template_id}} all_data += json.dumps(create_data, ensure_ascii=False) + '\n' all_data += json.dumps(doc, ensure_ascii=False) + '\n' ret = requests.post(url=url, data=all_data.encode('utf8'), auth=(es_user, es_password)) # print(ret.json()) # 添加别名 data = { "actions": [ {"remove": { "alias": alias_name, "index": "_all" }}, {"add": { "alias": alias_name, "index": current_es_index }} ] } url = "http://{}:{}/_aliases".format(es_host, es_port) r = requests.post(url, json=data, auth=(es_user, es_password)) print(r.json()) def create_one(_id, intent, bixuan, kexuan, es_host=ES_HOST, es_port=ES_PORT, _index=ES_INDEX, _type='intent', pid='all_baoxian'): """ 向意图表中插入单条数据 :param _id: :param intent: :param bixuan: :param kexuan: :return: """ es_index = "{}_{}".format(pid, _index) alias_name = '{}_alias'.format(es_index) url = "http://{}:{}/{}/{}/{}".format(es_host, es_port, alias_name, _type, _id) template_id = _id doc = {"intent": intent, "必选实体": bixuan, "可选实体": kexuan, '模板id': template_id} r = requests.post(url, json=doc, auth=(ES_USER, ES_PASSWORD)) print(r.json()) def main(): # es_user = 'elastic' # es_password = '<PASSWORD>' # es_host = '192.168.3.145' # es_port = '9200' # _index = 'intent' # _type = 'intent' intent_to_es(es_host=ES_HOST, es_port=ES_PORT, _index=ES_INDEX, _type='intent', es_user=ES_USER, es_password=ES_PASSWORD, data=intent_entity_dict, pid='zhongdeanlian') # 插入单条: # _id = 144 # intent = '测试意图' # bixuan = ['Jibing'] # kexuan = [] # create_one(_id, intent, bixuan, kexuan, _index=ES_INDEX, _type='intent', pid='all_baoxian') if __name__ == '__main__': main() <file_sep>/model/dl_model/model_transformer/tt.py import math import numpy as np s=math.log(math.log(0.01)) print(s)<file_sep>/corpus_data/tfidf.py # coding:utf-8 __author__ = "liuxuejiang" import jieba import jieba.posseg as pseg import os import sys from sklearn import feature_extraction from sklearn.feature_extraction.text import TfidfTransformer from sklearn.feature_extraction.text import CountVectorizer from sklearn.externals import joblib class TFIDF: def __init__(self): pass def train(self,sents): corpus = ["我 来到 北京 清华大学", # 第一类文本切词后的结果,词之间以空格隔开 "他 来到 了 网易 杭研 大厦", # 第二类文本的切词结果 "小明 硕士 毕业 与 中国 科学院", # 第三类文本的切词结果 "我 爱 北京 天安门"] # 第四类文本的切词结果 corpus=sents vectorizer = CountVectorizer() # 该类会将文本中的词语转换为词频矩阵,矩阵元素a[i][j] 表示j词在i类文本下的词频 transformer = TfidfTransformer() # 该类会统计每个词语的tf-idf权值 tfidf = transformer.fit_transform( vectorizer.fit_transform(corpus)) # 第一个fit_transform是计算tf-idf,第二个fit_transform是将文本转为词频矩阵 word = vectorizer.get_feature_names() # 获取词袋模型中的所有词语 weight = tfidf.toarray() # 将tf-idf矩阵抽取出来,元素a[i][j]表示j词在i类文本中的tf-idf权重 joblib.dump(transformer,'./transformer.pkl') joblib.dump(vectorizer,'./vectorizer.pkl') for i in range(len(weight)): # 打印每类文本的tf-idf词语权重,第一个for遍历所有文本,第二个for便利某一类文本下的词语权重 for j in range(len(word)): print(word[j], weight[i][j]) def infer(self,sents): vectorizer=joblib.load('./vectorizer.pkl') transformer=joblib.load('./transformer.pkl') tfidf = transformer.fit_transform( vectorizer.fit_transform(sents)) # 第一个fit_transform是计算tf-idf,第二个fit_transform是将文本转为词频矩阵 word = vectorizer.get_feature_names() # 获取词袋模型中的所有词语 weight = tfidf.toarray() if __name__ == "__main__": sents=[] for ele in open('./dn.txt','r').readlines(): ele=ele.replace('\n','') sent=ele.split('\t\t')[1] sents.append(' '.join([e for e in jieba.cut(sent)])) <file_sep>/rm_model.sh #!/bash/bin rm -r save_model/model_lstm rm -r save_model/model_lstm_mask<file_sep>/model/dl_model/model_s_lstm/Config.py import os from IntentConfig import Config base_path=os.path.split(os.path.split(os.path.split(os.path.split(os.path.realpath(__file__))[0])[0])[0])[0] intent_config=Config() class Config_lstm(object): ''' 默认配置 ''' learning_rate = 0.001 batch_size = 128 label_max_len=16 sent_len = 30 # 句子长度 embedding_dim = 100 # 词向量维度 hidden_dim = 400 train_dir = './data/train_out_%s.txt' dev_dir = './data/dev_out.txt' test_dir = './data/test.txt' model_dir = base_path+'/save_model/model_lstm_mask/%s.ckpt'%intent_config.save_model_name print('config_lstm',model_dir) if not os.path.exists(base_path+'/save_model/model_lstm_mask'): os.makedirs(base_path+'/save_model/model_lstm_mask') use_cpu_num = 16 keep_dropout = 0.7 summary_write_dir = "./tmp/r_net.log" epoch = 90 use_auto_buckets=False lambda1 = 0.01 step=3 model_mode = 'bilstm_attention_crf' # 模型选择:bilstm bilstm_crf bilstm_attention bilstm_attention_crf,cnn_crf random_initialize=True<file_sep>/model/dl_model/model_lstm_mask/tet.py from model.dl_model.model_lstm_mask.data_preprocess import Intent_Slot_Data from model.dl_model.model_lstm_mask.lstm_mask import get_sent_mask import tensorflow as tf from entity_recognition.ner import entity_dict import os import numpy as np base_path=os.path.split(os.path.split(os.path.split(os.path.split(os.path.realpath(__file__))[0])[0])[0])[0] # saver=tf.train.import_meta_graph(base_path+'/save_model/model_lstm_mask/intent_lstm_dn.ckpt.meta') # config = tf.ConfigProto(allow_soft_placement=True) # with tf.Session(config=config) as sess: # # saver.restore(sess,base_path+'/save_model/model_lstm_mask/intent_lstm_dn.ckpt') # # graph = tf.get_default_graph() # for v in tf.all_variables(): # print(v) # # sent_enc = graph.get_operation_by_name('sent_enc') # for e in graph.get_operations(): # print(e) # # sent_word=graph.get_tensor_by_name('sent_word:0') # sent_len=graph.get_tensor_by_name('sent_len:0') # sent_mask=graph.get_tensor_by_name('sent_mask:0') # intent_y=graph.get_tensor_by_name('intent_y:0') # # sent_emb=graph.get_tensor_by_name('stack_sent_enc:0') # # sent_enc = graph.get_tensor_by_name('sent_enc:0') # dd = Intent_Slot_Data(train_path=base_path + "/corpus_data/train_out_char.txt", # test_path=base_path + "/corpus_data/dev_out_char.txt", # dev_path=base_path + "/corpus_data/dev_out_char.txt", batch_size=128, # max_length=30, flag="train", # use_auto_bucket=False) # # dev_sent, dev_slot, dev_intent, dev_rel_len = dd.get_dev() # word_vocab = dd.vocab # entity_id = [] # for k, v in word_vocab.items(): # if k in entity_dict.keys(): # entity_id.append(v) # dev_sent_mask = get_sent_mask(dev_sent, entity_id) # # sent_enc1 = sess.run(sent_emb, feed_dict={sent_word: dev_sent, # sent_len: dev_rel_len, # sent_mask: dev_sent_mask, # }) # # print(sent_enc1[0][0]) # class test_class(object): def __init__(self,pre_sess,intent_num,dd): # init=tf.constant(value=) self.pre_sess=pre_sess self.dd=dd graph = tf.get_default_graph() # sent_enc = graph.get_operation_by_name('sent_enc') self.sent_word = graph.get_tensor_by_name('sent_word:0') self.sent_len = graph.get_tensor_by_name('sent_len:0') self.sent_mask = graph.get_tensor_by_name('sent_mask:0') self.intent_y = graph.get_tensor_by_name('intent_y:0') self.sent_emb = graph.get_tensor_by_name('stack_sent_enc:0') sent_encs = graph.get_tensor_by_name('stack_sent_enc:0') self.soft_logit=graph.get_tensor_by_name('mask_soft_logit:0') # sent_enc=tf.unstack(sent_encs,30,1)[0] # # logit=tf.layers.dense(sent_enc,intent_num) # self.soft_logit=tf.nn.softmax(logit,1,name='sss') # self.loss=tf.losses.softmax_cross_entropy(self.intent_y,logit) # # self.opt=tf.train.AdamOptimizer(0.01,name='ss').minimize(self.loss) def intent_acc(self,pre, label, id2intent): ''' 获取intent准确率 :param pre: :param label: :return: ''' pre_ = np.argmax(pre, 1) label_ = np.argmax(label, 1) ss = [[int(k), v] for k, v in id2intent.items()] ss.sort(key=lambda x: x[0], reverse=False) s1 = [e[1] for e in ss] # print(classification_report(y_true=label_,y_pred=pre_,target_names=s1)) all_sum = len(label_) num = sum([1 for e, e1 in zip(pre_, label_) if e == e1]) return float(num) / float(all_sum) def train(self): config = tf.ConfigProto(allow_soft_placement=True) sess=tf.Session(config=config) # sess.run(tf.global_variables_initializer()) # self.pre_sess.run(tf.global_variables_initializer()) dev_sent, dev_slot, dev_intent, dev_rel_len =self.dd.get_dev() print(dev_sent[0]) word_vocab = dd.vocab entity_id = [] for k, v in word_vocab.items(): if k in entity_dict.keys(): entity_id.append(v) dev_sent_mask = get_sent_mask(dev_sent, entity_id) for _ in range(50): dev_soft_logit = sess.run([self.soft_logit], feed_dict={self.sent_word: dev_sent, self.sent_len: dev_rel_len, self.sent_mask: dev_sent_mask, self.intent_y:dev_intent }) # print(loss) acc=self.intent_acc(dev_soft_logit[0],dev_intent,self.dd.id2sent) print(acc) if __name__ == '__main__': dd = Intent_Slot_Data(train_path=base_path + "/corpus_data/train_out_char.txt", test_path=base_path + "/corpus_data/dev_out_char.txt", dev_path=base_path + "/corpus_data/dev_out_char.txt", batch_size=128, max_length=30, flag="train_new", use_auto_bucket=False) intent_num=len(dd.id2intent) saver = tf.train.import_meta_graph(base_path + '/save_model/model_lstm_mask/intent_lstm_dn.ckpt.meta') config = tf.ConfigProto(allow_soft_placement=True) pre_sess=tf.Session(config=config) saver.restore(pre_sess, base_path + '/save_model/model_lstm_mask/intent_lstm_dn.ckpt') tc=test_class(pre_sess,intent_num,dd) tc.train() <file_sep>/model/doc2vec/doc2vec.py from gensim.models import ldamodel from gensim import corpora, models from gensim.models import Doc2Vec from gensim.models.doc2vec import LabeledSentence import os import re base_path=os.path.split(os.path.split(os.path.split(os.path.realpath(__file__))[0])[0])[0] stop_word=[e.replace('\n','') for e in open(base_path+'/corpus_data/stop_word.txt')] tokens=[] sub_pattern='eos|bos' sents=[] labels=[] index=0 for ele in open(base_path+'/corpus_data/train_out_char.txt','r').readlines(): ele=ele.replace('\n','') sent=re.subn(sub_pattern,'',ele.split('\t')[0].lower())[0] label=ele.split('\t')[2] labels.append(label) sents.append(sent) s=LabeledSentence(words=[ e for e in sent.split(' ') if e not in stop_word],labels=['SENT_%s'%index]) index+=1 tokens.append(s) # tokens.append([ e for e in sent.split(' ') if e not in stop_word]) model = models.Doc2Vec(size=300, window=10, min_count=5, workers=11,alpha=0.025, min_alpha=0.025) model.build_vocab(tokens) # model=Doc2Vec(documents=tokens,dm=1,epochs=50,size=50) for epoch in range(10): model.train(tokens) model.alpha -= 0.002 # decrease the learning rate model.min_alpha = model.alpha # fix the learning rate, no deca model.train(tokens) model.save('./doc2vec.model') print(model.most_similar('今天天气很好'))<file_sep>/model/dl_model/model_center_loss/tt.py # pop_list=[1,2,3,4,5] # # push_list=[4,5,3,1,2] # length=len(pop_list[:]) # stack=[] # for i in range(2*length): # if i<=length: # stack.append(pop_list[i]) # # # if push_list.index(stack[-1])==0: # print(stack[-1]) # push_list=push_list[1:] # pop_list=pop_list[:-1] import numpy as np s=np.zeros(shape=(3,)) s1=np.ones(shape=(3,)) ss=np.sum(np.equal(s,s1)) print(ss)<file_sep>/model/dl_model/model_transformer/pipeline_lstm_mask.py import logging import sys,os sys.path.append('./') import pickle from model.dl_model.model_lstm_mask.data_preprocess import Intent_Slot_Data from IntentConfig import Config from model.dl_model.model_lstm_mask.lstm_mask import LstmMask,Config_lstm import tensorflow as tf base_path=os.path.split(os.path.split(os.path.split(os.path.split(os.path.realpath(__file__))[0])[0])[0])[0] os.environ["CUDA_VISIBLE_DEVICES"] = "2" logging.basicConfig(level=logging.INFO, format='%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s', datefmt='%a, %d %b %Y %H:%M:%S', filename='modellog.log', filemode='w') _logger = logging.getLogger("intent_bagging") class IntentDLB(object): def __init__(self,config): intent_config = config vocab = pickle.load(open(base_path + "/save_model/vocab_%s.p" % intent_config.save_model_name, 'rb')) # 词典 slot_vocab = pickle.load( open(base_path + "/save_model/slot_vocab_%s.p" % intent_config.save_model_name, 'rb')) # 词典 intent_vocab = pickle.load( open(base_path + "/save_model/intent_vocab_%s.p" % intent_config.save_model_name, 'rb')) # 词典 id2intent={} for k, v in intent_vocab.items(): id2intent[v] = k self.nn_model = LstmMask(scope=intent_config.save_model_name,mod='infer') self.nn_model.word_vocab=vocab self.nn_model.word_num=len(vocab) self.nn_model.id2intent=id2intent self.nn_model.intent_num=len(id2intent) self.nn_model.dd.vocab=vocab self.nn_model.dd.slot_vocab=slot_vocab self.nn_model.dd.intent_vocab=intent_vocab self.nn_model.__build_model__() config = tf.ConfigProto(device_count={"CPU": 8}, # limit to num_cpu_core CPU usage inter_op_parallelism_threads=8, intra_op_parallelism_threads=8, log_device_placement=False, allow_soft_placement=True, ) saver=tf.train.Saver() self.sess=tf.Session(config=config) saver.restore(self.sess,self.nn_model.save_model) def get_intent(self,sents): ''' :param sents: :return: ''' return self.nn_model.__infer__(sents,self.sess) if __name__ == '__main__': id=IntentDLB() s=id.get_intent(['感冒保不保']) print(s)<file_sep>/model/dl_model/model_semantic_match/match_aggre_lstm.py import tensorflow as tf import os import sys sys.path.append('./') from model.dl_model.model_semantic_match.data_preprocess import Intent_Slot_Data from model.dl_model.model_semantic_match.model_fun import embedding, sent_encoder, self_attention, loss_function, \ intent_acc, cosin_com, \ label_sent_attention, output_layers, sigmiod_layer, last_relevant_output, match_attention from model.dl_model.model_one_shot.focal_loss import focal_loss from IntentConfig import Config import numpy as np import logging from entity_recognition.ner import entity_dict import pickle from sklearn.metrics import classification_report, precision_recall_fscore_support, confusion_matrix import gc path = os.path.dirname(os.path.dirname(__file__)) sys.path.insert(0, path) from basic_model import BasicModel base_path = os.path.split(os.path.split(os.path.split(os.path.split(os.path.realpath(__file__))[0])[0])[0])[0] from entity_recognition.ner import EntityRecognition from xmlrpc.server import SimpleXMLRPCServer logging.basicConfig(level=logging.INFO, format='%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s', datefmt='%a, %d %b %Y %H:%M:%S', filename='modellog.log', filemode='w') _logger = logging.getLogger("intent_bagging") intent_config = Config() gpu_id = 0 os.environ["CUDA_VISIBLE_DEVICES"] = "%s" % gpu_id class Config_lstm(object): ''' 默认配置 ''' learning_rate = 0.001 batch_size = 128 label_max_len = 16 sent_len = 30 # 句子长度 embedding_dim = 100 # 词向量维度 hidden_dim = 400 train_dir = './data/train_out_%s.txt' dev_dir = './data/dev_out.txt' test_dir = './data/test.txt' model_dir = base_path + '/save_model/model_lstm_mask/%s.ckpt' % 12 print('config_lstm', model_dir) if not os.path.exists(base_path + '/save_model/model_lstm_mask'): os.makedirs(base_path + '/save_model/model_lstm_mask') use_cpu_num = 16 keep_dropout = 0.7 summary_write_dir = "./tmp/r_net.log" epoch = 90 use_auto_buckets = False lambda1 = 0.01 model_mode = 'bilstm_attention_crf' # 模型选择:bilstm bilstm_crf bilstm_attention bilstm_attention_crf,cnn_crf config = Config_lstm() tf.app.flags.DEFINE_float("mask_lambda1", config.lambda1, "l2学习率") tf.app.flags.DEFINE_float("mask_learning_rate", config.learning_rate, "学习率") tf.app.flags.DEFINE_float("mask_keep_dropout", config.keep_dropout, "dropout") tf.app.flags.DEFINE_integer("mask_batch_size", config.batch_size, "批处理的样本数量") tf.app.flags.DEFINE_integer("mask_max_len", config.sent_len, "句子长度") tf.app.flags.DEFINE_integer("mask_max_label_len", config.label_max_len, "句子长度") tf.app.flags.DEFINE_integer("mask_embedding_dim", config.embedding_dim, "词嵌入维度.") tf.app.flags.DEFINE_integer("mask_hidden_dim", config.hidden_dim, "中间节点维度.") tf.app.flags.DEFINE_integer("mask_use_cpu_num", config.use_cpu_num, "限定使用cpu的个数") tf.app.flags.DEFINE_integer("mask_epoch", config.epoch, "epoch次数") tf.app.flags.DEFINE_string("mask_summary_write_dir", config.summary_write_dir, "训练数据过程可视化文件保存地址") tf.app.flags.DEFINE_string("mask_train_dir", config.train_dir, "训练数据的路径") tf.app.flags.DEFINE_string("mask_dev_dir", config.dev_dir, "验证数据文件路径") tf.app.flags.DEFINE_string("mask_test_dir", config.test_dir, "测试数据文件路径") tf.app.flags.DEFINE_string("mask_model_dir", config.model_dir, "模型保存路径") tf.app.flags.DEFINE_boolean('mask_use Encoder2Decoder', False, '') tf.app.flags.DEFINE_string("mask_mod", "infer_dev", "默认为训练") # true for prediction tf.app.flags.DEFINE_string('mask_model_mode', config.model_mode, '模型类型') tf.app.flags.DEFINE_boolean('mask_use_auto_buckets', config.use_auto_buckets, '是否使用自动桶') tf.app.flags.DEFINE_string('mask_only_mode', 'intent', '执行哪种单一任务') FLAGS = tf.app.flags.FLAGS def get_sent_mask(sent_ids, entity_ids): sent_mask = np.zeros_like(sent_ids, dtype=np.float32) for i in range(sent_ids.shape[0]): for j in range(sent_ids.shape[1]): if sent_ids[i, j] > 0 and sent_ids[i, j] not in entity_ids: sent_mask[i, j] = 1.0 elif sent_ids[i, j] > 0 and sent_ids[i, j] in entity_ids: sent_mask[i, j] = 1.0 return sent_mask class LstmMask(BasicModel): def __init__(self, scope='lstm', mod='train'): self.scope = scope if mod == 'train': flag = 'train_new' else: flag = 'test' with tf.device('/gpu:%s' % gpu_id): self.dd = Intent_Slot_Data(train_path=base_path + "/corpus_data/%s" % intent_config.train_name, test_path=base_path + "/corpus_data/%s" % intent_config.dev_name, dev_path=base_path + "/corpus_data/%s" % intent_config.dev_name, batch_size=FLAGS.mask_batch_size, max_length=FLAGS.mask_max_len, flag=flag, use_auto_bucket=FLAGS.mask_use_auto_buckets) self.word_vocab = self.dd.vocab self.word_num = self.dd.vocab_num self.id2intent = self.dd.id2intent self.intent_num = len(self.id2intent) self.entity_id = [] for k, v in self.word_vocab.items(): if k in entity_dict.keys(): self.entity_id.append(v) def _decay(self): costs = [] # 遍历所有可训练变量 for var in tf.trainable_variables(): # 只计算标有“DW”的变量 costs.append(tf.nn.l2_loss(var)) # 加和,并乘以衰减因子 return tf.multiply(0.0001, tf.add_n(costs)) def loss_fun(self, pos_0, pos_1, neg_0, m): distance_pos_0_1 = tf.sqrt(tf.reduce_sum(tf.square(pos_0 - pos_1), 2)) distance_pos_0_neg_0 = tf.sqrt(tf.reduce_sum(tf.square(pos_0 - neg_0), 2)) distance_pos_1_neg_0 = tf.sqrt(tf.reduce_sum(tf.square(pos_1 - neg_0), 2)) distance_1 = tf.nn.relu(m + distance_pos_0_1 - distance_pos_0_neg_0) distance_2 = tf.nn.relu(m + distance_pos_0_1 - distance_pos_1_neg_0) loss = distance_1 + distance_2 tf.reduce_mean(loss) return loss def __build_model__(self, ): with tf.variable_scope(name_or_scope=self.scope): with tf.device('/device:GPU:%s' % gpu_id): self.mod = 1 self.pos_0 = tf.placeholder(shape=(None, FLAGS.mask_max_len), dtype=tf.int32, name='pos_0') self.pos_1 = tf.placeholder(shape=(None, FLAGS.mask_max_len), dtype=tf.int32, name='pos_1') self.pos_0_len = tf.placeholder(shape=(None,), dtype=tf.int32, name='pos_0_len') self.pos_1_len = tf.placeholder(shape=(None,), dtype=tf.int32, name='pos_1_len') self.dropout = tf.placeholder(dtype=tf.float32) self.neg_0 = tf.placeholder(shape=(None, FLAGS.mask_max_len), dtype=tf.int32, name='neg_0') self.neg_0_len = tf.placeholder(shape=(None,), dtype=tf.int32, name='neg_0_len') self.pos_0_mask = tf.placeholder(shape=(None, FLAGS.mask_max_len), dtype=tf.float32, name='pos_0_mask') self.pos_1_mask = tf.placeholder(shape=(None, FLAGS.mask_max_len), dtype=tf.float32, name='pos_1_mask') self.neg_0_mask = tf.placeholder(shape=(None, FLAGS.mask_max_len), dtype=tf.float32, name='neg_0_mask') pos_0_emb, emb_0 = embedding(self.pos_0, self.word_num, FLAGS.mask_embedding_dim, 'sent_emb', reuse=False) pos_1_emb, emb_1 = embedding(self.pos_1, self.word_num, FLAGS.mask_embedding_dim, 'sent_emb', reuse=True) neg_0_emb, _ = embedding(self.neg_0, self.word_num, FLAGS.mask_embedding_dim, 'sent_emb', reuse=True) self.pos_0_emb = emb_0 self.pos_1_emb = emb_1 pos_0_emb = tf.nn.dropout(pos_0_emb, self.dropout) pos_1_emb = tf.nn.dropout(pos_1_emb, self.dropout) neg_0_emb = tf.nn.dropout(neg_0_emb, self.dropout) pos_0_enc = sent_encoder(sent_word_emb=pos_0_emb, hidden_dim=FLAGS.mask_hidden_dim, num=FLAGS.mask_max_len, sequence_length=self.pos_0_len, name='pos_0_enc', dropout=self.dropout, reuse=False) pos_1_enc = sent_encoder(sent_word_emb=pos_1_emb, hidden_dim=FLAGS.mask_hidden_dim, num=FLAGS.mask_max_len, sequence_length=self.pos_1_len, name='pos_0_enc', dropout=self.dropout, reuse=True) neg_0_enc = sent_encoder(sent_word_emb=neg_0_emb, hidden_dim=FLAGS.mask_hidden_dim, num=FLAGS.mask_max_len, sequence_length=self.neg_0_len, name='pos_0_enc', dropout=self.dropout, reuse=True) # pos_0_enc_new=match_attention(pos_0_enc,pos_1_enc,self.pos_0_mask,self.pos_1_mask,FLAGS.mask_hidden_dim,self.dropout,name='match_attention',seq_len=FLAGS.mask_max_len,reuse=False) # pos_0_enc_new_1=match_attention(pos_0_enc,pos_1_enc,self.pos_0_mask,self.pos_1_mask,FLAGS.mask_hidden_dim,self.dropout,name='match_attention',seq_len=FLAGS.mask_max_len,reuse=True) # self.pos_0_enc_new=pos_0_enc_new # self.pos_0_enc_new1 = pos_0_enc_new_1 # pos_1_enc_new=match_attention(pos_1_enc,pos_0_enc,self.pos_1_mask,self.pos_0_mask,FLAGS.mask_hidden_dim,self.dropout,name='match_attention',seq_len=FLAGS.mask_max_len,reuse=True) # neg_0_enc_new=match_attention(neg_0_enc,pos_0_enc,self.neg_0_mask,self.pos_0_mask,FLAGS.mask_hidden_dim,self.dropout,name='match_attention',seq_len=FLAGS.mask_max_len,reuse=True) # pos_0_self_attention=self_attention(pos_0_enc,self.pos_0_mask,reuse=False) # pos_1_self_attention=self_attention(pos_1_enc,self.pos_1_mask,reuse=True) # neg_0_self_attention=self_attention(neg_0_enc,self.pos_0_mask,reuse=True) pos_0_enc_new = pos_0_enc pos_1_enc_new = pos_1_enc neg_0_enc_new = neg_0_enc pos_0_last_enc = last_relevant_output(pos_0_enc_new, self.pos_0_len) pos_1_last_enc = last_relevant_output(pos_1_enc_new, self.pos_1_len) neg_0_last_enc = last_relevant_output(neg_0_enc_new, self.neg_0_len) # pos_0_1_enc=tf.concat([pos_0_last_enc,pos_1_self_attention],-1) # pos_neg_0_0_enc=tf.concat([pos_0_last_enc,neg_0_self_attention],-1) # # pos_1_0_enc=tf.concat([pos_1_last_enc,pos_0_self_attention],-1) # neg_pos_0_0_enc=tf.concat([neg_0_last_enc,pos_0_self_attention],-1) # pos_0_enc=sigmiod_layer(pos_0_enc,FLAGS.mask_hidden_dim,'sigmiod_layer_pos_0_enc',reuse=False) # pos_1_enc=sigmiod_layer(pos_1_enc,FLAGS.mask_hidden_dim,'sigmiod_layer_pos_1_enc',reuse=tr) # neg_0_enc=sigmiod_layer(neg_0_enc,FLAGS.mask_hidden_dim,'sigmiod_layer_neg_0_enc',reuse=False) pos_0_enc = tf.nn.dropout(pos_0_last_enc, self.dropout) pos_1_enc = tf.nn.dropout(pos_1_last_enc, self.dropout) neg_0_enc = tf.nn.dropout(neg_0_last_enc, self.dropout) if self.mod == 0: self.pos_0_encoder = pos_0_enc self.pos_1_encoder = pos_1_enc distance_pos_0_1 = tf.sqrt(tf.reduce_sum(tf.square(pos_0_enc - pos_1_enc), 1)) distance_pos_0_neg_0 = tf.sqrt(tf.reduce_sum(tf.square(pos_0_enc - neg_0_enc), 1)) distance_pos_1_neg_0 = tf.sqrt(tf.reduce_sum(tf.square(pos_1_enc - neg_0_enc), 1)) # distance_pos_0_1=tf.clip_by_value(distance_pos_0_1,1e-5,3.0) # distance_pos_1_neg_0=tf.clip_by_value(distance_pos_1_neg_0,1e-5,3.0) # distance_pos_0_neg_0=tf.clip_by_value(distance_pos_0_neg_0,1e-5,3.0) distance_1 = tf.nn.relu(50.0 + distance_pos_0_1 - distance_pos_0_neg_0) distance_2 = tf.nn.relu(50.0 + distance_pos_0_1 - distance_pos_1_neg_0) loss = distance_1 + distance_2 self.loss = tf.reduce_mean(loss) self.dis1_0 = tf.reduce_mean(distance_pos_0_1) self.dis1_1 = tf.reduce_mean(distance_pos_0_neg_0) self.dis1_2 = tf.reduce_mean(distance_pos_1_neg_0) self.dis1 = tf.reduce_mean(distance_1) self.dis2 = tf.reduce_mean(distance_2) # self.loss=self.loss_fun(pos_0_enc,pos_1_enc,neg_0_enc,2) # self.opt=tf.train.AdamOptimizer(FLAGS.mask_learning_rate).minimize(self.loss) # self.optimizer = tf.train.AdamOptimizer(learning_rate=FLAGS.mask_learning_rate) grads_vars = self.optimizer.compute_gradients(self.loss) capped_grads_vars = [[tf.clip_by_value(g, -1e-3, 1.0), v] for g, v in grads_vars] self.opt = self.optimizer.apply_gradients(capped_grads_vars) elif self.mod == 1: self.output_features_postive = tf.concat([pos_0_enc, pos_1_enc, pos_0_enc - pos_1_enc, pos_0_enc * pos_1_enc], axis=-1) self.output_features_negative = tf.concat([pos_0_enc, neg_0_enc, pos_0_enc - neg_0_enc, pos_0_enc * neg_0_enc], axis=-1) self.estimation_postive = tf.layers.dense( self.output_features_postive, units=2, name="prediction_layer", reuse=False) self.estimation_negative = tf.layers.dense( self.output_features_negative, units=2, name="prediction_layer", reuse=True) self.soft_pos = tf.nn.softmax(self.estimation_postive, 1) y = tf.zeros_like(self.pos_0_len) pos_y = tf.one_hot(y, 2, 1, 0, 1) neg_y = tf.one_hot(y, 2, 0, 1, 1) self.pred = tf.argmax(self.soft_pos, 1) self.pos_y = tf.argmax(pos_y, 1) self.neg_y = tf.argmax(neg_y, 1) self.acc = tf.cast(tf.reduce_sum(tf.cast(tf.equal(self.pred, self.pos_y), tf.int32)), tf.float32) \ / tf.cast(tf.reduce_sum(tf.ones_like(self.pos_0_len)), tf.float32) pos_loss = tf.losses.softmax_cross_entropy(pos_y, self.estimation_postive) neg_loss = tf.losses.softmax_cross_entropy(neg_y, self.estimation_negative) self.loss = tf.reduce_mean(pos_loss + neg_loss) self.optimizer = tf.train.AdamOptimizer(learning_rate=FLAGS.mask_learning_rate) grads_vars = self.optimizer.compute_gradients(self.loss) capped_grads_vars = [[tf.clip_by_value(g, -1e-3, 1.0), v] for g, v in grads_vars] self.opt = self.optimizer.apply_gradients(capped_grads_vars) def __deal_data(self,data): pos_0_array, pos_0_len, pos_1_array, pos_1_len, neg_0_array, neg_0_len = [], [], [], [], [], [] for ele in data: pos_0_array.append(ele['pos_0']['word_arr']) pos_0_len.append(ele['pos_0']['real_len_arr']) pos_1_array.append(ele['pos_1']['word_arr']) pos_1_len.append(ele['pos_1']['real_len_arr']) neg_0_array.append(ele['neg_0']['word_arr']) neg_0_len.append(ele['neg_0']['real_len_arr']) pos_0_array = np.array(pos_0_array) pos_1_array = np.array(pos_1_array) pos_0_len = np.array(pos_0_len) pos_1_len = np.array(pos_1_len) neg_0_array = np.array(neg_0_array) neg_0_len = np.array(neg_0_len) train_pos_0_mask = get_sent_mask(pos_0_array, self.entity_id) train_pos_1_mask = get_sent_mask(pos_1_array, self.entity_id) train_neg_0_mask = get_sent_mask(neg_0_array, self.entity_id) return pos_0_array,pos_1_array,pos_0_len,pos_1_len,neg_0_array,neg_0_len,train_pos_0_mask,train_pos_1_mask,train_neg_0_mask def compute_acc(self,sess,sent_arr,sent_len,sent_intent,data_dict,n): ''' :param sent_arr: :param sent_len: :param intent: :param data_dict: {k:list} k为意图类别 list为该类别下样本 :param n:选择每个样本下n个样本作为标准句 :return: ''' pass def get_norm_array(self,data_dict,n=-1): ''' 获取标准句的矩阵 :param data_dict: :param n: :return: ''' pos_1_array,pos_1_len,pos_1_label=[],[],[] for k,v in data_dict.items(): for ele in v[:n]: pos_1_array.append(ele['word_arr']) pos_1_len.append(ele['real_len_arr']) pos_1_label.append(k) pos_1_array=np.array(pos_1_array) pos_1_len=np.array(pos_1_len) pos_1_label=np.array(pos_1_label) pos_1_mask=get_sent_mask(pos_1_array,self.entity_id) return pos_1_array,pos_1_len,pos_1_mask,pos_1_label def __train__(self): config = tf.ConfigProto(allow_soft_placement=True) _logger.info("load data") # _logger.info('entity_words:%s'%(entity_dict.keyjr s())) with tf.Session(config=config) as sess: init_train_acc = 0.0 init_dev_acc = 0.0 init_train_loss = 9999.99 init_dev_loss = 9999.99 saver = tf.train.Saver() # if os.path.exists('./model.ckpt.meta' ): # saver.restore(sess, './model.ckpt') # else: # sess.run(tf.global_variables_initializer()) sess.run(tf.global_variables_initializer()) train_data = self.dd.train_data dev_data = self.dd.get_dev_data() pos_0_array, pos_1_array, pos_0_len, pos_1_len, neg_0_array, neg_0_len, train_pos_0_mask, train_pos_1_mask, train_neg_0_mask=self.__deal_data(train_data) dev_pos_0_array, dev_pos_1_array, dev_pos_0_len, dev_pos_1_len, dev_neg_0_array, dev_neg_0_len,dev_pos_0_mask, dev_pos_1_mask, dev_neg_0_mask=self.__deal_data(dev_data) # word_arr, real_len_arr, intent_arr=self.dd.get_dev_data_new() num_batch = int(pos_0_array.shape[0] / FLAGS.mask_batch_size) for _ in range(50): all_train_loss, all_train_acc = 0.0, 0.0 for i in range(num_batch): pos_0_array_batch = pos_0_array[i * FLAGS.mask_batch_size:(i + 1) * FLAGS.mask_batch_size] pos_0_len_batch = pos_0_len[i * FLAGS.mask_batch_size:(i + 1) * FLAGS.mask_batch_size] pos_1_array_batch = pos_1_array[i * FLAGS.mask_batch_size:(i + 1) * FLAGS.mask_batch_size] pos_1_len_batch = pos_1_len[i * FLAGS.mask_batch_size:(i + 1) * FLAGS.mask_batch_size] neg_0_array_batch = neg_0_array[i * FLAGS.mask_batch_size:(i + 1) * FLAGS.mask_batch_size] neg_0_len_batch = neg_0_len[i * FLAGS.mask_batch_size:(i + 1) * FLAGS.mask_batch_size] pos_0_mask_batch = train_pos_0_mask[i * FLAGS.mask_batch_size:(i + 1) * FLAGS.mask_batch_size] pos_1_mask_batch = train_pos_1_mask[i * FLAGS.mask_batch_size:(i + 1) * FLAGS.mask_batch_size] neg_0_mask_batch = train_neg_0_mask[i * FLAGS.mask_batch_size:(i + 1) * FLAGS.mask_batch_size] losses, _, train_acc = sess.run( [self.loss, self.opt, self.acc], feed_dict={ self.pos_0: pos_0_array_batch, self.pos_0_len: pos_0_len_batch, self.pos_1: pos_1_array_batch, self.pos_1_len: pos_1_len_batch, self.neg_0: neg_0_array_batch, self.neg_0_len: neg_0_len_batch, self.pos_0_mask: pos_0_mask_batch, self.pos_1_mask: pos_1_mask_batch, self.neg_0_mask: neg_0_mask_batch, self.dropout: 1.0 }) all_train_loss += losses all_train_acc += train_acc all_train_loss = all_train_loss / float(num_batch) all_train_acc = all_train_acc / float(num_batch) dev_losses, dev_acc = sess.run( [self.loss, self.acc], feed_dict={ self.pos_0: dev_pos_0_array, self.pos_0_len: dev_pos_0_len, self.pos_1: dev_pos_1_array, self.pos_1_len: dev_pos_1_len, self.neg_0: dev_neg_0_array, self.neg_0_len: dev_neg_0_len, self.pos_0_mask: dev_pos_0_mask, self.pos_1_mask: dev_pos_1_mask, self.neg_0_mask: dev_neg_0_mask, self.dropout: 1.0 }) _logger.info('train_loss:%s train_acc:%s dev_loss:%s dec_acc:%s' % ( all_train_loss, all_train_acc, dev_losses, dev_acc)) if dev_losses < init_dev_loss: init_dev_loss = dev_losses saver.save(sess, './model.ckpt') print('save........') def __infer__(self): config = tf.ConfigProto( # limit to num_cpu_core CPU usage inter_op_parallelism_threads=8, intra_op_parallelism_threads=8, log_device_placement=False, allow_soft_placement=True, ) id2intent = self.dd.id2intent id2sent = self.dd.id2sent train_data_dict = self.dd.get_train_data_dict() standard_sample = {} for k, v in train_data_dict.items(): np.random.shuffle(v) standard_sample[k] = v[:3] saver = tf.train.Saver() with tf.Session(config=config) as sess: saver.restore(sess, './model.ckpt') while True: sent=input('输入:') sent_arr, sent_vec = self.dd.get_sent_char([sent]) sent_mask = get_sent_mask(sent_arr, self.entity_id) opt_k=0 for stand_k, v_ in standard_sample.items(): stand_es = standard_sample[stand_k] alls_index = [] for stand_e in stand_es: stand_word_arr = stand_e['word_arr'] stand_rel_arr = stand_e['real_len_arr'] stand_word_arr = stand_word_arr.reshape((1, 30)) stand_rel_arr = stand_rel_arr.reshape((1,)) stand_mask = get_sent_mask(stand_word_arr, self.entity_id) pred, pos_y_, neg_y_ = sess.run( [self.pred, self.pos_y, self.neg_y], feed_dict={ self.pos_0: sent_arr, self.pos_0_len: sent_vec, self.pos_1: stand_word_arr, self.pos_1_len: stand_rel_arr, self.neg_0: stand_word_arr, self.neg_0_len: stand_rel_arr, self.pos_0_mask: sent_mask, self.pos_1_mask: stand_mask, self.neg_0_mask: stand_mask, self.dropout: 1.0}) soft_max = pred alls_index.append(soft_max) if alls_index.count(0) >= 2: opt_k = id2intent[stand_k] break print(''.join([id2sent[e] for e in sent_arr[0] if e not in [0]]), '\t\t', opt_k,) def infer_dev(self): config = tf.ConfigProto( # limit to num_cpu_core CPU usage inter_op_parallelism_threads=8, intra_op_parallelism_threads=8, log_device_placement=False, allow_soft_placement=True, ) id2intent = self.dd.id2intent id2sent = self.dd.id2sent saver = tf.train.Saver() with tf.Session(config=config) as sess: saver.restore(sess, './model.ckpt') dev_data_dict = self.dd.get_dev_data_dict() train_data_dict = self.dd.get_train_data_dict() dev_data_dict = train_data_dict standard_sample = {} for k, v in train_data_dict.items(): np.random.shuffle(v) standard_sample[k] = v[:3] all_num = 0 num = 0 for k, v in dev_data_dict.items(): for dev_e in v: dev_word_arr = dev_e['word_arr'] dev_rel_arr = dev_e['real_len_arr'] dev_word_arr = dev_word_arr.reshape((1, 30)) dev_rel_arr = dev_rel_arr.reshape((1,)) dev_mask = get_sent_mask(dev_word_arr, self.entity_id) min_dis = 100 opt_k = None for stand_k, v_ in standard_sample.items(): stand_es = standard_sample[stand_k] alls_index = [] for stand_e in stand_es: stand_word_arr = stand_e['word_arr'] stand_rel_arr = stand_e['real_len_arr'] stand_word_arr = stand_word_arr.reshape((1, 30)) stand_rel_arr = stand_rel_arr.reshape((1,)) stand_mask = get_sent_mask(stand_word_arr, self.entity_id) pred, pos_y_, neg_y_ = sess.run( [self.pred, self.pos_y, self.neg_y], feed_dict={ self.pos_0: dev_word_arr, self.pos_0_len: dev_rel_arr, self.pos_1: stand_word_arr, self.pos_1_len: stand_rel_arr, self.neg_0: stand_word_arr, self.neg_0_len: stand_rel_arr, self.pos_0_mask: dev_mask, self.pos_1_mask: stand_mask, self.neg_0_mask: stand_mask, self.dropout: 1.0}) soft_max = pred alls_index.append(soft_max) if alls_index.count(0) >= 2: opt_k = id2intent[stand_k] break print(''.join([id2sent[e] for e in dev_word_arr[0] if e not in [0]]), '\t\t', opt_k, '\t\t', id2intent[k]) if opt_k == id2intent[k]: num += 1 all_num += 1 print(float(num) / float(all_num)) def __server__(self): config = tf.ConfigProto(device_count={"CPU": FLAGS.mask_use_cpu_num}, # limit to num_cpu_core CPU usage inter_op_parallelism_threads=8, intra_op_parallelism_threads=8, log_device_placement=False, allow_soft_placement=True, ) _logger.info("load data") with tf.Session(config=config) as sess: saver = tf.train.Saver() sess = tf.Session(config=config) if os.path.exists('%s.meta' % FLAGS.mask_model_dir): saver.restore(sess, '%s' % FLAGS.mask_model_dir) else: _logger.error('lstm没有模型') def intent(sent_list): sents = [] _logger.info("%s" % len(sent_list)) sents = [] for sent in sent_list: sents.append(self.dd.get_sent_char(sent)) sent_arr, sent_vec = self.dd.get_sent_char(sents) infer_sent_mask = get_sent_mask(sent_arr, self.entity_id) intent_logit = sess.run(self.soft_logit, feed_dict={self.sent_word: sent_arr, self.sent_len: sent_vec, self.sent_mask: infer_sent_mask}) res = [] for ele in intent_logit: ss = [[self.id2intent[index], str(e)] for index, e in enumerate(ele) if e >= 0.3] if not ss: ss = [[self.id2intent[np.argmax(ele)], str(np.max(ele))]] res.append(ss) del sents gc.collect() _logger.info('process end') _logger.info('%s' % res) return res svr = SimpleXMLRPCServer((config_lstm.host, 8087), allow_none=True) svr.register_function(intent) svr.serve_forever() def matirx(self, pre_label, label, id2intent, id2sent, sent, indexs, type): pre_label_prob = np.max(pre_label, 1) pre_label = np.argmax(pre_label, 1) label = np.argmax(label, 1) pre_label = pre_label.flatten() label = label.flatten() ss = [[int(k), v] for k, v in id2intent.items()] ss.sort(key=lambda x: x[0], reverse=False) labels = [e[0] for e in ss] traget_name = [e[1] for e in ss] class_re = classification_report(label, pre_label, target_names=traget_name, labels=labels) print(class_re) # con_mat=confusion_matrix(y_true=label,y_pred=pre_label,labels=labels) sents = [] for ele in sent: s = ' '.join([id2sent[e] for e in ele if e != 0]) sents.append(s) confus_dict = {} for ele in traget_name: confus_dict[ele] = {} for e in traget_name: confus_dict[ele][e] = [0, []] for true, pred, sent, prob, ii in zip(label, pre_label, sents, pre_label_prob, indexs): true_name = id2intent[true] pred_name = id2intent[pred] data_list = confus_dict[true_name][pred_name] data_list[0] += 1 data_list[1].append((ii, prob, sent)) confus_dict[true_name][pred_name] = data_list # print(confus_dict) if type == 'train': pickle.dump(confus_dict, open('./train.p', 'wb')) elif type == 'dev': pickle.dump(confus_dict, open('./dev.p', 'wb')) def main(_): lm = LstmMask() lm.__build_model__() if FLAGS.mask_mod == 'train': lm.__train__() elif FLAGS.mask_mod == 'infer_dev': lm.infer_dev() elif FLAGS.mask_mod == 'server': lm.__server__() elif FLAGS.mask_mod == 'infer_': lm.__infer__() if __name__ == '__main__': tf.app.run()<file_sep>/corpus_data/data_read.py # import csv # # # # data=csv.reader(open('./保单查询标注意图(1).csv','r').readlines()) # # # # for ele in data: # # print(ele[0],'\t\t',ele[1]) # # import json # # for line in open('./待扩展模板同义句_6.12.txt').readlines(): # # line=line.replace('\n','') # # for e in line.split('\t'): # # print(e) # # fr=(line for line in open('./意图识别数据_all.txt','r').readlines()) # for e in fr: # e=e.replace(' ','').replace('\t\t\t\t','\t\t').replace('\n','') # print(e) # import re # sub_pattern='\\?' # fw=open('./tt.txt','w') # for ele in open('sentence.txt','r').readlines(): # ele=ele.replace('\n','') # sent=ele.split('|')[1] # label=ele.split('|')[0] # fw.write(sent) # fw.write('\t\t') # fw.write(label) # fw.write('\n') # for ele in open('./tt.txt','r').readlines(): # for e in ele.split(' '): # print(e) # # import csv # dd_dict={} # # for ele in open('./FAQ(2).txt','r').readlines(): # ele=ele.replace('\n','').replace('\t\t','\t') # try: # sent=ele.split('\t')[0] # label=ele.split('\t')[1] # except: # print(ele) # if sent not in dd_dict: # dd_dict[sent]=label # # for ele in open('./意图识别数据_all.txt', 'r').readlines(): # ele = ele.replace('\n', '').replace('\t\t', '\t') # try: # sent = ele.split('\t')[0] # label = ele.split('\t')[1] # except: # print(ele) # if sent not in dd_dict: # dd_dict[sent] = label # # fw=open('./tt.txt','w') # # for k,v in dd_dict.items(): # fw.write(k) # fw.write('\t\t') # fw.write(v) # fw.write('\n') # import xlrd # # work_sheet=xlrd.open_workbook('./dn_data_1.xlsx') # label_list=['1宏观预测','2产品诊断','3政策规范','4知识方法','5理财规划','6事实分析'] # # fw=open('./ww.txt','w') # # for ele in label_list: # sheet=work_sheet.sheet_by_name(ele) # # for i in range(sheet.nrows): # fw.write(sheet.cell_value(i,0)) # fw.write('\t\t') # fw.write(ele) # fw.write('\n') # import xlrd # # fw=open('FAQ.txt','w') # work_sheet=xlrd.open_workbook('./意图标注数据_第二批_20180711.xlsx') # # sheet=work_sheet.sheet_by_index(0) # # index=4963 # for i in range(sheet.nrows): # sent=sheet.cell_value(i,0) # label=sheet.cell_value(i,2) # sent=sent.replace('\n','') # print(sent,label) # if int(label)==1: # fw.write(str(index)) # fw.write('\t\t') # fw.write(sent) # fw.write('\t\t') # fw.write('1宏观预测') # fw.write('\n') # index+=1 # if int(label)==2: # fw.write(str(index)) # fw.write('\t\t') # fw.write(sent) # fw.write('\t\t') # fw.write('2产品诊断') # fw.write('\n') # index += 1 # if int(label)==3: # fw.write(str(index)) # fw.write('\t\t') # fw.write(sent) # fw.write('\t\t') # fw.write('3政策规范') # fw.write('\n') # index += 1 # if int(label)==4: # fw.write(str(index)) # fw.write('\t\t') # fw.write(sent) # fw.write('\t\t') # fw.write('4知识方法') # fw.write('\n') # index += 1 # if int(label)==5: # fw.write(str(index)) # fw.write('\t\t') # fw.write(sent) # fw.write('\t\t') # fw.write('5理财规划') # fw.write('\n') # index += 1 # if int(label)==6: # fw.write(str(index)) # fw.write('\t\t') # fw.write(sent) # fw.write('\t\t') # fw.write('6时事分析') # fw.write('\n') # index += 1 # import xlrd # fw=open('ww.txt','w') # work_sheet=xlrd.open_workbook('./20180710.xlsx') # # index=0 # for i in range(6): # sheet=work_sheet.sheet_by_index(i) # for j in range(sheet.nrows): # sent=sheet.cell_value(j,0).replace('\n','') # if sent: # fw.write(str(index)) # fw.write('\t\t') # fw.write(sent) # fw.write('\t\t') # fw.write(sheet.name) # fw.write('\n') # index+=1 # # import xlrd # # work_sheet = xlrd.open_workbook('./20180710.xlsx') # # sheet=work_sheet.sheet_by_index(0) # # index=4705 # for i in range(sheet.nrows): # sent=sheet.cell_value(i,0) # id=sheet.cell_value(i,2) # if sent: # if id==1: # print(index,'\t\t',sent.replace('\n',''),'\t\t','1宏观预测') # elif id==2: # print(index,'\t\t',sent.replace('\n',''),'\t\t','2产品诊断') # elif id==3: # print(index,'\t\t',sent.replace('\n',''),'\t\t','3政策规范') # elif id==4: # print(index,'\t\t',sent.replace('\n',''),'\t\t','4知识方法') # elif id==5: # print(index,'\t\t',sent.replace('\n',''),'\t\t','5理财规划') # index+=1 # from jieba import analyse # # tfidf=analyse.extract_tags # # s='黄怎样才算财富自由?我们普通人怎样才做到呢?谢谢' # # keys=tfidf(s) # # for k in keys: # print(k) # index=8909 # for ele in open('./ww.txt','r').readlines(): # ele=ele.replace('\n','') # print(index,'\t\t',ele,'\t\t','6时事分析') # # index+=1 # import xlrd # import os # tab=['1宏观预测','2产品诊断','5理财规划'] # # work_sheet=xlrd.open_workbook('./20180710.xlsx') # for ele in tab: # fw=open(ele+'.txt','w') # sheet=work_sheet.sheet_by_name(ele) # # for i in range(sheet.nrows): # sent=sheet.cell_value(i,0).replace('\n','') # label=sheet.cell_value(i,1) # fw.write(str(i)) # fw.write('\t\t') # fw.write(sent) # fw.write('\t\t') # fw.write(label) # fw.write('\n') import xlrd work_sheet=xlrd.open_workbook('./数据标注文档.xlsx') table=work_sheet.sheet_by_name('Corpus') index=0 for i in range(table.nrows): label=table.cell_value(i,0) sent=table.cell_value(i,1) if label=='其他': label='other' print(index,'\t\t',sent,'\t\t',label) index+=1<file_sep>/model/dl_model/model_resnet/ResNet.py import tensorflow as tf import os import sys sys.path.append('./') from model.dl_model.model_lstm_res.data_preprocess import Intent_Slot_Data from model.dl_model.model_lstm_mask.model_fun import embedding,sent_encoder,self_attention,loss_function,intent_acc,cosin_com,label_sent_attention,output_layers from model.dl_model.model_lstm_mask.focal_loss import focal_loss from IntentConfig import Config import numpy as np import logging import pickle from sklearn.metrics import classification_report,precision_recall_fscore_support,confusion_matrix import gc path=os.path.dirname(os.path.dirname(__file__)) sys.path.insert(0,path) import collections slim=tf.contrib.slim base_path=os.path.split(os.path.split(os.path.split(os.path.split(os.path.realpath(__file__))[0])[0])[0])[0] from tensorflow.python.training import moving_averages from entity_recognition.ner import EntityRecognition from xmlrpc.server import SimpleXMLRPCServer logging.basicConfig(level=logging.INFO, format='%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s', datefmt='%a, %d %b %Y %H:%M:%S', filename='modellog.log', filemode='w') _logger = logging.getLogger("intent_bagging") intent_config=Config() gpu_id=3 os.environ["CUDA_VISIBLE_DEVICES"] = "%s"%gpu_id class Block(collections.namedtuple('Block',['scope','unit_fn','args'])): pass class Config_lstm(object): ''' 默认配置 ''' learning_rate = 0.001 batch_size = 128 label_max_len=16 sent_len = 30 # 句子长度 embedding_dim = 100 # 词向量维度 hidden_dim = 400 train_dir = './data/train_out_%s.txt' dev_dir = './data/dev_out.txt' test_dir = './data/test.txt' model_dir = base_path+'/save_model/model_lstm_mask/intent_lstm_%s.ckpt'%intent_config.save_model_name if not os.path.exists(base_path+'/save_model/model_lstm_mask'): os.makedirs(base_path+'/save_model/model_lstm_mask') use_cpu_num = 16 keep_dropout = 0.7 summary_write_dir = "./tmp/r_net.log" epoch = 100 use_auto_buckets=False lambda1 = 0.01 model_mode = 'bilstm_attention_crf' # 模型选择:bilstm bilstm_crf bilstm_attention bilstm_attention_crf,cnn_crf config = Config_lstm() tf.app.flags.DEFINE_float("mask_lambda1", config.lambda1, "l2学习率") tf.app.flags.DEFINE_float("mask_learning_rate", config.learning_rate, "学习率") tf.app.flags.DEFINE_float("mask_keep_dropout", config.keep_dropout, "dropout") tf.app.flags.DEFINE_integer("mask_batch_size", config.batch_size, "批处理的样本数量") tf.app.flags.DEFINE_integer("mask_max_len", config.sent_len, "句子长度") tf.app.flags.DEFINE_integer("mask_max_label_len", config.label_max_len, "句子长度") tf.app.flags.DEFINE_integer("mask_embedding_dim", config.embedding_dim, "词嵌入维度.") tf.app.flags.DEFINE_integer("mask_hidden_dim", config.hidden_dim, "中间节点维度.") tf.app.flags.DEFINE_integer("mask_use_cpu_num", config.use_cpu_num, "限定使用cpu的个数") tf.app.flags.DEFINE_integer("mask_epoch", config.epoch, "epoch次数") tf.app.flags.DEFINE_string("mask_summary_write_dir", config.summary_write_dir, "训练数据过程可视化文件保存地址") tf.app.flags.DEFINE_string("mask_train_dir", config.train_dir, "训练数据的路径") tf.app.flags.DEFINE_string("mask_dev_dir", config.dev_dir, "验证数据文件路径") tf.app.flags.DEFINE_string("mask_test_dir", config.test_dir, "测试数据文件路径") tf.app.flags.DEFINE_string("mask_model_dir", config.model_dir, "模型保存路径") tf.app.flags.DEFINE_boolean('mask_use Encoder2Decoder',False,'') tf.app.flags.DEFINE_string("mask_mod", "train", "默认为训练") # true for prediction tf.app.flags.DEFINE_string('mask_model_mode', config.model_mode, '模型类型') tf.app.flags.DEFINE_boolean('mask_use_auto_buckets',config.use_auto_buckets,'是否使用自动桶') tf.app.flags.DEFINE_string('mask_only_mode','intent','执行哪种单一任务') FLAGS = tf.app.flags.FLAGS def get_sent_mask(sent_ids, entity_ids): sent_mask = np.zeros_like(sent_ids, dtype=np.float32) for i in range(sent_ids.shape[0]): for j in range(sent_ids.shape[1]): if sent_ids[i, j] > 0 and sent_ids[i, j] not in entity_ids: sent_mask[i, j] = 1.0 elif sent_ids[i, j] > 0 and sent_ids[i, j] in entity_ids: sent_mask[i, j] = 1.0 return sent_mask class ResNet(object): def __init__(self): with tf.device('/gpu:%s'%gpu_id): self.dd = Intent_Slot_Data(train_path=base_path+"/corpus_data/%s"%intent_config.train_name, test_path=base_path+"/corpus_data/%s"%intent_config.dev_name, dev_path=base_path+"/corpus_data/%s"%intent_config.dev_name, batch_size=FLAGS.mask_batch_size, max_length=FLAGS.mask_max_len, flag="train_new", use_auto_bucket=FLAGS.mask_use_auto_buckets) self.word_vocab = self.dd.vocab self.word_num = self.dd.vocab_num self.id2intent = self.dd.id2intent self.intent_num = len(self.id2intent) print(self.word_num) self.en=EntityRecognition() self.entity_id = [] for k, v in self.word_vocab.items(): if k in self.en.entity_dict.keys(): self.entity_id.append(v) self._extra_train_ops = [] def subsample(self,inputs,factor,ksizes,scope=None): with tf.variable_scope(name_or_scope=scope): if factor==1: return inputs else: return tf.nn.max_pool(inputs,ksize=[1,ksizes[0],ksizes[1],1],strides=[1,factor,factor,1],name=scope,padding='VALID') def conv2d_same(self,inputs,fliter_size,num_in,num_out,stride,scope=None): with tf.variable_scope(name_or_scope=scope): filter=tf.Variable(tf.random_uniform(shape=(fliter_size[0],fliter_size[1],num_in,num_out),dtype=tf.float32)) return tf.nn.conv2d(inputs,filter=filter,strides=[1,stride,stride,1],padding='SAME') def batch_norm(self, name, x): with tf.variable_scope(name): # 输入通道维数 params_shape = [x.get_shape()[-1]] # offset beta = tf.get_variable('beta', params_shape, tf.float32, initializer=tf.constant_initializer(0.0, tf.float32)) # scale gamma = tf.get_variable('gamma', params_shape, tf.float32, initializer=tf.constant_initializer(1.0, tf.float32)) if FLAGS.mask_mod == 'train': # 为每个通道计算均值、标准差 mean, variance = tf.nn.moments(x, [0, 1, 2], name='moments') # 新建或建立测试阶段使用的batch均值、标准差 moving_mean = tf.get_variable('moving_mean', params_shape, tf.float32, initializer=tf.constant_initializer(0.0, tf.float32), trainable=False) moving_variance = tf.get_variable('moving_variance', params_shape, tf.float32, initializer=tf.constant_initializer(1.0, tf.float32), trainable=False) # 添加batch均值和标准差的更新操作(滑动平均) # moving_mean = moving_mean * decay + mean * (1 - decay) # moving_variance = moving_variance * decay + variance * (1 - decay) self._extra_train_ops.append(moving_averages.assign_moving_average( moving_mean, mean, 0.9)) self._extra_train_ops.append(moving_averages.assign_moving_average( moving_variance, variance, 0.9)) else: # 获取训练中积累的batch均值、标准差 mean = tf.get_variable('moving_mean', params_shape, tf.float32, initializer=tf.constant_initializer(0.0, tf.float32), trainable=False) variance = tf.get_variable('moving_variance', params_shape, tf.float32, initializer=tf.constant_initializer(1.0, tf.float32), trainable=False) # 添加到直方图总结 tf.summary.histogram(mean.op.name, mean) tf.summary.histogram(variance.op.name, variance) # BN层:((x-mean)/var)*gamma+beta y = tf.nn.batch_normalization(x, mean, variance, beta, gamma, 0.001) y.set_shape(x.get_shape()) return y def resider(self,x, in_filter, out_filter, stride): ''' 默认前置激活 :param x: :param in_filter: :param out_filter: :param stride: :return: ''' with tf.variable_scope('shared'): x=self.batch_norm('init',x) x=tf.nn.relu(x) origin_x=x # 第1子层 with tf.variable_scope('sub1'): # 3x3卷积,使用输入步长,通道数(in_filter -> out_filter) x=self.conv2d_same(inputs=x,fliter_size=[3,3],num_in=in_filter,num_out=out_filter,stride=stride,scope='conv1') # 第2子层 with tf.variable_scope('sub2'): # BN和ReLU激活 x = self.batch_norm('bn2', x) x = tf.nn.relu(x) # 3x3卷积,步长为1,通道数不变(out_filter) x=self.conv2d_same(inputs=x,fliter_size=[3,3],num_in=out_filter,num_out=out_filter,stride=stride,scope='conv2') # 合并残差层 with tf.variable_scope('sub_add'): # 当通道数有变化时 if in_filter != out_filter: # 均值池化,无补零 origin_x = self.subsample(inputs=x,factor=1,ksizes=[1,1],scope='sub_add') # 通道补零(第4维前后对称补零) # origin_x = tf.pad(origin_x, # [[0, 0], # [0, 0], # [0, 0], # [(out_filter - in_filter) // 2, (out_filter - in_filter) // 2] # ]) # 合并残差 print('x',x) print('origin_x',origin_x) x += origin_x tf.logging.debug('image after unit %s', x.get_shape()) return x def __build_model__(self): with tf.device('/device:GPU:%s' % gpu_id): self.inputs=tf.placeholder(shape=(None,FLAGS.mask_max_len),dtype=tf.int32) self.intent_y=tf.placeholder(shape=(None,self.intent_num),dtype=tf.int32) embed=tf.Variable(tf.random_normal(shape=(self.word_num,FLAGS.mask_embedding_dim),dtype=tf.float32)) self.input_emb=tf.nn.embedding_lookup(embed,self.inputs) inputs=tf.expand_dims(self.input_emb,-1) # 第一次卷积 input_conv_1=self.conv2d_same(inputs=inputs,fliter_size=[3,3],num_in=1,num_out=16,stride=1,scope='init_conv') print(input_conv_1) res_func = self.resider # 通道数量 filters = [16, 16, 32, 64] # 第一组 with tf.variable_scope('unit_1_0'): x=res_func(x=input_conv_1,in_filter=16,out_filter=32,stride=1) for i in range(4): with tf.variable_scope('unit_1_%s'%(i+1)): x=res_func(x=x,in_filter=32,out_filter=32,stride=1) x=self.batch_norm('ll',x) #池化 x_mean=tf.reduce_max(x,1) x_out=tf.reshape(x_mean,[-1,3200]) x_out=tf.layers.dense(x_out,self.intent_num) self.soft_logit=tf.nn.softmax(x_out,1) self.loss=tf.losses.softmax_cross_entropy(self.intent_y,x_out) self.opt=tf.train.AdagradOptimizer(0.1).minimize(self.loss) def _decay(self): costs = [] # 遍历所有可训练变量 for var in tf.trainable_variables(): # 只计算标有“DW”的变量 costs.append(tf.nn.l2_loss(var)) # 加和,并乘以衰减因子 return tf.multiply(0.0001, tf.add_n(costs)) def __train__(self): config = tf.ConfigProto(allow_soft_placement=True) _logger.info("load data") _logger.info('entity_words:%s'%(self.en.entity_dict.keys())) with tf.Session(config=config) as sess: num_batch = self.dd.num_batch init_train_acc = 0.0 init_dev_acc = 0.0 init_train_loss=9999.99 init_dev_loss=9999.99 saver = tf.train.Saver() if os.path.exists('%s.meta' % FLAGS.mask_model_dir): saver.restore(sess, FLAGS.mask_model_dir) else: sess.run(tf.global_variables_initializer()) dev_sent, dev_slot, dev_intent, dev_rel_len,_ = self.dd.get_dev() train_sent, train_slot, train_intent, train_rel_len,_ = self.dd.get_train() for i in range(FLAGS.mask_epoch): for _ in range(num_batch): sent, slot, intent_label, rel_len, cur_len = self.dd.next_batch() batch_sent_mask = get_sent_mask(sent, self.entity_id) soft_logit_, loss_, _ = sess.run([self.soft_logit, self.loss, self.opt], feed_dict={self.inputs: sent, self.intent_y: intent_label, }) dev_soft_logit_, dev_loss_ = sess.run([self.soft_logit, self.loss], feed_dict={self.inputs: dev_sent, self.intent_y: dev_intent, }) dev_acc = intent_acc(dev_soft_logit_, dev_intent, self.id2intent) # if train_acc > init_train_acc and dev_acc > (init_dev_acc-0.05): if dev_acc>init_dev_acc: init_dev_loss=dev_loss_ init_dev_acc=dev_acc # init_train_acc = train_acc # init_dev_acc = dev_acc _logger.info('save') saver.save(sess, FLAGS.mask_model_dir) _logger.info('第 %s 次迭代 dev_loss:%s dev_acc:%s' % ( i, dev_loss_, dev_acc)) def __infer__(self,sents,sess): sent_arr, sent_vec = self.dd.get_sent_char(sents) sent_mask = get_sent_mask(sent_arr, self.entity_id) intent_logit = sess.run(self.soft_logit, feed_dict={self.sent_word: sent_arr, self.sent_len: sent_vec, self.sent_mask:sent_mask, self.dropout:1.0}) res = [] for ele in intent_logit: ss = [[self.id2intent[index], str(e)] for index, e in enumerate(ele) if e >= 0.3] if not ss: ss = [[self.id2intent[np.argmax(ele)], str(np.max(ele))]] res.append(ss) return res def infer_dev(self): config = tf.ConfigProto( # limit to num_cpu_core CPU usage inter_op_parallelism_threads=8, intra_op_parallelism_threads=8, log_device_placement=False, allow_soft_placement=True, ) id2intent = self.dd.id2intent id2sent=self.dd.id2sent saver = tf.train.Saver() with tf.Session(config=config) as sess: if os.path.exists('%s.meta' % FLAGS.mask_model_dir): saver.restore(sess, '%s' % FLAGS.mask_model_dir) else: sess.run(tf.global_variables_initializer()) dev_sent, dev_slot, dev_intent, dev_rel_len,dev_index = self.dd.get_dev() train_sent, train_slot, train_intent, train_rel_len,train_index = self.dd.get_train() dev_sent_mask = get_sent_mask(dev_sent, self.entity_id) train_sent_mask = get_sent_mask(train_sent, self.entity_id) dev_softmax_logit, dev_loss = sess.run([self.soft_logit, self.loss], feed_dict={self.sent_word: dev_sent, self.sent_len: dev_rel_len, self.intent_y: dev_intent, self.sent_mask: dev_sent_mask, self.dropout:1.0 }) self.matirx(dev_softmax_logit, dev_intent, id2intent,id2sent,dev_sent,dev_index, 'dev') train_softmax_logit, train_loss = sess.run([self.soft_logit, self.loss], feed_dict={self.sent_word: train_sent, self.sent_len: train_rel_len, self.intent_y: train_intent, self.sent_mask: train_sent_mask, self.dropout:1.0 }) self.matirx(train_softmax_logit, train_intent, id2intent,id2sent,train_sent,train_index, 'train') def __server__(self): config = tf.ConfigProto(device_count={"CPU": FLAGS.mask_use_cpu_num}, # limit to num_cpu_core CPU usage inter_op_parallelism_threads=8, intra_op_parallelism_threads=8, log_device_placement=False, allow_soft_placement=True, ) _logger.info("load data") with tf.Session(config=config) as sess: saver = tf.train.Saver() sess = tf.Session(config=config) if os.path.exists('%s.meta' % FLAGS.mask_model_dir): saver.restore(sess, '%s' % FLAGS.mask_model_dir) else: _logger.error('lstm没有模型') def intent(sent_list): sents = [] _logger.info("%s" % len(sent_list)) sents = [] for sent in sent_list: sents.append(self.dd.get_sent_char(sent)) sent_arr, sent_vec = self.dd.get_sent_char(sents) infer_sent_mask = get_sent_mask(sent_arr, self.entity_id) intent_logit = sess.run(self.soft_logit, feed_dict={self.sent_word: sent_arr, self.sent_len: sent_vec, self.sent_mask: infer_sent_mask}) res = [] for ele in intent_logit: ss = [[self.id2intent[index], str(e)] for index, e in enumerate(ele) if e >= 0.3] if not ss: ss = [[self.id2intent[np.argmax(ele)], str(np.max(ele))]] res.append(ss) del sents gc.collect() _logger.info('process end') _logger.info('%s' % res) return res svr = SimpleXMLRPCServer((config_lstm.host, 8087), allow_none=True) svr.register_function(intent) svr.serve_forever() def matirx(self,pre_label,label,id2intent,id2sent,sent,indexs,type): pre_label_prob=np.max(pre_label,1) pre_label=np.argmax(pre_label,1) label=np.argmax(label,1) pre_label=pre_label.flatten() label=label.flatten() ss = [[int(k), v] for k, v in id2intent.items()] ss.sort(key=lambda x: x[0], reverse=False) labels = [e[0] for e in ss] traget_name=[e[1] for e in ss] class_re=classification_report(label,pre_label,target_names=traget_name,labels=labels) print(class_re) # con_mat=confusion_matrix(y_true=label,y_pred=pre_label,labels=labels) sents=[] for ele in sent: s=' '.join([id2sent[e]for e in ele if e!=0]) sents.append(s) confus_dict={} for ele in traget_name: confus_dict[ele]={} for e in traget_name: confus_dict[ele][e]=[0,[]] for true,pred,sent,prob,ii in zip(label,pre_label,sents,pre_label_prob,indexs): true_name=id2intent[true] pred_name=id2intent[pred] data_list=confus_dict[true_name][pred_name] data_list[0]+=1 data_list[1].append((ii,prob,sent)) confus_dict[true_name][pred_name]=data_list # print(confus_dict) if type=='train': pickle.dump(confus_dict,open('./train.p','wb')) elif type=='dev': pickle.dump(confus_dict,open('./dev.p','wb')) def main(_): lm=ResNet() lm.__build_model__() if FLAGS.mask_mod=='train': lm.__train__() elif FLAGS.mask_mod=='infer_dev': lm.infer_dev() elif FLAGS.mask_mod=='server': lm.__server__() if __name__ == '__main__': tf.app.run()<file_sep>/model/dl_model/model_semantic_match_new/tt.py # fw=open('dev_en.txt','w') # for e in open('./dev_new.txt','r').readlines(): # e=e.replace('\n','') # sents=e.split(',') # fw.write(sents[0]) # fw.write('\t\t') # fw.write(sents[1]) # fw.write('\t\t') # fw.write(sents[2]) # fw.write('\n') s=[1,2,3,4,5] from functools import reduce f=reduce(lambda x,y:max(x,y),s) alist = [[1,2],3,4] blist = alist blist[0]=1 print(alist) # names = ['Amir', 'Betty', 'Chales', 'Tao'] # names.index("Edward") def addItem(listParam): listParam += [1] mylist = [1, 2, 3, 4] addItem(mylist) print(mylist) list1 = [1, 2, 3, 4] list2 = [5, 6, 7, 8] print(list1+list2 ) x=True;y,z=False,False if x or y and z: print('yes') else: print('no') def myfoo(x, y, z, a): return x + z nums = [1, 2, 3, 4] print(myfoo(*nums))<file_sep>/data_deal.py import re import random import sys sys.path.append('.') from entity_recognition.ner import EntityRecognition from IntentConfig import Config er=EntityRecognition() config=Config() import logging from jieba import analyse import jieba from collections import OrderedDict logging.basicConfig(level=logging.INFO, format='%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s', datefmt='%a, %d %b %Y %H:%M:%S', filemode='w') _logger=logging.getLogger("Intent_Data_Deal") jieba.load_userdict('./corpus_data/stop_word.txt') tfidf=analyse.extract_tags class Intent_Data_Deal(object): ''' 数据预处理 包括:去停用词/ ''' def __init__(self): self.stop_words = [ele.replace('\n', '') for ele in open('./stop_word.txt', 'r').readlines()] self.intent_indice=list(config.root_intent.keys())[-1] intent_dict_=config.root_intent self.intent_dict=OrderedDict() for k,v in intent_dict_.items(): v_=[e.lower() for e in v] self.intent_dict[k]=v_ def pre_data_deal(self,origin_sent): sub_pattern = '你好|.{0,4}老师|.{0,4}年|.{0,4}%|,|谢谢你|谢谢|。|!|?|~' replace_pattern = r'\d{6}' replace_pattern_0 = r'\d.' origin_sent=origin_sent.replace('\n','') try: index = origin_sent.split('\t\t')[0] sent = origin_sent.split('\t\t')[1] label = origin_sent.split('\t\t')[2] except Exception as ex: _logger.info('Error sent ',origin_sent) sent = re.subn(sub_pattern, '', sent)[0] sent = sent.split('?')[0].replace(' ', '') sent = re.subn(replace_pattern, 'stock', sent)[0] sent = re.subn(replace_pattern_0, '', sent)[0] res_sent='\t\t'.join([index,sent,label]) return res_sent def deal_sent(self,line): ''' 对句子进行处理,实体识别,增加eos/bos和实体标签 :param sent: :return: ''' pattern = '\d{1,3}(\\.|,|、|?)|《|》|?|。' line = line.replace('\n', '').strip() line=self.pre_data_deal(line) sent='' ll='' index='' line=line.replace('\t\t','\t').replace('Other','other').lower() if '\t' in line: index=str(line).split('\t')[0].strip().replace(' ','') sent=str(line).split('\t')[1].strip().replace(' ','') ll=str(line).split('\t')[2].strip().replace(' ','') else: try: index = str(line).split(' ')[0].strip().replace(' ', '') sent=str(line).split(' ')[1].strip().replace(' ','') ll=str(line).split(' ')[2].strip().replace(' ','') except Exception as ex: _logger.info('%s:%s'%(ex,[line])) sent = re.subn(pattern, '', sent)[0] ss=er.get_entity([sent])[0] #实体识别功能 # 结巴关键词提取实现 # sent=''.join(ss) # keys=tfidf(sent) # ss=keys sent=' '.join(ss) label = ll sent = 'bos' + ' ' + sent + ' ' + 'eos' entity = ' '.join(['o'] * len(sent.split(' '))) res = str(index)+'\t'+sent + '\t' + entity + '\t' + label return sent,res def deal_file(self,input_file_name,train_file_name,dev_file_name,split_rate=0.2): ''' 将输入的标注数据 转换为带实体标签的char数据 :param file_name: :return: ''' fw_train=open(train_file_name,'w') fw_dev=open(dev_file_name,'w') num_dict={} data=set() with open(input_file_name,'r') as fr: for ele in fr.readlines(): e=self.deal_sent(ele)[1] data.add(e) fr.close() data=list(data) random.shuffle(data) split_num=int(len(data)*split_rate) # dev write for ele in data[:split_num]: eles=ele.split('\t') left=eles[:-1] labels=eles[-1].split('##') true_label=[] if self.intent_indice==0: if labels[self.intent_indice] in self.intent_dict[0] and labels[self.intent_indice]!='none': left.append(labels[0]) true_label.append(labels[0]) sent='\t'.join(left) fw_dev.write(sent) fw_dev.write('\n') else: for i in range(self.intent_indice+1): if labels[i] == 'none': true_label=[] break elif labels[i] in self.intent_dict[i]: true_label.append(labels[i]) else: true_label=[] if true_label!=[]: left.append('_'.join(true_label)) sent='\t'.join(left) fw_dev.write(sent) fw_dev.write('\n') if true_label != []: true_label='_'.join(true_label) if true_label not in num_dict: num_dict[true_label]=1 else: s=num_dict[true_label] s+=1 num_dict[true_label]=s '''train write''' for ele in data[split_num::]: eles=ele.split('\t') left=eles[:-1] labels=eles[-1].split('##') true_label=[] if self.intent_indice==0: if labels[self.intent_indice] in self.intent_dict[0] and labels[self.intent_indice]!='none': left.append(labels[0]) true_label.append(labels[0]) sent='\t'.join(left) fw_train.write(sent) fw_train.write('\n') else: for i in range(self.intent_indice+1): if labels[i] == 'none': true_label=[] break elif labels[i] in self.intent_dict[i]: true_label.append(labels[i]) else: true_label=[] if true_label!=[]: left.append('_'.join(true_label)) sent='\t'.join(left) fw_train.write(sent) fw_train.write('\n') if true_label != []: true_label='_'.join(true_label) if true_label not in num_dict: num_dict[true_label]=1 else: s=num_dict[true_label] s+=1 num_dict[true_label]=s print('label num dict') print(num_dict) if __name__ == '__main__': idd=Intent_Data_Deal() # corpus=sys.argv[1] # train_out=sys.argv[2] # dev_out=sys.argv[3] # print(corpus,train_out,dev_out) idd.deal_file(config.corpus_name,config.train_name,config.dev_name) <file_sep>/model/dl_model/model_center_loss/data_preprocess_json.py import numpy as np import pickle import os PATH=os.path.split(os.path.split(os.path.split(os.path.split(os.path.realpath(__file__))[0])[0])[0])[0] print(PATH) import logging import json import random import re from IntentConfig import Config from entity_recognition.ner import EntityRecognition import jieba logging.basicConfig(level=logging.INFO, format='%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s', datefmt='%a, %d %b %Y %H:%M:%S', filemode='w') _logger=logging.getLogger("data_preprocess") config=Config() er=EntityRecognition() class Intent_Slot_Data(object): ''' intent_slot 数据处理模块 ''' def __init__(self, train_path, dev_path, test_path, batch_size, flag,max_length,use_auto_bucket): #分隔符 self.split_token='\t' self.train_path = train_path # 训练文件路径 self.dev_path = dev_path # 验证文件路径 self.test_path = test_path # 测试文件路径 self.batch_size = batch_size # batch大小 self.max_length = max_length self.use_auto_bucket=use_auto_bucket self.index=1 self.word_vocab = {'none': 0} self.index = 0 self.class_vocab = {} if flag == "train_new": self.datas_train = self.token_json(self.train_path) pickle.dump(self.datas_train, open('datas_train_json.p', 'wb')) pickle.dump(self.word_vocab, open(PATH+"/save_model/word_vocab.p", 'wb')) # 词典 pickle.dump(self.class_vocab, open( PATH+"/save_model/class_vocab.p", 'wb')) # 词典 elif flag == "test" or flag == "train": self.datas_train = pickle.load(open(PATH+"/save_model/datas_train_json.p", 'rb')) self.word_vocab = pickle.load(open(PATH+"/save_model/word_vocab.p", 'rb')) # 词典 self.class_vocab = pickle.load(open(PATH+"/save_model/class_vocab.p", 'rb')) # 词典 def get_vocab(self,args): ''' :param args: :return: ''' for ele in args: eles=list(jieba.cut(ele)) eles_words=[] rel_len=len(eles) for e in eles: if e not in self.word_vocab: self.word_vocab[e]=self.index self.index+=1 eles_words.append(self.word_vocab[e]) eles_words.extend([0]*self.max_length) eles_words=eles_words[:self.max_length] eles_words.append(rel_len) yield eles_words def token_json(self,json_path): ''' 读取json文件并分词, :param json_path: :return: ''' datas = json.load(open(json_path, 'r')) for k,v in datas.items(): v_=list(self.get_vocab(v)) if k not in self.class_vocab: self.class_vocab[k]=int(k) datas[k]=v_ _logger.info('%s finish'%k) return datas def get_train_test(self,split=0.1): ''' ''' sent_data=[] label_data=[] for k,v in self.datas_train.items(): for ele in v: sent_data.append([ele,k]) length=len(sent_data) random.shuffle(sent_data) num=int(length*split) test_data=sent_data[:num] train_data=sent_data[num:] return train_data,test_data def main(): dd = Intent_Slot_Data(train_path="./../../../corpus_data/train.json", test_path="./../../../corpus_data/dev.json", dev_path="./../../../corpus_data/test.json", batch_size=20 ,max_length=20, flag="train_new",use_auto_bucket=False) train,test=dd.get_train_test(0.1) print(test) if __name__ == '__main__': main() <file_sep>/model/dl_model/model_lstm_res/pipeline_lstm_mask.py import logging import sys,os sys.path.append('./') from model.dl_model.model_lstm_mask.data_preprocess import Intent_Slot_Data from IntentConfig import Config from model.dl_model.model_lstm_mask.lstm_mask import LstmMask,Config_lstm import tensorflow as tf config_lstm=Config_lstm() os.environ["CUDA_VISIBLE_DEVICES"] = "1" logging.basicConfig(level=logging.INFO, format='%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s', datefmt='%a, %d %b %Y %H:%M:%S', filename='modellog.log', filemode='w') _logger = logging.getLogger("intent_bagging") class IntentDLB(object): def __init__(self): self.nn_model = LstmMask() self.nn_model.__build_model__() config = tf.ConfigProto(device_count={"CPU": 8}, # limit to num_cpu_core CPU usage inter_op_parallelism_threads=8, intra_op_parallelism_threads=8, log_device_placement=False, allow_soft_placement=True, ) saver=tf.train.Saver() self.sess=tf.Session(config=config) saver.restore(self.sess,config_lstm.model_dir) def get_intent(self,sents): ''' :param sents: :return: ''' return self.nn_model.__infer__(sents,self.sess) if __name__ == '__main__': id=IntentDLB() data=[] for ele in open('tt.txt','r').readlines(): ele=ele.replace('\n','') data.append(ele) s=id.get_intent(data) print(s) fw=open('./tt_w.txt','w') for sent,label in zip(data,s): fw.write(sent) fw.write('\t\t') fw.write(label[0][0]) fw.write('\n') <file_sep>/model/dl_model/model_lstm_rl/lstm_mask.py import tensorflow as tf import os import sys sys.path.append('./') from model.dl_model.model_lstm_rl.data_preprocess import Intent_Slot_Data from model.dl_model.model_lstm_rl.model_fun import embedding,sent_encoder,self_attention,loss_function,intent_acc,cosin_com,label_sent_attention,output_layers from model.dl_model.model_lstm_rl.focal_loss import focal_loss from IntentConfig import Config import numpy as np import logging import copy import pickle from sklearn.metrics import classification_report,precision_recall_fscore_support,confusion_matrix import gc path=os.path.dirname(os.path.dirname(__file__)) sys.path.insert(0,path) from collections import deque, namedtuple base_path=os.path.split(os.path.split(os.path.split(os.path.split(os.path.realpath(__file__))[0])[0])[0])[0] from random import random from entity_recognition.ner import entity_dict import itertools from xmlrpc.server import SimpleXMLRPCServer logging.basicConfig(level=logging.INFO, format='%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s', datefmt='%a, %d %b %Y %H:%M:%S', filename='modellog.log', filemode='w') _logger = logging.getLogger("intent_bagging") config_lstm=Config() gpu_id=3 os.environ["CUDA_VISIBLE_DEVICES"] = "" class Config_lstm(object): ''' 默认配置 ''' learning_rate = 0.001 batch_size = 128 label_max_len=16 sent_len = 40 # 句子长度 embedding_dim = 100 # 词向量维度 hidden_dim = 200 train_dir = './data/train_out_%s.txt' dev_dir = './data/dev_out.txt' test_dir = './data/test.txt' model_dir = base_path+'/save_model/model_lstm_mask/intent_lstm_dn.ckpt' if not os.path.exists(base_path+'/save_model/model_lstm_mask'): os.makedirs(base_path+'/save_model/model_lstm_mask') use_cpu_num = 16 keep_dropout = 0.5 summary_write_dir = "./tmp/r_net.log" epoch = 100 use_auto_buckets=False lambda1 = 0.01 model_mode = 'bilstm_attention_crf' # 模型选择:bilstm bilstm_crf bilstm_attention bilstm_attention_crf,cnn_crf config = Config_lstm() tf.app.flags.DEFINE_float("mask_lambda1", config.lambda1, "l2学习率") tf.app.flags.DEFINE_float("mask_learning_rate", config.learning_rate, "学习率") tf.app.flags.DEFINE_float("mask_keep_dropout", config.keep_dropout, "dropout") tf.app.flags.DEFINE_integer("mask_batch_size", config.batch_size, "批处理的样本数量") tf.app.flags.DEFINE_integer("mask_max_len", config.sent_len, "句子长度") tf.app.flags.DEFINE_integer("mask_max_label_len", config.label_max_len, "句子长度") tf.app.flags.DEFINE_integer("mask_embedding_dim", config.embedding_dim, "词嵌入维度.") tf.app.flags.DEFINE_integer("mask_hidden_dim", config.hidden_dim, "中间节点维度.") tf.app.flags.DEFINE_integer("mask_use_cpu_num", config.use_cpu_num, "限定使用cpu的个数") tf.app.flags.DEFINE_integer("mask_epoch", config.epoch, "epoch次数") tf.app.flags.DEFINE_string("mask_summary_write_dir", config.summary_write_dir, "训练数据过程可视化文件保存地址") tf.app.flags.DEFINE_string("mask_train_dir", config.train_dir, "训练数据的路径") tf.app.flags.DEFINE_string("mask_dev_dir", config.dev_dir, "验证数据文件路径") tf.app.flags.DEFINE_string("mask_test_dir", config.test_dir, "测试数据文件路径") tf.app.flags.DEFINE_string("mask_model_dir", config.model_dir, "模型保存路径") tf.app.flags.DEFINE_boolean('mask_use Encoder2Decoder',False,'') tf.app.flags.DEFINE_string("mask_mod", "infer_dev", "默认为训练") # true for prediction tf.app.flags.DEFINE_string('mask_model_mode', config.model_mode, '模型类型') tf.app.flags.DEFINE_boolean('mask_use_auto_buckets',config.use_auto_buckets,'是否使用自动桶') tf.app.flags.DEFINE_string('mask_only_mode','intent','执行哪种单一任务') FLAGS = tf.app.flags.FLAGS def get_sent_mask(sent_ids, entity_ids): sent_mask = np.zeros_like(sent_ids, dtype=np.float32) for i in range(sent_ids.shape[0]): for j in range(sent_ids.shape[1]): if sent_ids[i, j] > 0 and sent_ids[i, j] not in entity_ids: sent_mask[i, j] = 1.0 elif sent_ids[i, j] > 0 and sent_ids[i, j] in entity_ids: sent_mask[i, j] = 1.5 return sent_mask class LstmRl(object): def __init__(self,scope): self.scope = scope with tf.variable_scope(name_or_scope=scope): with tf.device('/gpu:%s'%gpu_id): self.dd = Intent_Slot_Data(train_path=base_path+"/corpus_data/train_out_char.txt", test_path=base_path+"/corpus_data/dev_out_char.txt", dev_path=base_path+"/corpus_data/dev_out_char.txt", batch_size=FLAGS.mask_batch_size, max_length=FLAGS.mask_max_len, flag="train_new", use_auto_bucket=FLAGS.mask_use_auto_buckets) self.id2intent = self.dd.id2intent self.intent_num = len(self.id2intent) self.word_num = self.dd.vocab_num word_vocab = self.dd.vocab self.entity_id = [] for k, v in word_vocab.items(): if k in entity_dict.keys(): self.entity_id.append(v) self.__build_model__() def __build_model__(self): with tf.device('/device:GPU:%s'%gpu_id): self.sent_word = tf.placeholder(shape=(None, FLAGS.mask_max_len), dtype=tf.int32,name='sent_word') self.sent_len = tf.placeholder(shape=(None,), dtype=tf.int32,name='sent_len') self.sent_mask = tf.placeholder(shape=(None, FLAGS.mask_max_len), dtype=tf.float32,name='sent_mask') self.sent_action=tf.placeholder(shape=(None,),dtype=tf.int32,name='sent_action') self.dropout=tf.placeholder(dtype=tf.float32) self.intent_y = tf.placeholder(shape=(None, self.intent_num), dtype=tf.int32,name='intent_y') self.target_action=tf.placeholder(shape=(None,),dtype=tf.float32,name='target_action') sent_action_emb=embedding(self.sent_action,self.intent_num+1,50,'sent_action_emb') sent_emb = embedding(self.sent_word, self.word_num, FLAGS.mask_embedding_dim, 'sent_emb') sent_emb=tf.nn.dropout(sent_emb,self.dropout) label_emb = tf.Variable(tf.random_uniform(shape=(self.intent_num, 300),maxval=1.0,minval=-1.0, dtype=tf.float32), trainable=True) sen_enc = sent_encoder(sent_word_emb=sent_emb, hidden_dim=FLAGS.mask_hidden_dim, num=FLAGS.mask_max_len, sequence_length=self.sent_len, name='sent_enc',dropout=self.dropout) sent_attention = self_attention(sen_enc, self.sent_mask) stack_sent_enc = tf.stack([tf.concat((ele, sent_attention), 1) for ele in sen_enc], 1,name='stack_sent_enc') stack_sent_enc=tf.nn.dropout(stack_sent_enc,self.dropout) out = label_sent_attention(stack_sent_enc, label_emb, self.sent_mask) out=tf.concat((out,sent_action_emb),1) logit = output_layers(out, self.intent_num, name='out_layers', reuse=False) self.soft_logit = tf.nn.softmax(logit, 1,name='mask_soft_logit') max_logit=tf.reduce_max(tf.multiply(self.soft_logit,tf.cast(self.intent_y,tf.float32)),1) # loss=focal_loss(self.soft_logit,tf.cast(self.intent_y,tf.float32)) # class_y = tf.constant(name='class_y', shape=[self.intent_num, self.intent_num], dtype=tf.float32, # value=np.identity(self.intent_num), ) # # logit_label = output_layers(label_emb, self.intent_num, name='out_layers', reuse=True) # label_loss = tf.losses.softmax_cross_entropy(onehot_labels=class_y, logits=logit_label) # # loss = tf.losses.softmax_cross_entropy(onehot_labels=self.intent_y, logits=logit) # self.losses = tf.squared_difference(max_logit, self.target_action) self.loss = tf.reduce_mean(self.losses) # self.loss = 0.7 * loss + 0.3 * label_loss # ss=tf.concat((sent_attention,tf.stack_sent_enc),1) # cosin=cosin_com(ss,label_emb,intent_num) # loss, soft_logit=loss_function(cosin,intent_y) # loss,soft_logit=loss_function(cosin,intent_y) # ss=tf.concat((sent_attention,sen_enc[0]),1) # logit=tf.layers.dense(ss,intent_num) # soft_logit=tf.nn.softmax(logit,1) # loss=focal_loss(soft_logit,tf.cast(intent_y,tf.float32)) # # loss=tf.losses.softmax_cross_entropy(intent_y,logit) # # self.optimizer = tf.train.AdamOptimizer(FLAGS.mask_learning_rate).minimize(self.loss) def update(self,sess,state,action,action_target): sent_array, sent_vec,sent_action = [], [] ,[] for ele in state: sent_array.extend(ele['sent_array']) sent_vec.extend(ele['sent_vec']) sent_action.extend([ele['sent_action']]) sent_array = np.array(sent_array) sent_vec = np.array(sent_vec) sent_action=np.array(sent_action) sent_array_mask=get_sent_mask(sent_array,self.entity_id) intent_label=np.zeros(shape=(sent_array.shape[0],self.intent_num)) for index,ele in enumerate(action): intent_label[index][ele]=1 action_target=np.array(action_target) soft_logit_, loss_, _ = sess.run([self.soft_logit, self.loss, self.optimizer], feed_dict={self.sent_word: sent_array, self.sent_len:sent_vec , self.intent_y: intent_label, self.sent_mask: sent_array_mask, self.dropout:FLAGS.mask_keep_dropout, self.target_action:action_target, self.sent_action:sent_action }) return loss_ def predict(self,sess,state): if isinstance(state,list): sent_array,sent_vec,sent_action=[],[],[] for ele in state: sent_array.extend(ele['sent_array']) sent_vec.extend(ele['sent_vec']) sent_action.extend([ele['sent_action']]) sent_array=np.array(sent_array) sent_vec=np.array(sent_vec) sent_action=np.array(sent_action ) sent_mask = get_sent_mask(sent_array, self.entity_id) intent_logit = sess.run(self.soft_logit, feed_dict={self.sent_word: sent_array, self.sent_len: sent_vec, self.sent_mask:sent_mask, self.dropout:1.0, self.sent_action:sent_action}) return intent_logit elif isinstance(state,dict): sent_array=state['sent_array'] sent_vec=state['sent_vec'] sent_action=np.array([state['sent_action']]) sent_mask = get_sent_mask(sent_array, self.entity_id) intent_logit = sess.run(self.soft_logit, feed_dict={self.sent_word: sent_array, self.sent_len: sent_vec, self.sent_mask: sent_mask, self.dropout: 1.0, self.sent_action:sent_action}) return intent_logit def dev_predict(self,sess): ''' dev 预测结果 :param sess: :return: ''' dev_sent, dev_slot, dev_intent, dev_rel_len, dev_index = self.dd.get_dev() dev_sent_mask=get_sent_mask(dev_sent,self.entity_id) dev_sent_action=np.ones_like(dev_rel_len) dev_sent_action=dev_sent_action*self.intent_num intent_logit = sess.run(self.soft_logit, feed_dict={self.sent_word: dev_sent, self.sent_len: dev_rel_len, self.sent_mask: dev_sent_mask, self.dropout: 1.0, self.sent_action: dev_sent_action}) pred=np.argmax(intent_logit,1) true=np.argmax(dev_intent,1) dev_acc=float(np.equal(pred,true).sum())/float(len(pred)) train_sent, train_slot, train_intent, train_rel_len, train_index = self.dd.get_train() train_sent_mask = get_sent_mask(train_sent, self.entity_id) train_sent_action = np.ones_like(train_rel_len) train_sent_action = train_sent_action * self.intent_num train_intent_logit = sess.run(self.soft_logit, feed_dict={self.sent_word: train_sent, self.sent_len: train_rel_len, self.sent_mask: train_sent_mask, self.dropout: 1.0, self.sent_action: train_sent_action}) pred = np.argmax(train_intent_logit, 1) true = np.argmax(train_intent, 1) train_acc = float(np.equal(pred, true).sum()) / float(len(pred)) return dev_acc,train_acc def make_epsilon_greedy_policy(estimator, nA): """ Creates an epsilon-greedy policy based on a given Q-function approximator and epsilon. Args: estimator: An estimator that returns q values for a given state nA: Number of actions in the environment. Returns: A function that takes the (sess, observation, epsilon) as an argument and returns the probabilities for each action in the form of a numpy array of length nA. """ def policy_fn(sess, observation, epsilon): A = np.ones(nA, dtype=float) * epsilon / nA q_values = estimator.predict(sess=sess, state=observation)[0] best_action = np.argmax(q_values) A[best_action] += (1.0 - epsilon) return A return policy_fn class ENV(object): def __init__(self): self.dd = Intent_Slot_Data(train_path=base_path + "/corpus_data/train_out_char.txt", test_path=base_path + "/corpus_data/dev_out_char.txt", dev_path=base_path + "/corpus_data/dev_out_char.txt", batch_size=1, max_length=FLAGS.mask_max_len, flag="train_new", use_auto_bucket=FLAGS.mask_use_auto_buckets) self.id2intent = self.dd.id2intent self.intent_num = len(self.id2intent) self.word_num = self.dd.vocab_num word_vocab = self.dd.vocab self.entity_id = [] for k, v in word_vocab.items(): if k in entity_dict.keys(): self.entity_id.append(v) def get_init_state(self): ''' 获得初始的state :return: ''' state=self.dd.next_batch() return {'sent_array':state[0],'sent_vec':state[3],'label':state[2],'sent_action':self.intent_num} def step(self,action,state,turn,max_turn): ''' 根据反馈的action获取下一个state :param action: :return: ''' done=False label=state['label'] next_state={'sent_array':state['sent_array'],'sent_vec':state['sent_vec'],'sent_action':None,'label':state['label']} if turn<max_turn : if np.argmax(action)!=np.argmax(label): reward=-2 next_state['sent_action']=np.argmax(action) else: reward=2 next_state['sent_action']=np.argmax(action) next_state['sent_action']=np.argmax(action) elif turn==max_turn: done = True if np.argmax(action)!=np.argmax(label): reward=-5 # sent_array[0,sent_vec[0]]=np.argmax(action) next_state['sent_action']=np.argmax(action) # next_state['sent_array']=sent_array else: reward=5 # sent_array[0,sent_vec[0]]=np.argmax(action) next_state['sent_action']=np.argmax(action) # next_state['sent_array']=sent_array return next_state,reward,done def batch_step(self,batch_action,batch_state,turn,max_turn): batch_next_state=[] batch_reward=[] batch_done=[] for action,state in zip(batch_action,batch_state): next_state,reward,done=self.step(action,state,turn,max_turn) batch_next_state.append(next_state) batch_reward.append(reward) batch_done.append(done) batch_next_state=np.array(batch_next_state) batch_reward=np.array(batch_reward) batch_done=np.array(batch_done) return batch_next_state,batch_reward,batch_done def get_train_state(self): ''' 获取 train集的 state :return: ''' train_sent, train_slot, train_intent, train_rel_len, train_index = self.dd.get_train() train_sent_action = np.ones_like(train_rel_len) train_sent_action = train_sent_action * self.intent_num res=[] for i in range(train_sent.shape[0]): res.append({'sent_array':train_sent[i],'sent_vec':train_rel_len[i],'label':train_intent[i],'sent_action':train_sent_action[i]}) return res def get_dev_state(self): ''' 获取dev的init_state :return: ''' dev_sent, dev_slot, dev_intent, dev_rel_len, dev_index = self.dd.get_dev() dev_sent_action = np.ones_like(dev_rel_len) dev_sent_action = dev_sent_action * self.intent_num return {'sent_array': dev_sent, 'sent_vec': dev_rel_len, 'label': dev_intent, 'sent_action': dev_sent_action} def copy_model_parameters(sess, estimator1, estimator2): """ Copies the model parameters of one estimator to another. Args: sess: Tensorflow session instance estimator1: Estimator to copy the paramters from estimator2: Estimator to copy the parameters to """ e1_params = [t for t in tf.trainable_variables() if t.name.startswith(estimator1.scope)] e1_params = sorted(e1_params, key=lambda v: v.name) e2_params = [t for t in tf.trainable_variables() if t.name.startswith(estimator2.scope)] e2_params = sorted(e2_params, key=lambda v: v.name) update_ops = [] for e1_v, e2_v in zip(e1_params, e2_params): op = e2_v.assign(e1_v) update_ops.append(op) sess.run(update_ops) def deep_q_learning(sess, env, q_estimator, target_estimator, num_episodes, experiment_dir, replay_memory_size=50, replay_memory_init_size=50, update_target_estimator_every=50, discount_factor=0.5, epsilon_start=0.5, epsilon_end=0.1, epsilon_decay_steps=500, batch_size=32, record_video_every=50, max_turn=4): """ Q-Learning algorithm for off-policy TD control using Function Approximation. Finds the optimal greedy policy while following an epsilon-greedy policy. Args: sess: Tensorflow Session object env: OpenAI environment q_estimator: Estimator object used for the q values target_estimator: Estimator object used for the targets state_processor: A StateProcessor object num_episodes: Number of episodes to run for experiment_dir: Directory to save Tensorflow summaries in replay_memory_size: Size of the replay memory replay_memory_init_size: Number of random experiences to sampel when initializing the reply memory. update_target_estimator_every: Copy parameters from the Q estimator to the target estimator every N steps discount_factor: Gamma discount factor epsilon_start: Chance to sample a random action when taking an action. Epsilon is decayed over time and this is the start value epsilon_end: The final minimum value of epsilon after decaying is done epsilon_decay_steps: Number of steps to decay epsilon over batch_size: Size of batches to sample from the replay memory record_video_every: Record a video every N episodes Returns: An EpisodeStats object with two numpy arrays for episode_lengths and episode_rewards. """ print('开始DQN') #有效的action 列表 VALID_ACTIONS=list(range(q_estimator.intent_num+1)) stats={} # The replay memory # 经验池 replay_memory = [] # Keeps track of useful statistics # stats = plotting.EpisodeStats( # episode_lengths=np.zeros(num_episodes), # episode_rewards=np.zeros(num_episodes)) # Create directories for checkpoints and summaries # checkpoint_dir = os.path.join(experiment_dir, "checkpoints") # checkpoint_path = os.path.join(checkpoint_dir, "model") # monitor_path = os.path.join(experiment_dir, "monitor") # if not os.path.exists(checkpoint_dir): # os.makedirs(checkpoint_dir) # if not os.path.exists(monitor_path): # os.makedirs(monitor_path) # saver = tf.train.Saver() # sess.run(tf.global_variables_initializer()) # Load a previous checkpoint if we find one # latest_checkpoint = tf.train.latest_checkpoint(checkpoint_dir) # if latest_checkpoint: # print("Loading model checkpoint {}...\n".format(latest_checkpoint)) # saver.restore(sess, latest_checkpoint) # # # The epsilon decay schedule sess.run(tf.global_variables_initializer()) epsilons = np.linspace(epsilon_start, epsilon_end, epsilon_decay_steps) print('epsion',epsilons.shape) # The policy we're following policy = make_epsilon_greedy_policy( q_estimator, len(VALID_ACTIONS)) # Populate the replay memory with initial experience print("填充 经验池 ...") state = env.get_init_state() #获取初始state:{sent_arry,sent_vec,label,sent_action} turn=0 for i in range(replay_memory_init_size): action_probs = policy(sess=sess, observation=state, epsilon=epsilons[min(0, epsilon_decay_steps-1)]) action=np.argmax(action_probs) print('action:{}'.format(action)) # action = np.random.choice(np.arange(len(action_probs)), p=action_probs) next_state, reward, done= env.step(action_probs,state,turn,max_turn) turn += 1 replay_memory.append((state, action, reward, next_state, done)) if done or turn>max_turn: state = env.get_init_state() turn=0 else: state = next_state # # # Record videos # # Use the gym env Monitor wrapper # env = Monitor(env, # directory=monitor_path, # resume=True, # video_callable=lambda count: count % record_video_every ==0) # total_t = 0 for i_episode in range(num_episodes): # Reset the environment state = env.get_init_state() # One step in the environment turn=0 for t in range(len(replay_memory)): # Epsilon for this time step epsilon = epsilons[min(total_t, epsilon_decay_steps-1)] print('epsilon',epsilon) # Add epsilon to Tensorboard # episode_summary = tf.Summary() # episode_summary.value.add(simple_value=epsilon, tag="epsilon") # q_estimator.summary_writer.add_summary(episode_summary, total_t) # #Maybe update the target estimator if total_t % update_target_estimator_every == 0: copy_model_parameters(sess, q_estimator, target_estimator) print("\nCopied model parameters to target network.") # Print out which step we're on, useful for debugging. # sys.stdout.flush() # # # Take a step action_probs = policy(sess, state, epsilon) # action = np.random.choice(np.arange(len(action_probs)), p=action_probs) action=np.argmax(action_probs) print('\n','###### predict',state['label'],action) next_state, reward, done = env.step(action_probs,state,turn,max_turn) turn+=1 if turn>max_turn: turn=0 state = env.get_init_state() # If our replay memory is full, pop the first element if len(replay_memory) == replay_memory_size: replay_memory.pop(0) # Save transition to replay memory replay_memory.append((state, action, reward, next_state, done)) # Update statistics if i_episode in stats: w=stats[i_episode]['episode_rewards'] w+=reward stats[i_episode]['episode_rewards']=w stats[i_episode]['episode_lengths'] = t else: stats[i_episode]={"episode_rewards":reward,"episode_lengths":t} # Sample a minibatch from the replay memory for _ in range(1): np.random.shuffle(replay_memory) samples=replay_memory[:batch_size] # samples = random.sample(replay_memory, batch_size) states_batch, action_batch, reward_batch, next_states_batch, done_batch=[],[],[],[],[] for ele in samples: states_batch.append(ele[0]) action_batch.append(ele[1]) reward_batch.append(ele[2]) next_states_batch.append(ele[3]) done_batch.append(ele[4]) print('action_batch:{}'.format(action_batch)) # states_batch, action_batch, reward_batch, next_states_batch, done_batch = map(np.array, zip(*samples)) # Calculate q values and targets (Double DQN) q_values_next = q_estimator.predict(sess, next_states_batch) best_actions = np.argmax(q_values_next, axis=1) q_values_next_target = target_estimator.predict(sess, next_states_batch) targets_batch = reward_batch + np.invert(done_batch).astype(np.float32) * \ discount_factor * q_values_next_target[np.arange(batch_size), best_actions] # Perform gradient descent update states_batch = np.array(states_batch) loss = q_estimator.update(sess, states_batch, action_batch, targets_batch) print("\rStep {} ({}) @ Episode {}/{}, loss: {}".format( t, total_t, i_episode + 1, num_episodes, loss), end="") print('targets_batch:{}'.format(targets_batch),'\n') num=float(sum([1 for e in reward_batch if e>=1.0]))/float(len(reward_batch)) print('success:{}'.format(num)) print('done:{}'.format(done_batch)) if done: break state = next_state total_t += 1 turn=0 train_state=env.get_train_state() dev_state=env.get_dev_state() for i in range(max_turn): train_action_probs = policy(sess=sess, observation=train_state, epsilon=epsilons[min(0, epsilon_decay_steps - 1)]) train_next_state, train_reward, train_done = env.step(train_action_probs, train_state, i, max_turn) dev_action_probs = policy(sess=sess, observation=dev_state, epsilon=epsilons[min(0, epsilon_decay_steps - 1)]) dev_next_state, dev_reward, dev_done = env.step(dev_action_probs, dev_state, i, max_turn) train_state=train_next_state dev_state=dev_next_state train_logit=q_estimator.predict(sess=sess,state=train_state) dev_logit=q_estimator.predict(sess=sess,state=dev_state) print('train_logit:{}'.format(train_logit)) # dev_acc,train_acc=q_estimator.dev_predict(sess) # print('#'*10,'dev_acc:{} train:{}'.format(dev_acc,train_acc)) # # Add summaries to tensorboard # episode_summary = tf.Summary() # episode_summary.value.add(simple_value=stats.episode_rewards[i_episode], node_name="episode_reward", tag="episode_reward") # episode_summary.value.add(simple_value=stats.episode_lengths[i_episode], node_name="episode_length", tag="episode_length") # q_estimator.summary_writer.add_summary(episode_summary, total_t) # q_estimator.summary_writer.flush() # # yield total_t, plotting.EpisodeStats( # episode_lengths=stats.episode_lengths[:i_episode+1], # episode_rewards=stats.episode_rewards[:i_episode+1]) # # env.monitor.close() # return stats # def main(_): config = tf.ConfigProto(allow_soft_placement=True) with tf.Session(config=config) as sess: # sess.run(tf.global_variables_initializer()) env = ENV() q_estimator = LstmRl(scope='q_estimator') target_estimator = LstmRl(scope='target_estimator') deep_q_learning(sess=sess,env=env,q_estimator=q_estimator, target_estimator=target_estimator, num_episodes=100, experiment_dir=None) if __name__ == '__main__': tf.app.run() <file_sep>/model/dl_model/model_semantic_match/data_deal.py import os import random from collections import defaultdict base_path = os.path.split(os.path.split(os.path.split(os.path.split(os.path.realpath(__file__))[0])[0])[0])[0] train_path=base_path+'/corpus_data/train_out_char.txt' dev_path=base_path+'/corpus_data/dev_out_char.txt' fw=open('dev.txt','w') datas_dict=defaultdict(list) for line in open(dev_path,'r').readlines(): lines=line.replace('\n','').split('\t') sent=lines[1] intent=lines[3] datas_dict[intent].append(sent) pos_num=0 neg_num=0 keys=list(datas_dict.keys()) for k in datas_dict.keys(): keys.remove(k) other_k=keys # print(other_k) v=datas_dict[k] for i in range(len(v)-1): for j in range(len(v)): print(v[i],'\t\t',v[j],'\t\t',1) pos_num+=1 fw.write(v[i]) fw.write('\t\t') fw.write(v[j]) fw.write('\t\t') fw.write('1') fw.write('\n') # pass for ok in other_k: ov=datas_dict[ok] random.shuffle(ov) for e in ov[:1]: neg_num += 1 print(v[i],'\t\t',e,'\t\t',0) fw.write(v[i]) fw.write('\t\t') fw.write(ov[0]) fw.write('\t\t') fw.write('0') fw.write('\n') # pass keys.append(k) print(pos_num,neg_num)<file_sep>/pre_data_deal.py import re import sys sys.path.append('.') from IntentConfig import Config import logging from jieba import analyse import jieba from collections import OrderedDict logging.basicConfig(level=logging.INFO, format='%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s', datefmt='%a, %d %b %Y %H:%M:%S', filemode='w') _logger=logging.getLogger("Intent_Data_Deal") config=Config() jieba.load_userdict(config.stop_word_path) tfidf=analyse.extract_tags class Pre_Data_Deal(object): ''' 数据预处理 包括:去停用词/ ''' def __init__(self): print(config.port) self.stop_words = [ele.replace('\n', '') for ele in open(config.stop_word_path, 'r').readlines()] self.intent_indice=list(config.root_intent.keys())[-1] intent_dict_=config.root_intent self.intent_dict=OrderedDict() for k,v in intent_dict_.items(): v_=[e.lower() for e in v] self.intent_dict[k]=v_ def pre_data_deal(self,origin_sent): sub_pattern = '你好|.{0,4}老师|.{0,4}年|.{0,4}%|,|谢谢你|谢谢|。|!|?|~' replace_pattern = r'\d{6}' replace_pattern_0 = r'\d.' pattern = '\d{1,3}(\\.|,|、|?)|《|》|?|。' origin_sent=origin_sent.replace('\n','') try: index = origin_sent.split('\t\t')[0] sent = origin_sent.split('\t\t')[1] label = origin_sent.split('\t\t')[2] except Exception as ex: _logger.info('Error sent ',origin_sent) sent = re.subn(sub_pattern, '', sent)[0] sent = sent.split('?')[0].replace(' ', '') sent = re.subn(replace_pattern, 'stock', sent)[0] sent = re.subn(replace_pattern_0, '', sent)[0] sent = re.subn(pattern,'',sent)[0] res_sent='\t\t'.join([index,sent,label]) return res_sent def main(self,sent): return self.pre_data_deal(sent) <file_sep>/model/dl_model/model_lstm_rl/read_confusion.py import pickle data_dict={} for ele in open('../../../corpus_data/意图识别数据_all.txt','r').readlines(): index=ele.split('\t\t')[0] sent=ele.split('\t\t')[1] data_dict[index]=sent dev=pickle.load(open('./dev.p','rb')) # # for k,v in dev.items(): print(k) for k_ele,v_ele in v.items(): if v_ele[0]>=1: print(k_ele) for ele in v_ele[1]: pass # print(data_dict[ele[0]]) # print(ele[2]) print(k_ele,v_ele) print('\n\n') # import xlwt # 创建一个workbook 设置编码 workbook = xlwt.Workbook(encoding = 'utf-8') # 创建一个worksheet for k,v in dev.items(): print(k) worksheet = workbook.add_sheet(k) # 写入excel # 参数对应 行, 列, 值 index=1 for k_ele,v_ele in v.items(): if v_ele[0]>=1: worksheet.write(index,1, k_ele) for ele in v_ele[1]: sent=data_dict[ele[0]] ele=str(ele[1])+'_'+ele[2] worksheet.write(index,2,ele) worksheet.write(index,3,sent) index += 1 # 保存 workbook.save('意图预测结果_4类_20180706.xls') <file_sep>/model/dl_model/model_lstm_rl/read_confusion_train.py import pickle print('#'*100) dev=pickle.load(open('./train.p','rb')) for k,v in dev.items(): print(k) for k_ele,v_ele in v.items(): if v_ele[0]>=1: print(k_ele,v_ele) print('\n')<file_sep>/model/dl_model/model_transfer/lstm_transfer.py import tensorflow as tf import os import numpy as np from tensorflow.python import pywrap_tensorflow from model.dl_model.model_transfer.data_preprocess import Intent_Slot_Data from IntentConfig import Config intent_config=Config() from entity_recognition.ner import EntityRecognition base_path=os.path.split(os.path.split(os.path.split(os.path.split(os.path.realpath(__file__))[0])[0])[0])[0] config = tf.ConfigProto(allow_soft_placement=True) # saver = tf.train.import_meta_graph(base_path+"/save_model/model_lstm_mask/lstm.ckpt.meta") # with tf.Session(config=config) as sess: # saver.restore(sess, base_path+"/save_model/model_lstm_mask/lstm.ckpt") # # # checkpoint_path = os.path.join(base_path+"/save_model/model_lstm_mask/lstm.ckpt") # reader = pywrap_tensorflow.NewCheckpointReader(checkpoint_path) # tf.train.NewCheckpointReader # var_to_shape_map = reader.get_variable_to_shape_map() # for key in var_to_shape_map: # print("tensor_name: ", key) def get_sent_mask(sent_ids, entity_ids): sent_mask = np.zeros_like(sent_ids, dtype=np.float32) for i in range(sent_ids.shape[0]): for j in range(sent_ids.shape[1]): if sent_ids[i, j] > 0 and sent_ids[i, j] not in entity_ids: sent_mask[i, j] = 1.0 elif sent_ids[i, j] > 0 and sent_ids[i, j] in entity_ids: sent_mask[i, j] = 0.5 return sent_mask saver = tf.train.import_meta_graph(base_path+"/save_model/model_lstm_mask/lstm.ckpt.meta") # We can now access the default graph where all our metadata has been loaded graph = tf.get_default_graph() for ele in graph.get_operations(): print(ele.name) # Finally we can retrieve tensors, operations, etc. sent_word_operation = graph.get_tensor_by_name('lstm/sent_word:0') sent_len_operation = graph.get_tensor_by_name('lstm/sent_len:0') sent_mask_operation = graph.get_tensor_by_name('lstm/sent_mask:0') sent_dropout_operation = graph.get_tensor_by_name('lstm/Placeholder:0') sent_intent_y_operation = graph.get_tensor_by_name('lstm/intent_y:0') sent_emb=graph.get_tensor_by_name('lstm/out_layers/dense/BiasAdd:0') sent_emb=tf.layers.dense(sent_emb,79) sent_soft=tf.nn.softmax(sent_emb,1) sent_max=tf.argmax(sent_soft,1) sent_y=tf.argmax(sent_intent_y_operation,1) print(sent_max) print(sent_y) acc= tf.reduce_mean(tf.cast(tf.equal(sent_max,sent_y),tf.float32)) loss=tf.losses.softmax_cross_entropy(onehot_labels=sent_intent_y_operation,logits=sent_emb) train_op=tf.train.AdamOptimizer(0.001).minimize(loss) # sent_word_operation = graph.get_operation_by_name('lstm/sent_word') # sent_len_operation = graph.get_operation_by_name('lstm/sent_len') # sent_mask_operation = graph.get_operation_by_name('lstm/sent_mask') # sent_dropout_operation = graph.get_operation_by_name('lstm/Placeholder') # sent_intent_y_operation = graph.get_operation_by_name('lstm/intent_y') # # # sent_emb=graph.get_operation_by_name('lstm/out_layers/dense/BiasAdd') # train_op = graph.get_operation_by_name('loss/train_op') # hyperparameters = tf.get_collection('hyperparameters') saver_restore = tf.train.import_meta_graph(base_path+"/save_model/model_lstm_mask/lstm.ckpt.meta") with tf.Session(config=config) as sess: sess.run(tf.global_variables_initializer()) saver_restore.restore(sess,base_path+"/save_model/model_lstm_mask/lstm.ckpt") dd = Intent_Slot_Data(train_path=base_path + "/corpus_data/%s" % intent_config.train_name, test_path=base_path + "/corpus_data/%s" % intent_config.dev_name, dev_path=base_path + "/corpus_data/%s" % intent_config.dev_name, batch_size=32, max_length=30, flag='train_new', use_auto_bucket=False, save_model='lstm') ee = EntityRecognition() entity_id = [] for k, v in dd.vocab.items(): if k in ee.entity_dict.keys(): entity_id.append(v) for _ in range(10): sent, slot, intent_label, rel_len, cur_len = dd.next_batch() sent_mask = get_sent_mask(sent, entity_id) loss_, acc_,_ = sess.run([loss, acc,train_op], feed_dict={sent_word_operation: sent, sent_len_operation: rel_len, sent_mask_operation: sent_mask, sent_dropout_operation: 1.0, sent_intent_y_operation: intent_label }) print('train',loss_,acc_) # dev_sent, dev_slot, dev_intent, dev_rel_len, _ = dd.get_dev() # dev_sent_mask = get_sent_mask(dev_sent, entity_id) # # loss_,acc_=sess.run([loss,acc],feed_dict={sent_word_operation:dev_sent, # sent_len_operation:dev_rel_len, # sent_mask_operation:dev_sent_mask, # sent_dropout_operation:1.0, # sent_intent_y_operation:dev_intent # }) # # # print('dev_loss,',loss_,acc_)<file_sep>/IntentConfig.py ''' 配置类 ''' from collections import OrderedDict class Config(object): def __init__(self): self.corpus_name='意图识别数据_all.txt' self.train_name='train_out_char.txt' self.dev_name='dev_out_char.txt' self.ml_classifiers=['SVM','LR']#可选的机器学习模型NB','SVM','KNN','LR','RF','DT' self.dl_classifiers='DLB' self.host='192.168.3.132' self.port=8082 self.entity_level='level_1' self.root_intent=OrderedDict({0:["1宏观预测", "2产品诊断", "3知识方法", "4理财规划", "5时事分析"]}) self.save_model_name='intent_all' self.stop_word_path='./corpus_data/stop_word.txt' self.classifier_dict={'BLSTM':1.0,'SVM':0.5,'LR':0.5,'RF':0.5} #{'intent_1':{}} # self.root_intent_list=['1宏观预测','2产品诊断','3知识方法','4理财规划','5时事分析'] # if self.root_intent not in self.root_intent_list: # raise ValueError('错误的 root_intent') _instance=None def __new__(cls, *args, **kwargs): if not cls._instance: cls._instance=super(Config,cls).__new__(cls,*args,**kwargs) return cls._instance if __name__ == '__main__': config=Config() print(config.root_intent)<file_sep>/model/dl_model/model_lstm_rl/test1.py import tensorflow as tf s=tf.placeholder(dtype=tf.int32) with tf.Session() as sess: print(sess.run(s,feed_dict={s:1}))<file_sep>/dn_pipeline.py ''' 多层pipeline 可对多层意图进行infer或则 ''' from IntentConfig import Config from pipeline_tool import PipelineTool from collections import defaultdict import json #第一层意图infer import time import os import logging if not os.path.exists('./Log/'): os.mkdir('./Log') import time logging.basicConfig(level=logging.INFO, format='%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s', filename='./Log/intent.log', datefmt='%a, %d %b %Y %H:%M:%S', filemode='w') _logger=logging.getLogger("pipeline_tool") class pipeline(object): def __init__(self,config_train_path,config_infer_path): self.config_train_json=json.load(open(config_train_path,'r')) self.config=Config() self.config_infer_json=json.load(open(config_infer_path,'r')) def train_multi(self): ''' 多层 意图 训练 :return: ''' for k,v in self.config_train_json.items(): _logger.info('当前训练的意图层级为:%s 具体配置:%s'%(k,v)) self.config.save_model_name=self.config_train_json[k]['save_model_name'] self.config.root_intent={int(k):v for k,v in self.config_train_json[k]['root_intent'].items()} pipeline_tool=PipelineTool(self.config) pipeline_tool.train() def __infer__(self,sents,config): ''' infer_multi方法类 :param sents: :param config: :return: ''' pipeline_tool_level1 = PipelineTool(config) res_dict = pipeline_tool_level1.infer(sents,config) sentlist_dict = defaultdict(list) for sent, intent in res_dict.items(): sentlist_dict[intent].append(sent) return sentlist_dict def __change_dict__(self,list_dict): ''' 字典转换 'label':[sent1,sent2,...,]->'sent1':label,'sent2':label :param list_dict: :return: ''' new_dict={} for k ,v in list_dict.items(): for e in v: new_dict[e]=k return new_dict def infer_multi(self,sents): ''' 多层 意图 infer :return: ''' fin_dict={} # 第一层意图识别 index="0" save_model_name=self.config_train_json[self.config_infer_json[index]]['save_model_name'] self.config.save_model_name = save_model_name _logger.info('第一层意图识别模型 :%s' %self.config.save_model_name) list_dict = self.__infer__(sents, self.config) if "1" in self.config_infer_json.keys(): for k, v in list_dict.items(): if k in list(self.config_infer_json['1']): self.config.save_model_name = self.config_train_json[k]['save_model_name'] _logger.info('第二层意图识别 %s 的模型 :%s' % (k, self.config.save_model_name)) list_dict_1=self.__infer__(v,self.config) if "2" in self.config_infer_json.keys(): for k_3, v_3 in list_dict_1.items(): if k_3 in list(self.config_infer_json['2']): _logger.info('%s 的模型 :%s' % (k_3, self.config.save_model_name)) self.config.save_model_name = self.config_train_json[k_3]['save_model_name'] list_dict_2 = self.__infer__(v_3, self.config) fin_dict.update(list_dict_2) else: fin_dict.update({k_3:v_3}) else: fin_dict.update(list_dict_1) else: fin_dict.update({k:v}) else: fin_dict.update(list_dict) fin_dict=self.__change_dict__(fin_dict) return fin_dict # # 第一层意图识别 # level_1_save_model=self.config_train_json[self.config_infer_json['0']]['save_model_name'] # self.config.save_model_name=level_1_save_model # res_dict=self.__infer__(sents,self.config) # # sentlist_dict=defaultdict(list) # for sent,intent in res_dict.items(): # sentlist_dict[intent].append(sent) # # # for k,v in sentlist_dict.items(): # if k in list(self.config_infer_json['1']): # self.config.save_model_name=self.config_train_json[k]['save_model_name'] # _logger.info('%s 的模型 :%s'%(k,self.config.save_model_name)) # model=PipelineTool(self.config) # rr=model.infer(v) # rr_dict = defaultdict(list) # fin_dict.update(rr) # for sent, intent in rr.items(): # rr_dict[intent].append(sent) # for k_3,v_3 in rr_dict.items(): # if k_3 in list(self.config_infer_json['2']): # _logger.info('%s 的模型 :%s' % (k, self.config.save_model_name)) # self.config.save_model_name = self.config_train_json[k_3]['save_model_name'] # model = PipelineTool(self.config) # rr = model.infer(v) # fin_dict.update(rr) # # # print(fin_dict) if __name__ == '__main__': pipeline=pipeline('./train_config.json','./infer_config.json') pipeline.train_multi() # # # datas=['2018年A股是牛市吗?','能不能分析一下原油后续的走势?','微信刚出的那款保险怎么样','如何选择P2P平台?'] # datas=[] labels=[] origin_dict={} for ele in open('./corpus_data/意图识别数据_all.txt','r').readlines(): # index=ele.replace('\n','').split('\t\t')[0] ele1=ele.replace('\n','').split('\t\t')[1] origin_dict[str(index)]=ele1 # datas.append(ele1) # label=ele.replace('\n','').split('\t\t')[2] # label=label.replace('##None##None','').replace('##None','').replace('##','_') # labels.append(label) for ele in open('./corpus_data/dev_out_char.txt','r').readlines(): index=ele.replace('\n','').split('\t')[0] ele1=origin_dict[str(index)] # ele1=ele.replace('\n','').split('\t')[1].strip() datas.append(ele1) label=ele.replace('\n','').split('\t')[3] label=label.replace('##None##None','').replace('##None','').replace('##','_') labels.append(label) true_dict={} for e,label in zip(datas,labels): true_dict[e]=label # # # start_time=time.time() # print('开始预测',start_time) # import pickle pre_dict=pipeline.infer_multi(datas) pickle.dump(pre_dict,open('./pre_dict.p','wb')) end_time=time.time() # def com(): # avg=0.0 # total=0.0 # count=0.0 # while True: # num=yield avg # total+=num # count+=1 # avg=float(total)/float(count) # # com_avg=com() # next(com_avg) # for k,v in pre_dict.items(): # if k in true_dict and v!=true_dict[k]: # print(com_avg.send(0)) # elif k in true_dict and v == true_dict[k]: # print(com_avg.send(1)) import pickle # true_dict=pickle.load(open('./true_dict.p','rb')) pre_dict=pickle.load(open('./pre_dict.p','rb')) def com(): avg=0.0 total=0.0 count=0.0 while True: num=yield avg total+=num count+=1 avg=float(total)/float(count) com_avg=com() next(com_avg) for k,v in pre_dict.items(): if k in true_dict and v!=true_dict[k]: if true_dict[k].__contains__('5时事分析') and pre_dict[k].__contains__('5时事分析'): print(com_avg.send(1)) elif true_dict[k].__contains__('4理财规划') and pre_dict[k].__contains__('4理财规划'): print(com_avg.send(1)) elif true_dict[k].__contains__('2产品诊断') and pre_dict[k].__contains__('2产品诊断'): print(com_avg.send(1)) elif true_dict[k].__contains__('1宏观预测_基金') and pre_dict[k].__contains__('1宏观预测_基金'): print(com_avg.send(1)) elif true_dict[k].__contains__('1宏观预测_贵金属') and pre_dict[k].__contains__('1宏观预测_贵金属'): print(com_avg.send(1)) else: print(com_avg.send(0)) print(k, '\t\t', true_dict[k], '\t\t', pre_dict[k]) elif k in true_dict and v == true_dict[k]: print(com_avg.send(1)) pickle.dump(true_dict,open('./true_dict.p','wb')) pickle.dump(pre_dict,open('./pre_dict.p','wb')) # print(pre_dict) # print(end_time-start_time) # config.save_model_name='intent_all' # config.entity_level='level_1' # # pipeline_tool=PipelineTool(config=config) # # sents=['2018年A股是牛市吗?','能不能分析一下原油后续的走势?'] # # res_level1=pipeline_tool.infer(sents) # # print(res_level1) <file_sep>/hgyc_level2.py import jieba import re entity_types=[e.replace('\n','') for e in open('./entity_type_level_2.txt','r').readlines()] for e in entity_types: jieba.load_userdict('./entity_data/level_2/%s.txt'%e) # astock=[e.replace('\n','') for e in open('./entity_data/level_2/Astock.txt','r').readlines()] #A股 # dzsp=[e.replace('\n','') for e in open('./entity_data/level_2/Dazongshanpin.txt','r').readlines()]#大宗商品 # fdc=[e.replace('\n','') for e in open('./entity_data/level_2/Fandichan.txt','r').readlines()]#房地产 # gjs=[e.replace('\n','') for e in open('./entity_data/level_2/Fandichan.txt','r').readlines()] #贵金属 # hlwlc=[e.replace('\n','') for e in open('./entity_data/level_2/Hulianwanglicai.txt','r').readlines()]#互联网理财 # hb=[e.replace('\n','') for e in open('./entity_data/level_2/Huobi.txt','r').readlines()]#货币 # jj=[e.replace('\n','') for e in open('./entity_data/level_2/Jijin.txt','r').readlines()]#基金 # # # # class hgyc(object): # # # def __init__(self): # self.astock="|".join(astock) # self.dzsp="|".join(dzsp) # self.fdc="|".join(fdc) # self.gjs='|'.join(gjs) # self.hlwlc='|'.join(hlwlc) # self.hb='|'.join(hb) # self.jj='|'.join(jj) # # def infer(self,sent): # # ''' # # :param sent: # :return: # ''' # # # 贵金属 # pattern_0='(%s)'%self.gjs # if re.search(pattern_0,sent): # return '贵金属' # # # 大宗商品 # pattern_1='%s'%self.dzsp # if re.search(pattern_1,sent): # return '大宗商品' # # #房产 # pattern_2='(%s).*房|买房'%self.fdc # if re.search(pattern_2,sent): # return '房产' # if __name__ == '__main__': s={ 'level_1':{'save_model_name':'intent_all', 'root_intent':{0:['1宏观预测','2产品诊断','3知识方法','4理财规划','5时事分析']}}, 'hgyc_level_1':{'save_model_name':'hgyc_level_1', 'root_intent':{0:['1宏观预测'],1:['A股','大宗商品','房产','房地产','个股','贵金属','海外房产','宏观','互联网理财','黄金','基金','数字货币','行业']}} } import json json.dump(s,open('./config.json','w'),ensure_ascii=False) <file_sep>/model/dl_model/model_semantic_match/model_fun.py import tensorflow as tf import os import numpy as np from sklearn.metrics import classification_report,precision_recall_fscore_support def embedding(sent,num,emb_dim,name,reuse=False): ''' 词嵌入 :param sent: :param num: :param emb_dim: :param name: :return: ''' with tf.variable_scope(name_or_scope=name,reuse=reuse): embedding=tf.get_variable(name='sent_emb',shape=(num,emb_dim),initializer=tf.random_normal_initializer,trainable=True) emb=tf.nn.embedding_lookup(embedding,sent) return emb,embedding def sent_encoder(sent_word_emb,num,hidden_dim,sequence_length,name,dropout,reuse=False): ''' 句编码 :param sent_word_emb: :param hidden_dim: :param name: :return: ''' with tf.variable_scope(name_or_scope=name,reuse=reuse): lstm_cell=tf.contrib.rnn.BasicLSTMCell(hidden_dim) lstm_cell_1=tf.contrib.rnn.BasicLSTMCell(hidden_dim) lstm_cell=tf.nn.rnn_cell.DropoutWrapper(lstm_cell, output_keep_prob=dropout) lstm_cell_1=tf.nn.rnn_cell.DropoutWrapper(lstm_cell_1, output_keep_prob=dropout) encoder,_=tf.nn.bidirectional_dynamic_rnn( lstm_cell, lstm_cell_1, sent_word_emb, dtype=tf.float32, sequence_length=sequence_length, ) # encoder,_=tf.nn.static_rnn(lstm_cell,sent_word_embs,sequence_length=sequence_length,dtype=tf.float32) encoder=tf.concat(encoder,2) # encoder_fw,encoder_bw=encoder[0],encoder[1] # encoder_fw=last_relevant_output(encoder_fw,sequence_length) # encoder_bw=last_relevant_output(encoder_bw,sequence_length) # encoder=tf.concat([encoder_fw,encoder_bw],1) # encoder=tf.unstack(encoder,num,1) # encoder=tf.layers.dense(encoder,100,activation=tf.nn.tanh) # encoder=tf.unstack(encoder,num,1) return encoder def sigmiod_layer(input,hidden_dim,name,reuse=False): with tf.variable_scope(name_or_scope=name,reuse=reuse): w=tf.get_variable(name='w',initializer=tf.random_normal_initializer,shape=(2*hidden_dim,300)) b=tf.get_variable(name='b',initializer=tf.random_normal_initializer,shape=(300,)) return tf.nn.xw_plus_b(input,w,b) def last_relevant_output(output, sequence_length): """ Given the outputs of a LSTM, get the last relevant output that is not padding. We assume that the last 2 dimensions of the input represent (sequence_length, hidden_size). Parameters ---------- output: Tensor A tensor, generally the output of a tensorflow RNN. The tensor index sequence_lengths+1 is selected for each instance in the output. sequence_length: Tensor A tensor of dimension (batch_size, ) indicating the length of the sequences before padding was applied. Returns ------- last_relevant_output: Tensor The last relevant output (last element of the sequence), as retrieved by the output Tensor and indicated by the sequence_length Tensor. """ with tf.name_scope("last_relevant_output"): batch_size = tf.shape(output)[0] max_length = tf.shape(output)[-2] #seq_len out_size = int(output.get_shape()[-1]) #dim index = tf.range(0, batch_size) * max_length + (sequence_length - 1) print(index) flat = tf.reshape(output, [-1, out_size]) relevant = tf.gather(flat, index) return relevant def mean_pool(input_tensor, sequence_length=None): """ Given an input tensor (e.g., the outputs of a LSTM), do mean pooling over the last dimension of the input. For example, if the input was the output of a LSTM of shape (batch_size, sequence length, hidden_dim), this would calculate a mean pooling over the last dimension (taking the padding into account, if provided) to output a tensor of shape (batch_size, hidden_dim). Parameters ---------- input_tensor: Tensor An input tensor, preferably the output of a tensorflow RNN. The mean-pooled representation of this output will be calculated over the last dimension. sequence_length: Tensor, optional (default=None) A tensor of dimension (batch_size, ) indicating the length of the sequences before padding was applied. Returns ------- mean_pooled_output: Tensor A tensor of one less dimension than the input, with the size of the last dimension equal to the hidden dimension state size. """ with tf.name_scope("mean_pool"): # shape (batch_size, sequence_length) input_tensor_sum = tf.reduce_sum(input_tensor, axis=-2) # If sequence_length is None, divide by the sequence length # as indicated by the input tensor. if sequence_length is None: sequence_length = tf.shape(input_tensor)[-2] # Expand sequence length from shape (batch_size,) to # (batch_size, 1) for broadcasting to work. expanded_sequence_length = tf.cast(tf.expand_dims(sequence_length, -1), "float32") + 1e-08 # Now, divide by the length of each sequence. # shape (batch_size, sequence_length) mean_pooled_input = (input_tensor_sum / expanded_sequence_length) return mean_pooled_input def match_attention_ops(encoder_0_t,encoder_1,encoder_1_mask,hidden_dim,self_hidden_dim): ''' match_attention的辅助函数 :param encoder_0_t: :param encoder_1: :param encoder_1_mask: :return: ''' encoder_0_t=tf.expand_dims(encoder_0_t,1) with tf.variable_scope(name_or_scope='ops'): w_0=tf.get_variable(name='w_0',shape=(2*hidden_dim,self_hidden_dim),initializer=tf.random_normal_initializer) w_1=tf.get_variable(name='w_1',shape=(2*hidden_dim,self_hidden_dim),initializer=tf.random_normal_initializer) v=tf.get_variable(name='v',shape=(self_hidden_dim,1),initializer=tf.random_normal_initializer) encoder_0_t_=tf.einsum('ijk,kl->ijl',encoder_0_t,w_0) encoder_1_=tf.einsum('ijk,kl->ijl',encoder_1,w_1) encoder=tf.nn.tanh(tf.add(encoder_1_,encoder_0_t_)) logit=tf.einsum('ijk,kl->ijl',encoder,v) logit=tf.squeeze(logit,-1) logit=tf.multiply(logit,encoder_1_mask) soft_logit=tf.nn.softmax(logit,1) soft_logit=tf.expand_dims(soft_logit,-1) out=tf.einsum('ijk,ijl->ikl',encoder_1,soft_logit) out=tf.squeeze(out,-1) return out def match_attention(encoder_0,encoder_1,encoder_0_mask,encoder_1_mask,hidden_dim,dropout,name,seq_len,reuse=False): ''' match_attention, encoder_0的每个step 以encoder_1的attention作为输入 :param encoder_0: :param encoder_1: :param encoder_0_mask: :param encoder_1_mask: :return: ''' with tf.variable_scope(name_or_scope=name,reuse=reuse) as scope: cell=tf.contrib.rnn.BasicLSTMCell(hidden_dim) cell=tf.nn.rnn_cell.DropoutWrapper(cell=cell,input_keep_prob=dropout) encoder_0_list=tf.unstack(encoder_0,seq_len,1) encoder_ele=encoder_0_list[0][:,:hidden_dim] init_c=tf.zeros_like(encoder_ele) init_h=tf.zeros_like(encoder_ele) H=[init_h] C=[init_c] output=[] for t in range(len(encoder_0_list)): if t>0: scope.reuse_variables() encoder_0_t=encoder_0_list[t] h,c=H[-1],C[-1] state=(h,c) attention_t=match_attention_ops(encoder_0_t,encoder_1,encoder_1_mask,hidden_dim,hidden_dim) input_t=tf.concat([encoder_0_t,attention_t],1) out_t,state_t=cell(input_t,state) h_t,c_t=state_t[0],state_t[1] H.append(h_t) C.append(c_t) output.append(out_t) out=tf.stack(output,1) return out def self_attention(lstm_outs,sent_mask,reuse=False): ''' attention :param lstm_outs: :param sent_mask: :return: ''' with tf.variable_scope(name_or_scope='attention',reuse=reuse): if isinstance(lstm_outs,list): lstm_outs=tf.stack(lstm_outs,1) V=tf.get_variable(name='v',shape=(300,1),initializer=tf.random_normal_initializer) logit=tf.layers.dense(lstm_outs,300,activation=tf.nn.tanh,use_bias=True,reuse=reuse) logit=tf.einsum('ijk,kl->ijl',logit,V) logit=tf.squeeze(logit,-1) logit=tf.multiply(logit,sent_mask) soft_logit=tf.nn.softmax(logit,1) soft_logit=tf.expand_dims(soft_logit,-1) attention_out=tf.einsum('ijk,ijl->ilk',lstm_outs,soft_logit) attention_out=tf.squeeze(attention_out,1) return attention_out def cosin_com(sent_enc,label_enc,label_num): ''' 相似度计算 :param sent_enc: :param label_enc: :return: ''' sent=tf.layers.dense(sent_enc,300) label=tf.layers.dense(label_enc,300) sent_emb_norm = tf.sqrt(tf.reduce_sum(tf.square(sent), axis=1)) label=tf.unstack(label,label_num,0) cosins = [] # 内积 for ele in label: intent_norm = tf.sqrt(tf.reduce_sum(tf.square(ele))) ele = tf.expand_dims(ele, -1) sent_intent = tf.matmul(sent, ele) sent_intent = tf.reshape(sent_intent, [-1, ]) cosin = sent_intent / (sent_emb_norm * intent_norm) cosins.append(cosin) cosin = tf.stack(cosins, 1) return cosin def label_sent_attention(sent_encoder,label_emb,sent_mask): sent_encoder=tf.layers.dense(sent_encoder,300) label_emb=tf.layers.dense(label_emb,300) sent_encoder=tf.multiply(sent_encoder,tf.expand_dims(sent_mask,-1)) tran_label_emb=tf.transpose(label_emb,[1,0]) sent_encoder=tf.nn.l2_normalize(sent_encoder,-1) tran_label_emb=tf.nn.l2_normalize(tran_label_emb,0) G=tf.einsum('ijk,kl->ijl',sent_encoder,tran_label_emb) G=tf.expand_dims(G,-1) fliter_w=tf.Variable(tf.random_uniform(shape=(8,1,1,1),dtype=tf.float32)) max_G=tf.nn.relu(tf.nn.conv2d(G,filter=fliter_w,strides=[1,1,1,1],padding='SAME')) max_G=tf.squeeze(max_G,-1) max_G=tf.reduce_max(max_G,axis=-1,keep_dims=True) mask_G=tf.multiply(max_G,tf.expand_dims(sent_mask,-1)) soft_mask_G=tf.clip_by_value(tf.nn.softmax(mask_G,1),1e-5,1.0) out=tf.einsum('ijk,ijl->ikl',sent_encoder,soft_mask_G) out=tf.squeeze(out,-1) return out def output_layers(inputs,out_dim,name,reuse): with tf.variable_scope(name_or_scope=name,reuse=reuse): return tf.layers.dense(inputs,out_dim) def loss_function(cosin,label): soft_logit = tf.nn.softmax(cosin, 1) intent = tf.cast(label, tf.float32) intent_loss = -tf.reduce_sum(intent * tf.log(tf.clip_by_value(soft_logit, 1e-5, 1.0, name=None))) return intent_loss,soft_logit def intent_acc(pre,label,id2intent): ''' 获取intent准确率 :param pre: :param label: :return: ''' pre_ = np.argmax(pre, 1) label_ = np.argmax(label, 1) ss=[[int(k),v] for k,v in id2intent.items()] ss.sort(key=lambda x:x[0],reverse=False) s1=[e[1] for e in ss] # print(classification_report(y_true=label_,y_pred=pre_,target_names=s1)) all_sum = len(label_) num = sum([1 for e, e1 in zip(pre_, label_) if e == e1]) return float(num) / float(all_sum) <file_sep>/model/dl_model/model_semantic_match/tt.py import numpy as np # s1=np.array([[1,2,3],[3,4,5]]) # # s2=np.tile(s1,(2,1)) # # s3=np.repeat(s1,60,axis=0) # # print(s3.shape) from collections import Counter,OrderedDict s=[1,1,1,22,2,2,3,3,3] ss=[[k,v] for k,v in Counter(s).items()] ss.sort(key=lambda x:x[1],reverse=True) print(ss[0][0]) <file_sep>/train_dl_B.sh #!/bash/bin python model/dl_model/model_lstm_mask/lstm_mask.py --mask_mod=train <file_sep>/model/lda_model/lda.py from gensim.models import ldamodel from gensim import corpora, models import os import re base_path=os.path.split(os.path.split(os.path.split(os.path.realpath(__file__))[0])[0])[0] stop_word=[e.replace('\n','') for e in open(base_path+'/corpus_data/stop_word.txt')] class LDA(object): def __init__(self): pass def data_get(self,data_path): tokens=[] sub_pattern='eos|bos' sents=[] labels=[] for ele in open(data_path,'r').readlines(): ele=ele.replace('\n','') try: sent=re.subn(sub_pattern,'',ele.split('\t')[0].lower())[0] label=ele.split('\t')[2] labels.append(label) sents.append(sent) tokens.append([ e for e in sent.split(' ') if e not in stop_word]) except: pass # 得到文档-单词矩阵 (直接利用统计词频得到特征) dictionary = corpora.Dictionary(tokens) # 得到单词的ID,统计单词出现的次数以及统计信息 # print type(dictionary) # 得到的是gensim.corpora.dictionary.Dictionary的class类型 texts = [dictionary.doc2bow(text) for text in tokens] # 将dictionary转化为一个词袋,得到文档-单词矩阵 texts_tf_idf = models.TfidfModel(texts)[texts] # 文档的tf-idf形式(训练加转换的模式) lda=models.ldamodel.LdaModel.load('./lda.model') # lda = models.ldamodel.LdaModel(corpus=texts, id2word=dictionary, num_topics=6, update_every=0, passes=20,iterations=100) texts_lda = lda[texts_tf_idf] lda.save('lda.model') lda_word=lda.print_topics(num_topics=6, num_words=10) for ele in lda_word: print(ele) for ss,ll,doc in zip(sents,labels,texts_lda): print(ss,ll,doc) print('\n\n') if __name__ == '__main__': lda=LDA() lda.data_get(base_path+'/corpus_data/train_out_char.txt')<file_sep>/model/dl_model/model_center_loss/model_fun.py import tensorflow as tf import os import numpy as np from sklearn.metrics import classification_report,precision_recall_fscore_support def get_center_loss(features, labels, alpha, num_classes): """获取center loss及center的更新op Arguments: features: Tensor,表征样本特征,一般使用某个fc层的输出,shape应该为[batch_size, feature_length]. labels: Tensor,表征样本label,非one-hot编码,shape应为[batch_size]. alpha: 0-1之间的数字,控制样本类别中心的学习率,细节参考原文. num_classes: 整数,表明总共有多少个类别,网络分类输出有多少个神经元这里就取多少. Return: loss: Tensor,可与softmax loss相加作为总的loss进行优化. centers: Tensor,存储样本中心值的Tensor,仅查看样本中心存储的具体数值时有用. centers_update_op: op,用于更新样本中心的op,在训练时需要同时运行该op,否则样本中心不会更新 """ # 获取特征的维数,例如256维 len_features = features.get_shape()[1] # 建立一个Variable,shape为[num_classes, len_features],用于存储整个网络的样本中心, # 设置trainable=False是因为样本中心不是由梯度进行更新的 centers = tf.get_variable('centers', [num_classes, len_features], dtype=tf.float32, initializer=tf.constant_initializer(0), trainable=False) # 将label展开为一维的,输入如果已经是一维的,则该动作其实无必要 labels = tf.reshape(labels, [-1]) # 根据样本label,获取mini-batch中每一个样本对应的中心值 centers_batch = tf.gather(centers, labels) # 计算loss loss = tf.nn.l2_loss(features - centers_batch) # 当前mini-batch的特征值与它们对应的中心值之间的差 diff = centers_batch - features # 获取mini-batch中同一类别样本出现的次数,了解原理请参考原文公式(4) unique_label, unique_idx, unique_count = tf.unique_with_counts(labels) appear_times = tf.gather(unique_count, unique_idx) appear_times = tf.reshape(appear_times, [-1, 1]) diff = diff / tf.cast((1 + appear_times), tf.float32) diff = alpha * diff centers_update_op = tf.scatter_sub(centers, labels, diff) return loss, centers, centers_update_op def embedding(sent,num,emb_dim,name): ''' 词嵌入 :param sent: :param num: :param emb_dim: :param name: :return: ''' with tf.variable_scope(name_or_scope=name): embedding=tf.Variable(tf.random_uniform(shape=(num,emb_dim),dtype=tf.float32),name='sent_emb',trainable=True) emb=tf.nn.embedding_lookup(embedding,sent) return emb def sent_encoder(sent_word_emb,num,hidden_dim,sequence_length,name): ''' 句编码 :param sent_word_emb: :param hidden_dim: :param name: :return: ''' with tf.variable_scope(name_or_scope=name): sent_word_embs=tf.unstack(sent_word_emb,num,1) lstm_cell=tf.contrib.rnn.BasicLSTMCell(hidden_dim) lstm_cell_1=tf.contrib.rnn.BasicLSTMCell(hidden_dim) encoder,_=tf.nn.bidirectional_dynamic_rnn( lstm_cell, lstm_cell_1, sent_word_emb, dtype=tf.float32, sequence_length=sequence_length, ) # encoder,_=tf.nn.static_rnn(lstm_cell,sent_word_embs,sequence_length=sequence_length,dtype=tf.float32) encoder=tf.concat(encoder,2) encoder=tf.unstack(encoder,num,1) # encoder=tf.layers.dense(encoder,100,activation=tf.nn.tanh) # encoder=tf.unstack(encoder,num,1) return encoder def self_attention(lstm_outs,sent_mask): ''' attention :param lstm_outs: :param sent_mask: :return: ''' with tf.variable_scope(name_or_scope='attention'): if isinstance(lstm_outs,list): lstm_outs=tf.stack(lstm_outs,1) V=tf.Variable(tf.random_uniform(shape=(300,1),dtype=tf.float32)) logit=tf.layers.dense(lstm_outs,300,activation=tf.nn.tanh,use_bias=True) logit=tf.einsum('ijk,kl->ijl',logit,V) logit=tf.squeeze(logit,-1) logit=tf.multiply(logit,sent_mask) soft_logit=tf.nn.softmax(logit,1) soft_logit=tf.expand_dims(soft_logit,-1) attention_out=tf.einsum('ijk,ijl->ilk',lstm_outs,soft_logit) attention_out=tf.squeeze(attention_out,1) return attention_out def cosin_com(sent_enc,label_enc,label_num): ''' 相似度计算 :param sent_enc: :param label_enc: :return: ''' sent=tf.layers.dense(sent_enc,300) label=tf.layers.dense(label_enc,300) sent_emb_norm = tf.sqrt(tf.reduce_sum(tf.square(sent), axis=1)) label=tf.unstack(label,label_num,0) cosins = [] # 内积 for ele in label: intent_norm = tf.sqrt(tf.reduce_sum(tf.square(ele))) ele = tf.expand_dims(ele, -1) sent_intent = tf.matmul(sent, ele) sent_intent = tf.reshape(sent_intent, [-1, ]) cosin = sent_intent / (sent_emb_norm * intent_norm) cosins.append(cosin) cosin = tf.stack(cosins, 1) return cosin def label_sent_attention(sent_encoder,label_emb,sent_mask): sent_encoder=tf.layers.dense(sent_encoder,300) label_emb=tf.layers.dense(label_emb,300) sent_encoder=tf.multiply(sent_encoder,tf.expand_dims(sent_mask,-1)) tran_label_emb=tf.transpose(label_emb,[1,0]) sent_encoder=tf.nn.l2_normalize(sent_encoder,-1) tran_label_emb=tf.nn.l2_normalize(tran_label_emb,0) G=tf.einsum('ijk,kl->ijl',sent_encoder,tran_label_emb) G=tf.expand_dims(G,-1) fliter_w=tf.Variable(tf.random_uniform(shape=(8,1,1,1),dtype=tf.float32)) max_G=tf.nn.relu(tf.nn.conv2d(G,filter=fliter_w,strides=[1,1,1,1],padding='SAME')) max_G=tf.squeeze(max_G,-1) max_G=tf.reduce_max(max_G,axis=-1,keep_dims=True) mask_G=tf.multiply(max_G,tf.expand_dims(sent_mask,-1)) soft_mask_G=tf.clip_by_value(tf.nn.softmax(mask_G,1),1e-5,1.0) out=tf.einsum('ijk,ijl->ikl',sent_encoder,soft_mask_G) out=tf.squeeze(out,-1) return out def output_layers(inputs,out_dim,name,reuse): with tf.variable_scope(name_or_scope=name,reuse=reuse): return tf.layers.dense(inputs,out_dim) def loss_function(cosin,label): soft_logit = tf.nn.softmax(cosin, 1) intent = tf.cast(label, tf.float32) intent_loss = -tf.reduce_sum(intent * tf.log(tf.clip_by_value(soft_logit, 1e-5, 1.0, name=None))) return intent_loss,soft_logit def intent_acc(pre,label,id2intent): ''' 获取intent准确率 :param pre: :param label: :return: ''' pre_ = np.argmax(pre, 1) label_ = np.argmax(label, 1) ss=[[int(k),v] for k,v in id2intent.items()] ss.sort(key=lambda x:x[0],reverse=False) s1=[e[1] for e in ss] # print(classification_report(y_true=label_,y_pred=pre_,target_names=s1)) all_sum = len(label_) num = sum([1 for e, e1 in zip(pre_, label_) if e == e1]) return float(num) / float(all_sum) def accuray(pre_label_soft,label): pre_ = np.argmax(pre_label_soft, 1) num=np.sum(np.equal(pre_,label)) acc=float(num)/float(pre_label_soft.shape[0]) return acc def last_relevant_output(output, sequence_length): """ Given the outputs of a LSTM, get the last relevant output that is not padding. We assume that the last 2 dimensions of the input represent (sequence_length, hidden_size). Parameters ---------- output: Tensor A tensor, generally the output of a tensorflow RNN. The tensor index sequence_lengths+1 is selected for each instance in the output. sequence_length: Tensor A tensor of dimension (batch_size, ) indicating the length of the sequences before padding was applied. Returns ------- last_relevant_output: Tensor The last relevant output (last element of the sequence), as retrieved by the output Tensor and indicated by the sequence_length Tensor. """ with tf.name_scope("last_relevant_output"): batch_size = tf.shape(output)[0] max_length = tf.shape(output)[-2] #seq_len out_size = int(output.get_shape()[-1]) #dim index = tf.range(0, batch_size) * max_length + (sequence_length - 1) print(index) flat = tf.reshape(output, [-1, out_size]) relevant = tf.gather(flat, index) return relevant def positional_encoding(inputs, num_units, zero_pad=True, scale=True, scope="positional_encoding", reuse=None): '''Sinusoidal Positional_Encoding. Args: inputs: A 2d Tensor with shape of (N, T). num_units: Output dimensionality zero_pad: Boolean. If True, all the values of the first row (id = 0) should be constant zero scale: Boolean. If True, the output will be multiplied by sqrt num_units(check details from paper) scope: Optional scope for `variable_scope`. reuse: Boolean, whether to reuse the weights of a previous layer by the same name. Returns: A 'Tensor' with one more rank than inputs's, with the dimensionality should be 'num_units' ''' N, T = inputs.get_shape().as_list() with tf.variable_scope(scope, reuse=reuse): position_ind = tf.tile(tf.expand_dims(tf.range(T), 0), [N, 1]) # First part of the PE function: sin and cos argument position_enc = np.array([ [pos / np.power(10000, 2. * i / num_units) for i in range(num_units)] for pos in range(T)]) # Second part, apply the cosine to even columns and sin to odds. position_enc[:, 0::2] = np.sin(position_enc[:, 0::2]) # dim 2i position_enc[:, 1::2] = np.cos(position_enc[:, 1::2]) # dim 2i+1 # Convert to a tensor lookup_table = tf.convert_to_tensor(position_enc) if zero_pad: lookup_table = tf.concat((tf.zeros(shape=[1, num_units]), lookup_table[1:, :]), 0) outputs = tf.nn.embedding_lookup(lookup_table, position_ind) if scale: outputs = outputs * num_units ** 0.5 return outputs # ? def normalize(inputs, epsilon=1e-8, scope="ln", reuse=None): '''Applies layer normalization. Args: inputs: A tensor with 2 or more dimensions, where the first dimension has `batch_size`. epsilon: A floating number. A very small number for preventing ZeroDivision Error. scope: Optional scope for `variable_scope`. reuse: Boolean, whether to reuse the weights of a previous layer by the same name. Returns: A tensor with the same shape and data dtype as `inputs`. ''' with tf.variable_scope(scope, reuse=reuse): inputs_shape = inputs.get_shape() params_shape = inputs_shape[-1:] mean, variance = tf.nn.moments(inputs, [-1], keep_dims=True) beta = tf.Variable(tf.zeros(params_shape)) gamma = tf.Variable(tf.ones(params_shape)) normalized = (inputs - mean) / ((variance + epsilon) ** (.5)) outputs = gamma * normalized + beta return outputs def multihead_attention(queries, keys, num_units=None, num_heads=8, dropout_rate=0.1, is_training=True, causality=False, scope="multihead_attention", reuse=None): '''Applies multihead attention. Args: queries: A 3d tensor with shape of [N, T_q, C_q]. keys: A 3d tensor with shape of [N, T_k, C_k]. num_units: A scalar. Attention size. dropout_rate: A floating point number. is_training: Boolean. Controller of mechanism for dropout. causality: Boolean. If true, units that reference the future are masked. num_heads: An int. Number of heads. scope: Optional scope for `variable_scope`. reuse: Boolean, whether to reuse the weights of a previous layer by the same name. Returns A 3d tensor with shape of (N, T_q, C) ''' # 其中x,y的shape为[N,T],N即batch_size的大小,T为最大句子长度maxlen,默认为10 # # # with tf.variable_scope(scope, reuse=reuse): # Set the fall back option for num_units if num_units is None: num_units = queries.get_shape().as_list[-1] # Linear projections Q = tf.layers.dense(queries, num_units, activation=tf.nn.relu) # (N, T_q, C) K = tf.layers.dense(keys, num_units, activation=tf.nn.relu) # (N, T_k, C) V = tf.layers.dense(keys, num_units, activation=tf.nn.relu) # (N, T_k, C) # Split and concat Q_ = tf.concat(tf.split(Q, num_heads, axis=2), axis=0) # (h*N, T_q, C/h) K_ = tf.concat(tf.split(K, num_heads, axis=2), axis=0) # (h*N, T_k, C/h) V_ = tf.concat(tf.split(V, num_heads, axis=2), axis=0) # (h*N, T_k, C/h) # Multiplication outputs = tf.matmul(Q_, tf.transpose(K_, [0, 2, 1])) # (h*N, T_q, T_k) # Scale outputs = outputs / (K_.get_shape().as_list()[-1] ** 0.5) # Key Masking key_masks = tf.sign(tf.abs(tf.reduce_sum(keys, axis=-1))) # (N, T_k) key_masks = tf.tile(key_masks, [num_heads, 1]) # (h*N, T_k) key_masks = tf.tile(tf.expand_dims(key_masks, 1), [1, tf.shape(queries)[1], 1]) # (h*N, T_q, T_k) paddings = tf.ones_like(outputs) * (-2 ** 32 + 1) outputs = tf.where(tf.equal(key_masks, 0), paddings, outputs) # (h*N, T_q, T_k) # Causality = Future blinding if causality: diag_vals = tf.ones_like(outputs[0, :, :]) # (T_q, T_k) tril = tf.contrib.linalg.LinearOperatorLowerTriangular(diag_vals).to_dense() # (T_q, T_k) masks = tf.tile(tf.expand_dims(tril, 0), [tf.shape(outputs)[0], 1, 1]) # (h*N, T_q, T_k) paddings = tf.ones_like(masks) * (-2 ** 32 + 1) outputs = tf.where(tf.equal(masks, 0), paddings, outputs) # (h*N, T_q, T_k) # Activation outputs = tf.nn.softmax(outputs) # (h*N, T_q, T_k) # Query Masking query_masks = tf.sign(tf.abs(tf.reduce_sum(queries, axis=-1))) # (N, T_q) query_masks = tf.tile(query_masks, [num_heads, 1]) # (h*N, T_q) query_masks = tf.tile(tf.expand_dims(query_masks, -1), [1, 1, tf.shape(keys)[1]]) # (h*N, T_q, T_k) outputs *= query_masks # broadcasting. (N, T_q, C) # Dropouts outputs = tf.layers.dropout(outputs, rate=dropout_rate, training=tf.convert_to_tensor(is_training)) # Weighted sum outputs = tf.matmul(outputs, V_) # ( h*N, T_q, C/h) # Restore shape outputs = tf.concat(tf.split(outputs, num_heads, axis=0), axis=2) # (N, T_q, C) # Residual connection outputs += queries # Normalize outputs = normalize(outputs) # (N, T_q, C) return outputs def feedforward(inputs, num_units=[2048, 512], scope="multihead_attention", reuse=None): '''Point-wise feed forward net. Args: inputs: A 3d tensor with shape of [N, T, C]. num_units: A list of two integers. scope: Optional scope for `variable_scope`. reuse: Boolean, whether to reuse the weights of a previous layer by the same name. Returns: A 3d tensor with the same shape and dtype as inputs ''' with tf.variable_scope(scope, reuse=reuse): # Inner layer params = {"inputs": inputs, "filters": num_units[0], "kernel_size": 1, "activation": tf.nn.relu, "use_bias": True} outputs = tf.layers.conv1d(**params) # Readout layer params = {"inputs": outputs, "filters": num_units[1], "kernel_size": 1, "activation": None, "use_bias": True} outputs = tf.layers.conv1d(**params) # Residual connection outputs += inputs # Normalize outputs = normalize(outputs) return outputs def label_smoothing(inputs, epsilon=0.1): '''Applies label smoothing. See https://arxiv.org/abs/1512.00567. Args: inputs: A 3d tensor with shape of [N, T, V], where V is the number of vocabulary. epsilon: Smoothing rate. For example, ``` import tensorflow as tf inputs = tf.convert_to_tensor([[[0, 0, 1], [0, 1, 0], [1, 0, 0]], [[1, 0, 0], [1, 0, 0], [0, 1, 0]]], tf.float32) outputs = label_smoothing(inputs) with tf.Session() as sess: print(sess.run([outputs])) >> [array([[[ 0.03333334, 0.03333334, 0.93333334], [ 0.03333334, 0.93333334, 0.03333334], [ 0.93333334, 0.03333334, 0.03333334]], [[ 0.93333334, 0.03333334, 0.03333334], [ 0.93333334, 0.03333334, 0.03333334], [ 0.03333334, 0.93333334, 0.03333334]]], dtype=float32)] ``` ''' K = inputs.get_shape().as_list()[-1] # number of channels return ((1 - epsilon) * inputs) + (epsilon / K)
1f43006b09e88cce73aac7704a15c02efb759039
[ "Python", "Shell" ]
42
Python
jiakuanghe/Intent_Detection
9b699c100807dca7a601d96b7c25e736e5e2cfe9
30493c13351554ee4f8e9b40c9273a10b79ead31
refs/heads/Develoop
<file_sep>import { InicioService } from './inicio.service'; import { NgModule } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; import { AppRoutingModule } from './app-routing.module'; import { AppComponent } from './app.component'; import { BrowserAnimationsModule } from '@angular/platform-browser/animations'; import { FormsModule } from '@angular/forms' import {HttpClientModule} from '@angular/common/http'; import { BarraMenuComponent } from './barra-menu/barra-menu.component'; import { LayoutModule } from '@angular/cdk/layout'; import { MatToolbarModule } from '@angular/material/toolbar'; import { MatButtonModule } from '@angular/material/button'; import { MatSidenavModule } from '@angular/material/sidenav'; import { MatIconModule } from '@angular/material/icon'; import { MatListModule } from '@angular/material/list'; import { FormCrearComponent } from './form-crear/form-crear.component'; import { MatInputModule } from '@angular/material/input'; import { MatSelectModule } from '@angular/material/select'; import { FromUnirComponent } from './from-unir/from-unir.component'; /* ************************************************** *Nombre: AppModule ************************************************** *Entradas: N librerías ************************************************** *Salidas: Diferentes componentes ************************************************** *Objetivo: Agrupar todos los componentes que son utilizados ************************************************** *Restricciones: que las dependencias estén bien, que no falta ninguna librería instalada ************************************************** * */ @NgModule({ declarations: [ AppComponent, BarraMenuComponent, FormCrearComponent, FromUnirComponent, ], imports: [ BrowserModule, AppRoutingModule, BrowserAnimationsModule, LayoutModule, MatToolbarModule, MatButtonModule, MatSidenavModule, MatIconModule, MatListModule, FormsModule, MatInputModule, MatSelectModule ], providers: [InicioService], bootstrap: [AppComponent] }) export class AppModule { } <file_sep>import { InicioService } from './../inicio.service'; import { Component, OnInit } from '@angular/core'; //import { QueryBindingType } from '@angular/compiler/src/core'; @Component({ selector: 'app-form-crear', templateUrl: './form-crear.component.html', styleUrls: ['./form-crear.component.css'] }) /* ************************************************** *Nombre: FormCrearComponente ************************************************** *Entradas: Archivos de estilo y diseño ************************************************** *Salidas: El formulario para crear una carrera ************************************************** *Objetivo: solicitar datos al usuario y mostrar resultados ************************************************** *Restricciones: que el servidor este en ejecución. ************************************************** * */ export class FormCrearComponent implements OnInit { pistas: any; constructor(/*private service: InicioService*/) { } ngOnInit(): void { /* this.service.getPistas().subscribe(data => { console.log(data); });*/ } } <file_sep>import { Component, OnInit } from '@angular/core'; @Component({ selector: 'app-from-unir', templateUrl: './from-unir.component.html', styleUrls: ['./from-unir.component.css'] }) /* ************************************************** *Nombre: FromUnirComponent ************************************************** *Entradas: archivos de estilo y diseño ************************************************** *Salidas: El formulario necesario para unirse a un juego ************************************************** *Objetivo: capturar información y enviarla al backend ************************************************** *Restricciones: Que el backend esté en ejecución ************************************************** * */ export class FromUnirComponent implements OnInit { constructor() { } ngOnInit(): void { } } <file_sep>import { Component } from '@angular/core'; /* ************************************************** *Nombre: AppComponent ************************************************** *Entradas: archivos de estilo y diseño ************************************************** *Salidas: La componente principal ************************************************** *Objetivo: Ser la componente principal para derivar *componentes ************************************************** *Restricciones: No tiene restricciones ************************************************** * */ @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent { title = 'Luiki Kart'; } <file_sep>var express = require('express'); const bodyParser = require('body-parser'); const cors = require ('cors'); const Juego = require ('./juego'); var app = express(); app.use(bodyParser.json()); app.use(express.json()); app.use(cors()); app.post('/juegos', Juego.Juegos); app.post('/juegosEnEspera', Juego.JuegosEnEspera); app.post('/pistas', Juego.Pistas); app.post('/crear', Juego.Crear); app.post('/unirse', Juego.Unirse); var server = app.listen(8888, function (req, res) { console.log('El servidor se esta ejecutando en el puerto 8888'); });<file_sep>import { Injectable } from '@angular/core'; import {HttpClient} from '@angular/common/http'; import { Observable } from 'rxjs'; @Injectable({ providedIn: 'root' }) /* ************************************************** *Nombre: InicioService ************************************************** *Entradas: un http client pata peticiones al server ************************************************** *Salidas: Retorna la lista de pistas que existen ************************************************** *Objetivo: retornar las pistas de carreras en formato *json para mostrarlas en el juego ************************************************** *Restricciones: Que la api este corriendo en paralelo ************************************************** * */ export class InicioService { data: string[] = []; constructor(private http:HttpClient) { } getPistas(): Observable<any>{ return this.http.post("http://localhost:8888/pistas","") } }<file_sep>import { Component } from '@angular/core'; import { BreakpointObserver, Breakpoints } from '@angular/cdk/layout'; import { Observable } from 'rxjs'; import { map, shareReplay } from 'rxjs/operators'; /* ************************************************** *Nombre: BarraMenuComponent ************************************************** *Entradas: un archivo de estilos y uno de diseño ************************************************** *Salidas: Muestra el componente de angular material ************************************************** *Objetivo: Parsear los diferentes archivos para lograr *un menú de inicio de juego ************************************************** *Restricciones: Sin restricciones ************************************************** * */ @Component({ selector: 'app-barra-menu', templateUrl: './barra-menu.component.html', styleUrls: ['./barra-menu.component.css'] }) export class BarraMenuComponent { isHandset$: Observable<boolean> = this.breakpointObserver.observe(Breakpoints.Handset) .pipe( map(result => result.matches), shareReplay() ); constructor(private breakpointObserver: BreakpointObserver) {} } <file_sep>create database luikiKart; use luikiKart; create table `luikiKart`.`track`( idTrack int not null primary key, pathTrack varchar(100), thematic varchar(15) ); create table `luikiKart`.`game`( idGame int not null primary key, ipGame varchar(60), cantVueltas tinyint, gameType varchar(40), nickName varchar(50), idTrack int not null, key `fk_idTrack`(`idTrack`), constraint `fk_idTrack` foreign key(`idTrack`) references `track`(`idTrack`) ); <file_sep> var juegos = []; var identity = 0; /* * Nombre: * Juegos * * Salidas: * Arreglo de objetos * * Objetivo: * Devolver todos los juegos * que tenga actualmente el servidor */ exports.Juegos = function (req, resp) { resp.json( juegos ); }; /* * Nombre: * JuegosEnEspera * * Salidas: * Arreglo de objetos * * Objetivo: * Devolver todos los juegos * que tenga actualmente el servidor * que estén en espera */ exports.JuegosEnEspera = function (req, resp) { var juegosEnEspera = []; for (juego of juegos) { if (juego.jugadores.length < juego.maxJugadores) { juegosEnEspera.push(juego); } } resp.json( juegosEnEspera ); }; /* * Nombre: * Pistas * * Salidas: * Arreglo de strings * * Objetivo: * Devolver todos los nombres * de las pistas */ exports.Pistas = function (req, resp) { resp.json( ["Rainbow Road", "Waluigi Pinball", "Dino Dino Jungle", "Mute City"] ); }; /* * Nombre: * Crear * * Entradas: * cantVueltas: un entero, * maxJugadores: un entero, * jugadorActual: un string, * vehiculo: un string, * pistaElegida: un string, * modo: un string * * Salidas: * Un entero * * Restricciones: * cantVueltas debe ser entero positivo * maxJugadores debe ser entero positivo menor o igual a 5, * pistaElegida debe coincidir con una de las pistas establecidas * * Objetivo: * Crear un nuevo juego y agregarlo a la lista * de juegos del servidor */ exports.Crear = function (req, resp) { console.log(req.body); identity++; req.body.idPartida = identity; req.body.jugadores = [ { jugador: req.body.jugadorActual, vehiculo: req.body.vehiculo } ]; delete req.body.jugadorActual; delete req.body.vehiculo; juegos.push(req.body); resp.json( {id_juego : identity} ); }; /* * Nombre: * Unirse * * Entradas: * idPartida: un entero, * jugador: un string, * vehiculo: un string * * Salidas: * Un 0 o un 1 * * Objetivo: * Agregar un jugador a un juego * que tenga actualmente el servidor * en espera */ exports.Unirse = function (req, resp) { console.log(req.body); for (juego of juegos) { if (juego.idPartida == req.body.idPartida) { if (juego.jugadores.length < juego.maxJugadores) { for (jugador of juego.jugadores) { if (jugador.jugador == req.body.jugador || jugador.vehiculo == req.body.vehiculo) { resp.json( {exito: 0} ); return; } } delete req.body.idPartida; juego.jugadores.push(req.body); resp.json( {exito : 1} ); return; } else { resp.json( {exito: 0} ); return; } } } resp.json( {exito: 0} ); };<file_sep>import { FromUnirComponent } from './from-unir/from-unir.component'; import { FormCrearComponent } from './form-crear/form-crear.component'; import { NgModule } from '@angular/core'; import { RouterModule, Routes } from '@angular/router'; const routes: Routes = [ { path:'crear', component:FormCrearComponent }, { path:'unir', component:FromUnirComponent } ]; /* ************************************************** *Nombre: AppRoutingModule ************************************************** *Entradas: un conjunto de componentes ************************************************** *Salidas: la url de cada componente ************************************************** *Objetivo: tomar la url principal y derivarla a diferentes *url según las entradas ************************************************** *Restricciones: No tiene restricciones ************************************************** * */ @NgModule({ imports: [RouterModule.forRoot(routes)], exports: [RouterModule] }) export class AppRoutingModule { }
8ad290f67d2ad23190b85a2fa61c3577aa92abd7
[ "JavaScript", "SQL", "TypeScript" ]
10
TypeScript
AmpiePablo/luikiKart
889c0cebfcc828255f4b37aa2778a93fe657a09e
81ac6854736fb10ec9e42ca05c9787860b911f5f
refs/heads/master
<repo_name>henrikweimenhog/blueharvest<file_sep>/Limestone/TemplateProvider.cs using System; using System.Collections.Generic; using System.Linq; namespace Limestone { public class TemplateProvider:ITemplateProvider { public IStorage Storage { get; set; } public TemplateProvider(IStorage storage) { Storage = storage; } /// <summary> /// Loads and returns a full template object. /// </summary> /// <param name="path"></param> /// <returns></returns> public IPageTemplate Get(string path) { return Storage.GetTemplate(path); } public IEnumerable<IPageTemplate> GetAll() { return Storage.GetTemplates(); } /// <summary> /// Ensures that the page has all the fields declared in the template and removes any excess fields from the page /// </summary> /// <param name="page"></param> public void SyncPageWithTemplate(IPage page) { var template = Get(page.TemplatePath); if (template == null) return; // add missing fields foreach (var fieldSetting in template.FieldSettings) { var fld = page.Fields[fieldSetting.Name]; if (fld != null && fld.Type != fieldSetting.Type) { page.Fields.Remove(fld); fld = null; } if (fld == null) { fld = (Field)FieldFactory.CreateField(fieldSetting.Type); fld.Name = fieldSetting.Name; page.Fields.Add(fld); } } // remove excess fields var fieldsToRemove = (from field in page.Fields where template.FieldSettings[field.Name] == null select field.Name).ToList(); foreach (var fieldName in fieldsToRemove) { page.Fields.Remove(page.Fields[fieldName]); } } /// <summary> /// Loads fieldsettings from the template and appends them to their respective field in the page /// </summary> /// <param name="page"></param> public void AddFieldSettings(IPage page) { var template = Get(page.TemplatePath); if (template == null) return; foreach (var fieldSetting in template.FieldSettings) { var fld = page.Fields[fieldSetting.Name]; if (fld == null) { throw new Exception("Field missing in page. To avoid these exceptions, call SyncPageWithTemplate() first."); } if (fld.Type != fieldSetting.Type) { throw new Exception("Field type in page differs from tield type in template. To avoid these exceptions, call SyncPageWithTemplate() first."); } // append the field settings from the template to the page's field page.Fields[fieldSetting.Name].Settings = fieldSetting; } } /// <summary> /// persists the template to disc /// </summary> /// <returns></returns> public IPageTemplate Save(IPageTemplate template) { // TODO unique name in this folder return Storage.SaveTemplate(template); } } }<file_sep>/Limestone/IStorage.cs using System.Collections.Generic; namespace Limestone { public interface IStorage { IPage GetPage(string path); IPage SavePage(IPage page); IPageTemplate SaveTemplate(IPageTemplate page); IPageTemplate GetTemplate(string path); IEnumerable<IPageTemplate> GetTemplates(); bool MovePage(IPage page, string newParentPath); bool MovePage(IPage page, IPage newParentPage); bool CopyPage(IPage page, string targetParentPath); bool CopyPage(IPage page, IPage targetParentPage); bool DeletePage(IPage page); bool IsValidMoveTarget(IPage page, IPageStub newParentPage); bool IsValidCopyTarget(IPage page, IPage newParentPage); bool IsValidPageName(string name); IPageLookUp GetPageLookUp(bool forceDeepReload); void RemovePageFromLookUp(string pagePath); void AddPageToLookUp(IPageStub stub); IEnumerable<IPageStub> GetTrashCanRootPageStubs(); } } <file_sep>/Limestone/MVC/AbstractFieldSettingBinder.cs using System; using System.Web.Mvc; using Autofac.Integration.Mvc; namespace Limestone.MVC { [ModelBinderType(typeof(FieldSetting))] public class AbstractFieldSettingBinder : DefaultModelBinder { // TODO this should ideally reside in the Limestone assembly but for some reason Autofac wont bind to it properly protected override object CreateModel(ControllerContext controllerContext, ModelBindingContext bindingContext, Type modelType) { var fieldSettingTypeName = controllerContext.HttpContext.Request.Form[bindingContext.ModelName + ".Type"]; var fieldSetting = FieldFactory.CreateFieldSetting(fieldSettingTypeName); bindingContext.ModelMetadata = ModelMetadataProviders.Current.GetMetadataForType(() => fieldSetting, fieldSetting.GetType()); return fieldSetting; } } }<file_sep>/SampleSite/Areas/Limestone/Services/MenuHelperExtensions.cs using System.Web.Mvc; using System.Web.Mvc.Html; using System.Web.Routing; namespace SampleSite.Areas.Limestone.Services { public static class MenuHelperExtensions { public static MvcHtmlString MenuLink(this HtmlHelper helper, string text, string action, string controller, object routeValues, object htmlAttributes, string currentClass) { var attributes = new RouteValueDictionary(htmlAttributes); string currentController = helper.ViewContext.RouteData.Values["controller"] as string ?? "home"; string currentAction = helper.ViewContext.RouteData.Values["action"] as string ?? "index"; string page = string.Format("{0}:{1}", currentController, currentAction).ToLower(); string thisPage = string.Format("{0}:{1}", controller, action).ToLower(); attributes["class"] = (page == thisPage) ? currentClass : ""; return helper.ActionLink(text, action, controller, new RouteValueDictionary(routeValues), attributes); } } }<file_sep>/Limestone/GetCurrentUserFromHttpContext.cs using System.Web; namespace Limestone { public class GetCurrentUserFromHttpContext : IGetCurrentUserId { private HttpContext HttpContext { get; set; } public GetCurrentUserFromHttpContext(HttpContext httpContext) { HttpContext = httpContext; } public string CurrentUserId { get { return HttpContext.Current.User.Identity.Name; } } } }<file_sep>/Limestone/IPageProvider.cs using System.Collections.Generic; using System.Web; namespace Limestone { public interface IPageProvider { IStorage Storage { get; set; } IGetCurrentUserId GetCurrentUserId { get; set; } IPageStubCache PageStubCache { get; set; } /// <summary> /// Returns the current page /// </summary> /// <param name="context"></param> /// <returns></returns> IPage GetCurrentPage(HttpContext context); /// <summary> /// Loads and returns a full page object. /// For quick look ups, use GetPageStub instead /// </summary> /// <param name="path"></param> /// <returns></returns> IPage Get(string path); /// <summary> /// Loads a full page from a stub /// </summary> /// <param name="stub"></param> /// <returns></returns> IPage ExpandToPage(IPageStub stub); /// <summary> /// persists the page to storage /// </summary> /// <returns></returns> IPage Save(IPage page); /// <summary> /// Creates a new page beneath the current page /// </summary> /// <param name="page"> </param> /// <param name="title"></param> /// <returns></returns> IPage CreateChildPage(IPage page, string title); /// <summary> /// Returns the parent page /// </summary> /// <returns></returns> IPage GetParent(IPage page); /// <summary> /// /// </summary> /// <param name="page"> </param> /// <param name="newParentPath"></param> bool Move(IPage page, string newParentPath); /// <summary> /// /// </summary> /// <param name="page"> </param> /// <param name="targetParentPath"></param> bool Copy(IPage page, string targetParentPath); /// <summary> /// /// </summary> /// <param name="page"> </param> /// <param name="targetParentPage"></param> bool Copy(IPage page, IPage targetParentPage); /// <summary> /// /// </summary> /// <returns></returns> bool Delete(IPage page); bool Delete(string pagePath); IEnumerable<IPageStub> GetChildPages(string pagePath, bool excludeHidden); IEnumerable<IPageStub> GetChildPages(IPage page, bool excludeHidden); IPageStub ToPageStub(IPage page); } }<file_sep>/SampleSite/Areas/Limestone/LimestoneAreaRegistration.cs using System.Web.Mvc; namespace SampleSite.Areas.Limestone { public class LimestoneAreaRegistration : AreaRegistration { public override string AreaName { get { return "Limestone"; } } public override void RegisterArea(AreaRegistrationContext context) { context.MapRoute( "Limestone_default", "Limestone/{controller}/{action}/{id}", new { controller = "Home", action = "Index", id = UrlParameter.Optional } ); } } } <file_sep>/Limestone/IPage.cs using System; using System.Xml.Serialization; using Limestone.Fields; using Utils; namespace Limestone { public interface IPage { [XmlAttribute] string Name { get; set; } /// <summary> /// The path always begins with a / and includes the page name /// </summary> [XmlAttribute] string Path { get; set; } [XmlAttribute] string Title { get; set; } [XmlAttribute] string TemplatePath { get; set; } [XmlAttribute] bool Hidden { get; set; } [XmlAttribute] PageSortType SortChildPagesBy { get; set; } [XmlAttribute] int SortValue { get; set; } [XmlArray("ListItems")] [XmlArrayItem("ListItem", Type = typeof (AbstractXmlSerializer<Field>))] FieldCollection Fields { get; set; } [XmlIgnore] string ParentPath { get; } [XmlAttribute] DateTime Created { get; set; } [XmlAttribute] string CreatedBy { get; set; } [XmlAttribute] DateTime Modified { get; set; } [XmlAttribute] string ModifiedBy { get; set; } [XmlAttribute] DateTime Deleted { get; set; } [XmlAttribute] string DeletedBy { get; set; } } }<file_sep>/Limestone/FieldSettingsCollection.cs using System; using System.Collections.ObjectModel; using System.Linq; namespace Limestone { [Serializable] public class FieldSettingCollection : Collection<FieldSetting> { protected override void InsertItem(int index, FieldSetting newItem) { base.InsertItem(index, newItem); ResetIndices(); } protected override void SetItem(int index, FieldSetting newItem) { base.SetItem(index, newItem); // remove the item that is being replaced RemoveItem(index); InsertItem(index, newItem); ResetIndices(); } protected override void RemoveItem(int index) { // IField removedItem = Items[index]; base.RemoveItem(index); ResetIndices(); } public FieldSetting this[string fieldName] { get { return Items.FirstOrDefault(item => item.Name.ToLower() == fieldName.ToLower()); } set { var idx = 0; foreach (var item in Items) { if (item.Name.ToLower() == fieldName.ToLower()) { SetItem(idx, value); break; } idx++; } } } /// <summary> /// Helper function to re-enumerate the index property of the fields if it has been garbled or messed up /// </summary> public void ResetIndices() { var idx = 0; foreach (var field in Items.OrderBy(f => f.Index)) { field.Index = idx; idx++; } } } } <file_sep>/Limestone.Storage.XML/IFileReader.cs using System.Collections.Generic; using System.Xml; namespace Limestone.Storage.XML { public interface IFileReader { IPageStub ReadPageFile(string filePath); IEnumerable<IPageStub> GetPageStubsFromDirectory(string directoryPath); } }<file_sep>/Limestone/PageLookUp.cs using System.Collections.Generic; namespace Limestone { public class PageLookUp : IPageLookUp { public Dictionary<string, IPageStub> Pages { get; set; } public Dictionary<string, IEnumerable<IPageStub>> PagesByParentId { get; set; } } }<file_sep>/Limestone/IPageStub.cs namespace Limestone { public interface IPageStub { string Name { get; set; } string Path { get; set; } string Title { get; set; } bool Hidden { get; set; } string TemplatePath { get; set; } } }<file_sep>/Limestone/Fields/PageField.cs using System; namespace Limestone.Fields { [Serializable] public class PageField : Field, IField { public string Path { get; set; } public new PageFieldSetting Settings { get { return base.Settings as PageFieldSetting; } set { base.Settings = value; } } public PageField() : base(FieldType.PageField, "") { Path = ""; } public PageField(string name) : base(FieldType.PageField, name) { Path = ""; } public string GetHtml() { return "<a href=\"" + Path + "\">" + Path + "</a>"; } public string GetLink(PageStubCache pageStubCache) { var linkedPage = pageStubCache.GetPageStub(Path); if (linkedPage != null) { return "<a href=\"" + linkedPage.Path + "\">" + linkedPage.Title + "</a>"; } return ""; } } } <file_sep>/Limestone.Test/PageLookUpFixture.cs using System; using System.Linq; using System.Threading; using NUnit.Framework; using SharpTestsEx; namespace Limestone.Test { [TestFixture] public class PageLookUpFixture : TestBase { [Test] public void PageStructureTest() { var pageProvider = GetPageProvider(); /* wicked path */ var index = new Page("A title") { Name = "home", Path = "/a/wicked/long/path/to/my/home" }; pageProvider.Save(index); var lookup = GetStorage().GetPageLookUp(true); lookup.Pages.Count.Should().Be.EqualTo(8); } [Test] public void AddPageWithFunkyName() { var pageProvider = GetPageProvider(); var page = new Page("A page title") { Name = "page", Path = "//page" }; pageProvider.Save(page); page.Path.Should().Be.EqualTo("/page"); // remove excess slashes } [Test] public void ChildTest() { var pageProvider = GetPageProvider(); /* mom */ var mom = new Page("A title") { Name = "mom", Path = "/mom" }; pageProvider.Save(mom); /* child */ var child = new Page("A child title") { Name = "child", Path = "/mom/child" }; pageProvider.Save(child); GetStorage().GetPageLookUp(true).Pages.Count.Should().Be.EqualTo(3); // 2 pages plus the root } [Test] public void DeleteTest() { var pageProvider = GetPageProvider(); /* mom */ var goner = new Page("A title") { Name = "goner", Path = "/goner" }; pageProvider.Save(goner); pageProvider.Delete(goner); var store = GetStorage(); var look = store.GetPageLookUp(false); var cache = GetPageStubCache(); var rootStubs = cache.GetRootPageStubs(false); var cachedStub = cache.GetPageStub("/goner"); Assert.AreEqual(1, look.Pages.Count); // 1 = the root Assert.AreEqual(1, rootStubs.Count()); // 1 = the root Assert.IsNull(cachedStub); } [Test] public void ManyTest() { var pageProvider = GetPageProvider(); /* mom */ var mom = new Page("A title") { Name = "mom", Path = "/mom" }; pageProvider.Save(mom); /* child */ var child = new Page("A child title") { Name = "child", Path = "/mom/child" }; pageProvider.Save(child); var child2 = new Page("A child2 title") { Name = "child2", Path = "/mom/child2" }; pageProvider.Save(child2); var child3 = new Page("A child3 title") { Name = "child3", Path = "/mom/child3" }; pageProvider.Save(child3); /* dad */ var dad = new Page("A title") { Name = "dad", Path = "/dad" }; pageProvider.Save(dad); /* child */ var child4 = new Page("A child title") { Name = "child4", Path = "/dad/child" }; pageProvider.Save(child4); var child5 = new Page("A child2 title") { Name = "child5", Path = "/dad/child2" }; pageProvider.Save(child5); var child6 = new Page("A child3 title") { Name = "child6", Path = "/dad/child3" }; pageProvider.Save(child6); /* young dad */ var youngDad = new Page("A title") { Name = "youngDad", Path = "/youngDad" }; pageProvider.Save(youngDad); /* child */ var grandChild = new Page("A grandChild title") { Name = "grandChild", Path = "/youngDad/grandChild" }; pageProvider.Save(grandChild); var storage = GetStorage(); var lookup = storage.GetPageLookUp(true); lookup.Pages.Count.Should().Be.EqualTo(11); } } }<file_sep>/Limestone.Storage.XML/FileHelpers.cs using System; using System.IO; using System.Linq; using System.Text; using System.Xml.Serialization; namespace Limestone.Storage.XML { internal class FileHelpers:IFileHelpers { private readonly IXmlStorageConfig _xmlStorageConfig; public FileHelpers(IXmlStorageConfig xmlStorageConfig) { _xmlStorageConfig = xmlStorageConfig; } public string ToDiscPath(string path) { path = path.Replace('/', '\\'); return Path.Combine(_xmlStorageConfig.BasePagePath, (path.First() == '\\') ? path.Substring(1) : path); } public string GetPageFilePath(string pagePath) { var path = ToDiscPath(pagePath); path += Directory.Exists(path) ? "\\" + _xmlStorageConfig.FolderIndexPageName + ".page" : ".page"; return path; } public PageDiscInfo GetPageDiscInfo(string pagePath) { var path = ToDiscPath(pagePath); var isDir = Directory.Exists(path); var parentDirectoryPath = path.Substring(0, path.LastIndexOf("\\", StringComparison.Ordinal)); return new PageDiscInfo { IsDirectory = isDir, PageFilePath = path + ((isDir) ? "\\" + _xmlStorageConfig.FolderIndexPageName + ".page" : ".page"), ResidesInDirectory = isDir ? path + "\\" : parentDirectoryPath }; } public string ToValidName(string name) { var builder = new StringBuilder(); var invalid = Path.GetInvalidFileNameChars(); foreach (var cur in name.Where(cur => !invalid.Contains(cur))) { builder.Append(cur); } return builder.ToString(); } public T SaveToFile<T>(T templateOrPage, string path) { TextWriter w = null; var previousVersionContent = (File.Exists(path)) ? File.ReadAllText(path) : ""; try { var s = new XmlSerializer(typeof(T)); w = new StreamWriter(path); s.Serialize(w, templateOrPage); } catch (Exception) { // Rollback if (!String.IsNullOrEmpty(previousVersionContent)) { File.WriteAllText(path, previousVersionContent); } return default(T); } finally { if (w != null) w.Close(); } return templateOrPage; } public void EnsureParentDirectoryExists(string folderPath) { if (folderPath == "" || Directory.Exists(folderPath)) return; // check closest parent var parentFolderPath = Path.GetDirectoryName(folderPath); if (!Directory.Exists(parentFolderPath)) EnsureParentDirectoryExists(parentFolderPath); // create the folder Directory.CreateDirectory(folderPath); // check if there is a page which should be moved and turned into an index.page var indexPath = Path.Combine(_xmlStorageConfig.BasePagePath, folderPath + ".page"); if (File.Exists(indexPath)) { File.Move(indexPath, Path.Combine(folderPath, _xmlStorageConfig.FolderIndexPageName + ".page")); } /* not doing this. It creates a loop since saving the page will check for existence of the very same file // add an index page to the folder string folderIndexFilePath = folderPath + "/" + Config.FolderIndexPageName + ".page"; if (!File.Exists(HttpContext.Current.Server.MapPath(folderIndexFilePath))) { Page indexPage = new Page("Index", true); indexPage.Site = currentSite; indexPage.TemplatePath = Config.DefaultIndexTemplatePath; indexPage.Path = folderIndexFilePath; indexPage.Save(); } * */ } public T LoadObjectFromDisc<T>(string path) { TextReader r = null; T newObject; try { var s = new XmlSerializer(typeof(T)); r = new StreamReader(path); newObject = (T)s.Deserialize(r); } catch (Exception) { return default(T); } finally { if (r != null) r.Close(); } return newObject; } } }<file_sep>/Limestone/LimeMapNode.cs using System.Collections.Generic; namespace Limestone { public class LimeMapNode : ILimeMapNode { public IPageStub PageStub { get; set; } public IEnumerable<ILimeMapNode> Nodes { get; set; } } }<file_sep>/Limestone/PageProvider.cs using System; using System.Collections.Generic; using System.Web; namespace Limestone { public class PageProvider : IPageProvider { public IStorage Storage { get; set; } public IGetCurrentUserId GetCurrentUserId { get; set; } public IPageStubCache PageStubCache { get; set; } public PageProvider(IStorage storage, IGetCurrentUserId getCurrentUserId, IPageStubCache pageStubCache) { Storage = storage; GetCurrentUserId = getCurrentUserId; PageStubCache = pageStubCache; } /// <summary> /// Returns the current page /// </summary> /// <param name="context"></param> /// <returns></returns> public IPage GetCurrentPage(HttpContext context) { var path = context.Request.Url.PathAndQuery; var page = Storage.GetPage(path.Substring(context.Request.ApplicationPath.Length - 1)); return page; } /// <summary> /// Loads and returns a full page object. /// For quick look ups, use GetPageStub instead /// </summary> /// <param name="path"></param> /// <returns></returns> public IPage Get(string path) { if (!path.StartsWith("/")) path = "/" + path; var page = Storage.GetPage(path); return page; } /// <summary> /// Loads a full page from a stub /// </summary> /// <param name="stub"></param> /// <returns></returns> public IPage ExpandToPage(IPageStub stub) { var page = Get(stub.Path); return page; } /// <summary> /// persists the page to storage /// </summary> /// <returns></returns> public IPage Save(IPage page) { page.Path = CleanUpPath(page.Path); page.TemplatePath = page.TemplatePath.ToLower().Replace(".template", ""); page.Modified = new DateTime(); page.ModifiedBy = GetCurrentUserId.CurrentUserId; if(string.IsNullOrEmpty(page.CreatedBy)) page.CreatedBy = GetCurrentUserId.CurrentUserId; // TODO unique name in this parent if (!Storage.IsValidPageName(page.Name)) return null; // delegate to storage provider var returnPage = Storage.SavePage(page); if (!PageStubCache.IsCached(returnPage.Path)) { // insert the stub in the cache and update the navigation file PageStubCache.AddPageStub(ToPageStub(page), page.ParentPath); } return returnPage; } /// <summary> /// Creates a new page beneath the current page /// </summary> /// <param name="parentPage"> </param> /// <param name="title"></param> /// <returns></returns> public IPage CreateChildPage(IPage parentPage, string title) { var child = new Page(title); child.Path = parentPage.Path + "/" + child.Name; return child; } /// <summary> /// Returns the parent page /// </summary> /// <returns></returns> public IPage GetParent(IPage page) { if (page.ParentPath == "") return null; return Storage.GetPage(page.ParentPath); } /// <summary> /// /// </summary> /// <param name="page"> </param> /// <param name="newParentPath"></param> public bool Move(IPage page, string newParentPath) { var oldPath = page.Path; if (Storage.MovePage(page, newParentPath)) { // update navigation cache PageStubCache.MovePageStub(oldPath, newParentPath); return true; } return false; } /// <summary> /// /// </summary> /// <param name="page"> </param> /// <param name="targetParentPath"></param> public bool Copy(IPage page, string targetParentPath) { return Storage.CopyPage(page, targetParentPath); } /// <summary> /// /// </summary> /// <param name="page"> </param> /// <param name="targetParentPage"></param> public bool Copy(IPage page, IPage targetParentPage) { return Storage.CopyPage(page, targetParentPage); } public bool Delete(string pagePath) { return Delete(Get(pagePath)); } public bool Delete(IPage page) { var pagePath = page.Path; page.Deleted = new DateTime(); page.DeletedBy = GetCurrentUserId.CurrentUserId; if (!Storage.DeletePage(page)) { return false; } PageStubCache.RemovePageStub(pagePath); return true; } public IEnumerable<IPageStub> GetChildPages(string pagePath, bool excludeHidden) { return PageStubCache.GetChildPageStubsFor(pagePath); } public IEnumerable<IPageStub> GetChildPages(IPage page, bool excludeHidden) { return PageStubCache.GetChildPageStubsFor(page.Path); } public IPageStub ToPageStub(IPage page) { return new PageStub(page.Name, page.Path, page.Title, page.TemplatePath, page.Hidden); } private string CleanUpPath(string path) { if (path.StartsWith("//")) path = path.Substring(1); return path; } } } <file_sep>/SampleSite/Areas/Limestone/Controllers/TrashcanController.cs using System.Web.Mvc; using Limestone; namespace SampleSite.Areas.Limestone.Controllers { public class TrashcanController : Controller { private readonly IPageProvider _pageProvider; private readonly ITrashcan _trashcan; public TrashcanController(IPageProvider pageProvider, ITrashcan trashcan) { _pageProvider = pageProvider; _trashcan = trashcan; } public ActionResult Index() { var trash = _trashcan.GetRootPageStubs(); return View(trash); } } }<file_sep>/Limestone/PageHelper.cs using System; using System.Linq; namespace Limestone { public class PageHelper { /// <summary> /// Extracts the parent path out of a path. /// </summary> /// <param name="path"></param> /// <returns></returns> public static string GetParentPath(string path) { var idx = path.LastIndexOf(@"/", StringComparison.Ordinal); if (idx < 1) return "/"; return path.Substring(0, idx); } } }<file_sep>/Limestone/IPageTemplate.cs using System.Xml.Serialization; using Utils; namespace Limestone { public interface IPageTemplate { [XmlAttribute] string Name { get; set; } /// <summary> /// The path always begins with a / and includes the template name and ends with .template (the /sys/templates prefix should not be added) /// </summary> [XmlAttribute] string Path { get; set; } [XmlAttribute] string HelpText { get; set; } [XmlArray("ListItems")] [XmlArrayItem("ListItem", Type = typeof (AbstractXmlSerializer<FieldSetting>))] FieldSettingCollection FieldSettings { get; set; } } }<file_sep>/Limestone/Fields/TextFieldSetting.cs using System; using System.Xml.Serialization; namespace Limestone.Fields { [Serializable] public class TextFieldSetting : FieldSetting, IFieldSetting { [XmlAttribute] public bool Multiline { get; set; } [XmlAttribute] public TextEditMode EditMode { get; set; } public TextFieldSetting() : base(FieldType.TextField, "") { Name = ""; EditMode = TextEditMode.Text; } public TextFieldSetting(string name) : base(FieldType.TextField, name) { EditMode = TextEditMode.Text; } } } <file_sep>/Limestone/Controllers/LimestoneController.cs using System.Web.Mvc; namespace Limestone.Controllers { public class LimestoneController : Controller { public ActionResult Page() { var page = new Limestone.Page("tjo"); return View("StandardPage", page); } } }<file_sep>/Limestone.Storage.XML/XmlStorage.cs using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Xml; using System.Xml.Serialization; namespace Limestone.Storage.XML { public class XmlStorage : IStorage { private readonly IXmlStorageConfig _xmlStorageConfig; private IFileReader _fileReader; private XmlReaderSettings _xmlReadSettings; private FileHelpers _fileHelpers; public XmlStorage(IXmlStorageConfig xmlStorageConfig, IGetCurrentUserId getCurrentUserId) { _xmlStorageConfig = xmlStorageConfig; GetCurrentUserId = getCurrentUserId; _xmlReadSettings = new XmlReaderSettings { ConformanceLevel = ConformanceLevel.Fragment, IgnoreWhitespace = true, IgnoreComments = true }; _fileReader = new FileReader(_xmlReadSettings, _xmlStorageConfig); _fileHelpers = new FileHelpers(_xmlStorageConfig); LookUpProvider = new LookUpProvider(_fileReader, _xmlStorageConfig); //EnsureSetupIsCorrect(); } private void EnsureSetupIsCorrect() { if (GetPage("/") == null) { SavePage(new Page("Start") { Name = "Start", Path = "/" }); } } public IGetCurrentUserId GetCurrentUserId { get; set; } public LookUpProvider LookUpProvider { get; set; } #region pageLookUp public IPageLookUp GetPageLookUp(bool forceDeepReload) { return LookUpProvider.GetPageLookUp(forceDeepReload); } public void RemovePageFromLookUp(string pagePath) { LookUpProvider.RemovePageStub(pagePath); } public void AddPageToLookUp(IPageStub stub) { LookUpProvider.AddPageStub(stub, PageHelper.GetParentPath(stub.Path)); } #endregion #region get and save pages /// <summary> /// Loads and returns a full page object. /// For quick look ups, use GetPageStub instead /// </summary> /// <param name="pagePath"></param> /// <returns></returns> public IPage GetPage(string pagePath) { var filePath = _fileHelpers.GetPageFilePath(pagePath); if (!File.Exists(filePath)) { return null; } // TODO cache this var page = _fileHelpers.LoadObjectFromDisc<Page>(filePath); page.Fields.ResetIndices(); return page; } public IPage SavePage(IPage page) { var filePath = _fileHelpers.GetPageFilePath(page.Path); // if we are saving a new page, make sure all parents exists as folders if (!File.Exists(filePath)) { _fileHelpers.EnsureParentDirectoryExists(Path.GetDirectoryName(filePath)); } return _fileHelpers.SaveToFile<Page>(page as Page, filePath); } #endregion #region copy and move public bool MovePage(IPage page, string newParentPath) { var newParentPage = GetPage(newParentPath); return newParentPage != null && MovePage(page, newParentPage); } public bool MovePage(IPage page, IPage newParentPage) { var oldPath = page.Path; var movedPage = MovePageFile(page, newParentPage); if (movedPage == null) return false; movedPage.Modified = DateTime.Now; movedPage.ModifiedBy = GetCurrentUserId.CurrentUserId; SavePage(movedPage); // update navigation file LookUpProvider.MovePageStub(oldPath, newParentPage.Path); return true; } private IPage MovePageFile(IPage page, IPageStub newParentPage, bool autoRenameIfTargetExists = false) { // check if target is same as source if (page.ParentPath == newParentPage.Path || page.Path == newParentPage.Path) return null; var targetName = page.Name; if (!IsValidMoveTarget(page, newParentPage)) { if (autoRenameIfTargetExists) targetName = GetUniqueDiscName(_fileHelpers.ToDiscPath(newParentPage.Path + "/" + page.Name)); else return null; } // ensure target is a folder ConvertToFolder(newParentPage); var parentPageDiscInfo = _fileHelpers.GetPageDiscInfo(newParentPage.Path); // make the move var pageDiscInfo = _fileHelpers.GetPageDiscInfo(page.Path); if (pageDiscInfo.IsDirectory) { Directory.Move(pageDiscInfo.ResidesInDirectory, Path.Combine(parentPageDiscInfo.ResidesInDirectory, targetName)); } else { File.Move(pageDiscInfo.PageFilePath, parentPageDiscInfo.ResidesInDirectory + targetName + ".page"); } // update the path page.Path = newParentPage.Path + @"/" + targetName; return SavePage(page); } private string GetUniqueDiscName(string desiredTargetPath, int attempt = 0) { var tryPath = desiredTargetPath; if (attempt > 0) { tryPath = Path.Combine(Path.GetDirectoryName(desiredTargetPath), Path.GetFileNameWithoutExtension(desiredTargetPath) + " (" + attempt + ")"); } if (File.Exists(tryPath + ".page") || Directory.Exists(tryPath)) { return GetUniqueDiscName(desiredTargetPath, attempt + 1); } return Path.GetFileNameWithoutExtension(tryPath); } private void ConvertToFolder(IPageStub pageStub) { var discInfo = _fileHelpers.GetPageDiscInfo(pageStub.Path); if (discInfo.IsDirectory) return; // create the folder var folderPath = _fileHelpers.ToDiscPath(pageStub.Path); Directory.CreateDirectory(folderPath); File.Move(discInfo.PageFilePath, Path.Combine(folderPath, _xmlStorageConfig.FolderIndexPageName + ".page")); } // TODO a good candidate for being exposed as an interface to allow security checks by other modules and similar public bool IsValidMoveTarget(IPage page, IPageStub newParentPage) { var targetParent = _fileHelpers.ToDiscPath(newParentPage.Path); if (Directory.Exists(targetParent)) { return !File.Exists(targetParent + "\\" + page.Name + ".page") && !Directory.Exists(targetParent + "\\" + page.Name); } return true; } public bool IsValidCopyTarget(IPage page, IPage newParentPage) { return IsValidMoveTarget(page, ToPageStub(newParentPage)); } public bool IsValidPageName(string name) { return name.ToLower() != _xmlStorageConfig.FolderIndexPageName; } private IPage MovePageFile(IPage page, IPage newParentPage) { return MovePageFile(page, ToPageStub(newParentPage)); } private IPage CopyPageFile(IPage page, IPage newParentPage) { throw new NotImplementedException(); // TODO copy page file // check if target is same as source if (!IsValidCopyTarget(page, newParentPage)) return null; // check if target is a folder already, otherwise turn it into a folder // check if source is a folder without child pages // Copy file } public bool CopyPage(IPage page, string targetParentPath) { var targetParentPage = GetPage(targetParentPath); if (targetParentPage != null) return CopyPage(page, targetParentPage); return false; } public bool CopyPage(IPage page, IPage targetParentPage) { var newPage = CopyPageFile(page, targetParentPage); if (newPage == null) return false; // update navigation file LookUpProvider.AddPageStub(ToPageStub(newPage), newPage.ParentPath); // update navigation cache throw new NotImplementedException(); //return true; } public bool DeletePage(IPage page) { var oldPath = page.Path; page.Deleted = DateTime.Now; page.DeletedBy = GetCurrentUserId.CurrentUserId; page = SavePage(page); var movedPage = MovePageFile(page, GetTrashcanRoot(), true); if (movedPage != null) { LookUpProvider.RemovePageStub(oldPath); return true; } return false; } public IPageStub GetTrashcanRoot() { return ToPageStub(new Page("Trashcan") { Path = _xmlStorageConfig.BaseTrashcanPath }); } public IEnumerable<IPageStub> GetTrashCanRootPageStubs() { return _fileReader.GetPageStubsFromDirectory(_fileHelpers.ToDiscPath(_xmlStorageConfig.BaseTrashcanPath)); } private IPageStub ToPageStub(IPage page) { return new PageStub(page.Name, page.Path, page.Title, page.TemplatePath, page.Hidden); } #endregion #region Templates /// <summary> /// Loads and returns a template object. /// </summary> /// <param name="path">Relative path from templates root directory</param> /// <returns>Template</returns> public IPageTemplate GetTemplate(string path) { if (!path.ToLower().EndsWith(".template")) path += ".template"; path = path.Replace(@"/", @"\"); path = (path.StartsWith(@"\")) ? path.Substring(1) : path; path = Path.Combine(_xmlStorageConfig.BaseTemplatePath, path); if (!File.Exists(path)) return null; // TODO cache this var newTemplate = _fileHelpers.LoadObjectFromDisc<PageTemplate>(path); newTemplate.FieldSettings.ResetIndices(); return newTemplate; } public IPageTemplate SaveTemplate(IPageTemplate template) { if (string.IsNullOrEmpty(template.Path)) template.Path = _fileHelpers.ToValidName(template.Name); var path = _xmlStorageConfig.BaseTemplatePath + template.Path.Replace("/", @"\"); if (!path.ToLower().Contains(".template")) path = path + ".template"; // make sure all parents exists as folders if (!File.Exists(path)) { Directory.CreateDirectory(Path.GetDirectoryName(path)); } return _fileHelpers.SaveToFile<PageTemplate>(template as PageTemplate, path); } public IEnumerable<IPageTemplate> GetTemplates() { var folder = new DirectoryInfo(Path.Combine(_xmlStorageConfig.BaseTemplatePath)); return folder.GetFiles("*.template").Select(f => GetTemplate(f.Name)); } #endregion } } <file_sep>/LimestoneMVC/Controllers/PagePathConstraint.cs using System.Web; using System.Web.Routing; using Limestone; namespace LimestoneMVC.Controllers { public class PagePathConstraint : IRouteConstraint { public IPageStubCache PageStubCache { get; set; } public PagePathConstraint(IPageStubCache pageStubCache) { PageStubCache = pageStubCache; } public bool Match(HttpContextBase httpContext, Route route, string parameterName, RouteValueDictionary values, RouteDirection routeDirection) { var pagePath = values[parameterName] as string; if (string.IsNullOrEmpty(pagePath)) { pagePath = "/"; } else { if(!pagePath.StartsWith("/")) pagePath = "/" + pagePath; } return PageStubCache.GetPageStub(pagePath) != null; } } }<file_sep>/Limestone/MVC/DesignedTemplate.cs namespace Limestone.MVC { public class DesignedTemplate : PageTemplate, IPageTemplate { public string NewFieldName { get; set; } public FieldType NewFieldType { get; set; } } }<file_sep>/Limestone/Fields/Enums.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Limestone.Fields { public enum TextEditMode { Text, Basic, Rich } public enum PageSortType { CreatedDate, ModifiedDate, SortValue, Name, Title } } <file_sep>/Limestone/FieldFactory.cs using System; namespace Limestone { public class FieldFactory { public static IField CreateField(FieldType fieldType) { var fType = Type.GetType(fieldType.ToString(), true); return (IField)Activator.CreateInstance(fType); } public static IField CreateField(string fieldTypeName) { var fType = Type.GetType(fieldTypeName, true); return (IField)Activator.CreateInstance(fType); } public static IFieldSetting CreateFieldSetting(string fieldSettingTypeName) { var fType = Type.GetType(fieldSettingTypeName, true); return (IFieldSetting)Activator.CreateInstance(fType); } } } <file_sep>/Limestone.Storage.XML/IFileHelpers.cs namespace Limestone.Storage.XML { internal interface IFileHelpers { string ToDiscPath(string path); string GetPageFilePath(string pagePath); PageDiscInfo GetPageDiscInfo(string pagePath); string ToValidName(string name); } }<file_sep>/LimestoneMVC/App_Start/RegisterMVC3Routes.cs using System.Web.Mvc; using System.Web.Routing; using Limestone; using LimestoneMVC.App_Start; using LimestoneMVC.Controllers; [assembly: WebActivator.PostApplicationStartMethod(typeof(AppStart_RegisterRoutesAreasFilters), "Start")] namespace LimestoneMVC.App_Start { public static class AppStart_RegisterRoutesAreasFilters { public static void Start() { // Set everything up with you having to do any work. // I'm doing this because it means that // your app will just run. You might want to get rid of this // and integrate with your own Global.asax. // It's up to you. AreaRegistration.RegisterAllAreas(); RegisterGlobalFilters(GlobalFilters.Filters); RegisterRoutes(RouteTable.Routes); } public static void RegisterGlobalFilters(GlobalFilterCollection filters) { filters.Add(new HandleErrorAttribute()); } public static void RegisterRoutes(RouteCollection routes) { // resolve the pagestubcache with autoFac var pageStubCache = (IPageStubCache)DependencyResolver.Current.GetService(typeof(IPageStubCache)); var pageProvider = (IPageProvider)DependencyResolver.Current.GetService(typeof(IPageProvider)); routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); routes.IgnoreRoute("{resource}.aspx"); routes.IgnoreRoute("{*staticfile}", new { staticfile = @".*\.(jpg|gif|jpeg|png|js|css|htm|html|htc|flv|swf|ico|bmp|xml)$" }); // explicitly adding routes as the page catchall route below otherwise will get em all // handle pages using the TrialForm template routes.MapRoute("trialForm", "{*pagepath}", new { controller = "Trial", action = "ApplyTrial" }, new { pagePath = new HandledPagePathConstraint(pageProvider, "TrialForm") } ); // handle pages using the ContactForm template routes.MapRoute("contactForm", "{*pagepath}", new { controller = "Contact", action = "GetContact" }, new { pagePath = new HandledPagePathConstraint(pageProvider, "ContactForm") } ); // handle pages using the OrderForm template routes.MapRoute("orderForm", "{*pagepath}", new { controller = "Order", action = "PlaceOrder" }, new { pagePath = new HandledPagePathConstraint(pageProvider, "OrderForm") } ); // all other pages will go to the PageController routes.MapRoute("Pages", "{*pagepath}", new { controller = "Page", action = "OpenPage" }, new { pagePath = new PagePathConstraint(pageStubCache) } ); // will probably never reach here... routes.MapRoute( "Default", // Route name "{controller}/{action}/{id}", // URL with parameters new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults ); /* routes.MapRoute( "SuperCatchall", "{*urlParts}", new { controller = "Page", action = "OpenPage" } ); */ } /* public static void RegisterRoutes(RouteCollection routes) { routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); routes.Ignore("{*alllimstonepageextension}", new { allcustomextension = @".*\.page(/.*)?" }); routes.MapRoute( "Default", // Route name "{controller}/{action}/{id}", // URL with parameters new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults ); } */ } }<file_sep>/Limestone/ITrashcan.cs using System.Collections.Generic; namespace Limestone { public interface ITrashcan { IStorage Storage { get; set; } IEnumerable<IPageStub> GetRootPageStubs(); } }<file_sep>/SampleSite/Areas/Limestone/Controllers/HomeController.cs using System.Web.Mvc; using Limestone; namespace SampleSite.Areas.Limestone.Controllers { public class HomeController : Controller { private readonly IStorage _storage; private readonly IPageStubCache _pageStubCache; public HomeController(IStorage storage, IPageStubCache pageStubCache) { _storage = storage; _pageStubCache = pageStubCache; } public ActionResult Index() { return View(); } public ActionResult About() { return View(); } public ActionResult Contact() { return View(); } public ActionResult RebuildLookup() { _storage.GetPageLookUp(true); return View("Index"); } public ActionResult ClearPageStubCache() { _pageStubCache.LoadPageLookUpCache(true); return View("Index"); } } }<file_sep>/Limestone/IFieldSetting.cs namespace Limestone { public interface IFieldSetting { string HelpText { get; set; } string Title { get; set; } string Name { get; set; } FieldType Type { get; set; } int Index { get; set; } } } <file_sep>/Limestone/Fields/TextField.cs using System; using System.Web.Mvc; namespace Limestone.Fields { [Serializable] public class TextField : Field, IField { [AllowHtml] public string Text { get; set; } public new TextFieldSetting Settings { get { return base.Settings as TextFieldSetting; } set { base.Settings = value; } } public TextField() : base(FieldType.TextField, "") { Text = ""; } public TextField(string name) : base(FieldType.TextField, name) { } public override string GetHtml() { return Text; } } }<file_sep>/SampleSite/Areas/Limestone/Controllers/EditorController.cs using System; using System.Web.Mvc; using Limestone; using Limestone.MVC; namespace SampleSite.Areas.Limestone.Controllers { public class EditorController : Controller { public EditorController(IPageProvider pageProvider, ITemplateProvider templateProvider) { PageProvider = pageProvider; TemplateProvider = templateProvider; } protected IPageProvider PageProvider { get; set; } protected ITemplateProvider TemplateProvider { get; set; } public ActionResult Move(string pagePath, string cancelUrl) { var moveSettings = new EditPageModel { PagePath = pagePath, CancelUrl = cancelUrl }; return View("MovePage", moveSettings); } public ActionResult Copy(string pagePath, string cancelUrl) { var copySettings = new EditPageModel { PagePath = pagePath, CancelUrl = cancelUrl }; return View("CopyPage", copySettings); } public ActionResult Delete(string pagePath, string completeUrl) { PageProvider.Delete(pagePath); return Redirect(completeUrl); } public ActionResult Edit(string parentPagePath, string pagePath, string templatePath, string cancelUrl) { EditPageModel editSettings; var defaultName = "New-page"; EditedPage page; // create new page if (string.IsNullOrEmpty(pagePath)) { editSettings = new EditPageModel { ParentPagePath = parentPagePath, CancelUrl = cancelUrl, TemplatePath = templatePath }; page = new EditedPage { Name = defaultName, TemplatePath = templatePath, Path = (parentPagePath == "/") ? parentPagePath + defaultName : parentPagePath + "/" + defaultName, OriginalName = "" }; } else // edit existing page { var p = PageProvider.Get(pagePath); page = p.ToEditedPage(); editSettings = new EditPageModel { ParentPagePath = parentPagePath, PagePath = pagePath, CancelUrl = cancelUrl, Page = page, TemplatePath = page.TemplatePath }; } // creating new page but haven't selected a template yet if (string.IsNullOrEmpty(editSettings.TemplatePath)) { ViewBag.Templates = TemplateProvider.GetAll(); return View("SelectTemplate", editSettings); } TemplateProvider.SyncPageWithTemplate(page); TemplateProvider.AddFieldSettings(page); editSettings.Page = page; return View("Edit", editSettings); } [HttpPost, ValidateInput(false)] public ActionResult Save(EditPageModel editData) { if (!string.IsNullOrEmpty(editData.Page.OriginalName) && editData.Page.OriginalName != editData.Page.Name) { // TODO handle changed name // make sure the original page is not moved or deleted // make sure we don't overwrite another existing page throw new Exception("name change not handled"); } PageProvider.Save(editData.Page.ToIPage()); return RedirectToAction("OpenPage", "Page", new { area = "Limestone", pagePath = editData.Page.Path.TrimStart('/') }); } } }<file_sep>/SampleSite/Global.asax.cs using System.Web.Http; using System.Web.Mvc; using System.Web.Routing; using Autofac; using Autofac.Integration.Mvc; using SampleSite.Configuration; namespace SampleSite { // Note: For instructions on enabling IIS6 or IIS7 classic mode, // visit http://go.microsoft.com/?LinkId=9394801 public class MvcApplication : System.Web.HttpApplication { protected void Application_Start() { ViewEngines.Engines.Clear(); ViewEngines.Engines.Add(new RazorViewEngine()); // Important! Limestone needs this to properly model bind the different field types // ModelBinders.Binders.Add(typeof(Field), new FieldBinder()); RegisterComponents(); AreaRegistration.RegisterAllAreas(); WebApiConfig.Register(GlobalConfiguration.Configuration); FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); RouteConfig.RegisterRoutes(RouteTable.Routes); } private void RegisterComponents() { var builder = new ContainerBuilder(); // register the MVC controllers, Views and some autofac basics builder.RegisterControllers(typeof(MvcApplication).Assembly); builder.RegisterSource(new ViewRegistrationSource()); builder.RegisterModule(new AutofacWebTypesModule()); // register module dependencies builder.RegisterModule(new LimestoneModule()); var container = builder.Build(); DependencyResolver.SetResolver(new AutofacDependencyResolver(container)); } } }<file_sep>/Limestone.Test/TestBase.cs using System; using System.IO; using System.Threading; using Limestone.Storage.XML; using NUnit.Framework; namespace Limestone.Test { public class TestBase { protected const string BasePagePath = @"c:\temp\limestone\pages"; protected const string BaseTemplatePath = @"c:\temp\limestone\templates"; protected const string BaseTrashcanPath = @"c:\temp\limestone\trashcan"; [SetUp] public void CleanUp() { ClearFolder(BasePagePath); ClearFolder(BaseTemplatePath); ClearFolder(BaseTrashcanPath); } protected static IPageProvider GetPageProvider() { return new PageProvider(GetStorage(), GetCurrentUserId(), new PageStubCache(GetStorage())); } protected static IGetCurrentUserId GetCurrentUserId() { return new GetCurrentUserFromFake("Henke"); } protected static IStorage GetStorage() { return new XmlStorage(GetXmlCfg(), GetCurrentUserId()); } protected static ITemplateProvider GetTemplateProvider() { var getCurrentUserId = new GetCurrentUserFromFake("Henke"); return new TemplateProvider(new XmlStorage(GetXmlCfg(), getCurrentUserId)); } protected static IPageStubCache GetPageStubCache() { return new PageStubCache(GetStorage()); } protected static IXmlStorageConfig GetXmlCfg() { return new XmlStorageConfig { BasePagePath = BasePagePath, BaseTemplatePath = BaseTemplatePath, BaseTrashcanPath = BaseTrashcanPath }; } protected static void ClearFolder(string folderName) { var dir = new DirectoryInfo(folderName); foreach (var fi in dir.GetFiles()) { try { fi.Delete(); } catch (Exception) { } } foreach (var di in dir.GetDirectories()) { ClearFolder(di.FullName); try { di.Delete(true); } catch (Exception) { } } } } }<file_sep>/Limestone/ITemplateProvider.cs using System.Collections.Generic; namespace Limestone { public interface ITemplateProvider { IStorage Storage { get; set; } /// <summary> /// Loads and returns a full template object. /// </summary> /// <param name="path"></param> /// <returns></returns> IPageTemplate Get(string path); /// <summary> /// persists the template to disc /// </summary> /// <returns></returns> IPageTemplate Save(IPageTemplate template); IEnumerable<IPageTemplate> GetAll(); void SyncPageWithTemplate(IPage page); /// <summary> /// Loads fieldsettings from the template and appends them to their respective field in the page /// </summary> /// <param name="page"></param> void AddFieldSettings(IPage page); } }<file_sep>/Limestone/Fields/ImageField.cs using System; using System.Xml.Serialization; namespace Limestone.Fields { [Serializable] public class ImageField : Field, IField { [XmlAttribute] public string ImageUrl { get; set; } public string AlternateText { get; set; } public new ImageFieldSetting Settings { get { return base.Settings as ImageFieldSetting; } set { base.Settings = value; } } public ImageField() : base(FieldType.ImageField, "") { ImageUrl = ""; AlternateText = ""; } public ImageField(string name) : base(FieldType.ImageField, name) { ImageUrl = ""; AlternateText = ""; } public string GetHtml() { return "<img src=\"" + ImageUrl + "\" alt=\"" + AlternateText + "\" />"; } } } <file_sep>/Limestone.Storage.XML/LookUpProvider.cs using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Xml; namespace Limestone.Storage.XML { public class LookUpProvider { private readonly IFileReader _fileReader; private readonly IXmlStorageConfig _xmlStorageConfig; private XmlReaderSettings _xmlReadSettings; public LookUpProvider(IFileReader fileReader, IXmlStorageConfig xmlStorageConfig) { _fileReader = fileReader; _xmlStorageConfig = xmlStorageConfig; _xmlReadSettings = new XmlReaderSettings { ConformanceLevel = ConformanceLevel.Fragment, IgnoreWhitespace = true, IgnoreComments = true }; } public string CacheFilePath { get { return Path.Combine(_xmlStorageConfig.BasePagePath, @"Limestone.LookUpCache"); } } public IPageLookUp GetPageLookUp(bool forceDeepReload) { if (forceDeepReload || !File.Exists(CacheFilePath)) { RebuildNavigationConfig(); } var pages = new Dictionary<string, IPageStub>(StringComparer.OrdinalIgnoreCase); var byParentPath = new Dictionary<string, IEnumerable<IPageStub>>(StringComparer.OrdinalIgnoreCase); var xmlDoc = LoadCacheFile(); // TODO switch to an xmlreader to avoid in memory operations like now var pageNodes = xmlDoc.GetElementsByTagName("Page"); foreach (XmlNode xPage in pageNodes) { if (xPage.Attributes == null) continue; var path = xPage.Attributes["Path"].Value; var stub = new PageStub { Name = xPage.Attributes["Name"].Value, Path = path, Title = xPage.Attributes["Title"].Value, TemplatePath = xPage.Attributes["TemplatePath"].Value, Hidden = (bool.Parse(xPage.Attributes["Hidden"].Value)) }; pages.Add(path, stub); // the root page should be added to the byParentId list if (stub.Path == "/") continue; var parentPath = "/"; // not root pages if (path.LastIndexOf("/", StringComparison.Ordinal) > 0) { // identify index-pages if (stub.Name == _xmlStorageConfig.FolderIndexPageName) { parentPath = path.Substring(0, path.LastIndexOf("/", StringComparison.Ordinal)); var idx = parentPath.LastIndexOf("/", StringComparison.Ordinal); if (idx == 0) parentPath = "/"; else parentPath = (parentPath.Substring(0, idx + 1) + _xmlStorageConfig.FolderIndexPageName + ".page").ToLower(); } else parentPath = PageHelper.GetParentPath(path); } if (byParentPath.ContainsKey(parentPath)) byParentPath[parentPath] = byParentPath[parentPath].Concat(new[] { stub }); else { byParentPath.Add(parentPath, new[] { stub }); } } return new PageLookUp { Pages = pages, PagesByParentId = byParentPath }; } private XmlDocument LoadCacheFile() { var xmlDoc = new XmlDocument(); var attempts = 5; Exception cannotReadException = null; while (attempts > 0) { try { using (var fileStream = new FileStream(CacheFilePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)) { xmlDoc.Load(fileStream); attempts = 0; } } catch (Exception exception) { cannotReadException = exception; System.Threading.Thread.Sleep(100); attempts--; } } if (cannotReadException != null) { throw cannotReadException; } return xmlDoc; } /// <summary> /// /// </summary> /// <param name="stub">The page stub to add</param> /// <param name="parentPath">The path to the parent page</param> public void AddPageStub(IPageStub stub, string parentPath) { // load the XML document var navDoc = new XmlDocument(); using (var fileStream = new FileStream(CacheFilePath, FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite)) { navDoc.Load(fileStream); } // create a new node of the stub var xmlStub = navDoc.CreateElement("Page"); AddXmlAttribute(navDoc, xmlStub, "Title", stub.Title); AddXmlAttribute(navDoc, xmlStub, "Name", stub.Name); AddXmlAttribute(navDoc, xmlStub, "Path", stub.Path); AddXmlAttribute(navDoc, xmlStub, "TemplatePath", stub.TemplatePath); AddXmlAttribute(navDoc, xmlStub, "Hidden", (stub.Hidden) ? "true" : "false"); var parentNode = EnsureNode(navDoc, parentPath); if (parentNode == null) return; parentNode.AppendChild(xmlStub); // write the document back to the file system using (TextWriter sw = new StreamWriter(CacheFilePath, false, Encoding.UTF8)) { navDoc.Save(sw); } } private XmlNode EnsureNode(XmlDocument navDoc, string path) { var node = navDoc.SelectSingleNode("//Page[@Path='" + path + "']"); if (node != null) return node; var name = path.Substring(path.LastIndexOf(@"/") + 1); // create a new node of the stub var xmlStub = navDoc.CreateElement("Page"); AddXmlAttribute(navDoc, xmlStub, "Title", name); AddXmlAttribute(navDoc, xmlStub, "Name", name); AddXmlAttribute(navDoc, xmlStub, "Path", path); AddXmlAttribute(navDoc, xmlStub, "TemplatePath", ""); AddXmlAttribute(navDoc, xmlStub, "Hidden", "false"); var parentPath = PageHelper.GetParentPath(path); //var parentNode = parentPath == "/" ? navDoc.SelectSingleNode("//LookUpCache") : EnsureNode(navDoc, parentPath); var parentNode = EnsureNode(navDoc, parentPath); // add the new node return parentNode.AppendChild(xmlStub); } private static void AddXmlAttribute(XmlDocument navDoc, XmlElement xmlStub, string attributeName, string attributeValue) { var attr = navDoc.CreateAttribute(attributeName); attr.Value = attributeValue; xmlStub.Attributes.Append(attr); } public void RemovePageStub(string path) { // load the XML document var navDoc = new XmlDocument(); using (var fileStream = new FileStream(CacheFilePath, FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite)) { navDoc.Load(fileStream); } // find the element(s) we want to remove, using an XPath query var node = navDoc.SelectSingleNode("//Page[@Path='" + path + "']"); if (node == null || node.ParentNode == null) return; node.ParentNode.RemoveChild(node); // write the document back to the file system using (TextWriter sw = new StreamWriter(CacheFilePath, false, Encoding.UTF8)) { navDoc.Save(sw); } } public void MovePageStub(string oldPath, string newParentPath) { // load the XML document var navDoc = new XmlDocument(); using (var fileStream = new FileStream(CacheFilePath, FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite)) { navDoc.Load(fileStream); } // find the element(s) we want to remove, using an XPath query var node = navDoc.SelectSingleNode("//Page[@Path='" + oldPath + "']"); var newParentNode = navDoc.SelectSingleNode("//Page[@Path='" + newParentPath + "']"); if (node == null || newParentNode == null) return; newParentNode.AppendChild(node.CloneNode(true)); node.ParentNode.RemoveChild(node); // write the document back to the file system using (TextWriter sw = new StreamWriter(CacheFilePath, false, Encoding.UTF8)) { navDoc.Save(sw); } } // TODO consider speeding up by perhaps this one http://www.codeproject.com/KB/files/FastDirectoryEnumerator.aspx // or possible a deep search http://msdn.microsoft.com/en-us/library/ms143448%28VS.85%29.aspx /// <summary> /// This is a resource consuming process. Do not call it unless you know what you do /// </summary> /// <returns></returns> public bool RebuildNavigationConfig() { var writeSettings = new XmlWriterSettings { Indent = true, Encoding = Encoding.UTF8 }; var writer = XmlWriter.Create(CacheFilePath, writeSettings); writer.WriteStartDocument(); writer.WriteStartElement("Page"); writer.WriteAttributeString("CreationTime", DateTime.Now.ToShortDateString()); writer.WriteAttributeString("Path", "/"); writer.WriteAttributeString("Name", "Start"); writer.WriteAttributeString("Title", "Start"); writer.WriteAttributeString("TemplatePath", "Start"); writer.WriteAttributeString("Hidden", "false"); WriteNavigationXmlForDirectory(_xmlStorageConfig.BasePagePath, ref writer); writer.WriteEndElement(); writer.WriteEndDocument(); writer.Close(); return true; } private void WriteNavigationXmlForDirectory(string directoryPath, ref XmlWriter writer) { // possible sub pages and sub directories var di = new DirectoryInfo(directoryPath); var files = di.GetFiles("*.page"); var directories = di.GetDirectories(); // .page-files foreach (var fileInfo in files.Where(fileInfo => Path.GetFileNameWithoutExtension(fileInfo.FullName).ToLower() != _xmlStorageConfig.FolderIndexPageName.ToLower())) { WritePageStubXMLFromFile(ref writer, fileInfo.FullName, true); } // directories foreach (var directoryInfo in directories) { // begin page element WritePageStubXMLFromFile(ref writer, Path.Combine(directoryInfo.FullName, _xmlStorageConfig.FolderIndexPageName + ".page"), false); writer.WriteStartElement("Pages"); WriteNavigationXmlForDirectory( directoryInfo.FullName, ref writer); // end pages element writer.WriteEndElement(); // end page element writer.WriteEndElement(); } } private void WritePageStubXMLFromFile(ref XmlWriter writer, string filePath, bool closeElement) { var stub = _fileReader.ReadPageFile(filePath); if (stub == null) { stub = new PageStub() { Name = Path.GetFileNameWithoutExtension(filePath), Path = filePath.Substring(_xmlStorageConfig.BasePagePath.Length).Replace(@"\", "/"), Title = Path.GetFileNameWithoutExtension(filePath), TemplatePath = "", Hidden = false, }; } // write to the cache file WritePageXml(writer, stub); if (closeElement) writer.WriteEndElement(); } private static void WritePageXml(XmlWriter writer, IPageStub stub) { writer.WriteStartElement("Page"); writer.WriteAttributeString("Name", stub.Name); writer.WriteAttributeString("Path", stub.Path); writer.WriteAttributeString("Title", stub.Title); writer.WriteAttributeString("TemplatePath", stub.TemplatePath); writer.WriteAttributeString("Hidden", stub.Hidden.ToString()); } } }<file_sep>/Limestone/PageStub.cs using System; using System.Xml.Serialization; namespace Limestone { [Serializable] [XmlRoot("parameters", Namespace = "http://www.limestone.se", IsNullable = false)] public class PageStub : IPageStub { public string Name { get; set; } public string Path { get; set; } public string Title { get; set; } public string TemplatePath { get; set; } public bool Hidden { get; set; } public PageStub(){} public PageStub(string name, string path, string title, string templatePath, bool hidden) { Name = name; Path = path; Title = title; TemplatePath = templatePath; Hidden = hidden; } } } <file_sep>/Limestone/PageStubCache.cs using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Web; namespace Limestone { public class PageStubCache : IPageStubCache { #region props and ctx public IStorage Storage { get; set; } public bool IsLoaded { get; private set; } public PageStubCache(IStorage storage) { Storage = storage; // if (IsLoaded) return; // // // todo lock or check loading state or similar // LoadPageLookUpCache(); // IsLoaded = true; } private Dictionary<string, IEnumerable<IPageStub>> ByParentPath { get { var byParentPath = (Dictionary<string, IEnumerable<IPageStub>>)HttpRuntime.Cache["lime_allItemsByParentPath"]; if (byParentPath == null) { LoadPageLookUpCache(false); byParentPath = (Dictionary<string, IEnumerable<IPageStub>>)HttpRuntime.Cache["lime_allItemsByParentPath"]; } return byParentPath; } set { HttpRuntime.Cache["lime_allItemsByParentPath"] = value; } } private Dictionary<string, IPageStub> Pages { get { var pageStubs = (Dictionary<string, IPageStub>)HttpRuntime.Cache["lime_allItems"]; if (pageStubs == null) { LoadPageLookUpCache(false); pageStubs = (Dictionary<string, IPageStub>)HttpRuntime.Cache["lime_allItems"]; } return pageStubs; } set { HttpRuntime.Cache["lime_allItems"] = value; } } #endregion /// <summary> /// Caches all parent-child relations /// </summary> /// <param name="forceDeepReload"> </param> public void LoadPageLookUpCache(bool forceDeepReload) { var lookUpCache = Storage.GetPageLookUp(forceDeepReload); Pages = lookUpCache.Pages; ByParentPath = lookUpCache.PagesByParentId; } public void AddPageStub(IPageStub stub, string parentPath) { parentPath = parentPath.ToLower(); EnsureParentPathExists(parentPath); ByParentPath[parentPath] = ByParentPath[parentPath].Concat(new[] { stub }); if (!Pages.ContainsKey(stub.Path.ToLower())) Pages.Add(stub.Path, stub); Storage.AddPageToLookUp(stub); } private void EnsureParentPathExists(string parentPath) { if (ByParentPath.ContainsKey(parentPath)) return; var grandParentPath = PageHelper.GetParentPath(parentPath); if (grandParentPath != "/") EnsureParentPathExists(grandParentPath); ByParentPath.Add(parentPath, Enumerable.Empty<IPageStub>()); } /// <summary> /// Returns list of pagestubs that are direct descendants of path /// </summary> /// <param name="path"></param> /// <returns></returns> public IEnumerable<IPageStub> GetChildPageStubsFor(string path) { IEnumerable<IPageStub> children; ByParentPath.TryGetValue(path, out children); return children ?? Enumerable.Empty<IPageStub>(); } public IEnumerable<IPageStub> GetRootPageStubs(bool excludeHidden) { return GetChildPageStubsFor("/"); } public bool IsCached(string path) { return Pages.ContainsKey(path); } /// <summary> /// A quicker look up function /// </summary> /// <param name="path"></param> public IPageStub GetPageStub(string path) { IPageStub stub; Pages.TryGetValue(path.ToLower(), out stub); return stub; } public void RemovePageStub(string pagePath) { pagePath = pagePath.ToLower(); var parentPath = PageHelper.GetParentPath(pagePath).ToLower(); // get the page and its children to be removed var childPaths = GetAllChildPaths(pagePath).Concat(new[] { pagePath }); // do not operate directly on the caches when we have several operations to perform // TODO clone or lock var pagesTemp = Pages; var byParentPaths = ByParentPath; // remove the paths from the cache foreach (var childPath in childPaths) { pagesTemp.Remove(childPath); if (byParentPaths.ContainsKey(childPath)) byParentPaths.Remove(childPath); } // remove the page itself from its parent child listing byParentPaths[parentPath] = byParentPaths[parentPath].Where(p => p.Path != pagePath); // update caches Pages = pagesTemp; ByParentPath = byParentPaths; Storage.RemovePageFromLookUp(pagePath); } // Gather all paths in a single dimensional list private IEnumerable<string> GetAllChildPaths(string path) { IEnumerable<string> grandchildren = new string[] { }; IEnumerable<IPageStub> stubs; ByParentPath.TryGetValue(path, out stubs); if (stubs == null) return Enumerable.Empty<string>(); var children = stubs.Select(p => p.Path); foreach (var childPath in children) { grandchildren = children.Concat(GetAllChildPaths(childPath)); } return children.Concat(grandchildren); } public void MovePageStub(string oldPagePath, string newParentPath) { var stub = GetPageStub(oldPagePath); RemovePageStub(stub.Path); stub.Path = newParentPath.Last() == '/' ? newParentPath + stub.Name : newParentPath + "/" + stub.Name; AddPageStub(stub, newParentPath); } public ILimeMapNode GetSiteMap(bool includeHidden) { return new LimeMapNode { Nodes = GetMapNodes(new []{GetPageStub("/")}) }; } private IEnumerable<LimeMapNode> GetMapNodes(IEnumerable<IPageStub> nodes) { /* var res = new LimeMapNode[] {}; foreach (var node in nodes) { var children = GetChildPageStubsFor(node.Path); var child = new LimeMapNode { PageStub = node, Nodes = GetMapNodes(children) }; res = res.Concat(new[] {child}).ToArray(); } return res; */ return nodes.Select(pageStub => new LimeMapNode { PageStub = pageStub, Nodes = GetMapNodes(GetChildPageStubsFor(pageStub.Path)) }); } } }<file_sep>/Limestone/MVC/HtmlHelpers.cs using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; namespace Limestone.MVC { public static class HtmlHelpers { public static IHtmlString DisplayField(this HtmlHelper html, IField field) { return new HtmlString((field == null) ? "" : field.GetHtml()); } public static IHtmlString LimeMap(this HtmlHelper html, IEnumerable<ILimeMapNode> nodes) { string htmlOutput = string.Empty; if (nodes.Any()) { htmlOutput += "<ul>"; foreach (var node in nodes) { var css = (node.PageStub.Hidden) ? "page hidden" : "page"; htmlOutput += "<li class=\"node\" data-path=\""+node.PageStub.Path+"\">" + "<div class=\"" + css + "\">" + "<div class=\"path\">" + node.PageStub.Path + "</div>" + node.PageStub.Title + "<div class=\"btn-group operate\">" + " <a class=\"btn dropdown-toggle\" data-toggle=\"dropdown\" href=\"#\"><span class=\"caret\"></span></a>" + " <ul class=\"dropdown-menu\">" + " <li><a href=\"#\"><i class=\"icon-play\"></i> View</a></li>" + " <li><a href=\"#\"><i class=\"icon-pencil\"></i> Edit</a></li>" + " <li><a href=\"#\"><i class=\"icon-trash\"></i> Delete</a></li>" + " <li><a href=\"#\"><i class=\"icon-eye-close\"></i> Hide</a></li>" + " </ul>" + "</div>" + "<a class=\"btn btn-large add\" href=\"#\"><i class=\"icon-plus\"></i></a>" + "</div>" + html.LimeMap(node.Nodes) + "</li>"; } htmlOutput += "</ul>"; } return new MvcHtmlString(htmlOutput); } } } <file_sep>/Limestone.Test/PageStubCacheFixture.cs using System; using System.Threading; using Limestone.Storage.XML; using NUnit.Framework; namespace Limestone.Test { [TestFixture] public class PageStubCacheFixture:TestBase { [SetUp] public void CleanUp() { try { ClearFolder(BasePagePath); ClearFolder(BaseTemplatePath); ClearFolder(BaseTrashcanPath); } catch (Exception) { Thread.Sleep(2000); ClearFolder(BasePagePath); ClearFolder(BaseTemplatePath); ClearFolder(BaseTrashcanPath); } } [Test] public void AddStub() { var getCurrentUserId = new GetCurrentUserFromFake("Henke"); var storage = new XmlStorage(GetXmlCfg(), getCurrentUserId); var cache = new PageStubCache(storage); PopCache(cache); Assert.IsNotNull(cache.GetPageStub("/alpha.page")); Assert.IsNotNull(cache.GetPageStub("/beta.page")); Assert.IsNotNull(cache.GetPageStub("/alpha/gamma.page")); Assert.IsNotNull(cache.GetPageStub("/alpha/gamma/theta.page")); } [Test] public void RemoveStub() { var getCurrentUserId = new GetCurrentUserFromFake("Henke"); var storage = new XmlStorage(GetXmlCfg(), getCurrentUserId); var cache = new PageStubCache(storage); PopCache(cache); cache.RemovePageStub("/alpha.page"); Assert.IsNull(cache.GetPageStub("/alpha.page")); Assert.IsNull(cache.GetPageStub("/alpha/gamma.page")); Assert.IsNull(cache.GetPageStub("/alpha/gamma/theta.page")); } private static void PopCache(PageStubCache cache) { cache.AddPageStub(new PageStub("Alpha", "/alpha.page", "Alpha title", "/alphatemplate", false), "/"); cache.AddPageStub(new PageStub("Beta", "/beta.page", "Beta title", "/betatemplate", false), "/"); cache.AddPageStub(new PageStub("Gamma", "/alpha/gamma.page", "Gamma title", "/gammatemplate", false), "/alpha.page"); cache.AddPageStub(new PageStub("Theta", "/alpha/gamma/theta.page", "Theta title", "/thetatemplate", false), "/alpha/gamma.page"); } } }<file_sep>/Limestone.Storage.XML/XmlStorageConfig.cs using System.Web; namespace Limestone.Storage.XML { public class XmlStorageConfig:IXmlStorageConfig { public string FolderIndexPageName { get; set; } public string BasePagePath { get; set; } public string BaseTemplatePath { get; set; } public string BaseTrashcanPath { get; set; } public XmlStorageConfig() { FolderIndexPageName = "_folderindex"; } public XmlStorageConfig(HttpContext httpContext) { BasePagePath = httpContext.Server.MapPath("/Pages/").Replace("/", @"\"); BaseTemplatePath = httpContext.Server.MapPath("/Templates/").Replace("/", @"\"); BaseTrashcanPath = httpContext.Server.MapPath("/Trashcan/").Replace("/", @"\"); FolderIndexPageName = "_folderindex"; } } } <file_sep>/Limestone/IField.cs namespace Limestone { public interface IField { string Name { get; set; } FieldType Type { get; set; } int Index { get; set; } string GetHtml(); IFieldSetting Settings { get; set; } } }<file_sep>/Limestone/IPageStubCache.cs using System.Collections.Generic; namespace Limestone { public interface IPageStubCache { IStorage Storage { get; set; } /// <summary> /// Caches all parent-child relations /// </summary> /// <param name="forceDeepReload">Ensures that the cache is rebuilt from scratch</param> void LoadPageLookUpCache(bool forceDeepReload); void AddPageStub(IPageStub stub, string parentPath); /// <summary> /// Returns list of pagestubs that are direct descendants of path /// </summary> /// <param name="path"></param> /// <returns></returns> IEnumerable<IPageStub> GetChildPageStubsFor(string path); IEnumerable<IPageStub> GetRootPageStubs(bool excludeHidden); bool IsCached(string path); /// <summary> /// A quicker look up function /// </summary> /// <param name="path"></param> IPageStub GetPageStub(string path); void RemovePageStub(string pagePath); void MovePageStub(string oldPagePath, string newParentPath); ILimeMapNode GetSiteMap(bool includeHidden); } }<file_sep>/Limestone.Storage.XML/IXmlStorageConfig.cs namespace Limestone.Storage.XML { public interface IXmlStorageConfig { string FolderIndexPageName { get; set; } string BasePagePath { get; set; } string BaseTemplatePath { get; set; } string BaseTrashcanPath { get; set; } } }<file_sep>/Limestone/Fields/PageFieldSetting.cs using System; namespace Limestone.Fields { [Serializable] public class PageFieldSetting : FieldSetting, IFieldSetting { public PageFieldSetting() : base(FieldType.TextField, "") { Name = ""; } public PageFieldSetting(string name) : base(FieldType.PageField, name) { } } } <file_sep>/SampleSite/App_Start/RouteConfig.cs using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using System.Web.Routing; using Limestone; using Limestone.MVC; namespace SampleSite { public class RouteConfig { public static void RegisterRoutes(RouteCollection routes) { // resolve the pagestubcache with autoFac var pageStubCache = (IPageStubCache)DependencyResolver.Current.GetService(typeof(IPageStubCache)); var pageProvider = (IPageProvider)DependencyResolver.Current.GetService(typeof(IPageProvider)); routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); routes.IgnoreRoute("{resource}.aspx"); routes.IgnoreRoute("{*staticfile}", new { staticfile = @".*\.(jpg|gif|jpeg|png|js|css|htm|html|htc|flv|swf|ico|bmp|xml)$" }); // explicitly adding routes as the page catchall route below otherwise will get em all // handle pages using the OrderForm template //routes.MapRoute("orderForm", // "{*pagepath}", // new { controller = "Order", action = "PlaceOrder" }, // new { pagePath = new HandledPagePathConstraint(pageProvider, "OrderForm") } // ); // all other pages will go to the PageController routes.MapRoute("Pages", "{*pagepath}", new { controller = "Page", action = "OpenPage" }, new { pagePath = new PagePathConstraint(pageStubCache) } ); // will probably never reach here... routes.MapRoute( "Default", // Route name "{controller}/{action}/{id}", // URL with parameters new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults ); } } }<file_sep>/SampleSite/Scripts/limestone.js  /* ============================== FIELD EDITOR ============================== */ /* ============================== TEMPLATE EDITOR ============================== */ /* ============================== FILE BROWSER ============================== */ var fileBrowserCallers = new Array(); function BrowseToFile(targetElId, fileType) { var callerNo = fileBrowserCallers.length; fileBrowserCallers[callerNo] = targetElId; OpenDialog("/limestone/filebrowser?caller=custom&type=" + fileType + "&CKEditorFuncNum=" + callerNo); } function onFileBrowseComplete(callerNo, path) { $('#' + fileBrowserCallers[callerNo]).val(path); } /* ============================== PAGE BROWSER ============================== */ var pageBrowserCallers = new Array(); function BrowseToPage(targetElId) { var callerNo = pageBrowserCallers.length; pageBrowserCallers[callerNo] = targetElId; OpenDialog("/limestone/PageBrowser?callerNo=" + callerNo); } function onPageBrowseComplete(callerNo, path) { $('#' + pageBrowserCallers[callerNo]).val(path); } /* ============================== DIALOG ============================== */ function OpenDialog(url, width, height) { width = width || '80%'; height = height || '70%'; if (typeof width == 'string' && width.length > 1 && width.substr(width.length - 1, 1) == '%') width = parseInt(window.screen.width * parseInt(width, 10) / 100, 10); if (typeof height == 'string' && height.length > 1 && height.substr(height.length - 1, 1) == '%') height = parseInt(window.screen.height * parseInt(height, 10) / 100, 10); if (width < 640) width = 640; if (height < 420) height = 420; var top = parseInt((window.screen.height - height) / 2, 10); var left = parseInt((window.screen.width - width) / 2, 10); var settings = 'location=no,menubar=no,toolbar=no,dependent=yes,minimizable=no,modal=yes,alwaysRaised=yes,resizable=yes,width=' + width + ',height=' + height + ',top=' + top + ',left=' + left; var dialog = window.open('', null, settings, true); if (!dialog) return false; try { dialog.moveTo(top, left); dialog.resizeTo(width, height); dialog.focus(); dialog.location.href = url; } catch (s) { dialog = window.open(url, null, settings, true); } return true; }<file_sep>/SampleSite/Areas/Limestone/Controllers/TemplateDesignerController.cs using System.Web.Mvc; using Limestone; using Limestone.MVC; namespace SampleSite.Areas.Limestone.Controllers { public class TemplateDesignerController : Controller { private readonly ITemplateProvider _templateProvider; private readonly FieldFactory _fieldFactory; public TemplateDesignerController(ITemplateProvider templateProvider, FieldFactory fieldFactory) { _templateProvider = templateProvider; _fieldFactory = fieldFactory; } public ActionResult Index() { return View(_templateProvider.GetAll()); } public ActionResult New(DesignedTemplate template) { if (template != null && template.Name != null) return Save(template); template = new DesignedTemplate(); return View("TemplateDesigner", template); } [HttpGet] public ActionResult Edit(string templatePath) { var template = _templateProvider.Get(templatePath); if (template == null) return View("Error"); return View("TemplateDesigner", template.ToDesignedTemplate()); } [HttpPost] public ActionResult Save(DesignedTemplate designedTemplate) { var newTemplate = _templateProvider.Save(designedTemplate.ToIPageTemplate()); return View("TemplateDesigner", newTemplate.ToDesignedTemplate()); } public ActionResult Design(DesignedTemplate template) { if (!string.IsNullOrEmpty(template.NewFieldName)) { var fldSet = _fieldFactory.CreateFieldSetting(template.NewFieldType); template.FieldSettings.Add(fldSet); } template.NewFieldName = string.Empty; return View("TemplateDesigner", template); } } }<file_sep>/Limestone/Fields/FileField.cs using System; using System.Xml.Serialization; namespace Limestone.Fields { [Serializable] public class FileField : Field, IField { public string FileUrl { get; set; } [XmlIgnore] public string FileName { get { var idx = FileUrl.LastIndexOf("/", System.StringComparison.Ordinal); return idx == -1 ? FileUrl : FileUrl.Substring(idx+1); } } public new FileFieldSetting Settings { get { return base.Settings as FileFieldSetting; } set { base.Settings = value; } } public FileField() : base(FieldType.FileField, "") { FileUrl = ""; } public FileField(string name) : base(FieldType.FileField, name) { FileUrl = ""; } public string GetHtml() { if (string.IsNullOrEmpty(FileUrl)) return ""; return "<a href=\"" + FileUrl + "\" >" + FileName + "</a>"; } } } <file_sep>/Limestone/Page.cs using System; using System.Globalization; using System.Linq; using System.Text; using System.Xml.Serialization; using Limestone.Fields; using Utils; namespace Limestone { [Serializable] [XmlRoot("Page", Namespace = "http://www.limestone.se", IsNullable = false)] public class Page :IPage { #region props and fields [XmlAttribute] public string Name { get; set; } /// <summary> /// The path always begins with a / and includes the page name /// </summary> [XmlAttribute] public string Path { get; set; } [XmlAttribute] public string Title { get; set; } [XmlAttribute] public string TemplatePath { get; set; } [XmlAttribute] public bool Hidden { get; set; } [XmlAttribute] public PageSortType SortChildPagesBy { get; set; } [XmlAttribute] public int SortValue { get; set; } [XmlArray("Fields")] [XmlArrayItem("Field", Type = typeof(AbstractXmlSerializer<Field>))] public FieldCollection Fields { get; set; } [XmlIgnore] public string ParentPath { get { return PageHelper.GetParentPath(Path); } } [XmlAttribute] public DateTime Created { get; set; } [XmlAttribute] public string CreatedBy { get; set; } [XmlAttribute] public DateTime Modified { get; set; } [XmlAttribute] public string ModifiedBy { get; set; } [XmlAttribute] public DateTime Deleted { get; set; } [XmlAttribute] public string DeletedBy { get; set; } #endregion public Page() { Fields = new FieldCollection {Page = this}; Created = new DateTime(); CreatedBy = string.Empty; SortValue = -1; SortChildPagesBy = PageSortType.Title; TemplatePath = string.Empty; Title = "New page"; Name = ToFriendlyUrl("New page"); Path = "/" + Name; } /// <summary> /// /// </summary> /// <param name="title"></param> public Page(string title) { Fields = new FieldCollection {Page = this}; Created = new DateTime(); CreatedBy = string.Empty; Hidden = false; Title = title; Name = ToFriendlyUrl(title); Path = "/" + Name; SortValue = -1; SortChildPagesBy = PageSortType.Title; TemplatePath = string.Empty; } #region Tools private string ToFriendlyUrl(string title) { var name = new StringBuilder(); foreach (var c in Title) { if (c.ToString(CultureInfo.InvariantCulture) == " ") name.Append("-"); else { if ("?&:/!#@$§{[]}".Contains(c)) continue; name.Append(c.ToString(CultureInfo.InvariantCulture)); } } // TODO unique name in this directory return name.ToString(); } #endregion } } <file_sep>/LimestoneMVC/Models/CustomViewPage.cs using System.Web.Mvc; using Limestone; namespace LimestoneMVC.Models { public abstract class CustomViewPage : WebViewPage { public IPageStubCache PageStubCache { get; set; } public IPageProvider PageProvider { get; set; } } }<file_sep>/Limestone.Test/XmlStoragePageFixture.cs using System; using System.IO; using System.Threading; using Limestone.Fields; using Limestone.Storage.XML; using NUnit.Framework; using SharpTestsEx; namespace Limestone.Test { [TestFixture] public class XmlStoragePageFixture : TestBase { [Test] public void TemplateCreate() { var templateProvider = GetTemplateProvider(); /* Index */ var index = new PageTemplate { Name = "Index", HelpText = "", Path = "/Index" }; var tfld = new TextFieldSetting("content") { HelpText = "", Title = "Content", EditMode = TextEditMode.Rich, Multiline = true }; index.FieldSettings.Add(tfld); templateProvider.Save(index); var template = templateProvider.Get("/index"); Assert.AreEqual(index.Name, template.Name); } [Test] public void PageCreate() { var pageProvider = GetPageProvider(); /* Index */ var index = new Page("A title") { Name = "Start", Path = "/" }; pageProvider.Save(index); var page = pageProvider.Get("/"); Assert.AreEqual(index.Name, page.Name); } [Test] public void PageStructureCreate() { var pageProvider = GetPageProvider(); /* wicked path */ var index = new Page("A title") { Name = "Start", Path = "/a/wicked/long/path/to/my/page" }; pageProvider.Save(index); var page = pageProvider.Get("/a/wicked/long/path/to/my/page"); Assert.AreEqual(index.Name, page.Name); } [Test] public void ChildTest() { var pageProvider = GetPageProvider(); /* mom */ var mom = new Page("A title") { Name = "mom", Path = "/mom" }; pageProvider.Save(mom); var page = pageProvider.Get("/mom"); Assert.AreEqual(mom.Name, page.Name); /* child */ var child = new Page("A child title") { Name = "child", Path = "/mom/child" }; pageProvider.Save(child); var childPage = pageProvider.Get("/mom/child"); Assert.AreEqual(child.Name, childPage.Name); Assert.IsTrue(Directory.Exists(BasePagePath + @"\mom")); Assert.IsTrue(File.Exists(BasePagePath + @"\mom\" + GetXmlCfg().FolderIndexPageName + ".page")); Assert.IsFalse(File.Exists(BasePagePath + @"\mom.page")); // TODO kolla navigation } [Test] public void DeletePage() { var pageProvider = GetPageProvider(); var pageStubCache = GetPageStubCache(); /* mom */ var goner = new Page("A title") { Name = "goner", Path = "/goner" }; pageProvider.Save(goner); var page = pageProvider.Get("/goner"); Assert.AreEqual(goner.Name, page.Name); pageProvider.Delete(goner); Assert.IsNull(pageProvider.Get("/goner")); Assert.IsFalse(File.Exists(BasePagePath + @"\goner.page")); Assert.IsTrue(File.Exists(BaseTrashcanPath + @"\goner.page")); Assert.IsNull(pageStubCache.GetPageStub("/goner")); } [Test] public void DeleteDirectory() { var pageProvider = GetPageProvider(); var pageStubCache = GetPageStubCache(); // directories pageProvider.Save(new Page("A title") { Name = "gonerParent", Path = "/gonerParent" }); pageProvider.Save(new Page("A title") { Name = "goner", Path = "/gonerParent/goner" }); pageProvider.Delete("/gonerParent"); pageProvider.Get("/gonerParent").Should().Be.Null(); File.Exists(BasePagePath + @"\gonerParent.page").Should().Be.False(); pageStubCache.GetPageStub("/gonerParent").Should().Be.Null(); File.Exists(BaseTrashcanPath + @"\gonerParent\goner.page").Should().Be.True(); } [Test] public void DeleteMultipleTest() { var pageProvider = GetPageProvider(); var pageStubCache = GetPageStubCache(); // pages pageProvider.Save(new Page("A title") { Name = "goner", Path = "/goner" }); pageProvider.Delete("/goner"); pageProvider.Save(new Page("A title") { Name = "goner", Path = "/goner" }); pageProvider.Delete("/goner"); // directories pageProvider.Save(new Page("A title") { Name = "gonerParent", Path = "/gonerParent" }); pageProvider.Save(new Page("A title") { Name = "goner", Path = "/gonerParent/goner" }); pageProvider.Delete("/gonerParent"); pageProvider.Save(new Page("A title") { Name = "gonerParent", Path = "/gonerParent" }); pageProvider.Save(new Page("A title") { Name = "goner", Path = "/gonerParent/goner" }); pageProvider.Delete("/gonerParent"); pageProvider.Get("/goner").Should().Be.Null(); File.Exists(BasePagePath + @"\goner.page").Should().Be.False(); pageStubCache.GetPageStub("/goner").Should().Be.Null(); File.Exists(BaseTrashcanPath + @"\goner.page").Should().Be.True(); File.Exists(BaseTrashcanPath + @"\goner (1).page").Should().Be.True(); pageProvider.Get("/gonerParent").Should().Be.Null(); File.Exists(BasePagePath + @"\gonerParent.page").Should().Be.False(); pageStubCache.GetPageStub("/gonerParent").Should().Be.Null(); Directory.Exists(BaseTrashcanPath + @"\gonerParent").Should().Be.True(); Directory.Exists(BaseTrashcanPath + @"\gonerParent (1)").Should().Be.True(); } [Test] public void Testfilepathstuff() { var pageProvider = GetPageProvider(); pageProvider.Save(new Page("A title") { Name = "goner", Path = "/goner" }); var newFileName = GetUniqueDiscName(@"c:\temp\limestone\pages\goner.page"); var newFolderName = GetUniqueDiscName(@"c:\temp\limestone\unique"); var newFolderDoubleName = GetUniqueDiscName(@"c:\temp\limestone\pages"); Assert.AreEqual("goner (1)", newFileName); Assert.AreEqual("unique", newFolderName); Assert.AreEqual("pages (1)", newFolderDoubleName); } private string GetUniqueDiscName(string desiredTargetPath, int attempt = 0) { var tryPath = desiredTargetPath; if (attempt > 0) { tryPath = Path.Combine(Path.GetDirectoryName(desiredTargetPath), Path.GetFileNameWithoutExtension(desiredTargetPath) + " (" + attempt + ").page"); } if (File.Exists(tryPath) || Directory.Exists(tryPath)) { return GetUniqueDiscName(desiredTargetPath, attempt + 1); } return Path.GetFileNameWithoutExtension(tryPath); } [Test] public void MoveToPageDuplicateShouldFail() { var pageProvider = GetPageProvider(); var pageStubCache = GetPageStubCache(); var source = pageProvider.Save(new Page("A title") { Name = "dupe", Path = "/dupe" }); var targetParent = pageProvider.Save(new Page("A title") { Name = "targetParent", Path = "/targetParent" }); var target = pageProvider.Save(new Page("A title") { Name = "dupe", Path = "/targetParent/dupe" }); var moveResult = pageProvider.Move(source, targetParent.Path); moveResult.Should().Be.False(); pageProvider.Get("/dupe").Should().Not.Be.Null(); File.Exists(BasePagePath + @"\dupe.page").Should().Be.True(); pageStubCache.GetPageStub("/dupe").Should().Not.Be.Null(); } [Test] public void MoveToPage() { var pageProvider = GetPageProvider(); var pageStubCache = GetPageStubCache(); var source = pageProvider.Save(new Page("A title") { Name = "source", Path = "/source" }); var target = pageProvider.Save(new Page("A title") { Name = "target", Path = "/target" }); pageProvider.Move(source, target.Path); Assert.IsNull(pageProvider.Get("/source")); Assert.IsNotNull(pageProvider.Get("/target")); Assert.IsNotNull(pageProvider.Get("/target/source")); Assert.IsFalse(File.Exists(BasePagePath + @"\source.page")); Assert.IsNull(pageStubCache.GetPageStub("/source")); Assert.IsTrue(File.Exists(BasePagePath + @"\target\" + GetXmlCfg().FolderIndexPageName + ".page")); } [Test] public void LookupTinyFileCreation() { var pageProvider = GetPageProvider(); /* start */ var index = new Page("A title") { Name = "Start", Path = "/" }; pageProvider.Save(index); var cache = GetPageStubCache(); cache.LoadPageLookUpCache(true); Assert.IsNotNull(cache.GetPageStub("/")); } [Test] public void LookupFileCreation() { var pageProvider = GetPageProvider(); /* start */ var index = new Page("A title") { Name = "Start", Path = "/" }; pageProvider.Save(index); /* simple */ var simple = new Page("A title") { Name = "simple", Path = "/simple" }; pageProvider.Save(simple); var cache = GetPageStubCache(); cache.LoadPageLookUpCache(true); Assert.IsNotNull(cache.GetPageStub("/")); Assert.IsNotNull(cache.GetPageStub("/simple")); } [Test] public void LookupBigFileCreation() { var pageProvider = GetPageProvider(); /* start */ var index = new Page("A title") { Name = "Start", Path = "/" }; pageProvider.Save(index); /* simple */ var simple = new Page("A title") { Name = "simple", Path = "/simple" }; pageProvider.Save(simple); /* mom */ var mom = new Page("A title") { Name = "mom", Path = "/mom" }; pageProvider.Save(mom); /* child */ var child = new Page("A child title") { Name = "child", Path = "/mom/child" }; pageProvider.Save(child); /* wicked path */ var longPath = "/a/wicked/long/path/to/my/page"; var longPathPage = new Page("A title") { Name = "Longie", Path = longPath }; pageProvider.Save(longPathPage); var cache = GetPageStubCache(); cache.LoadPageLookUpCache(true); cache.GetPageStub("/").Should().Not.Be.Null(); //cache.GetPageStub("/a/wicked").Should().Not.Be.Null(); //cache.GetPageStub("/simple").Should().Not.Be.Null(); //cache.GetPageStub("/mom").Should().Not.Be.Null(); //cache.GetPageStub("/mom/child").Should().Not.Be.Null(); cache.GetPageStub(longPath).Should().Not.Be.Null(); } } } <file_sep>/LimestoneMVC/Models/EditedPage.cs using Limestone; namespace LimestoneMVC.Models { public class EditedPage:Page,IPage { public string OriginalName { get; set; } } }<file_sep>/Limestone/FieldSettingFactory.cs using System; using Limestone.Fields; namespace Limestone { public class FieldSettingFactory { public static IFieldSetting CreateFieldSetting(FieldType fieldType, string name) { switch (fieldType) { case FieldType.TextField: var tfld = new TextFieldSetting(name); return tfld; case FieldType.ImageField: var ifld = new ImageFieldSetting(name); return ifld; case FieldType.FileField: var ffld = new FileFieldSetting(name); return ffld; case FieldType.PageField: var pfld = new PageFieldSetting(name); return pfld; default: throw new ArgumentOutOfRangeException(); } } } } <file_sep>/LimestoneMVC/Controllers/PageController.cs using System.Web.Mvc; using Limestone; namespace LimestoneMVC.Controllers { public class PageController : Controller { private IPageProvider PageProvider { get; set; } public PageController(IPageProvider pageProvider) { PageProvider = pageProvider; } [HttpGet] public ActionResult Index() { return OpenPage("/"); } public ActionResult OpenPage(string pagePath) { if (string.IsNullOrEmpty(pagePath)) { pagePath = "/"; } var page = PageProvider.Get(pagePath); if (page == null) { return View("Error"); } var viewName = page.TemplatePath.Replace("/", ""); if (viewName == "") viewName = "start"; return View(viewName, page); } } } <file_sep>/LimestoneMVC/Models/EditPageModel.cs namespace LimestoneMVC.Models { public class EditPageModel { public string ParentPagePath { get; set; } public string PagePath { get; set; } public string CancelUrl { get; set; } public string TemplatePath { get; set; } public EditedPage Page { get; set; } } }<file_sep>/Limestone/MVC/EditedPage.cs namespace Limestone.MVC { public class EditedPage : Page, IPage { public string OriginalName { get; set; } } }<file_sep>/Limestone/IGetCurrentUserId.cs namespace Limestone { public interface IGetCurrentUserId { string CurrentUserId { get; } } }<file_sep>/SampleSite/Areas/Limestone/Models/FieldBinder.cs using System; using System.Web.Mvc; using Autofac.Integration.Mvc; using Limestone; namespace SampleSite.Areas.Limestone.Models { [ModelBinderType(typeof(Field))] public class FieldBinder : DefaultModelBinder { // TODO this should ideally reside in the Limestone assembly but for some reason Autofac wont bind to it properly protected override object CreateModel(ControllerContext controllerContext, ModelBindingContext bindingContext, Type modelType) { var fieldTypeName = controllerContext.HttpContext.Request.Form[bindingContext.ModelName + ".ModelType"]; var field = FieldFactory.CreateField(fieldTypeName); bindingContext.ModelMetadata = ModelMetadataProviders.Current.GetMetadataForType(() => field, field.GetType()); return field; } } }<file_sep>/SampleSite/Areas/Limestone/Controllers/SitemapController.cs using System.Web.Mvc; using Limestone; namespace SampleSite.Areas.Limestone.Controllers { public class SitemapController : Controller { private readonly IPageProvider _pageProvider; private readonly IPageStubCache _pageStubCache; public SitemapController(IPageProvider pageProvider, IPageStubCache pageStubCache) { _pageProvider = pageProvider; _pageStubCache = pageStubCache; } public ActionResult Index() { return View(_pageProvider.PageStubCache.GetSiteMap(false)); } public ActionResult AddPage(Page page) { // TODO validate // ensure that this is a new page!!! we do not allow editing (yet) if (_pageStubCache.GetPageStub(page.Path) != null) return Json(null); var newPage = _pageProvider.Save(page); return Json(newPage); } } }<file_sep>/Limestone/Fields/FileFieldSetting.cs using System; namespace Limestone.Fields { [Serializable] public class FileFieldSetting : FieldSetting, IFieldSetting { public FileFieldSetting() : base(FieldType.FileField, "") { Name = ""; } public FileFieldSetting(string name) : base(FieldType.FileField, name) { } } } <file_sep>/Limestone.Test/GetCurrentUserFromFake.cs namespace Limestone.Test { internal class GetCurrentUserFromFake : IGetCurrentUserId { public GetCurrentUserFromFake(string userId) { UserId = userId; } public string CurrentUserId { get { return UserId; } } protected string UserId { get; set; } } }<file_sep>/SampleSite/Configuration/LimestoneModule.cs using System; using System.Reflection; using System.Web; using System.Web.Mvc; using Autofac; using Autofac.Integration.Mvc; using Limestone; using Limestone.Fields; using Limestone.MVC; using Limestone.Storage.XML; namespace SampleSite.Configuration { public class LimestoneModule : Autofac.Module { protected override void Load(ContainerBuilder builder) { builder.RegisterType<PageProvider>().As<IPageProvider>(); builder.RegisterType<TemplateProvider>().As<ITemplateProvider>(); builder.RegisterType<PageStubCache>().As<IPageStubCache>(); builder.RegisterType<Trashcan>().As<ITrashcan>(); builder.Register(c => new GetCurrentUserFromHttpContext(HttpContext.Current)).As<IGetCurrentUserId>(); builder.RegisterType<XmlStorageConfig>().As<IXmlStorageConfig>(); builder.RegisterType<XmlStorage>().As<IStorage>(); builder.Register(c => new XmlStorageConfig(HttpContext.Current)).As<IXmlStorageConfig>(); /* builder.Register(c => new XmlStorage(HttpContext.Current.Server.MapPath("/Pages/"), HttpContext.Current.Server.MapPath("/Templates/"), HttpContext.Current.Server.MapPath("/Trashcan/"), new GetCurrentUserFromHttpContext(HttpContext.Current))).As<IStorage>(); */ builder.RegisterModelBinderProvider(); builder.RegisterModelBinders(new Assembly[] { typeof(AbstractFieldBinder).Assembly, Assembly.GetExecutingAssembly() }); } } }<file_sep>/Limestone/MVC/AbstractFieldBinder.cs using System; using System.Web.Mvc; using Autofac.Integration.Mvc; namespace Limestone.MVC { [ModelBinderType(typeof(Field))] public class AbstractFieldBinder : DefaultModelBinder { protected override object CreateModel(ControllerContext controllerContext, ModelBindingContext bindingContext, Type modelType) { var fieldTypeName = controllerContext.HttpContext.Request.Form[bindingContext.ModelName + ".Type"]; var typeValue = bindingContext.ValueProvider.GetValue(bindingContext.ModelName + ".ModelType"); var type = Type.GetType((string)typeValue.ConvertTo(typeof(string)), true); var model = Activator.CreateInstance(type); bindingContext.ModelMetadata = ModelMetadataProviders.Current.GetMetadataForType(() => model, type); //return model; var field = FieldFactory.CreateField(fieldTypeName); bindingContext.ModelMetadata = ModelMetadataProviders.Current.GetMetadataForType(() => field, field.GetType()); return field; } } }<file_sep>/Limestone.Storage.XML/PageDiscInfo.cs namespace Limestone.Storage.XML { internal class PageDiscInfo { public bool IsDirectory { get; set; } public string PageFilePath { get; set; } public string ResidesInDirectory { get; set; } } }<file_sep>/Limestone.Storage.XML/FileReader.cs using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Xml; namespace Limestone.Storage.XML { public class FileReader:IFileReader { private readonly XmlReaderSettings _xmlReaderSettings; private readonly IXmlStorageConfig _xmlStorageConfig; public FileReader(XmlReaderSettings xmlReaderSettings, IXmlStorageConfig xmlStorageConfig) { _xmlReaderSettings = xmlReaderSettings; _xmlStorageConfig = xmlStorageConfig; } public IEnumerable<IPageStub> GetPageStubsFromDirectory(string directoryPath) { var di = new DirectoryInfo(directoryPath); var files = di.GetFiles("*.page"); var directories = di.GetDirectories(); // .page-files var pages = ReadPageFiles(files); // directories var folders = ReadPageDirectories(directories); return pages.Concat(folders); } private IEnumerable<IPageStub> ReadPageDirectories(IEnumerable<DirectoryInfo> directories) { return directories.Select(directoryInfo => ReadPageFile(Path.Combine(directoryInfo.FullName, _xmlStorageConfig.FolderIndexPageName + ".page"))); } private IEnumerable<IPageStub> ReadPageFiles(IEnumerable<FileInfo> files) { return files.Where(fileInfo => Path.GetFileNameWithoutExtension(fileInfo.FullName).ToLower() != _xmlStorageConfig.FolderIndexPageName.ToLower()).Select(fileInfo => ReadPageFile(fileInfo.FullName)); } public IPageStub ReadPageFile(string filePath) { if (!File.Exists(filePath)) return null; using (var reader = XmlReader.Create(filePath, _xmlReaderSettings)) { while (reader.Read()) { if (!reader.IsStartElement()) continue; if (reader.IsEmptyElement || reader.Name != "Page") continue; var name = reader.GetAttribute("Name"); if (string.IsNullOrEmpty(name)) return null; return new PageStub() { Name = name, Path = reader.GetAttribute("Path"), Title = reader.GetAttribute("Title"), TemplatePath = reader.GetAttribute("TemplatePath"), Hidden = bool.Parse(reader.GetAttribute("Hidden")), }; } return null; } } } } <file_sep>/LimestoneMVC/Controllers/EditorController.cs using System; using System.Web.Mvc; using Limestone; using LimestoneMVC.Models; namespace LimestoneMVC.Controllers { public class EditorController : Controller { public EditorController(IPageProvider pageProvider, ITemplateProvider templateProvider) { PageProvider = pageProvider; TemplateProvider = templateProvider; } protected IPageProvider PageProvider { get; set; } protected ITemplateProvider TemplateProvider { get; set; } public ActionResult Move(string pagePath, string cancelUrl) { var moveSettings = new EditPageModel { PagePath = pagePath, CancelUrl = cancelUrl }; return View("MovePage", moveSettings); } public ActionResult Copy(string pagePath, string cancelUrl) { var copySettings = new EditPageModel { PagePath = pagePath, CancelUrl = cancelUrl }; return View("CopyPage", copySettings); } public ActionResult Delete(string pagePath, string completeUrl) { PageProvider.Delete(pagePath); return Redirect(completeUrl); } public ActionResult Edit(string parentPagePath, string pagePath, string templatePath, string cancelUrl) { EditPageModel editSettings; var defaultName = "New-page"; EditedPage page; // create new page if (string.IsNullOrEmpty(pagePath)) { editSettings = new EditPageModel { ParentPagePath = parentPagePath, CancelUrl = cancelUrl, TemplatePath = templatePath }; page = new EditedPage { Name = defaultName, TemplatePath = templatePath, Path = parentPagePath + "/" + defaultName, OriginalName = "" }; } else // edit existing page { var p = PageProvider.Get(pagePath); page = p.ToEditedPage(); editSettings = new EditPageModel { ParentPagePath = parentPagePath, PagePath = pagePath, CancelUrl = cancelUrl, Page = page, TemplatePath = page.TemplatePath }; } // creating new page but haven't selected a template yet if (string.IsNullOrEmpty(editSettings.TemplatePath)) { ViewBag.Templates = TemplateProvider.GetAll(); return View("SelectTemplate", editSettings); } TemplateProvider.SyncPageWithTemplate(page); TemplateProvider.AddFieldSettings(page); editSettings.Page = page; return View("Edit", editSettings); } [HttpPost] public ActionResult Save(EditPageModel editData) { if (!string.IsNullOrEmpty(editData.Page.OriginalName) && editData.Page.OriginalName != editData.Page.Name) { // TODO handle changed name // make sure the original page is moved or deleted // make sure we don't overwrite another existing page throw new Exception("name change not handled"); } PageProvider.Save(editData.Page.ToIPage()); return RedirectToAction("OpenPage", "Page", new { pagePath = editData.Page.Path.TrimStart('/') }); } } public static class Extensions { public static IPage ToIPage(this EditedPage p) { return new Page { Created = p.Created, Deleted = p.Deleted, Hidden = p.Hidden, CreatedBy = p.CreatedBy, DeletedBy = p.DeletedBy, Fields = p.Fields, Modified = p.Modified, ModifiedBy = p.ModifiedBy, Name = p.Name, Path = p.Path, SortChildPagesBy = p.SortChildPagesBy, SortValue = p.SortValue, TemplatePath = p.TemplatePath, Title = p.Title }; } public static EditedPage ToEditedPage(this IPage p) { return new EditedPage { Created = p.Created, Deleted = p.Deleted, Hidden = p.Hidden, CreatedBy = p.CreatedBy, DeletedBy = p.DeletedBy, Fields = p.Fields, Modified = p.Modified, ModifiedBy = p.ModifiedBy, Name = p.Name, Path = p.Path, SortChildPagesBy = p.SortChildPagesBy, SortValue = p.SortValue, TemplatePath = p.TemplatePath, Title = p.Title, OriginalName = p.Name }; } } }<file_sep>/Limestone/Field.cs using System; using System.Web.Mvc; using System.Xml.Serialization; namespace Limestone { [Serializable] [XmlRoot("Field", Namespace = "http://www.limestone.se", IsNullable = false)] public class Field : IField { [XmlAttribute] public string Name { get; set; } [XmlAttribute] public int Index { get; set; } [XmlAttribute] public FieldType Type { get; set; } public Field() { } public Field (FieldType type, string name) { Type = type; Name = name; } // I can't make this abstract since I need to be able to serialize this class public virtual string GetHtml() { throw new NotSupportedException("First cast this field to its specific type, then use the overriden GetHtml() instead"); } [XmlIgnore] public virtual IFieldSetting Settings { get; set; } } } <file_sep>/Limestone/MVC/ExtensionMethods.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Limestone.MVC { public static class ExtensionMethods { public static IPage ToIPage(this EditedPage p) { return new Page { Created = p.Created, Deleted = p.Deleted, Hidden = p.Hidden, CreatedBy = p.CreatedBy, DeletedBy = p.DeletedBy, Fields = p.Fields, Modified = p.Modified, ModifiedBy = p.ModifiedBy, Name = p.Name, Path = p.Path, SortChildPagesBy = p.SortChildPagesBy, SortValue = p.SortValue, TemplatePath = p.TemplatePath, Title = p.Title }; } public static EditedPage ToEditedPage(this IPage p) { return new EditedPage { Created = p.Created, Deleted = p.Deleted, Hidden = p.Hidden, CreatedBy = p.CreatedBy, DeletedBy = p.DeletedBy, Fields = p.Fields, Modified = p.Modified, ModifiedBy = p.ModifiedBy, Name = p.Name, Path = p.Path, SortChildPagesBy = p.SortChildPagesBy, SortValue = p.SortValue, TemplatePath = p.TemplatePath, Title = p.Title, OriginalName = p.Name }; } public static DesignedTemplate ToDesignedTemplate(this IPageTemplate template) { return new DesignedTemplate { Name = template.Name, HelpText = template.HelpText, Path = template.Path, FieldSettings = template.FieldSettings }; } public static IPageTemplate ToIPageTemplate(this DesignedTemplate template) { return new PageTemplate { Name = template.Name, HelpText = template.HelpText, Path = template.Path, FieldSettings = template.FieldSettings }; } } } <file_sep>/LimestoneMVC/Configuration/LimestoneModule.cs using System.Web; using Autofac; using Limestone; using Limestone.Storage.XML; namespace LimestoneMVC.Configuration { public class LimestoneModule : Autofac.Module { protected override void Load(ContainerBuilder builder) { builder.RegisterType<PageProvider>().As<IPageProvider>(); builder.RegisterType<TemplateProvider>().As<ITemplateProvider>(); builder.RegisterType<PageStubCache>().As<IPageStubCache>(); builder.Register(c => new GetCurrentUserFromHttpContext(HttpContext.Current)).As<IGetCurrentUserId>(); builder.Register(c => new XmlStorage(HttpContext.Current.Server.MapPath("/Pages/"), HttpContext.Current.Server.MapPath("/Templates/"), HttpContext.Current.Server.MapPath("/Trashcan/"), new GetCurrentUserFromHttpContext(HttpContext.Current))).As<IStorage>(); } } }<file_sep>/Limestone/IPageLookUp.cs using System.Collections.Generic; namespace Limestone { public interface IPageLookUp { Dictionary<string, IPageStub> Pages { get; set; } Dictionary<string, IEnumerable<IPageStub>> PagesByParentId { get; set; } } }<file_sep>/Limestone/Trashcan.cs using System.Collections.Generic; namespace Limestone { public class Trashcan : ITrashcan { public Trashcan(IStorage storage) { Storage = storage; } public IStorage Storage { get; set; } public IEnumerable<IPageStub> GetRootPageStubs() { return Storage.GetTrashCanRootPageStubs(); } } }<file_sep>/Limestone/Fields/ImageFieldSetting.cs using System; namespace Limestone.Fields { [Serializable] public class ImageFieldSetting : FieldSetting, IFieldSetting { public ImageFieldSetting() : base(FieldType.TextField, "") { this.Name = ""; } public ImageFieldSetting(string name) : base(FieldType.ImageField, name) { } } } <file_sep>/Limestone/PageTemplate.cs using System; using System.Xml.Serialization; using Utils; namespace Limestone { [Serializable] [XmlRoot("Template", Namespace = "http://www.limestone.se", IsNullable = false)] public class PageTemplate: IPageTemplate { [XmlAttribute] public string Name { get; set; } /// <summary> /// The path always begins with a / and includes the template name and ends with .template (the /sys/templates prefix should not be added) /// </summary> [XmlAttribute] public string Path { get; set; } [XmlAttribute] public string HelpText { get; set; } [XmlArray("Fields")] [XmlArrayItem("Field", Type = typeof(AbstractXmlSerializer<FieldSetting>))] public FieldSettingCollection FieldSettings { get; set; } public PageTemplate() { FieldSettings = new FieldSettingCollection(); } } } <file_sep>/LimestoneMVC/Controllers/HandledPagePathConstraint.cs using System; using System.Web; using System.Web.Routing; using Limestone; namespace LimestoneMVC.Controllers { public class HandledPagePathConstraint : IRouteConstraint { private readonly IPageProvider _pageProvider; private readonly string _handledTemplatePath; public HandledPagePathConstraint(IPageProvider pageProvider,string handledTemplatePath) { _pageProvider = pageProvider; _handledTemplatePath = handledTemplatePath.StartsWith("/") ? handledTemplatePath : "/" + handledTemplatePath; } public bool Match(HttpContextBase httpContext, Route route, string parameterName, RouteValueDictionary values, RouteDirection routeDirection) { var pagePath = values[parameterName] as string; if (string.IsNullOrEmpty(pagePath)) { pagePath = "/"; } var page = _pageProvider.Get(pagePath); return page != null && (page.TemplatePath.Equals(_handledTemplatePath, StringComparison.InvariantCultureIgnoreCase)); } } }<file_sep>/Limestone/FieldSetting.cs using System; using System.Xml.Serialization; namespace Limestone { [Serializable] [XmlRoot("FieldSetting", Namespace = "http://www.limestone.se", IsNullable = false)] public class FieldSetting : IFieldSetting { [XmlAttribute] public string HelpText { get; set; } [XmlAttribute] public string Title { get; set; } [XmlAttribute] public string Name { get; set; } [XmlAttribute] public FieldType Type { get; set; } [XmlAttribute] public int Index { get; set; } public FieldSetting() { } public FieldSetting(FieldType type, string name) { Type = type; Name = name; } } } <file_sep>/Limestone/FieldCollection.cs using System; using System.Collections.ObjectModel; using System.Linq; using System.Xml.Serialization; namespace Limestone { [Serializable] public class FieldCollection : Collection<Field> { [XmlIgnore] public Page Page { get; set; } protected override void InsertItem(int index, Field newItem) { //newItem.FieldCollection = this; base.InsertItem(index, newItem); ResetIndices(); } protected override void SetItem(int index, Field newItem) { base.SetItem(index, newItem); // TODO - verify that this is correct. Should i call remove? does newItem really have an id yet? // remove the item that is being replaced RemoveItem(index); // newItem.FieldCollection = this; InsertItem(index, newItem); ResetIndices(); } protected override void RemoveItem(int index) { // IField removedItem = Items[index]; base.RemoveItem(index); ResetIndices(); } public Field this[string fieldName] { get { return Items.FirstOrDefault(item => item.Name.ToLower() == fieldName.ToLower()); } set { var idx = 0; foreach (var item in Items) { if (item.Name.ToLower() == fieldName.ToLower()) { SetItem(idx, value); break; } idx++; } } } /// <summary> /// Helper function to re-enumerate the index property of the fields if it has been garbled or messed up /// </summary> public void ResetIndices() { var idx = 0; foreach (var field in Items.OrderBy(f => f.Index)) { field.Index = idx; idx++; } } } } <file_sep>/Limestone/FieldType.cs namespace Limestone { public enum FieldType { TextField, ImageField, PageField, FileField } }<file_sep>/Limestone/IFieldEditorControl.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Limestone { public interface IFieldEditorControl { IField Field { get; set; } } }
f5cb5f07c3a3fd7a51ee034b4a60fa24c9f6e619
[ "JavaScript", "C#" ]
82
C#
henrikweimenhog/blueharvest
e3db34c196f1887daca00de60108572261795ab4
06d64c644fc1e89ed8dc8b02c1320211a56cadf6
refs/heads/master
<repo_name>Vitorgpc/AppViolencia<file_sep>/src/Service/UsuarioService.java package Service; import Model.Usuario; import java.util.ArrayList; import dao.UsuarioDAO; public class UsuarioService { UsuarioDAO dao = new UsuarioDAO(); public int criar(Usuario usuario) { return dao.criar(usuario); } public void atualizar(Usuario usuario) { dao.atualizar(usuario); } public void excluir(int idUsuario) { dao.excluir(idUsuario); } public Usuario carregar(int idUsuario) { return dao.carregar(idUsuario); } public Usuario carregarEmail(String email) { return dao.carregarEmail(email); } public ArrayList<Usuario> listarUsuarios() { return dao.listarUsuarios(); } public ArrayList<Usuario> listarUsuarios(String chave) { return dao.listarUsuarios(chave); } public boolean validar(Usuario usuario) { UsuarioDAO dao = new UsuarioDAO(); return dao.validar(usuario); } } <file_sep>/src/Model/Usuario.java package Model; import java.io.Serializable; public class Usuario implements Serializable { private static final long serialVersionUID = 1L; private int idUsuario; private String nome; private String email; private String senha; public Usuario() { } public Usuario(int idUsuario, String nome, String email, String senha) { this.idUsuario = idUsuario; this.nome = nome; this.email = email; this.senha = senha; } public int getIdUsuario() { return idUsuario; } public void setIdUsuario(int idUsuario) { this.idUsuario = idUsuario; } public String getNome() { return nome; } public void setNome(String nome) { this.nome = nome; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getSenha() { return senha; } public void setSenha(String senha) { this.senha = senha; } @Override public String toString() { return "Usuario [idUsuario=" + idUsuario + ", nome=" + nome + ", email=" + email + ", senha=" + senha + "]"; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Usuario other = (Usuario) obj; if (email == null) { if (other.email != null) return false; } else if (!email.equals(other.email)) return false; return true;} }<file_sep>/src/Model/AudioVO.java package Model; import java.io.InputStream; public class AudioVO { int id; String nomeAudio; int idUsuario; private byte[] archivoaudioby; private InputStream archivoaudioin; private String base64; String data; public AudioVO() { } public int getId() { return id; } public int getIdUsuario() { return idUsuario; } public String getNomeAudio() { return nomeAudio; } public String getData() { return data; } public void setId(int id) { this.id = id; } public void setIdUsuario(int idUsuario) { this.idUsuario = idUsuario; } public void setNomeAudio(String nomeAudio) { this.nomeAudio = nomeAudio; } public void setData(String data) { this.data = data; } public InputStream getArchivoaudioin() { return archivoaudioin; } public void setArchivoaudioin(InputStream archivoaudio2) { this.archivoaudioin = archivoaudio2; } public byte[] getArchivoaudioby() { return archivoaudioby; } public void setArchivoaudioby(byte[] archivoaudio) { this.archivoaudioby = archivoaudio; } public String getBase64() { return base64; } public void setBase64(String archivoaudioby) { this.base64 = archivoaudioby; } } <file_sep>/src/command/AlterarMeusDados.java package command; import java.io.IOException; import javax.servlet.RequestDispatcher; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import Model.Usuario; import Service.UsuarioService; public class AlterarMeusDados implements Command { @Override public void executar(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String pIdUsuario = request.getParameter("idUsuario"); String pNome = request.getParameter("nome"); String pEmail = request.getParameter("email"); String pSenha = request.getParameter("senha"); int idUsuario = 1; try { idUsuario = Integer.parseInt(pIdUsuario); }catch (NumberFormatException e) { throw new ServletException(e); } Usuario usuario = new Usuario(); usuario.setIdUsuario(idUsuario); usuario.setNome(pNome); usuario.setEmail(pEmail); usuario.setSenha(pSenha); UsuarioService cs = new UsuarioService(); RequestDispatcher view = null; cs.atualizar(usuario); HttpSession session = request.getSession(); session.setAttribute("logado", usuario); session.setAttribute("idCliente", usuario.getIdUsuario()); session.setAttribute("logNome", usuario.getNome()); request.setAttribute("cliente", usuario); view = request.getRequestDispatcher("index.jsp"); view.forward(request, response); } }
d5741219280eaf9b958d47d16ece6aed0ea93855
[ "Java" ]
4
Java
Vitorgpc/AppViolencia
692715e6fbe3380c173aaed13d791a10e3e2d34e
cd56f36abe566076b5b5c47f29b33ca2ae3d0728
refs/heads/master
<file_sep>using Microsoft.EntityFrameworkCore.Migrations; namespace TinyShop.Migrations { public partial class add_c : Migration { protected override void Up(MigrationBuilder migrationBuilder) { migrationBuilder.AddColumn<string>( name: "Phonenumber", table: "Users", maxLength: 100, nullable: true); migrationBuilder.AddColumn<string>( name: "Jianjie", table: "Products", maxLength: 500, nullable: true); migrationBuilder.AddColumn<string>( name: "Time", table: "Cart", maxLength: 300, nullable: true); migrationBuilder.AddColumn<string>( name: "Total", table: "Cart", maxLength: 100, nullable: true); migrationBuilder.AddColumn<string>( name: "UserName", table: "Cart", maxLength: 100, nullable: true); } protected override void Down(MigrationBuilder migrationBuilder) { migrationBuilder.DropColumn( name: "Phonenumber", table: "Users"); migrationBuilder.DropColumn( name: "Jianjie", table: "Products"); migrationBuilder.DropColumn( name: "Time", table: "Cart"); migrationBuilder.DropColumn( name: "Total", table: "Cart"); migrationBuilder.DropColumn( name: "UserName", table: "Cart"); } } }
7dd4eba0a192c2f130b55235744375a66f3a8661
[ "C#" ]
1
C#
tsn778/U-Order
3761d6eb09dfb83004ca607a3bca689da4ed6c6c
e484987c7560278e55b915a5138662557baf8b20
refs/heads/master
<file_sep>/* * DebugSerial.c * * Created on: Feb 22, 2015 * Author: Administrador */ #include "DebugSerial.h" #include "RxBuf.h" #include "AS1.h" static UART_Desc deviceData; static uint8 bufferCommand[SIZE_BUFFER_COMMAND]; static uint8 indexCommand=0; static uint8 commandInterpreted=WAIT_COMMAND; movementType movement={-1,-1}; void printHex(unsigned char data) { uint8_t dataHex[2]; dataHex[0]=data & 0xf; dataHex[1]=(data>>4)& 0xf; if (dataHex[0]<10) { dataHex[0]=(unsigned char)(48+dataHex[0]); } else { dataHex[0]=(unsigned char)(55+dataHex[0]); } if (dataHex[1]<10) { dataHex[1]=(unsigned char)(48+dataHex[1]); } else { dataHex[1]=(unsigned char)(55+dataHex[1]); } debugChar('0'); debugChar('x'); debugChar(dataHex[1]); debugChar(dataHex[0]); } int myAtoi(char *str) { int res = 0; // Initialize result int sign = 1; // Initialize sign as positive int i = 0; // Initialize index of first digit // If number is negative, then update sign if (str[0] == '-') { sign = -1; i++; // Also update index of first digit } // Iterate through all digits and update the result for (; str[i] != '\0'; ++i) res = res*10 + str[i] - '0'; // Return result with sign return sign*res; } char* itoaDebug(int i, char b[]){ char const digit[] = "0123456789"; char* p = b; if(i<0){ *p++ = '-'; i *= -1; } int shifter = i; do{ //Move to where representation ends ++p; shifter = shifter/10; }while(shifter); *p = '\0'; do{ //Move back, inserting digits as u go *--p = digit[i%10]; i = i/10; }while(i); return b; } void debugStringGreen(const unsigned char *str) { SendString((unsigned char*)ANSI_COLOR_GREEN, &deviceData); SendString(str, &deviceData); SendString((unsigned char*)ANSI_COLOR_NO, &deviceData); } void debugStringRed(const unsigned char *str) { SendString((unsigned char*)ANSI_COLOR_RED, &deviceData); SendString(str, &deviceData); SendString((unsigned char*)ANSI_COLOR_NO, &deviceData); } void debugStringYellow(const unsigned char *str) { SendString((unsigned char*)ANSI_COLOR_YELLOW, &deviceData); SendString(str, &deviceData); SendString((unsigned char*)ANSI_COLOR_NO, &deviceData); } void debugString(const unsigned char *str) { SendString(str, &deviceData); } void debugChar(const unsigned char data) { SendChar(data, &deviceData); } void SendChar(unsigned char ch, UART_Desc *desc) { desc->isSent = FALSE; /* this will be set to 1 once the block has been sent */ while(AS1_SendBlock(desc->handle, (LDD_TData*)&ch, 1)!=ERR_OK) {} /* Send char */ while(!desc->isSent) {} /* wait until we get the green flag from the TX interrupt */ } void SendString(const unsigned char *str, UART_Desc *desc) { while(*str!='\0') { SendChar(*str++, desc); } } void InitSerial(void) { /* initialize struct fields */ deviceData.handle = AS1_Init(&deviceData); deviceData.isSent = FALSE; deviceData.rxChar = '\0'; deviceData.rxPutFct = RxBuf_Put; /* set up to receive RX into input buffer */ RxBuf_Init(); /* initialize RX buffer */ /* Set up ReceiveBlock() with a single byte buffer. We will be called in OnBlockReceived() event. */ while(AS1_ReceiveBlock(deviceData.handle, (LDD_TData *)&deviceData.rxChar, sizeof(deviceData.rxChar))!=ERR_OK) {} /* initial kick off for receiving data */ } void startSerial() { InitSerial(); SendString((unsigned char*)"\r\n******************************\r\n", &deviceData); SendString((unsigned char*)"\r\nStarting FDRM KL25 PWM \r\n", &deviceData); SendString((unsigned char*)"\r\n******************************\r\n", &deviceData); initBufferCommnad(); } void getDebugString() { if (RxBuf_NofElements()!=0) { //SendString((unsigned char*)"echo: ", &deviceData); while (RxBuf_NofElements()!=0) { unsigned char ch; (void)RxBuf_Get(&ch); //SendChar(ch, &deviceData); } //SendString((unsigned char*)"\r\n", &deviceData); } } uint8 isNumber(uint8 ch) { return ((ch>47)&&(ch<58)); } void initBufferCommnad() { uint16 i=0; for(i=0;i<SIZE_BUFFER_COMMAND;i++) { bufferCommand[i]='\0'; } indexCommand=0; commandInterpreted=WAIT_COMMAND; } void interpretComment() { switch(commandInterpreted) { case(STOP_DIRECTION): debugString((unsigned char*)"\r\nDirection received:"); debugStringRed(bufferCommand); movement.direction=myAtoi((char*)bufferCommand); break; case(STOP_SPEED): debugString((unsigned char*)"\r\nSpeed received:"); debugStringGreen(bufferCommand); movement.speed=myAtoi((char*)bufferCommand); break; //case(STOP_SPEED): default: debugString((unsigned char*)"\r\nWrong Command!"); break; } debugString((unsigned char*)"\r\n"); indexCommand=0; initBufferCommnad(); } void getCommandReceived() { if (RxBuf_NofElements()!=0) { unsigned char ch; while (RxBuf_NofElements()!=0) { (void)RxBuf_Get(&ch); if(ch==13)//Retorno de carro (CR) { initBufferCommnad(); debugString((unsigned char*)"\r\n"); } else { if(commandInterpreted==WAIT_COMMAND) { if (ch==SPEED_COMMAND_START) { commandInterpreted=START_SPEED; indexCommand=0; } if (ch==DIRECTION_COMMAND_START) { commandInterpreted=START_DIRECTION; indexCommand=0; } } else if((commandInterpreted==START_DIRECTION)||(commandInterpreted==START_SPEED)) { if (ch==SPEED_COMMAND_START) { commandInterpreted=START_SPEED; initBufferCommnad(); } else if (ch==DIRECTION_COMMAND_START) { commandInterpreted=START_DIRECTION; initBufferCommnad(); } else if (isNumber(ch)) { bufferCommand[indexCommand]=ch; indexCommand++; } else if (ch==SPEED_COMMAND_STOP) { if(indexCommand>0) { commandInterpreted=STOP_SPEED; } else { commandInterpreted=WAIT_COMMAND; } interpretComment(); } else if (ch==DIRECTION_COMMAND_STOP) { if(indexCommand>0) { commandInterpreted=STOP_DIRECTION; } else { commandInterpreted=WAIT_COMMAND; } interpretComment(); } else { commandInterpreted=WAIT_COMMAND; interpretComment(); } } }//No CR received } } } <file_sep>/* ################################################################### ** Filename : main.c ** Project : Freedom_LED ** Processor : MKL25Z128VLK4 ** Version : Driver 01.01 ** Compiler : GNU C Compiler ** Date/Time : 2015-01-26, 07:12, # CodeGen: 0 ** Abstract : ** Main module. ** This module contains user's application code. ** Settings : ** Contents : ** No public methods ** ** ###################################################################*/ /*! ** @file main.c ** @version 01.01 ** @brief ** Main module. ** This module contains user's application code. */ /*! ** @addtogroup main_module main module documentation ** @{ */ /* MODULE main */ /* Including needed modules to compile this module/procedure */ #include "Cpu.h" #include "Events.h" #include "LEDR.h" #include "LEDpin1.h" #include "BitIoLdd1.h" #include "LEDG.h" #include "LEDpin2.h" #include "BitIoLdd2.h" #include "LEDB.h" #include "LEDpin3.h" #include "BitIoLdd3.h" #include "WAIT1.h" #include "TU1.h" #include "Speed.h" #include "PwmLdd1.h" #include "Direction.h" #include "PwmLdd2.h" #include "RxBuf.h" #include "AS1.h" #include "Speed_Capture.h" #include "TU2.h" #include "Bit1.h" /* Including shared modules, which are used for whole project */ #include "PE_Types.h" #include "PE_Error.h" #include "PE_Const.h" #include "IO_Map.h" /* User includes (#include below this line is not maintained by Processor Expert) */ #include "DebugSerial.h" extern movementType movement; LDD_TDeviceData *SpeedCapture; LDD_TError ErrorSpeedCapture, FlagSpeedCapture; volatile uint32_t DataSpeedCapture; uint32_t DataSpeedCaptureOld; /*lint -save -e970 Disable MISRA rule (6.3) checking. */ int main(void) /*lint -restore Enable MISRA rule (6.3) checking. */ { /* Write your local variable definition here */ uint32_t dutySpeed_old=1000; uint32_t dutyDirection_old=1000; movement.direction=dutyDirection_old; movement.speed=dutySpeed_old; uint32_t counterSpeedCapture; uint32_t dutySpeedCapture; uint32_t periodSpeedCapture=50000; uint32_t timeLowSpeed=0; uint32_t timeHighSpeed=0; uint32_t counterPrint=0; char buffer[10]; /*** Processor Expert internal initialization. DON'T REMOVE THIS CODE!!! ***/ PE_low_level_init(); /*** End of Processor Expert internal initialization. ***/ /* Write your code here */ SpeedCapture = Speed_Capture_Init((LDD_TUserData *)NULL); startSerial(); ErrorSpeedCapture = Speed_Capture_Reset(SpeedCapture); /* Reset the counter */ FlagSpeedCapture = 1U; while (1) { //#define CAPTURE_AND_GENERATE_DEVICE 1 #ifdef CAPTURE_AND_GENERATE_DEVICE if(FlagSpeedCapture == ERR_OK) { FlagSpeedCapture=1; Speed_Capture_GetCaptureValue(SpeedCapture, &DataSpeedCapture); if(DataSpeedCaptureOld>DataSpeedCapture) { counterSpeedCapture=(65535-DataSpeedCaptureOld)+DataSpeedCapture; } else { counterSpeedCapture=DataSpeedCapture-DataSpeedCaptureOld; } DataSpeedCaptureOld=DataSpeedCapture; /*TODO!: coger el nivel del pin para saber si estamos midiendo * el duty o la frecuencia */ if(counterSpeedCapture < 25000) //duty never will be less that 50% { timeHighSpeed=counterSpeedCapture*1.53; LEDB_Neg(); } else { timeLowSpeed=counterSpeedCapture*1.53; } if(counterPrint++==10) { counterPrint=0; debugString((unsigned char *)"TimeHigh "); itoaDebug(timeHighSpeed,&buffer[0]); debugStringRed((unsigned char *)buffer); debugString((unsigned char *)"us.TimeLow "); itoaDebug(timeLowSpeed,&buffer[0]); debugStringRed((unsigned char *)buffer); debugString((unsigned char *)"us.Total "); itoaDebug(timeLowSpeed+timeHighSpeed,&buffer[0]); debugStringRed((unsigned char *)buffer); debugString((unsigned char *)"us\n\r"); } movement.speed=timeHighSpeed; } if(movement.speed!=dutySpeed_old) { dutySpeed_old=movement.speed; Speed_SetDutyUS(50000-dutySpeed_old); debugString((unsigned char *)"New duty speed:"); itoaDebug(movement.speed,&buffer[0]); debugStringGreen((unsigned char *)buffer); debugString((unsigned char *)"\n\r"); } if(movement.direction!=dutyDirection_old) { dutyDirection_old=movement.direction; Direction_SetDutyUS(50000-dutyDirection_old); debugString((unsigned char *)"New duty direction:"); itoaDebug(movement.direction,buffer); debugStringRed((unsigned char *)buffer); debugString((unsigned char *)"\n\r"); } #else //GENERATE PWM from CONSOLE getCommandReceived(); if(movement.speed!=dutySpeed_old) { dutySpeed_old=movement.speed; Speed_SetDutyUS(50000-dutySpeed_old); debugString((unsigned char *)"New duty speed:"); itoaDebug(movement.speed,&buffer[0]); debugStringGreen((unsigned char *)buffer); debugString((unsigned char *)"\n\r"); } if(movement.direction!=dutyDirection_old) { dutyDirection_old=movement.direction; Direction_SetDutyUS(50000-dutyDirection_old); debugString((unsigned char *)"New duty direction:"); itoaDebug(movement.direction,buffer); debugStringRed((unsigned char *)buffer); debugString((unsigned char *)"\n\r"); } WAIT1_Waitms(50); LEDG_Neg(); #endif } /* For example: for(;;) { } */ /*** Don't write any code pass this line, or it will be deleted during code generation. ***/ /*** RTOS startup code. Macro PEX_RTOS_START is defined by the RTOS component. DON'T MODIFY THIS CODE!!! ***/ #ifdef PEX_RTOS_START PEX_RTOS_START(); /* Startup of the selected RTOS. Macro is defined by the RTOS component. */ #endif /*** End of RTOS startup code. ***/ /*** Processor Expert end of main routine. DON'T MODIFY THIS CODE!!! ***/ for(;;){} /*** Processor Expert end of main routine. DON'T WRITE CODE BELOW!!! ***/ } /*** End of main routine. DO NOT MODIFY THIS TEXT!!! ***/ /* END main */ /*! ** @} */ /* ** ################################################################### ** ** This file was created by Processor Expert 10.3 [05.09] ** for the Freescale Kinetis series of microcontrollers. ** ** ################################################################### */ <file_sep>/* * DebugSerial.h * * Created on: Feb 22, 2015 * Author: Administrador */ #ifndef DEBUGSERIAL_H_ #define DEBUGSERIAL_H_ #include "PE_Types.h" #include "PE_LDD.h" #define SPEED_COMMAND_START 'S' #define SPEED_COMMAND_STOP 's' #define DIRECTION_COMMAND_START 'D' #define DIRECTION_COMMAND_STOP 'd' #define SIZE_BUFFER_COMMAND 20 #define ANSI_COLOR_NO "\033[0m" #define ANSI_COLOR_RED "\033[31m" #define ANSI_COLOR_GREEN "\033[32m" #define ANSI_COLOR_YELLOW "\033[33m" enum { WAIT_COMMAND, START_SPEED, STOP_SPEED, START_DIRECTION, STOP_DIRECTION }; typedef struct { int32 speed; int32 direction; }movementType; typedef struct { LDD_TDeviceData *handle; /* LDD device handle */ volatile uint8_t isSent; /* this will be set to 1 once the block has been sent */ uint8_t rxChar; /* single character buffer for receiving chars */ uint8_t (*rxPutFct)(uint8_t); /* callback to put received character into buffer */ } UART_Desc; void printHex(unsigned char data); void SendChar(unsigned char ch, UART_Desc *desc); void SendString(const unsigned char *str, UART_Desc *desc); void InitSerial(void); void startSerial(void) ; void debugString(const unsigned char *str); char* itoaDebug(int i, char b[]); void debugChar(const unsigned char data); void getDebugString(void); uint8 isNumber(uint8 ch); void initBufferCommnad(void); int myAtoi(char *str); void getCommandReceived(); void debugStringGreen(const unsigned char *str); void debugStringRed(const unsigned char *str); void debugStringYellow(const unsigned char *str); #endif /* DEBUGSERIAL_H_ */ <file_sep># kl25z_vcr Freedom KL25 project (Vehicle "Centro Rancing"): -UART0 115200. String management (with ANSI color) -PWM Generation(200HZ and 1us resolution duty) on PA12 & PA13 -Duty cycle editable by console: -Dxxxd: Sets PA12 ("Diretion") to xxx us of duty -Sxxxs: Sets PA13 ("Speed") to xxx us of duty
03780e4861b7940c7710f351a4f3e767173d7f20
[ "Markdown", "C" ]
4
C
nostradamux/kl25z_vcr
75132e784cbc7ffa4f856317bcdb5f48ac2c3835
7c2328149415046839b29c46b08122dfad9a5841
refs/heads/master
<repo_name>esalman/fplanalyzer<file_sep>/script.js // © 2013-2015 @ealman fplanalyzer.com var fplAnalyzer = { initialized: false, // teams for 2014-15 season :D teamArr: { "Leicester":"LEI", "Arsenal":"ARS", "Everton":"EVE", "West Brom":"WBA", "Newcastle":"NEW", "West Ham":"WHM", "Southampton":"SOU", "Sunderland":"SUN", "Stoke":"STK", "Crystal Palace":"CPA", "Aston Villa":"AVL", "Liverpool":"LIV", "Man City":"MCY", "Spurs":"TOT", "Swansea":"SWA", "Man Utd":"MUN", "Chelsea":"CHE", "Bournemouth":"BOU", "Watford":"WAT", "Norwich":"NOR" }, // contains opponent of each team, updates each gw fixArr: {}, // selected player price, nti playerAttrib: {}, currentGW: 0, totalPlayer: null, options: { domain: 'http://pure-ocean-7640.herokuapp.com/', numberOfOpponentsToDisplay: 1, predictors: { CTC: 'FISO CrackTheCode (http://www.fiso.co.uk/crackthecode.php)', TFPL: 'TotalFPL (http://totalfpl.com/pricechanges)' }, selectedPredictor: 'CTC', teamId: null }, // ui elements controls: { loader: $('<span style="background: #F00; color: #FFF; position: fixed; top: 0px; left: 0px; padding: 3px 3px; display: none;">Loading...</span>'), pitchControls: { reload: $('<a class="reload" style="background: #126e37; color: #FFF; padding: 2px 3px; display: inline-block; margin: 0px 1px 1px 0px; font-size: small; width: 14px; text-align: center;" href="javascript:void(0)" title="Reload">&#8634;</a>'), prevGW: $('<a class="prevGW" style="background: #126e37; color: #FFF; padding: 2px 3px; display: inline-block; margin: 0px 1px 1px 0px; font-size: small; width: 14px; text-align: center;" href="javascript:void(0)" title="Previous GW">◀</a>'), nextGW: $('<a class="nextGW" style="background: #126e37; color: #FFF; padding: 2px 3px; display: inline-block; margin: 0px 1px 1px 0px; font-size: small; width: 14px; text-align: center;" href="javascript:void(0)" title="Next GW">▶</a>'), oppoNos: $('<a class="oppoNos" style="background: #126e37; color: #FFF; padding: 2px 3px; display: inline-block; margin: 0px 1px 1px 0px; font-size: small; width: 14px; text-align: center; font-style: italic;" href="javascript:void(0)" title="Number of GW">1</a><br />'), points: $('<a class="points" style="background: #35A649; color: #FFF; padding: 2px 3px; display: inline-block; margin: 0px 1px 1px 0px; font-size: small; width: 14px; text-align: center;" href="javascript:void(0)" title="Points (Live BPS)">P</a>'), opponent: $('<a class="opponent" style="background: #35A649; color: #FFF; padding: 2px 3px; display: inline-block; margin: 0px 1px 1px 0px; font-size: small; width: 14px; text-align: center;" href="javascript:void(0)" title="Opponent">V</a>'), price: $('<a class="price" style="background: #35A649; color: #FFF; padding: 2px 3px; display: inline-block; margin: 0px 1px 1px 0px; font-size: small; width: 14px; text-align: center;" href="javascript:void(0)" title="Price">£</a>'), own: $('<a class="own" style="background: #35A649; color: #FFF; padding: 2px 3px; display: inline-block; margin: 0px 1px 1px 0px; font-size: small; width: 14px; text-align: center;" href="javascript:void(0)" title="% Ownership">%</a><br />'), ntit: $('<a class="ntit" style="background: #126e37; color: #FFF; padding: 2px 3px; display: inline-block; margin: 0px 1px 1px 0px; font-size: small; width: 14px; text-align: center;" href="javascript:void(0)" title="NTI Today">T</a>'), nti: $('<a class="nti" style="background: #126e37; color: #FFF; padding: 2px 3px; display: inline-block; margin: 0px 1px 1px 0px; font-size: small; width: 14px; text-align: center;" href="javascript:void(0)" title="% NTI">%</a>'), predictor: $('<a class="predictor" style="background: #126e37; color: #FFF; padding: 2px 3px; display: inline-block; margin: 0px 1px 1px 0px; font-size: small; width: 14px; text-align: center;" href="javascript:void(0)" title="Change Predictor">&#x25EA;</a><br />'), genRMT: $('<a class="genRMT" style="background: #35A649; color: #FFF; padding: 2px 3px; display: inline-block; margin: 0px 1px 1px 0px; font-size: small; width: 14px; text-align: center;" href="javascript:void(0)" title="Rate My Team!">★</a>'), webLink: $('<a class="webLink" style="background: #35A649; color: #FFF; padding: 2px 3px; display: inline-block; margin: 0px 1px 1px 0px; font-size: small; width: 14px; text-align: center;" href="http://fplanalyzer.com" target="_blank" title="www.fplanalyzer.com">?</a>'), share: $('<a class="share" style="background: #35A649; color: #FFF; padding: 2px 3px; display: inline-block; margin: 0px 1px 1px 0px; font-size: small; width: 14px; text-align: center;" href="javascript:void(0)" title="Share FPL Analyzer!">❤</a><div class="addthis_sharing_toolbox" style="display: none;" data-url="http://fplanalyzer.com" data-title="Check out FPL Analyzer!"></div>') } }, // executed when bookmark clicked second time, and never again init: function () { // second time fplAnalyzer.initialized = true // red loading block on top left of page $('body').append( fplAnalyzer.controls.loader ) // css $('.ismElementDetail').css('text-shadow', '1px 1px 1px #000') // create the overlay of pich area var top = $('.ismDefList.ismRHSDefList').length > 0 ? 0 : -42 var parentDiv = $('<div id="fplAnalyzerControl" style="position: absolute; top: '+top+'px; left: 0px; font-size: smaller;"></div>') // append ui controls above pitch area an dand bind their events $.each( fplAnalyzer.controls.pitchControls, function (i, v) { parentDiv.append( v ) v.bind( 'click', fplAnalyzer.events[i] ) } ) $('#ism .ismPitch').css('position', 'relative').append( parentDiv ) // bind function to fixture change event $('#ism .ismFixtureContainer').bind( 'DOMNodeInserted', function (e) { fplAnalyzer.updateFixtureNavigateButton() fplAnalyzer.update() } ) // team id- for anonymous (unique visit) tracking // fplAnalyzer.options.teamId = $('nav li:nth-child(2) a').attr('href').split('/')[2] // set total player if ( $('.ismDefList.ismRHSDefList').length > 0 ) { fplAnalyzer.totalPlayer = parseInt( $( $('.ismDefList.ismRHSDefList').children('dd')[2] ).text().replace(/,/g, '') ) createCookie('fplAnalyzerTotalPlayer', fplAnalyzer.totalPlayer, 30) } if ( readCookie('fplAnalyzerTotalPlayer') && fplAnalyzer.totalPlayer != readCookie('fplAnalyzerTotalPlayer') ) fplAnalyzer.totalPlayer = readCookie('fplAnalyzerTotalPlayer') // read predictor setting from cookie var selectedPredictor = readCookie('fplAnalyzerSelectedPredictor') if ( selectedPredictor ) fplAnalyzer.options.selectedPredictor = selectedPredictor // set predictor in button title $('a.predictor').attr('title', fplAnalyzer.options.selectedPredictor+'- Change Predictor') // read number of opponent setting from cookie var numberOfOpponentsToDisplay = readCookie('fplAnalyzerNumberOfOpponentsToDisplay') fplAnalyzer.options.numberOfOpponentsToDisplay = numberOfOpponentsToDisplay ? numberOfOpponentsToDisplay : 1 $('a.oppoNos').html(fplAnalyzer.options.numberOfOpponentsToDisplay) // addthis share buttons var f = document.createElement('script') f.setAttribute("type", "text/javascript") f.setAttribute("src", "//s7.addthis.com/js/300/addthis_widget.js#pubid=ra-53edcfcd20914b86") document.getElementsByTagName("head")[0].appendChild(f) }, // executed after bookmark clicked the first time, and also on reload button click update: function (reload) { fplAnalyzer.controls.loader.show() fplAnalyzer.loadNTIData(reload) }, // parse the fixture table and update fixArr loadFixture: function () { // fplAnalyzer.fixArr = {} if ( ! $('.ismFixtureTable caption').html() ) return fplAnalyzer.currentGW = $('.ismFixtureTable caption').html().split('-')[0].replace('Gameweek', '').trim() // clear current gw $.each( fplAnalyzer.teamArr, function ( i, v ) { if ( fplAnalyzer.fixArr[i] == undefined ) fplAnalyzer.fixArr[i] = {} fplAnalyzer.fixArr[i][fplAnalyzer.currentGW] = '' } ) $.each($(".ismFixtureTable tbody tr"), function (i, team) { h = $(team).children(".ismHomeTeam").html() a = $(team).children(".ismAwayTeam").html() if ( fplAnalyzer.teamArr[h] == undefined ) return // at home uppercase, at away lowercase // home on the left column fplAnalyzer.fixArr[h][fplAnalyzer.currentGW] += fplAnalyzer.teamArr[a].toUpperCase()+' ' // away on the right column fplAnalyzer.fixArr[a][fplAnalyzer.currentGW] += fplAnalyzer.teamArr[h].toLowerCase()+' ' }) }, // update data of each player in pitch area updateOpponent: function () { $.each($("#ismTeamDisplayGraphical div[id^=ismGraphical]"), function (i, player) { // find opponent using shirt title attribute var opponent = '<div class="opponent">'+ ( fplAnalyzer.getNextNOpponent( $(player).find(".ismShirt").attr("title") ) ) +'</div>' // get NTI Percent var nti = '<div class="nti" style="display: none;">'+ fplAnalyzer.playerAttrib[ fplAnalyzer.getPlayerIDFromContainer(player) ].NTIPercent +'%</div>' // get NTI Today var ntit = '<div class="ntit" style="display: none;">'+ fplAnalyzer.playerAttrib[ fplAnalyzer.getPlayerIDFromContainer(player) ].NTIToday +'</div>' // make price div var price = '<div class="price" style="display: none;">'+ fplAnalyzer.playerAttrib[ fplAnalyzer.getPlayerIDFromContainer(player) ].price +'</div>' // make %ownership div var ownership = '<div class="ownership" style="display: none;">'+ fplAnalyzer.playerAttrib[ fplAnalyzer.getPlayerIDFromContainer(player) ].ownership +'</div>' // points var bp = fplAnalyzer.playerAttrib[ fplAnalyzer.getPlayerIDFromContainer(player) ].bonus var pts = fplAnalyzer.getPlayerDataFromContainer( player, 'event_points' ) + ( bp != undefined && bp > 0 ? bp : 0 ) if ( fplAnalyzer.getPlayerDataFromContainer( player, 'is_captain' ) == true ) pts *= 2 var points = '<div class="points" style="display: none; '+( bp != undefined && bp > 0 ? 'color: #0F0; ' : '' )+'">'+ pts +'</div>' $(player).find(".ismElementDetail dd").html( opponent + price + nti + ntit + ownership + points ) }) fplAnalyzer.controls.loader.hide() }, // make an ajax call to heroku to scrape fiso/totalfpl data and return formatted nti data by player id loadNTIData: function (reload) { var ids = [] $.each( $('div[id^=ismGraphical]'), function (i, v) { var id = fplAnalyzer.getPlayerIDFromContainer(v) // only request those players not saved yet if ( reload === true || fplAnalyzer.playerAttrib[ id ] == undefined ) { fplAnalyzer.playerAttrib[ id ] = { 'name': fplAnalyzer.getPlayerNameFromContainer( v ) } ids.push( id ) } } ) // if nti of selected players are already available, new request will not be sent if ( ids.length < 1 ) { fplAnalyzer.loadFixture() fplAnalyzer.updateOpponent() return } // make request $.getJSON( fplAnalyzer.options.domain+'parse.php', { id: ids.join(','), p: fplAnalyzer.options.selectedPredictor, cid: fplAnalyzer.options.teamId } ).done( function ( json ) { // populate the player attribute array $.each( json, function (i, v) { fplAnalyzer.playerAttrib[i].NTIPercent = v.c fplAnalyzer.playerAttrib[i].price = v.p fplAnalyzer.playerAttrib[i].NTIToday = v.d fplAnalyzer.playerAttrib[i].ownership = fplAnalyzer.totalPlayer ? ( (v.n).replace(/[^\d\.\-\ ]/g, '') * 100 / fplAnalyzer.totalPlayer ).toFixed(2) + '%' : v.n } ) // update opponent // fplAnalyzer.loadFixture() fplAnalyzer.updateOpponent() } ) fplAnalyzer.loadFixture() fplAnalyzer.updateOpponent() }, getPlayerIDFromContainer: function ( el ) { return $(el).find('a.ismViewProfile').attr('href').replace('#', '') }, getPlayerNameFromContainer: function ( el ) { return $(el).find('.ismPitchWebName').html().trim() }, // some stats (e.g. event_points) are available in the class attrib on points and team page getPlayerDataFromContainer: function ( el, attrib ) { if ( $(el).attr( 'class' ).split(' ')[1][0] != '{' ) return '' return JSON.parse( $(el).attr( 'class' ).split(' ')[1] )[attrib] }, // events associated to ui elements events: { reload: function () { fplAnalyzer.update(true) }, prevGW: function () { fplAnalyzer.controls.loader.show() $('.ismPagination a').first().click() }, nextGW: function () { fplAnalyzer.controls.loader.show() $('.ismPagination a').last().click() }, points: function ( e ) { $('.ismElementDetail dd > div').css('display', 'none') $('.ismElementDetail dd > div.points').css('display', 'block') // for updating total points var totalPts = parseInt( $('.ismSBValue.ismSBPrimary div').html().split('<')[0].trim() ) var totalBP = 0 // cycle through players and build fixture array var fixtures = [] $.each( $('div[id^=ismGraphical]'), function (i, v) { // get this player's fixture var f = $('#ismFixtureTable td:contains("'+$(v).find('img.ismShirt').attr('title')+'")').parent().next().find('a.ismFixtureStatsLink').attr('data-id') // also check unique if ( f != undefined && fixtures.indexOf(f) == -1 ) fixtures.push(f) } ) for ( var i = 0; i < fixtures.length; i++ ) { // make requests fplAnalyzer.controls.loader.show() $.get('http://fantasy.premierleague.com/fixture/'+fixtures[i], function (response) { var bpsArr = [] var bpsSum = 0 // for home $.each( $($(response)[2]).find('tr'), function (i, v) { if ( $(v).find('td')[0] ) { bpsSum += parseInt( $( $(v).find('td')[12] ).html().trim() ) bpsArr.push( { "name": $( $(v).find('td')[0] ).html().trim(), "bps": parseInt( $( $(v).find('td')[14] ).html().trim() ), "tp": parseInt( $( $(v).find('td')[15] ).html().trim() ) } ) } } ) // for away $.each( $( $(response)[4] ).find('tr'), function (i, v) { if ( $(v).find('td')[0] ) { bpsSum += parseInt( $( $(v).find('td')[12] ).html().trim() ) bpsArr.push( { "name": $( $(v).find('td')[0] ).html().trim(), "bps": parseInt( $( $(v).find('td')[14] ).html().trim() ), "tp": parseInt( $( $(v).find('td')[15] ).html().trim() ) } ) } } ) // bonus already added by fpl if ( bpsSum > 0 ) { fplAnalyzer.controls.loader.hide() return } // sort for ( var i = 0; i < bpsArr.length-1; i++ ) { for ( var j = i+1; j < bpsArr.length; j++ ) { if ( bpsArr[i].bps < bpsArr[j].bps ) { var temp = bpsArr[j] bpsArr[j] = bpsArr[i] bpsArr[i] = temp } } } // calculate and assign var bp = 3 for ( var i = 0; i < bpsArr.length; i++ ) { if ( i > 0 && bp > 0 ) { if ( bpsArr[i].bps < bpsArr[i-1].bps ) bp-- if ( bp <= 0 ) break } $.each($("div[id^=ismGraphical]"), function (i1, player) { if ( fplAnalyzer.getPlayerNameFromContainer( player ) == bpsArr[i].name ) { var pts = bpsArr[i].tp + bp if ( fplAnalyzer.getPlayerDataFromContainer( player, 'is_captain' ) == true ) pts *= 2 $(player).find(".ismElementDetail dd div.points").html( pts ).css( 'color', '#0F0' ) fplAnalyzer.playerAttrib[ fplAnalyzer.getPlayerDataFromContainer( player, 'id' ) ].bonus = bp } }) } var totalPoints = 0 $.each($("div[id^=ismGraphical]"), function (i1, player) { if ( fplAnalyzer.getPlayerDataFromContainer( player, 'sub' ) == 0 ) { totalPoints += parseInt( $(player).find('.points').html() ) } }) $('.ismSBValue.ismSBPrimary div').html( totalPoints + '<sub>pts</sub>' ) fplAnalyzer.controls.loader.hide() }) } }, opponent: function () { $('.ismElementDetail dd > div').css('display', 'none') $('.ismElementDetail dd > div.opponent').css('display', 'block') }, price: function () { $('.ismElementDetail dd > div').css('display', 'none') $('.ismElementDetail dd > div.price').css('display', 'block') }, nti: function () { $('.ismElementDetail dd > div').css('display', 'none') $('.ismElementDetail dd > div.nti').css('display', 'block') }, ntit: function () { $('.ismElementDetail dd > div').css('display', 'none') $('.ismElementDetail dd > div.ntit').css('display', 'block') }, own: function () { $('.ismElementDetail dd > div').css('display', 'none') $('.ismElementDetail dd > div.ownership').css('display', 'block') }, share: function () { if ( $('.addthis_sharing_toolbox').css('display') === 'none' ) $('.addthis_sharing_toolbox').show() else $('.addthis_sharing_toolbox').hide() }, genRMT: function () { var rmtStr = ''; $.each( $(".ismPitchRow"), function (j, row) { rmtStr += '\n' if ( j == 4 ) rmtStr += '\nSubs: ' $.each( $(row).find('div[id^=ismGraphical]'), function (i, player) { rmtStr += $(player).find('span.ismPitchWebName').html().trim()+' ' }) }) window.prompt('You can copy the following RMT string:', rmtStr) }, predictor: function () { var prompt = fplAnalyzer.options.selectedPredictor == 'CTC' ? fplAnalyzer.options.predictors.TFPL : fplAnalyzer.options.predictors.CTC if ( fplAnalyzer.options.selectedPredictor == 'CTC' ) { if ( confirm("You are currently using "+fplAnalyzer.options.predictors.CTC+". Change predictor to "+fplAnalyzer.options.predictors.TFPL+'?') ) { fplAnalyzer.options.selectedPredictor = 'TFPL' createCookie('fplAnalyzerSelectedPredictor', fplAnalyzer.options.selectedPredictor, 30) $('a.predictor').attr('title', fplAnalyzer.options.selectedPredictor+'- Change Predictor') } } else if ( fplAnalyzer.options.selectedPredictor == 'TFPL' ) { if ( confirm("You are currently using "+fplAnalyzer.options.predictors.TFPL+". Change predictor to "+fplAnalyzer.options.predictors.CTC+'?') ) { fplAnalyzer.options.selectedPredictor = 'CTC' createCookie('fplAnalyzerSelectedPredictor', fplAnalyzer.options.selectedPredictor, 30) $('a.predictor').attr('title', fplAnalyzer.options.selectedPredictor+'- Change Predictor') } } }, oppoNos: function () { fplAnalyzer.options.numberOfOpponentsToDisplay = ( fplAnalyzer.options.numberOfOpponentsToDisplay % 3 ) + 1 createCookie('fplAnalyzerNumberOfOpponentsToDisplay', fplAnalyzer.options.numberOfOpponentsToDisplay, 30) $('a.oppoNos').html(fplAnalyzer.options.numberOfOpponentsToDisplay) } }, updateFixtureNavigateButton: function () { if ( $('.ismPagPrev').length > 0 ) $('#fplAnalyzerControl .prevGW').html( $('.ismPagPrev').html().replace('Gameweek ', '') ) if ( $('.ismPagNext').length > 0 ) $('#fplAnalyzerControl .nextGW').html( $('.ismPagNext').html().replace('Gameweek ', '') ) }, getNextNOpponent: function ( team ) { var opponentString = '' for ( i = 0; i < fplAnalyzer.options.numberOfOpponentsToDisplay; i++ ) { if ( fplAnalyzer.fixArr[ team ] == undefined || fplAnalyzer.fixArr[ team ][ parseInt( fplAnalyzer.currentGW ) + i ] == undefined ) continue opponentString += fplAnalyzer.fixArr[ team ][ parseInt( fplAnalyzer.currentGW ) + i ] + ( i < fplAnalyzer.options.numberOfOpponentsToDisplay - 1 ? ' ' : '' ) } return opponentString } } var fplAnalyzeTrigger = function () { if ( location.href.search('fantasy.premierleague.com') < 0 ) return if ( ! fplAnalyzer.initialized ) fplAnalyzer.init() fplAnalyzer.update() } var createCookie = function (name,value,days) { if (days) { var date = new Date(); date.setTime(date.getTime()+(days*24*60*60*1000)); var expires = "; expires="+date.toGMTString(); } else var expires = ""; document.cookie = name+"="+value+expires+"; path=/"; } var readCookie = function (name) { var nameEQ = name + "="; var ca = document.cookie.split(';'); for(var i=0;i < ca.length;i++) { var c = ca[i]; while (c.charAt(0)==' ') c = c.substring(1,c.length); if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length); } return null; } var eraseCookie = function (name) { createCookie(name,"",-1); } <file_sep>/README.md FPLAnalyzer =========== This bookmarklet allows you to preview opponents on different GW on [fantasy.premierleague.com](http://fantasy.premierleague.com) More details, how to setup, how to use: [fplanalyzer.com](http://fplanalyzer.com) **License** FPLAnalyzer is licensed under the MIT License. **Updated** Aug 21, 2014 by <NAME> **Introduction** All projects in the FPLAnalyzer code repository are open-source and may be used or modified under the MIT License. All projects, code, and assemblies are copyright 2013-2014 by <NAME>. **Details** http://opensource.org/licenses/MIT <file_sep>/index.php <?php header("Location: http://fplanalyzer.com"); exit();<file_sep>/bookmarklet.js javascript:(function (){ if ( window.fplAnalyzeTrigger == undefined ) { var f = document.createElement('script') f.setAttribute("type", "text/javascript") f.setAttribute("src", "http://pure-ocean-7640.herokuapp.com/script.min.js") document.getElementsByTagName("head")[0].appendChild(f) } else { window.fplAnalyzeTrigger() } })()
1779c1e0816cd3f2cdc14ced1e219958a9524001
[ "JavaScript", "PHP", "Markdown" ]
4
JavaScript
esalman/fplanalyzer
d17db6978764d14a3cb0022da70e041240bc4c43
1d21b79bdd917f6a97e39cf8a944018ef83bef98
refs/heads/master
<file_sep>/** * Created by Administrator on 2018/2/5. */ import $$ from './local' const localStoragePlugin = store => { // 注册监听 store 的 mutation // 在每个 mutation 完成后调用,接收 mutation 和经过 mutation 后的状态作为参数 store.subscribe((mutation, state) => { $$.set(mutation.type, mutation.payload) }) } export default [localStoragePlugin] <file_sep>import { Notification } from 'element-ui'; export default { dateFormat(val) { const fillWith0 = function(num) { if (num < 10) { return '0' + num } return num } if (!val) { return '' } let date = new Date(val) let y = date.getFullYear() let m = fillWith0(date.getMonth() + 1) let d = fillWith0(date.getDate()) return [y, m, d].join('-') }, getCatePath: function(cate, arr) { arr.unshift(cate.id) if (cate.parent) { return this.getCatePath(cate.parent, arr) } else { return arr } }, checkFile: function(file, reg, size) { if (!reg.test(file.name)) { Notification.error({ message: '文件格式有误' }) return false } if (file.size > size) { Notification.error({ message: '文件大小不能超过' + size / (1024 * 1024) + 'mb' }) return false } return true }, async handlePageChange(currPage, pageSize, param, apiRequest) { param = Object.assign(param, { page: currPage, num_per_page: pageSize }) let result = await apiRequest(param) return result }, formatAdmin(obj) { obj.forEach(function(e) { e.href = 'http://wpa.qq.com/msgrd?v=3&uin=' + e.qq + '&site=qq&menu=yes' e.src = 'http://wpa.qq.com/pa?p=2:' + e.qq + ':51' if (e.gender == '1') { e.gender = { label: '男', value: '1' } } if (e.gender == '0') { e.gender = { label: '女', value: '0' } } if (e.is_on == '0') { e.is_on = false } if (e.is_on == '1') { e.is_on = true } }) }, createImage(file) { return new Promise((resolve, reject) => { var reader = new FileReader() reader.onload = (e) => { resolve(e.target.result) } reader.readAsDataURL(file) }) }, removeArr(arr1, arr2) { let temp = [] let temparray = [] for (let i = 0; i < arr2.length; i++) { temp[arr2[i].id] = true; } for (let i = 0; i < arr1.length; i++) { if (!temp[arr1[i].id]) { temparray.push(arr1[i]) } } return temparray }, /** 是否为整数 */ isInt(val) { if (isNaN(val)) return false return typeof val === 'number' && val % 1 === 0 }, // 创建下载element createDownloadUrl(url) { console.log(url); const a = document.createElement('a'); a.style.display = 'none'; a.download = 'download'; a.href = url; document.body.appendChild(a); a.click(); document.body.removeChild(a); }, // 刷新页面 relaodPage(router) { router .push({ path: '/_empty' }); router.go(-1); } } <file_sep>// const baseUrl = 'http://sd.9peak.net'; const baseUrl = 'http://sd-wms.9peak.net/admin/' export { baseUrl }<file_sep>import types from './types' const mutations = { [types.ADMIN_LOGIN](state) { state.logined = true }, [types.ADMIN_LOGOUT](state) { state.logined = false }, setMenu(state, menu) { state.menu = menu } } export default mutations;<file_sep>import types from './types' const actions = { adminLogin({ commit }) { commit(types.ADMIN_LOGIN) }, adminLogout({ commit }) { commit(types.ADMIN_LOGOUT) }, createImage(store, payload) { return new Promise(function(resolve, reject) { var reader = new FileReader() reader.readAsDataURL(payload.file) reader.onload = (e) => { resolve(e.target.result) } if (!(payload.type.test(payload.file.name))) { reader.abort() reject(new Error('type')) } if (payload.file.size > payload.size * 1024 * 1024) { reader.abort() reject(new Error('size')) } }) } } export default actions;<file_sep>import { baseUrl } from './env' import axios from 'axios' import { Notification } from 'element-ui' axios.defaults.baseURL = baseUrl axios.defaults.headers.post['X-Request-With'] = 'XMLHttpRequest' export default async(url, method, data = {}, forbid) => { let response if (sessionStorage.getItem('token')) { // axios.defaults.headers.common['Authorization'] = sessionStorage.getItem('token') axios.defaults.headers.common['Authorization'] = 'Token <PASSWORD>' } if (method == 'get') { response = await axios.get(url, { params: data }) } else if (method == 'post') { // console.log(url); response = await axios.post(url, data) } if (response.data.res === 1) { if (!forbid) { Notification.success({ message: response.data.msg, duration: 1500 }) } if (response.data) { if (response.data.dat) { if (response.data.dat.token) { sessionStorage.setItem('token', response.data.dat.token) } } } // console.log(response.data); return Promise.resolve(response.data.dat) } else if (response.data.res === 0) { Notification.error({ message: response.data.msg, duration: 1500 }) return Promise.reject(response.data.msg) } } export function downloadexcel(url, data) { if (sessionStorage.getItem('token')) { axios.defaults.headers.common['Authorization'] = 'Token <PASSWORD>' } return axios.get(url, { params: data, responseType: 'blob' }) } export { axios } <file_sep>const getters = { menu: state => state.menu } export default getters;
281839ecb9bb9306b4bfd251a95f83cf0c06f29b
[ "JavaScript" ]
7
JavaScript
linjijian/Vue
1e1ed2eea4aa83da9e396b4028f6abf3f7bc6d3d
2b98dc973007cf5f4d0148a59b6d93d85e66adec
refs/heads/master
<repo_name>ngplug/ngplugtimer<file_sep>/src/app/timerc/timerc.module.spec.ts import { TimercModule } from './timerc.module'; describe('TimercModule', () => { let timercModule: TimercModule; beforeEach(() => { timercModule = new TimercModule(); }); it('should create an instance', () => { expect(timercModule).toBeTruthy(); }); });
7b7c4ff6825db347b44f348c3a09664c02ad41f9
[ "TypeScript" ]
1
TypeScript
ngplug/ngplugtimer
1a658d774dba48768f2486c944cc782b34f676bd
deaac9db67e77bca050394bab8a7441abcdf884a
refs/heads/master
<repo_name>hupe1980/udacity-fsnd-trivia-api<file_sep>/backend/Dockerfile FROM python:3.7.7-alpine3.11 RUN apk update \ && apk add \ build-base \ postgresql \ postgresql-dev \ libpq WORKDIR /usr/src/app COPY requirements.txt . RUN pip install -r requirements.txt COPY . . ENV PYTHONUNBUFFERED 1 ENV FLASK_RUN_HOST 0.0.0.0 ENV FLASK_ENV development ENV FLASK_APP flaskr EXPOSE 5000 ENTRYPOINT ["flask", "run"]<file_sep>/postgres/Dockerfile FROM postgres:11.7-alpine COPY init.sh /docker-entrypoint-initdb.d/ <file_sep>/backend/flaskr/__init__.py import os from flask import Flask, request, abort, jsonify from flask_sqlalchemy import SQLAlchemy from flask_cors import CORS import random from models import setup_db, Question, Category QUESTIONS_PER_PAGE = 10 def create_app(test_config=None): # create and configure the app app = Flask(__name__) setup_db(app) CORS(app) @app.after_request def after_request(response): response.headers.add('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS') response.headers.add('Access-Control-Allow-Headers', 'Content-Type,Authorization,true') return response # Helper function to paginate questions def paginate_questions(request, questions): page = request.args.get('page', 1, type=int) start = (page - 1) * QUESTIONS_PER_PAGE end = start + QUESTIONS_PER_PAGE current_question = [question.format() for question in questions[start:end]] return current_question @app.route('/categories', methods=['GET']) def get_categories(): '''Returns a list of categories''' categories = Category.query.order_by(Category.type).all() if len(categories) == 0: abort(404) return jsonify({ 'success': True, 'categories': {category.id: category.type for category in categories}, }), 200 @app.route('/questions', methods=['GET']) def get_questions(): '''Returns a list of questions''' all_questions = Question.query.order_by(Question.id).all() questions = paginate_questions(request, all_questions) current_category = [question['category'] for question in questions] current_category = list(set(current_category)) categories = Category.query.order_by(Category.type).all() if len(questions) == 0: abort(404) return jsonify({ 'success': True, 'questions': questions, 'total_questions': len(all_questions), 'categories': {category.id: category.type for category in categories}, 'current_category': current_category, }), 200 @app.route('/questions/<int:question_id>', methods=['DELETE']) def delete_question(question_id): '''Deletes a question by id''' try: question = Question.query.get(question_id) if not question: abort(404) question.delete() return jsonify({ 'success': True, 'deleted': question_id, }), 200 except Exception as e: abort(404) @app.route('/questions', methods=['POST']) def add_question(): '''Creates a new question''' body = request.get_json() question = body.get('question', None) answer = body.get('answer', None) category = body.get('category', None) difficulty = body.get('difficulty', None) if question is None or answer is None: abort(400) if len(question) == 0 or len(answer) == 0: abort(400) try: question = Question(question, answer, category, difficulty) question.insert() return jsonify({ 'success': True }), 201 except Exception as e: abort(422) @app.route('/questions/search', methods=['POST']) def search_questions(): '''Searchs questions''' search_term = request.json['searchTerm'] if search_term is None: abort(400) if len(search_term) == 0: abort(400) try: selection = Question.query.filter( Question.question.ilike(f'%{search_term}%')).all() search_results = paginate_questions(request, selection) return jsonify({ 'success': True, 'questions': search_results, 'total_questions': len(search_results), 'current_category': None }), 200 except Exception: abort(404) @app.route('/categories/<int:category_id>/questions', methods=['GET']) def get_questions_by_category(category_id): '''Gets questions by category id''' selection = Question.query.filter_by(category=category_id).all() questions = paginate_questions(request, selection) if len(questions) == 0: abort(404) return jsonify({ 'success': True, 'questions': questions, 'total_questions': len(selection), 'current_category': category_id, }) @app.route('/quizzes', methods=['POST']) def play_quiz(): '''Allows users to play the quiz game''' previous_questions = request.json['previous_questions'] category = request.json['quiz_category'] try: if category['id'] == 0: questions = Question.query.filter( Question.id.notin_(previous_questions)).all() else: questions = Question.query.filter_by(category=category['id']).filter( Question.id.notin_(previous_questions)).all() if len(questions) == 0: raise question_list = [(query.id, query.question, query.answer) for query in questions] question = questions[random.randrange( 0, len(questions))].format() if len(questions) > 0 else None return jsonify({ 'success': True, 'question': question }) except Exception: abort(404) @app.errorhandler(400) def bad_request(error): return jsonify({ "success": False, "error": 400, "message": "Bad request" }), 400 @app.errorhandler(404) def resource_not_found(error): return jsonify({ "success": False, "error": 404, "message": "Resource not found" }), 404 @app.errorhandler(422) def unprocessable(error): return jsonify({ "success": False, "error": 422, "message": "Unprocessable" }), 422 return app <file_sep>/postgres/init.sh #!/bin/bash set -e psql -v ON_ERROR_STOP=1 --username "$POSTGRES_USER" --dbname "$POSTGRES_DB" <<-EOSQL -- -- PostgreSQL database dump -- -- Dumped from database version 11.3 -- Dumped by pg_dump version 11.3 SET statement_timeout = 0; SET lock_timeout = 0; SET idle_in_transaction_session_timeout = 0; SET client_encoding = 'UTF8'; SET standard_conforming_strings = on; SELECT pg_catalog.set_config('search_path', '', false); SET check_function_bodies = false; SET xmloption = content; SET client_min_messages = warning; SET row_security = off; SET default_tablespace = ''; SET default_with_oids = false; -- -- Name: categories; Type: TABLE; Schema: public; Owner: caryn -- CREATE TABLE public.categories ( id integer NOT NULL, type text ); ALTER TABLE public.categories OWNER TO caryn; -- -- Name: categories_id_seq; Type: SEQUENCE; Schema: public; Owner: caryn -- CREATE SEQUENCE public.categories_id_seq AS integer START WITH 1 INCREMENT BY 1 NO MINVALUE NO MAXVALUE CACHE 1; ALTER TABLE public.categories_id_seq OWNER TO caryn; -- -- Name: categories_id_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: caryn -- ALTER SEQUENCE public.categories_id_seq OWNED BY public.categories.id; -- -- Name: questions; Type: TABLE; Schema: public; Owner: caryn -- CREATE TABLE public.questions ( id integer NOT NULL, question text, answer text, difficulty integer, category integer ); ALTER TABLE public.questions OWNER TO caryn; -- -- Name: questions_id_seq; Type: SEQUENCE; Schema: public; Owner: caryn -- CREATE SEQUENCE public.questions_id_seq AS integer START WITH 1 INCREMENT BY 1 NO MINVALUE NO MAXVALUE CACHE 1; ALTER TABLE public.questions_id_seq OWNER TO caryn; -- -- Name: questions_id_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: caryn -- ALTER SEQUENCE public.questions_id_seq OWNED BY public.questions.id; -- -- Name: categories id; Type: DEFAULT; Schema: public; Owner: caryn -- ALTER TABLE ONLY public.categories ALTER COLUMN id SET DEFAULT nextval('public.categories_id_seq'::regclass); -- -- Name: questions id; Type: DEFAULT; Schema: public; Owner: caryn -- ALTER TABLE ONLY public.questions ALTER COLUMN id SET DEFAULT nextval('public.questions_id_seq'::regclass); -- -- Data for Name: categories; Type: TABLE DATA; Schema: public; Owner: caryn -- COPY public.categories (id, type) FROM stdin; 1 Science 2 Art 3 Geography 4 History 5 Entertainment 6 Sports \. -- -- Data for Name: questions; Type: TABLE DATA; Schema: public; Owner: caryn -- COPY public.questions (id, question, answer, difficulty, category) FROM stdin; 5 Whose autobiography is entitled 'I Know Why the Caged Bird Sings'? <NAME> 2 4 9 What boxer's original name is <NAME>? <NAME> 1 4 2 What movie earned <NAME> his third straight Oscar nomination, in 1996? Apollo 13 4 5 4 What actor did author <NAME> first denounce, then praise in the role of her beloved Lestat? <NAME> 4 5 6 What was the title of the 1990 fantasy directed by <NAME> about a young man with multi-bladed appendages? <NAME> 3 5 10 Which is the only team to play in every soccer World Cup tournament? Brazil 3 6 11 Which country won the first ever soccer World Cup in 1930? Uruguay 4 6 12 Who invented Peanut Butter? <NAME> 2 4 13 What is the largest lake in Africa? Lake Victoria 2 3 14 In which royal palace would you find the Hall of Mirrors? The Palace of Versailles 3 3 15 The Taj Mahal is located in which Indian city? Agra 2 3 16 Which Dutch graphic artist–initials M C was a creator of optical illusions? Escher 1 2 17 La Giaconda is better known as what? <NAME> 3 2 18 How many paintings did <NAME> sell in his lifetime? One 4 2 19 Which American artist was a pioneer of Abstract Expressionism, and a leading exponent of action painting? <NAME> 2 2 20 What is the heaviest organ in the human body? The Liver 4 1 21 Who discovered penicillin? <NAME> 3 1 22 Hematology is a branch of medicine involving the study of what? Blood 4 1 23 Which dung beetle was worshipped by the ancient Egyptians? Scarab 4 4 \. -- -- Name: categories_id_seq; Type: SEQUENCE SET; Schema: public; Owner: caryn -- SELECT pg_catalog.setval('public.categories_id_seq', 6, true); -- -- Name: questions_id_seq; Type: SEQUENCE SET; Schema: public; Owner: caryn -- SELECT pg_catalog.setval('public.questions_id_seq', 23, true); -- -- Name: categories categories_pkey; Type: CONSTRAINT; Schema: public; Owner: caryn -- ALTER TABLE ONLY public.categories ADD CONSTRAINT categories_pkey PRIMARY KEY (id); -- -- Name: questions questions_pkey; Type: CONSTRAINT; Schema: public; Owner: caryn -- ALTER TABLE ONLY public.questions ADD CONSTRAINT questions_pkey PRIMARY KEY (id); -- -- Name: questions category; Type: FK CONSTRAINT; Schema: public; Owner: caryn -- ALTER TABLE ONLY public.questions ADD CONSTRAINT category FOREIGN KEY (category) REFERENCES public.categories(id) ON UPDATE CASCADE ON DELETE SET NULL; -- -- PostgreSQL database dump complete -- EOSQL
151fadf992ceb00ac93a3cadc4f0ff9ee843659a
[ "Python", "Dockerfile", "Shell" ]
4
Dockerfile
hupe1980/udacity-fsnd-trivia-api
6584c4808b7c85ce16290dec6ed9a9e27f457da9
e03bcd2ba66a8e97b884b129f8565b8700d10377
refs/heads/master
<repo_name>casim0/.999<file_sep>/README.md # [빅데이터 청년인재 BIG X CAMPUS 프로젝트] #### 프로젝트명: 영상 등급 분류 보조 시스템(Picker) #### 팀명: .999 (9할 9푼 9리) --- ### 1. 목적 DDDM(Data Driven Decision Making)을 통해 객관적으로 영화 등급을 분류할 수 있게 할것 자동화 시스템을 통해 영상 컨텐츠 증가에 따른 심사 인력 부족 현상을 해결할 것 ### 2. 주요 기능 영상 내 유해 요소 감지 영상 내 유해 요소 타임라인, 비중 정보 제공 ### 3. 진행 과정 #### 3-1. 데이터 수집 및 전처리 ##### (1) 데이터 수집 영상 등급 위원회에서 고려하는 7가지 요소(주제 대사, 공포, 약물, 선정성, 폭력성, 모방위험) 중 `선정성` `폭력성` `모방위험`에 초점을 맞춤 ![dataset](https://github.com/krispedia/.999/blob/master/_ect/dataset.jpg) ##### (2) 데이터 전처리 전처리 도구 : [VIA](http://www.robots.ox.ac.uk/~vgg/software/via/) ![annotation](https://github.com/krispedia/.999/blob/master/_ect/annotation.jpg) <전처리 기준> - 담배<br> `담배를 입에 물고 있는 경우` - 코 아래부터 입 포함 아래턱 까지 - 양 볼의 절반 포함 `담배를 손에 들고 있는 경우` - 손가락과 손 포함 손목까지 `담배를 손에 들고 입으로 물고 있는 경우` - 손가락 포함 양볼 절반, 코 아래부터 입포함 아래턱까지 - 총<br> - 칼<br> `칼 형태가 드러나있을 경우` - 칼 윤곽선만 마스킹 `사람이 칼을 쥐고있어 칼에서 칼날만 드러날 경우` - 칼날과 손(주먹)까지 마스킹 - 가슴<br> `뚜렷한 선이 없는 경우` - 정확한 가슴 모양이 아닌 조금 폭 넓게 마스킹 함 `가슴의 일부가 가려진 경우` - 손과 같은 다른 것이 일부만 가리는 경우에는 같이 포함하여 마스킹함 `가슴의 반 이상이 가려진 경우` - 옷이나, 손 등으로 가슴의 반 이상이 가려진 경우에는 그것들을 제외하고 마스킹함 - 주류<br> #### 3-2. 모델 학습 ##### (1) 모델 선정 ##### (2) 모델 학습 방법 ##### (3) 모델 최적화 ![hyperparameter](https://github.com/krispedia/.999/blob/master/_ect/hyperparameter.jpg) #### 3-3. 웹사이트 구현 ![service](https://github.com/krispedia/.999/blob/master/_ect/service.jpg) ### 4. 결과물 ![result](https://github.com/krispedia/.999/blob/master/_ect/website.jpg) <file_sep>/BCI_FINAL_MAC/video/migrations/0001_initial.py # Generated by Django 2.1.7 on 2019-08-23 06:29 from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Candidate', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(max_length=10)), ('introduction', models.TextField()), ('area', models.CharField(max_length=15)), ('party_number', models.IntegerField(default=1)), ], ), migrations.CreateModel( name='Post', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('title', models.CharField(max_length=100)), ('photo', models.ImageField(blank=True, upload_to='')), ], ), migrations.CreateModel( name='Ratio', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('title', models.CharField(max_length=500)), ('timeline', models.CharField(max_length=500)), ('ratio', models.CharField(max_length=500)), ('total_ratio', models.CharField(max_length=500)), ('time_dict', models.CharField(max_length=1500)), ], ), migrations.CreateModel( name='Video', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(max_length=500)), ('videofile', models.FileField(null=True, upload_to='videos/', verbose_name='')), ], ), ] <file_sep>/BCI_FINAL_WINDOWS/BCI/video/urls.py from django.conf.urls import url from django.urls import path from . import views app_name = 'video' urlpatterns = [ # url(r'^', views.showvideo), url(r'^$', views.video_list, name='list'), url(r'^new$', views.video_new, name='new'), # url(r'', views.video_new, name='new'), url(r'(?P<video_id>\d+)/$', views.video_detail, name='detail'), # url(r'^popup$', views.popup), ] <file_sep>/BCI_FINAL_MAC/video/models_origin.py from django.db import models # Create your models here. class Candidate(models.Model): name = models.CharField(max_length=10) introduction = models.TextField() area = models.CharField(max_length=15) party_number = models.IntegerField(default=1) class Post(models.Model): title = models.CharField(max_length=100) photo = models.ImageField(blank=True) class Video(models.Model): name = models.CharField(max_length=500) videofile = models.FileField(upload_to='videos/', null=True, verbose_name="") def __str__(self): return self.name + ": " + str(self.videofile) class Ratio(models.Model): title = models.CharField(max_length=500) timeline = models.CharField(max_length=500) ratio = models.CharField(max_length=500) total_ratio=models.CharField(max_length=500) def __str__(self): return self.title<file_sep>/BCI_FINAL_MAC/video/views.py from django.shortcuts import render, redirect from django.http import HttpResponse from django.http import HttpResponseRedirect from django.urls import reverse from .models import Video, Ratio from .forms import VideoForm import os learning_check = True # Create your views here. def index(request): return render(request, 'video/index.html') def showvideo(request): lastvideo= Video.objects.last() videofile= lastvideo.videofile form = VideoForm(request.POST or None, request.FILES or None) if form.is_valid(): form.save() context = {'videofile': videofile, 'form': form } return render(request, 'video/index.html', context) def video_list(request): video_list = Video.objects.all() print(os.getcwd()) return render(request, 'video/video_list.html', {'video_list': video_list}) def video_new(request): global learning_check form = VideoForm(request.POST or None, request.FILES or None) if request.method == 'POST': if form.is_valid(): form.save() learning_check = False return HttpResponseRedirect('/video') elif request.method == 'GET': return render(request, 'video/video_new.html', {'form':form}) def video_detail(request, video_id): from . import detection_video video = Video.objects.get(id=video_id) videofile = video.videofile form = VideoForm(request.POST or None, request.FILES or None) print('videofile :', videofile) if not learning_check: detection_video.learning(videofile) ratio_data = Ratio(title = video, timeline = detection_video.obj_sec, ratio = detection_video.count_obj, total_ratio = detection_video.total_obj, time_dict=detection_video.time_dict) ratio_data.save() elif learning_check: pass try : print(video) ratio = Ratio.objects.get(title=str(video)) print(ratio.timeline, ratio.ratio, ratio.total_ratio) context = {'videofile': videofile, 'form': form, 'ratios': eval(ratio.ratio), 'total_obj':eval(ratio.total_ratio), 'time_dict':eval(ratio.time_dict), } except : print("not learned yet") context = {'videofile': videofile, 'form': form } # print('real data :', detection_video.count_obj) # count_obj = {'gun': 8.75, # 'knife': 99.9, # 'cigarette': 12.3, # 'boob': 24.5, # 'alcohol': 22.3} # print('test data :', count_obj) return render(request, 'video/video_detail.html', context)<file_sep>/BCI_FINAL_MAC/video/admin.py from django.contrib import admin from .models import Video from .models import Ratio # Register your models here. admin.site.register(Video) admin.site.register(Ratio) <file_sep>/BCI_FINAL_WINDOWS/BCI/test.py import os os.chdir('./Mask_RCNN') print(os.listdir())<file_sep>/BCI_FINAL_UBUNTU/video/views_ddo.py from django.shortcuts import render, redirect from django.http import HttpResponse from django.http import HttpResponseRedirect from django.urls import reverse from .models import Video from .forms import VideoForm import os # Create your views here. def index(request): return render(request, 'video/index.html') def showvideo(request): lastvideo= Video.objects.last() videofile= lastvideo.videofile form= VideoForm(request.POST or None, request.FILES or None) if form.is_valid(): form.save() context = {'videofile': videofile, 'form': form } return render(request, 'video/index.html', context) def video_list(request): video_list = Video.objects.all() print(os.getcwd()) return render(request, 'video/video_list.html', {'video_list': video_list}) def video_new(request): form = VideoForm(request.POST, request.FILES) if request.method == 'POST': if form.is_valid(): form.save() return HttpResponseRedirect('/video') elif request.method == 'GET': return render(request, 'video/video_new.html', {'form':form}) def video_detail(request, video_id): from . import detection_video video = Video.objects.get(id=video_id) videofile = video.videofile form = VideoForm(request.POST or None, request.FILES or None) detection_video.learning(videofile) context = {'videofile': videofile, 'form': form, 'obj':detection_video.obj_list, 'ratio':detection_video.ratio_list, 'na':detection_video.na } print('videofile :', videofile) print(detection_video.obj_list) print(detection_video.ratio_list) return render(request, 'video/video_detail.html', context) <file_sep>/BCI_FINAL_WINDOWS/BCI/video/views.py from django.shortcuts import render, redirect from django.http import HttpResponse from django.http import HttpResponseRedirect from django.urls import reverse from .models import Video, Ratio from .forms import VideoForm import os learning_check = True # Create your views here. def index(request): return render(request, 'video/index.html') def showvideo(request): lastvideo= Video.objects.last() videofile= lastvideo.videofile form = VideoForm(request.POST or None, request.FILES or None) if form.is_valid(): form.save() context = {'videofile': videofile, 'form': form } return render(request, 'video/index.html', context) def video_list(request): video_list = Video.objects.all() print(os.getcwd()) return render(request, 'video/video_list.html', {'video_list': video_list}) def video_new(request): global learning_check form = VideoForm(request.POST or None , request.FILES or None) if request.method == 'POST': if form.is_valid(): form.save() learning_check = False return HttpResponseRedirect('/video') elif request.method == 'GET': return render(request, 'video/video_new.html', {'form':form}) def video_detail(request, video_id): if request.method == 'POST': pass from . import detection_video video = Video.objects.get(id=video_id) videofile = video.videofile form = VideoForm(request.POST or None, request.FILES or None) print('videofile :', videofile) if request.method == 'POST': # if not learning_check: # detection_video.learning(videofile) # ratio_data = Ratio(title=video, timeline=detection_video.obj_sec, # ratio=detection_video.count_obj, total_ratio=detection_video.total_obj, # time_dict=detection_video.time_dict) # ratio_data.save() # elif learning_check: # pass detection_video.learning(videofile) ratio_data = Ratio(title=video, timeline=detection_video.obj_sec, ratio=detection_video.count_obj, total_ratio=detection_video.total_obj, time_dict=detection_video.time_dict) ratio_data.save() try: print(video) ratio = Ratio.objects.get(title=str(video)) print(ratio.timeline, ratio.ratio, ratio.total_ratio) context = {'videofile': videofile, 'form': form, 'ratios': eval(ratio.ratio), 'total_obj': eval(ratio.total_ratio), 'time_dict': eval(ratio.time_dict), 'processing_time': detection_video.processing_time, } except: print("not learned yet") context = {'videofile': videofile, 'form': form } return render(request, 'video/video_detail.html', context) elif request.method == 'GET': try: print(video) ratio = Ratio.objects.get(title=str(video)) print(ratio.timeline, ratio.ratio, ratio.total_ratio) context = {'videofile': videofile, 'form': form, 'ratios': eval(ratio.ratio), 'total_obj': eval(ratio.total_ratio), 'time_dict': eval(ratio.time_dict), 'processing_time': detection_video.processing_time, } except: print("not learned yet") context = {'videofile': videofile, 'form': form } return render(request, 'video/video_detail.html', context) # def popup(request): # return render(request, 'video/popups/Processing.html')<file_sep>/BCI_FINAL_MAC/video/Mask_RCNN/det.py import os import sys import json import numpy as np import skimage.draw import collections from collections import defaultdict # Root directory of the project ROOT_DIR = os.path.abspath("../../") # Import Mask RCNN sys.path.append(ROOT_DIR) # To find local version of the library from mrcnn.config import Config from mrcnn import utils ############################################################ # Configurations ############################################################ class DetConfig(Config): """Configuration for training on the dataset. Derives from the base Config class and overrides some values. """ def __init__(self, dataset_name, classnames): # Give the configuration a recognizable name self.dataset_name = dataset_name self.NAME = dataset_name self.CLASS_NAMES = classnames self.ALL_CLASS_NAMES = ['BG'] + self.CLASS_NAMES # Number of classes (including background) self.NUM_CLASSES = len(self.ALL_CLASS_NAMES) self.map_name_to_id = {} Config.__init__(self) # A GPU with 12GB memory can fit two images. IMAGES_PER_GPU = 2 # Number of training steps per epoch STEPS_PER_EPOCH = 100 # Skip detections with < 90% confidence DETECTION_MIN_CONFIDENCE = 0.5 TRAINING_VERBOSE = 1 TRAIN_BN = False # 'relu' or 'leakyrelu' ACTIVATION = 'relu' ############################################################ # Multi-class Dataset ############################################################ # Example usage: # Load images from a training directory. # dataset_train = DetDataset() # dataset_train.load_dataset_images(dataset_path, "train", config.CLASS_NAMES) # # Alternatively use the convenience function for taking from one directory and spliting into train and test # dataset_train, dataset_val = create_datasets(dataset_path+'/train', config.CLASS_NAMES) class DetDataset(utils.Dataset): def __init__(self, config): self.dataset_name = config.NAME self.map_name_to_id = {} self.actual_class_names = collections.Counter() utils.Dataset.__init__(self) def load_by_annotations(self, dataset_dir, annotations_list, class_names): """Load a specific set of annotations and from them images. dataset_dir: Root directory of the dataset. annotations_list: The annotations (and images) to be loaded. class_names: List of classes to use. """ # Find the unique classes and track their count for a in annotations_list: regions = a['regions'] for r, v in regions.items(): object_name = v['region_attributes']['object_name'] self.actual_class_names[object_name] += 1 # Add classes. Use class_names to ensure consistency. for i, name in enumerate(class_names): # Skip over background if it appears in the class name list index = i + 1 if name != 'BG': print('Adding class {:3}:{}'.format(index, name)) self.add_class(self.dataset_name, index, name) self.map_name_to_id[name] = index # Add images for a in annotations_list: # Get the x, y coordinates of points of the polygons that make up # the outline of each object instance. There are stores in the # shape_attributes (see json format above) polygons = [r['shape_attributes'] for r in a['regions'].values()] r_object_name = [r['region_attributes']['object_name'] for r in a['regions'].values()] assert len(polygons) == len(r_object_name) # load_mask() needs the image shape. image_path = os.path.join(dataset_dir, a['filename']) # The annotation file needs to be pre-processed to save the shape of the image. # If it isn't it will have to be read in. if 'height' in a and 'width in a': height = a['height'] width = a['width'] else: image = skimage.io.imread(image_path) height, width = image.shape[:2] self.add_image( self.dataset_name, image_id=a['filename'], # use file name as a unique image id path=image_path, width=width, height=height, polygons=polygons, r_object_name=r_object_name) def load_dataset_images(self, dataset_dir, subset, class_names): """Load a subset of the dataset. dataset_dir: Root directory of the dataset. subset: Subset to load: train or val class_names: List of classes to use. """ # Train or validation dataset? assert subset in ["train", "val"] print(dataset_dir) print(subset) dataset_dir = os.path.join(dataset_dir, subset) # Load annotations annotations = json.load(open(os.path.join(dataset_dir, "annotations.json"))) annotations = list(annotations.values()) # don't need the dict keys # The VIA tool saves images in the JSON even if they don't have any # annotations. Skip unannotated images. annotations = [a for a in annotations if a['regions']] # Find the unique classes and track their count for a in annotations: for _, region in a['regions'].items(): object_name = region['region_attributes']['object_name'] self.actual_class_names[object_name] += 1 # Add classes. for i, name in enumerate(class_names): # Skip over background if it occurs in the index = i + 1 if name != 'BG': print('Adding class {:3}:{}'.format(index, name)) self.add_class('wolf', index, name) # Add images for a in annotations: # Get the x, y coordinaets of points of the polygons that make up # the outline of each object instance. There are stores in the # shape_attributes (see json format above) polygons = [r['shape_attributes'] for r in a['regions'].values()] # load_mask() needs the image size to convert polygons to masks. # Unfortunately, VIA doesn't include it in JSON, so we must read # the image. This is only managable since the dataset is tiny. image_path = os.path.join(dataset_dir, a['filename']) image = skimage.io.imread(image_path) height, width = image.shape[:2] self.add_image( self.dataset_name, image_id=a['filename'], # use file name as a unique image id path=image_path, width=width, height=height, polygons=polygons) def load_mask(self, image_id): """Generate instance masks for an image. Returns: masks: A bool array of shape [height, width, instance count] with one mask per instance. class_names: a 1D array of class IDs of the instance masks. """ # If not an object in our dataset image, delegate to parent class. image_info = self.image_info[image_id] if image_info["source"] not in self.class_names: print("warning: source {} not part of our classes, delegating to parent.".format(image_info["source"])) return super(self.__class__, self).load_mask(image_id) # Convert polygons to a bitmap mask of shape # [height, width, instance_count] info = self.image_info[image_id] mask = np.zeros([info["height"], info["width"], len(info["polygons"])], dtype=np.uint8) class_ids = [] for i, p in enumerate(info["polygons"]): # Get indexes of pixels inside the polygon and set them to 1 try: rr, cc = skimage.draw.polygon(p['all_points_y'], p['all_points_x']) mask[rr, cc, i] = 1 class_id = self.map_name_to_id[info['r_object_name'][i]] class_ids.append(class_id) except: print(image_info) raise # Return mask, and array of class IDs of each instance. Since we have # one class ID only, we return an array of 1s class_ids = np.array(class_ids, dtype=np.int32) return mask.astype(np.bool), class_ids def image_reference(self, image_id): """Return the path of the image.""" info = self.image_info[image_id] if info["source"] == self.dataset_name: return info["path"] else: print("warning: DetDataSet: using parent image_reference for: ", info["source"]) super(self.__class__, self).image_reference(image_id) def split_annotations(dataset_dir, config, train_pct=.8, annotation_filename="annotations.json", randomize=True): """ divide up an annotation file for training and validation dataset_dir: location of images and annotation file. config: config object for training. train_pct: the split between train and val default is .8 annotation_filename: name of annotation file. randomize: If true (default) shuffle the list of annotations. """ indexes = {} for idx, cn in enumerate(config.CLASS_NAMES): indexes[cn] = idx # Load annotations annotations = json.load(open(os.path.join(dataset_dir, annotation_filename))) annotations = list(annotations.values()) # The VIA tool saves images in the JSON even if they don't have any # annotations. Skip unannotated images. annotations = [a for a in annotations if a['regions']] if randomize: # Randomize the annotations then divide np.random.shuffle(annotations) # Find the unique classes and track their count uniq_class_names = collections.Counter() images_classes = {} total_classes = 0 for a in annotations: rc = np.zeros(len(config.CLASS_NAMES)) for id, region in a['regions'].items(): # print("region: ",type(region)) object_name = region['region_attributes']['object_name'] uniq_class_names[object_name] += 1 total_classes += 1 rc[indexes[object_name]] += 1 images_classes[a['filename']] = rc # Calculate the weights for assigning to buckets, # the fewer the greater the weight. class_weights = np.zeros(len(config.CLASS_NAMES)) for cn in uniq_class_names: class_weights[indexes[cn]] = total_classes / uniq_class_names[cn] # Distribute the annotations into buckets by class bucket_of_classes = defaultdict(list) for a in annotations: # Multiply class count by weights to select which bucket. t = images_classes[a['filename']] * class_weights selected_class = t.argmax() bucket_of_classes[config.CLASS_NAMES[selected_class]].append(a) train_ann = [] val_ann = [] for k, v in bucket_of_classes.items(): n_for_train = int(len(v)*train_pct) train_ann = train_ann + v[:n_for_train] val_ann = val_ann + v[n_for_train:] def validate_unique(ann, img_files={}): for a in ann: filename = a['filename'] if filename in img_files: raise RuntimeError(filename+' already exists') else: img_files[filename] = 1 return img_files img_files = validate_unique(train_ann) img_files = validate_unique(val_ann, img_files) assert len(train_ann)+len(val_ann) == len(img_files) return train_ann, val_ann def create_datasets(dataset_dir, config, train_pct=.8): """ set up the training and validation training set. dataset_dir: location of images and annotation file. config: config object that includes list of classes being trained for. train_pct: the split between train and val default is .8 """ train_ann, val_ann = split_annotations(dataset_dir, config, train_pct=train_pct) print(annotation_stats(train_ann)) print(annotation_stats(val_ann)) train_ds = DetDataset(config) train_ds.load_by_annotations(dataset_dir, train_ann, config.CLASS_NAMES) val_ds = DetDataset(config) val_ds.load_by_annotations(dataset_dir, val_ann, config.CLASS_NAMES) assert len(train_ds.image_info) == len(train_ann) and len(val_ds.image_info) == len(val_ann) return train_ds, val_ds def annotation_stats(annotations): # Find the unique classes and track their count uniq_class_names = collections.Counter() for a in annotations: for id, region in a['regions'].items(): object_name = region['region_attributes']['object_name'] uniq_class_names[object_name] += 1 return uniq_class_names if __name__ == "__main__": config = DetConfig('cigarette', ['cigarette']) dataset_train, dataset_val = create_datasets('./images/imgnet_n02114100/train', config) # config = DetConfig('sign', ['sign', 'yield_sign', 'stop_sign', 'oneway_sign', 'donotenter_sign', 'wrongway_sign']) # dataset_train, dataset_val = create_datasets('./images/signs/train', config) dataset_train.prepare() dataset_val.prepare() print("Training Images: {}\nClasses: {}".format(len(dataset_train.image_ids), dataset_train.class_names)) print("Validation Images: {}\nClasses: {}".format(len(dataset_val.image_ids), dataset_val.class_names)) <file_sep>/BCI_FINAL_MAC/video/models.py from django.db import models # from django.contrib.postgres.fields import ArrayField # Create your models here. class Candidate(models.Model): name = models.CharField(max_length=10) introduction = models.TextField() area = models.CharField(max_length=15) party_number = models.IntegerField(default=1) class Post(models.Model): title = models.CharField(max_length=100) photo = models.ImageField(blank=True) class Video(models.Model): name = models.CharField(max_length=500) videofile = models.FileField(upload_to='videos/', null=True, verbose_name="") def __str__(self): return self.name + ": " + str(self.videofile) class Ratio(models.Model): title = models.CharField(max_length=500) timeline = models.CharField(max_length=500) ratio = models.CharField(max_length=500) total_ratio = models.CharField(max_length=500) time_dict = models.CharField(max_length=1500) def __str__(self): return self.title
b9d964d98c83d5de0968c3a624c27b82071d7e3a
[ "Markdown", "Python" ]
11
Markdown
casim0/.999
93147079bbfc50c7619d232783f7db7ca372be26
1ee160a26bc972a19d543a00d3bb1ea5a26ec65c
refs/heads/master
<file_sep>const webpack = require('webpack'); const path = require('path'); const requireDir = require('require-dir'); const settings = requireDir('./webpack'); const env = process.env.NODE_ENV || 'development'; const config = { devtool: env !== 'development' ? '' : 'eval-source-map', entry: settings.entry(env), output: settings.output(env), resolve: { extensions: ['', '.js', '.jsx'], alias: { modernizr$: path.resolve(__dirname, '../.modernizrrc'), "TweenLite": "gsap/src/uncompressed/TweenLite" } }, plugins: settings.plugins(env), module: { preLoaders: settings.preloaders(env), loaders: settings.loaders(env), postLoaders: settings.postloaders(env) }, // postcss: function () { // return [ // require('autoprefixer') // ] // }, eslint: { configFile: path.join(__dirname, '../.eslintrc'), emitWarning: true } } module.exports = config;<file_sep>'use strict'; const path = require('path'); module.exports = function (env) { const entry = { app: [path.join(__dirname, '../../src', 'init.jsx')] }; if(env === 'development') { entry.app.unshift('webpack-hot-middleware/client') } else { // any production settings } return entry; }<file_sep>import React from 'react'; import ReactGA from 'react-ga'; import { Router, browserHistory } from 'react-router'; import routes from './routes'; if (process.env.BROWSER) { require('./App.sass'); } ReactGA.initialize('UA-XXXXXX-XX'); const logPageView = () => { ReactGA.set({ page: window.location.pathname }); ReactGA.pageview(window.location.pathname); }; const App = () => ( <Router history={browserHistory} routes={routes} onUpdate={logPageView} /> ); export default App; <file_sep>import path from 'path'; import compression from 'compression'; import express from 'express'; import middleware from './middleware'; import { createSitemap } from 'sitemap'; import React from 'react'; import { renderToString } from 'react-dom/server'; import { match, RouterContext } from 'react-router'; const env = process.env.NODE_ENV || 'development'; const port = process.env.PORT || 9000; // initialize the server const app = new express(); const sitemap = createSitemap({ hostname: 'http://example.com', cacheTime: 600000, urls: [ // {url: '/', changefreq: 'weekly', priority: 0.3}, // {url: '/about', changefreq: 'weekly', priority: 0.3} ] }) // set locals app.locals.env = env; // configure support for ejs app.set('view engine', 'ejs'); app.set('views', path.join(__dirname)); if (env !== 'production') { require('../tools/webpack/hot-module')(app, env); // get static assets app.use(express.static(path.join(__dirname, 'static', 'assets'))); } else { // get static assets and get compiled webpack paths app.use(express.static(path.join(__dirname, 'static', 'assets'))); app.use(express.static(path.join(__dirname, 'static', 'compiled'))); } app.use(compression()) // sitemap app.get('/sitemap.xml', (req, res) => { sitemap.toXML((err, xml) => { if (err) { return res.status(500).end(); } res.header('Content-Type', 'application/xml'); res.send(xml); }); }); // universal routing and rendering app.get('*', middleware); // start the server app.listen(port, err => { if(err) { return console.error(err); } console.info(`Server running on http://localhost:${port} [${env}]`) }) // proxy server to BrowserSync if (env !== 'production') { const browserSync = require('browser-sync'); browserSync.init({ proxy: `localhost:${port}`, port: 3000, ui: { port: 3001, weinre: { port: 3333 }, }, open: false }); } export default app;<file_sep>import React from 'react'; import { Route, IndexRoute } from 'react-router'; import Wrapper from 'layout/Wrapper/Wrapper'; import IndexPage from 'page/IndexPage/IndexPage'; import AboutPage from 'page/AboutPage/AboutPage'; import NotFoundPage from 'page/NotFoundPage/NotFoundPage'; const routes = ( <Route path="/" component={Wrapper}> <IndexRoute component={IndexPage} /> <Route path="/about" component={AboutPage} /> <Route path="*" component={NotFoundPage} /> </Route> ); export default routes; <file_sep>import React from 'react'; import { Link } from 'react-router'; const Nav = () => ( <div className="nav"> <div className="nav__row"> <div className="nav__col"> <ul> <li> <Link to="/">Home</Link> </li> <li> <Link to="/about">About</Link> </li> </ul> </div> </div> </div> ); export default Nav; <file_sep>import React, { Component } from 'react'; import { scaleSpriteToCanvas, spritePaths, positionSprite, spriteOnMouseMove } from 'utils/pixi.utils'; // LOADING BAR https://github.com/kittykatattack/learningPixi/blob/master/README.md export default class HeroCanvas extends Component { constructor(props) { super(props); this.settings = { transition: 3, speed: 1, dispScale: 20, dispX: false, dispY: true, count: 0, alpha: 1, }; // dispose of appended elements while hot reloading if (module.hot) { module.hot.dispose(() => { this.component.removeChild(this.renderer.view); }); } } componentDidMount() { // scripts called in componentDidMount will not execute // until after component is rendered. This means we can // use scripts meant for use in browser in our server-side // apps - the scripts won't be passed to our Node server and // result in undefined errors - not the greatest solution const PIXI = require('pixi.js'); PIXI.utils.skipHello(); // disable pixi banner in console // define all cached variables this.pixi = PIXI; this.renderer = PIXI.autoDetectRenderer(window.innerWidth, window.innerHeight); this.stage = new PIXI.Container(); this.bgContainer = new PIXI.Container(); this.layerAll = new PIXI.Container(); this.layerRight = new PIXI.Container(); this.layerLeft = new PIXI.Container(); // base canvas styles this.renderer.view.style.position = 'absolute'; this.renderer.view.style.display = 'block'; this.renderer.view.style.minHeight = 697; this.renderer.autoResize = true; const canvas = this.renderer.view; // append it to component // Pixi generates its own canvas element, which has to be // appended to dom. Here, this.component is assigned a reference // to the mounted component, using the 'ref' attribute in the // render method below. So, we are creating and appending our canvas // in one component, instead creating a component just to append to // another. If we weren't using Pixi, we could just render a canvas // element directly this.component.appendChild(canvas); // manipulate the pixi canvas this.addContainersToStage(); this.addPathstoLoader(); this.initPixiLoader(); this.animate(); } setSpritePositions() { /*eslint-disable*/ if (window.innerWidth < 768) { this.layerRight.y = window.innerHeight * 0.2; this.layerLeft.y = window.innerHeight * 0.2; // M positionSprite([this.layerRightChildren[0], this.layerRightChildren[1]], window.innerWidth * 0.2, window.innerHeight * 0.05, 0.35); // A positionSprite([this.layerRightChildren[2], this.layerRightChildren[3]], window.innerWidth * 0.25, window.innerHeight * 0.14, 0.35); // I positionSprite([this.layerRightChildren[4], this.layerRightChildren[5]], window.innerWidth * 0.53, window.innerHeight * 0.07, 0.35); // K positionSprite([this.layerLeftChildren[4], this.layerLeftChildren[5]], window.innerWidth * 0.52, window.innerHeight * 0.2, 0.35); // O positionSprite([this.layerRightChildren[6], this.layerRightChildren[7]], window.innerWidth * 0.67, window.innerHeight * 0.18, 0.35); // C positionSprite([this.layerRightChildren[10], this.layerRightChildren[11]], window.innerWidth * 0.15, window.innerHeight * 0.32, 0.35); // H positionSprite([this.layerRightChildren[8], this.layerRightChildren[9]], window.innerWidth * 0.4, window.innerHeight * 0.29, 0.35); // I positionSprite([this.layerLeftChildren[8], this.layerLeftChildren[9]], window.innerWidth * 0.32, window.innerHeight * 0.57, 0.35); // B positionSprite([this.layerLeftChildren[6], this.layerLeftChildren[7]], window.innerWidth * 0.67, window.innerHeight * 0.52, 0.35); // A positionSprite([this.layerLeftChildren[2], this.layerLeftChildren[3]], window.innerWidth * 0.85, window.innerHeight * 0.27, 0.35); // MAI positionSprite([this.layerLeftChildren[0], this.layerLeftChildren[1]], window.innerWidth * 0.73, window.innerHeight * 0.1, 0.35); // KO positionSprite([this.layerRightChildren[12], this.layerRightChildren[13]], window.innerWidth * 0.64, window.innerHeight * 0.37, 0.35); // CH positionSprite([this.layerLeftChildren[10], this.layerLeftChildren[11]], window.innerWidth * 0.4, window.innerHeight * 0, 0.35); // II positionSprite([this.layerLeftChildren[12], this.layerLeftChildren[13]], window.innerWidth * 0.15, window.innerHeight * 0.45, 0.35); // BA positionSprite([this.layerRightChildren[14], this.layerRightChildren[15]], window.innerWidth * 0.4, window.innerHeight * 0.47, 0.35); } else { this.layerRight.y = window.innerHeight * 0.15; this.layerLeft.y = window.innerHeight * 0.15; // M positionSprite([this.layerRightChildren[0], this.layerRightChildren[1]], window.innerWidth * 0.3, window.innerHeight * 0.04, 0.5); // A positionSprite([this.layerRightChildren[2], this.layerRightChildren[3]], window.innerWidth * 0.38, window.innerHeight * 0.2, 0.5); // I positionSprite([this.layerRightChildren[4], this.layerRightChildren[5]], window.innerWidth * 0.53, window.innerHeight * 0.11, 0.5); // K positionSprite([this.layerLeftChildren[4], this.layerLeftChildren[5]], window.innerWidth * 0.595, window.innerHeight * 0.31, 0.5); // O positionSprite([this.layerRightChildren[6], this.layerRightChildren[7]], window.innerWidth * 0.67, window.innerHeight * 0.14, 0.5); // C positionSprite([this.layerRightChildren[10], this.layerRightChildren[11]], window.innerWidth * 0.19, window.innerHeight * 0.41, 0.5); // H positionSprite([this.layerRightChildren[8], this.layerRightChildren[9]], window.innerWidth * 0.475, window.innerHeight * 0.41, 0.55); // I positionSprite([this.layerLeftChildren[8], this.layerLeftChildren[9]], window.innerWidth * 0.43, window.innerHeight * 0.6, 0.5); // B positionSprite([this.layerLeftChildren[6], this.layerLeftChildren[7]], window.innerWidth * 0.62, window.innerHeight * 0.58, 0.5); // A positionSprite([this.layerLeftChildren[2], this.layerLeftChildren[3]], window.innerWidth * 0.78, window.innerHeight * 0.27, 0.45); // MAI positionSprite([this.layerLeftChildren[0], this.layerLeftChildren[1]], window.innerWidth * 0.63, window.innerHeight * 0.03, 0.5); // KO positionSprite([this.layerRightChildren[12], this.layerRightChildren[13]], window.innerWidth * 0.65, window.innerHeight * 0.40, 0.5); // CH positionSprite([this.layerLeftChildren[10], this.layerLeftChildren[11]], window.innerWidth * 0.455, window.innerHeight * 0, 0.5); // II positionSprite([this.layerLeftChildren[12], this.layerLeftChildren[13]], window.innerWidth * 0.265, window.innerHeight * 0.25, 0.5); // BA positionSprite([this.layerRightChildren[14], this.layerRightChildren[15]], window.innerWidth * 0.31, window.innerHeight * 0.485, 0.4); } /*eslint-enable*/ } createFilters() { const PIXI = this.pixi; const resources = PIXI.loader.resources; // layers this.layerDpSprite = new PIXI.Sprite(resources['../img/displacement.png'].texture); this.layerDpFilter = new PIXI.filters.DisplacementFilter(this.layerDpSprite); this.layerDpSprite.width = window.innerWidth; this.layerAll.addChild(this.layerDpSprite); // bg this.bgDpSprite = new PIXI.Sprite(resources['../img/displacement-5.jpg'].texture); // scaleSpriteToCanvas(this.bgDpSprite, this.renderer.view); this.bgDpFilter = new PIXI.filters.DisplacementFilter(this.bgDpSprite); this.bgDpFilter.scale.x = this.bgDpFilter.scale.y = 60; this.bgContainer.addChild(this.bgDpSprite); // repeat pixi v4 this.displacementTexture = PIXI.Texture.fromImage('../img/displacement-5.jpg'); this.dTexture = PIXI.Texture.fromImage('../img/displacement.png'); this.displacementTexture.baseTexture.wrapMode = PIXI.WRAP_MODES.REPEAT; this.dTexture.baseTexture.wrapMode = PIXI.WRAP_MODES.REPEAT; } createAndAddSprites() { const PIXI = this.pixi; const resources = PIXI.loader.resources; // layerRight this.layerRightChildren = [ // M 0,1 new PIXI.Sprite(resources['../img/m-base.png'].texture), new PIXI.Sprite(resources['../img/m-fade.png'].texture), // A 2,3 new PIXI.Sprite(resources['../img/a-base.png'].texture), new PIXI.Sprite(resources['../img/a-fade.png'].texture), // I 4,5 new PIXI.Sprite(resources['../img/i-base.png'].texture), new PIXI.Sprite(resources['../img/i-fade.png'].texture), // O 6,7 new PIXI.Sprite(resources['../img/o-base.png'].texture), new PIXI.Sprite(resources['../img/o-fade.png'].texture), // H 8,9 new PIXI.Sprite(resources['../img/h-base.png'].texture), new PIXI.Sprite(resources['../img/h-fade.png'].texture), // C 10,11 new PIXI.Sprite(resources['../img/c-base.png'].texture), new PIXI.Sprite(resources['../img/c-fade.png'].texture), // KO 12, 13 new PIXI.Sprite(resources['../img/ko-base.png'].texture), new PIXI.Sprite(resources['../img/ko-fade.png'].texture), // BA 14, 15 new PIXI.Sprite(resources['../img/ba-base.png'].texture), new PIXI.Sprite(resources['../img/ba-fade.png'].texture), ]; this.layerRightChildren.map(child => this.layerRight.addChild(child) ); // layerLeft container this.layerLeftChildren = [ // MAI 0,1 new PIXI.Sprite(resources['../img/mai-base.png'].texture), new PIXI.Sprite(resources['../img/mai-fade.png'].texture), // A Small 2,3 new PIXI.Sprite(resources['../img/a-sm-base.png'].texture), new PIXI.Sprite(resources['../img/a-sm-fade.png'].texture), // K 4,5 new PIXI.Sprite(resources['../img/k-base.png'].texture), new PIXI.Sprite(resources['../img/k-fade.png'].texture), // B 6,7 new PIXI.Sprite(resources['../img/b-base.png'].texture), new PIXI.Sprite(resources['../img/b-fade.png'].texture), // I small 8,9 new PIXI.Sprite(resources['../img/i-sm-base.png'].texture), new PIXI.Sprite(resources['../img/i-sm-fade.png'].texture), // CH 10,11 new PIXI.Sprite(resources['../img/ch-base.png'].texture), new PIXI.Sprite(resources['../img/ch-fade.png'].texture), // II 12,13 new PIXI.Sprite(resources['../img/ii-base.png'].texture), new PIXI.Sprite(resources['../img/ii-fade.png'].texture), ]; this.layerLeftChildren.map(child => this.layerLeft.addChild(child)); } storeSpritePositions() { this.orgSpritePosRight = []; this.layerRightChildren.map((sprite) => { const spritePosObj = { x: sprite.x, y: sprite.y, }; return this.orgSpritePosRight.push(spritePosObj); }); this.orgSpritePosLeft = []; this.layerLeftChildren.map((sprite) => { const spritePosObj = { x: sprite.x, y: sprite.y, }; return this.orgSpritePosLeft.push(spritePosObj); }); } layersConfig() { // this.layerRight.filters = [this.layerDpFilter]; // this.layerLeft.filters = [this.layerDpFilter]; // this.layerRight.alpha = 0.9; // this.layerLeft.alpha = 0.9; this.layerAll.filters = [this.layerDpFilter] // scaleSpriteToCanvas(this.layerAll, this.renderer.view); } backgroundConfig() { const PIXI = this.pixi; const resources = PIXI.loader.resources; this.background = new PIXI.Sprite(resources['../img/darkness-10.jpg'].texture); scaleSpriteToCanvas(this.background, this.renderer.view); this.bgContainer.alpha = 0.35; this.bgContainer.addChild(this.background); this.bgContainer.filters = [this.bgDpFilter, this.layerDpFilter]; } addPathstoLoader() { const PIXI = this.pixi; // reset for HMR if (process.env.NODE_ENV === 'development') { PIXI.loader.reset(); } // add sprites spritePaths.map(path => PIXI.loader.add(path)); } addContainersToStage() { this.layerAll.addChild(this.layerRight); this.layerAll.addChild(this.layerLeft); [ this.bgContainer, this.layerAll, ].map(container => this.stage.addChild(container)); } moveSprites() { // M spriteOnMouseMove.apply(this, [ this.layerRightChildren, [0, 1], false, { x: 0.96, y: 0.81, mouseRatio: 0.0003 }, ]); // A spriteOnMouseMove.apply(this, [ this.layerRightChildren, [2, 3], false, { x: 0.82, y: 0.72, mouseRatio: 0.0007 }, ]); // I spriteOnMouseMove.apply(this, [ this.layerRightChildren, [4, 5], false, { x: 0.95, y: 0.8, mouseRatio: 0.0005 }, ]); // o spriteOnMouseMove.apply(this, [ this.layerRightChildren, [6, 7], false, { x: 0.98, y: 0.96, mouseRatio: 0.0002 }, ]); // H spriteOnMouseMove.apply(this, [ this.layerRightChildren, [8, 9], false, { x: 0.86, y: 0.81, mouseRatio: 0.00095 }, ]); // C spriteOnMouseMove.apply(this, [ this.layerRightChildren, [10, 11], false, { x: 0.91, y: 0.95, mouseRatio: 0.0005 }, ]); // KO spriteOnMouseMove.apply(this, [ this.layerRightChildren, [12, 13], false, { x: 0.98, y: 0.99, mouseRatio: 0.00025 }, ]); // BA spriteOnMouseMove.apply(this, [ this.layerRightChildren, [14, 15], false, { x: 0.98, y: 0.99, mouseRatio: 0.00025 }, ]); // MAI spriteOnMouseMove.apply(this, [ this.layerLeftChildren, [0, 1], true, { x: 1.01, y: 1.01, mouseRatio: 0.0002 }, ]); // A SMALL spriteOnMouseMove.apply(this, [ this.layerLeftChildren, [2, 3], true, { x: 1.035, y: 1.09, mouseRatio: 0.0008 }, ]); // K spriteOnMouseMove.apply(this, [ this.layerLeftChildren, [4, 5], true, { x: 1.01, y: 1.01, mouseRatio: 0.00018 }, ]); // B spriteOnMouseMove.apply(this, [ this.layerLeftChildren, [6, 7], true, { x: 1.01, y: 1.01, mouseRatio: 0.0002 }, ]); // I small spriteOnMouseMove.apply(this, [ this.layerLeftChildren, [8, 9], true, { x: 1.05, y: 1.04, mouseRatio: 0.0015 }, ]); // CH spriteOnMouseMove.apply(this, [ this.layerLeftChildren, [10, 11], true, { x: 1.04, y: 4, mouseRatio: 0.0003 }, ]); // II spriteOnMouseMove.apply(this, [ this.layerLeftChildren, [12, 13], true, { x: 1.04, y: 1.06, mouseRatio: 0.0002 }, ]); // this.layerRightChildren.map(child => { // if (this.layerRightChildren.indexOf(child) % 2 === 0) { // const index = this.layerRightChildren.indexOf(child) // spriteOnMouseMove.apply(this, [ // this.layerRightChildren, [index, index + 1] // ]); // } // }) } canvasSetup() { this.createFilters(); this.createAndAddSprites(); this.backgroundConfig(); this.layersConfig(); this.setSpritePositions(); this.storeSpritePositions(); // all mousemove events this.renderer.plugins.interaction.on('mousemove', (event) => { this.mouseX = event.data.global.x; this.mouseY = event.data.global.y; }); // scroll events window.addEventListener('scroll', () => { this.scrollPos = window.scrollY; }); // all resize events window.addEventListener('resize', () => { this.renderer.resize(window.innerWidth, window.innerHeight); scaleSpriteToCanvas(this.background, this.renderer.view); this.setSpritePositions(); this.storeSpritePositions(); }); } initPixiLoader() { const PIXI = this.pixi; const setup = this.canvasSetup; PIXI.loader .load(setup.bind(this)); } animate() { if (this.bgDpSprite && this.layerDpSprite) { this.bgDpFilter.scale.x = this.settings.dispX ? this.settings.transition * this.settings.dispScale : 0; this.bgDpFilter.scale.y = this.settings.dispY ? this.settings.transition * (this.settings.dispScale + 10) : 0; // this.bgDpFilter.scale.x += 0.4 // this.bgDpSprite.x = Math.sin(this.settings.count * 0.15) * 200; // this.bgDpSprite.y = Math.cos(this.settings.count * 0.13) * 200; this.bgDpSprite.x += 0.1; this.bgDpSprite.y += 0.4; this.layerDpSprite.x += 0.9; this.layerDpSprite.y += 1; // this.bgDpSprite.rotation = this.settings.count * 0.03; // this.layerRight.alpha = Math.round(Math.random(), Math.random()); // this.settings.alpha += 0.05 } if (this.settings.alpha >= 1) { setTimeout(() => { this.decrease = true; }, 1000); } else if (this.settings.alpha <= 0.76) { setTimeout(() => { this.decrease = false; }, 2000); } if (this.scrollPos) { if (this.scrollPos < 100) { this.layerAll.alpha = 1; } else { this.layerAll.alpha = (600 - this.scrollPos) / 600; } } if (this.decrease) { this.settings.alpha -= Math.random() * 0.003; } else { this.settings.alpha += Math.random() * 0.0025; } this.layerRight.alpha = this.settings.alpha; this.layerLeft.alpha = this.settings.alpha; if (this.mouseX) { this.moveSprites(); } this.settings.count += 0.05 * this.settings.speed; this.renderer.render(this.stage); requestAnimationFrame(this.animate.bind(this)); } render() { return ( <div className="hero-canvas" ref={(component) => { this.component = component; }} /> ); } } <file_sep>#React Universal >### !!! This is a living project and will often change !!! Single Page React App with Server Side Rendering, with a bunch of added features. ##Quick Start Yarn(recommended): `yarn && yarn start` NPM: `npm install && npm start` ##Features ***Hot Reloading*** Webpack build with HMR propagates changes to JS and CSS/Sass instantly without refreshing the page. ***Sass/Foundation*** Write styles with Sass, with [Foundation](http://foundation.zurb.com/sites/docs/) styles integrated by default, but easily excluded in the build. Post-CSS Autoprefixer included. ***Modern, modular JavaScript*** Use the power of next generation JavaScript. Write JS or JSX with ES6/2015, making modular architecture a breeze. ***Routing*** Easily manage routes with [React Router](https://github.com/ReactTraining/react-router). ***SEO*** Server side rendering makes helps search engines index each page. [React Helmet](https://github.com/nfl/react-helmet) allows for clear, simple meta tag management. ***Testing*** Test React components with [Enzyme](https://github.com/airbnb/enzyme), [Jasmine](https://jasmine.github.io/) and [Karma](https://karma-runner.github.io/1.0/index.html). ## Documentation * ###Tasks * `yarn start` Will run an Express dev server with webpack-dev-middleware and webpack-hot-middleware to enable hot reloading. The server is accessible via BrowserSync on `localhost:3000`, which proxies from port 9000. * `yarn run build` Copies the `src` directory to a `dist` directory with production settings. * `yarn run production` Same as `build` but also launches server on port 9000. * `yarn run deploy` This will build and push a production version of the app to a configured Heroku domain. * `yarn run test` Run all tests in the `test` directory. Via Chrome and PhantomJS.<file_sep>'use strict'; const webpack = require('webpack'); const path = require('path'); module.exports = function (env) { const preloaders = []; if(env === 'development') { preloaders.push({ test: /\.jsx?$/, loaders: ['eslint-loader'], include: path.join(__dirname, '../../src'), exclude: path.join(__dirname, '../../src', 'data') }) } return preloaders; } <file_sep>'use strict'; const webpack = require('webpack'); const path = require('path'); const CopyWebpackPlugin = require('copy-webpack-plugin'); const ExtractTextPlugin = require('extract-text-webpack-plugin'); // const StyleLintPlugin = require('stylelint-webpack-plugin'); module.exports = function (env) { const plugins = [ new webpack.NoErrorsPlugin(), new webpack.DefinePlugin({ 'process.env': { NODE_ENV: JSON.stringify(env), BROWSER: true } }), new webpack.optimize.OccurenceOrderPlugin() ]; if (env === 'development') { plugins.push( new webpack.HotModuleReplacementPlugin() // new StyleLintPlugin({ // configFile: '.stylelintrc', // files: ['**/*.sass'], // syntax: 'sugarss', // failOnError: false, // }) ); } else { plugins.push( new webpack.optimize.DedupePlugin(), new webpack.optimize.UglifyJsPlugin({ compress: { warnings: false }, mangle: true, sourcemap: false, beautify: false }), new CopyWebpackPlugin([ { from: path.join(__dirname, '../../src', 'static'), to: path.join(__dirname, '../../dist', 'static'), ignore: ['/compiled/bundle.js'] }, { from: path.join(__dirname, '../../src', 'index.ejs'), to: path.join(__dirname, '../../dist', 'index.ejs') } ]), new ExtractTextPlugin('bundle.css') ); } return plugins; } <file_sep>'use strict'; const path = require('path'); module.exports = function (env) { const output = { filename: 'bundle.js', publicPath: '/' }; // check env if(env === 'development') { output.path = path.join(__dirname, '../../src', 'static', 'compiled'); } else { output.publicPath = '/static/compiled', output.path = path.join(__dirname, '../../dist', 'static', 'compiled'); } return output; } <file_sep>import React from 'react'; import Footer from 'presentation/Footer/Footer'; const MainLayout = props => ( <div className="main-layout"> <div className="main-layout__content">{props.children}</div> <Footer /> </div> ); MainLayout.propTypes = { children: React.PropTypes.node.isRequired, }; export default MainLayout; <file_sep>import React from 'react'; import Helmet from 'react-helmet'; import MainLayout from 'layout/MainLayout/MainLayout'; const AboutPage = () => ( <MainLayout> <Helmet title="About" meta={[ { name: 'description', content: 'About page description' }, ]} /> <div className="about-page"> <div className="about-page__col"> <h2>Another Page</h2> <p>This page has differenct content.</p> </div> </div> </MainLayout> ); export default AboutPage; <file_sep>import React from 'react'; const PageWrapper = props => ( <div className="page-wrapper">{props.children}</div> ); PageWrapper.propTypes = { children: React.PropTypes.node.isRequired, }; export default PageWrapper; <file_sep>'use strict'; const webpack = require('webpack'); const path = require('path'); const ExtractTextPlugin = require('extract-text-webpack-plugin'); module.exports = function (env) { const loaders = [ { test: /\.jsx?$/, loaders: ['babel-loader'], exclude: path.join(__dirname, '../../node_modules') }, { test: /\.json$/, loader: 'json' }, { test: /\.modernizrrc.js$/, loader: "modernizr" }, { test: /\.modernizrrc(\.json)?$/, loader: "modernizr!json" } ]; // check env if(env === 'development') { loaders.push({ test: /\.(scss|sass)$/, loader: 'style!css?sourceMap!postcss-loader!sass?sourceMap', include: path.join(__dirname, '../../src') }); } else { loaders.push({ test: /\.(scss|sass)$/, loader: ExtractTextPlugin.extract('style', 'css!sass!postcss'), include: path.join(__dirname, '../../src') }); } return loaders; } <file_sep>import React from 'react'; const Footer = () => ( <div className="footer"> <div> <p className="footer__colophon">Built by <a href="//aboutevan.com" target="_blank" rel="noopener noreferrer" > Evan</a>. Contribute on <a href="//github.com/aboutevan/react-universal-boilerplate" target="_blank" rel="noopener noreferrer" > Github</a> </p> </div> </div> ); export default Footer; <file_sep>import React from 'react'; const Header = () => ( <div className="header"> <img className="header__logo" src="/img/react-logo.png" role="presentation" /> </div> ); export default Header; <file_sep>export const spritePaths = [ '../img/m-base.png', '../img/m-fade.png', '../img/a-base.png', '../img/a-fade.png', '../img/i-base.png', '../img/i-fade.png', '../img/k-base.png', '../img/k-fade.png', '../img/o-base.png', '../img/o-fade.png', '../img/h-base.png', '../img/h-fade.png', '../img/c-base.png', '../img/c-fade.png', '../img/i-sm-base.png', '../img/i-sm-fade.png', '../img/b-base.png', '../img/b-fade.png', '../img/a-sm-base.png', '../img/a-sm-fade.png', // japanese characters '../img/mai-base.png', '../img/mai-fade.png', '../img/ko-base.png', '../img/ko-fade.png', '../img/ch-base.png', '../img/ch-fade.png', '../img/ii-base.png', '../img/ii-fade.png', '../img/ba-base.png', '../img/ba-fade.png', // background // '../img/darkness-2.jpg', // '../img/darkness-3.jpg', // '../img/darkness-4.jpg', // '../img/darkness-5.jpg', // '../img/darkness-6.jpg', // '../img/darkness-7.jpg', // '../img/darkness-8.jpg', // '../img/darkness-9.png', '../img/darkness-10.jpg', // displacement '../img/displacement.png', // '../img/displacement-2.jpg', // '../img/displacement-3.png', // '../img/displacement-4.jpg', '../img/displacement-5.jpg', // '../img/displacement-7.png', ]; export function scaleSpriteToCanvas(spr, canvas) { const sprite = spr; const ratio = sprite.width / sprite.height; sprite.x = -(canvas.width * 0.10); if (canvas.width < canvas.height) { sprite.height = canvas.height * 1.20; sprite.width = ratio * sprite.height; } else { sprite.width = canvas.width * 1.20; sprite.height = sprite.width / ratio; if (sprite.height < canvas.height) { sprite.height = canvas.height * 1.20; sprite.width = ratio * sprite.height; } } } export function positionSprite(source, x = 0, y = 0, scale) { source.map((sprite, i) => { const spr = sprite; spr.x = x + i; spr.y = y + i; if (scale) { spr.scale.x = scale; spr.scale.y = scale; } return spr; }); } export function spriteOnMouseMove(parentContainer, arrIndex, reverse, obj) { const sprites = [parentContainer[arrIndex[0]], parentContainer[arrIndex[1]]]; const spritesWidth = sprites[0].width + sprites[1].width; // const spritesHeight = sprites[0].height + sprites[1].height; const options = { x: reverse ? 1.1 : 0.9, y: reverse ? 1.1 : 0.9, mouseRatio: spritesWidth * 0.0006, frameRatio: 0.05, }; if (obj) { if (typeof obj.x !== 'undefined') { options.x = obj.x; } if (typeof obj.y !== 'undefined') { options.y = obj.y; } if (typeof obj.mouseRatio !== 'undefined') { options.mouseRatio = spritesWidth * obj.mouseRatio; } if (typeof obj.frameRatio !== 'undefined') { options.frameRatio = obj.frameRatio; } } if (reverse) { sprites.map((spr, i) => { const sprite = spr; sprite.x += ( (this.orgSpritePosLeft[arrIndex[i]].x * options.x) + ((-(this.mouseX) * options.mouseRatio) - sprite.x) ) * options.frameRatio; sprite.y += ( (this.orgSpritePosLeft[arrIndex[i]].y * options.y) + ((-(this.mouseY) * options.mouseRatio) - sprite.y) ) * options.frameRatio; return sprite; }); } else { sprites.map((spr, i) => { const sprite = spr; sprite.x += ( (this.orgSpritePosRight[arrIndex[i]].x * options.x) + ((this.mouseX * options.mouseRatio) - sprite.x) ) * options.frameRatio; sprite.y += ( (this.orgSpritePosRight[arrIndex[i]].y * options.y) + ((this.mouseY * options.mouseRatio) - sprite.y) ) * options.frameRatio; return sprite; }); } } <file_sep>import React from 'react'; import Helmet from 'react-helmet'; import MainLayout from 'layout/MainLayout/MainLayout'; import HeroCanvas from 'presentation/HeroCanvas/HeroCanvas'; import PortImage from 'presentation/PortImage/PortImage'; import GalleryData from 'data/gallery'; const IndexPage = () => ( <MainLayout> <Helmet title="My title" meta={[ { name: 'description', content: 'Index Page description' }, ]} /> <div className="index-page"> <div className="index-page__hero"> <HeroCanvas /> </div> <div className="index-page__content"> {GalleryData.map((gallery, i) => ( <PortImage key={i} index={i + 1} url={gallery.url} title={gallery.title} /> ))} </div> </div> </MainLayout> ); export default IndexPage; <file_sep>import React from 'react'; import { renderToString } from 'react-dom/server'; import { match, RouterContext } from 'react-router'; import Helmet from 'react-helmet'; import routes from './components/routes'; import NotFoundPage from './components/page/NotFoundPage/NotFoundPage'; export default (req, res) => { match( { routes, location: req.url }, (err, redirectLocation, renderProps) => { // if error display message if (err) { return res.status(500).send(err.message); } // in case of redirect propagate the redirect to browser if (redirectLocation) { return res.redirect(302, redirectLocation.pathName + redirectLocation.search); } let markup; if (renderProps) { // if the current route matched then renderProps const returnedPage = renderProps.routes[1].component.name markup = renderToString(<RouterContext {...renderProps} />); // 404 if (returnedPage === 'NotFoundPage') { res.status(404); } } // reset Helmet meta to avoid memory leaks let head = Helmet.rewind(); head.htmlAttributes head.title head.base head.meta head.link head.script head.style // render the index template with the embedded react markup return res.render('index', { markup, head }) } ); }<file_sep>import React from 'react'; const PortImage = ({ index, url, title }) => ( <div className={`port-image port-image--${index}`}> <img src={`/img/${url}`} alt={title} /> </div> ); PortImage.propTypes = { url: React.PropTypes.string, title: React.PropTypes.string, index: React.PropTypes.number, }; export default PortImage; <file_sep>export default [ { url: 'gallery-1.jpg', title: 'scarface woman' }, { url: 'gallery-2.jpg', title: 'scarface 1' }, { url: 'gallery-3.jpg', title: 'scarface 2' }, { url: 'gallery-4.jpg', title: 'scarface 3' } ];<file_sep>import React from 'react'; import { Link } from 'react-router'; import Helmet from 'react-helmet'; import MainLayout from 'layout/MainLayout/MainLayout'; const NotFoundPage = () => ( <MainLayout> <Helmet title="Page Not Found" meta={[ { name: 'description', content: 'This page does not exist' }, ]} /> <div className="not-found-page"> <h1>404</h1> <h2>Page not found!</h2> <Link className="button" to="/">Go back to the main page</Link> </div> </MainLayout> ); export default NotFoundPage; <file_sep>import React from 'react'; import { shallow, mount } from 'enzyme'; import Counter from 'presentation/Counter/Counter'; describe('Counter', () => { it('renders', () => { const element = shallow(<Counter />); expect(element).toBeTruthy(); }); it('should have an inital counter state of 0', () => { const element = mount(<Counter />); expect(element.state('counter')).toEqual(0); }); it('should increment the counter on increment button click', () => { const element = mount(<Counter />); element.find('.Counter__increment').simulate('click'); expect(element.state('counter')).toBeGreaterThan(0); }); it('should decremnt the counter on decrement button click', () => { const element = mount(<Counter />); element.find('.Counter__decrement').simulate('click'); expect(element.state('counter')).toBeLessThan(0); }); });
0968ade0646b8b6f2351a9ea9f38149c05b0b8ce
[ "JavaScript", "Markdown" ]
24
JavaScript
aboutevan/maiko
d91acff5cfe85f6a2b8cc1c09172c52c554319c0
54c000ff786abcbd9c11f6435a9a43ba0143ee7a
refs/heads/main
<file_sep> function fn(target: any) { target.isok = true; // 相当于给传进来的类或类属性方法添加了isok属性 console.log(target); } @fn // 相当于fn(Zsq); 所以装饰器实际就是给类或者类属性方法添加内容(相当于现实给毛坯房装修) class Zsq { } // 装饰器在类new Zsq()实例前就已经执行了<file_sep>/** * 1.交叉类型(Intersection Types) * 交叉类型是将多个类型合并为一个类型。 这让我们可以把现有的多种类型叠加到一起成为一种类型,它包含了所需的所有类型的特性。 * 例如, Person & Serializable & Loggable同时是 Person 和 Serializable 和 Loggable。 就是说这个类型的对象同时拥有了这三种类型的成员。 */ function extend<T, U>(first: T, second: U): T & U { let result = <T & U>{}; return result; } /** * 2.联合类型(Union Types) * 联合类型表示一个值可以是几种类型之一。 用竖线( |)分隔每个类型 * number | string | boolean表示一个值可以是 number, string,或 boolean。 * 如果一个值是联合类型,我们只能访问此联合类型的所有类型里共有的成员。 */ interface Bird { fly(); layEggs(); } interface Fish { swim(); layEggs(); } function getSmallPet(): Fish | Bird { return <Fish | Bird>{} } let pet = getSmallPet(); pet.layEggs(); // okay // pet.swim(); // errors <file_sep>let a: {name: string, [propName: string]: any}; a = { name: 'test1', age: 23 }; let b: any, c: string; b = 2; c = b; let d: (a: string) => string; d = (a: string): string => { return a; } enum e{ a = 0, b = 1 } let f: {n1:e}; f = {n1: e.a}<file_sep>/** * T表示泛型,用作不知道类型的场合 * <T>相当于传参 * @param a * @returns */ function fn<T>(a: T): T{ return a; } fn(10); // ts类型推断number,T就是number fn<string>('hello'); // 指定泛型,T为string function fn2<T, K>(a: T, b: K): T{ console.log(b); return a; } fn2<number, string>(1, '1'); interface Integer{ length: number; } function fn3<T extends Integer>(a: T): number { return a.length; } fn3('123'); // 因为传的是字符串,string对象有length属性,所以不会报错 fn3({length: 123}); fn3<Integer>({length:457}); class Myclass<T>{ name: T; constructor(name: T) { this.name = name; } } const mc = new Myclass<string>('name');<file_sep>/** * 通常这会发生在你清楚地知道一个实体具有比它现有类型更确切的类型。 * TypeScript会假设你,程序员,已经进行了必须的检查。 */ // 类型断言有两种形式。 其一是“尖括号”语法: const strValue: any = 'hello world'; const strLength: number = (<string>strValue).length; // 另一个为as语法: const str2Value: any = '我是字符串2'; const str2Length: number = (str2Value as string).length;<file_sep>class Person { private _name: string; private _age: number; constructor(name: string, age: number) { this._name = name; this._age = age; } // 存取器 get name() : string { return this._name; } set name(v : string) { this._name = v; } } const man = new Person('name', 18); man.name = 'name1'; // 实际执行的是set name(v); console.log(man.name); // 实际执行的是get name(); <file_sep>// 1.布尔 const isShow: boolean = false; // 2.数值 const num: number = 1; // 3.字符串 const str: string = 'hello world'; // 4.数组 const arr1: number[] = [1, 2, 3]; const arr2: Array<number> = [1, 2, 3]; // 5.元组: 表示一个已知元素数量和类型的数组,各元素的类型不必相同。 const tup: [string, number, boolean, number[]] = ['hello world', 2, false, [1, 2, 3]]; // 6.枚举enum: 对JavaScript标准数据类型的一个补充,默认情况下,从0开始为元素编号。 也可以手动的指定成员的数值。 enum Color1 {Red, Blue, Green}; // 0 1 2 const color1: Color1 = Color1.Green; // 2 enum Color2 {Red=1, Blue, Green}; // 1 2 3 const color2: Color2 = Color2.Green; // 3 enum Color3 {Red=1, Blue=3, Green=5}; // 1 3 5 const color3: Color3 = Color3.Green; // 5 // 7.any: 类型检查器不对这些值进行检查,移除类型检查 let param: any = 1; param = 'hellow'; // 8.void: 某种程度上来说,void类型像是与any类型相反,它表示没有任何类型 // 当一个函数没有返回值时,你通常会见到其返回值类型是 void // 声明一个void类型的变量没有什么大用,因为你只能为它赋予undefined和null function fn(): void { console.log('log') } let vd: void = null; vd = undefined; // 9.null 10.undefined: TypeScript里,undefined和null两者各自有自己的类型分别叫做undefined和null。 和 void相似,它们的本身的类型用处不是很大 // 默认情况下null和undefined是所有类型的子类型。 就是说你可以把 null和undefined赋值给number类型的变量。 const u: undefined = undefined; const n: null = null; // 11.object: 表示非原始类型,也就是除number,string,boolean,symbol,null或undefined之外的类型。 const obj: object = {}; // 12.never: 表示的是那些永不存在的值的类型。 // 返回never的函数必须存在无法达到的终点 function error(message: string): never { throw new Error(message); } // 推断的返回值类型为never function fail() { return error("Something failed"); } // 返回never的函数必须存在无法达到的终点 function infiniteLoop(): never { while (true) { } }<file_sep>interface myInterface { name: string; age: number; } interface myInterface { gender: string; } const obj = { name: 'sss', age: 11, gender: 'man' }
02ab6300d81a794d39fb24b370ae61701d422c84
[ "TypeScript" ]
8
TypeScript
jiuguihuasheng/typescript-study
6bfb40544bb17a2f34a2de18115ca3e5fb2bac64
9fd76f1ac5474426f60fafd8f0a4d92ab2ebd78b
refs/heads/master
<repo_name>JoonHyeongPark/IMMethyl<file_sep>/PCDHG Gene Analysis/Step0.Merge.Methylation.Data.py cancerlist = ["ACC", "BLCA", "BRCA", "CESC", "CHOL", "COAD", "DLBC", "ESCA", "GBM", "HNSC", "KICH", "KIRC", "KIRP", "LGG", "LIHC", "LUAD", "LUSC", "MESO", "OV", "PAAD", "PCPG", "PRAD", "READ", "SARC", "SKCM", "STAD", "TGCT", "THCA", "THYM", "UCEC", "UCS", "UVM"] input_data_path = "/ngs/data3/public_data/TCGA_FireBrowse/Methylation" merge_data_path = "/home/kwangsookim_lab/joonhyeong_park/Practice" input_tumor = [] input_normal = [] output_merge_tumor = open(merge_data_path + "/PANCANCER.humanmethylation450.tumor.31tumors.txt", "w") output_merge_normal = open(merge_data_path + "/PANCANCER.humanmethylation450.normal.31tumors.txt", 'w') tumor_header = ["Site"] normal_header = ["Site"] for i in range(len(cancerlist)) : cancer_data_path = input_data_path + "/" + cancerlist[i] + ".humanmethylation450/" + cancerlist[i] + ".humanmethylation450." input_tumor.append(open(cancer_data_path + "tumor.txt", 'r')) input_normal.append(open(cancer_data_path + "normal.txt", 'r')) tumor_header += input_tumor[i].readline().replace('\n', '').split()[2:] input_tumor[i].readline() normal_header += input_normal[i].readline().replace('\n', '').split()[2:] input_normal[i].readline() output_merge_tumor.write("\t".join(tumor_header) + "\n") output_merge_normal.write("\t".join(normal_header) + "\n") iteration_number = 0 while(True) : empty_line_check = 0 for i in range(len(cancerlist)) : tumor_line = input_tumor[i].readline().split() normal_line = input_normal[i].readline().split() if(len(normal_line) == 0) : break empty_line_check += len(normal_line) - 1 if(i != 0) : del tumor_line[0] del normal_line[0] output_merge_tumor.write("\t".join(tumor_line)) output_merge_normal.write("\t".join(normal_line)) if(i != len(cancerlist) - 1) : output_merge_tumor.write("\t") output_merge_normal.write("\t") if(empty_line_check == 0) : break output_merge_tumor.write("\n") output_merge_normal.write("\n") if(iteration_number % 10000 == 0) : print(iteration_number) iteration_number += 1 <file_sep>/PCDHG Gene Analysis/Step1.Find.PCDHG.mRNA.Data.py import numpy cancerlist = ["ACC", "BLCA", "BRCA", "CESC", "CHOL", "COAD", "DLBC", "ESCA", "GBM", "HNSC", "KICH", "KIRC", "KIRP", "LGG", "LIHC", "LUAD", "LUSC", "MESO", "OV", "PAAD", "PCPG", "PRAD", "READ", "SARC", "STES", "STAD", "TGCT", "THCA", "THYM", "UCEC", "UCS", "UVM", "LAML"] input_data_path = "/ngs/data3/public_data/TCGA_FireBrowse/mRNASeq" merge_data_path = "/home/kwangsookim_lab/joonhyeong_park/Practice" input_target = open(merge_data_path + "/Targeted.Genes.txt", 'r') target = input_target.read().splitlines() input_mRNA = [] output_merge_mRNA = open(merge_data_path + "/PANCANCER.PCDHG.Gene.mRNAseq_RSEM_normalized.log2.32tumors.txt", "w") mRNA_header = ["Gene"] sample_id = [] flat_id = [] for i in range(len(cancerlist)) : mRNA_path = input_data_path + "/" + cancerlist[i] + "/gdac.broadinstitute.org_" + cancerlist[i] + ".mRNAseq_Preprocess.Level_3.2016012800.0.0/" + cancerlist[i] + ".uncv2.mRNAseq_RSEM_normalized_log2.txt" input_mRNA.append(open(mRNA_path, 'r')) sample_id.append(input_mRNA[i].readline().replace('\n', '').split()[1:]) flat_id += sample_id[i] target_dic = {} for each_id in flat_id : target_dic[each_id] = numpy.zeros((len(target)), dtype = float) output_merge_mRNA.write("Gene\t" + "\t".join(flat_id) + "\n") while(True) : empty_line_check = 0 for i in range(len(cancerlist)) : line = input_mRNA[i].readline().split() length = len(line) empty_line_check += length if(length == 0) : continue line[0] = line[0][:line[0].index("|")] if(line[0] in target) : target_index = target.index(line[0]) del line[0] for j in range(len(line)) : if(line[j] == "NA") : target_dic[sample_id[i][j]][target_index] = -1 else : target_dic[sample_id[i][j]][target_index] = line[j] if(empty_line_check == 0) : break A_TOTAL = {} B_TOTAL = {} for each_id in flat_id : A_TOTAL[each_id] = 0.0 B_TOTAL[each_id] = 0.0 for i in range(len(target)) : output_merge_mRNA.write(target[i]) for each_id in flat_id : if(target_dic[each_id][i] <= 0) : output_merge_mRNA.write("\tNA") continue output_merge_mRNA.write("\t" + str(target_dic[each_id][i])) if("PCDHGA" in target[i]) : A_TOTAL[each_id] += target_dic[each_id][i] else : B_TOTAL[each_id] += target_dic[each_id][i] output_merge_mRNA.write("\n") output_merge_mRNA.write("PCDHGA_TOTAL") for each_id in flat_id : output_merge_mRNA.write("\t%f" % A_TOTAL[each_id]) output_merge_mRNA.write("\nPCDHGA_MEAN") for each_id in flat_id : output_merge_mRNA.write("\t%f" % (A_TOTAL[each_id] / 12)) output_merge_mRNA.write("\nPCDHGB_TOTAL") for each_id in flat_id : output_merge_mRNA.write("\t%F" % B_TOTAL[each_id]) output_merge_mRNA.write("\nPCDHGB_MEAN") for each_id in flat_id : output_merge_mRNA.write("\t%f" % (B_TOTAL[each_id] / 8)) output_merge_mRNA.write("\nPCDHG_SCORE") for each_id in flat_id : output_merge_mRNA.write("\t%f" % ((A_TOTAL[each_id] + B_TOTAL[each_id]) / 20)) <file_sep>/CpG site Correlation/Excluded Version/Excluded_Create_PANCANCER_file.py # -*- coding: utf-8 -*- cancerlist = ["ACC", "BLCA", "BRCA", "CESC", "CHOL", "COAD", "ESCA", "ESCASTAD", "GBM", "HNSC", "KICH", "KIRC", "KIRP", "LIHC", "LUAD", "LUSC", "MESO", "PAAD", "PCPG", "PRAD", "READ", "SARC", "SKCM", "STAD", "TGCT", "THCA", "UCEC", "UCS", "UVM"] ########################################### 주의사항 : 완성된 파일에서 반드시 마지막 탭을 제거할 것 ################################################## probe_count = 485577 sample_count = 0 ###################################################################################################################################################### input_file1 = [] #input_file2 = [] output_tumor = open("PANCANCER.humanmethylation450.tumor.excluded.txt", 'w') #output_normal = open("PANCANCER.humanmethylation450.normal.excluded.txt", 'w') tumor_header = "Hybridization\tREF\t";#normal_header = "Hybridization\tREF\t" for i in range(0, len(cancerlist)) : input_file1.append(open(cancerlist[i] + ".humanmethylation450.tumor.txt", 'r')) # input_file2.append(open(cancerlist[i] + ".humanmethylation450.normal.txt", 'r')) sample_name1 = input_file1[i].readline().split() # sample_name2 = input_file2[i].readline().split() del sample_name1[0]; del sample_name1[0] # del sample_name2[0]; del sample_name2[0] for j in range(0, len(sample_name1)) : tumor_header += "%s\t" % sample_name1[j] # for j in range(0, len(sample_name2)) : normal_header += "%s\t" % sample_name2[j] input_file1[i].readline();# input_file2[i].readline() # 쓰레기 line 제거 output_tumor.write(tumor_header);# output_normal.write(normal_header) output_tumor.write("\n############################################################################################################\n") #output_normal.write("\n############################################################################################################\n") for site_number in range(0, probe_count) : value_print1 = "";# value_print2 = "" probe_name = "None" for i in range(0, len(cancerlist)) : tumor = input_file1[i].readline().split() # normal = input_file2[i].readline().split() probe_name = tumor.pop(0);# probe_name = normal.pop(0) for j in range(0, len(tumor)) : value_print1 += "%s\t" % tumor[j] # for j in range(0, len(normal)) : value_print2 += "%s\t" % normal[j] output_tumor.write("%s\t%s\n" % (probe_name, value_print1));# output_normal.write("%s\t%s\n" % (probe_name, value_print2)) if((site_number + 1) % 10000 == 0) : print(site_number + 1, " completed.\n") for i in range(0, len(cancerlist)) : input_file1[i].close() # input_file2[i].close() output_tumor.close() #output_normal.close() print("END") <file_sep>/PCDHG Gene Analysis/Step2.Compare.Summarized.Information.Of.PCDHG.CpGsite.Tumor.VS.Normal.py import numpy target = "PCDHG" file_path = "/home/kwangsookim_lab/joonhyeong_park/Practice/" cancerlist = ["PANCANCER"] for i in range(len(cancerlist)) : input_tumor = open(file_path + cancerlist[i] + "." + target + ".Methylation.Pattern.tumor.txt", 'r') input_normal = open(file_path + cancerlist[i] + "." + target + ".Methylation.Pattern.normal.txt", 'r') header1 = input_tumor.readline().split() header2 = input_normal.readline().split() output = open(file_path + cancerlist[i] + "." + target + ".Compare.Methylation.Information.txt", 'w') output.write("Site\tRelatedGenes\tTumorMean\tNormalMean\tMeanGap\tTumorMedian\tNormalMedian\tMedianGap\tTumorMax\tNormalMax\tTumorMin\tNormalMin\n") while(True) : line1 = input_tumor.readline().split() line2 = input_normal.readline().split() if(len(line2) == 0) : break raw_tumor_betavalue = line1[2:] raw_normal_betavalue = line2[2:] valid_tumor_betavalue = [] valid_normal_betavalue = [] for value in raw_tumor_betavalue : if(value == "NA") : continue valid_tumor_betavalue.append(float(value)) for value in raw_normal_betavalue : if(value == "NA") : continue valid_normal_betavalue.append(float(value)) output.write("\t".join(line1[:2]) + "\t") value = [] if(len(valid_normal_betavalue) == 0 or len(valid_tumor_betavalue) == 0) : output.write("NotEnoughValidValues\n") continue value.append(str(numpy.mean(valid_tumor_betavalue))) value.append(str(numpy.mean(valid_normal_betavalue))) value.append(str(abs(float(value[0]) - float(value[1])))) value.append(str(numpy.median(valid_tumor_betavalue))) value.append(str(numpy.median(valid_normal_betavalue))) value.append(str(abs(float(value[3]) - float(value[4])))) value.append(str(max(valid_tumor_betavalue))) value.append(str(max(valid_normal_betavalue))) value.append(str(min(valid_tumor_betavalue))) value.append(str(min(valid_normal_betavalue))) output.write("\t".join(value) + "\n") <file_sep>/CpG site Correlation/Results_Integration/Integration_Column_Without_PanCancer.py # -*- coding: utf-8 -*- cancerlist = ["PANCANCER", "ACC", "BLCA", "BRCA", "CESC", "CHOL", "COAD", "DLBC", "ESCA", "ESCASTAD", "GBM", "HNSC", "KICH", "KIRC", "KIRP", "LGG", "LIHC", "LUAD", "LUSC", "MESO", "OV", "PAAD", "PCPG", "PRAD", "READ", "SARC", "SKCM", "STAD", "TGCT", "THCA", "THYM", "UCEC", "UCS", "UVM"] #cancerlist = ["ACC", "BLCA", "BRCA", "CESC", "CHOL", "COAD", "DLBC", "ESCA", "ESCASTAD", "GBM", "HNSC", "KICH", "KIRC", "KIRP", "LGG", "LIHC", "LUAD", "LUSC", "MESO", "OV", "PAAD", "PCPG", "PRAD", "READ", "SARC", "SKCM", "STAD", "TGCT", "THCA", "THYM", "UCEC", "UCS", "UVM"] ########################################### 주의사항 : 완성된 파일에서 반드시 마지막 탭을 제거할 것 ################################################## probe_count = 485577 ###################################################################################################################################################### input_file1 = [] input_file2 = [] output_tumor1 = open("Tumor_Cor_CpGsite_CytAct_pearson.txt", 'w') output_tumor2 = open("Tumor_Cor_CpGsite_CytAct_spearman.txt", 'w') #tumor_header = "PANCANCER\tACC\tBLCA\tBRCA\tCESC\tCHOL\tCOAD\tDLBC\tESCA\tESCASTAD\tGBM\tHNSC\tKICH\tKIRC\tKIRP\tLGG\tLIHC\tLUAD\tLUSC\tMESO\tOV\tPAAD\tPCPG\tPRAD\tREAD\tSARC\tSKCM\tSTAD\tTGCT\tTHCA\tTHYM\tUCEC\tUCS\tUVM\n" tumor_header = "\tPANCANCER_cor\tPANCANCER_P-value\tACC_cor\tACC_P-value\tBLCA_cor\tBLCA_P-value\tBRCA_cor\tBRCA_P-value\tCESC_cor\tCESC_P-value\tCHOL_cor\tCHOL_P-value\tCOAD_cor\tCOAD_P-value\tDLBC_cor\tDLBC_P-value\tESCA_cor\tESCA_P-value\tESCASTAD_cor\tESCASTAD_P-value\tGBM_cor\tGBM_P-value\tHNSC_cor\tHNSC_P-value\tKICH_cor\tKICH_P-value\tKIRC_cor\tKIRC_P-value\tKIRP_cor\tKIRP_P-value\tLGG_cor\tLGG_P-value\tLIHC_cor\tLIHC_P-value\tLUAD_cor\tLUAD_P-value\tLUSC_cor\tLUSC_P-value\tMESO_cor\tMESO_P-value\tOV_cor\tOV_P-value\tPAAD_cor\tPAAD_P-value\tPCPG_cor\tPCPG_P-value\tPRAD_cor\tPRAD_P-value\tREAD_cor\tREAD_P-value\tSARC_cor\tSARC_P-value\tSKCM_cor\tSKCM_P-value\tSTAD_cor\tSTAD_P-value\tTGCT_cor\tTGCT_P-value\tTHCA_cor\tTHCA_P-value\tTHYM_cor\tTHYM_P-value\tUCEC_cor\tUCEC_P-value\tUCS_cor\tUCS_P-value\tUVM_cor\tUVM_P-value\n" for i in range(0, len(cancerlist)) : input_file1.append(open(cancerlist[i] + ".Tumor_Cor_CpGsite&CytAct_pearson.txt", 'r')) input_file2.append(open(cancerlist[i] + ".Tumor_Cor_CpGSite&CytAct_spearman.txt", 'r')) input_file1[i].readline() input_file2[i].readline() output_tumor1.write(tumor_header); output_tumor2.write(tumor_header) for site_number in range(0, probe_count) : value_print1 = ""; value_print2 = "" probe_name = "None" for i in range(0, len(cancerlist)) : tumor1 = input_file1[i].readline().split() tumor2 = input_file2[i].readline().split() probe_name = tumor1.pop(0) del tumor2[0] for j in range(0, len(tumor1)) : value_print1 += "%s\t" % tumor1[j] value_print2 += "%s\t" % tumor2[j] output_tumor1.write("%s\t%s\n" % (probe_name, value_print1)) output_tumor2.write("%s\t%s\n" % (probe_name, value_print2)) if((site_number + 1) % 10000 == 0) : print(site_number + 1, " completed.\n") for i in range(0, len(cancerlist)) : input_file1[i].close() input_file2[i].close() output_tumor1.close() output_tumor2.close() print("END") <file_sep>/CpG site Correlation/Results_Integration/Integration_Row_SEP8.py # -*- coding: utf-8 -*- target_cancer = "PANCANCER" input_file1 = [] input_file2 = [] output_tumor1 = open(target_cancer + ".SEP_8.Tumor_Cor_CpGsite&CytAct_pearson.txt", 'w') output_tumor2 = open(target_cancer + ".SEP_8..Tumor_Cor_CpGSite&CytAct_spearman.txt", 'w') for i in range(0, 10) : name = str(i) input_file1.append(open(target_cancer + ".SEP_8." + name + ".Tumor_Cor_CpGsite&CytAct_pearson.txt", 'r')) input_file2.append(open(target_cancer + ".SEP_8." + name + "..Tumor_Cor_CpGSite&CytAct_spearman.txt", 'r')) if(i == 0) : output_tumor1.write(input_file1[i].readline()) output_tumor2.write(input_file2[i].readline()) else : input_file1[i].readline() input_file2[i].readline() printarray1 = input_file1[i].readlines() printarray2 = input_file2[i].readlines() for line1 in printarray1 : output_tumor1.write(line1) for line2 in printarray2 : output_tumor2.write(line2) last1 = open(target_cancer + ".SEP_8._.Tumor_Cor_CpGsite&CytAct_pearson.txt", 'r') last2 = open(target_cancer + ".SEP_8._..Tumor_Cor_CpGSite&CytAct_spearman.txt", 'r') last1.readline(); last2.readline() lastprint1 = last1.readlines(); lastprint2 = last2.readlines() for line1 in lastprint1 : output_tumor1.write(line1) for line2 in lastprint2 : output_tumor2.write(line2) output_tumor1.close() output_tumor2.close() print("END") <file_sep>/Betavalue Count By Threshold/Betavalue_0.2_gap_count_tumor_each_cancer.py cancerlist = ["ACC", "BLCA", "BRCA", "CESC", "CHOL", "COAD", "DLBC", "ESCA", "GBM", "HNSC", "KICH", "KIRC", "KIRP", "LGG", "LIHC", "LUAD", "LUSC", "MESO", "OV", "PAAD", "PCPG", "PRAD", "READ", "SARC", "SKCM", "STAD", "TGCT", "THCA", "THYM", "UCEC", "UCS", "UVM"] input_file1 = [] output_file1 = [] gap = 0.2 probe_count = 485577 threshold_array = [] accumulation_array1 = [] header = "Threshold" def MakeThresholdArray(gap) : global threshold_array global header cutoff = 0.0 count = 0 while(cutoff <= 1.0) : threshold_array.append(cutoff) accumulation_array1.append(0) count += 1 cutoff = gap * float(count) print(threshold_array) for i in range(0, len(threshold_array) - 1) : header += "\t%s~%s" % (str(threshold_array[i]), str(threshold_array[i + 1])) return MakeThresholdArray(gap) header += "\n" def ReturnRange(value) : for i in range(0, len(threshold_array) - 1) : if(value >= threshold_array[i] and value <= threshold_array[i + 1]) : return i for i in range(0, len(cancerlist)) : input_file1.append(open(cancerlist[i] + ".humanmethylation450.tumor.txt", 'r')) output_file1.append(open(cancerlist[i] + "." + str(gap) + ".Betavalue_WholeTumorCount.txt", 'w')) input_file1[i].readline() input_file1[i].readline() output_file1[i].write(header) cancer_count = [] for i in range(0, probe_count) : cancer_count.append([]) for j in range(0, len(cancerlist)) : cancer_count[i].append([]) for k in range(0, len(threshold_array)) : cancer_count[i][j].append(0) line1 = input_file1[j].readline().split() while(len(line1) == 0) : line1 = input_file1[j].readline().split() print(cancerlist[j] + " tumor %d " % i + "has no line value.") sample_id = line1.pop(0) for cancer_value in line1 : if(cancer_value == "NA") : continue cancer_count[i][j][ReturnRange(float(cancer_value))] += 1 printline1 = sample_id for k in range(0, len(threshold_array) - 1) : printline1 += "\t%s" % str(cancer_count[i][j][k]) printline1 += "\n" output_file1[j].write(printline1) if(i % 10000 == 0) : print("%s completed." % str(i)) <file_sep>/CpG site Correlation/Procedure/Real_Final_Code.py # -*- coding: utf-8 -*- #cancerlist = ["ACC", "BLCA", "BRCA", "CESC", "CHOL", "COAD", "DLBC", "ESCA", "ESCASTAD", "GBM", "HNSC", "KICH", "KIRC", "KIRP", "LGG", "LIHC", "LUAD", "LUSC", "MESO", "OV", "PAAD", "PCPG", "PRAD", "READ", "SARC", "SKCM", "STAD", "TGCT", "THCA", "THYM", "UCEC", "UCS", "UVM"] cancerlist = ["STAD"] from operator import itemgetter #from scipy import stats betavalue_arr = [] cytoact_arr = [] probe_name = [] sample_id = [] probe_count = 485577 sample_count = 0 probe_separation_number = 10 probe_iteration = 0 tumor_pearson_output = open("Ready.txt", 'w'); tumor_spearman_output = open("Ready.txt", 'w') minus_pearson_output = open("Ready.txt", 'w'); minus_spearman_output = open("Ready.txt", 'w') FC_pearson_output = open("Ready.txt", 'w'); FC_spearman_output = open("Ready.txt", 'w') ###################################################################################################################################################### def getting_cytoact() : cytoact_file = open("TCGA_methylation_cowork_1.txt", 'r') header = cytoact_file.readline().split() # header 읽기 id_posit = header.index("id") # sample ID positioning cytoact_posit = header.index("CytAct") # CytAct positioning cytodata = cytoact_file.readlines() # 데이터 테이블 통째로 읽어들임 cytoact_file.close() for line in cytodata : line = line.split() sample_id.append(line[id_posit].replace('_', '')) # sample ID 추출 (주형으로 사용할 것) sample_count = len(sample_id) for i in range(0, sample_count) : cytoact_arr.append(None) # CytAct value table 초기화 for line in cytodata : line = line.split() # 1 sample data를 분절해서 CytAct value 추출하기 위함 if(line[cytoact_posit] != "NA") : # CytAct value가 결측치가 아니라면 sample_posit = sample_id.index(line[id_posit].replace('_', '')) cytoact_arr[sample_posit] = float(line[cytoact_posit]) # 저장한다 return; ###################################################################################################################################################### getting_cytoact() print("CytAct_Completed") ###################################################################################################################################################### def reset_betavalue() : for reset_x in range(0, probe_separation_number) : betavalue_arr.append([]) for reset_y in range(0, len(sample_id)) : betavalue_arr[reset_x].append([None, None]) return ###################################################################################################################################################### import math def mean(x): sum = 0.0 for i in x: sum += i return sum / len(x) def sampleStandardDeviation(x): sumv = 0.0 for i in x: sumv += (i - mean(x))**2 return math.sqrt(sumv/(len(x)-1)) def pearson(x, y): scorex = [] scorey = [] for i in x: scorex.append((i - mean(x))/sampleStandardDeviation(x)) for j in y: scorey.append((j - mean(y))/sampleStandardDeviation(y)) return (sum([i*j for i,j in zip(scorex,scorey)]))/(len(x)-1) ###################################################################################################################################################### def getting_betavalue(name) : tumor_pearson_output = open(name + ".Tumor_Cor_CpGsite&CytAct_pearson.txt", 'w'); tumor_spearman_output = open(name + ".Tumor_Cor_CpGSite&CytAct_spearman.txt", 'w') minus_pearson_output = open(name + ".minus_Cor_CpGsite&CytAct_pearson.txt", 'w'); minus_spearman_output = open(name + ".minus_Cor_CpGSite&CytAct_spearman.txt", 'w') FC_pearson_output = open(name + ".FC_Cor_CpGsite&CytAct_pearson.txt", 'w'); FC_spearman_output = open(name + ".FC_Cor_CpGSite&CytAct_spearman.txt", 'w') tumor_pearson_output.write("CpGsite\t%s\n" % name); tumor_spearman_output.write("CpGsite\t%s\n" % name) minus_pearson_output.write("CpGsite\t%s\n" % name); minus_spearman_output.write("CpGsite\t%s\n" % name) FC_pearson_output.write("CpGsite\t%s\n" % name); FC_spearman_output.write("CpGsite\t%s\n" % name) filename1 = name + ".humanmethylation450.tumor.txt" # cancer name별로 파일명이 다름을 고려해줌 filename2 = name + ".humanmethylation450.normal.txt" # cancer name별로 파일명이 다름을 고려해줌 input_file1 = open(filename1, 'r') input_file2 = open(filename2, 'r') sample_name1= input_file1.readline().split() # header에 sample ID가 있으므로 별도로 읽어준 후 sample_name2 = input_file2.readline().split() del sample_name1[0]; del sample_name1[0] del sample_name2[0]; del sample_name2[0] # 쓰레기 데이터를 제외 input_file1.readline() # betavalue임을 명시하는 row를 읽고 폐기 input_file2.readline() probe_separation_number_copy = probe_separation_number i = 0 while i < probe_count : ################################################################################################################################################## del probe_name[:] escape = False for normal_iteration in range(0, probe_separation_number_copy) : line1 = input_file1.readline().split() # 한 probe에 대한 여러 sample ID의 betavalue를 읽어들임 line2 = input_file2.readline().split() if(len(line1) == 0) : escape = True; probe_separation_number_copy = normal_iteration break probe_name.append(line1[0]) # CpG site name 추출한 뒤, betavalue가 아니므로 리스트에서 제거 del line1[0]; del line2[0] for j in range(0, len(line1)) : # sample ID의 개수만큼 반복함 sample_name1[j] = sample_name1[j][:15].replace('-', '') # sample ID의 형식을 통일해줌 if(line1[j] != "NA" and sample_name1[j] in sample_id) : # 결측치가 아니고, sample id에 포함된 경우 betavalue_arr[normal_iteration][sample_id.index(sample_name1[j])][0] = float(line1[j]) # sample ID에 맞는 index에 betavalue 저장 for j in range(0, len(line2)) : # sample ID의 개수만큼 반복함 sample_name2[j] = sample_name2[j][:15].replace('-', '') # sample ID의 형식을 통일해줌 if(line2[j] != "NA" and sample_name2[j] in sample_id) : # 결측치가 아니고, sample id에 포함된 경우 betavalue_arr[normal_iteration][sample_id.index(sample_name2[j])][1] = float(line2[j]) # sample ID에 맞는 index에 betavalue 저장 ################################################################################################################################################## for j in range(0, probe_separation_number_copy) : # 紐⑤뱺 probe瑜?寃 ?? printline1 = "%s\t" % probe_name[j]; printline2 = "%s\t" % probe_name[j]; printline3 = "%s\t" % probe_name[j]; printline4 = "%s\t" % probe_name[j]; printline5 = "%s\t" % probe_name[j]; printline6 = "%s\t" % probe_name[j] tumor = [None, None]; correction_FC = [None, None]; correction_minus = [None, None] tumor[0] = list(); correction_FC[0] = list(); correction_minus[0] = list(); tumor[1] = list(); correction_FC[1] = list(); correction_minus[1] = list() check_tumor = False; check_minus = False; check_FC = False for k in range(0, len(sample_id)) : if(betavalue_arr[j][k][0] != None and cytoact_arr[k] != None) : #pancancer_beta[j] = betavalue_arr[j] tumor[0].append(betavalue_arr[j][k][0]); tumor[1].append(cytoact_arr[k]) check_tumor = True if(betavalue_arr[j][k][1] != None) : if(abs(betavalue_arr[j][k][0] - betavalue[j][k][1]) > 0.3) : # tumor - normal betavalue > cutoff correction_minus[0].append(betavalue_arr[j][k][0]); correction_minus[1].append(cytoact_arr[k]) check_minus = True if(betavalue_arr[j][k][0] > betavalue[j][k][1]) : correction_FC[0].append(betavalue_arr[j][k][0]); correction_FC[1].append(cytoact_arr[k]) check_FC = True if(check_tumor) : tumor_pearson_pair = pearson(tumor[0], tumor[1]); printline1 += "%f\t" % tumor_pearson_pair # tumor_pearson_pair = stats.pearsonr(tumor[0], tumor[1]); printline1 += "%f\t" % tumor_pearson_pair[0] # tumor_spearman_pair = stats.spearmanr(tumor[0], tumor[1]); printline2 += "%f\t" % tumor_spearman_pair[0] else : printline1 += "NA\t"; printline2 += "NA\t" if(check_minus) : correction_minus_pearson_pair = pearson(correction_minus[0], correction_minus[1]); printline3 += "%f\t" % correction_minus_pearson_pair # correction_minus_pearson_pair = stats.pearsonr(correction_minus[0], correction_minus[1]); printline3 += "%f\t" % correction_minus_pearson_pair[0] # correction_minus_spearman_pair = stats.spearmanr(correction_minus[0], correction_minus[1]); printline4 += "%f\t" % correction_minus_spearman_pair[0] else : printline3 += "NA\t"; printline4 += "NA\t" if(check_FC) : correction_FC_pearson_pair = pearson(correction_FC[0], correction_FC[1]); printline5 += "%f\t" % correction_FC_pearson_pair # correction_FC_pearson_pair = stats.pearsonr(correction_FC[0], correction_FC[1]); printline5 += "%f\t" % correction_FC_pearson_pair[0] # correction_FC_spearman_pair = stats.spearmanr(correction_FC[0], correction_FC[1]); printline6 += "%f\t" % correction_FC_spearman_pair[0] else : printline5 += "NA\t"; printline6 += "NA\t" printline1 += "\n"; printline2 += "\n"; printline3 += "\n"; printline4 += "\n"; printline5 += "\n"; printline6 += "\n" tumor_pearson_output.write(printline1); #tumor_spearman_output.write(printline2) minus_pearson_output.write(printline3); #minus_spearman_output.write(printline4) FC_pearson_output.write(printline5); #FC_spearman_output.write(printline6) if(escape) : break ################################################################################################################################################## i += probe_separation_number print(i, probe_separation_number) input_file1.close(); input_file2.close() tumor_pearson_output.close(); tumor_spearman_output.close() minus_pearson_output.close(); minus_spearman_output.close() FC_pearson_output.close(); FC_spearman_output.close() return def process(cancer_name) : reset_betavalue() getting_betavalue(cancer_name) return for cancer_name in cancerlist : process(cancer_name); print(cancer_name + " completed") print("END") <file_sep>/Correlation Between CytAct and Summation - SimpleCutoff/ManWhitneyTest/WhitneyURankSumTest_EachCancer.py from scipy.stats import mannwhitneyu cancerlist = ["ACC", "BLCA", "BRCA", "CESC", "CHOL", "COAD", "DLBC", "ESCA", "GBM", "HNSC", "KICH", "KIRC", "KIRP", "LGG", "LIHC", "LUAD", "LUSC", "MESO", "OV", "PAAD", "PCPG", "PRAD", "READ", "SARC", "SKCM", "STAD", "TGCT", "THCA", "THYM", "UCEC", "UCS", "UVM"] input_file1 = [] input_file2 = [] output_file = [] probe_count = 485577 header = "site\tStatistics\tP-value\n" for i in range(0, len(cancerlist)) : input_file1.append(open(cancerlist[i] + ".humanmethylation450.tumor.txt", 'r')) input_file1[i].readline() input_file1[i].readline() input_file2.append(open(cancerlist[i] + ".humanmethylation450.normal.txt", 'r')) normalsample = input_file2[i].readline().split() input_file2[i].readline() output_file.append(open(cancerlist[i] + "CpGsitesByManWhitneyTest.txt", 'w')) output_file[i].write(header) if(len(normalsample) < 31) : print(cancerlist[i] + " has only %d normal sample." % (len(normalsample) - 2)) continue for j in range(0, probe_count) : line1 = input_file1[i].readline().split() line2 = input_file2[i].readline().split() tumor_value = [] normal_value = [] site_id1 = line1.pop(0) for value in line1 : if(value != "NA") : tumor_value.append(float(value)) site_id2 = line2.pop(0) for value in line2 : if(value != "NA") : normal_value.append(float(value)) manwhitney_pair = mannwhitneyu(tumor_value, normal_value) printline = site_id1 + "\t%f\t%f\n" % (manwhitney_pair[0], manwhitney_pair[1]) output_file[i].write(printline) print(cancerlist[i] + " completed.") input_file1[i].close() input_file2[i].close() output_file[i].close() <file_sep>/GeneMethyl Package/GeneMethyl/__init__.py __all__ = ['SimpleCutoff', 'TopPercentageCutoff', 'BetavalueDistribution'] <file_sep>/PCDHG Gene Analysis/Step2.Find.PCDHG.CpGsite.Betavalue.Selected.py target = "PCDHG" file_path = "/home/kwangsookim_lab/joonhyeong_park/Practice/" input_target_site = open(file_path + target + ".Selected.CpGsites.txt", 'r') data = input_target_site.read().splitlines() gene_index = data[0].split().index("UCSC_RefGene_Name") target_site = list(map(lambda x : data[x].split()[0], range(1, len(data)))) target_gene = list(map(lambda x : data[x].split()[gene_index], range(1, len(data)))) cancerlist = ["PANCANCER"] index = 0 for i in range(len(cancerlist)) : input_tumor = open(file_path + cancerlist[i] + ".humanmethylation450.tumor.31tumors.txt", 'r') input_normal = open(file_path + cancerlist[i] + ".humanmethylation450.normal.31tumors.txt", 'r') output_tumor = open(file_path + cancerlist[i] + "." + target + ".Methylation.Pattern.tumor.Selected.txt", 'w') output_normal = open(file_path + cancerlist[i] + "." + target + ".Methylation.Pattern.normal.Selected.txt", 'w') sample_tumor = input_tumor.readline().split()[1:] sample_normal = input_normal.readline().split()[1:] output_tumor.write("Site\tRelatedGene\t" + "\t".join(sample_tumor) + "\n") output_normal.write("Site\tRelatedGene\t" + "\t".join(sample_normal) + "\n") while(True) : line1 = input_tumor.readline().split() line2 = input_normal.readline().split() if(len(line2) == 0) : break if(line1[0] == target_site[index]) : index += 1 output_tumor.write(line1[0] + "\t" + target_gene[index - 1] + "\t" + "\t".join(line1[1:]) + "\n") output_normal.write(line2[0] + "\t" + target_gene[index - 1] + "\t" + "\t".join(line2[1:]) + "\n") if(index == len(target_site)) : break <file_sep>/Validation - Random Correlation/Rank.Correlation.py import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt matplotlib.style.use('ggplot') import seaborn as sns cancerlist = ["PANCANCER"] execution_number = 10000 target_value = -4.0 for i in range(len(cancerlist)) : input_file = open("RANDOM.MERGE." + cancerlist[i] + ".Correlation.Values." + str(execution_number) + ".Times.txt", 'r') pvalues = map(float, input_file.read().splitlines()) pvalues.sort(reverse = True) rank = 1 for pvalue in pvalues : if(target_value > pvalue) : break rank += 1 sns.set() sns.distplot(pvalues, kde = True, hist = True) plt.title("#10000 Random Correlation-values' Density Plot") plt.xlabel("Random Correlation-value") # plt.ylabel("Density") plt.grid(True) figure = plt.gcf() plt.show() figure.savefig(cancerlist[i] + ".Random.Correlation.Values.Density.Plot.pdf") <file_sep>/Optimal Cutoff/adding_cyt_cor.py from scipy import stats import matplotlib.pyplot as plt plt.style.use('ggplot') probe_count = 485577 cancerlist = ["KIRC", "BRCA", "THCA", "HNSC", "LIHC", "PRAD", "UCEC", "KIRP", "LUSC", "COAD", "LUAD", "PANCANCER"] sample_table = {} input_cytact = open("TCGA_methylation_cowork_1.txt",'r') header = input_cytact.readline().split() indexing = header.index("CytAct") whole_table = input_cytact.readlines() for line in whole_table : line = line.split() ID = line[0].replace("_", "") sample_table[ID] = line[indexing] input_file = [] output_file = [] for i in range(0, len(cancerlist)) : input_file.append(open(cancerlist[i] + ".optimal_cutoff_result.txt", 'r')) output_file.append(open(cancerlist[i] + ".optimal_cutoff_including_cytact.txt", 'w')) header = "Sample_ID\tNumber_of_sites\tCytAct\n" output_file[i].write(header) reading_table = input_file[i].readlines() num_table = [] cytact_table = [] for line in reading_table : line = line.split() if(line[0] not in sample_table or line[1] == "0") : continue line.append(sample_table[line[0]]) printline = "" for j in range(0, len(line)) : printline += "%s\t" % line[j] printline += "\n" output_file[i].write(printline) num_table.append(float(line[1])) cytact_table.append(float(line[2])) pearson = stats.pearsonr(num_table, cytact_table) spearman = stats.spearmanr(num_table, cytact_table) last_printline1 = "Pearson : %f\t%f\n" % (pearson[0], pearson[1]) last_printline2 = "Spearman : %f\t%f\n" % (spearman[0], spearman[1]) output_file[i].write(last_printline1) output_file[i].write(last_printline2) plt.scatter(num_table, cytact_table) plt.show() <file_sep>/GeneMethyl Package/build/lib/GeneMethyl/BetavalueDistribution.py import os import matplotlib matplotlib.use('Agg') import matplotlib.pyplot matplotlib.pyplot.style.use('ggplot') import seaborn as sns def DrawDensityPlot(disease, roughness_cutoff, whether_histogram) : def GetOnlyValidBetavalueRow(line, length) : betavalue_row = [] for k in range(length) : if(line[k] == "NA") : continue betavalue_row.append(float(line[k])) return betavalue_row input_tumor = open(disease + ".DNA_methylation_450K.tsv", 'r') input_tumor.readline() # sample line section_summation = [0 for i in range(int(1 / roughness_cutoff) + 1)] while(True) : line1 = input_tumor.readline().replace("\t\n", "\tNA\n").replace("\t\t", "\tNA\t").replace("\t\t", "\tNA\t").split() if(len(line1) == 0) : break site_id = line1.pop(0) betavalue_row = GetOnlyValidBetavalueRow(line1, len(line1)) # getting betavalue for each cpg site for value in betavalue_row : section_summation[int(value / roughness_cutoff)] += 1 path = os.pwd() + "/Result" if not os.path.exists("Result/DistributionPlot") : os.mkdir("Result/DistributionPlot") sns.set() sns.distplot(section_summation, kde = True, hist = whether_histogram) matplotlib.pyplot.title(disease + " Betavalue Distribution Plot") matplotlib.pyplot.xlabel("Betavalue") matplotlib.pyplot.grid(True) figure = matplotlib.pyplot.gcf() matplotlib.pyplot.show() figure.savefig(path + "/DistributionPlot/" + disease + ".Betavalue.Distribution.Plot.pdf") return section_summation #roughness_cutoff = float(0.001) #disease = "PANCANCER" #whether_histogram = True #Draw(disease, roughness_cutoff, True) <file_sep>/CpG site Correlation/Separation Version/P_Code_Server8_PANCANCER_0.py # -*- coding: utf-8 -*- cancerlist = ["PANCANCER"] # server1 from operator import itemgetter from scipy import stats import numpy as np betavalue_arr = [] cytoact_arr = [] probe_name = [] sample_id = [] start_number = 420000 SEP_NAME = ".SEP_8.0." probe_count = 6000 sample_count = 0 probe_separation_number = 1000 probe_iteration = 0 ###################################################################################################################################################### def getting_cytoact() : cytoact_file = open("TCGA_methylation_cowork_1.txt", 'r') header = cytoact_file.readline().split() # header 읽기 id_posit = header.index("id") # sample ID positioning cytoact_posit = header.index("CytAct") # CytAct positioning cytodata = cytoact_file.readlines() # 데이터 테이블 통째로 읽어들임 cytoact_file.close() for line in cytodata : line = line.split() sample_id.append(line[id_posit].replace('_', '')) # sample ID 추출 (주형으로 사용할 것) sample_count = len(sample_id) for i in range(0, sample_count) : cytoact_arr.append(None) # CytAct value table 초기화 for line in cytodata : line = line.split() # 1 sample data를 분절해서 CytAct value 추출하기 위함 if(line[cytoact_posit] != "NA") : # CytAct value가 결측치가 아니라면 sample_posit = sample_id.index(line[id_posit].replace('_', '')) cytoact_arr[sample_posit] = float(line[cytoact_posit]) # 저장한다 return; ###################################################################################################################################################### getting_cytoact() print("CytAct_Completed") ###################################################################################################################################################### def reset_betavalue() : del betavalue_arr[:] for reset_x in range(0, probe_separation_number) : betavalue_arr.append({}) return ###################################################################################################################################################### import math def mean(x): sum = 0.0 for i in x: sum += i return sum / len(x) def sampleStandardDeviation(x): sumv = 0.0 for i in x: sumv += (i - mean(x)) ** 2 return math.sqrt(sumv / (len(x) - 1)) def pearson(x, y): scorex = [] scorey = [] for i in x: scorex.append((i - mean(x)) / sampleStandardDeviation(x)) for j in y: scorey.append((j - mean(y)) / sampleStandardDeviation(y)) return (sum([i * j for i, j in zip(scorex, scorey)])) / (len(x) - 1) ###################################################################################################################################################### def getting_betavalue(name) : tumor_pearson_output = open(name + SEP_NAME + "Tumor_Cor_CpGsite&CytAct_pearson.txt", 'w'); tumor_spearman_output = open(name + SEP_NAME + ".Tumor_Cor_CpGSite&CytAct_spearman.txt", 'w') tumor_pearson_output.write("CpGsite\t%s\tP_value\n" % name); tumor_spearman_output.write("CpGsite\t%s\tP_value\n" % name) filename1 = name + ".humanmethylation450.tumor.txt" # cancer name별로 파일명이 다름을 고려해줌 # filename2 = name + ".humanmethylation450.normal.txt" # cancer name별로 파일명이 다름을 고려해줌 input_file1 = open(filename1, 'r') # input_file2 = open(filename2, 'r') sample_name1= input_file1.readline().split() # header에 sample ID가 있으므로 별도로 읽어준 후 # sample_name2 = input_file2.readline().split() for separation_count in range(0, start_number) : input_file1.readline() del sample_name1[0]; del sample_name1[0] # del sample_name2[0]; del sample_name2[0] # 쓰레기 데이터를 제외 input_file1.readline() # betavalue임을 명시하는 row를 읽고 폐기 # input_file2.readline() probe_separation_number_copy = probe_separation_number i = 0 while i < probe_count : ################################################################################################################################################## del probe_name[:] escape = False for normal_iteration in range(0, probe_separation_number_copy) : line1 = input_file1.readline().split() # 한 probe에 대한 여러 sample ID의 betavalue를 읽어들임 # line2 = input_file2.readline().split() if(len(line1) == 0) : # 끝까지 읽은 경우 루프 문을 빠져나감 escape = True; probe_separation_number_copy = normal_iteration break # while line1[0] != line2[0] : # 관심 있는 probe와 같아질 때까지 normal data를 훑어 내려감 # ############ 관심 없는 probe이므로 출력해준 뒤 Not interested 표시 # tumor_pearson_output.write("%s\tNot interested\n" % line2[0]); tumor_spearman_output.write("%s\tNot interested\n" % line2[0]) # line2 = input_file2.readline().split() # 새로운 probe를 읽어들임 probe_name.append(line1[0]) # CpG site name 추출한 뒤, betavalue가 아니므로 리스트에서 제거 del line1[0]; #del line2[0] ################################################################################################################################################## for j in range(0, len(line1)) : # sample ID의 개수만큼 반복함 sample_name1[j] = sample_name1[j][:15].replace('-', '') # sample ID의 형식을 통일해줌 if(line1[j] != "NA" and sample_name1[j] in sample_id) : # 결측치가 아니고, sample id에 포함된 경우 betavalue_arr[normal_iteration][sample_name1[j]] = [float(line1[j]), None] # sample ID에 맞는 index에 betavalue 저장 ################################################################################################################################################## # for j in range(0, len(line2)) : # sample ID의 개수만큼 반복함 # sample_name2[j] = sample_name2[j][:15].replace('-', '') # sample ID의 형식을 통일해줌 # if(line2[j] != "NA" and sample_name2[j] in sample_name1) : # 결측치가 아니고, sample id에 포함된 경우 # betavalue_arr[normal_iteration][sample_name2[j]][1] = float(line2[j]) # sample ID에 맞는 index에 betavalue 저장 ################################################################################################################################################## for j in range(0, probe_separation_number_copy) : printline1 = "%s\t" % probe_name[j]; printline2 = "%s\t" % probe_name[j] tumor = [None, None]; correction_FC = [None, None]; correction_minus = [None, None] tumor[0] = list(); tumor[1] = list() check_tumor = False iteration_number = len(betavalue_arr[j]) each_site_sample = betavalue_arr[j].items() for k in range(0, iteration_number) : if(each_site_sample[k][1][0] != None) : tumor[0].append(float(each_site_sample[k][1][0])); tumor[1].append(float(cytoact_arr[sample_id.index(each_site_sample[k][0])])) check_tumor = True if(check_tumor) : tumor_pearson_pair = stats.pearsonr(tumor[0], tumor[1]); tumor_spearman_pair = stats.spearmanr(tumor[0], tumor[1]) printline1 += "%f\t%.3f" % (tumor_pearson_pair[0], tumor_pearson_pair[1]); printline2 += "%f\t%.3f" % (tumor_spearman_pair[0], tumor_spearman_pair[1]) else : printline1 += "NA\tNA"; printline2 += "NA\tNA" printline1 += "\n"; printline2 += "\n" tumor_pearson_output.write(printline1) tumor_spearman_output.write(printline2) if(escape) : break ################################################################################################################################################## i += probe_separation_number print(i, probe_separation_number, "We are processing %s" % SEP_NAME) input_file1.close(); #input_file2.close() tumor_pearson_output.close(); tumor_spearman_output.close() return def process(cancer_name) : reset_betavalue() getting_betavalue(cancer_name) return for cancer_name in cancerlist : process(cancer_name); print(cancer_name + " completed") print("END") <file_sep>/CpG site Correlation/Results_Integration/Integration_Row_PRAD.py # -*- coding: utf-8 -*- target_cancer = "PRAD" input_file1 = [] input_file2 = [] output_tumor1 = open(target_cancer + ".Tumor_Cor_CpGsite&CytAct_pearson.txt", 'w') output_tumor2 = open(target_cancer + ".Tumor_Cor_CpGSite&CytAct_spearman.txt", 'w') for i in range(0, 9) : input_file1.append(open(target_cancer + ".SEP_4." + str(i) + ".Tumor_Cor_CpGsite&CytAct_pearson.txt", 'r')) input_file2.append(open(target_cancer + ".SEP_4." + str(i) + "..Tumor_Cor_CpGSite&CytAct_spearman.txt", 'r')) if(i == 0) : output_tumor1.write(input_file1[i].readline()) output_tumor2.write(input_file2[i].readline()) else : input_file1[i].readline() input_file2[i].readline() printarray1 = input_file1[i].readlines() printarray2 = input_file2[i].readlines() for line1 in printarray1 : output_tumor1.write(line1) for line2 in printarray2 : output_tumor2.write(line2) output_tumor1.close() output_tumor2.close() print("END") <file_sep>/CpG site Correlation/Filtering Cutoff/Compact.py input_file1 = open("Excluded_Tumor_Cor_CpGsite_CytAct_pearson.txt", 'r') input_file2 = open("Excluded_Tumor_Cor_CpGsite_CytAct_spearman.txt", 'r') probe_count = 485577 cancer_count = 33 # except PANCANCER per = 0.8 percentage = float(cancer_count) * per cutoff = 0.3 pearson_output1 = open(str(per) + "_pearson_" + str(cutoff) + "compact_version.txt", 'w') pearson_output2 = open(str(per) + "_pearson_" + "-" + str(cutoff) + "compact_version.txt", 'w') spearman_output1 = open(str(per) + "_spearman_" + str(cutoff) + "compact_versino.txt", 'w') spearman_output2 = open(str(per) + "_spearman_" + "-" + str(cutoff) + "compact_version.txt", 'w') header = input_file1.readline() header = input_file2.readline() pearson_output1.write(header) pearson_output2.write(header) spearman_output1.write(header) spearman_output2.write(header) for i in range(0, probe_count) : pearson_line = input_file1.readline().split() spearman_line = input_file2.readline().split() printline1 = pearson_line[0] printline2 = spearman_line[0] printline3 = pearson_line[0] printline4 = spearman_line[0] del pearson_line[0]; del spearman_line[0] p_pan_cor = pearson_line.pop(0) p_pan_P = pearson_line.pop(0) sp_pan_cor = spearman_line.pop(0) sp_pan_P = spearman_line.pop(0) if(p_pan_cor != "NA") : if(float(p_pan_P) < 0.05) : if(float(p_pan_cor) >= cutoff) : count_3 = 0 count_5 = 0 count_7 = 0 j = 0 while j < cancer_count * 2 : if(pearson_line[j] != "NA") : if(float(pearson_line[j]) >= 0.7 and float(pearson_line[j+1]) < 0.05) : count_7 += 1 elif(float(pearson_line[j]) >= 0.5 and float(pearson_line[j+1]) < 0.05) : count_5 += 1 elif(float(pearson_line[j]) >= 0.3 and float(pearson_line[j+1]) < 0.05) : count_3 += 1 j += 2 total_count = count_3 + count_5 + count_7 if(total_count >= percentage) : print("IN") printline1 += "\t" + str(p_pan_cor) + "\t" + str(p_pan_P) + "\t" for adding in pearson_line : printline1 += adding + "\t" printline1 += "\n" pearson_output1.write(printline1) if(float(p_pan_cor) <= 0 - cutoff) : count_3 = 0 count_5 = 0 count_7 = 0 j = 0 while j < cancer_count * 2 : if(pearson_line[j] != "NA") : if(float(pearson_line[j]) <= -0.7 and float(pearson_line[j+1]) < 0.05) : count_7 += 1 elif(float(pearson_line[j]) <= -0.5 and float(pearson_line[j+1]) < 0.05) : count_5 += 1 elif(float(pearson_line[j]) <= -0.3 and float(pearson_line[j+1]) < 0.05) : count_3 += 1 j += 2 total_count = count_3 + count_5 + count_7 if(total_count >= percentage) : printline2 += "\t" + str(p_pan_cor) + "\t" + str(p_pan_P) + "\t" for adding in pearson_line : printline2 += adding + "\t" printline2 += "\n" pearson_output2.write(printline2) if(sp_pan_cor != "NA") : if(float(sp_pan_P) < 0.05) : if(float(sp_pan_cor) >= cutoff) : count_3 = 0 count_5 = 0 count_7 = 0 j = 0 while j < cancer_count * 2 : if(spearman_line[j] != "NA") : if(float(spearman_line[j]) >= 0.7 and float(spearman_line[j+1]) < 0.05) : count_7 += 1 elif(float(spearman_line[j]) >= 0.5 and float(spearman_line[j+1]) < 0.05) : count_5 += 1 elif(float(spearman_line[j]) >= 0.3 and float(spearman_line[j+1]) < 0.05) : count_3 += 1 j += 2 total_count = count_3 + count_5 + count_7 if(total_count >= percentage) : printline3 += "\t" + str(sp_pan_cor) + "\t" + str(sp_pan_P) + "\t" print("IN") for adding in spearman_line : printline3 += adding + "\t" printline3 += "\n" spearman_output1.write(printline3) if(float(sp_pan_cor) <= 0 - cutoff) : count_3 = 0 count_5 = 0 count_7 = 0 j = 0 while j < cancer_count * 2 : if(spearman_line[j] != "NA") : if(float(spearman_line[j]) <= -0.7 and float(spearman_line[j+1]) < 0.05) : count_7 += 1 elif(float(spearman_line[j]) <= -0.5 and float(spearman_line[j+1]) < 0.05) : count_5 += 1 elif(float(spearman_line[j]) <= -0.3 and float(spearman_line[j+1]) < 0.05) : count_3 += 1 j += 2 total_count = count_3 + count_5 + count_7 if(total_count >= percentage) : printline4 += "\t" + str(sp_pan_cor) + "\t" + str(sp_pan_P) + "\t" print("IN") for adding in spearman_line : printline4 += adding + "\t" printline4 += "\n" spearman_output2.write(printline4) <file_sep>/Betavalue Count By Threshold/Betavalue_0.2_gap_sample_tumor.py cancerlist = ["ACC", "BLCA", "BRCA", "CESC", "CHOL", "COAD", "DLBC", "ESCA", "GBM", "HNSC", "KICH", "KIRC", "KIRP", "LGG", "LIHC", "LUAD", "LUSC", "MESO", "OV", "PAAD", "PCPG", "PRAD", "READ", "SARC", "SKCM", "STAD", "TGCT", "THCA", "THYM", "UCEC", "UCS", "UVM"] input_file1 = [] gap = 0.2 output_file1 = open(str(gap) + ".sample." + "Betavalue_WholeTumorCount.csv", 'w') probe_count = 485577 threshold_array = [] header = "Threshold" def MakeThresholdArray(gap) : global threshold_array global header cutoff = 0.0 threshold_array.append([]) count = 0 while(cutoff <= 1.0) : threshold_array.append(cutoff) count += 1 cutoff = gap * float(count) for i in range(0, len(threshold_array) - 1) : header += "\t%s~%s" % (str(threshold_array[i]), str(threshold_array[i + 1])) return sample_id = [] sample_count = {} def GetSample() : cytoact_file = open("TCGA_methylation_cowork_1.txt", 'r') header = cytoact_file.readline().split() # getting header id_posit = header.index("id") # sample ID positioning cytoact_posit = header.index("CytAct") # CytAct positioning cytodata = cytoact_file.readlines() # read data table cytoact_file.close() count = 0 global sample_id global sample_count global threshold_array for line in cytodata : line = line.split() sample_id.append(line[id_posit].replace('_', '')) # sample ID extraction sample_count[sample_id[count]] = [] for i in range(len(threshold_array)) : sample_count[sample_id[count]].append(0) count += 1 return MakeThresholdArray(gap) GetSample() header += "\n" output_file1.write(header) def ReturnRange(value) : for i in range(0, len(threshold_array) - 1) : if(value >= threshold_array[i] and value <= threshold_array[i + 1]) : return i for i in range(0, len(cancerlist)) : input_file1.append(open(cancerlist[i] + ".humanmethylation450.tumor.txt", 'r')) sample_header1 = input_file1[i].readline().split() input_file1[i].readline().split() del sample_header1[0]; del sample_header1[0] for j in range(0, len(sample_header1)) : sample_header1[j] = sample_header1[j][:15].replace('-', '') for j in range(0, probe_count) : line1 = input_file1[i].readline().split() while(len(line1) == 0) : line1 = input_file1[i].readline().split() site_id = line1.pop(0) for k in range(0, len(line1)) : cancer_value = line1[k] if(cancer_value == "NA" or sample_header1[k] not in sample_id) : continue sample_count[sample_header1[k]][ReturnRange(float(cancer_value))] += 1 for name in sample_id : printline1 = name print_array = sample_count[name].itemes() for data in print_array : printline1 += "\t%s" % str(data) printline1 += "\n" output_file1.write(printline1) <file_sep>/Betavalue Count In Segment/CountSort.py input_file = open("Betavalue_Array.csv", 'r') output_file = open("Betavalue_Array_CountSort.csv", 'w') count_array = [] def Process() : line = input_file.readline() debug_count = 1 for i in range(0, 10 ** 7 + 1) : count_array.append(0) while(len(line) > 1) : value = int(float(line) * (10 ** 7)) count_array[value] += 1 line = input_file.readline() debug_count += 1 if(debug_count % 10000 == 0) : print(str(debug_count) + " completed.") for i in range(0, 10 ** 7 + 1) : for j in range(0, count_array[i]) : printline = str(float(i) / float(10 ** 7)) + "\n" output_file.write(printline) return Process() <file_sep>/Filtering Invalid Samples/ValidCpGsitesOfEachSample.py #cancerlist = ["ACC", "BLCA", "BRCA", "CESC", "CHOL", "COAD", "DLBC", "ESCA", "GBM", "HNSC", "KICH", "KIRC", "KIRP", "LGG", "LIHC", "LUAD", "LUSC", "MESO", "OV", "PAAD", "PCPG", "PRAD", "READ", "SARC", "SKCM", "STAD", "TGCT", "THCA", "THYM", "UCEC", "UCS", "UVM", "PANCANCER"] cancerlist = ["PANCANCER"] probe_count = 485577 cpgsites = [] p_threshold = [0.05, 0.005, 0.0005, 0.0000001] for i in range(0, len(cancerlist)) : site_index = [] for j in range(len(p_threshold)) : cpgsites.append([]) site_index.append(0) input_cpgsites = open(str(p_threshold[j]) + "." + cancerlist[i] + ".CpGsites.By.TTest.txt", 'r') input_cpgsites.readline() lines = input_cpgsites.read().splitlines() for line in lines : cpgsites[j].append(line.split()[0]) cpgsites[j].append("END_POINT") input_tumor = open(cancerlist[i] + ".humanmethylation450.tumor.txt", 'r') sample_header1 = input_tumor.readline().split() # sample line del sample_header1[0]; del sample_header1[0] print("#Samples : %s" % str(len(sample_header1))) valid_cpgsites = [] for j in range(len(p_threshold)) : valid_cpgsites.append([]) for k in range(len(sample_header1)) : valid_cpgsites[j].append(0) input_tumor.readline() # junk line for j in range(probe_count) : line1 = input_tumor.readline().split() site_id = line1.pop(0) for k in range(len(p_threshold)) : if(site_id == cpgsites[k][site_index[k]]) : for l in range(len(line1)) : if(line1[k] == "NA") : continue valid_cpgsites[k][l] += 1 site_index[k] += 1 if(j % 10000 == 0) : print(cancerlist[i] + " %d" % j) for j in range(len(p_threshold)) : output_file = open(str(p_threshold[j]) + "." + cancerlist[i] + ".Valid.CpGsties.Of.Each.Sample.txt", 'w') for k in range(len(sample_header1)) : output_file.write(sample_header1[k] + "\t%d\n" % valid_cpgsites[j][k]) <file_sep>/Correlation Between CytAct and Summation - SimpleCutoff/Ttest/PAN_Correlation.SummationWithCytActTtest0.005.py from operator import itemgetter from scipy import stats import numpy import matplotlib matplotlib.use('Agg') import matplotlib.pyplot import matplotlib.pylab matplotlib.pyplot.style.use('ggplot') #cancerlist = ["ACC", "BLCA", "BRCA", "CESC", "CHOL", "COAD", "DLBC", "ESCA", "GBM", "HNSC", "KICH", "KIRC", "KIRP", "LGG", "LIHC", "LUAD", "LUSC", "MESO", "OV", "PAAD", "PCPG", "PRAD", "READ", "SARC", "SKCM", "STAD", "TGCT", "THCA", "THYM", "UCEC", "UCS", "UVM", "PAN"] cancerlist = ["PANCANCER"] input_file1 = [] output_file1 = [] probe_count = 485577 sample_id = [] cytoact = [] sample_index = [] def GetSample() : cytoact_file = open("TCGA_methylation_cowork_1.txt", 'r') header = cytoact_file.readline().split() # getting header id_posit = header.index("id") # sample ID positioning cytoact_posit = header.index("CytAct") # CytAct positioning cytodata = cytoact_file.readlines() # read data table cytoact_file.close() count = 0 global sample_id global cytoact for line in cytodata : line = line.split() sample_id.append(line[id_posit].replace('_', '')) # sample ID extraction cytoact.append(float(line[cytoact_posit])) # CytAct extraction count += 1 return count # Sample number return sample_number = GetSample() PN = ["Positive", "Negative", "Both", "Tstat"] percentage = ["0.01", "0.025", "0.05", "0.1", "0.125", "0.15", "0.175", "0.2", "0.225", "0.25", "0.275", "0.3"] P_value = 0.005 correlation_table = [] for i in range(0, len(cancerlist)) : correlation_table.append([]) for k in range(len(percentage)) : correlation_table[i].append([]) summation = [] cytact = [] for j in range(len(PN)) : summation.append([]) cytact.append([]) for j in range(len(PN)) : correlation_table[i][k].append([]) input_file1 = open("Pvalue." + str(P_value) + ".Percentage." + percentage[k] + "." + cancerlist[i] + "." + PN[j] + ".MeaningfulCpGsites.By.Ttest_Binarization.Summation.By.Tstat.txt", 'r') lines = input_file1.readlines() for line in lines : line = line.split() if(line[0] in sample_id) : index = sample_id.index(line[0]) summation[j].append(float(line[1])) cytact[j].append(cytoact[index]) xlimit = max(map(lambda x : max(summation[x]), range(len(PN)))) ylimit = max(map(lambda x : max(cytact[x]), range(len(PN)))) for j in range(len(PN)) : if(len(summation[j]) < 1 / float(percentage[k])) : print("Pvalue." + str(P_value) + "." + percentage[j] + ", " + cancerlist[i] + " " + PN[j] + " " + percentage[k] + " has less than %s samples." % str(1 / float(percentage[k]))) correlation_table[i][k][j].append("NA") correlation_table[i][k][j].append("NA") continue matplotlib.pyplot.hold(False) matplotlib.pyplot.title(cancerlist[i] + " " + PN[j] + " " + percentage[k] + " T-test's P-value < " + str(P_value)) matplotlib.pyplot.xlabel("Summation") matplotlib.pyplot.ylabel("CytAct") matplotlib.pyplot.legend() matplotlib.pyplot.grid(True) # pearson_pair = stats.pearsonr(summation[j], cytact[j]) spearman_pair = stats.spearmanr(summation[j], cytact[j]) spearman_cor = "{0:.3f}".format(spearman_pair[0]) spearman_P = "{0:.3f}".format(spearman_pair[1]) correlation_table[i][k][j].append("{0:.5f}".format(spearman_pair[0])) correlation_table[i][k][j].append("{0:.5f}".format(spearman_pair[1])) matplotlib.pyplot.scatter(summation[j], cytact[j], marker = '.', c = 'b') matplotlib.pyplot.title(cancerlist[i] + " " + PN[j] + " Spearman Cor = %s, P = %s" % (spearman_cor, spearman_P)) matplotlib.pyplot.hold(True) matplotlib.pylab.plot(summation[j], cytact[j], '.') z = numpy.polyfit(summation[j], cytact[j], 1) p = numpy.poly1d(z) matplotlib.pylab.plot(summation[j], p(summation[j]), "r--") figure = matplotlib.pyplot.gcf() matplotlib.pyplot.xlim(0, xlimit) matplotlib.pyplot.ylim(0, ylimit) matplotlib.pyplot.show() figure.savefig("Pvalue." + str(P_value) + "." + cancerlist[i] + "." + percentage[k] + "." + PN[j] + ".pdf") output_file = open("Pvalue." + str(P_value) + ".PANCANCER.Correlation.CytAct.Between.Meaningful.Betavalue.Count.Of.Each.CpGsite.EveryPercentage.txt", 'w') header2 = "Percentage" for j in range(len(PN)) : header2 += "\t%s\t%s" % (PN[j] + "(Cor)", PN[j] + "(P)") header2 += "\n" output_file.write(header2) for k in range(len(percentage)) : # output_file = open(percentage[k] + ".Meaningful.Betavalue.Count.Of.Each.CpGsite.Positive.Negative.Both.Correlation.Table.txt", 'w') for i in range(0, len(cancerlist)) : printline = percentage[k] for j in range(len(PN)) : printline += "\t%s\t%s" % (correlation_table[i][k][j][0], correlation_table[i][k][j][1]) output_file.write(printline + "\n") <file_sep>/GeneMethyl Package/build/lib/GeneMethyl/SimpleCutoff.py import os import numpy import math from scipy import stats import matplotlib matplotlib.use('Agg') import matplotlib.pyplot import matplotlib.pylab matplotlib.pyplot.style.use('ggplot') sample_id = [] cytoact = [] path = os.getcwd() + "/Result/SimpleCutoff" def TargetGeneActivity(disease, target_gene) : if not os.path.exists(disease + ".RNAseq.tsv") : print("Error : " + disease + ".RNAseq.tsv is not found.") return False RNAseq_file = open(disease + ".RNAseq.tsv", 'r') gene_score_file = open(path + "/" + disease + ".TargetGeneActivity.txt", 'w') gene_length = len(target_gene) header = RNAseq_file.readline().split()[1:] sample_length = len(header) for i in range(sample_length) : header[i] = header[i].replace('"', '') expression_level = numpy.zeros((sample_length, len(target_gene)), dtype = float) gene_check = [False for i in range(len(target_gene))] while(True) : line = RNAseq_file.readline().replace("\t\n", "\tNA\n").replace("\t\t", "\tNA\t").replace("\t\t", "\tNA\t").split() if(len(line) == 0) : break gene_id = line.pop(0).replace('"', '') if(gene_id.find('|') != -1) : gene_id = gene_id[:gene_id.index('|')] if(gene_id in target_gene) : gene_check[target_gene.index(gene_id)] = True gene_index = target_gene.index(gene_id) for i in range(len(line)) : expression_level[i][gene_index] = float(line[i]) if(False in gene_check) : missing_gene = [] for i in range(len(target_gene)) : if(gene_check[i] == False) : missing_gene.append(target_gene[i]) if(len(missing_gene) == 1) : print("Error : " + " ".join(missing_gene) + " gene is not found in " + disease + ".RNAseq.tsv.") else : print("Error : " + " ".join(missing_gene) + " genes are not found in " + disease + ".RNAseq.tsv.") return False gene_score_file.write("Sample\t" + "\t".join(target_gene) + "\tPseudocount1_Activity(log)" + "\n") pseudocount_score = [] for i in range(sample_length) : if(len(target_gene) != 1) : pseudocount_score.append(math.log(sum(expression_level[i]) + gene_length, gene_length)) gene_score_file.write(header[i] + "\t" + "\t".join(map(str, expression_level[i])) + "\t" + str(pseudocount_score[i]) + "\n") else : pseudocount_score.append(expression_level[i][0] + 1) gene_score.write(header[i] + "\t" + str(expression_level[i][0]) + "\t" + "\t" + str(pseudocount_score[i]) + "\n") return True def View_Correlation_AND_ScatterPlot(disease, gene_name, cutoff, Type, whether_FoldChange) : if not os.path.exists("Result/SimpleCutoff") : os.makedirs(path) if not os.path.exists("Result/SimpleCutoff/FC_CpGsites") and whether_FoldChange == True : os.makedirs(path + "/FC_CpGsites") if not os.path.exists("Result/SimpleCutoff/Summation") : os.makedirs(path + "/Summation") if not os.path.exists("Result/SimpleCutoff/ScatterPlot") : os.makedirs(path + "/ScatterPlot") if not os.path.exists("Result/SimpleCutoff/Correlation") : os.makedirs(path + "/Correlation") if(Type not in ["Lower", "Higher", "Both", "All"]) : print("Error : Type %s is not valid. Valid Types are Lower, Higher, Both and All." % Type) return new_cutoff = [] for i in range(len(cutoff)) : if(cutoff[i] > 1 or cutoff[i] < 0) : print("%s cutoff is not valid. Cutoff must be in [0, 1]." % str(cutoff[i])) continue new_cutoff.append(cutoff[i]) cutoff = new_cutoff def GetSampleScoreData(disease) : cytoact_file = open(path + "/" + disease + ".TargetGeneActivity.txt", 'r') header = cytoact_file.readline().split() # getting header id_posit = header.index("Sample") # sample ID positioning cytoact_posit = header.index("Pseudocount1_Activity(log)") # CytAct positioning cytodata = cytoact_file.readlines() # read data table cytoact_file.close() count = 0 global sample_id global cytoact for line in cytodata : line = line.split() sample_id.append(line[id_posit].replace('-', '').replace('_', '')[:12]) # sample ID extraction cytoact.append(float(line[cytoact_posit])) # CytAct extraction count += 1 return count # Sample number return def MedianInSortedRow(betavalue_row, new_length) : betavalue_median = betavalue_row[int(new_length / 2)][0] if(new_length % 2 == 0) : betavalue_median = (betavalue_median + betavalue_row[int(new_length / 2) - 1][0]) / 2 return betavalue_median def GetValidBetavalueRowAndSorted(line, length, sample_index) : betavalue_row = [] new_length = length for k in range(length) : if(line[k] == "NA" or sample_index[k] == -1) : new_length -= 1 continue betavalue_row.append([float(line[k]), k]) betavalue_row.sort(key = lambda x : x[0]) return betavalue_row, new_length def GetSampleHeader(sample_header, length) : global sample_id sample_index = [] original_sample_header = [] for j in range(0, length) : original_sample_header.append(sample_header[j]) sample_header[j] = sample_header[j].replace('-', '').replace('_', '')[:12] if(sample_header[j] in sample_id) : sample_index.append(sample_id.index(sample_header[j])) else : sample_index.append(-1) return sample_header, sample_index, original_sample_header if not os.path.exists(disease + ".DNA_methylation_450K.tsv") : print("Error : " + disease + ".DNA_methylation_450K.tsv is not found.") return input_tumor = open(disease + ".DNA_methylation_450K.tsv", 'r') MissingCheck = TargetGeneActivity(disease, gene_name) if(MissingCheck == False) : return sample_number = GetSampleScoreData(disease) sample_header = input_tumor.readline().split() # sample line sample_index = [] sample_binary_table = [] length = len(sample_header) sample_header, sample_index, original_sample_header = GetSampleHeader(sample_header, length) sample_binary_table = numpy.zeros((len(cutoff), 3, length), dtype = int) if(whether_FoldChange == True) : output_FC_cutoff = [] for i in range(len(cutoff)) : output_FC_cutoff.append([]) if(Type == "Lower" or Type == "All") : output_FC_cutoff[i].append(open(path + "/FC_CpGsites/" + "WholeSites.Cutoff." + str(cutoff[i]) + "." + disease + ".Lower.FC.CpGsites.txt", 'w')) output_FC_cutoff[i][0].write("Site\tFC(high_median/low_median)\tFC(high_mean/low_mean)\tP-value\n") else : output_FC_cutoff[i].append(None) if(Type == "Higher" or Type == "All") : output_FC_cutoff[i].append(open(path + "/FC_CpGsites/" + "WholeSites.Cutoff." + str(cutoff[i]) + "." + disease + ".Higher.FC.CpGsites.txt", 'w')) output_FC_cutoff[i][1].write("Site\tFC(high_median/low_median)\tFC(high_mean/low_mean)\tP-value\n") else : output_FC_cutoff[i].append(None) if(Type == "Both" or Type == "All") : output_FC_cutoff[i].append(open(path + "/FC_CpGsites/" + "WholeSites.Cutoff." + str(cutoff[i]) + "." + disease + ".Both.FC.CpGsites.txt", 'w')) output_FC_cutoff[i][2].write("Site\tFC(high_median/low_median)\tFC(high_mean/low_mean)\tP-value\n") else : output_FC_cutoff[i].append(None) j = 1 while(True) : line1 = input_tumor.readline().replace("\t\n", "\tNA\n").replace("\t\t", "\tNA\t").replace("\t\t", "\tNA\t").split() if(len(line1) == 0) : break site_id = line1.pop(0) betavalue_row, new_length = GetValidBetavalueRowAndSorted(line1, length, sample_index) # getting betavalue for each cpg site if(new_length > 0) : if(Type == "Lower" or Type == "All") : for cutoff_i in range(len(cutoff)) : breaking_point = new_length for l in range(new_length) : if(betavalue_row[l][0] > cutoff[cutoff_i]) : breaking_point = l break sample_binary_table[cutoff_i][0][betavalue_row[l][1]] += 1 if(whether_FoldChange == True) : chosen_cytact = []; notchosen_cytact = [] for l in range(breaking_point) : chosen_cytact.append(cytoact[sample_index[betavalue_row[l][1]]]) for l in range(breaking_point, new_length) : notchosen_cytact.append(cytoact[sample_index[betavalue_row[l][1]]]) FC_median, FC_mean = numpy.median(chosen_cytact) / numpy.median(notchosen_cytact), numpy.mean(chosen_cytact) / numpy.mean(notchosen_cytact) manwhitney_pair = stats.mannwhitneyu(chosen_cytact, notchosen_cytact) output_FC_cutoff[cutoff_i][0].write(site_id + "\t%s\t%s\t%s\n" % (str(FC_median), str(FC_mean), str(manwhitney_pair[1]))) if(Type == "Higher" or Type == "All") : for cutoff_i in range(len(cutoff)) : breaking_point = new_length for l in range(new_length) : if(betavalue_row[new_length - l - 1][0] < cutoff[cutoff_i]) : breaking_point = l break sample_binary_table[cutoff_i][1][betavalue_row[new_length - l - 1][1]] += 1 if(whether_FoldChange == True) : chosen_cytact = []; notchosen_cytact = [] for l in range(breaking_point) : chosen_cytact.append(cytoact[sample_index[betavalue_row[new_length - l - 1][1]]]) for l in range(breaking_point, new_length) : notchosen_cytact.append(cytoact[sample_index[betavalue_row[new_length - l - 1][1]]]) FC_median, FC_mean = numpy.median(chosen_cytact) / numpy.median(notchosen_cytact), numpy.mean(chosen_cytact) / numpy.mean(notchosen_cytact) manwhitney_pair = stats.mannwhitneyu(chosen_cytact, notchosen_cytact) output_FC_cutoff[cutoff_i][1].write(site_id + "\t%s\t%s\t%s\n" % (str(FC_median), str(FC_mean), str(manwhitney_pair[1]))) if(Type == "Both" or Type == "All") : for cutoff_i in range(len(cutoff)) : breaking_point1 = new_length for l in range(new_length) : if(betavalue_row[l][0] < cutoff[cutoff_i] / 2) : breaking_point = l break sample_binary_table[cutoff_i][2][betavalue_row[l][1]] += 1 breaking_point2 = new_length for l in range(new_length) : if(betavalue_row[new_length - l - 1][0] < cutoff[cutoff_i] / 2) : breaking_point2 = l break sample_binary_table[cutoff_i][2][betavalue_row[new_length - l - 1][1]] += 1 if(whether_FoldChange == True) : chosen_cytact = []; notchosen_cytact = [] for l in range(breaking_point1) : chosen_cytact.append(cytoact[sample_index[betavalue_row[l][1]]]) for l in range(breaking_point1, new_length) : notchosen_cytact.append(cytoact[sample_index[betavalue_row[l][1]]]) for l in range(breaking_point2) : chosen_cytact.append(cytoact[sample_index[betavalue_row[new_length - l - 1][1]]]) for l in range(breaking_point2, new_length) : notchosen_cytact.append(cytoact[sample_index[betavalue_row[new_length - l - 1][1]]]) FC_median, FC_mean = numpy.median(chosen_cytact) / numpy.median(notchosen_cytact), numpy.mean(chosen_cytact) / numpy.mean(notchosen_cytact) manwhitney_pair = stats.mannwhitneyu(chosen_cytact, notchosen_cytact) output_FC_cutoff[cutoff_i][2].write(site_id + "\t%s\t%s\t%s\n" % (str(FC_median), str(FC_mean), str(manwhitney_pair[1]))) if(j % 10000 == 0) : print("%dth sites completed." % j) j += 1 input_tumor.close() output_left_skewed.close() output_right_skewed.close() output_correlation_table = [] if(Type == "Lower" or Type == "All"): output_correlation_table.append(open(path + "/Correlation/" + "WholeSites." + disease + "." + "Lower" + ".Correlation.Summation.And." + "TargetGeneActivity.txt", 'w')) output_correlation_table[0].write("Cutoff\tCor\tPvalue\n") else : output_correlation_table.append(None) if(Type == "Higher" or Type == "All") : output_correlation_table.append(open(path + "/Correlation/" + "WholeSites." + disease + "." + "Higher" + ".Correlation.Summation.And." + "TargetGeneActivity.txt", 'w')) output_correlation_table[1].write("Cutoff\tCor\tPvalue\n") else : output_correlation_table.append(None) if(Type == "Both" or Type == "All") : output_correlation_table.append(open(path + "/Correlation/" + "WholeSites." + disease + "." + "Both" + ".Correlation.Summation.And." + "TargetGeneActivity.txt", 'w')) output_correlation_table[2].write("Cutoff\tCor\tPvalue\n") else : output_correlation_table.append(None) correlation_table = [] correlation_table = numpy.zeros((len(cutoff), 3, 2), dtype = float) Type_array = [] Type_dic = ["Lower", "Higher", "Both"] if(Type == "Lower" or Type == "All") : Type_array.append(0) if(Type == "Higher" or Type == "All") : Type_array.append(1) if(Type == "Both" or Type == "All") : Type_array.append(2) for k in range(len(cutoff)) : for type_i in range(len(Type_array)) : output_file = open(path + "/Summation/" + "WholeSites.Cutoff." + str(cutoff[k]) + "." + disease + "." + Type_dic[type_i] + ".Binarization.Summation.txt", 'w') header = "Site\t#%sMethylation\tTargetGeneActivity\n" % Type_dic[type_i] output_file.write(header) summation = [] cytact = [] for l in range(length) : if(sample_index[l] == -1) : printline = original_sample_header[l] + "\tNA\tNA\tNA\tNA\n" else : printline = original_sample_header[l] + "\t%s\t%s\n" % (str(sample_binary_table[k][Type_array[type_i]][l]), str(cytoact[sample_index[l]])) summation.append(sample_binary_table[k][Type_array[type_i]][l]); cytact.append(cytoact[sample_index[l]]) output_file.write(printline) params = {'legend.fontsize': 'x-large', 'figure.figsize': (10, 10), 'axes.labelsize': 'x-large', 'axes.titlesize':'x-large', 'xtick.labelsize':'x-large', 'ytick.labelsize':'x-large'} matplotlib.pylab.rcParams.update(params) matplotlib.pyplot.hold(False) matplotlib.pyplot.xlabel("Summation") matplotlib.pyplot.ylabel("".join(gene_name) + "Activity") matplotlib.pyplot.legend() matplotlib.pyplot.grid(True) spearman_pair = stats.spearmanr(summation, cytact) correlation_table[k][Type_array[type_i]][0] = spearman_pair[0] correlation_table[k][Type_array[type_i]][1] = spearman_pair[1] spearman_cor = "{0:.3f}".format(spearman_pair[0]) spearman_P = "{0:.3f}".format(spearman_pair[1]) matplotlib.pyplot.scatter(summation, cytact, marker = '.', c = 'b') matplotlib.pyplot.title(disease + ".WholeSites." + Type_dic[type_i] + ".Cutoff.%s" % str(cutoff[k]) + " Spearman Cor = %s, P = %s" % (spearman_cor, spearman_P)) matplotlib.pyplot.hold(True) matplotlib.pylab.plot(summation, cytact, '.') z = numpy.polyfit(summation, cytact, 1) p = numpy.poly1d(z) matplotlib.pylab.plot(summation, p(summation), "r--") figure = matplotlib.pyplot.gcf() matplotlib.pyplot.show() figure.savefig(path + "/ScatterPlot/" + "WholeSites.Cutoff." + str(cutoff[k]) + "." + disease + "." + Type_dic[type_i] + ".ScatterPlot.pdf") output_correlation_table[Type_array[type_i]].write("%s" % (str(cutoff[k])) + "\t%f\t%f\n" % (correlation_table[k][Type_array[type_i]][0], correlation_table[k][Type_array[type_i]][1])) if(Type == "All") : output_compare_table = open(path + "/Correlation/" + "WholeSites." + disease + "." + "CompareAll" + ".Correlation.Summation.And." + "TargetGeneActivity.txt", 'w') header_compare = "Cutoff" for j in range(3) : header_compare += "\t%s\t%s" % (Type_dic[j] + "(Cor)", Type_dic[j] + "(Pvalue)") header_compare += "\n" output_compare_table.write(header_compare) for i in range(len(cutoff)) : printline = str(cutoff[i]) for j in range(3) : printline += "\t%s\t%s" % (str(correlation_table[i][j][0]), str(correlation_table[i][j][1])) output_compare_table.write(printline + "\n") return sample_binary_table #target_genes = ["GZMA", "PRF1"] #cutoff_list = [0.05] #analysis_type = "All" #whether_FC_anaylsis = True #View_Correlation_AND_ScatterPlot("PANCANCER", target_gene, cutoff_list, analysis_type, whether_FC_analysis) <file_sep>/Optimal Cutoff/Over_30_normal_whole_cancers.py # -*- coding: utf-8 -*- #cancerlist = ["ACC", "BLCA", "BRCA", "CESC", "CHOL", "COAD", "DLBC", "ESCA", "GBM", "HNSC", "KICH", "KIRC", "KIRP", "LGG", "LIHC", "LUAD", "LUSC", "MESO", "OV", "PAAD", "PCPG", "READ", "SARC", "SKCM", "STAD", "TGCT", "THCA", "THYM", "UCEC", "UCS", "UVM", "PRAD"] cancerlist = ["KIRC", "BRCA", "THCA", "HNSC", "LIHC", "PRAD", "UCEC", "KIRP", "LUSC", "COAD", "LUAD"] probe_count = 485577 input_file1 = [] input_file2 = [] tumor_sample_name = [] normal_sample_name = [] header = "\t" output_file = open("PANCANCER.optimal_cutoff_data.txt", 'w') for i in range(0, len(cancerlist)) : input_file1.append(open(cancerlist[i] + ".humanmethylation450.tumor.txt", 'r')) input_file2.append(open(cancerlist[i] + ".humanmethylation450.normal.txt", 'r')) tumor_sample_name.append(input_file1[i].readline().split()) normal_sample_name.append(input_file2[i].readline().split()) del tumor_sample_name[i][0]; del tumor_sample_name[i][0] del normal_sample_name[i][0]; del normal_sample_name[i][0] for j in range(0, len(tumor_sample_name[i])) : tumor_sample_name[i][j] = tumor_sample_name[i][j][:15].replace('-', "") header += "%s\tTumor/Normal\t" % tumor_sample_name[i][j] for j in range(0, len(normal_sample_name[i])) : normal_sample_name[i][j] = normal_sample_name[i][j][:15].replace('-', "") header += "%s\tTumor/Normal\t" % normal_sample_name[i][j] input_file1[i].readline() input_file2[i].readline() header += "\n" output_file.write(header) for i in range(0, probe_count) : probe_name = "" printline = "" for j in range(0, len(cancerlist)) : line1 = input_file1[j].readline().split() line2 = input_file2[j].readline().split() probe_name = line1.pop(0) probe_name = line2.pop(0) for k in range(0, len(line1)) : printline += "%s\t%d\t" % (line1[k], j + 1) for k in range(0, len(line2)) : printline += "%s\t0\t" % line2[k] printline = probe_name + "\t" + printline + "\n" output_file.write(printline) if(i % 1000 == 0) : print(i) output_file.close() for i in range(0, len(cancerlist)) : input_file1[i].close() input_file2[i].close() <file_sep>/CytAct FC value/GettingMeaningfulCpGsitesIncludingExtremeSites.py cancerlist = ["PANCANCER"] input_file1 = [] output_file1 = [] threshold = 0.3 probe_count = 485577 for i in range(0, len(cancerlist)) : input_file1.append(open(str(threshold) + ".Cutoff.FC.Pvalue." + cancerlist[i] + ".txt", 'r')) output_file1.append(open(str(threshold) + ".MeaningfulCpGsitesByPvalue0.05." + cancerlist[i] + ".txt", 'w')) input_file1[i].readline() for j in range(0, probe_count) : line1 = input_file1[i].readline().split() site_id = line1.pop(0) if(line1[0] == "NoSamples") : continue elif(len(line1) != 1) : if(float(line1[2]) > 0.05) : continue printline = site_id for k in range(0, len(line1)) : printline += "\t" + line1[k] printline += "\n" output_file1[i].write(printline) if(j % 10000 == 0) : print(cancerlist[i] + " %d completed." % j) <file_sep>/Optimal Cutoff/PANCANCER_Optimal_cutoff.py import operator import numpy probe_count = 485577 #probe_count = 5 cancerlist = ["PANCANCER"] input_file = [] output_file = [] sample_id = [] for k in range(0, len(cancerlist)) : input_file.append(open(cancerlist[k] + ".optimal_cutoff_data.txt", 'r')) output_file.append(open(cancerlist[k] + ".optimal_cutoff_result.txt", 'w')) sample_id.append(input_file[k].readline().split()) for i in range(0, len(sample_id[k]) / 2) : del sample_id[k][i + 1] sample_cutoff_count = [[0 for j in range(len(sample_id[i]))] for i in range(len(cancerlist))] for k in range(0, len(cancerlist)) : for i in range(0, probe_count) : line = input_file[k].readline().split() if(len(line) == 0) : print(probe_count) continue del line[0] beta_value = [] whole_tumor = 0; whole_normal = 0 valid_data = 0 for j in range(0, len(line) / 2) : if(line[j * 2] == "NA") : continue check = True if(line[j * 2 + 1] == "0") : check = False whole_normal += 1 beta_value.append([float(line[j * 2]), check, j]) valid_data += 1 if(valid_data == 0) : continue whole_tumor = valid_data - whole_normal beta_value = sorted(beta_value, key = operator.itemgetter(0)) count_tumor = []; count_normal = [] count_tumor.append(beta_value[0][1]) count_normal.append(1 - beta_value[0][1]) for j in range(1, valid_data) : count_tumor.append(count_tumor[j - 1] + beta_value[j][1]) count_normal.append(count_normal[j - 1] + (1 - beta_value[j][1])) cutoff = [] tumor_low = []; tumor_high = [] normal_low = []; normal_high = [] fpr = []; tpr = [] argmax_parameter = [] for j in range(0, valid_data - 1) : cutoff.append(float(beta_value[j][0] + beta_value[j + 1][0]) / 2) tumor_low.append(float(count_tumor[j])) # normal -> tumor -> false negative tumor_high.append(float(whole_tumor - count_tumor[j])) # tumor -> tumor -> true positive normal_low.append(float(count_normal[j])) # normal -> normal -> true negative normal_high.append(float(whole_normal - count_normal[j])) # tumor -> normal -> false positive fpr.append(normal_high[j] / (normal_high[j] + normal_low[j])) tpr.append(tumor_high[j] / (tumor_high[j] + tumor_low[j])) argmax_parameter.append(tpr[j] - fpr[j]) optimal_index = numpy.argmax(argmax_parameter) optimal_threshold = cutoff[optimal_index] optimal_tpr = tumor_high[optimal_index] for j in range(optimal_index + 1, valid_data) : if(beta_value[j][1]) : sample_cutoff_count[k][beta_value[j][2]] += 1 #printline = "%f %d" % (optimal_threshold, optimal_tpr) #print(printline) print(cancerlist[k] + " completed.") for i in range(0, len(cancerlist)) : for j in range(0, len(sample_id[i])) : printline = sample_id[i][j] printline += "\t%d\n" % sample_cutoff_count[i][j] output_file[i].write(printline) for k in range(0, len(cancerlist)) : input_file[k].close() output_file[k].close() <file_sep>/PCDHG Gene Analysis/PANCANCER.Site.Info.py from numpy import mean, median cancerlist = ["PANCANCER"] probe_site = 485577 high_threshold = 0.8 low_threshold = 0.2 header = "Site\tTumorMean\tNormalMean\tMeanGap\tTumorMedian\tNormalMedian\tMedianGap\tTumorMax\tNormalMax\tMaxGap\tTumorMin\tNormalMin\tMinGap\t#ValidTumorSamples\t#ValidNormalSamples\n" for i in range(len(cancerlist)) : input_tumor = open(cancerlist[i] + ".humanmethylation450.tumor.txt", 'r') input_normal = open(cancerlist[i] + ".humanmethylation450.normal.txt", 'r') output = open(cancerlist[i] + ".Extreme.Site.Tumor." + str(high_threshold) + ".Normal." + str(low_threshold) + ".txt", 'w') output_site_infor = open(cancerlist[i] + ".Site.INFO.txt", 'w') output_site_infor.write(header) sample_header1 = input_tumor.readline().split() del sample_header1[0]; del sample_header1[0] input_tumor.readline() tumor_sample_length = len(sample_header1) sample_header2 = input_normal.readline().split() del sample_header2[0]; del sample_header2[0] input_normal.readline() normal_sample_length = len(sample_header2) for j in range(probe_site) : if(j % 10000 == 0) : print(cancerlist[i] + " %d completed." % j) tumor_line = input_tumor.readline().split() normal_line = input_normal.readline().split() site_id1 = tumor_line.pop(0) site_id2 = normal_line.pop(0) new_length1 = tumor_sample_length new_length2 = normal_sample_length tumor_beta = [] normal_beta = [] for k in range(tumor_sample_length) : if(tumor_line[k] == "NA") : new_length1 -= 1 continue tumor_beta.append(float(tumor_line[k])) for k in range(normal_sample_length) : if(normal_line[k] == "NA") : new_length2 -= 1 continue normal_beta.append(float(normal_line[k])) if(new_length1 == 0 or new_length2 == 0) : continue tumor_mean = mean(tumor_beta) normal_mean = mean(normal_beta) tumor_median = median(tumor_beta) normal_median = median(normal_beta) tumor_max = max(tumor_beta) normal_max = max(normal_beta) tumor_min = min(tumor_beta) normal_min = min(normal_beta) output_site_infor.write("%s\t%f\t%f\t%f\t%f\t%f\t%f\t%f\t%f\t%f\t%f\t%f\t%f\t%d\t%d\n" % (site_id1, tumor_mean, normal_mean, abs(tumor_mean - normal_mean), tumor_median, normal_median, abs(tumor_median - normal_median), tumor_max, normal_max, abs(tumor_max - normal_max), tumor_min, normal_min, abs(tumor_min - normal_min), new_length1, new_length2)) <file_sep>/Betavalue Count In Segment/Cutoff_0.025.py #input_file = open("Betavalue_Array_Sorted.csv", 'r') input_file = open("Betavalue_Array_CountSort.csv", 'r') threshold_array = [] count_array = [] last_index = [] def MakeThresholdArray() : global threshold_array, count_array, last_index gap = [0.025] for i in range(0, len(gap)) : cutoff = 0.0 threshold_array.append([]) count_array.append([]) last_index.append(0) count = 0 while(cutoff <= 1.0) : threshold_array[i].append(cutoff) count_array[i].append(0) count += 1 cutoff = gap[i] * float(count) return def Process() : line = input_file.readline() debug_count = 1 while(len(line) > 1) : # line = line.replace('"', '') # line = line.replace('q', '') value = float(line) for j in range(0, len(threshold_array)) : for k in range(last_index[j], len(threshold_array[j]) - 1) : if(value < threshold_array[j][k + 1]) : count_array[j][k] += 1 last_index[j] = k break line = input_file.readline() debug_count += 1 if(debug_count % 10000 == 0) : print(str(debug_count) + " completed.") for j in range(0, len(threshold_array)) : output_file = open(str(threshold_array[j][1]) + "cutoff.count_array.txt", 'w') for k in range(0, len(threshold_array[j]) - 1) : printline = str(threshold_array[j][k]) + " : " + str(count_array[j][k]) + "\n" output_file.write(printline) return MakeThresholdArray() Process() <file_sep>/Correlation Between CytAct and Summation - SimpleCutoff/ManWhitneyTest/WhitneyURankSumTest_PanCancer.py from scipy.stats import mannwhitneyu #cancerlist = ["ACC", "BLCA", "BRCA", "CESC", "CHOL", "COAD", "DLBC", "ESCA", "GBM", "HNSC", "KICH", "KIRC", "KIRP", "LGG", "LIHC", "LUAD", "LUSC", "MESO", "OV", "PAAD", "PCPG", "PRAD", "READ", "SARC", "SKCM", "STAD", "TGCT", "THCA", "THYM", "UCEC", "UCS", "UVM"] cancerlist = ["PANCANCER"] input_file1 = [] input_file2 = [] output_file = [] probe_count = 485577 header = "site\tStatistics\tP-value\n" cancer_number = len(cancerlist) for i in range(0, cancer_number) : input_file1.append(open(cancerlist[i] + ".humanmethylation450.tumor.txt", 'r')) input_file1[i].readline() input_file1[i].readline() input_file2.append(open(cancerlist[i] + ".humanmethylation450.normal.txt", 'r')) normalsample = input_file2[i].readline().split() input_file2[i].readline() output_file = [] pvalue_threshold = [0.05, 0.005, 0.0005, 0.0000001] for i in range(len(pvalue_threshold)) : output_file.append(open(str(pvalue_threshold[i]) + ".PANCANCER.CpGsites.By.ManWhitneyTest.txt", 'w')) output_file[i].write(header) for i in range(0, probe_count) : tumor_value = [] normal_value = [] site_id1 = "" site_id2 = "" for j in range(0, cancer_number) : line1 = input_file1[j].readline().split() line2 = input_file2[j].readline().split() site_id1 = line1.pop(0) for value in line1 : if(value != "NA") : tumor_value.append(float(value)) site_id2 = line2.pop(0) for value in line2 : if(value != "NA") : normal_value.append(float(value)) if(len(tumor_value) == 0 or len(normal_value) == 0) : continue manwhitney_pair = mannwhitneyu(tumor_value, normal_value) printline = site_id1 + "\t%f\t%f\n" % (manwhitney_pair[0], manwhitney_pair[1]) for j in range(len(pvalue_threshold)) : if(manwhitney_pair[1] < pvalue_threshold[j]) : output_file[j].write(printline) if(i % 10000 == 0) : print(str(i) + " completed") <file_sep>/Correlation Between CytAct and Summation - SimpleCutoff/Ttest/Random.Table.Correlation.py import random cancerlist = ["PANCANCER"] p_threshold = [0.05, 0.005, 0.0005, 0.0000001] percentage = [0.01, 0.025, 0.05, 0.1, 0.125, 0.15, 0.175, 0.2, 0.225, 0.25, 0.275, 0.3] CpGsites_number = [] test_type = "TTest" sample_number = 8357 execution_number = 10000 for i in range(len(cancerlist)) : for j in range(len(p_threshold)) : input_cpgsites = open(str(p_threshold[j]) + "." + cancerlist[i] + ".CpGsites.By." + test_type + ".txt", 'r') input_cpgsites.readline() # junk line lines1 = input_cpgsites.read().splitlines() CpGsites_number.append(len(lines1)) for k in range(len(percentage)) : input_samples = open("Pvalue." + str(p_threshold[j]) + ".Percentage." + str(percentage[k]) + "." + cancerlist[i] + "." + "Positive.MeaningfulCpGsites.By.Ttest_Binarization.Summation.By.Tstat.txt", 'r') lines2 = input_samples.read().splitlines() sample_id = [] total_check = 0 for line in lines2 : line = line.split() sample_id.append(line[0]) total_check += int(line[1]) total = CpGsites_number[j] * sample_number print("%s %s, #CpGsites : %s, #Samples : %s, #Total : %s" % (str(p_threshold[j]), str(percentage[k]), str(CpGsites_number[j]), str(len(sample_id)), str(total_check))) print(total) for iteration in range(execution_number) : random_summation = [] total_random = 0 for l in range(sample_number) : random_temp = random.randrange(0, CpGsites_number[j] + 1) if(total_random + random_temp > total) : random_temp = random.randrange(0, total - total_random + 1) elif(total_random + random_temp == total) : random_temp = 0 total_random += random_temp random_summation.append(random_temp) random.shuffle(random_summation) # output.write(random_summation) <file_sep>/Validation - Random Correlation/Merge.Random.Correlation.Values.py division_part = 20 execution_number = 500 cancerlist = ["PANCANCER"] for k in range(len(cancerlist)) : output_file = open("RANDOM.MERGE." + cancerlist[k] + ".Correlation.Values." + str(execution_number * division_part) + ".Times.txt", 'w') for i in range(division_part) : number = "" if(i < 9) : number = "0" + str(i + 1) else : number = str(i + 1) input_file = open("RANDOM." + number + "." + cancerlist[k] + ".Correlation.Values." + str(execution_number) + ".Times.txt", 'r') lines = input_file.read().splitlines() for line in lines : output_file.write(line + "\n") <file_sep>/Filtering Invalid Samples/ValidSampleCountsOfEachCpGsite.py #cancerlist = ["ACC", "BLCA", "BRCA", "CESC", "CHOL", "COAD", "DLBC", "ESCA", "GBM", "HNSC", "KICH", "KIRC", "KIRP", "LGG", "LIHC", "LUAD", "LUSC", "MESO", "OV", "PAAD", "PCPG", "PRAD", "READ", "SARC", "SKCM", "STAD", "TGCT", "THCA", "THYM", "UCEC", "UCS", "UVM", "PANCANCER"] cancerlist = ["PANCANCER"] probe_count = 485577 for i in range(0, len(cancerlist)) : input_tumor = open(cancerlist[i] + ".humanmethylation450.tumor.txt", 'r') sample_header1 = input_tumor.readline().split() # sample line input_tumor.readline() # junk line output_file = open(cancerlist[i] + ".Valid.Sample.Counts.Of.Each.CpGsite.txt", 'w') for j in range(probe_count) : line1 = input_tumor.readline().split() site_id = line1.pop(0) new_length = 0 for data in line1 : if(data == "NA") : continue new_length += 1 output_file.write(site_id + "\t%s\n" % str(new_length)) <file_sep>/GeneMethyl Package/README.md GeneMethyl 1.0.0 Written by <NAME>, Seoul National University, Applied Biology and Chemistry, <EMAIL>. A. Goal DNA methylation, adding methyl group to 5' carbon of a cytosine pyrimidine ring, is considered as a important biomarker for some diseases. And CpG sites, regions of a single DNA strand where a cytosine nucleotide is followed by a guanine nucleotide, are known as easily methylated in human body. Methylation of CpG sites can affect specific genes' expression levels and in some diseases like cancer, CpG sites' hypermethylation silence tumor suppressor genes' activities and hypomethylation promote retrotransposons' activities like LINE-1 to make chromosome instability. So, numerous clinical researches about methylation of CpG sites were already completed and still be underway. To make easily analyze relationship between DNA methylation status and target genes' activities, I made the packaged named GeneMethyl. I hope this package will contribute to many researches. And I plan to add more functions to solve more complicated problems. B. Input data format Required Files : DNA methylation data, RNAseq data(raw counts or normalized by RSEM) of samples about a target disease. 1. File name : [TargetDiseaseName].DNA_methylation_450K.tsv (Separated by tab) Column : Each sample Row : Each CpG site Missing values are denoted as nothing. (Just separted by tab) We recognize sample length up to 12. (excluding '-', or '_') Illumina's Infinium HumanMethylation450K Beadchip made us easily get DNA methylation data for selected CpG sites about 480,000. So, this package use beta-value data table generated from HumanMethylation450K. And the format of a DNA methylation dataset is the same with a TCGA's pan-cancer atlas methylation dataset. 2. File name : [TargetDiseaseName].PANCANCER.RNAseq.tsv (Separated by tab) Column : Each sample Row : Each gene Missing values are denoted as nothing. (Just separted by tab) We recognize sample length up to 12. (excluding '-', or '_') Your target gene expression levels are automatically calculated from RNAseq raw counts data or normalized data by RSEM package. And the format of a RNAseq dataset is the same with a TCGA's pan-cancer atlas RNAseq dataset. C. Package functions 1. BetavalueDistribution (1) BetavalueDistribution.Draw("TargetDiseaseName", Cutoff, WhetherHistogram) : Drawing beta-value distribution by density plot based on histogram. Input parameters : "TargetDiseaseName" : Target disease name Cutoff : Cutoff must be in [0, 1] and sections are divided by this cutoff. ex) Cutoff : 0.1 -> Your Sections : 0~0.1, 0.1~0.2, 0.2~0.3, 0.3~0.4, 0.4~0.5, 0.5~0.6, 0.6~0.7, 0.7~0.8, 0.8~0.9, 0.9~1.0 WhetherHistogram : True or False. If you choose True, histogram of beta-values divided by cutoff is also shown. Description : DNA methylation data is too large to easily handle, so receiving whole DNA methylation data and drawing density plot at once is not effective from the perspective of memory. So, I received DNA methylation data line by line and approximated DNA methylation beta-values into several sections divided by specific cutoff. (You can choose cutoff) Then by using histogram, I made density plot of beta-values' distribution. Output file : /Result/DistributionPlot/[TargetDiseaseName].Betavalue.Distribution.Plot.pdf 2. SimpleCutoff (1) SimpleCutoff.TargetGeneActivity("TargetDiseaseName", [TargetGenesList]) : Calculating target genes' activities. Input parameters : "TargetDiseaseName" : Target disease name [TargetGenesList] : Target genes' list. You can choose multiple genes. Description : You can simply calculate target genes' activities. I decided representative target genes' activity by using logarithm. base : a number of gene anti-logarithm : geometric mean of target genes' RNAseq data added to pseudocount(1). cf) I added whole RNAseq data to pseudocount(1) to prevent from minus value of representative target genes' activity. Output file : /Result/SimpleCutoff/[TargetDiseaseName].TargetGeneActivity.txt (2) SimpleCutoff.View_Correlation_AND_ScatterPlot("TargetDiseaseName", [TargetGenesList], [Cutoff], Type, WhetherFoldChange) : Calculating sperman's correlation between representative target genes' activities and summations of whole samples. Drawing scatter plots of this correlation. Input parameters : "TargetDiseaseName" : Target disease name [TargetGenesList] : Target genes' list. You can choose multiple genes. Cutoff, Type : Calculating summations by using Cutoff depending on Type. Type : "Lower", "Higher", "Both", "All" "Lower" : If beta-value is lower than cutoff, sample's beta-value is converted into 1. Or, into 0. Then summate this values to each sample. -> You can get the number of beta-values lower than cutoff to each sample. (in [0, cutoff]) "Higher" : If beta-value is higher than cutoff, sample's beta-value is converted into 1. Or, into 0. Then summate this values to each sample. -> You can get the number of beta-values higher than cutoff to each sample. (in [cutoff, 1]) "Both" : If beta-value is lower than cutoff/2 or higher than 1 - cutoff/2, sample's beta-value is converted into 1. Or, into 0. Then summate this values to each sample. -> You can get the number of beta-values in [0, cutoff/2] or [1 - cutoff/2, 1] to each sample. "All" : Doing all of theses types respectively. Cutoff : Cutoff must be in [0, 1] and it determine the section. You can choose multiple cutoffes. WhetherFoldChange : Calculating the fold change Fold change = Mean or Median of the representative target genes' activity of samples included in the section by cutoff / Mean or Median of the representative target genes' activity of samples NOT included in the section by cutoff Output file : /Result/SimpleCutoff/FC_CpGsites/WholeSites.Cutoff.[Cutoff].[TargetDiseaseName].[Type].FC.CpGsites.txt /Result/SimpleCutoff/Summation/WholeSites.Cutoff.[Cutoff].[TargetDiseaseName].[Type].Binarization.Summation.txt /Result/SimpleCutoff/Correlation/WholeSites.[TargetDiseaseName].[Type].Correlation.Summation.And.TargetGeneActivity.txt -> including whole cutoffes to compare easily /Result/SimpleCutoff/Correlation/WholeSites.[TargetDiseaseName].CompareAll.Correlation.Summation.And.TargetGeneActivity.txt -> only emerging if Type is All to compare easily /Result/SimpleCutoff/ScatterPlot/WholeSites.Cutoff.[Cutoff].[TargetDiseaseName].[Type].ScatterPlot.pdf 3. TopPercentageCutoff (1) TopPercentageCutoff.TargetGeneActivity("TargetDiseaseName", [TargetGenesList]) : Calculating target genes' activities. Input parameters : "TargetDiseaseName" : Target disease name [TargetGenesList] : Target genes' list. You can choose multiple genes. Description : You can simply calculate target genes' activities. I decided representative target genes' activity by using logarithm. base : a number of gene anti-logarithm : geometric mean of target genes' RNAseq data added to pseudocount(1). cf) I added whole RNAseq data to pseudocount(1) to prevent from minus value of representative target genes' activity. Output file : /Result/TopNpercentageCutoff/[TargetDiseaseName].TargetGeneActivity.txt (2) TopPercentageCutoff.View_Correlation_AND_ScatterPlot("TargetDiseaseName", [TargetGenesList], [Percentage], Type, WhetherMeanMethod, WhetherFoldChange) : Calculating sperman's correlation between representative target genes' activities and summations of whole samples. Drawing scatter plots of this correlation. Background : Before explaining TopNpercentageCutoff, we have to determine what percentage means in this method. In some diseases like cancer, beta-value distribution of each CpG site is look like roughly 2-peaked graph. So, I roughly classified beta-value distribution of each CpG site as 2 categories, left-skewed and right-skewed. To determine skewedness of CpG sites, we compare median of each CpG site with mean or 0.5( = an exact half of [0, 1]). If you want to use 'mean method', you need to make WhetherMeanMethod True. If you want to use '0.5 method', you need to make WhetherMeanMethod False. After determining skewedness, we can classify types as "Positive", "Negative", "Both". If type is "Positive" and CpG site's beta-value distribution is right-skewed, top N% of sample beta-value is converted into 1. Or, into 0. If type is "Positive" and CpG site's beta-value distribution is left-skewed, bottom N% of sample beta-value is converted into 1. Or into 0. Thus, "Positive" type means we count the number of beta-values following the tendency of each CpG site's distribution for each sample. If type is "Negative" and CpG site's beta-value distribution is right-skewed, bottom N% of sample beta-value is converted into 1. Or, into 0. If type is "Negative" and CpG site's beta-value distribution is left-skewed, top N% of sample beta-value is converted into 1. Or into 0. Thus, "Negative" type means we count the number of beta-values not following the tendency of each CpG site's distribution for each sample. If type is "Both", regardless of CpG site's skewedness top N/2% and bottom N/2% of sample beta-value is converted into 1. Or, into 0. Thus, "Both" type means we count the number of strongly methylated or demethylated CpG sites for each sample. By using this method, we can simply count the number of hypermethylated or hypomethylated CpG sites for the specific situation. To explain this, let's take an example of cancer. Globally, CpG sites are hypomethylated to increase chromosomal instability, by expressing retrotranspons(just one example). But, CpG sites are hypermethylated near the promoter regions to silence life-critical genes. So, If we use TopNpercentageCutoff Positive type method, we can count the number of these hypermethylated or hypomethylated CpG sites. Then, we can correlate this values with the representative target genes' activity. In short, we can analyze the epigenetic impact of diseases. Input parameters : "TargetDiseaseName" : Target disease name [TargetGenesList] : Target genes' list. You can choose multiple genes. Percentage, Type : Calculating summations by using Percentage depending on Type. Type : "Positive", "Negative", "Both", "All" Percentage : What percentage do you want? WhetherFoldChange : Calculating the fold change Fold change = Mean or Median of the representative target genes' activity of samples included in the section by percentage / Mean or Median of the representative target genes' activity of samples NOT included in the section by percentage. WhetherMeanMethod : Choosing the method of determining skewedness Output file : /Result/TopPercentageCutoff/FC_CpGsites/WholeSites.Percentage.[Percentage].[TargetDiseaseName].[Type].FC.CpGsites.txt /Result/TopPercentageCutoff/Summation/WholeSites.Percentage.[Percentage].[TargetDiseaseName].[Type].Binarization.Summation.txt /Result/TopPercentageCutoff/Skewed/WholeSites.[TargetDiseaseName].Left.Skewed.CpGsites.txt /Result/TopPercentageCutoff/Skewed/WholeSites.[TargetDiseaseName].Right.Skewed.CpGsites.txt /Result/TopPercentageCutoff/Correlation/WholeSites.[TargetDiseaseName].[Type].Correlation.Summation.And.TargetGeneActivity.txt -> including whole percentages to compare easily /Result/TopPercentageCutoff/Correlation/WholeSites.[TargetDiseaseName].CompareAll.Correlation.Summation.And.TargetGeneActivity.txt -> only emerging if Type is All to compare easily /Result/TopPercentageCutoff/ScatterPlot/WholeSites.Percentage.[Percentage].[TargetDiseaseName].[Type].ScatterPlot.pdf D. Usage Example from GeneMethyl import * BetavalueDistribution.DrawDensityPlot("PANCANCER", 0.001, True) SimpleCutoff.TargetGeneActivity("PANCANCER", ["GZMA", "PRF1"]) SimpleCutoff.View_Correlation_AND_ScatterPlot("PANCANCER", ["GZMA", "PRF1"], [0.1, 0.2], "All", True) cf) Even before not calling TargetGeneActivity, it will automatically executed in this function. TopPercentageCutoff.TargetGeneActivity("PANCANCER", ["GZMA", "PRF1"]) TopPercentageCutoff.View_Correlation_AND_ScatterPlot("PANCANCER", ["GZMA", "PRF1"], [0.05, 0.1, 0.15, 0.2], "All", False, True) cf) Even before not calling TargetGeneActivity, it will automatically executed in this function. <file_sep>/GeneMethyl Package/setup.py import setuptools with open("README.md", "r") as fh: long_description = fh.read() setuptools.setup( name = "GeneMethyl", version = "1.0.0", author = "<NAME>", author_email = "<EMAIL>", description = "By this package, you can simply calculate the epigenetic result caused by a specific disease and reveal the relationship between the epigenetic effect and specific genes' expressions. For numerous samples of a specific disease, you can get a correlation value between gene expression levels and summations calculated from DNA methylation beta-values. Additionally you can simply know beta-value distribution by density plot.", long_description = long_description, long_description_content_type = "text/markdown", url = "https://github.com/JoonHyeongPark/GeneMethyl", packages = setuptools.find_packages(), ) <file_sep>/Correlation Between CytAct and Summation - SimpleCutoff/Ttest/MeaningfulCpGsitesTtest.py from scipy import stats cancerlist = ["ACC", "BLCA", "BRCA", "CESC", "CHOL", "COAD", "DLBC", "ESCA", "GBM", "HNSC", "KICH", "KIRC", "KIRP", "LGG", "LIHC", "LUAD", "LUSC", "MESO", "OV", "PAAD", "PCPG", "PRAD", "READ", "SARC", "SKCM", "STAD", "TGCT", "THCA", "THYM", "UCEC", "UCS", "UVM"] #cancerlist = ["PANCANCER"] input_file1 = [] input_file2 = [] probe_count = 485577 p_threshold = [0.0000001] #p_threshold = [0.05, 0.005, 0.0005, 0.0000001] header = "site\tStatistics\tP-value\n" for i in range(0, len(cancerlist)) : input_file1.append(open(cancerlist[i] + ".humanmethylation450.tumor.txt", 'r')) input_file1[i].readline() input_file1[i].readline() input_file2.append(open(cancerlist[i] + ".humanmethylation450.normal.txt", 'r')) normalsample = input_file2[i].readline().split() input_file2[i].readline() output_file = [] for j in range(len(p_threshold)) : output_file.append(open(str(p_threshold[j]) + "." + cancerlist[i] + ".CpGsites.By.TTest.txt", 'w')) output_file[j].write(header) if(len(normalsample) < 12) : print(cancerlist[i] + " has only %d normal sample." % (len(normalsample) - 2)) continue for j in range(0, probe_count) : line1 = input_file1[i].readline().split() line2 = input_file2[i].readline().split() tumor_value = [] normal_value = [] site_id1 = line1.pop(0) for value in line1 : if(value != "NA") : tumor_value.append(float(value)) site_id2 = line2.pop(0) for value in line2 : if(value != "NA") : normal_value.append(float(value)) equal_variance = stats.levene(tumor_value, normal_value) if(equal_variance >= 0.05) : ttest_pair = stats.ttest_ind(tumor_value, normal_value, equal_var = True) else : ttest_pair = stats.ttest_ind(tumor_value, normal_value, equal_var = False) for k in range(len(p_threshold)) : if(ttest_pair[1] < p_threshold[k]) : output_file[k].write(site_id1 + "\t%f\t%f\n" % (ttest_pair[0], ttest_pair[1])) if(j % 10000 == 0) : print(cancerlist[i] + " %d completed." % j) print(cancerlist[i] + " completed.") input_file1[i].close() input_file2[i].close() <file_sep>/Validation - Random Correlation/Random.Table.Correlation.py cancerlist = ["PANCANCER"] p_threshold = [0.05, 0.005, 0.0005, 0.0000001] percentage = [0.01, 0.025, 0.05, 0.1, 0.125, 0.15, 0.175, 0.2, 0.225, 0.25, 0.275, 0.3] input_invalid_samples = open("PANCANCER.Invalid.Samples.By.CytAct.txt", 'r') invalid_samples = input_invalid_samples.read().splitlines() sample_id = [] cytoact = [] def GetSample() : cytoact_file = open("TCGA_methylation_cowork_1.txt", 'r') header = cytoact_file.readline().split() # getting header id_posit = header.index("id") # sample ID positioning cytoact_posit = header.index("CytAct") # CytAct positioning cytodata = cytoact_file.readlines() # read data table cytoact_file.close() count = 0 global sample_id global cytoact for line in cytodata : line = line.split() sample_id.append(line[id_posit].replace('_', '')) # sample ID extraction cytoact.append(float(line[cytoact_posit])) # CytAct extraction count += 1 return count # Sample number return GetSample() for i in range(len(cancerlist)) : for j in range(len(p_threshold)) : input_file = open(str(p_threshold[j]) + "." + cancerlist[i] + ".ValidCpGsites.Of.Each.Sample.txt", 'r') probability = [] cytact = [] lines = input_file.readlines() total = 0 for line in lines : line = line.split() sample = line[0][:15].replace('-', '') if(sample in sample_id) : probability.append(int(line[1])) cytact.append(cytoact[sample_id.index(sample)]) total += probability[-1] probability = map(lambda x : float(probability[x] / total), range(len(probability))) print(probability) print(cytact) <file_sep>/PCDHG Gene Analysis/Step4.Correlation.2.Betavalue.Expression.Score.PCDHG.py import scipy.stats as stat target = "PCDHG" file_path = "/home/kwangsookim_lab/joonhyeong_park/Practice/" cancerlist = ["PANCANCER"] for i in range(len(cancerlist)) : input_tumor = open(file_path + cancerlist[i] + "." + target + ".Score.Matching.2.Of.Each.Sample.tumor.txt", 'r') input_normal = open(file_path + cancerlist[i] + "." + target + ".Score.Matching.2.Of.Each.Sample.Normal.txt", 'r') input_tumor.readline() input_normal.readline() tumor_methylationburden_score = [] tumor_expression_score = [] while(True) : line = input_tumor.readline().split() if(len(line) == 0) : break tumor_methylationburden_score.append(float(line[1])) tumor_expression_score.append(float(line[2])) normal_methylationburden_score = [] normal_expression_score = [] while(True) : line = input_normal.readline().split() if(len(line) == 0) : break normal_methylationburden_score.append(float(line[1])) normal_expression_score.append(float(line[2])) print(stat.spearmanr(tumor_methylationburden_score, tumor_expression_score)) print(stat.spearmanr(normal_methylationburden_score, normal_expression_score)) <file_sep>/CytAct FC value/0.8.Threshold.FC.PvalueByMannWhitney.PAN.py import numpy from scipy.stats import mannwhitneyu cancerlist = ["PANCANCER"] input_file1 = [] output_file1 = [] probe_count = 485577 threshold = 0.8 sample_id = [] cytoact = [] sample_index= [] def GetSample() : cytoact_file = open("TCGA_methylation_cowork_1.txt", 'r') header = cytoact_file.readline().split() # getting header id_posit = header.index("id") # sample ID positioning cytoact_posit = header.index("CytAct") # CytAct positioning cytodata = cytoact_file.readlines() # read data table cytoact_file.close() count = 0 global sample_id global cytoact for line in cytodata : line = line.split() sample_id.append(line[id_posit].replace('_', '')) # sample ID extraction cytoact.append(float(line[cytoact_posit])) # CytAct extraction count += 1 return count # Sample number return sample_number = GetSample() header = "CpGsite\tFC(high_mean/low_mean)\tFC(high_median/low_median)\tP-value\n" output_extreme = [] for i in range(0, len(cancerlist)) : input_file1.append(open(cancerlist[i] + ".humanmethylation450.tumor.txt", 'r')) output_file1.append(open(str(threshold) + ".Cutoff.FC.Pvalue." + cancerlist[i] + ".txt", 'w')) output_extreme.append(open(str(threshold) + ".Cutoff.Extreme.Sites." + cancerlist[i] + ".txt", 'w')) output_file1[i].write(header) sample_header1 = input_file1[i].readline().split() input_file1[i].readline().split() del sample_header1[0]; del sample_header1[0] sample_index = [] length = len(sample_header1) for j in range(0, length) : sample_header1[j] = sample_header1[j][:15].replace('-', '') if(sample_header1[j] in sample_id) : sample_index.append(sample_id.index(sample_header1[j])) else : sample_index.append(-1) for j in range(0, probe_count) : line1 = input_file1[i].readline().split() site_id = line1.pop(0) betavalue_low = []; betavalue_high = [] cytoact_low = []; cytoact_high = [] for k in range(0, length) : cancer_value = line1[k] if(cancer_value == "NA" or sample_index[k] == -1) : continue if(float(cancer_value) <= threshold) : betavalue_low.append(float(cancer_value)) cytoact_low.append(cytoact[sample_index[k]]) else : betavalue_high.append(float(cancer_value)) cytoact_high.append(cytoact[sample_index[k]]) high_mean = numpy.mean(cytoact_high) low_mean = numpy.mean(cytoact_low) high_median = numpy.median(cytoact_high) low_median = numpy.median(cytoact_low) if(len(cytoact_high) == 0 and len(cytoact_low) != 0) : printline1 = site_id + "\tWhole<=%s\n" % str(threshold) printline2 = site_id + "\t<=%s\n" % str(threshold) output_file1[i].write(printline1) output_extreme[i].write(printline2) continue if(len(cytoact_high) != 0 and len(cytoact_low) == 0) : printline1 = site_id + "\tWhole>%s\n" % str(threshold) printline2 = site_id + "\t>%s\n" % str(threshold) output_file1[i].write(printline1) output_extreme[i].write(printline2) continue if(len(cytoact_high) == 0 and len(cytoact_low) == 0) : printline1 = site_id + "\tNoSamples\n" output_file1[i].write(printline1) continue FC1 = high_mean / low_mean FC2 = high_median / low_median manwhitney_pair = mannwhitneyu(cytoact_high, cytoact_low) printline = site_id printline += "\t%s\t%s\t%s\n" % (str(FC1), str(FC2), str(manwhitney_pair[1])) output_file1[i].write(printline) if(j % 10000 == 0) : print(cancerlist[i] + " %d completed." % j) print(cancerlist[i] + " completed.") <file_sep>/Betavalue Count In Segment/Histogram.py import pandas as pd import matplotlib.pyplot as plt gap = [0.05, 0.025, 0.01, 0.001, 0.0001] def Draw(cutoff_gap) : input_file = open(str(cutoff_gap) + "cutoff.count_array.txt", 'r') input_table = input_file.readlines() histogram_vector = [] for line in input_table : histogram_vector.append(int(line.split()[2])) plt.hist(histogram_vector) plt.show() input_file.close() return Draw(0.05) <file_sep>/CpG site Correlation/Debug/Debug_Specific_CpGsite_Pancancer.py # -*- coding: utf-8 -*- from operator import itemgetter from scipy import stats import numpy as np betavalue_arr = [] cytoact_arr = [] probe_name = [] sample_id = [] ###################################################################################################################################################### def getting_cytoact() : cytoact_file = open("TCGA_methylation_cowork_1.txt", 'r') header = cytoact_file.readline().split() # header 읽기 id_posit = header.index("id") # sample ID positioning cytoact_posit = header.index("CytAct") # CytAct positioning cytodata = cytoact_file.readlines() # 데이터 테이블 통째로 읽어들임 cytoact_file.close() for line in cytodata : line = line.split() sample_id.append(line[id_posit].replace('_', '')) # sample ID 추출 (주형으로 사용할 것) sample_count = len(sample_id) for i in range(0, sample_count) : cytoact_arr.append(None) # CytAct value table 초기화 for line in cytodata : line = line.split() # 1 sample data를 분절해서 CytAct value 추출하기 위함 if(line[cytoact_posit] != "NA") : # CytAct value가 결측치가 아니라면 sample_posit = sample_id.index(line[id_posit].replace('_', '')) cytoact_arr[sample_posit] = float(line[cytoact_posit]) # 저장한다 return; ###################################################################################################################################################### getting_cytoact() print("CytAct_Completed") ###################################################################################################################################################### def reset_betavalue() : del betavalue_arr[:] for reset_x in range(0, probe_separation_number) : betavalue_arr.append({}) return ###################################################################################################################################################### output = open("debug2.txt", 'w') filename1 = open("PANCANCER.humanmethylation450.tumor.txt", 'r') # cancer name별로 파일명이 다름을 고려해줌 sample_name = filename1.readline().split(); filename1.readline() del sample_name[0]; del sample_name[0] now_target = filename1.readline().split() probe_name = now_target.pop(0) output.write("%s\n" % probe_name) column1 = [] column2 = [] for i in range(0, len(sample_name)) : sample_name[i] = sample_name[i][:15].replace('-', '') if(sample_name[i] in sample_id and now_target[i] != "NA") : posit = sample_id.index(sample_name[i]) printline = "%s\t%s\t%s\n" % (sample_name[i], now_target[i], cytoact_arr[posit]) column1.append(float(now_target[i])) column2.append(float(cytoact_arr[posit])) output.write(printline) cor = stats.spearmanr(column1, column2) lastprint = "%f\t%f\n" % (cor[0], cor[1]) output.write(lastprint) output.close() print("END") <file_sep>/CpG site Correlation/Debug/Debug_Specific_CpGSite_EachCancer.py # -*- coding: utf-8 -*- from scipy import stats #cancerlist = ["ACC", "BLCA", "BRCA", "CESC", "CHOL", "COAD", "DLBC", "ESCA", "ESCASTAD", "GBM", "HNSC", "KICH", "KIRC", "KIRP", "LGG", "LIHC", "LUAD", "LUSC", "MESO", "OV", "PAAD", "PCPG", "READ", "SARC", "SKCM", "STAD", "TGCT", "THCA", "THYM", "UCEC", "UCS", "UVM", "PRAD"] cancerlist = ["ACC", "BLCA", "BRCA", "CESC", "CHOL", "COAD", "ESCA", "ESCASTAD", "GBM", "HNSC", "KICH", "KIRC", "KIRP", "LIHC", "LUAD", "LUSC", "MESO", "PAAD", "PCPG", "READ", "SARC", "SKCM", "STAD", "TGCT", "THCA", "UCEC", "UCS", "UVM", "PRAD"] probe_count = 485577 target_site = "cg00066663" betavalue_vector = [] cytact_vector = [] sample_id = [] sample_table = {} check_table = {} input_file1 = [] input_cytact = open("TCGA_methylation_cowork_1.txt",'r') header = input_cytact.readline().split() indexing = header.index("CytAct") whole_table = input_cytact.readlines() for line in whole_table : line = line.split() ID = line[0].replace("_", "") sample_table[ID] = line[indexing] output = open("debug1.txt",'w') output.write("%s\n" % target_site) for i in range(0, len(cancerlist)) : input_file1.append(open(cancerlist[i] + ".humanmethylation450.tumor.txt", 'r')) sample_name = input_file1[i].readline().split() del sample_name[0]; del sample_name[0] for j in range(0, len(sample_name)) : sample_name[j] = sample_name[j][:15].replace("-", "") input_file1[i].readline() for j in range(0, probe_count) : line = input_file1[i].readline().split() comparison = line.pop(0) if(comparison == target_site) : for k in range(0, len(line)) : if(sample_name[k] in sample_table and line[k] != "NA" and sample_name[k] not in sample_id) : sample_id.append(sample_name[k]) betavalue_vector.append(float(line[k])) cytact_vector.append(float(sample_table[sample_name[k]])) break input_file1[i].close() for i in range(0, len(betavalue_vector)) : printline = "%s\t%s\t%s\n" % (sample_id[i], betavalue_vector[i], cytact_vector[i]) output.write(printline) cor = stats.spearmanr(betavalue_vector, cytact_vector) lastline = "%f\t%f\n" % (cor[0], cor[1]) output.write(lastline) output.close() print("END") <file_sep>/Correlation Between CytAct and Summation - SimpleCutoff/ManWhitneyTest/PANCANCER/PANCANCER.Binarization.Positive.Summation.ManWhitneyTest.py from operator import itemgetter #cancerlist = ["ACC", "BLCA", "BRCA", "CESC", "CHOL", "COAD", "DLBC", "ESCA", "GBM", "HNSC", "KICH", "KIRC", "KIRP", "LGG", "LIHC", "LUAD", "LUSC", "MESO", "OV", "PAAD", "PCPG", "PRAD", "READ", "SARC", "SKCM", "STAD", "TGCT", "THCA", "THYM", "UCEC", "UCS", "UVM", "PANCANCER"] cancerlist = ["PANCANCER"] input_file1 = [] input_file2 = [] probe_count = 485577 p_threshold = [0.05, 0.005, 0.0005, 0.0000001] sample_id = [] cytoact = [] sample_index = [] def GetSample() : cytoact_file = open("TCGA_methylation_cowork_1.txt", 'r') header = cytoact_file.readline().split() # getting header id_posit = header.index("id") # sample ID positioning cytoact_posit = header.index("CytAct") # CytAct positioning cytodata = cytoact_file.readlines() # read data table cytoact_file.close() count = 0 global sample_id global cytoact for line in cytodata : line = line.split() sample_id.append(line[id_posit].replace('_', '')) # sample ID extraction cytoact.append(float(line[cytoact_posit])) # CytAct extraction count += 1 return count # Sample number return sample_number = GetSample() percentage = [0.01, 0.025, 0.05, 0.1, 0.125, 0.15, 0.175, 0.2, 0.225, 0.25, 0.275, 0.3] for i in range(0, len(cancerlist)) : input_tumor = open(cancerlist[i] + ".humanmethylation450.tumor.txt", 'r') sample_header1 = input_tumor.readline().split() # sample line input_tumor.readline() # junk line ############################################################################################################################################################################ # make sample index table del sample_header1[0]; del sample_header1[0] sample_index = [] sample_binary_table = [] length = len(sample_header1) for j in range(0, length) : sample_header1[j] = sample_header1[j][:15].replace('-', '') if(sample_header1[j] in sample_id) : sample_index.append(sample_id.index(sample_header1[j])) else : sample_index.append(-1) for j in range(len(p_threshold)) : sample_binary_table.append([]) for k in range(len(percentage)) : sample_binary_table[j].append([]) for l in range(length) : sample_binary_table[j][k].append(0) ############################################################################################################################################################################ whole_skew = []; whole_skew_index = [] for j in range(len(p_threshold)) : input_file = open(str(p_threshold[j]) + "." + cancerlist[i] + ".CpGsites.By.ManWhitneyTest.txt", 'r') input_file.readline() # junk line whole_skew.append([]) lines = input_file.readlines() for line in lines : # Derivation of meaningful CpG sites line = line.split() whole_skew[j].append(line[0]) whole_skew[j].append("END_POINT") whole_skew_index.append(0) for j in range(probe_count) : line1 = input_tumor.readline().split() site_id = line1.pop(0) ############################################################################################################################################################################ # getting betavalue for each cpg site betavalue_row = [] new_length = length for k in range(0, length) : if(line1[k] == "NA") : new_length -= 1 continue betavalue_row.append([float(line1[k]), k]) betavalue_row.sort(key = itemgetter(0)) ############################################################################################################################################################################ if(new_length > 0) : for k in range(len(p_threshold)) : if(whole_skew[k][whole_skew_index[k]] == site_id) : betavalue_median = betavalue_row[new_length / 2][0] if(new_length % 2 == 0) : betavalue_median = (betavalue_median + betavalue_row[new_length / 2 - 1][0]) / 2 if(betavalue_median > 0.5) : for percentage_i in range(len(percentage)) : threshold = int(new_length * percentage[percentage_i]) for l in range(threshold) : sample_binary_table[k][percentage_i][betavalue_row[new_length - l - 1][1]] += 1 else : for percentage_i in range(len(percentage)) : threshold = int(new_length * percentage[percentage_i]) for l in range(threshold) : sample_binary_table[k][percentage_i][betavalue_row[l][1]] += 1 whole_skew_index[k] += 1 if(j % 10000 == 0) : print(cancerlist[i] + " %d completed." % j) for j in range(len(p_threshold)) : for k in range(len(percentage)) : output_file = open("Pvalue." + str(p_threshold[j]) + ".Percentage." + str(percentage[k]) + "." + cancerlist[i] + ".Positive.MeaningfulCpGsites.By.ManWhitneyTest_Binarization.Summation.txt", 'w') for l in range(length) : printline = sample_header1[l] + "\t%s\n" % str(sample_binary_table[j][k][l]) output_file.write(printline) <file_sep>/CpG site Correlation/Excluded Version/Remake_SimpleCode(Practice).py # -*- coding: utf-8 -*- from scipy import stats cancerlist = ["ACC", "BLCA", "BRCA", "CESC", "CHOL", "COAD", "DLBC", "ESCA", "GBM", "HNSC", "KICH", "KIRC", "KIRP", "LGG", "LIHC", "LUAD", "LUSC", "MESO", "OV", "PAAD", "PCPG", "READ", "SARC", "SKCM", "STAD", "TGCT", "THCA", "THYM", "UCEC", "UCS", "UVM", "PRAD"] probe_count = 485577 #probe_count = 10 pan_betavalue = [] pan_cytact = [] sample_id = [] sample_table = {} input_file1 = [] output_file_pearson = [] output_file_spearman = [] input_cytact = open("TCGA_methylation_cowork_1.txt",'r') header = input_cytact.readline().split() indexing = header.index("CytAct") whole_table = input_cytact.readlines() for line in whole_table : line = line.split() ID = line[0].replace("_", "") sample_table[ID] = line[indexing] sample_name = [] for i in range(0, len(cancerlist)) : input_file1.append(open(cancerlist[i] + ".humanmethylation450.tumor.txt", 'r')) output_file_pearson.append(open(cancerlist[i] + ".pearson.txt", 'w')) output_file_spearman.append(open(cancerlist[i] + ".spearman.txt", 'w')) sample_name.append(input_file1[i].readline().split()) del sample_name[i][0]; del sample_name[i][0] for j in range(0, len(sample_name[i])) : sample_name[i][j] = sample_name[i][j][:15].replace('-', "") input_file1[i].readline() output_whole_pearson = open("whole_pearson.txt", 'w') output_whole_spearman = open("whole_spearman.txt", 'w') output_pan_pearson = open("PAN.pearson.txt", 'w') output_pan_spearman = open("PAN.spearman.txt", 'w') for probe_iteration in range(0, probe_count) : pearson_printline = "" spearman_printline = "" probe_name = "" for i in range(0, len(cancerlist)) : line = input_file1[i].readline().split() probe_name = line.pop(0) betavalue_vector = [] cytact_vector = [] for k in range(0, len(line)) : if(sample_name[i][k] in sample_table and line[k] != "NA") : betavalue_vector.append(float(line[k])) cytact_vector.append(float(sample_table[sample_name[i][k]])) pan_betavalue.append(float(line[k])) pan_cytact.append(float(sample_table[sample_name[i][k]])) cor1 = stats.pearsonr(betavalue_vector, cytact_vector) cor2 = stats.spearmanr(betavalue_vector, cytact_vector) each_pearson = "%s\t%s\t" % (str(cor1[0]), str(cor1[1])) each_spearman = "%s\t%s\t" % (str(cor2[0]), str(cor2[1])) pearson_printline += "%s" % each_pearson spearman_printline += "%s" % each_spearman output_file_pearson[i].write(probe_name); output_file_pearson[i].write("\t"); output_file_pearson[i].write(each_pearson); output_file_pearson[i].write("\n") output_file_spearman[i].write(probe_name); output_file_spearman[i].write("\t"); output_file_spearman[i].write(each_spearman); output_file_spearman[i].write("\n") cor1 = stats.pearsonr(pan_betavalue, pan_cytact) cor2 = stats.spearmanr(pan_betavalue, pan_cytact) pan_pearson = probe_name + "\t%s\t%s\t" % (str(cor1[0]), str(cor1[1])) pan_spearman = probe_name + "\t%s\t%s\t" % (str(cor2[0]), str(cor2[1])) pearson_printline = pan_pearson + pearson_printline spearman_printlnie = pan_spearman + spearman_printline output_whole_pearson.write(pearson_printline); output_whole_pearson.write("\n") output_whole_spearman.write(spearman_printline); output_whole_spearman.write("\n") output_pan_pearson.write(pan_pearson); output_pan_pearson.write("\n") output_pan_spearman.write(pan_spearman); output_pan_spearman.write("\n") if(probe_iteration % 100 == 0) : print(probe_iteration) <file_sep>/CytAct FC value/Debug.SingleGroupCpGsites.PAN.py import numpy from scipy.stats import mannwhitneyu cancerlist = ["PANCANCER"] input_file1 = [] output_file1 = [] probe_count = 485577 threshold = 0.2 sample_id = [] cytoact = [] sample_index= [] def GetSample() : cytoact_file = open("TCGA_methylation_cowork_1.txt", 'r') header = cytoact_file.readline().split() # getting header id_posit = header.index("id") # sample ID positioning cytoact_posit = header.index("CytAct") # CytAct positioning cytodata = cytoact_file.readlines() # read data table cytoact_file.close() count = 0 global sample_id global cytoact for line in cytodata : line = line.split() sample_id.append(line[id_posit].replace('_', '')) # sample ID extraction cytoact.append(float(line[cytoact_posit])) # CytAct extraction count += 1 return count # Sample number return sample_number = GetSample() header = "CpGsite\tFC(high_mean/low_mean)\tFC(high_median/low_median)\tP-value\n" for i in range(0, len(cancerlist)) : input_file1.append(open(cancerlist[i] + ".humanmethylation450.tumor.txt", 'r')) output_file1.append(open("SingleGroupCpGsites.txt", 'w')) output_file1[i].write(header) sample_header1 = input_file1[i].readline().split() input_file1[i].readline().split() del sample_header1[0]; del sample_header1[0] sample_index = [] length = len(sample_header1) for j in range(0, length) : sample_header1[j] = sample_header1[j][:15].replace('-', '') if(sample_header1[j] in sample_id) : sample_index.append(sample_id.index(sample_header1[j])) else : sample_index.append(-1) for j in range(0, probe_count) : line1 = input_file1[i].readline().split() site_id = line1.pop(0) betavalue_low = []; betavalue_high = [] cytoact_low = []; cytoact_high = [] for k in range(0, length) : cancer_value = line1[k] if(cancer_value == "NA" or sample_index[k] == -1) : continue if(float(cancer_value) <= threshold) : betavalue_low.append(float(cancer_value)) cytoact_low.append(cytoact[sample_index[k]]) else : betavalue_high.append(float(cancer_value)) cytoact_high.append(cytoact[sample_index[k]]) if(len(cytoact_high) == 0 or len(cytoact_low) == 0) : print(site_id, len(cytoact_high), len(cytoact_low)) printline = site_id + "\t%s\t%s\n" % (str(len(cytoact_high)), str(len(cytoact_low))) output_file1[i].write(printline) if(j % 10000 == 0) : print(cancerlist[i] + " %d completed." % j) print(cancerlist[i] + " completed.") <file_sep>/Validation - Random Correlation/Correlation.Check.PANCANCER.Binarization.Random.Summation.py import random import scipy.stats as stat #cancerlist = ["ACC", "BLCA", "BRCA", "CESC", "CHOL", "COAD", "DLBC", "ESCA", "GBM", "HNSC", "KICH", "KIRC", "KIRP", "LGG", "LIHC", "LUAD", "LUSC", "MESO", "OV", "PAAD", "PCPG", "PRAD", "READ", "SARC", "SKCM", "STAD", "TGCT", "THCA", "THYM", "UCEC", "UCS", "UVM", "PANCANCER"] cancerlist = ["PANCANCER"] #probe_count = 485577 probe_count = 1000 percentage = 0.05 execution_number = 1000 sample_id = [] cytoact = [] ORDER = "RANDOM.01." def GetSample() : cytoact_file = open("TCGA_methylation_cowork_1.txt", 'r') header = cytoact_file.readline().split() # getting header id_posit = header.index("id") # sample ID positioning cytoact_posit = header.index("CytAct") # CytAct positioning cytodata = cytoact_file.readlines() # read data table cytoact_file.close() count = 0 global sample_id global cytoact for line in cytodata : line = line.split() sample_id.append(line[id_posit].replace('_', '')) # sample ID extraction cytoact.append(float(line[cytoact_posit])) # CytAct extraction count += 1 return count # Sample number return sample_number = GetSample() for i in range(0, len(cancerlist)) : input_tumor = open(cancerlist[i] + ".humanmethylation450.tumor.txt", 'r') sample_header1 = input_tumor.readline().split() # sample line del sample_header1[0]; del sample_header1[0] input_tumor.readline() # junk line length = len(sample_header1) for j in range(length) : sample_header1[j] = sample_header1[j][:15].replace('-', '') output_file = open(ORDER + cancerlist[i] + ".Correlation.Values." + str(execution_number) + ".Times.txt", 'w') sample_summation = [] temp_summation = [] for j in range(length) : if(sample_header1[j] not in sample_id) : temp_summation.append(-1) else : temp_summation.append(0) for iteration in range(execution_number) : sample_summation.append([]) for j in range(length) : sample_summation[iteration].append(temp_summation[j]) input_index = open(cancerlist[i] + ".Valid.Samples.For.Each.CpGsite.txt", 'r') for j in range(probe_count) : line = input_index.readline().split() site_id = line.pop(0) choosing_number = int(len(line) * percentage) line = map(int, line) for iteration in range(execution_number) : chosen_index = random.sample(line, choosing_number) for index in chosen_index : sample_summation[iteration][index] += 1 cor_cytoact = [] # valid cytact for j in range(length) : if(temp_summation[j] != -1) : cor_cytoact.append(cytoact[sample_id.index(sample_header1[j])]) for iteration in range(execution_number) : cor_summation = [] for j in range(length) : if(sample_summation[iteration][j] != -1) : cor_summation.append(sample_summation[iteration][j]) output_file.write(str(stat.spearmanr(cor_cytoact, cor_summation)[0]) + "\n") <file_sep>/Optimal Cutoff/Second_Version_Optimal_cutoff.py import operator import numpy probe_count = 485577 #probe_count = 5 cancerlist = ["KIRC", "BRCA", "THCA", "HNSC", "LIHC", "PRAD", "UCEC", "KIRP", "LUSC", "COAD", "LUAD"] input_file = [] output_file = [] sample_id = [] sample_table = {} input_cytact = open("TCGA_methylation_cowork_1.txt",'r') header = input_cytact.readline().split() indexing = header.index("CytAct") whole_table = input_cytact.readlines() for line in whole_table : line = line.split() ID = line[0].replace("_", "") sample_table[ID] = line[indexing] for k in range(0, len(cancerlist)) : input_file.append(open(cancerlist[k] + ".optimal_cutoff_data.txt", 'r')) output_file.append(open(cancerlist[k] + ".optimal_cutoff_result.txt", 'w')) sample_id.append(input_file[k].readline().split()) for i in range(0, len(sample_id[k]) / 2) : del sample_id[k][i + 1] sample_cutoff_count = [[0 for j in range(len(sample_id[i]))] for i in range(len(cancerlist))] for k in range(0, len(cancerlist)) : for i in range(0, probe_count) : line = input_file[k].readline().split() if(len(line) == 0) : print(probe_count) continue del line[0] beta_value = [] whole_tumor = 0; whole_normal = 0 valid_data = 0 for j in range(0, len(line) / 2) : if(line[j * 2] == "NA") : continue check = True if(line[j * 2 + 1] == "0") : check = False whole_normal += 1 beta_value.append([float(line[j * 2]), check, j]) valid_data += 1 if(valid_data == 0) : continue whole_tumor = valid_data - whole_normal beta_value = sorted(beta_value, key = operator.itemgetter(0)) count_tumor = []; count_normal = [] count_tumor.append(beta_value[0][1]) count_normal.append(1 - beta_value[0][1]) for j in range(1, valid_data) : count_tumor.append(count_tumor[j - 1] + beta_value[j][1]) count_normal.append(count_normal[j - 1] + (1 - beta_value[j][1])) cutoff = [] tumor_low = []; tumor_high = [] normal_low = []; normal_high = [] fpr = []; tpr = [] argmax_parameter = [] if(whole_normal == 0) : # no valid data in normal sample optimal_index = -1 optimal_threshold = beta_value[0][0] / 2 optimal_tpr = whole_tumor elif(whole_tumor == 0) : # no valid data in tumor sample optimal_index = valid_data optimal_threshold = beta_value[valid_data - 1] + 0.1 optimal_tpr = 0 else : for j in range(0, valid_data - 1) : cutoff.append(float(beta_value[j][0] + beta_value[j + 1][0]) / 2) tumor_low.append(float(count_tumor[j])) # normal -> tumor -> false negative tumor_high.append(float(whole_tumor - count_tumor[j])) # tumor -> tumor -> true positive normal_low.append(float(count_normal[j])) # normal -> normal -> true negative normal_high.append(float(whole_normal - count_normal[j])) # tumor -> normal -> false positive fpr.append(normal_high[j] / (normal_high[j] + normal_low[j])) tpr.append(tumor_high[j] / (tumor_high[j] + tumor_low[j])) argmax_parameter.append(tpr[j] - fpr[j]) optimal_index = numpy.argmax(argmax_parameter) optimal_threshold = cutoff[optimal_index] optimal_tpr = tumor_high[optimal_index] for j in range(optimal_index + 1, valid_data) : if(beta_value[j][1]) : sample_cutoff_count[k][beta_value[j][2]] += 1 for j in range(0, len(sample_id[k])) : if(sample_cutoff_count[k][j] == 0) : break printline = sample_id[k][j] printline += "\t%d\n" % sample_cutoff_count[k][j] output_file[k].write(printline) print(cancerlist[k] + " completed.") for k in range(0, len(cancerlist)) : input_file[k].close() output_file[k].close() <file_sep>/Validation - Random Correlation/Valid.Sample.Index.Table.py #cancerlist = ["ACC", "BLCA", "BRCA", "CESC", "CHOL", "COAD", "DLBC", "ESCA", "GBM", "HNSC", "KICH", "KIRC", "KIRP", "LGG", "LIHC", "LUAD", "LUSC", "MESO", "OV", "PAAD", "PCPG", "PRAD", "READ", "SARC", "SKCM", "STAD", "TGCT", "THCA", "THYM", "UCEC", "UCS", "UVM", "PANCANCER"] cancerlist = ["PANCANCER"] input_file1 = [] probe_count = 485577 sample_id = [] cytoact = [] sample_index = [] def GetSample() : cytoact_file = open("TCGA_methylation_cowork_1.txt", 'r') header = cytoact_file.readline().split() # getting header id_posit = header.index("id") # sample ID positioning cytoact_posit = header.index("CytAct") # CytAct positioning cytodata = cytoact_file.readlines() # read data table cytoact_file.close() count = 0 global sample_id global cytoact for line in cytodata : line = line.split() sample_id.append(line[id_posit].replace('_', '')) # sample ID extraction cytoact.append(float(line[cytoact_posit])) # CytAct extraction count += 1 return count # Sample number return sample_number = GetSample() for i in range(0, len(cancerlist)) : input_tumor = open(cancerlist[i] + ".humanmethylation450.tumor.txt", 'r') sample_header1 = input_tumor.readline().split() # sample line input_tumor.readline() # junk line ############################################################################################################################################################################ # make sample index table del sample_header1[0]; del sample_header1[0] sample_index = [] sample_binary_table = [] length = len(sample_header1) output_file = open(cancerlist[i] + ".Valid.Samples.For.Each.CpGsite.txt", 'w') for j in range(0, length) : sample_header1[j] = sample_header1[j][:15].replace('-', '') if(sample_header1[j] in sample_id) : sample_index.append(sample_id.index(sample_header1[j])) else : sample_index.append(-1) print("Default Completed.") ############################################################################################################################################################################ for j in range(probe_count) : line1 = input_tumor.readline().split() site_id = line1.pop(0) ############################################################################################################################################################################ site_index = [site_id] for k in range(0, length) : if(line1[k] == "NA" or sample_index[k] == -1) : continue site_index.append(str(k)) ############################################################################################################################################################################ output_file.write(reduce(lambda x, y : x + "\t" + y, site_index) + "\n") if(j % 10000 == 0) : print(cancerlist[i] + " %d completed." % j) <file_sep>/PCDHG Gene Analysis/Step2.Compare.Summarized.Information.Of.PCDHG.Expression.Tumor.VS.Normal.py target = "PCDHG" file_path = "/home/kwangsookim_lab/joonhyeong_park/Practice/" cancerlist = ["PANCANCER"] for i in range(len(cancerlist)) : input_tumor = open(file_path + cancerlist[i] + "." + target + ".Methylation.Pattern.tumor.txt", 'r') input_normal = open(file_path + cancerlist[i] + "." + target + ".Methylation.Pattern.normal.txt", 'r') input_expression = open(file_path + cancerlist[i] + "." + target + ".Gene.mRNAseq_RSEM_normalized.log2.32tumors.txt", "r") output_tumor_expression = open(file_path + cancerlist[i] + "." + target + ".Expression.Pattern.tumor.txt", 'w') output_normal_expression = open(file_path + cancerlist[i] + "." + target + ".Expression.Pattern.normal.txt", 'w') sample_tumor = input_tumor.readline().split()[2:] sample_normal = input_normal.readline().split()[2:] sample_tumor = list(map(lambda x : sample_tumor[x][:15].replace('-', ''), range(len(sample_tumor)))) sample_normal = list(map(lambda x : sample_normal[x][:15].replace('-', ''), range(len(sample_normal)))) sample_expression = input_expression.readline().split()[1:] tumor_expression_index = [] normal_expression_index = [] tumor_header = "Gene" normal_header = "Gene" for j in range(len(sample_expression)) : check_sample = sample_expression[j][:15].replace('-', '') if(check_sample in sample_tumor) : tumor_expression_index.append(sample_tumor.index(check_sample)) tumor_header += "\t" + sample_expression[j] else : tumor_expression_index.append(-1) if(check_sample in sample_normal) : normal_expression_index.append(sample_normal.index(check_sample)) normal_header += "\t" + sample_expression[j] else : normal_expression_index.append(-1) output_tumor_expression.write(tumor_header + "\n") output_normal_expression.write(normal_header + "\n") while(True) : expression_line = input_expression.readline().split() if(len(expression_line) == 0) : break gene_name = expression_line.pop(0) output_tumor_expression.write(gene_name) output_normal_expression.write(gene_name) for j in range(len(sample_expression)) : if(tumor_expression_index[j] != -1) : output_tumor_expression.write("\t" + expression_line[j]) if(normal_expression_index[j] != -1) : output_normal_expression.write("\t" + expression_line[j]) output_tumor_expression.write("\n") output_normal_expression.write("\n") <file_sep>/PCDHG Gene Analysis/Step1.Find.PCDHG.CpGsite.Information.py target = "PCDHG" file_path = "/home/kwangsookim_lab/joonhyeong_park/Practice" input_file = open(file_path + "/HumanMethylation450_15017482_v1-2.prc.txt", 'r') output_file = open(file_path + "/" + target + ".CpGsites.Information.txt", 'w') header = input_file.readline().split() gene_index = header.index("UCSC_RefGene_Name") output_file.write("\t".join(header) + "\n") while(True) : line = input_file.readline().split() if(len(line) == 0) : break gene_list = line[gene_index].split(';') check = False for gene in gene_list : if(target in gene) : check = True break if(check == True) : output_file.write("\t".join(line) + "\n") <file_sep>/PCDHG Gene Analysis/Step3.Score.Matching.To.Each.Sample.PCDHG.py import numpy target = "PCDHG" file_path = "/home/kwangsookim_lab/joonhyeong_park/Practice/" cancerlist = ["PANCANCER"] for i in range(len(cancerlist)) : input_tumor = open(file_path + cancerlist[i] + "." + target + ".Methylation.Pattern.tumor.txt", 'r') input_normal = open(file_path + cancerlist[i] + "." + target + ".Methylation.Pattern.normal.txt", 'r') output_tumor = open(file_path + cancerlist[i] + "." + target + ".Score.Matching.Of.Each.Sample.tumor.txt", 'w') output_normal = open(file_path + cancerlist[i] + "." + target + ".Score.Matching.Of.Each.Sample.Normal.txt", 'w') header = "Sample\tBetavalueMean\tExpressionMean\n" output_tumor.write(header) output_normal.write(header) sample_tumor = input_tumor.readline().split()[2:] sample_normal = input_normal.readline().split()[2:] original_sample_tumor = [] original_sample_normal = [] tumor_sample_information = [] normal_sample_information = [] for j in range(len(sample_tumor)) : original_sample_tumor.append(sample_tumor[j]) sample_tumor[j] = sample_tumor[j][:15].replace('-', '') tumor_sample_information.append({"Betavalue" : [], "Expression" : []}) for j in range(len(sample_normal)) : original_sample_normal.append(sample_normal[j]) sample_normal[j] = sample_normal[j][:15].replace('-','') normal_sample_information.append({"Betavalue" : [], "Expression" : []}) input_expression = open(file_path + cancerlist[i] + "." + target + ".Gene.mRNAseq_RSEM_normalized.log2.32tumors.txt", 'r') sample_expression = input_expression.readline().split()[1:] tumor_expression_index = [] normal_expression_index = [] for j in range(len(sample_expression)) : check_sample = sample_expression[j][:15].replace('-', '') if(check_sample in sample_tumor) : tumor_expression_index.append(sample_tumor.index(check_sample)) else : tumor_expression_index.append(-1) if(check_sample in sample_normal) : normal_expression_index.append(sample_normal.index(check_sample)) else : normal_expression_index.append(-1) while(True) : tumor_line = input_tumor.readline().split()[2:] normal_line = input_normal.readline().split()[2:] if(len(normal_line) == 0) : break for j in range(len(tumor_line)) : if(tumor_line[j] == "NA") : continue tumor_sample_information[j]["Betavalue"].append(float(tumor_line[j])) for j in range(len(normal_line)) : if(normal_line[j] == "NA") : continue normal_sample_information[j]["Betavalue"].append(float(normal_line[j])) while(True) : expression_line = input_expression.readline().split()[1:] if(len(expression_line) == 0) : break for j in range(len(expression_line)) : if(tumor_expression_index[j] != -1) : if(expression_line[j] == "NA") : tumor_sample_information[tumor_expression_index[j]]["Expression"].append(0) else : tumor_sample_information[tumor_expression_index[j]]["Expression"].append(float(expression_line[j])) if(normal_expression_index[j] != -1) : if(expression_line[j] == "NA") : normal_sample_information[normal_expression_index[j]]["Expression"].append(0) else : normal_sample_information[normal_expression_index[j]]["Expression"].append(float(expression_line[j])) for j in range(len(sample_tumor)) : if(len(tumor_sample_information[j]["Expression"]) != 0) : printline = original_sample_tumor[j] + "\t" + str(numpy.mean(tumor_sample_information[j]["Betavalue"])) + "\t" + str(tumor_sample_information[j]["Expression"][-1]) output_tumor.write(printline + "\n") for j in range(len(sample_normal)) : if(len(normal_sample_information[j]["Expression"]) != 0) : printline = original_sample_normal[j] + "\t" + str(numpy.mean(normal_sample_information[j]["Betavalue"])) + "\t" + str(normal_sample_information[j]["Expression"][-1]) output_normal.write(printline + "\n") <file_sep>/CpG site Correlation/Procedure/Optimization.py # -*- coding: utf-8 -*- #cancerlist = ["ACC", "BLCA", "BRCA", "CESC", "CHOL", "COAD", "DLBC", "ESCA", "ESCASTAD", "GBM", "HNSC", "KICH", "KIRC", "KIRP", "LGG", "LIHC", "LUAD", "LUSC", "MESO", "OV", "PAAD", "PCPG", "PRAD", "READ", "SARC", "SKCM", "STAD", "TGCT", "THCA", "THYM", "UCEC", "UCS", "UVM"] from operator import itemgetter #from scipy import stats #import numpy as np cancerlist = ["STAD"] betavalue_arr = [] cytoact_arr = [] probe_name = [] sample_id = [] def getting_cytoact() : cytoact_file = open("TCGA_methylation_cowork_1.txt", 'r') header = cytoact_file.readline().split() # header 읽기 id_posit = header.index("tissue.code") # sample ID 위치 인덱싱 cancer_posit= header.index("origin") # cancer type 위치 인덱싱 cytoact_posit = header.index("CytAct") # cytact 위치 인덱싱 cytodata = cytoact_file.readlines() # 관련 data를 통째로 읽어들임 cytoact_file.close() for line in cytodata : line = line.split() sample_id.append(line[id_posit].replace('.', '-')) # sample ID 추출 ############# betavalue 리스트 초기화 ################### #probe_count = 485577; sample_count = len(sample_id) probe_count = 485577; sample_count = len(sample_id) for reset_x in range(0, probe_count) : betavalue_arr.append([]) for reset_y in range(0, len(cancerlist) + 1) : betavalue_arr[reset_x].append([]) for reset_z in range(0, sample_count) : betavalue_arr[reset_x][reset_y].append([None, None]) ######################################################### for i in range(0, len(cancerlist)) : cytoact_arr.append([]) # 미리 cytoact dictionary에서 cancer type별 cytact data를 list 형태로 저장할 것을 명시 for j in range(0, sample_count) : cytoact_arr[i].append(None) cytoact_arr.append([]) for line in cytodata : line = line.split() # sample 별로 정리된 data를 읽어들이고 분절 if(line[cytoact_posit] != "NA") : #cancer_posit = cancerlist.index(line[cancer_posit].replace('_', '')) cancer_posit = cancerlist.index("STAD") sample_posit = sample_id.index(line[id_posit].replace('.', '-')) cytoact_arr[cancer_posit][sample_posit] = float(line[cytoact_posit]) for i in range(0, len(cancerlist)) : if(cytoact_arr[i] != None) : cytoact_arr[len(cancerlist)].extend(cytoact_arr[i]) # pan cancer에 데이터를 합쳐줌 return; getting_cytoact() first = True def getting_betavalue(normality_str, name, cancer_number, basic_posit) : filename = name + ".humanmethylation450." + normality_str + ".txt" # 각각의 cancer name에 대한 파일명을 문자열로 형성 single = open(filename, 'r') # 각각의 cancer에 대한 데이터 파일을 single_cancer라고 지정 sample_name = single.readline().split() # 첫번째 줄은 sample name이므로 읽고 분절 del sample_name[0]; del sample_name[0] # sample name은 3번째부터 시작하므로 1, 2번째 문자열은 제거 single.readline() # 2번째 line은 필요 없는 data이므로 읽고 버리기 probedata = single.readlines() # 각각의 probe에 대한 beta-value를 2차원 배열로 통째로 긁어냄 i = 0 for line in probedata : line = line.split() # 받아들인 값들을 일차원 배열 형태로 정제 if(first) : probe_name.append(line[0]) del line[0] for j in range(0, len(line)) : # 2차원 배열 형태로 sample명과 beta value를 동시에 넣어줌 if(line[j] != "NA" and sample_name[j] in sample_id) : sample_posit = sample_id.index(sample_name[j]) betavalue_arr[i][cancer_number][sample_posit][basic_posit] = float(line[j]) i += 1 single.close() return; import math # calculate the mean def mean(x): sum = 0.0 for i in x: sum += i return sum / len(x) # calculates the sample standard deviation def sampleStandardDeviation(x): sumv = 0.0 for i in x: sumv += (i - mean(x))**2 return math.sqrt(sumv/(len(x)-1)) # calculates the PCC using both the 2 functions above def pearson(x, y): scorex = [] scorey = [] for i in x: scorex.append((i - mean(x))/sampleStandardDeviation(x)) for j in y: scorey.append((j - mean(y))/sampleStandardDeviation(y)) # multiplies both lists together into 1 list (hence zip) and sums the whole list return (sum([i*j for i,j in zip(scorex,scorey)]))/(len(x)-1) print("----------------------------------------") can_num = 0 for cancer_name in cancerlist : getting_betavalue("tumor", cancer_name, can_num, 0) can_num += 1 first = False can_num = 0 for cancer_name in cancerlist : getting_betavalue("normal", cancer_name, can_num, 1) can_num += 1 tumor_pearson_output = open("Tumor_Cor_CpGsite&CytAct_pearson.txt", 'w'); tumor_spearman_output = open("Tumor_Cor_CpGSite&CytAct_spearman.txt", 'w') minus_pearson_output = open("minus_Cor_CpGsite&CytAct_pearson.txt", 'w'); minus_spearman_output = open("minus_Cor_CpGSite&CytAct_spearman.txt", 'w') FC_pearson_output = open("FC_Cor_CpGsite&CytAct_pearson.txt", 'w'); FC_spearman_output = open("FC_Cor_CpGSite&CytAct_spearman.txt", 'w') printline_header = "\t" for cancer_name in cancerlist : printline_header += "%s\t" % cancer_name printline_header += "pan_cancer\n" tumor_pearson_output.write(printline_header); tumor_spearman_output.write(printline_header) minus_pearson_output.write(printline_header); minus_spearman_output.write(printline_header) FC_pearson_output.write(printline_header); FC_spearman_output.write(printline_header) cancerlist.append("pan_cancer") # 분석에 pan-cancer도 포함되므로 cancerlist에 pan-cancer를 넣어줌, 맨 앞에 출력시킬 것이므로 앞에다가 더해줌 cutoff = 0.3 for i in range(0, len(probe_name)) : # 모든 probe를 검색 printline1 = "%s\t" % probe_name[i]; printline2 = "%s\t" % probe_name[i]; printline3 = "%s\t" % probe_name[i]; printline4 = "%s\t" % probe_name[i]; printline5 = "%s\t" % probe_name[i]; printline6 = "%s\t" % probe_name[i] for j in range(0, len(cancerlist) - 1) : betavalue_arr[i][len(cancerlist) - 1].extend(betavalue_arr[i][j]) # 각각의 CpGSite betavalue의 pan-cancer data를 얻는 과정 tumor = [None, None]; correction_FC = [None, None]; correction_minus = [None, None] tumor[0] = list(); correction_FC[0] = list(); correction_minus[0] = list(); tumor[1] = list(); correction_FC[1] = list(); correction_minus[1] = list() check_tumor = False; check_minus = False; check_FC = False for j in range(0, len(cancerlist)) : for k in range(0, len(sample_id)) : if(betavalue_arr[i][j][k][0] != None and cytoact_arr[j][k] != None) : tumor[0].append(betavalue_arr[i][j][k][0]); tumor[1].append(cytoact_arr[j][k]) check_tumor = True if(betavalue_arr[i][j][k][1] != None) : if(abs(betavalue_arr[i][j][k][0] - betavalue[i][j][k][1]) > cutoff) : # tumor - normal betavalue > cutoff correction_minus[0].append(abs(betavalue_arr[i][j][k][0] - betavalue[i][j][k][1])); correction_minus[1].append(cytoact_arr[j][k]) check_minus = True if(betavalue_arr[i][j][k][0] > betavalue[i][j][k][1]) : correction_FC[0].append(betavalue_arr[i][j][k][0]); correction_FC[1].append(cytoact_arr[j][k]) check_FC = True if(check_tumor) : tumor_pearson_pair = pearson(tumor[0], tumor[1]); printline1 += "%f\t" % tumor_pearson_pair # tumor_pearson_pair = stats.pearsonr(tumor[0], tumor[1]); printline1 += "%f\t" % tumor_pearson_pair[0] # tumor_spearman_pair = stats.spearmanr(tumor[0], tumor[1]); printline2 += "%f\t" % tumor_spearman_pair[0] else : printline1 += "NA\t"; printline2 += "NA\t" if(check_minus) : correction_minus_pearson_pair = pearson(correction_minus[0], correction_minus[1]); printline3 += "%f\t" % correction_minus_pearson_pair # correction_minus_pearson_pair = stats.pearsonr(correction_minus[0], correction_minus[1]); printline3 += "%f\t" % correction_minus_pearson_pair[0] # correction_minus_spearman_pair = stats.spearmanr(correction_minus[0], correction_minus[1]); printline4 += "%f\t" % correction_minus_spearman_pair[0] else : printline3 += "NA\t"; printline4 += "NA\t" if(check_FC) : correction_FC_pearson_pair = pearson(correction_FC[0], correction_FC[1]); printline5 += "%f\t" % correction_FC_pearson_pair # correction_FC_pearson_pair = stats.pearsonr(correction_FC[0], correction_FC[1]); printline5 += "%f\t" % correction_FC_pearson_pair[0] # correction_FC_spearman_pair = stats.spearmanr(correction_FC[0], correction_FC[1]); printline6 += "%f\t" % correction_FC_spearman_pair[0] else : printline5 += "NA\t"; printline6 += "NA\t" printline1 += "\n"; printline2 += "\n"; printline3 += "\n"; printline4 += "\n"; printline5 += "\n"; printline6 += "\n" tumor_pearson_output.write(printline1); #tumor_spearman_output.write(printline2) minus_pearson_output.write(printline3); #minus_spearman_output.write(printline4) FC_pearson_output.write(printline5); #FC_spearman_output.write(printline6) tumor_pearson_output.close(); tumor_spearman_output.close() minus_pearson_output.close(); minus_spearman_output.close() FC_pearson_output.close(); FC_spearman_output.close() <file_sep>/README.md # IMMethyl Open Source Code for DNA Methylation Project <file_sep>/CpG site Correlation/Procedure/PythonCode.py #-*- coding: utf-8 -*- cancerlist = ["ACC", "BLCA", "BRCA", "CESC", "CHOL", "COAD", "DLBC", "ESCA", "ESCASTAD", "GBM", "HNSC", "KICH", "KIRC", "KIRP", "LGG", "LIHC", "LUAD", "LUSC", "MESO", "OV", "PAAD", "PCPG", "PRAD", "READ", "SARC", "SKCM", "STAD", "TGCT", "THCA", "THYM", "UCEC", "UCS", "UVM"] cancer_number = 0 betavalue_arr = {} cytoact_arr = {} for cancer_name in cancerlist : filename = cancer_name + ".humanmethylation450.tumor.txt" # 각각의 cancer name에 대한 파일명을 문자열로 형성 single_cancer = open(filename, 'r') # 각각의 cancer에 대한 데이터 파일을 single_cancer라고 지정 sample_name = single_cancer.readline().split() # 첫번째 줄은 sample name이므로 읽고 분절 del sample_name[0]; del sample_name[0] # sample name은 3번째부터 시작하므로 1, 2번째 문자열은 제거 single_cancer.readline() # 2번째 line은 필요 없는 data이므로 읽고 버리기 probedata = single_cancer.readlines() # 각각의 probe에 대한 beta-value를 2차원 배열로 통째로 긁어냄 for line in probedata : line = line.split() # 받아들인 값들을 일차원 배열 형태로 정제 probe_name = line.pop(0) # site만 문자열이므로 별도로 저장하고 삭제 betavalue_arr[probe_name] = { cancer_name : list() } # betavalue dictionary에서 각각의 CpGSite에 대한 Cancer type별 data를 list 형태로 넣겠다 for i in range(0, len(line)) : # 2차원 배열 형태로 sample명과 beta value를 동시에 넣어줌 if(line[i] != "NA") : betavalue_arr[probe_name][cancer_name].append([sample_name[i], float(line[i])]) single_cancer.close() cytoact_file = open("TCGA_methylation_cowork_1.txt", 'r') header = cytoact_file.readline().split() # header 읽기 id_posit = header.index("tissue.code") # sample ID 위치 인덱싱 cancer_posit= header.index("origin") # cancer type 위치 인덱싱 cytoact_posit = header.index("CytAct") # cytact 위치 인덱싱 cytodata = cytoact_file.readlines() # 관련 data를 통째로 읽어들임 cytoact_file.close() for cancer_name in cancerlist : cytoact_arr[cancer_name] = list() # 미리 cytoact dictionary에서 cancer type별 cytact data를 list 형태로 저장할 것을 명시 cytoact_arr["pan_cancer"] = list() # pan-cancer 형태도 추가해줌 for line in cytodata : line = line.split() # sample 별로 정리된 data를 읽어들이고 분절 if(line[cytoact_posit] != "NA") : sample_name = line[id_posit] # id 위치로부터 sample 명을 읽어들인 후 통일된 양식으로 가공 sample_name = sample_name.replace('.', '-') cancer_name = line[cancer_posit] # cancer type 위치로부터 sample 명을 읽어들인 후 통일된 양식으로 가공 cancer_name = cancer_name.replace('_', '') cytoact_arr[cancer_name].append([sample_name, float(line[cytoact_posit])]) from operator import itemgetter from scipy import stats import pandas as pd for cancer_name in cancerlist : if(cytoact_arr[cancer_name] != None) : cytoact_arr["pan_cancer"] += cytoact_arr[cancer_name] # pan cancer에 데이터를 합쳐줌 pearson_output = open("Cor_CpGsite&CytAct_pearson.txt", 'w') spearman_output = open("Cor_CpGSite&CytAct_spearman.txt", 'w') allprobe = betavalue_arr.keys() # CpgSite의 이름만 별도로 추출해서 배열 형태로 저장 allprobe.sort() # CpgSite를 이름 순서대로 정렬 printline_header = "\tpan_cancer\t" for cancer_name in cancerlist : printline_header += "%s\t" % cancer_name printline_header += "\n" pearson_output.write(printline_header) spearman_output.write(printline_header) cancerlist.insert(0, "pan_cancer") # 분석에 pan-cancer도 포함되므로 cancerlist에 pan-cancer를 넣어줌, 맨 앞에 출력시킬 것이므로 앞에다가 더해줌 for probe_name in allprobe : # 모든 probe를 검색 printline1 = printline2 = "%s\t" % probe_name betavalue_arr[probe_name]["pan_cancer"] = list() # betavalue의 pan-cancer data를 합치기 위한 예비작업 for cancer_name in cancerlist : if(cancer_name != "pan_cancer") : betavalue_arr[probe_name]["pan_cancer"] += betavalue_arr[probe_name][cancer_name] # 각각의 CpGSite betavalue의 pan-cancer data를 얻는 과정 for cancer_name in cancerlist : if(len(betavalue_arr[probe_name][cancer_name]) > 0 and len(cytoact_arr[cancer_name]) > 0) : sample1, beta = zip(*betavalue_arr[probe_name][cancer_name]) sample2, cyt = zip(*cytoact_arr[cancer_name]) beta_table = pd.DataFrame({"ID" : sample1, "value" : beta}) cyt_table = pd.DataFrame({"ID" : sample2, "value" : cyt}) total = pd.merge(beta_table, cyt_table, on = "ID", how = "inner") pearson_pair = stats.pearsonr(total["value_x"], total["value_y"]); printline1 += "%f\t" % pearson_pair[0] spearman_pair = stats.spearmanr(total["value_x"], total["value_y"]); printline2 += "%f\t" % spearman_pair[0] else : printline1 += "NA\t"; printline2 += "NA\t" printline1 += "\n"; printline2 += "\n" pearson_output.write(printline1) spearman_output.write(printline2) pearson_output.close() spearman_output.close() <file_sep>/Filtering Invalid Samples/Find.NA.sites.py cancerlist = ["PANCANCER"] probe_site = 485577 for i in range(len(cancerlist)) : input_file = open(cancerlist[i] + ".humanmethylation450.tumor.txt", 'r') output_file = open(cancerlist[i] + ".NA.sites.txt", 'w') input_file.readline() input_file.readline() for j in range(probe_site) : line = input_file.readline().split() site_id = line.pop(0) check = False for k in range(len(line)) : if(line[k] != "NA") : check = True break if(check == False) : output_file.write(site_id + "\n") if(j % 10000 == 0) : print("%d completed." % j)
39f3cb6db0982102bf4334dbcfe6c3d4fe326d4e
[ "Markdown", "Python" ]
53
Python
JoonHyeongPark/IMMethyl
bb4aa43475460b0ce0dd8b46606f3e61c672ee8f
56892179d8f5eaf1232d4ac9dc3a42852f481988
refs/heads/master
<file_sep>namespace MantenimientoVisitas.Migrations { using System; using System.Data.Entity.Migrations; public partial class mgration : DbMigration { public override void Up() { CreateTable( "dbo.Persona", c => new { PersonaID = c.Int(nullable: false, identity: true), Nombre = c.String(nullable: false), Apellido = c.String(nullable: false), Identificacion = c.String(nullable: false), Fecha = c.DateTime(nullable: false), }) .PrimaryKey(t => t.PersonaID); CreateTable( "dbo.Visita", c => new { VisitaID = c.Int(nullable: false, identity: true), Motivo = c.String(nullable: false), Fecha = c.DateTime(nullable: false), HoraEntrada = c.Time(nullable: false, precision: 7), HoraSalida = c.Time(nullable: false, precision: 7), PersonaID = c.Int(nullable: false), Usuario = c.String(nullable: false), }) .PrimaryKey(t => t.VisitaID) .ForeignKey("dbo.Persona", t => t.PersonaID, cascadeDelete: true) .Index(t => t.PersonaID); } public override void Down() { DropForeignKey("dbo.Visita", "PersonaID", "dbo.Persona"); DropIndex("dbo.Visita", new[] { "PersonaID" }); DropTable("dbo.Visita"); DropTable("dbo.Persona"); } } } <file_sep>using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Data; using System.Linq; using System.Web; namespace MantenimientoVisitas.Models { public class Visita { [Key] public int VisitaID { get; set; } [Required] [Display(Name = "Motivo de visita")] public string Motivo { get; set; } [Required] [DataType(DataType.Date)] [Display(Name = "Fecha de Visita")] public DateTime Fecha { get; set; } [Required] [DataType(DataType.Time)] [Display(Name = "Hora de Entrada")] public TimeSpan HoraEntrada { get; set; } [Required] [DataType(DataType.Time)] [Display(Name = "Hora de Salida")] public TimeSpan HoraSalida { get; set; } [Required] [Display(Name = "Visitante")] public int PersonaID { get; set; } public virtual Persona Persona { get; set; } [Required] [Display(Name = "Persona que le recibió")] public string Usuario { get; set; } } }<file_sep>using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Web; namespace MantenimientoVisitas.Models { public class Persona { [Key] [Required] public int PersonaID { get; set; } [Required] [Display(Name = "Nombre")] public string Nombre { get; set; } [Required] [Display(Name = "Apellido")] public string Apellido { get; set; } [Required] [Display(Name = "Cédula/Pasaporte")] public string Identificacion { get; set; } [Required] [DataType(DataType.Date)] [Display(Name ="Fecha de Creación")] public DateTime Fecha { get; set; } } }
e103db6899381a45d18241f09f8e8bed67cab789
[ "C#" ]
3
C#
Felixx26/MantenimientoDeVisitas
8214c9d400a2f8276b55eb5f81da0cc13d429097
645e6faafb34364e02cac84c47ce283543724dd1
refs/heads/main
<repo_name>tdangkhoa0303/bookstore<file_sep>/server.js if (process.env.LOCAL) require("dotenv").config(); const express = require("express"); const app = express(); const bodyParser = require("body-parser"); const cookieParser = require("cookie-parser"); const mongoose = require("mongoose"); const cors = require("cors"); const bookRoute = require("./routes/book.route"); const userRoute = require("./routes/user.route"); const transactionRoute = require("./routes/transaction.route"); const authRoute = require("./routes/auth.route"); const profileRoute = require("./routes/profile.route"); const cartRoute = require("./routes/cart.route"); // API Route const authAPI = require("./api/routes/auth.route"); const transactionAPI = require("./api/routes/transaction.route"); const bookAPI = require("./api/routes/book.route"); const userAPI = require("./api/routes/user.route"); const profileAPI = require("./api/routes/profile.route"); const cartAPI = require("./api/routes/cart.route"); // API Middlewares const authMiddlewareAPI = require("./api/middlewares/auth.middleware"); const authorizeMiddlewareAPI = require("./api/middlewares/authorize.middleware"); const authMiddleware = require("./middlewares/auth.middleware"); const authorizeMiddleware = require("./middlewares/authorize.middleware"); const sessionMiddleware = require("./middlewares/session.middleware"); mongoose.connect(process.env.MONGO_URL, { useNewUrlParser: true, useUnifiedTopology: true, useFindAndModify: false, dbName: "bookManager", }); app.use(bodyParser.urlencoded({ extended: true })); app.use(bodyParser.json()); app.use(cookieParser(process.env.SESSION_SECRET)); app.use(express.static("./public")); app.use( cors({ origin: true, credentials: true, }) ); app.use(sessionMiddleware); app.set("view engine", "pug"); app.set("views", "./views"); app.get("/", (request, response) => { response.render("./index"); }); app.use("/books", bookRoute); app.use("/users", authorizeMiddleware, userRoute); app.use("/transactions", authMiddleware.requireAuth, transactionRoute); app.use("/profile", authMiddleware.requireAuth, profileRoute); app.use("/auth", authRoute); app.use("/cart", cartRoute); app.use("/api/", authAPI); app.use("/api/transactions", transactionAPI); app.use("/api/books", bookAPI); app.use("/api/users", authorizeMiddlewareAPI, userAPI); app.use("/api/transactions", authMiddlewareAPI.requireAuth, transactionAPI); app.use("/api/profile", authMiddlewareAPI.requireAuth, profileAPI); app.use("/api/cart", cartAPI); app.use((err, req, res, next) => { console.error(err.stack); res.status(500).render("./errors/500"); }); const PORT = process.env.PORT || 1402; app.listen(PORT, () => console.log("Server listening on port: " + PORT)); <file_sep>/helpers/user.helper.js const User = require("../models/user.model"); const mongoose = require("mongoose"); const basicDetails = (user) => { const { _id, userName, email, avatarUrl, books } = user; return { _id, userName, email, avatarUrl, books }; }; <file_sep>/api/routes/profile.route.js const express = require("express"); const multer = require("multer"); const router = express.Router(); const controller = require("../controllers/profile.controller"); const validate = require("../validate/profile.validate"); const upload = multer({ dest: "./public/uploads/" }); router.get("/", controller.index); router.post("/", validate.postProfile, controller.postProfile); router.post("/avatar", upload.single("avatar"), controller.postAvatar); module.exports = router; <file_sep>/routes/user.route.js const express = require("express"); const router = express.Router(); const controller = require("../controllers/user.controller"); router.get("/", controller.index); router.get("/:id/edit", controller.getEditUser); router.post("/:id/edit", controller.editUser); router.get("/:id/delete", controller.deleteUser); module.exports = router; <file_sep>/middlewares/session.middleware.js const mongoose = require("mongoose"); const User = require("../models/user.model"); const Session = require("../models/session.model"); module.exports = async (req, res, next) => { try { if (!req.signedCookies.sessionId) { var sessionId = new mongoose.Types.ObjectId(); res.cookie("sessionId", sessionId, { signed: true }); await Session.create({ _id: sessionId }); } if (req.signedCookies.userId) { var user = await User.findOne({ _id: req.signedCookies.userId }); res.locals.user = user; } } catch (err) { console.log(err); } next(); }; <file_sep>/middlewares/authorize.middleware.js const User = require("../models/user.model"); module.exports = async (req, res, next) => { try { var user = await User.findOne({ _id: req.signedCookies.userId }); } catch (err) { console.log(err); } res.locals.user = user; if (!(user && user.isAdmin)) { res.send("You cannot access this page."); return; } next(); }; <file_sep>/api/controllers/profile.controller.js const cloudinary = require("cloudinary").v2; const User = require("../../models/user.model"); module.exports.index = async (req, res) => { try { var user = await User.findOne({ _id: req.signedCookies.userId }); } catch (err) { console.log(err); res.json({ success: false, errors: [err] }); return; } res.json({ success: true, response: user }); }; module.exports.postProfile = async (req, res) => { try { var user = await User.where({ _id: req.signedCookies.userId }).updateOne( req.body ); } catch (err) { console.log(err); res.json({ success: false, errors: [err] }); return; } res.json({ success: true, response: user }); }; module.exports.postAvatar = async (req, res) => { var path = req.file.path; var result; try { result = await cloudinary.uploader.upload(path, { folder: "Coders-x/Avatars/", }); } catch (err) { res.json({ success: false, errors: [err] }); return; } await User.findOne({ _id: req.signedCookies.userId }).updateOne({ avatarUrl: result.secure_url, }); const fs = require("fs"); fs.unlinkSync(path); res.json({ success: true, data: { avatarUrl: result.secure_url } }); }; <file_sep>/api/controllers/user.controller.js const shortid = require("shortid"); const bcrypt = require("bcrypt"); const User = require("../../models/user.model"); module.exports.index = async (req, res) => { var q = req.query.q; try { var users = await User.find({ userName: { $regex: q ? q : "", $options: "i" }, }); } catch (err) { console.log(err); res.json({ success: false, message: err.message }); return; } res.json({ success: true, response: users }); }; module.exports.getUser = (req, res) => { const user = req.user; if (!user) return res.status(404).json({ success: false, message: "No information" }); res.status(200).json({ success: true, data: { user } }); }; module.exports.editUser = async (req, res) => { var id = req.params.id; try { var user = await User.where({ _id: id }).update({ userName: req.body.userName, }); } catch (err) { console.log(err); res.json({ success: false, message: err.message }); return; } res.json({ success: true, response: user }); }; module.exports.deleteUser = async (req, res) => { var id = req.params.id; try { var user = await User.deleteOne({ _id: id }); } catch (err) { console.log(err); res.json({ success: false, message: err.message }); return; } res.json({ success: true, response: user }); }; <file_sep>/api/controllers/auth.controller.js const bcrypt = require("bcrypt"); const sgMail = require("@sendgrid/mail"); const User = require("../../models/user.model"); const { basicDetails } = require("../../helpers/user.helper"); module.exports.postSignIn = async (req, res) => { var email = req.body.email, password = req.body.password; try { var user = await User.findOne({ email: email }).populate({ path: "books" }); } catch (err) { console.log(err); } if (!user) { res.status(401).json({ message: "This user does not exist.", }); return; } if (user.wrongLoginCount >= 4) { res.status(401).json({ values: req.body, message: "Cannot login. You have entered wrong password more than 4 times.", }); return; } var checkPassword = await bcrypt.compare(password, <PASSWORD>); if (!checkPassword) { try { User.where(user).updateOne({ wrongLoginCount: user.wrongLoginCount ? user.wrongLoginCount + 1 : 1, }); } catch (err) { console.log(err); } if (user.wrongLoginCount === 3) { sgMail.setApiKey(process.env.SENDGRID_API_KEY); const msg = { to: user.email, from: process.env.FROM_ADDRESS, subject: "Securce Alert", html: "<strong>Someone are trying to access your account. Please check your account to make sure it's stil safe.</strong>", }; try { await sgMail.send(msg); } catch (error) { console.log(error); } } res.status(401).json({ values: req.body, message: "Wrong password.", }); return; } res.cookie("userId", user._id, { signed: true, ...(process.env.LOCAL ? {} : { sameSite: "none", secure: true }), }); res.json({ success: true, data: { user: basicDetails(user) } }); }; module.exports.postSignUp = async (req, res) => { var saltRounds = 10; req.body.password = await bcrypt.hash(req.body.password, saltRounds); req.body.isAdmin = false; req.body.avatarUrl = "https://cdn.glitch.com/aca73c48-f323-427a-a4d2-8951b055938d%2F57633af1-a357-4d7a-a693-a11426eee969.image.png?v=1589613113114"; try { var user = await User.create(req.body); } catch (err) { console.log(err); res.json({ success: false, errors: [err] }); return; } res.json({ success: true, respsone: basicDetails(user) }); }; <file_sep>/api/controllers/transaction.controller.js const Transaction = require("../../models/transaction.model"); const User = require("../../models/user.model"); const mongoose = require("mongoose"); const Book = require("../../models/book.model"); module.exports.index = async (req, res) => { var userId = req.signedCookies.userId; var page = parseInt(req.query.page) || 1; var perPage = 4; try { var transactions = await Transaction.find({ user: userId }) .populate("book") .limit(perPage) .skip(perPage * (page - 1)) .sort("_id"); var count = await Transaction.countDocuments({ user: userId }); } catch (err) { res.json({ success: false, message: err.message }); return; } var start = (page - 1) * perPage; var end = page * perPage; res.json({ success: true, data: { transactions: transactions, maxPageNum: Math.round(count / perPage), currentPage: page, perPage: perPage, }, }); }; module.exports.createTransactions = async (req, res) => { var userId = req.signedCookies.userId; try { var user = await User.findOne({ _id: userId }) .populate("cart") .select("cart"); // user.cart.map( // async (book) => await Transaction.create({ user: userId, book: book }) // ); await Promise.all( user.cart.map((book) => Transaction.create({ user: userId, book: book })) ); await User.findOne({ _id: userId }).updateOne({ cart: [], }); } catch (err) { console.log(err); res.json({ success: false, message: err.message }); return; } res.json({ success: true }); }; module.exports.completeTransaction = async (req, res) => { var transactionId = req.params.id; try { var transaction = await Transaction.findOne({ _id: transactionId }); if (!transaction) { res.redirect("/transactions"); return; } await Transaction.where({ _id: transactionId }).updateOne({ isComplete: true, }); const book = await Book.findById(transaction.book); if (book.type !== "giveaway") { await Book.findByIdAndUpdate(transaction.book, { available: true, }); } } catch (err) { console.log(err); res.json({ success: false, message: err.message }); return; } res.json({ success: true, data: { transaction } }); }; <file_sep>/api/controllers/cart.controller.js const User = require("../../models/user.model"); const Session = require("../../models/session.model"); const Book = require("../../models/book.model"); const ObjectId = require("mongoose").Types.ObjectId; module.exports.index = async (req, res) => { var cart; var userId = req.signedCookies.userId; if (userId) { try { var user = await User.findOne({ _id: userId }) .populate("cart") .select("cart"); } catch (err) { console.log(err); res.json({ success: false, errors: [err] }); return; } res.json({ success: true, data: { cart: user.cart } }); return; } var sessionId = req.signedCookies.sessionId; if (!sessionId) { res.status(401).send("Unauthorized request"); return; } try { var session = await Session.findOne({ _id: sessionId }) .populate("cart") .select("cart"); } catch (err) { console.log(err); res.json({ success: false, errors: [err] }); return; } res.json({ success: true, data: { cart: session.cart } }); }; module.exports.addToCart = async (req, res) => { var bookId = req.params.bookId; var userId = req.signedCookies.userId; try { if (userId) { const user = await User.findByIdAndUpdate(userId, { $push: { cart: bookId }, }) .populate("cart") .select("cart"); console.log(user.cart.length); res.json({ success: true, data: { cart: user.cart } }); } else { var sessionId = req.signedCookies.sessionId; if (!sessionId) { res.status(401).json({ success: false, message: "Unauthorized request", }); } const session = await Session.findByIdAndUpdate(sessionId, { $push: { cart: bookId }, }) .populate("cart") .select("cart"); res.json({ success: true, data: { cart: session.cart } }); } } catch (err) { console.log(err); return res.json({ success: false, message: err.message }); } await Book.findByIdAndUpdate(bookId, { available: false, }); }; module.exports.removeFromCart = async (req, res) => { var bookId = req.params.bookId; var userId = req.signedCookies.userId; try { if (userId) { const user = await User.findByIdAndUpdate(userId, { $pull: { cart: ObjectId(bookId) }, }) .populate("cart") .select("cart"); res.json({ success: true, data: { cart: user.cart } }); } else { var sessionId = req.signedCookies.sessionId; if (!sessionId) { res.status(401).json({ success: false, message: "Unauthorized request", }); } const session = await Session.findByIdAndUpdate(sessionId, { $pull: { cart: ObjectId(bookId) }, }) .populate("cart") .select("cart"); res.json({ success: true, data: { cart: session.cart } }); } } catch (err) { console.log(err); return res.json({ success: false, message: err.message }); } await Book.findByIdAndUpdate(bookId, { available: true, }); }; <file_sep>/api/validate/profile.validate.js const User = require("../../models/user.model") module.exports.postProfile = async (req, res, next) => { var errors = []; if (req.body.userName.length >= 30) { errors.push("Username length cannot be longer than 30 chanracters."); } try{ var user = User.findOne({ email: req.body.email }); }catch(err){ console.log(err); } if (user && user._id !== req.signedCookies.userId) { errors.push("Email has been used by another user."); } if (errors.length) { res.status(400).json({ errors: errors, success: false }); return; } next(); }; <file_sep>/controllers/auth.controller.js const bcrypt = require("bcrypt"); const sgMail = require("@sendgrid/mail"); const User = require("../models/user.model"); module.exports.signin = (req, res) => { res.render("../views/auth/signin"); }; module.exports.postSignIn = async (req, res, next) => { var email = req.body.email, password = req.body.password; try { var user = await User.findOne({ email: email }); } catch (err) { console.log(err); next(err); } if (!user) { res.render("../views/auth/signin", { values: req.body, errors: ["This user does not exist."] }); return; } if (user.wrongLoginCount >= 4) { res.render("../views/auth/signin", { values: req.body, errors: [ "Cannot login. You have entered wrong password more than 4 times." ] }); return; } var checkPassword = await bcrypt.compare(password, user.password); if (!checkPassword) { try { User.where(user).updateOne({ wrongLoginCount: user.wrongLoginCount ? user.wrongLoginCount + 1 : 1 }); } catch (err) { console.log(err); next(err); } if (user.wrongLoginCount === 3) { sgMail.setApiKey(process.env.SENDGRID_API_KEY); const msg = { to: user.email, from: process.env.FROM_ADDRESS, subject: "Securce Alert", html: "<strong>Someone are trying to access your account. Please check your account to make sure it's stil safe.</strong>" }; try { await sgMail.send(msg); } catch (error) { console.log(error); } } res.render("../views/auth/signin", { values: req.body, errors: ["Wrong password."] }); return; } res.cookie("userId", user._id, { signed: true }); res.redirect("/books"); }; module.exports.signUp = async (req, res) => { res.render("./auth/signup"); }; module.exports.postSignUp = async (req, res, next) => { var saltRounds = 10; req.body.password = await bcrypt.hash(req.body.password, saltRounds); req.body.isAdmin = false; req.body.avatarUrl = "https://cdn.glitch.com/aca73c48-f323-427a-a4d2-8951b055938d%2F57633af1-a357-4d7a-a693-a11426eee969.image.png?v=1589613113114"; try { await User.create(req.body); } catch (err) { console.log(err); next(err); } res.redirect("/auth/signin"); }; <file_sep>/api/controllers/book.controller.js const cloudinary = require("cloudinary").v2; const Book = require("../../models/book.model"); const User = require("../../models/user.model"); module.exports.index = async (req, res) => { const perPage = process.env.PER_PAGE || 10; const { p: page = 1 } = req.query; try { var books = await Book.find() .limit(perPage) .skip((page - 1) * perPage); var count = await Book.countDocuments(); } catch (err) { console.log(err); res.status(500).json({ success: false, message: "Something went wrong." }); return; } res.status(200).json({ success: true, data: { data: books, maxPageNum: Math.round(count / perPage), currentPage: page, perPage: perPage, }, }); }; module.exports.createBook = async (req, res) => { console.log(req.body); var path = req.file.path; const user = req.user; var result; try { result = await cloudinary.uploader.upload(path, { folder: "Coders-x/Covers/", }); req.body.coverUrl = result.secure_url; } catch (err) { res.json({ success: false, errors: [err] }); return; } const fs = require("fs"); fs.unlinkSync(path); req.body.owner = user._id; try { var book = await Book.create(req.body); } catch (err) { console.log(err); res.json({ success: false, message: err.message }); return; } await User.findByIdAndUpdate(user._id, { $push: { books: book._id } }); res.json({ success: true, data: { book } }); }; module.exports.deleteBook = async (req, res) => { var _id = req.params.id; try { var book = await Book.deleteOne({ _id: _id }); } catch (err) { console.log(err); res.json({ success: false, errors: [err] }); return; } res.json({ success: true, response: book }); }; module.exports.getEditBookTitle = async (req, res) => { var id = req.params.id; try { var book = await Book.find({ _id: id }); } catch (err) { console.log(err); res.json({ success: false, errors: [err] }); return; } res.json({ success: true, response: book }); }; module.exports.editBookTitle = async (req, res) => { var id = req.params.id, newTitle = req.body.title; try { var book = await Book.where({ _id: id }).updateOne({ title: newTitle }); } catch (err) { console.log(err); res.json({ success: false, errors: [err] }); } res.json({ success: true, response: book }); }; <file_sep>/api/middlewares/auth.middleware.js const User = require("../../models/user.model"); module.exports.requireAuth = async (req, res, next) => { if (!req.signedCookies.userId) { res.status(401).json({ success: false, error: "Unauthorized request" }); return; } try { var user = await User.findOne({ _id: req.signedCookies.userId }).populate({ path: "books", }); } catch (err) { console.log(err); } if (!user) { res.status(401).json({ success: false, error: "Unauthorized request" }); return; } next(); }; <file_sep>/README.md # teeBook API A simple API for teeBook, it also provide the server-side rendering version of teeBook and admin CMS featured Visit teeBook here: https://github.com/tdangkhoa0303/react-bookstore/ ## Script ## yarn start To run the server on http://localhost:1402 You need add necessary env to make the server run correctly ##### Developed by Keentee, visit my Portfolio at http://tadaaa.web.app <file_sep>/routes/book.route.js const express = require("express"); const router = express.Router(); const multer = require("multer"); const authorizeMiddleware = require("../middlewares/authorize.middleware"); const controller = require("../controllers/book.controller"); const upload = multer({ dest: "./public/uploads/" }); router.get("/", controller.index); router.post( "/create", authorizeMiddleware, upload.single("cover"), controller.createBook ); router.get("/:id/delete", authorizeMiddleware, controller.deleteBook); router.get("/:id/edit", authorizeMiddleware, controller.getEditBookTitle); router.post("/:id/edit", authorizeMiddleware, controller.editBookTitle); module.exports = router; <file_sep>/controllers/book.controller.js const cloudinary = require("cloudinary").v2; const Book = require("../models/book.model"); module.exports.index = async (req, res, next) => { try { var books = await Book.find(); } catch (err) { console.log(err); next(err); } res.render("books/index", { books: books }); }; module.exports.createBook = async (req, res, next) => { var path = req.file.path; var result; try { result = await cloudinary.uploader.upload(path, { folder: "Coders-x/Covers/" }); req.body.coverUrl = result.secure_url; } catch (err) { res.send(err); return; } const fs = require("fs"); fs.unlinkSync(path); try { await Book.create(req.body); } catch (err) { console.log(err); next(err); } res.redirect("/books"); }; module.exports.deleteBook = async (req, res, next) => { var _id = req.params.id; try { await Book.deleteOne({ _id: _id }); } catch (err) { console.log(err); next(err); } res.redirect("/books"); }; module.exports.getEditBookTitle = async (req, res, next) => { var id = req.params.id, newTitle = req.body.title; try { var book = await Book.find({ _id: id }); } catch (err) { console.log(err); next(err); } res.render("books/edit", { book: book }); }; module.exports.editBookTitle = async (req, res, next) => { var id = req.params.id, newTitle = req.body.title; try { await Book.where({ _id: id }).updateOne({ title: newTitle }); } catch (err) { console.log(err); next(err); } res.redirect("/books"); };
2bae1de235b48d65aaa1cfa56d075cf8f9a92db9
[ "JavaScript", "Markdown" ]
18
JavaScript
tdangkhoa0303/bookstore
dcf3158fa7adb47ab2988d793e49627d365e98fa
4d4ace9826d7c6ca7379af97d5048a094c539a51
refs/heads/main
<repo_name>Ahmed-Ihsan/QR<file_sep>/QT5/mian.py import sys from PySide2.QtUiTools import QUiLoader from PyQt5.QtWidgets import QApplication from PySide2.QtCore import QFile, QIODevice from openpyxl import Workbook import qrcode from sqlalchemy import * import os import random path = "QR_images" try: os.mkdir(path) except Exception as e: print(1) metadata = MetaData() engine = create_engine('sqlite:///db.sqlite') conn = engine.connect() users = Table('users', metadata, Column('id', Integer, primary_key=True), Column('name', String), Column('number', Integer), Column('code', String), ) metadata.create_all(engine) ins = users.insert() x=None def aa(): conn = engine.connect() # The result of a "cursor.execute" can be iterated over by row f = open("db.txt", "w",encoding="utf-8") for row in conn.execute('SELECT * FROM users;'): f.write(str(row)+"\n") f.close() # Be sure to close the connection conn.close() def aa2(): workbook = Workbook() sheet = workbook.active workbook.save(filename="db.xlsx") conn = engine.connect() # The result of a "cursor.execute" can be iterated over by row x=1 for row in conn.execute('SELECT * FROM users;'): sheet["A"+str(x)] = str(row.name) sheet["B"+str(x)] = str(row.number) sheet["c"+str(x)] = str(row.code) x=x+1 conn.close() workbook.save(filename="db.xlsx") def foo(): print( 1, 2) try: if window.lineEdit.text() and int(window.spinBox.text()): # The result of a "cursor.execute" can be iterated over by row conn = engine.connect() for row in conn.execute('SELECT * FROM users;'): global x x = row[1] in window.comboBox.currentText() if x : qr = qrcode.QRCode( version=1, error_correction=qrcode.constants.ERROR_CORRECT_L, box_size=20, border=4, ) number=int(window.spinBox.text())+int(row[2]) qr.add_data("اسم القطعة :"+window.comboBox.currentText()+"\n عدد القطع :"+str(number)+"\n الرمز:: "+window.lineEdit.text()) qr.make(fit=True) print(row[0]) img = qr.make_image(fill_color="black", back_color="white") stmt = users.update().\ values(number=number).\ where(users.c.id == row[0]) conn.execute(stmt) conn.close() img.show() with open('QR_images/'+window.lineEdit.text()+'.png', 'wb') as f: img.save(f) else: qr = qrcode.QRCode( version=1, error_correction=qrcode.constants.ERROR_CORRECT_L, box_size=20, border=4, ) qr.add_data("اسم القطعة :"+str(window.comboBox.currentText())+"\n عدد القطع :"+str(window.spinBox.text())) qr.make(fit=True) img = qr.make_image(fill_color="black", back_color="white") print(conn.execute(ins, { "name":str(window.comboBox.currentText()), "number": window.spinBox.text() , "code": str(window.lineEdit.text())})) conn.close() img.show() with open('QR_images/'+window.lineEdit.text()+'.png', 'wb') as f: img.save(f) except Exception as e: print(e) if __name__ == "__main__": app = QApplication(sys.argv) ui_file_name = "a.ui" ui_file = QFile(ui_file_name) if not ui_file.open(QIODevice.ReadOnly): print("Cannot open {}: {}".format(ui_file_name, ui_file.errorString())) sys.exit(-1) loader = QUiLoader() window = loader.load(ui_file) ui_file.close() if not window: print(loader.errorString()) sys.exit(-1) window.pushButton.clicked.connect(foo) window.pushButton_2.clicked.connect(aa) window.pushButton_3.clicked.connect(aa2) window.show() sys.exit(app.exec_())<file_sep>/QR.py import tkinter as tk from tkinter import * import qrcode from openpyxl import Workbook from sqlalchemy import * from PIL import ImageTk, Image import os # define the name of the directory to be deleted path = "QR_images" try: os.mkdir(path) except Exception as e: print(1) metadata = MetaData() engine = create_engine('sqlite:///db.sqlite') conn = engine.connect() users = Table('users', metadata, Column('id', Integer, primary_key=True), Column('name', String), Column('number', Integer), Column('code', String), ) metadata.create_all(engine) ins = users.insert() x=None def aa2(): workbook = Workbook() sheet = workbook.active workbook.save(filename="db.xlsx") conn = engine.connect() # The result of a "cursor.execute" can be iterated over by row x=1 for row in conn.execute('SELECT * FROM users;'): sheet["A"+str(x)] = str(row.name) sheet["B"+str(x)] = str(row.number) sheet["c"+str(x)] = str(row.code) x=x+1 conn.close() workbook.save(filename="db.xlsx") res.configure(text = "تم استخراج البيانات") def evaluate(): try: if variable.get() and int(entry2.get()): # The result of a "cursor.execute" can be iterated over by row conn = engine.connect() for row in conn.execute('SELECT * FROM users;'): global x x = row[1] in variable.get() if x : qr = qrcode.QRCode( version=1, error_correction=qrcode.constants.ERROR_CORRECT_L, box_size=20, border=4, ) number=int(entry2.get())+int(row[2]) qr.add_data("اسم القطعة :"+variable.get()+"\n عدد القطع :"+str(number)+"\n الرمز:: "+entry3.get()) qr.make(fit=True) print(row[0]) img = qr.make_image(fill_color="black", back_color="white") stmt = users.update().\ values(number=number).\ where(users.c.id == row[0]) conn.execute(stmt) conn.close() res.configure(text ="تم ادخال البيانات" ) img.show() with open('QR_images/'+entry3.get()+'.png', 'wb') as f: img.save(f) else: qr = qrcode.QRCode( version=1, error_correction=qrcode.constants.ERROR_CORRECT_L, box_size=20, border=4, ) qr.add_data("اسم القطعة :"+str(variable.get())+"\n عدد القطع :"+str(entry2.get())) qr.make(fit=True) img = qr.make_image(fill_color="black", back_color="white") print(conn.execute(ins, { "name":str(variable.get()), "number": entry2.get() , "code": str(entry3.get())})) conn.close() res.configure(text ="تم ادخال البيانات" ) img.show() with open('QR_images/'+entry3.get()+'.png', 'wb') as f: img.save(f) except Exception as e: print(e) res.configure(text = "تاكد من ادخال البيانات") def helloCallBack(): conn = engine.connect() # The result of a "cursor.execute" can be iterated over by row f = open("db.txt", "w") for row in conn.execute('SELECT * FROM users;'): f.write(str(row)+"\n") f.close() # Be sure to close the connection conn.close() res.configure(text = "تم استخراج البيانات ") w = tk.Tk() #w.geometry("200x350") w.title("كلية الحكمة الجامعة ") tk.Label(w, text="اسم المادة").grid() variable = tk.StringVar(w) variable.set("حاسبات" ) r = tk.OptionMenu(w, variable,"حاسبات","طابعة","راوتر" ) r.grid() tk.Label(w, text="العدد").grid() entry2 = tk.Entry(w,width=30) entry2.bind("<Return>", evaluate) entry2.grid() tk.Label(w, text="الرمز").grid() entry3 = tk.Entry(w,width=30) entry3.bind("<Return>", evaluate) entry3.grid() tk.Label(w, text=" ").grid() B = tk.Button(w, text ="ادخال", command = evaluate) B.grid() tk.Label(w,text="").grid() o = tk.Button(w, text ="Excel", command = aa2) o.grid() tk.Label(w,text="").grid() c = tk.Button(w, text ="Text", command = helloCallBack) c.grid() res = tk.Label(w) res.grid() load = Image.open("b.png") render = ImageTk.PhotoImage(load) label1 = tk.Label(image=render) label1.image = render label1.grid() w.mainloop()
b718a3ff400105b69ab7f3036281456abbef7817
[ "Python" ]
2
Python
Ahmed-Ihsan/QR
9fa1d938b83d7ffb67839982e992ec52dbb2c245
fef94e3114b6fafdd476941ed59bae97c02d29db
refs/heads/master
<file_sep>/* * Copyright (C) 2019 Nafundi * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package org.opendatakit.aggregate.submission.type.jr; final class JRTemporalUtils { private JRTemporalUtils() { // Prevent instantiation of this class } static String fixOffset(String raw) { char thirdCharFromTheEnd = raw.charAt(raw.length() - 3); return thirdCharFromTheEnd == '+' || thirdCharFromTheEnd == '-' ? raw + ":00" : raw; } }
b034a3b75e609e7cc92c6141fcb57c00cf51c2a5
[ "Java" ]
1
Java
anviloro/aggregate
adb8168388e8b1eb54b10390a28ad3772384d9f3
4fa139cf7a275dc9fa2e337f19cdc5dc9acc872f
refs/heads/master
<file_sep>import { Component, OnInit } from '@angular/core'; import { FormGroup, FormBuilder, Validators } from '@angular/forms'; // import { FormGroup, FormBuilder, Validators } from '@angular/forms'; @Component({ selector: 'app-basic-form', templateUrl: './basic-form.component.html', styleUrls: [ './basic-form.component.css' ] }) export class BasicFormComponent implements OnInit { rf: FormGroup; // submitted = false; constructor(private formBuilder: FormBuilder) {} ngOnInit() { this.rf = this.formBuilder.group({ name: [ '', Validators.required ], email: [ '', Validators.required ], gender: [ '', Validators.required ], comments: [ '', Validators.required ] }); } // convenience getter for easy access to form fields // get f() { // return this.rf.controls; // } public hasError = (controlName: string, errorName: string) => { return this.rf.controls[controlName].hasError(errorName); } onSubmit() { // this.submitted = true; // stop here if form is invalid if (this.rf.invalid) { return; } console.log(this.rf.value); } } <file_sep>## POC's related to DBS. <file_sep>import { Component, OnInit, Input, Output, EventEmitter } from '@angular/core'; @Component({ selector: 'alpha-progress-bar', templateUrl: './progress-bar.component.html', styleUrls: ['./progress-bar.component.scss'] }) export class ProgressBarComponent implements OnInit { @Input() mode: string; @Input() color: string; @Input() steps: number; @Input() stepSize: number; // @Output() _increment = new EventEmitter(); // @Output() _decrment = new EventEmitter(); stepIncrementValue: number; value: number; constructor() {} ngOnInit() { this.stepIncrementValue = 100 / this.steps; this.value = this.stepIncrementValue; } increment = () => { if (this.stepSize > this.steps - 1) { return; } this.stepSize++; this.value += this.stepIncrementValue; // this._increment.emit(this.stepSize); } decrement = () => { if (this.stepSize - 1 < 1) { return; } this.stepSize--; this.value -= this.stepIncrementValue; // this._increment.emit(this.stepSize); } } <file_sep>import { Component, OnInit } from '@angular/core'; @Component({ selector: 'alpha-select-account-type', templateUrl: './select-account-type.component.html', styleUrls: ['./select-account-type.component.scss'] }) export class SelectAccountTypeComponent implements OnInit { constructor() { } ngOnInit() { } } <file_sep>import { Component, OnInit, forwardRef, AfterViewInit, OnChanges, Input, ViewChild, Injector, SimpleChanges } from '@angular/core'; import { ControlValueAccessor, NG_VALUE_ACCESSOR, NG_VALIDATORS, Validator, NgControl, AbstractControl } from '@angular/forms'; import { MatAutocompleteTrigger, MatInput } from '@angular/material'; @Component({ selector: 'alpha-autocomplete', templateUrl: './autocomplete.component.html', styleUrls: ['./autocomplete.component.scss'], providers: [ { provide: NG_VALUE_ACCESSOR, useExisting: forwardRef(() => AutocompleteComponent), multi: true }, { provide: NG_VALIDATORS, useExisting: forwardRef(() => AutocompleteComponent), multi: true } ] }) export class AutocompleteComponent implements AfterViewInit, OnChanges, ControlValueAccessor, Validator { @Input() options: any[] = []; @Input() readonly = false; @Input() displayFunction: (value: any) => string = this.defaultDisplayFn; @Input() filterFunction: (value: any) => any[] = this.defaultFilterFn; @ViewChild(MatAutocompleteTrigger) trigger: MatAutocompleteTrigger; @ViewChild(MatInput) matInput: MatInput; filteredOptions: any[]; optionSelected = ''; onChange = (val: any) => {}; onTouched = () => {}; constructor( private injector: Injector ) { } ngAfterViewInit() { this.trigger.panelClosingActions .subscribe( e => { if (this.trigger.activeOption) { const value = this.trigger.activeOption.value; this.writeValue(value); this.onChange(value); } } ); // this is needed in order for the mat-form-field to be marked as invalid when the control is invalid setTimeout(() => { this.matInput.ngControl = this.injector.get(NgControl, null); }); } ngOnChanges(changes: SimpleChanges) { if (changes.options) { this.filterOptions(this.optionSelected); } } writeValue(obj: any): void { if (obj) { this.trigger.writeValue(obj); this.optionSelected = obj; this.filterOptions(obj); } } registerOnChange(fn: any): void { this.onChange = fn; } registerOnTouched(fn: any): void { this.onTouched = fn; } setDisabledState?(isDisabled: boolean): void { this.matInput.disabled = isDisabled; this.trigger.setDisabledState(isDisabled); } // validate(c: AbstractControl): { [key: string]: any; } { // return forbiddenAutocompleteValue()(c); // } validate(c: AbstractControl): { [key: string]: any; } { return null; } valueChanged(event) { const value = event.target.value; this.optionSelected = value; this.onChange(value); this.filterOptions(value); } onOptionSelected(event) { const value = event.option.value; this.optionSelected = value; this.onChange(value); this.filterOptions(value); } filterOptions(value) { this.filteredOptions = this.filterFunction(value); } private defaultFilterFn(value) { let name = value; if (value && typeof value === 'object') { name = value.name; } return this.options.filter( o => o.name.toLowerCase().indexOf(name ? name.toLowerCase() : '') !== -1 ); } defaultDisplayFn(value) { return value ? value.name : value; } }<file_sep>import { Component, OnInit } from '@angular/core'; @Component({ selector: 'alpha-file-uplaod', templateUrl: './file-uplaod.component.html', styleUrls: ['./file-uplaod.component.scss'] }) export class FileUplaodComponent implements OnInit { constructor() { } ngOnInit() { } } <file_sep>import { Component, ViewChild, OnInit } from '@angular/core'; import { ValueConverter } from '@angular/compiler/src/render3/view/template'; import { ProgressBarComponent } from './components/progress-bar/progress-bar.component'; import { StepperComponent } from './components/stepper/stepper.component'; import { Router } from '@angular/router'; @Component({ selector: 'alpha-root', templateUrl: './app.component.html', styleUrls: ['./app.component.scss'] }) export class AppComponent implements OnInit { @ViewChild(ProgressBarComponent) progressBar: ProgressBarComponent; @ViewChild(StepperComponent) stepper: StepperComponent; constructor( private router: Router ) {} ngOnInit(): void { // load to first page on refresh. this.router.navigate(['/']); } decrement = () => { this.progressBar.decrement(); this.stepper.previousLink(); } increment = () => { this.progressBar.increment(); this.stepper.nextLink(); } } <file_sep>import { Component, OnInit } from '@angular/core'; import { Router, ActivatedRoute } from '@angular/router'; @Component({ selector: 'alpha-stepper', templateUrl: './stepper.component.html', styleUrls: ['./stepper.component.scss'] }) export class StepperComponent implements OnInit { constructor( private router: Router, private activateRoute: ActivatedRoute ) { } items = [ { 'name': 'Basic Information', 'link': 'application-contact-info', 'subItems': [ { 'name': 'Application Contact Info', 'link': 'application-contact-info' }, { 'name': 'Select Account type', 'link': 'select-account-type' } ] }, { 'name': 'Enterprise Information', 'link': 'enterprise-information', 'subItems': [ { 'name': 'Enterprise Information', 'link': 'enterprise-information' }, { 'name': 'Select Account type', 'link': 'select-account-type' } ] }, { 'name': 'Bank of service application', 'link': 'bank-of-service-application' }, { 'name': 'File Uplaod', 'link': 'file-uplaod' }, { 'name': 'Confirm', 'link': 'confirm' } ]; // items = [ // { // 'name': 'Basic Information', // 'link': 'application-contact-info', // 'subItems': [ // { 'name': 'Contact Info', 'link': 'application-contact-info' }, // { 'name': 'Select Account type', 'link': 'select-account-type' } // ] // }, // { // 'name': 'Enterprise Information', // 'link': 'enterprise-information', // 'subItems': [ // { 'name': 'Enterprise Information', 'link': 'enterprise-information' }, // { 'name': 'legal Representaive/ Unit Person Incharge ', 'link': 'enterprise-information' }, // { 'name': 'Finincial Officer', 'link': 'enterprise-information' }, // { 'name': 'Other authorised signed', 'link': 'enterprise-information' }, // { 'name': 'Other pament contents', 'link': 'enterprise-information' } // ] // }, // { 'name': 'Bank of service application', 'link': 'bank-of-service-application' }, // { 'name': 'File Uplaod', 'link': 'file-uplaod' }, // { 'name': 'Confirm', 'link': 'confirm' } // ]; itemsLength: number; subItemsLength: number; selectedUserIndex: number; currentItemIndexState: number; subItemIndexState: number; linkState: String; ngOnInit() { this.currentItemIndexState = 0; this.subItemIndexState = 1; this.itemsLength = this.items.length; this.linkState = 'nextLink'; for (let i = 0; i < this.itemsLength; i++) { (this.items[i])['tickIcon'] = false; (this.items[i])['arrowIcon'] = false; (this.items[i])['state'] = false; // provides indexing to list-items (this.items[i])['i'] = i; if (this.items[i].subItems) { for (let j = 0; j < this.items[i].subItems.length; j++) { (this.items[i].subItems[j])['tickIcon'] = false; (this.items[i].subItems[j])['arrowIcon'] = false; (this.items[i].subItems[j])['state'] = false; // provides indexing to sub-list-items (this.items[i].subItems[j])['j'] = j; } } } // (this.items[0])['tickIcon'] = true; // (this.items[0].subItems[0])['tickIcon'] = true; // console.log(this.items); } // to remove last divider in item-list isMdDividerRequiredForListItem = (index: number) => { if (index === this.itemsLength - 1) { return false; } return true; } // show and hide functionality of sublist items based on onclick. selectUserIndex = (index: any) => { if (this.selectedUserIndex !== index) { this.selectedUserIndex = index; } else { this.selectedUserIndex = undefined; } } subRouterLink = () => { if (this.linkState === 'previousLink') { this.router.navigateByUrl(this.items[this.currentItemIndexState].subItems[this.subItemIndexState].link); // tslint:disable-next-line: max-line-length console.log(`this.items[${this.currentItemIndexState}].subItems[${this.subItemIndexState}].link = ${this.items[this.currentItemIndexState].subItems[this.subItemIndexState].link} = [${this.currentItemIndexState} ${this.subItemIndexState}]`); } if (this.linkState === 'nextLink') { this.router.navigateByUrl(this.items[this.currentItemIndexState].subItems[this.subItemIndexState].link); // tslint:disable-next-line: max-line-length console.log(`this.items[${this.currentItemIndexState}].subItems[${this.subItemIndexState}].link = ${this.items[this.currentItemIndexState].subItems[this.subItemIndexState].link} = [${this.currentItemIndexState} ${this.subItemIndexState}]`); } } stepperRouteSubItem = () => { // console.log(this.items[this.currentItemIndexState].subItems); if (this.linkState === 'previousLink') { // if (this.subItemIndexState === this.subItemsLength - 1) { // this.subRouterLink(); // this.currentItemIndexState--; // this.subItemIndexState = 0; // } else { // this.subRouterLink(); // if (this.currentItemIndexState === 1 && this.subItemIndexState === 0) { // this.subItemIndexState = this.subItemsLength; // } // if (this.subItemIndexState > 0) { // this.subItemIndexState--; // } // } // if (this.subItemIndexState === this.subItemsLength - 1) { // this.subRouterLink(); // if (this.currentItemIndexState >= 0) { // this.currentItemIndexState--; // } // this.subItemIndexState = 0; // } else { // this.subRouterLink(); // this.subItemIndexState = this.subItemsLength; // if (this.subItemIndexState > 0) { // this.subItemIndexState--; // } // } if ( this.currentItemIndexState === 0 && this.subItemIndexState === 0 ) { return; } if (this.subItemIndexState === this.subItemsLength - 1) { this.subItemIndexState --; this.subRouterLink(); this.currentItemIndexState--; } else { this.subItemIndexState = this.subItemsLength - 1; this.subRouterLink(); } } if (this.linkState === 'nextLink') { if (this.subItemIndexState === this.subItemsLength - 1) { this.subRouterLink(); this.currentItemIndexState++; this.subItemIndexState = 0; } else { this.subRouterLink(); this.subItemIndexState++; } } } stepperRouteItem = () => { // else route to list tem this.router.navigateByUrl(this.items[this.currentItemIndexState].link); console.log(`${this.items[this.currentItemIndexState].link} = ${this.currentItemIndexState}`); } previousLink = () => { this.linkState = 'previousLink'; if (this.currentItemIndexState < 0) { return ; } // if (this.currentItemIndexState === 0 && this.subItemIndexState === 1) { return; } if (this.currentItemIndexState === this.items.length) { this.currentItemIndexState -= 2; } // if (this.currentItemIndexState === this.items.length - 1) { // this.currentItemIndexState--; // } // check if subitem exists. if (this.items[this.currentItemIndexState].subItems) { this.subItemsLength = this.items[this.currentItemIndexState].subItems.length; this.stepperRouteSubItem(); } else { this.stepperRouteItem(); this.currentItemIndexState--; } } nextLink = () => { this.linkState = 'nextLink'; if (this.currentItemIndexState > this.itemsLength - 1 ) { return; } // check if subitem exists. if (this.items[this.currentItemIndexState].subItems) { this.subItemsLength = this.items[this.currentItemIndexState].subItems.length; this.stepperRouteSubItem(); } else { // if (this.currentItemIndexState === this.itemsLength) { // return; // } this.stepperRouteItem(); this.currentItemIndexState++; } } } <file_sep>import { Component, OnInit } from '@angular/core'; import { FormGroup, FormBuilder, Validators } from '@angular/forms'; @Component({ selector: 'app-login', templateUrl: './login.component.html', styleUrls: ['./login.component.css'] }) export class LoginComponent implements OnInit { rf: FormGroup; constructor(private formBuilder: FormBuilder) { } ngOnInit() { this.rf = this.formBuilder.group({ username: ['', Validators.required], password: ['', Validators.required], }); } public hasError = (controlName: string, errorName: string) => { return this.rf.controls[controlName].hasError(errorName); } onSubmit() { // this.submitted = true; // stop here if form is invalid if (this.rf.invalid) { return; } console.log(this.rf.value); } } <file_sep>import { Component, OnInit } from '@angular/core'; import { FormGroup, FormControl, Validators } from '@angular/forms'; @Component({ selector: 'alpha-application-contact-info', templateUrl: './application-contact-info.component.html', styleUrls: ['./application-contact-info.component.scss'] }) export class ApplicationContactInfoComponent implements OnInit { validateForm: FormGroup; inputData = [ { 'label': 'red', 'checked': true, 'disabled': false }, { 'label': 'green', 'checked': false, 'disabled': false }, { 'label': 'yellow', 'checked': true, 'disabled': true } ]; inputData1 = [ { 'label': 'red', 'checked': true, 'disabled': false }, { 'label': 'green', 'checked': false, 'disabled': false }, { 'label': 'yellow', 'checked': true, 'disabled': true } ]; options = [ {'name': 'one'}, {'name': 'two'}, {'name': 'three'} ]; constructor() { } ngOnInit() { this.validateForm = new FormGroup({ // items: new FormControl('', Validators.required), // items1: new FormControl('', Validators.required) branch: new FormControl({'name': 'one'}, Validators.required), branch1: new FormControl({'name': 'three'}, Validators.required) }); } submit() { if(this.validateForm.valid) { console.log(this.validateForm.value); } } } <file_sep>import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import { AppRoutingModule } from './app-routing.module'; import { AppComponent } from './app.component'; import { BrowserAnimationsModule } from '@angular/platform-browser/animations'; import { FlexLayoutModule } from '@angular/flex-layout'; import { ProgressBarComponent } from './components/progress-bar/progress-bar.component'; import { MaterialModule } from './modules/material/material.module'; import { StepperComponent } from './components/stepper/stepper.component'; import { NavbarComponent } from './components/navbar/navbar.component'; import { ApplicationContactInfoComponent } from './containers/application-contact-info/application-contact-info.component'; import { EnterpriseInformationComponent } from './containers/enterprise-information/enterprise-information.component'; import { SelectAccountTypeComponent } from './containers/select-account-type/select-account-type.component'; import { BankOfServiceApplicationComponent } from './containers/bank-of-service-application/bank-of-service-application.component'; import { FileUplaodComponent } from './containers/file-uplaod/file-uplaod.component'; import { ConfirmComponent } from './containers/confirm/confirm.component'; import { CheckboxGroupComponent } from './components/checkbox-group/checkbox-group.component'; import { FormsModule, ReactiveFormsModule } from '@angular/forms'; import { AutocompleteComponent } from './components/autocomplete/autocomplete.component'; @NgModule({ declarations: [ AppComponent, ProgressBarComponent, StepperComponent, NavbarComponent, ApplicationContactInfoComponent, EnterpriseInformationComponent, SelectAccountTypeComponent, BankOfServiceApplicationComponent, FileUplaodComponent, ConfirmComponent, CheckboxGroupComponent, AutocompleteComponent ], imports: [ BrowserModule, AppRoutingModule, BrowserAnimationsModule, FlexLayoutModule, MaterialModule, FormsModule, ReactiveFormsModule ], providers: [], bootstrap: [AppComponent] }) export class AppModule { } <file_sep>import { NgModule } from '@angular/core'; import { Routes, RouterModule } from '@angular/router'; import { ApplicationContactInfoComponent } from './containers/application-contact-info/application-contact-info.component'; import { SelectAccountTypeComponent } from './containers/select-account-type/select-account-type.component'; import { EnterpriseInformationComponent } from './containers/enterprise-information/enterprise-information.component'; import { BankOfServiceApplicationComponent } from './containers/bank-of-service-application/bank-of-service-application.component'; import { FileUplaodComponent } from './containers/file-uplaod/file-uplaod.component'; import { ConfirmComponent } from './containers/confirm/confirm.component'; const routes: Routes = [ { path: 'application-contact-info', component: ApplicationContactInfoComponent}, { path: 'select-account-type', component: SelectAccountTypeComponent}, { path: 'enterprise-information', component: EnterpriseInformationComponent }, { path: 'bank-of-service-application', component: BankOfServiceApplicationComponent}, { path: 'file-uplaod', component: FileUplaodComponent}, { path: 'confirm', component: ConfirmComponent }, { path: '**', redirectTo: '/application-contact-info', pathMatch: 'full' } ]; @NgModule({ imports: [RouterModule.forRoot(routes)], exports: [RouterModule] }) export class AppRoutingModule { } <file_sep>import { async, ComponentFixture, TestBed } from '@angular/core/testing'; import { ApplicationContactInfoComponent } from './application-contact-info.component'; describe('ApplicationContactInfoComponent', () => { let component: ApplicationContactInfoComponent; let fixture: ComponentFixture<ApplicationContactInfoComponent>; beforeEach(async(() => { TestBed.configureTestingModule({ declarations: [ ApplicationContactInfoComponent ] }) .compileComponents(); })); beforeEach(() => { fixture = TestBed.createComponent(ApplicationContactInfoComponent); component = fixture.componentInstance; fixture.detectChanges(); }); it('should create', () => { expect(component).toBeTruthy(); }); }); <file_sep>export interface User { name: string; email: String; gender: string; comments: string; } <file_sep>import { Component, OnInit } from '@angular/core'; @Component({ selector: 'alpha-bank-of-service-application', templateUrl: './bank-of-service-application.component.html', styleUrls: ['./bank-of-service-application.component.scss'] }) export class BankOfServiceApplicationComponent implements OnInit { constructor() { } ngOnInit() { } } <file_sep>import { Component, OnInit, Input, forwardRef, SimpleChanges, OnChanges, ElementRef, Renderer2, Optional, Self } from '@angular/core'; import { FormControl, FormGroup, FormBuilder, ControlValueAccessor, FormArray, NgControl } from '@angular/forms'; import { ReplaySubject } from 'rxjs'; @Component({ selector: 'alpha-checkbox-group', templateUrl: './checkbox-group.component.html', styleUrls: ['./checkbox-group.component.scss'], providers: [ // { provide: NG_VALUE_ACCESSOR, useExisting: forwardRef(() => CheckboxGroupComponent), multi: true }, // { provide: NG_VALIDATORS, useExisting: forwardRef(() => CheckboxGroupComponent), multi: true }, ] }) export class CheckboxGroupComponent implements ControlValueAccessor, OnInit, OnChanges { validateForm: FormGroup; @Input() inputData: any[]; @Input() color: string; public items: any = []; public chechBoxGroup = []; delegatedMethodCalls = new ReplaySubject<(_: ControlValueAccessor) => void>(); propagateChange: any = () => { }; propagateTouch: any = () => { }; validateFn: any = () => { }; constructor( private formBuilder: FormBuilder, @Optional() @Self() public ngControl: NgControl, private _renderer: Renderer2, private _elementRef: ElementRef ) { // Replace the provider from above with this. if (this.ngControl != null) { // Setting the value accessor directly (instead of using // the providers) to avoid running into a circular import. this.ngControl.valueAccessor = this; } } ngOnInit() { this.validateForm = this.formBuilder.group({ checkbox: this.formBuilder.array([]) }); const checkboxFormArray = <FormArray>this.validateForm.controls.checkbox; for (let index = 0; index < this.inputData.length; index++) { if (this.inputData[index].checked) { checkboxFormArray.push(new FormControl(this.inputData[index].label)); } } this.items = this.validateForm.value; } ngOnChanges(changes: SimpleChanges): void { // this.propagateChange(changes.inputData.currentValue); changes.inputData.currentValue.forEach(element => { if (element.checked) { this.chechBoxGroup.push(element.label); } }); // this.propagateChange(changes.inputData.currentValue); this.propagateChange(this.chechBoxGroup); console.log(changes ); } onToggle(item: any, event: any, isChecked: any, index: number) { event.preventDefault(); // alert(this.inputData[index].disabled); if (this.inputData[index].disabled) { return; } // console.log(event.checked); // console.log(`${item} ${isChecked} ${index}`); this.inputData[index].checked = !isChecked; const checkboxFormArray = <FormArray>this.validateForm.controls.checkbox; if (!isChecked) { checkboxFormArray.push(new FormControl(item)); this.chechBoxGroup.push(item); } else { for (let index1 = 0; index1 < this.chechBoxGroup.length; index1++) { if (this.chechBoxGroup[index1] === item) { this.chechBoxGroup.splice(index1, 1); } } const indexToRemove = checkboxFormArray.controls.findIndex(x => x.value === item); checkboxFormArray.removeAt(indexToRemove); } // console.log(this.validateForm.value); } writeValue(value) { // this.items = value; // console.log(value); // this.checkbox. // if (value !== undefined) { // this.inputData = value; // } // this._renderer.setProperty(this._elementRef.nativeElement, 'value', value); // this.delegatedMethodCalls.next(valueAccessor => valueAccessor.writeValue(this.validateForm.value)); } registerOnChange(fn) { this.propagateChange = fn; } registerOnTouched(fn) { this.propagateTouch = fn; } // validate(c: FormControl) { // return this.validateFn(c); // } setDisabledState?(isDisabled: boolean): void { } } export function setUpControl(control: FormControl, dir: NgControl) { // initialize a form control dir.valueAccessor.writeValue(control.value); // setup a listener for changes on the native control // and set this value to form control dir.valueAccessor.registerOnChange((newValue: any) => { control.setValue(newValue, { emitModelToViewChange: false }); }); // setup a listener for changes on the Angular formControl // and set this value to the native control control.registerOnChange((newValue: any) => { dir.valueAccessor.writeValue(newValue); }); }
bb8fa9dc3b15272fe1cf1dc9b8b9cfc10a9a3319
[ "Markdown", "TypeScript" ]
16
TypeScript
skybarer/dbs
7f41dbb3b8835e381078fd71fe948b0f86dcc692
bcd482f771801fb40959e1fb11631113c21de42b
refs/heads/master
<file_sep>package main.gfx; import java.awt.image.BufferedImage; /** * Cette classe permet de créer des sprite à partir d'une sprite sheet * @author Octikoros * */ public class SpriteSheet { // Contient tout ce qui est images private BufferedImage sheet; /** * Initialise une nouvelle image * @param sheet : l'image */ public SpriteSheet(BufferedImage sheet) { this.sheet = sheet; } /** * @param x : l'axe des abscisse (de gauche à droite) * @param y : l'axe des ordonnées (de haut en bas) * @param width : la largeur de l'image découpée * @param height : la hauteur de l'image découpée * @return une partie de l'image utilisée */ public BufferedImage crop(int x, int y, int width, int height) { // Renvoie une partie de l'image de base return sheet.getSubimage(x, y, width, height); } } <file_sep>package main.display; import java.awt.Canvas; import java.awt.Dimension; import javax.swing.JFrame; /** * Cette classe permet d'afficher la fenêtre de jeu * @author Octikoros * */ public class Display { // La fenêtre private JFrame frame; // Un espace rectangulaire de l'écran dans lequel on dessine/ajoute des éléments graphiques // Ces éléments graphiques seront ensuite affiché dans la fenêtre private Canvas canvas; // Le titre de la fenêtre (ce qui apparait au dessus) private String title; //La largeur de la fenêtre (en pixel) private int width; // La hauteur de la fenêtre (en pixel) private int height; /** * Initialise une nouvelle fenêtre * @param title : titre * @param width : largeur * @param height : hauteur */ public Display(String title, int width, int height) { this.title = title; this.width = width; this.height = height; createDisplay(); } /** * Crée une fenêtre */ public void createDisplay() { // La fenêtre est invisible de base frame = new JFrame(title); // Définit la taille de la fenêtre frame.setSize(width, height); // Définit ce qu'il se passe lorsqu'on veut fermer la fenêtre // Dans ce cas là on ferme complètement l'application frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // Ne permet pas à l'utilisateur de changer la taille de la fenêtre frame.setResizable(false); // La fenêtre s'affiche au centre de l'écran frame.setLocationRelativeTo(null); // La fenêtre est maintenant visible frame.setVisible(true); // Initialise un nouveau canvas canvas = new Canvas(); // Définit la taille du canvas canvas.setPreferredSize(new Dimension(width, height)); // S'assurer que la taille du canvas ne changeras pas canvas.setMaximumSize(new Dimension(width, height)); canvas.setMinimumSize(new Dimension(width, height)); // Ne permet pas au canvas d'être focus // Permet uniquement à la fenêtre d'être focus canvas.setFocusable(false); // Ajouter le canvas à la fenêtre frame.add(canvas); // Redimensionne la fenêtre pour que l'on puisse voir l'intégralité du canvas // La redimension se fait en fonction de setPreferredSize du canvas frame.pack(); } /** * @return le contenu de la variable "canvas" */ public Canvas getCanvas() { return canvas; } /** * @return le contenu de la variable "frame" */ public JFrame getFrame() { return frame; } }<file_sep>package main.tiles; import java.awt.Graphics; import java.awt.image.BufferedImage; /** * Cette classe représente une case * @author Octikoros * */ public class Tile { // Tableau comportant tout les types de case public static Tile[] tiles = new Tile[4]; // Initialisation de toutes les cases public static Tile backgroundTile = new BackGroundTile(0); public static Tile floorTile1 = new FloorTile1(1); public static Tile floorTile2 = new FloorTile2(2); public static Tile flagTile = new FlagTile(3); // Largeur d'une case public static final int TILEWIDTH = 25; // Hauteur d'une case public static final int TILEHEIGHT = 25; // La texture des cases protected BufferedImage texture; // L'id des cases protected final int id; /** * Initialisation d'une nouvelle case * @param texture : la texture de la case * @param id : l'id de la case */ public Tile(BufferedImage texture, int id) { this.texture = texture; this.id = id; tiles[id] = this; } /** * Affiche les éléments mis à jour * @param g : L'espace graphique sur lequel va être dessinée l'image * @param x : la position horizontale de la case * @param y : la postion verticale de la case */ public void render(Graphics g, int x, int y) { g.drawImage(texture, x, y, TILEWIDTH, TILEHEIGHT, null); } /** * Vérifie si la case demandée est une case d'arrivée * @return true si oui, sinon false */ public boolean isFlag() { return false; } /** * Vérifie si une case est solide ou non * @return true si oui, false si non */ public boolean isSolid() { return false; } } <file_sep>package main.entities; import java.awt.Graphics; import java.util.ArrayList; import model.Game; /** * Cette classe représente la liste des ennemis * @author Octikoros * */ public class ListEntity implements Runnable{ // Le jeu possédant les données de cette liste private Game game; // Le tableau contenant les ennemis private ArrayList<Mob> arrayMob; // Permet de savoir si les ennemis sont en train de tourner ou pas private boolean running = false; /** * Initialise une nouvelle liste d'ennemis * @param game : les données de jeu */ public ListEntity(Game game) { this.game = game; arrayMob = new ArrayList<Mob>(); running = true; new Thread(this).start(); } /** * Affiche les éléments mis à jour en GUI */ public void renderGUI(Graphics g) { for(Mob mob : arrayMob) { mob.renderGUI(g); } } /* * Affiche les élements mis à jour en console */ public void renderCon() { for(Mob mob : arrayMob) { mob.renderCon(); } } @Override /** * Cette méthode est appelée lorsque la méthode start() du thread courant est appelée */ public void run() { setMob(); while(running) { for(Mob mob : arrayMob) { mob.move(); } game.moveMob(); try { Thread.sleep(1000 / 3); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } /** * Initialise la postion et le mouvement de tous les ennemis par niveau */ public void setMob() { arrayMob.removeAll(arrayMob); if(game.getWorld().getId() == 1) { arrayMob.add(new Mob(game, 5, 5, "up", "", 0, 0, 3, 3)); arrayMob.add(new Mob(game, 6, 5, "down", "", 0, 0, 3, 3)); arrayMob.add(new Mob(game, 7, 5, "up", "", 0, 0, 3, 3)); arrayMob.add(new Mob(game, 8, 5, "down", "", 0, 0, 3, 3)); arrayMob.add(new Mob(game, 9, 5, "up", "", 0, 0, 3, 3)); arrayMob.add(new Mob(game, 10, 5, "down", "", 0, 0, 3, 3)); arrayMob.add(new Mob(game, 11, 5, "up", "", 0, 0, 3, 3)); arrayMob.add(new Mob(game, 12, 5, "down", "", 0, 0, 3, 3)); arrayMob.add(new Mob(game, 13, 5, "up", "", 0, 0, 3, 3)); arrayMob.add(new Mob(game, 14, 5, "down", "", 0, 0, 3, 3)); arrayMob.add(new Mob(game, 15, 5, "up", "", 0, 0, 3, 3)); arrayMob.add(new Mob(game, 16, 5, "down", "", 0, 0, 3, 3)); } else if(game.getWorld().getId() == 2){ arrayMob.add(new Mob(game, 3, 8, "up", "", 0, 0, 3, 3)); arrayMob.add(new Mob(game, 4, 8, "down", "", 0, 0, 3, 3)); arrayMob.add(new Mob(game, 5, 8, "up", "", 0, 0, 3, 3)); arrayMob.add(new Mob(game, 6, 8, "down", "", 0, 0, 3, 3)); arrayMob.add(new Mob(game, 7, 8, "up", "", 0, 0, 3, 3)); arrayMob.add(new Mob(game, 8, 8, "down", "", 0, 0, 3, 3)); arrayMob.add(new Mob(game, 9, 8, "up", "", 0, 0, 3, 3)); arrayMob.add(new Mob(game, 10, 8, "down", "", 0, 0, 3, 3)); arrayMob.add(new Mob(game, 11, 8, "up", "", 0, 0, 3, 3)); arrayMob.add(new Mob(game, 12, 8, "down", "", 0, 0, 3, 3)); arrayMob.add(new Mob(game, 13, 8, "up", "", 0, 0, 3, 3)); arrayMob.add(new Mob(game, 14, 8, "down", "", 0, 0, 3, 3)); arrayMob.add(new Mob(game, 15, 8, "up", "", 0, 0, 3, 3)); arrayMob.add(new Mob(game, 9, 7, "right", "", 6, 6, 0, 0)); arrayMob.add(new Mob(game, 9, 9, "left", "", 6, 6, 0, 0)); } else if(game.getWorld().getId() == 3) { arrayMob.add(new Mob(game, 3, 3, "right", "turnRight", 0, 6, 0, 6)); arrayMob.add(new Mob(game, 9, 3, "down", "turnRight", 6, 0, 0, 6)); arrayMob.add(new Mob(game, 9, 9, "left", "turnRight", 6, 0, 6, 0)); arrayMob.add(new Mob(game, 3, 9, "up", "turnRight", 0, 6, 6, 0)); } else if(game.getWorld().getId() == 4){ arrayMob.add(new Mob(game, 2, 9, "up", "", 0, 0, 3, 3)); arrayMob.add(new Mob(game, 3, 9, "down", "", 0, 0, 3, 3)); arrayMob.add(new Mob(game, 4, 9, "up", "", 0, 0, 3, 3)); arrayMob.add(new Mob(game, 5, 8, "down", "", 0, 0, 0, 4)); arrayMob.add(new Mob(game, 6, 7, "up", "", 0, 0, 5, 5)); arrayMob.add(new Mob(game, 7, 7, "down", "", 0, 0, 5, 5)); arrayMob.add(new Mob(game, 8, 7, "up", "", 0, 0, 5, 5)); arrayMob.add(new Mob(game, 9, 6, "up", "", 0, 0, 4, 0)); arrayMob.add(new Mob(game, 10, 7, "up", "", 0, 0, 5, 5)); arrayMob.add(new Mob(game, 11, 7, "down", "", 0, 0, 5, 5)); arrayMob.add(new Mob(game, 12, 7, "up", "", 0, 0, 5, 5)); arrayMob.add(new Mob(game, 13, 8, "down", "", 0, 0, 0, 4)); arrayMob.add(new Mob(game, 14, 7, "up", "", 0, 0, 5, 5)); arrayMob.add(new Mob(game, 15, 7, "down", "", 0, 0, 5, 5)); arrayMob.add(new Mob(game, 16, 7, "up", "", 0, 0, 5, 5)); arrayMob.add(new Mob(game, 17, 6, "up", "", 0, 0, 4, 0)); arrayMob.add(new Mob(game, 18, 5, "up", "", 0, 0, 3, 3)); arrayMob.add(new Mob(game, 19, 5, "down", "", 0, 0, 3, 3)); arrayMob.add(new Mob(game, 20, 5, "up", "", 0, 0, 3, 3)); } else if(game.getWorld().getId() == 5) { arrayMob.add(new Mob(game, 4, 2, "right", "turnRight", 0, 13, 0, 9)); arrayMob.add(new Mob(game, 17, 2, "down", "turnRight", 13, 0, 0, 9)); arrayMob.add(new Mob(game, 17, 11, "left", "turnRight", 13, 0, 9, 0)); arrayMob.add(new Mob(game, 4, 11, "up", "turnRight", 0, 13, 9, 0)); arrayMob.add(new Mob(game, 6, 4, "right", "turnRight", 0, 9, 0, 5)); arrayMob.add(new Mob(game, 15, 4, "down", "turnRight", 9, 0, 0, 5)); arrayMob.add(new Mob(game, 15, 9, "left", "turnRight", 9, 0, 5, 0)); arrayMob.add(new Mob(game, 6, 9, "up", "turnRight", 0, 9, 5, 0)); arrayMob.add(new Mob(game, 9, 5, "right", "turnRight", 0, 3, 0, 3)); arrayMob.add(new Mob(game, 12, 5, "down", "turnRight", 3, 0, 0, 3)); arrayMob.add(new Mob(game, 12, 8, "left", "turnRight", 3, 0, 3, 0)); arrayMob.add(new Mob(game, 9, 8, "up", "turnRight", 0, 3, 3, 0)); } else if(game.getWorld().getId() == 6){ arrayMob.add(new Mob(game, 2, 4, "right", "turnRight", 0, 1, 0, 1)); arrayMob.add(new Mob(game, 4, 4, "right", "turnRight", 0, 1, 0, 1)); arrayMob.add(new Mob(game, 2, 6, "right", "turnRight", 0, 1, 0, 1)); arrayMob.add(new Mob(game, 4, 6, "right", "turnRight", 0, 1, 0, 1)); arrayMob.add(new Mob(game, 2, 8, "right", "turnRight", 0, 1, 0, 1)); arrayMob.add(new Mob(game, 4, 8, "right", "turnRight", 0, 1, 0, 1)); arrayMob.add(new Mob(game, 6, 8, "right", "turnRight", 0, 1, 0, 1)); arrayMob.add(new Mob(game, 8, 8, "right", "turnRight", 0, 1, 0, 1)); arrayMob.add(new Mob(game, 10, 8, "right", "turnRight", 0, 1, 0, 1)); arrayMob.add(new Mob(game, 8, 6, "right", "turnRight", 0, 1, 0, 1)); arrayMob.add(new Mob(game, 10, 6, "right", "turnRight", 0, 1, 0, 1)); arrayMob.add(new Mob(game, 8, 4, "right", "turnRight", 0, 1, 0, 1)); arrayMob.add(new Mob(game, 10, 4, "right", "turnRight", 0, 1, 0, 1)); arrayMob.add(new Mob(game, 12, 4, "right", "turnRight", 0, 1, 0, 1)); arrayMob.add(new Mob(game, 14, 4, "right", "turnRight", 0, 1, 0, 1)); arrayMob.add(new Mob(game, 16, 4, "right", "turnRight", 0, 1, 0, 1)); arrayMob.add(new Mob(game, 14, 6, "right", "turnRight", 0, 1, 0, 1)); arrayMob.add(new Mob(game, 16, 6, "right", "turnRight", 0, 1, 0, 1)); arrayMob.add(new Mob(game, 14, 8, "right", "turnRight", 0, 1, 0, 1)); arrayMob.add(new Mob(game, 16, 8, "right", "turnRight", 0, 1, 0, 1)); } else if(game.getWorld().getId() == 7){ arrayMob.add(new Mob(game, 5, 2, "down", "", 0, 0, 0, 10)); arrayMob.add(new Mob(game, 7, 7, "right", "", 0, 9, 0, 0)); arrayMob.add(new Mob(game, 7, 10, "right", "", 0, 7, 0, 0)); arrayMob.add(new Mob(game, 16, 14, "up", "", 0, 0, 9, 0)); arrayMob.add(new Mob(game, 18, 5, "left", "", 11, 0, 0, 0)); arrayMob.add(new Mob(game, 2, 12, "right", "", 0, 14, 0, 0)); } else if(game.getWorld().getId() == 8){ arrayMob.add(new Mob(game, 3, 11, "", "", 0, 0, 0, 0)); arrayMob.add(new Mob(game, 4, 11, "", "", 0, 0, 0, 0)); arrayMob.add(new Mob(game, 3, 12, "", "", 0, 0, 0, 0)); arrayMob.add(new Mob(game, 4, 12, "", "", 0, 0, 0, 0)); arrayMob.add(new Mob(game, 3, 7, "", "", 0, 0, 0, 0)); arrayMob.add(new Mob(game, 4, 7, "", "", 0, 0, 0, 0)); arrayMob.add(new Mob(game, 3, 8, "", "", 0, 0, 0, 0)); arrayMob.add(new Mob(game, 4, 8, "", "", 0, 0, 0, 0)); arrayMob.add(new Mob(game, 3, 3, "", "", 0, 0, 0, 0)); arrayMob.add(new Mob(game, 4, 3, "", "", 0, 0, 0, 0)); arrayMob.add(new Mob(game, 3, 4, "", "", 0, 0, 0, 0)); arrayMob.add(new Mob(game, 4, 4, "", "", 0, 0, 0, 0)); arrayMob.add(new Mob(game, 7, 3, "", "", 0, 0, 0, 0)); arrayMob.add(new Mob(game, 8, 3, "", "", 0, 0, 0, 0)); arrayMob.add(new Mob(game, 7, 4, "", "", 0, 0, 0, 0)); arrayMob.add(new Mob(game, 8, 4, "", "", 0, 0, 0, 0)); arrayMob.add(new Mob(game, 11, 3, "", "", 0, 0, 0, 0)); arrayMob.add(new Mob(game, 12, 3, "", "", 0, 0, 0, 0)); arrayMob.add(new Mob(game, 11, 4, "", "", 0, 0, 0, 0)); arrayMob.add(new Mob(game, 12, 4, "", "", 0, 0, 0, 0)); arrayMob.add(new Mob(game, 15, 3, "", "", 0, 0, 0, 0)); arrayMob.add(new Mob(game, 16, 3, "", "", 0, 0, 0, 0)); arrayMob.add(new Mob(game, 15, 4, "", "", 0, 0, 0, 0)); arrayMob.add(new Mob(game, 16, 4, "", "", 0, 0, 0, 0)); arrayMob.add(new Mob(game, 15, 7, "", "", 0, 0, 0, 0)); arrayMob.add(new Mob(game, 16, 7, "", "", 0, 0, 0, 0)); arrayMob.add(new Mob(game, 15, 8, "", "", 0, 0, 0, 0)); arrayMob.add(new Mob(game, 16, 8, "", "", 0, 0, 0, 0)); arrayMob.add(new Mob(game, 15, 11, "", "", 0, 0, 0, 0)); arrayMob.add(new Mob(game, 16, 11, "", "", 0, 0, 0, 0)); arrayMob.add(new Mob(game, 15, 12, "", "", 0, 0, 0, 0)); arrayMob.add(new Mob(game, 16, 12, "", "", 0, 0, 0, 0)); arrayMob.add(new Mob(game, 2, 10, "right", "turnRight", 0, 3, 0, 3)); arrayMob.add(new Mob(game, 2, 6, "right", "turnRight", 0, 3, 0, 3)); arrayMob.add(new Mob(game, 2, 2, "right", "turnRight", 0, 3, 0, 3)); arrayMob.add(new Mob(game, 6, 2, "right", "turnRight", 0, 3, 0, 3)); arrayMob.add(new Mob(game, 10, 2, "right", "turnRight", 0, 3, 0, 3)); arrayMob.add(new Mob(game, 14, 2, "right", "turnRight", 0, 3, 0, 3)); arrayMob.add(new Mob(game, 14, 6, "right", "turnRight", 0, 3, 0, 3)); arrayMob.add(new Mob(game, 14, 10, "right", "turnRight", 0, 3, 0, 3)); arrayMob.add(new Mob(game, 5, 13, "left", "turnRight", 3, 0, 3, 0)); arrayMob.add(new Mob(game, 5, 9, "left", "turnRight", 3, 0, 3, 0)); arrayMob.add(new Mob(game, 5, 5, "left", "turnRight", 3, 0, 3, 0)); arrayMob.add(new Mob(game, 9, 5, "left", "turnRight", 3, 0, 3, 0)); arrayMob.add(new Mob(game, 13, 5, "left", "turnRight", 3, 0, 3, 0)); arrayMob.add(new Mob(game, 17, 5, "left", "turnRight", 3, 0, 3, 0)); arrayMob.add(new Mob(game, 17, 9, "left", "turnRight", 3, 0, 3, 0)); arrayMob.add(new Mob(game, 17, 13, "left", "turnRight", 3, 0, 3, 0)); } for(Mob mob : arrayMob) { mob.changeDirection(); } } /** * @return le tableau d'ennemis */ public ArrayList<Mob> getArrayMob() { return arrayMob; } } <file_sep>package main.utils; import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; /** * Cette classe regroupe diverse fonctionnalités facilitant le codage d'autre classes * @author Octikoros * */ public class Utils { /** * @param path : le chemin d'accès vers le fichier * @return le contenu d'un fichier sous forme de string */ public static String loadFileAsString(String path) { // Permet de construire des chaînes de caractère StringBuilder builder = new StringBuilder(); try { // Génère un flux consacré à la lecture d'un fichier BufferedReader br = new BufferedReader(new FileReader(path)); String line; // Tant que la ligne n'est pas terminée while((line = br.readLine()) != null) { //aggrégation de la variable line avec le contenu du fichier builder.append(line + "\n"); } // Fermeture du flux consacré à la lecture br.close(); }catch(IOException e) { // Vérifie si il n'y a pas eu d'erreur de lecture e.printStackTrace(); } return builder.toString(); } /** * @param number : le numéro "string" à mettre sous forme integer * @return un string sous forme d'integer */ public static int parseInt(String number) { try { return Integer.parseInt(number); }catch(NumberFormatException e) { // Vérifie si le format est bien celui d'un numéro e.printStackTrace(); return 0; } } } <file_sep># projetJava Projet Java dans un cadre scolaire <file_sep>package main; import control.GameController; import model.Game; import view.GameViewConsole; import view.GameViewGUI; /** * Cette classe permet de lancer le jeu * @author Octikoros * */ public class Launcher { public static void main(String[] args) { // Création du modèle Game model = new Game("Pète une case !"); model.init(); //Création des contrôleurs : un pour chaque vue //Chaque contrôleur doit avoir une référence vers le modèle pour pouvoir le commander GameController ctrlGUI = new GameController(model); GameController ctrlConsole = new GameController(model); // Création des vues // Chaque vue doit connaître son contrôleur et avoir une référence vers le modèle GameViewGUI GUI = new GameViewGUI(model, ctrlGUI); GameViewConsole console = new GameViewConsole(model, ctrlConsole); // On donne la référence à la vue pour chaque contrôleur ctrlGUI.addView(GUI); ctrlConsole.addView(console); } } <file_sep>package main.gfx; import java.io.File; import java.io.IOException; import javax.sound.sampled.AudioFormat; import javax.sound.sampled.AudioInputStream; import javax.sound.sampled.AudioSystem; import javax.sound.sampled.Clip; import javax.sound.sampled.FloatControl; import javax.sound.sampled.LineUnavailableException; import javax.sound.sampled.UnsupportedAudioFileException; import javax.sound.sampled.DataLine.Info; /** * Cette classe représente la musique du jeu * @author Octikoros * */ public class Music { // Le fichier .wav comportant le son private File soundFile; // Le flux permettant de transporter le son en output private AudioInputStream stream; // Le format du son (.wav) private AudioFormat format; // Les informations supplémentaires concernant le son private Info info; // Ce qui permet de lancer le son private Clip clip; // Permet de contrôler divers éléments du son (par exemple les décibels) private FloatControl control; // Le chemin d'accès au fichier audio private String path; /** * Initialisation d'un nouveau son * @param path : chemin d'accès au fichier audio */ public Music(String path) { this.path = path; } /** * Permet de jouer le son */ public void playSound() { try { soundFile = new File(path); stream = AudioSystem.getAudioInputStream(soundFile); format = stream.getFormat(); info = new Info(Clip.class, format); clip = (Clip) AudioSystem.getLine(info); clip.open(stream); if(path != "res/music/fart.wav") clip.loop(Clip.LOOP_CONTINUOUSLY); control = (FloatControl) clip.getControl(FloatControl.Type.MASTER_GAIN); control.setValue(-20); clip.start(); } catch (UnsupportedAudioFileException | IOException | LineUnavailableException e) { e.printStackTrace(); } } /** * Permet d'arrêter le son lorsqu'il est en train d'être joué */ public void stopSound() { clip.stop(); } } <file_sep>package main.entities; import java.awt.Graphics; import main.gfx.Assets; import main.tiles.Tile; import model.Game; /** * Cette classe représente un joueur * @author Octikoros * */ public class Player extends MobileEntity{ /** * Initialisation d'un nouveau joueur * @param x : abscisse * @param y : ordonnée */ public Player(Game game, int positionX, int positionY) { super(game, positionX, positionY, MobileEntity.DEFAULT_WIDTH, MobileEntity.DEFAULT_HEIGHT); game.getWorld().getGridCon()[startXCon][startYCon] = "[P]"; } @Override /** * Affiche les éléments mis à jour */ public void renderGUI(Graphics g) { g.drawImage(Assets.player, (int) x, (int) y, width, height, null); } /** * Affiche les éléments mis à jour en console */ public void renderCon(){ game.getWorld().getGridCon()[xCon][yCon] = "[P]"; } /** * Permet de changer la position du joueur */ public void move(){ moveX(); moveY(); for(Mob mob : game.getList().getArrayMob()) { if(collisionEntity(mob)) restart(); } } /** * Gère le déplacement horizontal du joueur */ public void moveX() { centerX = (int) (x + xMove + (hitbox.x / 2) + (hitbox.y / 2)) / Tile.TILEWIDTH; centerY = (int) (y + (hitbox.x / 2) + (hitbox.y / 2)) / Tile.TILEHEIGHT; // Mouvement à droite if(xMove > 0 || xMoveCon > 0) { if(!collisionTile(centerX, centerY)) { x += xMove; } movexCon(); } // Mouvement à gauche else if(xMove < 0 || xMoveCon < 0) { if(!collisionTile(centerX, centerY)) { x += xMove; } movexCon(); } } /** * Gère le déplacement vertical du joueur */ public void moveY() { centerX = (int) (x +(hitbox.x / 2) + (hitbox.y / 2)) / Tile.TILEWIDTH; centerY = (int) (y + yMove + (hitbox.x / 2) + (hitbox.y / 2)) / Tile.TILEHEIGHT; // Mouvement vers le bas if(yMove > 0 || yMoveCon > 0) { if(!collisionTile(centerX, centerY)) { y += yMove; } moveyCon(); } // Mouvement vers le haut else if(yMove < 0 || yMoveCon < 0) { if(!collisionTile(centerX, centerY)) { y += yMove; } moveyCon(); } } /** * Gère le déplacement horizontal du joueur en console */ public void movexCon(){ game.getWorld().getGridCon()[xCon][yCon] = "[_]"; xCon += xMoveCon; if(collisionTileCon()) xCon -= xMoveCon; if(collisionEntityCon()) restart(); } /** * Gère le déplacement vertical du joueur en console */ public void moveyCon(){ game.getWorld().getGridCon()[xCon][yCon] = "[_]"; yCon += yMoveCon; if(collisionTileCon()) yCon -= yMoveCon; if(collisionEntityCon()) restart(); } /** * Réinitialise la postion du joueur */ public void restart(){ x = startX; y = startY; game.getWorld().getGridCon()[xCon][yCon] = "[_]"; xCon = startXCon; yCon = startYCon; game.setDeath(game.getDeath() + 1); game.getDS().playSound(); } /** * @return la valeur du centre horizontal du joueur */ public int getCenterX() { return centerX; } /** * @return la valeur du centre vertical du joueur */ public int getCenterY() { return centerY; } } <file_sep>package view; import java.awt.Color; import java.awt.Font; import java.awt.event.KeyEvent; import java.awt.event.KeyListener; import java.util.Observable; import control.GameController; import main.gfx.Assets; import model.Game; /** * Cette classe représente la vue graphique de l'architecture MVC * @author Octikoros * */ public class GameViewGUI extends GameView implements KeyListener{ /** * Initialisation d'une nouvelle vue GUI * @param model : le modèle * @param controller : le contrôleur */ public GameViewGUI(Game model, GameController controller) { super(model, controller); // Ajout d'un key listener à la fenêtre courante model.getDisplay().getFrame().addKeyListener(this); } @Override /** * Cette méthode est appelée lorsque le modèle notifie la vue d'un changement */ public void update(Observable o, Object arg) { render(); } @Override /** * Méthode appelée lorsqu'on presse une touche du clavier */ public void keyPressed(KeyEvent e) { if(!pushed) { int i = e.getKeyCode(); controller.moveGUI(i); pushed = true; } } @Override /** * Méthode appelée lorsqu'on relache une touche du clavier */ public void keyReleased(KeyEvent e) { pushed = false; model.getPlayer().setxMove(0); model.getPlayer().setyMove(0); model.getPlayer().setxMoveCon(0); model.getPlayer().setyMoveCon(0); } @Override public void keyTyped(KeyEvent e) { } /** * Rafraichissement de la fenêtre avec les éléments mis à jour */ public void render() { //model.bs = model.getDisplay().getCanvas().getBufferStrategy(); /*if(model.bs == null) { model.getDisplay().getCanvas().createBufferStrategy(3); render(); }*/ model.g = model.bs.getDrawGraphics(); model.g.clearRect(0, 0, model.getWidth(), model.getHeight()); // Début affichage model.getWorld().renderGUI(model.g); if(model.getPlayer() != null) { model.getPlayer().renderGUI(model.g); model.getList().renderGUI(model.g); model.g.drawImage(Assets.rip, 5, 20, 20, 20, null); model.g.setFont(new Font("Arial black", Font.PLAIN, 14)); model.g.setColor(Color.BLACK); model.g.drawString("Timer : " + Integer.toString(model.getScore()), 7, 17); model.g.drawString(Integer.toString(model.getDeath()), 32, 37); model.g.setColor(Color.WHITE); model.g.drawString("Timer : " + Integer.toString(model.getScore()), 5, 15); model.g.drawString(Integer.toString(model.getDeath()), 30, 35); } else { model.g.drawImage(Assets.time, 5, 20, 15, 20, null); model.g.setFont(new Font("Arial black", Font.PLAIN, 14)); model.g.setColor(Color.BLACK); model.g.drawString("Final result : " + Integer.toString(model.getResult()), 7, 17); model.g.drawString(Integer.toString(model.getTime()) + " sec", 32, 37); model.g.setColor(Color.WHITE); model.g.drawString("Final result : " + Integer.toString(model.getResult()), 5, 15); model.g.drawString(Integer.toString(model.getTime()) + " sec", 30, 35); } // Fin affichage model.bs.show(); model.g.dispose(); } } <file_sep>package main.test; import static org.junit.Assert.*; import org.junit.Before; import org.junit.Test; import main.display.Display; import main.entities.Mob; import main.entities.Player; import main.worlds.World; import model.Game; /** * Cette classe va effectuer certains tests unitaires * @author Octikoros * */ public class JUnitTest{ Player player; Game game; Mob mob; World world; Display display; @Before public void setUp(){ game = new Game("Title"); game.init(); display = new Display("Title", game.getWidth(), game.getHeight()); player = new Player(game, 3, 5); mob = new Mob(game, 3, 6, "" , "", 0, 0, 0, 0); } @Test public void test(){ assertEquals(79, player.getX(), 0.0); assertEquals(129, player.getY(), 0.0); assertEquals(3, player.getxCon(), 0.0); assertEquals(5, player.getyCon(), 0.0); player.setxMove(player.getSpeed()); player.setxMoveCon(player.getSpeedCon()); player.setyMove(- player.getSpeed()); player.setyMoveCon(- player.getSpeedCon()); player.move(); assertEquals(104, player.getX(), 0.0); assertEquals(104, player.getY(), 0.0); assertEquals(4, player.getxCon(), 0.0); assertEquals(4, player.getyCon(), 0.0); player.restart(); assertEquals(79,player.getX(), 0.0); assertEquals(129,player.getY(), 0.0); assertEquals(3, player.getxCon(), 0.0); assertEquals(5, player.getyCon(), 0.0); } @Test public void testFlag(){ assertFalse(player.isFlagged(3, 5)); assertFalse(player.isFlaggedCon()); } @Test public void testMoveMob(){ mob.setDirection("up"); mob.changeDirection(); assertEquals(- mob.getSpeed(), mob.getyMove(), 0.0); mob.setDirection("right"); mob.changeDirection(); assertEquals(mob.getSpeed(), mob.getxMove(), 0.0); mob.setDirection("down"); mob.changeDirection(); assertEquals(mob.getSpeed(), mob.getyMove(), 0.0); mob.setDirection("left"); mob.changeDirection(); assertEquals(- mob.getSpeed(), mob.getxMove(), 0.0); } }
c0bceaf39221edc4c01faf65063a552fb500d6eb
[ "Markdown", "Java" ]
11
Java
eganlcq/projetJava
7829b6ee119d29813fea9c73b9ecf14adf51ebd2
e2cb6a83255ec70d40b191112110e884204ea898
refs/heads/master
<file_sep>from django.forms import ModelForm from django.contrib.auth.forms import UserCreationForm from django import forms from django.contrib.auth.models import User from django.contrib.auth.forms import AuthenticationForm, PasswordChangeForm from .models import * class BootstrapStylesMixin: form_fields = None def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) if self.form_fields: for fieldname in self.form_fields: self.fields[fieldname].widget.attrs = {'class': 'form-control'} else: raise ValueError('The form_fields should be set') class ItemForm(ModelForm): class Meta: model = Item fields = '__all__' class OrderType(ModelForm): class Meta: model = OrderItem fields = ['order_type'] class OrderForm(ModelForm): class Meta: model = Order fields = '__all__' class CreateUserForm(UserCreationForm): class Meta: model = User fields = ['first_name', 'last_name', 'username', 'email', '<PASSWORD>', '<PASSWORD>'] class CustomerForm(ModelForm): class Meta: model = Customer fields = '__all__' exclude = ['user'] class MyPasswordChangeForm(BootstrapStylesMixin, PasswordChangeForm): form_fields = ['old_password', 'new_password1', 'new_password2'] <file_sep># Generated by Django 3.1.3 on 2021-05-17 15:27 from django.db import migrations, models import django.utils.timezone class Migration(migrations.Migration): dependencies = [ ('store', '0012_auto_20210517_0633'), ] operations = [ migrations.AddField( model_name='customer', name='date_created', field=models.DateTimeField(auto_now_add=True, default=django.utils.timezone.now), preserve_default=False, ), ] <file_sep># Generated by Django 3.1.3 on 2021-05-10 18:01 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('store', '0001_initial'), ] operations = [ migrations.AddField( model_name='item', name='type', field=models.CharField(choices=[('BREAKFAST', 'BREAKFAST'), ('LUNCH', 'LUNCH'), ('DINNER', 'DINNER')], max_length=200, null=True), ), ] <file_sep># Generated by Django 3.1.3 on 2021-05-26 14:27 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('store', '0027_auto_20210525_1316'), ] operations = [ migrations.AddField( model_name='item', name='available', field=models.CharField(choices=[('Yes', 'Yes'), ('No', 'No')], default='Yes', max_length=200, null=True), ), ] <file_sep>virtualenv pillow django-filter~=2.4.0 Django~=3.1.3<file_sep># Generated by Django 3.1.3 on 2021-05-17 06:33 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('store', '0011_auto_20210514_0643'), ] operations = [ migrations.AlterField( model_name='item', name='category', field=models.CharField(choices=[('VEG', 'VEG'), ('NON-VEG', 'NON-VEG'), ('SNACKS', 'SNACKS')], max_length=200, null=True), ), ] <file_sep>{% extends 'stores/main.html' %} {% load static %} {% block content %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0, shrink-to-fit=no"> <title>Untitled</title> <link rel="stylesheet" href="{% static 'css/bootstrap.min.css' %}"> <link rel="stylesheet" href="{% static 'css/Navigation-with-Search.css' %}"> <link rel="stylesheet" href="{% static 'css/Projects-Horizontal.css' %}"> <link rel="stylesheet" href="{% static 'css/styles.css' %}"> </head> <body> <div> <h2 style="align-content: center">About Online Food Ordering System</h2> <hr> <p>Contrary to popular belief, Lorem Ipsum is not simply random text. It has roots in a piece of classical Latin literature from 45 BC, making it over 2000 years old. <NAME>, a Latin professor at Hampden-Sydney College in Virginia, looked up one of the more obscure Latin words, consectetur, from a Lorem Ipsum passage, and going through the cites of the word in classical literature, discovered the undoubtable source. Lorem Ipsum comes from sections 1.10.32 and 1.10.33 of "de Finibus Bonorum et Malorum" (The Extremes of Good and Evil) by Cicero, written in 45 BC. This book is a treatise on the theory of ethics, very popular during the Renaissance. The first line of Lorem Ipsum, "Lorem ipsum dolor sit amet..", comes from a line in section 1.10.32. </p> </div> <hr> <section class="projects-horizontal"> <div class="container"> <div class="intro"> <h2 class="text-center">Reviews from our Satisfied Customers </h2> </div> <div class="row projects"> <div class="col-sm-6 item"> <div class="row"> <div class="col-md-12 col-lg-5"><a href="#"><img class="img-fluid" src="{% static 'images/rajini.jpg' %}" style="height: 150px; width: 150px"></a></div> <div class="col"> <h3 class="name"><NAME></h3> <p class="description">Aenean tortor est, vulputate quis leo in, vehicula rhoncus lacus. Praesent aliquam in tellus eu gravida.</p> </div> </div> </div> <div class="col-sm-6 item"> <div class="row"> <div class="col-md-12 col-lg-5"><a href="#"><img class="img-fluid" src="{% static 'images/ambani.jpg' %}" style="height: 150px; width: 150px"></a></div> <div class="col"> <h3 class="name">Ambani</h3> <p class="description">Aenean tortor est, vulputate quis leo in, vehicula rhoncus lacus. Praesent aliquam in tellus eu gravida.</p> </div> </div> </div> <div class="col-sm-6 item"> <div class="row"> <div class="col-md-12 col-lg-5"><a href="#"><img class="img-fluid" src="{% static 'images/dhoni.jpg' %}" style="height: 150px; width: 150px"></a></div> <div class="col"> <h3 class="name"><NAME></h3> <p class="description">Aenean tortor est, vulputate quis leo in, vehicula rhoncus lacus. Praesent aliquam in tellus eu gravida.</p> </div> </div> </div> <div class="col-sm-6 item"> <div class="row"> <div class="col-md-12 col-lg-5"><a href="#"><img class="img-fluid" src="{% static 'images/modi.jpg' %}" style="height: 150px; width: 150px"></a></div> <div class="col"> <h3 class="name"><NAME></h3> <p class="description">Aenean tortor est, vulputate quis leo in, vehicula rhoncus lacus. Praesent aliquam in tellus eu gravida.</p> </div> </div> </div> </div> </div> </section> <script src="assets/js/jquery.min.js"></script> <script src="assets/bootstrap/js/bootstrap.min.js"></script> </body> </html> {% endblock %}<file_sep># Generated by Django 3.1.3 on 2021-05-13 09:02 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('store', '0009_auto_20210513_0856'), ] operations = [ migrations.RenameModel( old_name='Product', new_name='Item', ), ] <file_sep>from django.urls import path, reverse_lazy from django.contrib.auth.views import PasswordChangeView, PasswordChangeDoneView from django.contrib.auth import views as auth_views from . import views from .forms import MyPasswordChangeForm urlpatterns = [ path('', views.menu, name="menu"), path('cart/', views.cart, name="cart"), path('checkout/', views.checkout, name="checkout"), path('about/', views.about, name="about"), path('register/', views.register, name="register"), path('login/', views.loginPage, name="login"), path('logout/', views.logoutUser, name="logout"), path('user/', views.userPage, name="user-page"), path('account/', views.account, name="account"), path('search/', views.search, name="search"), path('update_item/', views.updateItem, name="updateitem"), path('process_order/', views.processOrder, name="process_order"), path('admin/', views.dashboard, name="dashboard"), path('admin/items', views.items, name="items"), path('customer/<str:pk>', views.customer, name="customer"), path('orders/', views.orders, name="orders"), # path('order_type/<str:pk>/', views.orderType, name="order_type"), path('update_order/<str:pk>/', views.updateOrder, name="update_order"), path('delete_order/<str:pk>/', views.deleteOrder, name="delete_order"), path('addItem/', views.addItem, name="addItem"), path('update_item/<str:pk>/', views.updateitem, name="update_item"), path('reset_password/', auth_views.PasswordResetView.as_view(template_name='stores/password_reset.html'), name="reset_password"), path('reset_password_sent/', auth_views.PasswordResetDoneView.as_view(template_name='stores/password_reset_sent.html'), name="password_reset_done"), path('reset/<uidb64>/<token>/', auth_views.PasswordResetConfirmView.as_view(template_name='stores/password_reset_form.html'), name="password_reset_confirm"), path('reset_password_complete/', auth_views.PasswordResetCompleteView.as_view(template_name='stores/password_reset_done.html'), name="password_reset_complete"), path('change_password/', PasswordChangeView.as_view( template_name='stores/change_password.html', success_url=reverse_lazy('password_change_done'), form_class=MyPasswordChangeForm ), name='password_change'), path('change_password/done/', PasswordChangeDoneView.as_view( template_name='stores/password_change_done.html' ), name='password_change_done'), ] <file_sep># Generated by Django 3.1.3 on 2021-05-14 06:43 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('store', '0010_auto_20210513_0902'), ] operations = [ migrations.AlterField( model_name='customer', name='email', field=models.EmailField(max_length=100, null=True), ), migrations.AlterField( model_name='item', name='price', field=models.DecimalField(decimal_places=2, max_digits=10, null=True), ), ] <file_sep>from django.db import models from django.contrib.auth.models import User # Create your models here.w class Customer(models.Model): user = models.OneToOneField(User, null=True, related_name='customer', on_delete=models.CASCADE, blank=True) name = models.CharField(max_length=100, null=True) email = models.EmailField(max_length=100, null=True) phone = models.CharField(max_length=100, null=True) profile_pic = models.ImageField(null=True, blank=True, default="user.jpg") date_created = models.DateTimeField(auto_now_add=True, null=True) def __str__(self): return str(self.name) class Item(models.Model): CATEGORY = ( ('VEG', 'VEG'), ('NON-VEG', 'NON-VEG'), ('SNACKS', 'SNACKS'), ) AVA = ( ('Yes', 'Yes'), ('No', 'No'), ) name = models.CharField(max_length=200, null=True) price = models.DecimalField(null=True, max_digits=10, decimal_places=2) category = models.CharField(max_length=200, null=True, choices=CATEGORY) description = models.CharField(max_length=500, null=True) image = models.ImageField(null=True, blank=True) available = models.CharField(max_length=200, null=True, choices=AVA, default=AVA[0][0]) def __str__(self): return self.name @property def imageURL(self): try: url = self.image.url except: url = '' return url class Order(models.Model): STATUS = ( ('Pending', 'Pending'), ('Delivered', 'Delivered'), ) customer = models.ForeignKey(Customer, on_delete=models.SET_NULL, blank=True, null=True) date_ordered = models.DateTimeField(auto_now_add=True) complete = models.BooleanField(default=False, null=True, blank=False) transaction_id = models.CharField(max_length=200, null=True) status = models.CharField(max_length=200, null=True, choices=STATUS, default=STATUS[0][0]) def __str__(self): return str(self.id) @property def delivery(self): delivery = False orderitems = self.orderitem_set.all() for i in orderitems: if i.order_type == "HOME DELIVERY": delivery = True return delivery @property def get_cart_total(self): orderitems = self.orderitem_set.all() total = sum([item.get_total for item in orderitems]) return total @property def get_cart_items(self): orderitems = self.orderitem_set.all() total = sum([item.quantity for item in orderitems]) return total class OrderItem(models.Model): ORDER_TYPE = ( ('HOME DELIVERY', 'HOME DELIVERY'), ('DINE IN', 'DINE IN'), ) item = models.ForeignKey(Item, on_delete=models.SET_NULL, null=True) order = models.ForeignKey(Order, on_delete=models.SET_NULL, blank=True, null=True) quantity = models.IntegerField(default=0, null=True, blank=True) order_type = models.CharField(max_length=100, null=True, blank=True, choices=ORDER_TYPE, default=ORDER_TYPE[0][0]) date_added = models.DateTimeField(auto_now_add=True) def __str__(self): return str(self.item) @property def get_total(self): total = self.item.price * self.quantity return total class DeliveryInfo(models.Model): customer = models.ForeignKey(Customer, on_delete=models.SET_NULL, blank=True, null=True) order = models.ForeignKey(Order, on_delete=models.SET_NULL, blank=True, null=True) address = models.CharField(max_length=200, null=True) city = models.CharField(max_length=200, null=True) state = models.CharField(max_length=200, null=True) zip_code = models.CharField(max_length=200, null=True) date_added = models.DateTimeField(auto_now_add=True) def __str__(self): return self.address <file_sep># Generated by Django 3.1.3 on 2021-05-12 16:09 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('store', '0006_item_image'), ] operations = [ migrations.RemoveField( model_name='order', name='status', ), ] <file_sep>import django_filters from django_filters import DateFilter from .models import * class OrderFilter(django_filters.FilterSet): start_date = DateFilter(field_name="date_ordered", lookup_expr='gte') end_date = DateFilter(field_name="date_ordered", lookup_expr='lte') class Meta: model = Order fields = ['status'] class MenuFilter(django_filters.FilterSet): class Meta: model = Item fields = ['category']<file_sep># F00d_0rdering_System ## Steps Please do install all the requirements pip install -r requirements.txt then cd into project directory Run => python manage.py runserver Please refer to project Abstract here => https://drive.google.com/file/d/1s6YHbJJt-RoRFMiFnK3OkeHbmNMD-Ra6/view?usp=sharing <file_sep># Generated by Django 3.1.3 on 2021-05-26 19:30 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('store', '0030_auto_20210526_1928'), ] operations = [ migrations.AlterField( model_name='order', name='status', field=models.CharField(choices=[('Pending', 'Pending'), ('Delivered', 'Delivered')], max_length=200, null=True), ), migrations.AlterField( model_name='orderitem', name='order_type', field=models.CharField(blank=True, choices=[('HOME DELIVERY', 'HOME DELIVERY'), ('DINE IN', 'DINE IN')], default='HOME DELIVERY', max_length=100, null=True), ), ] <file_sep># Generated by Django 3.1.3 on 2021-05-25 11:14 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('store', '0023_order_item'), ] operations = [ migrations.RemoveField( model_name='order', name='item', ), ] <file_sep>import datetime from django.shortcuts import render, redirect from django.http import JsonResponse import json from django.contrib.auth.forms import UserCreationForm from django.contrib.auth import authenticate, login, logout from django.contrib import messages from django.contrib.auth.decorators import login_required from django.contrib.auth.models import Group from .models import * from .forms import * from .filters import * from .decorators import unauthenticated_user, allowed_users, admin_only # Create your views here. def menu(request): # now = int((datetime.now()).strftime("%H")) if request.user.is_authenticated: customer = request.user.customer order, created = Order.objects.get_or_create(customer=customer, complete=False) items = order.orderitem_set.all() cartItems = order.get_cart_items else: order = {'get_cart_total': 0, 'get_cart_items': 0, 'order_type': False} items = [] cartItems = order['get_cart_items'] products = Item.objects.filter(available='Yes') myFilter = MenuFilter(request.GET, queryset=products) products = myFilter.qs context = {'products': products, 'cartItems': cartItems, 'myFilter': myFilter} return render(request, 'stores/menu.html', context) @unauthenticated_user def register(request): if request.user.is_authenticated: customer = request.user.customer order, created = Order.objects.get_or_create(customer=customer, complete=False) items = order.orderitem_set.all() cartItems = order.get_cart_items else: order = {'get_cart_total': 0, 'get_cart_items': 0, 'order_type': False} items = [] cartItems = order['get_cart_items'] form = CreateUserForm() if request.method == 'POST': form = CreateUserForm(request.POST) if form.is_valid(): user = form.save() username = form.cleaned_data.get('username') email = form.cleaned_data.get('email') messages.success(request, 'Account was created ') return redirect('login') context = {'cartItems': cartItems, 'form': form} return render(request, 'stores/register.html', context) @unauthenticated_user def loginPage(request): if request.user.is_authenticated: customer = request.user.customer order, created = Order.objects.get_or_create(customer=customer, complete=False) items = order.orderitem_set.all() cartItems = order.get_cart_items else: order = {'get_cart_total': 0, 'get_cart_items': 0, 'order_type': False} items = [] cartItems = order['get_cart_items'] if request.method == 'POST': username = request.POST.get('username') password = <PASSWORD>('<PASSWORD>') user = authenticate(request, username=username, password=<PASSWORD>) if user is not None: login(request, user) return redirect('menu') else: messages.info(request, 'Username Or Password is Incorrect') context = {'cartItems': cartItems} return render(request, 'stores/login.html', context) def logoutUser(request): logout(request) return redirect('menu') @login_required(login_url='login') def cart(request): if request.user.is_authenticated: customer = request.user.customer order, created = Order.objects.get_or_create(customer=customer, complete=False) items = order.orderitem_set.all() cartItems = order.get_cart_items else: order = {'get_cart_total': 0, 'get_cart_items': 0, 'order_type': False} items = [] cartItems = order['get_cart_items'] context = {'items': items, 'order': order, 'cartItems': cartItems} return render(request, 'stores/cart.html', context) @login_required(login_url='login') def checkout(request): if request.user.is_authenticated: customer = request.user.customer order, created = Order.objects.get_or_create(customer=customer, complete=False) items = order.orderitem_set.all() cartItems = order.get_cart_items else: order = {'get_cart_total': 0, 'get_cart_items': 0, 'order_type': False} items = [] cartItems = order['get_cart_items'] context = {'items': items, 'order': order, 'cartItems': cartItems} return render(request, 'stores/checkout.html', context) def about(request): if request.user.is_authenticated: customer = request.user.customer order, created = Order.objects.get_or_create(customer=customer, complete=False) items = order.orderitem_set.all() cartItems = order.get_cart_items else: order = {'get_cart_total': 0, 'get_cart_items': 0, 'order_type': False} items = [] cartItems = order['get_cart_items'] context = {'items': items, 'order': order, 'cartItems': cartItems} return render(request, 'stores/about.html', context) def updateItem(request): data = json.loads(request.body) productId = data['productId'] action = data['action'] # print('Action:', action) # print('productId:', productId) customer = request.user.customer product = Item.objects.get(id=productId) order, created = Order.objects.get_or_create(customer=customer, complete=False) orderItem, created = OrderItem.objects.get_or_create(order=order, item=product) if action == 'add': orderItem.quantity = (orderItem.quantity + 1) elif action == 'remove': orderItem.quantity = (orderItem.quantity - 1) orderItem.save() if orderItem.quantity <= 0: orderItem.delete() return JsonResponse('Item was added', safe=False) def processOrder(request): trasaction_id = datetime.datetime.now().timestamp() data = json.loads(request.body) if request.user.is_authenticated: customer = request.user.customer order, created = Order.objects.get_or_create(customer=customer, complete=False) total = float(data['form']['total']) order.transaction_id = trasaction_id if total == order.get_cart_total: order.complete = True order.save() if order.delivery: DeliveryInfo.objects.create( customer=customer, order=order, address=data['delivery']['address'], city=data['delivery']['city'], state=data['delivery']['state'], zip_code=data['delivery']['zip_code'], ) else: print("User is not logged in..") return JsonResponse('Payment Complete', safe=False) @login_required(login_url='login') @allowed_users(allowed_roles=['admin']) def dashboard(request): orders = Order.objects.all() customer = Customer.objects.all() total_customers = customer.count() total_orders = Order.objects.all().filter(complete='True').count() # if total_orders != 0: # total_orders = total_orders - total_customers delivered = Order.objects.all().filter(complete='True').filter(status='Delivered').count() pending = Order.objects.all().filter(complete='True').filter(status='Pending').count() # if pending != 0: # pending = pending - 1 ordrs = orders.filter(complete='True').order_by('-id')[:5][::1] context = {'orders': ordrs, 'customers': customer, 'total_orders': total_orders, 'delivered': delivered, 'pending': pending} return render(request, 'stores/dashboard.html', context) @login_required(login_url='login') @allowed_users(allowed_roles=['admin']) def items(request): products = Item.objects.all() context = {'products': products} return render(request, 'stores/items.html', context) @login_required(login_url='login') @allowed_users(allowed_roles=['admin']) def orders(request): orders = Order.objects.all().filter(complete='True').order_by('-id')[::1] customer = Customer.objects.all() context = {'orders': orders, 'customers': customer} return render(request, 'stores/order.html', context) @login_required(login_url='login') @allowed_users(allowed_roles=['admin']) def customer(request, pk): customer = Customer.objects.get(id=pk) orders = customer.order_set.filter(complete='True') order_count = orders.count() myFilter = OrderFilter(request.GET, queryset=orders) orders = myFilter.qs context = {'customer': customer, 'orders': orders, 'order_count': order_count, 'myFilter': myFilter} return render(request, 'stores/customer.html', context) @login_required(login_url='login') @allowed_users(allowed_roles=['admin']) def updateOrder(request, pk): order = Order.objects.get(id=pk) form = OrderForm(instance=order) if request.method == 'POST': form = OrderForm(request.POST, instance=order) if form.is_valid(): form.save() return redirect('/admin') context = {'form': form, 'ord': order} return render(request, 'stores/order_item.html', context) # def orderType(request, pk): # order = request.user.customer.order_set.get(id=pk) # form = OrderType(instance=order) # if request.method == 'POST': # form = OrderType(request.POST, instance=order) # if form.is_valid(): # form.save() # return redirect('/cart') # # context = {'form': form} # return render(request, 'stores/order_item.html', context) @login_required(login_url='login') @allowed_users(allowed_roles=['admin']) def deleteOrder(request, pk): order = Order.objects.get(id=pk) if request.method == 'POST': order.delete() return redirect('/admin') context = {'item': order} return render(request, 'stores/deleteItem.html', context) @login_required(login_url='login') @allowed_users(allowed_roles=['admin']) def addItem(request): form = ItemForm() if request.method == 'POST': form = ItemForm(request.POST, request.FILES) if form.is_valid(): form.save() return redirect('/admin/items') context = {'form': form} return render(request, 'stores/order_item.html', context) @login_required(login_url='login') @allowed_users(allowed_roles=['admin']) def updateitem(request, pk): item = Item.objects.get(id=pk) form = ItemForm(instance=item) if request.method == 'POST': form = ItemForm(request.POST, request.FILES, instance=item) if form.is_valid(): form.save() return redirect('/admin/items') context = {'form': form, 'item': item} return render(request, 'stores/order_item.html', context) @login_required(login_url='login') @allowed_users(allowed_roles=['customer', 'admin']) def userPage(request): orders = request.user.customer.order_set.filter(complete='True') total_orders = orders.count() delivered = orders.filter(status='Delivered').count() quantity = OrderItem.quantity pending = orders.filter(status='Pending').count() context = {'orders': orders, 'total_orders': total_orders, 'delivered': delivered, 'pending': pending, 'quantity': quantity} return render(request, 'stores/user.html', context) @login_required(login_url='login') @allowed_users(allowed_roles=['customer', 'admin']) def account(request): customer = request.user.customer form = CustomerForm(instance=customer) if request.method == 'POST': form = CustomerForm(request.POST, request.FILES, instance=customer) if form.is_valid(): form.save() return redirect('account') context = {'form': form} return render(request, 'stores/account.html', context) def search(request): # now = int((datetime.now()).strftime("%H")) if request.user.is_authenticated: customer = request.user.customer order, created = Order.objects.get_or_create(customer=customer, complete=False) items = order.orderitem_set.all() cartItems = order.get_cart_items else: order = {'get_cart_total': 0, 'get_cart_items': 0, 'order_type': False} items = [] cartItems = order['get_cart_items'] query = request.GET['query'] products = Item.objects.filter(available='Yes', name__icontains=query) print(products) myFilter = MenuFilter(request.GET, queryset=products) products = myFilter.qs context = {'products': products, 'cartItems': cartItems, 'myFilter': myFilter} return render(request, 'stores/menu.html', context)
5db24ce8fac3f0710729e78ba4bd140ccbc4eab5
[ "Markdown", "Python", "Text", "HTML" ]
17
Python
rakeshdama/Food_Ordering_System
573d4fdff674ff116f20dfcaf6bb28747c326b71
294cda903fc96fd41be0c88c1b3efc56ec56a4be
refs/heads/master
<file_sep>/* Copyright 2020 Mozilla Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import { BaseTreeViewer } from "./base_tree_viewer.js"; /** * @typedef {Object} PDFTTSViewerOptions * @property {HTMLDivElement} container - The viewer element. * @property {EventBus} eventBus - The application event bus. * @property {IL10n} l10n - Localization service. * @property {boolean} isNewSelection - track whether selection has changed * since last utterance. * @property {boolean} isPaused - track paused state ourselves as Microsoft * and Google Online voices don't report `speechSynthesis.paused` state. * @property {SpeechSynthesisVoice} [storedVoices] - Store voices so we don't * regenerate list which can change and desync indexes. */ /** * @typedef {Object} PDFTTSViewerRenderParameters * @property {OptionalContentConfig|null} optionalContentConfig - An * {OptionalContentConfig} instance. * @property {PDFDocument} pdfDocument - A {PDFDocument} instance. */ class PDFTTSViewer extends BaseTreeViewer { constructor(options) { super(options); this.l10n = options.l10n; this.isPaused = options.isPaused; this.isNewSelection = options.isNewSelection; document.addEventListener("selectionchange", () => { /* Reset if new selection made to allow playing it (but ignore empty selection). */ const text = window.getSelection().toString(); if (text) { this.toggleToolbarPlayingIcon(false); this.isNewSelection = true; } }); window.speechSynthesis.addEventListener("voiceschanged", () => { this.updateVoiceSelect(); }); } reset() { super.reset(); this._optionalContentConfig = null; } /** * @private */ _dispatchEvent(ttsAvailable) { this.eventBus.dispatch("ttsloaded", { source: this, ttsAvailable, }); } get isTTSAvailable() { return "speechSynthesis" in window; } get isPlaying() { // Note isPaused definition return speechSynthesis.speaking && !this.isPaused; } /* Render all HTML here. Can't put static HTML in viewer.html because container is cleared by base_tree_viewer.reset() */ /** * @param {PDFTTSViewerRenderParameters} params */ render({ optionalContentConfig, pdfDocument }) { const DEFAULT_RATE = 10; if (this._optionalContentConfig) { this.reset(); } this._optionalContentConfig = optionalContentConfig || null; this._pdfDocument = pdfDocument || null; if (!this.isTTSAvailable) { this._dispatchEvent(0); return; } const fragment = document.createDocumentFragment(); // PlayPause // Voice select const voiceslabel = document.createElement("label"); voiceslabel.textContent = "Choose voice"; voiceslabel.className = "toolbarLabel"; voiceslabel.setAttribute("data-l10n-id", "tts_voice_label"); fragment.appendChild(voiceslabel); const voicelist = this.updateVoiceSelect(); const voicespan = document.createElement("span"); voicespan.className = "dropdownSideBarButton"; voicespan.appendChild(voicelist); fragment.appendChild(voicespan); // Rate const ratelabel = document.createElement("label"); ratelabel.textContent = "Rate"; ratelabel.title = "Change rate (double-click here to reset)"; ratelabel.className = "toolbarLabel"; ratelabel.setAttribute("data-l10n-id", "tts_rate_label"); ratelabel.ondblclick = function () { rateinput.value = DEFAULT_RATE; localStorage.PDFJS_TTS_Rate = DEFAULT_RATE; }; fragment.appendChild(ratelabel); const ratespan = document.createElement("span"); ratespan.className = "range-field"; const rateinput = document.createElement("input"); rateinput.type = "range"; rateinput.id = "rate"; rateinput.min = 1; rateinput.max = 100; // Load rate pref if (localStorage.PDFJS_TTS_Rate == undefined) { rateinput.value = DEFAULT_RATE; } else { rateinput.value = localStorage.PDFJS_TTS_Rate; } // Save rate pref rateinput.onchange = function () { localStorage.PDFJS_TTS_Rate = this.value; }; ratespan.appendChild(rateinput); fragment.appendChild(ratespan); this._finishRendering(fragment, 1); } /* Update voicelist if exists and return voicelist. */ updateVoiceSelect() { const oldvoicelist = document.getElementById("voiceSelect"); const voicelist = document.createElement("select"); voicelist.id = "voiceSelect"; this.loadVoices(voicelist); if (oldvoicelist !== null) { oldvoicelist.replaceWith(voicelist); } return voicelist; } /* */ async loadVoices(voicelist) { const voices = window.speechSynthesis.getVoices(); voices.forEach(function (voice) { const option = document.createElement("option"); option.textContent = voice.name + (voice.default ? " (default)" : ""); voicelist.appendChild(option); }); /* Store for later use by playpause(), so we don't regenerate list which may have changed and will desync selectedIndex. */ this.storedVoices = voices; // Save voice preference voicelist.onchange = function () { localStorage.PDFJS_TTS_Voice = this.value; }; // Load voice preference if (localStorage.PDFJS_TTS_Voice == undefined) { voicelist.value = getDefaultVoiceName(voices); } else { voicelist.value = localStorage.PDFJS_TTS_Voice; } return voicelist; } getDefaultVoiceName(voices) { voices.forEach(function (voice) { if (voice.default) return voice.name + (voice.default ? " (default)" : ""); }); return undefined; } toggleToolbarPlayingIcon(playing) { const button = document.getElementById("ttsPlayPause"); if (playing) { button.className = "toolbarButton ttsPause"; } else { button.className = "toolbarButton ttsPlay"; } } startedPlaying() { this.isPaused = false; this.isNewSelection = false; /* Initial timeout required for Firefox, * which is slow to update speechSynthesis.speaking */ setTimeout(() => { // Set toolbar icon to Pause. if (this.isPlaying) { this.toggleToolbarPlayingIcon(true); } // Poll until speaking stops to reset toolbar icon to Play. this._pollStillSpeaking({ interval: 500 }).then(p => this.toggleToolbarPlayingIcon(p) ); }, 100); } pausedPlaying() { this.isPaused = true; } playpause() { const text = window.getSelection().toString(); if (!this.isNewSelection) { // Always speak new selection if (this.isPlaying) { // Pause speechSynthesis.pause(); this.pausedPlaying(); return; } else if (this.isPaused) { // Resume paused speech speechSynthesis.resume(); this.startedPlaying(); return; } } // Speak selected const msg = new SpeechSynthesisUtterance(); const voicesel = document.getElementById("voiceSelect"); msg.voice = this.storedVoices[voicesel.selectedIndex]; msg.rate = document.getElementById("rate").value / 10; msg.text = text; speechSynthesis.cancel(); speechSynthesis.speak(msg); this.startedPlaying(); } /** * @private */ async _pollStillSpeaking(interval) { console.log(" Start poll"); const executePoll = async (resolve, reject) => { console.log( " - poll", speechSynthesis.speaking, speechSynthesis.paused, speechSynthesis.pending ); const stillSpeaking = this.isPlaying; if (stillSpeaking) { setTimeout(executePoll, interval, resolve, reject); return false; } return resolve(stillSpeaking); }; return new Promise(executePoll); } /** * @private */ async _resetTTS() { if (!this._optionalContentConfig) { return; } // Fetch the default optional content configuration... const optionalContentConfig = await this._pdfDocument.getOptionalContentConfig(); this.eventBus.dispatch("optionalcontentconfig", { source: this, promise: Promise.resolve(optionalContentConfig), }); // ... and reset the sidebarView to the default state. this.render({ optionalContentConfig, pdfDocument: this._pdfDocument, }); } } export { PDFTTSViewer }; <file_sep># PDF.js with Text-to-speech This is a fork of [PDF.js](https://mozilla.github.io/pdf.js/) to adds Text-to-speech using the SpeechSynthesis interface of the Web Speech API. Implemented: toolbar button to speak the currently selected text Implemented: sidebar options to choose voice and speed.
c9bf524a9e2ff60e1a5f3e62e40b80b37e86d429
[ "JavaScript", "Markdown" ]
2
JavaScript
samharwood/pdf.js-tts
2e7eaa16a814bf2e19fead5bb47708c02fc232ed
6fffcafa39a049280f153851290ac182ab875c32
refs/heads/master
<file_sep>var app = angular.module("app",[]) .controller("ToDoController",["$scope",function($scope){ $scope.todo = []; $scope.percent = 0; //Añadir watcher para que siempre que se realice una acción se deseleccione $scope.$watchCollection('todo', function(newValue, oldValue){ console.log(oldValue); console.log(newValue); for (var i = 0; i < $scope.todo.length; i++){ if($scope.todo[i].selected){ $scope.todo[i].selected = false; } } }); $scope.addActv = function(){ $scope.todo.push($scope.newActv); $scope.newActv = {}; calculatePercent(); } $scope.delete = function(){ $scope.todo = []; calculatePercent(); } $scope.deleteSelected = function(){ for (var i = 0; i < $scope.todo.length; i++){ if($scope.todo[i].selected){ $scope.todo.splice(i, 1); i--; } } calculatePercent(); } $scope.doneSelected = function(){ for (var i = 0; i < $scope.todo.length; i++){ if($scope.todo[i].selected){ $scope.todo[i].done = true; } } calculatePercent(); } $scope.undoneSelected = function(){ for (var i = 0; i < $scope.todo.length; i++){ if($scope.todo[i].selected){ $scope.todo[i].done = false; } } calculatePercent(); } $scope.selectAll = function(){ for (var i = 0; i < $scope.todo.length; i++){ $scope.todo[i].selected = true; } } $scope.unselectAll = function(){ for (var i = 0; i < $scope.todo.length; i++){ $scope.todo[i].selected = false; } } function calculatePercent(){ var counter = 0; for (var i = 0; i < $scope.todo.length ; i++){ if($scope.todo[i].done){ counter++; } } $scope.percent = (counter / $scope.todo.length) * 100; } }]);
a44da864f3466d6bc7b88bfee91e57a3edc5f0d7
[ "JavaScript" ]
1
JavaScript
adrian-afergon/Angular-ToDoList
e43fb2eaf96a70a9b74bc7232cfd3f0403f64ade
4aea4b7d408302db81be8562451bcaa5aca6039d
refs/heads/master
<file_sep>package main import ( "fmt" "log" "net/http" // c "golang-rest-api-2/controller" _ "github.com/go-sql-driver/mysql" // "github.com/gorilla/mux" rt "golang-rest-api-2/routers" ) func main() { // router := mux.NewRouter().StrictSlash(false) // router.HandleFunc("/users", c.ReturnAllUsers).Methods("GET") // router.HandleFunc("/users/{id}", c.GetUser).Methods("GET") // router.HandleFunc("/users", c.InsertUser).Methods("POST") // router.HandleFunc("/users/{id}", c.DeleteUser).Methods("DELETE") // router.HandleFunc("/users/{id}", c.UpdateUser).Methods("PUT") router := rt.SetUsersRoute() fmt.Println("Connected to port 1234") log.Fatal(http.ListenAndServe(":1234", router)) } <file_sep>package routers import ( c "golang-rest-api-2/controller" "github.com/gorilla/mux" ) func SetUsersRoute() *mux.Router { usersRouter := mux.NewRouter().StrictSlash(false) usersRouter.HandleFunc("/users", c.ReturnAllUsers).Methods("GET") usersRouter.HandleFunc("/users/{id}", c.GetUser).Methods("GET") usersRouter.HandleFunc("/users", c.InsertUser).Methods("POST") usersRouter.HandleFunc("/users/{id}", c.DeleteUser).Methods("DELETE") usersRouter.HandleFunc("/users/{id}", c.UpdateUser).Methods("PUT") return usersRouter } <file_sep>package controller import ( "encoding/json" "fmt" "log" "net/http" c "golang-rest-api-2/config" m "golang-rest-api-2/model" "github.com/gorilla/mux" ) func ReturnAllUsers(w http.ResponseWriter, r *http.Request) { var users m.Users var arrUsers []m.Users var response m.Response db := c.Connect() defer db.Close() rows, err := db.Query("SELECT users.id, users.first_name,users.last_name FROM users") if err != nil { log.Print(err) } for rows.Next() { if err := rows.Scan(&users.ID, &users.FirstName, &users.LastName); err != nil { log.Fatal(err.Error()) } else { arrUsers = append(arrUsers, users) } } response.Status = 1 response.Message = "Success" response.Data = arrUsers w.Header().Set("Content-Type", "application/json") json.NewEncoder(w).Encode(response) } func GetUser(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "application/json") var user m.Users var arrUsers []m.Users var response m.Response db := c.Connect() defer db.Close() params := mux.Vars(r) query := `SELECT * FROM users WHERE id = ?` statement, err := db.Prepare(query) defer statement.Close() if err != nil { log.Print(err) } err = statement.QueryRow(params["id"]).Scan(&user.ID, &user.FirstName, &user.LastName) if err != nil { log.Print(err) } response.Status = 1 response.Message = "Success get data" response.Data = append(arrUsers, user) log.Print("Success get data") json.NewEncoder(w).Encode(response) } func InsertUser(w http.ResponseWriter, r *http.Request) { var user m.Users var response m.Response db := c.Connect() defer db.Close() w.Header().Set("Content-Type", "application/json") _ = json.NewDecoder(r.Body).Decode(&user) query := `INSERT INTO users(first_name, last_name) VALUES (?, ?)` statement, err := db.Prepare(query) defer statement.Close() if err != nil { log.Print(err) } _, err = statement.Exec(user.FirstName, user.LastName) if err != nil { log.Print(err) } response.Status = 1 response.Message = "Success Add" log.Print("Insert user data to database") json.NewEncoder(w).Encode(response) } func DeleteUser(w http.ResponseWriter, r *http.Request) { var response m.Response w.Header().Set("Content-Type", "application/json") params := mux.Vars(r) db := c.Connect() defer db.Close() query := `DELETE FROM users WHERE id = ?` statement, err := db.Prepare(query) if err != nil { log.Print(err) } defer statement.Close() _, err = statement.Exec(params["id"]) if err != nil { log.Print(err) } response.Status = 1 response.Message = "Success Delete" log.Print("Delete data from database") json.NewEncoder(w).Encode(response) } func UpdateUser(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "application/json") var user m.Users var arrUsers []m.Users var response m.Response db := c.Connect() defer db.Close() _ = json.NewDecoder(r.Body).Decode(&user) fmt.Println(user) params := mux.Vars(r) query := `UPDATE users SET first_name=?, last_name=? WHERE id=?` statement, err := db.Prepare(query) defer statement.Close() if err != nil { log.Print(err) } _, err = statement.Exec(user.FirstName, user.LastName, params["id"]) if err != nil { log.Print(err) } response.Status = 1 response.Message = "Success update data" response.Data = append(arrUsers, user) log.Print("Success update data") json.NewEncoder(w).Encode(response) } <file_sep>package config import ( "database/sql" "log" ) // Connect - db mysql connection func Connect() *sql.DB { db, err := sql.Open("mysql", "root:root@tcp(localhost:3306)/person_db") if err != nil { log.Fatal(err) } return db } <file_sep># golang-rest-api-2 Go REST API with person table
078454f78944c62fea8dec797c87b3f8e7a9f5dd
[ "Markdown", "Go" ]
5
Go
milhamhidayat/golang-rest-api-2
1cf1fa9c576f1bceb18ff67aef40ec4ce279fe50
5155691a3ae0592a5c10fd568068af3b4f1e6dc7
refs/heads/master
<repo_name>Gagan112233/bin2dec<file_sep>/script.js $( "#submitBtn" ).click(function() { var inputVal = $("#bin-input-field").val(); var inpFieldLen = inputVal.length; var result = 0; tempArr = inputVal.split(""); for(k=0;k<tempArr.length;k++){ if(tempArr[k] !== '0' && tempArr[k] !== '1'){ $("#dec-output-field").val(" "); return alert("Please Enter a Binary Number"); } } for(i=inputVal.length-1;i>=0;i--){ result += inputVal.charAt(i) * Math.pow(2, inputVal.length-1-i); } $("#dec-output-field").val(result); });<file_sep>/README.md # Binary to Decimal Convertor ### A simple Binary to Decimal Convertor built using HTML, CSS and JavaScript [Click Here to view the webpage](https://bin2dec-3b08a0.netlify.app) ![Binary to decimal convertor](https://i.postimg.cc/cJSckhvN/Binary-to-decimal-convertor.png)
e5fd4c91f4c78af690b7e724a9978d5b12be8908
[ "JavaScript", "Markdown" ]
2
JavaScript
Gagan112233/bin2dec
4974e1e3e5b781feea9928f62a193d79c7f3b10a
ed3386de753d0c10d6035cf8d73f37cda422199f
refs/heads/master
<repo_name>seedalpha/uv<file_sep>/index.js /** * UserVoice browserify */ /** * Module dependencies */ var script = require('scriptjs'); /** * Ployfill */ var UserVoice = window.UserVoice || []; /** * Helpers */ var helpers = {}; ['set', 'identify', 'addTrigger'].forEach(function(cmd) { helpers[cmd] = function(params) { UserVoice.push([cmd, params]); } }); /** * Load script */ exports = module.exports = function(key) { script('//widget.uservoice.com/' + key + '.js'); return helpers; }<file_sep>/README.md # UV browserify uservoice wrapper ### Installation $ npm install seed-uv ### Usage ```javascript var uv = require('seed-uv'); var UserVoice = uv(user_voice_key); // Set colors UserVoice.set({ accent_color: '#448dd6', trigger_color: 'white', trigger_background_color: 'rgba(46, 49, 51, 0.6)' }); // Identify the user and pass traits // To enable, replace sample data with actual user traits and uncomment the line UserVoice.identify({ email: user.email, name: user.name }); // Add default trigger to the bottom-right corner of the window: UserVoice.addTrigger({ mode: 'contact', trigger_position: 'bottom-right' }); ``` ### Author <NAME> <<EMAIL>> ### License MIT
2df42504069fad7676a9e2ab59f2b16892f71d14
[ "JavaScript", "Markdown" ]
2
JavaScript
seedalpha/uv
639921094d4ebd37ec877925c3bbeaf03bff86ce
6ecd8ef00f1d2ebb0bdd48d1308e4cf6cf36352a
refs/heads/master
<repo_name>fhuzero/assistive-mouse-capstone<file_sep>/cameramouse/control/filters.py """ Control Module Contents: Filters: FIR and IIR filters to reduce noise """ import time, copy import numpy as np import gesture_recognition class Filter(): def __init__(self, size): self.positions = np.ones((size, 2)) self.filter_size = size """Push a new detected centroid onto the stack""" def insert_point(self, point): self.positions[1:,:] = self.positions[:-1,:] self.positions[0, :] = point def get_filtered_position(self): pass class FIRFilter(Filter): def __init__(self, size): super().__init__(size) """Returns the averaged position of our x most recent detections""" def get_filtered_position(self, centroid): self.insert_point(centroid) p_x = np.average(self.positions[:, 0]) p_y = np.average(self.positions[:, 1]) try: return np.array([int(p_x), int(p_y)]) except: return np.array([0, 0]) class IIRFilter(Filter): def __init__(self, size): super().__init__(size) self.alpha = 0.7 # how much to weight old readings def get_filtered_position(self, centroid): try: frac = self.alpha/self.filter_size p_x = np.sum(frac*self.positions[:, 0]) + (1-self.alpha)*centroid[0] p_y = np.sum(frac*self.positions[:, 1]) + (1-self.alpha)*centroid[1] self.insert_point(np.array([p_x, p_y])) return np.array([p_x, p_y]) except: return np.array([0, 0])<file_sep>/gesture_learning/GestureRecognition.py #!/usr/bin/env python3 """ Description: Gesture recognition via MediaPipe keypoints Author: <NAME> (<EMAIL>) """ import os import argparse import socket import numpy as np import joblib from keras import models import keypoints as kp IP = 'localhost' # IP address of MediaPipe UDP client PORT = 2000 # port number of MediaPipe UDP client MAX_BYTES = 1024 # maximum number of bytes to read over UDP def green(string): return "\033[92m{}\033[00m".format(string) def yellow(string): return "\033[93m{}\033[00m".format(string) def red(string): return "\033[91m{}\033[00m".format(string) def display(gesture): if gesture == 0: # CLOSE string = green("CLOSE") + " | OPEN | FINGERS_ONE | FINGERS_TWO | THUMB_BENT" elif gesture == 1: # OPEN string = "CLOSE | " + green("OPEN") + " | FINGERS_ONE | FINGERS_TWO | THUMB_BENT" elif gesture == 2: # FINGERS_ONE string = "CLOSE | OPEN | " + green("FINGERS_ONE") + " | FINGERS_TWO | THUMB_BENT" elif gesture == 3: # FINGERS_TWO string = "CLOSE | OPEN | FINGERS_ONE | " + green("FINGERS_TWO") + " | THUMB_BENT" elif gesture == 4: # THUMB_BENT string = "CLOSE | OPEN | FINGERS_ONE | FINGERS_TWO | " + green("THUMB_BENT") else: # UNKNOWN string = red("CLOSE") + " | " + red("OPEN") + " | " + red("FINGERS_ONE") + " | " + red("FINGERS_TWO") + " | " + red("THUMB_BENT") print(string, end='\r') def main(args): assert os.path.splitext(args.model)[1] == '.h5' or os.path.splitext(args.model)[1] == '.sav' if args.model.endswith('.h5'): keras_model = True # load model model = models.load_model(args.model) # load data normalization parameters try: data = np.load(args.model.replace('.h5', '.npz')) mean = data['mean'] std = data['std'] except: print("Error: missing data normalization parameters") exit() elif args.model.endswith('.sav'): keras_model = False # load model model = joblib.load(args.model) print("=================================================================") print("Using model {}".format(args.model)) print("-----------------------------------------------------------------") # establish UDP connection sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) sock.bind((IP, PORT)) while True: try: # receive keypoints over UDP data, addr = sock.recvfrom(MAX_BYTES) keypoints = kp.decode(data) # convert keypoints to features features = kp.keypointsToFeatures(keypoints[:, :-1].flatten()) features = features.reshape((1, -1)) # skip bad data if np.isnan(np.sum(features)): continue # predict gesture if keras_model is True: features = kp.dataset.normalize(features, mean, std) output = model.predict(features)[0] gesture = np.argmax(output) else: gesture = model.predict(features)[0] # display gesture display(gesture) except KeyboardInterrupt: print("") break; if __name__ == '__main__': parser = argparse.ArgumentParser(add_help=False) parser.add_argument('model') args = parser.parse_args() main(args) <file_sep>/gesture_learning/keypoints.py """ Description: Functions to manipulate MediaPipe keypoints Author: <NAME> (<EMAIL>) """ import numpy as np import pandas as pd NUM_KEYPOINTS = 21 # number of keypoints # container for learning data and labels class dataset: def __init__(self, data, labels): self.data = data self.labels = labels if data.shape[0] != 0: self.mean = data.mean(axis=0) self.std = data.std(axis=0) else: self.mean = None self.std = None def normalize(data, mean, std): return (data - mean) / std def shuffle(a, b): p = np.random.permutation(min(len(a), len(b))) return a[p], b[p] # calculates the length of a vector def length(vector): return np.linalg.norm(vector) # calculates the angle of a vector with respect to the x-axis def angle(vector): return np.arctan2(vector[1], vector[0]) # expresses a point in a different coordinate frame def rigid_body_transform(point, origin, angle): R = np.array([[np.cos(angle), -np.sin(angle)], [np.sin(angle), np.cos(angle)]]) g = np.eye(3) g[0:2, 0:2] = R.transpose() g[0:2, 2] = (-1 * R.transpose()) @ origin return (g @ np.append(point, 1))[:-1] # normalizes keypoints in cartesian coordinates def normalize_cartesian(keypoints): if keypoints.ndim == 1: keypoints = keypoints.reshape((NUM_KEYPOINTS, -1)) flatten = True else: flatten = False normalized = np.zeros(keypoints.shape) origin = keypoints[0, 0:2] fixed = keypoints[9, 0:2] theta = angle(fixed - origin) + np.pi/2 for index, keypoint in enumerate(keypoints): normalized[index, 0:2] = rigid_body_transform(keypoint[0:2], origin, theta) * np.array([1, -1]) if flatten is True: normalized = normalized.flatten() return normalized # normalizes keypoints in polar coordinates def normalize_polar(keypoints): if keypoints.ndim == 1: keypoints = normalize_cartesian(keypoints.reshape((NUM_KEYPOINTS, -1))) flatten = True else: keypoints = normalize_cartesian(keypoints) flatten = False normalized = np.zeros(keypoints.shape) for index, keypoint in enumerate(keypoints): normalized[index, 0:2] = (length(keypoint[0:2]), angle(keypoint[0:2])) if flatten is True: normalized = normalized.flatten() return normalized # converts keypoints to a stirng def to_string(keypoints): string = "" if keypoints.ndim == 1: keypoints = keypoints.reshape((NUM_KEYPOINTS, -1)) if keypoints.shape == (NUM_KEYPOINTS, 2): keypoints = np.hstack((keypoints, np.zeros((NUM_KEYPOINTS, 1)))) for index, keypoint in enumerate(keypoints): x, y, z = keypoint string += str(x) + ',' + str(y) + ',' + str(z) + ';' return string # converts a string to keypoints def from_string(string): keypoints = np.zeros((NUM_KEYPOINTS, 3)) array = string.strip(';').split(';') for index, value in enumerate(array): x, y, z = [float(num) for num in value.strip(',').split(',')] keypoints[index] = (x, y, z) return keypoints # encodes keypoints as data def encode(keypoints): return to_string(keypoints).encode() # decodes keypoints from data def decode(data): return from_string(data.decode()) # parses file made up of lines containing 21 (x,y) keypoints and a label def parse(f, shuffle=False, normalization=None, split=None): raw = np.array(pd.read_csv(f, sep=',', header=None).values[1:]) data = raw[:, :-1].astype('float32') labels = raw[:, -1].astype('int8') if shuffle is True: data, labels = dataset.shuffle(data, labels) if normalization == 'cartesian': data = np.apply_along_axis(normalize_cartesian, 1, data) data = data[:, 2:] elif normalization == 'polar': data = np.apply_along_axis(normalize_polar, 1, data) data = data[:, 2:] elif normalization == 'features': data = np.apply_along_axis(keypointsToFeatures, 1, data) if split is not None: split = int(data.shape[0] * split) else: split = data.shape[0] train = dataset(data[:split], labels[:split]) test = dataset(data[split:], labels[split:]) return train, test # displays keypoints def display(keypoints): for index, keypoint in enumerate(keypoints): print("keypoint[" + str(index) + "] = " + str(keypoint)) ''' This function will convert a set of keypoints to a set of features. param keypoints: numpy array of 21 (x,y) keypoints return features: numpy array of 20 features ''' def keypointsToFeatures(keypoints): # construct feature matirx features = np.zeros(20) # distance ratio features for i in range(5): denominator = (keypoints[8*(i+1) - 1] - keypoints[0])**2 + (keypoints[8*(i+1)] - keypoints[1])**2 # distance from tip to palm for j in range(3): numerator = (keypoints[8*i + 2*j + 1] - keypoints[0])**2 + (keypoints[8*i + 2*j + 2] - keypoints[1])**2 # distance from root/mid1/mid2 to palm ratio = np.sqrt(numerator) / np.sqrt(denominator) features[i*3 + j] = ratio # features[i*3 + j] = ratio * 10 # 10 times to make more spearable? # finger number feature for i in range(len(features)): features[15] = sum(features[3 : 15 : 4] <= 1) * 10 # stretch finger number, weighted by 10 # angle features for i in range(4): # four pairs x1 = np.array([keypoints[8*(i+1) - 1] - keypoints[0], keypoints[8*(i+1)] - keypoints[1]], dtype=np.float32).T x2 = np.array([keypoints[8*(i+2) - 1] - keypoints[0], keypoints[8*(i+2)] - keypoints[1]], dtype=np.float32).T cos = np.sum(x1*x2) / (np.sqrt(np.sum(x1**2)) * np.sqrt(np.sum(x2**2))) # caculate cos(theta) # when zero angle, it is possible if cos > 1: cos = 1 elif cos < -1: cos = -1 features[16 + i] = (np.arccos(cos) / np.pi * 180) # features[16 + i] = (np.arccos(cos) / np.pi * 180)**2 # Note: use quadratic here # return feature matrix return features <file_sep>/cameramouse/control/mouse_states.py from gesture_recognition.gestures import Gestures class State(object): """ We define a state object which provides some utility functions for the individual states within the state machine. """ def __init__(self, mouse): print(str(self)) self.mouse = mouse def on_event(self, event): """ Handle events that are delegated to this State. """ pass def on_entry(self, event): """ What to do when you enter a given state """ return def __repr__(self): """ Leverages the __str__ method to describe the State. """ return self.__str__() def __str__(self): """ Returns the name of the State. """ return self.__class__.__name__ class OutOfRange(State): '''State when the hand is out of range.''' def on_event(self, event): if event != Gestures.out_of_range: new_state = InRange(self.mouse) new_state.on_entry() return new_state else: return self def on_entry(self): if self.mouse.state == "DOWN": self.mouse.mouse_up() return def execute(self, gesture, cmd_x, cmd_y): return class InRange(State): '''State where hand motion is tracked''' def on_event(self, event): if event == Gestures.drag: new_state = Drag(self.mouse) new_state.on_entry() return new_state elif event == Gestures.out_of_range: new_state = OutOfRange(self.mouse) new_state.on_entry() return new_state else: return self def on_entry(self): if self.mouse.state == "DOWN": self.mouse.mouse_up() return def execute(self, gesture, cmd_x, cmd_y): if gesture == Gestures.click: self.mouse.left_click() elif gesture == Gestures.double_click: self.mouse.double_click() elif gesture == Gestures.right_click: self.mouse.right_click() self.mouse.move(cmd_x, cmd_y) return class Drag(State): '''State where we have clicked and will move objects around on the screen or write in a note taking application''' def on_event(self, event): if event != Gestures.drag: new_state = InRange(self.mouse) new_state.on_entry() return new_state else: return self def on_entry(self): self.mouse.mouse_down() return def execute(self, gesture, cmd_x, cmd_y): self.mouse.moveD(cmd_x, cmd_y) # needs to use differences return<file_sep>/mediapipe/mediapipe/calculators/util/centroid_to_render_data_calculator.cc // Copyright 2019 The MediaPipe Authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #include "absl/memory/memory.h" // #include "absl/strings/str_cat.h" // #include "absl/strings/str_join.h" #include "mediapipe/framework/calculator_framework.h" #include "mediapipe/framework/calculator_options.pb.h" #include "mediapipe/framework/formats/landmark.pb.h" #include "mediapipe/framework/port/ret_check.h" #include "mediapipe/util/color.pb.h" #include "mediapipe/util/render_data.pb.h" namespace mediapipe { namespace { constexpr char kLandmarkTag[] = "LANDMARK"; constexpr char kRenderDataTag[] = "RENDER_DATA"; } // namespace class CentroidToRenderDataCalculator : public CalculatorBase { public: CentroidToRenderDataCalculator() {} ~CentroidToRenderDataCalculator() override {} static ::mediapipe::Status GetContract(CalculatorContract* cc); ::mediapipe::Status Open(CalculatorContext* cc) override; ::mediapipe::Status Process(CalculatorContext* cc) override; }; REGISTER_CALCULATOR(CentroidToRenderDataCalculator); ::mediapipe::Status CentroidToRenderDataCalculator::GetContract( CalculatorContract* cc) { cc->Inputs().Tag(kLandmarkTag).Set<Landmark>(); RET_CHECK(cc->Outputs().HasTag(kRenderDataTag)); cc->Outputs().Tag(kRenderDataTag).Set<RenderData>(); return ::mediapipe::OkStatus(); } ::mediapipe::Status CentroidToRenderDataCalculator::Open( CalculatorContext* cc) { cc->SetOffset(TimestampDiff(0)); return ::mediapipe::OkStatus(); } ::mediapipe::Status CentroidToRenderDataCalculator::Process( CalculatorContext* cc) { const auto& centroid = cc->Inputs().Tag(kLandmarkTag).Get<Landmark>(); auto render_data = absl::make_unique<RenderData>(); auto* render_data_annotation = render_data.get()->add_render_annotations(); render_data_annotation->set_thickness(4.0); auto* landmark_data = render_data_annotation->mutable_point(); /* LANDMARK */ landmark_data->set_normalized(false); landmark_data->set_x(centroid.x()); landmark_data->set_y(centroid.y()); /* SEND IT */ cc->Outputs().Tag(kRenderDataTag).Add(render_data.release(), cc->InputTimestamp()); return ::mediapipe::OkStatus(); } } // namespace mediapipe <file_sep>/gesture_learning/learn.py import numpy as np import numpy.linalg as la import pandas as pa import sklearn as sk from sklearn.cluster import KMeans from sklearn.ensemble import RandomForestClassifier from sklearn.mixture import GaussianMixture from sklearn import metrics from sklearn.manifold import TSNE import matplotlib.pyplot as plt import seaborn as sns import pickle import joblib from sklearn.ensemble import RandomForestClassifier def plotValidation(X, y, title, xlabel, ylabel, filename): fig = plt.figure() plt.plot(X, y) plt.title(title) plt.xlabel(xlabel) plt.ylabel(ylabel) plt.xticks(X) fig.savefig(filename) def tSNE(train, label, filename, k=None): ''' t-SNE is a tool to visualize high-dimensional data. It converts similarities between data points to joint probabilities and tries to minimize the Kullback-Leibler divergence between the joint probabilities of the low-dimensional embedding and the high-dimensional data ''' embedded = TSNE(n_components=2, verbose=1, perplexity=40, n_iter=500).fit_transform(train) # embedded = TSNE(n_components=2).fit_transform(train) df = pa.DataFrame(train) df['label'] = label df_plot = df.copy() df_plot['tsne-2d-one'] = embedded[:, 0] df_plot['tsne-2d-two'] = embedded[:, 1] plt.figure(figsize=(8,5)) snsplt = sns.scatterplot( x="tsne-2d-one", y="tsne-2d-two", hue="label", palette=sns.color_palette("hls", k), data=df_plot, legend="full", alpha=1 ) snsplt.get_figure().savefig(filename) ''' This function will read in raw data, return a train matrix after data modification. Raw data: Each line is corresponding to one image. Each line has 21x2 numbers, which indicates (x, y) of 21 joint locations. Note that these are joint CENTRE locations. Note that (x, y) are already normalized by the palm key point. The order of 21 joints is Palm, Thumb root, Thumb mid1, Thumb mid2, Thumb tip, Index root, Thumb mid1, Thumb mid2, Index tip, Middle root, Middle mid1, Middle mid2, Middle tip, Ring root, Ring mid1, Ring mid2, Ring tip, Pinky root, Pinky mid1, Pinky mid2, Pinky tip. Revised data: Each line is corresponding to one image. Each line has 20 numbers. The order of 20 numbers is ratio of distance of (root, mid) / distance of tip of (Thumb, Index, Middle, Ring, Pinky); finger count; angle between fingers. param file: raw data file path param n: the number of samples we using; default None, use all samples return train: revised trained data ''' def generateTrainAndTest(file, n=None): # read in dataset and slice rawData = np.array(pa.read_csv(file, sep=",", header=None).values[1:]) label = rawData[:, -1] data = rawData[:, :-1] if n != None: data = data[:n, :] # Note: only use n lines # construct feature matirx feature = np.zeros((data.shape[0], 20)) # distance ratio features for i in range(5): denominator = (data[:, 8*(i+1) - 1] - data[:, 0])**2 + (data[:, 8*(i+1)] - data[:, 1])**2 # distance from tip to palm for j in range(3): numerator = (data[:, 8*i + 2*j + 1] - data[:, 0])**2 + (data[:, 8*i + 2*j + 2] - data[:, 1])**2 # distance from root/mid1/mid2 to palm ratio = np.sqrt(numerator) / np.sqrt(denominator) feature[:, i*3 + j] = ratio # feature[:, i*3 + j] = ratio * 10 # 10 times to make more spearable? # finger number feature for i in range(len(feature)): temp = feature[i, :] feature[i, 15] = sum(temp[2 : 15 : 3] <= 1) * 10 # stretch finger number, weighted by 10 # angle features for i in range(4): # four pairs x1 = np.array([data[:, 8*(i+1) - 1] - data[:, 0], data[:, 8*(i+1)] - data[:, 1]], dtype=np.float32).T x2 = np.array([data[:, 8*(i+2) - 1] - data[:, 0], data[:, 8*(i+2)] - data[:, 1]], dtype=np.float32).T cos = np.sum(x1*x2, axis=1) / (np.sqrt(np.sum(x1**2, axis=1)) * np.sqrt(np.sum(x2**2, axis=1))) # caculate cos(theta) # when zero angle, it is possible cos[cos > 1] = 1 cos[cos < -1] = -1 feature[:, 16 + i] = (np.arccos(cos) / np.pi * 180) # feature[:, 16 + i] = (np.arccos(cos) / np.pi * 180)**2 # Note: use quadratic here # shuffle the dataset and divide into 80/20 indices = np.arange(feature.shape[0]) np.random.shuffle(indices) feature = feature[indices] label = label[indices] n_train = int(feature.shape[0] * 0.8) feature_train, feature_test = feature[:n_train], feature[n_train:] label_train, label_test = label[:n_train], label[n_train:] # return revised matrix return feature_train, label_train, feature_test, label_test def getAccuracy(prediction, truth, funcName): n = len(prediction) acc = sum(prediction == truth) / n * 100 # print("The accuracy of " + funcName + " is " + str(acc) + "%") return acc def unsupervisedMetrics(feature, prediction): chIndex = metrics.calinski_harabasz_score(feature, prediction) # Calinski-Harabasz Index; a higher Calinski-Harabasz score relates to a model with better defined clusters dbIndex = metrics.davies_bouldin_score(feature, prediction) # Davies-Bouldin index; a lower Davies-Bouldin index relates to a model with better separation between the clusters siScode = metrics.silhouette_score(feature, prediction, metric='euclidean') # Silhouette Coefficient score; a higher Silhouette Coefficient score relates to a model with better defined clusters # print("ch: " + str(chIndex) + ", db: " + str(dbIndex) + ", si: " + str(siScode)) return chIndex, dbIndex, siScode def unsupervisedReorder(feature, label, prediction, k): # sort label and prediction indices = np.argsort(label) label = label[indices] # 0~4 prediction = prediction[indices] feature = feature[indices] # reorder prediction convert = {} # conversion map; convert key to value i = 0 for idx in range(len(prediction)): if prediction[idx] not in convert: convert[prediction[idx]] = i i += 1 if i == k: break for idx in range(len(prediction)): prediction[idx] = convert[prediction[idx]] return feature, label, prediction ''' K_means algorithms; use validation to find the best K param train: tarin matrix return chIndex Calinski-Harabasz Index array ''' def K_means_validation(train, min, max): chIndex = [] # Calinski-Harabasz Index; a higher Calinski-Harabasz score relates to a model with better defined clusters dbIndex = [] # Davies-Bouldin index; a lower Davies-Bouldin index relates to a model with better separation between the clusters siScode = [] # Silhouette Coefficient score; a higher Silhouette Coefficient score relates to a model with better defined clusters for k in range(min, max+1): kmeans_model = KMeans(n_clusters=k, random_state=0).fit(train) # print(kmeans_model.labels_) # print(kmeans_model.cluster_centers_) labels = kmeans_model.labels_ chIndex.append(metrics.calinski_harabasz_score(train, labels)) dbIndex.append(metrics.davies_bouldin_score(train, labels)) siScode.append(metrics.silhouette_score(train, labels, metric='euclidean')) # plot image here plotValidation(range(min, max+1), chIndex, "K_means validation", "K", "Calinski-Harabasz Index", "/Users/sean/GestureLearning/K_means_ch_validation") plotValidation(range(min, max+1), dbIndex, "K_means validation", "K", "Davies-Bouldin Index", "/Users/sean/GestureLearning/K_means_db_validation") plotValidation(range(min, max+1), siScode, "K_means validation", "K", "Silhouette Coefficient score", "/Users/sean/GestureLearning/K_means_si_validation") # return Calinski-Harabasz Index array return chIndex ''' Use best K to train. ''' def K_means_train(feature_train, label_train, feature_test, label_test, k, filename=None): km = KMeans(n_clusters=k, random_state=0) km.fit(feature_train) # Train accuracy prediction_train = km.predict(feature_train) feature_train, label_train, prediction_train = unsupervisedReorder(feature_train, label_train, prediction_train, k) train_acc = getAccuracy(prediction_train, label_train, "Kmeans Train") # Test accuracy prediction_test = km.predict(feature_test) feature_test, label_test, prediction_test = unsupervisedReorder(feature_test, label_test, prediction_test, k) test_acc = getAccuracy(prediction_test, label_test, "Kmeans Test") # check index ch, db, si = unsupervisedMetrics(feature_test, prediction_test) # save model joblib.dump(km, './models/KMEANS.sav') # dump the Kmean model # write to csv if filename: df = pa.DataFrame(prediction_test) df.to_csv(filename, index=False) return test_acc, ch, db, si ''' K_means algorithms; use validation to find the best K param train: tarin matrix return chIndex Calinski-Harabasz Index array ''' def EM_validation(train, min, max): chIndex = [] # Calinski-Harabasz Index; a higher Calinski-Harabasz score relates to a model with better defined clusters dbIndex = [] # Davies-Bouldin index; a lower Davies-Bouldin index relates to a model with better separation between the clusters siScode = [] # Silhouette Coefficient score; a higher Silhouette Coefficient score relates to a model with better defined clusters for k in range(min, max+1): gmm = GaussianMixture(n_components=k, covariance_type='full', init_params='kmeans', max_iter=5000) # 'spherical', 'diag', 'tied', 'full' gmm.fit(train) labels = gmm.predict(train) chIndex.append(metrics.calinski_harabasz_score(train, labels)) dbIndex.append(metrics.davies_bouldin_score(train, labels)) siScode.append(metrics.silhouette_score(train, labels, metric='euclidean')) # plot image here plotValidation(range(min, max+1), chIndex, "EM validation", "K", "Calinski-Harabasz Index", "/Users/sean/GestureLearning/EM_ch_validation") plotValidation(range(min, max+1), dbIndex, "EM validation", "K", "Davies-Bouldin Index", "/Users/sean/GestureLearning/EM_db_validation") plotValidation(range(min, max+1), siScode, "EM validation", "K", "Silhouette Coefficient score", "/Users/sean/GestureLearning/EM_si_validation") # return Calinski-Harabasz Index array return chIndex ''' Use best K to train. ''' def EM_train(feature_train, label_train, feature_test, label_test, k, filename=None): gmm = GaussianMixture(n_components=k, covariance_type='spherical', init_params='kmeans', max_iter=250) # 'spherical', 'diag', 'tied', 'full' gmm.fit(feature_train) # Train accuracy prediction_train = gmm.predict(feature_train) feature_train, label_train, prediction_train = unsupervisedReorder(feature_train, label_train, prediction_train, k) train_acc = getAccuracy(prediction_train, label_train, "GMM Train") # Test accuracy prediction_test = gmm.predict(feature_test) feature_test, label_test, prediction_test = unsupervisedReorder(feature_test, label_test, prediction_test, k) test_acc = getAccuracy(prediction_test, label_test, "GMM Test") # check index ch, db, si = unsupervisedMetrics(feature_test, prediction_test) # save model joblib.dump(gmm, './models/GMM.sav') # dump the Kmean model # write to csv if filename: df = pa.DataFrame(prediction_test) df.to_csv(filename, index=False) return test_acc, ch, db, si ''' Random Forest with aggregated feature ''' def RF_train(feature_train, label_train, feature_test, label_test, filename=None): rf = RandomForestClassifier(max_depth=10, random_state=0) rf.fit(feature_train, label_train) # Train accuracy prediction_train = rf.predict(feature_train) trian_acc = getAccuracy(prediction_train, label_train, "RF Train") # Test accuracy prediction_test = rf.predict(feature_test) test_acc = getAccuracy(prediction_test, label_test, "RF Test") # save model joblib.dump(rf, './models/RF.sav') # dump the Kmean model # write to csv if filename: df = pa.DataFrame(prediction_test) df.to_csv(filename, index=False) return test_acc feature_train, label_train, feature_test, label_test = generateTrainAndTest('./dataset/fiveClass') epoches = 1 # KMean algorithms # acc, ch, db, si = 0, 0, 0, 0 # for i in range(epoches): # a, c, d, s = K_means_train(feature_train, label_train, feature_test, label_test, 5) # acc += a # ch += c # db += d # si += s # print("The accuracy of KMean is " + str(acc/epoches) + "%") # print("ch: " + str(ch/epoches) + ", db: " + str(db/epoches) + ", si: " + str(si/epoches)) # EM algorithms # acc, ch, db, si = 0, 0, 0, 0 # for i in range(epoches): # a, c, d, s = EM_train(feature_train, label_train, feature_test, label_test, 5) # acc += a # ch += c # db += d # si += s # print("The accuracy of GMM is " + str(acc/epoches) + "%") # print("ch: " + str(ch/epoches) + ", db: " + str(db/epoches) + ", si: " + str(si/epoches)) # Random Forest algorithms acc = 0 for i in range(epoches): acc += RF_train(feature_train, label_train, feature_test, label_test) print("The accuracy of RF is " + str(acc/epoches) + "%") # plot tSNE # tSNE(feature_train, label_train, './tSNE_5.jpg', 5) <file_sep>/mediapipe/mediapipe/calculators/util/pipe_writing_calculator.cc // Copyright 2019 The MediaPipe Authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include <memory> #include <fcntl.h> #include "mediapipe/framework/calculator_framework.h" #include "mediapipe/framework/formats/detection.pb.h" #include "mediapipe/framework/formats/landmark.pb.h" #include "mediapipe/framework/formats/location_data.pb.h" #include "mediapipe/framework/port/ret_check.h" #include <iostream> namespace mediapipe { namespace { constexpr char kNormalizedLandmarksTag[] = "LANDMARKS"; constexpr char kGestureTag[] = "GESTURE"; } // namespace class PipeWritingCalculator : public CalculatorBase { public: static ::mediapipe::Status GetContract(CalculatorContract* cc); ::mediapipe::Status Open(CalculatorContext* cc) override; ::mediapipe::Status Process(CalculatorContext* cc) override; private: int fd; }; REGISTER_CALCULATOR(PipeWritingCalculator); ::mediapipe::Status PipeWritingCalculator::GetContract( CalculatorContract* cc) { RET_CHECK(cc->Inputs().HasTag(kNormalizedLandmarksTag)); RET_CHECK(cc->Inputs().HasTag(kGestureTag)); // TODO: Also support converting Landmark to Detection. cc->Inputs().Tag(kNormalizedLandmarksTag).Set<NormalizedLandmarkList>(); cc->Inputs().Tag(kGestureTag).Set<int>(); return ::mediapipe::OkStatus(); } ::mediapipe::Status PipeWritingCalculator::Open( CalculatorContext* cc) { cc->SetOffset(TimestampDiff(0)); fd = open("/home/weihao/Mouse", O_WRONLY); return ::mediapipe::OkStatus(); } ::mediapipe::Status PipeWritingCalculator::Process( CalculatorContext* cc) { const auto& landmarks = cc->Inputs().Tag(kNormalizedLandmarksTag).Get<NormalizedLandmarkList>(); RET_CHECK_GT(landmarks.landmark_size(), 0) << "Input landmark vector is empty."; const auto& gesture = cc->Inputs().Tag(kGestureTag).Get<int>(); std::string res = ""; double x_avg = (landmarks.landmark(0).x() + landmarks.landmark(5).x() + landmarks.landmark(9).x() + landmarks.landmark(13).x() + landmarks.landmark(17).x()) / 5; double y_avg = (landmarks.landmark(0).y() + landmarks.landmark(5).y() + landmarks.landmark(9).y() + landmarks.landmark(13).y() + landmarks.landmark(17).y()) / 5; //double x_avg = (landmarks[8].x() + landmarks[12].x() + landmarks[16].x() + landmarks[20].x()) / 4; //double y_avg = (landmarks[8].y() + landmarks[12].y() + landmarks[16].y() + landmarks[20].y()) / 4; //res += std::to_string(landmarks[0].x()); res += std::to_string(x_avg); res += ","; //res += std::to_string(landmarks[0].y()); res += std::to_string(y_avg); res += ","; res += std::to_string(gesture); res += "\n"; write(fd, res.c_str(), res.length()); return ::mediapipe::OkStatus(); } } // namespace mediapipe <file_sep>/colour_segmentation_cpp/README.md ### Instructions for using this 1. mkdir -p build && cd build 2. cmake .. 3. make 4. ./hand_tracker ### Overview This is simply a c++ implementation of ```../cameramouse/hand_tracking/```. It was created to make the OpenCV code integrable with mediapipe. The resulting mediapipe code can be found in ```../mediapipe/mediapipe/calculators/util/hand_tracking_calculator.cc```. To view the mediapipe graph to understand how this works go https://viz.mediapipe.dev/ and paste the contents of ```../mediapipe/mediapipe/graphs/hand_tracking/gesture_recognition.pbtxt``` into it. <file_sep>/cameramouse/utils.py """ utils.py currently just has functions to load in classes """ """ Author: <NAME> Title: loaders.py - functions to load hardware objects Date Created: 28 Nov 2018 """ import hardware.monitor as monitor import hardware.mouse as mouse import hardware.camera as camera from control.controllers import * from control.filters import * from gesture_recognition.gestures import * from gesture_recognition.keyboard import KeyboardGestureRecognition from hand_tracking import tracking, colour_segmentation class Loader(): def load_monitor(os): if os not in ["linux", "windows"]: raise ValueError('Only Windows and Linux Supported') if os == "linux": print("[DEBUG] Loading Linux Monitor") return monitor.LinuxMonitor() elif os == "windows": print("[DEBUG] Loading Windows Monitor") return monitor.WindowsMonitor() def load_mouse(os): if os not in ["linux", "windows"]: raise ValueError('Only Windows and Linux Supported Currently') if os == "linux": print("[DEBUG] Loading Linux Mouse") return mouse.LinuxMouse() elif os == "windows": print("[DEBUG] Loading Windows Mouse") return mouse.WindowsMouse() def load_camera(opts): camera_type = opts["type"] src = int(opts["src"]) if camera_type not in ["webcam", "realsense"]: raise ValueError('Only standard webcam or realsense camera supported currently') if camera_type == "realsense": print("[DEBUG] Loading Realsense Camera") return camera.RealSenseCamera() elif camera_type == "webcam": print("[DEBUG] Loading Webcam Camera") return camera.WebcamCamera(opts["src"]) def load_control(opts, mouse, monitor, im_shape): def load_filter(filter_type, length): if filter_type == "iir": return IIRFilter(length) elif filter_type == "fir": return FIRFilter(length) filter_type = opts["filter"] filter_len = opts["filter_length"] control_type = opts["type"] if control_type not in ["absolute", "joystick", "relative"]: raise ValueError('Only absolute, relative or joystick style control supported') if filter_type not in ["iir", "fir"]: raise ValueError('Only iir and fir filters are supported') filter = load_filter(filter_type, filter_len) if control_type == "absolute": print("[DEBUG] Loading Absolute Controller") return AbsoluteControl(filter, mouse, monitor, im_shape) elif control_type == "relative": print("[DEBUG] Loading Relative Controller") return RelativeControl(filter, mouse) elif control_type == "joystick": print("[DEBUG] Loading Joystick Controller") return JoystickControl(filter, mouse, im_shape) def load_tracker(opts, camera): """ Function for loading various hand trackers/segmentation methods. Currently there's one tracker and one segmentation method so it's not really implemented """ seg_type = opts["segmentation"] track_type = opts["type"] if seg_type == "colour": return tracking.HandTracker(camera) def load_gesture(opts): gesture_type = opts["type"] if gesture_type not in ["keyboard", "none"]: raise ValueError('Select an available Gesture Recognition Module. Options: keyboard, none') if gesture_type == "keyboard": print("[DEBUG] Loading Keyboard Gesture Recognition") return KeyboardGestureRecognition() elif gesture_type == "none": print("[DEBUG] Loading Blank Gesture Recognition") return GestureRecognition()<file_sep>/README.md # assistive-mouse-capstone Empowering those who cannot use computer mouses/stylus' to be able to use them with only a webcam and some basic gestures. ## MediaPipe ### Installation Follow the instructions in `mediapipe/README.md` Note that this is using MediaPipe v0.7.0 with Bazel v1.2.1 ### Building Source ``` cd mediapipe ./scripts/build.sh ``` ### Running Demo 1 ``` cd mediapipe ./scripts/run_demo1.sh ``` Demo 1 uses a frame reduced MediaPipe (described in the capstone report, implemented in commit d98bf446c65d2c046703090f4216b1a2c5ee4469 in mediapipe, note assistive-mouse-capstone/mediapipe itself is also a repo). [gesture_detection_calculator.cc](https://github.com/toby-l-baker/assistive-mouse-capstone/blob/master/mediapipe/mediapipe/calculators/util/gesture_detection_calculator.cc) gets the coordinates of 21 key points and uses hand geometry to determine the current gesture, and uses a number to represent it. There are two versions of this file, the old version simply counts the number of scretch fingers, the [new version](https://github.com/toby-l-baker/assistive-mouse-capstone/blob/master/mediapipe/mediapipe/calculators/util/gesture_detection_new_calculator.cc) uses a gesture definition like [this](https://docs.google.com/presentation/d/1R5K-rlorkxrP03RoG5ys7vCLMY0H_5_y4Tqb3lC5Uv8/edit?usp=sharing). Currently if you build MediaPipe you get the old version, you need to mannually substitute the file to get the new version. The number representation of the gesture then goes to [pipe_writing_calculator.cc](https://github.com/toby-l-baker/assistive-mouse-capstone/blob/master/mediapipe/mediapipe/calculators/util/pipe_writing_calculator.cc) which calculates the centroid of the 5 picked key points (described in the report) and writes it to a FIFO structure with the gesture. The [mouse control script](https://github.com/toby-l-baker/assistive-mouse-capstone/blob/master/mouse-control-test/mouse_control_for_demo1_with_new_gesures.py) works with the new version. ### Running Demo 2 ``` cd mediapipe ./scripts/run_demo2.sh ``` Demo 2 aims to integrate HSV OpenCV Colour Segmentation with MediaPipe. This means calibration can happen automatically when MediaPipe detects the hand. It doens't work super reliably as MediaPipe has false positives. It needs improvements where when mediapipe is laggy, frames still get passed to the OpenCV Segmentation node. I believe it is possible to have some nodes receive data more often than others. It aims to get the benefits of MediaPipe with regard to key points for gestures and more speed by using the hand segmentation in parallel with MedaPipe. ### Networking Protocol: UDP IP Address: `127.0.0.1` Ports: `2000`, `3000`, `4000` The 21 key points of the hand can be received over ports `2000` or `3000`. The data is transmitted as a string formatted as `"x_i, y_i, z_i;"` where `1 <= i <= 21`. Note that each entry in the tuple is a floating-point number between 0 and 1. Hand tracking information can be received over port `4000`. The data is transmitted as a string formatted as `"x_cent, y_cent, x_rect, y_rect, w_rect, h_rect;"`. `(x_cent, y_cent)` is the location of the centroid of the hand expressed as floating-point numbers. `(x_rect, y_rect, w_rect, h_rect)` is the location and size of the bounding box expressed as floating-point numbers. Note that this information is only available when running Demo 2. ## OpenCV Read `cameramouse/README.md` to understand more about the purely OpenCV implementation and possible future steps on this particular avenue. Created since this will be portable to all OS's and is lightweight in terms of computation, currently runs at the full 30 FPS. MediaPipe is very promising and provides a lot of good information regarding gestures but is computationally expensive and only works on Linux. Differentiating hand gestures is hard with OpenCV but inputs such as voice could be useful. I believe Weihao had some luck with the voice recognition software [Snowboy](https://snowboy.kitt.ai/). ## Gesture Learning ### Dataset `gesture_learning/data/` stores all dataset we created. Each line in dataset consists (x, y) coordinates of 21 key points and its class number. We denote its class number in braces. twoClass includes close (0) and open (1) gestures; threeClass includes close (0), OK (1), open(2) gestures; fourClass includes close (0), open (1), OK (2) and click (index finger bent, 3) gestures; fiveClass includes close (0), open (1), scroll_down (index finger stretching, 2), scroll_up (ndex and middle fingers stretching, 3) and slow (thumb stretching, 4). See vedio example for more concrete gesture examples. ### Training `gesture_learning/learn.py` reads in raw dataset mentioned in the previous part, generates augmented features and runs KMeans/Gaussian Mixture/Random Forest Model. The augmented features are strecthing finger numbers, angles between finger pairs and finger distance ratio. See comments in code for more information. We also provide functionality that get mean validation accuracy in several epochs and save models for other use (intergrated in MediaPipe, i.e. `joblib.dump(modle, 'path')`). Moreover, it is easy to add parser and args to make the `learn.py` more flexible. `gesture_learning/keypoints.py` containts utility functions to parse gesture datasets or decode key point data transmitted via UDP. It also has several functions for key point normalization. `gesture_learning/template.py` is a template that can be used to get started with gesture learning. More information is contained in the comments in the file. ### Models `gesture_learning/models/` stores all models we trained for five models. There are KMeans, Gaussian Mixture, Random Forest and a simple DNN we tried. To be noticed, KMeans, Gaussian Mixture, Random Forest models are kept in joblib format (use `joblib_model= joblib.load('path')` to load). DNN model is kept in h5 format (use `keras.models.load_model('path')` to load). ## Mouse Control For Demo 1 mouse control, see the comments in the [script](https://github.com/toby-l-baker/assistive-mouse-capstone/blob/master/mouse-control-test/mouse_control_for_demo1_with_new_gesures.py) for details. ## Testing See the capstone report for details. Testing scripts can be found under `testing/`. ## Depth Camera We have an Intel Realsense depth camera that is able to get extra depth information. The camera should work with [IntelRealsense](https://github.com/IntelRealSense/librealsense). The repository contains many depth camera examples such as outputting depth information and point cloud. It also contains a OpenCV implementation of DNN. To compile the examples, one can follow the instructions in readme from that repo. We did some reseach of the depth camera, some infomation can be found in this [slides](https://docs.google.com/presentation/d/1SyncibUJNlsJfWg0QvKgYm_z7swszJZDxj19tprEECY/edit?usp=sharing) as well as the report. ## Important Files/Directories `mediapipe/mediapipe/calculators/util/gesture_detection_calculator.cc`: performs gesture recognition with hand geometry `mediapipe/mediapipe/calculators/util/pipe_writing_calculator.cc`: calculates centroid and forwards over a Unix pipe `mediapipe/mediapipe/calculators/util/landmark_forwarder_calculator.cc`: forwards 21 key points over UDP `mediapipe/mediapipe/calculators/util/hand_tracking_calculator.cc`: hand segmentation and tracking with OpenCV `gesture_learning/keypoints.py`: utility functions to manipulate key points generated by MediaPipe `gesture_learning/GestureRecognition.py`: runs a gesture learning model in real-time alongside MediaPipe `gesture_learning/template.py`: template for training a gesture learning model `gesture_learning/data/`: contains gesture datasets `gesture_learning/models/`: contains gesture learning models `cameramouse/config.yaml`:contains the parameters required to load each module along with various tunable constants. `cameramouse/utils.py`: if you make a new module you will need to edit the Loaders class to include it. `cameramouse/cameramouse.py`: handles the initialisation and running of all modules, passes data between them. `cameramouse/control/filters.py`: contains super and subclasses for simple IIR and FIR filters. `cameramouse/control/controllers.py`: contains various methods of mapping hand movement to cursor movement. `cameramouse/gestures/`: contains Gestures object as well as an implementation that uses keyboard presses. `cameramouse/hand_tracking/`: contains hand segmentation objects and hand tracking objects. <file_sep>/mediapipe/mediapipe/calculators/util/hand_tracking_calculator.cc #include <iostream> #include <cmath> #include <opencv2/opencv.hpp> #include <opencv2/imgproc.hpp> #include <opencv2/highgui.hpp> #include "mediapipe/framework/calculator_framework.h" #include "mediapipe/framework/formats/landmark.pb.h" #include "mediapipe/framework/port/ret_check.h" #include "mediapipe/framework/udp.h" #include "mediapipe/framework/formats/image_frame.h" #include "mediapipe/framework/formats/image_frame_opencv.h" #include "mediapipe/framework/formats/rect.pb.h" using namespace cv; using namespace std; // Image Capture Parameters #define BLUR_KERNEL_SIZE 5 // Calibration Parameters #define BOX_SIZE 50 // Hand Histogram Parameters #define H_BINS 12 #define S_BINS 15 #define HIST_SENSITIVITY 0.01 // Thresholding Parameters #define HS_THRESH 50 #define EROSION_IT 2 #define DILATION_IT 4 // Tracker Parameters #define EXPANSION_VAL 50 #define SAMPLE_BOX_SIZE 30 /*** GLOBALS ***/ // width and height of the frame double dHeight; double dWidth; // Hand Histogram cv::Mat hand_hist; // Setup for various histogram values int ch[] = {0, 1}; int hist_size[] = {H_BINS, S_BINS}; float h_ranges[] = {0, 180}; float s_ranges[] = {0, 255}; const float* ranges[] = { h_ranges, s_ranges }; // For drawing on frames cv::Scalar blue (255, 0, 0); cv::Scalar green (0, 255, 0); cv::Scalar red (0, 0, 255); /*** Helper Functions ***/ // Initialises our histogram using a hand sample when it first enters the frame cv::Mat get_histogram(const cv::Mat& roi) { cv::Mat hand_histogram; cv::calcHist(&roi, 1, ch, cv::Mat(), //do not use a mask hand_histogram, 2, hist_size, ranges, true); cv::normalize(hand_histogram, hand_histogram, 0, 255, cv::NORM_MINMAX); return hand_histogram; } // Adapts the histogram based off of each new frame to account for changes in lighting // takes in a sample and the current histogram and returns a new one cv::Mat adapt_histogram(const cv::Mat& roi, cv::Mat& histogram) { cv::Mat new_hist; cv::calcHist(&roi, 1, ch, cv::Mat(), //do not use a mask new_hist, 2, hist_size, ranges, true); cv::normalize(new_hist, new_hist, 0, 255, cv::NORM_MINMAX); return histogram*(1-HIST_SENSITIVITY) + HIST_SENSITIVITY*new_hist; } // Clips an integer value to be in some range lower < n < upper int clip(int n, int lower, int upper) { return std::max(lower, std::min(n, upper)); } // Takes in an hsv frame, performs some morphology and thresholding // it then finds all contours in the image matching the hand and returns // them vector<vector<Point>> get_contours(cv::Mat hsv_frame) { cv::Mat temp; // cv::Mat filtered; cv::Mat backproj; cv::calcBackProject(&hsv_frame, 1, ch, hand_hist, backproj, ranges); // see how well the pixels fit our histogram cv::Mat erosion_kernel = cv::getStructuringElement(cv::MORPH_RECT, Size(7, 7)); cv::Mat dilation_kernel = cv::getStructuringElement(cv::MORPH_ELLIPSE, Size(8, 8)); // Filtering, morphological operations and thresholding cv::filter2D(backproj, temp, -1, // dimension the same as source image getStructuringElement(cv::MORPH_ELLIPSE, cv::Size(6,6))); //convolves the image with this kernel cv::threshold(temp, temp, HS_THRESH, 255, 0); // 0 is binary thresholding cv::erode(temp, temp, erosion_kernel, cv::Point(-1, -1), EROSION_IT); //anchor, iterations cv::dilate(temp, temp, dilation_kernel, cv::Point(-1, -1), DILATION_IT); cv::medianBlur(temp, temp, 5); // Get contours vector<vector<Point>> contours; vector<Vec4i> hierarchy; cv::findContours(temp, contours, hierarchy, cv::RETR_EXTERNAL, cv::CHAIN_APPROX_SIMPLE); // //show the thresholded frame // cv::imshow("Thresholded Output", temp); // //show the output of filter 2D // cv::imshow("Filtered Back Projection", filtered); return contours; } /*** Hand Object ***/ class Hand { public: cv::Point centroid; // centroid of the contour cv::Rect bound; // bounding box of the contour double area; // area of the contour // double timestamp; cv::Point velocity; // the relative movement of the centroid compared to the previous frame void set_state(cv::Point, cv::Rect, double); // sets the above variables void update_velocity(Hand); // sets the velocity using the previous state } hand; void Hand::set_state (cv::Point centroid_, cv::Rect bound_, double area_) { centroid = centroid_; bound = bound_; area = area_; // timestamp = timestamp_; } void Hand::update_velocity(Hand old) { // float dt = timestamp - old.timestamp; velocity = centroid - old.centroid; } /*** Hand Tracker Object ***/ class HandTracker { public: Hand old_hand; Hand new_hand; cv::Rect predict_position(void); // predicts a region where the hand will be based on the prior velocity cv::Rect update_position(cv::Mat, cv::Rect roi_mp, bool mp_available); // locates the hand in the bounded region defined by predict_position void initialise(cv::Mat frame); } tracker; cv::Rect HandTracker::predict_position() { float vx = old_hand.velocity.x; float vy = old_hand.velocity.y; cv::Rect prediction (old_hand.bound.x, old_hand.bound.y, old_hand.bound.width+EXPANSION_VAL, old_hand.bound.height+EXPANSION_VAL); // create a wider region to search for the hand in prediction.x = prediction.x + vx - EXPANSION_VAL/2; // shift the origin of the rect so their centers align prediction.y = prediction.y + vy - EXPANSION_VAL/2; prediction.x = clip(prediction.x, 0, dWidth); // co-ordinate shift to global frame and clamping prediction.y = clip(prediction.y, 0, dHeight); int max_width = dWidth - prediction.x; int max_height = dHeight - prediction.y; prediction.width = clip(prediction.width, 0, max_width); prediction.height = clip(prediction.height, 0, max_height); return prediction; } // Returns a hand struct of where the hand is in the frame currently cv::Rect HandTracker::update_position(cv::Mat frame, cv::Rect roi_mp, bool mp_available) { // // To fix crashing // int width = clip(roi_mp.width, 0, dWidth-1); // int height = clip(roi_mp.height, 0, dHeight-1); cv::Rect roi (roi_mp.x, roi_mp.y, roi_mp.width, roi_mp.height); if (mp_available == false) { roi = predict_position(); } vector<vector<Point>> contours; try { contours = get_contours(frame(roi)); // this will be in local coords } catch (const std::exception& e) { roi.x = 0; roi.y = 0; roi.width = dWidth-1; roi.height = dHeight-1; contours = get_contours(frame(roi)); // this will be in local coords } // Currently uses largest contour by area double max_area = 0.0; vector<Point> max_contour; for (int it = 0; it < contours.size(); it++) { double area = cv::contourArea(contours[it]); if (area > max_area) { max_area = area; max_contour = contours[it]; } } // Draw a bounding box around the largest contour cv::Rect bound = cv::boundingRect(max_contour); bound.x = bound.x + roi.x; // co-ordinate shift to global frame and clamping bound.y = bound.y + roi.y; // Get the centroid cv::Moments m = cv::moments(max_contour); cv::Point centroid (m.m10/m.m00, m.m01/m.m00); centroid.x += roi.x; centroid.y += roi.y; // Set the state of the new hand new_hand.set_state(centroid, bound, max_area); return roi; } void HandTracker::initialise(cv::Mat frame) { cv::Mat hsv; cv::cvtColor(frame, hsv, cv::COLOR_BGR2HSV); // convert to hsv colour space vector<vector<Point>> conts = get_contours(hsv); // get all contours double max_area = 0.0; vector<Point> max_contour; // find max contour by area for (int it = 0; it < conts.size(); it++) { double area = cv::contourArea(conts[it]); if (area > max_area) { max_area = area; max_contour = conts[it]; } } cv::Rect bound = cv::boundingRect(max_contour); // Get the centroid cv::Moments m = cv::moments(max_contour); cv::Point centroid (m.m10/m.m00, m.m01/m.m00); // Set the state of the new hand old_hand.set_state(centroid, bound, max_area); old_hand.velocity = {0, 0}; } namespace mediapipe { namespace { constexpr char kInputFrameTag[] = "IMAGE"; constexpr char kLandmarksTag[] = "LANDMARKS"; constexpr char kLandmarkTag[] = "LANDMARK"; constexpr char kRectTag[] = "RECT"; constexpr char kNormRectTag[] = "NORM_RECT"; constexpr char kRectsTag[] = "RECTS"; constexpr char kHeightTag[] = "HEIGHT"; // constexpr char kImageTag[] = "IMAGE"; // constexpr char kImageGpuTag[] = "IMAGE_GPU"; constexpr char kWidthTag[] = "WIDTH"; } const char *IP = "localhost"; // IP address of UDP server const short PORT = 4000; // port number of UDP server class HandTrackingCalculator : public CalculatorBase { private: udp::client *forwarder; bool image_frame_available; bool calibrated; cv::Mat frame; cv::Mat frame_blurred; cv::Mat hsv; cv::Mat hsv_roi; HandTracker hand_tracker; cv::Rect sample_region; // for taking samples of skin colour cv::Rect bbox; cv::Rect prediction; double initial_area; // initial area of the hand - used to detect failures bool rect_available; bool landmarks_available; int hand_lost; // Setup for various histogram values // int ch[2]; // int hist_size[2]; // float h_ranges[2]; // float s_ranges[2]; // const float* ranges[2]; public: /* GetContract is the Input Handler */ static ::mediapipe::Status GetContract(CalculatorContract* cc) { RET_CHECK(cc->Inputs().HasTag(kLandmarksTag)) << "No landmark input stream provided."; RET_CHECK(cc->Inputs().HasTag(kInputFrameTag)) << "No input image stream provided."; RET_CHECK((cc->Inputs().HasTag(kNormRectTag))) << "No norm rect input provided"; /* If we have an image present then we set the image */ if (cc->Inputs().HasTag(kInputFrameTag)) { // RET_CHECK(cc->Outputs().HasTag(kInputFrameTag)); cc->Inputs().Tag(kInputFrameTag).Set<ImageFrame>(); // cc->Outputs().Tag(kInputFrameTag).Set<ImageFrame>(); } if(cc->Inputs().HasTag(kLandmarksTag)) { cc->Inputs().Tag(kLandmarksTag).Set<NormalizedLandmarkList>(); } if(cc->Inputs().HasTag(kNormRectTag)) { cc->Inputs().Tag(kNormRectTag).Set<NormalizedRect>(); } if (cc->Outputs().HasTag(kRectsTag)) { cc->Outputs().Tag(kRectsTag).Set<std::vector<Rect>>(); } if (cc->Outputs().HasTag(kLandmarkTag)) { cc->Outputs().Tag(kLandmarkTag).Set<Landmark>(); } return(::mediapipe::OkStatus()); } ::mediapipe::Status Open(CalculatorContext* cc) override { cc->SetOffset(TimestampDiff(0)); if(cc->Inputs().HasTag(kInputFrameTag)) { image_frame_available = true; } else { image_frame_available = false; } forwarder = new udp::client(IP, PORT); rect_available = false; landmarks_available = false; calibrated = false; // uncalibrated histogram initially hand_lost = 0; return(::mediapipe::OkStatus()); } ::mediapipe::Status Process(CalculatorContext* cc) override { /* If we have no image data just return */ if (cc->Inputs().Tag(kInputFrameTag).IsEmpty()) { return ::mediapipe::OkStatus(); } // Load input image const auto& input_img = cc->Inputs().Tag(kInputFrameTag).Get<ImageFrame>(); frame = formats::MatView(&input_img); // frame used further down for CV things dWidth = frame.size().width; dHeight = frame.size().height; if (cc->Inputs().HasTag(kNormRectTag) && !cc->Inputs().Tag(kNormRectTag).IsEmpty()) { // if (hand_present_rect(cc, dWidth, dHeight)) { rect_available = true; } else { rect_available = false; } if (cc->Inputs().HasTag(kLandmarksTag) && !cc->Inputs().Tag(kLandmarksTag).IsEmpty()) { // if (hand_present_landmark(cc, dWidth, dHeight)) { landmarks_available = true; } else { landmarks_available = false; } // if landmarks available get the region to sample if (landmarks_available) { sample_region = get_sample_rect(cc, dWidth, dHeight); if ((sample_region.width == 15) && (sample_region.height == 15)) { landmarks_available = false; } } // if MP has a bounding box for the hand if (rect_available) { // Load normalized rect bbox = get_bounding_box(cc, dWidth, dHeight); if ((bbox.width == dWidth-1) && (bbox.height == dHeight-1)) { rect_available = false; } } /* CHECK IF THE HAND IS GONE */ if ((!rect_available) && (!landmarks_available)) { hand_lost++; } else { hand_lost = 0; } if (hand_lost > 5) { calibrated = false; } /* For displaying rectangles */ int num_rects = 1; if (landmarks_available) { num_rects = 2; } if (calibrated == false) { if (!landmarks_available) { VLOG(1) << "No Landmarks Available to Calibrate with" << cc->InputTimestamp(); return ::mediapipe::OkStatus(); } if (!rect_available) { VLOG(1) << "No Rect Available to Initialize Tracker with" << cc->InputTimestamp(); return ::mediapipe::OkStatus(); } cv::GaussianBlur(frame, frame_blurred, Size(BLUR_KERNEL_SIZE, BLUR_KERNEL_SIZE), 0); // Blur image with 5x5 kernel cv::Mat roi = frame_blurred(sample_region); // grab the region of the frame we want cv::cvtColor(roi, hsv_roi, cv::COLOR_BGR2HSV); // convert roi to HSV colour space hand_hist = get_histogram(hsv_roi); // get initial histogram calibrated = true; // hand histogram has been calibrated cv::Mat blurred_roi = frame_blurred(bbox); // search bounding region from MPipe hand_tracker.initialise(blurred_roi); initial_area = hand_tracker.old_hand.area; } else { cv::GaussianBlur(frame, frame_blurred, Size(BLUR_KERNEL_SIZE, BLUR_KERNEL_SIZE), 0); // Blur image with 5x5 kernel cv::cvtColor(frame_blurred, hsv, cv::COLOR_BGR2HSV); // convert entire frame to hsv colour space // TODO: need to know when // 1. hand is present or absent by checking mediapipe data // 2. when only frame info is available (i.e. MP at 10 FPS and camera at 30 FPS, there will be times when we only have frame data) if (landmarks_available && rect_available) { // media pipe output available as well as frame info hsv_roi = hsv(sample_region); // for histogram adaption hand_hist = adapt_histogram(hsv_roi, hand_hist); // adapt the histogram /* Update where we are */ prediction = hand_tracker.update_position(hsv, bbox, true); // true since MP rect is available hand_tracker.new_hand.update_velocity(hand_tracker.old_hand); hand_tracker.old_hand.set_state(hand_tracker.new_hand.centroid, hand_tracker.new_hand.bound, hand_tracker.new_hand.area); hand_tracker.old_hand.velocity = hand_tracker.new_hand.velocity; } else { // only frame information available prediction = hand_tracker.update_position(hsv, bbox, false); // pass an empty rect hand_tracker.new_hand.update_velocity(hand_tracker.old_hand); hand_tracker.old_hand.set_state(hand_tracker.new_hand.centroid, hand_tracker.new_hand.bound, hand_tracker.new_hand.area); hand_tracker.old_hand.velocity = hand_tracker.new_hand.velocity; } auto output_rects = absl::make_unique<std::vector<Rect>>(num_rects); auto output_landmark = absl::make_unique<Landmark>(); if (!landmarks_available) { convert_bbox(hand_tracker.new_hand.bound, &(output_rects->at(0))); } else { convert_bbox(hand_tracker.new_hand.bound, &(output_rects->at(0))); convert_bbox(sample_region, &(output_rects->at(1))); } convert_centroid(hand_tracker.new_hand.centroid, output_landmark.get()); cc->Outputs().Tag(kRectsTag).Add(output_rects.release(), cc->InputTimestamp()); cc->Outputs().Tag(kLandmarkTag).Add(output_landmark.release(), cc->InputTimestamp()); // cout << "Hand Vel: " << hand_tracker.new_hand.centroid << endl; // cv::rectangle(frame_blurred, hand_tracker.new_hand.bound, red, 2); // cv::rectangle(frame_blurred, prediction, green, 2); // cv::rectangle(frame_blurred, sample_region, blue, 2); // cv::circle(frame_blurred, hand_tracker.new_hand.centroid, 5, blue, -1); // cv::imshow("Feed", frame_blurred); } string data; data += std::to_string(hand_tracker.new_hand.centroid.x) + ','; data += std::to_string(hand_tracker.new_hand.centroid.y) + ','; data += std::to_string(hand_tracker.new_hand.bound.x) + ','; data += std::to_string(hand_tracker.new_hand.bound.y) + ','; data += std::to_string(hand_tracker.new_hand.bound.width) + ','; data += std::to_string(hand_tracker.new_hand.bound.height) + ';'; forwarder->send(data.c_str(), data.length()); return(::mediapipe::OkStatus()); } ::mediapipe::Status Close(CalculatorContext* cc) override { delete forwarder; return(::mediapipe::OkStatus()); } cv::Rect get_sample_rect(const CalculatorContext* cc, int src_width, int src_height) { /* Inputs: cc: calculator context src_width: width of the source frame src_height: height of the source frame Outputs: rect: a CV rect that contains the coordinates of the region to sample for the hand histogram */ const auto& landmarks = cc->Inputs().Tag(kLandmarksTag).Get<NormalizedLandmarkList>(); int keypoints[] = {0, 1, 5, 9, 13, 17}; int size = sizeof(keypoints) / sizeof(keypoints[0]); float center_x = 0; float center_y = 0; for(int i = 0; i < size; i++) { const NormalizedLandmark& keypoint = landmarks.landmark(keypoints[i]); center_x += keypoint.x()*src_width; center_y += keypoint.y()*src_height; } center_x /= size; center_y /= size; // create rectangle cv::Point top_left (clip(center_x - SAMPLE_BOX_SIZE/2, 0, src_width), clip(center_y - SAMPLE_BOX_SIZE/2, 0, src_height)); cv::Point bottom_right (clip(center_x + SAMPLE_BOX_SIZE/2, 0, src_width), clip(center_y + SAMPLE_BOX_SIZE/2, 0, src_height)); cv::Rect roi (top_left, bottom_right); return roi; } cv::Rect get_bounding_box(const CalculatorContext* cc, int src_width, int src_height) { /* Inputs: cc: calculator context src_width: width of the source frame src_height: height of the source frame Outputs: rect: a CV rect that will represent a bounding box for the hand in the frame by manipulating the normalized rect */ // by default use the whole frame to search int width = src_width-1; int height = src_height-1; int min_x = 1; int min_y = 1; const auto& norm_rect = cc->Inputs().Tag(kNormRectTag).Get<NormalizedRect>(); if (norm_rect.width() > 0.0 && norm_rect.height() > 0.0) { float normalized_width = norm_rect.width(); float normalized_height = norm_rect.height(); int x_center = std::round(norm_rect.x_center() * src_width); int y_center = std::round(norm_rect.y_center() * src_height); width = std::round(normalized_width * src_width); height = std::round(normalized_height * src_height); min_x = std::round(x_center - width/2); min_y = std::round(y_center - height/2); min_x = clip(min_x, 0, src_width-width); min_y = clip(min_y, 0, src_height-height); } cv::Rect roi (min_x, min_y, width, height); return roi; } void convert_bbox(cv::Rect bounding_box, Rect* rect) { rect->set_x_center(bounding_box.x + bounding_box.width / 2); rect->set_y_center(bounding_box.y + bounding_box.height / 2); rect->set_width(bounding_box.width); rect->set_height(bounding_box.height); } void convert_centroid(cv::Point centroid, Landmark* landmark) { landmark->set_x(centroid.x); landmark->set_y(centroid.y); } }; REGISTER_CALCULATOR(HandTrackingCalculator); } <file_sep>/mediapipe/mediapipe/calculators/util/gesture_detection_new_calculator.cc #include <chrono> #include "absl/memory/memory.h" #include "absl/strings/str_cat.h" #include "absl/strings/str_join.h" #include "mediapipe/framework/calculator_framework.h" #include "mediapipe/framework/calculator_options.pb.h" #include "mediapipe/framework/formats/landmark.pb.h" #include "mediapipe/framework/formats/location_data.pb.h" #include "mediapipe/framework/port/ret_check.h" #include "mediapipe/util/color.pb.h" #include "mediapipe/util/render_data.pb.h" #define PI 3.141592653589793238462643383279502884L namespace mediapipe { namespace { constexpr char kLandmarksTag[] = "LANDMARKS"; constexpr char kNormLandmarksTag[] = "NORM_LANDMARKS"; constexpr char kGestureTag[] = "GESTURE"; // point1: (x1, y1) point2(x2, y2) double distance(double x1, double y1, double x2, double y2) { return sqrt(pow(x1 - x2, 2) + pow(y1 - y2, 2)); } // vector1: starts from (x1, y1), ends at (x2, y2) // vector2: starts from (x3, y3), ends at (x4, y4) double angle_cos(double x1, double y1, double x2, double y2, double x3, double y3, double x4, double y4) { double vector1x = x2 - x1; double vector1y = y2 - y1; double vector2x = x4 - x3; double vector2y = y4 - y3; double vector1_length = distance(x1, y1, x2, y2); double vector2_length = distance(x3, y3, x4, y4); return (vector1x * vector2x + vector1y * vector2y) / (vector1_length * vector2_length); } // vector1: starts from (x1, y1), ends at (x2, y2) // vector2: starts from (0, 0), ends at (0, 1) double angle_cos(double x1, double y1, double x2, double y2) { double vector1x = x2 - x1; double vector1y = y2 - y1; double vector2x = 0; double vector2y = 1; double vector1_length = distance(x1, y1, x2, y2); double vector2_length = 1.0; return (vector1x * vector2x + vector1y * vector2y) / (vector1_length * vector2_length); } // vector1: starts from (x1, y1), ends at (x2, y2) // vector2: starts from (0, 0), ends at (0, 1) double angle_sin(double x1, double y1, double x2, double y2) { double cosine = angle_cos(x1, y1, x2, y2); double vector1x = x2 - x1; if (vector1x <= 0) { return -1.0 * sqrt(1 - pow(cosine, 2)); } else { return sqrt(1 - pow(cosine, 2)); } } // vector1: starts from (x1, y1), ends at (x2, y2) // vector2: starts from (0, 0), ends at (1, 0) int angle(double x1, double y1, double x2, double y2) { double vector1x = x2 - x1; double vector1y = y2 - y1; double vector2x = 1; double vector2y = 0; double dot = vector1x * vector2x + vector1y * vector2y; double det = vector1x * vector2y - vector1y * vector2x; int angle = atan2(det, dot) / PI * 180; return (360 + angle) % 360; } /* * 0 1 * 2 3 */ double* get_matrix(double x1, double y1, double x2, double y2) { double* matrix = new double[4]; double sine = angle_sin(x1, y1, x2, y2); double cosine = angle_cos(x1, y1, x2, y2); double len = distance(x1, y1, x2, y2); matrix[0] = cosine / len; matrix[1] = sine / len; matrix[2] = -1.0 * sine / len; matrix[3] = cosine / len; return matrix; } class MyLandmark { public: double _x, _y; MyLandmark(double x, double y) { _x = x; _y = y; } double x() { return _x; } double y() { return _y; } }; std::vector<MyLandmark>* normalize(const std::vector<NormalizedLandmark>& landmarks) { // 0, 9 std::vector<MyLandmark>* my_landmarks = new std::vector<MyLandmark>(); double* matrix = get_matrix(landmarks[9].x(), landmarks[9].y(), landmarks[0].x(), landmarks[0].y()); for (const auto& landmark : landmarks) { double x = landmark.x() - landmarks[0].x(); double y = landmark.y() - landmarks[0].y(); double x_new = x * matrix[0] + y * matrix[2]; double y_new = x * matrix[1] + y * matrix[3]; my_landmarks->push_back(*(new MyLandmark(x_new, y_new))); } delete[] matrix; return my_landmarks; } } class GestureDetectionCalculator : public CalculatorBase { public: GestureDetectionCalculator() {} ~GestureDetectionCalculator() override {} static ::mediapipe::Status GetContract(CalculatorContract* cc); ::mediapipe::Status Open(CalculatorContext* cc) override; ::mediapipe::Status Process(CalculatorContext* cc) override; }; REGISTER_CALCULATOR(GestureDetectionCalculator); ::mediapipe::Status GestureDetectionCalculator::GetContract(CalculatorContract* cc) { RET_CHECK(cc->Inputs().HasTag(kLandmarksTag) || cc->Inputs().HasTag(kNormLandmarksTag)) << "None of the input streams are provided."; RET_CHECK(!(cc->Inputs().HasTag(kLandmarksTag) && cc->Inputs().HasTag(kNormLandmarksTag))) << "Can only one type of landmark can be taken. Either absolute or " "normalized landmarks."; if (cc->Inputs().HasTag(kLandmarksTag)) { //cc->Inputs().Tag(kLandmarksTag).Set<std::vector<Landmark>>(); cc->Inputs().Tag(kLandmarksTag).SetAny(); } if (cc->Inputs().HasTag(kNormLandmarksTag)) { //cc->Inputs().Tag(kNormLandmarksTag).Set<std::vector<NormalizedLandmark>>(); cc->Inputs().Tag(kNormLandmarksTag).SetAny(); } cc->Outputs().Tag(kGestureTag).Set<int>(); return ::mediapipe::OkStatus(); } ::mediapipe::Status GestureDetectionCalculator::Open(CalculatorContext* cc) { cc->SetOffset(TimestampDiff(0)); return ::mediapipe::OkStatus(); } ::mediapipe::Status GestureDetectionCalculator::Process(CalculatorContext* cc) { if (cc->Inputs().HasTag(kNormLandmarksTag) || cc->Inputs().HasTag(kLandmarksTag)) { const auto& landmarks = cc->Inputs().Tag(kLandmarksTag).Get<std::vector<NormalizedLandmark>>(); std::vector<MyLandmark>* normalized_landmarks_ptr = normalize(landmarks); std::vector<MyLandmark>& normalized_landmarks = *normalized_landmarks_ptr; // 0: wrist // 4: thumb // 8: index finger // 12: middle finger // 16: ring finger // 20: little finger int from5to4 = angle(normalized_landmarks[5].x(), normalized_landmarks[5].y(), normalized_landmarks[4].x(), normalized_landmarks[4].y()); int from6to8 = angle(normalized_landmarks[6].x(), normalized_landmarks[6].y(), normalized_landmarks[8].x(), normalized_landmarks[8].y()); int from10to12 = angle(normalized_landmarks[10].x(), normalized_landmarks[10].y(), normalized_landmarks[12].x(), normalized_landmarks[12].y()); int from14to16 = angle(normalized_landmarks[14].x(), normalized_landmarks[14].y(), normalized_landmarks[16].x(), normalized_landmarks[16].y()); int from18to20 = angle(normalized_landmarks[18].x(), normalized_landmarks[18].y(), normalized_landmarks[20].x(), normalized_landmarks[20].y()); int gesture = 0; // move: gesture = 1 if (abs(from6to8 - 90) + abs(from10to12 - 90) + abs(from14to16 - 90) + abs(from18to20 - 90) <= 80) { gesture = 1; } // scroll down: gesture = 2 else if (abs(from6to8 - 90) + abs(from10to12 - 90) <= 40 && from14to16 > 150 && from18to20 > 150) { gesture = 2; } // scroll up: gesture = 3 else if (abs(from6to8 - 90) <= 20 && from10to12 > 150 && from14to16 > 150 && from18to20 > 150) { gesture = 3; } // left click: gesture = 4 else if (from6to8 > 150 && from10to12 > 150 && from14to16 > 150 && from18to20 > 150) { gesture = 4; } // right click: gesture = 5 else if (from5to4 > 190) { gesture = 5; } if ((from6to8 - 120) + (from10to12 - 120) + (from14to16 - 120) + (from18to20 - 120) >= 10) { gesture += 10; } //std::cout << from5to4 << " " << from6to8 << " " << from10to12 << " " << from14to16 << " " << from18to20 << " " << gesture << "\n"; delete normalized_landmarks_ptr; int* i = new int; *i = gesture; cc->Outputs().Tag(kGestureTag).Add(i, cc->InputTimestamp()); } return ::mediapipe::OkStatus(); } } <file_sep>/mouse-control-test/mouse_states.py class State(object): """ We define a state object which provides some utility functions for the individual states within the state machine. """ def __init__(self): print(str(self)) def on_event(self, event): """ Handle events that are delegated to this State. """ pass def __repr__(self): """ Leverages the __str__ method to describe the State. """ return self.__str__() def __str__(self): """ Returns the name of the State. """ return self.__class__.__name__ class OutOfRange(State): '''State when the hand is out of range.''' def on_event(self, event): if event == 'in_range': return InRange() else: return self class InRange(State): '''State where hand motion is tracked''' def on_event(self, event): if event == 'drag': return Drag() elif event == 'out_of_range': return OutOfRange() else: return self class Drag(State): '''State where we have clicked and will move objects around on the screen or write in a note taking application''' def on_event(self, event): if event == 'in_range': return InRange() else: return self <file_sep>/mediapipe/mediapipe/calculators/util/landmark_forwarder_calculator.cc #include <unistd.h> #include <string.h> #include <netdb.h> #include <sys/types.h> #include <sys/socket.h> #include "mediapipe/framework/calculator_framework.h" #include "mediapipe/framework/formats/landmark.pb.h" #include "mediapipe/framework/port/ret_check.h" #include "mediapipe/framework/udp.h" namespace mediapipe { namespace { constexpr char kLandmarksTag[] = "LANDMARKS"; } const char *GL_IP = "localhost"; // IP address of gesture learning UDP server const short GL_PORT = 2000; // port number of gesture learning UDP server const char *MC_IP = "localhost"; // IP address of mouse control UDP server const short MC_PORT = 3000; // port number of mouse control UDP server class LandmarkForwarderCalculator : public CalculatorBase { private: udp::client *gl_forwarder; udp::client *mc_forwarder; public: static ::mediapipe::Status GetContract(CalculatorContract* cc) { RET_CHECK(cc->Inputs().HasTag(kLandmarksTag)) << "No input stream provided."; if(cc->Inputs().HasTag(kLandmarksTag)) { cc->Inputs().Tag(kLandmarksTag).Set<NormalizedLandmarkList>(); } return(::mediapipe::OkStatus()); } ::mediapipe::Status Open(CalculatorContext* cc) override { cc->SetOffset(TimestampDiff(0)); gl_forwarder = new udp::client(GL_IP, GL_PORT); mc_forwarder = new udp::client(MC_IP, MC_PORT); return(::mediapipe::OkStatus()); } ::mediapipe::Status Process(CalculatorContext* cc) override { if(cc->Inputs().Tag(kLandmarksTag).IsEmpty()) { return(::mediapipe::OkStatus()); } const auto& landmarks = cc->Inputs().Tag(kLandmarksTag).Get<NormalizedLandmarkList>(); std::string data; for(int i = 0; i < landmarks.landmark_size(); i++) { const NormalizedLandmark& landmark = landmarks.landmark(i); data += std::to_string(landmark.x()) + ','; data += std::to_string(landmark.y()) + ','; data += std::to_string(landmark.z()) + ';'; } gl_forwarder->send(data.c_str(), data.length()); mc_forwarder->send(data.c_str(), data.length()); return(::mediapipe::OkStatus()); } ::mediapipe::Status Close(CalculatorContext* cc) override { delete gl_forwarder; delete mc_forwarder; return(::mediapipe::OkStatus()); } }; REGISTER_CALCULATOR(LandmarkForwarderCalculator); }<file_sep>/cameramouse/hardware/monitor.py """ Author: <NAME> Title: Interface for capturing metrics about monitors on different OS's Date Created: 28 Nov 2018 """ try: import win32api, win32con except: import mouse import pyautogui class Monitor(): '''Class for storing data about the display''' def __init__(self): # Windows only at this stage pass class WindowsMonitor(Monitor): def __init__(self): super().__init__() self.width = win32api.GetSystemMetrics(0) self.height = win32api.GetSystemMetrics(1) print('Monitor Width: %d, Monitor Height: %d' % (self.width, self.height)) print("[DEBUG] Windows Monitor Initialized") class LinuxMonitor(Monitor): def __init__(self): super().__init__() self.width, self.height = pyautogui.size() print('Monitor Width: %d, Monitor Height: %d' % (self.width, self.height)) print("[DEBUG] Linux Monitor Initialized")<file_sep>/cameramouse/gesture_recognition/keyboard.py """ Author: <NAME> Title: Camera Mouse Date Created: 28/NOV/2019 """ import keyboard, time from gesture_recognition.gestures import GestureRecognition, Gestures class KeyboardGestureRecognition(GestureRecognition): def __init__(self): super().__init__() self.pressed = {"a": False, "s": False, "d": False, "o": False} # a: click, s:d_click, d: r_click keyboard.hook(self.update) self.i = 0 print("[DEBUG] Keyboard Gesture Input Initialized") def update(self, event): #print(event.event_type) self.i += 1 if event.name == "s": if event.event_type == "down": self.pressed["o"] = False if self.pressed[event.name]: self.gesture = Gestures.null # debouncing return # set state of key to pressed self.pressed[event.name] = True self.gesture = Gestures.click else: self.pressed[event.name] = False self.gesture = Gestures.null elif event.name == "a": if event.event_type == "down": self.pressed["o"] = False if self.pressed[event.name]: self.gesture = Gestures.null return # set state of key to pressed self.pressed[event.name] = True self.gesture = Gestures.double_click else: self.pressed[event.name] = False self.gesture = Gestures.null elif event.name == "r": if event.event_type == "down": self.pressed["o"] = False if self.pressed[event.name]: self.gesture = Gestures.null return # set state of key to pressed self.pressed[event.name] = True self.gesture = Gestures.right_click else: self.pressed[event.name] = False self.gesture = Gestures.null elif event.name == "d": if event.event_type == "down": self.pressed["o"] = False if self.pressed[event.name]: return # set state of key to pressed self.pressed[event.name] = True if self.gesture == Gestures.drag: self.gesture = Gestures.null else: self.gesture = Gestures.drag else: self.pressed[event.name] = False elif event.name == "o": if event.event_type == "down": # set state of key to pressed self.gesture = Gestures.out_of_range # else: # self.pressed[event.name] = False # self.gesture = Gestures.out_of_range <file_sep>/cameramouse/cameramouse.py """ Author: <NAME> Title: Camera Mouse Date Created: 28/Nov/2019 Description: Full implementation of a computer mouse including cursor movement, and mouse actions. This was intended to be as interchangable as possible so different control, filters, segmentation and gesture recognition techniques can be tested """ import numpy as np import cv2, sys, argparse from gesture_recognition.gestures import Gestures import utils try: import win32api except: pass class CameraMouse(): def __init__(self, opts): self.opts = opts self.monitor = utils.Loader.load_monitor(opts["os"]) self.mouse = utils.Loader.load_mouse(opts["os"]) self.camera = utils.Loader.load_camera(opts["camera"]) self.gesture_recognition = utils.Loader.load_gesture(opts["gesture"]) self.tracker = utils.Loader.load_tracker(opts["tracking"], self.camera) self.control = utils.Loader.load_control(opts["control"], self.mouse, self.monitor, self.camera.im_shape) self.last_gesture_update = 0 def run(self): cv2.namedWindow("CameraMouse") while True: # grab frames gray_frame, color_frame = self.camera.capture_frames() # if the hand is lost, recalibrate and locate the hand if not self.tracker.found: initial_pos = self.tracker.calibrate(frame) if initial_pos is not None: self.control.setup(initial_pos) # hand is still in view, track it else: centroid = self.tracker.update_position(color_frame, self.opts["control"]["type"]) cur_gesture = self.gesture_recognition.update() # Make sure we aren't doubling down on the same action if self.last_gesture_update < self.gesture_recognition.i: self.last_gesture_update = self.gesture_recognition.i elif self.last_gesture_update == self.gesture_recognition.i and not (cur_gesture == Gestures.drag): cur_gesture = Gestures.null self.control.update(centroid) self.control.execute(cur_gesture) cv2.imshow("CameraMouse", color_frame) ch = 0xFF & cv2.waitKey(1) if ch == 27: cv2.destroyWindow("CameraMouse") break class HandSegmentationMouse(CameraMouse): def __init__(self, opts): super().__init__(opts) def run(self): calibrated = False cv2.namedWindow("CameraMouse") while True: # grab frames gray_frame, color_frame = self.camera.capture_frames() # if the hand is lost, recalibrate and locate the hand if not self.tracker.found: # print("Heyo") if calibrated == False: self.tracker.handSeg.get_histogram() calibrated = True initial_pos = self.tracker.global_recognition(color_frame) if initial_pos is not None: self.control.setup(initial_pos) # hand is still in view, track it else: # print("neyo") centroid = self.tracker.update_position(color_frame, self.opts["control"]["type"]) # gesture = self.gesture_recognition.update() # Make sure we aren't doubling down on the same action, keyboard recognition is slower than main algorithm if self.last_gesture_update < self.gesture_recognition.i: self.last_gesture_update = self.gesture_recognition.i elif self.gesture_recognition.gesture == Gestures.out_of_range: pass elif self.last_gesture_update == self.gesture_recognition.i and not (self.gesture_recognition.gesture == Gestures.drag): self.gesture_recognition.gesture = Gestures.null self.control.update(centroid) self.control.execute(self.gesture_recognition.gesture) calibrated = False # to ensure if the hand is lost we recalibrate cv2.imshow("CameraMouse", color_frame) ch = 0xFF & cv2.waitKey(1) if ch == 27: cv2.destroyWindow("CameraMouse") break<file_sep>/mediapipe/mediapipe/calculators/util/gesture_to_render_data_calculator.cc // Copyright 2019 The MediaPipe Authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "absl/memory/memory.h" #include "absl/strings/str_cat.h" #include "absl/strings/str_join.h" #include "mediapipe/framework/calculator_framework.h" #include "mediapipe/framework/calculator_options.pb.h" #include "mediapipe/framework/formats/location_data.pb.h" #include "mediapipe/framework/port/ret_check.h" #include "mediapipe/util/color.pb.h" #include "mediapipe/util/render_data.pb.h" namespace mediapipe { namespace { constexpr char kGestureTag[] = "GESTURE"; constexpr char kRenderDataTag[] = "RENDER_DATA"; } // namespace class GestureToRenderDataCalculator : public CalculatorBase { public: GestureToRenderDataCalculator() {} ~GestureToRenderDataCalculator() override {} static ::mediapipe::Status GetContract(CalculatorContract* cc); ::mediapipe::Status Open(CalculatorContext* cc) override; ::mediapipe::Status Process(CalculatorContext* cc) override; }; REGISTER_CALCULATOR(GestureToRenderDataCalculator); ::mediapipe::Status GestureToRenderDataCalculator::GetContract( CalculatorContract* cc) { cc->Inputs().Tag(kGestureTag).Set<int>(); cc->Outputs().Tag(kRenderDataTag).Set<RenderData>(); return ::mediapipe::OkStatus(); } ::mediapipe::Status GestureToRenderDataCalculator::Open( CalculatorContext* cc) { cc->SetOffset(TimestampDiff(0)); return ::mediapipe::OkStatus(); } ::mediapipe::Status GestureToRenderDataCalculator::Process( CalculatorContext* cc) { const auto& gesture = cc->Inputs().Tag(kGestureTag).Get<int>(); auto render_data = absl::make_unique<RenderData>(); auto* render_data_annotation = render_data.get()->add_render_annotations(); auto* data = render_data_annotation->mutable_text(); data->set_normalized(true); data->set_display_text(std::to_string(gesture)); data->set_left(0.5); data->set_baseline(0.9); data->set_font_height(0.05); render_data_annotation->set_thickness(2.0); render_data_annotation->mutable_color()->set_r(255); cc->Outputs().Tag(kRenderDataTag).Add(render_data.release(), cc->InputTimestamp()); return ::mediapipe::OkStatus(); } } // namespace mediapipe <file_sep>/testing/button_click.py #! /usr/bin/env python # -*- coding: utf-8 -*- # vim:fenc=utf-8 # # Copyright © 2020 weihao <<EMAIL>> # # Distributed under terms of the MIT license. from sys import argv import random import time from tkinter import * from tkinter import messagebox if len(argv) != 4: print('python3 button.py width height seed') exit() script, width, height, seed = argv height = int(height) width = int(width) random.seed(int(seed)) window_width = 800 window_height = 600 root = Tk() root.title("button test") root.geometry("%dx%d" % (window_width, window_height)) max_count = 10 count = 0 prev_button = None def randomButton(): global count global max_count global prev_button if prev_button != None: prev_button.destroy() if count >= max_count: print(time.time() - start, "seconds") root.quit() B = Button(root, command = randomButton, bg="red") prev_button = B x = random.randint(0, window_width - width) y = random.randint(0, window_height - height) B.place(x = x,y = y, width=width, height=height) count += 1 start = time.time() randomButton() root.mainloop() <file_sep>/mouse-control-test/point_filter.py import matplotlib.pyplot as plt import numpy as np from scipy.signal import kaiserord, lfilter, firwin, freqz, butter, lfilter_zi, filtfilt class Data: def __init__(self, data): self.x = data[1:, 0]*1280 # read x mouse_data self.y = data[1:, 1]*780 # read y data self.t = data[1:, 2]/1000 # read time and convert to seconds self.xn = self.x + np.random.normal(0, 1.5, len(self.x)) self.yn = self.y + np.random.normal(0, 1.5, len(self.x)) self.dt = self.t[1:] - self.t[:-1] # calculate dt self.vx = (self.x[1:] - self.x[:-1])/self.dt # calculate x velocity self.vy = (self.y[1:] - self.y[:-1])/self.dt # calculate y velocity self.x_av = np.average(self.x) # calulate average x self.y_av = np.average(self.y) # calculate average y self.x_std = np.std(self.x) self.y_std = np.std(self.y) '''Grab data from log file''' data_stat = np.genfromtxt('mouse_data/stay_still.csv', delimiter=',') data_right = np.genfromtxt('mouse_data/move_right.csv', delimiter=',') data_circle = np.genfromtxt('mouse_data/circle.csv', delimiter=',') stat = Data(data_stat) right = Data(data_right) circle = Data(data_circle) circle.vx = (circle.xn[1:] - circle.xn[:-1])/circle.dt # calculate x velocity circle.vy = (circle.yn[1:] - circle.yn[:-1])/circle.dt # calculate y velocity print("Static Mean X: %f, Static Standard Deviation X: %f" % (stat.x_av, stat.x_std)) # std_x is 1.5 print("Static Mean Y: %f, Static Standard Deviation Y: %f" % (stat.y_av, stat.y_std)) # std_y is 1.5 print("Moving Mean X: %f, Moving Standard Deviation X: %f" % (right.x_av, right.x_std)) print("Moving Mean Y: %f, Moving Standard Deviation Y: %f" % (right.y_av, right.y_std)) print("Circle Mean X: %f, Moving Standard Deviation X: %f" % (circle.x_av, circle.x_std)) print("Circle Mean Y: %f, Moving Standard Deviation Y: %f" % (circle.y_av, circle.y_std)) FIR = 1 '''Apply the filter to both sets of data''' if FIR: n = 10 taps = np.ones(n)/n stat.filt_x = lfilter(taps, 1.0, stat.x) stat.filt_y = lfilter(taps, 1.0, stat.y) right.filt_x = lfilter(taps, 1.0, right.x) right.filt_y = lfilter(taps, 1.0, right.y) circle.filt_x = lfilter(taps, 1.0, circle.xn) circle.filt_y = lfilter(taps, 1.0, circle.yn) else: b, a = butter(1, 0.05) print(b) print(a) zi = lfilter_zi(b, a) n = 1 stat.filt_x, _ = lfilter(b, a, stat.x, zi=zi*stat.x[0]) stat.filt_y, _ = lfilter(b, a, stat.y, zi=zi*stat.y[0]) right.filt_x, _ = lfilter(b, a, right.x, zi=zi*right.x[0]) right.filt_y, _ = lfilter(b, a, right.y, zi=zi*right.y[0]) circle.filt_x, _= lfilter(b, a, circle.xn, zi=zi*circle.xn[0]) circle.filt_y, _ = lfilter(b, a, circle.yn, zi=zi*circle.yn[0]) '''Setup a 2 by 2 plot for showing data''' fig, axs = plt.subplots(nrows=3, ncols=2, sharex='row', sharey='row') axs[1,0].set_title('Original Moving Data') axs[1,1].set_title('Filtered Moving Data') axs[0,0].set_title('Original Static Data') axs[0,1].set_title('Filtered Static Data') axs[2,0].set_title('Original Circle Data') axs[2,1].set_title('Filtered Circle Data') '''Plot the true path to compare our results to''' axs[0,0].plot(stat.x_av, stat.y_av, 'x') axs[1,0].plot(right.x, np.ones(len(right.y))*right.y_av) axs[0,1].plot(stat.x_av, stat.y_av, 'x') axs[1,1].plot(right.x, np.ones(len(right.y))*right.y_av) axs[2,0].plot(circle.x, circle.y, 'g') axs[2,1].plot(circle.x, circle.y, 'g') '''Plot points at two times the real speed''' for i in range(n, len(right.filt_x)-1): axs[1,0].scatter(right.x[i], right.y[i]) axs[1,1].scatter(right.filt_x[i], right.filt_y[i]) axs[0,0].scatter(stat.x[i], stat.y[i]) axs[0,1].scatter(stat.filt_x[i], stat.filt_y[i]) axs[2,0].scatter(circle.xn[i], circle.yn[i]) axs[2,1].scatter(circle.filt_x[i], circle.filt_y[i]) plt.pause(right.dt[i]/2) plt.show() <file_sep>/colour_segmentation_cpp/CMakeLists.txt cmake_minimum_required(VERSION 3.1) project( cameramousecpp ) find_package( OpenCV REQUIRED ) add_executable( hand_tracker main.cpp ) target_link_libraries( hand_tracker ${OpenCV_LIBS} )<file_sep>/cameramouse/hardware/mouse.py """ Author: <NAME> Title: Mouse interface to abstract different mouse APIs Date Created: 28 Nov 2018 """ try: import win32api, win32con import mouse except: import mouse import pyautogui class Mouse(): '''Class for each mouse e.g. Winsdows/Linux/MacOS''' def __init__(self): self.state = "UP" pass def left_click(self): pass def right_click(self): pass def double_click(self): pass def move(self, x, y): pass def moveD(self, dx, dy): pass def position(self): return 0, 0 class WindowsMouse(Mouse): def __init__(self): super().__init__() print("[DEBUG] Windows Mouse Initialized") def left_click(self): self.mouse_down() self.mouse_up() def right_click(self): win32api.mouse_event(win32con.MOUSEEVENTF_RIGHTDOWN,0,0,0,0) win32api.mouse_event(win32con.MOUSEEVENTF_RIGHTUP,0,0,0,0) def double_click(self): self.mouse_down() self.mouse_up() self.mouse_down() self.mouse_up() def mouse_down(self): # x, y = win32api.GetCursorPos() win32api.mouse_event(win32con.MOUSEEVENTF_LEFTDOWN,0,0,0,0) self.state = "DOWN" def mouse_up(self): # x, y = win32api.GetCursorPos() win32api.mouse_event(win32con.MOUSEEVENTF_LEFTUP,0,0,0,0) self.state = "UP" def moveD(self, dx, dy): # MOVE DRAG win32api.mouse_event(win32con.MOUSEEVENTF_MOVE,int(dx),int(dy),0,0) def move(self, x, y): win32api.SetCursorPos((int(x), int(y))) def position(self): return win32api.GetCursorPos() class LinuxMouse(Mouse): def __init__(self): super().__init__() print("[DEBUG] Linux Mouse Initialized") def left_click(self): self.mouse_down() self.mouse_up() def right_click(self): mouse.press(button='right') mouse.release(button='right') def double_click(self): self.mouse_down() self.mouse_up() self.mouse_down() self.mouse_up() def mouse_down(self): mouse.press(button='left') def mouse_up(self): mouse.release(button='left') def moveD(self, dx, dy): # MOVE DRAG mouse.move(dx, dy, absolute=False, duration=0) def move(self, x, y): mouse.move(x, y, absolute=True, duration=0) def position(self): return mouse.get_position() <file_sep>/cameramouse/control/controllers.py """ Control Module Contents: Various cursor control methods - absolute, relative and joystick control """ import time, copy import numpy as np import gesture_recognition.gestures as gr from control.mouse_states import InRange, OutOfRange, Drag class Control(): """ Class used for mouse control, tackling the issue of how to map hand motion to cursor movements """ def __init__(self, filter, mouse): self.filter = filter self.mouse = mouse # Dictionaries to hold filtered information about the velocity and position of the hand self.current = {"position": np.array([0, 0]), "velocity": np.array([0, 0]), "timestamp": time.time()} self.previous = {"position": np.array([0, 0]), "velocity": np.array([0, 0]), "timestamp": time.time()} self.state = InRange(self.mouse) def setup(self, point): """ Setup needs to be done to fill the positions buffer """ self.filter.positions[:, 0] *= point[0] self.filter.positions[:, 1] *= point[1] self.previous["timestamp"] = time.time() self.previous["position"] = point def map_absolute(self): """ Returns the absolute position the cursor should move to """ raise NotImplementedError def map_relative(self): """ Return how much the cursor should move """ raise NotImplementedError def update(self, point): """ When a new postion of the hand is found we need to add that position to the filter Inputs: point: a (2, ) numpy.ndarray holding the (x, y) coordinates of the hand in the image frame """ self.current["timestamp"] = time.time() self.current["position"] = self.filter.get_filtered_position(point) dt = self.current["timestamp"] - self.previous["timestamp"] self.current["velocity"] = -(self.current["position"] - self.previous["position"]) / dt self.previous = copy.copy(self.current) def update_state(self, gesture): """ Description: updates the state of the mouse based on the most recent gesture input Inputs: gesture: Gesture obj, used to trigger state changes """ self.state = self.state.on_event(gesture) def execute(self, gesture): """ According to the gesture being made this function executes cursor movements and actions """ # x, y = self.map_absolute() # dx, dy = self.map_relative() self.update_state(gesture) cmd_x, cmd_y = None, None if self.state.__repr__() == "InRange": cmd_x, cmd_y = self.map_absolute() else: cmd_x, cmd_y = self.map_relative() self.state.execute(gesture, cmd_x, cmd_y) # # Execution of gestures # if gesture == gr.Gestures.drag: # if self.mouse.state == "UP": # self.mouse.mouse_down() # self.mouse.state = "DOWN" # else: # self.mouse.moveD(dx, dy) # needs to use differences # else: # if self.mouse.state == "DOWN": # self.mouse.mouse_up() # self.mouse.state = "UP" # if gesture == gr.Gestures.click: # self.mouse.left_click() # elif gesture == gr.Gestures.double_click: # self.mouse.double_click() # elif gesture == gr.Gestures.right_click: # self.mouse.right_click() # else: # self.mouse.move(x, y) # # print("Moving to {}".format((x, y))) class AbsoluteControl(Control): def __init__(self, filter, mouse, monitor, im_shape): super().__init__(filter, mouse) self.monitor = monitor # shrink useful area since hand centroid never reaches the edge of the frame self.new_width = int(0.5 * im_shape[0]) self.new_height = int(0.5 * im_shape[1]) # print("Abs New Region {}".format((self.new_width, self.new_height))) # calculate the new origin we will be using when mapping abs position to the cursor position self.new_orig_x = (im_shape[0] - self.new_width) // 2 self.new_orig_y = (im_shape[1] - self.new_height) // 2 # print("Abs New Origin {}".format((self.new_orig_x, self.new_orig_y))) # scaling ratios self.x_ratio = self.monitor.width**2 / (self.new_width * im_shape[0]) self.y_ratio = self.monitor.height**2 / (self.new_height * im_shape[1]) # print("RATIOs {}".format((self.x_ratio, self.y_ratio))) print("[DEBUG] Absolute Controller Initialised") def remap(self, point): # coordinate shift to new origin x, y = point x -= self.new_orig_x y -= self.new_orig_y x = np.clip(x, 0, self.new_width) y = np.clip(y, 0, self.new_height) return np.array([x, y]) def map_absolute(self): pos_mapped = self.remap(self.current["position"]) x_cam = self.x_ratio * pos_mapped[0] y_cam = self.y_ratio * pos_mapped[1] # print("Remapped Position {}".format((x_cam, y_cam))) return [int(self.monitor.width-x_cam), int(self.monitor.height-y_cam)] # accounts for camera facing down def map_relative(self): pos_mapped = self.remap(self.current["position"]) x_cam = self.x_ratio * pos_mapped[0] y_cam = self.y_ratio * pos_mapped[1] print("Screen Position {}".format((int(self.monitor.width-x_cam), int(self.monitor.height-y_cam)))) cx, cy = self.mouse.position() dx = int(self.monitor.width-x_cam) - cx dy = int(self.monitor.height-y_cam) - cy return [dx, dy] class RelativeControl(Control): def __init__(self, filter, mouse): super().__init__(filter, mouse) self.lin_term = 7/100 self.quad_term = 4/20000 print("[DEBUG] Relative Controller Initialised") def map_absolute(self): """ Returns the x, y for the cursor to move to """ vel = self.current["velocity"] ret_x = int(vel[0] * self.get_gain(vel[0])) ret_y = int(vel[1] * self.get_gain(vel[1])) cx, cy = self.mouse.position() return np.array([ret_x+cx, ret_y+cy]) def map_relative(self): """ Returns the dx, dy for the cursor to move """ vel = self.current["velocity"] ret_x = int(vel[0] * self.get_gain(vel[0])) ret_y = int(vel[1] * self.get_gain(vel[1])) return np.array([ret_x, ret_y]) def get_gain(self, vel): return self.lin_term + self.quad_term*abs(vel) class JoystickControl(Control): def __init__(self, filter, mouse, im_shape): super().__init__(filter, mouse) self.centre = [im_shape[0] // 2, im_shape[1] // 2] self.centre_radius = 85 self.scale = 5 / self.centre_radius print("[DEBUG] Joystick Controller Initialised") def get_vector_from_centre(self, point): vec = [point[0] - self.centre[0], point[1] - self.centre[1]] return np.array(vec) def map_absolute(self): vector = self.get_vector_from_centre(self.current["position"]) change = None if np.linalg.norm(vector) < self.centre_radius: change = 0.0 * vector else: change = self.scale * vector cx, cy = self.mouse.position() return np.array([change[0] + cx, change[1] + cy]) def map_relative(self): vector = self.get_vector_from_centre(self.current["position"]) if np.linalg.norm(vector) < self.centre_radius: return 0.0 * vector else: return self.scale * vector<file_sep>/mouse-control-test/main.py #import cv2 import sys import keyboard import numpy as np import matplotlib.pyplot as plt from mouse_states import OutOfRange from pymouse import PyMouse from time import sleep class Monitor: '''Class for storing data about the display''' def __init__(self): # Windows only at this stage print("NO") class Camera: '''Class for storing camera parameters''' def __init__(self): # TODO pass class MouseFSM(object): '''Class for the mouse FSM, handles state changes and what code is executed''' def __init__(self): self.state = OutOfRange() def on_event(self, event): '''Handle a gesture input and use it to either remain in the current state or move states''' self.state = self.state.on_event(event) def draw(vx, vy, dt): x_cur, y_cur = mouse.position() for i in range(0, len(vx)): x_cur = int(0.3*vx[i]) + x_cur y_cur = int(0.3*vy[i]) + y_cur mouse.move(x_cur, y_cur) sleep(dt) '''Initialise our mouse class''' mouse = PyMouse() '''Get monitor information''' monitor = Monitor() '''Initialise state machine''' state = MouseFSM() '''TODO: Get camera information''' # https://www.pyimagesearch.com/2014/08/18/skin-detection-step-step-example-using-python-opencv/ # https://stackoverflow.com/questions/8593091/robust-hand-detection-via-computer-vision '''Setup variables for a preset mouse path''' t = 10 dt = t / 100 theta = np.linspace(0, 6.2, t/dt) r = 100 '''Calculate x, y, dx, dy for the desired shape''' x = r*np.cos(theta) + np.random.normal(0, 5, len(theta)) #mu, sigma y = r*np.sin(theta) + np.random.normal(0, 5, len(theta)) dx = x[1:] - x[:-1] dy = y[1:] - y[:-1] '''Calculate the velocity between points''' vx = dx/dt vy = dy/dt plt.plot(x, y) plt.show() entry = 1 while True: '''Check for keypresses to move between states''' if str(state.state) == 'OutOfRange': # Wait for state change if entry: entry = 0 pass else: if keyboard.is_pressed('i'): state.on_event('in_range') entry = 1 elif str(state.state) == 'InRange': # Track hand motion # Calculate change in position # Move the mouse if entry: draw(vx, vy, dt) entry = 0 else: if keyboard.is_pressed('o'): state.on_event('out_of_range') entry = 1 elif keyboard.is_pressed('d'): state.on_event('drag') entry = 1 elif str(state.state) == 'Drag': # Track hand motion # Calculate change in position # Move the mouse and the item it has clicked on if entry: entry = 0 pass else: if keyboard.is_pressed('i'): state.on_event('in_range') entry = 1 <file_sep>/mediapipe/scripts/build.sh #!/bin/sh bazel-1.2.1 build -c opt --define MEDIAPIPE_DISABLE_GPU=1 mediapipe/examples/desktop/hand_tracking:hand_tracking_cpu <file_sep>/cameramouse/hand_tracking/colour_segmentation.py import cv2, yaml import numpy as np import time class Hand(): """ Class to represent the hand with member variables and helper functions to update the state """ def __init__(self): self.centroid = None self.rectangle = None self.area = None self.timestamp = None self.velocity = np.array([0, 0]) def set_state(self, rect, centroid, area, timestamp): """ Sets the state of the hand using output of CV functions """ self.centroid = centroid self.rectangle = rect self.area = area self.timestamp = timestamp class HandSegmetation(): """ Hand Segmentation Class for HS Colour Segmentation """ def __init__(self, camera, testMorphology=False, numRectangles=9, blurKernel=(7,7)): self.blurKernel = blurKernel # size of kernel for Gaussian Blurring self.numRectangles = numRectangles self.testMorphology = testMorphology self.camera = camera # needed for the segmentation to calibrate _, self.color_frame = self.camera.capture_frames() # create a rectangle to sample skin colour from self.sample_rect_size = 100 centre = [self.color_frame.shape[1] // 2, self.color_frame.shape[0] // 2 - 100] self.sample_rectangle = self.create_rectangle(centre, self.sample_rect_size) self.morphElement = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (8, 16)) self.denoiseElement = cv2.getStructuringElement(cv2.MORPH_RECT, (7, 7)) self.dilationIterations = 4 self.erosionIterations = 2 self.colorThresh = 50 self.areaThreshold = 0 self.alpha = 0.0 print("[DEBUG] Colour Segmentation Module Initialized") def get_histogram(self): """ Loops until the user presses 'z', after that it'll parse the region in the green square to get an HSV histogram representation of the users skin colour. """ # loop until we have a hand histogram (indicated by pressing 'z') cv2.namedWindow("CalibrationFeed") hand_hist_created = False while hand_hist_created == False: pressed_key = cv2.waitKey(1) gray_frame, self.color_frame = self.camera.capture_frames() self.blur = cv2.GaussianBlur(self.color_frame, self.blurKernel, 0) cv2.rectangle(self.color_frame, self.sample_rectangle[0], self.sample_rectangle[1], (0, 255, 0), 1) if pressed_key & 0xFF == ord('z'): hand_hist_created = True self.hand_hist = self.hand_histogram() cv2.imshow("CalibrationFeed", self.color_frame) cv2.destroyWindow("CalibrationFeed") def create_rectangle(self, centre, rect_size): """ Used to create sqaures given a centre point and the size Returns a rectangle: [top_left_coords, bottom_right_coords] """ x, y = centre tl_x = x - (rect_size // 2) tl_y = y - (rect_size // 2) # top right corner of the squares br_x = tl_x + rect_size br_y = tl_y + rect_size return [(tl_x, tl_y), (br_x, br_y)] def hand_histogram(self): """ Returns the cv histogram in HSV colour space from the self.sample_rectangle """ hsv_frame = cv2.cvtColor(self.blur, cv2.COLOR_BGR2HSV) roi = np.zeros([self.sample_rect_size, self.sample_rect_size, 3], dtype=hsv_frame.dtype) #region of interest # load our pixel values from each rectangle into roi variable roi = hsv_frame[self.sample_rectangle[0][1]:self.sample_rectangle[1][1], self.sample_rectangle[0][0]:self.sample_rectangle[1][0]] hand_hist = cv2.calcHist([roi], [0, 1], None, [12, 15], [0, 180, 0, 256]) return cv2.normalize(hand_hist, hand_hist, 0, 255, cv2.NORM_MINMAX) def adapt_histogram(self, sample): """ Takes in an RGB sample from an image and updates the hand histogram at rate self.alpha """ roi = cv2.cvtColor(sample, cv2.COLOR_BGR2HSV) try: hand_hist_new = cv2.calcHist([roi], [0, 1], None, [12, 15], [0, 180, 0, 256]) hand_hist_new = cv2.normalize(hand_hist_new, hand_hist_new, 0, 255, cv2.NORM_MINMAX) self.hand_hist = hand_hist_new * self.alpha + (1-self.alpha) * self.hand_hist self.hand_hist = cv2.normalize(self.hand_hist, self.hand_hist, 0, 255, cv2.NORM_MINMAX) except: pass def get_objects(self, frame): """ Takes in a frame and returns the contours of all of the skin coloured regions in that area """ blur = cv2.GaussianBlur(frame, self.blurKernel, 0) hsv = cv2.cvtColor(blur, cv2.COLOR_BGR2HSV) dst = cv2.calcBackProject([hsv], [0, 1], self.hand_hist, [0, 180, 0, 256], 1) disc = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (5,5)) cv2.filter2D(dst, -1, disc, dst) _, thresh = cv2.threshold(dst,self.colorThresh,255,cv2.THRESH_BINARY) erosion = cv2.erode(thresh, self.denoiseElement, iterations = self.erosionIterations) dilation = cv2.dilate(erosion, self.morphElement, iterations = self.dilationIterations) locatedObject = cv2.medianBlur(dilation, 5) if self.testMorphology: cv2.imshow("MorphologyTest", locatedObject) # get contours from thresholded image try: _, cont, hierarchy = cv2.findContours(locatedObject, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) except: cont, hierarchy = cv2.findContours(locatedObject, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) return cont <file_sep>/cameramouse/main.py """ Main file for running the full python computer mouse """ import cameramouse import yaml with open('config.yaml') as f: opts = yaml.load(f, Loader=yaml.FullLoader) mouse = cameramouse.HandSegmentationMouse(opts) if __name__ == "__main__": mouse.run() <file_sep>/cameramouse/README.md # OpenCV Only Full Python Implementation ### Dependencies ``` pip3 install keyboard==0.13.4 \ numpy==1.16.5 \ matplotlib==3.1.1 \ opencv-python pyyaml==5.3.1 \ argparse \ pyrealsense2==2.29.0.1124 \ mouse==0.7.1 \ pyautogui==0.9.48 ``` ### Files of interest to run Make sure to edit ```config.yaml``` to match your setup and the different control/segmentation type you want to use. A video demo can be seen [here](https://youtu.be/ekWOpIs6XiM). You place your hand in the green square, press 'z' to calibrate the user's skin colour and finally outstretch your hand to have it be detected. After this you can move your hand around to control the cursor. When using the keyboard mouse press 'o' to go out of range and any other key to exit this state. 'd' to start dragging and 'd' to stop. 's' is single click and the other actions can be found in gesture_recognition/keyboard.py. ``` cd cameramouse python3 main.py ``` To run only the hand tracking module ``` cd cameramouse python3 -m hand_tracking --webcam -src 0 or python3 -m hand_tracking --realsense ``` ### System Overview 1. Hand Tracking 1. Responsible for keeping track of the hands state (position and velocity information). 2. In particular I have been using hand tracking to predict where the hand will be so I only need to check a small subset of the frame. 2. Hand Segmentation: 1. Just needs to take in an image and return the coordinates of the hand centroid in the frame provided. 2. Colour segmentation is sensitive to the calibration & lighting. If your encountering issues just pull your hand away and recalibrate. 3. Another issue with colour segmentation is that it performs poorly when the hand is moved to the edges of the frame. On calibration it may be worth taking several hand samples, some from the corners and others from the centre of the frame. 3. The tracker calls ```adapt_histogram``` and passes a square subsection of the frame that surrounds the centroid. This attempts to account for changes in lighting but mostly makes it perform worse. Perhaps because the region is too small. The histogram representation of the skin is updated by a rate according to ```self.alpha```. 4. Other hand location techniques should definitely be tested such as classifiers or anything else that seems feasible. 3. Filter 1. Takes in the hands position and is capable of getting the filtered position. 2. Has two primary functions: ```insert_point``` and ```get_filtered_position```. 3. These filters are very basic and use constant scale factors. The FIR is basically just a moving average filter. These could be improved on with better analysis on noise/users tremors or shakes. 4. Control 1. Takes in the filtered positions of the hand and maps this to cursor motion. 2. Also takes in gesture info(type Gestures in gesture_recognition/gestures.py) and maps that to cursor actions such as a click or right-click. 5. Gesture Recognition 1. Processes whatever input be it video or voice and outputs the gesture type at any point to the controller module. 2. Currently there is only a keyboard implementation which maps key presses to different mouse actions. ![cameramouse-system-diagram](https://github.com/toby-l-baker/assistive-mouse-capstone/blob/master/cameramouse/cameramouse-system-diagram.PNG) ### File Structure 1. hardware/ 1. camera.py: captures image frames 2. monitor: captures width and height of system info 3. mouse: api interface's for different OS's 2. hand_tracking/ 1. colour_segmentation.py: performs hsv colour segmentation on frames 2. tracking.py: tracks hand movement and predicts where it will be and passes predictions to segmentation module. 3. gesture_recognition/ 1. gestures.py: containes Gestures class and GestureRecognition parent class 2. keyboard.py: using key presses to map to gestures 4. control/ 1. controllers.py 2. filters.py: IIR and FIR filter: very basic implementation with constant scale factors for each value in the stored array - could easily be improved 3. mouse_states.py: state machine which handles what gets execute in different states and the transitions: the states are OUT_OF_RANGE - don't execute mouse actions or movements, IN_RANGE - track movement and execute clicks, DRAG - click down on entry and then track movement, on exit move the mouse up. 5. test/ 1. was used to test out different filters on recorded data and simulates cursor movement in matplotlib 5. utils.py 1. a loading class for loading different modules eg iir vs fir filter 6. cameramouse.py 1. brings together all of the above ### Future Work 1. Anti-Shake Filtering for people with tremors 2. Voice recognition for mouse actions - CV tracking works reasonably particularly with relative control and IIR filtering and could easily be adapted to use this over the keyboard input for mouse actions. 3. Other hand segmentation methods 4. OpenCV Gesture Recognition <file_sep>/colour_segmentation_cpp/main.cpp //Uncomment the following line if you are compiling this code in Visual Studio //#include "stdafx.h" #include <opencv2/opencv.hpp> #include <opencv2/imgproc.hpp> #include <opencv2/highgui.hpp> #include <iostream> #include "params.hpp" using namespace cv; using namespace std; /*** GLOBALS ***/ // width and height of the frame double dHeight; double dWidth; // For drawing on frames cv::Scalar blue (255, 0, 0); cv::Scalar green (0, 255, 0); cv::Scalar red (0, 0, 255); // Hand Histogram cv::Mat hand_hist; // Setup for various histogram values // int ch[] = {0, 1}; // int hist_size[] = {H_BINS, S_BINS}; // float h_ranges[] = {0, 180}; // float s_ranges[] = {0, 255}; // const float* ranges[] = { h_ranges, s_ranges }; // Setup for various histogram values int ch[2]; int hist_size[2]; float h_ranges[2]; float s_ranges[2]; const float* ranges[2]; /*** Helper Functions ***/ // Initialises our histogram using a hand sample when it first enters the frame cv::Mat get_histogram(const cv::Mat& roi) { cv::Mat hand_histogram; cv::calcHist(&roi, 1, ch, cv::Mat(), //do not use a mask hand_histogram, 2, hist_size, ranges, true); cv::normalize(hand_histogram, hand_histogram, 0, 255, cv::NORM_MINMAX); return hand_histogram; } // Adapts the histogram based off of each new frame to account for changes in lighting // takes in a sample and the current histogram and returns a new one cv::Mat adapt_histogram(const cv::Mat& roi, cv::Mat& histogram) { cv::Mat new_hist; cv::calcHist(&roi, 1, ch, cv::Mat(), //do not use a mask new_hist, 2, hist_size, ranges, true); cv::normalize(new_hist, new_hist, 0, 255, cv::NORM_MINMAX); return histogram*(1-HIST_SENSITIVITY) + HIST_SENSITIVITY*new_hist; } // Clips an integer value to be in some range lower < n < upper int clip(int n, int lower, int upper) { return std::max(lower, std::min(n, upper)); } // Takes in an hsv frame, performs some morphology and thresholding // it then finds all contours in the image matching the hand and returns // them vector<vector<Point>> get_contours(cv::Mat hsv_frame) { cv::Mat temp; // cv::Mat filtered; cv::Mat backproj; cv::calcBackProject(&hsv_frame, 1, ch, hand_hist, backproj, ranges); // see how well the pixels fit our histogram cv::Mat erosion_kernel = cv::getStructuringElement(cv::MORPH_RECT, Size(7, 7)); cv::Mat dilation_kernel = cv::getStructuringElement(cv::MORPH_ELLIPSE, Size(8, 8)); // Filtering, morphological operations and thresholding cv::filter2D(backproj, temp, -1, // dimension the same as source image getStructuringElement(cv::MORPH_ELLIPSE, cv::Size(6,6))); //convolves the image with this kernel cv::threshold(temp, temp, HS_THRESH, 255, 0); // 0 is binary thresholding cv::erode(temp, temp, erosion_kernel, cv::Point(-1, -1), EROSION_IT); //anchor, iterations cv::dilate(temp, temp, dilation_kernel, cv::Point(-1, -1), DILATION_IT); cv::medianBlur(temp, temp, 5); // Get contours vector<vector<Point>> contours; vector<Vec4i> hierarchy; cv::findContours(temp, contours, hierarchy, cv::RETR_EXTERNAL, cv::CHAIN_APPROX_SIMPLE); // //show the thresholded frame // cv::imshow("Thresholded Output", temp); // //show the output of filter 2D // cv::imshow("Filtered Back Projection", filtered); return contours; } /*** Hand Object ***/ class Hand { public: cv::Point centroid; // centroid of the contour cv::Rect bound; // bounding box of the contour double area; // area of the contour // double timestamp; cv::Point velocity; // the relative movement of the centroid compared to the previous frame void set_state(cv::Point, cv::Rect, double); // sets the above variables void update_velocity(Hand); // sets the velocity using the previous state } hand; void Hand::set_state (cv::Point centroid_, cv::Rect bound_, double area_) { centroid = centroid_; bound = bound_; area = area_; // timestamp = timestamp_; } void Hand::update_velocity(Hand old) { // float dt = timestamp - old.timestamp; velocity = centroid - old.centroid; } /*** Hand Tracker Object ***/ class HandTracker { public: Hand old_hand; Hand new_hand; cv::Rect predict_position(void); // predicts a region where the hand will be based on the prior velocity void update_position(cv::Mat, cv::Rect roi_mp, bool mp_available); // locates the hand in the bounded region defined by predict_position } tracker; cv::Rect HandTracker::predict_position() { float vx = old_hand.velocity.x; float vy = old_hand.velocity.y; cv::Rect prediction (old_hand.bound.x, old_hand.bound.y, old_hand.bound.width+EXPANSION_VAL, old_hand.bound.height+EXPANSION_VAL); // create a wider region to search for the hand in prediction.x = prediction.x + vx - EXPANSION_VAL/2; // shift the origin of the rect so their centers align prediction.y = prediction.y + vy - EXPANSION_VAL/2; prediction.x = clip(prediction.x, 0, dWidth); // co-ordinate shift to global frame and clamping prediction.y = clip(prediction.y, 0, dHeight); int max_width = dWidth - prediction.x; int max_height = dHeight - prediction.y; prediction.width = clip(prediction.width, 0, max_width); prediction.height = clip(prediction.height, 0, max_height); return prediction; } // Returns a hand struct of where the hand is in the frame currently void HandTracker::update_position(cv::Mat frame, cv::Rect roi_mp, bool mp_available) { cv::Rect roi (roi_mp.x, roi_mp.y, roi_mp.width, roi_mp.height); if (mp_available == false) { roi = predict_position(); } vector<vector<Point>> contours = get_contours(frame(roi)); // this will be in local coords // Currently uses largest contour by area double max_area = 0.0; vector<Point> max_contour; for (int it = 0; it < contours.size(); it++) { double area = cv::contourArea(contours[it]); if (area > max_area) { max_area = area; max_contour = contours[it]; } } // Draw a bounding box around the largest contour cv::Rect bound = cv::boundingRect(max_contour); bound.x = bound.x + roi.x; // co-ordinate shift to global frame and clamping bound.y = bound.y + roi.y; // Get the centroid cv::Moments m = cv::moments(max_contour); cv::Point centroid (m.m10/m.m00, m.m01/m.m00); centroid.x += roi.x; centroid.y += roi.y; // Set the state of the new hand new_hand.set_state(centroid, bound, max_area); cv::rectangle(frame, bound, red, 2); cv::rectangle(frame, roi, green, 2); // cv::rectangle(frame, hand_sample, blue, 2); cv::circle(frame, centroid, 5, blue, -1); } int main(int argc, char* argv[]) { //Open the default video camera VideoCapture cap(0); // if not success, exit program if (cap.isOpened() == false) { cout << "Cannot open the video camera" << endl; cin.get(); //wait for any key press return -1; } cap.set(cv::CAP_PROP_FPS, 30); // set frame rate to 30 bool calibrated = false; ch[0] = 0; ch[1] = 1; hist_size[0] = H_BINS; hist_size[1] = S_BINS; h_ranges[0] = 0; h_ranges[1] = 180; s_ranges[0] = 0; s_ranges[1] = 255; ranges[0] = h_ranges; ranges[1] = s_ranges; HandTracker hand_tracker; cv::Mat frame; cv::Mat frame_blurred; cv::Mat hsv; bool bSuccess; while (true) { // HISTOGRAM CALIBRATION // TODO: interface with medaipipe so each time the camera moves from our of frame to in frame we take a sample and initialise the hands position if (calibrated == false) { bSuccess = cap.read(frame); // read a new frame from video cv::GaussianBlur(frame, frame_blurred, Size(BLUR_KERNEL_SIZE, BLUR_KERNEL_SIZE), 0); // Blur image with 5x5 kernel dWidth = frame.size().width; dHeight = frame.size().height; int centre [2] = {dWidth/2, dHeight/2}; // centre of the frame cv::Rect roi_rect (centre[0], centre[1], BOX_SIZE, BOX_SIZE); cv::rectangle(frame_blurred, roi_rect.tl(), roi_rect.br(), blue); if (waitKey(10) == 'z') { // hand is in the right spot, sample histogram cv::Mat roi = frame_blurred(roi_rect); cv::cvtColor(roi, hsv, cv::COLOR_BGR2HSV); hand_hist = get_histogram(hsv); calibrated = true; cv::cvtColor(frame_blurred, hsv, cv::COLOR_BGR2HSV); vector<vector<Point>> conts = get_contours(hsv); // Currently uses largest contour by area double max_area = 0.0; vector<Point> max_contour; for (int it = 0; it < conts.size(); it++) { double area = cv::contourArea(conts[it]); if (area > max_area) { max_area = area; max_contour = conts[it]; } } cv::Rect bound = cv::boundingRect(max_contour); // Get the centroid cv::Moments m = cv::moments(max_contour); cv::Point centroid (m.m10/m.m00, m.m01/m.m00); // Set the state of the new hand hand_tracker.old_hand.set_state(centroid, bound, max_area); hand_tracker.old_hand.velocity = {0, 0}; } cv::imshow("Feed", frame_blurred); } else { // Hand Calibrated bSuccess = cap.read(frame); // read a new frame from video cv::GaussianBlur(frame, frame_blurred, Size(BLUR_KERNEL_SIZE, BLUR_KERNEL_SIZE), 0); // Blur image with 5x5 kernel cv::cvtColor(frame_blurred, hsv, cv::COLOR_BGR2HSV); cv::Rect roi_mp (0, 0, 1, 1); hand_tracker.update_position(hsv, roi_mp, false); hand_tracker.new_hand.update_velocity(hand_tracker.old_hand); hand_tracker.old_hand.set_state(hand_tracker.new_hand.centroid, hand_tracker.new_hand.bound, hand_tracker.new_hand.area); hand_tracker.old_hand.velocity = hand_tracker.new_hand.velocity; //show the filtered back projection cv::cvtColor(hsv, frame_blurred, cv::COLOR_HSV2BGR); cv::imshow("Feed", frame_blurred); } // Breaking the while loop if the frames cannot be captured if (bSuccess == false) {break;} // Check if 'esc' is pressed if (waitKey(10) == 27) {break;} } return 0; }<file_sep>/cameramouse/test/filter_test.py import numpy as np import csv, argparse, sys sys.path.append('../cameramouse') from interface import WindowsMonitor import matplotlib.pyplot as plt # construct the argument parse and parse the arguments ap = argparse.ArgumentParser() ap.add_argument("-fname", "--filename", type=str, required=True, help="filename of data you want to test: still_fist, circle, up_down, left_right, finger_extensions") ap.add_argument("-os", "--os", type=str, required=False, default="win", help="your OS: win, linux") ap.add_argument("-filt", "--filter", type=str, required=False, help="filter you want to test: averaging ") ap.add_argument("-p", "--plot", type=bool, default=True, help="whether you want to plot or not") args = ap.parse_args() class Filter(): def __init__(self, rects, centroids, vels, areas, times): self.rects = rects self.centroids = centroids self.vels = vels self.areas = areas self.times = times self.cursor_initial = [monitor.width//2, monitor.height//2] def filter(self): pass def map_vel_to_pixels(self, vel): # tf = tanh((1/10)x - 2) + 1 where x is the speed in terms of movement on the screen g_x = 1/15 + abs(1/3000*vel[0]) g_y = 1/15 + abs(1/3000*vel[1]) # print("{}, {}".format(g_x, g_y)) ret_x = int(vel[0] * g_x) ret_y = int(vel[1] * g_y) return [ret_x, ret_y] def simulate_cursor_unfilt(self): cursor_positions = [] cursor_positions.append(self.cursor_initial) for i in range(1, len(self.centroids)): # dt = self.times[i] - self.times[i-1] dt = 1/30 dx = self.centroids[i][0] - self.centroids[i-1][0] dy = self.centroids[i][1] - self.centroids[i-1][1] v = self.map_vel_to_pixels([-dx/dt, -dy/dt]) pos = [v[0] + cursor_positions[i-1][0], v[1] + cursor_positions[i-1][1]] pos[0] = np.clip(pos[0], 0, monitor.width) pos[1] = np.clip(pos[1], 0, monitor.height) cursor_positions.append(pos) return np.array(cursor_positions) def simulate_cursor(self): self.filter() cursor_positions = [] cursor_positions.append(self.cursor_initial) for i in range(1, len(self.averaged_positions)): dt = 1 / 30 # self.times[i] - self.times[i-1] dx = self.averaged_positions[i][0] - self.averaged_positions[i-1][0] dy = self.averaged_positions[i][1] - self.averaged_positions[i-1][1] v = self.map_vel_to_pixels([-dx/dt, -dy/dt]) pos = [v[0] + cursor_positions[i-1][0], v[1] + cursor_positions[i-1][1]] pos[0] = np.clip(pos[0], 0, monitor.width) pos[1] = np.clip(pos[1], 0, monitor.height) cursor_positions.append(pos) return np.array(cursor_positions) class AveragingFilter(Filter): def __init__(self,rects, centroids, vels, areas, times, filter_size): super().__init__(rects, centroids, vels, areas, times) self.filter_size = filter_size def filter(self): self.averaged_positions = [] for i in range(0, len(self.centroids)-self.filter_size): x = np.average(self.centroids[i:i+self.filter_size, 0]) y = np.average(self.centroids[i:i+self.filter_size, 1]) self.averaged_positions.append([x, y]) class RecursiveFilter(Filter): def __init__(self,rects, centroids, vels, areas, times, scale_factor): super().__init__(rects, centroids, vels, areas, times) assert(scale_factor < 1 and scale_factor > 0) self.scale_factor = scale_factor self.filter_size = 2 def filter(self): self.averaged_positions = [] for i in range(self.filter_size, len(self.centroids)): x_1, y_1 = self.centroids[i-1, :] x_2, y_2 = self.centroids[i-2, :] x_0, y_0 = self.centroids[i, :] x = self.scale_factor / 2 * (x_1 + x_2) + (1 - self.scale_factor) * x_0 y = self.scale_factor / 2 * (y_1 + y_2) + (1 - self.scale_factor) * y_0 self.averaged_positions.append([x, y]) class AreaFilter(Filter): def __init__(self,rects, centroids, vels, areas, times, threshold): super().__init__(rects, centroids, vels, areas, times) self.thresh = threshold self.unfiltered_vels = vels.copy() def filter(self): self.averaged_positions = self.centroids count = 0 dt = 1/30 delta_area = areas[1:] - areas[:-1] rate_delta_area = (delta_area)/(dt) for i in range(1, len(velocities)): if abs(rate_delta_area[i-1]) > self.thresh: count += 1 print("setting me to zero, total count = {}".format(count)) self.vels[i, 0] = 0 self.vels[i, 1] = 0 def simulate_cursor(self): self.filter() cursor_positions = [] cursor_positions.append(self.cursor_initial) for i in range(0, len(self.vels)): v = self.map_vel_to_pixels([-self.vels[i, 0], -self.vels[i, 1]]) pos = [v[0] + centroids[i-1][0], v[1] + centroids[i-1][1]] # print(pos) pos[0] = np.clip(pos[0], 0, monitor.width) pos[1] = np.clip(pos[1], 0, monitor.height) cursor_positions.append(pos) return np.array(cursor_positions) raw_data = np.loadtxt(args.filename+'.csv', delimiter=',') rectangles = raw_data[:, 0:4] centroids = raw_data[:, 4:6] velocities = raw_data[:, 6:8] areas = raw_data[:, 8] timestamps = raw_data[:, 9] #- raw_data[0, 9] # load times and set initial time to zero if args.os == "win": global monitor monitor = WindowsMonitor() elif args.os == "linux": pass #TODO Make this automatic global cam_res cam_res = [1280, 720] if args.filter == "averaging": filter = AveragingFilter(rectangles, centroids, velocities, areas, timestamps, 5) elif args.filter == "area": filter = AreaFilter(rectangles, centroids, velocities, areas, timestamps, 50000) elif args.filter == "recursive": filter = RecursiveFilter(rectangles, centroids, velocities, areas, timestamps, 0.5) # fig, axs = plt.subplots(2, 2) # axs[0, 0].plot(np.arange(0, int(len(areas)*1/30), 1/30), areas, 'x') # axs[0, 0].set_title('Contour Area over Time') # axs[0, 1].plot(centroids[2:,0], centroids[2:, 1], 'o') # axs[0, 1].set_title('Centroids over time') # dt = 1/30 # delta_area = areas[1:] - areas[:-1] # rate_delta_area = (delta_area)/(dt) # t = np.arange(1/30, int(len(areas)*1/30), 1/30) # axs[1, 0].plot(t, rate_delta_area, 'x') # axs[1, 0].set_ylim([-200000, 200000]) # axs[1, 0].set_title('Change in area at each timestep') # vels = np.array([np.sqrt(x**2 + y**2) for x, y in filter.vels]) # axs[1, 1].plot(t, vels[1:], 'x') # axs[1, 1].set_title('Velocities') # axs.legend(numpoints=1, loc='upper left') positions = filter.simulate_cursor() # print(postions) positions_unfilt = filter.simulate_cursor_unfilt() if args.plot == True: # plt.figure() fig, axs = plt.subplots(1, 2) axs[0].set_title('Filtered Positions') axs[1].set_title('Unfiltered Cursor Positions') # axs[2].set_title('Filtered Velocities') axs[0].set_xlim([0, monitor.width]) axs[0].set_ylim([0, monitor.height]) axs[1].set_xlim([0, monitor.width]) axs[1].set_ylim([0, monitor.height]) axs[0].plot(positions_unfilt[:, 0], positions_unfilt[:, 1]) axs[1].plot(positions[:, 0], positions[:, 1]) for i in range(1, len(positions)): axs[0].plot(positions[i, 0], positions[i, 1], 'o') if args.filter in ["averaging", "recursive"]: axs[1].plot(positions_unfilt[i+filter.filter_size, 0], positions_unfilt[i+filter.filter_size, 1], 'o') elif args.filter == "area": axs[1].plot(positions_unfilt[i-1, 0], positions_unfilt[i-1, 1], 'o') # print(positions_unfilt.shape) # vels = np.array([np.sqrt(x**2 + y**2) for x, y in filter.vels]) # axs[2].plot(t, vels[1:], 'o') plt.pause(0.02) if args.filter == "area": fig, axs = plt.subplots(4, 1) axs[0].plot(np.arange(0, int(len(areas)*1/30), 1/30), areas, 'g') axs[0].set_title('Contour Area over Time') axs[0].grid(True) dt = 1/30 delta_area = areas[1:] - areas[:-1] rate_delta_area = (delta_area)/(dt) t = np.arange(1/30, int(len(areas)*1/30), 1/30) axs[1].plot(t, rate_delta_area, 'r') axs[1].set_ylim([-250000, 250000]) axs[1].set_title('Change in area at each timestep') axs[1].grid(True) vels = np.array([np.sqrt(x**2 + y**2) for x, y in filter.vels]) axs[2].plot(t, vels[1:], 'm') axs[2].set_title('Velocities') axs[2].set_ylim([-50, np.max(filter.unfiltered_vels)]) axs[2].grid(True) vels_u = np.array([np.sqrt(x**2 + y**2) for x, y in filter.unfiltered_vels]) axs[3].plot(t, vels_u[1:], 'b') axs[3].set_title('Velocities Unfiltered') axs[3].set_ylim([-50, np.max(filter.unfiltered_vels)]) axs[3].grid(True) plt.show() <file_sep>/mouse-control-test/mouse_control_for_demo1_with_new_gesures.py #! /usr/bin/env python # -*- coding: utf-8 -*- # vim:fenc=utf-8 # # Copyright © 2020 weihao <<EMAIL>> # # Distributed under terms of the MIT license. """ """ import pyautogui # NOTE set pyautogui.FAILSAFE = False is important trust me im engineer pyautogui.FAILSAFE = False from collections import deque import numpy as np width, height = pyautogui.size() left_down = False right_down = False skip_counter = 0 left_down_counter = 0 queue_size = 5 x_queue = deque() y_queue = deque() x_sum = 0 y_sum = 0 x_res_queue = deque() y_res_queue = deque() x_res_sum = 0 y_res_sum = 0 x_prev = y_prev = 0 # Mouse is a fifo where PipeWritingCalculator writes to, you can create it with 'mkfifo Mouse' with open("Mouse") as f: for line in f: # skip 1 frame for every 2 frames since the frame reduction strategy employed by MediaPipe skip_counter += 1 if skip_counter != 2: continue else: skip_counter = 0 # the format of the input should be coordinate_x,coordinate_y,digit_representation_of_gesture split = line.rstrip('\n').split(",") x = float(split[0]) y = float(split[1]) gesture = int(split[2]) # x_prev is the previous x coordinate, here we calculate the difference x_diff = x - x_prev y_diff = y - y_prev x_prev = x y_prev = y # we use a queue to cache incoming coordinates, once the queue is full, we use the average to represent the x/y coordinate # basically a naive filter if len(x_queue) == queue_size: x_removed = x_queue.popleft() y_removed = y_queue.popleft() x_sum -= x_removed y_sum -= y_removed x_sum += x_diff y_sum += y_diff x_queue.append(x_diff) y_queue.append(y_diff) else: x_queue.append(x_diff) y_queue.append(y_diff) x_sum += x_diff y_sum += y_diff continue # when there is no hand if gesture == 0 and x_diff == 0 and y_diff == 0: left_down = False pyautogui.mouseUp() # when there is a hand else: # when slow down gesture detected, mediapipe +10 to the digit representation of gesture slow_down = gesture >= 10 gesture = gesture % 10 # gesture=4 means press left button # left_down_counter is used in the context of dragging. The usual scenario of a left click is you first slow down, then click # if you want to drag something, you also first slow down, then press left button # then you drag it to somewhere else. But you're still in slow down mode # well, but after 5 frames, if your gesture is still 4, the slow down mode will be cancelled. if gesture == 4: left_down_counter += 1 if not left_down: left_down = True pyautogui.mouseDown() else: if left_down: left_down = False left_down_counter = 0 pyautogui.mouseUp() # gesture=2/3 means scroll up/down (maybe down/up) if gesture == 2: pyautogui.scroll(-1) if gesture == 3: pyautogui.scroll(1) # gesture=5 means right click if gesture == 5: if not right_down: pyautogui.click(button='right') right_down = True else: right_down = False # x_vel means x_velocity x_vel = x_diff y_vel = y_diff # some iir filter algorithm that I'm not satisfied with, feel free to implement your own if len(x_res_queue) != queue_size - 1: x_res_queue.append(x_diff) y_res_queue.append(y_diff) x_res_sum += x_diff y_res_sum += y_diff continue else: x_vel = (5 * x_sum - x_res_sum) / 21 y_vel = (5 * y_sum - y_res_sum) / 21 x_res_removed = x_res_queue.popleft() y_res_removed = y_res_queue.popleft() x_res_queue.append(x_vel) y_res_queue.append(y_vel) x_res_sum -= x_res_removed y_res_sum -= y_res_removed x_res_sum += x_vel y_res_sum += y_vel x_gain = np.tanh(abs(4*x_vel-2)) + 1 y_gain = np.tanh(abs(4*y_vel-2)) + 1 x_ = x_gain * x_vel * 3 y_ = y_gain * y_vel * 3 # the dragging thing that I mentioned earlier if left_down_counter > 5: slow_down = False # if slow down, the movement will be 10 times slower if slow_down: x_ *= 0.1 y_ *= 0.1 # the acutal move, NOTE set _pause=False is important, otherwise you'll find the script runs slower overtime pyautogui.moveRel(x_ * width, y_ * height, _pause=False) <file_sep>/mediapipe/scripts/run_demo2.sh export GLOG_logtostderr=1 bazel-bin/mediapipe/examples/desktop/hand_tracking/hand_tracking_cpu --calculator_graph_config_file=mediapipe/graphs/hand_tracking/gesture_recognition.pbtxt <file_sep>/mediapipe/scripts/run_demo1.sh #! /bin/sh # # hand.sh # Copyright (C) 2020 weihao <<EMAIL>> # # Distributed under terms of the MIT license. # GLOG_logtostderr=1 bazel-bin/mediapipe/examples/desktop/hand_tracking/hand_tracking_cpu \ --calculator_graph_config_file=mediapipe/graphs/hand_tracking/hand_tracking_desktop_live.pbtxt <file_sep>/cameramouse/hand_tracking/tracking.py import numpy as np import time, argparse, cv2, sys, copy, yaml import hand_tracking.colour_segmentation as colour_segmentation class HandTracker(): def __init__(self, camera): self.handSeg = colour_segmentation.HandSegmetation(camera, testMorphology=True) self.hand = colour_segmentation.Hand() # average 5 most recent positions self.prev_hand = colour_segmentation.Hand() # constants used during global recognition self.dist_threshold = 7500 # how far contour defects need to be from convex hull self.area_threshold = 45000 # how big detected hand area needs to be self.found = 0 # if we know where the hand is self.expansion_const = 50 # how much to expand ROI in prediction step # Initialise the size of the frame gray, color = camera.capture_frames() self.y_bound, self.x_bound, _ = color.shape self.centre = (self.x_bound // 2, self.y_bound // 2) # For writing on frames self.writer = {"font": cv2.FONT_HERSHEY_SIMPLEX, "origin": (50, 50), "font_size": 1, "colour": (255, 0, 0), "thickness": 2} print("[DEBUG] Hand Tracker Initialised") def global_recognition(self, color_frame): """ Description: Processes full frames to initialise the position of the hand, works by detecting an outstretched hand. Specifically it looks for defects in the convex hull of the contour which are far enough from the hull. These points correspond to the webbing in between each finger. Inputs: color_frame: returned from camera object, it is a numpy array Outputs: centroid: centroid of the located hand """ image = cv2.putText(color_frame, 'Outstretch hand to be detected', \ self.writer["origin"], self.writer["font"], self.writer["font_size"], \ self.writer["colour"], self.writer["thickness"], cv2.LINE_AA) # locate contours of skin-coloured regions conts = self.handSeg.get_objects(color_frame) # Iterate over all contours and check if they are a hand for i, cont in enumerate(conts): contArea = cv2.contourArea(cont) hull = cv2.convexHull(cont, returnPoints = False) defects = cv2.convexityDefects(cont, hull) out_count = 0 for i in range(defects.shape[0]): s,e,f,d = defects[i,0] far = tuple(cont[f][0]) #farthest point on contour from the line if d > self.dist_threshold: out_count += 1 cv2.circle(color_frame,far,5,[0,0,255],-1) # found the hand: initialise the tracker if (out_count >= 4) and (contArea > self.area_threshold): # thresholds for hand being found # Get bounding region rect = np.array(cv2.boundingRect(cont)) # Get centroid moment = cv2.moments(cont) cx = int(moment['m10']/moment['m00']) cy = int(moment['m01']/moment['m00']) centroid = np.array([cx, cy]) # Set our initial state self.prev_hand.set_state(rect, centroid, contArea, time.time()) self.found = 1 return centroid def update_position(self, frame, control_type): """ Steps: 1. Predict where the hand will be using prior velocity 2. Search the predicted region for the hand and find the centroid 3. Take a new skin colour sample from around the centroid and adapt the histogram 4. Draw bounding rectangles on the frame Input: frame: frame to search Outputs: centroid: the position of the new hand in the image frame """ # predict hand location based on velocity of hand in prev frame box = self._predict_position() # only look where we think the hand is roi = frame[box[1]:box[3], box[0]:box[2], :] # get all contours in roi conts = self.handSeg.get_objects(roi) # Get all contour areas and store in a numpy array areas = np.array([cv2.contourArea(cont) for cont in conts]) if len(conts) == 0: # no hand - reset self.found = 0 else: # multiple objects - get largest maxI = np.where(areas == np.amax(areas))[0] maxI = maxI[0] rect_area = areas[maxI] cont = conts[maxI] # get bounding rectangle rect = np.array(cv2.boundingRect(cont)) # need to do a coordinate shift as only searching roi rect[0] += box[0] # rect in global coords rect[1] += box[1] # get centroid m = cv2.moments(cont) centroid = np.array([int(m['m10']/m['m00']), int(m['m01']/m['m00'])]) local_centroid = centroid.copy() # need to do a coordinate shift as only searching roi not the whole frame centroid[0] += box[0] centroid[1] += box[1] # set the state of the new hand self.hand.set_state(rect, centroid, rect_area, time.time()) # adapt the histogram representation with a new sample from around the hand centroid sample_size = 50 top_left = centroid - sample_size // 2 hand_sample = frame[top_left[1]:top_left[1]+sample_size, top_left[0]:top_left[0]+sample_size, :] self.handSeg.adapt_histogram(hand_sample) # draw ROI bounding box and bounding box for the hand cv2.rectangle(frame, (int(box[0]), int(box[1])), \ (int(box[2]), int(box[3])), \ [0, 0, 255], 2) # draw the located hand area cv2.rectangle(frame, (int(rect[0]), int(rect[1])), \ (int(rect[0]+rect[2]), int(rect[1]+rect[3])), \ [0, 255, 0], 2) # draw the region we a re resampling from # cv2.rectangle(frame, (int(top_left[0]), int(top_left[1])), \ # (int(top_left[0]+sample_size), int(top_left[1]+sample_size)), \ # [255, 0, 0], 2) cv2.circle(frame, (centroid[0], centroid[1]), 5, (255, 0, 0), 1) if control_type == "joystick": cv2.circle(frame, self.centre, 85, (0, 0, 0), 1) vel = self.hand.centroid - self.prev_hand.centroid self.prev_hand = copy.copy(self.hand) self.prev_hand.velocity = vel return self.hand.centroid def _predict_position(self): """ Steps: 1. Use the old hand position as an initial guess 2. Translate the box by the prior velocity of the hand 3. Expand the box by a constant to ensure the whole hand is found 4. Clip to ensure the box doesn't leave the boundaries Outputs: corners: the corner locations for the box [top_left_x, top_left_y, bottom_right_x, bottom_right_y] """ # set corners to be prev bounding box corners = np.zeros((4), dtype=int) corners = self.prev_hand.rectangle # transform to corner locations corners[2] = corners[0] + corners[2] corners[3] = corners[1] + corners[3] # translate the box by the hands relative movement # print("Current: {}\nPrevious: {}".format(self.hand.centroid, self.prev_hand.centroid)) if self.hand.centroid is None: # on startup the new hand has no velocity velocity = np.array([0, 0]) else: velocity = self.prev_hand.velocity corners[0:2] = velocity + corners[0:2] corners[2:] = velocity + corners[2:] # expand the box size a constant amount corners[0:2] -= self.expansion_const corners[2:] += self.expansion_const corners[0] = np.clip(corners[0], 0, self.x_bound) corners[1] = np.clip(corners[1], 0, self.y_bound) corners[2] = np.clip(corners[2], 0, self.x_bound) corners[3] = np.clip(corners[3], 0, self.y_bound) return corners <file_sep>/mediapipe/mediapipe/framework/udp.h #ifndef MEDIAPIPE_FRAMEWORK_UDP_H_ #define MEDIAPIPE_FRAMEWORK_UDP_H_ #include <sys/types.h> #include <sys/socket.h> #include <netdb.h> namespace mediapipe { namespace udp { // =============================== CLIENT =================================== class client { private: int f_socket; int f_port; std::string f_addr; struct addrinfo *f_addrinfo; public: client(const std::string& addr, int port); ~client(); int get_socket() const; int get_port() const; std::string get_addr() const; int send(const char *msg, size_t size); }; // =============================== SERVER =================================== class server { private: int f_socket; int f_port; std::string f_addr; struct addrinfo *f_addrinfo; public: server(const std::string& addr, int port); ~server(); int get_socket() const; int get_port() const; std::string get_addr() const; int recv(char *msg, size_t max_size); int timed_recv(char *msg, size_t max_size, int max_wait_ms); }; } } #endif<file_sep>/mediapipe/scripts/clean.sh #!/bin/sh bazel-1.2.1 clean <file_sep>/testing/AccuracyTest.py #!/usr/bin/env python3 import numpy as np import cv2 import os import sys HEIGHT = 720 WIDTH = 720 FONT = cv2.FONT_HERSHEY_SIMPLEX SCALE = 24 THICKNESS = 24 TIMEOUT = 10 ENTER_KEY = 13 BASE_IMAGE = None TEST_IMAGE = None FULL_IMAGE = None DRAWING = False def callback(event, x, y, flags, param): global TEST_IMAGE, FULL_IMAGE, DRAWING # state machine to use mouse as a paintbrush if event == cv2.EVENT_LBUTTONDOWN: DRAWING = True elif event == cv2.EVENT_LBUTTONUP: DRAWING = False elif event == cv2.EVENT_MOUSEMOVE: if DRAWING is True: cv2.circle(TEST_IMAGE, (x, y), THICKNESS//2, (0, 0, 255), -1) cv2.circle(FULL_IMAGE, (x, y), THICKNESS//2, (0, 0, 255), -1) def test(letter): global BASE_IMAGE, TEST_IMAGE, FULL_IMAGE # create images BASE_IMAGE = np.full((HEIGHT, WIDTH, 3), 255, dtype='uint8') TEST_IMAGE = np.full((HEIGHT, WIDTH, 3), 255, dtype='uint8') FULL_IMAGE = np.full((HEIGHT, WIDTH, 3), 255, dtype='uint8') # draw letter on image size = cv2.getTextSize(letter, FONT, SCALE, THICKNESS) cv2.putText(BASE_IMAGE, letter, (WIDTH//2 - size[1], HEIGHT//2 + size[1]), FONT, SCALE, (0, 0, 0), THICKNESS) cv2.putText(FULL_IMAGE, letter, (WIDTH//2 - size[1], HEIGHT//2 + size[1]), FONT, SCALE, (0, 0, 0), THICKNESS) # save base image to file cv2.imwrite('base.png', BASE_IMAGE) while True: # update image cv2.imshow('image', FULL_IMAGE) # wait for keyboard input key = cv2.waitKey(TIMEOUT) # finish if Enter key is pressed if key == ENTER_KEY: break # save test image to file cv2.imwrite('test.png', TEST_IMAGE) # load images as grayscale base_image = cv2.imread('base.png', cv2.IMREAD_GRAYSCALE) test_image = cv2.imread('test.png', cv2.IMREAD_GRAYSCALE) # threshold test image and subtract from base_image thresh, thresh_image = cv2.threshold(test_image, 127, 255, cv2.THRESH_BINARY) # invert images base_image_inv = cv2.bitwise_not(base_image) thresh_image_inv = cv2.bitwise_not(thresh_image) # get overlapping region of the two images inside_image = cv2.bitwise_and(thresh_image_inv, base_image_inv) outside_image = cv2.bitwise_and(thresh_image_inv, base_image) # calculate number of pixels letter_pixels = int(np.sum(base_image_inv) / 255) # number of pixels in the letter inside_pixels = int(np.sum(inside_image) / 255) # number of pixels drawn inside the letter outside_pixels = int(np.sum(outside_image) / 255) # number of pixels drawn outside the letter total_pixels = int(np.sum(thresh_image_inv) / 255) # number of pixels drawn in total # calculate score if total_pixels == 0: score = 0 else: score = 50 * (inside_pixels / letter_pixels) + 50 * (inside_pixels / total_pixels) # delete saved images os.remove('base.png') os.remove('test.png') return score def main(args): scores = [] # check for correct number of arguments if len(args) != 2: print('Usage: AccuracyTest.py test_string') exit() else: letters = args[1] # create window cv2.namedWindow('image') cv2.setMouseCallback('image', callback) # run a test for each letter for letter in letters: score = test(letter) scores.append(score) # delete window cv2.destroyWindow('image') # calculate average score average = sum(scores) / len(scores) # display scores for letter, score in zip(letters, scores): print(letter + ": {0:.2f}".format(score) + "%") print("average: {0:.2f}".format(average) + "%") main(sys.argv) <file_sep>/colour_segmentation_cpp/params.hpp // Image Capture Parameters #define BLUR_KERNEL_SIZE 5 // Calibration Parameters #define BOX_SIZE 50 // Hand Histogram Parameters #define H_BINS 12 #define S_BINS 15 #define HIST_SENSITIVITY 0.01 // Thresholding Parameters #define HS_THRESH 50 #define EROSION_IT 2 #define DILATION_IT 4 // Tracker Parameters #define EXPANSION_VAL 50 #define SAMPLE_BOX_SIZE 25<file_sep>/gesture_learning/template.py #!/usr/bin/env python3 """ Description: Template for gesture recognition via machine learning Author: <NAME> (<EMAIL>) """ import sys import numpy as np import matplotlib.pyplot as plt import keypoints as kp # -------------------------------------------------------------------------------------------------- SPLIT = 0.75 # split percentage for training vs. testing data NORMALIZATION = 'features' # type of data normalization ('cartesian', 'polar', or 'features') # -------------------------------------------------------------------------------------------------- # NOTE: program needs keypoints.py which is located in gesture_learning/ def main(args): # check for correct arguments if len(args) != 2: # NOTE: data is located in gesture_learning/data/ print("Usage: python template.py data") exit() # process file with open(args[1], 'r') as f: train, test = kp.parse(f, shuffle=True, normalization=NORMALIZATION, split=SPLIT) # NOTE: training on a normal distribution can be easier for some approaches train.data = kp.dataset.normalize(train.data, train.mean, train.std) # NOTE: need to use training data information to normalize testing data test.data = kp.dataset.normalize(test.data, train.mean, train.std) ''' do all machine learning work here train.data contains entries that are formatted as 21 (x,y) points in order. These points were generated from MediaPipe and correspond to keypoints on the user's hand. When normalized, this becomes a set of 20 features depending on the normalization method. train.labels contains integers corresponding to different gestures. Each data entry has a corresponding label arranged such that train.data[i] is categorized by train.labels[i]. The gesture classes for the 'fiveClass' dataset are: 0 - CLOSE 1 - OPEN 2 - FINGERS_ONE 3 - FINGERS_TWO 4 - THUMB_BENT test.data is formatted the same as train.data and can be used to test the model against data it has never seen before test.labels is formatted the same as train.labels and can be used to quantify the accuracy of the model ''' print("shape of training data: " + str(train.data.shape)) print("shape of training labels: " + str(train.labels.shape)) print("") print("shape of testing data: " + str(test.data.shape)) print("shape of testing labels: " + str(test.labels.shape)) # NOTE: save models in gesture_learning/models/ # -------------------------------------------------------------------------------------------------- if __name__ == '__main__': main(sys.argv) <file_sep>/gesture_learning/DLNN.py #!/usr/bin/env python3 """ Description: Deep Learning Neural Network (DLNN) approach for gesture recognition Author: <NAME> (<EMAIL>) """ import os import argparse import numpy as np import matplotlib.pyplot as plt from keras import models, layers, utils import keypoints as kp EPOCHS = 100 # number of epochs to train the model BATCH_SIZE = 32 # training data batch size NORMALIZATION = 'features' # type of data normalization def plot_training(epochs, results): plt.subplots(2) # loss plt.subplot(2, 1, 1) plt.plot(epochs, results['loss'], '--', label="Training") plt.plot(epochs, results['val_loss'], '-', label="Validation") plt.title('Model Performance') plt.ylabel('Loss') plt.grid() plt.legend() # accuracy plt.subplot(2, 1, 2) plt.plot(epochs, results['acc'], '--', label="Training") plt.plot(epochs, results['val_acc'], '-', label="Validation") plt.xlabel('Epoch') plt.ylabel('Accuracy') plt.grid() plt.legend() plt.show() def build_model(inputs, outputs, summary=False): model = models.Sequential() model.add(layers.Dense(16, activation='relu', input_shape=(inputs,))) model.add(layers.Dense(16, activation='relu')) model.add(layers.Dense(16, activation='relu')) model.add(layers.Dense(16, activation='relu')) model.add(layers.Dense(outputs, activation='softmax')) model.compile(loss='categorical_crossentropy', optimizer='rmsprop', metrics=['acc']) if summary is True: model.summary() return model def k_fold_cross_validation(data, labels, epochs, batch_size, K=4): results = {'loss': [], 'acc': [], 'val_loss': [], 'val_acc': []} samples = data.shape[0] // K for i in range(K): print("Processing fold {}/{}".format(i+1, K)) # validation data and lables val_data = data[samples*i:samples*(i+1)] val_labels = labels[samples*i:samples*(i+1)] # training data and labels train_data = np.concatenate([data[:samples*i], data[samples*(i+1):]], axis=0) train_labels = np.concatenate([labels[:samples*i], labels[samples*(i+1):]], axis=0) # build model model = build_model(data.shape[1], labels.shape[1]) # train model history = model.fit(train_data, train_labels, validation_data=(val_data, val_labels), epochs=epochs, batch_size=batch_size) # record scores results['loss'].append(history.history['loss']) results['acc'].append(history.history['acc']) results['val_loss'].append(history.history['val_loss']) results['val_acc'].append(history.history['val_acc']) print("") # average results results['loss'] = np.mean(results['loss'], axis=0) results['acc'] = np.mean(results['acc'], axis=0) results['val_loss'] = np.mean(results['val_loss'], axis=0) results['val_acc'] = np.mean(results['val_acc'], axis=0) return results def main(args): assert args.model is None or os.path.splitext(args.model)[1] == '.h5' # process file with open(args.dataset, 'r') as f: train, test = kp.parse(f, normalization=NORMALIZATION, shuffle=True) # format training set train.data = kp.dataset.normalize(train.data, train.mean, train.std) train.labels = utils.to_categorical(train.labels) if args.model is None: # perform K-fold cross-validation results = k_fold_cross_validation(train.data, train.labels, EPOCHS, BATCH_SIZE) # visualize training plot_training(np.arange(EPOCHS), results) else: # build model model = build_model(train.data.shape[1], train.labels.shape[1], summary=True) # train model model.fit(train.data, train.labels, epochs=EPOCHS, batch_size=BATCH_SIZE) # save model model.save(args.model) # save data normalization parameters np.savez_compressed(args.model.replace('.h5', '.npz'), mean=train.mean, std=train.std) if __name__ == '__main__': parser = argparse.ArgumentParser(add_help=False) parser.add_argument('dataset') parser.add_argument('-m', '--model', metavar='model') args = parser.parse_args() main(args) <file_sep>/cameramouse/hand_tracking/__main__.py import argparse from hardware.camera import * from hand_tracking.tracking import * def parse_args(): # construct the argument parse and parse the arguments ap = argparse.ArgumentParser() ap.add_argument("--webcam", action="store_true") ap.add_argument("--realsense", action="store_true") ap.add_argument("-src", "--src", type=int, default=0, help="src number of camera input") args = ap.parse_args() if args.webcam and args.realsense: raise ValueError('Only select one camera type') elif not (args.webcam or args.realsense): raise ValueError('Select a camera type using --webcam or --realsense') return args args = parse_args() camera = None if args.webcam: camera = WebcamCamera(args.src) elif args.realsense: camera = RealSenseCamera() cv2.namedWindow("Tracker Feed") hand_tracker = HandTracker(camera) recalibrated = False while True: # grab frames gray_frame, color_frame = camera.capture_frames() if not hand_tracker.found: # hand is lost if not recalibrated: hand_tracker.handSeg.get_histogram() recalibrated = True else: hand_tracker.global_recognition(color_frame) else: # found the hand lets track it hand_tracker.update_position(color_frame, " ") recalibrated = False cv2.imshow("Tracker Feed", color_frame) ch = 0xFF & cv2.waitKey(1) if ch == 27: cv2.destroyWindow("Tracker Feed") break<file_sep>/mediapipe/mediapipe/calculators/util/gesture_detection_calculator.cc // Copyright 2019 The MediaPipe Authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include <memory> #include "mediapipe/framework/calculator_framework.h" #include "mediapipe/framework/formats/detection.pb.h" #include "mediapipe/framework/formats/landmark.pb.h" #include "mediapipe/framework/formats/location_data.pb.h" #include "mediapipe/framework/port/ret_check.h" #include <iostream> namespace mediapipe { namespace { constexpr char kNormalizedLandmarksTag[] = "LANDMARKS"; constexpr char kGestureTag[] = "GESTURE"; // point1: (x1, y1) point2(x2, y2) double distance(double x1, double y1, double x2, double y2) { return sqrt(pow(x1 - x2, 2) + pow(y1 - y2, 2)); } // line1: starts from (x1, y1), ends at (x2, y2) // line2: starts from (x3, y3), ends at (x4, y4) double angle_cos(double x1, double y1, double x2, double y2, double x3, double y3, double x4, double y4) { double vector1x = x2 - x1; double vector1y = y2 - y1; double vector2x = x4 - x3; double vector2y = y4 - y3; double vector1_length = distance(x1, y1, x2, y2); double vector2_length = distance(x3, y3, x4, y4); return (vector1x * vector2x + vector1y * vector2y) / (vector1_length * vector2_length); } } // namespace class GestureDetectionCalculator : public CalculatorBase { public: static ::mediapipe::Status GetContract(CalculatorContract* cc); ::mediapipe::Status Open(CalculatorContext* cc) override; ::mediapipe::Status Process(CalculatorContext* cc) override; }; REGISTER_CALCULATOR(GestureDetectionCalculator); ::mediapipe::Status GestureDetectionCalculator::GetContract( CalculatorContract* cc) { RET_CHECK(cc->Inputs().HasTag(kNormalizedLandmarksTag)); RET_CHECK(cc->Outputs().HasTag(kGestureTag)); // TODO: Also support converting Landmark to Detection. cc->Inputs().Tag(kNormalizedLandmarksTag).Set<NormalizedLandmarkList>(); cc->Outputs().Tag(kGestureTag).Set<int>(); return ::mediapipe::OkStatus(); } ::mediapipe::Status GestureDetectionCalculator::Open( CalculatorContext* cc) { cc->SetOffset(TimestampDiff(0)); return ::mediapipe::OkStatus(); } ::mediapipe::Status GestureDetectionCalculator::Process( CalculatorContext* cc) { const auto& landmarks = cc->Inputs().Tag(kNormalizedLandmarksTag).Get<NormalizedLandmarkList>(); RET_CHECK_GT(landmarks.landmark_size(), 0) << "Input landmark vector is empty."; // 0: wrist // 4: thumb // 8: index finger // 12: middle finger // 16: ring finger // 20: little finger double indexTipWristDistance = distance(landmarks.landmark(0).x(), landmarks.landmark(0).y(), landmarks.landmark(8).x(), landmarks.landmark(8).y()); double indexBottomWristDistance = distance(landmarks.landmark(0).x(), landmarks.landmark(0).y(), landmarks.landmark(5).x(), landmarks.landmark(5).y()); double middleTipWristDistance = distance(landmarks.landmark(0).x(), landmarks.landmark(0).y(), landmarks.landmark(12).x(), landmarks.landmark(12).y()); double middleBottomWristDistance = distance(landmarks.landmark(0).x(), landmarks.landmark(0).y(), landmarks.landmark(9).x(), landmarks.landmark(9).y()); double ringTipWristDistance = distance(landmarks.landmark(0).x(), landmarks.landmark(0).y(), landmarks.landmark(16).x(), landmarks.landmark(16).y()); double ringBottomWristDistance = distance(landmarks.landmark(0).x(), landmarks.landmark(0).y(), landmarks.landmark(13).x(), landmarks.landmark(13).y()); double littleTipWristDistance = distance(landmarks.landmark(0).x(), landmarks.landmark(0).y(), landmarks.landmark(20).x(), landmarks.landmark(20).y()); double littleBottomWristDistance = distance(landmarks.landmark(0).x(), landmarks.landmark(0).y(), landmarks.landmark(17).x(), landmarks.landmark(17).y()); double thumbAngleCos = angle_cos(landmarks.landmark(2).x(), landmarks.landmark(2).y(), landmarks.landmark(5).x(), landmarks.landmark(5).y(), landmarks.landmark(2).x(), landmarks.landmark(2).y(), landmarks.landmark(4).x(), landmarks.landmark(4).y()); double thumbTipWristDistance = distance(landmarks.landmark(0).x(), landmarks.landmark(0).y(), landmarks.landmark(4).x(), landmarks.landmark(4).y()); double thumbBottomWristDistance = distance(landmarks.landmark(0).x(), landmarks.landmark(0).y(), landmarks.landmark(2).x(), landmarks.landmark(2).y()); int fingers = 0; if (indexTipWristDistance / indexBottomWristDistance > 1.5) { fingers++; } if (middleTipWristDistance / middleBottomWristDistance > 1.5) { fingers++; } if (ringTipWristDistance / ringBottomWristDistance > 1.5) { fingers++; } if (littleTipWristDistance / littleBottomWristDistance > 1.5) { fingers++; } if (thumbTipWristDistance / thumbBottomWristDistance > 1.5) { fingers++; } if (thumbAngleCos < 0.3) { fingers *= -1; } int* i = new int; *i = fingers; cc->Outputs().Tag(kGestureTag).Add(i, cc->InputTimestamp()); return ::mediapipe::OkStatus(); } } // namespace mediapipe <file_sep>/cameramouse/hardware/camera.py """ Author: <NAME> Title: Camera Objects to allow for testing of multiple cameras Date Created: 28 Nov 2018 """ import numpy as np import cv2 import pyrealsense2 as rs class CameraObject(): """ Camera object to read frames and process them to get points to track """ def __init__(self): pass def capture_color_frame(self): pass def capture_gray_frame(self): img = self.capture_color_frame() return cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) def capture_frames(self): img = self.capture_color_frame() return (cv2.cvtColor(img, cv2.COLOR_BGR2GRAY), img) class WebcamCamera(CameraObject): def __init__(self, src): super().__init__() self.cam = cv2.VideoCapture(src) frame = self.capture_color_frame() self.width, self.height, _ = frame.shape self.im_shape = (self.width, self.height) print("[DEBUG] Image Resolution: Width {}, Height {}".format(self.width, self.height)) print("[DEBUG] Initialised Webcam") def capture_color_frame(self): ret, frame = self.cam.read() return frame class RealSenseCamera(CameraObject): def __init__(self, color=True, depth=False): super().__init__() self.pipeline = rs.pipeline() self.config = rs.config() if depth: self.config.enable_stream(rs.stream.depth, 1280, 720, rs.format.z16, 30) if color: self.config.enable_stream(rs.stream.color, 1280, 720, rs.format.bgr8, 30) self.pipeline.start(self.config) frame = self.capture_color_frame() self.height, self.width, _ = frame.shape self.im_shape = (self.width, self.height) print("[DEBUG] Image Resolution: Width {}, Height {}".format(self.width, self.height)) print("[DEBUG] Initialised Realsense") def capture_color_frame(self): frames = self.pipeline.wait_for_frames() color_frame = frames.get_color_frame() color_image = np.asanyarray(color_frame.get_data()) return color_image <file_sep>/cameramouse/gesture_recognition/gestures.py """Parent Classes for Gesture Recognition and Gesture enum""" from enum import Enum class Gestures(Enum): null = 0 click = 1 double_click = 2 right_click = 3 drag = 4 out_of_range = 5 class GestureRecognition(): def __init__(self): self.gesture = Gestures.null self.i = 0 print("[DEBUG] Empty Gesture Input Initialized") def update(self): pass<file_sep>/mediapipe/mediapipe/framework/udp.cc #include <unistd.h> #include <string.h> #include <stdexcept> #include "mediapipe/framework/udp.h" namespace mediapipe { namespace udp { // =============================== CLIENT =================================== client::client(const std::string& addr, int port) : f_port(port), f_addr(addr) { char decimal_port[16]; struct addrinfo hints; int ret_val; snprintf(decimal_port, sizeof(decimal_port), "%d", f_port); memset(&hints, 0, sizeof(hints)); hints.ai_family = AF_UNSPEC; hints.ai_socktype = SOCK_DGRAM; hints.ai_protocol = IPPROTO_UDP; ret_val = getaddrinfo(addr.c_str(), decimal_port, &hints, &f_addrinfo); if(ret_val != 0 || f_addrinfo == NULL) { throw std::runtime_error(("invalid address or port: \"" + addr + ":" + decimal_port + "\"").c_str()); } f_socket = socket(f_addrinfo->ai_family, SOCK_DGRAM | SOCK_CLOEXEC, IPPROTO_UDP); if(f_socket == -1) { freeaddrinfo(f_addrinfo); throw std::runtime_error(("could not create socket for: \"" + addr + ":" + decimal_port + "\"").c_str()); } } client::~client() { freeaddrinfo(f_addrinfo); close(f_socket); } int client::get_socket() const { return(f_socket); } int client::get_port() const { return(f_port); } std::string client::get_addr() const { return(f_addr); } int client::send(const char *msg, size_t size) { return(sendto(f_socket, msg, size, 0, f_addrinfo->ai_addr, f_addrinfo->ai_addrlen)); } // =============================== SERVER =================================== server::server(const std::string& addr, int port) : f_port(port), f_addr(addr) { char decimal_port[16]; struct addrinfo hints; int ret_val; snprintf(decimal_port, sizeof(decimal_port), "%d", f_port); decimal_port[sizeof(decimal_port) / sizeof(decimal_port[0] - 1)] = '\0'; memset(&hints, 0, sizeof(hints)); hints.ai_family = AF_UNSPEC; hints.ai_socktype = SOCK_DGRAM; hints.ai_protocol = IPPROTO_UDP; ret_val = getaddrinfo(addr.c_str(), decimal_port, &hints, &f_addrinfo); if(ret_val != 0 || f_addrinfo == NULL) { throw std::runtime_error(("invalid address or port for UDP socket: \"" + addr + ":" + decimal_port + "\"").c_str()); } f_socket = socket(f_addrinfo->ai_family, SOCK_DGRAM | SOCK_CLOEXEC, IPPROTO_UDP); if(f_socket == -1) { freeaddrinfo(f_addrinfo); throw std::runtime_error(("could not create UDP socket for: \"" + addr + ":" + decimal_port + "\"").c_str()); } ret_val = bind(f_socket, f_addrinfo->ai_addr, f_addrinfo->ai_addrlen); if(ret_val != 0) { freeaddrinfo(f_addrinfo); close(f_socket); throw std::runtime_error(("could not bind UDP socket with: \"" + addr + ":" + decimal_port + "\"").c_str()); } } server::~server() { freeaddrinfo(f_addrinfo); close(f_socket); } int server::get_socket() const { return(f_socket); } int server::get_port() const { return(f_port); } std::string server::get_addr() const { return(f_addr); } int server::recv(char *msg, size_t max_size) { return(::recv(f_socket, msg, max_size, 0)); } int server::timed_recv(char *msg, size_t max_size, int max_wait_ms) { fd_set s; FD_ZERO(&s); FD_SET(f_socket, &s); int ret_val; struct timeval timeout; timeout.tv_sec = max_wait_ms / 1000; timeout.tv_usec = (max_wait_ms % 1000) * 1000; ret_val = select(f_socket + 1, &s, &s, &s, &timeout); if(ret_val == -1) { return(-1); } else if(ret_val > 0) { return(::recv(f_socket, msg, max_size, 0)); } else { errno = EAGAIN; return(-1); } } } }
fb64f2d4765184af9da8e1d7d43c23d4303cf571
[ "CMake", "Markdown", "Python", "C++", "Shell" ]
45
Python
fhuzero/assistive-mouse-capstone
2438e0c3d473b4b825f13186fc47403915667eef
a5dabcf8e3342c0a66fe483d2f98a7ed2cee4840
refs/heads/main
<file_sep># MvvmNewsApp ## Technoloies In The Project ![#000000](https://via.placeholder.com/15/000000/000000?text=+) MVVM architecture ![#000000](https://via.placeholder.com/15/000000/000000?text=+) Retrofit ![#000000](https://via.placeholder.com/15/000000/000000?text=+) Kotlin Coroutine ![#000000](https://via.placeholder.com/15/000000/000000?text=+) ViewModel - Livedata ![#000000](https://via.placeholder.com/15/000000/000000?text=+) Room ![#000000](https://via.placeholder.com/15/000000/000000?text=+) Navigation ![#000000](https://via.placeholder.com/15/000000/000000?text=+) ViewBinding ![#000000](https://via.placeholder.com/15/000000/000000?text=+) Recyclerview ![#000000](https://via.placeholder.com/15/000000/000000?text=+) Fragments ![#000000](https://via.placeholder.com/15/000000/000000?text=+) Glide ## Application Flow ![NewsApp](https://user-images.githubusercontent.com/52356960/136936993-b4846ce7-6dd7-4dcb-acf0-ee8c94b2cbca.gif)) <file_sep>package com.androiddevs.mvvmnewsapp import android.app.Application class NewsApplication:Application()
8979faf1e9d1e608cee302c6284edfd707578567
[ "Markdown", "Kotlin" ]
2
Markdown
FurkanAdemoglu/MvvmNewsApp
bff46145f0d6be00dcb797f8991f08cd9597dcca
d37dd18b7c78a228e8320dd3ec9f811f6156e192
refs/heads/master
<file_sep>var links = document.querySelectorAll("nav > a"); // > especifica que el siguiente elemento es su hijo.s console.log(links); /*Funcion Nominada (no tiene nombre)*/ links.forEach(function(link){ console.log("El argumento 'link' contiene:"); console.log(link); link.onclick = function(evento){ evento.preventDefault(); console.log(evento); var rta = confirm("¿Esta seguro que desea abandonar el sitio?"); if( rta ) { //ir a la pagina correspondiente console.log("Ahora deberia ir a:") console.log(evento.target.href) window.location.href = evento.target.href //ir a donde iria el elemento clickeado } else { alert("gracias por quedarse"); } } }) /*Funcion Nominada (tiene nombre) function clickEvent(link){ console.log("en el argumento 'link' hay:");} console.log(link) }*/
c2646c4452894df520f5ec65914e1692fb0b4839
[ "JavaScript" ]
1
JavaScript
leonelgwetzel/pwfe-m1-08
be8101d1e7f0c19374768206d0b1e35de94c3259
791cad242f8578371c4fb71cb96d1beaacd1c496
refs/heads/master
<repo_name>jcam/anypoint-deploy-action<file_sep>/README.md # Anypoint Build/Deploy Container Action <file_sep>/entrypoint.sh #!/bin/bash -l yell() { echo "$0: $*" >&2; } die() { yell "$*"; exit 111; } try() { "$@" || die "cannot $*"; } if [[ "${ENVIRONMENT}" = "dev" ]]; then ANYPOINT_ENVIRONMENT="Sandbox" TARGET_FABRIC="mule-dev-us-west-2" elif [[ "${ENVIRONMENT}" = "qa" ]]; then ANYPOINT_ENVIRONMENT="QA" TARGET_FABRIC="mule-qa-us-east-1" elif [[ "${ENVIRONMENT}" = "prod" ]]; then ANYPOINT_ENVIRONMENT="Production" TARGET_FABRIC="mule-prod-us-east-1" fi GIT_REPO=${GITHUB_REPOSITORY##*/} ANYPOINT_LAYER=${GIT_REPO%%-*} ANYPOINT_LAYER=${ANYPOINT_LAYER//sys/System} ANYPOINT_LAYER=${ANYPOINT_LAYER//proc/Process} ANYPOINT_LAYER=${ANYPOINT_LAYER//exp/Experience} APP_NAME=${GIT_REPO##*api-} ANYPOINT_LAYER_LOWERCASE=$(echo $ANYPOINT_LAYER | tr '[:upper:]' '[:lower:]') ANYPOINT_ASSET_ID=$APP_NAME-$ANYPOINT_LAYER_LOWERCASE-api GIT_SHORTSHA=${GITHUB_SHA::8} #========================================================== # The branch name is added to the APP name if not # the master branch. # if [[ -z "$API_INSTANCE_LABEL" ]]; then API_INSTANCE_LABEL=${GITHUB_REF##*/} API_INSTANCE_LABEL=${API_INSTANCE_LABEL##*-} if [[ $API_INSTANCE_LABEL != "master" ]]; then APP_NAME_SUFFIX=-$API_INSTANCE_LABEL fi fi ANYPOINT_APPLICATION_NAME=$GIT_REPO-$API_RELEASE$APP_NAME_SUFFIX ANYPOINT_APPLICATION_PATH=$APP_NAME$APP_NAME_SUFFIX/$API_RELEASE #========================================================== # Build the JAR using Maven # Production should only deploy an existing, tested build # if [[ "$ENVIRONMENT" = "prod" ]]; then mvn -B -s/m2_settings.xml exists:remote -Dexists.failIfNotExists=true -Drevision=$API_VERSION-R$GIT_SHORTSHA || die "Build not found, deploy to QA first" else mvn -B -s/m2_settings.xml exists:remote deploy -DskipTests -Drevision=$API_VERSION-R$GIT_SHORTSHA || die "Build Failed" fi #========================================================== # Deploy to runtime fabric # mvn_deploy_cmd="mvn -B -s/m2_settings.xml deploy -DmuleDeploy -DskipTests -Drevision=$API_VERSION-R$GIT_SHORTSHA" mvn_deploy_cmd+=" -Dmule.env=$ENVIRONMENT" mvn_deploy_cmd+=" -Ddeployment.environment=$ANYPOINT_ENVIRONMENT" mvn_deploy_cmd+=" -Ddeployment.target=$TARGET_FABRIC" mvn_deploy_cmd+=" -Dapp.name=${ANYPOINT_APPLICATION_NAME::42}" mvn_deploy_cmd+=" -Dapp.path=${ANYPOINT_APPLICATION_PATH}" mvn_deploy_cmd+=" -Dhost.external=api.${DOMAIN}" mvn_deploy_cmd+=" -Dhost.internal=api.internal.${DOMAIN}" mvn_deploy_cmd+=" -Danypoint.platform.config.analytics.agent.enabled=true" mvn_deploy_cmd+=" -Danypoint.platform.visualizer.layer=$ANYPOINT_LAYER" if [[ ! -z "$API_ID" ]]; then mvn_deploy_cmd+=" -DapiId=$API_ID" fi if [[ "$ANYPOINT_ENVIRONMENT" = "Production" ]]; then mvn_deploy_cmd+=" -Ddeployment.replicas=2" else mvn_deploy_cmd+=" -Ddeployment.skipVerification=true" fi eval $mvn_deploy_cmd <file_sep>/Dockerfile FROM openjdk:8-alpine RUN apk add --no-cache bash git maven COPY LICENSE README.md m2_settings.xml / COPY entrypoint.sh /entrypoint.sh ENTRYPOINT ["/entrypoint.sh"]
847ebafe792783fb05c31361c0dcc4c56a338482
[ "Markdown", "Dockerfile", "Shell" ]
3
Markdown
jcam/anypoint-deploy-action
614efdcf7179f98e3371119814d81541856b3998
afa388916b6770fab194ae7e8ab2800a6174f6d6
refs/heads/master
<file_sep>package com.example.moneymanager; import androidx.annotation.NonNull; import androidx.appcompat.app.AppCompatActivity; import android.app.ProgressDialog; import android.content.Intent; import android.os.Bundle; import android.text.Layout; import android.text.TextUtils; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.ProgressBar; import android.widget.RelativeLayout; import android.widget.TextView; import android.widget.Toast; import com.google.android.gms.tasks.OnCompleteListener; import com.google.android.gms.tasks.Task; import com.google.firebase.auth.AuthResult; import com.google.firebase.auth.FirebaseAuth; public class RegistrationActivity extends AppCompatActivity { private EditText etEmail; private EditText etPass; private Button btnReg; private TextView etSignIn; private ProgressDialog progressDialog; // Firebase private FirebaseAuth firebaseAuth; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_registration); initialize(); registrationHandler(); } private void registrationHandler() { btnReg.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String email = etEmail.getText().toString().trim(); String password = etPass.getText().toString().trim(); if (TextUtils.isEmpty(email)){ etEmail.setError("Email jest wymagany!"); return; } if (TextUtils.isEmpty(password)){ etPass.setError("Hasło jest wymagane!"); return; } progressDialog.setMessage("Przetwarzanie..."); // Create user and add to database firebaseAuth.createUserWithEmailAndPassword(email, password).addOnCompleteListener(new OnCompleteListener<AuthResult>() { @Override public void onComplete(@NonNull Task<AuthResult> task) { if (task.isSuccessful()){ progressDialog.dismiss(); Toast.makeText(getApplicationContext(), "Zarejestrowano pomyślnie!", Toast.LENGTH_SHORT).show(); // Redirect to home activity startActivity(new Intent(getApplicationContext(), HomeActivity.class)); } else { progressDialog.dismiss(); Toast.makeText(getApplicationContext(), "Coś poszło nie tak :/", Toast.LENGTH_SHORT).show(); } } }); } }); // Already signIn text view handler etSignIn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { startActivity(new Intent(getApplicationContext(), MainActivity.class)); } }); } // Connect variables to layout private void initialize(){ etEmail = findViewById(R.id.et_email_reg); etPass = findViewById(R.id.et_password_reg); btnReg = findViewById(R.id.btn_reg); etSignIn = findViewById(R.id.tv_login); progressDialog = new ProgressDialog(this); firebaseAuth = FirebaseAuth.getInstance(); } } <file_sep># Money Manager Money manager is simple mobile app to manage your incomes and expenses. <img align="right" src="https://github.com/pieetrus/Money-Manager/blob/master/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png"> ## Technologies - Android - Google Firebase ## Features/highlights - create accounts - login to account - add/remove/update incomes - add/remove/update expenses ## Usage example ![2](https://github.com/pieetrus/Money-Manager/blob/master/readmefiles/presentation.gif) ## Release History * 0.1.0 * First version * 0.0.1 * Work in progress ## Meta <NAME> – [@Github](https://github.com/pieetrus) – <EMAIL> <file_sep>package com.example.moneymanager; import android.app.AlertDialog; import android.os.Bundle; import androidx.annotation.NonNull; import androidx.fragment.app.Fragment; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; import com.example.moneymanager.Model.Data; import com.firebase.ui.database.FirebaseRecyclerAdapter; 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 java.text.DateFormat; import java.util.Date; /** * A simple {@link Fragment} subclass. */ public class IncomeFragment extends Fragment { private View view; private DatabaseReference incomeDatabase; // Recycler view private RecyclerView recyclerView; private TextView tvIncomeTotal; // Update private EditText etUpdAmount; private EditText etUpdType; private EditText etUpdNote; // Data item private String type; private String note; private int amount; private String post_key; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment view = inflater.inflate(R.layout.fragment_income, container, false); incomeRecyclerViewHandler(); return view; } @Override public void onStart() { super.onStart(); FirebaseRecyclerAdapter<Data, MyViewHolder> adapter = new FirebaseRecyclerAdapter<Data, MyViewHolder>( Data.class, R.layout.income_recycler_data, MyViewHolder.class, incomeDatabase ) { @Override protected void populateViewHolder(MyViewHolder myViewHolder, final Data data, final int i) { myViewHolder.setType(data.getType()); myViewHolder.setNote(data.getNote()); myViewHolder.setDate(data.getDate()); myViewHolder.setAmount(data.getAmount()); myViewHolder.myView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { post_key = getRef(i).getKey(); type = data.getType(); note = data.getNote(); amount = data.getAmount(); updateDataItem(); } }); } }; recyclerView.setAdapter(adapter); } public static class MyViewHolder extends RecyclerView.ViewHolder{ View myView; public MyViewHolder(View itemView) { super(itemView); myView = itemView; } private void setType(String type){ TextView tvType = myView.findViewById(R.id.tv_type_income); tvType.setText(type); } private void setNote(String note){ TextView tvNote = myView.findViewById(R.id.tv_note_income); tvNote.setText(note); } private void setDate(String date){ TextView tvDate = myView.findViewById(R.id.tv_date_income); tvDate.setText(date); } private void setAmount(int amount){ TextView tvAmount = myView.findViewById(R.id.tv_amount_income); tvAmount.setText(amount + " zł"); } } private void incomeRecyclerViewHandler(){ // Firebase database FirebaseAuth firebaseAuth = FirebaseAuth.getInstance(); FirebaseUser firebaseUser = firebaseAuth.getCurrentUser(); String id = firebaseUser.getUid(); incomeDatabase = FirebaseDatabase.getInstance().getReference().child("IncomeData").child(id); recyclerView = view.findViewById(R.id.recycle_income); tvIncomeTotal = view.findViewById(R.id.tv_income_total); LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity()); layoutManager.setReverseLayout(true); layoutManager.setStackFromEnd(true); recyclerView.setHasFixedSize(true); recyclerView.setLayoutManager(layoutManager); incomeDatabase.addValueEventListener(new ValueEventListener() { @Override public void onDataChange(@NonNull DataSnapshot dataSnapshot) { int totalValue = 0; for (DataSnapshot snapshot: dataSnapshot.getChildren()){ Data data = snapshot.getValue(Data.class); totalValue += data.getAmount(); tvIncomeTotal.setText(totalValue + " zł"); } } @Override public void onCancelled(@NonNull DatabaseError databaseError) { } }); } private void updateDataItem() { AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(getActivity()); LayoutInflater inflater = LayoutInflater.from(getActivity()); View view = inflater.inflate(R.layout.update_data_item, null); dialogBuilder.setView(view); etUpdAmount = view.findViewById(R.id.et_upd_amount); etUpdNote = view.findViewById(R.id.et_upd_note); etUpdType = view.findViewById(R.id.et_upd_type); Button btnUpdDelete = view.findViewById(R.id.btn_upd_delete); Button btnUpdUpdate = view.findViewById(R.id.btn_upd_update); // Set data etUpdType.setText(type); etUpdNote.setText(note); etUpdAmount.setText(String.valueOf(amount)); etUpdType.setSelection(type.length()); etUpdNote.setSelection(note.length()); etUpdAmount.setSelection(String.valueOf(amount).length()); final AlertDialog dialog = dialogBuilder.create(); btnUpdUpdate.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { type = etUpdType.getText().toString().trim(); note = etUpdNote.getText().toString().trim(); amount = Integer.parseInt(etUpdAmount.getText().toString().trim()); String date = DateFormat.getDateInstance().format(new Date()); Data data = new Data(post_key, amount, type, note, date); incomeDatabase.child(post_key).setValue(data); dialog.dismiss(); } }); btnUpdDelete.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { incomeDatabase.child(post_key).removeValue(); dialog.dismiss(); } }); dialog.show(); } }
3aa888e9127578f8b6b030e7b43af786366028b5
[ "Markdown", "Java" ]
3
Java
pieetrus/Money-Manager
cc1ee07b50c977e38f9c95f71d8bcac75a22e0d1
e0dfb6923c674d18d2b82dffcea442ea86ed736a
refs/heads/master
<repo_name>caslanbigeyes/LLF_IMG<file_sep>/index.js function myPromise(exector) { let _this = this; _this.status = 'pending' _this.value = undefined _this.reason = undefined _this.onResolveCallbacks = [] _this.onRejectedCallbacks = [] function resolve(value) { if (_this.status === 'pending') { _this.status = 'resolved' _this.value = value _this.onResolveCallbacks.push(function () { onFulfilled(_this.value) }) _this.onResolveCallbacks.forEach(function (fn) { fn() }) } } function reject(reason) { if (_this.status === 'pending') { _this.status = 'rejected' _this.reason = reason _this.onRejectedCallbacks.push(function () { onRejected(_this.reason) }) _this.onRejectedCallbacks.forEach(function (fn) { fn() }) } } try { exector(resolve, reject) //将这两个方法传到执行器函数中 } catch (e) { reject(e) } } Promise.prototype.then = function (onFulfilled, onRejected) { let _this = this; if (_this.status === 'resolved') { onFulfilled(_this.value) } if (_this.status === 'rejected') { onRejected(_this.reason) } } module.exports = Promise <file_sep>/ES6_yuan/1.异步解决方案/index.js function getPermission(useName,callback){ setTimeout(()=>{ var res = Math.random() if(res<0.1){ callback('error',null) //网络中断 }else if(res>0.5){ callback(null,false) //没有权限 }else{ callback(null,true) //有权限 } },1000) } //文章 getPermission('LLF',function(err,result){ if(err){ //提示网络中断 } else if(result){ //有权限 }else{ //没有权限 } }) //留言 getPermission('TL',function(err,result){ if(err){ //提示网络中断 } else if(result){ //有权限 }else{ //没有权限 } }) // node回调模式 // 1.所有回调函数不能作为属性出现 // 2.所有回调函数必须作为函数最后的参数 // 3.所有回调函数必须有两个参数,第一个参数表示错误,第二个参数表示结果
76ffded0c2f24f4060072610e391c376a68f7922
[ "JavaScript" ]
2
JavaScript
caslanbigeyes/LLF_IMG
b2cd2a45afe90520d4d7ac46fe11b0e2f38dd874
ec7162f8e622baedcc8ebe6c04b917c43ccf7056
refs/heads/master
<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace XNull { class AI { public const char AIFIG = '0'; Field Battlefield; public AI(ref Field field) { this.Battlefield = field; } public void SetField(Inputer Inputer) { int coordinate = GetRandomCoordinate(); Battlefield.getSquare(coordinate).State = AIFIG;// } public int GetRandomCoordinate() { Random Random = new Random(); int minValue = 1; int maxValue = 4; int coordinate = 0; bool key = true; while (key) { int coordinateX = Random.Next(minValue, maxValue); int coordinateY = Random.Next(minValue, maxValue); coordinate = coordinateX * 10 + coordinateY; Console.WriteLine(coordinate); int state = Battlefield.getSquare(coordinate).State;// if (state != ' ') { coordinate = 0; key = true; } else { key = false; } } return coordinate; } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace XNull { public class Square { public char State { get; set; } public int Coordinate { get; set; } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace XNull { public class Field { public const char EMPTY = ' '; public const int DEMENSION = 3; public Square[,] arrayOfSquare { get; private set; } public Field() { this.arrayOfSquare = new Square[DEMENSION, DEMENSION]; for (int i = 0; i < DEMENSION; i++) { for (int j = 0; j < DEMENSION; j++) { this.arrayOfSquare[i, j] = new Square(); this.arrayOfSquare[i, j].State = EMPTY; this.arrayOfSquare[i, j].Coordinate = (i + 1) * 10 + j + 1; } } } public Square getSquare(int position) { int i = position / 10; int j = position % 10; return arrayOfSquare[i-1, j-1]; } public void isGameOver() { if (arrayOfSquare[0, 0].State.Equals(arrayOfSquare[1, 1]) && arrayOfSquare[0, 0].State.Equals(arrayOfSquare[2, 2])) { } else if (arrayOfSquare[2, 0].State.Equals(arrayOfSquare[1, 1]) && arrayOfSquare[0, 2].State.Equals(arrayOfSquare[2, 0])) { } else if (arrayOfSquare[0, 0].State.Equals(arrayOfSquare[0, 1]) && arrayOfSquare[0, 0].State.Equals(arrayOfSquare[0, 2])) { } else if (arrayOfSquare[0, 0].State.Equals(arrayOfSquare[1, 0]) && arrayOfSquare[0, 0].State.Equals(arrayOfSquare[2, 0])) { } else if (arrayOfSquare[1, 0].State.Equals(arrayOfSquare[1, 1]) && arrayOfSquare[1, 1].State.Equals(arrayOfSquare[1, 2])) { } } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace XNull { class Inputer { public int GetData() { Console.WriteLine("Input startPosition (11 - 33): "); string input = Console.ReadLine(); return ParseToPositionX(input)*10 + ParseToPositionY(input); } public int ParseToPositionX(string input) { int position= Int32.Parse(input); int positionX = position / 10; if (positionX > 3) throw new FormatException("Wrong positionX"); return positionX; } public int ParseToPositionY(string input) { int position = Int32.Parse(input); int positionY = position % 10; if (positionY > 3) throw new FormatException("Wrong positionY"); return positionY; } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace XNull { class Outputer { public void PrintField(Field field) { for (int i = 0; i < field.arrayOfSquare.GetLength(0); i++) { for (int j = 0; j < field.arrayOfSquare.GetLength(0); j++) { Console.Write("{0,3}|", field.arrayOfSquare[i,j].State); } Console.WriteLine(""); } } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace XNull { class Program { static void Main(string[] args) { Inputer inputer = new Inputer(); Outputer outputer = new Outputer(); Field field = new Field(); outputer.PrintField(field); Player player = new Player(ref field); AI ai = new AI(ref field); int count = 0; while (true) { count++; player.SetField(inputer); outputer.PrintField(field); count++; if (count < 9) { Console.WriteLine("Computer turn: "); ai.SetField(inputer); outputer.PrintField(field); } else { Console.WriteLine("It's a draw. "); } } } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace XNull { class Player { public const char PLAYERFIG = 'x'; Field Battlefield; public Player(ref Field field) { this.Battlefield = field; } public void SetField(Inputer Inputer) { bool key = true; while (key) { int coordinate = Inputer.GetData(); if (Battlefield.getSquare(coordinate).State == ' ') { Battlefield.getSquare(coordinate).State = PLAYERFIG; key = false; } else { Console.WriteLine("This square is occupied. Enter correct square. "); key = true; } } } } }
c3bec21063cfa964f8034a1c1d8b6bab3143be96
[ "C#" ]
7
C#
AntonRedzkin/main
58cc29aff3b87ae20dc9b163a1ad9139f8a5d7dd
d8b65a8fa20a7cef1adb4deca1066fe2723ea6d4
refs/heads/master
<repo_name>VictoryEddie/Launder_Mart<file_sep>/app/src/main/java/com/example/laundermart/helper.kt package com.example.laundermart import android.content.Context import android.widget.Toast fun Context.toast(message: String) = Toast.makeText(this,message, Toast.LENGTH_SHORT).show()<file_sep>/app/src/main/java/com/example/laundermart/Registering.kt package com.example.laundermart import android.content.Intent import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.util.Patterns import android.widget.CheckBox import android.widget.EditText import android.widget.Toast import com.google.firebase.auth.FirebaseAuth import kotlinx.android.synthetic.main.activity_registering.* class Registering : AppCompatActivity() { private lateinit var mAuth: FirebaseAuth private lateinit var termsAccept: CheckBox private lateinit var email: EditText private lateinit var password: EditText private lateinit var names: EditText override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_registering) mAuth = FirebaseAuth.getInstance() supportActionBar?.hide() textView5.setOnClickListener { val intent = Intent(this@Registering, Loginpage::class.java) startActivity(intent) } sign_in_button.setOnClickListener { termsAccept = findViewById(R.id.registercheckBox) val email = registermail.text.toString() val password = <PASSWORD>.<PASSWORD>() val name = registername.text.toString() if (email.isEmpty() && password.isEmpty() && name.isEmpty()) { Toast.makeText(this, "Fill All The Blanks Please", Toast.LENGTH_SHORT).show() return@setOnClickListener } if (email.isEmpty()) { registermail.error = "Valid Email Required" registermail.requestFocus() return@setOnClickListener } if (!Patterns.EMAIL_ADDRESS.matcher(email).matches()) { registermail.error = "Valid Email Required" registermail.requestFocus() return@setOnClickListener } if (password.isEmpty() || password.length < 6) { registerpassword.error = "Six or more characters Required" registerpassword.requestFocus() return@setOnClickListener } if (name.isEmpty() || name.length < 3) { registername.error = "Valid Name Required" registername.requestFocus() return@setOnClickListener } registerUser() // checkLoggedInState() } } private fun registerUser() { val email = registermail.text.toString() val password = <PASSWORD>password.text.toString() mAuth.createUserWithEmailAndPassword(email, password) .addOnCompleteListener(this) { task -> if (task.isSuccessful) { Toast.makeText(this, "Registration Successful!!", Toast.LENGTH_SHORT).show() val intent = Intent(this@Registering, Locator::class.java).apply { flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK } startActivity(intent) } else { task.exception?.message?.let { toast(it) } } } } // private fun checkLoggedInState() { // if (mAuth.currentUser == null) { // Toast.makeText(this, "YOU ARE NOT LOOGED IN", Toast.LENGTH_LONG).show() // val intent = Intent(this, Loginpage::class.java) // startActivity(intent) // } else { // Toast.makeText(this, "Welcome Back!!", Toast.LENGTH_LONG).show() // val intent = Intent(this, Locator::class.java) // startActivity(intent) // } // } override fun onBackPressed() { super.onBackPressed() finishAffinity() } } <file_sep>/app/src/main/java/com/example/laundermart/Loginpage.kt package com.example.laundermart import android.content.Intent import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.util.Patterns import android.widget.CheckBox import android.widget.EditText import android.widget.Toast import androidx.core.content.ContextCompat import androidx.core.content.ContextCompat.startActivity import com.google.firebase.auth.FirebaseAuth import kotlinx.android.synthetic.main.activity_loginpage.* import kotlinx.android.synthetic.main.activity_registering.* class Loginpage : AppCompatActivity() { private lateinit var mAuth: FirebaseAuth private lateinit var rememberme: CheckBox private lateinit var email: EditText private lateinit var password: EditText override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_loginpage) mAuth = FirebaseAuth.getInstance() supportActionBar?.hide() sign_up.setOnClickListener { val intent = Intent(this@Loginpage, Registering::class.java) startActivity(intent) } loginbutton.setOnClickListener { // rememberme = findViewById(R.id.loginbutton) val email = loginemail.text.toString() val password = loginpassword.text.toString() if (email.isEmpty() && password.isEmpty()) { Toast.makeText(this, "Fill All The Blanks Please", Toast.LENGTH_SHORT).show() return@setOnClickListener } if (email.isEmpty()) { registermail.error = "Valid Email Required" registermail.requestFocus() return@setOnClickListener } if (!Patterns.EMAIL_ADDRESS.matcher(email).matches()) { registermail.error = "Valid Email Required" registermail.requestFocus() return@setOnClickListener } if (password.isEmpty() || password.length < 6) { registerpassword.error = "Six or more characters Required" registerpassword.requestFocus() return@setOnClickListener } loginUser(email, password) // checkLoggedInState() } } // override fun onStart() { // super.onStart() // checkLoggedInState() // } private fun loginUser(email: String, password: String) { val email = loginemail.text.toString() val password = <PASSWORD>() mAuth.signInWithEmailAndPassword(email, password) .addOnCompleteListener(this) { task -> if (task.isSuccessful) { val intent = Intent(this@Loginpage, Locator::class.java).apply { flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK } startActivity(intent) } else { task.exception?.message?.let { toast(it) } } } } // private fun checkLoggedInState() { // if (mAuth.currentUser == null) { // val intent = Intent(this, Loginpage::class.java) // startActivity(intent) // } else { // Toast.makeText(this, "Welcome Back!!", Toast.LENGTH_LONG).show() // val intent = Intent(this, Locator::class.java) // startActivity(intent) // } // } override fun onBackPressed() { super.onBackPressed() finishAffinity() } } <file_sep>/app/src/main/java/com/example/laundermart/Locator.kt package com.example.laundermart import android.content.Intent import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.view.Menu import android.view.MenuInflater import android.view.MenuItem import android.widget.Toast import com.google.firebase.auth.FirebaseAuth class Locator : AppCompatActivity() { private lateinit var mAuth: FirebaseAuth override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_locator) mAuth = FirebaseAuth.getInstance() //supportActionBar?.hide() } override fun onCreateOptionsMenu(menu: Menu?): Boolean { val inflater: MenuInflater = menuInflater inflater.inflate(R.menu.menus, menu) return true } override fun onOptionsItemSelected(item: MenuItem): Boolean { if (item.itemId == R.id.sign_off) { mAuth.signOut() Toast.makeText(this, "Signing Out", Toast.LENGTH_LONG).show() val intent = Intent(this@Locator, Loginpage::class.java) startActivity(intent) return true } return super.onOptionsItemSelected(item) } override fun onBackPressed() { super.onBackPressed() finishAffinity() } } <file_sep>/settings.gradle include ':app' rootProject.name = "<NAME>"<file_sep>/app/src/main/java/com/example/laundermart/MainActivity.kt package com.example.laundermart import android.content.Intent import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.os.Handler import android.widget.Toast import com.google.firebase.auth.FirebaseAuth class MainActivity : AppCompatActivity() { private lateinit var mAuth: FirebaseAuth override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) supportActionBar?.hide() Handler().postDelayed({ val intent = Intent(this@MainActivity, Loginpage::class.java) startActivity(intent) checkLoggedInState() finish() }, 3500) mAuth = FirebaseAuth.getInstance() // checkLoggedInState() } private fun checkLoggedInState() { if (mAuth.currentUser == null) { Toast.makeText(this, "You Are Not Logged In", Toast.LENGTH_SHORT).show() } else { Toast.makeText(this, "Welcome Back!!", Toast.LENGTH_SHORT).show() val intent = Intent(this, Locator::class.java) startActivity(intent) } } // // override fun onStart() { // super.onStart() // checkLoggedInState() // } }
007eae2c2a6c3c28bca85713a70a9426ba62f24f
[ "Kotlin", "Gradle" ]
6
Kotlin
VictoryEddie/Launder_Mart
9d648ac037a495c3fb7b478409be922622dfba7f
e2b68d58a36401efb859566407b5495263e6ce76
refs/heads/main
<file_sep>var desperates = document.querySelectorAll(".desperate"); // console.log(desperate); desperates.forEach(d => { var slackMessages = d.querySelector(".info-slack-message").textContent; var callByDay = d.querySelector(".info-calls-by-day").textContent; var desperateIndex = d.querySelector(".info-desperate-index"); desperateIndex.textContent = desperateEquation(slackMessages, callByDay); }); function desperateEquation(slackMessages, callByDay){ return slackMessages * callByDay; }<file_sep># desperate-index A basic JS form to calculate the desperate index from a person <file_sep>var person = document.querySelector("#add-person"); person.addEventListener("click", function(event){ event.preventDefault(); // console.log("my god"); var formPerson = document.querySelector("#form-person"); // console.log(formPerson.name.value); var person = getPerson(formPerson); if(!validatePerson(person)) return; addPersonOnTable(person); var errorUl = document.querySelector("#error-msg"); errorUl.textContent = ""; // console.log(person); formPerson.reset(); }); function getPerson(formPerson){ var person = { name: formPerson.name.value, slackMessage: formPerson.slackMessage.value, callsByDay: formPerson.callsByDay.value, desperateIndex: desperateEquation(formPerson.slackMessage.value, formPerson.callsByDay.value) } return person; } function validatePerson(person){ var errors = []; // console.log(person); if(person.name.length == 0) errors.push("Name can't be empty"); if(isNaN(person.slackMessage) || person.slackMessage.length == 0) errors.push("Slack message has invalid number format"); if(isNaN(person.callsByDay) || person.callsByDay.length == 0) errors.push("Calls By Day has invalid number format"); if(errors.length > 0){ showMessageError(errors); return false; } return true; } function showMessageError(errors){ var errorUl = document.querySelector("#error-msg"); errorUl.innerHTML = ""; errors.forEach(error => { var li = document.createElement("li"); li.textContent = error; // console.log(li); // console.log(errorUl); errorUl.appendChild(li); }); } function addPersonOnTable(person){ var personTr = addTrPerson(person); var table = document.querySelector("#table-desperate-index"); table.appendChild(personTr); } function addTrPerson(person){ var personTr = document.createElement("tr"); var nameTd = addTdPerson(person.name, "info-name"); var slackMessageTd = addTdPerson(person.slackMessage, "info-slack-message"); var callsByDayTd = addTdPerson(person.callsByDay, "info-calls-by-day"); var desperateIndexTd = addTdPerson(person.desperateIndex, "info-desperate-index"); personTr.appendChild(nameTd); personTr.appendChild(slackMessageTd); personTr.appendChild(callsByDayTd); personTr.appendChild(desperateIndexTd); return personTr; } function addTdPerson(textContent, cssClass){ var nameTd = document.createElement("td"); nameTd.textContent = textContent; nameTd.classList.add(cssClass); return nameTd; }
dee13b98f106812cc123f21415d0820d5e5a61b2
[ "JavaScript", "Markdown" ]
3
JavaScript
henriquesfreitas/desperate-index-js
14a503126778245599b2df65746f43886a8a1019
a12dc6ec19723717d961f20a594b674d9394a22a
refs/heads/master
<repo_name>tavo20/platziStoreAngular<file_sep>/src/app/admin/components/products/products.component.ts import { Component, OnInit } from '@angular/core'; import { ProductService } from 'src/app/core/services/products/product.service'; @Component({ selector: 'app-products', templateUrl: './products.component.html', styleUrls: ['./products.component.scss'] }) export class ProductsComponent implements OnInit { productos = []; displayedColumns: string[] = ['id', 'Titulo', 'Precio', 'Acciones']; constructor( private productService: ProductService ) { } ngOnInit() { console.log(123); this.fetchProduts(); } fetchProduts() { this.productService.getProductos() .subscribe((productos) => { this.productos = productos; console.log(this.productos); }); } deleteProducto(id: string){ this.productService.deleteProduct(id) .subscribe(() => { console.log('Elimina'); for (let i = 0; i < this.productos.length; i++) { if (this.productos[i].id == id) { this.productos.splice(i, 1); } } }); } } <file_sep>/src/app/product/containers/products/products.container.ts import { Component, OnInit } from '@angular/core'; import {Product} from '../../../product.model'; import { ProductService } from '@core/services/products/product.service'; @Component({ selector: 'app-products', templateUrl: './products.container.html', styleUrls: ['./products.container.scss'] }) // tslint:disable-next-line: component-class-suffix export class ProductsContainer implements OnInit { products: Product[] = []; constructor( private productService: ProductService ) { } ngOnInit() { const x = this.productService.getProductos() .subscribe((productos) => { this.products = (productos); x.unsubscribe(); console.log(productos); }, (err) => {console.error(`error al obtener los productos ${JSON.stringify(err)}`)}); } clickProduct(id: number) { console.log(`product ${id}`); } } <file_sep>/src/app/product/components/product-detail/product-detail.component.ts import { Component, OnInit } from '@angular/core'; import {ActivatedRoute, Params} from '@angular/router'; import { ProductService } from '../../../core/services/products/product.service'; import {Product} from '../../../product.model'; import { switchMap } from 'rxjs/operators'; import { Observable } from 'rxjs'; @Component({ selector: 'app-product-detail', templateUrl: './product-detail.component.html', styleUrls: ['./product-detail.component.scss'] }) export class ProductDetailComponent implements OnInit { producto$: Observable<Product>; constructor( private route: ActivatedRoute, private productService: ProductService, ) { } ngOnInit() { this.producto$ = this.route.params .pipe( switchMap((params: Params) => { return this.productService.getProducto(params.id); }) ); // .subscribe((product) => { // clase 12 profesional // this.producto = product; // console.log(params); // const id = params.id; // this.fetchProduct(id); // }); } // Lo comentamos en la clase 12 del profesional // fetchProduct(id: string) { // this.productService.getProducto(id) // .subscribe((producto) => { // console.log(producto); // this.producto = producto; // }, (err) => {console.error(`errro al obtener la información del producto ${err}`)}); // } createProduct() { const newProduct: Product = { id: '222', title: 'Producto desde angular', image: 'assets/images/pin.png', price: 35000, description: 'Nuevo producto' }; this.productService.createProduct(newProduct) .subscribe(() => { },(err) => {console.error(`error al guardar el producto`)}); } updateProduct(){ const updateProduct: Partial<Product> = { price: 8888888, description: 'Edición Product' }; this.productService.updateProduct('222', updateProduct) .subscribe(() => { },(err) => {console.error(`error al guardar el producto`)}); } deleteProduct() { this.productService.deleteProduct('222') .subscribe(() => { },(err) => {console.error(`èrror al borrar el producto ${err}`)}) } getRandomUsers() { this.productService.getRandomUsers() .subscribe(users => { console.log(users); }, (err) => { console.error(err); }); } getFile() { this.productService.getFile() .subscribe((content) => { console.log(content); }); } // getFileReto() { // var blob = new Blob(["Hello, world!"], {type: "text/plain;charset=utf-8"}); // FileSaver.saveAs(blob, "hello world.txt"); // } } <file_sep>/src/app/contact/components/layou/layou.component.ts import { Component, OnInit, OnDestroy } from '@angular/core'; import { GeneratorService } from './../../../core/services/generator.service'; import { EmployeeData } from './../../../core/models/employee.model'; import { Observable, Subscription } from 'rxjs'; import { tap, } from 'rxjs/operators'; const names = [ 'Gustavo', 'Gissel', 'Dennis', 'Imagine' ]; @Component({ selector: 'app-layou', templateUrl: './layou.component.html', styleUrls: ['./layou.component.scss'] }) export class LayouComponent implements OnInit, OnDestroy { salesList: EmployeeData[] = []; bList: EmployeeData[] = []; value$: Observable<number>; sub$: Subscription; constructor( private generatorService: GeneratorService ) { } ngOnInit() { this.salesList = this.generatorService.generate(names, [10, 20], 10); this.bList = this.generatorService.generate(names, [10, 20], 10); this.value$ = this.generatorService.getData() .pipe( tap(num => console.log(num)) ); // this.sub$ = this.generatorService.getData() // .subscribe((value) => { // this.value = value; // console.log(this.value); // }); } addItem(list: EmployeeData[], label: string) { list.unshift({ label, num: this.generatorService.generateNumber([10, 20]) }); } ngOnDestroy() { // this.sub$.unsubscribe(); } } <file_sep>/src/app/contact/components/list/list.component.ts import { Component, OnInit, Input, EventEmitter, Output, ChangeDetectionStrategy } from '@angular/core'; import { EmployeeData } from './../../../core/models/employee.model' import { from } from 'rxjs'; const fibonacci = (num: number): number => { if (num === 1 || num === 2) { return 1; } return fibonacci(num - 1) + fibonacci(num - 2); }; @Component({ selector: 'app-list', templateUrl: './list.component.html', styleUrls: ['./list.component.scss'], changeDetection: ChangeDetectionStrategy.OnPush }) export class ListComponent implements OnInit { @Input() title; @Input() data: EmployeeData[] = []; @Output() add = new EventEmitter<string>(); label: string; constructor() { } ngOnInit() { } addItem() { // this.data.push({ // label: this.label, // num: 30 // }); this.add.emit(this.label); this.label = ''; } // calc(item: EmployeeData) { // console.log('LIST', this.title); // return fibonacci(item.num); // } } <file_sep>/src/environments/environment.prod.ts export const environment = { production: true, url_api: 'http://platzi-store.herokuapp.com', firebaseConfig: { apiKey: "<KEY>", authDomain: "examplefirebase-ba4cc.firebaseapp.com", databaseURL: "https://examplefirebase-ba4cc.firebaseio.com", projectId: "examplefirebase-ba4cc", storageBucket: "examplefirebase-ba4cc.appspot.com", messagingSenderId: "874510915686", appId: '1:874510915686:web:7d8f8dfbc1254360' } };
2cc6791cb424cf96bee5f96a846e4668d326b107
[ "TypeScript" ]
6
TypeScript
tavo20/platziStoreAngular
0b674fcdbe71cfb4a8812419301b6b4e13526991
70c1cad6e946f6b1e45fb98bf6b834366061d15c
refs/heads/master
<repo_name>Shaman1774/Java_Lab_1<file_sep>/src/main/java/ru/bstu/iitus/vt41/bli/Barbell.java package ru.bstu.iitus.vt41.bli; import lombok.ToString; import java.util.Scanner; @ToString public class Barbell extends Coaching { @Override public void init(Scanner scanner) { super.init(scanner); } } <file_sep>/src/main/java/ru/bstu/iitus/vt41/bli/VolleyBall.java package ru.bstu.iitus.vt41.bli; import lombok.Setter; import lombok.ToString; import java.util.Scanner; @Setter @ToString(callSuper = true) public class VolleyBall extends Ball { @Override public void init(Scanner scanner) { super.init(scanner); } } <file_sep>/src/main/java/ru/bstu/iitus/vt41/bli/Ball.java package ru.bstu.iitus.vt41.bli; import lombok.Getter; import lombok.Setter; import lombok.ToString; import java.util.Scanner; @Setter @Getter @ToString(callSuper = true) public class Ball extends SportsEquipment { protected int radius; @Override public void init(Scanner scanner) { System.out.println("Вводите тип инвентаря "); setSportType(scanner.nextLine()); System.out.println("Введите название производителя "); this.setName(scanner.nextLine()); System.out.println("Вводите радиус мяча "); this.radius = scanner.nextInt(); scanner.nextLine(); } } <file_sep>/src/main/java/ru/bstu/iitus/vt41/bli/Main.java package ru.bstu.iitus.vt41.bli; import java.util.ArrayList; import java.util.Scanner; public class Main { static Scanner scanner = new Scanner(System.in); public static void main(String[] args) { System.out.println("Введите колличество спортивного инвентаря "); int count = Integer.parseInt(scanner.nextLine()); SportsEquipment[] sportsEquipments = new SportsEquipment[count]; initSportsEqs(sportsEquipments); } private static void initSportsEqs(SportsEquipment[] sportsEquipments) { Scanner scanner = new Scanner(System.in); for (int i = 0; i < sportsEquipments.length; i++) { System.out.print("Выберете тип инвентаря: \n" + "1 - Волейбольный_мяч;\n" + "2 - Теннисный_мяч;\n" + "3 - Ракетка;\n" + "4 - Метательное_копье;\n" + "5 - Штанга;\n" + "6 - Гиря;\n"); sportsEquipments[i] = createEquipment(scanner); sportsEquipments[i].init(scanner); } ArrayList<SportsEquipment> tennis = anTennis(sportsEquipments); System.out.println("Инвентарь, относящийся к теннису:\n"); for (SportsEquipment anTennis : tennis) System.out.println(anTennis.toString()); } private static SportsEquipment createEquipment(Scanner scanner) { switch (Integer.parseInt(scanner.nextLine())) { case 1: return new VolleyBall(); case 2: return new TennisBall(); case 3: return new Racket(); case 4: return new Javelin(); case 5: return new Barbell(); case 6: return new Poise(); default: return null; } } private static ArrayList<SportsEquipment> anTennis(SportsEquipment[] sportsEquipments) { ArrayList<SportsEquipment> tennis = new ArrayList<SportsEquipment>(); for (SportsEquipment anSportsEquipments : sportsEquipments) if (anSportsEquipments instanceof TennisBall || anSportsEquipments instanceof Racket) tennis.add(anSportsEquipments); return tennis; } }
beed51b07cb4eba7e869f6b70b144ee5ad0316d4
[ "Java" ]
4
Java
Shaman1774/Java_Lab_1
30c55e27ca5e2e4e9505fa21ad85875966f082f2
236a8cbfb363e62db11646aa83edce904eb7d0be
refs/heads/master
<file_sep>library(dplyr) # download if(!file.exists("./dane")){dir.create("./dane")} fileUrl <- "https://d396qusza40orc.cloudfront.net/getdata%2Fprojectfiles%2FUCI%20HAR%20Dataset.zip" download.file(fileUrl,destfile="./dane/Dataset.zip") # Unzip unzip(zipfile="./dane/Dataset.zip",exdir="./dane") # load train tables train1= read.table("./dane/UCI HAR Dataset/train/X_train.txt") train2= read.table("./dane/UCI HAR Dataset/train/y_train.txt") sub_train=read.table("./dane/UCI HAR Dataset/train/subject_train.txt") # load test tables test1= read.table("./dane/UCI HAR Dataset/test/X_test.txt") test2= read.table("./dane/UCI HAR Dataset/test/y_test.txt") sub_test=read.table("./dane/UCI HAR Dataset/test/subject_test.txt") # Read act labels actlab = read.table('./dane/UCI HAR Dataset/activity_labels.txt') # Read features features <- read.table('./dane/UCI HAR Dataset/features.txt') # Column names # train set colnames(train1) <- features[,2] colnames(train2) <-"actid" colnames(sub_train) <- "subid" # test set colnames(test1) <- features[,2] colnames(test2) <-"actid" colnames(sub_test) <- "subid" # act labels colnames(actlab) <- c('activityId','activityType') # merge train <- cbind(train2, sub_train, train1) test <- cbind(test2, sub_test, test1) final = rbind(train,test) colnam = (grepl("mean..", colnames(final)) | grepl("std..", colnames(final)) | grepl("actid", colnames(final)) | grepl("subid", colnames(final))) final = final[, colnam==TRUE] final = final %>% group_by(actid, subid) %>% summarise_all(mean) write.table(final, file = "tidydata.txt", row.names = FALSE) <file_sep># TidyData Getting and cleaning data Courseera project The purpose of this project is to demonstrate your ability to collect, work with, and clean a data set. The goal is to prepare tidy data that can be used for later analysis. You will be graded by your peers on a series of yes/no questions related to the project You will be required to submit: 1. Tidy data set, 2. Link to a Github repository with your script for performing the analysis, 3. Code book that describes the variables, the data, and any transformations or work that you performed to clean up the data, 4. README.md ## Review criteria 1. The submitted data set is tidy. 2. The Github repo contains the required scripts. 3. GitHub contains a code book that modifies and updates the available codebooks with the data to indicate all the variables and summaries calculated, along with units, and any other relevant information. 4. The README that explains the analysis files is clear and understandable. 5. The work submitted for this project is the work of the student who submitted it. ## Github repository contains following files: 1. Code Book 2. Run analysis r file 3. Readme file
c0fea9bf7fd4566b7e7e3486d4967a3442ebb68e
[ "Markdown", "R" ]
2
R
MichalDzwolak/TidyData
2364e6dd2442896f6bd0d1d585246bc58caf892f
2c2e69f303fc09b648c0ed3ea6816227bd3c412c
refs/heads/main
<file_sep>import React from 'react' import './style.css' const Panel = props => { const { image, input, button, data, draw } = props return ( <div className="panel"> <div className="graph"> {!data && <img src={image} alt="ícone img"></img>} {data && draw} </div> <form> <h2>Informe o Caminho</h2> {input} {button} </form> </div> ) } export default Panel<file_sep>import React from 'react' import './style.css' const Header = () => ( <header> <div className="container"> <h1>Graph App</h1> <a href="https://github.com/diasjoaovitor/graph-app" target="blank"> Github </a> </div> </header> ) export default Header<file_sep>import React from 'react' import image from '../../img/GitHub-Mark-32px.png' import './style.css' const Footer = () => ( <footer> <a href="https://github.com/diasjoaovitor" target="_blank"> <img src={image}></img> </a> </footer> ) export default Footer<file_sep>import React from 'react' import './style.css' const Modal = props => { const { display, input, button, routes, digraph, cost, handleChange, handleDigraph, handleCost } = props return ( <div className={`modal ${display}`}> <form> <h2>Informe as Rotas</h2> <div className="content"> <div className="options"> <label> <span>Dígrafo</span> <input onChange={handleDigraph} value={digraph ? false : true}type="checkbox"></input> </label> <label> <span>Custo</span> <input onChange={handleCost} value={cost ? false : true} type="checkbox"></input> </label> </div> <div className="modal-routes" onChange={handleChange}> {input} {routes && routes.map(() => input)} </div> {button} </div> </form> </div> ) } export default Modal<file_sep>import React, { useState, useEffect } from 'react' import Menu from '../../components/Menu' import Panel from '../../components/Panel' import Output from '../../components/Output' import Button from '../../components/Button' import Input from '../../components/Input' import Draw from '../../components/Draw' import Modal from '../../components/Modal' import Graph from '../../helpers/Graph' import api from '../../services/api' import image from '../../img/panorama-black-18dp.svg' import './style.css' const Main = () => { const [ expandedNodes, setExpandedNodes ] = useState('vazio') const [ path, setPath ] = useState('vazio') const [ totalCost, setTotalCost ] = useState(0) const [ origin, setOrigin ] = useState('') const [ destination, setDestination ] = useState('') const [ routes, setRoutes ] = useState(null) const [ algorithm, setAlgorithm ] = useState('bfs') const [ digraph, setDigraph ] = useState(false) const [ hasCost, setHasCost ] = useState(null) const [ modal, setModal ] = useState('not-visible') const [ data, setData ] = useState(null) const [ cost, setCost ] = useState(null) const [ file, setFile ] = useState() const [ upload, setUpload ] = useState() useEffect(() => { if(file) { (async () => { try { const formData = new FormData() formData.append('file', file) api.post('/upload', formData) console.log(file.name) const { data } = await api.get(`/data?name=${file.name}`) setUpload(data) } catch (error) { return window.alert('Erro no upload! Tente atualizar a página.') } })() } }, [file]) useEffect(() => { if(upload) { const { routes, cost, digraph } = upload setRoutes(routes) setCost(cost) setDigraph(digraph) draw() } }, [upload, routes, cost, digraph]) const init = () => { const modalRoutes = document.querySelector('.modal-routes') const inputs = modalRoutes.querySelectorAll('input') const routes = [] const cost = [] routes.push([]) let a = 0 inputs.forEach((input, index) => { if(!hasCost) { routes[a].push(input.value) if(index % 2 && index > 0) { routes.push([]) a++ } } else { if(input.placeholder !== 'Custo') { routes[a].push(input.value) if(index % 3 && index > 0) { routes.push([]) a++ } } else { cost.push(Number(input.value)) } setCost(cost.filter(value => value)) } }) setRoutes(routes.filter(([ origin, destination ]) => origin || destination)) } const draw = () => { if(routes) { const graph = new Graph(routes, cost, digraph) setData(graph.draw()) } } const search = () => { if(routes) { const graph = new Graph(routes, cost, digraph, algorithm) const data = graph.start(origin, destination) const { expandedNodes, isPath } = data setExpandedNodes( expandedNodes[0] ? expandedNodes.map((node, index) => { return expandedNodes.length - 1 > index ? `${node} => ` : node }) : 'vazio' ) if(isPath) { const { path, totalCost } = data setPath( path.map((node, index) => { return path.length - 1 > index ? `${node} => ` : node }) ) setTotalCost(totalCost) } else { setPath('não existe') setTotalCost(0) } } } return ( <main className="container"> <section> <Menu algorithm={algorithm} create={ <Button label="Criar Grafo" type="button" handleChange={() => { setModal('') }} /> } upload={ <Button label="Carregar Grafo" type="file" handleFile={event => setFile(event.target.files[0])} /> } handleChange={event => setAlgorithm(event.target.value)} modal={ <Modal display={modal} routes={routes} origin={origin} destination={destination} digraph={digraph} cost={hasCost} handleChange={() => init()} handleDigraph={event => setDigraph(event.target.value)} handleCost={event => setHasCost(event.target.value)} input={ <Input handleOrigin={event => setOrigin(event.target.value)} handleDestination={event => setDestination(event.target.value)} cost={hasCost} /> } button={ <Button label="Salvar" handleChange={() => { setModal('not-visible') draw() }} /> } /> } /> </section> <section> <Panel image={image} routes={routes} input={ <Input handleOrigin={event => setOrigin(event.target.value)} handleDestination={event => setDestination(event.target.value)} /> } button={ <Button label="Buscar" type="button" handleChange={() => search()} /> } data={data} draw={<Draw data={data} digraph={digraph} />} /> </section> <section> <Output label="Caminho:" value={path} /> <Output label="Custo:" value={totalCost} /> <Output label="Nós Expandidos:" value={expandedNodes} /> </section> </main> ) } export default Main<file_sep>import bfs from './algorithms/bfs' import dfs from './algorithms/dfs' class Graph { constructor(routes, cost, isDigraph, algorithm) { this.routes = routes this.isDigraph = isDigraph this.cost = cost this.algorithm = algorithm this.nodes = [] this.adjacencyList = new Map() this.path = [] this.init() } init() { const distinguishedNodes = new Set() this.routes.forEach(([ a, b ]) => { distinguishedNodes.add(a) distinguishedNodes.add(b) }) this.nodes = Array.from(distinguishedNodes) this.nodes.forEach(node => this.adjacencyList.set(node, [])) this.routes.forEach(([a, b]) => { this.adjacencyList.get(a).push(b) !this.isDigraph && this.adjacencyList.get(b).push(a) }) this.nodes = this.nodes.filter(node => node) } draw() { const nodes = this.nodes.map(node => { return { id: node, label: node } }) const edges = this.routes.map((route, index) => { return { source: route[0], target: route[1], label: !this.cost ? '' : this.cost[index] } }) const data = { nodes, edges } return data } calculatePath(nodes, origin, destination, visited = new Set()) { visited.add(origin) const current = this.adjacencyList.get(origin).reverse() nodes.find(node => { return current.find(next => { return node === next && !visited.has(node) && origin !== destination && this.calculatePath(nodes, node, destination, visited) }) }) return Array.from(visited) } calculateCost() { let cost = 0 this.cost && this.path.forEach((node, index) => { if(index > 0) { const last = this.path[index - 1] const route = this.routes.find(([ a, b ]) => a === last && b === node) const position = this.routes.indexOf(route) cost += this.cost[position] } }) return cost } start(origin, destination) { let data = {} switch(this.algorithm) { case 'bfs': data = bfs(this.adjacencyList, origin, destination) break case 'dfs': data = dfs(this.adjacencyList, origin, destination) break default: return } const { expandedNodes, isPath } = data if(isPath) { const nodes = this.algorithm === 'dfs' ? [...expandedNodes] : [...dfs(this.adjacencyList, origin, destination).expandedNodes] nodes.reverse() this.path = this.calculatePath(nodes, origin, destination) data = { ...data, path: this.path, totalCost: this.calculateCost() } } return data } } export default Graph<file_sep>const dfs = (adjacencyList, origin, destination, visited = new Set()) => { visited.add(origin) const current = adjacencyList.get(origin) current.find(node => { !visited.has(node) && !visited.has(destination) && dfs(adjacencyList, node, destination, visited) }) return { expandedNodes: Array.from(visited), isPath: visited.has(destination) } } export default dfs<file_sep>import React from 'react' import './style.css' const Button = props => { const { label, type, handleChange, handleFile } = props return ( <label onClick={handleChange} onChange={handleFile} className="button"> <span>{label}</span> <input className="not-visible" type={type}></input> </label> ) } export default Button<file_sep>import express from 'express' import fileUpload from 'express-fileupload' import cors from 'cors' import fs from 'fs' import dotenv from 'dotenv' import path from 'path' const port = process.env.PORT || 3001 const app = express() dotenv.config() app.use(express.static('uploads')) app.use(express.static(path.join('client/build'))) app.use(cors()) app.use(fileUpload()) app.post('/api/upload', (req, res) => { try { const file = req.files.file file.mv(`uploads/${file.name}`) return res.status(200).json({ message: 'Sucesso' }) } catch (error) { return res.status(500).json({ message: error.message}) } }) app.get('/api/data', (req, res) => { try { const file = req.query.name const data = JSON.parse(fs.readFileSync(`uploads/${file}`)) fs.unlinkSync(`uploads/${file}`) console.log(data, 'olá') return res.status(200).json(data) } catch (error) { return res.status(500).json({ message: error.message }) } }) app.listen(port, () => console.log('> Servidor executando...')) <file_sep># Graph App <p align="center"> <img src="https://user-images.githubusercontent.com/43608067/105108005-1774ee00-5a98-11eb-807e-67be03456373.png" width="500"> </p> ## Tecnologias * Node.js * React.js * AntV G6 ## Como rodar o projeto * Faça o clone do repositório ```bash $ git clone https://github.com/diasjoaovitor/graph-app ``` * Inicie o backend, caso deseje fazer upload de arquivos ```bash $ cd graph-app $ yarn ou npm i $ yarn start ou npm start ``` * Inicie o frontend ```bash $ cd client $ yarn ou npm i $ yarn start ou npm start ``` <file_sep>const bfs = (adjacencyList, origin, destination) => { const visited = new Set() visited.add(origin) const queue = [origin] let isPath = '' while(queue.length > 0 && visited.size !== adjacencyList.size) { const node = queue.shift() const current = adjacencyList.get(node) if(!current) break isPath = current.find(node => { visited.add(node) queue.push(node) return node === destination }) if(isPath) break } return { expandedNodes: Array.from(visited), isPath } } export default bfs
7a6cfe320d56b2ef346f101622b1677bc2c012e8
[ "JavaScript", "Markdown" ]
11
JavaScript
lucasbat/graph-app
c977272cedf8a10faf673c74aebd41096cda0d15
6809e353b254a436d58e414600d7edc45df6e4d8
refs/heads/master
<file_sep> This is test line.`
c171c94768428c466f5f9c4e39565e4130c54f79
[ "Python" ]
1
Python
2016aho/BattleCode
36ed0335e0ab56ddf717cf2303d2aed56969eb61
113a916bf2d4f8728dee8f6488ee0780b3ab7deb
refs/heads/master
<repo_name>Tigralt/Extinction<file_sep>/README.md Extinction ========== Il faut installer la bbliothèque fblend: http://sourceforge.net/projects/fblend/ Etape 1: Transferer les fichier lib et include dans les fichiers lib et include de Codeblocks Etape 2: Linker le fichier libfblend.a Etape 3: Rajouter dans "Other Link Option" la ligne: -lfblend -lalleg<file_sep>/decor.h #ifndef DECOR_H_INCLUDED #define DECOR_H_INCLUDED #include "projet.h" class Bloc { public: Bloc(); void assombrir(Bloc fond,int heure=0,int flash=0); int x,y,lum; bool collision,interieur; BITMAP* image; }; Bloc** chargement(Bloc** carte); int chrono(clock_t temps_1); int horloge(int heure,clock_t* temps_1,bool* matin); void affiche_fond(Bloc** carte, BITMAP* bufferFond, int heure,int x,int y); void cacher_interieur(Bloc** carte,BITMAP* buffer); BITMAP* remplir_mask(Bloc** carte); #endif // DECOR_H_INCLUDED <file_sep>/acteurs.h #ifndef ACTEURS_H_INCLUDED #define ACTEURS_H_INCLUDED class Balle { public: Balle(float xi=0, float yi=0, int ai=0); void trajectoire(BITMAP* mask); void afficher(BITMAP* buffer,BITMAP* mask); void collision(BITMAP* mask); float x,y; int a; bool del; int xo,yo; }; class Arme { public: Arme(); void changerArme(); void recharger(); void tir(float x, float y, int a); Balle* b; int armeEquipe; bool armeInventaire[4]; bool gachette; int chargeur, chargeurSize[4]; }; class Personnage { public: Personnage(float xi, float yi, float zi, BITMAP* p[3]); void afficher(BITMAP* buffer, BITMAP* bufferFond, BITMAP* mask); int collision(BITMAP* mask,int dir); void action(BITMAP* mask); BITMAP* remplir_mask(BITMAP* mask); int hp; float x,y,z; private: int pos,a,tmp; BITMAP* img[3]; Arme arme; }; class Zombie { public: Zombie(); void afficher(BITMAP* buffer, BITMAP* mask); void actualisation(BITMAP* buffer,Personnage p); void deplacement_aleatoire(); void collision(BITMAP* buffer); void reperage_acteur(Personnage p); void deplacement_aggressif(Personnage p); BITMAP* img[4]; BITMAP* maskImg; private: float x,y,z,vitx,vity; int a,tmp,pos; bool aggressif; bool mort; }; #endif // ACTEURS_H_INCLUDED <file_sep>/ath.h #ifndef ATH_H_INCLUDED #define ATH_H_INCLUDED void watch(int heure,BITMAP* tab[11],BITMAP* buffer); void affiche_watch(int x,int d,int u,BITMAP* tab[11],BITMAP* buffer); void barre_hp(int hp,BITMAP* imgHp,BITMAP* buffer); #endif // ATH_H_INCLUD <file_sep>/acteurs.cpp #include "projet.h" /************************************************/ /** Fonction Personnage **/ /************************************************/ Personnage::Personnage(float xi, float yi, float zi, BITMAP* p[3]) : x(xi), y(yi), z(zi), pos(0), hp(100), tmp(0) { for(int i=0;i<3;i++)img[i]=p[i]; } void Personnage::afficher(BITMAP* buffer, BITMAP* bufferFond, BITMAP* mask) { BITMAP* aff; switch(pos) { case 0:case 2: aff = img[0]; break; case 1: aff = img[1]; break; case 3: aff = img[2]; } for(int i=0;i<arme.chargeurSize[arme.armeEquipe]-1;i++) if(!arme.b[i].del)arme.b[i].afficher(bufferFond,mask); rotate_sprite(buffer,aff,(SCREEN_W-img[0]->w)/2,(SCREEN_H-img[0]->h)/2,itofix(a)); } void Personnage::action(BITMAP* mask) { a = atan2(mouse_y-(SCREEN_H-img[0]->h)/2-9,mouse_x-(SCREEN_W-img[0]->w)/2)*180/M_PI*64/90+64; if(key[KEY_W]&&!collision(mask,0)) y-=DEP; else if(key[KEY_S]&&!collision(mask,1)) y+=DEP; if(key[KEY_A]&&!collision(mask,2)) x-=DEP; else if(key[KEY_D]&&!collision(mask,3)) x+=DEP; if(mouse_b&1){arme.tir(x,y,a);arme.gachette=true;} else if(!mouse_b&1){arme.gachette=false;} if(key[KEY_R])arme.recharger(); if(key[KEY_W]||key[KEY_S]||key[KEY_A]||key[KEY_D])tmp++; if(tmp>=7){pos++;tmp=0;} if(pos>3)pos=0; } int Personnage::collision(BITMAP* mask,int dir) { switch(dir) { case 0: if(getpixel(mask,x*ECH+9,(y-DEP)*ECH+2)==0xFFFFFF) return 1; break; case 1: if(getpixel(mask,x*ECH+9,(y+DEP)*ECH+9)==0xFFFFFF) return 1; break; case 2: if(getpixel(mask,(x-DEP)*ECH-1,y*ECH+6)==0xFFFFFF) return 1; break; case 3: if(getpixel(mask,(x+DEP)*ECH+18,y*ECH+6)==0xFFFFFF) return 1; break; } return 0; } BITMAP* Personnage::remplir_mask(BITMAP* mask) { circlefill(mask,x*ECH+9,y*ECH+9,9,0xFFFFFF); return mask; } /************************************************/ /** Fonction Balles **/ /************************************************/ Balle::Balle(float xi, float yi, int ai){} void Balle::afficher(BITMAP* buffer, BITMAP* mask) { trajectoire(mask); rectfill(buffer,x,y,x,y,0xFFFFFF); } void Balle::trajectoire(BITMAP* mask) { x+=10*cos((a-64)*M_PI/180*90/64); y+=10*sin((a-64)*M_PI/180*90/64); collision(mask); if(x>xo+SCREEN_W/2||x<xo-SCREEN_W/2||y>yo+SCREEN_H/2||y<yo-SCREEN_H/2)del=TRUE; } void Balle::collision(BITMAP* mask) { if(getpixel(mask,x,y)==0xFF0000)del=TRUE; } /**************************************************/ /** Fonction Arme **/ /**************************************************/ Arme::Arme(): chargeurSize({1,20,6,30}), chargeur(0), b(new Balle[20]), armeInventaire({false,true,false,false}), gachette(false), armeEquipe(1) { } void Arme::recharger() { chargeur=chargeurSize[armeEquipe]-1; } void Arme::tir(float x, float y, int a) { if(chargeur>0&&(!gachette&&armeEquipe==1)) { int xo = x; int yo = y; b[chargeur].x=x*ECH; b[chargeur].y=y*ECH; b[chargeur].xo=x*ECH; b[chargeur].yo=y*ECH; b[chargeur].a=a; b[chargeur].del=FALSE; chargeur--; } } void Arme::changerArme() { } /*************************************************** ******************Zombie**************************** ***************************************************/ Zombie::Zombie() { x = rand()%50+5; y = rand()%50+5; z = 1; pos = 0; aggressif = false; tmp = 0; mort=FALSE; } void Zombie::afficher(BITMAP* buffer, BITMAP* mask) { BITMAP* aff; switch((int)pos) { case 0:case 2: aff = img[0]; break; case 1: aff = img[1]; break; case 3: aff = img[2]; } if(!mort)draw_sprite(mask,maskImg,x*ECH,y*ECH); rotate_sprite(buffer,aff,x*ECH,y*ECH,itofix(a)); } void Zombie::actualisation(BITMAP* buffer,Personnage p) { if(!mort) { if(tmp>=10) { if(aggressif)deplacement_aggressif(p); else deplacement_aleatoire(); reperage_acteur(p); if(vitx||vity)pos++; if(pos>3)pos-=4; tmp = 0; } else tmp++; x+=vitx; y+=vity; collision(buffer); } } void Zombie::deplacement_aleatoire() { float vitesse; a += rand()%50 - 25; vitesse =(float)(rand()%200)/2000; vitx = cos((a-64)*M_PI/180*90/64) * vitesse; vity = sin((a-64)*M_PI/180*90/64) * vitesse; } void Zombie::collision(BITMAP* buffer) { int i,j,k; for(i=x*ECH;i<x*ECH+17;i++) for(j=y*ECH-2;j<y*ECH+15;j++) { if(getpixel(buffer,i,j)==0xFFFFFF) { mort=TRUE; for(k=0;k<3;k++)img[k]=img[3]; } } } void Zombie::reperage_acteur(Personnage p) { float dx,dy; dx = p.x-x; dy = p.y-y; /// acteur face et proche du zombie if(((dx*cos((a-64)*M_PI/180*90/64)>0&&dx*cos((a-64)*M_PI/180*90/64)<4)|| (dy*sin((a-64)*M_PI/180*90/64)>0&&dy*sin((a-64)*M_PI/180*90/64)<4))&&(abs(dx)<4)&&(abs(dy)<4)) aggressif=1; } void Zombie::deplacement_aggressif(Personnage p) { a = atan2(p.y-y, p.x-x)*180/M_PI*64/90+64; vitx=cos((a-64)*M_PI/180*90/64)*0.1; vity=sin((a-64)*M_PI/180*90/64)*0.1; } <file_sep>/decor.cpp #include "projet.h" using namespace std; /************************************************/ /** Fonction Bloc **/ /************************************************/ Bloc::Bloc():lum(0){} /************************************************/ /** Fonction Decor **/ /************************************************/ Bloc** chargement(Bloc** carte) { string tab[TAILLE_MAP]; string ligne="",ligne_p=""; char x; BITMAP *herbe_0,*herbe_1,*herbe_2,*herbe_3,*herbe_4,*route,*mur,*planche,*carrelage,*sable,*terre; herbe_0=load_bitmap("img/fond/herbe_0.bmp",NULL); herbe_1=load_bitmap("img/fond/herbe_1.bmp",NULL); herbe_2=load_bitmap("img/fond/herbe_3.bmp",NULL); herbe_3=load_bitmap("img/fond/herbe_2.bmp",NULL); herbe_4=load_bitmap("img/fond/herbe_4.bmp",NULL); route=load_bitmap("img/fond/route.bmp",NULL); mur=load_bitmap("img/fond/mur.bmp",NULL); planche=load_bitmap("img/fond/planche.bmp",NULL); carrelage=load_bitmap("img/fond/carrelage.bmp",NULL); sable=load_bitmap("img/fond/sable.bmp",NULL); terre=load_bitmap("img/fond/terre.bmp",NULL); ifstream fichier("map.txt",ios::in); for(int i=0;i<TAILLE_MAP;i++) { getline(fichier,ligne); tab[i]=ligne; for(int j=0;j<TAILLE_MAP;j++) { switch(ligne[j]) { case 'h':carte[i][j].collision=false; carte[i][j].interieur=false; carte[i][j].image=herbe_0; if((ligne[j-1]!='h')&&(ligne[j+1]=='h')&&(ligne_p[j]!='h')) carte[i][j].image=herbe_1; if((ligne[j-1]=='h')&&(ligne[j+1]!='h')&&(ligne_p[j]!='h')) carte[i][j].image=herbe_3; break; case 'r':carte[i][j].collision=false; carte[i][j].interieur=false; carte[i][j].image=route; break; case 'm':carte[i][j].collision=true; carte[i][j].interieur=false; carte[i][j].image=mur; break; case 'M':carte[i][j].collision=true; carte[i][j].interieur=true; carte[i][j].image=mur; break; case 'P':carte[i][j].collision=false; carte[i][j].interieur=true; carte[i][j].image=planche; break; case 'p':carte[i][j].collision=false; carte[i][j].interieur=false; carte[i][j].image=planche; break; case 'C':carte[i][j].collision=false; carte[i][j].interieur=true; carte[i][j].image=carrelage; break; case 's':carte[i][j].collision=false; carte[i][j].interieur=false; carte[i][j].image=sable; break; case 'c':carte[i][j].collision=false; carte[i][j].interieur=false; carte[i][j].image=carrelage; break; case 't':carte[i][j].collision=false; carte[i][j].interieur=false; carte[i][j].image=terre; break; } switch(ligne_p[j]) { case 'h':if((ligne_p[j-1]!='h')&&(ligne_p[j+1]=='h')&&(ligne[j]!='h')) carte[i-1][j].image=herbe_2; if((ligne_p[j-1]=='h')&&(ligne_p[j+1]!='h')&&(ligne[j]!='h')) carte[i-1][j].image=herbe_4; break; } } ligne_p=ligne; } fichier.close(); return carte; } int chrono(clock_t temps_1) { clock_t temps_2 = clock(); if((temps_2-temps_1)/CLOCKS_PER_SEC>=1) return 1; else return 0; } void affiche_fond(Bloc** carte, BITMAP* bufferFond, int heure,int x,int y) { int i,j,coeff; for(j=0;j<TAILLE_MAP;j++) for(i=0;i<TAILLE_MAP;i++) { if((!carte[j][i].interieur)||(carte[j][i].collision)) carte[j][i].lum=(heure/360); else carte[j][i].lum=0; coeff=50+(carte[j][i].lum*2); if(coeff>255) coeff=255; fblend_add(carte[j][i].image,bufferFond,i*ECH,j*ECH,coeff); } } int horloge(int heure,clock_t* temps_1,bool* matin) { if(chrono(*temps_1)) { *temps_1=clock(); if(*matin) heure+=48; else heure-=48; if(heure>=43200) *matin=false; if(heure<=0) *matin=true; } return heure; } BITMAP* remplir_mask(Bloc** carte) { BITMAP* mask; mask=create_bitmap(TAILLE_MAP*ECH,TAILLE_MAP*ECH); for(int i=0;i<TAILLE_MAP;i++) for(int j=0;j<TAILLE_MAP;j++) if(carte[i][j].collision) rectfill(mask,(carte[i][j].x)*ECH,(carte[i][j].y)*ECH,(carte[i][j].x+1)*ECH,(carte[i][j].y+1)*ECH,0xFFFFFF); return mask; } void cacher_interieur(Bloc** carte,BITMAP* buffer) { for(int i=0;i<TAILLE_MAP;i++) for(int j=0;j<TAILLE_MAP;j++) if((carte[j][i].interieur)&&(!carte[j][i].collision)) rectfill(buffer,i*ECH,j*ECH,(i+1)*ECH,(j+1)*ECH,0x000000); } <file_sep>/projet.h #ifndef PROJET_H_INCLUDED #define PROJET_H_INCLUDED #include <stdio.h> #include <allegro.h> #include <new> #include <math.h> #include <time.h> #include <iostream> #include <fstream> #include <fblend.h> #define ECH 20 #define DEP 0.15 #define TAILLE_MAP 100 #define X_WATCH 720 #define X_HP 600 #include "acteurs.h" #include "decor.h" #include "objet.h" #include "ath.h" #endif // PROJET_H_INCLUDED <file_sep>/objet.h #ifndef OBJET_H_INCLUDED #define OBJET_H_INCLUDED #endif // OBJET_H_INCLUDED <file_sep>/main.cpp #include "projet.h" using namespace std; int main() { Bloc** carte; Zombie* z; BITMAP* buffer = NULL; BITMAP* bufferPerso = NULL; BITMAP* perso[3] = {NULL,NULL,NULL},* zombie[4] = {NULL,NULL,NULL,NULL}; BITMAP* bufferFond = NULL; BITMAP* maskCol = NULL; BITMAP* maskColActeur = NULL; BITMAP* maskZombie = NULL; BITMAP* montre[11]; BITMAP* imgHP; clock_t temps_1=(clock_t)0; bool matin=true; int heure=43200; int i,j; allegro_init(); install_keyboard(); install_mouse(); set_color_depth(desktop_color_depth()); if(!set_gfx_mode(GFX_AUTODETECT_WINDOWED,800,600,0,0)); srand(time(NULL)); show_mouse(screen); buffer = create_bitmap(SCREEN_W,SCREEN_H); bufferPerso = create_bitmap(SCREEN_W,SCREEN_H); bufferFond = create_bitmap(TAILLE_MAP*ECH,TAILLE_MAP*ECH); maskCol = create_bitmap(TAILLE_MAP*ECH,TAILLE_MAP*ECH); maskColActeur = create_bitmap(TAILLE_MAP*ECH,TAILLE_MAP*ECH); clear_bitmap(maskColActeur); perso[0] = load_bitmap("img/acteurs/perso1.bmp",NULL); perso[1] = load_bitmap("img/acteurs/perso2.bmp",NULL); perso[2] = load_bitmap("img/acteurs/perso3.bmp",NULL); zombie[0] = load_bitmap("img/acteurs/zombie1.bmp",NULL); zombie[1] = load_bitmap("img/acteurs/zombie2.bmp",NULL); zombie[2] = load_bitmap("img/acteurs/zombie3.bmp",NULL); zombie[3] = load_bitmap("img/acteurs/sang.bmp",NULL); maskZombie = load_bitmap("img/acteurs/maskZombie.bmp",NULL); montre[0] = load_bitmap("img/ath/0.bmp",NULL); montre[1] = load_bitmap("img/ath/1.bmp",NULL); montre[2] = load_bitmap("img/ath/2.bmp",NULL); montre[3] = load_bitmap("img/ath/3.bmp",NULL); montre[4] = load_bitmap("img/ath/4.bmp",NULL); montre[5] = load_bitmap("img/ath/5.bmp",NULL); montre[6] = load_bitmap("img/ath/6.bmp",NULL); montre[7] = load_bitmap("img/ath/7.bmp",NULL); montre[8] = load_bitmap("img/ath/8.bmp",NULL); montre[9] = load_bitmap("img/ath/9.bmp",NULL); montre[10] = load_bitmap("img/ath/2dots.bmp",NULL); imgHP = load_bitmap("img/ath/hp.bmp",NULL); Personnage p1(10,10,1,perso); z = new Zombie[50]; for(i=0;i<50;i++) for(j=0;j<4;j++) { z[i].img[j]=zombie[j]; z[i].maskImg=maskZombie; } /** Chargement de la carte **/ carte=new Bloc*[TAILLE_MAP]; for(i=0;i<TAILLE_MAP;i++) { carte[i]=new Bloc[TAILLE_MAP]; for(j=0;j<TAILLE_MAP;j++) { carte[i][j].x=j; carte[i][j].y=i; } } carte=chargement(carte); /****************************/ maskCol=remplir_mask(carte); while(!key[KEY_ESC]) { if(!temps_1) temps_1=clock(); heure=horloge(heure,&temps_1,&matin); draw_sprite(maskColActeur,maskCol,0,0); p1.action(maskColActeur); maskColActeur=p1.remplir_mask(maskColActeur); heure=horloge(heure,&temps_1,&matin); affiche_fond(carte,bufferFond,heure,p1.x,p1.y); for(i=0;i<50;i++)z[i].afficher(bufferFond,maskColActeur); if(!carte[(int)p1.y][(int)p1.x].interieur) cacher_interieur(carte,bufferFond); p1.afficher(bufferPerso,bufferFond,maskColActeur); draw_sprite(buffer,bufferFond,(SCREEN_W-20)/2-p1.x*ECH,(SCREEN_H-20)/2-p1.y*ECH); for(i=0;i<50;i++) z[i].actualisation(bufferFond,p1); watch(heure,montre,buffer); barre_hp(p1.hp,imgHP,buffer); draw_sprite(buffer,bufferPerso,0,0); draw_sprite(screen,buffer,0,0); //draw_sprite(screen,maskColActeur,0,0); clear_bitmap(buffer); clear_bitmap(bufferFond); clear_bitmap(maskColActeur); clear_to_color(bufferPerso,0xFF00FF); rest(20); } return 0; }END_OF_MAIN(); <file_sep>/ath.cpp #include "projet.h" void watch(int heure,BITMAP* tab[11],BITMAP* buffer) { int h,mins,sec; int d,u; h=heure/3600; mins=(heure-(h*3600))/60; d=h/10; u=h-d*10; affiche_watch(0,d,u,tab,buffer); draw_sprite(buffer,tab[10],X_WATCH+ECH,0); d=mins/10; u=mins-d*10; affiche_watch(3,d,u,tab,buffer); } void affiche_watch(int x,int d,int u,BITMAP* tab[11],BITMAP* buffer) { draw_sprite(buffer,tab[d],X_WATCH+x*ECH/2,0); draw_sprite(buffer,tab[u],X_WATCH+(x+1)*ECH/2,0); } void barre_hp(int hp,BITMAP* imgHp,BITMAP* buffer) { for(int i=0;i<hp;i++) { draw_sprite(buffer,imgHp,X_HP+i,0); } textprintf(buffer,font,X_HP,12,makecol(250,0,0),"%d%%",hp); }
bc1b1fa1990f2626bc3c7be8c1de78f5b4335b90
[ "Markdown", "C", "C++" ]
10
Markdown
Tigralt/Extinction
81d279b337b311923ed8094039c0ebba6957be66
11dc021eb67ddb1c10a4b69b129f8e022536a658
refs/heads/master
<file_sep>package com.example.repository; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.jdbc.core.BeanPropertyRowMapper; import org.springframework.jdbc.core.RowMapper; import org.springframework.jdbc.core.namedparam.BeanPropertySqlParameterSource; import org.springframework.jdbc.core.namedparam.MapSqlParameterSource; import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate; import org.springframework.jdbc.core.namedparam.SqlParameterSource; import org.springframework.stereotype.Repository; import com.example.domain.UserMail; /** * ユーザーのメールを管理するリポジトリ. * * @author iidashuhei * */ @Repository public class UserMailRepository { @Autowired private NamedParameterJdbcTemplate template; private RowMapper<UserMail> rowMapper = new BeanPropertyRowMapper<UserMail>(UserMail.class); /** * ユーザーのメールアドレスを登録する. * * @param userMail ユーザーのメール情報 */ public void insert(UserMail userMail) { String sql = "insert into user_mails(user_id, mail_type_id, mail_address)values(:userId,:mailTypeId,:mailAddress)"; SqlParameterSource param = new BeanPropertySqlParameterSource(userMail); template.update(sql, param); } /** * メールアドレスの重複チェックをする. * * @param mailAddress メールアドレス * @return メールアドレス情報 */ public UserMail findByEmail(String mailAddress) { String sql = "select user_id, mail_type_id, mail_address from user_mails where mail_address =:mailAddress"; SqlParameterSource param = new MapSqlParameterSource().addValue("mailAddress", mailAddress); List<UserMail> userMailList = template.query(sql, param, rowMapper); if(userMailList.isEmpty()) { return null; } else { return userMailList.get(0); } } } <file_sep>package com.example.domain; public class UserRank { private Integer rankId; private String rank; public Integer getRankId() { return rankId; } public void setRankId(Integer rankId) { this.rankId = rankId; } public String getRank() { return rank; } public void setRank(String rank) { this.rank = rank; } @Override public String toString() { return "UserRank [rankId=" + rankId + ", rank=" + rank + "]"; } } <file_sep>package com.example.domain; public class UserMail { private Integer userId; private Integer mailTypeId; private String mailAddress; public Integer getUserId() { return userId; } public void setUserId(Integer userId) { this.userId = userId; } public Integer getMailTypeId() { return mailTypeId; } public void setMailTypeId(Integer mailTypeId) { this.mailTypeId = mailTypeId; } public String getMailAddress() { return mailAddress; } public void setMailAddress(String mailAddress) { this.mailAddress = mailAddress; } @Override public String toString() { return "UserMail [userId=" + userId + ", mailTypeId=" + mailTypeId + ", mailAddress=" + mailAddress + "]"; } } <file_sep>$(function(){ var map = new Map(); var array = []; var countMail = 0; $("#phone").on('click',function(){ if(this.checked){ var count1 = $('#phoneMail').length; var count2 = $('#pcMail').length; countMail = count1 + count2 ; if(countMail === 0) { countMail = 0 }else{ countMail = countMail } //keyを取り出してarray[]につめている var keys = map.keys(); for(var key of keys){ array.push(key); } //array[]を回して中にある値とcountWaseを比べて、同じだったらarray[]の最大値を取得し、その値に+1したものをCountMobileの値とする for (var value of array){ if(value === countMail){ countMail = Math.max.apply(null,array) + 1; }else{ countMail = countMail; } } //mapにセットしている map.set(countMail,'countMail'); var mailAddress = document.getElementById("phone"); mailAddress.setAttribute("name","mailAddressList["+ countMail + "].mailAddress"); //<div id="phoneMail">の中に<input>を形成していく var parentM = document.getElementById("phoneMail"); var childM = document.createElement("div"); childM.setAttribute("id","idM"); var phone = document.createElement("input"); phone.setAttribute("type","text"); phone.setAttribute("placeholder","phoneメールアドレス"); phone.setAttribute("name","mailAddressList["+ countMail + "].mailAddress"); phone.setAttribute("class","mail1"); childM.appendChild(phone); parentM.appendChild(childM); var del = document.createElement("input"); del.setAttribute("type","button"); del.setAttribute("value","削除"); del.setAttribute("id","del1"); del.setAttribute("class","mail1"); childM.appendChild(del); parentM.appendChild(childM); $("#del1").on('click',function(){ $(".mail1").remove(); map.delete(countMail); }) //チェックが外れたら }else { $("#idM").remove(); map.delete(countMail); } }); $("#pc").on("click",function(){ if(this.checked){ var count1 = $('#phoneMail').length; var count2 = $('#pcMail').length; countMail = count1 + count2 ; if(countMail === 0) { countMail = 0 }else{ countMail = countMail } //keyを取り出してarray[]につめている var keys = map.keys(); for(var key of keys){ array.push(key); } //array[]を回して中にある値とcountWaseを比べて、同じだったらarray[]の最大値を取得し、その値に+1したものをCountMobileの値とする for (var value of array){ if(value === countMail){ countMail = Math.max.apply(null,array) + 1; }else{ countMail = countMail; } } //mapにセットしている map.set(countMail,'countMail'); var mailAddress = document.getElementById("pc"); mailAddress.setAttribute("name","mailAddressList["+ countMail + "].mailAddress"); //<div id="phoneMail">の中に<input>を形成していく var parentTue = document.getElementById("pcMail"); var childTue = document.createElement("div"); childTue.setAttribute("id","idTue"); var pc = document.createElement("input"); pc.setAttribute("type","text"); pc.setAttribute("placeholder","pcメールアドレス"); pc.setAttribute("name","mailAddressList["+ countMail + "].mailAddress"); pc.setAttribute("class","mail2"); childTue.appendChild(pc); parentTue.appendChild(childTue); var del = document.createElement("input"); del.setAttribute("type","button"); del.setAttribute("value","削除"); del.setAttribute("id","del1"); del.setAttribute("class","mail2"); childTue.appendChild(del); parentTue.appendChild(childTue); $("#del1").on('click',function(){ $(".mail2").remove(); map.delete(countMail); }) //チェックが外れたら }else{ $("#idTue").remove(); map.delete(countMail); } })  });
4e1683114eeb407f116715c50836952a9a5001c6
[ "JavaScript", "Java" ]
4
Java
shun053013/practice2
bf42632140ac32b332436cea75fa06a6efc83389
5b15ea369c8f424a0373a70fb6b5681a53e9a521
refs/heads/master
<file_sep>export interface IProduct{ Id: number; Name: string; Brand: string; Category: string; ManufacturePrice: number; RetailPrice: number; Quantity: number; DiscountType:string; Image:string; } <file_sep>export class User { Id:number; NIC: string; Username: string; Passwords: string; FirstName: string; LastName: string; ResidenceNo: string; Lane: string; City: string; ContactNo: string; Email: string; Gender: string; UserType:String; }<file_sep>import {Component, OnInit} from '@angular/core'; import {Observable} from 'rxjs/Observable'; import { ProductService } from '../services/product.service'; import { IProduct } from '../models/product'; import {FormGroup,FormControl,Validators} from '@angular/forms'; @Component({ templateUrl: './product-list.component.html', styleUrls: ['./product-list.component.css'] }) export class ProductListComponent implements OnInit { pageTitle= 'Product List'; errorMessage: string; products: IProduct[]; productForm:boolean=false; editProductForm:boolean=false; isNewForm:boolean; newProduct:any={}; editedProduct:any={}; _listFilter:string; isShow:boolean=false; get listFilter():string{ return this._listFilter; } set listFilter(value:string){ this._listFilter=value; this.filteredProducts=this.listFilter?this.performFilter(this.listFilter):this.products; } filteredProducts:IProduct[]; constructor(private _productService: ProductService) {} performFilter(filterBy:string):IProduct[]{ filterBy=filterBy.toLocaleLowerCase(); return this.products.filter((product:IProduct)=> product.Name.toLocaleLowerCase().indexOf(filterBy)!==-1); } showEditProductForm(product:IProduct) { if(!product){ this.productForm=false; return; } this.editProductForm=true; //this.isNewForm=false; this.editedProduct=product; console.log(product); } showAddProductForm() { if(this.products.length) { this.newProduct={}; } this.productForm=true; this.isNewForm=true; } saveProduct(product:IProduct) { if(this.isNewForm) { this.products.push(product); this._productService.addProduct(product) .subscribe(product => { }); } this.productForm=false; } updateProduct(product:IProduct){ this._productService.updateProduct(this.editedProduct).subscribe(product=>{ }); this.editProductForm=false; this.editedProduct={}; } removeProduct(Id:number) { this._productService.deleteProduct(Id).subscribe(product=>{ this.products = this.products.filter(h => h !== product); console.log(product); }); } cancelEdits() { this.editedProduct={}; this.editProductForm=false; } ngOnInit(): void { this._productService.getProducts() .subscribe(res => { this.products = res; this.filteredProducts = this.products; }, error => this.errorMessage = <any>error); if(localStorage.getItem('userType')==='Sales' || localStorage.getItem('userType')==='Admin' ){ this.isShow=true; } } } <file_sep>import { Injectable } from '@angular/core'; import {HttpClient, HttpErrorResponse} from '@angular/common/http'; import {Response} from '@angular/http'; import {Observable} from 'rxjs/Observable'; import 'rxjs/add/observable/throw'; import 'rxjs/add/operator/catch'; import 'rxjs/add/operator/do'; import 'rxjs/add/operator/map'; import { RouteOutlet } from '../models/routeOutlet'; @Injectable() export class NotificationService { private notificationUrl= 'http://salesforcenew20180208102258.azurewebsites.net/api/Leave'; constructor(private http: HttpClient) { } getNotification():Observable<any>{ return this.http.get(this.notificationUrl) .map(response=>response); //.catch(this.handleError); } private handleError(err: HttpErrorResponse){ console.log('error prd'); console.log(err.message); return Observable.throw(err.message); } updateStatus(status:String,Id:number) { console.log(status,Id); return this.http.put('http://salesforcenew20180208102258.azurewebsites.net/api/Leave/'+Id,{params:{status:status}}); } }<file_sep>import { Injectable } from '@angular/core'; import {HttpClient, HttpErrorResponse} from '@angular/common/http'; import {Observable} from 'rxjs/Observable'; import 'rxjs/add/observable/throw'; import 'rxjs/add/operator/catch'; import 'rxjs/add/operator/do'; import { User } from '../models/user'; @Injectable() export class UserService { users: any[] = []; private userUrl= 'http://salesforcenew20180208102258.azurewebsites.net/api/Users'; constructor(private _http: HttpClient) { } getUsers(): Observable<any> { return this._http.get<User>(this.userUrl) .do(data => console.log('All: ' + JSON.stringify(data))) .catch(this.handleError); } getUser(Id: number): Observable<User> { return this.getUsers() .map((users: User[]) => users.find(p => p.Id === Id)); } addUser(user:User) { //console.log(user); return this._http.post<User>(this.userUrl, user); } updateUser(user:User) { console.log(user); return this._http.put<User>(this.userUrl,user); } deleteUser(Id:number) { return this._http.delete('http://salesforcenew20180208102258.azurewebsites.net/api/Users/'+Id); } private handleError(err: HttpErrorResponse){ console.log(err.message); return Observable.throw(err.message); } } <file_sep>import { Component, OnInit } from '@angular/core'; import { VanService } from '../services/van.service'; import { Van } from '../models/van'; @Component({ selector: 'app-van', templateUrl: './van.component.html', styleUrls: ['./van.component.css'] }) export class VanComponent implements OnInit { errorMessage: string; vans:Van[]; editedVan:any={}; vanForm:boolean=false; editVanForm:boolean=false; newVan:any={}; isNewForm:boolean; constructor(private vanService:VanService) { } ngOnInit() { this.vanService.getVans() .subscribe(res => { this.vans = res; }, error => this.errorMessage = <any>error); } showAddVanForm() { if(this.vans.length) { this.newVan={}; } this.vanForm=true; this.isNewForm=true; } showEditVanForm(van:Van) { if(!van){ this.vanForm=false; return; } this.editVanForm=true; //this.isNewForm=false; this.editedVan=van; } saveVan(van:Van) { if(this.isNewForm) { this.vans.push(van); this.vanService.addVan(van) .subscribe(route => { }); } this.vanForm=false; } } <file_sep>import { Component, OnInit } from '@angular/core'; import {ActivatedRoute,Router} from '@angular/router'; import { RouteService } from '../services/route.service'; import { Route } from '../models/route'; @Component({ selector: 'app-route-detail', templateUrl: './route-detail.component.html', styleUrls: ['./route-detail.component.css'] }) export class RouteDetailComponent implements OnInit { route:Route; editedRoute:any={}; routeForm:boolean=false; editRouteForm:boolean=false; constructor(private _route:ActivatedRoute, private router:Router,private routeService:RouteService) { console.log(this._route.snapshot.paramMap.get('id')); } ngOnInit() { const param=+this._route.snapshot.paramMap.get('id'); if(param){ const id=+param; this.getRoute(id); } } getRoute(id:number) { this.routeService.getRoute(id).subscribe( res=>this.route=res, ); } showEditRouteForm(route:Route) { if(!route){ this.routeForm=false; return; } this.editRouteForm=true; //this.isNewForm=false; this.editedRoute=route; } updateRoute(route:Route){ this.routeService.updateRoute(this.editedRoute).subscribe(route=>{ }); this.editRouteForm=false; this.editedRoute={}; } onBack() :void { this.router.navigate(['/routes']); } } <file_sep>import { Component, OnInit } from '@angular/core'; import { LoginService } from '../services/login.service'; import { error } from 'util'; import { Router, ActivatedRoute } from '@angular/router'; @Component({ selector: 'app-login', templateUrl: './login.component.html', styleUrls: ['./login.component.css'] }) export class LoginComponent { errorMessage: string; loginData: any= { }; isLoggedIn : boolean; userId: string; userType: string; isAdmin:boolean; isSales:boolean; isFinance:boolean; isHR:boolean; token:string; constructor(private loginService: LoginService, private route: ActivatedRoute, private router: Router) { } post() { this.isLoggedIn=false; console.log(this.loginData); this.loginService.loginUser(this.loginData).subscribe(res => { console.log(res); if(res.status=='Success'){ alert('Login Successfull'); console.log('success'); this.userId = res.Id; if(res.UserType === 'Admin') this.userType = 'Admin'; else if(res.UserType === 'Finance') this.userType = 'Finance'; else if(res.UserType === 'HR') this.userType = 'HR'; else if(res.UserType === 'Sales') this.userType = 'Sales'; this.token=res.Token; console.log(this.userId,this.userType); localStorage.setItem('isLoggedIn','true'); localStorage.setItem('userId',this.userId); localStorage.setItem('userType',this.userType); localStorage.setItem('token',this.token); console.log(localStorage.getItem('isLoggedIn')); console.log(localStorage.getItem('token')); this.router.navigate(['/home']); } else{ alert('Invalid username or password'); console.log('failed'); this.router.navigate(['/login']); } }, (error) => { console.log('Error'); }); } logOut() { localStorage.removeItem('currentUser'); this.isLoggedIn=false; this.router.navigate(['/login']); } } <file_sep>import { Injectable } from '@angular/core'; import {HttpClient, HttpErrorResponse} from '@angular/common/http'; import {Observable} from 'rxjs/Observable'; import 'rxjs/add/observable/throw'; import 'rxjs/add/operator/catch'; import 'rxjs/add/operator/do'; import { Van } from '../models/van'; @Injectable() export class VanService { vans: any[] = []; private vanUrl= 'http://salesforcenew20180208102258.azurewebsites.net/api/Van'; constructor(private http: HttpClient) { } getVans(): Observable<any> { return this.http.get<Van>(this.vanUrl) .do(data => console.log('All: ' + JSON.stringify(data))) } addVan(van:Van) { console.log(van); return this.http.post<Van>(this.vanUrl, van); } updateVan(van:Van) { console.log(van); return this.http.put<Van>(this.vanUrl,van); } private handleError(err: HttpErrorResponse){ console.log(err.message); return Observable.throw(err.message); } }<file_sep>import { Component, OnInit } from '@angular/core'; import {ActivatedRoute,Router} from '@angular/router'; import { UserService } from '../services/user.service'; import { User } from '../models/user'; @Component({ templateUrl: './user-detail.component.html', styleUrls: ['./user-detail.component.css'] }) export class UserDetailComponent implements OnInit { user:User; editedUser:any={}; userForm:boolean=false; editUserForm:boolean=false; constructor(private route:ActivatedRoute, private router:Router,private userService:UserService) { console.log(this.route.snapshot.paramMap.get('id')); } ngOnInit() { const param=+this.route.snapshot.paramMap.get('id'); if(param){ const id=+param; this.getUser(id); } } getUser(id:number) { this.userService.getUser(id).subscribe( res=>this.user=res, ); } showEditUserForm(user:User) { if(!user){ this.userForm=false; return; } this.editUserForm=true; //this.isNewForm=false; this.editedUser=user; } updateUser(user:User){ this.userService.updateUser(this.editedUser).subscribe(user=>{ }); this.editUserForm=false; this.editedUser={}; } onBack() :void { this.router.navigate(['/users']); } } <file_sep>export class Notification{ Id: number; StartingDate: string; EndingDate: string; Reason: string; status: string; UserId: number; }<file_sep>import { Component, OnInit } from '@angular/core'; import { UserService } from '../services/user.service'; import { User } from '../models/user'; @Component({ selector: 'app-users', templateUrl: './users.component.html', styleUrls: ['./users.component.css'] }) export class UsersComponent implements OnInit { errorMessage: string; users: User[]; newUser:any={}; userForm:boolean=false; isNewForm:boolean; editUserForm:boolean=false; editedUser:any={}; constructor(private userService:UserService) { } ngOnInit() { this.userService.getUsers() .subscribe(res => { this.users = res; }, error => this.errorMessage = <any>error); } showAddUserForm() { if(this.users.length) { this.newUser={}; } this.userForm=true; this.isNewForm=true; } showEditUserForm(user:User) { if(!user){ this.userForm=false; return; } this.editUserForm=true; //this.isNewForm=false; this.editedUser=user; console.log(user); } removeUser(Id:number) { this.userService.deleteUser(Id).subscribe(user=>{ this.users = this.users.filter(h => h !== user); console.log(user); }); } saveUser(user:User) { if(this.isNewForm) { this.users.push(user); this.userService.addUser(user) .subscribe(user => { }); } this.userForm=false; } } <file_sep>import { Component } from '@angular/core'; import { RegisterService } from '../services/register.service'; import { Router } from '@angular/router'; import {FormGroup,FormControl,Validators} from '@angular/forms'; @Component({ selector: 'app-register', templateUrl: './register.component.html', styleUrls: ['./register.component.css'] }) export class RegisterComponent { errorMessage: string; registerData:any={ }; form; constructor(private registerService: RegisterService,private router: Router) { } post(){ console.log(this.registerData) this.registerService.sendUserRegistration(this.registerData).subscribe(res => { }, error => this.errorMessage = <any>error); this.router.navigate(['/home']); } ngOnInit() { } } <file_sep>export class Expense{ Id: number; Date: string; Description: string; Amount: number; status: string; UserId: number }<file_sep>import { Injectable } from '@angular/core'; import {HttpClient, HttpErrorResponse} from '@angular/common/http'; import {Observable} from 'rxjs/Observable'; import 'rxjs/add/observable/throw'; import 'rxjs/add/operator/catch'; import 'rxjs/add/operator/do'; import { Outlet } from '../models/outlet'; @Injectable() export class OutletService { outlets: any[] ; private OutletUrl= 'http://salesforcenew20180208102258.azurewebsites.net/api/Outlets'; constructor(private _http: HttpClient) { } getOutlets(): Observable<any> { return this._http.get<Outlet>(this.OutletUrl) .do(data => console.log('All: ' + JSON.stringify(data))) .catch(this.handleError); } addOutlet(outlet:Outlet) { console.log(outlet); return this._http.post<Outlet>(this.OutletUrl, outlet); } updateOutlet(outlet:Outlet) { console.log(outlet); return this._http.put<Outlet>(this.OutletUrl,outlet); } deleteOutlet(Id:number) { return this._http.delete('http://salesforcenew20180208102258.azurewebsites.net/api/Outlets/'+Id); } private handleError(err: HttpErrorResponse){ console.log('error in outlet service'); console.log(err.message); return Observable.throw(err.message); } } <file_sep>import { Component, OnInit } from '@angular/core'; import { NotificationService } from '../services/notification.service'; import { Notification } from '../models/notification'; @Component({ selector: 'app-notify', templateUrl: './notify.component.html', styleUrls: ['./notify.component.css'] }) export class NotifyComponent implements OnInit { private notifications: Notification[]; constructor(private notificationService:NotificationService) { } ngOnInit() { this.notificationService.getNotification().subscribe(data=>{ this.notifications=data; }); } updateStatus(Id:number,status:string) { /*this.notificationService.updateStatus("confirm").subscribe( notification=> { console.log(notification); } );*/ } } <file_sep>import { Injectable } from '@angular/core'; import {HttpClient, HttpErrorResponse} from '@angular/common/http'; import {Observable} from 'rxjs/Observable'; import 'rxjs/add/observable/throw'; import 'rxjs/add/operator/catch'; import 'rxjs/add/operator/do'; import { Route } from '../models/route'; @Injectable() export class RouteService { routes: any[] = []; private routeUrl= 'http://salesforcenew20180208102258.azurewebsites.net/api/Route'; constructor(private http: HttpClient) { } getRoutes(): Observable<any> { return this.http.get<Route>(this.routeUrl) .do(data => console.log('All: ' + JSON.stringify(data))) .catch(this.handleError); } getRoute(Id: number): Observable<Route> { return this.getRoutes() .map((routes: Route[]) => routes.find(p => p.Id === Id)); } addRoute(route:Route) { console.log(route); return this.http.post<Route>(this.routeUrl, route); } updateRoute(route:Route) { console.log(route); return this.http.put<Route>(this.routeUrl,route); } deleteRoute(Id:number) { return this.http.delete('http://salesforcenew20180208102258.azurewebsites.net/api/Route/'+Id); } getLocations(id: number): Observable<any> { return this.http.get('http://salesforcenew20180208102258.azurewebsites.net/api/OutletsOfTheRoute/'+id) .map(response => response); } private handleError(err: HttpErrorResponse){ console.log(err.message); return Observable.throw(err.message); } } <file_sep>import { Component, OnInit } from '@angular/core'; import { UserService } from '../services/user.service'; import { User } from '../models/user'; import { RouteService } from '../services/route.service'; import { Route } from '../models/route'; import { Van } from '../models/van'; import { VanService } from '../services/van.service'; import { RouteOutlet } from '../models/routeOutlet'; import { RouteOutletService } from '../services/routeOutlet.service'; import { IProduct } from '../models/product'; import { ProductService } from '../services/product.service'; import { FormsModule } from '@angular/forms'; @Component({ selector: 'app-user-route', templateUrl: './user-route.component.html', styleUrls: ['./user-route.component.css'] }) export class UserRouteComponent implements OnInit { errorMessage: string; users: User[]; routes:Route[]; vans:Van[]; products:IProduct[]; userRoutedata:any={ }; constructor(private userService:UserService,private routeService:RouteService,private vanService:VanService,private routeOutletService:RouteOutletService,private productService:ProductService) { } addFieldValue() { this.products.push(this.userRoutedata) this.userRoutedata = {}; } ngOnInit() { this.userService.getUsers() .subscribe(res => { this.users = res; }), this.routeService.getRoutes() .subscribe(res => { this.routes = res; }), this.vanService.getVans() .subscribe(res => { this.vans = res; }), this.productService.getProducts() .subscribe(res => { this.products = res; }), error => this.errorMessage = <any>error } post(){ console.log(this.userRoutedata) this.routeOutletService.sendUserRoute(this.userRoutedata).subscribe(res => { }, error => this.errorMessage = <any>error); } } <file_sep>import { Component, OnInit } from '@angular/core'; import { ExpenseService } from '../services/expense.service'; import { Expense } from '../models/expense'; @Component({ selector: 'app-expenses', templateUrl: './expenses.component.html', styleUrls: ['./expenses.component.css'] }) export class ExpensesComponent implements OnInit { private expenses: Expense[]; constructor(private expenseService:ExpenseService) { } ngOnInit() { this.expenseService.getExpense().subscribe(data=>{ this.expenses=data; }); } updateStatus(Id:number) { console.log(Id); this.expenseService.updateStatus("Confirmed",Id).subscribe( expense=> { console.log(expense); } ); } updateCancel(Id:number) { console.log(Id); this.expenseService.updateStatus("Rejected",Id).subscribe( notification=> { console.log(notification); } ); } } <file_sep>export interface RouteOutlet { UserId:number; RouteId:number; VanId:number; Date1:DateTimeFormat; l1: IProduct[]; } export interface IProduct{ Id: number; Quantity: number; } <file_sep>import { Component,OnInit,Inject } from '@angular/core'; import { ProductService } from './services/product.service'; import { RegisterService } from './services/register.service'; import { LoginService } from './services/login.service'; import { OutletService } from './services/outlet.service'; import { UserService } from './services/user.service'; import { RouteService } from './services/route.service'; import { VanService } from './services/van.service'; import { RouteOutletService } from './services/routeOutlet.service'; import { NotificationService } from './services/notification.service'; import { Notification } from './models/notification'; import { ExpenseService } from './services/expense.service'; import { AuthInterceptorService } from './services/authInterceptor.service'; import { MatDialog,MatDialogRef,MAT_DIALOG_DATA } from '@angular/material'; import { Observable } from 'rxjs'; import {HttpClientModule,HTTP_INTERCEPTORS} from '@angular/common/http'; //import {routerTransition} from './' @Component({ selector: 'app-notify', templateUrl: './notify.component.html', //styleUrls: ['./notify.component.css'] }) export class NotifyComponent implements OnInit { private notifications: Notification[]; constructor(private notificationService:NotificationService) { } ngOnInit() { this.notificationService.getNotification().subscribe(data=>{ this.notifications=data; console.log(this.notifications) }); } updateStatus(Id:number) { console.log(Id); this.notificationService.updateStatus("Confirmed",Id).subscribe( notification=> { console.log(notification); } ); } updateCancel(Id:number) { console.log(Id); this.notificationService.updateStatus("Rejected",Id).subscribe( notification=> { console.log(notification); } ); } } @Component({ selector: 'pm-root', templateUrl:'./app.component.html', styleUrls: ['./app.component.css'] //animations:[routerTransition()] , providers:[ ProductService ,RegisterService,LoginService,OutletService,UserService,RouteService,VanService,RouteOutletService,NotificationService,ExpenseService ,{provide:HTTP_INTERCEPTORS,useClass:AuthInterceptorService,multi:true}] }) export class AppComponent implements OnInit{ pageTitle: string = 'SFA-Products'; notifications: Notification[]; notificationsLength:number; constructor(private notificationService:NotificationService,private loginService:LoginService,public dialog:MatDialog ,@Inject(MAT_DIALOG_DATA) public data:any){ } ngOnInit() { Observable.interval(10000) .takeWhile(() => true) .subscribe(i => { this.notificationService.getNotification().subscribe(data=>{ this.notifications=data; this.notificationsLength=this.notifications.length; console.log(this.notifications) }); }); } showNotifications(){ this.dialog.open(NotifyComponent,{ data:{notifications:this.notifications}, width:'550px' }); } logOut() { localStorage.removeItem('isLoggedIn'); localStorage.removeItem('userType'); localStorage.removeItem('isShowNav'); localStorage.removeItem('token'); } } <file_sep>import { Injectable } from '@angular/core'; import {HttpClient, HttpErrorResponse} from '@angular/common/http'; import {Observable} from 'rxjs/Observable'; import 'rxjs/add/observable/throw'; import 'rxjs/add/operator/map'; import 'rxjs/add/operator/catch'; import 'rxjs/add/operator/do'; import { User } from '../models/user'; import {RegisteredUser} from '../models/registereduser'; @Injectable() export class LoginService { currentUser:User; private userUrl= 'http://salesforcenew20180208102258.azurewebsites.net/api/Login'; constructor(private http: HttpClient) { } loginUser(loginData: RegisteredUser): Observable<any> { return this.http.get<any>(this.userUrl + '?Username=' + loginData.Username + '&password=' + <PASSWORD>) .do(response => JSON.stringify(response) ) .catch(this.handleError); } getToken(){ return localStorage.getItem('token'); } logout(): void { //this.currentUser = ; } private handleError(err: HttpErrorResponse){ console.log('error in login'); console.log(err.message); return Observable.throw(err.message); } } <file_sep>import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import {FormsModule} from '@angular/forms'; import { AppComponent,NotifyComponent } from './app.component'; import { HttpModule } from '@angular/http'; import {HttpClientModule,HTTP_INTERCEPTORS} from '@angular/common/http'; import {RouterModule} from '@angular/router'; import {BsDatepickerModule} from 'ngx-bootstrap/datepicker'; import {MatDialogModule,MatDialogRef,MAT_DIALOG_DATA} from '@angular/material'; import { AgmCoreModule } from '@agm/core'; import { BrowserAnimationsModule } from '@angular/platform-browser/animations'; import { PushNotificationModule } from 'ng-push-notification'; import { CarouselModule } from 'ngx-bootstrap/carousel'; import { NotificationService } from './services/notification.service'; import { ProductListComponent } from './products/product-list.component'; import { WelcomeComponent } from './home/welcome.component'; import { LoginComponent } from './login/login.component'; import { RegisterComponent } from './register/register.component'; import { OutletComponent } from './outlet/outlet.component'; import { UsersComponent } from './users/users.component'; import { UserDetailComponent } from './user-detail/user-detail.component'; import { DashboardComponent } from './dashboard/dashboard.component'; import { RouteComponent, RootMapComponent } from './route/route.component'; import { RouteDetailComponent } from './route-detail/route-detail.component'; import { UserRouteComponent } from './user-route/user-route.component'; import { VanComponent } from './van/van.component'; import { AuthGuard,AdminHrGuard,AdminGuard,AdminFinanceGuard} from './guard/auth.guard'; import { ExpensesComponent } from './expenses/expenses.component'; //import { NotifyComponent } from './notify/notify.component'; @NgModule({ declarations: [ AppComponent, ProductListComponent, WelcomeComponent, LoginComponent, RegisterComponent, OutletComponent, UsersComponent, UserDetailComponent, DashboardComponent, RouteComponent, RootMapComponent, RouteDetailComponent, UserRouteComponent, VanComponent, NotifyComponent, ExpensesComponent ], imports: [ BrowserAnimationsModule, BrowserModule, FormsModule, HttpClientModule, HttpModule, MatDialogModule, CarouselModule.forRoot(), BsDatepickerModule.forRoot(), AgmCoreModule.forRoot({ apiKey: '<KEY>' }), RouterModule.forRoot([ {path: 'home', component: WelcomeComponent,canActivate:[AuthGuard]}, {path: 'products', component: ProductListComponent,canActivate:[AuthGuard]}, { path: 'routes/:id', component: RouteDetailComponent }, { path: 'routes', component: RouteComponent ,canActivate:[AuthGuard], children:[ { path: 'routes/user-route', component: UserRouteComponent }, { path: 'routes/van', component: VanComponent } ]}, {path: 'outlet', component: OutletComponent,canActivate:[AuthGuard]}, {path: 'users/:id', component: UserDetailComponent}, {path: 'users', component: UsersComponent, canActivate:[AdminHrGuard]}, {path: 'expenses', component: ExpensesComponent,canActivate:[AdminFinanceGuard]}, {path: 'app', component: NotifyComponent ,canActivate:[AdminHrGuard]}, {path: 'register', component: RegisterComponent,canActivate:[AdminGuard]}, {path: 'login', component: LoginComponent}, {path: '', redirectTo: 'login', pathMatch: 'full'}, {path: '**', redirectTo: 'login', pathMatch: 'full'} ]) ], providers: [ NotificationService, {provide:MAT_DIALOG_DATA,useValue:{}}, {provide:MatDialogRef,useValue:{}}, AuthGuard, AdminHrGuard, AdminGuard, AdminFinanceGuard ], entryComponents:[ NotifyComponent, RootMapComponent ], bootstrap: [AppComponent] }) export class AppModule { } <file_sep>export class Van { Id:number; VanType: string; RegistrationNo: string; }<file_sep>import { Component, OnInit, Inject } from '@angular/core'; import { MatDialog, MatDialogRef, MAT_DIALOG_DATA } from '@angular/material'; import { RouteService } from '../services/route.service'; import { Route } from '../models/route'; import { UserService } from '../services/user.service'; import { User } from '../models/user'; import { Location } from './location'; import { MouseEvent } from '@agm/core'; import { google } from '@agm/core/services/google-maps-types'; @Component({ selector: 'app-root-map', templateUrl: './app-root-map.component.html', styleUrls: [ './app-root-map.component.css' ] }) export class RootMapComponent implements OnInit { locations: Location[]; constructor( public dialogRef: MatDialogRef<RootMapComponent>, @Inject(MAT_DIALOG_DATA) public data: any ){} ngOnInit() { this.locations = this.data.locations; } end: any; // google maps zoom level zoom: number = 14; // initial center position for the map lat: number = 6.796443; lng: number = 79.900668; clickedMarker(label: string, index: number) { //console.log(clicked the marker: ${label || index}) } /*markers: marker[] = [ { lat: 6.797128, lng: 79.901893, label: 'FIT', draggable: false }, { lat: 6.795911, lng: 79.887597, label: 'KZONE', draggable: false }, { lat: 6.82125, lng: 79.891498, label: 'Rathmalana Air Port', draggable: false } ]*/ } // just an interface for type safety. interface marker { lat: number; lng: number; label?: string; draggable: boolean; } @Component({ selector: 'app-route', templateUrl: './route.component.html', styleUrls: ['./route.component.css'] }) export class RouteComponent implements OnInit { errorMessage: string; routes: Route[]; editedRoute:any={}; routeForm:boolean=false; editRouteForm:boolean=false; newRoute:any={}; isNewForm:boolean; isShow:boolean=false; locations: Location[]; constructor( private routeService:RouteService, public dialog: MatDialog ) { } ngOnInit() { this.routeService.getRoutes().subscribe(res => { this.routes = res; }, error => this.errorMessage = <any>error ); if(localStorage.getItem('userType')==='Sales' || localStorage.getItem('userType')==='Admin' ){ this.isShow=true; } } showAddRouteForm() { if(this.routes.length) { this.newRoute={}; } this.routeForm=true; this.isNewForm=true; } showEditRouteForm(route:Route) { if(!route){ this.routeForm=false; return; } this.editRouteForm=true; //this.isNewForm=false; this.editedRoute=route; } saveRoute(route:Route) { if(this.isNewForm) { this.routes.push(route); this.routeService.addRoute(route) .subscribe(route => {}); } this.routeForm=false; } updateRoute(route:Route){ this.routeService.updateRoute(this.editedRoute).subscribe(route=>{ }); this.editRouteForm=false; this.editedRoute={}; } removeRoute(Id:number) { this.routeService.deleteRoute(Id).subscribe(route=>{ this.routes = this.routes.filter(h => h !== route); console.log(route); }); } cancelEdits() { this.editedRoute={}; this.editRouteForm=false; } showMap(id: number) { this.routeService.getLocations(id).subscribe(data => { //console.log(data); this.locations = data; //console.log(this.locations); this.dialog.open(RootMapComponent, { data: { locations: this.locations }, width: '800px' }); }, (error) => {console.log(error)} ); } } <file_sep>import { Injectable } from '@angular/core'; import {HttpClient, HttpErrorResponse} from '@angular/common/http'; import {Observable} from 'rxjs/Observable'; import 'rxjs/add/observable/throw'; import 'rxjs/add/operator/catch'; import 'rxjs/add/operator/do'; import { RouteOutlet } from '../models/routeOutlet'; @Injectable() export class RouteOutletService { private userRouteUrl= 'http://salesforcenew20180208102258.azurewebsites.net/api/RoutesOutlets'; constructor(private http: HttpClient) { } sendUserRoute(userRoutedata:RouteOutlet):Observable<any>{ return this.http.post(this.userRouteUrl,userRoutedata); } }<file_sep>export interface Outlet{ Id: number; Name: string; ContactNo: string; Barcode: string; Longitude: number; Latitude: number; OwnerName: string; Email: string; Status:string; RouteId:string; } <file_sep>import { Injectable } from '@angular/core'; import {HttpClient, HttpErrorResponse} from '@angular/common/http'; import {Observable} from 'rxjs/Observable'; import 'rxjs/add/observable/throw'; import 'rxjs/add/operator/catch'; import 'rxjs/add/operator/do'; import { User } from '../models/user'; @Injectable() export class RegisterService { private userUrl= 'http://salesforcenew20180208102258.azurewebsites.net/api/Users'; constructor(private http: HttpClient) { } sendUserRegistration(registerData:User):Observable<any>{ return this.http.post(this.userUrl,registerData); } }<file_sep>import { Component, OnInit } from '@angular/core'; import { OutletService } from '../services/outlet.service'; import { Outlet } from '../models/outlet'; import { RouteService } from '../services/route.service'; import { Route } from '../models/route'; @Component({ selector: 'app-outlet', templateUrl: './outlet.component.html', styleUrls: ['./outlet.component.css'] }) export class OutletComponent implements OnInit { pageTitle= 'Outlet List'; errorMessage: string; private outlets: Outlet[]; newOutlet:any={}; outletForm:boolean=false; editOutletForm:boolean=false; isNewForm:boolean; editedOutlet:any={}; isShow:boolean=false; _listFilter:string; routes:Route[]; get listFilter():string{ return this._listFilter; } set listFilter(value:string){ this._listFilter=value; this.filteredOutlets=this.listFilter?this.performFilter(this.listFilter):this.outlets; } filteredOutlets:Outlet[]; constructor(private outletService:OutletService,private routeService:RouteService) { // this.outletService.getOutlets() // .subscribe(res => { this.outlets = res; }, // error => this.errorMessage = <any>error); } performFilter(filterBy:string):Outlet[]{ filterBy=filterBy.toLocaleLowerCase(); return this.outlets.filter((outlet:Outlet)=> outlet.Name.toLocaleLowerCase().indexOf(filterBy)!==-1); } showEditOutletForm(outlet:Outlet) { if(!outlet){ this.outletForm=false; return; } this.editOutletForm=true; //this.isNewForm=false; this.editedOutlet=outlet; } showAddOutletForm() { if(this.outlets.length) { this.newOutlet={}; } this.outletForm=true; this.isNewForm=true; } saveOutlet(outlet:Outlet) { if(this.isNewForm) { this.outlets.push(outlet); this.outletService.addOutlet(outlet) .subscribe(outlet => { }); } this.outletForm=false; } updateOutlet(outlet:Outlet){ this.outletService.updateOutlet(this.editedOutlet).subscribe(outlet=>{ }); this.editOutletForm=false; this.editedOutlet={}; } removeOutlet(Id:number) { //this.outlets = this.outlets.filter(h => h !== outlet); this.outletService.deleteOutlet(Id).subscribe(outlet=>{ this.outlets = this.outlets.filter(h => h !== outlet); console.log(outlet); }); } cancelEdits() { this.editedOutlet={}; this.editOutletForm=false; } ngOnInit() { this.outletService.getOutlets() .subscribe(res => { this.outlets = res; this.filteredOutlets = this.outlets; }, error => this.errorMessage = <any>error); this.routeService.getRoutes() .subscribe(res => { this.routes = res; }); if(localStorage.getItem('userType')==='Sales' || localStorage.getItem('userType')==='Admin' ){ this.isShow=true; } } }
94ee1a87fdbd9cb4b07b7e6e5169f05c35684461
[ "TypeScript" ]
29
TypeScript
Tharindri/SalesForce
09f073396d04ab70a90af12258421ad064cc0444
ad88843651b1f218ce43732b4c54f91d7220a3a9
refs/heads/master
<repo_name>burhanshakir/weather-app-ios<file_sep>/WeatherApp/Services/CurrentWeatherService.swift // // CurrentWeatherService.swift // WeatherApp // // Created by <NAME> on 17/01/18. // Copyright © 2018 <NAME>. All rights reserved. // import Foundation import Alamofire import SwiftyJSON class CurrentWeatherService{ static let instance = CurrentWeatherService() var currentWeather = CurrentWeather() func getCurrentWeather(url:String!, completion : @escaping CompletionHandler) { Alamofire.request(url, method: .get).validate().responseJSON { response in switch response.result { case .success(let value): let json = JSON(value) let city = json["name"].stringValue let date = json["dt"].intValue let weather = json["weather"][0]["main"].stringValue let temperature = json["main"]["temp"].doubleValue let currentWeather = CurrentWeather(date: date, city: city, temperature: temperature, weather: weather) self.currentWeather = currentWeather completion(true) case .failure(let error): print(error) completion(false) } } } } <file_sep>/WeatherApp/View/ForecastCell.swift // // ForecastCell.swift // WeatherApp // // Created by <NAME> on 17/01/18. // Copyright © 2018 <NAME>. All rights reserved. // import UIKit class ForecastCell: UITableViewCell { @IBOutlet weak var dayLabel: UILabel! @IBOutlet weak var minTempLabel: UILabel! @IBOutlet weak var maxTempLabel: UILabel! @IBOutlet weak var weatherLabel: UILabel! @IBOutlet weak var weatherImage: UIImageView! func updateViews(forecast: Forecast) { let weather = forecast.weather ?? "Clear" weatherImage.image = UIImage(named: weather) weatherLabel.text = forecast.weather ?? "Clear" minTempLabel.text = String(getTempInDegrees(temp: forecast.minTemperature)) maxTempLabel.text = String(getTempInDegrees(temp: forecast.maxTemperature)) dayLabel.text = getDay(dt: forecast.date) } } <file_sep>/WeatherApp/Services/ForecastWeatherService.swift // // ForecastWeatherService.swift // WeatherApp // // Created by <NAME> on 17/01/18. // Copyright © 2018 <NAME>. All rights reserved. // import Foundation import Alamofire import SwiftyJSON class ForecastWeatherService{ static let instance = ForecastWeatherService() var forecasts = [Forecast]() func getForecast(url : String!, completion: @escaping CompletionHandler){ Alamofire.request(url, method: .get).validate().responseJSON { response in switch response.result { case .success(let value): self.forecasts.removeAll() let json = JSON(value) let city = json["city"]["name"].stringValue if let forecastList = json["list"].array{ for item in forecastList{ let date = item["dt"].intValue let weather = item["weather"][0]["main"].stringValue var minTemp = 0.0 var maxTemp = 0.0 var pressure = 0.0 let description = item["weather"][0]["description"].stringValue var humidity = 0.0 var wind = 0.0 if item["temp"].count > 0{ minTemp = item["temp"]["min"].doubleValue maxTemp = item["temp"]["max"].doubleValue pressure = item["pressure"].doubleValue humidity = item["humidity"].doubleValue wind = item["speed"].doubleValue } else{ minTemp = item["main"]["temp_min"].doubleValue maxTemp = item["main"]["temp_max"].doubleValue pressure = item["main"]["pressure"].doubleValue humidity = item["main"]["humidity"].doubleValue wind = item["wind"]["speed"].doubleValue } let forecast = Forecast(date: date, minTemperature: minTemp, maxTemperature: maxTemp, weather: weather, description: description, pressure: pressure, humidity: humidity, wind: wind, city:city) self.forecasts.append(forecast) } } completion(true) case .failure(let error): print(error) completion(false) } } } } <file_sep>/WeatherApp/Controller/DetailWeatherVC.swift // // DetailWeatherVC.swift // WeatherApp // // Created by <NAME> on 20/01/18. // Copyright © 2018 <NAME>. All rights reserved. // import UIKit class DetailWeatherVC: UIViewController { @IBOutlet weak var cityLabel: UILabel! @IBOutlet weak var dateLabel: UILabel! @IBOutlet weak var descriptionLabel: UILabel! @IBOutlet weak var weatherImage: UIImageView! @IBOutlet weak var temperatureLabel: UILabel! @IBOutlet weak var humidityLable: UILabel! @IBOutlet weak var pressureLabel: UILabel! @IBOutlet weak var windLabel: UILabel! public var forecast: Forecast! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. updateViews() } func updateViews(){ cityLabel.text = forecast.city dateLabel.text = getDate(dt: forecast.date) descriptionLabel.text = forecast.description weatherImage.image = UIImage(named: forecast.weather) temperatureLabel.text = "\(String(getTempInDegrees(temp: forecast.minTemperature))) C" humidityLable.text = "\(String(forecast.humidity))%" pressureLabel.text = "\(String(format: "%.0f",forecast.pressure))hPa" windLabel.text = "\(String(format: "%.2f",forecast.wind * 3.6))Kmh" } } <file_sep>/WeatherAppTests/WeatherAppTests.swift // // WeatherAppTests.swift // WeatherAppTests // // Created by <NAME> on 18/01/18. // Copyright © 2018 <NAME>. All rights reserved. // import XCTest class WeatherAppTests: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testExample() { // This is an example of a functional test case. // Use XCTAssert and related functions to verify your tests produce the correct results. } func testPerformanceExample() { // This is an example of a performance test case. self.measure { // Put the code you want to measure the time of here. } } func testTempInDegrees(){ XCTAssert(getTempInDegrees(temp: 273.15) == 0.0) XCTAssert(getTempInDegrees(temp: 287.35 ) == 14.0) XCTAssert(getTempInDegrees(temp: 288.05 ) == 15.0) } func testGetDate(){ // XCTAssert(getDate(dt: 1516319385) == "Today, January 18, 2018") //will fail if tested on another date XCTAssert(getDate(dt: 1485741600) == "Monday, January 30, 2017") } func testGetDay(){ XCTAssert(getDay(dt: 1486519200) == "Wednesday") XCTAssert(getDay(dt: 820886400) == "Saturday") } } <file_sep>/WeatherApp/Utilities/Constants.swift // // Constants.swift // WeatherApp // // Created by <NAME> on 17/01/18. // Copyright © 2018 <NAME>. All rights reserved. // import Foundation typealias CompletionHandler = (_ Success : Bool) -> () // URL Constants let BASE_URL = "http://samples.openweathermap.org/data/2.5" let DYNAMIC_LOCATION_URL = "http://api.openweathermap.org/data/2.5" let WEATHER_PARAMETERS = "?lat=22.5726&lon=88.3639&appid=khwbacqbjerov" let FORECAST_PARAMETERS = "?lat=37.785834&lon=62.66&cnt=10&appid=khwbacqbjerov" let APP_ID = "ab7a26d0ad2e5bd4356c78fdc3eed914" let CURRENT_WEATHER_URL = "\(BASE_URL)/weather\(WEATHER_PARAMETERS)" let FORECAST_URL = "\(BASE_URL)/forecast/daily\(FORECAST_PARAMETERS)" let GOOGLE_API_KEY = "<KEY>" func getTempInDegrees(temp : Double) -> Double{ let celsius = round((temp - 273.15)*10/10) return celsius } func getDate(dt:Int) -> String{ let date = Date(timeIntervalSince1970: TimeInterval(dt)) let todaysDate = Date(timeIntervalSince1970:TimeInterval(NSDate().timeIntervalSince1970)) let dateFormatter = DateFormatter() dateFormatter.timeZone = TimeZone(abbreviation: "GMT") //Set timezone that you want dateFormatter.locale = NSLocale.current dateFormatter.dateFormat = "MMMM d, yyyy" //Specify your format that you want let strInputDate = dateFormatter.string(from: date) let strCurrentDate = dateFormatter.string(from: todaysDate) var result = "" if(strInputDate.elementsEqual(strCurrentDate)){ // Printing Today if todays date is equal to weather date result = "Today, \(strInputDate)" } else{ dateFormatter.dateFormat = "EEEE, MMMM d, yyyy" result = dateFormatter.string(from: date) } return result } func getDay(dt:Int) -> String{ let date = Date(timeIntervalSince1970: TimeInterval(dt)) let dateFormatter = DateFormatter() dateFormatter.timeZone = TimeZone(abbreviation: "GMT") dateFormatter.locale = NSLocale.current dateFormatter.dateFormat = "EEEE" let strDate = dateFormatter.string(from: date) return strDate } <file_sep>/README.md # weather-app-ios ![alt text](http://thescorekeeper.gwiddle.co.uk/weatherapp/1.png) ![alt text](http://thescorekeeper.gwiddle.co.uk/weatherapp/2.png) ![alt text](http://thescorekeeper.gwiddle.co.uk/weatherapp/3.png) ![alt text](http://thescorekeeper.gwiddle.co.uk/weatherapp/4.png) <file_sep>/WeatherApp/Model/CurrentWeather.swift // // CurrentWeather.swift // WeatherApp // // Created by <NAME> on 17/01/18. // Copyright © 2018 <NAME>. All rights reserved. // import Foundation struct CurrentWeather{ public private(set) var date: Int! public private(set) var city: String! public private(set) var temperature: Double! public private(set) var weather: String! } <file_sep>/WeatherApp/Model/Forecast.swift // // Forecast.swift // WeatherApp // // Created by <NAME> on 17/01/18. // Copyright © 2018 <NAME>. All rights reserved. // import Foundation struct Forecast{ public private(set) var date: Int! public private(set) var minTemperature: Double! public private(set) var maxTemperature: Double! public private(set) var weather: String! public private(set) var description: String! public private(set) var pressure: Double! public private(set) var humidity: Double! public private(set) var wind: Double! public private(set) var city: String! } <file_sep>/WeatherApp/Controller/CurrentWeatherVC.swift // // CurrentWeatherVC.swift // WeatherApp // // Created by <NAME> on 15/01/18. // Copyright © 2018 <NAME>. All rights reserved. // import UIKit import GooglePlaces class CurrentWeatherVC: UIViewController,UITableViewDataSource, UITableViewDelegate, GMSAutocompleteResultsViewControllerDelegate { @IBOutlet weak var dateLabel: UILabel! @IBOutlet weak var tempLabel: UILabel! @IBOutlet weak var cityLabel: UILabel! @IBOutlet weak var weatherLabel: UILabel! @IBOutlet weak var weatherImage: UIImageView! @IBOutlet weak var forecastTable: UITableView! let currentWeatherService = CurrentWeatherService.instance let forecastService = ForecastWeatherService.instance var resultsViewController: GMSAutocompleteResultsViewController? var searchController: UISearchController? var resultView: UITextView? var weatherURL = CURRENT_WEATHER_URL var forecastURL = FORECAST_URL override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. initGooglePlacesSearch() forecastTable.dataSource = self forecastTable.delegate = self forecastTable.rowHeight = 150.0 getData(weatherURL : weatherURL, forecastURL : forecastURL) } // Service functions func getData(weatherURL : String, forecastURL : String ){ currentWeatherService.getCurrentWeather(url: weatherURL){(success) in let currentWeather = CurrentWeatherService.instance.currentWeather self.updateViews(currentWeather: currentWeather) } forecastService.getForecast(url: forecastURL) { (success) in self.forecastTable.reloadData() } } func updateViews(currentWeather : CurrentWeather){ self.dateLabel.text = getDate(dt:currentWeather.date) self.tempLabel.text = String(getTempInDegrees(temp: currentWeather.temperature)) self.cityLabel.text = currentWeather.city self.weatherLabel.text = currentWeather.weather self.weatherImage.image = UIImage(named: currentWeather.weather) ?? UIImage(named: "Partially Cloudy") } // Table View Functions func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return forecastService.forecasts.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { if let forecastCell = tableView.dequeueReusableCell(withIdentifier: "ForecastCell") as? ForecastCell { let forecast = forecastService.forecasts[indexPath.row] forecastCell.updateViews(forecast: forecast) return forecastCell } else { return ForecastCell() } } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let forecast = ForecastWeatherService.instance.forecasts[indexPath.row] performSegue(withIdentifier: "DetailWeatherVC", sender: forecast) } // Google Places func initGooglePlacesSearch(){ resultsViewController = GMSAutocompleteResultsViewController() resultsViewController?.delegate = self searchController = UISearchController(searchResultsController: resultsViewController) searchController?.searchResultsUpdater = resultsViewController let filter = GMSAutocompleteFilter() filter.type = .city let subView = UIView(frame: CGRect(x: 0, y: 30.0, width: 350.0, height: 45.0)) subView.addSubview((searchController?.searchBar)!) view.addSubview(subView) searchController?.searchBar.sizeToFit() searchController?.hidesNavigationBarDuringPresentation = false definesPresentationContext = true } func resultsController(_ resultsController: GMSAutocompleteResultsViewController, didAutocompleteWith place: GMSPlace) { searchController?.isActive = false let lat = place.coordinate.latitude let lon = place.coordinate.longitude weatherURL = "\(DYNAMIC_LOCATION_URL)/weather?lat=\(lat)&lon=\(lon)&appid=\(APP_ID)" forecastURL = "\(DYNAMIC_LOCATION_URL)/forecast?lat=\(lat)&lon=\(lon)&cnt=10&appid=\(APP_ID)" getData(weatherURL: weatherURL, forecastURL: forecastURL) } func resultsController(_ resultsController: GMSAutocompleteResultsViewController, didFailAutocompleteWithError error: Error) { // TODO: handle the error. print("Error: ", error.localizedDescription) } // Turn the network activity indicator on and off again. func didRequestAutocompletePredictions(forResultsController resultsController: GMSAutocompleteResultsViewController) { UIApplication.shared.isNetworkActivityIndicatorVisible = true } func didUpdateAutocompletePredictions(forResultsController resultsController: GMSAutocompleteResultsViewController) { UIApplication.shared.isNetworkActivityIndicatorVisible = false } // Segue functions override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if let detailWeatherVC = segue.destination as? DetailWeatherVC{ detailWeatherVC.forecast = sender as! Forecast } } @IBAction func unwindFromDetailWeatherVC(unwindsegue: UIStoryboardSegue){ } }
3bdf7ea8e9fef5da515e1018c88813ad2432327b
[ "Swift", "Markdown" ]
10
Swift
burhanshakir/weather-app-ios
8908ebf7c18a49ce4ba36f49bf6d1d687ef34729
dde56b0e0301dfc1bf431e25d11812b7c8915853
refs/heads/master
<repo_name>pangqiqiang/trans_mongo_es<file_sep>/convert_shebao_info.rb #!/usr/bin/env ruby #-*-coding:utf-8-*- require 'rubygems' require 'json' require 'time' require './common_funcs' require './sqlite_treat' require './es_handler' file_input = "shebao_info.json" INDEX = "shebao_info" TYPE = "credit_data" SQLDB = MyDB.new("ids.db", "id_pairs") ES_DB = ELS.new("10.111.30.171:9200", "10.111.30.172:9200", "10.111.30.173:9200") BODY_QUEUE = [] File.open(file_input, "r") do |fin| fin.each do |line| output_hash = Hash.new line.chomp! input_hash = JSON.parse(line) output_hash["old_id"] = input_hash["_id"] #忽略身份证号不存在记录 next unless output_hash["old_id"].kind_of? String # 忽略社保记录为空记录 next unless input_hash["c_shebao_info"] and input_hash["c_shebao_info"].size > 0 output_hash["report_id"] = SQLDB.fetch_from_id(output_hash["old_id"]) output_hash["shebao_data"] = input_hash["c_shebao_info"].to_json # 增加字段识别jjd和第一风控 output_hash["system_name"] = "JJD" #写入es out_body = gen_store_doc_bodies(gen_id_body(INDEX, TYPE, output_hash["report_id"],output_hash), BODY_QUEUE, 1000) ES_DB.bulk_push(out_body) if out_body.is_a? Array end if BODY_QUEUE.size > 0 out_body = gen_remain_store_bodies(BODY_QUEUE) ES_DB.bulk_push(out_body) end end <file_sep>/convert_face_verify.rb #!/usr/bin/env ruby #-*-coding:utf-8-*- require 'rubygems' require './sqlite_treat' require './common_funcs' require 'json' require './es_handler' Encoding.default_external=Encoding.find("utf-8") file_input = "t_face_verify.txt" INDEX = "face_verify" TYPE = "credit_data" SQLDB = MyDB.new("ids.db", "id_pairs") ES_DB = ELS.new("10.111.30.171:9200", "10.111.30.172:9200", "10.111.30.173:9200") BODY_QUEUE = [] File.open(file_input) do |fin| fin.each do |line| next if fin.lineno == 1 temp = {} line.chomp! row = line.split("\t") temp["old_id"] = row[0] temp["report_id"] = SQLDB.fetch_from_uid(temp["old_id"]) temp["live_img"] = row[1] temp["live_status"] = row[2] temp["card_front_img"] = row[3] temp["card_back_img"] = row[4] temp["card_verify_status"] = row[5] temp["compare_status"] = row[6] temp["update_time"] = date2int(row[7]) temp["crt_tm"] = date2int(row[8]) temp["biz_id"] = row[9] temp["n_type"] = row[10] temp["name"] = row[11] temp["idcard_no"] = row[12] temp["biz_no"] = row[13] #标志jjd数据来源 temp["system_name"] = "JJD" #写入es out_body = gen_store_doc_bodies(gen_id_body(INDEX, TYPE, temp["report_id"],temp), BODY_QUEUE, 3000) ES_DB.bulk_push(out_body) if out_body.is_a? Array end if BODY_QUEUE.size > 0 out_body = gen_remain_store_bodies(BODY_QUEUE) ES_DB.bulk_push(out_body) end end <file_sep>/convert_deliver_address_report.rb #!/usr/bin/env ruby #-*-coding:utf-8-*- require 'rubygems' require 'json' require 'time' require './common_funcs' require './sqlite_treat' require './es_handler' file_input = "deliver_address_report.json" SQLDB = MyDB.new("ids.db", "id_pairs") ES_DB = ELS.new("10.111.30.171:9200", "10.111.30.172:9200", "10.111.30.173:9200") INDEX = "deliver_address_report" TYPE = "credit_data" BODY_QUEUE = [] do_each_row = Proc.new do |fin, line| output_hash = Hash.new line.chomp! input_hash = JSON.parse(line) output_hash["old_id"] = input_hash["_id"] #忽略身份证号不存在记录 next unless output_hash["old_id"].kind_of? String #忽略deliver为空的记录 next unless input_hash["l_report_deliver_address"] && input_hash["l_report_deliver_address"].size > 0 #获取report_id output_hash["report_id"] = SQLDB.fetch_from_id(output_hash["old_id"]) output_hash["update_time"] = Time.now.to_i #开始deliver_addresse_list output_hash["deliver_addresse_list"] = Array.new input_hash["l_report_deliver_address"].each do |item| temp_hash = Hash.new #获取多个名字相同字段 %w{address lng lat begin_date total_amount total_count t_begin_date t_end_date predict_addr_type}.each do |key| temp_hash[key] = item[key] end #兼容可能的时间对象 temp_hash["t_begin_date"] = date_compat(temp_hash["t_begin_date"]) if temp_hash["t_begin_date"] temp_hash["t_end_date"] = date_compat(temp_hash["t_end_date"]) if temp_hash["t_end_date"] #处理receiver if item["receiver"] && (item["receiver"].is_a? Array) temp_hash["ebusiness_receiver_list"] = Array.new item["receiver"].each do |receiver| temp_recervers = Hash.new %w{amout count name phone_num_list}.each do |k| temp_recervers[k] = receiver[k] end temp_hash["ebusiness_receiver_list"] << temp_recervers end end output_hash["deliver_addresse_list"] << temp_hash end # 增加字段识别jjd和第一风控 output_hash["system_name"] = "JJD" #写入es out_body = out_body = gen_store_doc_bodies(gen_id_body(INDEX, TYPE, output_hash["report_id"],output_hash), BODY_QUEUE, 1000) ES_DB.bulk_push(out_body) if out_body.is_a? Array end File.open(file_input, "r") do |fin| fin.each do |line| do_each_row.call(fin, line) end if BODY_QUEUE.size > 0 out_body = gen_remain_store_bodies(BODY_QUEUE) ES_DB.bulk_push(out_body) end end <file_sep>/mysql_deal.rb require "rubygems" require "mysql2" class Mysql_DB def initialize(host,port,user,pass,db,tablename) @client = Mysql2::Client.new host: host, username: user, password: <PASSWORD>, database: db, port: port @tablename = tablename end def get_from_salt(salt) return if not salt or salt.size == 0 result = @client.query("SELECT uid FROM #{@tablename} WHERE salt ='#{salt}'") return result.first["uid"] if result.first end def get_face_from_uid(uid) return if not uid or uid.size == 0 result = @client.query("SELECT * FROM #{@tablename} WHERE id = '#{uid}'") return result.first["b_compare_status"], result.first["t_update_tm"].to_s if result.first end end <file_sep>/convert_urgent_contact_history.rb #!/usr/bin/env ruby #-*-coding:utf-8-*- require 'rubygems' require 'json' require 'time' require './common_funcs' require './sqlite_treat' require './es_handler' file_input = "urgent_contact_report_history.json" SQLDB = MyDB.new("ids.db", "id_pairs") ES_DB = ELS.new("10.111.30.171:9200", "10.111.30.172:9200", "10.111.30.173:9200") INDEX = "urgent_contact_report_history" TYPE = "credit_data" BODY_QUEUE = [] File.open(file_input, "r") do |fin| fin.each do |line| #output_hash = Hash.new line.chomp! input_hash = JSON.parse(line) old_id = input_hash["_id"] #忽略身份证号不存在记录 next unless input_hash["_id"].kind_of? String user_report_id = SQLDB.fetch_from_id(old_id) next unless input_hash["l_base_info_history"].is_a? Array and input_hash["l_base_info_history"].size > 0 input_hash["l_base_info_history"].each_with_index do |item| #next unless item.is_a? Array and item.size > 0 output_hash = Hash.new output_hash["old_id"] = old_id output_hash["user_report_id"] = user_report_id output_hash["contactDetail"] = item["l_contacts"] output_hash["update_time"] = date2int(item["t_base_upd_tm"]) # 增加字段识别jjd和第一风控 output_hash["system_name"] = "JJD" #写入es out_body = gen_store_doc_bodies(gen_body(INDEX,TYPE,output_hash), BODY_QUEUE, 2000) ES_DB.bulk_push(out_body) if out_body.is_a? Array end end if BODY_QUEUE.size > 0 out_body = gen_remain_store_bodies(BODY_QUEUE) ES_DB.bulk_push(out_body) end end <file_sep>/convert_mobile_call_report.rb require 'rubygems' require 'json' require 'time' require './common_funcs' require './mongo_handler' require './sqlite_treat' require './es_handler' require 'thread' INDEX = "mobile_call_report" TYPE = "credit_data" SQLDB = MyDB.new("ids.db", "id_pairs") ES_DB = ELS.new("10.111.30.171:9200", "10.111.30.172:9200", "10.111.30.173:9200") body_queue0=[]; body_queue1=[]; body_queue2=[]; body_queue3=[]; body_queue4=[]; body_queue5=[] body_queue6=[]; body_queue7=[];body_queue8=[];body_queue9=[] threads = [] #防止线程无警告中断 Thread.abort_on_exception = true def gen_thr(filename, body_queue) open(filename, 'r') do |fin| fin.each do |line| output_hash = Hash.new line.chomp! input_hash = JSON.parse(line) output_hash["old_id"] = input_hash["_id"] #忽略身份证号不存在记录 next unless output_hash["old_id"].kind_of? String #忽略call记录为空记录 next unless input_hash["l_report_contact_list"] and input_hash["l_report_contact_list"].size > 0 output_hash["report_id"] = SQLDB.fetch_from_id(output_hash["old_id"]) output_hash["report_detail_list"] = input_hash["l_report_contact_list"] output_hash["update_time"] = Time.now.to_i # 增加字段识别jjd和第一风控 output_hash["system_name"] = "JJD" #写入es out_body = gen_store_doc_bodies(gen_id_body(INDEX, TYPE, output_hash["report_id"],output_hash), body_queue, 300) ES_DB.bulk_push(out_body) if out_body.is_a? Array end if body_queue.size > 0 out_body = gen_remain_store_bodies(body_queue) ES_DB.bulk_push(out_body) end end end threads << Thread.new { gen_thr("mobile_call_report_000", body_queue0)} threads << Thread.new { gen_thr("mobile_call_report_001", body_queue1)} threads << Thread.new { gen_thr("mobile_call_report_002", body_queue2)} threads << Thread.new { gen_thr("mobile_call_report_003", body_queue3)} threads << Thread.new { gen_thr("mobile_call_report_004", body_queue4)} threads << Thread.new { gen_thr("mobile_call_report_005", body_queue5)} threads << Thread.new { gen_thr("mobile_call_report_006", body_queue6)} threads << Thread.new { gen_thr("mobile_call_report_007", body_queue7)} threads << Thread.new { gen_thr("mobile_call_report_008", body_queue8)} threads << Thread.new { gen_thr("mobile_call_report_009", body_queue9)} threads.map(&:join) <file_sep>/es_handler.rb #!/usr/bin/env ruby #-*-coding:utf-8-*- require 'rubygems' require 'elasticsearch' require 'hashie' class ELS def initialize(*hosts) @client = Elasticsearch::Client.new hosts:hosts, request_timeout:5*60, randomize_hosts: true end def store(index, type, doc) result = @client.index index:index, type:type, body:doc result["_id"] end def update(index, type, doc) @client.update index:index, type:type, body: { doc: doc } end def bulk_push(docs) @client.bulk body: docs end def search_with_puid(index, type, puid) response = @client.search index:index, type:type, body: {query: { match: { puid: puid } }} response = Hashie::Mash.new response #response.hits.hits.first._source.puid return response.hits.hits.first._id, response.hits.hits.first._source.puid end def search_by_name(index, type, name) response = @client.search index:index, type:type, body: {query: { match: { user_name: name } }} response = Hashie::Mash.new response #response.hits.hits.first._source.puid return response.hits.hits.first._id, response.hits.hits.first._source.puid end def search_by_query(index, type, query) response = @client.search index:index, type:type, body: {query: { match: query}} response = Hashie::Mash.new response response.hits.hits.first._id end end <file_sep>/convert_EbusinessContact.rb #!/usr/bin/env ruby #-*-coding:utf-8-*- require 'rubygems' require 'json' require 'time' require './common_funcs' require './sqlite_treat' require './es_handler' file_input = "EbusinessContact.json" INDEX = "ebusiness_contact_report" TYPE = "credit_data" SQLDB = MyDB.new("ids.db", "id_pairs") ES_DB = ELS.new("10.111.30.171:9200", "10.111.30.172:9200", "10.111.30.173:9200") BODY_QUEUE = [] do_each_row = Proc.new do |fin,line| output_hash = Hash.new line.chomp! input_hash = JSON.parse(line) output_hash["old_id"] = input_hash["_id"] #忽略身份证号不存在记录 next unless output_hash["old_id"].kind_of? String #忽略contact为空的记录 next unless input_hash["l_report_collection_contact"] && input_hash["l_report_collection_contact"].size > 0 #获取report_id output_hash["report_id"] = SQLDB.fetch_from_id(output_hash["old_id"]) output_hash["update_time"] = Time.now.to_i #开始deliver_addresse_list output_hash["l_report_collection_contact"] = Array.new input_hash["l_report_collection_contact"].each do |item| temp_hash = Hash.new #获取多个名字相同字段 %w{contact_type contact_name begin_date end_date total_coun total_amount t_begin_date t_end_date}.each do |key| temp_hash[key] = item[key] end #兼容可能的时间对象 temp_hash["t_begin_date"] = date_compat(temp_hash["t_begin_date"]) if temp_hash["t_begin_date"] temp_hash["t_end_date"] = date_compat(temp_hash["t_end_date"]) if temp_hash["t_end_date"] temp_hash["begin_date"] = date_compat(temp_hash["begin_date"]) if temp_hash["begin_date"] temp_hash["end_date"] = date_compat(temp_hash["end_date"]) if temp_hash["end_date"] #处理contacts if item["contact_details"] && (item["contact_details"].is_a? Array) temp_hash["mobile_call_list"] = Array.new item["contact_details"].each do |contact| temp_contacts = Hash.new %w{phone_num call_cnt call_len call_out_cnt call_out_len call_in_cnt call_in_len sms_cnt}.each do |k| temp_contacts[k] = contact[k] end temp_hash["mobile_call_list"] << temp_contacts end end temp_hash["update_time"] = Time.now.to_i output_hash["l_report_collection_contact"] << temp_hash end # 增加字段识别jjd和第一风控 output_hash["system_name"] = "JJD" #写入es out_body = gen_store_doc_bodies(gen_id_body(INDEX, TYPE, output_hash["report_id"],output_hash), BODY_QUEUE, 2000) ES_DB.bulk_push(out_body) if out_body.is_a? Array end File.open(file_input, "r") do |fin| fin.each do |line| do_each_row.call(fin, line) end if BODY_QUEUE.size > 0 out_body = gen_remain_store_bodies(BODY_QUEUE) ES_DB.bulk_push(out_body) end end <file_sep>/convert_person_report.rb #!/usr/bin/env ruby #-*-coding:utf-8-*- require 'rubygems' require 'json' require 'time' require './common_funcs' require './sqlite_treat' require './es_handler' file_input = "person_report.json" INDEX = "person_report" TYPE = "credit_data" SQLDB = MyDB.new("ids.db", "id_pairs") ES_DB = ELS.new("10.111.30.171:9200", "10.111.30.172:9200", "10.111.30.173:9200") BODY_QUEUE = [] do_each_row = Proc.new do |fin, line| output_hash = Hash.new line.chomp! input_hash = JSON.parse(line) output_hash["old_id"] = input_hash["_id"] #忽略身份证号不存在记录 next unless output_hash["old_id"].kind_of? String #获取report_id output_hash["report_id"] = SQLDB.fetch_from_id(output_hash["old_id"]) output_hash["real_name"] = hash_link(input_hash, ["c_report_person", "real_name"]) output_hash["home_addr"] = hash_link(input_hash, ["c_report_person", "c_home_addr"]) output_hash["wechat_id"] = hash_link(input_hash, ["c_report_person", "c_wechat_id"]) rename_hash_item(input_hash["c_report_person"], output_hash, %w<id_card_num gender age head>) #开始zhengXinReport output_hash["zhengXinReport"] = Hash.new output_hash["zhengXinReport"]["courtAccept"] = hash_link(input_hash, ["c_report_person", "n_court_accept"]) output_hash["zhengXinReport"]["tongdunAccept"] = hash_link(input_hash, ["c_report_person", "n_tongdun_accept"]) output_hash["zhengXinReport"]["nameEqualsZhengxin"] = hash_link(input_hash, ["c_report_person", "n_name_equals_zhengxin"]) output_hash["zhengXinReport"]["zhengxinOverudeCounts_90day"] = hash_link(input_hash, ["c_report_person", "n_zhengxin_overude_90_days"]) output_hash["zhengXinReport"]["nameEqualsXueXin"] = hash_link(input_hash, ["c_report_person", "n_name_equals_xuexin"]) output_hash["zhengXinReport"]["idcardEqualsXueXin"] = hash_link(input_hash, ["c_report_person", "n_idcard_equals_xuexin"]) output_hash["zhengXinReport"]["zhengxinAccountCount"] = hash_link(input_hash, ["c_report_person", "n_zhengxin_account_count"]) output_hash["zhengXinReport"]["zhengxinHouseCount"] = hash_link(input_hash, ["c_report_person", "n_zhengxin_house_count"]) output_hash["zhengXinReport"]["zhengxinOtherCount"] = hash_link(input_hash, ["c_report_person", "n_zhengxin_other_count"]) output_hash["zhengXinReport"]["zhengxinOverdueCount"] = hash_link(input_hash, ["c_report_person", "n_zhengxin_overdue_count"]) rename_hash_item(input_hash["c_report_person"], output_hash["zhengXinReport"], %w<watchListDetails antifraudScore antifraudVerify antifraudRisk>) output_hash["zhengXinReport"]["antifraudVerify"] = output_hash["zhengXinReport"]["antifraudVerify"].to_json output_hash["zhengXinReport"]["antifraudRisk"] = output_hash["zhengXinReport"]["antifraudRisk"].to_json #开始ebusinessReport output_hash["ebusinessReport"] = Hash.new output_hash["ebusinessReport"]["ebusynessTotalAmount"] = hash_link(input_hash, ["c_report_person", "n_ebusyness_total_amount"]) output_hash["ebusinessReport"]["ebusynessTotalTm"] = hash_link(input_hash, ["c_report_person", "n_ebusyness_total_tm"]) output_hash["ebusinessReport"]["ebusynessTotalCount"] = hash_link(input_hash, ["c_report_person", "n_ebusyness_total_count"]) output_hash["ebusinessReport"]["telEbusynessCount"] = hash_link(input_hash, ["c_report_person", "n_tel_ebusyness_count"]) #开始mobileReport output_hash["mobileReport"] = Hash.new output_hash["mobileReport"]["mobilePhone"] = hash_link(input_hash, ["c_report_person", "c_mobile_phone"]) output_hash["mobileReport"]["telUseTm"] = hash_link(input_hash, ["c_report_person", "n_tel_use_tm"]) output_hash["mobileReport"]["telExchange"] = hash_link(input_hash, ["c_report_person", "n_tel_exchange"]) # 增加字段识别jjd和第一风控 output_hash["system_name"] = "JJD" #写入es out_body = gen_store_doc_bodies(gen_id_body(INDEX, TYPE, output_hash["report_id"],output_hash), BODY_QUEUE, 2000) ES_DB.bulk_push(out_body) if out_body.is_a? Array end File.open(file_input, "r") do |fin| fin.each do |line| do_each_row.call(fin, line) end if BODY_QUEUE.size > 0 out_body = gen_remain_store_bodies(BODY_QUEUE) ES_DB.bulk_push(out_body) end end <file_sep>/convert_StudentInfo.rb #!/usr/bin/env ruby #-*-coding:utf-8-*- require 'rubygems' require 'json' require 'time' require './common_funcs' require './sqlite_treat' require './mongo_handler' require './es_handler' file_input = "StudentInfo.json" SQLDB = MyDB.new("ids.db", "id_pairs") MONDB = Deal_Mongo.new("10.25.141.106:18000", "credit", "c_user_data", "trans", "123456") ES_DB = ELS.new("10.111.30.171:9200", "10.111.30.172:9200", "10.111.30.173:9200") INDEX = "student_info_report" TYPE = "credit_data" BODY_QUEUE = [] do_each_row = Proc.new do |fin, line| output_hash = Hash.new line.chomp! input_hash = JSON.parse(line) output_hash["old_id"] = input_hash["_id"] #忽略身份证号不存在记录 next unless output_hash["old_id"].kind_of? String #获取report_id output_hash["report_id"] = SQLDB.fetch_from_id(output_hash["old_id"]) output_hash["update_time"] = Time.now.to_i #查询l_xueji_info列表 xueji_info = MONDB.fetch_item_from_id(output_hash["old_id"])["l_xueji_info"] rescue nil #开始student_info_list if input_hash["l_report_xuexin"].is_a?(Array) output_hash["student_info_list"] = Array.new for i in (0 ... input_hash["l_report_xuexin"].size) temp_hash = Hash.new #获取多个字段 %w{c_enter_img c_graduate_img c_university c_major c_student_begin_time c_student_end_time c_student_level c_student_status c_full_time}.each do |key| temp_hash[key] = input_hash["l_report_xuexin"][i][key] end #添加l_xueji_info if xueji_info.is_a?(Array) temp_hash["name"] = xueji_info[i]["name"] temp_hash["idCardNo"] = xueji_info[i]["idCardNo"] end output_hash["student_info_list"] << temp_hash end end # 增加字段识别jjd和第一风控 output_hash["system_name"] = "JJD" #写入ES out_body = gen_store_doc_bodies(gen_id_body(INDEX, TYPE, output_hash["report_id"],output_hash), BODY_QUEUE, 2000) ES_DB.bulk_push(out_body) if out_body.is_a? Array end File.open(file_input, "r") do |fin| fin.each do |line| do_each_row.call(fin, line) end if BODY_QUEUE.size > 0 out_body = gen_remain_store_bodies(BODY_QUEUE) ES_DB.bulk_push(out_body) end end <file_sep>/common_funcs.rb #!/usr/bin/env ruby #-*-coding:utf-8-*- require 'time' def bool2int(bool, time) return 3 if bool return 4 if time return 0 end def date2int(time) begin case time when String datetime = Time.parse(time) when Hash datetime = Time.parse(time["$date"]) end return datetime.to_i if datetime rescue return end end def date_compat(time) case time when String return time when Hash return time["$date"] end return time end def rename_hash_item(inobj, outobj, keys) return if not inobj keys.each { |key| outobj[key] = inobj && inobj[key] } end def hash_link(nest, keys) return if not nest result = nest begin keys.each do |key| result = result[key] end rescue NoMethodError return end return result end def transfer_list(list_in, list_out, key) return unless list_in.is_a? Array list_in.each do |item| list_out << item[key] end end def transfer_list_with_item(list_in, list_out, key) return unless list_in.is_a? Array list_in.each do |item| if item[key].is_a? Array item[key].flatten.each do |nest| list_out << nest end end end end def gen_id_body(index, type, id, output_hash) {_index: index, _type: type, _id: id, data: output_hash} end def gen_body(index, type, output_hash) {_index: index, _type: type, data: output_hash} end def gen_store_doc_bodies(doc, list, limit) list << doc return if list.size < limit body = Array.new while item = list.shift each_doc = {index: item} body << each_doc end return body end def gen_remain_store_bodies(list) body = Array.new while item = list.shift each_doc = {index: item} body << each_doc end return body end def gen_update_doc_bodies(index, type, doc, list, key, limit) list << doc return if list.size < limit body = Array.new while item = list.shift each_doc = {update: { _index: index, _type: type, _id: item[key], data: {doc: item} }} body << each_doc end return body end def gen_remain_update_bodies(index, type, list, key) body = Array.new while item = list.shift each_doc = {update: { _index: index, _type: type, _id: item[key], data: {doc: item} }} body << each_doc end return body end def gen_sql_list(item, list, limit) list << item return if list.size < limit body = Array.new while item = list.shift body << item end return body end <file_sep>/test_mysql.rb require "./mysql_deal" #MyDB = Mysql_DB.new("10.111.30.20", 3306, "op", "KRkFcVCbopZbS8R7", "jjd_11th", "user_passport") FACEDB = Mysql_DB.new("10.111.20.2", 3306, "dev", "KRkFcVCbopZbS8R7", "jjd", "t_face_verify") #puts MyDB.get_from_salt("19b80d6d-423a-425c-9589-ad57e27d8962") puts FACEDB.get_face_from_uid("0003fe4c-6e4f-41e0-ba42-d7b798d83ed9") <file_sep>/mongo_handler.rb #!/usr/bin/env ruby #-*-coding:utf-8-*- require 'rubygems' require 'mongo' class Deal_Mongo def initialize(host, database, collect, user, pass) client = Mongo::Client.new([host], :database=>database, :user=>user, :password=><PASSWORD>, :server_selection_timeout=>3) @collection = client[collect] end def fetch_item_from_id(id) @collection.find({_id: id}).first end end <file_sep>/update_doc_by_name.rb #!/usr/bin/env ruby #-*-coding:utf-8-*- require "./es_handler" require "./mysql_deal" ES_DB = ELS.new("10.111.30.171:9200", "10.111.30.172:9200", "10.111.30.173:9200") MSQLDB = Mysql_DB.new("10.111.30.20", 3306, "op", "KRkFcVCbopZbS8R7", "jjd_11th", "user_passport") =begin names = ["訾渊","孙新超","贾海娜","春宵","刘春肖"] names.each do |name| id, puid = ES_DB.search_by_name("user_info","credit_data",name) new_id = MSQLDB.get_from_salt(puid) ES_DB.update("user_info","credit_data", id, {puid: new_id}) end =end #id = ES_DB.search_by_query("user_info","credit_data",{username:"孙新超"}) ES_DB.update("user_info","credit_data", "AWWixyd3cNu35budItVj", {face_verify_status: 0}) ES_DB.update("user_info","credit_data", "AWWixy6_QGidtPst7mao", {face_verify_status: 3}) ES_DB.update("user_info","credit_data", "AWWiwve2P1hdiMKR4WSa", {face_verify_status: 3})<file_sep>/convert_report_basic_info.rb #!/usr/bin/env ruby #-*-coding:utf-8-*- require 'rubygems' require 'json' require 'time' require './common_funcs' require './mongo_handler' require './sqlite_treat' require './es_handler' file_input = "report_basic_info.json" DB = Deal_Mongo.new("10.25.141.106:18000", "credit", "c_user_data", "trans", "123456") SQLDB = MyDB.new("ids.db", "id_pairs") ES_DB = ELS.new("10.111.30.171:9200", "10.111.30.172:9200", "10.111.30.173:9200") INDEX = "report_basic_info" TYPE = "credit_data" BODY_QUEUE = [] do_each_row = Proc.new do |fin, line| output_hash = Hash.new line.chomp! input_hash = JSON.parse(line) output_hash["old_id"] = input_hash["_id"] #忽略身份证号不存在记录 next unless output_hash["old_id"].kind_of? String #获取report_id output_hash["report_id"] = SQLDB.fetch_from_id(output_hash["old_id"]) #开始user_base_info output_hash["user_base_info"] = Hash.new output_hash["user_base_info"]["telephone"] = hash_link(input_hash, ["l_business_system", 0, "c_telephone"]) rename_hash_item(input_hash["c_base_info"],output_hash["user_base_info"], %w<level_1_code level_1_name level_2_code level_2_name level_3_code level_3_name> ) output_hash["user_base_info"]["home_addr"] = hash_link(input_hash,["c_base_info", "c_home_addr"]) output_hash["user_base_info"]["wechat_id"] = hash_link(input_hash, ["c_base_info", "c_wechat_id"]) output_hash["user_base_info"]["update_time"] = date2int(hash_link(input_hash, ["c_base_info","t_base_upd_tm"])) ##开始car_info output_hash["car_info"] = Hash.new output_hash["car_info"]["car_brand"] = hash_link(input_hash, ["c_car_info","c_car_brand"]) output_hash["car_info"]["car_mileage"] = hash_link(input_hash, ["c_car_info", "c_car_mileage"]) output_hash["car_info"]["car_price"] = hash_link(input_hash, ["c_car_info", "c_car_price"]) output_hash["car_info"]["car_pay_status"] = hash_link(input_hash, ["c_car_info", "c_car_pay_status"]) output_hash["car_info"]["car_paid"] = hash_link(input_hash, ["c_car_info", "c_car_paid"]) rename_hash_item(input_hash["c_car_info"],output_hash["car_info"], %w<level_1_code level_1_name level_2_code level_2_name level_3_code level_3_name>) output_hash["car_info"]["car_age"] = hash_link(input_hash, ["c_car_info", "c_car_age"]) output_hash["car_info"]["car_is_used"] = hash_link(input_hash, ["c_car_info", "b_car_is_used"]) output_hash["car_info"]["car_is_mortgage"] = hash_link(input_hash, ["c_car_info", "b_car_is_mortgage"]) output_hash["car_info"]["car_image_list"] = hash_link(input_hash, ["c_car_info", "l_car_image"]) output_hash["car_info"]["update_time"] = Time.now.to_i #当前时间用整型表示 #开始earn_info output_hash["earn_info"] = Hash.new output_hash["earn_info"]["earn_month"] = hash_link(input_hash, ["c_earn_info", "c_earn_month"]) output_hash["earn_info"]["earn_image_list"] = hash_link(input_hash, ["c_earn_info", "l_earn_image"]) output_hash["earn_info"]["update_time"] = Time.now.to_i #当前时间用整型表示 #开始house_info output_hash["house_info"] = Hash.new rename_hash_item(input_hash["c_house_info"],output_hash["house_info"], %w<level_1_code level_1_name level_2_code level_2_name level_3_code level_3_name>) output_hash["house_info"]["house_address"] = hash_link(input_hash, ["c_house_info", "c_house_address"]) output_hash["house_info"]["house_type"] = hash_link(input_hash, ["c_house_info", "c_house_type"]) output_hash["house_info"]["house_area"] = hash_link(input_hash, ["c_house_info", "c_house_area"]) output_hash["house_info"]["house_price"] = hash_link(input_hash, ["c_house_info", "c_house_price"]) output_hash["house_info"]["house_pay_status"] = hash_link(input_hash, ["c_house_info", "c_house_pay_status"]) output_hash["house_info"]["house_paid"] = hash_link(input_hash, ["c_house_info", "c_house_paid"]) output_hash["house_info"]["house_age"] = hash_link(input_hash, ["c_house_info", "c_house_age"]) output_hash["house_info"]["house_is_used"] = hash_link(input_hash, ["c_house_info", "b_house_is_used"]) output_hash["house_info"]["house_is_mortgage"] = hash_link(input_hash, ["c_house_info", "b_house_is_mortgage"]) output_hash["house_info"]["house_image_list"] = hash_link(input_hash, ["c_house_info", "l_house_image"]) output_hash["house_info"]["update_time"] = Time.now.to_i #开始job_info output_hash["job_info"] = Hash.new output_hash["job_info"]["company_name"] = hash_link(input_hash, ["c_job_info", "c_company"]) output_hash["job_info"]["position"] = hash_link(input_hash, ["c_job_info", "c_position"]) output_hash["job_info"]["employment_date"] = date2int(hash_link(input_hash, ["c_job_info", "c_employment_date"])) output_hash["job_info"]["company_tel"] = hash_link(input_hash, ["c_job_info", "c_company_tel"]) rename_hash_item(input_hash["c_job_info"],output_hash["job_info"], %w<level_1_code level_1_name level_2_code level_2_name level_3_code level_3_name> ) output_hash["job_info"]["company_address"] = hash_link(input_hash, ["c_job_info", "company_address"]) output_hash["job_info"]["company_image_list"] = hash_link(input_hash, ["c_job_info", "l_company_image"]) output_hash["job_info"]["update_time"] = Time.now.to_i #开始location_Info output_hash["location_Info"] = Hash.new output_hash["location_Info"]["province_name"] = hash_link(input_hash, ["c_recent_location_info", "c_location_recent_province"]) output_hash["location_Info"]["city_name"] = hash_link(input_hash, ["c_recent_location_info", "c_location_recent_city"]) output_hash["location_Info"]["district_name"] = hash_link(input_hash, ["c_recent_location_info", "c_location_recent_district"]) output_hash["location_Info"]["address"] = hash_link(input_hash, ["c_recent_location_info", "c_location_recent_address"]) output_hash["location_Info"]["location_tm"] = Time.now.to_i output_hash["location_Info"]["location_count"] = hash_link(input_hash, ["c_recent_location_info", "n_location_count"]) output_hash["location_Info"]["update_time"] = date2int(hash_link(input_hash, ["c_recent_location_info", "t_location_recent_tm"])) #开始gjj_base_info output_hash["gjj_base_info"] = Hash.new rename_hash_item(hash_link(input_hash, ["c_gjj_info", "task_data", "base_info"]),output_hash["gjj_base_info"], %w<cert_type begin_date last_pay_date pay_status balance cust_no pay_status_desc cert_no corp_name name>) #时间格式不统一做兼容处理,es output_hash["gjj_base_info"]["begin_date"] = date_compat(output_hash["gjj_base_info"]["begin_date"]) output_hash["gjj_base_info"]["last_pay_date"] = date_compat(output_hash["gjj_base_info"]["last_pay_date"]) #开始shebao_base_info output_hash["shebao_base_info"] = Hash.new rename_hash_item(hash_link(input_hash, ["c_shebao_info", "task_data", "user_info"]), output_hash["shebao_base_info"], %w<name nation gender hukou_type certificate_number home_address company_name mobile begin_date time_to_work>) #时间格式不统一做兼容处理,es output_hash["shebao_base_info"]["begin_date"] = date_compat(output_hash["shebao_base_info"]["begin_date"]) output_hash["shebao_base_info"]["time_to_work"] = date_compat(output_hash["shebao_base_info"]["time_to_work"]) #查询记录 user_data = DB.fetch_item_from_id(output_hash["old_id"]) #开始ebusiness_basice_info output_hash["ebusiness_basice_info"] = Hash.new output_hash["ebusiness_basice_info"]["update_time"] = date2int(hash_link(user_data, ["c_jingdong_basic", "update_time"])) rename_hash_item(hash_link(user_data, ["c_jingdong_basic"]), output_hash["ebusiness_basice_info"], %w<level nickname real_name website_id email cell_phone>) #开始mobile_info output_hash["mobile_basic_info"] = Hash.new rename_hash_item(hash_link(user_data, ["c_mobile_basic"]), output_hash["mobile_basic_info"], %w<cell_phone idcard reg_time real_name>) output_hash["mobile_basic_info"]["reg_time"] = date_compat(output_hash["mobile_basic_info"]["reg_time"]) output_hash["mobile_basic_info"]["update_time"] = date2int(hash_link(user_data, ["c_mobile_basic", "update_time"])) # 增加字段识别jjd和第一风控 output_hash["system_name"] = "JJD" #写入es out_body = gen_store_doc_bodies(gen_id_body(INDEX, TYPE, output_hash["report_id"],output_hash), BODY_QUEUE, 2000) ES_DB.bulk_push(out_body) if out_body.is_a? Array end File.open(file_input, "r") do |fin| fin.each do |line| do_each_row.call(fin, line) end if BODY_QUEUE.size > 0 out_body = gen_remain_store_bodies(BODY_QUEUE) ES_DB.bulk_push(out_body) end end <file_sep>/test_es.rb #!/usr/bin/env ruby #-*-coding:utf-8-*- require "./es_handler" require "json" ES_DB = ELS.new("10.111.30.171:9200", "10.111.30.172:9200", "10.111.30.173:9200") #output_hash={"old_id" => "1234567908"} #report_id = ES_DB.store("user_info", "history", output_hash) #output_hash["puid"] = "5699789" #output_hash["report_id"] = report_id #output_hash["quid"] = "213242334324" #ES_DB.update("user_info", "history", report_id, output_hash) #puts ES_DB.search_with_puid("user_info","credit_data","201708161330119638") #puts ES_DB.search_by_name("user_info","credit_data","刘春肖") puts ES_DB.search_by_query("user_info", "credit_data", {user_name:"刘春肖"})<file_sep>/convert_urgent_contact_report.rb #!/usr/bin/env ruby #-*-coding:utf-8-*- require 'rubygems' require 'json' require 'time' require './common_funcs' require './sqlite_treat' require './es_handler' file_input = "urgent_contact_report.json" SQLDB = MyDB.new("ids.db", "id_pairs") ES_DB = ELS.new("10.111.30.171:9200", "10.111.30.172:9200", "10.111.30.173:9200") INDEX = "urgent_contact_report" TYPE = "credit_data" BODY_QUEUE = [] do_each_row = Proc.new do |fin, line| output_hash = Hash.new line.chomp! input_hash = JSON.parse(line) output_hash["old_id"] = input_hash["_id"] #忽略身份证号不存在记录 next unless output_hash["old_id"].kind_of? String #获取report_id output_hash["report_id"] = SQLDB.fetch_from_id(output_hash["old_id"]) #开始contactDetail output_hash["contactDetail"] = Hash.new if input_hash["l_report_base_contract"].is_a?(Array) output_hash["contactDetail"] = Array.new input_hash["l_report_base_contract"].each do |item| temp_hash = Hash.new temp_hash["contact_tel"] = item["contact_tel"] temp_hash["contact_name"] = item["contact_name"] temp_hash["contact_type"] = item["contact_type"] temp_hash["call_len"] = item["n_call_cnt"] temp_hash["sms_cnt"] = item["n_sms_cnt"] temp_hash["begin_date"] = item["c_begin_date"] temp_hash["end_date"] = item["c_end_date"] temp_hash["total_count"] = item["n_total_count"] temp_hash["total_amount"] = item["n_total_amount"] output_hash["contactDetail"] << temp_hash end end # 增加字段识别jjd和第一风控 output_hash["system_name"] = "JJD" #写入es out_body = gen_store_doc_bodies(gen_id_body(INDEX, TYPE, output_hash["report_id"],output_hash), BODY_QUEUE, 2000) ES_DB.bulk_push(out_body) if out_body.is_a? Array end File.open(file_input, "r") do |fin| fin.each do |line| do_each_row.call(fin, line) end if BODY_QUEUE.size > 0 out_body = gen_remain_store_bodies(BODY_QUEUE) ES_DB.bulk_push(out_body) end end <file_sep>/convert_face_verify_result.rb #!/usr/bin/env ruby #-*-coding:utf-8-*- require 'rubygems' require './sqlite_treat' require './common_funcs' require 'json' require './es_handler' Encoding.default_external=Encoding.find("utf-8") file_input = "t_face_verify_result.txt" INDEX = "face_verify_result" TYPE = "credit_data" SQLDB = MyDB.new("ids.db", "id_pairs") ES_DB = ELS.new("10.111.30.171:9200", "10.111.30.172:9200", "10.111.30.173:9200") BODY_QUEUE = [] File.open(file_input) do |fin| fin.each do |line| next if fin.lineno == 1 temp = {} line.chomp! row = line.split("\t") temp["old_id"] = row[0] temp["report_id"] = SQLDB.fetch_from_uid(temp["old_id"]) temp["live_result"] = row[1] temp["card_verify_result"] = row[2] temp["compare_result"] = row[3] #标志jjd数据来源 temp["system_name"] = "JJD" #写入es out_body = gen_store_doc_bodies(gen_id_body(INDEX, TYPE, temp["report_id"],temp), BODY_QUEUE, 1000) ES_DB.bulk_push(out_body) if out_body.is_a? Array end if BODY_QUEUE.size > 0 out_body = gen_remain_store_bodies(BODY_QUEUE) ES_DB.bulk_push(out_body) end end <file_sep>/sqlite_treat.rb #!/usr/bin/env ruby #-*-coding:utf-8-*- require 'rubygems' require 'sqlite3' class MyDB def initialize(dbfile, table_name) @db = SQLite3::Database.new(dbfile) @table_name = table_name @db.execute <<-SQL CREATE TABLE IF NOT EXISTS #{table_name} (id TEXT PRIMARY KEY NOT NULL, report_id TEXT, uid TEXT) SQL end def store(list) @db.execute("INSERT INTO #{@table_name} VALUES (?,?,?)", list) end def fetch_from_id(id) @db.execute("SELECT report_id FROM #{@table_name} WHERE id=?", id)[0][0] rescue nil end def fetch_from_uid(uid) @db.execute("SELECT report_id FROM #{@table_name} WHERE uid=?", uid)[0][0] rescue nil end def create_index @db.execute "CREATE INDEX ID_INDEX ON #{@table_name} (id)" @db.execute "CREATE INDEX UID_INDEX ON #{@table_name} (uid)" end def bulk_store(list) @db.execute "BEGIN TRANSACTION" list.each do |item| @db.execute("INSERT INTO #{@table_name} VALUES (?,?,?)", item) end @db.execute "COMMIT TRANSACTION" end end <file_sep>/test_mongo.rb #!/usr/bin/env ruby #-*-coding:utf-8-*- # # require './mongo_handler' DB = Deal_Mongo.new("10.25.141.106:18000", "credit", "c_user_data", "trans", "123456") puts DB.fetch_item_from_id("342427199603284413")["c_jingdong_basic"] puts DB.fetch_item_from_id("342427199603284413")["c_mobile_basic"] <file_sep>/convert_user_info.rb #!/usr/bin/env ruby #-*-coding:utf-8-*- require 'rubygems' require 'json' require 'time' require './common_funcs' require './sqlite_treat' require './es_handler' require './mysql_deal' require 'thread' INDEX = "user_info" TYPE = "credit_data" SQLDB = MyDB.new("ids.db", "id_pairs") DB_PASS = {host:"rm-2zeoc1o61ykfe62v6.mysql.rds.aliyuncs.com", port:3306, user:"dev", pass:"<PASSWORD>", database:"jjd", table: "user_passport"} DB_FACE = {host:"10.111.33.181", port:3306, user:"mysqltords", pass:"<PASSWORD>", database:"jjd", table: "t_face_verify"} MSQLDB0 = Mysql_DB.new(DB_PASS[:host], DB_PASS[:port], DB_PASS[:user], DB_PASS[:pass], DB_PASS[:database], DB_PASS[:table]) FACEDB0 = Mysql_DB.new(DB_FACE[:host], DB_FACE[:port], DB_FACE[:user], DB_FACE[:pass], DB_FACE[:database], DB_FACE[:table]) MSQLDB1 = Mysql_DB.new(DB_PASS[:host], DB_PASS[:port], DB_PASS[:user], DB_PASS[:pass], DB_PASS[:database], DB_PASS[:table]) FACEDB1 = Mysql_DB.new(DB_FACE[:host], DB_FACE[:port], DB_FACE[:user], DB_FACE[:pass], DB_FACE[:database], DB_FACE[:table]) MSQLDB2 = Mysql_DB.new(DB_PASS[:host], DB_PASS[:port], DB_PASS[:user], DB_PASS[:pass], DB_PASS[:database], DB_PASS[:table]) FACEDB2 = Mysql_DB.new(DB_FACE[:host], DB_FACE[:port], DB_FACE[:user], DB_FACE[:pass], DB_FACE[:database], DB_FACE[:table]) MSQLDB3 = Mysql_DB.new(DB_PASS[:host], DB_PASS[:port], DB_PASS[:user], DB_PASS[:pass], DB_PASS[:database], DB_PASS[:table]) FACEDB3 = Mysql_DB.new(DB_FACE[:host], DB_FACE[:port], DB_FACE[:user], DB_FACE[:pass], DB_FACE[:database], DB_FACE[:table]) MSQLDB4 = Mysql_DB.new(DB_PASS[:host], DB_PASS[:port], DB_PASS[:user], DB_PASS[:pass], DB_PASS[:database], DB_PASS[:table]) FACEDB4 = Mysql_DB.new(DB_FACE[:host], DB_FACE[:port], DB_FACE[:user], DB_FACE[:pass], DB_FACE[:database], DB_FACE[:table]) MSQLDB5 = Mysql_DB.new(DB_PASS[:host], DB_PASS[:port], DB_PASS[:user], DB_PASS[:pass], DB_PASS[:database], DB_PASS[:table]) FACEDB5 = Mysql_DB.new(DB_FACE[:host], DB_FACE[:port], DB_FACE[:user], DB_FACE[:pass], DB_FACE[:database], DB_FACE[:table]) MSQLDB6 = Mysql_DB.new(DB_PASS[:host], DB_PASS[:port], DB_PASS[:user], DB_PASS[:pass], DB_PASS[:database], DB_PASS[:table]) FACEDB6 = Mysql_DB.new(DB_FACE[:host], DB_FACE[:port], DB_FACE[:user], DB_FACE[:pass], DB_FACE[:database], DB_FACE[:table]) MSQLDB7 = Mysql_DB.new(DB_PASS[:host], DB_PASS[:port], DB_PASS[:user], DB_PASS[:pass], DB_PASS[:database], DB_PASS[:table]) FACEDB7 = Mysql_DB.new(DB_FACE[:host], DB_FACE[:port], DB_FACE[:user], DB_FACE[:pass], DB_FACE[:database], DB_FACE[:table]) MSQLDB8 = Mysql_DB.new(DB_PASS[:host], DB_PASS[:port], DB_PASS[:user], DB_PASS[:pass], DB_PASS[:database], DB_PASS[:table]) FACEDB8 = Mysql_DB.new(DB_FACE[:host], DB_FACE[:port], DB_FACE[:user], DB_FACE[:pass], DB_FACE[:database], DB_FACE[:table]) MSQLDB9 = Mysql_DB.new(DB_PASS[:host], DB_PASS[:port], DB_PASS[:user], DB_PASS[:pass], DB_PASS[:database], DB_PASS[:table]) FACEDB9 = Mysql_DB.new(DB_FACE[:host], DB_FACE[:port], DB_FACE[:user], DB_FACE[:pass], DB_FACE[:database], DB_FACE[:table]) SQLDB.create_index ES_DB = ELS.new("10.111.30.171:9200", "10.111.30.172:9200", "10.111.30.173:9200") body_queue0=[]; body_queue1=[]; body_queue2=[]; body_queue3=[]; body_queue4=[]; body_queue5=[] body_queue6=[]; body_queue7=[];body_queue8=[]; body_queue9=[] $queue = Queue.new #防止线程无警告中断 Thread.abort_on_exception = true do_each_row = Proc.new do |line, body_queue, sql_queue,face_db,user_db| output_hash = Hash.new line.chomp! input_hash = JSON.parse(line) output_hash["old_id"] = input_hash["_id"] #忽略身份证号不存在记录 next unless output_hash["old_id"].kind_of? String #插入id获取es主键_id值 report_id = ES_DB.store(INDEX, TYPE, output_hash) output_hash["report_id"] = report_id output_hash["puid"] = hash_link(input_hash, ["l_business_system", 0, "_id"]) output_hash["ouid"] = output_hash["puid"] #根据puid获取新id output_hash["puid"] = user_db.get_from_salt(output_hash["ouid"]).to_s #获取face_verify_status,face_verify_upd_tm face_status, face_tm = face_db.get_face_from_uid(output_hash["ouid"]) case face_status when 0 output_hash["face_verify_status"] = 4 when 1 output_hash["face_verify_status"] = 3 else output_hash["face_verify_status"] = 0 end output_hash["face_verify_upd_tm"] = date2int(face_tm) #维护report_id, id, uid映射关系 #100条一次事务加快速度 #sql_bulk = gen_sql_list([output_hash["old_id"],report_id,output_hash["puid"]], SQL_VALUES, 100) #SQLDB.store(output_hash["old_id"], report_id, output_hash["puid"]) sql_queue << [output_hash["old_id"], report_id, output_hash["ouid"]] #output_hash["quid"] = hash_link(input_hash, ["l_business_system", 0, "_id"]) output_hash["system_type"] = hash_link(input_hash, ["l_business_system", 0, "c_system_name"]) output_hash["user_name"] = hash_link(input_hash, ["c_base_info","c_user_name"]) output_hash["card_no"] = input_hash["_id"] output_hash["telephone"] = hash_link(input_hash, ["l_business_system", 0, "c_telephone"]) output_hash["data_change"] = true output_hash["student_status"] = -1; output_hash["bind_card"] = true output_hash["up_special"] = hash_link(input_hash, ["c_base_info","b_xueli_up_zhuanke"]) output_hash["mobile_phone"] = hash_link(input_hash, ["c_base_info","c_mobile_phone"]) output_hash["base_upd_tm"] = date2int(hash_link(input_hash, ["c_base_info","t_base_upd_tm"])) output_hash["mobile_upd_tm"] = date2int(hash_link(input_hash, ["c_base_info","t_mobile_upd_tm"])) output_hash["taobao_upd_tm"] = date2int(hash_link(input_hash, ["c_base_info","t_taobao_upd_tm"])) output_hash["jingdong_upd_tm"] = date2int(hash_link(input_hash, ["c_base_info","t_jingdong_upd_tm"])) output_hash["shebao_upd_tm"] = date2int(hash_link(input_hash, ["c_base_info","t_shebao_upd_tm"])) output_hash["gjj_upd_tm"] = date2int(hash_link(input_hash, ["c_base_info","t_gjj_upd_tm"])) output_hash["xuexin_upd_tm"] = date2int(hash_link(input_hash, ["c_base_info","t_xuexin_upd_tm"])) output_hash["zhengxin_upd_tm"] = date2int(hash_link(input_hash, ["c_base_info","t_zhengxin_upd_tm"])) output_hash["house_upd_tm"] = date2int(hash_link(input_hash, ["c_base_info","t_house_upd_tm"])) output_hash["car_upd_tm"] = date2int(hash_link(input_hash, ["c_base_info","t_car_upd_tm"])) output_hash["income_upd_tm"] = date2int(hash_link(input_hash, ["c_base_info","t_income_upd_tm"])) output_hash["job_upd_tm"] = date2int(hash_link(input_hash, ["c_base_info","t_job_upd_tm"])) output_hash["zhima_credit_upd_tm"] = date2int(hash_link(input_hash, ["c_base_info","t_zhima_credit_upd_tm"])) output_hash["mobile_analysis_upd_tm"] = date2int(hash_link(input_hash, ["c_base_info","t_mobile_analysis_upd_tm"])) output_hash["location_upd_tm"] = date2int(hash_link(input_hash, ["c_base_info","t_location_upd_tm"])) output_hash["baseInfo_credit_status"] = bool2int(hash_link(input_hash,["c_base_info","b_base_info"]), output_hash["base_upd_tm"]) output_hash["mobile_credit_status"] = bool2int(hash_link(input_hash, ["c_base_info","b_mobile_info"]), output_hash["mobile_upd_tm"]) output_hash["taobao_credit_status"] = bool2int(hash_link(input_hash, ["c_base_info","b_taobao_info"]), output_hash["taobao_upd_tm"]) output_hash["jingdong_credit_status"] = bool2int(hash_link(input_hash, ["c_base_info","b_jingdong_info"]), output_hash["jingdong_upd_tm"]) output_hash["shebao_credit_status"] = bool2int(hash_link(input_hash, ["c_base_info","b_shebao_info"]), output_hash["shebao_upd_tm"]) output_hash["gjj_credit_status"] = bool2int(hash_link(input_hash, ["c_base_info","b_gjj_info"]), output_hash["gjj_upd_tm"]) output_hash["xuexin_credit_status"] = bool2int(hash_link(input_hash, ["c_base_info","b_xuexin_info"]), output_hash["xuexin_upd_tm"]) output_hash["zhengxin_credit_status"] = bool2int(hash_link(input_hash, ["c_base_info","b_zhengxin_info"]), output_hash["zhengxin_upd_tm"]) output_hash["house_credit_status"] = bool2int(hash_link(input_hash, ["c_base_info","b_house_info"]), output_hash["house_upd_tm"]) output_hash["car_credit_status"] = bool2int(hash_link(input_hash, ["c_base_info","b_car_info"]), output_hash["car_upd_tm"]) output_hash["income_credit_status"] = bool2int(hash_link(input_hash, ["c_base_info","b_income_info"]), output_hash["income_upd_tm"]) output_hash["job_credit_status"] = bool2int(hash_link(input_hash, ["c_base_info","b_job_info"]), output_hash["job_upd_tm"]) output_hash["zhima_credit_status"] = bool2int(hash_link(input_hash, ["c_base_info","b_zhima_credit"]), output_hash["zhima_credit_upd_tm"]) output_hash["mobileAnalysis_credit_status"] = bool2int(hash_link(input_hash, ["c_base_info","b_mobile_analysis_info"]), output_hash["mobile_analysis_upd_tm"]) output_hash["location_credit_status"] = bool2int(hash_link(input_hash, ["c_base_info","b_location_info"]), output_hash["location_upd_tm"]) output_hash["update_time"] = Time.now.to_i # 增加字段识别jjd和第一风控 output_hash["system_name"] = "JJD" out_body = gen_update_doc_bodies(INDEX, TYPE, output_hash, body_queue, "report_id", 3000) ES_DB.bulk_push(out_body) if out_body.is_a? Array end def thr_gen(filename, do_each_row, body_queue, sql_queue,face_db,user_db) File.open(filename, "r") do |fin| fin.each do |line| do_each_row.call(line, body_queue, sql_queue, face_db, user_db) end #处理es最后未到limit的记录 if body_queue.size > 0 out_body = gen_remain_update_bodies(INDEX, TYPE, body_queue, "report_id") ES_DB.bulk_push(out_body) end end end Thread.new {thr_gen("user_info_000", do_each_row, body_queue0, $queue,FACEDB0, MSQLDB0)} Thread.new {thr_gen("user_info_001", do_each_row, body_queue1, $queue,FACEDB1, MSQLDB1)} Thread.new {thr_gen("user_info_002", do_each_row, body_queue2, $queue,FACEDB2, MSQLDB2)} Thread.new {thr_gen("user_info_003", do_each_row, body_queue3, $queue,FACEDB3, MSQLDB3)} Thread.new {thr_gen("user_info_004", do_each_row, body_queue4, $queue,FACEDB4, MSQLDB4)} Thread.new {thr_gen("user_info_005", do_each_row, body_queue5, $queue,FACEDB5, MSQLDB5)} Thread.new {thr_gen("user_info_006", do_each_row, body_queue6, $queue,FACEDB6, MSQLDB6)} Thread.new {thr_gen("user_info_007", do_each_row, body_queue7, $queue,FACEDB7, MSQLDB7)} Thread.new {thr_gen("user_info_008", do_each_row, body_queue8, $queue,FACEDB8, MSQLDB8)} Thread.new {thr_gen("user_info_009", do_each_row, body_queue9, $queue,FACEDB9, MSQLDB9)} #生产速度慢,先跑30s sleep 30 consumer = Thread.new do until $queue.empty? #如果队列少于5,停止30s等等生产,防止丢失数据 sleep 30 if $queue.size <= 5 value = $queue.pop #p value SQLDB.store(value) end end consumer.join
0eae81e453894edc1493ec037f679960285175cb
[ "Ruby" ]
21
Ruby
pangqiqiang/trans_mongo_es
ad6aeecb9eaca5256097efdc847c180e5b6b3526
6e44f55a9d12685f240d0dc1ccbb9410feb4b1eb